@kvndy/text-view 0.0.0-stage → 0.0.1

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 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,7 @@
1
- # Temporary Holding Version
1
+ # Attributed String
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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.
@@ -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 {};
@@ -0,0 +1,9 @@
1
+ /** Supplies identity keys to the consumer's UndoManager.group; owns no history. */
2
+ export declare class EditCoalescing {
3
+ private key;
4
+ private timer;
5
+ private inputType;
6
+ interrupt(): void;
7
+ input(inputType: string): symbol;
8
+ dispose(): void;
9
+ }
package/dist/main.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ export { TextView, 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,285 @@
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", { id: "virtual", 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, scrollTop, softWrap = true, fontSize = 16, highlighted = true, disabled = false, revealOffset, onInput, 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
+ useLayoutEffect(() => {
154
+ const viewport = viewportRef.current;
155
+ const measure = measureRef.current;
156
+ const glyph = glyphRef.current;
157
+ const refresh = () => setView(layout.refresh(text, softWrap, viewport, measure, glyph));
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
+ useLayoutEffect(() => {
177
+ if (revealOffset == null || !view.lines.length)
178
+ return;
179
+ const viewport = viewportRef.current;
180
+ const top = findLineAtOffset(view.lines, revealOffset).y + padding;
181
+ if (top < viewport.scrollTop || top + lineHeight > viewport.scrollTop + viewport.clientHeight) {
182
+ viewport.scrollTop = top - viewport.clientHeight / 2;
183
+ }
184
+ }, [revealOffset, view.lines, lineHeight]);
185
+ const reportSelection = () => {
186
+ if (disabled)
187
+ return;
188
+ const next = readSelection(textareaRef.current);
189
+ if (next.start === selection.start && next.end === selection.end &&
190
+ (next.start === next.end || next.direction === selection.direction))
191
+ return;
192
+ coalescing.interrupt();
193
+ onSelectionChange?.(next);
194
+ };
195
+ const selectionHandler = useRef(reportSelection);
196
+ selectionHandler.current = reportSelection;
197
+ useEffect(() => {
198
+ const textarea = textareaRef.current;
199
+ const listener = () => selectionHandler.current();
200
+ textarea.addEventListener("selectionchange", listener);
201
+ return () => textarea.removeEventListener("selectionchange", listener);
202
+ }, []);
203
+ useEffect(() => () => coalescing.dispose(), [coalescing]);
204
+ const viewport = viewportRef.current;
205
+ const visibleRange = viewport
206
+ ? calculateVisibleLineRange(viewport, view.lines.length, lineHeight, padding)
207
+ : emptyLines;
208
+ const wrapping = {
209
+ whiteSpace: softWrap ? "pre-wrap" : "pre",
210
+ overflowWrap: softWrap ? "break-word" : "normal",
211
+ };
212
+ const textLayer = {
213
+ ...wrapping,
214
+ position: "absolute",
215
+ boxSizing: "border-box",
216
+ width: "100%",
217
+ paddingTop: `${padding}px`,
218
+ };
219
+ return (jsxs("div", { class: "editor-deluxe", style: {
220
+ position: "relative",
221
+ width: "100%",
222
+ height: "100%",
223
+ minWidth: 0,
224
+ minHeight: 0,
225
+ overflow: "hidden",
226
+ fontFamily: "monospace",
227
+ fontWeight: 400,
228
+ fontVariantLigatures: "none",
229
+ fontSize: `${fontSize}px`,
230
+ lineHeight: `${lineHeight}px`,
231
+ }, children: [jsx("span", { ref: glyphRef, "aria-hidden": "true", style: {
232
+ position: "absolute", visibility: "hidden", whiteSpace: "pre",
233
+ }, children: "M" }), jsx("div", { class: "editor-scroll", ref: viewportRef, style: {
234
+ height: "100%",
235
+ overflowX: softWrap ? "hidden" : "auto",
236
+ overflowY: "auto",
237
+ scrollbarGutter: "stable",
238
+ }, onScroll: event => {
239
+ const element = event.currentTarget;
240
+ coalescing.interrupt();
241
+ onScroll?.(element.scrollTop);
242
+ updateOverlay.current?.(calculateVisibleLineRange(element, view.lines.length, lineHeight, padding));
243
+ }, children: jsxs("div", { class: "editor-document", style: {
244
+ position: "relative",
245
+ width: softWrap ? "100%" : "max-content",
246
+ minWidth: "100%",
247
+ }, children: [jsx("textarea", { id: "textview", ref: textareaRef, "aria-label": ariaLabel, value: text, wrap: softWrap ? "soft" : "off", spellcheck: false, disabled: disabled, style: {
248
+ ...wrapping,
249
+ position: "relative",
250
+ zIndex: 1,
251
+ display: "block",
252
+ boxSizing: "border-box",
253
+ fieldSizing: "content",
254
+ width: softWrap ? "100%" : "auto",
255
+ minWidth: "100%",
256
+ minHeight: `${lineHeight + 2 * padding}px`,
257
+ margin: 0,
258
+ padding: `${padding}px`,
259
+ border: 0,
260
+ resize: "none",
261
+ overflow: "hidden",
262
+ background: "transparent",
263
+ color: showOverlay ? "rgb(0 0 0 / 25%)" : "black",
264
+ caretColor: "black",
265
+ font: "inherit",
266
+ fontVariantLigatures: "inherit",
267
+ }, onInput: event => {
268
+ const textarea = event.currentTarget;
269
+ const { inputType = "", isComposing = false } = event;
270
+ onInput({
271
+ text: textarea.value,
272
+ selection: readSelection(textarea),
273
+ inputType,
274
+ isComposing,
275
+ coalescingKey: coalescing.input(inputType),
276
+ });
277
+ }, onSelect: reportSelection, onFocus: () => { coalescing.interrupt(); onFocus?.(); }, onBlur: () => { coalescing.interrupt(); onBlur?.(); } }), jsxs("div", { class: "editor-overlay", "aria-hidden": "true", style: {
278
+ position: "absolute",
279
+ inset: `0 ${padding}px`,
280
+ overflow: "clip",
281
+ pointerEvents: "none",
282
+ }, children: [jsx("div", { id: "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 }))] })] }) })] }));
283
+ }
284
+
285
+ export { EditCoalescing, TextView };
@@ -0,0 +1,19 @@
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
+ scrollTop?: number;
8
+ softWrap?: boolean;
9
+ fontSize?: number;
10
+ highlighted?: boolean;
11
+ disabled?: boolean;
12
+ revealOffset?: number | null;
13
+ onInput: (input: TextInput) => void;
14
+ onSelectionChange?: (selection: TextSelection) => void;
15
+ onScroll?: (scrollTop: number) => void;
16
+ onFocus?: () => void;
17
+ onBlur?: () => void;
18
+ }
19
+ export declare function TextView({ value: { text, runs }, selection, ariaLabel, scrollTop, softWrap, fontSize, highlighted, disabled, revealOffset, onInput, onSelectionChange, onScroll, onFocus, onBlur, }: TextViewProps): import("preact").JSX.Element;
@@ -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
- "name": "@kvndy/text-view",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@kvndy/text-view",
3
+ "version": "0.0.1",
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
+ }