@bigpixelrocket/uiok 0.3.0 → 0.4.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 (121) hide show
  1. package/CHANGELOG.md +23 -1
  2. package/dist/dialog/ConfirmDialog.d.ts +7 -1
  3. package/dist/dialog/ConfirmDialog.js +2 -2
  4. package/dist/dialog/ProgressDialog.d.ts +7 -1
  5. package/dist/dialog/ProgressDialog.js +2 -2
  6. package/dist/dialog/TypedNameDialog.d.ts +8 -0
  7. package/dist/field/Check.d.ts +9 -2
  8. package/dist/field/Check.js +5 -4
  9. package/dist/field/Controls.d.ts +198 -0
  10. package/dist/field/Controls.js +94 -0
  11. package/dist/field/FieldLayout.d.ts +126 -0
  12. package/dist/field/FieldLayout.js +89 -0
  13. package/dist/field/index.d.ts +9 -6
  14. package/dist/field/index.js +9 -6
  15. package/dist/frame/Dock.js +1 -1
  16. package/dist/frame/SidebarResizer.js +1 -1
  17. package/dist/frame/Tree.d.ts +9 -2
  18. package/dist/frame/Tree.js +29 -6
  19. package/dist/labels/UiokLabels.d.ts +3 -0
  20. package/dist/labels/UiokLabels.js +3 -1
  21. package/dist/labels/index.d.ts +1 -0
  22. package/dist/labels/index.js +1 -0
  23. package/dist/labels/viewer.d.ts +193 -0
  24. package/dist/labels/viewer.js +124 -0
  25. package/dist/listing/PaneMessage.d.ts +28 -0
  26. package/dist/listing/PaneMessage.js +12 -0
  27. package/dist/listing/index.d.ts +4 -2
  28. package/dist/listing/index.js +4 -2
  29. package/dist/styles.css +3 -0
  30. package/dist/surface/Card.d.ts +18 -0
  31. package/dist/surface/Card.js +10 -0
  32. package/dist/surface/Notice.d.ts +45 -0
  33. package/dist/surface/Notice.js +27 -0
  34. package/dist/surface/index.d.ts +5 -3
  35. package/dist/surface/index.js +5 -3
  36. package/dist/themes/themes.generated.css +1 -0
  37. package/dist/themes/tokens.js +4 -1
  38. package/dist/viewer/AudioView.d.ts +13 -0
  39. package/dist/viewer/AudioView.js +25 -0
  40. package/dist/viewer/HexJump.logic.d.ts +16 -0
  41. package/dist/viewer/HexJump.logic.js +27 -0
  42. package/dist/viewer/HexRows.logic.d.ts +55 -0
  43. package/dist/viewer/HexRows.logic.js +84 -0
  44. package/dist/viewer/HexSelection.logic.d.ts +57 -0
  45. package/dist/viewer/HexSelection.logic.js +68 -0
  46. package/dist/viewer/HexView.d.ts +10 -0
  47. package/dist/viewer/HexView.js +291 -0
  48. package/dist/viewer/HexViewport.logic.d.ts +61 -0
  49. package/dist/viewer/HexViewport.logic.js +79 -0
  50. package/dist/viewer/ImageView.d.ts +19 -0
  51. package/dist/viewer/ImageView.js +230 -0
  52. package/dist/viewer/ImageZoom.logic.d.ts +65 -0
  53. package/dist/viewer/ImageZoom.logic.js +119 -0
  54. package/dist/viewer/LatestRead.logic.d.ts +27 -0
  55. package/dist/viewer/LatestRead.logic.js +55 -0
  56. package/dist/viewer/MediaControls.d.ts +25 -0
  57. package/dist/viewer/MediaControls.js +183 -0
  58. package/dist/viewer/MediaPlayer.logic.d.ts +53 -0
  59. package/dist/viewer/MediaPlayer.logic.js +68 -0
  60. package/dist/viewer/PdfView.d.ts +23 -0
  61. package/dist/viewer/PdfView.js +25 -0
  62. package/dist/viewer/QuietFocus.d.ts +19 -0
  63. package/dist/viewer/QuietFocus.js +27 -0
  64. package/dist/viewer/ScaledScroll.logic.d.ts +30 -0
  65. package/dist/viewer/ScaledScroll.logic.js +28 -0
  66. package/dist/viewer/ScaledScrollbar.d.ts +19 -0
  67. package/dist/viewer/ScaledScrollbar.js +71 -0
  68. package/dist/viewer/SyntaxHighlighter.d.ts +29 -0
  69. package/dist/viewer/SyntaxHighlighter.js +144 -0
  70. package/dist/viewer/SyntaxLanguage.logic.d.ts +110 -0
  71. package/dist/viewer/SyntaxLanguage.logic.js +283 -0
  72. package/dist/viewer/SyntaxService.d.ts +75 -0
  73. package/dist/viewer/SyntaxService.js +49 -0
  74. package/dist/viewer/SyntaxSession.logic.d.ts +78 -0
  75. package/dist/viewer/SyntaxSession.logic.js +221 -0
  76. package/dist/viewer/SyntaxWorker.d.ts +6 -0
  77. package/dist/viewer/SyntaxWorker.js +8 -0
  78. package/dist/viewer/TextEncoding.logic.d.ts +35 -0
  79. package/dist/viewer/TextEncoding.logic.js +58 -0
  80. package/dist/viewer/TextRows.logic.d.ts +86 -0
  81. package/dist/viewer/TextRows.logic.js +241 -0
  82. package/dist/viewer/TextSelection.logic.d.ts +97 -0
  83. package/dist/viewer/TextSelection.logic.js +139 -0
  84. package/dist/viewer/TextView.d.ts +13 -0
  85. package/dist/viewer/TextView.js +448 -0
  86. package/dist/viewer/TextViewport.logic.d.ts +70 -0
  87. package/dist/viewer/TextViewport.logic.js +116 -0
  88. package/dist/viewer/VideoView.d.ts +18 -0
  89. package/dist/viewer/VideoView.js +53 -0
  90. package/dist/viewer/ViewerClipboard.d.ts +30 -0
  91. package/dist/viewer/ViewerClipboard.js +70 -0
  92. package/dist/viewer/ViewerFrame.logic.d.ts +61 -0
  93. package/dist/viewer/ViewerFrame.logic.js +130 -0
  94. package/dist/viewer/ViewerKeys.d.ts +16 -0
  95. package/dist/viewer/ViewerKeys.js +14 -0
  96. package/dist/viewer/ViewerScope.d.ts +12 -0
  97. package/dist/viewer/ViewerScope.js +22 -0
  98. package/dist/viewer/ViewerViews.d.ts +28 -0
  99. package/dist/viewer/ViewerViews.js +22 -0
  100. package/dist/viewer/ViewerWindow.d.ts +53 -0
  101. package/dist/viewer/ViewerWindow.js +219 -0
  102. package/dist/viewer/index.d.ts +12 -0
  103. package/dist/viewer/index.js +12 -0
  104. package/dist/viewer/types.d.ts +151 -0
  105. package/dist/viewer/types.js +26 -0
  106. package/dist/viewer/useElementHeight.d.ts +6 -0
  107. package/dist/viewer/useElementHeight.js +22 -0
  108. package/dist/viewer/useElementSize.d.ts +7 -0
  109. package/dist/viewer/useElementSize.js +24 -0
  110. package/dist/viewer/useEscapeToClear.d.ts +8 -0
  111. package/dist/viewer/useEscapeToClear.js +26 -0
  112. package/dist/viewer/useHexDocument.d.ts +41 -0
  113. package/dist/viewer/useHexDocument.js +144 -0
  114. package/dist/viewer/useMediaElement.d.ts +10 -0
  115. package/dist/viewer/useMediaElement.js +24 -0
  116. package/dist/viewer/useSyntaxHighlight.d.ts +24 -0
  117. package/dist/viewer/useSyntaxHighlight.js +133 -0
  118. package/dist/viewer/useTextDocument.d.ts +66 -0
  119. package/dist/viewer/useTextDocument.js +245 -0
  120. package/dist/viewer/viewer.css +645 -0
  121. package/package.json +7 -1
@@ -0,0 +1,144 @@
1
+ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
2
+ import { settleRead } from './types.js';
3
+ import { useLabels } from '../labels/UiokProvider.js';
4
+ import { copyRange, hexCopy, hexSelectionTooLarge, textCopy } from './HexSelection.logic.js';
5
+ import { clampTop, covers, endAfterRead, readWindowFor, rowsFrom } from './HexViewport.logic.js';
6
+ import { latestRead } from './LatestRead.logic.js';
7
+ const chunkOf = ({ offset, bytes, endOfFile }) => ({
8
+ offset,
9
+ bytes,
10
+ eof: endOfFile
11
+ });
12
+ /**
13
+ * Reads the window's file for the hex view: each screen comes from the bytes
14
+ * already held or from one bounded read around it, the newest target
15
+ * winning. A read about another generation of the file (one in flight across
16
+ * a reload) is dropped. A read that finds the file shrunk ends the view at
17
+ * the new end for as long as the view lives, pulling the screen back when it
18
+ * was past it; a read that lands wholly past the new end asks the file's size
19
+ * once, so the screen comes back in one more read however far it was.
20
+ */
21
+ export function useHexDocument(reader, info, view) {
22
+ const labels = useLabels();
23
+ const noAnswer = labels.viewer.noAnswer;
24
+ const [screen, setScreen] = useState(null);
25
+ const [failure, setFailure] = useState(null);
26
+ const chunk = useRef(null);
27
+ // Where the readable bytes end: the opened size, lowered when the file is
28
+ // found shorter. A reload remounts the view, so it never rises.
29
+ const end = useRef(info.sizeBytes);
30
+ const viewRef = useRef(view);
31
+ const requests = useRef(null);
32
+ const current = useRef(0);
33
+ const clamp = useCallback((row) => clampTop(row, end.current, viewRef.current.fullRows), []);
34
+ const show = useCallback((target) => {
35
+ const held = chunk.current;
36
+ if (held === null)
37
+ return;
38
+ const top = clamp(target);
39
+ current.current = top;
40
+ // The file shrank under the screen: show the last screen there is.
41
+ if (top !== target) {
42
+ requests.current?.request(top);
43
+ return;
44
+ }
45
+ setScreen({
46
+ top,
47
+ end: end.current,
48
+ rows: rowsFrom(held, top, viewRef.current.screenRows, end.current)
49
+ });
50
+ }, [clamp]);
51
+ useEffect(() => {
52
+ let disposed = false;
53
+ // The size the file has now, for a read that found it shorter without
54
+ // saying by how much.
55
+ const measure = () => {
56
+ void settleRead(noAnswer, () => reader.inspect()).then((result) => {
57
+ if (disposed)
58
+ return;
59
+ if (!result.ok) {
60
+ setFailure(result.error.message);
61
+ return;
62
+ }
63
+ if (result.value.generation !== info.generation)
64
+ return;
65
+ end.current = Math.min(end.current, result.value.sizeBytes);
66
+ current.current = clamp(current.current);
67
+ requests.current?.request(current.current);
68
+ });
69
+ };
70
+ const byteReader = latestRead({
71
+ covered: (target) => covers(chunk.current, clamp(target), viewRef.current.screenRows),
72
+ read: (target) => settleRead(noAnswer, () => reader.readRange(readWindowFor(clamp(target), viewRef.current.screenRows))),
73
+ store: (result) => {
74
+ if (disposed)
75
+ return false;
76
+ if (!result.ok) {
77
+ setFailure(result.error.message);
78
+ return false;
79
+ }
80
+ // A read that was in flight across a reload belongs to the file
81
+ // this view no longer shows.
82
+ if (result.value.generation !== info.generation)
83
+ return false;
84
+ const next = chunkOf(result.value);
85
+ const nextEnd = endAfterRead(next, end.current);
86
+ if (nextEnd === null) {
87
+ measure();
88
+ return false;
89
+ }
90
+ end.current = nextEnd;
91
+ chunk.current = next;
92
+ setFailure(null);
93
+ return true;
94
+ },
95
+ show
96
+ });
97
+ requests.current = byteReader;
98
+ byteReader.request(current.current);
99
+ return () => {
100
+ disposed = true;
101
+ byteReader.dispose();
102
+ requests.current = null;
103
+ };
104
+ }, [noAnswer, reader, clamp, info.generation, show]);
105
+ // A taller window redraws from the same row.
106
+ useEffect(() => {
107
+ viewRef.current = view;
108
+ requests.current?.request(current.current);
109
+ }, [view]);
110
+ const go = useCallback((row) => {
111
+ current.current = clamp(row);
112
+ requests.current?.request(current.current);
113
+ }, [clamp]);
114
+ const scroll = useCallback((rows) => {
115
+ if (rows !== 0)
116
+ go(current.current + rows);
117
+ }, [go]);
118
+ const copy = useCallback((selection, as) => {
119
+ const range = copyRange(selection, end.current);
120
+ const format = as === 'hex' ? hexCopy : textCopy;
121
+ if (range === null)
122
+ return { error: hexSelectionTooLarge(labels.viewer) };
123
+ if (range.length === 0)
124
+ return { text: '' };
125
+ const held = chunk.current;
126
+ if (held !== null &&
127
+ held.offset <= range.offset &&
128
+ held.offset + held.bytes.length >= range.offset + range.length) {
129
+ const from = range.offset - held.offset;
130
+ return { text: format(held.bytes.subarray(from, from + range.length)) };
131
+ }
132
+ return {
133
+ pending: settleRead(noAnswer, () => reader.readRange(range)).then((result) => {
134
+ if (!result.ok)
135
+ throw new Error(result.error.message);
136
+ if (result.value.generation !== info.generation) {
137
+ throw new Error(labels.viewer.hex.copyReloaded);
138
+ }
139
+ return format(result.value.bytes);
140
+ })
141
+ };
142
+ }, [labels.viewer, noAnswer, reader, info.generation]);
143
+ return useMemo(() => ({ screen, failure, go, scroll, copy }), [screen, failure, go, scroll, copy]);
144
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * A media element for a native view, loading `url` while it is mounted. The
3
+ * source is set here rather than as an attribute, so that unmounting (a
4
+ * switch to hex, a fallback, a reload's new generation) can pause the
5
+ * element and drop its source, which ends playback and cancels any range
6
+ * request still streaming from the media URL at once rather than when
7
+ * the element is collected. Returns the ref callback for the element and the
8
+ * element once mounted.
9
+ */
10
+ export declare function useMediaElement<T extends HTMLMediaElement>(url: string): readonly [(element: T | null) => void, T | null];
@@ -0,0 +1,24 @@
1
+ import { useEffect, useState } from 'react';
2
+ /**
3
+ * A media element for a native view, loading `url` while it is mounted. The
4
+ * source is set here rather than as an attribute, so that unmounting (a
5
+ * switch to hex, a fallback, a reload's new generation) can pause the
6
+ * element and drop its source, which ends playback and cancels any range
7
+ * request still streaming from the media URL at once rather than when
8
+ * the element is collected. Returns the ref callback for the element and the
9
+ * element once mounted.
10
+ */
11
+ export function useMediaElement(url) {
12
+ const [media, setMedia] = useState(null);
13
+ useEffect(() => {
14
+ if (!media)
15
+ return;
16
+ media.src = url;
17
+ return () => {
18
+ media.pause();
19
+ media.removeAttribute('src');
20
+ media.load();
21
+ };
22
+ }, [media, url]);
23
+ return [setMedia, media];
24
+ }
@@ -0,0 +1,24 @@
1
+ import { type HighlightPlan } from './SyntaxLanguage.logic.js';
2
+ import type { SyntaxStyle, SyntaxToken } from './SyntaxSession.logic.js';
3
+ import type { TextLayout } from './TextEncoding.logic.js';
4
+ import type { TextScreen } from './useTextDocument.js';
5
+ /** The highlighting the text view draws: each row's tokens, their styles, and the status bar's word. */
6
+ export interface SyntaxHighlight {
7
+ readonly styles: readonly SyntaxStyle[];
8
+ /** The tokens of the row starting at byte `start`; null while it has none, or shows plain. */
9
+ readonly tokensFor: (start: number) => readonly SyntaxToken[] | null;
10
+ /** The language and any reason text shows plain; null for a file with no known language. */
11
+ readonly status: string | null;
12
+ }
13
+ /**
14
+ * Highlights the text view's screen in a worker, per `plan`. The worker is
15
+ * started for the plan's language and file generation and stopped with the
16
+ * view. Each screen asks the worker once for its rows, sending the bytes the
17
+ * screen was drawn from when the worker does not hold them yet; while it
18
+ * answers, newer screens only wait, and the newest is asked next, so a
19
+ * fling never queues up work. Answers are kept by row, so a row drawn
20
+ * before draws again at once. A row answered from an approximate state is
21
+ * asked again when a new screen shows it, in case a known state now reaches
22
+ * it.
23
+ */
24
+ export declare function useSyntaxHighlight(plan: HighlightPlan, generation: number, layout: TextLayout | null, screen: TextScreen | null): SyntaxHighlight;
@@ -0,0 +1,133 @@
1
+ import { use, useCallback, useEffect, useRef, useState } from 'react';
2
+ import { useLabels } from '../labels/UiokProvider.js';
3
+ import { HIGHLIGHT_MAX_LINE_BYTES, highlightStatus } from './SyntaxLanguage.logic.js';
4
+ import { SyntaxWorkerContext } from './SyntaxService.js';
5
+ /** Rows whose highlighting the page keeps, so scrolling back draws them without asking. */
6
+ const MAX_CACHED_ROWS = 5000;
7
+ const NO_STYLES = [];
8
+ /**
9
+ * Highlights the text view's screen in a worker, per `plan`. The worker is
10
+ * started for the plan's language and file generation and stopped with the
11
+ * view. Each screen asks the worker once for its rows, sending the bytes the
12
+ * screen was drawn from when the worker does not hold them yet; while it
13
+ * answers, newer screens only wait, and the newest is asked next, so a
14
+ * fling never queues up work. Answers are kept by row, so a row drawn
15
+ * before draws again at once. A row answered from an approximate state is
16
+ * asked again when a new screen shows it, in case a known state now reaches
17
+ * it.
18
+ */
19
+ export function useSyntaxHighlight(plan, generation, layout, screen) {
20
+ const labels = useLabels().viewer;
21
+ const openWorker = use(SyntaxWorkerContext);
22
+ const language = plan.kind === 'highlight' && openWorker !== null ? plan.language : null;
23
+ const [styles, setStyles] = useState(null);
24
+ const [failed, setFailed] = useState(false);
25
+ const [rows, setRows] = useState(new Map());
26
+ const port = useRef(null);
27
+ const cache = useRef(new Map());
28
+ const sent = useRef(null);
29
+ const asking = useRef(false);
30
+ const latest = useRef({
31
+ screen,
32
+ layout
33
+ });
34
+ /** Asks for the newest screen's rows that have no answer, and with `again`, the approximate ones too. */
35
+ const ask = useCallback((again) => {
36
+ const worker = port.current;
37
+ const { screen: shown, layout: textLayout } = latest.current;
38
+ if (worker === null || shown === null || textLayout === null || asking.current)
39
+ return;
40
+ const wanted = shown.rows.some((row) => {
41
+ const known = cache.current.get(row.start);
42
+ return known === undefined || (again && !known.exact && known.plain !== 'long');
43
+ });
44
+ if (!wanted)
45
+ return;
46
+ if (sent.current !== shown.source) {
47
+ const { offset, bytes, eof } = shown.source;
48
+ const copy = bytes.slice();
49
+ worker.postMessage({ type: 'chunk', offset, bytes: copy, eof, layout: textLayout }, [
50
+ copy.buffer
51
+ ]);
52
+ sent.current = shown.source;
53
+ }
54
+ asking.current = true;
55
+ worker.postMessage({
56
+ type: 'highlight',
57
+ rows: shown.rows.map(({ start, kind }) => ({ start, kind }))
58
+ });
59
+ }, []);
60
+ useEffect(() => {
61
+ if (language === null || openWorker === null)
62
+ return;
63
+ let worker;
64
+ try {
65
+ worker = openWorker();
66
+ }
67
+ catch {
68
+ // A page that cannot start the worker shows the text plain, and says so.
69
+ setFailed(true);
70
+ return () => setFailed(false);
71
+ }
72
+ port.current = worker;
73
+ cache.current = new Map();
74
+ sent.current = null;
75
+ asking.current = false;
76
+ worker.onmessage = ({ data }) => {
77
+ switch (data.type) {
78
+ case 'ready':
79
+ setStyles(data.styles);
80
+ ask(true);
81
+ return;
82
+ case 'failed':
83
+ setFailed(true);
84
+ return;
85
+ case 'rows': {
86
+ const known = cache.current;
87
+ for (const row of data.rows) {
88
+ known.delete(row.start);
89
+ known.set(row.start, row);
90
+ }
91
+ for (const start of known.keys()) {
92
+ if (known.size <= MAX_CACHED_ROWS)
93
+ break;
94
+ known.delete(start);
95
+ }
96
+ asking.current = false;
97
+ setRows(new Map(known));
98
+ ask(false);
99
+ return;
100
+ }
101
+ }
102
+ };
103
+ worker.onerror = () => setFailed(true);
104
+ worker.postMessage({ type: 'open', language, maxLineBytes: HIGHLIGHT_MAX_LINE_BYTES });
105
+ return () => {
106
+ worker.terminate();
107
+ port.current = null;
108
+ setStyles(null);
109
+ setFailed(false);
110
+ setRows(new Map());
111
+ };
112
+ }, [ask, generation, language, openWorker]);
113
+ useEffect(() => {
114
+ latest.current = { screen, layout };
115
+ if (styles !== null)
116
+ ask(true);
117
+ }, [ask, layout, screen, styles]);
118
+ const tokensFor = useCallback((start) => rows.get(start)?.tokens ?? null, [rows]);
119
+ let note = null;
120
+ if (plan.kind === 'too-large')
121
+ note = 'too-large';
122
+ else if (failed)
123
+ note = 'unavailable';
124
+ else if (screen?.rows.some((row) => rows.get(row.start)?.plain === 'long'))
125
+ note = 'long-lines';
126
+ return {
127
+ styles: styles ?? NO_STYLES,
128
+ tokensFor,
129
+ status: plan.kind === 'none' || openWorker === null
130
+ ? null
131
+ : highlightStatus(plan.language, note, labels)
132
+ };
133
+ }
@@ -0,0 +1,66 @@
1
+ import { type ViewerReader, type ViewerFileInfo } from './types.js';
2
+ import { type TextLayout } from './TextEncoding.logic.js';
3
+ import { type RowStart, type TextChunk } from './TextRows.logic.js';
4
+ import { type TextSelection } from './TextSelection.logic.js';
5
+ import { type ViewTarget } from './TextViewport.logic.js';
6
+ import type { ViewerCopy } from './ViewerClipboard.js';
7
+ /** One row on screen: its place in the file, its text, and its line number when known. */
8
+ export interface ScreenRow {
9
+ readonly start: number;
10
+ readonly end: number;
11
+ readonly kind: RowStart['kind'];
12
+ readonly text: string;
13
+ /** The row's line number; null on a row that continues a line, or while the index has not reached it. */
14
+ readonly line: number | null;
15
+ }
16
+ /** The screen the view draws. */
17
+ export interface TextScreen {
18
+ readonly top: RowStart;
19
+ readonly rows: readonly ScreenRow[];
20
+ /** The line holding the first row, once the line index has reached the screen; until then the gutter shows byte offsets. */
21
+ readonly topLine: number | null;
22
+ /** False while a move longer than a page is still on its way; the view lands it on the screen where it ends. */
23
+ readonly settled: boolean;
24
+ /** Where the readable bytes end: the opened size, or less once a read found the file shrunk. */
25
+ readonly end: number;
26
+ /** The bytes the rows were drawn from, which highlighting tokenizes too. */
27
+ readonly source: TextChunk;
28
+ }
29
+ /** The text view's file state: what is on screen, and the calls that move it. */
30
+ export interface TextDocument {
31
+ readonly layout: TextLayout | null;
32
+ /** The file's first line (its first 256 bytes at most), once read; it names a script's interpreter. */
33
+ readonly firstLine: string | null;
34
+ readonly screen: TextScreen | null;
35
+ /** True once the file turned out to hold no text. */
36
+ readonly empty: boolean;
37
+ /** Why the file could not be read, in the reader's copy. */
38
+ readonly failure: string | null;
39
+ /** Shows `target`, reading at most once, and only for the newest target. */
40
+ readonly go: (target: ViewTarget) => void;
41
+ /** Moves `rows` rows from the newest target, so moves made while a read is in flight add up. */
42
+ readonly scroll: (rows: number) => void;
43
+ /** The selected text, read in one bounded read when the screen does not hold it; or why not. */
44
+ readonly copy: (selection: TextSelection) => ViewerCopy;
45
+ }
46
+ /** The document's settings that change without a new file: screen height and wrapping. */
47
+ export interface TextDocumentView {
48
+ /** Rows drawn, the last of which may show only in part. */
49
+ readonly screenRows: number;
50
+ /** Rows that fit whole, so the end of the file pulls its last row fully into view. */
51
+ readonly fullRows: number;
52
+ readonly wrap: boolean;
53
+ }
54
+ /**
55
+ * Reads the window's file for the text view, the way `less` does: the first
56
+ * read finds the encoding and the first screen, and each later screen comes
57
+ * from bytes already held or from one bounded read, the newest target
58
+ * winning. Line numbers come from the reader's line count, asked
59
+ * only for the top row and carried down the screen; a read or an answer
60
+ * about another generation of the file (one in flight across a reload) is
61
+ * dropped. A read that finds the file shrunk ends the view at the new end
62
+ * for as long as the view lives; a read that lands wholly past it asks the
63
+ * file's size once, so the screen comes back in one more read however far
64
+ * past the end it was.
65
+ */
66
+ export declare function useTextDocument(reader: ViewerReader, info: ViewerFileInfo, view: TextDocumentView): TextDocument;
@@ -0,0 +1,245 @@
1
+ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
2
+ import { settleRead } from './types.js';
3
+ import { useLabels } from '../labels/UiokProvider.js';
4
+ import { latestRead } from './LatestRead.logic.js';
5
+ import { detectEncoding, textDecoder } from './TextEncoding.logic.js';
6
+ import { rowsFrom } from './TextRows.logic.js';
7
+ import { copyRange, orderedSelection, selectedText, selectionTooLarge } from './TextSelection.logic.js';
8
+ import { covers, lineFromAnchor, numberRows, readWindowFor, resolveViewport } from './TextViewport.logic.js';
9
+ const chunkOf = ({ offset, bytes, endOfFile }) => ({
10
+ offset,
11
+ bytes,
12
+ eof: endOfFile
13
+ });
14
+ /** How much of the head the first line is read from. */
15
+ const FIRST_LINE_BYTES = 256;
16
+ /**
17
+ * Where the readable bytes end after a read: lowered to the end of a read
18
+ * that reached the end of the file; null for a read that found nothing past
19
+ * a shrunk end, which says the file is shorter but not by how much.
20
+ */
21
+ function endAfterRead(chunk, end) {
22
+ if (!chunk.eof)
23
+ return end;
24
+ if (chunk.bytes.length === 0 && chunk.offset > 0)
25
+ return null;
26
+ return Math.min(end, chunk.offset + chunk.bytes.length);
27
+ }
28
+ /**
29
+ * Reads the window's file for the text view, the way `less` does: the first
30
+ * read finds the encoding and the first screen, and each later screen comes
31
+ * from bytes already held or from one bounded read, the newest target
32
+ * winning. Line numbers come from the reader's line count, asked
33
+ * only for the top row and carried down the screen; a read or an answer
34
+ * about another generation of the file (one in flight across a reload) is
35
+ * dropped. A read that finds the file shrunk ends the view at the new end
36
+ * for as long as the view lives; a read that lands wholly past it asks the
37
+ * file's size once, so the screen comes back in one more read however far
38
+ * past the end it was.
39
+ */
40
+ export function useTextDocument(reader, info, view) {
41
+ const labels = useLabels();
42
+ const noAnswer = labels.viewer.noAnswer;
43
+ const [layout, setLayout] = useState(null);
44
+ const [firstLine, setFirstLine] = useState(null);
45
+ const [screen, setScreen] = useState(null);
46
+ const [empty, setEmpty] = useState(false);
47
+ const [failure, setFailure] = useState(null);
48
+ const chunk = useRef(null);
49
+ // Where the readable bytes end: the opened size, lowered when the file is
50
+ // found shorter. A reload remounts the view, so it never rises.
51
+ const readableEnd = useRef(info.sizeBytes);
52
+ const layoutRef = useRef(null);
53
+ const viewRef = useRef(view);
54
+ const requests = useRef(null);
55
+ const current = useRef({ anchor: 0, rows: 0 });
56
+ const lineAnchor = useRef(null);
57
+ const asked = useRef(null);
58
+ const decoder = useRef(null);
59
+ const decode = useCallback((source, from, to) => {
60
+ const active = decoder.current;
61
+ return active === null
62
+ ? ''
63
+ : active.decode(source.bytes.subarray(from - source.offset, to - source.offset));
64
+ }, []);
65
+ const show = useCallback((target) => {
66
+ const held = chunk.current;
67
+ const textLayout = layoutRef.current;
68
+ if (held === null || textLayout === null)
69
+ return;
70
+ const { screenRows, fullRows, wrap } = viewRef.current;
71
+ const viewport = resolveViewport(held, textLayout, target, screenRows, wrap ? 1 : fullRows);
72
+ current.current = viewport ? { anchor: viewport.top.start, rows: viewport.rest } : target;
73
+ if (viewport === null) {
74
+ setEmpty(true);
75
+ setScreen(null);
76
+ return;
77
+ }
78
+ const known = lineAnchor.current;
79
+ const topLine = known === null ? null : lineFromAnchor(held, textLayout, known, viewport.top.start);
80
+ const lines = topLine === null ? null : numberRows(viewport.rows, topLine);
81
+ if (topLine !== null) {
82
+ lineAnchor.current = { offset: viewport.top.start, line: topLine };
83
+ }
84
+ setEmpty(false);
85
+ setScreen({
86
+ top: viewport.top,
87
+ topLine,
88
+ settled: viewport.rest === 0,
89
+ end: readableEnd.current,
90
+ source: held,
91
+ rows: viewport.rows.map((row, index) => ({
92
+ start: row.start,
93
+ end: row.end,
94
+ kind: row.kind,
95
+ text: decode(held, row.start, row.textEnd),
96
+ line: lines?.[index] ?? null
97
+ }))
98
+ });
99
+ // A move longer than a page goes on from this screen; only where it
100
+ // ends does the line index get asked.
101
+ if (viewport.rest !== 0) {
102
+ requests.current?.request(current.current);
103
+ return;
104
+ }
105
+ if (topLine === null && asked.current !== viewport.top.start) {
106
+ const offset = viewport.top.start;
107
+ asked.current = offset;
108
+ void settleRead(noAnswer, () => reader.lineNumber({ offset, encoding: textLayout.encoding })).then((result) => {
109
+ // Answered either way, so coming back to this row later asks again.
110
+ if (asked.current === offset)
111
+ asked.current = null;
112
+ if (!result.ok || result.value.generation !== info.generation)
113
+ return;
114
+ if (result.value.line === null)
115
+ return;
116
+ lineAnchor.current = { offset, line: result.value.line };
117
+ requests.current?.request(current.current);
118
+ });
119
+ }
120
+ }, [noAnswer, reader, decode, info.generation]);
121
+ useEffect(() => {
122
+ let disposed = false;
123
+ // The size the file has now, for a read that found it shorter without
124
+ // saying by how much: the target comes back within it.
125
+ const measure = () => {
126
+ void settleRead(noAnswer, () => reader.inspect()).then((result) => {
127
+ if (disposed)
128
+ return;
129
+ if (!result.ok) {
130
+ setFailure(result.error.message);
131
+ return;
132
+ }
133
+ if (result.value.generation !== info.generation)
134
+ return;
135
+ readableEnd.current = Math.min(readableEnd.current, result.value.sizeBytes);
136
+ // Bytes held past the new end are no longer the file's, so the
137
+ // target is read again rather than drawn from them.
138
+ const held = chunk.current;
139
+ if (held !== null && held.offset + held.bytes.length > readableEnd.current) {
140
+ chunk.current = null;
141
+ }
142
+ current.current = {
143
+ anchor: Math.min(current.current.anchor, readableEnd.current),
144
+ rows: current.current.rows
145
+ };
146
+ requests.current?.request(current.current);
147
+ });
148
+ };
149
+ const byteReader = latestRead({
150
+ covered: (target) => covers(chunk.current, target, viewRef.current.screenRows),
151
+ read: (target) => {
152
+ const window = readWindowFor(target, viewRef.current.screenRows);
153
+ return settleRead(noAnswer, () => reader.readRange(window));
154
+ },
155
+ store: (result) => {
156
+ if (disposed)
157
+ return false;
158
+ if (!result.ok) {
159
+ setFailure(result.error.message);
160
+ return false;
161
+ }
162
+ // A read that was in flight across a reload belongs to the file
163
+ // this view no longer shows.
164
+ if (result.value.generation !== info.generation)
165
+ return false;
166
+ const next = chunkOf(result.value);
167
+ const nextEnd = endAfterRead(next, readableEnd.current);
168
+ if (nextEnd === null) {
169
+ measure();
170
+ return false;
171
+ }
172
+ if (layoutRef.current === null) {
173
+ if (next.offset !== 0)
174
+ return false;
175
+ const detected = detectEncoding(next.bytes, next.eof);
176
+ const head = next.bytes.subarray(detected.contentStart, FIRST_LINE_BYTES);
177
+ layoutRef.current = detected;
178
+ decoder.current = textDecoder(detected.encoding);
179
+ setLayout(detected);
180
+ setFirstLine(decoder.current.decode(head).split(/\r?\n/u, 1)[0] ?? '');
181
+ }
182
+ readableEnd.current = nextEnd;
183
+ chunk.current = next;
184
+ setFailure(null);
185
+ return true;
186
+ },
187
+ show
188
+ });
189
+ requests.current = byteReader;
190
+ byteReader.request(current.current);
191
+ return () => {
192
+ disposed = true;
193
+ byteReader.dispose();
194
+ requests.current = null;
195
+ };
196
+ }, [noAnswer, reader, info.generation, show]);
197
+ // A taller window or a wrap toggle redraws the same place.
198
+ useEffect(() => {
199
+ viewRef.current = view;
200
+ requests.current?.request(current.current);
201
+ }, [view]);
202
+ const go = useCallback((target) => {
203
+ current.current = { anchor: Math.min(target.anchor, readableEnd.current), rows: target.rows };
204
+ requests.current?.request(current.current);
205
+ }, []);
206
+ const scroll = useCallback((rows) => {
207
+ if (rows !== 0)
208
+ go({ anchor: current.current.anchor, rows: current.current.rows + rows });
209
+ }, [go]);
210
+ const copy = useCallback((selection) => {
211
+ const textLayout = layoutRef.current;
212
+ const range = copyRange(selection, readableEnd.current);
213
+ if (range === null)
214
+ return { error: selectionTooLarge(labels.viewer) };
215
+ if (textLayout === null || range.length === 0)
216
+ return { text: '' };
217
+ const [start, end] = orderedSelection(selection);
218
+ const textFrom = (source) => selectedText(selection, rowsFrom(source, textLayout, { start: start.row, kind: start.kind }, Number.MAX_SAFE_INTEGER)
219
+ .rows.filter((row) => row.start <= end.row)
220
+ .map((row) => ({
221
+ start: row.start,
222
+ end: row.end,
223
+ kind: row.kind,
224
+ text: decode(source, row.start, row.textEnd),
225
+ lineBreak: decode(source, row.textEnd, row.end)
226
+ })));
227
+ const held = chunk.current;
228
+ if (held !== null &&
229
+ held.offset <= range.offset &&
230
+ (held.eof || held.offset + held.bytes.length >= range.offset + range.length)) {
231
+ return { text: textFrom(held) };
232
+ }
233
+ return {
234
+ pending: settleRead(noAnswer, () => reader.readRange(range)).then((result) => {
235
+ if (!result.ok)
236
+ throw new Error(result.error.message);
237
+ if (result.value.generation !== info.generation) {
238
+ throw new Error(labels.viewer.text.copyReloaded);
239
+ }
240
+ return textFrom(chunkOf(result.value));
241
+ })
242
+ };
243
+ }, [labels.viewer, noAnswer, reader, decode, info.generation]);
244
+ return useMemo(() => ({ layout, firstLine, screen, empty, failure, go, scroll, copy }), [layout, firstLine, screen, empty, failure, go, scroll, copy]);
245
+ }