@noix-dev/brix-core 0.0.0-stage → 0.2.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 NoiX
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,57 @@
1
- # Temporary Holding Version
1
+ # @noix-dev/brix-core
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The framework-free half of Brix, a small design system for Vue 3 and Tailwind
4
+ CSS 4 applications. Two things, no dependencies:
5
+
6
+ - **Appearance.** Applies the four choices a user makes about how an interface
7
+ looks — the named theme, the colour mode, and the two density axes — to
8
+ `document.documentElement`, and remembers each one in `localStorage`.
9
+ - **The label contract.** A typed set of interface strings an application fills
10
+ with its own wording, with German and English catalogues to start from, so the
11
+ components carry no hard-coded text.
12
+
13
+ Plain TypeScript, shipped as source. Vue is an optional peer dependency and is
14
+ only needed for the label provider.
15
+
16
+ ## Install
17
+
18
+ ```bash
19
+ pnpm add @noix-dev/brix-core
20
+ ```
21
+
22
+ ## Use
23
+
24
+ Apply the remembered appearance before the application mounts, so the first
25
+ paint is already right rather than flipping a frame later:
26
+
27
+ ```ts
28
+ import { initAppearance } from '@noix-dev/brix-core';
29
+
30
+ // Storage prefix, fallback theme, and the themes this application ships —
31
+ // a remembered name outside that list falls back instead of being written
32
+ // onto the document, where it would match no stylesheet.
33
+ initAppearance('myapp', 'graphite', ['graphite', 'noix', 'kingfisher']);
34
+ ```
35
+
36
+ Then change it as the user asks:
37
+
38
+ ```ts
39
+ import { applyThemeName, applyTheme, applyTableDensity } from '@noix-dev/brix-core';
40
+
41
+ applyThemeName('kingfisher', 'myapp.theme'); // the named theme
42
+ applyTheme('system', 'myapp.mode'); // light | dark | system
43
+ applyTableDensity('compact', 'myapp.tableDensity'); // normal | compact | dense
44
+ ```
45
+
46
+ `subscribeAppearance(fn)` reports every change, including the OS flipping its
47
+ colour scheme while the mode is `system`, so a control on screen can follow
48
+ without watching the document.
49
+
50
+ The functions read and write the document directly, so call them in a browser.
51
+
52
+ The roles these attributes bind live in `@noix-dev/brix-tokens`; without that
53
+ stylesheet there is nothing for `data-brix-theme` to select.
54
+
55
+ ## Repository
56
+
57
+ <https://github.com/NoiXdev/noix-brix> — MIT.
package/package.json CHANGED
@@ -1,6 +1,40 @@
1
1
  {
2
2
  "name": "@noix-dev/brix-core",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.2.0",
4
+ "description": "Brix logic: applies a theme, a colour mode and the two density axes to the document (no Vue needed for that entry), and defines the label contract, with de/en catalogues, an application fills with its own wording",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "sideEffects": false,
8
+ "exports": {
9
+ ".": "./src/index.ts",
10
+ "./appearance": "./src/appearance.ts",
11
+ "./catalogues/*.json": "./src/catalogues/*.json",
12
+ "./package.json": "./package.json"
13
+ },
14
+ "files": [
15
+ "src",
16
+ "!src/**/*.test.ts"
17
+ ],
18
+ "devDependencies": {
19
+ "@types/node": "^26.6.6",
20
+ "@vue/test-utils": "^2.6.0",
21
+ "jsdom": "^27.0.0",
22
+ "typescript": "~5.8.3",
23
+ "vite": "^7.3.7",
24
+ "vitest": "^4.1.12",
25
+ "vue": "^3.5.44"
26
+ },
27
+ "peerDependencies": {
28
+ "vue": "^3.5.44"
29
+ },
30
+ "peerDependenciesMeta": {
31
+ "vue": {
32
+ "optional": true
33
+ }
34
+ },
35
+ "scripts": {
36
+ "lint": "eslint . --max-warnings 0",
37
+ "typecheck": "tsc -p tsconfig.json --noEmit",
38
+ "test": "vitest run"
39
+ }
6
40
  }
@@ -0,0 +1,324 @@
1
+ /**
2
+ * Applies the four things a user can choose about how the interface looks to the
3
+ * document root: the named theme, the colour mode, and the two density axes. All
4
+ * of them are attributes or a class on `document.documentElement`, and each
5
+ * choice is remembered in `localStorage` so the next page load can apply it
6
+ * before anything else answers.
7
+ *
8
+ * The theme stylesheets bind their roles under `[data-brix-theme='<name>']` for light
9
+ * and under `.dark [data-brix-theme='<name>']` / `[data-brix-theme='<name>'].dark` for
10
+ * dark, so the theme attribute and the `dark` class belong on the same element.
11
+ *
12
+ * Anything on screen that shows the current appearance — a picker, a preview — can
13
+ * follow these changes with `subscribeAppearance`, rather than watching the document.
14
+ */
15
+
16
+ export type ThemePreference = 'light' | 'dark' | 'system';
17
+ export type TableDensity = 'normal' | 'compact' | 'dense';
18
+ export type PageDensity = 'normal' | 'compact' | 'dense';
19
+
20
+ const PREFERENCES: readonly string[] = ['light', 'dark', 'system'] satisfies ThemePreference[];
21
+ const TABLE_DENSITIES: readonly string[] = ['normal', 'compact', 'dense'] satisfies TableDensity[];
22
+ const PAGE_DENSITIES: readonly string[] = ['normal', 'compact', 'dense'] satisfies PageDensity[];
23
+ const DARK_SCHEME_QUERY = '(prefers-color-scheme: dark)';
24
+
25
+ // Storage access. Browsers throw on both reads and writes (private mode, blocked
26
+ // site data), and neither may stop the document from being themed.
27
+
28
+ function readStored(storageKey: string): string | null {
29
+ try {
30
+ return localStorage.getItem(storageKey);
31
+ } catch {
32
+ return null;
33
+ }
34
+ }
35
+
36
+ function persist(storageKey: string, value: string): void {
37
+ try {
38
+ localStorage.setItem(storageKey, value);
39
+ } catch {
40
+ // Storage disabled: the choice is applied for this page load, just not remembered.
41
+ }
42
+ }
43
+
44
+ // Notification. Two things change the document behind the back of whatever is on screen:
45
+ // another part of the application calling an `apply*` function, and this module's own
46
+ // OS-scheme listener flipping the `dark` class while the preference is 'system'. A control
47
+ // that shows the current appearance has to hear about both, and reverse-engineering them
48
+ // from the DOM would be guessing at events this module is in a position to announce.
49
+
50
+ const listeners = new Set<() => void>();
51
+
52
+ /**
53
+ * Be told whenever the applied appearance changes — any `apply*` call, and the OS flipping
54
+ * its colour scheme while the preference is 'system'. The listener is called after the
55
+ * change has been applied to the document and persisted, so it can simply read the current
56
+ * state back. Returns the unsubscribe.
57
+ *
58
+ * Two limits worth knowing: a change made in ANOTHER browser tab is not reported (this
59
+ * module has no cross-tab propagation at all), and neither is an application writing
60
+ * `data-brix-theme` or the `dark` class onto the document itself instead of calling these
61
+ * functions.
62
+ */
63
+ export function subscribeAppearance(listener: () => void): () => void {
64
+ listeners.add(listener);
65
+
66
+ return () => {
67
+ listeners.delete(listener);
68
+ };
69
+ }
70
+
71
+ /**
72
+ * Synchronous, and deliberately forgiving: a listener that throws must not stop the others
73
+ * from being told, and must not turn an appearance change — which has already happened —
74
+ * into a failed call for whoever asked for it.
75
+ */
76
+ function notify(): void {
77
+ for (const listener of [...listeners]) {
78
+ try {
79
+ listener();
80
+ } catch {
81
+ // Not this module's error to handle, and not a reason to abandon the rest.
82
+ }
83
+ }
84
+ }
85
+
86
+ // Density
87
+
88
+ /** Narrow an untrusted value to a table density; anything unrecognised becomes 'normal'. */
89
+ export function asTableDensity(value: unknown): TableDensity {
90
+ return typeof value === 'string' && TABLE_DENSITIES.includes(value)
91
+ ? (value as TableDensity)
92
+ : 'normal';
93
+ }
94
+
95
+ /** Narrow an untrusted value to a page density; anything unrecognised becomes 'normal'. */
96
+ export function asPageDensity(value: unknown): PageDensity {
97
+ return typeof value === 'string' && PAGE_DENSITIES.includes(value)
98
+ ? (value as PageDensity)
99
+ : 'normal';
100
+ }
101
+
102
+ /**
103
+ * Every density rule is keyed on `compact` or `dense`, so 'normal' must leave no
104
+ * attribute behind rather than write `data-brix-table-density="normal"`.
105
+ */
106
+ function setTableDensity(density: TableDensity): void {
107
+ if (density === 'normal') {
108
+ delete document.documentElement.dataset.brixTableDensity;
109
+ return;
110
+ }
111
+ document.documentElement.dataset.brixTableDensity = density;
112
+ }
113
+
114
+ /**
115
+ * Same rule for the page axis, which lives in `data-brix-page-density`, separate from the
116
+ * table's.
117
+ */
118
+ function setPageDensity(density: PageDensity): void {
119
+ if (density === 'normal') {
120
+ delete document.documentElement.dataset.brixPageDensity;
121
+ return;
122
+ }
123
+ document.documentElement.dataset.brixPageDensity = density;
124
+ }
125
+
126
+ /** Apply the table density to the document root and remember it under `storageKey`. */
127
+ export function applyTableDensity(density: TableDensity, storageKey: string): void {
128
+ setTableDensity(density);
129
+ persist(storageKey, density);
130
+ notify();
131
+ }
132
+
133
+ /** Apply the page density to the document root and remember it under `storageKey`. */
134
+ export function applyPageDensity(density: PageDensity, storageKey: string): void {
135
+ setPageDensity(density);
136
+ persist(storageKey, density);
137
+ notify();
138
+ }
139
+
140
+ /** Apply the remembered table density. Missing, unknown or unreadable storage means 'normal'. */
141
+ export function initTableDensity(storageKey: string): void {
142
+ setTableDensity(asTableDensity(readStored(storageKey)));
143
+ }
144
+
145
+ /** Apply the remembered page density. Missing, unknown or unreadable storage means 'normal'. */
146
+ export function initPageDensity(storageKey: string): void {
147
+ setPageDensity(asPageDensity(readStored(storageKey)));
148
+ }
149
+
150
+ // Colour mode
151
+
152
+ /**
153
+ * The one OS-scheme subscription this module ever holds. Non-null exactly while
154
+ * the active preference is 'system'; kept so it can be removed again and so a
155
+ * repeated 'system' never registers a second listener.
156
+ */
157
+ let systemScheme: MediaQueryList | null = null;
158
+
159
+ function setDark(dark: boolean): void {
160
+ document.documentElement.classList.toggle('dark', dark);
161
+ }
162
+
163
+ function onSystemSchemeChange(event: MediaQueryListEvent): void {
164
+ setDark(event.matches);
165
+ // The applied colour just changed without anyone asking for it, which is exactly the
166
+ // case a control on screen cannot see coming.
167
+ notify();
168
+ }
169
+
170
+ function stopFollowingSystem(): void {
171
+ systemScheme?.removeEventListener('change', onSystemSchemeChange);
172
+ systemScheme = null;
173
+ }
174
+
175
+ function followSystem(): void {
176
+ if (typeof window.matchMedia !== 'function') {
177
+ // No way to ask the OS: stay on the safe default instead of throwing.
178
+ setDark(false);
179
+ return;
180
+ }
181
+ if (systemScheme === null) {
182
+ systemScheme = window.matchMedia(DARK_SCHEME_QUERY);
183
+ systemScheme.addEventListener('change', onSystemSchemeChange);
184
+ }
185
+ setDark(systemScheme.matches);
186
+ }
187
+
188
+ function setMode(preference: ThemePreference): void {
189
+ if (preference === 'system') {
190
+ followSystem();
191
+ return;
192
+ }
193
+ stopFollowingSystem();
194
+ setDark(preference === 'dark');
195
+ }
196
+
197
+ /** Narrow an untrusted value to a colour-mode preference; anything unrecognised becomes 'light'. */
198
+ export function asThemePreference(value: unknown): ThemePreference {
199
+ return typeof value === 'string' && PREFERENCES.includes(value)
200
+ ? (value as ThemePreference)
201
+ : 'light';
202
+ }
203
+
204
+ /**
205
+ * Apply the colour MODE (light, dark or system) by toggling the `dark` class on the
206
+ * document root, and persist it under `storageKey`. Despite the name this is not the
207
+ * named theme; that is `applyThemeName`. 'system' follows prefers-color-scheme and
208
+ * keeps following it until another preference is applied; what is stored is 'system'
209
+ * itself, not the colour it currently resolves to.
210
+ */
211
+ export function applyTheme(preference: ThemePreference, storageKey: string): void {
212
+ setMode(preference);
213
+ persist(storageKey, preference);
214
+ notify();
215
+ }
216
+
217
+ /**
218
+ * Apply the remembered colour MODE (light, dark or system), not the named theme; that
219
+ * is `initThemeName`. Missing, unknown or unreadable storage means 'light'.
220
+ */
221
+ export function initTheme(storageKey: string): void {
222
+ setMode(asThemePreference(readStored(storageKey)));
223
+ }
224
+
225
+ // Named theme
226
+
227
+ /**
228
+ * Narrow an untrusted theme name to one of `known`; anything else becomes `fallback`. The
229
+ * same shape as `asTableDensity` and `asThemePreference`, with the list passed in rather
230
+ * than built in, because this package deliberately holds no registry of theme names: a
231
+ * theme is a CSS file an application chooses to import, and only the application knows
232
+ * which ones it did.
233
+ *
234
+ * An EMPTY `known` therefore means "no list to check against", not "no name is valid": any
235
+ * non-blank name is kept, which is what every caller that passes no list gets. A blank name
236
+ * is never a theme either way — `[data-brix-theme='']` matches no stylesheet.
237
+ *
238
+ * Matching is exact and case-sensitive, because a CSS attribute selector is.
239
+ *
240
+ * There is deliberately no console warning on a rejected name, for the reason the two
241
+ * density axes have none: a package shipped as source has no reliable way to tell a
242
+ * development build from a production one without reaching for one bundler's
243
+ * `import.meta.env`, and a warning that fires in production is worse than the fallback it
244
+ * announces. The fallback IS the message — the page comes up on a theme that exists.
245
+ */
246
+ export function asThemeName(value: unknown, known: readonly string[], fallback: string): string {
247
+ if (typeof value !== 'string') return fallback;
248
+ const name = value.trim();
249
+ if (name === '') return fallback;
250
+ return known.length === 0 || known.includes(name) ? name : fallback;
251
+ }
252
+
253
+ /**
254
+ * Apply the named THEME by writing it as `data-brix-theme` on the document root, and
255
+ * persist it under `storageKey`. One value, replaced on each call. The name is
256
+ * trimmed, and a blank one is ignored. This is not the
257
+ * colour mode; that is `applyTheme`.
258
+ *
259
+ * Not validated against a list: the name comes from the application's own control (a
260
+ * picker built from the names it ships), not from storage, and this is the call that puts
261
+ * a name INTO storage. The reading side is where a stale one has to be caught.
262
+ */
263
+ export function applyThemeName(theme: string, storageKey: string): void {
264
+ const name = theme.trim();
265
+ // A blank name is not a theme: `initThemeName` reads it as absent, so storing it
266
+ // would only leave the page with an attribute that matches no stylesheet.
267
+ if (name === '') return;
268
+ document.documentElement.dataset.brixTheme = name;
269
+ persist(storageKey, name);
270
+ notify();
271
+ }
272
+
273
+ /**
274
+ * Apply the remembered named THEME, not the colour mode; that is `initTheme`. Absent,
275
+ * blank or unreadable storage applies `fallback`, and so does a stored name that is not
276
+ * in `known`.
277
+ *
278
+ * Pass `known` — the names the application actually imports a stylesheet for. Without it
279
+ * any stored string is written onto the document, and a name no stylesheet defines unbinds
280
+ * all 71 roles at once: every utility built on them resolves to nothing, which is a blank
281
+ * page with nothing on the console. Storage goes stale on its own, so this is not a
282
+ * hypothetical hostile value — renaming or retiring a theme leaves the old name behind in
283
+ * every browser that had chosen it.
284
+ *
285
+ * The corrected name is NOT written back: this function reads, and a visitor whose theme
286
+ * returns under its old name gets it back.
287
+ */
288
+ export function initThemeName(
289
+ storageKey: string,
290
+ fallback: string,
291
+ known: readonly string[] = [],
292
+ ): void {
293
+ document.documentElement.dataset.brixTheme = asThemeName(
294
+ readStored(storageKey),
295
+ known,
296
+ fallback,
297
+ );
298
+ }
299
+
300
+ // One call
301
+
302
+ /**
303
+ * Apply everything a user has chosen, from the keys `<prefix>.theme` (the theme's
304
+ * name), `<prefix>.mode` (light, dark or system), `<prefix>.tableDensity` and
305
+ * `<prefix>.pageDensity`. Call it before first paint. A theme's roles only exist
306
+ * under `[data-brix-theme='<name>']`, so a visitor with nothing stored would otherwise
307
+ * get a page with no tokens bound; `fallbackTheme` is bound for them, and defaults
308
+ * to the brand-free reference theme.
309
+ *
310
+ * `knownThemes` is the list of theme names the application imports a stylesheet for. Pass
311
+ * it: a stored name outside it then falls back to `fallbackTheme` instead of being written
312
+ * onto the document, where it would match no rule and unbind every role. Omitted, any
313
+ * stored name is applied as it stands — see `initThemeName`.
314
+ */
315
+ export function initAppearance(
316
+ prefix: string,
317
+ fallbackTheme = 'graphite',
318
+ knownThemes: readonly string[] = [],
319
+ ): void {
320
+ initThemeName(`${prefix}.theme`, fallbackTheme, knownThemes);
321
+ initTheme(`${prefix}.mode`);
322
+ initTableDensity(`${prefix}.tableDensity`);
323
+ initPageDensity(`${prefix}.pageDensity`);
324
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * What a build says about itself: a version, and the short commit it was cut from when git was
3
+ * there to ask.
4
+ *
5
+ * This module declares no bundler global. The upstream it was ported from read a constant that
6
+ * one bundler injects at build time; brix ships source, not a build (ADR 0002), so a consumer's
7
+ * bundler may be any of them, and the application hands its own build in. What is left is the
8
+ * shape `BuildStamp` is given and the shape a `fetchVersion` must return, plus `parseBuild`,
9
+ * which turns an untrusted value into that shape or into nothing.
10
+ *
11
+ * `parseBuild` also holds the one piece of knowledge the removed default fetcher carried: a
12
+ * host that lacks the version file answers with its index document, which is not a build and is
13
+ * refused here. With `response.json()` that body throws a SyntaxError before `parseBuild` is
14
+ * reached, so a caller's `fetchVersion` is what must catch it; the string case arises for a
15
+ * fetcher that reads `.text()`.
16
+ */
17
+ export interface Build {
18
+ version: string;
19
+ /** Short commit hash, or null where the build had no git to ask. */
20
+ commit: string | null;
21
+ }
22
+
23
+ /** The build a decoded value describes, or null when it is not one. Never throws. */
24
+ export function parseBuild(value: unknown): Build | null {
25
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
26
+ return null;
27
+ }
28
+ const { version, commit } = value as { version?: unknown; commit?: unknown };
29
+
30
+ return typeof version === 'string' && version !== ''
31
+ ? { version, commit: typeof commit === 'string' ? commit : null }
32
+ : null;
33
+ }