@flairstudio/kit 0.1.0 → 0.2.0-beta.1

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/CHANGELOG.md CHANGED
@@ -2,6 +2,25 @@
2
2
 
3
3
  Renaming or removing a token is a breaking change. Adding a token, or changing a value, is a minor release. Before 1.0, a breaking change bumps the minor version.
4
4
 
5
+ ## 0.2.0-beta.1
6
+
7
+ A beta, published under npm's `next` tag. `latest` stays at 0.1.0 until 0.2.0.
8
+
9
+ - **Added:** FlairDesigner's local addresses, `http://localhost:3300` (its dev server) and `http://localhost:4330` (its tests), to `DEFAULT_ALLOW`. A page that FlairDesigner frames now needs no `allow` list of its own. Flair Design's two addresses stay.
10
+ - **Changed:** a message from the host that isn't flair-kit's, one whose `type` doesn't start with `flair-kit:`, such as a browser extension's, is now ignored without a word. In beta.0 it got a console warning and a `refused` answer with the reason `type`, so the host showed a refusal while the theme was on. An unknown `flair-kit:` type is still refused.
11
+ - **Changed:** in Chrome and Safari, which name the parent's origin, the listener now sends `ready` only to that origin, or to none if it isn't allowed. A framed page no longer logs a console warning for each other allowed address. Where the browser doesn't name the parent, as in Firefox, or names it `"null"`, `ready` still goes to each allowed address.
12
+ - **Docs:** "Showing a site in Flair" in the README names FlairDesigner as the app that frames the page, and calls it the host.
13
+ - Two of its subheadings are renamed: "Which Flair may theme the page" is now "Which hosts may theme the page", and "Flair's side: `preview-host.js`" is now "The host's side: `preview-host.js`".
14
+ - The Playwright recipe's host address is now `HOST`, on `http://localhost:4330`, instead of `FLAIR`, on `http://localhost:4317`. Both are allowed, so a test copied from beta.0's recipe still runs.
15
+
16
+ ## 0.2.0-beta.0
17
+
18
+ A beta, published under npm's `next` tag. `latest` stays at 0.1.0 until 0.2.0.
19
+
20
+ - **Added:** `preview.js`, the listener that lets Flair Design show a site's page in its frame, wearing the theme being edited. Also `preview-host.js`, Flair's side, which a site's own tests can use too. Both ship with type declarations. See "Showing a site in Flair" in the README.
21
+ - **Added:** `layers` in `tokens.json`, and a "Cascade layers" section in `TOKENS.md`.
22
+ - **Breaking, for palettes:** the cascade layers are now `flair-kit.tokens, flair-kit.palette, flair-kit.components, flair-kit.preview`. Move the palette file's blocks inside `@layer flair-kit.palette { … }`, and open the file with the order line, so it works whatever order the CSS loads in. A palette left outside the layer still works on the site, but in Flair it beats the preview, so the page doesn't follow the theme being edited.
23
+
5
24
  ## 0.1.0
6
25
 
7
26
  First release: colour, spacing, type, radius, layer, motion, size and font tokens; light and dark modes; opt-in Inter.
package/README.md CHANGED
@@ -1,15 +1,15 @@
1
1
  # flair-kit
2
2
 
3
3
  Published on npm as `@flairstudio/kit`. Design tokens as plain CSS: colours with light and dark modes, spacing, type sizes, radius, layers, motion and fonts. No build step is needed to use them. The colour names are the ones the Flair Design theme tool uses.
4
- - A Flair theme exported in the `data-theme` style drops straight in as a site's palette file (see below).
5
- - Flair's `light-dark()` export doesn't, because it can't follow `data-theme`.
4
+ - A Flair theme exported in the `data-theme` style becomes a site's palette file once it sits inside the palette layer (see below). Until Flair's Export writes that wrapper, add it by hand.
5
+ - Flair's `light-dark()` export can't be used that way, because it can't follow `data-theme`.
6
6
 
7
7
  Every token is listed in `TOKENS.md`, which ships in the package.
8
8
 
9
9
  ## Use it in a site with a build
10
10
 
11
11
  ```sh
12
- npm install @flairstudio/kit@0.1.0 --save-exact
12
+ npm install @flairstudio/kit@0.2.0-beta.1 --save-exact
13
13
  ```
14
14
 
15
15
  Import in this order:
@@ -29,7 +29,7 @@ Install it as a dev dependency, copy `node_modules/@flairstudio/kit/dist/` into
29
29
  <link rel="stylesheet" href="assets/flair-kit/tokens.css">
30
30
  ```
31
31
 
32
- Line 1 of each CSS file names its version, `/* flair-kit 0.1.0 · … */`, so a test can check that the copy matches the installed version.
32
+ Line 1 of each generated file names its version, `/* flair-kit <version> · … */`, so a test can check that the copy matches the installed version.
33
33
 
34
34
  ## Light and dark
35
35
 
@@ -41,20 +41,28 @@ Line 1 of each CSS file names its version, `/* flair-kit 0.1.0 · … */`, so a
41
41
 
42
42
  The package's colours are a default. A site's palette file replaces them, and it must:
43
43
 
44
+ - **open with the layer order line, then put everything inside `@layer flair-kit.palette { … }`.** The line fixes the order of the layers whichever CSS file the browser reads first, so the palette beats the package's defaults even if it loads before `tokens.css`. The layer lets the preview beat the palette while a host shows the page (see "Showing a site in Flair").
44
45
  - **use the same three selectors as `tokens.css`, in this order.** The dark block must come after the light one, or `data-theme="dark"` on `<html>` stops working:
45
46
 
46
47
  ```css
47
- :root,
48
- [data-theme="light"] { color-scheme: light; --color-background: #…; /* … */ --gradient-angle: 110deg; }
48
+ @layer flair-kit.tokens, flair-kit.palette, flair-kit.components, flair-kit.preview;
49
49
 
50
- [data-theme="dark"] { color-scheme: dark; --color-background: #…; /* … */ }
50
+ @layer flair-kit.palette {
51
+ :root,
52
+ [data-theme="light"] { color-scheme: light; --color-background: #…; /* … */ --gradient-angle: 110deg; }
51
53
 
52
- @media (prefers-color-scheme: dark) {
53
- :root:not([data-theme="light"]) { color-scheme: dark; --color-background: #…; /* … */ }
54
+ [data-theme="dark"] { color-scheme: dark; --color-background: #…; /* … */ }
55
+
56
+ @media (prefers-color-scheme: dark) {
57
+ :root:not([data-theme="light"]) { color-scheme: dark; --color-background: #…; /* … */ }
58
+ }
54
59
  }
55
60
  ```
56
61
 
57
62
  - **set every colour in both modes.** A colour the file leaves out falls back to the package's default. `tokens.json` lists them all under `colors.names`, so a site test can check its palette covers them.
63
+ - **set colours only on `:root` and on elements with `data-theme`.** A palette may use stronger selectors, such as `#page[data-palette][data-theme]`, as long as the element carries `data-theme`. A colour set on any other element, such as `body` or `.page`, isn't reached by the preview: the element keeps the palette's value instead of inheriting the preview's.
64
+
65
+ A palette left outside the layer still works on the site, but in the host's frame it beats the preview, so the page doesn't change as the theme is edited.
58
66
 
59
67
  Override a colour with those same three selectors. A colour set only on `:root` behaves differently:
60
68
  - it applies to the page in every mode, so a value chosen for light mode also shows in dark mode;
@@ -63,7 +71,13 @@ Override a colour with those same three selectors. A colour set only on `:root`
63
71
 
64
72
  Check colour values carefully. The colours are registered as `<color>`, so a misspelt value (`#1f2a3`, `banana`) doesn't fail loudly. The element quietly takes its parent's colour instead, which inside a `data-theme` region can mean a light colour in a dark region.
65
73
 
66
- Every token declaration in the package sits in the `flair-kit.tokens` cascade layer. The `@property` registrations in `tokens.css` and the `@font-face` rules in `fonts.css` sit outside it by design, because neither needs overriding. A site's own CSS outside a layer always wins, whatever its selectors, so no override needs `!important`. A site that uses its own layers declares them after `@layer flair-kit.tokens, flair-kit.components;`.
74
+ Every token declaration in the package sits in the `flair-kit.tokens` cascade layer. The `@property` registrations in `tokens.css` and the `@font-face` rules in `fonts.css` sit outside it by design, because neither needs overriding. A site's own CSS outside a layer always wins, whatever its selectors, so no override needs `!important`, and overrides stay outside a layer. From lowest to highest, the order is the package's defaults, the site's palette, components, the preview, then the site's unlayered CSS:
75
+
76
+ ```css
77
+ @layer flair-kit.tokens, flair-kit.palette, flair-kit.components, flair-kit.preview;
78
+ ```
79
+
80
+ A site that uses its own layers declares them after flair-kit's.
67
81
 
68
82
  ## Breakpoints
69
83
 
@@ -73,6 +87,144 @@ Every token declaration in the package sits in the `flair-kit.tokens` cascade la
73
87
 
74
88
  The package adds no transitions. `--dur-theme` is there for a site that fades between themes; under `prefers-reduced-motion: reduce` it becomes `0.01ms`, never `0s`, so code waiting on a transition's end event still hears it. A site that sets its own `--dur-theme` overrides that as well, so it should set it again inside its own `@media (prefers-reduced-motion: reduce)` block.
75
89
 
90
+ ## Showing a site in Flair
91
+
92
+ FlairDesigner can show a site's real page in a frame, wearing the theme being edited, and follow every change live. This section calls it the host: any app that frames the page and sends it themes with `preview-host.js`. The page needs the listener, `preview.js`, from this package. It loads only inside a frame, so visitors never download it.
93
+
94
+ ### Load the listener
95
+
96
+ A site with a build, in its entry file:
97
+
98
+ ```js
99
+ if (window.self !== window.top) import('@flairstudio/kit/preview.js').then((m) => m.listen());
100
+ ```
101
+
102
+ The bundler puts the import in a file of its own, which loads only when the page is framed.
103
+
104
+ A site without a build, with `dist/` copied to `assets/flair-kit/`, after its stylesheet links:
105
+
106
+ ```html
107
+ <script type="module">
108
+ if (window.self !== window.top) import('./assets/flair-kit/preview.js').then((m) => m.listen());
109
+ </script>
110
+ ```
111
+
112
+ Outside a frame, `listen()` does nothing. Calling it again while it runs changes nothing, and it returns a function that stops it.
113
+
114
+ ### Which hosts may theme the page
115
+
116
+ `listen()` takes themes only from the hosts' own local addresses, which it exports as `DEFAULT_ALLOW`:
117
+ - `http://localhost:3000` and `http://localhost:4317`: Flair Design's dev server and its tests;
118
+ - `http://localhost:3300` and `http://localhost:4330`: the same for FlairDesigner.
119
+
120
+ Pass `allow` to replace the list, or spread the default to add to it:
121
+
122
+ ```js
123
+ import('@flairstudio/kit/preview.js').then(({ listen, DEFAULT_ALLOW }) =>
124
+ listen({ allow: [...DEFAULT_ALLOW, 'https://flair.example'] }));
125
+ ```
126
+
127
+ Addresses must match exactly: `http://127.0.0.1:3300` isn't `http://localhost:3300`. A message from any other address, or from a window that isn't the page's parent, is ignored without a word. So is a message from the host that isn't flair-kit's, one whose `type` doesn't start with `flair-kit:`, such as a browser extension's. Only colour names the package knows and `#rrggbb` values get through, so a message can't add any other CSS.
128
+
129
+ When it starts, the listener tells the page's parent it's ready. Chrome and Safari name the parent's origin (`location.ancestorOrigins`), so there it sends to that origin alone, or to none if the origin isn't allowed. Where the browser doesn't name the parent, as in Firefox, or names it `"null"`, the listener sends to each allowed address, and the browser drops the ones that don't match. A browser may log a console warning for each one it drops.
130
+
131
+ ### What the listener changes
132
+
133
+ Only these, and only once the host has sent a theme:
134
+ - its own `<style>`, in the `flair-kit.preview` layer, which beats the site's palette but not its unlayered overrides;
135
+ - `data-theme` on `<html>`, set to the mode chosen in the host;
136
+ - `data-flair-preview` on `<html>`, set with the first theme;
137
+ - an inline `--dur-theme` on `<html>`: `0.01ms` for the first theme and while a colour is being dragged, so nothing fades.
138
+
139
+ The preview beats the palette only when the palette sits in its layer (see "A site's palette and overrides"). If a router or hydration rebuilds `<head>`, the listener puts its `<style>` back with the next theme. A Content Security Policy whose `style-src` doesn't allow inline styles blocks that `<style>`, so the page keeps its own colours in the host's frame. Allow inline styles on the pages a host frames.
140
+
141
+ ### Review tools step aside
142
+
143
+ A site's own review tools, such as a theme switcher, notes or a palette menu, would fight the host's. Hide them under the attribute:
144
+
145
+ ```css
146
+ [data-flair-preview] .review-tools { display: none; }
147
+ ```
148
+
149
+ A script that needs to react listens for the event, fired on `document` each time a theme goes on:
150
+
151
+ ```js
152
+ document.addEventListener('flair-kit:preview', (event) => {
153
+ const { mode, first } = event.detail; // 'light' or 'dark'; true for the first theme
154
+ });
155
+ ```
156
+
157
+ The host shows the page once the listeners have run and two frames have been drawn, so a change made in the handler is in place by then.
158
+
159
+ ### Two rules
160
+
161
+ - **The host sets the mode on `<html>`, and an element with its own `data-theme` keeps it.** So a page root that sets its own `data-theme`, such as `#page`, copies `event.detail.mode` into it on every event. Regions that always stay one mode keep theirs.
162
+ - **Set `--dur-theme` on `:root` only.** The listener's inline value on `<html>` beats it there. A value set on another element would bring the fade back during a drag.
163
+
164
+ ### The host's side: `preview-host.js`
165
+
166
+ The host sends themes with `preview-host.js`, and a site's tests can too:
167
+
168
+ ```js
169
+ import { connect } from '@flairstudio/kit/preview-host.js';
170
+
171
+ const { send, close } = connect(iframe, {
172
+ origin: 'http://localhost:5173', // the site's address
173
+ onReady: ({ kit, names }) => {}, // the frame's package version and colour names
174
+ onApplied: () => {}, // the theme is on: the frame is ready to be seen
175
+ onRefused: (reason) => {}, // a short code, such as 'value'
176
+ onMismatch: ({ host, frame }) => {}, // the frame speaks another format version
177
+ });
178
+ send({ light, dark, mode: 'light', angle: 110, instant: false });
179
+ ```
180
+
181
+ `light` and `dark` map colour names, without the `--color-` prefix, to `#rrggbb` values. `send` throws a `TypeError` on a theme the frame would refuse. It keeps the latest theme and sends it whenever the frame says it's ready: at once, and again after a reload or a link inside the frame. It sends only the colour names the frame knows. `close()` stops listening.
182
+
183
+ ### Testing a site's pages with a Flair theme
184
+
185
+ A site's Playwright tests can put a theme on its pages without the host running. The test answers an allowed address itself with `page.route`, serving a small host page and the two scripts. The site's own server serves the page under test.
186
+
187
+ ```js
188
+ import { test, expect } from '@playwright/test';
189
+ import { createRequire } from 'node:module';
190
+ import { dirname, join } from 'node:path';
191
+
192
+ const HOST = 'http://localhost:4330'; // an allowed address; nothing needs to run there
193
+ const SITE = 'http://localhost:5173/'; // the page under test
194
+ const require = createRequire(import.meta.url);
195
+ const dist = dirname(require.resolve('@flairstudio/kit/preview-host.js'));
196
+ // The package's default palette; use a Flair export's values to test a real theme
197
+ const { light, dark } = require('@flairstudio/kit/tokens.json').colors;
198
+
199
+ const HOST_PAGE = `<!doctype html>
200
+ <iframe src="${SITE}" title="Site" style="width: 1480px; height: 900px; border: 0"></iframe>
201
+ <script type="module">
202
+ import { connect } from './preview-host.js';
203
+ const frame = document.querySelector('iframe');
204
+ window.flairKit = { applied: 0, refused: [] };
205
+ window.flairKit.host = connect(frame, {
206
+ origin: new URL(frame.src).origin,
207
+ onApplied: () => { window.flairKit.applied++; },
208
+ onRefused: (reason) => { window.flairKit.refused.push(reason); },
209
+ });
210
+ </script>`;
211
+
212
+ test('the home page wears a Flair theme', async ({ page }) => {
213
+ await page.route(`${HOST}/**`, (route) => {
214
+ const { pathname } = new URL(route.request().url());
215
+ if (pathname === '/') return route.fulfill({ contentType: 'text/html', body: HOST_PAGE });
216
+ return route.fulfill({ path: join(dist, pathname.slice(1)) }); // preview-host.js, and the preview.js it imports
217
+ });
218
+ await page.goto(`${HOST}/`);
219
+ await page.evaluate((theme) => window.flairKit.host.send(theme), { light, dark, mode: 'dark', angle: 110 });
220
+ await expect.poll(() => page.evaluate(() => window.flairKit.applied)).toBeGreaterThan(0);
221
+ const site = page.frameLocator('iframe');
222
+ // check the site's page through `site`
223
+ });
224
+ ```
225
+
226
+ In a TypeScript test, `window.flairKit` needs a cast inside `page.evaluate`, such as `(window as any).flairKit`.
227
+
76
228
  ## Versions
77
229
 
78
230
  Pin an exact version, and read `CHANGELOG.md` (it ships in the package) before upgrading. Renaming or removing a token is a breaking change.
package/TOKENS.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # flair-kit tokens
2
2
 
3
- Version 0.1.0. Colours change with the mode; everything else stays the same in light and dark.
3
+ Version 0.2.0-beta.1. Colours change with the mode; everything else stays the same in light and dark.
4
4
 
5
5
  ## Colours
6
6
 
@@ -183,4 +183,13 @@ Under `prefers-reduced-motion: reduce`:
183
183
 
184
184
  - `--dur-theme` becomes `0.01ms`
185
185
 
186
+ ## Cascade layers
187
+
188
+ From lowest to highest, then the site's own unlayered CSS, which beats them all:
189
+
190
+ - `flair-kit.tokens`: the package's defaults, which are every token in this file
191
+ - `flair-kit.palette`: the site's palette file
192
+ - `flair-kit.components`: components
193
+ - `flair-kit.preview`: the theme Flair sends while it shows the page in its frame
194
+
186
195
  Generated from src/tokens.ts by npm run build.
package/dist/fonts.css CHANGED
@@ -1,4 +1,4 @@
1
- /* flair-kit 0.1.0 · generated from src/tokens.ts · do not edit */
1
+ /* flair-kit 0.2.0-beta.1 · generated from src/tokens.ts · do not edit */
2
2
 
3
3
  @font-face {
4
4
  font-family: Inter;
@@ -0,0 +1,39 @@
1
+ /* flair-kit 0.2.0-beta.1 · generated from src/tokens.ts · do not edit */
2
+
3
+ import type { Colors, Mode } from './preview.js';
4
+
5
+ export { COLOR_NAMES, FORMAT_VERSION, KIT_VERSION } from './preview.js';
6
+ export type { ColorName, Colors, Mode, Reason } from './preview.js';
7
+
8
+ /** A theme as the host sends it: both modes' colours, the canvas mode, the gradient angle, and whether a drag is under way */
9
+ export interface Theme {
10
+ readonly light: Colors;
11
+ readonly dark: Colors;
12
+ readonly mode: Mode;
13
+ /** Degrees, from 0 to 360 */
14
+ readonly angle: number;
15
+ /** True while a drag or typing is under way, so the page doesn't fade */
16
+ readonly instant?: boolean;
17
+ }
18
+ /** What the frame said when it became ready */
19
+ export interface ReadyInfo { readonly kit: string; readonly names: readonly string[] }
20
+ export interface ConnectOptions {
21
+ /** The site's origin, or any address on it */
22
+ readonly origin: string;
23
+ /** The frame is listening: its package version and the colour names it accepts */
24
+ readonly onReady?: (info: ReadyInfo) => void;
25
+ /** The frame has put the theme on and is ready to be seen */
26
+ readonly onApplied?: () => void;
27
+ /** The frame refused the theme, or shares no colour names with it ("name") */
28
+ readonly onRefused?: (reason: string) => void;
29
+ /** The frame speaks another format version, so nothing is sent */
30
+ readonly onMismatch?: (versions: { readonly host: number; readonly frame: unknown }) => void;
31
+ }
32
+ export interface Connection {
33
+ /** Checks the theme, keeps it, and sends it now and whenever the frame says ready again. Throws a TypeError on a theme the frame would refuse */
34
+ send(theme: Theme): void;
35
+ /** Stops listening to the frame */
36
+ close(): void;
37
+ }
38
+ /** Connects to the page in an <iframe> of a site */
39
+ export declare function connect(frame: HTMLIFrameElement, options: ConnectOptions): Connection;
@@ -0,0 +1,94 @@
1
+ /* flair-kit 0.2.0-beta.1 · generated from src/preview-host.js · do not edit */
2
+
3
+ // The host's side of the preview: frames a site's page and sends it the theme being edited. A site's own tests use
4
+ // it too, to put a Flair theme on their pages without the host running. The names and the checks come from
5
+ // ./preview.js, so both sides of the format are written once.
6
+ import { COLOR_NAMES, FORMAT_VERSION, KIT_VERSION, MESSAGE_TYPES, checkTheme } from './preview.js';
7
+
8
+ export { COLOR_NAMES, FORMAT_VERSION, KIT_VERSION };
9
+
10
+ /** An address as an origin. Only an http or https page can be framed and posted to */
11
+ function toOrigin(address) {
12
+ let url = null;
13
+ try {
14
+ url = new URL(address);
15
+ } catch {
16
+ // not a URL at all
17
+ }
18
+ if (!url || (url.protocol !== 'http:' && url.protocol !== 'https:')) {
19
+ throw new TypeError(`flair-kit: connect() needs an http or https origin, not ${JSON.stringify(String(address))}`);
20
+ }
21
+ return url.origin;
22
+ }
23
+
24
+ /**
25
+ * Connects to the page in `frame`, an <iframe> of a site at `options.origin`. Returns { send, close }.
26
+ * send(theme) keeps the latest theme and sends it whenever the frame says ready: now, after a reload, after a link.
27
+ */
28
+ export function connect(frame, options) {
29
+ const origin = toOrigin(options?.origin);
30
+ const { onReady, onApplied, onRefused, onMismatch } = options;
31
+ const win = frame.ownerDocument.defaultView;
32
+
33
+ let names = null;
34
+ let latest = null;
35
+ let closed = false;
36
+
37
+ const toFrame = (message) => frame.contentWindow?.postMessage(message, origin);
38
+
39
+ const sendLatest = () => {
40
+ if (!latest || !names) return;
41
+ const shared = names.filter((name) => Object.hasOwn(latest.light, name));
42
+ if (shared.length === 0) {
43
+ onRefused?.('name');
44
+ return;
45
+ }
46
+ const pick = (values) => Object.fromEntries(shared.map((name) => [name, values[name]]));
47
+ toFrame({
48
+ type: MESSAGE_TYPES.theme,
49
+ v: FORMAT_VERSION,
50
+ light: pick(latest.light),
51
+ dark: pick(latest.dark),
52
+ mode: latest.mode,
53
+ angle: latest.angle,
54
+ instant: latest.instant === true,
55
+ });
56
+ };
57
+
58
+ const onMessage = (event) => {
59
+ if (event.origin !== origin || !event.source || event.source !== frame.contentWindow) return;
60
+ const { data } = event;
61
+ if (data === null || typeof data !== 'object') return;
62
+ if (data.type === MESSAGE_TYPES.ready) {
63
+ if (data.v !== FORMAT_VERSION) {
64
+ names = null;
65
+ onMismatch?.({ host: FORMAT_VERSION, frame: data.v });
66
+ return;
67
+ }
68
+ names = Array.isArray(data.names) ? data.names.filter((name) => typeof name === 'string') : [];
69
+ onReady?.({ kit: String(data.kit), names: [...names] });
70
+ sendLatest();
71
+ } else if (data.type === MESSAGE_TYPES.applied) {
72
+ onApplied?.();
73
+ } else if (data.type === MESSAGE_TYPES.refused) {
74
+ onRefused?.(String(data.reason));
75
+ }
76
+ };
77
+
78
+ win.addEventListener('message', onMessage);
79
+ toFrame({ type: MESSAGE_TYPES.hello, v: FORMAT_VERSION });
80
+
81
+ return {
82
+ send(theme) {
83
+ const reason = checkTheme(theme, COLOR_NAMES);
84
+ if (reason) throw new TypeError(`flair-kit: send() was given a theme the frame would refuse (${reason})`);
85
+ if (closed) return;
86
+ latest = { light: { ...theme.light }, dark: { ...theme.dark }, mode: theme.mode, angle: theme.angle, instant: theme.instant };
87
+ sendLatest();
88
+ },
89
+ close() {
90
+ closed = true;
91
+ win.removeEventListener('message', onMessage);
92
+ },
93
+ };
94
+ }
@@ -0,0 +1,37 @@
1
+ /* flair-kit 0.2.0-beta.1 · generated from src/tokens.ts · do not edit */
2
+
3
+ /** The package version this listener came from */
4
+ export declare const KIT_VERSION: string;
5
+ /** The message format's version. It goes up only when a field changes meaning or a new field becomes required */
6
+ export declare const FORMAT_VERSION: 1;
7
+ /** The colour names this listener accepts, without the --color- prefix, in the package's order */
8
+ export declare const COLOR_NAMES: readonly ["background","card","muted","secondary","foreground","card-foreground","muted-foreground","on-secondary","border","outline","primary","on-primary","primary-hover","primary-pressed","primary-text","ring","tertiary","on-tertiary","accent-2","glow","destructive","on-destructive","chart-1","chart-2","chart-3","chart-4","brand","gradient-1","gradient-2","gradient-3"];
9
+ /** A colour name, without the --color- prefix */
10
+ export type ColorName = (typeof COLOR_NAMES)[number];
11
+ /** A colour mode */
12
+ export type Mode = 'light' | 'dark';
13
+ /** The host addresses listen() allows when it's given no list: Flair Design's dev server and tests, then FlairDesigner's */
14
+ export declare const DEFAULT_ALLOW: readonly ["http://localhost:3000","http://localhost:4317","http://localhost:3300","http://localhost:4330"];
15
+ /** The type of each message in the format */
16
+ export declare const MESSAGE_TYPES: { readonly ready: "flair-kit:ready"; readonly hello: "flair-kit:hello"; readonly theme: "flair-kit:theme"; readonly applied: "flair-kit:applied"; readonly refused: "flair-kit:refused"; };
17
+ /** Why a theme was refused. A refusal never echoes the values it was sent */
18
+ export type Reason = "type" | "version" | "mode" | "angle" | "name" | "value";
19
+ /** Colours by name, each a #rrggbb value */
20
+ export type Colors = { readonly [N in ColorName]?: string };
21
+ /** The detail of the flair-kit:preview event, fired on document each time a theme goes on */
22
+ export interface PreviewEventDetail { readonly mode: Mode; readonly first: boolean }
23
+ /** Options for listen() */
24
+ export interface ListenOptions {
25
+ /** The host addresses that may theme the page, as origins or page addresses. It replaces DEFAULT_ALLOW */
26
+ readonly allow?: readonly string[];
27
+ }
28
+ /** Starts listening for the host if the page is in a frame, and returns a function that stops it. A second call while it runs returns the same function */
29
+ export declare function listen(options?: ListenOptions): () => void;
30
+ /** Checks a theme's mode, angle and colours against `names`: the first reason it fails, or null. Never throws */
31
+ export declare function checkTheme(theme: unknown, names: readonly string[]): Reason | null;
32
+
33
+ declare global {
34
+ interface DocumentEventMap {
35
+ 'flair-kit:preview': CustomEvent<PreviewEventDetail>;
36
+ }
37
+ }
@@ -0,0 +1,220 @@
1
+ /* flair-kit 0.2.0-beta.1 · generated from src/preview.js and src/tokens.ts · do not edit */
2
+
3
+ // Written by the build from src/tokens.ts and src/preview-format.ts
4
+ export const KIT_VERSION = "0.2.0-beta.1";
5
+ export const FORMAT_VERSION = 1;
6
+ export const COLOR_NAMES = Object.freeze(["background","card","muted","secondary","foreground","card-foreground","muted-foreground","on-secondary","border","outline","primary","on-primary","primary-hover","primary-pressed","primary-text","ring","tertiary","on-tertiary","accent-2","glow","destructive","on-destructive","chart-1","chart-2","chart-3","chart-4","brand","gradient-1","gradient-2","gradient-3"]);
7
+ export const DEFAULT_ALLOW = Object.freeze(["http://localhost:3000","http://localhost:4317","http://localhost:3300","http://localhost:4330"]);
8
+ export const MESSAGE_TYPES = Object.freeze({"ready":"flair-kit:ready","hello":"flair-kit:hello","theme":"flair-kit:theme","applied":"flair-kit:applied","refused":"flair-kit:refused"});
9
+ const MESSAGE_PREFIX = "flair-kit:";
10
+ const LAYER_ORDER = "@layer flair-kit.tokens, flair-kit.palette, flair-kit.components, flair-kit.preview;";
11
+ const PREVIEW_LAYER = "flair-kit.preview";
12
+
13
+ // The listener that lets a host, such as FlairDesigner, show this page in its frame, wearing the theme being edited.
14
+ // KIT_VERSION, FORMAT_VERSION, COLOR_NAMES, DEFAULT_ALLOW, MESSAGE_TYPES, MESSAGE_PREFIX, LAYER_ORDER and PREVIEW_LAYER are
15
+ // written above this file by the build (scripts/lib/preview.ts). Nothing here runs until listen() is called.
16
+
17
+ const HEX = /^#[0-9a-f]{6}$/i;
18
+ const MODES = ['light', 'dark'];
19
+ const EVENT = 'flair-kit:preview';
20
+ const ATTRIBUTE = 'data-flair-preview';
21
+ /** Never 0s, so code waiting on a transition's end event still hears it */
22
+ const HOLD = '0.01ms';
23
+ /** applied waits for two animation frames; this stands behind them in case the browser holds frames back */
24
+ const APPLIED_FALLBACK_MS = 500;
25
+
26
+ /** The running listener for each window, so a page never has two */
27
+ const running = new WeakMap();
28
+ /** The listener's one <style> in each document, kept across a stop() and a fresh listen() */
29
+ const sheets = new WeakMap();
30
+
31
+ /** The preview stylesheet, built only from checked names and values, in the frame's colour order */
32
+ function stylesheet({ light, dark, angle }) {
33
+ const names = COLOR_NAMES.filter((name) => Object.hasOwn(light, name));
34
+ const colours = (values, pad) => names.map((name) => `${pad}--color-${name}: ${values[name]};`);
35
+ return [
36
+ LAYER_ORDER,
37
+ `@layer ${PREVIEW_LAYER} {`,
38
+ ' :root,',
39
+ ' [data-theme="light"] {',
40
+ ' color-scheme: light;',
41
+ ...colours(light, ' '),
42
+ ` --gradient-angle: ${angle}deg;`,
43
+ ' }',
44
+ ' [data-theme="dark"] {',
45
+ ' color-scheme: dark;',
46
+ ...colours(dark, ' '),
47
+ ' }',
48
+ ' @media (prefers-color-scheme: dark) {',
49
+ ' :root:not([data-theme="light"]) {',
50
+ ' color-scheme: dark;',
51
+ ...colours(dark, ' '),
52
+ ' }',
53
+ ' }',
54
+ '}',
55
+ '',
56
+ ].join('\n');
57
+ }
58
+
59
+ /** An address as an origin. Only an http or https page can frame this one and post to it */
60
+ function toOrigin(address) {
61
+ let url = null;
62
+ try {
63
+ url = new URL(address);
64
+ } catch {
65
+ // not a URL at all
66
+ }
67
+ if (!url || (url.protocol !== 'http:' && url.protocol !== 'https:')) {
68
+ throw new TypeError(`flair-kit: listen() allows only http and https addresses, not ${JSON.stringify(String(address))}`);
69
+ }
70
+ return url.origin;
71
+ }
72
+
73
+ const isColors = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
74
+
75
+ /**
76
+ * Checks a theme's mode, angle and colours: the first reason it fails, or null. Never throws.
77
+ * `names` are the colour names that may appear, without the --color- prefix.
78
+ */
79
+ export function checkTheme(theme, names) {
80
+ if (theme === null || typeof theme !== 'object' || !MODES.includes(theme.mode)) return 'mode';
81
+ const { angle, light, dark } = theme;
82
+ if (typeof angle !== 'number' || !Number.isFinite(angle) || angle < 0 || angle > 360) return 'angle';
83
+ if (!isColors(light) || !isColors(dark)) return 'name';
84
+ const keys = Object.keys(light);
85
+ if (keys.length === 0 || keys.length !== Object.keys(dark).length || !keys.every((key) => Object.hasOwn(dark, key))) return 'name';
86
+ const known = new Set(names);
87
+ if (!keys.every((key) => known.has(key))) return 'name';
88
+ const isHex = (value) => typeof value === 'string' && HEX.test(value);
89
+ if (!keys.every((key) => isHex(light[key]) && isHex(dark[key]))) return 'value';
90
+ return null;
91
+ }
92
+
93
+ /** True for an object whose type starts flair-kit:. Anything else, such as an extension's chatter, isn't ours to answer */
94
+ const isOurs = (data) => data !== null && typeof data === 'object' && typeof data.type === 'string' && data.type.startsWith(MESSAGE_PREFIX);
95
+
96
+ /** Why a flair-kit message from the allowed parent can't be used, or null */
97
+ function messageReason(data) {
98
+ if (data.type !== MESSAGE_TYPES.theme && data.type !== MESSAGE_TYPES.hello) return 'type';
99
+ if (data.v !== FORMAT_VERSION) return 'version';
100
+ return data.type === MESSAGE_TYPES.theme ? checkTheme(data, COLOR_NAMES) : null;
101
+ }
102
+
103
+ const readyMessage = () => ({ type: MESSAGE_TYPES.ready, v: FORMAT_VERSION, kit: KIT_VERSION, names: [...COLOR_NAMES] });
104
+
105
+ /**
106
+ * Starts listening for the host, if this page is inside a frame. Returns a function that stops it.
107
+ * `allow` lists the host addresses that may theme the page; without it, DEFAULT_ALLOW, the hosts' own local addresses.
108
+ * Calling it again while it runs returns the same stop function and changes nothing.
109
+ */
110
+ export function listen(options = {}) {
111
+ const win = globalThis.window;
112
+ if (!win || win.self === win.top) return () => {};
113
+ const current = running.get(win);
114
+ if (current) return current.stop;
115
+
116
+ const allow = [...(options.allow ?? DEFAULT_ALLOW)].map(toOrigin);
117
+ const post = (message, origin) => win.parent.postMessage(message, origin);
118
+ // Chrome and Safari name the parent's origin, so ready goes there alone, or nowhere if it isn't allowed, and no
119
+ // post fails with a console warning. Elsewhere, or when it's hidden as "null", ready goes to each allowed origin.
120
+ const parentOrigin = win.location?.ancestorOrigins?.[0];
121
+ const named = typeof parentOrigin === 'string' && parentOrigin !== 'null';
122
+ const readyTo = named ? allow.filter((origin) => origin === parentOrigin).slice(0, 1) : allow;
123
+
124
+ let first = true;
125
+ /** True once the first theme has been drawn and its applied has gone. Until then every theme keeps the hold */
126
+ let firstDrawn = false;
127
+ let pending = null;
128
+ let pendingFrame = 0;
129
+ const waits = new Set();
130
+
131
+ /** Runs `done` once, after two animation frames or the fallback timer, whichever comes first */
132
+ const afterTwoFrames = (done) => {
133
+ const wait = { frame: 0, timer: 0 };
134
+ const finish = () => {
135
+ if (!waits.delete(wait)) return;
136
+ win.cancelAnimationFrame(wait.frame);
137
+ win.clearTimeout(wait.timer);
138
+ done();
139
+ };
140
+ waits.add(wait);
141
+ wait.frame = win.requestAnimationFrame(() => {
142
+ wait.frame = win.requestAnimationFrame(finish);
143
+ });
144
+ wait.timer = win.setTimeout(finish, APPLIED_FALLBACK_MS);
145
+ };
146
+
147
+ const apply = (theme, origin) => {
148
+ const doc = win.document;
149
+ const root = doc.documentElement;
150
+ let sheet = sheets.get(doc);
151
+ if (!sheet) {
152
+ sheet = doc.createElement('style');
153
+ sheets.set(doc, sheet);
154
+ }
155
+ // A router or hydration can rebuild <head>; put the sheet back rather than theme a detached element
156
+ if (!sheet.isConnected) (doc.head ?? root).append(sheet);
157
+ const isFirst = first;
158
+ first = false;
159
+ sheet.textContent = stylesheet(theme);
160
+ root.setAttribute('data-theme', theme.mode);
161
+ // A theme that lands before the first has been drawn keeps the hold too, or the first would fade after all
162
+ if (!firstDrawn || theme.instant === true) root.style.setProperty('--dur-theme', HOLD);
163
+ else root.style.removeProperty('--dur-theme');
164
+ if (isFirst) root.setAttribute(ATTRIBUTE, '');
165
+ doc.dispatchEvent(new win.CustomEvent(EVENT, { detail: { mode: theme.mode, first: isFirst } }));
166
+ afterTwoFrames(() => {
167
+ if (isFirst) firstDrawn = true;
168
+ post({ type: MESSAGE_TYPES.applied, v: FORMAT_VERSION }, origin);
169
+ });
170
+ };
171
+
172
+ /** The first theme goes on at once; later ones are coalesced, the latest once per animation frame */
173
+ const receiveTheme = (theme, origin) => {
174
+ if (first) {
175
+ apply(theme, origin);
176
+ return;
177
+ }
178
+ pending = { theme, origin };
179
+ if (pendingFrame) return;
180
+ pendingFrame = win.requestAnimationFrame(() => {
181
+ pendingFrame = 0;
182
+ const next = pending;
183
+ pending = null;
184
+ if (next) apply(next.theme, next.origin);
185
+ });
186
+ };
187
+
188
+ const onMessage = (event) => {
189
+ if (!allow.includes(event.origin)) return;
190
+ if (event.source !== win.parent) return;
191
+ const { data } = event;
192
+ if (!isOurs(data)) return;
193
+ const reason = messageReason(data);
194
+ if (reason) {
195
+ console.warn(`flair-kit: a preview message from the host was refused (${reason})`);
196
+ post({ type: MESSAGE_TYPES.refused, v: FORMAT_VERSION, reason }, event.origin);
197
+ return;
198
+ }
199
+ if (data.type === MESSAGE_TYPES.hello) post(readyMessage(), event.origin);
200
+ else receiveTheme(data, event.origin);
201
+ };
202
+
203
+ const stop = () => {
204
+ win.removeEventListener('message', onMessage);
205
+ if (pendingFrame) win.cancelAnimationFrame(pendingFrame);
206
+ pendingFrame = 0;
207
+ pending = null;
208
+ for (const wait of waits) {
209
+ win.cancelAnimationFrame(wait.frame);
210
+ win.clearTimeout(wait.timer);
211
+ }
212
+ waits.clear();
213
+ if (running.get(win)?.stop === stop) running.delete(win);
214
+ };
215
+
216
+ running.set(win, { stop });
217
+ win.addEventListener('message', onMessage);
218
+ for (const origin of readyTo) post(readyMessage(), origin);
219
+ return stop;
220
+ }
package/dist/tokens.css CHANGED
@@ -1,6 +1,6 @@
1
- /* flair-kit 0.1.0 · generated from src/tokens.ts · do not edit */
1
+ /* flair-kit 0.2.0-beta.1 · generated from src/tokens.ts · do not edit */
2
2
 
3
- @layer flair-kit.tokens, flair-kit.components;
3
+ @layer flair-kit.tokens, flair-kit.palette, flair-kit.components, flair-kit.preview;
4
4
 
5
5
  /* Registered so colours can fade between themes; inherits: true so a data-theme region gets its own values */
6
6
  @property --color-background { syntax: '<color>'; inherits: true; initial-value: #f6faf9; }
package/dist/tokens.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "0.1.0",
2
+ "version": "0.2.0-beta.1",
3
3
  "colors": {
4
4
  "names": [
5
5
  "background",
@@ -592,5 +592,11 @@
592
592
  },
593
593
  "reducedMotion": {
594
594
  "--dur-theme": "0.01ms"
595
- }
595
+ },
596
+ "layers": [
597
+ "flair-kit.tokens",
598
+ "flair-kit.palette",
599
+ "flair-kit.components",
600
+ "flair-kit.preview"
601
+ ]
596
602
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flairstudio/kit",
3
- "version": "0.1.0",
3
+ "version": "0.2.0-beta.1",
4
4
  "description": "Design tokens as plain CSS: colours with light and dark modes, spacing, type, layers and motion.",
5
5
  "license": "MIT",
6
6
  "author": "FlairStudio",
@@ -10,11 +10,14 @@
10
10
  "./tokens.css": "./dist/tokens.css",
11
11
  "./fonts.css": "./dist/fonts.css",
12
12
  "./tokens.json": "./dist/tokens.json",
13
+ "./preview.js": { "types": "./dist/preview.d.ts", "default": "./dist/preview.js" },
14
+ "./preview-host.js": { "types": "./dist/preview-host.d.ts", "default": "./dist/preview-host.js" },
13
15
  "./package.json": "./package.json"
14
16
  },
15
17
  "sideEffects": ["**/*.css"],
16
18
  "publishConfig": {
17
- "access": "public"
19
+ "access": "public",
20
+ "tag": "next"
18
21
  },
19
22
  "scripts": {
20
23
  "build": "node scripts/build.ts",