Provider and Scoping
Concept
1. Why
Components never receive a skin or theme as a parameter. Passing them into every call would bring back the boilerplate Camouflage exists to remove. Instead, CamouflageProvider puts a skin and a theme into the UI tree, and every Camo* component below it reads the nearest one. Because providers can be nested, one app can use several skins or themes (per screen, per section, per platform) and switch them at runtime, without touching component call sites.
2. Shape
Mechanism. Each platform has a tree-scoped lookup:
- Kotlin:
CompositionLocals namedLocalCamoSkinandLocalCamoTheme. - Flutter: an
InheritedWidgetnamedCamouflageScope.
The provider writes to them, and components read the nearest value above them. The platform notes decide the details: Provider and Scoping / Provider and Scoping.
Responsibilities of the provider
- Resolve the effective skin and theme: its own argument, else inherited from the provider above.
- Fail fast if neither exists.
- Apply system adjustments to the theme once, at the provider:
- reduced motion becomes
motion.reduced(); - text scale is left to the platform's text scaler (see §5).
- reduced motion becomes
- Reset the content color to
theme.colors.onSurfaceand the icon style to the resolvediconcomponent theme (Minimal default: 20,onSurface) for its subtree, so text and icons outside any container are readable.
3. API
fun CamouflageProvider(
skin: CamoSkin? = null, // null → inherit from the provider above
theme: CamoTheme? = null, // null → inherit from the provider above
content: Slot,
)
object Camouflage {
val skin: CamoSkin // nearest effective skin, or fail fast
val theme: CamoTheme // nearest effective theme (with system adjustments), or fail fast
val colors: CamoColors // = theme.colors (shortcut)
val typography: CamoTypography // = theme.typography
val shapes: CamoShapes
val spacing: CamoSpacing
val elevation: CamoElevation
val motion: CamoMotion
val contentColor: Color // the current content color set by the nearest container
val iconStyle: IconStyle // the current icon size + color set by the nearest container
fun <T : CamoTokenSet<T>> tokens(): T // the theme's token set of type T (ADR-32), or fail fast naming the missing set
val skinOrNull: CamoSkin? // null when there's no provider; never used by Camo* components
val themeOrNull: CamoTheme?
}
| Name | What it's for |
|---|---|
CamouflageProvider | set or override the skin and/or theme for a subtree |
Camouflage.skin / .theme | read by core components and, rarely, by app code (a custom chart that wants colors.primary) |
Camouflage.skinOrNull / .themeOrNull | for family packages that must also work in an app without a provider (Blueprint, Storybook, camouflage-filesystem): if the app has a provider, their UI follows its skin and theme; if not, they wrap their UI in their own CamouflageProvider(MinimalSkin, minimalLight). Camo* components never use them, so they still fail fast. |
Camouflage.colors … .motion | shortcuts so app code reads Camouflage.colors.primary instead of Camouflage.theme.colors.primary |
Camouflage.contentColor, Camouflage.iconStyle | what CamoText / CamoIcon (and your own icon widgets) use when no color or size is given (set by renderers, see Skin Contract §2.1) |
Tree keys LocalCamoSkin, LocalCamoTheme, LocalCamoContentColor, LocalCamoIconStyle (Kotlin) / CamouflageScope (Flutter) | the storage. Internal, except where a platform needs them public for tests |
3.1 Inheritance rules
| Outer provides | Inner provides | Effective inside inner |
|---|---|---|
| skin A, theme T | nothing | A, T |
| skin A, theme T | theme U | A, U |
| skin A, theme T | skin B | B, T |
| skin A, theme T | skin B, theme U | B, U |
| nothing (no outer) | skin B only | fail fast: no theme anywhere |
| nothing | theme U only | fail fast: no skin anywhere |
| nothing | skin B, theme U | B, U |
The error message names what is missing and where:
No CamouflageProvider found above CamoButton: missing skin. Wrap your app in CamouflageProvider(skin = …, theme = …).
3.2 Adaptive root (skin per platform)
val skin = when (currentPlatform) {
Android, Web -> MinimalSkin // or MaterialSkin once built (Later)
Desktop -> FluentSkin // v1 (ADR-38)
iOS -> MinimalSkin // or CupertinoSkin once built (Later)
}
CamouflageProvider(skin = skin, theme = if (systemIsDark) brandDark else brandLight) { App() }
This is the Flutter-style "adaptive" behavior, but done once at the root instead of with .adaptive constructors on every widget.
3.3 Runtime switching
Switching means passing a different value to a provider (from app state):
var dark by state(false)
var skin by state(MinimalSkin)
CamouflageProvider(skin = skin, theme = if (dark) brandDark else brandLight) {
SettingsScreen(onToggleDark = { dark = !dark }, onPickSkin = { skin = it })
}
Every component below re-renders with the new values. Component state (text typed, checkbox value, which dialog is open) lives in the app, because components are controlled. Visual-only state inside renderers (a ripple in flight) may reset, and that's acceptable.
4. Build steps
- Create the tree keys (
LocalCamoSkin,LocalCamoTheme,LocalCamoContentColor,LocalCamoIconStyle/CamouflageScope) with no default value, so a missing provider is detectable. - Implement
CamouflageProvider:- read the parent values (nullable);
- resolve the effective values with the rules in §3.1;
- apply reduced motion;
- set the content color and icon style;
- provide the result.
- Implement the
Camouflageaccessors with the fail-fast error message. - Use
DebugSkinfrom Skin Contract with a sample theme to render one placeholder component under a provider. - Tests:
- each row of the inheritance table;
- the error text when there is no provider, and when there is only a theme;
- switching the skin re-renders the child;
- reduced motion zeroes the durations.
Done when
- All seven inheritance rows are covered by tests and pass.
- The missing-provider error names the component and the missing half.
- The sample app switches between
DebugSkinand a second debug skin at runtime with a button.
5. Edge cases
| Case | Decided behavior |
|---|---|
| No provider at all | Fail fast on the first component, with the message in §3.1. There is no silent default: a silent default would hide the bug until a designer notices the wrong look. |
| Partial nested provider (theme only) | It inherits the skin from above (row 2 of the table). |
| Switching skin or theme while a text field is focused | Focus and text survive, because the value lives in the app and focus lives in the platform's focus system, keyed by the component's position in the tree. The skin switch must not change the tree position of the input. Platform notes enforce this by keeping the editable text node in the component (core), not in the renderer. |
| Switching while a dialog is open | The dialog stays open (it's an overlay entry, independent of the screen's state) and redraws with the new skin. |
| Dialogs, menus and other overlays | They render in a separate platform layer (a window/overlay), outside the caller's subtree. In Flutter, showCamoDialog/showCamoBottomSheet capture the effective skin and theme at the call site and re-provide them inside the route. In Compose, the Navigation 3 entry renders inside the NavDisplay's provider tree (see Overlays). Without this, a dialog opened from a nested promo section would lose the promo theme or crash with "no provider". |
| Deep nesting (a provider in every list item) | Allowed, but it costs a lookup and possibly a re-render per provider. Guidance: providers belong at screen or section level. Per-item overrides should use component parameters (variant) instead. |
| Text scaling | The provider does not change typography sizes. The platform text scaler applies to every CamoText. Changing sizes at the provider would scale text twice. |
| Reduced motion | Applied once here (theme.copy(motion = motion.reduced())), so renderers need no checks. |
App code reads Camouflage.colors outside any provider | The same fail-fast. |
- ADR-41 is built.
CamoEnvironment(windowSize, input, platform, capabilities)is computed by the root provider and can be set by any provider; nested providers inherit it.CamoBreakpoints(600 / 840 / 1200) live on the theme;CamoCapabilities(backdropBlur, runtimeShaders, windowMaterial, reduceTransparency)is part of the environment (ADR-42). - Adaptive themes:
theme.adapt(rule)adds a rule (they compose in order);theme.forEnvironment(env)runs them and attaches the environment. A provider keeps the theme as written beside the adapted one, so a nested provider with another environment adapts the original, not an already-adapted copy. A theme that already carries that environment (read from a provider and passed on) is returned as is, so rules never run twice. - Order in a provider: the rules run first, then reduced motion.
Camouflage.theme.environmentisnullfor a theme you build and set for the one components read; skins read it indefaults(theme).- Found in the build:
flutter testruns asTargetPlatform.android, so an environment-following default (Fluent's density) differs from the desktop look under test. Goldens pin their density.
Implementation
1. Why
Compose's tree-scoped values are CompositionLocals. This note maps the provider onto them:
- which locals exist;
staticvs dynamic locals, and why;- how the fail-fast error works;
- where the platform
actuals (reduced motion) plug in.
It also covers how overlays (dialogs, sheets) see the provider: they're drawn in-layer by core's frames, inside the tree, so no capture step is needed.
2. Shape
| Local | Kind | Default | Why this kind |
|---|---|---|---|
LocalCamoSkin | staticCompositionLocalOf<CamoSkin?> | null | changes rarely (a skin switch). Static locals don't track readers individually, so reads are cheaper. A change recomposes the whole subtree, which a skin switch needs anyway. |
LocalCamoTheme | staticCompositionLocalOf<CamoTheme?> | null | the same: every component reads it, and it changes rarely (dark mode, brand swap). |
LocalCamoContentColor | compositionLocalOf<Color> | Color.Unspecified | set by every container, often, and deep. Dynamic tracking recomposes only the readers. |
LocalCamoIconStyle | compositionLocalOf<IconStyle?> | null | the same as content color |
The locals are internal. Apps use CamouflageProvider and the Camouflage accessors. Skin authors use ProvideContentStyle (Skin Contract).
3. API
3.1 CamouflageProvider
@Composable
public fun CamouflageProvider(
skin: CamoSkin? = null,
theme: CamoTheme? = null,
content: @Composable () -> Unit,
) {
val effectiveSkin = skin ?: LocalCamoSkin.current
val baseTheme = theme ?: LocalCamoTheme.current
val reduceMotion = rememberReducedMotion() // expect/actual
val effectiveTheme = remember(baseTheme, reduceMotion) {
if (baseTheme != null && reduceMotion) baseTheme.copy(motion = baseTheme.motion.reduced()) else baseTheme
}
// the icon component theme resolves straight to an IconStyle (size + color); until the icon renderer exists (M3), core's default IconStyle(20.dp, onSurface) (ADR-39)
val rootIcon: IconStyle? = effectiveSkin?.let { s -> effectiveTheme?.let { t -> s.icon.defaults(t).merge(t.components.icon) } }
CompositionLocalProvider(
LocalCamoSkin provides effectiveSkin,
LocalCamoTheme provides effectiveTheme,
LocalCamoContentColor provides (effectiveTheme?.colors?.onSurface ?: Color.Unspecified),
LocalCamoIconStyle provides rootIcon,
content = content,
)
}
A provider with both missing (no argument and nothing above) doesn't throw itself. It provides null, and the first component that reads it throws with its own name. That keeps the error pointing at the component that needs it.
3.2 Camouflage accessors
public object Camouflage {
public val skin: CamoSkin
@Composable @ReadOnlyComposable get() = LocalCamoSkin.current ?: missing("skin")
public val theme: CamoTheme
@Composable @ReadOnlyComposable get() = LocalCamoTheme.current ?: missing("theme")
public val colors: CamoColors @Composable @ReadOnlyComposable get() = theme.colors
public val typography: CamoTypography @Composable @ReadOnlyComposable get() = theme.typography
public val shapes: CamoShapes @Composable @ReadOnlyComposable get() = theme.shapes
public val spacing: CamoSpacing @Composable @ReadOnlyComposable get() = theme.spacing
public val elevation: CamoElevation @Composable @ReadOnlyComposable get() = theme.elevation
public val motion: CamoMotion @Composable @ReadOnlyComposable get() = theme.motion
public val contentColor: Color @Composable @ReadOnlyComposable get() = LocalCamoContentColor.current
public val iconStyle: IconStyle @Composable @ReadOnlyComposable get() = LocalCamoIconStyle.current ?: missing("icon style")
public val skinOrNull: CamoSkin? @Composable @ReadOnlyComposable get() = LocalCamoSkin.current // optional use only
public val themeOrNull: CamoTheme? @Composable @ReadOnlyComposable get() = LocalCamoTheme.current
@Composable @ReadOnlyComposable
public inline fun <reified T : CamoTokenSet<T>> tokens(): T =
theme.tokens<T>() ?: missing("token set ${T::class.simpleName}") // ADR-32
}
// components call the named variant so the message names them:
@Composable @ReadOnlyComposable
internal fun requireSkin(component: String): CamoSkin = LocalCamoSkin.current ?: throw CamouflageMissingProviderException(component, "skin")
public class CamouflageMissingProviderException(component: String, missing: String) : IllegalStateException(
"No CamouflageProvider found above $component: missing $missing. " +
"Wrap your app in CamouflageProvider(skin = …, theme = …)."
)
3.3 Reduced motion: expect/actual
// commonMain
@Composable internal expect fun rememberReducedMotion(): Boolean
| Target | actual |
|---|---|
| android | Settings.Global.getFloat(contentResolver, ANIMATOR_DURATION_SCALE, 1f) == 0f (the "Remove animations" setting), read through LocalContext |
| ios | UIAccessibilityIsReduceMotionEnabled(), re-read on UIAccessibilityReduceMotionStatusDidChangeNotification |
| jvm | false (desktop OSes don't expose a common setting to the JVM; revisit per-OS later) |
| wasmJs | window.matchMedia("(prefers-reduced-motion: reduce)").matches, updated through a change listener in a DisposableEffect |
3.4 Adaptive root and runtime switching
@Composable
fun SampleApp() {
var dark by rememberSaveable { mutableStateOf(false) }
var brand by rememberSaveable { mutableStateOf(Brand.Default) }
val theme = animateCamoTheme(brand.theme(dark)) // optional smooth switch
CamouflageProvider(skin = MinimalSkin, theme = theme) {
SettingsScreen(onToggleDark = { dark = !dark }, onBrand = { brand = it })
}
}
Pass isSystemInDarkTheme() (common Compose API, works on every target) as the initial dark value to follow the system.
4. Build steps
- The four locals (
internal),IconStyle, andCamouflageMissingProviderException. CamouflageProviderwith the inheritance rules and the root content color and icon style.Camouflageaccessors +requireSkin(component)/requireTheme(component).rememberReducedMotionexpect+ the fouractuals.commonTestwithrunComposeUiTest:- each of the seven inheritance rows from Provider and Scoping §3.1;
- the exception message for "no provider" and "theme only";
- a skin switch recomposes a child;
- (M6, with the frame, ADR-39) a standalone
CamoDialogFrameinside a nested provider reads the nested theme.
Done when
- All seven inheritance rows pass on jvm and iOS simulator.
- The sample switches skin, theme and dark mode at runtime on all four platforms.
- Turning on "Remove animations" (Android) or "Reduce Motion" (iOS) makes transitions instant.
5. Edge cases
| Case | Decided behavior |
|---|---|
| Dialogs and sheets | Core's CamoDialogFrame/CamoSheetFrame draw in-layer, inside the composition. With Navigation 3 they render inside NavDisplay, which sits inside the root provider, so they see the root skin and theme. A screen-local override doesn't reach a separate entry: apply it inside the entry's content (Overlays §5). Platform Popups (tooltips later) inherit locals through the parent CompositionContext. |
A static local changing | It recomposes everything below that reads any part of the subtree. Fine for skin and theme switches (rare, whole-screen changes anyway). Don't put frequently changing values in them. |
@ReadOnlyComposable accessors throwing | Throwing during composition surfaces as a crash with the message, which is what fail-fast wants. It shows in previews too, so wrap previews in a provider. |
Previews (Android Studio / IntelliJ @Preview) | Core ships CamouflagePreview(skin, theme) { } (no defaults, so core still has no default skin, ADR-9); camouflage-skin-minimal ships MinimalPreview(dark = false) { }. Apps use them in their own previews; no extra artifact. |
| Reduced motion changing while the app runs (iOS, web) | The actuals listen for changes and recompose. On Android the setting is read on composition, and changing it usually recreates the activity anyway. |
| Text scale | Handled by Compose's LocalDensity.fontScale. Camouflage never touches it. |
CamouflageProviderhas an overload withenvironment: CamoEnvironment(a required argument, so the existing positional calls stay unambiguous).Camouflage.environmentreads it; outside a provider it computes one.- The system environment follows the window's
containerSize(so tests fake a width with aWindowInfo, like the select) and each platform'sexpect/actual: Android 12+ for blur and 13+ for shaders; iOS reads Reduce Transparency and its change notification; the desktop JVM detects the OS (Mica only on Windows 11); wasm readsprefers-reduced-transparency.
Web (planned)
1. Why
On Kotlin and Flutter the provider writes a skin and a theme into the UI tree, and components read the nearest one. On the web the tree is the DOM, and there are two carriers for the same information:
- CSS custom properties carry the theme. They cascade through the DOM, cross shadow roots and work without JavaScript, so they are server-safe (Theme).
- The context protocol carries the skin and the environment (window size, input kind, capabilities). A component asks for them with a DOM event that the nearest
camo-providerabove it answers (@lit/context, the W3C community protocol, so non-Lit elements can take part).
2. Shape
Responsibilities of the provider (the same as in the base note):
- Resolve the effective skin and theme: its own value, else the one inherited from the provider above.
- Apply system adjustments once: reduced motion zeroes the motion tokens; reduced transparency and blur support feed the capabilities.
- Reset the content color and icon style for its subtree (
--camo-content-color,--camo-icon-size), so text and icons outside any container are readable. - Provide the environment:
windowSize(Compact, Medium, Expanded, Large),input(Touch, Pointer),platformandcapabilities(ADR-41, ADR-42).
3. API
3.1 The element
<camo-provider skin="minimal" scheme="light">
<camo-button appearance="solid">Save</camo-button>
</camo-provider>
| Attribute / property | Meaning |
|---|---|
skin (attribute, a registered name) | selects a skin by name; needs the skin's register entry (see the Skin Contract note) |
.skin (property, a CamoSkin) | the typed way from TypeScript; wins over the attribute |
scheme (light, dark; reflected as data-camo-scheme) | the color scheme for the subtree; with none, prefers-color-scheme decides |
.theme (property, a CamoTheme) | applies a theme object (applyTheme); equivalent to setting the variables by hand |
.adjustTheme (property, a function) | after ADR-44: applied to the effective theme, before the system adjustments |
The provider is display: contents, so it never changes layout.
3.2 Reading from code
import { camouflage } from "@srctool/camouflage-core";
class MyWidget extends LitElement {
private cx = camouflage(this); // a reactive controller: skin, theme, environment
render() {
return html`<span style="color: var(--camo-color-primary)">${this.cx.environment.input}</span>`;
}
}
camouflage(host) returns a typed controller with skin, theme (as resolved values), tokens<T>() for a brand's token set, environment and contentColor. A change in the provider re-renders the hosts that read it.
3.3 Environment
| Value | Source on the web |
|---|---|
windowSize | a ResizeObserver on the provider, with the breakpoints of ADR-41 |
input | matchMedia("(pointer: coarse)") and (hover: none) |
platform | Web, or the host platform inside Tauri when the app sets it |
capabilities.backdropBlur | CSS.supports("backdrop-filter", "blur(1px)") |
capabilities.runtimeShaders | true where SVG displacement filters work inside backdrop-filter (Chromium); false elsewhere |
capabilities.windowMaterial | false on the web |
capabilities.reduceTransparency | matchMedia("(prefers-reduced-transparency: reduce)") |
| reduced motion | matchMedia("(prefers-reduced-motion: reduce)"), kept live with a change listener |
On the server none of these can be measured. The server uses attributes and defaults (the provider's window-size, input and platform attributes, with sensible defaults) and corrects them on the client after hydration. See the SSR note.
3.4 Inheritance rules
The seven rows of the base note apply. In short: a nested provider with no value inherits from the one above; with a skin, only the skin changes; with a theme, only the theme changes (until ADR-44, which adds adjustTheme). On the web the theme half is the CSS cascade itself, so a partial theme needs no merge code.
4. Build steps
- The registry and the context keys (
skin,environment) with@lit/context. camo-providerwith theskin,schemeand theme-variable handling.- The
camouflage(host)controller. - The environment sources of §3.3, each behind a small function so the server can replace them.
- Tests in the browser: nesting, inheritance, scheme per subtree, live reduced motion; and a render-to-string test with attributes only.
Done when
- A nested provider changes only what it sets.
- A component outside any provider renders with the fallback and logs once in development.
- Every row of the inheritance table has a test.
5. Edge cases
| Case | Decided behavior |
|---|---|
| A component with no provider | Decided (ADR-48): with a fallback skin registered (Minimal's register entry does it) it uses that skin and its starter theme; with none it renders unstyled but working and warns once. It never throws, because that would break server rendering. This differs from Kotlin and Flutter, which fail fast. |
The skin attribute names an unregistered skin | One warning naming it, then the fallback as above (tested on the server). |
| A component is moved to another provider | It re-requests the context and re-renders (the context protocol handles reconnection). |
| Nested providers in different shadow roots | Context requests cross shadow roots (the events are composed), CSS variables inherit through them, so it works. |
Two copies of core on one page | The context key is a Symbol.for(...), so they share it; a version mismatch warns once. |
6. What W1 settled (srctool/camouflage-web#10)
| Finding | Decision |
|---|---|
| Environment sources | Each value the environment reads is a small replaceable function (setEnvironmentSources): viewport width and its changes, media queries (read and watched), CSS.supports. A server (or a test) replaces them; with none that answer, the provider keeps its attributes and defaults. |
| Reduced motion | Part of the environment (reducedMotion), live through a change listener, and also zeroed in CSS (prefers-reduced-motion) for the durations, so it works with no JavaScript. |
| Input | (pointer: coarse) or (hover: none) is touch. |
| Measured beats attributes | window-size, input and platform are the server's guesses; once the client measures, the measurement wins. |
camouflage(host) | skin, theme (values, for the scheme in force), scheme, tokens(name) (names the missing set), environment, contentColor (the live reference var(--camo-content-color)). |
| Content reset | The provider resets color, --camo-content-color and --camo-icon-size for its subtree. |
| Inheritance rows | The seven rows are tested, including the three with no provider above (a skin only, a theme only, both). With a theme only, the fallback skin takes it. |
.adjustTheme | Not built: ADR-44 is still proposed. createCamoTheme is its web equivalent. |