@open-artifact/design-system-core 0.2.1 → 0.9.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/package.json +1 -1
- package/src/check.d.ts +1 -1
- package/src/check.js +87 -12
- package/src/edit.d.ts +2 -0
- package/src/edit.js +30 -12
- package/src/generate.d.ts +1 -1
- package/src/generate.js +66 -16
- package/src/system.d.ts +9 -0
- package/src/system.js +78 -24
- package/src/tokens.d.ts +7 -1
- package/src/tokens.js +87 -27
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@open-artifact/design-system-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.9.0",
|
|
4
4
|
"description": "The Design System artifact model: tokens.json grammar and tokens.css compiler, the index, components, assets, manifest and checks.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"exports": {
|
package/src/check.d.ts
CHANGED
|
@@ -10,4 +10,4 @@ export interface SystemDiagnostic {
|
|
|
10
10
|
message: string;
|
|
11
11
|
}
|
|
12
12
|
/** Checks a design system's files. */
|
|
13
|
-
export declare function checkDesignSystem(files: ReadonlyMap<string, string
|
|
13
|
+
export declare function checkDesignSystem(files: ReadonlyMap<string, string>, blobExists?: (id: string) => boolean): SystemDiagnostic[];
|
package/src/check.js
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* their paths matter here.
|
|
5
5
|
*/
|
|
6
6
|
import { normalizeTokens } from "./tokens.js";
|
|
7
|
-
import { COMPONENT_NAME, MAX_SECTIONS, fileRole, hasMarker, listSections, normalizeSystemIndex, parseBundleHeader, parseCardMarker, pathProblem, } from "./system.js";
|
|
7
|
+
import { COMPONENT_NAME, MAX_SECTIONS, fileRole, hasMarker, isAssetGroupName, listSections, normalizeSystemIndex, parseBundleHeader, parseCardMarker, pathProblem, } from "./system.js";
|
|
8
8
|
/** Size caps of text files, bytes. */
|
|
9
9
|
const CAPS = {
|
|
10
10
|
readme: 200 * 1024,
|
|
@@ -19,7 +19,7 @@ const CAPS = {
|
|
|
19
19
|
/** Embeds a preview may not use. */
|
|
20
20
|
const PREVIEW_EMBEDS = /<(iframe|frame|object|embed|portal|noscript)\b/i;
|
|
21
21
|
/** Checks a design system's files. */
|
|
22
|
-
export function checkDesignSystem(files) {
|
|
22
|
+
export function checkDesignSystem(files, blobExists) {
|
|
23
23
|
const out = [];
|
|
24
24
|
const add = (file, level, message) => {
|
|
25
25
|
out.push({ file, level, message });
|
|
@@ -27,6 +27,7 @@ export function checkDesignSystem(files) {
|
|
|
27
27
|
// The index.
|
|
28
28
|
const indexText = files.get('design-system.json');
|
|
29
29
|
let namespace = '';
|
|
30
|
+
const restored = new Set();
|
|
30
31
|
if (indexText === undefined) {
|
|
31
32
|
add('design-system.json', 'error', 'project/design-system.json is missing: the page treats the system as empty.');
|
|
32
33
|
}
|
|
@@ -35,18 +36,85 @@ export function checkDesignSystem(files) {
|
|
|
35
36
|
const raw = JSON.parse(indexText);
|
|
36
37
|
if (!hasMarker(raw))
|
|
37
38
|
add('design-system.json', 'error', 'The index has no createdOnFiles or convertedFrom marker; the page opens read-only.');
|
|
39
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw))
|
|
40
|
+
throw new Error('Expected an index object.');
|
|
41
|
+
const fields = raw;
|
|
42
|
+
if (typeof fields.v !== 'number' || fields.v < 3 || fields.layout !== 'files') {
|
|
43
|
+
add('design-system.json', 'error', 'Expected version 3 or later with layout "files".');
|
|
44
|
+
}
|
|
38
45
|
const index = normalizeSystemIndex(raw);
|
|
39
46
|
namespace = index.namespace;
|
|
40
|
-
if (
|
|
41
|
-
add('design-system.json', 'error', `namespace "${index.namespace}" must be a JS identifier.`);
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
47
|
+
if (!COMPONENT_NAME.test(index.namespace))
|
|
48
|
+
add('design-system.json', 'error', `namespace "${index.namespace}" must be a JS identifier of at most 64 characters.`);
|
|
49
|
+
const object = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
50
|
+
const issue = (message) => add('design-system.json', 'error', message);
|
|
51
|
+
if (object(fields.content))
|
|
52
|
+
issue('Unpack the content envelope into project files before editing.');
|
|
53
|
+
if (fields.title !== undefined && typeof fields.title !== 'string')
|
|
54
|
+
issue('title must be text.');
|
|
55
|
+
if (fields.namespace !== undefined && (typeof fields.namespace !== 'string' || !fields.namespace))
|
|
56
|
+
issue('namespace must be a JavaScript identifier.');
|
|
57
|
+
if (fields.sections !== undefined && (!object(fields.sections) || Object.values(fields.sections).some((title) => typeof title !== 'string')))
|
|
58
|
+
issue('sections must map section names to titles.');
|
|
59
|
+
const docs = fields.docs;
|
|
60
|
+
if (docs !== undefined && (!object(docs) || (docs.readme !== undefined && typeof docs.readme !== 'string') ||
|
|
61
|
+
(docs.sections !== undefined && (!Array.isArray(docs.sections) || docs.sections.some((path) => typeof path !== 'string')))))
|
|
62
|
+
issue('docs needs an optional readme path and a list of section paths.');
|
|
63
|
+
if (fields.libraries !== undefined && !Array.isArray(fields.libraries))
|
|
64
|
+
issue('libraries must be a list.');
|
|
65
|
+
for (const [i, lib] of (Array.isArray(fields.libraries) ? fields.libraries : []).entries()) {
|
|
66
|
+
if (!object(lib) || typeof lib.name !== 'string' || typeof lib.version !== 'string')
|
|
67
|
+
issue(`libraries[${i}] needs a name and version.`);
|
|
68
|
+
else if (lib.file !== undefined) {
|
|
69
|
+
if (typeof lib.file !== 'string' || !lib.file.startsWith('components/lib/') || !files.has(lib.file))
|
|
70
|
+
issue(`libraries[${i}] must point to an existing file under components/lib/.`);
|
|
71
|
+
if (lib.global !== undefined && (typeof lib.global !== 'string' || !COMPONENT_NAME.test(lib.global)))
|
|
72
|
+
issue(`libraries[${i}].global must be a JavaScript identifier.`);
|
|
73
|
+
}
|
|
74
|
+
else if (lib.name !== 'react' && lib.name !== 'react-dom')
|
|
75
|
+
issue(`libraries[${i}] needs a local file for ${lib.name}.`);
|
|
76
|
+
}
|
|
77
|
+
const records = (value, location, prefix = '') => {
|
|
78
|
+
if (value === undefined)
|
|
79
|
+
return;
|
|
80
|
+
if (!object(value)) {
|
|
81
|
+
add('design-system.json', 'error', `${location} must be an object of upload records.`);
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
for (const [key, record] of Object.entries(value)) {
|
|
85
|
+
if (!object(record) || typeof record.name !== 'string' || !record.name || pathProblem(prefix + record.name) ||
|
|
86
|
+
!Number.isSafeInteger(record.size) || Number(record.size) < 0 || typeof record.type !== 'string' || !/^[\w!#$&^.+-]+\/[\w!#$&^.+-]+(?:;.*)?$/.test(record.type)) {
|
|
87
|
+
add('design-system.json', 'error', `${location}.${key} needs name, blob, size and type.`);
|
|
88
|
+
}
|
|
89
|
+
else if (!files.has(prefix + record.name) && (typeof record.blob !== 'string' || !/^[a-f0-9]{32}$/.test(record.blob))) {
|
|
90
|
+
issue(`${location}.${key} needs a 32-character hex upload id.`);
|
|
48
91
|
}
|
|
92
|
+
else if (!files.has(prefix + record.name) && blobExists && !blobExists(String(record.blob))) {
|
|
93
|
+
issue(`Missing upload for ${prefix}${record.name}: ${record.blob}.`);
|
|
94
|
+
}
|
|
95
|
+
else
|
|
96
|
+
restored.add(prefix + record.name);
|
|
49
97
|
}
|
|
98
|
+
};
|
|
99
|
+
records(fields.blobs, 'blobs');
|
|
100
|
+
if (fields.groups !== undefined && (!Array.isArray(fields.groups) || fields.groups.some((key) => typeof key !== 'string'))) {
|
|
101
|
+
add('design-system.json', 'error', 'groups must be a list of asset group keys.');
|
|
102
|
+
}
|
|
103
|
+
if (fields.assetGroups !== undefined && !object(fields.assetGroups))
|
|
104
|
+
add('design-system.json', 'error', 'assetGroups must be an object.');
|
|
105
|
+
for (const [key, group] of Object.entries(object(fields.assetGroups) ? fields.assetGroups : {})) {
|
|
106
|
+
if (!object(group)) {
|
|
107
|
+
add('design-system.json', 'error', `assetGroups.${key} must be an object.`);
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
const name = index.assetGroups[key].name;
|
|
111
|
+
if (!isAssetGroupName(group.name ?? name))
|
|
112
|
+
issue(`assetGroups.${key} needs a valid group folder name.`);
|
|
113
|
+
if (group.tile !== undefined && !['xs', 's', 'm', 'l', 'xl'].includes(String(group.tile)))
|
|
114
|
+
add('design-system.json', 'error', `Invalid tile size in ${name}.`);
|
|
115
|
+
if (group.order !== undefined && (!Array.isArray(group.order) || group.order.some((item) => typeof item !== 'string')))
|
|
116
|
+
add('design-system.json', 'error', `Expected a list of file names in ${name}.order.`);
|
|
117
|
+
records(group.files, `assetGroups.${key}.files`, `assets/${name}/`);
|
|
50
118
|
}
|
|
51
119
|
if (index.lastChange && (typeof index.lastChange.by !== 'string' || typeof index.lastChange.at !== 'string')) {
|
|
52
120
|
add('design-system.json', 'warning', 'lastChange needs "by" and "at".');
|
|
@@ -63,9 +131,16 @@ export function checkDesignSystem(files) {
|
|
|
63
131
|
}
|
|
64
132
|
else {
|
|
65
133
|
try {
|
|
66
|
-
const
|
|
134
|
+
const raw = JSON.parse(tokensText);
|
|
135
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw))
|
|
136
|
+
add('tokens.json', 'error', 'Expected an object of token families.');
|
|
137
|
+
const { tokens, notes } = normalizeTokens(raw);
|
|
67
138
|
for (const note of notes)
|
|
68
|
-
add('tokens.json', note.level, note.message);
|
|
139
|
+
add('tokens.json', note.level === 'warning' ? 'error' : note.level, note.message);
|
|
140
|
+
for (const font of tokens.fonts) {
|
|
141
|
+
if (!files.has(font.file) && !restored.has(font.file))
|
|
142
|
+
add('tokens.json', 'error', `Font file ${font.file} is missing.`);
|
|
143
|
+
}
|
|
69
144
|
}
|
|
70
145
|
catch (error) {
|
|
71
146
|
add('tokens.json', 'error', `tokens.json is not valid JSON: ${String(error)}`);
|
package/src/edit.d.ts
CHANGED
|
@@ -36,6 +36,8 @@ export declare function updateEntry(raw: RawTokens, family: ListFamily, name: st
|
|
|
36
36
|
* theme's), and a map whose themes all agree collapses back to one value.
|
|
37
37
|
*/
|
|
38
38
|
export declare function setThemedValue(raw: RawTokens, family: 'color' | 'shadow', name: string, value: string, theme: string | null): RawTokens;
|
|
39
|
+
/** Restores inheritance for one secondary theme, keeping all other overrides. */
|
|
40
|
+
export declare function clearThemeOverride(raw: RawTokens, family: string, name: string, theme: string): RawTokens;
|
|
39
41
|
/** Adds a token at the end of a family (creating the family if needed). */
|
|
40
42
|
export declare function addEntry(raw: RawTokens, family: ListFamily, entry: RawEntry): RawTokens;
|
|
41
43
|
/** Removes a token. */
|
package/src/edit.js
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
* extra fields) survive every edit. Each function returns a new object and
|
|
7
7
|
* never mutates its input, so the caller can keep the old one for undo.
|
|
8
8
|
*/
|
|
9
|
+
import { cleanName, storedTokenList } from "./tokens.js";
|
|
9
10
|
/** Parses `tokens.json`; an empty or missing file is an empty object. */
|
|
10
11
|
export function parseTokensFile(text) {
|
|
11
12
|
if (text === undefined || !text.trim())
|
|
@@ -28,27 +29,31 @@ const isObject = (value) => Boolean(value) && typeof value === 'object' && !Arra
|
|
|
28
29
|
/** The token list of a family (empty when absent or malformed). */
|
|
29
30
|
export function familyEntries(raw, family) {
|
|
30
31
|
const node = raw[family];
|
|
31
|
-
|
|
32
|
-
return [];
|
|
33
|
-
return node.tokens.filter((entry) => isObject(entry) && typeof entry.name === 'string');
|
|
32
|
+
return (storedTokenList(family, node) ?? []).filter((entry) => isObject(entry) && typeof entry.name === 'string');
|
|
34
33
|
}
|
|
35
34
|
/** Replaces a family's token list, keeping the family's other keys. */
|
|
36
35
|
function withEntries(raw, family, update) {
|
|
37
36
|
const node = isObject(raw[family]) ? raw[family] : {};
|
|
38
|
-
const entries =
|
|
39
|
-
|
|
37
|
+
const entries = storedTokenList(family, node) ?? [];
|
|
38
|
+
const next = { ...node, tokens: update(entries) };
|
|
39
|
+
if (family === 'color' && Array.isArray(node.groups))
|
|
40
|
+
delete next.groups;
|
|
41
|
+
return { ...raw, [family]: next };
|
|
40
42
|
}
|
|
41
43
|
/** The theme ids of the color family, first theme first. */
|
|
42
44
|
export function themeIds(raw) {
|
|
43
45
|
const color = raw.color;
|
|
44
46
|
if (!isObject(color) || !Array.isArray(color.themes))
|
|
45
47
|
return [];
|
|
46
|
-
return color.themes.
|
|
48
|
+
return color.themes.flatMap((theme) => {
|
|
49
|
+
const id = cleanName(isObject(theme) ? theme.id : theme)?.toLowerCase();
|
|
50
|
+
return id ? [id] : [];
|
|
51
|
+
});
|
|
47
52
|
}
|
|
48
53
|
/** Merges fields into one entry. A field set to `undefined` is removed. */
|
|
49
54
|
export function updateEntry(raw, family, name, fields) {
|
|
50
55
|
return withEntries(raw, family, (entries) => entries.map((entry) => {
|
|
51
|
-
if (!isObject(entry) || entry.name !== name)
|
|
56
|
+
if (!isObject(entry) || cleanName(entry.name) !== name)
|
|
52
57
|
return entry;
|
|
53
58
|
const next = { ...entry, ...fields };
|
|
54
59
|
for (const [key, value] of Object.entries(fields))
|
|
@@ -63,7 +68,7 @@ export function updateEntry(raw, family, name, fields) {
|
|
|
63
68
|
* theme's), and a map whose themes all agree collapses back to one value.
|
|
64
69
|
*/
|
|
65
70
|
export function setThemedValue(raw, family, name, value, theme) {
|
|
66
|
-
const entry = familyEntries(raw, family).find((candidate) => candidate.name === name);
|
|
71
|
+
const entry = familyEntries(raw, family).find((candidate) => cleanName(candidate.name) === name);
|
|
67
72
|
if (!entry)
|
|
68
73
|
return raw;
|
|
69
74
|
const themes = themeIds(raw);
|
|
@@ -76,6 +81,18 @@ export function setThemedValue(raw, family, name, value, theme) {
|
|
|
76
81
|
const collapsed = values.every((v) => v === values[0]) && Object.keys(map).every((key) => themes.includes(key));
|
|
77
82
|
return updateEntry(raw, family, name, { value: collapsed ? values[0] : map });
|
|
78
83
|
}
|
|
84
|
+
/** Restores inheritance for one secondary theme, keeping all other overrides. */
|
|
85
|
+
export function clearThemeOverride(raw, family, name, theme) {
|
|
86
|
+
const themes = themeIds(raw);
|
|
87
|
+
const value = familyEntries(raw, family).find((entry) => cleanName(entry.name) === name)?.value;
|
|
88
|
+
if (!isObject(value) || !themes.includes(theme) || theme === themes[0] || !Object.hasOwn(value, theme))
|
|
89
|
+
return raw;
|
|
90
|
+
const copy = { ...value };
|
|
91
|
+
// A later-only value was borrowed by the first theme on read.
|
|
92
|
+
copy[themes[0]] ??= themes.map((id) => copy[id]).find((v) => v !== undefined);
|
|
93
|
+
delete copy[theme];
|
|
94
|
+
return updateEntry(raw, family, name, { value: Object.keys(copy).length === 1 ? copy[themes[0]] : copy });
|
|
95
|
+
}
|
|
79
96
|
/** Adds a token at the end of a family (creating the family if needed). */
|
|
80
97
|
export function addEntry(raw, family, entry) {
|
|
81
98
|
let next = raw;
|
|
@@ -85,7 +102,7 @@ export function addEntry(raw, family, entry) {
|
|
|
85
102
|
}
|
|
86
103
|
/** Removes a token. */
|
|
87
104
|
export function removeEntry(raw, family, name) {
|
|
88
|
-
return withEntries(raw, family, (entries) => entries.filter((entry) => !isObject(entry) || entry.name !== name));
|
|
105
|
+
return withEntries(raw, family, (entries) => entries.filter((entry) => !isObject(entry) || cleanName(entry.name) !== name));
|
|
89
106
|
}
|
|
90
107
|
/** Renames a token; color and shadow aliases (`{old}`) follow it. */
|
|
91
108
|
export function renameEntry(raw, family, from, to) {
|
|
@@ -93,7 +110,7 @@ export function renameEntry(raw, family, from, to) {
|
|
|
93
110
|
if (family !== 'color' && family !== 'shadow')
|
|
94
111
|
return next;
|
|
95
112
|
const rewrite = (value) => {
|
|
96
|
-
if (value === `{${from}}`)
|
|
113
|
+
if (value === `{${from}}` || value === `{--${from}}`)
|
|
97
114
|
return `{${to}}`;
|
|
98
115
|
if (isObject(value))
|
|
99
116
|
return Object.fromEntries(Object.entries(value).map(([key, v]) => [key, rewrite(v)]));
|
|
@@ -109,7 +126,7 @@ export function renameEntry(raw, family, from, to) {
|
|
|
109
126
|
/** Moves a token to `index` within its family. */
|
|
110
127
|
export function moveEntry(raw, family, name, index) {
|
|
111
128
|
return withEntries(raw, family, (entries) => {
|
|
112
|
-
const from = entries.findIndex((entry) => isObject(entry) && entry.name === name);
|
|
129
|
+
const from = entries.findIndex((entry) => isObject(entry) && cleanName(entry.name) === name);
|
|
113
130
|
if (from < 0)
|
|
114
131
|
return entries;
|
|
115
132
|
const list = [...entries];
|
|
@@ -154,7 +171,8 @@ export function setFamilyNote(raw, family, note) {
|
|
|
154
171
|
}
|
|
155
172
|
/** A token name not yet used in `family`, built from `stem`. */
|
|
156
173
|
export function freeTokenName(raw, family, stem) {
|
|
157
|
-
const
|
|
174
|
+
const families = new Set([family, ...Object.keys(raw).filter((key) => key !== 'type')]);
|
|
175
|
+
const taken = new Set([...families].flatMap((key) => familyEntries(raw, key).map((entry) => cleanName(entry.name))));
|
|
158
176
|
for (let n = 1;; n++) {
|
|
159
177
|
const name = n === 1 ? stem : `${stem}-${n}`;
|
|
160
178
|
if (!taken.has(name))
|
package/src/generate.d.ts
CHANGED
|
@@ -26,7 +26,7 @@ export interface GenerateInput {
|
|
|
26
26
|
files: ReadonlyMap<string, string>;
|
|
27
27
|
}
|
|
28
28
|
/** The "How to use this system" block. */
|
|
29
|
-
export declare function usageBlock(input: GenerateInput): string;
|
|
29
|
+
export declare function usageBlock(input: GenerateInput, cards?: Record<string, string>): string;
|
|
30
30
|
/** Generates every `api/` card, keyed by project path. */
|
|
31
31
|
export declare function buildApiCards(input: GenerateInput): Record<string, string>;
|
|
32
32
|
/** What {@link generateSystemFiles} reads. */
|
package/src/generate.js
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
*/
|
|
12
12
|
import { componentProps } from "./props.js";
|
|
13
13
|
import { parseTokensFile } from "./edit.js";
|
|
14
|
-
import { buildManifest, listAssets, listComponents, listSections, normalizeSystemIndex, parseBundleHeader } from "./system.js";
|
|
14
|
+
import { buildManifest, listAssets, listComponents, listSections, parseCardMarker, normalizeSystemIndex, parseBundleHeader } from "./system.js";
|
|
15
15
|
import { compileTokensCss, normalizeTokens } from "./tokens.js";
|
|
16
16
|
/** Markers around the generated block of `README.md`. */
|
|
17
17
|
export const USAGE_START = '<!-- open-artifact:usage (generated, do not edit) -->';
|
|
@@ -19,8 +19,11 @@ export const USAGE_END = '<!-- /open-artifact:usage -->';
|
|
|
19
19
|
/** The README without its generated block. */
|
|
20
20
|
export function stripUsageBlock(readme) {
|
|
21
21
|
const start = readme.indexOf(USAGE_START);
|
|
22
|
-
if (start < 0)
|
|
23
|
-
|
|
22
|
+
if (start < 0) {
|
|
23
|
+
// Published systems delimit the generated tail with a rule and these exact headings.
|
|
24
|
+
const marker = /(?:^|\r?\n)---\r?\n\s*## Consuming this system \(generated — do not edit\)\s*(?:\r?\n|$)/.exec(readme);
|
|
25
|
+
return marker ? readme.slice(0, marker.index).trimEnd() + '\n' : readme;
|
|
26
|
+
}
|
|
24
27
|
const end = readme.indexOf(USAGE_END, start);
|
|
25
28
|
const tail = end < 0 ? '' : readme.slice(end + USAGE_END.length);
|
|
26
29
|
return `${readme.slice(0, start).trimEnd()}${tail.trim() ? `\n\n${tail.trim()}` : ''}\n`;
|
|
@@ -35,12 +38,12 @@ function bundleNamespace({ index, files }) {
|
|
|
35
38
|
const bundle = files.get('components/bundle.js');
|
|
36
39
|
if (bundle === undefined)
|
|
37
40
|
return null;
|
|
38
|
-
return parseBundleHeader(bundle)?.namespace ||
|
|
41
|
+
return index.namespace || parseBundleHeader(bundle)?.namespace || null;
|
|
39
42
|
}
|
|
40
43
|
/** The "How to use this system" block. */
|
|
41
|
-
export function usageBlock(input) {
|
|
44
|
+
export function usageBlock(input, cards = buildApiCards(input)) {
|
|
42
45
|
const { tokens } = input;
|
|
43
|
-
const lines = ['##
|
|
46
|
+
const lines = ['## Consuming this system (generated — do not edit)', ''];
|
|
44
47
|
lines.push('Load the compiled tokens; every token is a CSS custom property and every text style a class:', '');
|
|
45
48
|
lines.push('```html', '<link rel="stylesheet" href="tokens.css">', '```', '');
|
|
46
49
|
if (tokens.themes.length > 1) {
|
|
@@ -59,7 +62,13 @@ export function usageBlock(input) {
|
|
|
59
62
|
if (namespace && components.length) {
|
|
60
63
|
lines.push(`Components are ${react ? 'React components' : 'exports'} on \`window.${namespace}\` after loading \`components/bundle.js\`${input.files.has('components/bundle.css') ? ' and `components/bundle.css`' : ''}:`, '', '```js', `const { ${components.slice(0, 3).map((component) => component.name).join(', ')} } = window.${namespace};`, '```', '');
|
|
61
64
|
}
|
|
62
|
-
|
|
65
|
+
for (const font of tokens.fonts)
|
|
66
|
+
lines.push(`- ${font.family} (${font.weight}, ${font.style}): \`${font.file}\`.`);
|
|
67
|
+
lines.push('', '## Index (generated — do not edit)', '');
|
|
68
|
+
for (const path of Object.keys(cards)) {
|
|
69
|
+
const title = cards[path].split('\n', 1)[0].replace(/^#\s*/, '');
|
|
70
|
+
lines.push(`- \`${path}\` — ${title}`);
|
|
71
|
+
}
|
|
63
72
|
return lines.join('\n');
|
|
64
73
|
}
|
|
65
74
|
/** Escapes a table cell. */
|
|
@@ -85,14 +94,27 @@ function tokensCard({ tokens }) {
|
|
|
85
94
|
}
|
|
86
95
|
}
|
|
87
96
|
lines.push('');
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
97
|
+
}
|
|
98
|
+
const families = Object.entries(tokens.families);
|
|
99
|
+
if (families.length)
|
|
100
|
+
lines.push('## Font families', '', ...families.map(([key, stack]) => `- \`--font-${key}\`: ${stack}`), '');
|
|
101
|
+
if (tokens.fonts.length) {
|
|
102
|
+
lines.push('## Font files', '', '| Family | File | Weight | Style |', '|---|---|---|---|');
|
|
103
|
+
for (const font of tokens.fonts)
|
|
104
|
+
lines.push(`| ${cell(font.family)} | \`${cell(font.file)}\` | ${font.weight} | ${font.style} |`);
|
|
105
|
+
lines.push('');
|
|
106
|
+
}
|
|
107
|
+
if (tokens.shadows.length) {
|
|
108
|
+
lines.push('## Shadows', '', `| Token | ${tokens.themes.map((t) => cell(t.name)).join(' | ')} | Usage |`, `|---|${tokens.themes.map(() => '---|').join('')}---|`);
|
|
109
|
+
for (const shadow of tokens.shadows) {
|
|
110
|
+
const first = tokens.themes[0].id;
|
|
111
|
+
lines.push(`| \`--${shadow.name}\` | ${tokens.themes.map((t) => cell(shadow.declared[t.id] ?? shadow.declared[first])).join(' | ')} | ${cell(shadow.usage ?? '')} |`);
|
|
112
|
+
}
|
|
113
|
+
lines.push('');
|
|
91
114
|
}
|
|
92
115
|
const plain = [
|
|
93
116
|
['Spacing', tokens.spacing],
|
|
94
117
|
['Radius', tokens.radius],
|
|
95
|
-
['Shadow', tokens.shadows.map((s) => ({ name: s.name, value: s.declared[tokens.themes[0].id] ?? '', ...(s.usage ? { usage: s.usage } : {}) }))],
|
|
96
118
|
...tokens.extras.map((family) => [family.title, family.tokens]),
|
|
97
119
|
];
|
|
98
120
|
for (const [title, list] of plain) {
|
|
@@ -112,8 +134,13 @@ function componentCard(input, name) {
|
|
|
112
134
|
const readme = files.get(`components/${name}/README.md`)?.trim();
|
|
113
135
|
const declared = componentProps((path) => files.get(path), name);
|
|
114
136
|
const lines = [`# ${name}`, ''];
|
|
115
|
-
|
|
116
|
-
|
|
137
|
+
const preview = files.get(`components/${name}/preview.html`);
|
|
138
|
+
const page = preview && parseCardMarker(preview)?.page;
|
|
139
|
+
if (namespace && !page) {
|
|
140
|
+
lines.push(`\`const { ${name} } = window.${namespace};\``, '', '~~~jsx', `<${namespace}.${name} />`, '~~~', '', '~~~html', `<x-import component-from-global-scope="${namespace}.${name}"></x-import>`, '~~~', '');
|
|
141
|
+
}
|
|
142
|
+
if (!namespace && !page)
|
|
143
|
+
lines.push('This component has no runtime bundle. Use its documented guidelines to implement it.', '');
|
|
117
144
|
if (declared) {
|
|
118
145
|
const { props, dts } = declared;
|
|
119
146
|
if (props?.length) {
|
|
@@ -129,7 +156,8 @@ function componentCard(input, name) {
|
|
|
129
156
|
}
|
|
130
157
|
if (readme)
|
|
131
158
|
lines.push('## Notes', '', readme.replace(/^#\s+[^\n]*\n+/, ''), '');
|
|
132
|
-
|
|
159
|
+
if (preview !== undefined)
|
|
160
|
+
lines.push(`Preview: \`components/${name}/preview.html\`.`);
|
|
133
161
|
return `${lines.join('\n').trimEnd()}\n`;
|
|
134
162
|
}
|
|
135
163
|
/** The assets card. */
|
|
@@ -150,17 +178,39 @@ function assetsCard({ index, files }) {
|
|
|
150
178
|
export function buildApiCards(input) {
|
|
151
179
|
const cards = {};
|
|
152
180
|
const components = listComponents(input.files).filter((component) => component.name !== 'Cover');
|
|
153
|
-
const
|
|
181
|
+
const groups = listAssets(input.index, input.files.keys()).filter((group) => group.items.length);
|
|
182
|
+
const hasAssets = groups.length > 0;
|
|
154
183
|
cards['api/tokens.md'] = tokensCard(input);
|
|
155
184
|
for (const component of components)
|
|
156
185
|
cards[`api/components/${component.name}.md`] = componentCard(input, component.name);
|
|
157
186
|
if (hasAssets)
|
|
158
187
|
cards['api/assets.md'] = assetsCard(input);
|
|
188
|
+
const groupPaths = new Set();
|
|
189
|
+
for (const group of groups) {
|
|
190
|
+
const slug = group.name.replace(/[^A-Za-z0-9_.]+/g, '-').replace(/^[-.]+|[-.]+$/g, '') || 'group';
|
|
191
|
+
let path = `api/assets/${slug}.md`;
|
|
192
|
+
for (let n = 2; groupPaths.has(path.toLowerCase()); n++)
|
|
193
|
+
path = `api/assets/${slug}-${n}.md`;
|
|
194
|
+
groupPaths.add(path.toLowerCase());
|
|
195
|
+
const lines = [`# ${group.name}`, '', input.files.get(`assets/${group.name}/README.md`)?.trim() ?? '', '', '| File | Read |', '| --- | --- |'];
|
|
196
|
+
for (const item of group.items) {
|
|
197
|
+
lines.push(`| ${cell(item.name)} | \`${cell(item.path ?? '/_blob/' + item.blob)}\` |`);
|
|
198
|
+
}
|
|
199
|
+
cards[path] = lines.join('\n') + '\n';
|
|
200
|
+
}
|
|
201
|
+
const iconType = /\btype\s+IconName\s*=\s*((?:\s*\|?\s*["'][^"'\n]+["']\s*)+)/.exec(input.files.get('components/index.d.ts') ?? '');
|
|
202
|
+
if (iconType) {
|
|
203
|
+
const names = [...iconType[1].matchAll(/["']([^"']+)["']/g)].map((match) => match[1]).sort();
|
|
204
|
+
cards['api/icons.md'] = ['# Icons', '', ...names.map((name) => `- \`${name}\``), ''].join('\n');
|
|
205
|
+
}
|
|
159
206
|
const readme = [`# ${input.index.title || 'Design system'} — agent reference`, ''];
|
|
160
207
|
readme.push('Generated by the design system page on save. Read these instead of the whole project.', '');
|
|
161
208
|
readme.push('- `api/tokens.md`: every token and text style with its usage.');
|
|
162
209
|
if (hasAssets)
|
|
163
210
|
readme.push('- `api/assets.md`: logos, icons and images by group.');
|
|
211
|
+
for (const path of Object.keys(cards).filter((path) => path.startsWith('api/assets/') || path === 'api/icons.md')) {
|
|
212
|
+
readme.push(`- \`${path}\`: ${cards[path].split('\n', 1)[0].slice(2)}.`);
|
|
213
|
+
}
|
|
164
214
|
if (components.length) {
|
|
165
215
|
readme.push('- Components:');
|
|
166
216
|
for (const component of components)
|
|
@@ -212,6 +262,6 @@ export function generateSystemFiles({ files, fallbackTitle }) {
|
|
|
212
262
|
Object.assign(out, cards);
|
|
213
263
|
const { readme } = listSections(files);
|
|
214
264
|
if (readme)
|
|
215
|
-
out[readme.path] = withUsageBlock(files.get(readme.path) ?? '', usageBlock(input));
|
|
265
|
+
out[readme.path] = withUsageBlock(files.get(readme.path) ?? '', usageBlock(input, cards));
|
|
216
266
|
return out;
|
|
217
267
|
}
|
package/src/system.d.ts
CHANGED
|
@@ -80,8 +80,14 @@ export declare function toNamespace(title: string): string;
|
|
|
80
80
|
export declare function hasMarker(index: unknown): boolean;
|
|
81
81
|
/** Normalizes a parsed index, keeping unknown keys. */
|
|
82
82
|
export declare function normalizeSystemIndex(input: unknown): SystemIndex;
|
|
83
|
+
/** Display names that can form one asset folder and one index entry. */
|
|
84
|
+
export declare function isAssetGroupName(name: unknown): name is string;
|
|
83
85
|
/** The record key of an asset name: bytes outside `[A-Za-z0-9_./-]` written `~` + two hex digits. */
|
|
84
86
|
export declare function assetKey(name: string): string;
|
|
87
|
+
/** Display name for an encoded index key in a system without an explicit name. */
|
|
88
|
+
export declare function decodeAssetKey(key: string): string;
|
|
89
|
+
/** Also recognizes older Open Artifact indexes that used literal group keys. */
|
|
90
|
+
export declare function assetGroupKey(groups: Record<string, AssetGroup>, name: string): string;
|
|
85
91
|
/** What a project file is. */
|
|
86
92
|
export type FileRole = 'index' | 'tokens' | 'tokens-css' | 'manifest' | 'readme' | 'section' | 'bundle' | 'bundle-css' | 'types' | 'library' | 'component-preview' | 'component-readme' | 'component-types' | 'component-source' | 'font' | 'asset' | 'archived' | 'api-card' | 'other';
|
|
87
93
|
/** Component folder names must be ASCII JS identifiers. */
|
|
@@ -167,6 +173,8 @@ export declare function assetGroupOf(path: string): {
|
|
|
167
173
|
group: string;
|
|
168
174
|
name: string;
|
|
169
175
|
};
|
|
176
|
+
/** Uploads restored to their logical paths when an exported system has no physical copy. */
|
|
177
|
+
export declare function indexedUploads(index: SystemIndex): Map<string, AssetRecord>;
|
|
170
178
|
/** Lists asset groups and their items: index records first (in `order`), then files. */
|
|
171
179
|
export declare function listAssets(index: SystemIndex, paths: Iterable<string>): {
|
|
172
180
|
name: string;
|
|
@@ -176,6 +184,7 @@ export declare function listAssets(index: SystemIndex, paths: Iterable<string>):
|
|
|
176
184
|
/** The generated manifest (v3). */
|
|
177
185
|
export interface SystemManifest {
|
|
178
186
|
manifestVersion: 3;
|
|
187
|
+
files: string[];
|
|
179
188
|
name: string;
|
|
180
189
|
namespace: string;
|
|
181
190
|
libraries: Library[];
|
package/src/system.js
CHANGED
|
@@ -27,25 +27,25 @@ export function emptySystemIndex(title, now = new Date()) {
|
|
|
27
27
|
}
|
|
28
28
|
/** A JS identifier from a title (`"Acme UI"` → `AcmeUI`). */
|
|
29
29
|
export function toNamespace(title) {
|
|
30
|
-
const id = title.replace(/[^A-Za-z0-9_$]+/g, '');
|
|
31
|
-
return
|
|
30
|
+
const id = title.replace(/[^A-Za-z0-9_$]+/g, '').slice(0, 64);
|
|
31
|
+
return COMPONENT_NAME.test(id) ? id : `DS${id}`.slice(0, 64);
|
|
32
32
|
}
|
|
33
33
|
/** True when the parsed index carries the marker (`createdOnFiles` or `convertedFrom`). */
|
|
34
34
|
export function hasMarker(index) {
|
|
35
35
|
const raw = index;
|
|
36
|
-
return
|
|
36
|
+
return !!raw && [raw.createdOnFiles, raw.convertedFrom].some((marker) => marker !== null && typeof marker === 'object' && !Array.isArray(marker));
|
|
37
37
|
}
|
|
38
38
|
/** Normalizes a parsed index, keeping unknown keys. */
|
|
39
39
|
export function normalizeSystemIndex(input) {
|
|
40
40
|
const raw = (input && typeof input === 'object' && !Array.isArray(input) ? input : {});
|
|
41
|
-
const assetGroups =
|
|
41
|
+
const assetGroups = Object.create(null);
|
|
42
42
|
if (raw.assetGroups && typeof raw.assetGroups === 'object') {
|
|
43
43
|
for (const [key, group] of Object.entries(raw.assetGroups)) {
|
|
44
44
|
if (!group || typeof group !== 'object')
|
|
45
45
|
continue;
|
|
46
46
|
assetGroups[key] = {
|
|
47
47
|
...group,
|
|
48
|
-
name: typeof group.name === 'string' ? group.name : key,
|
|
48
|
+
name: typeof group.name === 'string' ? group.name : decodeAssetKey(key),
|
|
49
49
|
order: Array.isArray(group.order) ? group.order.filter((name) => typeof name === 'string') : [],
|
|
50
50
|
files: group.files && typeof group.files === 'object' ? group.files : {},
|
|
51
51
|
};
|
|
@@ -66,6 +66,11 @@ export function normalizeSystemIndex(input) {
|
|
|
66
66
|
docs: raw.docs && typeof raw.docs === 'object' ? raw.docs : { sections: [] },
|
|
67
67
|
};
|
|
68
68
|
}
|
|
69
|
+
/** Display names that can form one asset folder and one index entry. */
|
|
70
|
+
export function isAssetGroupName(name) {
|
|
71
|
+
return typeof name === 'string' && name.length > 0 && name.length <= 80 && name.trim() === name &&
|
|
72
|
+
!/[/\\\u0000-\u001f\u007f]/.test(name) && !name.startsWith('.') && !Object.hasOwn(Object.prototype, name) && name !== 'prototype';
|
|
73
|
+
}
|
|
69
74
|
/** The record key of an asset name: bytes outside `[A-Za-z0-9_./-]` written `~` + two hex digits. */
|
|
70
75
|
export function assetKey(name) {
|
|
71
76
|
let out = '';
|
|
@@ -75,8 +80,21 @@ export function assetKey(name) {
|
|
|
75
80
|
}
|
|
76
81
|
return out;
|
|
77
82
|
}
|
|
83
|
+
/** Display name for an encoded index key in a system without an explicit name. */
|
|
84
|
+
export function decodeAssetKey(key) {
|
|
85
|
+
try {
|
|
86
|
+
return decodeURIComponent(key.replace(/%/g, '%25').replace(/~([0-9a-f]{2})/gi, '%$1'));
|
|
87
|
+
}
|
|
88
|
+
catch {
|
|
89
|
+
return key;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
/** Also recognizes older Open Artifact indexes that used literal group keys. */
|
|
93
|
+
export function assetGroupKey(groups, name) {
|
|
94
|
+
return Object.keys(groups).find((key) => (groups[key]?.name ?? decodeAssetKey(key)) === name) ?? assetKey(name);
|
|
95
|
+
}
|
|
78
96
|
/** Component folder names must be ASCII JS identifiers. */
|
|
79
|
-
export const COMPONENT_NAME = /^[A-Za-z_$][A-Za-z0-9_$]
|
|
97
|
+
export const COMPONENT_NAME = /^(?!(?:__proto__|constructor|prototype)$)[A-Za-z_$][A-Za-z0-9_$]{0,63}$/;
|
|
80
98
|
/** Most brand-book sections besides the README. */
|
|
81
99
|
export const MAX_SECTIONS = 24;
|
|
82
100
|
/** Path rules: relative, `/`-separated, no `..`, no dot-files, no toolchain manifests. */
|
|
@@ -273,6 +291,24 @@ export function assetGroupOf(path) {
|
|
|
273
291
|
const slash = rest.indexOf('/');
|
|
274
292
|
return slash === -1 ? { group: 'Other', name: rest } : { group: rest.slice(0, slash), name: rest.slice(slash + 1) };
|
|
275
293
|
}
|
|
294
|
+
/** Uploads restored to their logical paths when an exported system has no physical copy. */
|
|
295
|
+
export function indexedUploads(index) {
|
|
296
|
+
const uploads = new Map();
|
|
297
|
+
const collect = (entries, prefix) => {
|
|
298
|
+
for (const value of Object.values(entries)) {
|
|
299
|
+
const record = value;
|
|
300
|
+
if (!record || typeof record.name !== 'string' || !/^[0-9a-f]{32}$/.test(record.blob))
|
|
301
|
+
continue;
|
|
302
|
+
const path = prefix + record.name;
|
|
303
|
+
if (!pathProblem(path) && (path.startsWith('assets/') || path.startsWith('fonts/')))
|
|
304
|
+
uploads.set(path, record);
|
|
305
|
+
}
|
|
306
|
+
};
|
|
307
|
+
collect(index.blobs, '');
|
|
308
|
+
for (const group of Object.values(index.assetGroups))
|
|
309
|
+
collect(group.files, `assets/${group.name}/`);
|
|
310
|
+
return uploads;
|
|
311
|
+
}
|
|
276
312
|
/** Lists asset groups and their items: index records first (in `order`), then files. */
|
|
277
313
|
export function listAssets(index, paths) {
|
|
278
314
|
const groups = new Map();
|
|
@@ -282,28 +318,40 @@ export function listAssets(index, paths) {
|
|
|
282
318
|
list.push(item);
|
|
283
319
|
groups.set(item.group, list);
|
|
284
320
|
};
|
|
285
|
-
|
|
286
|
-
groups.set(key, groups.get(key) ?? []);
|
|
287
|
-
for (const record of Object.values(group.files))
|
|
288
|
-
add({ group: key, name: record.name, blob: record.blob, type: record.type, size: record.size });
|
|
289
|
-
}
|
|
321
|
+
// A folder exported with both a file and its old upload record uses the file.
|
|
290
322
|
for (const path of paths) {
|
|
291
|
-
if (!path.startsWith('assets/')
|
|
323
|
+
if (!path.startsWith('assets/'))
|
|
292
324
|
continue;
|
|
293
|
-
|
|
325
|
+
const { group, name } = assetGroupOf(path);
|
|
326
|
+
if (name.toLowerCase() === 'readme.md')
|
|
327
|
+
groups.set(group, groups.get(group) ?? []);
|
|
328
|
+
else
|
|
329
|
+
add({ group, name, path });
|
|
330
|
+
}
|
|
331
|
+
const keys = [...new Set([...index.groups, ...Object.keys(index.assetGroups)])];
|
|
332
|
+
const orderedNames = new Set();
|
|
333
|
+
for (const key of keys) {
|
|
334
|
+
const group = index.assetGroups[key];
|
|
335
|
+
const name = group?.name ?? decodeAssetKey(key);
|
|
336
|
+
orderedNames.add(name);
|
|
337
|
+
groups.set(name, groups.get(name) ?? []);
|
|
338
|
+
for (const record of Object.values(group?.files ?? {})) {
|
|
339
|
+
if (typeof record?.name === 'string' && typeof record.blob === 'string') {
|
|
340
|
+
add({ group: name, name: record.name, blob: record.blob, type: record.type, size: record.size });
|
|
341
|
+
}
|
|
342
|
+
}
|
|
294
343
|
}
|
|
295
|
-
const order = [...
|
|
296
|
-
return order
|
|
297
|
-
|
|
298
|
-
.
|
|
299
|
-
const
|
|
300
|
-
const tileOrder = index.assetGroups[key]?.order ?? [];
|
|
344
|
+
const order = [...orderedNames, ...[...groups.keys()].filter((name) => !orderedNames.has(name)).sort()];
|
|
345
|
+
return order.map((name) => {
|
|
346
|
+
const items = groups.get(name);
|
|
347
|
+
const metadata = index.assetGroups[assetGroupKey(index.assetGroups, name)];
|
|
348
|
+
const tileOrder = metadata?.order ?? [];
|
|
301
349
|
items.sort((a, b) => {
|
|
302
350
|
const ia = tileOrder.indexOf(a.name);
|
|
303
351
|
const ib = tileOrder.indexOf(b.name);
|
|
304
352
|
return (ia === -1 ? Infinity : ia) - (ib === -1 ? Infinity : ib) || a.name.localeCompare(b.name);
|
|
305
353
|
});
|
|
306
|
-
return { name
|
|
354
|
+
return { name, tile: metadata?.tile ?? 'm', items };
|
|
307
355
|
});
|
|
308
356
|
}
|
|
309
357
|
/** Generates `manifest.json`, carrying the islands of the previous one. */
|
|
@@ -312,17 +360,23 @@ export function buildManifest(index, files, previous) {
|
|
|
312
360
|
manifestVersion: 3,
|
|
313
361
|
name: index.title,
|
|
314
362
|
namespace: index.namespace || parseBundleHeader(files.get('components/bundle.js') ?? '')?.namespace || toNamespace(index.title),
|
|
363
|
+
files: [...new Set([...files.keys()].filter((path) => {
|
|
364
|
+
const role = fileRole(path);
|
|
365
|
+
if (['bundle', 'bundle-css', 'types', 'component-readme', 'component-types', 'library', 'font', 'section'].includes(role))
|
|
366
|
+
return true;
|
|
367
|
+
return role === 'asset' && path.endsWith('/README.md');
|
|
368
|
+
}).concat(files.has('tokens.json') ? ['tokens.css'] : []))].sort(),
|
|
315
369
|
libraries: index.libraries,
|
|
316
|
-
components: listComponents(files).map(({ name, group, summary, page }) => ({
|
|
370
|
+
components: listComponents(files).filter(({ name }) => name !== 'Cover').map(({ name, group, summary, page }) => ({
|
|
317
371
|
name,
|
|
318
372
|
...(group ? { group } : {}),
|
|
319
373
|
...(summary ? { summary } : {}),
|
|
320
374
|
...(page ? { page } : {}),
|
|
321
375
|
})),
|
|
322
|
-
assetGroups: listAssets(index, files.keys()).map((group) => {
|
|
323
|
-
const key =
|
|
376
|
+
assetGroups: listAssets(index, files.keys()).filter((group) => group.items.length || files.has(`assets/${group.name}/README.md`)).map((group) => {
|
|
377
|
+
const key = assetGroupKey(index.assetGroups, group.name);
|
|
324
378
|
const record = index.assetGroups[key];
|
|
325
|
-
const uploads = group.items.filter((item) => item.blob).map((item) => ({ path: `assets/${
|
|
379
|
+
const uploads = group.items.filter((item) => item.blob).map((item) => ({ path: `assets/${group.name}/${item.name}`, id: item.blob }));
|
|
326
380
|
return {
|
|
327
381
|
name: group.name,
|
|
328
382
|
...(record?.tile ? { tile: record.tile } : {}),
|
package/src/tokens.d.ts
CHANGED
|
@@ -121,6 +121,8 @@ export declare function familyStack(value: unknown): string | null;
|
|
|
121
121
|
export declare function shadowValue(value: unknown): string | null;
|
|
122
122
|
/** A plain CSS value of an extra family. */
|
|
123
123
|
export declare function plainValue(value: unknown): string | null;
|
|
124
|
+
/** Older systems kept color tokens inside named groups. A flat list takes precedence. */
|
|
125
|
+
export declare function storedTokenList(family: string, node: unknown): unknown[] | null;
|
|
124
126
|
/** Why something was dropped or kept unshown. */
|
|
125
127
|
export interface TokenNote {
|
|
126
128
|
level: 'warning' | 'info';
|
|
@@ -216,5 +218,9 @@ export declare function tokensToCss(text: string, options?: CompileOptions): {
|
|
|
216
218
|
css: string;
|
|
217
219
|
notes: TokenNote[];
|
|
218
220
|
};
|
|
219
|
-
/**
|
|
221
|
+
/** The label shared by tokens in a palette (after any common namespace). */
|
|
220
222
|
export declare function colorStem(name: string): string;
|
|
223
|
+
export declare function colorGroups(colors: ThemedToken[]): {
|
|
224
|
+
prefix: string;
|
|
225
|
+
groups: Map<string, ThemedToken[]>;
|
|
226
|
+
};
|
package/src/tokens.js
CHANGED
|
@@ -37,19 +37,19 @@ export const KNOWN_FAMILIES = ['color', 'type', 'spacing', 'radius', 'shadow'];
|
|
|
37
37
|
const META_KEYS = new Set(['name', 'version', '$schema', 'description']);
|
|
38
38
|
const HEX = /^#(?:[0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
|
|
39
39
|
const COLOR_FN = /^(?:rgba?|hsla?|oklch|oklab|lab|lch|color)\(\s*[A-Za-z0-9.%,/\s+-]*\)$/i;
|
|
40
|
-
const ALIAS = /^\{([A-Za-z0-9][A-Za-z0-9_.-]{0,63})\}$/;
|
|
40
|
+
const ALIAS = /^\{(?:--)?([A-Za-z0-9][A-Za-z0-9_.-]{0,63})\}$/;
|
|
41
41
|
const LENGTH = /^-?(?:\d+\.?\d*|\.\d+)(?:px|rem|em|%)$/;
|
|
42
42
|
const PLAIN_VALUE = /^[A-Za-z0-9 #%(),./+_-]+$/;
|
|
43
43
|
/** Strips a leading `--` or `.` and validates; `null` when invalid. */
|
|
44
44
|
export function cleanName(raw) {
|
|
45
45
|
if (typeof raw !== 'string')
|
|
46
46
|
return null;
|
|
47
|
-
const name = raw.replace(/^--/, '').replace(/^\./, '');
|
|
47
|
+
const name = raw.trim().replace(/^--/, '').replace(/^\./, '');
|
|
48
48
|
return TOKEN_NAME.test(name) ? name : null;
|
|
49
49
|
}
|
|
50
50
|
/** Escapes a name for a CSS identifier (`.` → `\.`). */
|
|
51
51
|
export function cssIdent(name) {
|
|
52
|
-
return name.replace(/\./g, '\\.');
|
|
52
|
+
return name.replace(/\./g, '\\.').replace(/^\d/, (digit) => '\\3' + digit + ' ');
|
|
53
53
|
}
|
|
54
54
|
/** A literal color (not an alias): hex lowercased, or a plain color function. */
|
|
55
55
|
export function literalColor(value) {
|
|
@@ -145,6 +145,26 @@ export function plainValue(value) {
|
|
|
145
145
|
return null;
|
|
146
146
|
return text;
|
|
147
147
|
}
|
|
148
|
+
/** Older systems kept color tokens inside named groups. A flat list takes precedence. */
|
|
149
|
+
export function storedTokenList(family, node) {
|
|
150
|
+
if (!node || typeof node !== 'object')
|
|
151
|
+
return null;
|
|
152
|
+
const { tokens, groups } = node;
|
|
153
|
+
if (Array.isArray(tokens))
|
|
154
|
+
return tokens;
|
|
155
|
+
if (family === 'color' && Array.isArray(groups)) {
|
|
156
|
+
return groups.flatMap((group) => Array.isArray(group?.tokens) ? group.tokens : []);
|
|
157
|
+
}
|
|
158
|
+
return null;
|
|
159
|
+
}
|
|
160
|
+
function motionValue(value) {
|
|
161
|
+
if (typeof value === 'number' && value >= 0 && value < 1e6)
|
|
162
|
+
return `${Math.round(value)}ms`;
|
|
163
|
+
const text = plainValue(value);
|
|
164
|
+
if (text && /^\.\d+(ms|s)$/i.test(text))
|
|
165
|
+
return '0' + text.toLowerCase();
|
|
166
|
+
return text;
|
|
167
|
+
}
|
|
148
168
|
const clamp = (text, max) => typeof text === 'string' && text ? text.slice(0, max) : undefined;
|
|
149
169
|
/** Title of an extra family from its key. */
|
|
150
170
|
export function familyTitle(key) {
|
|
@@ -177,7 +197,7 @@ export function normalizeTokens(input) {
|
|
|
177
197
|
const family = raw[key];
|
|
178
198
|
if (family === undefined)
|
|
179
199
|
return null;
|
|
180
|
-
const tokens = family
|
|
200
|
+
const tokens = storedTokenList(key, family);
|
|
181
201
|
if (!Array.isArray(tokens)) {
|
|
182
202
|
note(`${key}: not a {"tokens": [...]} list, so it shows empty. Rewrite it as a list of {name, value, usage}.`);
|
|
183
203
|
return null;
|
|
@@ -188,8 +208,8 @@ export function normalizeTokens(input) {
|
|
|
188
208
|
const color = raw.color;
|
|
189
209
|
const themeList = Array.isArray(color?.themes) ? color.themes : [];
|
|
190
210
|
for (const theme of themeList) {
|
|
191
|
-
const id = cleanName(theme?.id)?.toLowerCase();
|
|
192
|
-
if (!id || out.themes.some((t) => t.id === id)) {
|
|
211
|
+
const id = cleanName(typeof theme === 'string' ? theme : theme?.id)?.toLowerCase();
|
|
212
|
+
if (!id || id === 'prototype' || Object.hasOwn(Object.prototype, id) || out.themes.some((t) => t.id === id)) {
|
|
193
213
|
note(`color.themes: theme ${JSON.stringify(theme?.id)} dropped (bad or duplicate id).`);
|
|
194
214
|
continue;
|
|
195
215
|
}
|
|
@@ -197,10 +217,10 @@ export function normalizeTokens(input) {
|
|
|
197
217
|
note(`color.themes: more than ${TOKEN_LIMITS.themes} themes; "${id}" dropped.`);
|
|
198
218
|
continue;
|
|
199
219
|
}
|
|
200
|
-
out.themes.push({ id, name: typeof theme
|
|
220
|
+
out.themes.push({ id, name: typeof theme?.name === 'string' ? theme.name : id });
|
|
201
221
|
}
|
|
202
222
|
if (!out.themes.length)
|
|
203
|
-
out.themes.push({ id: '
|
|
223
|
+
out.themes.push({ id: 'light', name: 'Light' });
|
|
204
224
|
const themeIds = out.themes.map((theme) => theme.id);
|
|
205
225
|
const firstTheme = themeIds[0];
|
|
206
226
|
out.colorNote = clamp(color?.note, TOKEN_LIMITS.note);
|
|
@@ -225,7 +245,7 @@ export function normalizeTokens(input) {
|
|
|
225
245
|
return null;
|
|
226
246
|
// A value only in a later theme is borrowed for the first.
|
|
227
247
|
if (!declared[firstTheme])
|
|
228
|
-
declared[firstTheme] = declared[
|
|
248
|
+
declared[firstTheme] = declared[themeIds.find((id) => declared[id] !== undefined)];
|
|
229
249
|
return declared;
|
|
230
250
|
};
|
|
231
251
|
// Colors.
|
|
@@ -329,17 +349,21 @@ export function normalizeTokens(input) {
|
|
|
329
349
|
const declared = readThemed('shadow', name, e.value, shadowValue);
|
|
330
350
|
if (!declared)
|
|
331
351
|
continue;
|
|
352
|
+
if (out.shadows.length >= TOKEN_LIMITS.familyTokens) {
|
|
353
|
+
note(`shadow: at most ${TOKEN_LIMITS.familyTokens} tokens are read.`);
|
|
354
|
+
break;
|
|
355
|
+
}
|
|
332
356
|
taken.add(name);
|
|
333
357
|
out.shadows.push({ name, usage: clamp(e.usage, TOKEN_LIMITS.usage), declared, resolved: { ...declared } });
|
|
334
358
|
}
|
|
335
|
-
out.spacing = readPlain('spacing', length, TOKEN_LIMITS.familyTokens
|
|
336
|
-
out.radius = readPlain('radius', length, TOKEN_LIMITS.familyTokens
|
|
359
|
+
out.spacing = readPlain('spacing', length, TOKEN_LIMITS.familyTokens);
|
|
360
|
+
out.radius = readPlain('radius', (value) => value === 'full' ? '9999px' : length(value), TOKEN_LIMITS.familyTokens);
|
|
337
361
|
// Extra families.
|
|
338
362
|
for (const key of Object.keys(raw)) {
|
|
339
363
|
if (META_KEYS.has(key) || KNOWN_FAMILIES.includes(key))
|
|
340
364
|
continue;
|
|
341
365
|
const family = raw[key];
|
|
342
|
-
if (!family || typeof family !== 'object' || !Array.isArray(family.tokens)) {
|
|
366
|
+
if (!/^(?!(?:prototype|constructor)$)[A-Za-z][A-Za-z0-9_-]{0,31}$/.test(key) || !family || typeof family !== 'object' || !Array.isArray(family.tokens)) {
|
|
343
367
|
note(`"${key}" is not a token family; kept, not shown.`, 'info');
|
|
344
368
|
continue;
|
|
345
369
|
}
|
|
@@ -351,7 +375,7 @@ export function normalizeTokens(input) {
|
|
|
351
375
|
key,
|
|
352
376
|
title: familyTitle(key),
|
|
353
377
|
note: clamp(family.note, TOKEN_LIMITS.note),
|
|
354
|
-
tokens: readPlain(key, plainValue, TOKEN_LIMITS.familyTokens),
|
|
378
|
+
tokens: readPlain(key, key === 'motion' ? motionValue : plainValue, TOKEN_LIMITS.familyTokens),
|
|
355
379
|
});
|
|
356
380
|
}
|
|
357
381
|
// Type.
|
|
@@ -364,12 +388,16 @@ export function normalizeTokens(input) {
|
|
|
364
388
|
note(`type.families.${rawKey}: invalid family stack; dropped.`);
|
|
365
389
|
continue;
|
|
366
390
|
}
|
|
391
|
+
if (Object.keys(out.families).length >= 12) {
|
|
392
|
+
note('type.families: at most 12 font families are read.');
|
|
393
|
+
break;
|
|
394
|
+
}
|
|
367
395
|
out.families[key] = value;
|
|
368
396
|
}
|
|
369
397
|
for (const font of Array.isArray(type.fonts) ? type.fonts.slice(0, TOKEN_LIMITS.fonts) : []) {
|
|
370
398
|
const family = typeof font?.family === 'string' ? font.family.trim() : '';
|
|
371
399
|
const file = typeof font?.file === 'string' ? font.file.trim() : '';
|
|
372
|
-
if (!family || /["';{}<>\\()]/.test(family) || !file ||
|
|
400
|
+
if (!family || /["';{}<>\\()]/.test(family) || !file || /(?:^|\/)\.\.(?:\/|$)|^\/|[:\x00-\x1f"'()\\]/.test(file)) {
|
|
373
401
|
note(`type.fonts: ${JSON.stringify(font)} dropped (family must be a bare name, file a relative path).`);
|
|
374
402
|
continue;
|
|
375
403
|
}
|
|
@@ -452,12 +480,14 @@ function cssThemed(text) {
|
|
|
452
480
|
/** Compiles normalized tokens to the `tokens.css` every consumer loads. */
|
|
453
481
|
export function compileTokensCss(tokens, options = {}) {
|
|
454
482
|
const lines = [];
|
|
483
|
+
const comment = (value) => value.replace(/\*\//g, '* /').replace(/<\//g, '< /').replace(/[\r\n\f]+/g, ' ').trim();
|
|
484
|
+
const usage = (value) => value ? ` /* ${comment(value)} */` : '';
|
|
455
485
|
const first = tokens.themes[0].id;
|
|
456
|
-
lines.push(`/* ${(options.title ?? tokens.name ?? 'Design system')
|
|
486
|
+
lines.push(`/* ${comment(options.title ?? tokens.name ?? 'Design system')} — generated from tokens.json */`);
|
|
457
487
|
// Colors and shadows of the first theme.
|
|
458
488
|
lines.push(`:root, [data-theme="${first}"] {`);
|
|
459
489
|
for (const token of [...tokens.colors, ...tokens.shadows]) {
|
|
460
|
-
lines.push(` --${cssIdent(token.name)}: ${cssThemed(token.declared[first])}
|
|
490
|
+
lines.push(` --${cssIdent(token.name)}: ${cssThemed(token.declared[first])};${usage(token.usage)}`);
|
|
461
491
|
}
|
|
462
492
|
lines.push('}');
|
|
463
493
|
// Further themes: overrides, plus aliases re-declared so they follow the theme.
|
|
@@ -468,7 +498,7 @@ export function compileTokensCss(tokens, options = {}) {
|
|
|
468
498
|
const inherited = token.declared[first];
|
|
469
499
|
if (own !== undefined && own !== inherited)
|
|
470
500
|
body.push(` --${cssIdent(token.name)}: ${cssThemed(own)};`);
|
|
471
|
-
else if (own
|
|
501
|
+
else if (aliasTarget(own ?? inherited))
|
|
472
502
|
body.push(` --${cssIdent(token.name)}: ${cssThemed(inherited)};`);
|
|
473
503
|
}
|
|
474
504
|
if (body.length)
|
|
@@ -477,10 +507,19 @@ export function compileTokensCss(tokens, options = {}) {
|
|
|
477
507
|
// Theme-independent values.
|
|
478
508
|
const root = [];
|
|
479
509
|
for (const token of [...tokens.spacing, ...tokens.radius, ...tokens.extras.flatMap((family) => family.tokens)]) {
|
|
480
|
-
root.push(` --${cssIdent(token.name)}: ${token.value}
|
|
510
|
+
root.push(` --${cssIdent(token.name)}: ${token.value};${usage(token.usage)}`);
|
|
481
511
|
}
|
|
482
512
|
for (const [key, stack] of Object.entries(tokens.families))
|
|
483
513
|
root.push(` --font-${cssIdent(key)}: ${stack};`);
|
|
514
|
+
const declared = new Set([...tokens.colors, ...tokens.shadows, ...tokens.spacing, ...tokens.radius, ...tokens.extras.flatMap((family) => family.tokens)].map((token) => token.name));
|
|
515
|
+
for (const group of tokens.groups) {
|
|
516
|
+
for (const style of group.styles) {
|
|
517
|
+
if (declared.has('text-' + style.name))
|
|
518
|
+
continue;
|
|
519
|
+
const italic = style.fontStyle === 'italic' ? 'italic ' : '';
|
|
520
|
+
root.push(` --text-${cssIdent(style.name)}: ${italic}${style.fontWeight ?? '400'} ${style.fontSize}/${style.lineHeight ?? '1.4'} ${style.family ?? 'inherit'};${usage(style.usage)}`);
|
|
521
|
+
}
|
|
522
|
+
}
|
|
484
523
|
if (root.length)
|
|
485
524
|
lines.push(':root {', ...root, '}');
|
|
486
525
|
// One class per type style.
|
|
@@ -490,19 +529,16 @@ export function compileTokensCss(tokens, options = {}) {
|
|
|
490
529
|
if (style.family)
|
|
491
530
|
decls.push(`font-family: ${style.family}`);
|
|
492
531
|
decls.push(`font-size: ${style.fontSize}`);
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
decls.push(`font-weight: ${style.fontWeight}`);
|
|
497
|
-
if (style.letterSpacing)
|
|
498
|
-
decls.push(`letter-spacing: ${style.letterSpacing}`);
|
|
532
|
+
decls.push(`line-height: ${style.lineHeight ?? '1.4'}`);
|
|
533
|
+
decls.push(`font-weight: ${style.fontWeight ?? '400'}`);
|
|
534
|
+
decls.push(`letter-spacing: ${style.letterSpacing ?? '0'}`);
|
|
499
535
|
if (style.fontStyle)
|
|
500
536
|
decls.push(`font-style: ${style.fontStyle}`);
|
|
501
537
|
if (style.textTransform)
|
|
502
538
|
decls.push(`text-transform: ${style.textTransform}`);
|
|
503
539
|
if (style.opticalSize !== undefined)
|
|
504
540
|
decls.push(`font-variation-settings: 'opsz' ${style.opticalSize}`);
|
|
505
|
-
lines.push(`.${cssIdent(style.name)} {
|
|
541
|
+
lines.push(`.${cssIdent(style.name)} {`, ...decls.map((declaration) => ` ${declaration};`), '}');
|
|
506
542
|
}
|
|
507
543
|
}
|
|
508
544
|
// Font faces.
|
|
@@ -528,7 +564,31 @@ export function tokensToCss(text, options) {
|
|
|
528
564
|
const { tokens, notes } = normalizeTokens(parsed);
|
|
529
565
|
return { css: compileTokensCss(tokens, options), notes };
|
|
530
566
|
}
|
|
531
|
-
/**
|
|
567
|
+
/** The label shared by tokens in a palette (after any common namespace). */
|
|
532
568
|
export function colorStem(name) {
|
|
533
|
-
return name
|
|
569
|
+
return /^(.*?)-\d{1,4}$/.exec(name)?.[1] ?? name.split('-')[0];
|
|
570
|
+
}
|
|
571
|
+
export function colorGroups(colors) {
|
|
572
|
+
const names = colors.map((color) => color.name);
|
|
573
|
+
let prefix = '';
|
|
574
|
+
const parts = (names[0] ?? '').split('-');
|
|
575
|
+
for (let n = 1; names.length > 1 && n < parts.length; n++) {
|
|
576
|
+
const candidate = parts.slice(0, n).join('-') + '-';
|
|
577
|
+
if (!names.every((name) => name.startsWith(candidate) && name.length > candidate.length))
|
|
578
|
+
break;
|
|
579
|
+
if (names.some((name) => name.slice(candidate.length).includes('-')))
|
|
580
|
+
prefix = candidate;
|
|
581
|
+
}
|
|
582
|
+
const stems = new Set(names.map((name) => name.slice(prefix.length)).filter((name) => name.includes('-')).map(colorStem));
|
|
583
|
+
const groups = new Map([['', []]]);
|
|
584
|
+
for (const color of colors) {
|
|
585
|
+
const stem = colorStem(color.name.slice(prefix.length));
|
|
586
|
+
const key = stems.has(stem) ? stem : '';
|
|
587
|
+
if (!groups.has(key))
|
|
588
|
+
groups.set(key, []);
|
|
589
|
+
groups.get(key).push(color);
|
|
590
|
+
}
|
|
591
|
+
if (!groups.get('').length)
|
|
592
|
+
groups.delete('');
|
|
593
|
+
return { prefix, groups };
|
|
534
594
|
}
|