@bigpixelrocket/uiok 0.6.0 → 0.7.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.
Files changed (49) hide show
  1. package/CHANGELOG.md +37 -1
  2. package/dist/button/TextLink.d.ts +14 -2
  3. package/dist/button/TextLink.js +13 -3
  4. package/dist/dialog/SectionedDialog.js +2 -1
  5. package/dist/field/FieldLayout.d.ts +3 -2
  6. package/dist/field/FieldLayout.js +8 -3
  7. package/dist/frame/PageParts.js +1 -1
  8. package/dist/frame/SideBySide.d.ts +2 -1
  9. package/dist/frame/SideBySide.js +16 -4
  10. package/dist/frame/Tree.d.ts +19 -6
  11. package/dist/frame/Tree.js +20 -8
  12. package/dist/frame/frame.css +8 -0
  13. package/dist/keychord/KeyChord.d.ts +4 -3
  14. package/dist/keychord/KeyChord.js +10 -6
  15. package/dist/legend/legend.css +6 -10
  16. package/dist/listing/Listing.d.ts +19 -1
  17. package/dist/listing/Listing.js +43 -4
  18. package/dist/listing/listing.css +41 -2
  19. package/dist/menu/Menu.js +2 -2
  20. package/dist/menu/menu.css +4 -6
  21. package/dist/palette/Palette.d.ts +3 -1
  22. package/dist/palette/Palette.js +14 -2
  23. package/dist/palette/PaletteRows.d.ts +17 -12
  24. package/dist/palette/PaletteRows.js +17 -15
  25. package/dist/pane/Pane.d.ts +8 -0
  26. package/dist/pane/Pane.js +26 -6
  27. package/dist/pane/PaneTabs.js +7 -3
  28. package/dist/pane/panetabs.css +14 -2
  29. package/dist/styles.css +34 -11
  30. package/dist/surface/surface.css +10 -0
  31. package/dist/terminal/TerminalMenu.js +1 -1
  32. package/dist/terminal/terminal.css +3 -2
  33. package/dist/themes/tokens.js +5 -2
  34. package/dist/tokens.css +4 -0
  35. package/dist/viewer/HexView.js +17 -8
  36. package/dist/viewer/ImageView.js +5 -3
  37. package/dist/viewer/PdfView.d.ts +8 -1
  38. package/dist/viewer/PdfView.js +27 -2
  39. package/dist/viewer/SyntaxHighlighter.d.ts +3 -2
  40. package/dist/viewer/SyntaxHighlighter.js +7 -2
  41. package/dist/viewer/SyntaxLanguage.logic.d.ts +5 -0
  42. package/dist/viewer/SyntaxLanguage.logic.js +17 -3
  43. package/dist/viewer/SyntaxService.d.ts +3 -1
  44. package/dist/viewer/SyntaxService.js +8 -1
  45. package/dist/viewer/TextView.js +14 -7
  46. package/dist/viewer/ViewerClipboard.js +17 -6
  47. package/dist/viewer/ViewerFrame.logic.js +4 -1
  48. package/dist/viewer/types.d.ts +3 -2
  49. package/package.json +1 -1
@@ -114,14 +114,16 @@ function ImageView({ info, onFallback }) {
114
114
  zoomTo(() => 1);
115
115
  }, [zoomTo]);
116
116
  // The zoom chords and arrows answer anywhere in the viewer, or with nothing
117
- // focused; a control of the page beside it keeps its own keys.
117
+ // focused; a control of the page beside it keeps its own keys, and a key a
118
+ // control in the viewer already handled (the mode switch's arrows) does
119
+ // nothing more.
118
120
  useEffect(() => {
119
121
  const onKeyDown = (event) => {
120
- if (!isViewerEvent(event))
122
+ if (event.defaultPrevented || !isViewerEvent(event))
121
123
  return;
122
124
  const command = event.metaKey && !event.ctrlKey && !event.altKey;
123
125
  const plain = !event.metaKey && !event.ctrlKey && !event.altKey && !event.shiftKey;
124
- const arrow = ARROWS[event.key];
126
+ const arrow = Object.hasOwn(ARROWS, event.key) ? ARROWS[event.key] : undefined;
125
127
  if (command && (event.code === 'Equal' || event.key === '+'))
126
128
  zoomTo((s) => stepScale(s, 1));
127
129
  else if (command && event.code === 'Minus')
@@ -5,8 +5,15 @@ import type { ViewerViewProps } from './ViewerViews.js';
5
5
  * Where the PDF view loads the document: the file's media URL with its name
6
6
  * as a last segment, which Chromium's PDF viewer shows as the toolbar's
7
7
  * title (a document's own title metadata wins). The reader's media URL must
8
- * therefore serve the file whatever segment follows it (`ViewerFileInfo`'s
8
+ * therefore serve the file whatever segment follows it, and carry no query
9
+ * or fragment, which the segment would land in (`ViewerFileInfo`'s
9
10
  * `mediaUrl`); a `blob:` URL cannot, since its path is fixed.
11
+ *
12
+ * The name stays one segment below the media URL: `encodeURIComponent`
13
+ * escapes `/`, `?`, and `#`, and a name that is empty or a dot segment is
14
+ * replaced, since `.` and `..` are left as they are, as is a name
15
+ * `encodeURIComponent` refuses. A `%2e` in a name is escaped to `%252e`, so
16
+ * it is no dot segment either.
10
17
  */
11
18
  export declare function pdfDocumentUrl(info: ViewerFileInfo): string;
12
19
  /**
@@ -1,13 +1,38 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
+ /**
3
+ * The last segment for a file whose name is empty or a dot segment (`.` or
4
+ * `..`), which the URL parser would resolve to the media URL's parent, or
5
+ * cannot be encoded (a lone UTF-16 surrogate); it only feeds the PDF
6
+ * viewer's title.
7
+ */
8
+ const UNNAMED_SEGMENT = 'document.pdf';
2
9
  /**
3
10
  * Where the PDF view loads the document: the file's media URL with its name
4
11
  * as a last segment, which Chromium's PDF viewer shows as the toolbar's
5
12
  * title (a document's own title metadata wins). The reader's media URL must
6
- * therefore serve the file whatever segment follows it (`ViewerFileInfo`'s
13
+ * therefore serve the file whatever segment follows it, and carry no query
14
+ * or fragment, which the segment would land in (`ViewerFileInfo`'s
7
15
  * `mediaUrl`); a `blob:` URL cannot, since its path is fixed.
16
+ *
17
+ * The name stays one segment below the media URL: `encodeURIComponent`
18
+ * escapes `/`, `?`, and `#`, and a name that is empty or a dot segment is
19
+ * replaced, since `.` and `..` are left as they are, as is a name
20
+ * `encodeURIComponent` refuses. A `%2e` in a name is escaped to `%252e`, so
21
+ * it is no dot segment either.
8
22
  */
9
23
  export function pdfDocumentUrl(info) {
10
- return `${info.mediaUrl}/${encodeURIComponent(info.name)}`;
24
+ const { name } = info;
25
+ let segment = UNNAMED_SEGMENT;
26
+ if (name !== '' && name !== '.' && name !== '..') {
27
+ try {
28
+ segment = encodeURIComponent(name);
29
+ }
30
+ catch {
31
+ // A name with a lone surrogate, which only some file systems allow,
32
+ // has no UTF-8 form; the frame still opens, under the fallback name.
33
+ }
34
+ }
35
+ return `${info.mediaUrl}/${segment}`;
11
36
  }
12
37
  /**
13
38
  * The PDF view: the browser's built-in PDF viewer, in a frame loaded from
@@ -14,7 +14,7 @@
14
14
  */
15
15
  import { type LanguageRegistration } from '@shikijs/primitive';
16
16
  import { type StateStack } from '@shikijs/primitive/textmate';
17
- import type { SyntaxLanguageId } from './SyntaxLanguage.logic.js';
17
+ import { type SyntaxLanguageId } from './SyntaxLanguage.logic.js';
18
18
  import type { LineTokenizer } from './SyntaxSession.logic.js';
19
19
  type GrammarModule = Promise<{
20
20
  readonly default: LanguageRegistration[];
@@ -23,7 +23,8 @@ type GrammarModule = Promise<{
23
23
  export declare const SYNTAX_GRAMMARS: Readonly<Record<SyntaxLanguageId, () => GrammarModule>>;
24
24
  /**
25
25
  * Loads `language`'s grammar (and the grammars it embeds) and the theme,
26
- * and returns a tokenizer over them. Rejects when a chunk fails to load.
26
+ * and returns a tokenizer over them. Rejects when a chunk fails to load, or
27
+ * `language` names no shipped grammar (it arrives from another thread).
27
28
  */
28
29
  export declare function loadLineTokenizer(language: SyntaxLanguageId): Promise<LineTokenizer<StateStack>>;
29
30
  export {};
@@ -15,6 +15,7 @@
15
15
  import { createJavaScriptRegexEngine } from '@shikijs/engine-javascript';
16
16
  import { createShikiPrimitiveAsync } from '@shikijs/primitive';
17
17
  import { EncodedTokenMetadata, INITIAL } from '@shikijs/primitive/textmate';
18
+ import { isSyntaxLanguage } from './SyntaxLanguage.logic.js';
18
19
  /** Each shipped grammar, as a chunk of its own that loads on first use. */
19
20
  export const SYNTAX_GRAMMARS = {
20
21
  apache: () => import('@shikijs/langs/apache'),
@@ -86,7 +87,8 @@ const BOLD = 2;
86
87
  const STRIKETHROUGH = 8;
87
88
  /** The style for a theme color and font style; the text's own color stays unset. */
88
89
  function styleFor(color, fontStyle) {
89
- const role = color === undefined ? undefined : MOCHA_ROLES[color.toLowerCase()];
90
+ const key = color?.toLowerCase();
91
+ const role = key !== undefined && Object.hasOwn(MOCHA_ROLES, key) ? MOCHA_ROLES[key] : undefined;
90
92
  return {
91
93
  color: role === undefined ? null : `var(--syntax-${role})`,
92
94
  italic: (fontStyle & ITALIC) !== 0,
@@ -98,9 +100,12 @@ function styleFor(color, fontStyle) {
98
100
  const LINE_TIME_LIMIT_MS = 500;
99
101
  /**
100
102
  * Loads `language`'s grammar (and the grammars it embeds) and the theme,
101
- * and returns a tokenizer over them. Rejects when a chunk fails to load.
103
+ * and returns a tokenizer over them. Rejects when a chunk fails to load, or
104
+ * `language` names no shipped grammar (it arrives from another thread).
102
105
  */
103
106
  export async function loadLineTokenizer(language) {
107
+ if (!isSyntaxLanguage(language))
108
+ throw new Error('No grammar ships for this language');
104
109
  const shiki = await createShikiPrimitiveAsync({
105
110
  engine: createJavaScriptRegexEngine(),
106
111
  themes: [import('@shikijs/themes/catppuccin-mocha')],
@@ -58,6 +58,11 @@ export declare const SYNTAX_LANGUAGES: {
58
58
  };
59
59
  /** A shipped grammar's id. */
60
60
  export type SyntaxLanguageId = keyof typeof SYNTAX_LANGUAGES;
61
+ /**
62
+ * Whether `value` is a shipped language's id. Checks own keys only, so a
63
+ * name such as `constructor` or `__proto__` is no language.
64
+ */
65
+ export declare function isSyntaxLanguage(value: unknown): value is SyntaxLanguageId;
61
66
  /**
62
67
  * Files past this size open as plain text. Highlighting costs the same per
63
68
  * screen at any size, since only the rows in view are tokenized, so this is
@@ -54,6 +54,20 @@ export const SYNTAX_LANGUAGES = {
54
54
  xml: 'XML',
55
55
  yaml: 'YAML'
56
56
  };
57
+ /**
58
+ * Whether `value` is a shipped language's id. Checks own keys only, so a
59
+ * name such as `constructor` or `__proto__` is no language.
60
+ */
61
+ export function isSyntaxLanguage(value) {
62
+ return typeof value === 'string' && Object.hasOwn(SYNTAX_LANGUAGES, value);
63
+ }
64
+ /**
65
+ * `table`'s entry for `key`, an untrusted file name, extension, or
66
+ * interpreter; own keys only, so `constructor` or `__proto__` finds nothing.
67
+ */
68
+ function ownEntry(table, key) {
69
+ return Object.hasOwn(table, key) ? table[key] : undefined;
70
+ }
57
71
  /**
58
72
  * Files past this size open as plain text. Highlighting costs the same per
59
73
  * screen at any size, since only the rows in view are tokenized, so this is
@@ -231,7 +245,7 @@ export function languageFromShebang(firstLine) {
231
245
  if (command === 'env') {
232
246
  command = words.slice(1).find((word) => !word.startsWith('-') && !word.includes('=')) ?? '';
233
247
  }
234
- return INTERPRETERS[command.replace(/[\d.]+$/u, '')] ?? null;
248
+ return ownEntry(INTERPRETERS, command.replace(/[\d.]+$/u, '')) ?? null;
235
249
  }
236
250
  /**
237
251
  * The language of a file named `name` whose first line is `firstLine`: a
@@ -241,7 +255,7 @@ export function languageFromShebang(firstLine) {
241
255
  */
242
256
  export function languageFor(name, firstLine) {
243
257
  const lower = name.toLowerCase();
244
- const known = FILE_NAMES[lower];
258
+ const known = ownEntry(FILE_NAMES, lower);
245
259
  if (known)
246
260
  return known;
247
261
  if (lower.endsWith('.blade.php'))
@@ -251,7 +265,7 @@ export function languageFor(name, firstLine) {
251
265
  if (lower.startsWith('.env.'))
252
266
  return 'dotenv';
253
267
  const dot = lower.lastIndexOf('.');
254
- const byExtension = dot > 0 ? EXTENSIONS[lower.slice(dot + 1)] : undefined;
268
+ const byExtension = dot > 0 ? ownEntry(EXTENSIONS, lower.slice(dot + 1)) : undefined;
255
269
  return byExtension ?? languageFromShebang(firstLine);
256
270
  }
257
271
  /**
@@ -5,7 +5,7 @@
5
5
  * rows by their starting bytes; the worker answers with each row's tokens.
6
6
  * Grammar states never leave the worker.
7
7
  */
8
- import type { SyntaxLanguageId } from './SyntaxLanguage.logic.js';
8
+ import { type SyntaxLanguageId } from './SyntaxLanguage.logic.js';
9
9
  import { type LineTokenizer, type RowHighlight, type SyntaxStyle } from './SyntaxSession.logic.js';
10
10
  import type { TextLayout } from './TextEncoding.logic.js';
11
11
  import type { RowStart } from './TextRows.logic.js';
@@ -70,6 +70,8 @@ export declare const SyntaxWorkerContext: import("react").Context<SyntaxWorkerFa
70
70
  * Answers the page's requests in `scope`, tokenizing with what `load`
71
71
  * returns for the language `open` names. Requests other than `open` wait
72
72
  * for the page to have seen `ready`, so none arrive before a session exists.
73
+ * An `open` naming no shipped language, or whose load throws, is answered
74
+ * with `failed`.
73
75
  */
74
76
  export declare function serveSyntax<State>(scope: SyntaxScope, load: (language: SyntaxLanguageId) => Promise<LineTokenizer<State>>): void;
75
77
  export {};
@@ -6,6 +6,7 @@
6
6
  * Grammar states never leave the worker.
7
7
  */
8
8
  import { createContext } from 'react';
9
+ import { isSyntaxLanguage } from './SyntaxLanguage.logic.js';
9
10
  import { createSyntaxSession } from './SyntaxSession.logic.js';
10
11
  /**
11
12
  * Starts the viewer's own highlighting worker: Shiki on its JavaScript
@@ -26,13 +27,19 @@ export const SyntaxWorkerContext = createContext(openSyntaxWorker);
26
27
  * Answers the page's requests in `scope`, tokenizing with what `load`
27
28
  * returns for the language `open` names. Requests other than `open` wait
28
29
  * for the page to have seen `ready`, so none arrive before a session exists.
30
+ * An `open` naming no shipped language, or whose load throws, is answered
31
+ * with `failed`.
29
32
  */
30
33
  export function serveSyntax(scope, load) {
31
34
  let session = null;
32
35
  scope.onmessage = ({ data }) => {
33
36
  switch (data.type) {
34
37
  case 'open':
35
- load(data.language).then((tokenizer) => {
38
+ if (!isSyntaxLanguage(data.language)) {
39
+ scope.postMessage({ type: 'failed' });
40
+ return;
41
+ }
42
+ new Promise((resolve) => resolve(load(data.language))).then((tokenizer) => {
36
43
  session = createSyntaxSession(tokenizer, data.maxLineBytes);
37
44
  scope.postMessage({ type: 'ready', styles: tokenizer.styles });
38
45
  }, () => scope.postMessage({ type: 'failed' }));
@@ -66,6 +66,7 @@ function TextView({ reader, info }) {
66
66
  const tokenStyles = useMemo(() => syntax.styles.map(cssFor), [syntax.styles]);
67
67
  const rowsElement = useRef(null);
68
68
  const wheelRemainder = useRef(0);
69
+ // The drag in progress, which owns its window listeners and scroll timer.
69
70
  const drag = useRef(null);
70
71
  const shown = useRef([]);
71
72
  const contentStart = layout?.contentStart ?? 0;
@@ -357,15 +358,17 @@ function TextView({ reader, info }) {
357
358
  useEffect(() => {
358
359
  focusQuietly(rowsElement.current);
359
360
  }, []);
361
+ /** Ends the drag in progress, if any: its scroll timer and window listeners go with it. */
360
362
  const endDrag = useCallback(() => {
361
- if (drag.current?.timer)
362
- clearInterval(drag.current.timer);
363
+ drag.current?.stop();
363
364
  drag.current = null;
364
365
  }, []);
365
366
  useEffect(() => endDrag, [endDrag]);
366
367
  const onMouseDown = (event) => {
367
368
  if (event.button !== 0)
368
369
  return;
370
+ // A drag whose mouseup never came (released outside the window) ends here.
371
+ endDrag();
369
372
  // The page's own selection would cover only the rows in the DOM, so the
370
373
  // view keeps its own and the native one never starts.
371
374
  event.preventDefault();
@@ -393,7 +396,6 @@ function TextView({ reader, info }) {
393
396
  y: event.clientY,
394
397
  timer: null
395
398
  };
396
- drag.current = state;
397
399
  const extend = (clientX, clientY) => {
398
400
  const focus = pointAt(clientX, clientY);
399
401
  if (focus)
@@ -416,10 +418,15 @@ function TextView({ reader, info }) {
416
418
  state.timer = null;
417
419
  }
418
420
  };
419
- const onUp = () => {
420
- window.removeEventListener('mousemove', onMove);
421
- window.removeEventListener('mouseup', onUp);
422
- endDrag();
421
+ const onUp = () => endDrag();
422
+ drag.current = {
423
+ stop: () => {
424
+ if (state.timer !== null)
425
+ clearInterval(state.timer);
426
+ state.timer = null;
427
+ window.removeEventListener('mousemove', onMove);
428
+ window.removeEventListener('mouseup', onUp);
429
+ }
423
430
  };
424
431
  window.addEventListener('mousemove', onMove);
425
432
  window.addEventListener('mouseup', onUp);
@@ -52,14 +52,25 @@ export function deliverCopy(copied, clipboardData, say, labels, current = () =>
52
52
  text = copied.pending;
53
53
  }
54
54
  // A read ends after the copy event, so the text goes to the clipboard on
55
- // its own; a failed read explains itself. A copy a newer one overtook, or
56
- // one of a view that has gone, writes and says nothing.
55
+ // its own; a failed read explains itself. A failed write says only that
56
+ // the copy failed, including on a page with no clipboard API (one served
57
+ // from an insecure origin), where the call itself throws. A copy a newer
58
+ // one overtook, or one of a view that has gone, writes and says nothing.
59
+ // The ticket is checked and the write started in one callback, so no
60
+ // newer copy can land between them and be overwritten by this one.
57
61
  text
58
- .then((value) => current()
59
- ? navigator.clipboard.writeText(value).then(() => true, () => {
62
+ .then((value) => {
63
+ if (!current())
64
+ return false;
65
+ try {
66
+ return navigator.clipboard.writeText(value).then(() => true, () => {
67
+ throw new Error(labels.copyFailed);
68
+ });
69
+ }
70
+ catch {
60
71
  throw new Error(labels.copyFailed);
61
- })
62
- : false)
72
+ }
73
+ })
63
74
  .then((written) => {
64
75
  if (written && current())
65
76
  say(null);
@@ -63,7 +63,10 @@ const FORMAT_NAMES = {
63
63
  };
64
64
  /** The content in a word or two: "Text", "PNG image", "QuickTime video", "PDF document". */
65
65
  export function contentLabel(content, labels) {
66
- const format = FORMAT_NAMES[content.mimeType];
66
+ // The media type is the file's, so a type such as `toString` names nothing.
67
+ const format = Object.hasOwn(FORMAT_NAMES, content.mimeType)
68
+ ? FORMAT_NAMES[content.mimeType]
69
+ : undefined;
67
70
  switch (content.kind) {
68
71
  case 'text':
69
72
  return labels.content.text;
@@ -50,8 +50,9 @@ export interface ViewerFileOrigin {
50
50
  * loadable for as long as this generation is open, mode switches included,
51
51
  * and retired by the reader after it (the PDF
52
52
  * view appends `/<name>` to it, so a PDF's URL must serve the file whatever
53
- * last segment follows, and frames it unsandboxed, so it must answer with
54
- * the PDF alone); `origin` is set only for a copy.
53
+ * last segment follows and carry no query or fragment, and frames it
54
+ * unsandboxed, so it must answer with the PDF alone); `origin` is set only
55
+ * for a copy.
55
56
  */
56
57
  export interface ViewerFileInfo {
57
58
  readonly generation: number;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bigpixelrocket/uiok",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "A React UI library with a retro look: themeable design tokens and accessible components.",
5
5
  "keywords": [
6
6
  "react",