@omerdlw/base-framework 3.2.1 → 3.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/MIGRATION.md +24 -0
- package/dist/ambient/index.js +8 -8
- package/dist/ambient/server/index.js +2 -2
- package/dist/ambient/worker/index.js +1 -1
- package/dist/background/index.js +7 -7
- package/dist/{chunk-GQKGOLHJ.js → chunk-67MOKJFZ.js} +178 -79
- package/dist/chunk-67MOKJFZ.js.map +1 -0
- package/dist/{chunk-2BLGNT5I.js → chunk-6IP6YFQX.js} +6 -6
- package/dist/{chunk-2BLGNT5I.js.map → chunk-6IP6YFQX.js.map} +1 -1
- package/dist/{chunk-CT4UILO2.js → chunk-7VU2OAJB.js} +4 -77
- package/dist/chunk-7VU2OAJB.js.map +1 -0
- package/dist/{chunk-5H6FZW3N.js → chunk-D222OCTV.js} +15 -9
- package/dist/chunk-D222OCTV.js.map +1 -0
- package/dist/{chunk-2LGI33JP.js → chunk-GKAJ4EM2.js} +169 -73
- package/dist/chunk-GKAJ4EM2.js.map +1 -0
- package/dist/{chunk-66MHDFNF.js → chunk-HFR6YROB.js} +9 -16
- package/dist/chunk-HFR6YROB.js.map +1 -0
- package/dist/{chunk-ZE6OGGA7.js → chunk-IH3STE7W.js} +120 -49
- package/dist/chunk-IH3STE7W.js.map +1 -0
- package/dist/chunk-K3LXE6D5.js +17 -0
- package/dist/{chunk-IR3DCLBM.js.map → chunk-K3LXE6D5.js.map} +1 -1
- package/dist/{chunk-NTUQYA73.js → chunk-KOYTJW5E.js} +60 -9
- package/dist/chunk-KOYTJW5E.js.map +1 -0
- package/dist/{chunk-WYVA6AN5.js → chunk-LKYW4LH6.js} +5 -5
- package/dist/{chunk-WYVA6AN5.js.map → chunk-LKYW4LH6.js.map} +1 -1
- package/dist/{chunk-PUD4IB3L.js → chunk-NCXFWCXP.js} +497 -366
- package/dist/chunk-NCXFWCXP.js.map +1 -0
- package/dist/{chunk-J4WUCHNR.js → chunk-QRXDXAQI.js} +5 -5
- package/dist/{chunk-J4WUCHNR.js.map → chunk-QRXDXAQI.js.map} +1 -1
- package/dist/{chunk-AAT3QWHN.js → chunk-R4K6VAOK.js} +4 -4
- package/dist/{chunk-AAT3QWHN.js.map → chunk-R4K6VAOK.js.map} +1 -1
- package/dist/{chunk-OEXWOZPS.js → chunk-RGC2VFQO.js} +6 -6
- package/dist/chunk-RGC2VFQO.js.map +1 -0
- package/dist/chunk-TAWTGCWJ.js +113 -0
- package/dist/chunk-TAWTGCWJ.js.map +1 -0
- package/dist/{chunk-LTO77WSO.js → chunk-UDJ7ARCH.js} +3 -3
- package/dist/{chunk-LTO77WSO.js.map → chunk-UDJ7ARCH.js.map} +1 -1
- package/dist/{chunk-26K6W4OQ.js → chunk-UE2KBW3D.js} +7 -7
- package/dist/{chunk-26K6W4OQ.js.map → chunk-UE2KBW3D.js.map} +1 -1
- package/dist/{chunk-WBBM67WL.js → chunk-UQLTP3XB.js} +6 -6
- package/dist/{chunk-WBBM67WL.js.map → chunk-UQLTP3XB.js.map} +1 -1
- package/dist/{chunk-LA3CQ6NY.js → chunk-VNSMNGWP.js} +5 -5
- package/dist/{chunk-LA3CQ6NY.js.map → chunk-VNSMNGWP.js.map} +1 -1
- package/dist/{chunk-Y2Q74PJP.js → chunk-WQTMOUCA.js} +3 -3
- package/dist/{chunk-Y2Q74PJP.js.map → chunk-WQTMOUCA.js.map} +1 -1
- package/dist/chunk-WZ5T2NXH.js +702 -0
- package/dist/chunk-WZ5T2NXH.js.map +1 -0
- package/dist/{chunk-RF2YGILF.js → chunk-XGAYTDSI.js} +37 -37
- package/dist/chunk-XGAYTDSI.js.map +1 -0
- package/dist/{chunk-KMN6J5SL.js → chunk-YZS2B6YE.js} +6 -6
- package/dist/{chunk-KMN6J5SL.js.map → chunk-YZS2B6YE.js.map} +1 -1
- package/dist/{chunk-5GVH4BQV.js → chunk-ZXRE2KZO.js} +5 -5
- package/dist/{chunk-5GVH4BQV.js.map → chunk-ZXRE2KZO.js.map} +1 -1
- package/dist/context-menu/index.js +13 -13
- package/dist/controls/index.js +4 -4
- package/dist/core/kernel/hooks.d.ts.map +1 -1
- package/dist/core/kernel/operations-records.d.ts +7 -0
- package/dist/core/kernel/operations-records.d.ts.map +1 -1
- package/dist/core/kernel/operations-resolve.d.ts.map +1 -1
- package/dist/core/kernel/operations.d.ts.map +1 -1
- package/dist/core/kernel/stabilize.d.ts.map +1 -1
- package/dist/core/provider/index.d.ts.map +1 -1
- package/dist/dock/index.js +12 -12
- package/dist/error/index.js +5 -5
- package/dist/foundation/recipes/cn.d.ts +3 -3
- package/dist/foundation/recipes/cn.d.ts.map +1 -1
- package/dist/foundation/recipes/define.d.ts +2 -3
- package/dist/foundation/recipes/define.d.ts.map +1 -1
- package/dist/foundation/recipes/recipe.d.ts +4 -4
- package/dist/foundation/recipes/recipe.d.ts.map +1 -1
- package/dist/foundation/utils/scheduler.d.ts +1 -1
- package/dist/foundation/utils/scheduler.d.ts.map +1 -1
- package/dist/hooks/index.js +2 -2
- package/dist/index.js +22 -22
- package/dist/kernel/index.js +3 -3
- package/dist/loading/index.js +6 -6
- package/dist/media/index.js +4 -4
- package/dist/modal/index.js +11 -11
- package/dist/modules/ambient/analyze-ground.d.ts +42 -0
- package/dist/modules/ambient/analyze-ground.d.ts.map +1 -0
- package/dist/modules/ambient/analyze.d.ts +1 -1
- package/dist/modules/ambient/analyze.d.ts.map +1 -1
- package/dist/modules/ambient/dom.d.ts.map +1 -1
- package/dist/modules/ambient/hooks.d.ts.map +1 -1
- package/dist/modules/ambient/settings.d.ts.map +1 -1
- package/dist/modules/ambient/types.d.ts +16 -4
- package/dist/modules/ambient/types.d.ts.map +1 -1
- package/dist/modules/background/context.d.ts.map +1 -1
- package/dist/modules/dock/hooks/use-card-item-model.d.ts +4 -4
- package/dist/modules/dock/hooks/use-dock-height-controller.d.ts +1 -1
- package/dist/modules/dock/hooks/use-dock-height-controller.d.ts.map +1 -1
- package/dist/modules/dock/hooks/use-dock-viewport.d.ts.map +1 -1
- package/dist/modules/dock/lib/helpers.d.ts +1 -1
- package/dist/modules/dock/lib/helpers.d.ts.map +1 -1
- package/dist/modules/dock/lib/styles.d.ts +2 -2
- package/dist/modules/dock/model/layout.d.ts +19 -4
- package/dist/modules/dock/model/layout.d.ts.map +1 -1
- package/dist/modules/dock/model/paths.d.ts +7 -0
- package/dist/modules/dock/model/paths.d.ts.map +1 -1
- package/dist/modules/dock/motion.d.ts +2 -2
- package/dist/modules/dock/routing/navigation.d.ts.map +1 -1
- package/dist/modules/dock/runtime/dock.d.ts.map +1 -1
- package/dist/modules/dock/runtime/hooks/use-dock.d.ts.map +1 -1
- package/dist/modules/dock/types/card.d.ts +6 -0
- package/dist/modules/dock/types/card.d.ts.map +1 -1
- package/dist/modules/dock/types/theme.d.ts +20 -0
- package/dist/modules/dock/types/theme.d.ts.map +1 -1
- package/dist/modules/index.js +20 -20
- package/dist/modules/modal/module.d.ts.map +1 -1
- package/dist/navigation/index.js +7 -7
- package/dist/notification/index.js +5 -5
- package/dist/overlay-7QLGWHCH.js +13 -0
- package/dist/{overlay-YC336DAS.js.map → overlay-7QLGWHCH.js.map} +1 -1
- package/dist/provider/index.js +9 -8
- package/dist/react/ui/components/tooltip-group.d.ts +34 -0
- package/dist/react/ui/components/tooltip-group.d.ts.map +1 -0
- package/dist/react/ui/components/tooltip-placement.d.ts +43 -0
- package/dist/react/ui/components/tooltip-placement.d.ts.map +1 -0
- package/dist/react/ui/components/tooltip-slot.d.ts +23 -0
- package/dist/react/ui/components/tooltip-slot.d.ts.map +1 -0
- package/dist/react/ui/components/tooltip.d.ts +9 -7
- package/dist/react/ui/components/tooltip.d.ts.map +1 -1
- package/dist/react/ui/types.d.ts +24 -3
- package/dist/react/ui/types.d.ts.map +1 -1
- package/dist/recipes/index.js +22 -3
- package/dist/recipes/index.js.map +1 -1
- package/dist/ui/index.js +8 -8
- package/dist/utils/index.js +13 -7
- package/dist/utils/index.js.map +1 -1
- package/docs/architecture-and-rules.md +0 -2
- package/docs/core-engine.md +2 -2
- package/docs/design.md +17 -17
- package/docs/getting-started.md +6 -7
- package/docs/modules/ambient.md +79 -58
- package/docs/modules/dock.md +15 -15
- package/docs/modules/modal.md +2 -2
- package/package.json +1 -4
- package/dist/chunk-2LGI33JP.js.map +0 -1
- package/dist/chunk-37OBXNEO.js +0 -116
- package/dist/chunk-37OBXNEO.js.map +0 -1
- package/dist/chunk-5H6FZW3N.js.map +0 -1
- package/dist/chunk-66MHDFNF.js.map +0 -1
- package/dist/chunk-7RSRDKYE.js +0 -22
- package/dist/chunk-7RSRDKYE.js.map +0 -1
- package/dist/chunk-CT4UILO2.js.map +0 -1
- package/dist/chunk-GQKGOLHJ.js.map +0 -1
- package/dist/chunk-IR3DCLBM.js +0 -17
- package/dist/chunk-NTUQYA73.js.map +0 -1
- package/dist/chunk-OEXWOZPS.js.map +0 -1
- package/dist/chunk-PUD4IB3L.js.map +0 -1
- package/dist/chunk-RF2YGILF.js.map +0 -1
- package/dist/chunk-ZE6OGGA7.js.map +0 -1
- package/dist/overlay-YC336DAS.js +0 -13
package/docs/modules/ambient.md
CHANGED
|
@@ -28,12 +28,14 @@ client image URL ─fetch─▶ createImageBitmap ─────┤ (w
|
|
|
28
28
|
▼
|
|
29
29
|
roles: dominant · vibrant · muted · accent (each: colour, `on`, 11-tone ramp)
|
|
30
30
|
regions: top · bottom · left · right · center
|
|
31
|
-
|
|
31
|
+
page: the page tone for the ground (dark or light) · presence: how colourful
|
|
32
32
|
▼
|
|
33
33
|
CSS variables on the target element ─▶ everything that reads them re-tints
|
|
34
34
|
```
|
|
35
35
|
|
|
36
|
-
Ambient is a **colour pipeline**, not a component: pick an image (or pass colors directly), and the `--ambient-*` variables change. The app maps its own tokens onto them, e.g. `:root { --primary: var(--ambient-vibrant, #101010); --
|
|
36
|
+
Ambient is a **colour pipeline**, not a component: pick an image (or pass colors directly), and the `--ambient-*` variables change. The app maps its own tokens onto them, e.g. `:root { --primary: var(--ambient-vibrant, #101010); --bg: var(--ambient-page, #0b0b0b) }`; Tailwind classes such as `bg-primary` and anything using `var(--bg)` then follow automatically, and the fallbacks apply whenever no palette is set.
|
|
37
|
+
|
|
38
|
+
A palette is made for one **ground**, the kind of page it lies on: `"dark"` (default) or `"light"`. The app says which once (`configureAmbient({ analysis: { ground: "light" } })`, and the same `analysis` on the server); the framework then makes the page tone, the region glows and the roles for that ground, and stays out of everything else. See §6.1.
|
|
37
39
|
|
|
38
40
|
A palette is plain JSON (~2.7 KB), so it can be computed once on the server, cached, and passed down as `initialPalette`. When its `source` is the same image URL, the client does not extract again. Client extraction is the fallback.
|
|
39
41
|
|
|
@@ -53,7 +55,7 @@ useAmbientTheme({ image: backdropUrl || account?.avatarUrl || null });
|
|
|
53
55
|
// 4. Explicit colors, scoped to one element
|
|
54
56
|
const cardRef = useRef<HTMLDivElement>(null);
|
|
55
57
|
useAmbientTheme({
|
|
56
|
-
colors: { "--ambient-vibrant": "#e5d3ff", "--ambient-
|
|
58
|
+
colors: { "--ambient-vibrant": "#e5d3ff", "--ambient-page": "#140d1f" },
|
|
57
59
|
scope: cardRef,
|
|
58
60
|
});
|
|
59
61
|
```
|
|
@@ -110,14 +112,15 @@ The app builds the `Worker` itself because only its bundler can turn `new URL(".
|
|
|
110
112
|
|
|
111
113
|
Default names; see §5.2 to rename them or turn groups off. Nothing is written until a palette exists.
|
|
112
114
|
|
|
113
|
-
| Variable | Value
|
|
114
|
-
| :----------------------------- |
|
|
115
|
-
| `--ambient-
|
|
116
|
-
| `--ambient-
|
|
117
|
-
| `--ambient-
|
|
118
|
-
| `--ambient-{role}
|
|
119
|
-
| `--ambient-{
|
|
120
|
-
|
|
|
115
|
+
| Variable | Value |
|
|
116
|
+
| :----------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------- |
|
|
117
|
+
| `--ambient-page` | the page tone for the ground (§6.1): dark L ≈ 0.16 in the shadows' hue; light L 0.9–0.955 in the image's mood (chroma 0 for grey images) |
|
|
118
|
+
| `--ambient-presence` | how colourful the image is, `0` (grey) … `1`: e.g. the opacity of a wash |
|
|
119
|
+
| `--ambient-{role}` | the role's colour; roles: `dominant`, `vibrant`, `muted`, `accent` |
|
|
120
|
+
| `--ambient-on-{role}` | text colour on that role, ≥ 4.5:1 (WCAG 2) by default |
|
|
121
|
+
| `--ambient-{role}-{tone}` | ramp tones `10 15 20 30 40 50 60 70 80 90 95` (= OKLCH L × 100) |
|
|
122
|
+
| `--ambient-{region}` | regions: `top`, `bottom`, `left`, `right`, `center` |
|
|
123
|
+
| any variable named in `colors` | the literal value |
|
|
121
124
|
|
|
122
125
|
`colors` keys are custom property names: a key starting with `--` is used verbatim; anything else becomes `--color-<key>`. `colors` always wins over extracted values.
|
|
123
126
|
|
|
@@ -164,23 +167,25 @@ Until a palette exists the shared state's `palette` is `null` and no variable is
|
|
|
164
167
|
|
|
165
168
|
Settings live on `globalThis`, so every bundled copy of the module (one per package entry) shares them. Call it once at start-up, in a client module (and on the server too if you change `analysis`).
|
|
166
169
|
|
|
167
|
-
| Setting | Default
|
|
168
|
-
| :----------- |
|
|
169
|
-
| `proxy` | `"/api/ambient/proxy?url="`
|
|
170
|
-
| `strategy` | `"auto"`
|
|
171
|
-
| `worker` | `null`
|
|
172
|
-
| `cssVars` | `--ambient-
|
|
173
|
-
| `analysis` | `DEFAULT_ANALYSIS`
|
|
174
|
-
| `cacheLimit` | `100`
|
|
175
|
-
| `linger` | `3000` (`DEFAULT_LINGER_MS`)
|
|
170
|
+
| Setting | Default | Meaning |
|
|
171
|
+
| :----------- | :----------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
172
|
+
| `proxy` | `"/api/ambient/proxy?url="` | Tried last, only for cross-origin images whose direct request (and its one cache-bypassing retry) failed. A string is a prefix the encoded URL is appended to, or a template with `{url}`; a function returns the URL; `null` turns it off. |
|
|
173
|
+
| `strategy` | `"auto"` | `"auto"`: the worker if one is configured, else the main thread. `"worker"`: worker only (no main-thread extraction). `"main"`: main thread only. `"none"`: never extract on the client (server palettes only). |
|
|
174
|
+
| `worker` | `null` | `() => Worker` running `serveAmbientWorker()` (§3.2). If it fails to start or errors, extraction falls back to the main thread (except under `"worker"`). |
|
|
175
|
+
| `cssVars` | `--ambient-page`, `--ambient-presence`, `--ambient-{role}`, `--ambient-on-{role}`, `--ambient-{role}-{tone}`, `--ambient-{region}`, all 11 tones | Rename any variable; `null` turns that variable or group off; `tones: [10, 20, 90]` or `false` limits the ramp variables. |
|
|
176
|
+
| `analysis` | `DEFAULT_ANALYSIS` | `sampleSize` 128, `clusters` 7, `centerWeight` 0.5, `letterbox` true, `minHueDistance` 40, `minContrast` 4.5, `ground` `"dark"`. |
|
|
177
|
+
| `cacheLimit` | `100` | Client palettes kept (oldest evicted). |
|
|
178
|
+
| `linger` | `3000` (`DEFAULT_LINGER_MS`) | How long (ms) a page-wide theme's variables stay after it goes, so the next page takes over from them. `0` removes them at once. |
|
|
176
179
|
|
|
177
180
|
### 5.3 `AmbientPalette`
|
|
178
181
|
|
|
179
182
|
```ts
|
|
180
183
|
{
|
|
181
184
|
source?: string | null; // the image URL it was made from
|
|
185
|
+
ground: "dark" | "light"; // the ground it was made for
|
|
182
186
|
neutral: boolean; // the image has (almost) no colour
|
|
183
|
-
|
|
187
|
+
presence: number; // 0 grey … 1 fully coloured
|
|
188
|
+
page: string; // the page tone for the ground (oklch())
|
|
184
189
|
roles: Record<"dominant" | "vibrant" | "muted" | "accent", {
|
|
185
190
|
color: string; on: string; // oklch() strings
|
|
186
191
|
l: number; c: number; h: number;
|
|
@@ -217,29 +222,44 @@ Before every request, redirects included, the host is resolved (`resolve`, defau
|
|
|
217
222
|
- **Clustering.** Pixels are binned by 15-bit RGB (OKLab averaged per bin). Coloured bins (chroma ≥ 0.022) and grey bins are clustered **apart** with weighted, deterministically seeded k-means in OKLab (ΔL counts 0.45×, so hue beats lightness; vivid bins pull up to ~2.5× harder), 5 + 2 clusters by default. Splitting them keeps the greys of a dark poster from using up every cluster and swallowing its one coloured detail. The vivid pull only shapes the clusters: a cluster's colour is the plain mean of its pixels, so a face is not tinted toward the red title it shares a cluster with.
|
|
218
223
|
- **Roles.** A hue's share is that of its family (clusters within 20°). `dominant` = max share × chroma; `vibrant` = max chroma² × share^0.3; `accent` = the best hue at least `minHueDistance` (40°) from `dominant`, or `vibrant` marked `fromImage: false` when the image has one hue; `muted` = the largest low-chroma (≤ 0.09) colour, or a quiet tone of the dominant hue. Skin, hair, wood and tungsten-lit walls (hues near 54°, chroma 0.03–0.12, see `skinLikeness`) count up to 65% less in every pick, roles and regions alike: film frames are full of them, and they are what a frame shows, rarely its mood. Hue trust fades below L 0.28 and above L 0.9.
|
|
219
224
|
- **Tones.** A role keeps about its source's **chroma**, not its share of the gamut: × 1.15 (`dominant`, regions), × 1.3 (`accent`), × 1.35 (`vibrant`), × 1 (`muted`); a faint tint is raised to at most 0.05 so it still reads as a colour; skin is held back up to 30%; and reds and oranges get a 30% lower ceiling, since they read louder than blues at the same chroma. Carrying the gamut share instead (as before `AMBIENT_ANALYSIS_VERSION` 2) turned pale faces and beige rooms into loud orange: at mid lightness orange has twice the room teal has. The ramp keeps the role's share of the gamut at each L (`toneOf`, × 0.96 of `maxChroma`), so a dark tone of blue stays blue; nothing is ever out of gamut.
|
|
220
|
-
- **`
|
|
225
|
+
- **`page`.** Dark ground: the hue of the shadows (clusters at L ≤ 0.5, scored by share × relative chroma) or, without coloured shadows, of `dominant`; at L 0.16 ± 0.02 and up to 0.1 chroma. Light ground: paper in the hue of `dominant` (the image's mood, not its shadows), 35% of its chroma held to 0.01–0.05 (warm and skin hues 30% less, scaled down for faint images), at L 0.955 ± 0.008, stepping down (no lower than 0.9) until the hue has the gamut room for that chroma: near white, sRGB holds five times more yellow than violet, so a yellow film's paper stays near white and a violet one's turns lilac.
|
|
226
|
+
- **`presence`.** The coloured share of the image (weighted by colourfulness and hue trust), 1 from 25% up; 0 for a neutral image.
|
|
221
227
|
- **`on`.** A near-white or near-black carrying a hint of the role's hue, pushed toward pure white / black until it reaches `minContrast`.
|
|
222
|
-
- **Regions.** Each region (thirds of the content box; `center` is the middle half) takes its most chromatic-and-present cluster, coloured by that cluster's own pixels **in the region** (not its frame-wide mean), at
|
|
223
|
-
- **Neutral images.** If coloured pixels make up under 3% (weighted), the palette is grey: `neutral: true`, `dominant`, `vibrant`, `muted`, `
|
|
228
|
+
- **Regions.** Each region (thirds of the content box; `center` is the middle half) takes its most chromatic-and-present cluster, coloured by that cluster's own pixels **in the region** (not its frame-wide mean), at the ground's region lightness (§6.1) and × 1.15 its chroma; `strength` is how coloured the region is.
|
|
229
|
+
- **Neutral images.** If coloured pixels make up under 3% (weighted), the palette is grey: `neutral: true`, `dominant`, `vibrant`, `muted`, `page` and regions have chroma 0, `presence` is 0. A vivid detail (≥ 0.6% of the image, chroma ≥ 0.06) still becomes `accent`, e.g. the red coat in _Schindler's List_.
|
|
224
230
|
- **Cost.** About 3–8 ms per image for the analysis (Node, warm); in Chromium, ~13 ms for a cached image end to end on the main thread, ~20 ms through the worker (off the main thread). ~2.7 KB of JSON per palette.
|
|
225
231
|
- **Cache.** Client: `cacheLimit` palettes (oldest evicted), keyed by URL (+ analysis overrides); concurrent requests share one promise. Server: 500 per process. A cache that outlives a deploy (`unstable_cache`, a database) should carry `AMBIENT_ANALYSIS_VERSION` in its key, so palettes are computed again when the analysis changes.
|
|
226
232
|
- **Stability.** `colors`, `cssVars`, `options` and `initialPalette` are stabilized with `shallowEqual`, so fresh object literals each render do **not** re-apply the theme (keep `cssVars.tones` a constant array). The same pixels always give the same palette.
|
|
227
233
|
- **Failure.** Client: `extractPaletteFromImage` resolves `null` and the hooks keep `initialPalette` (or nothing); it never throws. Server: `null`, except a missing decoder.
|
|
228
234
|
|
|
235
|
+
### 6.1 Grounds
|
|
236
|
+
|
|
237
|
+
Everything else in the analysis (clusters, role picks, skin, ramps, `on`) is the same on both grounds; the ground moves only these:
|
|
238
|
+
|
|
239
|
+
| | `dark` (default) | `light` |
|
|
240
|
+
| :---------------------- | :------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------- |
|
|
241
|
+
| `page` | L 0.16, the shadows' hue | L 0.9–0.955, the mood's (dominant) hue; lower where the hue needs room for its colour |
|
|
242
|
+
| Role lightness bands | dominant 0.42–0.74 · vibrant 0.62–0.84 · muted 0.38–0.66 · accent 0.55–0.8 | dominant 0.42–0.6 · vibrant 0.5–0.64 · muted 0.42–0.58 · accent 0.46–0.62 |
|
|
243
|
+
| Role contrast on `page` | ≥ 3:1 (lifted if needed) | ≥ 4.5:1 (deepened if needed): a role reads as text on paper |
|
|
244
|
+
| Regions | L 0.42–0.72 (glows on dark); colourless 0.3–0.7 | L 0.8–0.9 (pale light on paper); colourless at the page's lightness, so they leave no grey stain |
|
|
245
|
+
|
|
246
|
+
A palette carries its `ground`; an `initialPalette` made for another ground than the one configured is not shown (its page and roles would sit at the wrong lightness), so set the same `analysis.ground` on the server and the client.
|
|
247
|
+
|
|
229
248
|
## 7. Recipes and gotchas
|
|
230
249
|
|
|
231
|
-
| I want to…
|
|
232
|
-
|
|
|
233
|
-
| Tint a page from its hero image
|
|
234
|
-
| No flash, no client work
|
|
235
|
-
| Glows that follow the picture
|
|
236
|
-
| Text on a role colour
|
|
237
|
-
| A surface a few steps
|
|
238
|
-
|
|
|
239
|
-
|
|
|
240
|
-
|
|
|
241
|
-
|
|
|
242
|
-
|
|
|
250
|
+
| I want to… | Do this |
|
|
251
|
+
| :---------------------------------- | :---------------------------------------------------------------------------------------------------- |
|
|
252
|
+
| Tint a page from its hero image | `usePage({ ambient: heroUrl })` |
|
|
253
|
+
| No flash, no client work | Compute on the server (§3.1); add `configureAmbient({ strategy: "none" })` if every image has one |
|
|
254
|
+
| Glows that follow the picture | `radial-gradient(at 20% 0%, color-mix(in oklab, var(--ambient-top) 30%, transparent), transparent)` … |
|
|
255
|
+
| Text on a role colour | `background: var(--ambient-accent); color: var(--ambient-on-accent)` |
|
|
256
|
+
| A surface a few steps off the page | dark: `var(--ambient-dominant-20)` / `-30`; light: `-90` / `-95` |
|
|
257
|
+
| Fade a wash with the image's colour | `opacity: var(--ambient-presence, 0)` |
|
|
258
|
+
| Tint only one section | `useAmbientTheme({ image, scope: "#section" })` |
|
|
259
|
+
| Rename the variables | `configureAmbient({ cssVars: { page: "--bg", role: "--tint-{role}" } })` |
|
|
260
|
+
| Fewer variables on `<html>` | `configureAmbient({ cssVars: { tones: [20, 80], region: null } })` |
|
|
261
|
+
| Own proxy / no proxy | `configureAmbient({ proxy: "/img?u={url}" })` / `{ proxy: null }` |
|
|
262
|
+
| Disable tint on one page | `usePage({ ambient: false })` |
|
|
243
263
|
|
|
244
264
|
- The theme is global by default: two components calling `useAmbientTheme` without `scope` fight over the `--ambient-*` variables; the last effect wins.
|
|
245
265
|
- Cross-origin images that block CORS **and** the proxy cannot be sampled on the client; `initialPalette` (or the app's CSS fallbacks) stays. The server has no CORS limits.
|
|
@@ -248,28 +268,29 @@ Before every request, redirects included, the host is resolved (`resolve`, defau
|
|
|
248
268
|
|
|
249
269
|
## 8. File map
|
|
250
270
|
|
|
251
|
-
| File | Responsibility
|
|
252
|
-
| :-------------------- |
|
|
253
|
-
| `index.ts` | Public barrel export (client entry).
|
|
254
|
-
| `constants.ts` | `ambientTheme` spec.
|
|
255
|
-
| `types.ts` | Palette, swatch, region, settings, config, descriptor, page contracts.
|
|
256
|
-
| `settings.ts` | Defaults, `configureAmbient` (on `globalThis`), proxy resolution. Pure.
|
|
257
|
-
| `oklab.ts` | OKLab/OKLCH math, gamut room (`maxChroma`), tones, WCAG contrast, `on` colours. Pure.
|
|
258
|
-
| `quantize.ts` | Deterministic weighted k-means. Pure.
|
|
259
|
-
| `analyze.ts` | `analyzeAmbientPixels`: roles, ramps, regions, `
|
|
260
|
-
| `analyze-
|
|
261
|
-
| `analyze-
|
|
262
|
-
| `analyze-
|
|
263
|
-
| `analyze-
|
|
264
|
-
| `
|
|
265
|
-
| `
|
|
266
|
-
| `
|
|
267
|
-
| `
|
|
268
|
-
| `server/
|
|
269
|
-
| `
|
|
270
|
-
| `
|
|
271
|
-
| `
|
|
272
|
-
| `
|
|
271
|
+
| File | Responsibility |
|
|
272
|
+
| :-------------------- | :--------------------------------------------------------------------------------------------- |
|
|
273
|
+
| `index.ts` | Public barrel export (client entry). |
|
|
274
|
+
| `constants.ts` | `ambientTheme` spec. |
|
|
275
|
+
| `types.ts` | Palette, swatch, region, settings, config, descriptor, page contracts. |
|
|
276
|
+
| `settings.ts` | Defaults, `configureAmbient` (on `globalThis`), proxy resolution. Pure. |
|
|
277
|
+
| `oklab.ts` | OKLab/OKLCH math, gamut room (`maxChroma`), tones, WCAG contrast, `on` colours. Pure. |
|
|
278
|
+
| `quantize.ts` | Deterministic weighted k-means. Pure. |
|
|
279
|
+
| `analyze.ts` | `analyzeAmbientPixels`: roles, ramps, regions, `page`, `presence`, from the parts below. Pure. |
|
|
280
|
+
| `analyze-ground.ts` | Per-ground lightness bands, the page tone and role readability. Pure. |
|
|
281
|
+
| `analyze-bounds.ts` | Letterbox cut (`findContentBounds`). Pure. |
|
|
282
|
+
| `analyze-clusters.ts` | Binning and clustering of pixels. Pure. |
|
|
283
|
+
| `analyze-measures.ts` | Thresholds, cluster reliability and colorfulness measures. Pure. |
|
|
284
|
+
| `analyze-swatches.ts` | Role chroma and tone fitting, swatch building. Pure. |
|
|
285
|
+
| `pipeline.ts` | fetch → `createImageBitmap` → canvas pixels → analysis; runs in a window or a worker. |
|
|
286
|
+
| `extractor.ts` | Client cache, strategy, worker dispatch with main-thread fallback. |
|
|
287
|
+
| `worker/index.ts` | `serveAmbientWorker` (the `ambient/worker` entry). |
|
|
288
|
+
| `server/index.ts` | `extractAmbientPalette`, sharp decoder, URL guard, server cache (the `ambient/server` entry). |
|
|
289
|
+
| `server/address.ts` | Host normalization and private-address checks for the URL guard. |
|
|
290
|
+
| `dom.ts` | Target resolution, CSS variable maps, scoped style restoration. |
|
|
291
|
+
| `hooks.ts` | `useAmbientColor`, `useAmbientTheme`, `useAmbient`, `useStableObject`. |
|
|
292
|
+
| `context.tsx` | `AmbientContext` and `AmbientProvider` store. |
|
|
293
|
+
| `module.tsx` | `ambientModule`, `resolvePageAmbientTheme`, `defineAmbient`, kernel type augmentation. |
|
|
273
294
|
|
|
274
295
|
## 9. Dependencies
|
|
275
296
|
|
package/docs/modules/dock.md
CHANGED
|
@@ -655,15 +655,15 @@ See [media.md](./media.md) for how sources are registered (`usePage({ media })`,
|
|
|
655
655
|
|
|
656
656
|
## 16. Layout and geometry
|
|
657
657
|
|
|
658
|
-
| What | Value
|
|
659
|
-
| :--------------- |
|
|
660
|
-
| Card
|
|
661
|
-
| Card width | 460 px
|
|
662
|
-
| Published height | `--dock-h` on `<html>` and `dockHeight` in state (card height + 16 px buffer)
|
|
658
|
+
| What | Value |
|
|
659
|
+
| :--------------- | :--------------------------------------------------------------------------------------------------------------- |
|
|
660
|
+
| Card height | content + `motion.deck.padding` × 2 (default 10 px); at least 48 px / HUD 32 px + padding; viewport margin 24 px |
|
|
661
|
+
| Card width | `motion.deck.width` (default 460 px), or the card/surface `width`; clamped to `viewport − 16/32 px` |
|
|
662
|
+
| Published height | `--dock-h` on `<html>` and `dockHeight` in state (card height + 16 px buffer) |
|
|
663
663
|
|
|
664
664
|
These are what the layout **measures**, so they stay in the module. Where the cards _rest_ is yours: `motion.deck.stacking` holds the offsets, scales, depth fade and how many cards stay in view ([§17](#17-theming)). If you change a card's height, change `stacking.expanded.offsetY` with it (the starter spaces expanded cards by the card height plus a 4 px gap).
|
|
665
665
|
|
|
666
|
-
Reserve space with `useDockHeight().padding` or `padding-bottom: var(--dock-h)`. Height changes are measured with a `ResizeObserver` and ignored below 0.5 px; during surface close phases the height is locked to the base height.
|
|
666
|
+
Reserve space with `useDockHeight().padding` or `padding-bottom: var(--dock-h)`. The variable sits on `<html>`, so each write restyles the whole page; set `deck.heightVar: false` in the dock theme to skip it and size only the elements that need the height from `dockHeight`. Height changes are measured with a `ResizeObserver` and ignored below 0.5 px; during surface close phases the height is locked to the base height.
|
|
667
667
|
|
|
668
668
|
## 17. Theming
|
|
669
669
|
|
|
@@ -671,15 +671,15 @@ The module contains **no design classes**. Every slot comes from `dockTheme` (`s
|
|
|
671
671
|
|
|
672
672
|
The theme also carries the dock's **motion** (`motion: DockMotion`, [theming §5](../theming.md#5-motion-your-app-owns-every-animation)). Everything the dock animates, and every number that shapes it, is yours:
|
|
673
673
|
|
|
674
|
-
| Key | What you decide
|
|
675
|
-
| :------------------------ |
|
|
676
|
-
| `transitions`, `variants` | Every transition and variant, including `transitions.layout` for parts that slide when their neighbours change (the surface close control, the breadcrumbs).
|
|
677
|
-
| `phases` | What the deck, header and body play in each surface phase (`idle`, `dismissAction`, `expandBody`, `open`, `anticipation`, `collapseBody`, `restoreHeader`): the deck's size/shadow transition (`null` follows its resting one, a function gets the resize distance), its transform transition and `scale` (below 1 compresses it), the body's and header's transitions, and `headerReturn`.
|
|
678
|
-
| `timings` | How long each phase holds (`dismissAction`, `anticipation`, `expandBody`, `collapseBody`, `restoreHeader`) plus the card staggers, in seconds. The surface state machine schedules its phases from these, so they follow the app's tempo. `restoreHeader: 0` skips that phase.
|
|
679
|
-
| `deck` | `elevation`, `peek`, `exit`, `tapScale`; `stacking` (where cards rest: collapsed/expanded offsets, scale, depth fade, the shelf, and how many cards stay in view normally, with an extension shelf and under a status); `breadcrumbOffset`; `fullscreenOpacity`; `origin`; `resizeFallback
|
|
680
|
-
| `opacity` | The resting opacity of the card **banner** and **description**. A page's own `bannerOpacity` or description `style.opacity` still wins.
|
|
681
|
-
| `drag` | The swipe-to-dismiss feel (`elastic`, `range`, `opacity`, `scale`) and `dismiss: { offset, velocity }`, the distance (px) or speed (px/s) past which a swipe closes the surface.
|
|
682
|
-
| `skeleton` | The class of the loading skeletons.
|
|
674
|
+
| Key | What you decide |
|
|
675
|
+
| :------------------------ | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
676
|
+
| `transitions`, `variants` | Every transition and variant, including `transitions.layout` for parts that slide when their neighbours change (the surface close control, the breadcrumbs). |
|
|
677
|
+
| `phases` | What the deck, header and body play in each surface phase (`idle`, `dismissAction`, `expandBody`, `open`, `anticipation`, `collapseBody`, `restoreHeader`): the deck's size/shadow transition (`null` follows its resting one, a function gets the resize distance), its transform transition and `scale` (below 1 compresses it), the body's and header's transitions, and `headerReturn`. |
|
|
678
|
+
| `timings` | How long each phase holds (`dismissAction`, `anticipation`, `expandBody`, `collapseBody`, `restoreHeader`) plus the card staggers, in seconds. The surface state machine schedules its phases from these, so they follow the app's tempo. `restoreHeader: 0` skips that phase. |
|
|
679
|
+
| `deck` | `elevation`, `peek`, `exit`, `tapScale`; `stacking` (where cards rest: collapsed/expanded offsets, scale, depth fade, the shelf, and how many cards stay in view normally, with an extension shelf and under a status); `breadcrumbOffset`; `fullscreenOpacity`; `origin`; `resizeFallback`; `width` (optional resting card width in px, default 460); `padding` (the card's vertical padding per side, px, default 10: match your CSS). |
|
|
680
|
+
| `opacity` | The resting opacity of the card **banner** and **description**. A page's own `bannerOpacity` or description `style.opacity` still wins. |
|
|
681
|
+
| `drag` | The swipe-to-dismiss feel (`elastic`, `range`, `opacity`, `scale`) and `dismiss: { offset, velocity }`, the distance (px) or speed (px/s) past which a swipe closes the surface. |
|
|
682
|
+
| `skeleton` | The class of the loading skeletons. |
|
|
683
683
|
|
|
684
684
|
The framework ships no dock motion: write `DockMotion` in your app. Geometry and opacities are not times, so tempo and reduced motion leave them alone; only transitions and `timings` are stretched or collapsed.
|
|
685
685
|
|
package/docs/modules/modal.md
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
| :----------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
11
11
|
| **Import** | `import { defineModal, useModal, ModalContainer, … } from "@omerdlw/base-framework/modal"` |
|
|
12
12
|
| **Module id** | `modal` (`modalModule`, in `defaultModules`) |
|
|
13
|
-
| **Renders** | `Modal` overlay, **lazy-loaded** (`
|
|
13
|
+
| **Renders** | `Modal` overlay, **lazy-loaded** (`React.lazy`, mounted after the first open, chunk preloaded when idle), portalled to `document.body` |
|
|
14
14
|
| **Registry type** | `modal` — key policy `named`, value kind `component`, lifecycle `immediate` (entries are removed the moment the registering page unmounts; the declared 600 ms delay applies only if a registration opts into `graceful` / `route`) |
|
|
15
15
|
| **Page slice** | `usePage({ modal: { key: Component } })` → `page.modules.modal` (`open`, `set`, + actions) |
|
|
16
16
|
| **Peers (`uses`)** | none |
|
|
@@ -228,5 +228,5 @@ Folder layout ([README §4](./README.md#4-canonical-module-template)), under `sr
|
|
|
228
228
|
|
|
229
229
|
## 10. Dependencies
|
|
230
230
|
|
|
231
|
-
- **Uses:** `@omerdlw/base-framework/kernel` (`defineModule`, `useModuleRegistration`, `useRegistryEntries`, `ModuleBoundary`), `@omerdlw/base-framework/utils` (`acquireGlobalScrollLock`, `createStore`), `@omerdlw/base-framework/ui` (`Button`, `Icon`), `@omerdlw/base-framework/theme`, `
|
|
231
|
+
- **Uses:** `@omerdlw/base-framework/kernel` (`defineModule`, `useModuleRegistration`, `useRegistryEntries`, `ModuleBoundary`), `@omerdlw/base-framework/utils` (`acquireGlobalScrollLock`, `createStore`), `@omerdlw/base-framework/ui` (`Button`, `Icon`), `@omerdlw/base-framework/theme`, `motion/react`.
|
|
232
232
|
- **Used by:** `src/core/provider.tsx` (installs it), pages and features through `useModal` / `page.modules.modal`.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@omerdlw/base-framework",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.3.0",
|
|
4
4
|
"description": "Microkernel engine and first-party declarative UI modules for app-like Next.js products.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": [
|
|
@@ -173,9 +173,6 @@
|
|
|
173
173
|
},
|
|
174
174
|
"dependencies": {
|
|
175
175
|
"@iconify-icon/react": "3.0.3",
|
|
176
|
-
"@radix-ui/react-tooltip": "1.2.16",
|
|
177
|
-
"clsx": "2.1.1",
|
|
178
|
-
"loading-dev": "^0.3.5",
|
|
179
176
|
"tailwind-merge": "^3.7.0"
|
|
180
177
|
},
|
|
181
178
|
"devDependencies": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/modules/ambient/oklab.ts","../src/modules/ambient/analyze-bounds.ts","../src/modules/ambient/settings.ts","../src/modules/ambient/analyze-measures.ts","../src/modules/ambient/quantize.ts","../src/modules/ambient/analyze-clusters.ts","../src/modules/ambient/analyze-swatches.ts","../src/modules/ambient/analyze.ts"],"names":["DEG","Math","PI","GAMUT_EPSILON","CHROMA_SEARCH_LIMIT","CHROMA_SEARCH_STEPS","ACHROMATIC_CHROMA","DISPLAY_ACHROMATIC_CHROMA","GAMUT_HEADROOM","DEFAULT_TONE_CHROMA_CAP","DEFAULT_MIN_CONTRAST","ON_COLOR_STEPS","ON_LIGHT_START","ON_LIGHT_STEP","ON_DARK_START","ON_DARK_STEP","LINEAR_LUT","Float32Array","i","v","pow","clamp","value","min","max","smoothstep","edge0","edge1","t","srgbToOklab","r","g","b","lr","lg","lb","l","cbrt","m","s","oklchToLinearSrgb","c","h","a","cos","sin","l_","m_","s_","labToLch","sqrt","atan2","inGamut","rgb","every","maxChroma","low","high","step","middle","hueDistance","d","abs","luminance","map","contrastRatio","la","round","digits","factor","formatOklch","chroma","toFixed","toneOf","rel","cap","room","onColorFor","background","minContrast","light","dark","towardLight","towardDark","useLight","candidate","ALPHA_THRESHOLD","BAR_MEAN_LIGHTNESS","BAR_MAX_LIGHTNESS","MAX_BAR_SHARE","lightnessAt","data","index","findContentBounds","height","width","isBar","count","at","sum","seen","row","y","x","maxRows","floor","maxColumns","top","bottom","column","left","right","AMBIENT_TONES","Object","freeze","AMBIENT_REGIONS","DEFAULT_ANALYSIS","centerWeight","clusters","letterbox","minHueDistance","sampleSize","shadowLightness","DEFAULT_CSS_VAR_NAMES","on","region","role","shadow","tone","DEFAULT_PROXY","DEFAULT_LINGER_MS","createDefaults","analysis","cacheLimit","cssVars","tones","linger","proxy","strategy","worker","SETTINGS_KEY","Symbol","for","scope","globalThis","getAmbientSettings","mergeAmbientSettings","base","input","undefined","configureAmbient","previous","next","resolveAnalysis","overrides","MIN_CHROMA","MIN_PRESENCE","MIN_POPULATION","REGION_BITS","center","reliability","colorfulness","isChromatic","cluster","rely","pickBest","items","score","best","bestScore","item","round3","skinLikeness","warmth","salience","color","seedCentroids","points","weights","centroids","k","distance","n","length","first","set","subarray","nearest","Float64Array","fill","Infinity","found","assignPoints","assignment","moved","bestDistance","j","updateCentroids","sums","w","kmeans","requested","iterations","lightnessWeight","Int32Array","dl","da","db","slice","COLOR_KEY_SPACE","BIN_STRIDE","CENTER_SIGMA","MIN_COLOURED_LIGHTNESS","MIN_CLUSTERS","MAX_CLUSTERS","MANY_CLUSTERS","GREY_CLUSTERS_FEW","GREY_CLUSTERS_MANY","CHROMA_WEIGHT_GAIN","CENTER_REGION_HALF","LOW_EDGE","HIGH_EDGE","regionBitsAt","u","accumulateBins","bounds","boxWidth","boxHeight","binOf","binSums","pixelBins","pixelRegions","Uint8Array","sigma2","total","sumL","bb","du","dv","weight","exp","key","bin","push","local","splitByColour","groups","bins","coloured","allocateBudgets","requestedClusters","greyClusters","clusterBins","budgets","clusterOfBin","forEach","members","group","channel","pop","lch","accumulateRegions","clusterCount","regionWeights","regionLab","bits","clusterAmbientPixels","pixels","options","accumulation","meanL","regions","roleChroma","source","gain","fitTone","buildSwatch","population","fromImage","ramp","roleTone","spec","fallback","dilution","AMBIENT_ANALYSIS_VERSION","FAMILY_HUE_RANGE","MUTED_MAX_CHROMA","MUTED_CHROMA_SPAN","NEUTRAL_ACCENT_MIN_SHARE","NEUTRAL_ACCENT_MIN_CHROMA","ACCENT_MIN_CHROMA","FULL_DILUTION_PRESENCE","MIN_DILUTION","DILUTION_RANGE","GREY_LIGHTNESS_RANGE","DOMINANT_SPEC","VIBRANT_SPEC","MUTED_SPEC","ACCENT_SPEC","REGION_SPEC","REGION_LIGHTNESS_RANGE","REGION_FALLBACK_LIGHTNESS_RANGE","SHADOW_MAX_SOURCE_LIGHTNESS","SHADOW_MIN_SOURCE_CHROMA","SHADOW_MIN_SOURCE_POPULATION","SHADOW_LIGHTNESS_DRIFT","SHADOW_MEAN_LIGHTNESS_PIVOT","SHADOW_MEAN_LIGHTNESS_GAIN","SHADOW_CHROMA_CAP","createFamilyShare","chromatic","family","Map","share","other","get","pickRoleClusters","neutral","dominant","vivid","filter","isAccentCandidate","accent","muted","buildRoles","picks","grey","dominantHue","accentSource","vibrant","Boolean","buildShadow","baseLightness","shadowPick","deepSource","lightness","pickRegionColor","lab","regionTotal","strength","pick","pickScore","part","buildRegion","regionL","chosen","buildRegions","context","analyzeAmbientPixels","presence","reduce","roles","fitSample","size","scale"],"mappings":";AAKA,IAAMA,GAAAA,GAAMC,KAAKC,EAAAA,GAAK,GAAA;AAEtB,IAAMC,aAAAA,GAAgB,IAAA;AAEtB,IAAMC,mBAAAA,GAAsB,GAAA;AAC5B,IAAMC,mBAAAA,GAAsB,EAAA;AAE5B,IAAMC,iBAAAA,GAAoB,IAAA;AAC1B,IAAMC,yBAAAA,GAA4B,IAAA;AAE3B,IAAMC,cAAAA,GAAiB,IAAA;AAC9B,IAAMC,uBAAAA,GAA0B,GAAA;AAChC,IAAMC,oBAAAA,GAAuB,GAAA;AAC7B,IAAMC,cAAAA,GAAiB,EAAA;AACvB,IAAMC,cAAAA,GAAiB,KAAA;AACvB,IAAMC,aAAAA,GAAgB,KAAA;AACtB,IAAMC,aAAAA,GAAgB,IAAA;AACtB,IAAMC,YAAAA,GAAe,KAAA;AAErB,IAAMC,UAAAA,GAAa,IAAIC,YAAAA,CAAa,GAAG,CAAA;AACvC,KAAA,IAASC,CAAAA,GAAI,CAAA,EAAGA,CAAAA,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rE,EAAA,MAAMC,KAAAA,GAAQjW,IAAAA,CAAKsB,GAAAA,CAAI,CAAA,EAAG0U,IAAAA,GAAOhW,KAAKuB,GAAAA,CAAIuE,KAAAA,EAAOD,MAAAA,EAAQ,CAAC,CAAC,CAAA;AAC3D,EAAA,OAAO;AACLA,IAAAA,MAAAA,EAAQ7F,KAAKuB,GAAAA,CAAI,CAAA,EAAGvB,KAAKkE,KAAAA,CAAM2B,MAAAA,GAASoQ,KAAK,CAAC,CAAA;AAC9CnQ,IAAAA,KAAAA,EAAO9F,KAAKuB,GAAAA,CAAI,CAAA,EAAGvB,KAAKkE,KAAAA,CAAM4B,KAAAA,GAAQmQ,KAAK,CAAC;AAC9C,GAAA;AACF","file":"chunk-2LGI33JP.js","sourcesContent":["import type { OklchColor } from \"./types\";\n\nexport type Lab = [l: number, a: number, b: number];\nexport type Rgb = [r: number, g: number, b: number];\n\nconst DEG = Math.PI / 180;\n/** Tolerance when testing whether a linear sRGB channel is inside the gamut. */\nconst GAMUT_EPSILON = 1e-5;\n/** Upper bound for the chroma search, above any sRGB colour's chroma. */\nconst CHROMA_SEARCH_LIMIT = 0.4;\nconst CHROMA_SEARCH_STEPS = 18;\n/** Chroma below which a colour is treated as achromatic. */\nconst ACHROMATIC_CHROMA = 1e-6;\nconst DISPLAY_ACHROMATIC_CHROMA = 0.0005;\n/** Share of the gamut's chroma that tones may use, keeping them off the edge. */\nexport const GAMUT_HEADROOM = 0.96;\nconst DEFAULT_TONE_CHROMA_CAP = 0.3;\nconst DEFAULT_MIN_CONTRAST = 4.5;\nconst ON_COLOR_STEPS = 12;\nconst ON_LIGHT_START = 0.985;\nconst ON_LIGHT_STEP = 0.0025;\nconst ON_DARK_START = 0.18;\nconst ON_DARK_STEP = 0.015;\n\nconst LINEAR_LUT = new Float32Array(256);\nfor (let i = 0; i < 256; i++) {\n const v = i / 255;\n LINEAR_LUT[i] = v <= 0.04045 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);\n}\n\n/** Restricts a value to the range from min to max. */\nexport function clamp(value: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, value));\n}\n\n/** Smooth 0-to-1 ramp between two edges. */\nexport function smoothstep(\n edge0: number,\n edge1: number,\n value: number,\n): number {\n const t = clamp((value - edge0) / (edge1 - edge0), 0, 1);\n return t * t * (3 - 2 * t);\n}\n\n/**\n * Converts 8-bit sRGB channels to Oklab [L, a, b].\n */\nexport function srgbToOklab(r: number, g: number, b: number): Lab {\n const lr = LINEAR_LUT[r & 255];\n const lg = LINEAR_LUT[g & 255];\n const lb = LINEAR_LUT[b & 255];\n\n const l = Math.cbrt(\n 0.4122214708 * lr + 0.5363325363 * lg + 0.0514459929 * lb,\n );\n const m = Math.cbrt(\n 0.2119034982 * lr + 0.6806995451 * lg + 0.1073969566 * lb,\n );\n const s = Math.cbrt(\n 0.0883024619 * lr + 0.2817188376 * lg + 0.6299787005 * lb,\n );\n\n return [\n 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s,\n 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s,\n 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s,\n ];\n}\n\nexport function oklchToLinearSrgb(l: number, c: number, h: number): Rgb {\n const a = c * Math.cos(h * DEG);\n const b = c * Math.sin(h * DEG);\n const l_ = (l + 0.3963377774 * a + 0.2158037573 * b) ** 3;\n const m_ = (l - 0.1055613458 * a - 0.0638541728 * b) ** 3;\n const s_ = (l - 0.0894841775 * a - 1.291485548 * b) ** 3;\n return [\n 4.0767416621 * l_ - 3.3077115913 * m_ + 0.2309699292 * s_,\n -1.2684380046 * l_ + 2.6097574011 * m_ - 0.3413193965 * s_,\n -0.0041960863 * l_ - 0.7034186147 * m_ + 1.707614701 * s_,\n ];\n}\n\nexport function labToLch([l, a, b]: Lab): OklchColor {\n const c = Math.sqrt(a * a + b * b);\n const h = c < ACHROMATIC_CHROMA ? 0 : (Math.atan2(b, a) / DEG + 360) % 360;\n return { c, h, l };\n}\n\nconst inGamut = (rgb: Rgb) =>\n rgb.every((v) => v >= -GAMUT_EPSILON && v <= 1 + GAMUT_EPSILON);\n\n/**\n * Largest chroma that stays inside the sRGB gamut for a lightness and hue.\n */\nexport function maxChroma(l: number, h: number): number {\n if (l <= 0 || l >= 1) return 0;\n let low = 0;\n let high = CHROMA_SEARCH_LIMIT;\n for (let step = 0; step < CHROMA_SEARCH_STEPS; step++) {\n const middle = (low + high) / 2;\n if (inGamut(oklchToLinearSrgb(l, middle, h))) low = middle;\n else high = middle;\n }\n return low;\n}\n\nexport function relativeChroma({ c, h, l }: OklchColor): number {\n const room = maxChroma(l, h);\n return room <= 0 ? 0 : clamp(c / room, 0, 1);\n}\n\nexport function hueDistance(a: number, b: number): number {\n const d = Math.abs(a - b) % 360;\n return d > 180 ? 360 - d : d;\n}\n\nexport function luminance({ c, h, l }: OklchColor): number {\n const [r, g, b] = oklchToLinearSrgb(l, c, h).map((v) => clamp(v, 0, 1));\n return 0.2126 * r + 0.7152 * g + 0.0722 * b;\n}\n\n/**\n * WCAG contrast ratio between two colours, from 1 to 21.\n */\nexport function contrastRatio(a: OklchColor, b: OklchColor): number {\n const la = luminance(a);\n const lb = luminance(b);\n return (Math.max(la, lb) + 0.05) / (Math.min(la, lb) + 0.05);\n}\n\nconst round = (value: number, digits: number) => {\n const factor = 10 ** digits;\n return Math.round(value * factor) / factor;\n};\n\n/**\n * Formats a colour as a CSS `oklch()` string.\n */\nexport function formatOklch({ c, h, l }: OklchColor): string {\n const chroma = c < DISPLAY_ACHROMATIC_CHROMA ? 0 : c;\n return `oklch(${round(clamp(l, 0, 1), 3).toFixed(3)} ${round(chroma, 3).toFixed(3)} ${round(chroma === 0 ? 0 : h, 1).toFixed(1)})`;\n}\n\n/**\n * Builds a colour at a hue and lightness whose chroma is a fraction of the\n * gamut's room, capped at `cap`.\n */\nexport function toneOf(\n h: number,\n l: number,\n rel: number,\n cap = DEFAULT_TONE_CHROMA_CAP,\n): OklchColor {\n const room = maxChroma(l, h) * GAMUT_HEADROOM;\n return { c: Math.min(cap, clamp(rel, 0, 1) * room), h, l };\n}\n\n/**\n * Picks a near-white or near-black text colour that meets `minContrast` on a\n * background.\n */\nexport function onColorFor(\n background: OklchColor,\n minContrast = DEFAULT_MIN_CONTRAST,\n): OklchColor {\n const light = (l: number) => toneOf(background.h, l, 0.12, 0.012);\n const dark = (l: number) => toneOf(background.h, l, 0.35, 0.03);\n const towardLight = contrastRatio(light(ON_LIGHT_START), background);\n const towardDark = contrastRatio(dark(ON_DARK_START), background);\n const useLight = towardLight >= minContrast || towardLight >= towardDark;\n\n for (let step = 0; step <= ON_COLOR_STEPS; step++) {\n const candidate = useLight\n ? light(Math.min(1, ON_LIGHT_START + step * ON_LIGHT_STEP))\n : dark(Math.max(0, ON_DARK_START - step * ON_DARK_STEP));\n if (contrastRatio(candidate, background) >= minContrast) return candidate;\n }\n return useLight ? { c: 0, h: 0, l: 1 } : { c: 0, h: 0, l: 0 };\n}\n","import { srgbToOklab } from \"./oklab\";\nimport type { AmbientPixels } from \"./types\";\n\nexport interface Bounds {\n bottom: number;\n left: number;\n right: number;\n top: number;\n}\n\nconst ALPHA_THRESHOLD = 128;\n/** A bar is dark on average and never bright. */\nconst BAR_MEAN_LIGHTNESS = 0.12;\nconst BAR_MAX_LIGHTNESS = 0.2;\n/** Letterbox bars are searched for only within this share of each side. */\nconst MAX_BAR_SHARE = 0.22;\n\nconst lightnessAt = (data: ArrayLike<number>, index: number) =>\n srgbToOklab(data[index], data[index + 1], data[index + 2])[0];\n\n/**\n * Finds the content rectangle of an image, ignoring dark letterbox bars.\n */\nexport function findContentBounds({\n data,\n height,\n width,\n}: AmbientPixels): Bounds {\n const isBar = (count: number, at: (step: number) => number) => {\n let sum = 0;\n let max = 0;\n let seen = 0;\n for (let step = 0; step < count; step++) {\n const index = at(step);\n if (data[index + 3] < ALPHA_THRESHOLD) continue;\n const l = lightnessAt(data, index);\n sum += l;\n if (l > max) max = l;\n seen++;\n }\n return (\n seen > 0 && sum / seen < BAR_MEAN_LIGHTNESS && max < BAR_MAX_LIGHTNESS\n );\n };\n const row = (y: number) => isBar(width, (x) => (y * width + x) * 4);\n const maxRows = Math.floor(height * MAX_BAR_SHARE);\n const maxColumns = Math.floor(width * MAX_BAR_SHARE);\n\n let top = 0;\n while (top < maxRows && row(top)) top++;\n let bottom = height;\n while (height - bottom < maxRows && bottom - 1 > top && row(bottom - 1))\n bottom--;\n\n const column = (x: number) =>\n isBar(bottom - top, (step) => ((top + step) * width + x) * 4);\n let left = 0;\n while (left < maxColumns && column(left)) left++;\n let right = width;\n while (width - right < maxColumns && right - 1 > left && column(right - 1))\n right--;\n\n return { bottom, left, right, top };\n}\n","import type {\n AmbientAnalysisOptions,\n AmbientCssVarNames,\n AmbientProxy,\n AmbientSettings,\n AmbientSettingsInput,\n AmbientTone,\n} from \"./types\";\n\n/**\n * Every tone step of a colour ramp, from darkest to lightest.\n */\nexport const AMBIENT_TONES = Object.freeze([\n 10, 15, 20, 30, 40, 50, 60, 70, 80, 90, 95,\n] as const) satisfies readonly AmbientTone[];\n\n/**\n * Names of the palette colours.\n */\nexport const AMBIENT_ROLES = Object.freeze([\n \"dominant\",\n \"vibrant\",\n \"muted\",\n \"accent\",\n] as const);\n\n/**\n * Names of the image regions that have their own colour.\n */\nexport const AMBIENT_REGIONS = Object.freeze([\n \"top\",\n \"bottom\",\n \"left\",\n \"right\",\n \"center\",\n] as const);\n\n/**\n * Default palette analysis options.\n */\nexport const DEFAULT_ANALYSIS: Readonly<AmbientAnalysisOptions> = Object.freeze(\n {\n centerWeight: 0.5,\n clusters: 7,\n letterbox: true,\n minContrast: 4.5,\n minHueDistance: 40,\n sampleSize: 128,\n shadowLightness: 0.16,\n },\n);\n\n/**\n * Default CSS variable name templates.\n */\nexport const DEFAULT_CSS_VAR_NAMES: Readonly<AmbientCssVarNames> =\n Object.freeze({\n on: \"--ambient-on-{role}\",\n region: \"--ambient-{region}\",\n role: \"--ambient-{role}\",\n shadow: \"--ambient-shadow\",\n tone: \"--ambient-{role}-{tone}\",\n });\n\nexport const DEFAULT_PROXY = \"/api/ambient/proxy?url=\";\n\n/**\n * How long, in milliseconds, page-level variables stay after their owner\n * unmounts.\n */\nexport const DEFAULT_LINGER_MS = 3_000;\n\nconst createDefaults = (): AmbientSettings => ({\n analysis: { ...DEFAULT_ANALYSIS },\n cacheLimit: 100,\n cssVars: { ...DEFAULT_CSS_VAR_NAMES, tones: AMBIENT_TONES },\n linger: DEFAULT_LINGER_MS,\n proxy: DEFAULT_PROXY,\n strategy: \"auto\",\n worker: null,\n});\n\nconst SETTINGS_KEY = Symbol.for(\"@omerdlw/base-framework/ambient/settings\");\ntype GlobalWithSettings = typeof globalThis & {\n [SETTINGS_KEY]?: AmbientSettings;\n};\nconst scope = globalThis as GlobalWithSettings;\n\n/**\n * Returns the current global ambient settings.\n */\nexport function getAmbientSettings(): AmbientSettings {\n return (scope[SETTINGS_KEY] ??= createDefaults());\n}\n\nexport function mergeAmbientSettings(\n base: AmbientSettings,\n input: AmbientSettingsInput,\n): AmbientSettings {\n return {\n analysis: { ...base.analysis, ...input.analysis },\n cacheLimit: input.cacheLimit ?? base.cacheLimit,\n cssVars: { ...base.cssVars, ...input.cssVars },\n linger: input.linger ?? base.linger,\n proxy: input.proxy === undefined ? base.proxy : input.proxy,\n strategy: input.strategy ?? base.strategy,\n worker: input.worker === undefined ? base.worker : input.worker,\n };\n}\n\n/**\n * Overrides global ambient settings. Returns a function that restores the\n * previous settings.\n */\nexport function configureAmbient(input: AmbientSettingsInput): () => void {\n const previous = getAmbientSettings();\n const next = mergeAmbientSettings(previous, input);\n scope[SETTINGS_KEY] = next;\n return () => {\n if (scope[SETTINGS_KEY] === next) scope[SETTINGS_KEY] = previous;\n };\n}\n\nexport function resolveAnalysis(\n overrides?: Partial<AmbientAnalysisOptions> | null,\n): AmbientAnalysisOptions {\n return { ...getAmbientSettings().analysis, ...overrides };\n}\n\nexport function resolveProxyUrl(\n proxy: AmbientProxy,\n src: string,\n): string | null {\n if (!proxy || !/^https?:\\/\\//i.test(src)) return null;\n if (typeof proxy === \"function\") return proxy(src);\n const encoded = encodeURIComponent(src);\n return proxy.includes(\"{url}\")\n ? proxy.replace(\"{url}\", encoded)\n : `${proxy}${encoded}`;\n}\n","import { hueDistance, smoothstep } from \"./oklab\";\nimport type { AmbientRegion, OklchColor } from \"./types\";\n\nexport const MIN_CHROMA = 0.022;\nexport const MIN_PRESENCE = 0.03;\nexport const MIN_POPULATION = 0.004;\n\nexport const REGION_BITS: Record<AmbientRegion, number> = {\n top: 1,\n bottom: 2,\n left: 4,\n right: 8,\n center: 16,\n};\n\nexport interface Cluster extends OklchColor {\n pop: number;\n rel: number;\n rely: number;\n}\n\nexport const reliability = (l: number) =>\n smoothstep(0.1, 0.28, l) * (1 - smoothstep(0.9, 0.98, l));\n\nexport const colorfulness = (c: number) => smoothstep(MIN_CHROMA, 0.06, c);\n\nexport const isChromatic = (cluster: Cluster) =>\n cluster.c >= MIN_CHROMA && cluster.rely > 0;\n\nexport function pickBest<T>(items: T[], score: (item: T) => number): T | null {\n let best: T | null = null;\n let bestScore = 0;\n for (const item of items) {\n const value = score(item);\n if (value > bestScore) {\n bestScore = value;\n best = item;\n }\n }\n return best;\n}\n\nexport const round3 = (value: number) => Math.round(value * 1000) / 1000;\n\n/**\n * Scores how close a colour is to a skin tone, from 0 to 1.\n */\nexport function skinLikeness({ c, h, l }: OklchColor): number {\n return (\n (1 - smoothstep(12, 26, hueDistance(h, 54))) *\n smoothstep(0.02, 0.035, c) *\n (1 - smoothstep(0.11, 0.15, c)) *\n smoothstep(0.26, 0.38, l) *\n (1 - smoothstep(0.88, 0.95, l))\n );\n}\n\nexport const warmth = (h: number) => 1 - smoothstep(22, 50, hueDistance(h, 42));\n\nexport const salience = (color: OklchColor) => 1 - 0.65 * skinLikeness(color);\n","export interface KMeansResult {\n assignment: Int32Array;\n centroids: Float64Array;\n k: number;\n}\n\nexport interface KMeansOptions {\n iterations?: number;\n lightnessWeight?: number;\n}\n\ntype Distance = (i: number, j: number) => number;\n\n/**\n * Seeds centroids: the heaviest point first, then repeatedly the point with the\n * highest weight times distance to its nearest centroid. Returns how many\n * centroids were placed.\n */\nfunction seedCentroids(\n points: Float64Array,\n weights: Float64Array,\n centroids: Float64Array,\n k: number,\n distance: Distance,\n): number {\n const n = weights.length;\n let first = 0;\n for (let i = 1; i < n; i++) if (weights[i] > weights[first]) first = i;\n centroids.set(points.subarray(first * 3, first * 3 + 3), 0);\n\n const nearest = new Float64Array(n).fill(Infinity);\n let found = 1;\n for (; found < k; found++) {\n let best = -1;\n let bestScore = 0;\n for (let i = 0; i < n; i++) {\n const d = distance(i, found - 1);\n if (d < nearest[i]) nearest[i] = d;\n const score = weights[i] * nearest[i];\n if (score > bestScore) {\n bestScore = score;\n best = i;\n }\n }\n if (best < 0) break;\n centroids.set(points.subarray(best * 3, best * 3 + 3), found * 3);\n }\n return found;\n}\n\n/** Assigns each point to its nearest centroid. Returns whether any moved. */\nfunction assignPoints(\n assignment: Int32Array,\n found: number,\n distance: Distance,\n moved: boolean,\n): boolean {\n for (let i = 0; i < assignment.length; i++) {\n let best = 0;\n let bestDistance = Infinity;\n for (let j = 0; j < found; j++) {\n const d = distance(i, j);\n if (d < bestDistance) {\n bestDistance = d;\n best = j;\n }\n }\n if (assignment[i] !== best) {\n assignment[i] = best;\n moved = true;\n }\n }\n return moved;\n}\n\n/** Moves each centroid to the weighted mean of its points. */\nfunction updateCentroids(\n points: Float64Array,\n weights: Float64Array,\n assignment: Int32Array,\n centroids: Float64Array,\n sums: Float64Array,\n found: number,\n): void {\n sums.fill(0);\n for (let i = 0; i < weights.length; i++) {\n const j = assignment[i] * 4;\n const w = weights[i];\n sums[j] += points[i * 3] * w;\n sums[j + 1] += points[i * 3 + 1] * w;\n sums[j + 2] += points[i * 3 + 2] * w;\n sums[j + 3] += w;\n }\n for (let j = 0; j < found; j++) {\n const w = sums[j * 4 + 3];\n if (w <= 0) continue;\n centroids[j * 3] = sums[j * 4] / w;\n centroids[j * 3 + 1] = sums[j * 4 + 1] / w;\n centroids[j * 3 + 2] = sums[j * 4 + 2] / w;\n }\n}\n\n/**\n * Weighted k-means over 3-component points (Lab), with lightness\n * down-weighted. Returns each point's cluster and the centroids.\n */\nexport function kmeans(\n points: Float64Array,\n weights: Float64Array,\n requested: number,\n { iterations = 16, lightnessWeight = 0.45 }: KMeansOptions = {},\n): KMeansResult {\n const n = weights.length;\n const assignment = new Int32Array(n);\n const k = Math.max(0, Math.min(requested, n));\n const centroids = new Float64Array(k * 3);\n if (k === 0) return { assignment, centroids, k };\n\n const distance: Distance = (i, j) => {\n const dl = points[i * 3] - centroids[j * 3];\n const da = points[i * 3 + 1] - centroids[j * 3 + 1];\n const db = points[i * 3 + 2] - centroids[j * 3 + 2];\n return lightnessWeight * dl * dl + da * da + db * db;\n };\n\n const found = seedCentroids(points, weights, centroids, k, distance);\n\n const sums = new Float64Array(found * 4);\n for (let round = 0; round < iterations; round++) {\n const moved = assignPoints(assignment, found, distance, round === 0);\n if (!moved) break;\n updateCentroids(points, weights, assignment, centroids, sums, found);\n }\n\n return { assignment, centroids: centroids.slice(0, found * 3), k: found };\n}\n","import { type Bounds, findContentBounds } from \"./analyze-bounds\";\nimport {\n type Cluster,\n MIN_CHROMA,\n REGION_BITS,\n reliability,\n} from \"./analyze-measures\";\nimport { clamp, labToLch, maxChroma, srgbToOklab } from \"./oklab\";\nimport { kmeans } from \"./quantize\";\nimport { AMBIENT_REGIONS } from \"./settings\";\nimport type { AmbientAnalysisOptions, AmbientPixels } from \"./types\";\n\nexport interface AmbientClustering {\n clusters: Cluster[];\n meanL: number;\n regionLab: Float64Array[];\n regionWeights: Float64Array[];\n}\n\n/** Size of the 5-bit-per-channel colour key space. */\nconst COLOR_KEY_SPACE = 32768;\n/** Values stored per colour bin in `binSums`: weighted L, a, b and weight. */\nconst BIN_STRIDE = 4;\nconst ALPHA_THRESHOLD = 128; // matches analyze-bounds\nconst CENTER_SIGMA = 0.35;\n/** Lightness below which a coloured bin is treated as grey. */\nconst MIN_COLOURED_LIGHTNESS = 0.06;\nconst MIN_CLUSTERS = 2;\nconst MAX_CLUSTERS = 16;\n/** From this many requested clusters, the grey group gets one more cluster. */\nconst MANY_CLUSTERS = 8;\nconst GREY_CLUSTERS_FEW = 2;\nconst GREY_CLUSTERS_MANY = 3;\nconst CHROMA_WEIGHT_GAIN = 5;\n/** Side of the centred square, as a distance from the middle, in units of size. */\nconst CENTER_REGION_HALF = 0.25;\nconst LOW_EDGE = 1 / 3;\nconst HIGH_EDGE = 2 / 3;\n\ninterface BinAccumulation {\n binSums: number[];\n boxHeight: number;\n boxWidth: number;\n pixelBins: Int32Array;\n pixelRegions: Uint8Array;\n sumL: number;\n total: number;\n}\n\nfunction regionBitsAt(u: number, v: number): number {\n return (\n (v < LOW_EDGE ? REGION_BITS.top : 0) |\n (v > HIGH_EDGE ? REGION_BITS.bottom : 0) |\n (u < LOW_EDGE ? REGION_BITS.left : 0) |\n (u > HIGH_EDGE ? REGION_BITS.right : 0) |\n (Math.abs(u - 0.5) < CENTER_REGION_HALF &&\n Math.abs(v - 0.5) < CENTER_REGION_HALF\n ? REGION_BITS.center\n : 0)\n );\n}\n\n/**\n * Quantises the visible pixels into 5-bit colour bins, weighting pixels near\n * the centre more, and records which bin and region each pixel fell into.\n */\nfunction accumulateBins(\n { data, width }: AmbientPixels,\n bounds: Bounds,\n centerWeight: number,\n): BinAccumulation {\n const boxWidth = Math.max(1, bounds.right - bounds.left);\n const boxHeight = Math.max(1, bounds.bottom - bounds.top);\n const binOf = new Int32Array(COLOR_KEY_SPACE).fill(-1);\n const binSums: number[] = [];\n const pixelBins = new Int32Array(boxWidth * boxHeight).fill(-1);\n const pixelRegions = new Uint8Array(boxWidth * boxHeight);\n const sigma2 = 2 * CENTER_SIGMA * CENTER_SIGMA;\n let total = 0;\n let sumL = 0;\n\n for (let y = bounds.top; y < bounds.bottom; y++) {\n const v = (y - bounds.top + 0.5) / boxHeight;\n for (let x = bounds.left; x < bounds.right; x++) {\n const index = (y * width + x) * 4;\n if (data[index + 3] < ALPHA_THRESHOLD) continue;\n const r = data[index];\n const g = data[index + 1];\n const b = data[index + 2];\n const [l, a, bb] = srgbToOklab(r, g, b);\n const u = (x - bounds.left + 0.5) / boxWidth;\n const du = (u - 0.5) * 2;\n const dv = (v - 0.5) * 2;\n const weight =\n 1 -\n centerWeight +\n 2 * centerWeight * Math.exp(-(du * du + dv * dv) / sigma2);\n\n const key = ((r >> 3) << 10) | ((g >> 3) << 5) | (b >> 3);\n let bin = binOf[key];\n if (bin < 0) {\n bin = binSums.length / BIN_STRIDE;\n binOf[key] = bin;\n binSums.push(0, 0, 0, 0);\n }\n binSums[bin * BIN_STRIDE] += l * weight;\n binSums[bin * BIN_STRIDE + 1] += a * weight;\n binSums[bin * BIN_STRIDE + 2] += bb * weight;\n binSums[bin * BIN_STRIDE + 3] += weight;\n total += weight;\n sumL += l * weight;\n\n const local = (y - bounds.top) * boxWidth + (x - bounds.left);\n pixelBins[local] = bin;\n pixelRegions[local] = regionBitsAt(u, v);\n }\n }\n return { binSums, boxHeight, boxWidth, pixelBins, pixelRegions, sumL, total };\n}\n\n/** Splits bins into coloured (group 0) and grey (group 1). */\nfunction splitByColour(binSums: number[]): [number[], number[]] {\n const groups: [number[], number[]] = [[], []];\n const bins = binSums.length / BIN_STRIDE;\n for (let i = 0; i < bins; i++) {\n const w = binSums[i * BIN_STRIDE + 3];\n const a = binSums[i * BIN_STRIDE + 1] / w;\n const b = binSums[i * BIN_STRIDE + 2] / w;\n const coloured =\n Math.sqrt(a * a + b * b) >= MIN_CHROMA &&\n binSums[i * BIN_STRIDE] / w >= MIN_COLOURED_LIGHTNESS;\n groups[coloured ? 0 : 1].push(i);\n }\n return groups;\n}\n\n/** Divides the requested cluster count between the coloured and grey groups. */\nfunction allocateBudgets(\n groups: [number[], number[]],\n requestedClusters: number,\n): [number, number] {\n const requested = clamp(\n Math.round(requestedClusters),\n MIN_CLUSTERS,\n MAX_CLUSTERS,\n );\n let greyClusters: number;\n if (groups[0].length === 0) greyClusters = requested;\n else if (groups[1].length === 0) greyClusters = 0;\n else if (requested >= MANY_CLUSTERS) greyClusters = GREY_CLUSTERS_MANY;\n else greyClusters = GREY_CLUSTERS_FEW;\n return [requested - greyClusters, greyClusters];\n}\n\n/**\n * Runs k-means over each colour group's bins and appends the resulting\n * clusters. Returns the cluster index of every bin (-1 when unassigned).\n */\nfunction clusterBins(\n groups: [number[], number[]],\n budgets: [number, number],\n { binSums, total }: Pick<BinAccumulation, \"binSums\" | \"total\">,\n clusters: Cluster[],\n): Int32Array {\n const clusterOfBin = new Int32Array(binSums.length / BIN_STRIDE).fill(-1);\n groups.forEach((members, group) => {\n if (members.length === 0 || budgets[group] <= 0) return;\n const points = new Float64Array(members.length * 3);\n const weights = new Float64Array(members.length);\n members.forEach((bin, i) => {\n const w = binSums[bin * BIN_STRIDE + 3];\n const a = binSums[bin * BIN_STRIDE + 1] / w;\n const b = binSums[bin * BIN_STRIDE + 2] / w;\n points[i * 3] = binSums[bin * BIN_STRIDE] / w;\n points[i * 3 + 1] = a;\n points[i * 3 + 2] = b;\n weights[i] = w * (1 + CHROMA_WEIGHT_GAIN * Math.sqrt(a * a + b * b));\n });\n const { assignment, k } = kmeans(points, weights, budgets[group]);\n const sums = new Float64Array(k * BIN_STRIDE);\n members.forEach((bin, i) => {\n for (let channel = 0; channel < BIN_STRIDE; channel++) {\n sums[assignment[i] * BIN_STRIDE + channel] +=\n binSums[bin * BIN_STRIDE + channel];\n }\n });\n const index = new Int32Array(k).fill(-1);\n for (let j = 0; j < k; j++) {\n const pop = sums[j * BIN_STRIDE + 3];\n if (pop <= 0) continue;\n const lch = labToLch([\n sums[j * BIN_STRIDE] / pop,\n sums[j * BIN_STRIDE + 1] / pop,\n sums[j * BIN_STRIDE + 2] / pop,\n ]);\n const room = maxChroma(lch.l, lch.h);\n index[j] = clusters.length;\n clusters.push({\n ...lch,\n pop: pop / total,\n rel: room > 0 ? clamp(lch.c / room, 0, 1) : 0,\n rely: reliability(lch.l),\n });\n }\n members.forEach((bin, i) => (clusterOfBin[bin] = index[assignment[i]]));\n });\n return clusterOfBin;\n}\n\n/** Totals, per region, how many pixels each cluster covers and its mean Lab. */\nfunction accumulateRegions(\n clusterCount: number,\n clusterOfBin: Int32Array,\n { binSums, pixelBins, pixelRegions }: BinAccumulation,\n): Pick<AmbientClustering, \"regionLab\" | \"regionWeights\"> {\n const regionWeights = AMBIENT_REGIONS.map(\n () => new Float64Array(clusterCount),\n );\n const regionLab = AMBIENT_REGIONS.map(\n () => new Float64Array(clusterCount * 3),\n );\n for (let i = 0; i < pixelBins.length; i++) {\n const bin = pixelBins[i];\n if (bin < 0) continue;\n const cluster = clusterOfBin[bin];\n const bits = pixelRegions[i];\n const w = binSums[bin * BIN_STRIDE + 3];\n AMBIENT_REGIONS.forEach((region, r) => {\n if (!(bits & REGION_BITS[region])) return;\n regionWeights[r][cluster] += 1;\n for (let channel = 0; channel < 3; channel++) {\n regionLab[r][cluster * 3 + channel] +=\n binSums[bin * BIN_STRIDE + channel] / w;\n }\n });\n }\n return { regionLab, regionWeights };\n}\n\n/**\n * Groups an image's pixels into weighted colour clusters, plus per-region\n * statistics, ready for palette selection.\n */\nexport function clusterAmbientPixels(\n pixels: AmbientPixels,\n options: AmbientAnalysisOptions,\n): AmbientClustering {\n const { height, width } = pixels;\n const bounds = options.letterbox\n ? findContentBounds(pixels)\n : { bottom: height, left: 0, right: width, top: 0 };\n\n const accumulation = accumulateBins(pixels, bounds, options.centerWeight);\n const { binSums, sumL, total } = accumulation;\n const meanL = total > 0 ? sumL / total : 0.5;\n\n const groups = splitByColour(binSums);\n const budgets = allocateBudgets(groups, options.clusters);\n const clusters: Cluster[] = [];\n const clusterOfBin = clusterBins(groups, budgets, accumulation, clusters);\n const regions = accumulateRegions(\n clusters.length,\n clusterOfBin,\n accumulation,\n );\n\n return { clusters, meanL, ...regions };\n}\n","import { type Cluster, round3, skinLikeness, warmth } from \"./analyze-measures\";\nimport {\n clamp,\n formatOklch,\n GAMUT_HEADROOM,\n maxChroma,\n onColorFor,\n toneOf,\n} from \"./oklab\";\nimport { AMBIENT_TONES } from \"./settings\";\nimport type { AmbientRamp, AmbientSwatch, OklchColor } from \"./types\";\n\ninterface ChromaSpec {\n cap: number;\n gain: number;\n}\n\nexport const roleChroma = (source: OklchColor, { cap, gain }: ChromaSpec) =>\n Math.min(\n cap * (1 - 0.3 * warmth(source.h)),\n Math.max(source.c * gain, Math.min(0.05, source.c * 1.6)) *\n (1 - 0.3 * skinLikeness(source)),\n );\n\nexport const fitTone = (h: number, l: number, c: number): OklchColor => ({\n c: Math.max(0, Math.min(c, maxChroma(l, h) * GAMUT_HEADROOM)),\n h,\n l,\n});\n\nexport function buildSwatch(\n tone: OklchColor,\n population: number,\n fromImage: boolean,\n minContrast: number,\n): AmbientSwatch {\n const room = maxChroma(tone.l, tone.h) * GAMUT_HEADROOM;\n const rel = room > 0 ? tone.c / room : 0;\n const ramp = {} as AmbientRamp;\n for (const step of AMBIENT_TONES) {\n ramp[step] = formatOklch(\n toneOf(tone.h, step / 100, rel, Math.max(tone.c, 0.04)),\n );\n }\n return {\n c: round3(tone.c),\n color: formatOklch(tone),\n fromImage,\n h: Math.round(tone.h * 10) / 10,\n l: round3(tone.l),\n on: formatOklch(onColorFor(tone, minContrast)),\n population: round3(population),\n ramp,\n };\n}\n\ninterface RoleSpec extends ChromaSpec {\n max: number;\n min: number;\n}\n\nexport function roleTone(\n source: Cluster | null,\n spec: RoleSpec,\n fallback: OklchColor,\n dilution = 1,\n): OklchColor {\n if (!source)\n return fitTone(\n fallback.h,\n clamp(fallback.l, spec.min, spec.max),\n fallback.c,\n );\n return fitTone(\n source.h,\n clamp(source.l, spec.min, spec.max),\n roleChroma(source, spec) * dilution,\n );\n}\n","import { clusterAmbientPixels } from \"./analyze-clusters\";\nimport {\n type Cluster,\n colorfulness,\n isChromatic,\n MIN_CHROMA,\n MIN_POPULATION,\n MIN_PRESENCE,\n pickBest,\n reliability,\n round3,\n salience,\n} from \"./analyze-measures\";\nimport { buildSwatch, fitTone, roleChroma, roleTone } from \"./analyze-swatches\";\nimport {\n clamp,\n formatOklch,\n hueDistance,\n labToLch,\n smoothstep,\n toneOf,\n} from \"./oklab\";\nimport { AMBIENT_REGIONS, DEFAULT_ANALYSIS } from \"./settings\";\nimport type {\n AmbientAnalysisOptions,\n AmbientPalette,\n AmbientPixels,\n AmbientRegion,\n AmbientRegionColor,\n AmbientRole,\n AmbientSwatch,\n OklchColor,\n} from \"./types\";\n\n/**\n * Version of the palette analysis algorithm; bump it to invalidate palettes\n * cached from an older version.\n */\nexport const AMBIENT_ANALYSIS_VERSION = 2;\n\nexport { findContentBounds } from \"./analyze-bounds\";\nexport { skinLikeness } from \"./analyze-measures\";\n\n/** Two hues within this distance count as the same colour family. */\nconst FAMILY_HUE_RANGE = 20;\n/** Chroma at or below which a cluster can serve as the muted role. */\nconst MUTED_MAX_CHROMA = 0.09;\n/** Chroma at which the muted score reaches zero. */\nconst MUTED_CHROMA_SPAN = 0.12;\n/** Minimum chroma and share for an accent when the image is neutral. */\nconst NEUTRAL_ACCENT_MIN_SHARE = 0.006;\nconst NEUTRAL_ACCENT_MIN_CHROMA = 0.06;\nconst ACCENT_MIN_CHROMA = 0.035;\n/** Presence at which colour dilution stops applying. */\nconst FULL_DILUTION_PRESENCE = 0.25;\nconst MIN_DILUTION = 0.55;\nconst DILUTION_RANGE = 0.45;\nconst GREY_LIGHTNESS_RANGE = [0.3, 0.8] as const;\n\nconst DOMINANT_SPEC = { cap: 0.2, gain: 1.15, max: 0.74, min: 0.42 };\nconst VIBRANT_SPEC = { cap: 0.22, gain: 1.35, max: 0.84, min: 0.62 };\nconst MUTED_SPEC = { cap: 0.07, gain: 1, max: 0.66, min: 0.38 };\nconst ACCENT_SPEC = { cap: 0.22, gain: 1.3, max: 0.8, min: 0.55 };\nconst REGION_SPEC = { cap: 0.18, gain: 1.15 };\nconst REGION_LIGHTNESS_RANGE = [0.42, 0.72] as const;\nconst REGION_FALLBACK_LIGHTNESS_RANGE = [0.3, 0.7] as const;\n\nconst SHADOW_MAX_SOURCE_LIGHTNESS = 0.5;\nconst SHADOW_MIN_SOURCE_CHROMA = 0.02;\nconst SHADOW_MIN_SOURCE_POPULATION = 0.02;\nconst SHADOW_LIGHTNESS_DRIFT = 0.02;\nconst SHADOW_MEAN_LIGHTNESS_PIVOT = 0.45;\nconst SHADOW_MEAN_LIGHTNESS_GAIN = 0.06;\nconst SHADOW_CHROMA_CAP = 0.1;\n\ntype ClusterShare = (cluster: Cluster) => number;\n\ninterface RolePicks {\n accent: Cluster | null;\n dominant: Cluster | null;\n muted: Cluster | null;\n vivid: Cluster | null;\n}\n\ninterface PaletteContext {\n clusters: Cluster[];\n dilution: number;\n meanL: number;\n minContrast: number;\n neutral: boolean;\n share: ClusterShare;\n}\n\n/** Sums the population of every cluster whose hue is within the family range. */\nfunction createFamilyShare(chromatic: Cluster[]): ClusterShare {\n const family = new Map<Cluster, number>();\n for (const cluster of chromatic) {\n let share = 0;\n for (const other of chromatic) {\n if (hueDistance(cluster.h, other.h) <= FAMILY_HUE_RANGE) {\n share += other.pop;\n }\n }\n family.set(cluster, share);\n }\n return (cluster) => family.get(cluster) ?? cluster.pop;\n}\n\nfunction pickRoleClusters(\n chromatic: Cluster[],\n share: ClusterShare,\n neutral: boolean,\n minHueDistance: number,\n): RolePicks {\n const dominant = neutral\n ? null\n : pickBest(\n chromatic,\n (cluster) =>\n share(cluster) * cluster.c * cluster.rely * salience(cluster),\n );\n const vivid = neutral\n ? null\n : pickBest(\n chromatic.filter((cluster) => share(cluster) >= MIN_POPULATION),\n (cluster) =>\n cluster.c *\n cluster.c *\n Math.pow(share(cluster), 0.3) *\n cluster.rely *\n salience(cluster),\n );\n const isAccentCandidate = (cluster: Cluster) => {\n if (neutral) {\n return (\n share(cluster) >= NEUTRAL_ACCENT_MIN_SHARE &&\n cluster.c >= NEUTRAL_ACCENT_MIN_CHROMA\n );\n }\n return (\n share(cluster) >= MIN_POPULATION &&\n cluster.c >= ACCENT_MIN_CHROMA &&\n (!dominant || hueDistance(cluster.h, dominant.h) >= minHueDistance)\n );\n };\n const accent = pickBest(\n chromatic.filter(isAccentCandidate),\n (cluster) =>\n Math.pow(share(cluster), 0.6) *\n cluster.c *\n cluster.rely *\n salience(cluster),\n );\n const muted = neutral\n ? null\n : pickBest(\n chromatic.filter((cluster) => cluster.c <= MUTED_MAX_CHROMA),\n (cluster) =>\n share(cluster) * cluster.rely * (1 - cluster.c / MUTED_CHROMA_SPAN),\n );\n return { accent, dominant, muted, vivid };\n}\n\nfunction buildRoles(\n picks: RolePicks,\n { dilution, meanL, minContrast, neutral, share }: PaletteContext,\n): Record<AmbientRole, AmbientSwatch> {\n const { accent, dominant, muted, vivid } = picks;\n const grey = {\n c: 0,\n h: 0,\n l: clamp(meanL, GREY_LIGHTNESS_RANGE[0], GREY_LIGHTNESS_RANGE[1]),\n };\n const dominantHue = dominant?.h ?? vivid?.h ?? 0;\n const accentSource = accent ?? vivid;\n return {\n dominant: buildSwatch(\n roleTone(dominant, DOMINANT_SPEC, grey),\n dominant ? share(dominant) : 0,\n true,\n minContrast,\n ),\n vibrant: buildSwatch(\n roleTone(\n vivid,\n VIBRANT_SPEC,\n { c: 0, h: dominantHue, l: 0.78 },\n dilution,\n ),\n vivid ? share(vivid) : 0,\n true,\n minContrast,\n ),\n muted: buildSwatch(\n roleTone(muted, MUTED_SPEC, {\n c: dominant ? 0.035 : 0,\n h: dominantHue,\n l: clamp(meanL, 0.38, 0.66),\n }),\n muted ? share(muted) : 0,\n Boolean(muted) || neutral,\n minContrast,\n ),\n accent: buildSwatch(\n roleTone(\n accentSource,\n ACCENT_SPEC,\n { c: 0, h: dominantHue, l: 0.72 },\n dilution,\n ),\n accentSource ? share(accentSource) : 0,\n Boolean(accent),\n minContrast,\n ),\n };\n}\n\nfunction buildShadow(\n dominant: Cluster | null,\n { clusters, meanL, neutral }: PaletteContext,\n baseLightness: number,\n): OklchColor {\n const shadowPick = neutral\n ? null\n : pickBest(\n clusters.filter(\n (cluster) =>\n cluster.l <= SHADOW_MAX_SOURCE_LIGHTNESS &&\n cluster.c >= SHADOW_MIN_SOURCE_CHROMA &&\n cluster.pop >= SHADOW_MIN_SOURCE_POPULATION,\n ),\n (cluster) =>\n cluster.pop * cluster.rel * smoothstep(0.05, 0.14, cluster.l),\n );\n const deepSource = shadowPick ?? dominant;\n const lightness = clamp(\n baseLightness +\n (meanL - SHADOW_MEAN_LIGHTNESS_PIVOT) * SHADOW_MEAN_LIGHTNESS_GAIN,\n baseLightness - SHADOW_LIGHTNESS_DRIFT,\n baseLightness + SHADOW_LIGHTNESS_DRIFT,\n );\n if (!deepSource) return { c: 0, h: 0, l: lightness };\n return toneOf(\n deepSource.h,\n lightness,\n clamp(0.3 + 0.7 * deepSource.rel, 0, 0.85),\n SHADOW_CHROMA_CAP,\n );\n}\n\n/** Picks the most salient reliable colour among one region's cluster samples. */\nfunction pickRegionColor(\n clusters: Cluster[],\n weights: Float64Array,\n lab: Float64Array,\n regionTotal: number,\n): { pick: OklchColor | null; strength: number } {\n let strength = 0;\n let pick: OklchColor | null = null;\n let pickScore = 0;\n for (let j = 0; j < clusters.length; j++) {\n const count = weights[j];\n if (count <= 0) continue;\n const local = labToLch([\n lab[j * 3] / count,\n lab[j * 3 + 1] / count,\n lab[j * 3 + 2] / count,\n ]);\n const rely = reliability(local.l);\n if (local.c < MIN_CHROMA || rely <= 0) continue;\n const part = count / regionTotal;\n strength += part * colorfulness(local.c) * rely;\n const score = part * local.c * rely * salience(local);\n if (score > pickScore) {\n pickScore = score;\n pick = local;\n }\n }\n return { pick, strength };\n}\n\nfunction buildRegion(\n weights: Float64Array,\n lab: Float64Array,\n { clusters, meanL, neutral }: PaletteContext,\n): AmbientRegionColor {\n let regionTotal = 0;\n let regionL = 0;\n clusters.forEach((cluster, j) => {\n regionTotal += weights[j];\n regionL += cluster.l * weights[j];\n });\n const { pick, strength } = pickRegionColor(\n clusters,\n weights,\n lab,\n regionTotal,\n );\n const chosen = neutral || strength < MIN_PRESENCE ? null : pick;\n const tone = chosen\n ? fitTone(\n chosen.h,\n clamp(chosen.l, REGION_LIGHTNESS_RANGE[0], REGION_LIGHTNESS_RANGE[1]),\n roleChroma(chosen, REGION_SPEC),\n )\n : {\n c: 0,\n h: 0,\n l: clamp(\n regionTotal > 0 ? regionL / regionTotal : meanL,\n REGION_FALLBACK_LIGHTNESS_RANGE[0],\n REGION_FALLBACK_LIGHTNESS_RANGE[1],\n ),\n };\n return {\n c: round3(tone.c),\n color: formatOklch(tone),\n h: Math.round(tone.h * 10) / 10,\n l: round3(tone.l),\n strength: round3(chosen ? clamp(strength, 0, 1) : 0),\n };\n}\n\nfunction buildRegions(\n context: PaletteContext,\n regionWeights: Float64Array[],\n regionLab: Float64Array[],\n): Record<AmbientRegion, AmbientRegionColor> {\n const regions = {} as Record<AmbientRegion, AmbientRegionColor>;\n AMBIENT_REGIONS.forEach((region, r) => {\n regions[region] = buildRegion(regionWeights[r], regionLab[r], context);\n });\n return regions;\n}\n\n/**\n * Derives a colour palette (roles, regions, shadow) from raw RGBA pixels.\n * Options override DEFAULT_ANALYSIS.\n */\nexport function analyzeAmbientPixels(\n pixels: AmbientPixels,\n overrides: Partial<AmbientAnalysisOptions> = {},\n): AmbientPalette {\n const options = { ...DEFAULT_ANALYSIS, ...overrides };\n const { clusters, meanL, regionLab, regionWeights } = clusterAmbientPixels(\n pixels,\n options,\n );\n\n const chromatic = clusters.filter(isChromatic);\n const presence = chromatic.reduce(\n (sum, cluster) =>\n sum + cluster.pop * colorfulness(cluster.c) * cluster.rely,\n 0,\n );\n const context: PaletteContext = {\n clusters,\n dilution:\n MIN_DILUTION +\n DILUTION_RANGE * Math.min(1, presence / FULL_DILUTION_PRESENCE),\n meanL,\n minContrast: options.minContrast,\n neutral: presence < MIN_PRESENCE,\n share: createFamilyShare(chromatic),\n };\n\n const picks = pickRoleClusters(\n chromatic,\n context.share,\n context.neutral,\n options.minHueDistance,\n );\n return {\n neutral: context.neutral,\n regions: buildRegions(context, regionWeights, regionLab),\n roles: buildRoles(picks, context),\n shadow: formatOklch(\n buildShadow(picks.dominant, context, options.shadowLightness),\n ),\n };\n}\n\n/**\n * Scales an image size down to fit a square sample, keeping its aspect ratio.\n */\nexport function fitSample(width: number, height: number, size: number) {\n const scale = Math.min(1, size / Math.max(width, height, 1));\n return {\n height: Math.max(1, Math.round(height * scale)),\n width: Math.max(1, Math.round(width * scale)),\n };\n}\n"]}
|