@bridgebrew/design-system 0.0.0-stage → 0.1.9
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/README.md +21 -2
- package/browser.tsx +227 -0
- package/design-system.css +110 -0
- package/e2e.test.ts +253 -0
- package/highlight.ts +29 -0
- package/model.test.ts +69 -0
- package/package.json +72 -3
- package/stories/action.tsx +101 -0
- package/stories/data-display.tsx +371 -0
- package/stories/feedback.tsx +109 -0
- package/stories/foundations.tsx +157 -0
- package/stories/input.tsx +851 -0
- package/stories/interaction.tsx +76 -0
- package/stories/layout.tsx +510 -0
- package/stories/navigation.tsx +220 -0
- package/stories/overlay.tsx +293 -0
- package/stories/parts.tsx +201 -0
- package/stories.ts +149 -0
- package/tsconfig.json +20 -0
package/README.md
CHANGED
|
@@ -1,3 +1,22 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Design system
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A browser-only plugin (no server, no storage). **Design system**, at the sidebar's root, is a home: what the kit is,
|
|
4
|
+
then its sections, each a screen under it: Foundations, then the kit's layers (Core, Layout, Composite, Template), then
|
|
5
|
+
Shell. A section's screen is a MultiPane: on the left its stories, with a search (title, id or layer, any case or
|
|
6
|
+
accent; Escape clears, ↓ enters the list); on the right, the story: its title and one line, then sections (Variants,
|
|
7
|
+
Sizes, States, Examples), each framing live kit components. On a phone, the list alone, a tap pushes the story, Back
|
|
8
|
+
returns to the list, then to the home. Foundations show the theme's tokens read live (colours, type scale, heights,
|
|
9
|
+
radii, shadows) and every `ICON_NAMES` entry, searchable. The interactive examples have real state: Pickers pick (1–9),
|
|
10
|
+
a Combobox and a Picker search a fake server (400 ms), dialogs open and validate, toasts fire, lists reorder by drag.
|
|
11
|
+
|
|
12
|
+
The story is its section's item: `/<workspace>/<node>/design-system/<section>/<id>`
|
|
13
|
+
(`/admin/root/design-system/composite/picker`), so a reload or a link opens it; no item, or an unknown one, shows the
|
|
14
|
+
section's first story. A component's id is its folder in the kit
|
|
15
|
+
(`../ui/src/components/<layer>/<id>/`: `core`, `composite`, `layout` or `shell`); `pnpm test:design-system` fails when a kit component has no story, or sits in another
|
|
16
|
+
category than its `*.meta.yaml` says. The stories follow the page's theme: switch it with the shell's theme control.
|
|
17
|
+
|
|
18
|
+
Add a story: an entry in `stories.ts` (id, title, category, one-line description), and its page in
|
|
19
|
+
`stories/<category>.tsx`, built from `Group` and `Sample` (`stories/parts.tsx`) and kit components only.
|
|
20
|
+
|
|
21
|
+
Released with the kit, at its version: its peer `@bridge/ui` is that version. `pnpm e2e` (at the repository's root)
|
|
22
|
+
installs it in a real Bridge serving this repository's kit and checks every story renders.
|
package/browser.tsx
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
// The design system's screens, in the `screen` slot: a storyboard of the @bridge/ui kit. Design system itself is a home
|
|
2
|
+
// (what the kit is, its sections); each child screen (Foundations, Core, Layout, Composite, Template, Shell) is a
|
|
3
|
+
// MultiPane, as Contacts: its layer's stories (a search on top, ↑ ↓ to move) and the story shown, a page of sections each
|
|
4
|
+
// framing live kit components; on a phone, the list alone, then the story alone. The story is its section's item
|
|
5
|
+
// (`/<workspace>/<node>/design-system/<section>/<id>`): a reload or a link opens it; no item, or an unknown one, shows
|
|
6
|
+
// the section's first. Browser only: no server, no storage. Everything
|
|
7
|
+
// shown is the kit's, in the page's theme (the shell's theme control switches it, popups included).
|
|
8
|
+
import * as React from 'react';
|
|
9
|
+
import {
|
|
10
|
+
AddressBookTemplate, EmptyState, Icon, Input, List, ListItem, MailTemplate, MainContent, MultiPane, Pane, PaneBody,
|
|
11
|
+
PaneHeader, ScrollArea, Section, useFollow, type FollowEvent,
|
|
12
|
+
} from '@bridge/ui';
|
|
13
|
+
import './design-system.css';
|
|
14
|
+
import { layers, search, stories, storiesOf, storyOf, type StoryId } from './stories.ts';
|
|
15
|
+
import { foundations } from './stories/foundations.tsx';
|
|
16
|
+
import { action } from './stories/action.tsx';
|
|
17
|
+
import { input } from './stories/input.tsx';
|
|
18
|
+
import { dataDisplay } from './stories/data-display.tsx';
|
|
19
|
+
import { navigation } from './stories/navigation.tsx';
|
|
20
|
+
import { overlay } from './stories/overlay.tsx';
|
|
21
|
+
import { feedback } from './stories/feedback.tsx';
|
|
22
|
+
import { layout } from './stories/layout.tsx';
|
|
23
|
+
import { interaction } from './stories/interaction.tsx';
|
|
24
|
+
|
|
25
|
+
interface ScreenProps { screen: string; node: string; readOnly: boolean; item?: string }
|
|
26
|
+
interface Ctx {
|
|
27
|
+
slots: { register(options: { name: 'screen' | 'mobileScreen' }, render: (props: ScreenProps) => React.ReactNode): void };
|
|
28
|
+
screen: { open(item?: string): void; title?(item: string, title: string): void };
|
|
29
|
+
sidebar: { items(screen: string, items: readonly { id: string; title: string; icon?: string }[]): void };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export const name = 'design-system';
|
|
33
|
+
export const inject = ['slots', 'screen', 'sidebar'];
|
|
34
|
+
|
|
35
|
+
/** Each story's page; the typecheck fails when a story of the registry has none. */
|
|
36
|
+
const pages: Record<StoryId, React.ComponentType> = {
|
|
37
|
+
...foundations, ...action, ...input, ...dataDisplay, ...navigation, ...overlay, ...feedback, ...layout, ...interaction,
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
function Storyboard({ screen, item, open, phone = false, title }: {
|
|
41
|
+
screen: string; item: string | undefined; open: (id: string) => void;
|
|
42
|
+
/** Bridge's phone shell: no item, the list alone; a story, its page alone, the shell's Back returning to the list. */
|
|
43
|
+
phone?: boolean;
|
|
44
|
+
/** Names the story in the shell's header and breadcrumb. */
|
|
45
|
+
title?: (item: string, title: string) => void;
|
|
46
|
+
}) {
|
|
47
|
+
const story = storyOf(item, screen);
|
|
48
|
+
const Page = pages[story.id as StoryId];
|
|
49
|
+
const [query, setQuery] = React.useState('');
|
|
50
|
+
const shown = search(query, screen);
|
|
51
|
+
const list = React.useRef<HTMLDivElement>(null);
|
|
52
|
+
const page = React.useRef<HTMLDivElement>(null);
|
|
53
|
+
// A new story starts at its top; the list keeps its row in view (a link, Back).
|
|
54
|
+
React.useEffect(() => {
|
|
55
|
+
page.current?.scrollTo({ top: 0 });
|
|
56
|
+
list.current?.querySelector(`[data-value="${CSS.escape(story.id)}"]`)?.scrollIntoView({ block: 'nearest' });
|
|
57
|
+
}, [story.id]);
|
|
58
|
+
React.useEffect(() => {
|
|
59
|
+
if (item === story.id) title?.(item, story.title);
|
|
60
|
+
}, [item, story, title]);
|
|
61
|
+
// On a phone, no row is selected while the list shows alone (nothing is open).
|
|
62
|
+
const selected = phone && item === undefined ? undefined : story.id;
|
|
63
|
+
|
|
64
|
+
const nav = (
|
|
65
|
+
<Pane aria-label="Stories">
|
|
66
|
+
<PaneHeader>
|
|
67
|
+
<Input
|
|
68
|
+
variant="outline"
|
|
69
|
+
type="search"
|
|
70
|
+
aria-label="Search stories"
|
|
71
|
+
placeholder="Search"
|
|
72
|
+
icon={<Icon name="search" size={14} />}
|
|
73
|
+
value={query}
|
|
74
|
+
onChange={(event) => setQuery(event.currentTarget.value)}
|
|
75
|
+
onKeyDown={(event) => {
|
|
76
|
+
if (event.key === 'Escape') setQuery('');
|
|
77
|
+
if (event.key !== 'ArrowDown') return;
|
|
78
|
+
event.preventDefault();
|
|
79
|
+
const target = list.current?.querySelector<HTMLElement>('[data-slot="list-item"][aria-selected="true"]')
|
|
80
|
+
?? list.current?.querySelector<HTMLElement>('[data-slot="list-item"]');
|
|
81
|
+
target?.focus();
|
|
82
|
+
// On a phone a story replaces the list: ↓ only enters it, Enter opens.
|
|
83
|
+
if (!phone && target?.dataset.value) open(target.dataset.value);
|
|
84
|
+
}}
|
|
85
|
+
/>
|
|
86
|
+
</PaneHeader>
|
|
87
|
+
<PaneBody>
|
|
88
|
+
{shown.length === 0 ? (
|
|
89
|
+
<EmptyState fill>No stories match</EmptyState>
|
|
90
|
+
) : (
|
|
91
|
+
<List
|
|
92
|
+
ref={list}
|
|
93
|
+
aria-label="Stories"
|
|
94
|
+
selectionMode="single"
|
|
95
|
+
selectionFollowsFocus={!phone}
|
|
96
|
+
selectedKey={selected}
|
|
97
|
+
onSelectionChange={([id]) => { if (id && (phone || id !== story.id)) open(id); }}
|
|
98
|
+
>
|
|
99
|
+
{shown.map((each) => (
|
|
100
|
+
<ListItem key={each.id} value={each.id} textValue={each.title} size={phone ? 'default' : 'sm'}>
|
|
101
|
+
{each.title}
|
|
102
|
+
</ListItem>
|
|
103
|
+
))}
|
|
104
|
+
</List>
|
|
105
|
+
)}
|
|
106
|
+
</PaneBody>
|
|
107
|
+
</Pane>
|
|
108
|
+
);
|
|
109
|
+
const main = (
|
|
110
|
+
<ScrollArea className="ds-fill" viewportRef={page}>
|
|
111
|
+
<MainContent width="wide"><article aria-label={story.title}>
|
|
112
|
+
<Section size="lg" title={story.title} description={story.description}>
|
|
113
|
+
<Page key={story.id} />
|
|
114
|
+
</Section>
|
|
115
|
+
</article></MainContent>
|
|
116
|
+
</ScrollArea>
|
|
117
|
+
);
|
|
118
|
+
|
|
119
|
+
return (
|
|
120
|
+
<div className="ds-storyboard">
|
|
121
|
+
{/* A desktop window always shows a story beside the list: no collapse to the list alone in a narrow one. */}
|
|
122
|
+
<MultiPane mode={phone ? (item === undefined ? 'nav' : 'main') : 'split'} collapse={false} defaultNavSize="260px" nav={nav} main={main} />
|
|
123
|
+
</div>
|
|
124
|
+
);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Design system's home, on a desktop as on a phone: what the kit is, then its sections, each opening its screen (a
|
|
128
|
+
* plain click here, ⌘ beside, as any link to a screen). */
|
|
129
|
+
function Home({ node, phone }: { node: string; phone: boolean }) {
|
|
130
|
+
const follow = useFollow();
|
|
131
|
+
const go = (id: string, event: FollowEvent) => follow?.follow({ node, screen: { plugin: name, id } }, event);
|
|
132
|
+
const intro = "Bridge's UI kit, @bridge/ui, live in this page's theme: each component with its variants, sizes and states.";
|
|
133
|
+
const sections = (
|
|
134
|
+
<List aria-label="Sections">
|
|
135
|
+
{layers.map((layer) => (
|
|
136
|
+
<ListItem
|
|
137
|
+
key={layer.id}
|
|
138
|
+
value={layer.id}
|
|
139
|
+
textValue={layer.title}
|
|
140
|
+
size={phone ? 'default' : 'sm'}
|
|
141
|
+
leading={<Icon name={layer.icon} />}
|
|
142
|
+
trailing={<span className="ds-count">{storiesOf(layer.id).length}</span>}
|
|
143
|
+
onClick={(event) => go(layer.id, event)}
|
|
144
|
+
onAuxClick={(event) => { if (event.button !== 1) return; event.preventDefault(); go(layer.id, event); }}
|
|
145
|
+
onKeyDown={(event) => { if (event.key !== 'Enter' && event.key !== ' ') return; event.preventDefault(); go(layer.id, event); }}
|
|
146
|
+
>
|
|
147
|
+
{layer.title}
|
|
148
|
+
</ListItem>
|
|
149
|
+
))}
|
|
150
|
+
</List>
|
|
151
|
+
);
|
|
152
|
+
const structure = 'The tokens first, then from the smallest component to a whole screen: Core builds Layout and Composite, a Template is a Layout filled with Composites.';
|
|
153
|
+
return (
|
|
154
|
+
<ScrollArea className="ds-fill">
|
|
155
|
+
<MainContent width="read">
|
|
156
|
+
{/* On a phone the shell's header already says "Design system": the introduction goes with the sections. */}
|
|
157
|
+
{phone ? (
|
|
158
|
+
<Section title="Sections" description={`${intro} ${structure}`}>{sections}</Section>
|
|
159
|
+
) : (
|
|
160
|
+
<Section size="lg" title="Design system" description={intro}>
|
|
161
|
+
<Section title="Sections" description={structure}>{sections}</Section>
|
|
162
|
+
</Section>
|
|
163
|
+
)}
|
|
164
|
+
</MainContent>
|
|
165
|
+
</ScrollArea>
|
|
166
|
+
);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
export function apply(ctx: Ctx) {
|
|
170
|
+
const open = (id: string) => ctx.screen.open(id);
|
|
171
|
+
// Design system itself is the home. `key`: another screen (Core, Layout…) starts with an empty search. On the Template
|
|
172
|
+
// screen, `<template>/<opened>` is that template alone, as a real screen (its Fullscreen button; `~`: no row open).
|
|
173
|
+
ctx.slots.register({ name: 'screen' }, ({ screen, item, node }) =>
|
|
174
|
+
screen === 'design-system'
|
|
175
|
+
? <Home node={node} phone={false} />
|
|
176
|
+
: screen === 'template' && item?.includes('/')
|
|
177
|
+
? <TemplateScreen item={item} ctx={ctx} />
|
|
178
|
+
: <Storyboard key={screen} screen={screen} item={item} open={open} title={ctx.screen.title} />);
|
|
179
|
+
// On a phone (`"mobile": true` on every screen): the home; the Template screen shows the template alone, full screen,
|
|
180
|
+
// in the phone's shell (the Mobile tab's frame shows this page so, research-070); the others their list, then a story
|
|
181
|
+
// alone.
|
|
182
|
+
ctx.slots.register({ name: 'mobileScreen' }, ({ screen, item, node }) =>
|
|
183
|
+
screen === 'design-system'
|
|
184
|
+
? <Home node={node} phone />
|
|
185
|
+
: screen === 'template'
|
|
186
|
+
? <TemplateScreen item={item} ctx={ctx} />
|
|
187
|
+
: <Storyboard key={screen} screen={screen} item={item} open={open} phone title={ctx.screen.title} />);
|
|
188
|
+
// The templates under Template in Bridge's tree (the sidebar, the phone's menu): each opens its story, or on a phone
|
|
189
|
+
// the template alone.
|
|
190
|
+
ctx.sidebar.items('template', templates.map(({ id, title, icon }) => ({ id, title, icon })));
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** The templates that stand alone, in the tree's order. */
|
|
194
|
+
const templates = [
|
|
195
|
+
{ id: 'address-book-template', title: 'Address book', icon: 'users' },
|
|
196
|
+
{ id: 'mail-template', title: 'Mail', icon: 'mail' },
|
|
197
|
+
] as const;
|
|
198
|
+
|
|
199
|
+
/** Each template as it stands alone, a real screen (Fullscreen, or a phone): the person (or row) open is the item's
|
|
200
|
+
* second part, opened by the shell and closed by its Back, as a real screen's would be. */
|
|
201
|
+
const screenTemplates: Record<string, (open: string | undefined, onOpen: (id: string) => void) => React.ReactNode> = {
|
|
202
|
+
'address-book-template': (open, onOpen) => <AddressBookTemplate openId={open} onOpen={onOpen} />,
|
|
203
|
+
'mail-template': (open, onOpen) => <MailTemplate openId={open} onOpen={onOpen} />,
|
|
204
|
+
};
|
|
205
|
+
|
|
206
|
+
/** A template alone (Fullscreen, or the Template screen on a phone): `<template>/<opened>`, `~` or none for no row
|
|
207
|
+
* open; none at all, the list of templates (the tree's level above each). */
|
|
208
|
+
function TemplateScreen({ item, ctx }: { item: string | undefined; ctx: Ctx }) {
|
|
209
|
+
const [asked, opened] = (item ?? '').split('/');
|
|
210
|
+
const id = asked && screenTemplates[asked] ? asked : undefined;
|
|
211
|
+
React.useEffect(() => {
|
|
212
|
+
if (item && id) ctx.screen.title?.(item, stories.find((each) => each.id === id)?.title ?? id);
|
|
213
|
+
}, [ctx, item, id]);
|
|
214
|
+
if (!id)
|
|
215
|
+
return (
|
|
216
|
+
<div className="ds-phone-template">
|
|
217
|
+
<List aria-label="Templates" selectionMode="single" onSelectionChange={([next]) => next && ctx.screen.open(next)}>
|
|
218
|
+
{templates.map((each) => (
|
|
219
|
+
<ListItem key={each.id} value={each.id} textValue={each.title} leading={<Icon name={each.icon} />}>
|
|
220
|
+
{each.title}
|
|
221
|
+
</ListItem>
|
|
222
|
+
))}
|
|
223
|
+
</List>
|
|
224
|
+
</div>
|
|
225
|
+
);
|
|
226
|
+
return <div className="ds-phone-template">{screenTemplates[id]!(opened && opened !== '~' ? opened : undefined, (next) => ctx.screen.open(`${id}/${next}`))}</div>;
|
|
227
|
+
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
/* The design system's layout. Everything visible is the kit's (Section for every heading and caption, Card for every
|
|
2
|
+
frame); these rules only place it, in theme variables. Each covers one kit gap, named in its comment: the kit's
|
|
3
|
+
stylesheet compiles no Tailwind class from plugins outside Bridge, and has no layout primitive (Stack, Grid). */
|
|
4
|
+
|
|
5
|
+
/* Gap: the screen slot's box is a flex column; MultiPane fills a sized box. */
|
|
6
|
+
.ds-storyboard { flex: 1; display: flex; flex-direction: column; min-width: 0; min-height: 0; }
|
|
7
|
+
/* Gap: ScrollArea needs a sized box to scroll. */
|
|
8
|
+
.ds-fill { height: 100%; }
|
|
9
|
+
/* Gap: a list row's trailing count (the home's sections). */
|
|
10
|
+
.ds-count { color: var(--color-muted); font-size: 12px; font-variant-numeric: tabular-nums; }
|
|
11
|
+
/* Gap: no EmptyState inside a Card (an icon search with no match). */
|
|
12
|
+
.ds-empty { display: flex; justify-content: center; padding: 40px 16px; text-align: center; }
|
|
13
|
+
|
|
14
|
+
/* Gap: no Stack/Grid primitive to place samples inside a frame (a Card). */
|
|
15
|
+
.ds-frame.ds-frame { padding: 20px 24px; }
|
|
16
|
+
.ds-layout-row { display: flex; flex-wrap: wrap; align-items: flex-start; gap: 24px 32px; }
|
|
17
|
+
.ds-layout-grid, .ds-layout-columns { display: grid; grid-template-columns: repeat(auto-fill, minmax(168px, 1fr)); gap: 24px; }
|
|
18
|
+
.ds-layout-columns { grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); }
|
|
19
|
+
/* A grid's samples share its rows: captions of one or two lines, the samples still start level. */
|
|
20
|
+
:is(.ds-layout-grid, .ds-layout-columns) > .ds-sample { display: grid; grid-template-rows: subgrid; grid-row: span 2; row-gap: 8px; align-content: start; }
|
|
21
|
+
:is(.ds-layout-grid, .ds-layout-columns) > .ds-sample > .ds-sample-body { align-self: start; }
|
|
22
|
+
.ds-layout-stack { display: flex; flex-direction: column; gap: 20px; }
|
|
23
|
+
.ds-layout-fill { min-width: 0; }
|
|
24
|
+
/* A layout's sample, a screen: edge to edge in its frame, the frame's corners clipping it. */
|
|
25
|
+
.ds-frame.ds-layout-bleed { padding: 0; overflow: hidden; min-width: 0; }
|
|
26
|
+
.ds-screen { display: flex; min-width: 0; overflow: hidden; }
|
|
27
|
+
.ds-screen-desktop { width: 100%; aspect-ratio: 1920 / 1080; }
|
|
28
|
+
.ds-screen-scaled { flex: none; display: flex; min-width: 0; transform-origin: top left; }
|
|
29
|
+
/* A sample drawn at a desktop's width, scrolling sideways on a phone (Wide). */
|
|
30
|
+
.ds-min-wide { min-width: 640px; }
|
|
31
|
+
.ds-screen-mobile { box-sizing: border-box; width: 393px; max-width: 100%; aspect-ratio: 393 / 852; margin: 16px auto; padding: 8px; border: 1px solid var(--color-border); border-radius: 52px; }
|
|
32
|
+
.ds-screen-glass { flex: 1; display: flex; min-width: 0; overflow: hidden; padding: 40px 0 28px; border-radius: 44px; border: 1px solid var(--color-border-subtle); }
|
|
33
|
+
.ds-phone-frame { flex: 1; min-width: 0; border: 0; }
|
|
34
|
+
.ds-phone-template { display: flex; flex-direction: column; height: 100%; min-height: 0; box-sizing: border-box; padding-bottom: var(--mobile-inset-bottom, 0); }
|
|
35
|
+
.ds-code { margin-top: 8px; }
|
|
36
|
+
.ds-flow { box-sizing: border-box; display: flex; align-items: center; justify-content: center; gap: 12px; width: max-content; min-width: 100%; padding: 16px; }
|
|
37
|
+
.ds-flow-step { display: flex; flex-direction: column; align-items: center; gap: 8px; font-size: 12px; color: var(--color-muted); }
|
|
38
|
+
.ds-flow-step .ds-screen-mobile { zoom: 0.55; margin: 0; }
|
|
39
|
+
.ds-flow-arrow { color: var(--color-muted); }
|
|
40
|
+
.ds-sample { min-width: 0; }
|
|
41
|
+
.ds-wide { flex: 1 1 100%; grid-column: 1 / -1; }
|
|
42
|
+
.ds-sample-body { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; min-width: 0; }
|
|
43
|
+
/* A form control's sample at a form's width. */
|
|
44
|
+
.ds-control { width: 280px; max-width: 100%; }
|
|
45
|
+
.ds-control-wide { width: 420px; max-width: 100%; }
|
|
46
|
+
.ds-readout { width: 48px; flex-shrink: 0; text-align: right; font-variant-numeric: tabular-nums; color: var(--fg-secondary); font-size: 13px; }
|
|
47
|
+
/* Gap: no inline row primitive (a control and its text label side by side). */
|
|
48
|
+
.ds-inline { display: inline-flex; align-items: center; gap: 8px; }
|
|
49
|
+
.ds-columns { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 24px; width: 100%; }
|
|
50
|
+
|
|
51
|
+
/* Foundations. Gap: no swatch or specimen component; a Card is the swatch, sized here. */
|
|
52
|
+
.ds-specimen { margin: 0; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
53
|
+
.ds-swatch { width: 100%; height: 56px; }
|
|
54
|
+
.ds-bar { width: 100%; }
|
|
55
|
+
.ds-box { width: 88px; height: 64px; }
|
|
56
|
+
.ds-icons { display: grid; grid-template-columns: repeat(auto-fill, minmax(120px, 1fr)); gap: 12px; }
|
|
57
|
+
.ds-icon-tile { display: flex; flex-direction: column; align-items: center; gap: 10px; padding: 18px 8px 12px; }
|
|
58
|
+
.ds-icon-tile > [data-slot="section"] { width: 100%; }
|
|
59
|
+
.ds-icon-tile [data-slot="section-title"] { text-align: center; }
|
|
60
|
+
|
|
61
|
+
/* Inputs. Gap: Field is a column; a checkbox or a toggle sits beside its label. */
|
|
62
|
+
.ds-field-row.ds-field-row { flex-direction: row; align-items: center; gap: 8px; }
|
|
63
|
+
.ds-checklist { display: flex; flex-direction: column; gap: 10px; }
|
|
64
|
+
.ds-indent { display: flex; flex-direction: column; gap: 10px; padding-left: 24px; }
|
|
65
|
+
/* Gap: no Form layout (stacked fields, a right-aligned action row). */
|
|
66
|
+
.ds-form { display: flex; flex-direction: column; gap: 16px; width: 420px; max-width: 100%; }
|
|
67
|
+
.ds-actions { display: flex; justify-content: flex-end; gap: 8px; }
|
|
68
|
+
/* Gap: a menu item's text that pushes its check to the end. */
|
|
69
|
+
.ds-grow-text { flex: 1; min-width: 0; }
|
|
70
|
+
|
|
71
|
+
/* Data display. Gap: Table and PropertyRow cells are flex rows without a gap; List has no frame of its own. */
|
|
72
|
+
.ds-gap { display: inline-block; width: 8px; flex-shrink: 0; }
|
|
73
|
+
.ds-num { justify-content: flex-end; font-variant-numeric: tabular-nums; }
|
|
74
|
+
.ds-span-all { grid-column: 1 / -1; }
|
|
75
|
+
.ds-list { width: 100%; }
|
|
76
|
+
|
|
77
|
+
/* Navigation. Gap: the Sidebar fills its parent's height; a story gives it a box (and its own width variable). */
|
|
78
|
+
.ds-sidebar-frame { position: relative; display: flex; height: 460px; overflow: hidden; border-radius: var(--radius-dropdown); }
|
|
79
|
+
.ds-sidebar-main { flex: 1; min-width: 0; padding: 20px 24px; border-left: 1px solid var(--border); }
|
|
80
|
+
.ds-sidebar-strip { display: flex; height: 230px; --sidebar-width: 260px; }
|
|
81
|
+
|
|
82
|
+
/* Overlay. Gap: DialogFooter's actions are not end-aligned; DialogBody has no bottom padding. */
|
|
83
|
+
.ds-dialog-footer { justify-content: flex-end; gap: 8px; }
|
|
84
|
+
.ds-dialog-body, .ds-dialog-form { padding-bottom: 20px; }
|
|
85
|
+
.ds-dialog-form { width: 100%; }
|
|
86
|
+
.ds-context-area { width: 260px; max-width: 100%; padding: 16px; }
|
|
87
|
+
|
|
88
|
+
/* Layout. Gap: AppShell is h-screen; a story frames it in a fixed box. */
|
|
89
|
+
.ds-shell-frame { height: 440px; overflow: hidden; border-radius: var(--radius-dropdown); }
|
|
90
|
+
.ds-shell.ds-shell { height: 100%; }
|
|
91
|
+
.ds-shell-header { display: flex; align-items: center; gap: 10px; height: 44px; padding: 0 12px; }
|
|
92
|
+
.ds-shell-main { padding: 20px 24px; }
|
|
93
|
+
.ds-card-foot { margin-top: 10px; }
|
|
94
|
+
.ds-split { height: 180px; padding: 0; overflow: hidden; }
|
|
95
|
+
.ds-split-tall { height: 240px; }
|
|
96
|
+
.ds-pane-pad { padding: 14px 16px; }
|
|
97
|
+
.ds-block { flex: 1; box-sizing: border-box; height: calc(100% - 8px); display: flex; align-items: center; justify-content: center; margin: 4px; border-radius: 6px; background: var(--color-hover); color: var(--color-muted); font-size: 12px; }
|
|
98
|
+
.ds-scroll-box { height: 220px; padding: 0; overflow: hidden; }
|
|
99
|
+
.ds-scroll-short { height: 98px; }
|
|
100
|
+
.ds-scroll-row { display: flex; gap: 8px; padding: 12px; width: max-content; }
|
|
101
|
+
.ds-scroll-chip { display: flex; flex-direction: column; align-items: center; gap: 8px; width: 96px; }
|
|
102
|
+
.ds-scroll-wide { display: flex; flex-direction: column; gap: 10px; padding: 12px; width: max-content; }
|
|
103
|
+
|
|
104
|
+
/* Interaction. Gap: no Stack for sortable items and board columns. */
|
|
105
|
+
.ds-sortable { display: flex; flex-direction: column; gap: 6px; }
|
|
106
|
+
.ds-sortable-row { display: flex; gap: 8px; }
|
|
107
|
+
.ds-task { display: flex; align-items: center; gap: 10px; }
|
|
108
|
+
.ds-board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px; }
|
|
109
|
+
.ds-column { min-width: 0; }
|
|
110
|
+
.ds-column-title { display: inline-flex; align-items: center; gap: 6px; }
|
package/e2e.test.ts
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
// End-to-end in a real Bridge. Starts the host from Bridge's checkout (`BRIDGE_REPO`, else `bridge` beside this
|
|
2
|
+
// repository) on a temp root (no plugin watching), its `_host` serving this repository's Bridge UI plugin (research-112:
|
|
3
|
+
// a preset naming `packages/bridge-ui` in place of `@bridgebrew/bridge-ui`), installs this
|
|
4
|
+
// folder, linked, in workspace `admin`, and drives Chromium with the Bridge repo's Playwright: every story renders with
|
|
5
|
+
// no console error and no page error on its screen (Design system, or its child Core, Layout, Composite), the URL's item picks the story (and survives a reload), the list search filters,
|
|
6
|
+
// and the interactive stories work. Run with a Node Bridge supports (>= 24.21): `pnpm e2e`. The temp root and the host
|
|
7
|
+
// are removed afterwards.
|
|
8
|
+
import assert from 'node:assert/strict';
|
|
9
|
+
import { execFile, spawn, type ChildProcess } from 'node:child_process';
|
|
10
|
+
import { mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
|
|
11
|
+
import { createRequire } from 'node:module';
|
|
12
|
+
import { tmpdir } from 'node:os';
|
|
13
|
+
import { basename, dirname, join, resolve } from 'node:path';
|
|
14
|
+
import { after, before, test } from 'node:test';
|
|
15
|
+
import { fileURLToPath } from 'node:url';
|
|
16
|
+
import { promisify } from 'node:util';
|
|
17
|
+
import { screenOf, stories, storiesOf } from './stories.ts';
|
|
18
|
+
|
|
19
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
20
|
+
const bridge = realpathSync(resolve(process.env.BRIDGE_REPO ?? resolve(here, '../../../bridge')));
|
|
21
|
+
/** The Bridge UI plugin `_host` serves the kit from: this repository's (`packages/bridge-ui`, its kit this checkout's
|
|
22
|
+
* `packages/ui`), or another folder (`DESIGN_SYSTEM_UI_PLUGIN`: the consumer gate's, carrying the candidate). */
|
|
23
|
+
const uiPlugin = process.env.DESIGN_SYSTEM_UI_PLUGIN ?? realpathSync(resolve(here, '../bridge-ui'));
|
|
24
|
+
/** What is installed: this folder, or a candidate's packed tarball (`DESIGN_SYSTEM_PACKAGE`, the consumer gate). */
|
|
25
|
+
const pkg = process.env.DESIGN_SYSTEM_PACKAGE ?? here;
|
|
26
|
+
const { chromium } = createRequire(join(bridge, 'package.json'))('@playwright/test');
|
|
27
|
+
|
|
28
|
+
const [major = 0, minor = 0] = process.versions.node.split('.').map(Number);
|
|
29
|
+
if (major < 24 || (major === 24 && minor < 21)) throw new Error(`Bridge needs Node >= 24.21, this is ${process.version}`);
|
|
30
|
+
|
|
31
|
+
const root = mkdtempSync(join(tmpdir(), 'design-system-e2e-'));
|
|
32
|
+
// Bridge's preset, its `_host` taking the Bridge UI plugin above in place of the registry's. A Bridge from before
|
|
33
|
+
// presets named `_host` (no `host`) serves its own kit: the preset as it is.
|
|
34
|
+
const presets = JSON.parse(
|
|
35
|
+
readFileSync(join(bridge, 'packages/workspace-presets/preset.json'), 'utf8'),
|
|
36
|
+
) as { host?: string[] };
|
|
37
|
+
const preset = join(root, '..', `${basename(root)}-preset.json`);
|
|
38
|
+
writeFileSync(
|
|
39
|
+
preset,
|
|
40
|
+
JSON.stringify({
|
|
41
|
+
...presets,
|
|
42
|
+
...(presets.host && {
|
|
43
|
+
host: presets.host.map((entry) => (entry === '@bridgebrew/bridge-ui' ? uiPlugin : entry)),
|
|
44
|
+
}),
|
|
45
|
+
}),
|
|
46
|
+
);
|
|
47
|
+
const env = {
|
|
48
|
+
...process.env,
|
|
49
|
+
BRIDGE_ROOT: root,
|
|
50
|
+
BRIDGE_WATCH: '0',
|
|
51
|
+
BRIDGE_WORKSPACE_PRESET_PATH: preset,
|
|
52
|
+
};
|
|
53
|
+
const cli = (...args: string[]) => promisify(execFile)(process.execPath, ['packages/host/src/cli.ts', ...args], { cwd: bridge, env });
|
|
54
|
+
|
|
55
|
+
let host: ChildProcess | undefined;
|
|
56
|
+
let stderr = '';
|
|
57
|
+
let browser: any;
|
|
58
|
+
let page: any;
|
|
59
|
+
let base = '';
|
|
60
|
+
/** The page's console errors and uncaught errors since the last `clean()`. */
|
|
61
|
+
let errors: string[] = [];
|
|
62
|
+
|
|
63
|
+
/** Starts the host; answers its address once printed. */
|
|
64
|
+
const start = () => new Promise<string>((done, fail) => {
|
|
65
|
+
host = spawn(process.execPath, ['packages/host/src/cli.ts', 'start', '--port', '0'], { cwd: bridge, env, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
66
|
+
let stdout = '';
|
|
67
|
+
const timer = setTimeout(() => fail(new Error(`host did not start within 30 s:\n${stdout}\n${stderr}`)), 30_000);
|
|
68
|
+
host.stderr!.on('data', (chunk: Buffer) => { stderr += chunk; });
|
|
69
|
+
host.stdout!.on('data', (chunk: Buffer) => {
|
|
70
|
+
stdout += chunk;
|
|
71
|
+
const url = /Bridge listening on (http:\/\/127\.0\.0\.1:\d+)\n/.exec(stdout)?.[1];
|
|
72
|
+
if (url && /^Open Bridge: (\S+)\n/m.test(stdout)) {
|
|
73
|
+
clearTimeout(timer);
|
|
74
|
+
done(url);
|
|
75
|
+
}
|
|
76
|
+
});
|
|
77
|
+
host.once('exit', (code) => { clearTimeout(timer); fail(new Error(`host exited with code ${code}:\n${stdout}\n${stderr}`)); });
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
before(async () => {
|
|
81
|
+
base = await start();
|
|
82
|
+
await cli('install', pkg, '--workspace', 'admin');
|
|
83
|
+
// A fresh launch link: the one printed at start may predate the install's restart.
|
|
84
|
+
const { stdout } = await cli('open', '--workspace', 'admin');
|
|
85
|
+
const link = /Open Bridge: (\S+)/.exec(stdout)?.[1];
|
|
86
|
+
assert.ok(link, `no launch link in: ${stdout}`);
|
|
87
|
+
browser = await chromium.launch();
|
|
88
|
+
page = await browser.newPage({ viewport: { width: 1440, height: 900 } });
|
|
89
|
+
page.on('console', (message: { type(): string; text(): string }) => { if (message.type() === 'error') errors.push(message.text()); });
|
|
90
|
+
page.on('pageerror', (error: Error) => errors.push(`pageerror: ${error.message}`));
|
|
91
|
+
await page.goto(link);
|
|
92
|
+
}, { timeout: 180_000 });
|
|
93
|
+
|
|
94
|
+
after(async () => {
|
|
95
|
+
await browser?.close();
|
|
96
|
+
await cli('stop').catch(() => {});
|
|
97
|
+
host?.kill('SIGKILL');
|
|
98
|
+
rmSync(root, { recursive: true, force: true, maxRetries: 3 });
|
|
99
|
+
rmSync(preset, { force: true });
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
const screen = `/admin/root/design-system`;
|
|
103
|
+
/** A screen's path: Design system (the home), or one of its sections (`foundations`, `core`…). */
|
|
104
|
+
const pathOf = (child: string) => (child === 'design-system' ? screen : `${screen}/${child}`);
|
|
105
|
+
/** Opens the story `item` on its screen (an unknown one: on Foundations) and waits for the story `title`. */
|
|
106
|
+
const open = async (item: string, title: string) => {
|
|
107
|
+
const story = stories.find((each) => each.id === item);
|
|
108
|
+
await page.goto(`${base}${pathOf(story ? screenOf(story) : 'foundations')}/${item}`);
|
|
109
|
+
await shows(title);
|
|
110
|
+
};
|
|
111
|
+
const shows = (title: string) => page.getByRole('heading', { level: 2, name: title, exact: true }).waitFor();
|
|
112
|
+
const list = () => page.getByRole('listbox', { name: 'Stories' });
|
|
113
|
+
const selected = async () => list().locator('[aria-selected="true"]').getAttribute('data-value');
|
|
114
|
+
const clean = () => { errors = []; };
|
|
115
|
+
const noErrors = (where: string) => assert.deepEqual(errors, [], `${where}: ${errors.join('\n')}`);
|
|
116
|
+
|
|
117
|
+
test('Design system opens on its home; a section opens its screen on its first story, Back returns home', { timeout: 30_000 }, async () => {
|
|
118
|
+
clean();
|
|
119
|
+
await page.goto(`${base}${screen}`);
|
|
120
|
+
await shows('Design system');
|
|
121
|
+
const sections = page.getByRole('listbox', { name: 'Sections' });
|
|
122
|
+
assert.deepEqual((await sections.getByRole('option').allInnerTexts()).map((each: string) => each.replace(/\d+/g, '').trim()), ['Foundations', 'Core', 'Layout', 'Composite', 'Template', 'Shell']);
|
|
123
|
+
await sections.getByRole('option', { name: 'Foundations' }).click();
|
|
124
|
+
await shows('Colors');
|
|
125
|
+
assert.ok(page.url().endsWith(`${screen}/foundations`), page.url());
|
|
126
|
+
assert.equal(await selected(), 'colors');
|
|
127
|
+
assert.ok(await page.getByRole('heading', { level: 4, name: '--bg-surface', exact: true }).isVisible());
|
|
128
|
+
await page.goBack();
|
|
129
|
+
await shows('Design system');
|
|
130
|
+
noErrors('home');
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
test('every story renders, with no console or React error', { timeout: 180_000 }, async () => {
|
|
134
|
+
for (const story of stories) {
|
|
135
|
+
clean();
|
|
136
|
+
await open(story.id, story.title);
|
|
137
|
+
assert.equal(await selected(), story.id, story.id);
|
|
138
|
+
// Let effects, measurements and timers settle.
|
|
139
|
+
await page.waitForTimeout(150);
|
|
140
|
+
noErrors(story.id);
|
|
141
|
+
}
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
test('the URL item picks the story and survives a reload; the list opens another; an unknown item shows the first', { timeout: 30_000 }, async () => {
|
|
145
|
+
clean();
|
|
146
|
+
await open('picker', 'Picker');
|
|
147
|
+
await page.reload();
|
|
148
|
+
await shows('Picker');
|
|
149
|
+
assert.equal(await selected(), 'picker');
|
|
150
|
+
await list().getByRole('option', { name: 'Wizard', exact: true }).click();
|
|
151
|
+
await shows('Wizard');
|
|
152
|
+
assert.ok(page.url().endsWith(`${screen}/composite/wizard`), page.url());
|
|
153
|
+
await page.goBack();
|
|
154
|
+
await shows('Picker');
|
|
155
|
+
await open('no-such-story', 'Colors');
|
|
156
|
+
assert.equal(await selected(), 'colors');
|
|
157
|
+
noErrors('routing');
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
test('the list search filters its screen\'s stories by title, and says when nothing matches', { timeout: 30_000 }, async () => {
|
|
161
|
+
clean();
|
|
162
|
+
await page.goto(`${base}${pathOf('core')}`);
|
|
163
|
+
await shows(storiesOf('core')[0]!.title);
|
|
164
|
+
const search = page.getByRole('searchbox', { name: 'Search stories' });
|
|
165
|
+
await search.fill('tog');
|
|
166
|
+
const names = async () => (await list().getByRole('option').allInnerTexts()).map((each: string) => each.trim());
|
|
167
|
+
assert.deepEqual(await names(), ['Toggle', 'Toggle group']);
|
|
168
|
+
await search.fill('menu');
|
|
169
|
+
assert.deepEqual(await names(), ['Pick menu', 'Tag menu', 'Dropdown menu']);
|
|
170
|
+
await search.fill('zzz');
|
|
171
|
+
await page.getByText('No stories match').waitFor();
|
|
172
|
+
await search.press('Escape');
|
|
173
|
+
assert.equal((await names()).length, storiesOf('core').length);
|
|
174
|
+
noErrors('search');
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
test('Picker: open the status pill, press 3, the third status is picked', { timeout: 30_000 }, async () => {
|
|
178
|
+
clean();
|
|
179
|
+
await open('picker', 'Picker');
|
|
180
|
+
await page.getByRole('combobox', { name: 'Status: Todo', exact: true }).click();
|
|
181
|
+
// The search row takes the focus once the popup is up: the digit is for it, not the pill.
|
|
182
|
+
await page.waitForFunction(() => document.activeElement?.getAttribute('data-slot') === 'picker-search', undefined, { timeout: 5_000 });
|
|
183
|
+
await page.keyboard.press('3');
|
|
184
|
+
await page.getByRole('combobox', { name: 'Status: In progress', exact: true }).waitFor({ timeout: 5_000 });
|
|
185
|
+
await page.locator('[data-slot="picker-content"]').waitFor({ state: 'detached' });
|
|
186
|
+
noErrors('picker');
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
test('Combobox: the fake server says Loading…, then answers', { timeout: 30_000 }, async () => {
|
|
190
|
+
clean();
|
|
191
|
+
await open('combobox', 'Combobox');
|
|
192
|
+
const input = page.getByRole('combobox', { name: 'Organization' });
|
|
193
|
+
await input.fill('wi');
|
|
194
|
+
await page.locator('[data-slot="combobox-empty"]', { hasText: 'Loading…' }).waitFor();
|
|
195
|
+
await page.getByRole('option', { name: 'Windmill Labs', exact: true }).click();
|
|
196
|
+
assert.equal(await input.inputValue(), 'Windmill Labs');
|
|
197
|
+
noErrors('combobox');
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
test('Dialog opens, validates, and closes with a toast', { timeout: 30_000 }, async () => {
|
|
201
|
+
clean();
|
|
202
|
+
await open('dialog', 'Dialog');
|
|
203
|
+
await page.getByRole('button', { name: 'New project' }).click();
|
|
204
|
+
const dialog = page.getByRole('dialog', { name: 'New project' });
|
|
205
|
+
await dialog.getByRole('button', { name: 'Create project' }).click();
|
|
206
|
+
await dialog.getByText('Enter a project name').waitFor();
|
|
207
|
+
await dialog.getByRole('textbox', { name: 'Name' }).fill('Relaunch');
|
|
208
|
+
await dialog.getByRole('button', { name: 'Create project' }).click();
|
|
209
|
+
await page.getByText('Project “Relaunch” created').waitFor();
|
|
210
|
+
await dialog.waitFor({ state: 'detached' });
|
|
211
|
+
noErrors('dialog');
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
test('on a phone: home, a section\'s list alone, a story alone, Back to the list, the same story again, Back home', { timeout: 60_000 }, async () => {
|
|
215
|
+
// Bridge's phone shell: a narrow window with a coarse pointer (iPhone 15), signed in as the desktop page is.
|
|
216
|
+
const context = await browser.newContext({ viewport: { width: 393, height: 852 }, isMobile: true, hasTouch: true, storageState: await page.context().storageState() });
|
|
217
|
+
const phone = await context.newPage();
|
|
218
|
+
const phoneErrors: string[] = [];
|
|
219
|
+
phone.on('console', (message: { type(): string; text(): string }) => { if (message.type() === 'error') phoneErrors.push(message.text()); });
|
|
220
|
+
phone.on('pageerror', (error: Error) => phoneErrors.push(`pageerror: ${error.message}`));
|
|
221
|
+
try {
|
|
222
|
+
const stories = phone.getByRole('listbox', { name: 'Stories' });
|
|
223
|
+
const story = (title: string) => phone.getByRole('article', { name: title, exact: true });
|
|
224
|
+
const back = () => phone.getByRole('button', { name: 'Back' }).first().tap();
|
|
225
|
+
await phone.goto(`${base}${screen}`);
|
|
226
|
+
await phone.getByRole('listbox', { name: 'Sections' }).getByRole('option', { name: /^Core/ }).tap();
|
|
227
|
+
await stories.waitFor();
|
|
228
|
+
assert.equal(await story('Button').count(), 0, 'no story beside the list');
|
|
229
|
+
await stories.getByRole('option', { name: 'Table', exact: true }).tap();
|
|
230
|
+
await story('Table').waitFor();
|
|
231
|
+
assert.ok(!(await stories.isVisible()), 'the story alone');
|
|
232
|
+
// A table drawn at a desktop's width, scrolling sideways rather than squeezed.
|
|
233
|
+
const table = await story('Table').locator('[data-slot="table"]').first().boundingBox();
|
|
234
|
+
assert.ok(table && table.width >= 600, `table width ${table?.width}`);
|
|
235
|
+
await back();
|
|
236
|
+
await stories.waitFor();
|
|
237
|
+
assert.ok(phone.url().endsWith(`${screen}/core`), phone.url());
|
|
238
|
+
await stories.getByRole('option', { name: 'Table', exact: true }).tap();
|
|
239
|
+
await story('Table').waitFor();
|
|
240
|
+
await back();
|
|
241
|
+
await stories.waitFor();
|
|
242
|
+
await back();
|
|
243
|
+
await phone.getByRole('listbox', { name: 'Sections' }).waitFor();
|
|
244
|
+
// A dialog fits the phone's width.
|
|
245
|
+
await phone.goto(`${base}${pathOf('core')}/dialog`);
|
|
246
|
+
await story('Dialog').getByRole('button', { name: 'New project' }).tap();
|
|
247
|
+
const dialog = await phone.getByRole('dialog', { name: 'New project' }).boundingBox();
|
|
248
|
+
assert.ok(dialog && dialog.x >= 0 && dialog.x + dialog.width <= 393, `dialog ${JSON.stringify(dialog)}`);
|
|
249
|
+
assert.deepEqual(phoneErrors, [], phoneErrors.join('\n'));
|
|
250
|
+
} finally {
|
|
251
|
+
await context.close();
|
|
252
|
+
}
|
|
253
|
+
});
|
package/highlight.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// A sample's code coloured (research-070): Shiki here, in Design system's own bundle (never the kit's, which every page
|
|
2
|
+
// loads), its css-variables theme, as the docs plugin; the kit's CodeBlock draws the tokens in the theme's colours.
|
|
3
|
+
import { createCssVariablesTheme, createHighlighterCore } from 'shiki/core';
|
|
4
|
+
import { createJavaScriptRegexEngine } from 'shiki/engine/javascript';
|
|
5
|
+
import type { CodeToken } from '@bridge/ui';
|
|
6
|
+
|
|
7
|
+
let highlighter: ReturnType<typeof createHighlighterCore> | undefined;
|
|
8
|
+
const getHighlighter = () =>
|
|
9
|
+
(highlighter ??= createHighlighterCore({
|
|
10
|
+
engine: createJavaScriptRegexEngine(),
|
|
11
|
+
themes: [createCssVariablesTheme()],
|
|
12
|
+
langs: [import('shiki/langs/tsx.mjs'), import('shiki/langs/bash.mjs'), import('shiki/langs/css.mjs')],
|
|
13
|
+
}));
|
|
14
|
+
|
|
15
|
+
const aliases: Record<string, string> = { sh: 'bash', shell: 'bash' };
|
|
16
|
+
|
|
17
|
+
/** `code` cut into coloured tokens, line by line; plain (undefined) for a language not loaded or a grammar too hard. */
|
|
18
|
+
export async function tokensOf(code: string, language: string): Promise<CodeToken[][] | undefined> {
|
|
19
|
+
const lang = aliases[language] ?? language;
|
|
20
|
+
const engine = await getHighlighter();
|
|
21
|
+
if (!engine.getLoadedLanguages().includes(lang)) return undefined;
|
|
22
|
+
try {
|
|
23
|
+
return engine.codeToTokens(code, { lang, theme: 'css-variables' }).tokens.map((line) =>
|
|
24
|
+
line.map((token) => ({ content: token.content, color: token.color })),
|
|
25
|
+
);
|
|
26
|
+
} catch {
|
|
27
|
+
return undefined;
|
|
28
|
+
}
|
|
29
|
+
}
|