@stacksjs/components 0.2.853 → 0.2.855

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.
Files changed (44) hide show
  1. package/dist/CodeEditor-jg4w7e15.stx +497 -0
  2. package/dist/code-editor/editor.js +2166 -0
  3. package/dist/components/CodeBlock.d.ts +12 -5
  4. package/dist/index.d.ts +2 -0
  5. package/dist/index.js +29 -12
  6. package/dist/ui/code-editor/CodeEditor.d.ts +46 -0
  7. package/dist/ui/code-editor/controller.d.ts +103 -0
  8. package/dist/ui/code-editor/core/commands.d.ts +55 -0
  9. package/dist/ui/code-editor/core/completion.d.ts +40 -0
  10. package/dist/ui/code-editor/core/editor.d.ts +69 -0
  11. package/dist/ui/code-editor/core/highlight.d.ts +61 -0
  12. package/dist/ui/code-editor/core/history.d.ts +27 -0
  13. package/dist/ui/code-editor/core/index.d.ts +13 -0
  14. package/dist/ui/code-editor/core/keymap.d.ts +38 -0
  15. package/dist/ui/code-editor/core/selection.d.ts +30 -0
  16. package/dist/ui/code-editor/core/text.d.ts +64 -0
  17. package/dist/ui/code-editor/editor.d.ts +15 -0
  18. package/dist/ui/code-editor/index.d.ts +29 -0
  19. package/dist/ui/code-editor/tokenizer.d.ts +18 -0
  20. package/dist/ui/code-editor/view.d.ts +59 -0
  21. package/dist/utils/highlighter.d.ts +19 -1
  22. package/dist/utils/highlighter.js +24 -7
  23. package/dist/utils/syntax-theme.d.ts +44 -0
  24. package/package.json +9 -4
  25. package/src/components/CodeBlock.stx +195 -17
  26. package/src/index.ts +2 -0
  27. package/src/ui/code-editor/CodeEditor.stx +497 -0
  28. package/src/ui/code-editor/README.md +134 -0
  29. package/src/ui/code-editor/controller.ts +517 -0
  30. package/src/ui/code-editor/core/commands.ts +381 -0
  31. package/src/ui/code-editor/core/completion.ts +212 -0
  32. package/src/ui/code-editor/core/editor.ts +319 -0
  33. package/src/ui/code-editor/core/highlight.ts +203 -0
  34. package/src/ui/code-editor/core/history.ts +190 -0
  35. package/src/ui/code-editor/core/index.ts +14 -0
  36. package/src/ui/code-editor/core/keymap.ts +125 -0
  37. package/src/ui/code-editor/core/selection.ts +104 -0
  38. package/src/ui/code-editor/core/text.ts +252 -0
  39. package/src/ui/code-editor/editor.ts +16 -0
  40. package/src/ui/code-editor/index.ts +46 -0
  41. package/src/ui/code-editor/tokenizer.ts +74 -0
  42. package/src/ui/code-editor/view.ts +1066 -0
  43. package/src/utils/highlighter.ts +121 -218
  44. package/src/utils/syntax-theme.ts +144 -0
@@ -1,26 +1,33 @@
1
1
  import type { Highlighter as TSHighlighter } from 'ts-syntax-highlighter'
2
+ import { codeBlockCss, SYNTAX_DARK, SYNTAX_LIGHT, syntaxPanelCss, syntaxTokenRules, syntaxVariables } from './syntax-theme'
2
3
 
3
- // Imported at call time, not at module load. A static import here made the
4
- // highlighter's own resolution a load-time dependency of this module, so
5
- // anything importing it -- CodeBlock's <script server> -- died with it, and a
6
- // server block that throws renders the component as nothing at all. 0.2.17
7
- // ships a bundle that imports `bunfig` while declaring no dependencies, which
8
- // is exactly the resolution failure that has to stay survivable.
9
- //
10
- // In a browser bundle it is not there at all: package.json's `browser` map
11
- // swaps it for an empty module, since it needs Node's streams and zlib. The
12
- // package root re-exports this file, so without that a page importing anything
13
- // from the root -- a component, the overlay stack -- failed to bundle. A
14
- // browser call lands in the "could not be loaded" path below; highlighting is
15
- // a server render's job (CodeBlock's <script server>).
16
- async function loadCreateHighlighter(): Promise<typeof import('ts-syntax-highlighter')['createHighlighter'] | null> {
17
- try {
18
- const mod = await import('ts-syntax-highlighter')
19
- return mod.createHighlighter
20
- }
21
- catch {
22
- return null
23
- }
4
+ type BrowserEntry = typeof import('ts-syntax-highlighter/browser')
5
+
6
+ /*
7
+ * The highlighter, through its browser entry.
8
+ *
9
+ * This used to import the package root, and the root loads a config file from
10
+ * disk through `bunfig`. Two things followed. In a browser bundle the root had
11
+ * to be mapped to an empty module (package.json's `browser` field), so a call
12
+ * from a page fell straight to plain text: client-side highlighting did not
13
+ * exist. And on a server where `bunfig` was not reachable - which included this
14
+ * package's own test runner - the import threw, and every block rendered plain
15
+ * there too, quietly.
16
+ *
17
+ * The browser entry is the tokenizer, the grammars and nothing that touches a
18
+ * filesystem, so the same call now works in both places.
19
+ *
20
+ * Still imported at call time, and still survivable: highlighting is
21
+ * decoration and the code is the content, so a highlighter that cannot load
22
+ * must not take the block with it. A `<script server>` that throws renders the
23
+ * whole component as nothing.
24
+ */
25
+ let entry: Promise<BrowserEntry | null> | null = null
26
+
27
+ function loadHighlighter(): Promise<BrowserEntry | null> {
28
+ entry ??= import('ts-syntax-highlighter/browser').catch(() => null)
29
+
30
+ return entry
24
31
  }
25
32
 
26
33
  let highlighterInstance: TSHighlighter | null = null
@@ -31,6 +38,7 @@ const DARK = 'github-dark'
31
38
  export interface HighlighterOptions {
32
39
  theme?: 'light' | 'dark' | 'auto'
33
40
  language?: string
41
+ /** Number the lines. Drawn by CSS, so they are never part of a copy. */
34
42
  lineNumbers?: boolean
35
43
  wrapLines?: boolean
36
44
  }
@@ -38,32 +46,37 @@ export interface HighlighterOptions {
38
46
  export interface HighlightResult {
39
47
  html: string
40
48
  /**
41
- * The token styles for `html`. Nothing else in this package ships styles for
42
- * the highlighter's class names, so a block rendered without this CSS is
43
- * correctly marked up and visually plain.
49
+ * The styles `html` needs: the palettes as custom properties, the rules that
50
+ * colour each token class from them, and the panel. `<CodeBlock>` ships the
51
+ * same sheet itself, so this is for a caller rendering `html` somewhere a
52
+ * `<CodeBlock>` is not.
44
53
  */
45
54
  css: string
46
55
  language: string
47
56
  theme: string
48
57
  }
49
58
 
50
- /** The code itself, escaped, for when highlighting is unavailable. */
51
- function plainCodeHtml(code: string): string {
52
- const escaped = code
59
+ function escapeHtml(text: string): string {
60
+ return text
53
61
  .replace(/&/g, '&amp;')
54
62
  .replace(/</g, '&lt;')
55
63
  .replace(/>/g, '&gt;')
56
- return `<pre class="syntax"><code>${escaped}</code></pre>`
64
+ }
65
+
66
+ /** The code itself, escaped, for when highlighting is unavailable. */
67
+ function plainCodeHtml(code: string): string {
68
+ return `<pre class="syntax"><code>${escapeHtml(code)}</code></pre>`
57
69
  }
58
70
 
59
71
  /**
60
- * Initialize or get the syntax highlighter instance
72
+ * The full highlighter from the package root, for a caller that wants its API.
73
+ *
74
+ * Server only: the root entry reads a config file. `highlight()` below does
75
+ * not use it.
61
76
  */
62
77
  export async function getHighlighter(): Promise<TSHighlighter> {
63
78
  if (!highlighterInstance) {
64
- const createHighlighter = await loadCreateHighlighter()
65
- if (!createHighlighter)
66
- throw new Error('ts-syntax-highlighter could not be loaded')
79
+ const { createHighlighter } = await import('ts-syntax-highlighter')
67
80
  highlighterInstance = await createHighlighter({
68
81
  theme: 'github-light',
69
82
  })
@@ -71,124 +84,85 @@ export async function getHighlighter(): Promise<TSHighlighter> {
71
84
  return highlighterInstance
72
85
  }
73
86
 
74
- /*
75
- * Matched on the class ATTRIBUTE generally, then filtered, rather than with
76
- * `class="token …"` written into the pattern: the linter reads that literal as
77
- * a Tailwind class list and asks for it to be reordered.
78
- */
79
- const STYLED_SPAN = /<span class="([^"]*)"[^>]*style="([^"]*)"/g
80
- const TOKEN_CLASS = /^token\s+(\S.*)$/
81
-
82
- /** `color: #rrggbb; font-style: italic` on each token span, in document order. */
83
- function tokenStyles(html: string): Array<[string, string]> {
84
- const out: Array<[string, string]> = []
85
- for (const m of html.matchAll(STYLED_SPAN)) {
86
- const token = TOKEN_CLASS.exec(m[1] ?? '')
87
- if (token)
88
- out.push([token[1]!.trim(), m[2] ?? ''])
89
- }
90
- return out
91
- }
92
-
93
- /** A CSS class is safe to put in a selector; a scope name from a theme is not. */
94
- function selectorSafe(cls: string): boolean {
95
- return /^[\w-]+$/.test(cls)
96
- }
97
-
98
87
  /**
99
- * Both palettes as CSS, with the inline colours stripped so the rules apply.
88
+ * Tokenized code as HTML, or null when it cannot be tokenized.
100
89
  *
101
- * The engine writes token colours inline, which no media query can override, so
102
- * `auto` could only ever ship one palette (stacksjs/stx#2015). This renders the
103
- * same code under each theme, pairs the spans by position - they are the same
104
- * tokens, so the two renders align exactly - and re-emits the colours as rules
105
- * on the `.token` classes the spans already carry.
90
+ * A class on each token and no colour: `tok-keyword`, not
91
+ * `style="color: #cf222e"`. The highlighter's own renderer writes the colour
92
+ * inline, where no stylesheet can reach it, which is why this block could not
93
+ * follow a dark-mode switch without rendering everything twice and reading the
94
+ * colours back out (stacksjs/stx#2015). With classes, light and dark are one
95
+ * piece of markup under two sets of custom properties.
106
96
  *
107
- * Returns null when the two renders do not align or nothing is coloured, so a
108
- * surprise from the engine degrades to the single-palette path rather than to
109
- * an unstyled block.
97
+ * Works in a browser as well as on a server, so a block whose code changes
98
+ * after the page has loaded can be highlighted again where it is.
110
99
  */
111
- async function dualTheme(
112
- highlighter: TSHighlighter,
100
+ export async function highlightToHtml(
113
101
  code: string,
114
- language: string,
115
- ): Promise<{ html: string, css: string } | null> {
116
- let light: { html?: string, css?: string }
117
- let dark: { html?: string, css?: string }
118
- try {
119
- light = await highlighter.highlight(code, language, { theme: LIGHT }) as { html?: string, css?: string }
120
- dark = await highlighter.highlight(code, language, { theme: DARK }) as { html?: string, css?: string }
121
- }
122
- catch {
123
- return null
124
- }
125
-
126
- const lightHtml = light?.html
127
- const darkHtml = dark?.html
128
- if (!lightHtml || !darkHtml)
102
+ options: { language?: string, theme?: 'light' | 'dark' | 'auto', lineNumbers?: boolean } = {},
103
+ ): Promise<string | null> {
104
+ const highlighter = await loadHighlighter()
105
+ if (!highlighter)
129
106
  return null
130
107
 
131
- const lightStyles = tokenStyles(lightHtml)
132
- const darkStyles = tokenStyles(darkHtml)
133
- if (lightStyles.length === 0 || lightStyles.length !== darkStyles.length)
134
- return null
108
+ let lines: Array<{ tokens: Array<{ type: string, content: string }> }>
109
+ try {
110
+ const grammar = await highlighter.resolveGrammar(options.language ?? 'typescript')
111
+ if (!grammar)
112
+ return null
135
113
 
136
- // First occurrence wins: a token class maps to one scope, so every span
137
- // carrying it resolves to the same colour in a given theme.
138
- const palette = new Map<string, { light: string, dark: string }>()
139
- for (let i = 0; i < lightStyles.length; i++) {
140
- const [cls, lightStyle] = lightStyles[i]!
141
- const darkStyle = darkStyles[i]![1]
142
- if (!cls || !lightStyle || !darkStyle || palette.has(cls) || !selectorSafe(cls))
143
- continue
144
- palette.set(cls, { light: lightStyle, dark: darkStyle })
114
+ lines = new highlighter.Tokenizer(grammar).tokenizeLinesFrom(code.replace(/\r\n?/g, '\n').split('\n')).lines
145
115
  }
146
- if (palette.size === 0)
116
+ catch {
147
117
  return null
148
-
149
- const rules: string[] = []
150
- const darkRules: string[] = []
151
- for (const [cls, { light: l, dark: d }] of palette) {
152
- rules.push(`.syntax .token.${cls} { ${l} }`)
153
- darkRules.push(`.syntax .token.${cls} { ${d} }`)
154
118
  }
155
119
 
156
- /*
157
- * The PANEL as well as the tokens. `.syntax` carries
158
- * `background-color: #ffffff` from the light stylesheet and the issue names
159
- * it directly - dark token colours on a white panel is the same bug in
160
- * reverse, and it is the half a reader notices first. Taken from the engine's
161
- * own dark stylesheet rather than from the theme's `colors` map, for the same
162
- * reason the token colours are: its resolution stays authoritative.
163
- */
164
- const darkPanel = /\.syntax\s*\{([^}]*)\}/.exec(dark.css ?? '')?.[1]
165
- const panelDecls = darkPanel
166
- ? darkPanel.split(';').map(d => d.trim()).filter(d => /^(?:background-color|color)\s*:/.test(d)).join('; ')
167
- : ''
168
- if (panelDecls)
169
- darkRules.unshift(`.syntax { ${panelDecls} }`)
120
+ const html = lines.map((line) => {
121
+ let out = ''
122
+ let run = ''
123
+ let runClass = ''
124
+
125
+ const flush = (): void => {
126
+ if (run !== '')
127
+ out += runClass === '' ? escapeHtml(run) : `<span class="tok-${runClass}">${escapeHtml(run)}</span>`
128
+ run = ''
129
+ }
130
+
131
+ // Neighbours of one class are one span.
132
+ for (const token of line.tokens) {
133
+ const cls = highlighter.tokenClass(token.type)
134
+ if (cls !== runClass) {
135
+ flush()
136
+ runClass = cls
137
+ }
138
+ run += token.content
139
+ }
140
+ flush()
141
+
142
+ return `<span class="line">${out}</span>`
143
+ }).join('\n')
144
+
145
+ const attributes = [
146
+ 'class="syntax"',
147
+ options.theme === 'light' || options.theme === 'dark' ? `data-syntax-theme="${options.theme}"` : '',
148
+ options.lineNumbers ? 'data-line-numbers' : '',
149
+ ].filter(Boolean).join(' ')
150
+
151
+ return `<pre ${attributes}><code>${html}</code></pre>`
152
+ }
170
153
 
171
- /*
172
- * Both switches, matching how the rest of the library does dark mode: the
173
- * media query for a viewer following their OS, and `.dark` for an app with a
174
- * manual toggle. The media query is guarded against a page pinned to light,
175
- * or an app that chose light on a dark OS would get dark code.
176
- */
177
- const css = [
178
- light.css ?? '',
179
- rules.join('\n'),
180
- `@media (prefers-color-scheme: dark) {\n:root:not(.light) ${darkRules.join('\n:root:not(.light) ')}\n}`,
181
- darkRules.map(rule => `.dark ${rule}`).join('\n'),
182
- ].filter(Boolean).join('\n')
154
+ /** The stylesheet for one result: every palette for `auto`, one for a pinned theme. */
155
+ function cssFor(theme: 'light' | 'dark' | 'auto'): string {
156
+ if (theme === 'auto')
157
+ return codeBlockCss()
183
158
 
184
- // Stripped, or the inline colour beats every rule above. Same reason as
185
- // STYLED_SPAN for not writing the class literal into the pattern.
186
- const html = lightHtml.replace(
187
- /(<span class="[^"]*")[^>]*?\s+style="[^"]*"/g,
188
- (whole, open: string) => (TOKEN_CLASS.test(/class="([^"]*)"/.exec(open)?.[1] ?? '') ? open : whole),
189
- )
159
+ const palette = theme === 'dark' ? SYNTAX_DARK : SYNTAX_LIGHT
190
160
 
191
- return { html, css }
161
+ return [
162
+ `[data-syntax-theme="${theme}"] {\n${syntaxVariables(palette)}\n}`,
163
+ syntaxTokenRules(),
164
+ syntaxPanelCss(),
165
+ ].join('\n')
192
166
  }
193
167
 
194
168
  /**
@@ -201,96 +175,25 @@ export async function highlight(
201
175
  const {
202
176
  theme = 'auto',
203
177
  language = 'typescript',
204
- lineNumbers: _lineNumbers = false,
205
- wrapLines: _wrapLines = true,
178
+ lineNumbers = false,
206
179
  } = options
207
180
 
208
- /*
209
- * Resolved before anything can return, so every exit reports the theme that
210
- * was asked for.
211
- *
212
- * It used to be computed after the load guard below, which returned a
213
- * hardcoded `github-light` on that path: a caller asking for dark and getting
214
- * the plain-text floor was told it got light, which is a second untruth on
215
- * top of the first (stacksjs/stx#2015).
216
- *
217
- * `auto` emits BOTH palettes and lets CSS choose, rather than probing
218
- * matchMedia. `highlight()` runs in `<script server>`, where
219
- * `globalThis.matchMedia` does not exist and a viewer's preference is not
220
- * knowable at render time anyway, so selecting a palette in JS cannot answer
221
- * the question at all - it just always answered "light".
222
- *
223
- * `renderDualTheme` is the shape the engine offers for this and does not
224
- * solve it: its CSS styles the `.syntax` CONTAINER for both modes but leaves
225
- * every token colour where the highlighter puts it, in an inline `style`
226
- * attribute that no stylesheet rule can override. That would give a dark
227
- * panel with light-theme token colours - the unreadable half of the bug,
228
- * kept. There are no per-token-type rules in its output to override either,
229
- * in single or dual mode.
230
- *
231
- * So `dualTheme()` below renders the same code under each palette, reads
232
- * back the colours the highlighter itself assigned, and emits them as rules
233
- * keyed on the token classes already present on the spans - with the inline
234
- * styles stripped so the rules win. Reading them back rather than resolving
235
- * the themes' TextMate scopes keeps the engine's own resolution authoritative
236
- * instead of reimplementing it.
237
- */
238
- const effectiveTheme = theme === 'auto'
239
- ? (globalThis.matchMedia?.('(prefers-color-scheme: dark)').matches ? 'github-dark' : 'github-light')
240
- : theme === 'dark' ? DARK : LIGHT
241
-
242
- // A highlighter that cannot load must not take the code with it. Highlighting
243
- // is decoration; the code is the content. ts-syntax-highlighter@0.2.17 ships a
244
- // bundle that imports `bunfig` while declaring no dependencies, so it throws
245
- // outright wherever that package is not reachable -- and a <script server>
246
- // that throws renders the whole component as nothing, with no error logged.
247
- // Escaped plain text is the floor.
248
- let highlighter: TSHighlighter
249
- try {
250
- highlighter = await getHighlighter()
251
- }
252
- catch {
253
- return { html: plainCodeHtml(code), css: '', language, theme: effectiveTheme }
254
- }
181
+ const html = await highlightToHtml(code, { language, theme, lineNumbers })
255
182
 
256
- /*
257
- * `auto` means both palettes, chosen by CSS. Falls through to the single
258
- * palette below if the engine's two renders do not line up, so a surprise
259
- * degrades to today's behaviour rather than to an unstyled block.
260
- */
261
- if (theme === 'auto') {
262
- const dual = await dualTheme(highlighter, code, language)
263
- if (dual)
264
- return { html: dual.html, css: dual.css, language, theme: 'auto' }
265
- }
266
-
267
- // ts-syntax-highlighter returns { html, css, tokens, ansi }. This read the
268
- // whole result as if it were the HTML string, and the `String(...)` meant to
269
- // be defensive turned the object into the literal text [object Object] --
270
- // which is what every CodeBlock rendered, instead of the code. A fallback
271
- // that stringifies anything cannot tell a wrong shape from a right one.
272
- let result: unknown
273
- try {
274
- // The theme belongs here. It was resolved above and then dropped, so every
275
- // render came from the instance's own `github-light` and every CodeBlock in
276
- // every app was light whatever it asked for, while the returned `theme`
277
- // field reported the request. `RenderOptions.theme` overrides the instance
278
- // per call, which is what keeps one shared highlighter usable for both.
279
- result = await highlighter.highlight(code, language, { theme: effectiveTheme })
280
- }
281
- catch {
282
- return { html: plainCodeHtml(code), css: '', language, theme: effectiveTheme }
183
+ if (html === null) {
184
+ /*
185
+ * The plain-text floor. It reports a concrete palette even for `auto`,
186
+ * because `auto` means "both palettes shipped" and here neither did
187
+ * (stacksjs/stx#2015): the field says what was emitted, not what was asked.
188
+ */
189
+ return { html: plainCodeHtml(code), css: '', language, theme: theme === 'dark' ? DARK : LIGHT }
283
190
  }
284
- const shaped = result as { html?: string, css?: string } | string | null
285
- const highlighted = typeof shaped === 'string'
286
- ? { html: shaped, css: '' }
287
- : { html: shaped?.html ?? plainCodeHtml(code), css: shaped?.css ?? '' }
288
191
 
289
192
  return {
290
- html: highlighted.html,
291
- css: highlighted.css,
193
+ html,
194
+ css: cssFor(theme),
292
195
  language,
293
- theme: effectiveTheme,
196
+ theme: theme === 'auto' ? 'auto' : theme === 'dark' ? DARK : LIGHT,
294
197
  }
295
198
  }
296
199
 
@@ -0,0 +1,144 @@
1
+ /**
2
+ * The colours of code, as CSS custom properties.
3
+ *
4
+ * Two places draw highlighted code - `<CodeBlock>` and `<CodeEditor>` - and
5
+ * both write a class on each token (`tok-keyword`) rather than a colour. What a
6
+ * keyword looks like is decided here, once, as `--stx-syntax-keyword`, so an
7
+ * app re-themes both by setting a variable, and light and dark are the same
8
+ * markup under a different set of values.
9
+ *
10
+ * The defaults are the highlighter's GitHub pair. `test/syntax-theme.test.ts`
11
+ * holds them to `ts-syntax-highlighter`'s own themes, so they cannot drift from
12
+ * what the highlighter would have written inline.
13
+ *
14
+ * A component's `<style>` block is extracted from its source before anything
15
+ * is interpolated, so the two components carry this CSS as literal text rather
16
+ * than importing it. The same test holds those copies to this file.
17
+ */
18
+
19
+ /** The token classes, in the order the rules are written. */
20
+ export const SYNTAX_TOKENS: readonly string[] = [
21
+ 'keyword',
22
+ 'string',
23
+ 'comment',
24
+ 'numeric',
25
+ 'constant',
26
+ 'function',
27
+ 'operator',
28
+ 'punctuation',
29
+ 'type',
30
+ 'variable',
31
+ 'tag',
32
+ 'attribute',
33
+ ]
34
+
35
+ export const SYNTAX_LIGHT: Readonly<Record<string, string>> = {
36
+ background: '#ffffff',
37
+ foreground: '#24292f',
38
+ keyword: '#cf222e',
39
+ string: '#0a3069',
40
+ comment: '#6e7781',
41
+ numeric: '#0550ae',
42
+ constant: '#0550ae',
43
+ function: '#8250df',
44
+ operator: '#cf222e',
45
+ punctuation: '#24292f',
46
+ type: '#953800',
47
+ variable: '#953800',
48
+ tag: '#116329',
49
+ attribute: '#0550ae',
50
+ }
51
+
52
+ export const SYNTAX_DARK: Readonly<Record<string, string>> = {
53
+ background: '#0d1117',
54
+ foreground: '#c9d1d9',
55
+ keyword: '#ff7b72',
56
+ string: '#a5d6ff',
57
+ comment: '#8b949e',
58
+ numeric: '#79c0ff',
59
+ constant: '#79c0ff',
60
+ function: '#d2a8ff',
61
+ operator: '#ff7b72',
62
+ punctuation: '#c9d1d9',
63
+ type: '#ffa657',
64
+ variable: '#ffa657',
65
+ tag: '#7ee787',
66
+ attribute: '#79c0ff',
67
+ }
68
+
69
+ /** The properties a palette sets: the panel's two, then one per token. */
70
+ export const SYNTAX_PROPERTIES: readonly string[] = ['background', 'foreground', ...SYNTAX_TOKENS]
71
+
72
+ /** `--stx-syntax-keyword: #cf222e;` for every property, one per line. */
73
+ export function syntaxVariables(palette: Readonly<Record<string, string>>, indent = ' '): string {
74
+ return SYNTAX_PROPERTIES.map(name => `${indent}--stx-syntax-${name}: ${palette[name]};`).join('\n')
75
+ }
76
+
77
+ /** The rules that colour a token class from its variable. */
78
+ export function syntaxTokenRules(): string {
79
+ return SYNTAX_TOKENS
80
+ .map(name => `.tok-${name} { color: var(--stx-syntax-${name}); }`)
81
+ .concat('.tok-comment { font-style: italic; }')
82
+ .join('\n')
83
+ }
84
+
85
+ /**
86
+ * The whole sheet: light values, dark values for a reader following their
87
+ * system and for an app with a `.dark` toggle, an explicit theme on the
88
+ * element itself, and the token rules.
89
+ *
90
+ * `:where()` throughout, so none of it outranks a single class an app writes.
91
+ */
92
+ export function syntaxThemeCss(): string {
93
+ const light = syntaxVariables(SYNTAX_LIGHT)
94
+ const dark = syntaxVariables(SYNTAX_DARK)
95
+
96
+ return [
97
+ `:where(:root) {\n${light}\n}`,
98
+ `@media (prefers-color-scheme: dark) {\n:where(:root:not(.light)) {\n${dark}\n}\n}`,
99
+ `:where(.dark) {\n${dark}\n}`,
100
+ `:where([data-syntax-theme="light"]) {\n${light}\n}`,
101
+ `:where([data-syntax-theme="dark"]) {\n${dark}\n}`,
102
+ syntaxTokenRules(),
103
+ ].join('\n')
104
+ }
105
+
106
+ /**
107
+ * The block a `<CodeBlock>` draws its code in.
108
+ *
109
+ * Line numbers are a counter, not text, so selecting a numbered block and
110
+ * copying it gives the code and not `1const a = 1`.
111
+ */
112
+ export function syntaxPanelCss(): string {
113
+ return [
114
+ '.syntax {',
115
+ ' margin: 0;',
116
+ ' padding: 1rem;',
117
+ ' overflow-x: auto;',
118
+ ' border-radius: 0.375rem;',
119
+ ' background-color: var(--stx-syntax-background);',
120
+ ' color: var(--stx-syntax-foreground);',
121
+ ' font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace;',
122
+ ' font-size: 0.875rem;',
123
+ ' line-height: 1.5;',
124
+ ' tab-size: 2;',
125
+ '}',
126
+ '.syntax code { display: block; font-family: inherit; }',
127
+ '.syntax[data-line-numbers] { counter-reset: stx-syntax-line; }',
128
+ '.syntax[data-line-numbers] .line::before {',
129
+ ' counter-increment: stx-syntax-line;',
130
+ ' content: counter(stx-syntax-line);',
131
+ ' display: inline-block;',
132
+ ' width: 2.5em;',
133
+ ' margin-right: 1em;',
134
+ ' text-align: right;',
135
+ ' opacity: 0.5;',
136
+ ' user-select: none;',
137
+ '}',
138
+ ].join('\n')
139
+ }
140
+
141
+ /** Everything `<CodeBlock>` needs: the palettes, the token rules and the panel. */
142
+ export function codeBlockCss(): string {
143
+ return `${syntaxThemeCss()}\n${syntaxPanelCss()}`
144
+ }