@kvndy/text-view 0.0.0-stage → 0.0.2
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/LICENSE +21 -0
- package/README.md +147 -2
- package/dist/content-view.d.ts +13 -0
- package/dist/edit-coalescing.d.ts +9 -0
- package/dist/main.d.ts +4 -0
- package/dist/main.js +315 -0
- package/dist/text-view.d.ts +26 -0
- package/dist/types.d.ts +11 -0
- package/dist/view-state.d.ts +11 -0
- package/package.json +40 -5
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Kevin Doughty
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,148 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Attributed String
|
|
2
2
|
|
|
3
|
-
This
|
|
3
|
+
This is a simple attributed string and virtualized/windowing text view for **Preact**, inspired by NSAttributedString and NSTextView. Text must be monospace with no ligatures, and the only usable styling is foreground and background color. It **does** support soft-wrapped text. The intended use is for lightweight syntax highlighting.
|
|
4
|
+
|
|
5
|
+
It works by appending overlay spans on top of a textarea (for editing) and a div (for glyph metrics). Due to this, the browser’s built-in search control will find text in triplicate. On scroll, reconciliation is bypassed and spans are directly inserted into the DOM, which get removed on resize or re-render.
|
|
6
|
+
|
|
7
|
+
The API and implementation is still under development. Until version 1.0.0, expect breaking semver changes. Consumers should pin to specific releases.
|
|
8
|
+
|
|
9
|
+
## Usage
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
npm install --save-exact @kvndy/text-view@0.0.1
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
`AttributedString` is a TypeScript type for a plain object containing the full `text` and its attribute `runs`. Each run applies foreground color, background color, or both to a range in that text. Offsets are UTF-16 code units, like textarea selection offsets, and range ends are exclusive.
|
|
16
|
+
|
|
17
|
+
`TextView` is the Preact component that renders and edits the text. Pass your `AttributedString` as `value` and the current caret or selection as `selection`. Use `onInput` to update the value and selection after an edit. Use `onSelectionChange` to track caret or selection movement.
|
|
18
|
+
|
|
19
|
+
The editor fills its parent, which must give it a height. It uses the browser's default monospace font with ligatures disabled. `fontSize` is in CSS pixels and defaults to 16. Text wraps by default. Set `softWrap={false}` to scroll long lines horizontally. TextView requires support for `field-sizing: content`.
|
|
20
|
+
|
|
21
|
+
Use `selection` to set a selection and `revealOffset` to reveal a text offset
|
|
22
|
+
after rendering. For commands, pass a stable `onController` callback.
|
|
23
|
+
TextView gives it a `TextViewController` after mount and calls it with `null`
|
|
24
|
+
on unmount or when the callback is replaced. Store the controller wherever
|
|
25
|
+
your app handles commands. Call `controller.focus()` to focus without
|
|
26
|
+
scrolling or changing selection, or `controller.revealOffset(offset)` to
|
|
27
|
+
reveal an offset again after a user scroll or resize.
|
|
28
|
+
|
|
29
|
+
`onInput` supplies a `coalescingKey` for apps that group edits in their undo
|
|
30
|
+
history. If your input handler already opens a group, use the key there.
|
|
31
|
+
Otherwise you can pass `runInputTransaction` to wrap the mutation. Call its
|
|
32
|
+
`apply` function once, synchronously, inside your transaction. Without this
|
|
33
|
+
prop, TextView calls `onInput` directly.
|
|
34
|
+
|
|
35
|
+
```tsx
|
|
36
|
+
import { useState } from "preact/hooks";
|
|
37
|
+
import { TextView, type AttributedString, type TextSelection } from "@kvndy/text-view";
|
|
38
|
+
|
|
39
|
+
export function Editor() {
|
|
40
|
+
const [text, setText] = useState("Hello world");
|
|
41
|
+
const [selection, setSelection] = useState<TextSelection>({
|
|
42
|
+
start: 0,
|
|
43
|
+
end: 0,
|
|
44
|
+
direction: "none",
|
|
45
|
+
});
|
|
46
|
+
const firstWord = text.match(/^\S+/)?.[0] ?? "";
|
|
47
|
+
const value: AttributedString = {
|
|
48
|
+
text,
|
|
49
|
+
runs: firstWord
|
|
50
|
+
? [{ range: { start: 0, end: firstWord.length }, attributes: { foreground: "royalblue" } }]
|
|
51
|
+
: [],
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
return (
|
|
55
|
+
<div style={{ height: "12rem" }}>
|
|
56
|
+
<TextView
|
|
57
|
+
ariaLabel="Example editor"
|
|
58
|
+
value={value}
|
|
59
|
+
selection={selection}
|
|
60
|
+
onInput={edit => {
|
|
61
|
+
setText(edit.text);
|
|
62
|
+
setSelection(edit.selection);
|
|
63
|
+
}}
|
|
64
|
+
onSelectionChange={setSelection}
|
|
65
|
+
/>
|
|
66
|
+
</div>
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
## Type definitions
|
|
72
|
+
|
|
73
|
+
`TextRange`, `TextAttributes`, `AttributeRun`, and `AttributedString` are
|
|
74
|
+
re-exported from `@kvndy/attributed-string`.
|
|
75
|
+
|
|
76
|
+
```ts
|
|
77
|
+
export interface TextRange {
|
|
78
|
+
readonly start: number;
|
|
79
|
+
readonly end: number;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export interface TextAttributes {
|
|
83
|
+
readonly foreground?: string;
|
|
84
|
+
readonly background?: string;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export interface AttributeRun {
|
|
88
|
+
readonly range: TextRange;
|
|
89
|
+
readonly attributes: TextAttributes;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export interface AttributedString {
|
|
93
|
+
readonly text: string;
|
|
94
|
+
readonly runs: readonly AttributeRun[];
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export interface TextSelection extends TextRange {
|
|
98
|
+
readonly direction: "forward" | "backward" | "none";
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export interface TextInput {
|
|
102
|
+
readonly text: string;
|
|
103
|
+
readonly selection: TextSelection;
|
|
104
|
+
readonly inputType: string;
|
|
105
|
+
readonly isComposing: boolean;
|
|
106
|
+
readonly coalescingKey: symbol;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export interface TextViewController {
|
|
110
|
+
focus(): void;
|
|
111
|
+
revealOffset(offset: number): void;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export interface TextViewProps {
|
|
115
|
+
value: AttributedString;
|
|
116
|
+
selection: TextSelection;
|
|
117
|
+
ariaLabel?: string;
|
|
118
|
+
onController?: (controller: TextViewController | null) => void;
|
|
119
|
+
scrollTop?: number;
|
|
120
|
+
softWrap?: boolean;
|
|
121
|
+
fontSize?: number;
|
|
122
|
+
highlighted?: boolean;
|
|
123
|
+
disabled?: boolean;
|
|
124
|
+
revealOffset?: number | null;
|
|
125
|
+
onInput: (input: TextInput) => void;
|
|
126
|
+
runInputTransaction?: (input: TextInput, apply: () => void) => void;
|
|
127
|
+
onSelectionChange?: (selection: TextSelection) => void;
|
|
128
|
+
onScroll?: (scrollTop: number) => void;
|
|
129
|
+
onFocus?: () => void;
|
|
130
|
+
onBlur?: () => void;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export declare function TextView(props: TextViewProps): import("preact").JSX.Element;
|
|
134
|
+
|
|
135
|
+
export declare class EditCoalescing {
|
|
136
|
+
interrupt(): void;
|
|
137
|
+
input(inputType: string): symbol;
|
|
138
|
+
dispose(): void;
|
|
139
|
+
}
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
## Example
|
|
143
|
+
|
|
144
|
+
[Proof-of-concept live example](https://kevindoughty.gitlab.io/attributed-string/).
|
|
145
|
+
|
|
146
|
+
## License
|
|
147
|
+
|
|
148
|
+
MIT
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { JSX, RefObject } from "preact";
|
|
2
|
+
import { type AttributeRun } from "@kvndy/attributed-string";
|
|
3
|
+
import { type LineDescriptor, type LineRange } from "@kvndy/glyph-metrics";
|
|
4
|
+
interface ContentViewProps {
|
|
5
|
+
lines: LineDescriptor[];
|
|
6
|
+
visibleRange: LineRange;
|
|
7
|
+
attributes: readonly AttributeRun[];
|
|
8
|
+
text: string;
|
|
9
|
+
style: Exclude<JSX.IntrinsicElements["div"]["style"], string | undefined>;
|
|
10
|
+
scrollHandler: RefObject<((range: LineRange) => void) | null>;
|
|
11
|
+
}
|
|
12
|
+
export declare function ContentView({ lines, visibleRange, attributes, text, style, scrollHandler }: ContentViewProps): JSX.Element;
|
|
13
|
+
export {};
|
package/dist/main.d.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { TextView, type TextViewController, type TextViewProps } from "./text-view.js";
|
|
2
|
+
export { EditCoalescing } from "./edit-coalescing.js";
|
|
3
|
+
export type { AttributedString, TextRange, TextAttributes, AttributeRun } from "@kvndy/attributed-string";
|
|
4
|
+
export type { TextSelection, TextInput } from "./types.js";
|
package/dist/main.js
ADDED
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
import { jsx, jsxs } from 'preact/jsx-runtime';
|
|
2
|
+
import { useRef, useLayoutEffect, useState, useMemo, useEffect } from 'preact/hooks';
|
|
3
|
+
import { iterateAttributes } from '@kvndy/attributed-string';
|
|
4
|
+
import { findLineAtOffset, readGlyphMetrics, performGlyphLayout, calculateVisibleLineRange } from '@kvndy/glyph-metrics';
|
|
5
|
+
|
|
6
|
+
function ContentView({ lines, visibleRange, attributes, text, style, scrollHandler }) {
|
|
7
|
+
const elementRef = useRef(null);
|
|
8
|
+
const insertedSpans = useRef([]);
|
|
9
|
+
// Clear the extra spans before Preact reconciles the rendered window.
|
|
10
|
+
for (const span of insertedSpans.current)
|
|
11
|
+
span.remove();
|
|
12
|
+
insertedSpans.current = [];
|
|
13
|
+
const start = lines[visibleRange.firstLine]?.charStart ?? 0;
|
|
14
|
+
const end = lines[visibleRange.lastLine]?.charEnd ?? 0;
|
|
15
|
+
const children = [];
|
|
16
|
+
let renderedStart;
|
|
17
|
+
let renderedEnd = 0;
|
|
18
|
+
if (end > start) {
|
|
19
|
+
for (const run of iterateAttributes(text, attributes, (content, color, background, first, last) => ({
|
|
20
|
+
first, last, span: jsx("span", { style: { color, background }, children: content }, last),
|
|
21
|
+
}), start, end, true)) {
|
|
22
|
+
renderedStart ??= run.first;
|
|
23
|
+
renderedEnd = run.last;
|
|
24
|
+
children.push(run.span);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
const top = renderedStart === undefined ? 0 : findLineAtOffset(lines, renderedStart).y;
|
|
28
|
+
useLayoutEffect(() => {
|
|
29
|
+
const element = elementRef.current;
|
|
30
|
+
element.style.top = `${top}px`;
|
|
31
|
+
let first = renderedStart ?? start;
|
|
32
|
+
let last = renderedEnd || end;
|
|
33
|
+
const insert = (direction, from, to) => {
|
|
34
|
+
for (const run of iterateAttributes(text, attributes, (content, color, background, start, end) => {
|
|
35
|
+
const span = element.ownerDocument.createElement("span");
|
|
36
|
+
span.style.color = color;
|
|
37
|
+
span.style.background = background;
|
|
38
|
+
span.textContent = content;
|
|
39
|
+
return { start, end, span };
|
|
40
|
+
}, from, to, direction < 0, direction)) {
|
|
41
|
+
if (direction > 0)
|
|
42
|
+
element.appendChild(run.span);
|
|
43
|
+
else
|
|
44
|
+
element.insertBefore(run.span, element.firstChild);
|
|
45
|
+
insertedSpans.current.push(run.span);
|
|
46
|
+
first = Math.min(first, run.start);
|
|
47
|
+
last = Math.max(last, run.end);
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
scrollHandler.current = range => {
|
|
51
|
+
const firstLine = lines[range.firstLine];
|
|
52
|
+
const lastLine = lines[range.lastLine];
|
|
53
|
+
if (!firstLine || !lastLine)
|
|
54
|
+
return;
|
|
55
|
+
if (firstLine.charStart < first) {
|
|
56
|
+
insert(-1, firstLine.charStart, first);
|
|
57
|
+
element.style.top = `${findLineAtOffset(lines, first).y}px`;
|
|
58
|
+
}
|
|
59
|
+
if (lastLine.charEnd > last)
|
|
60
|
+
insert(1, last, lastLine.charEnd);
|
|
61
|
+
};
|
|
62
|
+
return () => { scrollHandler.current = null; };
|
|
63
|
+
});
|
|
64
|
+
return jsx("div", { "data-text-view-part": "content", ref: elementRef, style: { ...style, top: `${top}px` }, children: children });
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Supplies identity keys to the consumer's UndoManager.group; owns no history. */
|
|
68
|
+
class EditCoalescing {
|
|
69
|
+
key = Symbol("text edit");
|
|
70
|
+
timer;
|
|
71
|
+
inputType = "";
|
|
72
|
+
interrupt() {
|
|
73
|
+
this.dispose();
|
|
74
|
+
this.key = Symbol("text edit");
|
|
75
|
+
this.inputType = "";
|
|
76
|
+
}
|
|
77
|
+
input(inputType) {
|
|
78
|
+
const continuous = ["insertText", "deleteContentBackward", "deleteContentForward", "insertCompositionText"].includes(inputType);
|
|
79
|
+
if (!continuous || inputType !== this.inputType)
|
|
80
|
+
this.interrupt();
|
|
81
|
+
this.inputType = inputType;
|
|
82
|
+
const key = this.key;
|
|
83
|
+
this.dispose();
|
|
84
|
+
if (continuous)
|
|
85
|
+
this.timer = setTimeout(() => this.interrupt(), 1000);
|
|
86
|
+
else
|
|
87
|
+
this.interrupt();
|
|
88
|
+
return key;
|
|
89
|
+
}
|
|
90
|
+
dispose() { if (this.timer !== undefined)
|
|
91
|
+
clearTimeout(this.timer); this.timer = undefined; }
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function createLayoutState() {
|
|
95
|
+
const initialView = { lines: [], height: 0 };
|
|
96
|
+
let view = initialView;
|
|
97
|
+
let previousText;
|
|
98
|
+
let previousWidth = 0;
|
|
99
|
+
let previousCharWidth = 0;
|
|
100
|
+
let previousLineHeight = 0;
|
|
101
|
+
let previousWrap;
|
|
102
|
+
return {
|
|
103
|
+
initialView,
|
|
104
|
+
refresh(text, softWrap, viewport, measure, glyph) {
|
|
105
|
+
const width = measure.getBoundingClientRect().width;
|
|
106
|
+
const fontInfo = readGlyphMetrics(glyph);
|
|
107
|
+
const { char: charWidth, height: lineHeight } = fontInfo;
|
|
108
|
+
const height = viewport.clientHeight;
|
|
109
|
+
let { lines } = view;
|
|
110
|
+
if (text !== previousText || width !== previousWidth || charWidth !== previousCharWidth ||
|
|
111
|
+
lineHeight !== previousLineHeight || softWrap !== previousWrap) {
|
|
112
|
+
lines = width > 0 && charWidth > 0 && lineHeight > 0
|
|
113
|
+
? performGlyphLayout(measure, text.length, fontInfo)
|
|
114
|
+
: [];
|
|
115
|
+
previousText = text;
|
|
116
|
+
previousWidth = width;
|
|
117
|
+
previousCharWidth = charWidth;
|
|
118
|
+
previousLineHeight = lineHeight;
|
|
119
|
+
previousWrap = softWrap;
|
|
120
|
+
}
|
|
121
|
+
if (lines !== view.lines || height !== view.height)
|
|
122
|
+
view = { lines, height };
|
|
123
|
+
return view;
|
|
124
|
+
},
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const padding = 8;
|
|
129
|
+
const emptyLines = { firstLine: 0, lastLine: 0 };
|
|
130
|
+
function readSelection(textarea) {
|
|
131
|
+
return {
|
|
132
|
+
start: textarea.selectionStart,
|
|
133
|
+
end: textarea.selectionEnd,
|
|
134
|
+
direction: textarea.selectionDirection ?? "none",
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
function TextView({ value: { text, runs }, selection, ariaLabel, onController, scrollTop, softWrap = true, fontSize = 16, highlighted = true, disabled = false, revealOffset, onInput, runInputTransaction, onSelectionChange, onScroll, onFocus, onBlur, }) {
|
|
138
|
+
const textareaRef = useRef(null);
|
|
139
|
+
const viewportRef = useRef(null);
|
|
140
|
+
const measureRef = useRef(null);
|
|
141
|
+
const glyphRef = useRef(null);
|
|
142
|
+
const updateOverlay = useRef(null);
|
|
143
|
+
const [layout] = useState(createLayoutState);
|
|
144
|
+
const [view, setView] = useState(layout.initialView);
|
|
145
|
+
const [coalescing] = useState(() => new EditCoalescing());
|
|
146
|
+
const lineHeight = fontSize * 1.5;
|
|
147
|
+
const showOverlay = highlighted && !disabled;
|
|
148
|
+
const measureLines = useMemo(() => {
|
|
149
|
+
// Keep Range queries local to a logical line. The suffix makes the
|
|
150
|
+
// final blank caret row measurable without changing the document.
|
|
151
|
+
return (text + "\n ").match(/[^\n]*\n|[^\n]+$/g);
|
|
152
|
+
}, [text]);
|
|
153
|
+
const refreshLayout = () => layout.refresh(text, softWrap, viewportRef.current, measureRef.current, glyphRef.current);
|
|
154
|
+
useLayoutEffect(() => {
|
|
155
|
+
const viewport = viewportRef.current;
|
|
156
|
+
const measure = measureRef.current;
|
|
157
|
+
const refresh = () => setView(refreshLayout());
|
|
158
|
+
refresh();
|
|
159
|
+
const observer = new ResizeObserver(refresh);
|
|
160
|
+
observer.observe(viewport);
|
|
161
|
+
observer.observe(measure);
|
|
162
|
+
return () => observer.disconnect();
|
|
163
|
+
}, [layout, text, softWrap, fontSize]);
|
|
164
|
+
useLayoutEffect(() => {
|
|
165
|
+
const textarea = textareaRef.current;
|
|
166
|
+
if (selection.start !== textarea.selectionStart ||
|
|
167
|
+
selection.end !== textarea.selectionEnd ||
|
|
168
|
+
selection.direction !== textarea.selectionDirection) {
|
|
169
|
+
textarea.setSelectionRange(selection.start, selection.end, selection.direction);
|
|
170
|
+
}
|
|
171
|
+
}, [selection.start, selection.end, selection.direction, text]);
|
|
172
|
+
useLayoutEffect(() => {
|
|
173
|
+
if (scrollTop !== undefined)
|
|
174
|
+
viewportRef.current.scrollTop = scrollTop;
|
|
175
|
+
}, [scrollTop]);
|
|
176
|
+
const reveal = (offset) => {
|
|
177
|
+
const viewport = viewportRef.current;
|
|
178
|
+
if (!viewport || !measureRef.current || !glyphRef.current)
|
|
179
|
+
return;
|
|
180
|
+
const currentView = refreshLayout();
|
|
181
|
+
setView(currentView);
|
|
182
|
+
if (!currentView.lines.length)
|
|
183
|
+
return;
|
|
184
|
+
const top = findLineAtOffset(currentView.lines, offset).y + padding;
|
|
185
|
+
if (top < viewport.scrollTop || top + lineHeight > viewport.scrollTop + viewport.clientHeight) {
|
|
186
|
+
viewport.scrollTop = top - viewport.clientHeight / 2;
|
|
187
|
+
}
|
|
188
|
+
};
|
|
189
|
+
const revealHandler = useRef(reveal);
|
|
190
|
+
useLayoutEffect(() => { revealHandler.current = reveal; });
|
|
191
|
+
const [controller] = useState(() => ({
|
|
192
|
+
focus: () => textareaRef.current?.focus({ preventScroll: true }),
|
|
193
|
+
revealOffset: offset => revealHandler.current(offset),
|
|
194
|
+
}));
|
|
195
|
+
useLayoutEffect(() => {
|
|
196
|
+
if (!onController)
|
|
197
|
+
return;
|
|
198
|
+
onController(controller);
|
|
199
|
+
return () => onController(null);
|
|
200
|
+
}, [onController, controller]);
|
|
201
|
+
useLayoutEffect(() => {
|
|
202
|
+
if (revealOffset != null)
|
|
203
|
+
reveal(revealOffset);
|
|
204
|
+
}, [revealOffset, view, lineHeight]);
|
|
205
|
+
const reportSelection = () => {
|
|
206
|
+
const textarea = textareaRef.current;
|
|
207
|
+
if (disabled || !textarea)
|
|
208
|
+
return;
|
|
209
|
+
const next = readSelection(textarea);
|
|
210
|
+
if (next.start === selection.start && next.end === selection.end &&
|
|
211
|
+
(next.start === next.end || next.direction === selection.direction))
|
|
212
|
+
return;
|
|
213
|
+
coalescing.interrupt();
|
|
214
|
+
onSelectionChange?.(next);
|
|
215
|
+
};
|
|
216
|
+
const selectionHandler = useRef(reportSelection);
|
|
217
|
+
selectionHandler.current = reportSelection;
|
|
218
|
+
useEffect(() => {
|
|
219
|
+
const textarea = textareaRef.current;
|
|
220
|
+
const listener = () => selectionHandler.current();
|
|
221
|
+
textarea.addEventListener("selectionchange", listener);
|
|
222
|
+
return () => textarea.removeEventListener("selectionchange", listener);
|
|
223
|
+
}, []);
|
|
224
|
+
useEffect(() => () => coalescing.dispose(), [coalescing]);
|
|
225
|
+
const viewport = viewportRef.current;
|
|
226
|
+
const visibleRange = viewport
|
|
227
|
+
? calculateVisibleLineRange(viewport, view.lines.length, lineHeight, padding)
|
|
228
|
+
: emptyLines;
|
|
229
|
+
const wrapping = {
|
|
230
|
+
whiteSpace: softWrap ? "pre-wrap" : "pre",
|
|
231
|
+
overflowWrap: softWrap ? "break-word" : "normal",
|
|
232
|
+
};
|
|
233
|
+
const textLayer = {
|
|
234
|
+
...wrapping,
|
|
235
|
+
position: "absolute",
|
|
236
|
+
boxSizing: "border-box",
|
|
237
|
+
width: "100%",
|
|
238
|
+
paddingTop: `${padding}px`,
|
|
239
|
+
};
|
|
240
|
+
return (jsxs("div", { class: "editor-deluxe", style: {
|
|
241
|
+
position: "relative",
|
|
242
|
+
width: "100%",
|
|
243
|
+
height: "100%",
|
|
244
|
+
minWidth: 0,
|
|
245
|
+
minHeight: 0,
|
|
246
|
+
overflow: "hidden",
|
|
247
|
+
fontFamily: "monospace",
|
|
248
|
+
fontWeight: 400,
|
|
249
|
+
fontVariantLigatures: "none",
|
|
250
|
+
letterSpacing: "normal",
|
|
251
|
+
wordSpacing: "normal",
|
|
252
|
+
fontSize: `${fontSize}px`,
|
|
253
|
+
lineHeight: `${lineHeight}px`,
|
|
254
|
+
}, children: [jsx("span", { ref: glyphRef, "aria-hidden": "true", style: {
|
|
255
|
+
position: "absolute", visibility: "hidden", whiteSpace: "pre",
|
|
256
|
+
}, children: "M" }), jsx("div", { class: "editor-scroll", ref: viewportRef, style: {
|
|
257
|
+
height: "100%",
|
|
258
|
+
overflowX: softWrap ? "hidden" : "auto",
|
|
259
|
+
overflowY: "auto",
|
|
260
|
+
scrollbarGutter: "stable",
|
|
261
|
+
}, onClick: event => {
|
|
262
|
+
if (event.target === event.currentTarget)
|
|
263
|
+
controller.focus();
|
|
264
|
+
}, onScroll: event => {
|
|
265
|
+
const element = event.currentTarget;
|
|
266
|
+
coalescing.interrupt();
|
|
267
|
+
onScroll?.(element.scrollTop);
|
|
268
|
+
updateOverlay.current?.(calculateVisibleLineRange(element, view.lines.length, lineHeight, padding));
|
|
269
|
+
}, children: jsxs("div", { class: "editor-document", style: {
|
|
270
|
+
position: "relative",
|
|
271
|
+
width: softWrap ? "100%" : "max-content",
|
|
272
|
+
minWidth: "100%",
|
|
273
|
+
}, children: [jsx("textarea", { ref: textareaRef, "aria-label": ariaLabel, value: text, wrap: softWrap ? "soft" : "off", spellcheck: false, disabled: disabled, style: {
|
|
274
|
+
...wrapping,
|
|
275
|
+
position: "relative",
|
|
276
|
+
zIndex: 1,
|
|
277
|
+
display: "block",
|
|
278
|
+
boxSizing: "border-box",
|
|
279
|
+
fieldSizing: "content",
|
|
280
|
+
width: softWrap ? "100%" : "auto",
|
|
281
|
+
minWidth: "100%",
|
|
282
|
+
minHeight: `${lineHeight + 2 * padding}px`,
|
|
283
|
+
margin: 0,
|
|
284
|
+
padding: `${padding}px`,
|
|
285
|
+
border: 0,
|
|
286
|
+
resize: "none",
|
|
287
|
+
overflow: "hidden",
|
|
288
|
+
background: "transparent",
|
|
289
|
+
color: showOverlay ? "rgb(0 0 0 / 25%)" : "black",
|
|
290
|
+
caretColor: "black",
|
|
291
|
+
font: "inherit",
|
|
292
|
+
fontVariantLigatures: "inherit",
|
|
293
|
+
}, onInput: event => {
|
|
294
|
+
const textarea = event.currentTarget;
|
|
295
|
+
const { inputType = "", isComposing = false } = event;
|
|
296
|
+
const input = {
|
|
297
|
+
text: textarea.value,
|
|
298
|
+
selection: readSelection(textarea),
|
|
299
|
+
inputType,
|
|
300
|
+
isComposing,
|
|
301
|
+
coalescingKey: coalescing.input(inputType),
|
|
302
|
+
};
|
|
303
|
+
if (runInputTransaction)
|
|
304
|
+
runInputTransaction(input, () => onInput(input));
|
|
305
|
+
else
|
|
306
|
+
onInput(input);
|
|
307
|
+
}, onSelect: reportSelection, onFocus: () => { coalescing.interrupt(); onFocus?.(); }, onBlur: () => { coalescing.interrupt(); onBlur?.(); } }), jsxs("div", { class: "editor-overlay", "aria-hidden": "true", style: {
|
|
308
|
+
position: "absolute",
|
|
309
|
+
inset: `0 ${padding}px`,
|
|
310
|
+
overflow: "clip",
|
|
311
|
+
pointerEvents: "none",
|
|
312
|
+
}, children: [jsx("div", { "data-text-view-part": "measure", ref: measureRef, style: { ...textLayer, color: "transparent" }, children: measureLines }), showOverlay && (jsx(ContentView, { lines: view.lines, visibleRange: visibleRange, text: text, attributes: runs, style: textLayer, scrollHandler: updateOverlay }))] })] }) })] }));
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
export { EditCoalescing, TextView };
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { AttributedString } from "@kvndy/attributed-string";
|
|
2
|
+
import type { TextInput, TextSelection } from "./types.js";
|
|
3
|
+
export interface TextViewProps {
|
|
4
|
+
value: AttributedString;
|
|
5
|
+
selection: TextSelection;
|
|
6
|
+
ariaLabel?: string;
|
|
7
|
+
onController?: (controller: TextViewController | null) => void;
|
|
8
|
+
scrollTop?: number;
|
|
9
|
+
softWrap?: boolean;
|
|
10
|
+
fontSize?: number;
|
|
11
|
+
highlighted?: boolean;
|
|
12
|
+
disabled?: boolean;
|
|
13
|
+
revealOffset?: number | null;
|
|
14
|
+
onInput: (input: TextInput) => void;
|
|
15
|
+
/** Call apply once, synchronously, inside the app's edit transaction. */
|
|
16
|
+
runInputTransaction?: (input: TextInput, apply: () => void) => void;
|
|
17
|
+
onSelectionChange?: (selection: TextSelection) => void;
|
|
18
|
+
onScroll?: (scrollTop: number) => void;
|
|
19
|
+
onFocus?: () => void;
|
|
20
|
+
onBlur?: () => void;
|
|
21
|
+
}
|
|
22
|
+
export interface TextViewController {
|
|
23
|
+
focus(): void;
|
|
24
|
+
revealOffset(offset: number): void;
|
|
25
|
+
}
|
|
26
|
+
export declare function TextView({ value: { text, runs }, selection, ariaLabel, onController, scrollTop, softWrap, fontSize, highlighted, disabled, revealOffset, onInput, runInputTransaction, onSelectionChange, onScroll, onFocus, onBlur, }: TextViewProps): import("preact").JSX.Element;
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { TextRange } from "@kvndy/attributed-string";
|
|
2
|
+
export interface TextSelection extends TextRange {
|
|
3
|
+
readonly direction: "forward" | "backward" | "none";
|
|
4
|
+
}
|
|
5
|
+
export interface TextInput {
|
|
6
|
+
readonly text: string;
|
|
7
|
+
readonly selection: TextSelection;
|
|
8
|
+
readonly inputType: string;
|
|
9
|
+
readonly isComposing: boolean;
|
|
10
|
+
readonly coalescingKey: symbol;
|
|
11
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { type LineDescriptor } from "@kvndy/glyph-metrics";
|
|
2
|
+
export declare function createLayoutState(): {
|
|
3
|
+
initialView: {
|
|
4
|
+
lines: LineDescriptor[];
|
|
5
|
+
height: number;
|
|
6
|
+
};
|
|
7
|
+
refresh(text: string, softWrap: boolean, viewport: HTMLElement, measure: HTMLElement, glyph: HTMLElement): {
|
|
8
|
+
lines: LineDescriptor[];
|
|
9
|
+
height: number;
|
|
10
|
+
};
|
|
11
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,41 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
"name": "@kvndy/text-view",
|
|
3
|
+
"version": "0.0.2",
|
|
4
|
+
"description": "Preact windowing/virtualized textarea for syntax highlighting",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "Kevin Doughty",
|
|
7
|
+
"type": "module",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://gitlab.com/kevindoughty/attributed-string.git",
|
|
11
|
+
"directory": "text-view"
|
|
12
|
+
},
|
|
13
|
+
"files": [
|
|
14
|
+
"dist"
|
|
15
|
+
],
|
|
16
|
+
"main": "./dist/main.js",
|
|
17
|
+
"types": "./dist/main.d.ts",
|
|
18
|
+
"exports": {
|
|
19
|
+
".": {
|
|
20
|
+
"types": "./dist/main.d.ts",
|
|
21
|
+
"import": "./dist/main.js"
|
|
22
|
+
}
|
|
23
|
+
},
|
|
24
|
+
"scripts": {
|
|
25
|
+
"build": "tsc && rollup -c"
|
|
26
|
+
},
|
|
27
|
+
"devDependencies": {
|
|
28
|
+
"rollup": "^4.0.0",
|
|
29
|
+
"typescript": "^7.0.2"
|
|
30
|
+
},
|
|
31
|
+
"dependencies": {
|
|
32
|
+
"@kvndy/glyph-metrics": "^0.0.1",
|
|
33
|
+
"@kvndy/attributed-string": "^0.0.1"
|
|
34
|
+
},
|
|
35
|
+
"peerDependencies": {
|
|
36
|
+
"preact": "^11.2.0"
|
|
37
|
+
},
|
|
38
|
+
"keywords": [
|
|
39
|
+
"Preact", "textarea", "virtualized", "windowing"
|
|
40
|
+
]
|
|
41
|
+
}
|