@mwillbanks/tuil-editor 0.0.0 → 1.0.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mike Willbanks
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,45 +1,106 @@
1
- # @mwillbanks/tuil-editor
1
+ # tuil
2
+
3
+ <p align="center">
4
+ <img src="logo.svg" alt="tuil terminal interface logo" width="220" />
5
+ </p>
2
6
 
3
- ## ⚠️ IMPORTANT NOTICE ⚠️
7
+ <p align="center">
8
+ <strong>Terminal UI, without the runtime tax.</strong><br />
9
+ A renderer-neutral terminal application runtime with React Ink compatibility.
10
+ </p>
4
11
 
5
- **This package is created solely for the purpose of setting up OIDC (OpenID Connect) trusted publishing with npm.**
12
+ <p align="center">
13
+ <a href="https://www.npmjs.com/package/@mwillbanks/tuil"><img alt="npm" src="https://img.shields.io/npm/v/@mwillbanks/tuil" /></a>
14
+ <a href="https://github.com/mwillbanks/tuil/actions/workflows/ci.yml"><img alt="CI" src="https://github.com/mwillbanks/tuil/actions/workflows/ci.yml/badge.svg" /></a>
15
+ <a href="https://app.codecov.io/gh/mwillbanks/tuil"><img alt="Coverage" src="https://codecov.io/gh/mwillbanks/tuil/branch/main/graph/badge.svg" /></a>
16
+ <a href="LICENSE"><img alt="MIT" src="https://img.shields.io/badge/license-MIT-blue.svg" /></a>
17
+ </p>
6
18
 
7
- This is **NOT** a functional package and contains **NO** code or functionality beyond the OIDC setup configuration.
19
+ tuil combines a renderer-neutral application runtime, React Ink compatibility,
20
+ deterministic cell rendering, typed forms and routes, focus and hotkey
21
+ management, cancellable operations, persistent workflows, plugins, themes,
22
+ source-owned components, portable stories, and semantic testing. Applications
23
+ share one set of runtime contracts across interactive terminals, redirected
24
+ output, tests, documentation, and Storybook.
8
25
 
9
- ## Purpose
26
+ **[Read the documentation](https://mwillbanks.github.io/tuil/)**
10
27
 
11
- This package exists to:
12
- 1. Configure OIDC trusted publishing for the package name `@mwillbanks/tuil-editor`
13
- 2. Enable secure, token-less publishing from CI/CD workflows
14
- 3. Establish provenance for packages published under this name
28
+ ## Why tuil
15
29
 
16
- ## What is OIDC Trusted Publishing?
30
+ | Capability | What it provides |
31
+ | --- | --- |
32
+ | Application runtime | Explicit services, lifecycle, capabilities, typed events, and teardown |
33
+ | Terminal-native UX | Focus scopes, hotkey sequences, overlays, forms, routing, and responsive layouts |
34
+ | Deterministic output | Interactive, static, text, silent, and JSON modes from the same application |
35
+ | Portable stories | One catalog for live previews, Storybook, snapshots, and generated documentation |
36
+ | Semantic testing | Query roles and labels instead of brittle terminal coordinates |
37
+ | Source ownership | Install inspectable components and blocks through the registry CLI |
38
+ | Live composition | Observable plugin extensions and capability-normalized theme switching |
17
39
 
18
- OIDC trusted publishing allows package maintainers to publish packages directly from their CI/CD workflows without needing to manage npm access tokens. Instead, it uses OpenID Connect to establish trust between the CI/CD provider (like GitHub Actions) and npm.
40
+ ## Install
19
41
 
20
- ## Setup Instructions
42
+ Install the framework, Ink adapter, renderer, and React:
21
43
 
22
- To properly configure OIDC trusted publishing for this package:
44
+ ```npm
45
+ npm install @mwillbanks/tuil @mwillbanks/tuil-ink ink react
46
+ ```
23
47
 
24
- 1. Go to [npmjs.com](https://www.npmjs.com/) and navigate to your package settings
25
- 2. Configure the trusted publisher (e.g., GitHub Actions)
26
- 3. Specify the repository and workflow that should be allowed to publish
27
- 4. Use the configured workflow to publish your actual package
48
+ Create a project with the self-hosted initializer:
28
49
 
29
- ## DO NOT USE THIS PACKAGE
50
+ ```npm
51
+ npx @mwillbanks/tuil init
52
+ ```
30
53
 
31
- This package is a placeholder for OIDC configuration only. It:
32
- - Contains no executable code
33
- - Provides no functionality
34
- - Should not be installed as a dependency
35
- - Exists only for administrative purposes
54
+ The initializer validates the destination before writing and can install
55
+ registry components and bundled Agent Skills alongside the generated
56
+ application.
36
57
 
37
- ## More Information
58
+ ## Ecosystem
38
59
 
39
- For more details about npm's trusted publishing feature, see:
40
- - [npm Trusted Publishing Documentation](https://docs.npmjs.com/generating-provenance-statements)
41
- - [GitHub Actions OIDC Documentation](https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/about-security-hardening-with-openid-connect)
60
+ - `@mwillbanks/tuil` — application creation, runtime services, and the CLI
61
+ - `@mwillbanks/tuil-ink` — Ink rendering, input, semantics, and overlays
62
+ - `@mwillbanks/tuil-form` — typed forms, validation, and controlled fields
63
+ - `@mwillbanks/tuil-router` — typed routes, guards, history, and layouts
64
+ - `@mwillbanks/tuil-operations` — observable asynchronous work and cancellation
65
+ - `@mwillbanks/tuil-workflow` — persistent, resumable multi-step workflows
66
+ - `@mwillbanks/tuil-plugin` — dependency-aware plugin lifecycle
67
+ - `@mwillbanks/tuil-theme` — tokens, variants, utilities, and theme registries
68
+ - `@mwillbanks/tuil-testing` — portable stories and semantic assertions
69
+ - `@mwillbanks/tuil-testing-ink` — Ink-backed application test rendering
70
+ - `@mwillbanks/tuil-story` — browser, Storybook, snapshot, and docs adapters
42
71
 
43
- ---
72
+ The complete package map, architecture, component registry, examples, skills,
73
+ and migration guidance live in the
74
+ [documentation](https://mwillbanks.github.io/tuil/).
44
75
 
45
- **Maintained for OIDC setup purposes only**
76
+ ## Development
77
+
78
+ Bun 1.3.14 or newer is required.
79
+
80
+ ```npm
81
+ bun install --frozen-lockfile
82
+ bun run check
83
+ bun run docs
84
+ ```
85
+
86
+ `bun run check` validates formatting and types, runs coverage-gated tests,
87
+ builds every publication artifact, and audits the project with Fallow. Run the
88
+ dependency security gate separately:
89
+
90
+ ```npm
91
+ bun run security
92
+ ```
93
+
94
+ See [CONTRIBUTING.md](CONTRIBUTING.md) for the complete workflow and pull
95
+ request expectations. Usage questions and maintenance expectations are in
96
+ [SUPPORT.md](SUPPORT.md); community participation is governed by the
97
+ [Code of Conduct](CODE_OF_CONDUCT.md).
98
+
99
+ ## Security
100
+
101
+ Do not report vulnerabilities in a public issue. Follow
102
+ [SECURITY.md](SECURITY.md) to submit a private GitHub Security Advisory.
103
+
104
+ ## License
105
+
106
+ MIT
package/buffer.d.ts ADDED
@@ -0,0 +1,25 @@
1
+ import { type EditorCommand, type EditorDecoration, type EditorDiagnostic, type EditorPosition, type EditorProvider, type EditorProviderOptions, type EditorRange, type EditorSession, type EditorSnapshot, type EditorTransaction } from "./index";
2
+ export declare class TextBufferSession implements EditorSession {
3
+ #private;
4
+ constructor(options?: EditorProviderOptions);
5
+ snapshot(): EditorSnapshot;
6
+ dispatch(transaction: EditorTransaction): EditorSnapshot;
7
+ execute(command: string | EditorCommand, argument?: unknown): boolean | Promise<boolean>;
8
+ copy(): string | Promise<string>;
9
+ cut(): string | Promise<string>;
10
+ paste(value?: string): boolean | Promise<boolean>;
11
+ undo(): boolean;
12
+ redo(): boolean;
13
+ search(query: string | RegExp): readonly EditorRange[];
14
+ replace(query: string | RegExp, replacement: string, all?: boolean): number;
15
+ serialize(format?: "text" | "json" | "markdown"): string;
16
+ subscribe(observer: (snapshot: EditorSnapshot) => void): () => void;
17
+ setDecorations(decorations: readonly EditorDecoration[]): void;
18
+ setDiagnostics(diagnostics: readonly EditorDiagnostic[]): void;
19
+ setMode(mode: string): void;
20
+ setViewportAnchor(anchor: EditorPosition): void;
21
+ dispose(): void;
22
+ }
23
+ export declare const textBufferProvider: EditorProvider;
24
+ export declare function insertText(session: EditorSession, value: string): EditorSnapshot;
25
+ //# sourceMappingURL=buffer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"buffer.d.ts","sourceRoot":"","sources":["../src/buffer.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,KAAK,aAAa,EAClB,KAAK,gBAAgB,EACrB,KAAK,gBAAgB,EACrB,KAAK,cAAc,EACnB,KAAK,cAAc,EACnB,KAAK,qBAAqB,EAC1B,KAAK,WAAW,EAEhB,KAAK,aAAa,EAClB,KAAK,cAAc,EACnB,KAAK,iBAAiB,EAGvB,MAAM,SAAS,CAAC;AA8FjB,qBAAa,iBAAkB,YAAW,aAAa;;IAmBrD,YAAY,OAAO,GAAE,qBAA0B,EAW9C;IAED,QAAQ,IAAI,cAAc,CAiBzB;IAED,QAAQ,CAAC,WAAW,EAAE,iBAAiB,GAAG,cAAc,CAcvD;IAyCD,OAAO,CACL,OAAO,EAAE,MAAM,GAAG,aAAa,EAC/B,QAAQ,CAAC,EAAE,OAAO,GACjB,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAM5B;IA+BD,IAAI,IAAI,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAW/B;IAED,GAAG,IAAI,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAE9B;IAED,KAAK,CAAC,KAAK,CAAC,EAAE,MAAM,GAAG,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAEhD;IAED,IAAI,IAAI,OAAO,CAEd;IAED,IAAI,IAAI,OAAO,CAEd;IAkBD,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,WAAW,EAAE,CAerD;IAED,OAAO,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,WAAW,EAAE,MAAM,EAAE,GAAG,UAAO,GAAG,MAAM,CAWvE;IAED,SAAS,CAAC,MAAM,GAAE,MAAM,GAAG,MAAM,GAAG,UAAmB,GAAG,MAAM,CAS/D;IAMD,SAAS,CAAC,QAAQ,EAAE,CAAC,QAAQ,EAAE,cAAc,KAAK,IAAI,GAAG,MAAM,IAAI,CAIlE;IAED,cAAc,CAAC,WAAW,EAAE,SAAS,gBAAgB,EAAE,GAAG,IAAI,CAG7D;IAED,cAAc,CAAC,WAAW,EAAE,SAAS,gBAAgB,EAAE,GAAG,IAAI,CAG7D;IAED,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAG1B;IAED,iBAAiB,CAAC,MAAM,EAAE,cAAc,GAAG,IAAI,CAG9C;IAED,OAAO,IAAI,IAAI,CAKd;CAUF;AAwCD,eAAO,MAAM,kBAAkB,EAAE,cAwB/B,CAAC;AAEH,wBAAgB,UAAU,CACxB,OAAO,EAAE,aAAa,EACtB,KAAK,EAAE,MAAM,GACZ,cAAc,CAKhB"}
package/buffer.js ADDED
@@ -0,0 +1,466 @@
1
+ // @bun
2
+ // src/index.ts
3
+ function validateEditorProvider(providers, defaultId, provider, options) {
4
+ if (!provider.id.trim() || !provider.version.trim()) {
5
+ throw new Error("Editor providers require a stable id and version");
6
+ }
7
+ if (providers.has(provider.id) && !options.replace) {
8
+ throw new Error(`Editor provider "${provider.id}" is already registered`);
9
+ }
10
+ const replacesDefault = options.default && defaultId && defaultId !== provider.id;
11
+ if (replacesDefault && !options.replace) {
12
+ throw new Error(`Default editor "${defaultId}" cannot be replaced accidentally`);
13
+ }
14
+ }
15
+ function supportsOptional(required, provided) {
16
+ return !required || !provided || provided.includes(required);
17
+ }
18
+ function supportsEditorRequirements(provider, requirements) {
19
+ if (requirements.documentType && provider.documentTypes && !provider.documentTypes.includes(requirements.documentType)) {
20
+ return false;
21
+ }
22
+ const capabilities = requirements.capabilities ?? [];
23
+ if (!capabilities.every((capability) => provider.capabilities.has(capability)))
24
+ return false;
25
+ return supportsOptional(requirements.renderer, provider.rendererCapabilities) && supportsOptional(requirements.input, provider.inputCapabilities) && supportsOptional(requirements.staticMode, provider.staticModes);
26
+ }
27
+
28
+ class EditorProviderRegistry {
29
+ #providers;
30
+ #defaultId;
31
+ constructor() {
32
+ this.#providers = new Map;
33
+ this.#defaultId = undefined;
34
+ }
35
+ register(provider, options = {}) {
36
+ validateEditorProvider(this.#providers, this.#defaultId, provider, options);
37
+ this.#providers.set(provider.id, provider);
38
+ if (options.default || !this.#defaultId)
39
+ this.#defaultId = provider.id;
40
+ return Object.freeze({
41
+ provider,
42
+ default: this.#defaultId === provider.id,
43
+ dispose: this.#providerDisposer(provider)
44
+ });
45
+ }
46
+ #providerDisposer(provider) {
47
+ let disposed = false;
48
+ return () => {
49
+ if (disposed || this.#providers.get(provider.id) !== provider)
50
+ return;
51
+ disposed = true;
52
+ this.#providers.delete(provider.id);
53
+ if (this.#defaultId === provider.id) {
54
+ this.#defaultId = this.#providers.keys().next().value;
55
+ }
56
+ };
57
+ }
58
+ resolve(id, requirements = {}) {
59
+ const preferred = this.#defaultId ? this.#providers.get(this.#defaultId) : undefined;
60
+ const candidates = id ? [this.#providers.get(id)] : [preferred, ...this.#providers.values()];
61
+ const provider = candidates.find((candidate) => candidate !== undefined && supportsEditorRequirements(candidate, requirements));
62
+ if (!provider) {
63
+ throw new Error(`No compatible editor provider found${id ? ` for "${id}"` : ""}`);
64
+ }
65
+ return provider;
66
+ }
67
+ list() {
68
+ return Object.freeze([...this.#providers.values()]);
69
+ }
70
+ }
71
+ function position(line, column) {
72
+ return Object.freeze({
73
+ line: Math.max(0, Math.floor(line)),
74
+ column: Math.max(0, Math.floor(column))
75
+ });
76
+ }
77
+ function selection(anchor, head = anchor, primary = true) {
78
+ return Object.freeze({
79
+ anchor: position(anchor.line, anchor.column),
80
+ head: position(head.line, head.column),
81
+ primary
82
+ });
83
+ }
84
+
85
+ // src/buffer.ts
86
+ import { createGlobalSearchExpression } from "@mwillbanks/tuil-core";
87
+
88
+ // src/session-commands.ts
89
+ function executeClipboardCommand(session, command, argument) {
90
+ if (command === "copy")
91
+ return Promise.resolve(session.copy()).then(() => true);
92
+ if (command === "cut")
93
+ return Promise.resolve(session.cut()).then(() => true);
94
+ if (command === "paste") {
95
+ return session.paste(typeof argument === "string" ? argument : undefined);
96
+ }
97
+ return;
98
+ }
99
+ function replaceSelections(session, content) {
100
+ const snapshot = session.snapshot();
101
+ if (content === undefined || snapshot.readOnly)
102
+ return false;
103
+ session.dispatch({
104
+ changes: snapshot.selections.map((range) => ({
105
+ range,
106
+ insert: content
107
+ }))
108
+ });
109
+ return true;
110
+ }
111
+ function cutSelections(session, copied) {
112
+ const remove = (value) => {
113
+ replaceSelections(session, "");
114
+ return value;
115
+ };
116
+ return copied instanceof Promise ? copied.then(remove) : remove(copied);
117
+ }
118
+ function pasteSelections(session, clipboard, value) {
119
+ if (value !== undefined)
120
+ return replaceSelections(session, value);
121
+ if (!clipboard)
122
+ return false;
123
+ return Promise.resolve(clipboard.read()).then((content) => replaceSelections(session, content));
124
+ }
125
+
126
+ // src/buffer.ts
127
+ var graphemeSegmenter = new Intl.Segmenter(undefined, {
128
+ granularity: "grapheme"
129
+ });
130
+ function graphemes(value) {
131
+ return Object.freeze([...graphemeSegmenter.segment(value)].map((segment) => segment.segment));
132
+ }
133
+ function maskText(value) {
134
+ return value.split(`
135
+ `).map((line) => "\u2022".repeat(graphemes(line).length)).join(`
136
+ `);
137
+ }
138
+ function starts(value) {
139
+ const result = [0];
140
+ for (let index = 0;index < value.length; index += 1) {
141
+ if (value[index] === `
142
+ `)
143
+ result.push(index + 1);
144
+ }
145
+ return result;
146
+ }
147
+ function clamp(value, target) {
148
+ const lines = value.split(`
149
+ `);
150
+ const line = Math.min(Math.max(0, target.line), Math.max(0, lines.length - 1));
151
+ return position(line, Math.min(Math.max(0, target.column), graphemes(lines[line] ?? "").length));
152
+ }
153
+ function offsetAt(value, target) {
154
+ const safe = clamp(value, target);
155
+ return (starts(value)[safe.line] ?? 0) + graphemes(value.split(`
156
+ `)[safe.line] ?? "").slice(0, safe.column).join("").length;
157
+ }
158
+ function positionAt(value, offset) {
159
+ const safe = Math.max(0, Math.min(value.length, offset));
160
+ const lineStarts = starts(value);
161
+ let line = 0;
162
+ for (let index = 0;index < lineStarts.length; index += 1) {
163
+ if ((lineStarts[index] ?? 0) <= safe)
164
+ line = index;
165
+ else
166
+ break;
167
+ }
168
+ return position(line, graphemes(value.slice(lineStarts[line] ?? 0, safe)).length);
169
+ }
170
+ function offsets(value, range) {
171
+ const anchor = offsetAt(value, range.anchor);
172
+ const head = offsetAt(value, range.head);
173
+ return anchor <= head ? [anchor, head] : [head, anchor];
174
+ }
175
+ function freezeSelections(value, items) {
176
+ return Object.freeze(items.map((item, index) => selection(clamp(value, item.anchor), clamp(value, item.head), item.primary ?? index === 0)));
177
+ }
178
+
179
+ class TextBufferSession {
180
+ #id;
181
+ #type;
182
+ #readOnly;
183
+ #masked;
184
+ #clipboard;
185
+ #onDocumentChange;
186
+ #observers = new Set;
187
+ #undo = [];
188
+ #redo = [];
189
+ #text;
190
+ #version = 0;
191
+ #selections;
192
+ #decorations = [];
193
+ #diagnostics = [];
194
+ #mode;
195
+ #viewportAnchor;
196
+ #disposed = false;
197
+ constructor(options = {}) {
198
+ this.#id = options.id ?? "document";
199
+ this.#type = options.documentType ?? "text/plain";
200
+ this.#text = options.value ?? "";
201
+ this.#readOnly = options.readOnly ?? false;
202
+ this.#masked = options.masked ?? false;
203
+ this.#clipboard = options.clipboard;
204
+ this.#onDocumentChange = options.onDocumentChange;
205
+ this.#mode = options.mode ?? "insert";
206
+ this.#viewportAnchor = options.viewportAnchor;
207
+ this.#selections = [selection(position(0, 0))];
208
+ }
209
+ snapshot() {
210
+ return Object.freeze({
211
+ document: Object.freeze({
212
+ id: this.#id,
213
+ type: this.#type,
214
+ version: this.#version,
215
+ text: this.#exportText()
216
+ }),
217
+ selections: this.#selections,
218
+ decorations: this.#decorations,
219
+ diagnostics: this.#diagnostics,
220
+ mode: this.#mode,
221
+ readOnly: this.#readOnly,
222
+ canUndo: this.#undo.length > 0,
223
+ canRedo: this.#redo.length > 0,
224
+ viewportAnchor: this.#viewportAnchor
225
+ });
226
+ }
227
+ dispatch(transaction) {
228
+ this.#assertActive();
229
+ const changes = [...transaction.changes ?? []];
230
+ if (changes.length > 0 && this.#readOnly) {
231
+ throw new Error("Editor session is read-only");
232
+ }
233
+ this.#recordTransactionHistory(changes, transaction.addToHistory);
234
+ const edits = prepareEdits(this.#text, changes);
235
+ this.#text = applyEdits(this.#text, edits);
236
+ this.#applyTransactionSelection(edits, transaction.selections);
237
+ if (changes.length > 0 || transaction.selections)
238
+ this.#version += 1;
239
+ if (changes.length > 0)
240
+ this.#onDocumentChange?.(this.#text);
241
+ this.#notify();
242
+ return this.snapshot();
243
+ }
244
+ #recordTransactionHistory(changes, addToHistory) {
245
+ if (changes.length === 0 || addToHistory === false)
246
+ return;
247
+ this.#undo.push({ text: this.#text, selections: this.#selections });
248
+ this.#redo.length = 0;
249
+ }
250
+ #applyTransactionSelection(edits, selections) {
251
+ if (selections) {
252
+ this.#selections = freezeSelections(this.#text, selections);
253
+ return;
254
+ }
255
+ if (edits.length === 0)
256
+ return;
257
+ this.#selections = edits.toSorted((left, right) => left.index - right.index).map((edit) => {
258
+ const precedingDelta = edits.filter((candidate) => candidate.offsets[0] < edit.offsets[0]).reduce((total, candidate) => total + candidate.change.insert.length - (candidate.offsets[1] - candidate.offsets[0]), 0);
259
+ return selection(positionAt(this.#text, edit.offsets[0] + edit.change.insert.length + precedingDelta));
260
+ });
261
+ }
262
+ execute(command, argument) {
263
+ this.#assertActive();
264
+ if (typeof command !== "string")
265
+ return command.execute(this, argument);
266
+ const clipboard = executeClipboardCommand(this, command, argument);
267
+ if (clipboard !== undefined)
268
+ return clipboard;
269
+ return this.#executeSelectionCommand(command);
270
+ }
271
+ #executeSelectionCommand(command) {
272
+ if (command === "select-all") {
273
+ this.#selections = [
274
+ selection(position(0, 0), positionAt(this.#text, this.#text.length))
275
+ ];
276
+ } else if (command === "delete-selection") {
277
+ this.dispatch({
278
+ changes: this.#selections.map((range) => ({ range, insert: "" }))
279
+ });
280
+ return true;
281
+ } else if (command === "cursor-start") {
282
+ this.dispatch({
283
+ selections: [selection(position(0, 0))],
284
+ addToHistory: false
285
+ });
286
+ return true;
287
+ } else if (command === "cursor-end") {
288
+ this.dispatch({
289
+ selections: [selection(positionAt(this.#text, this.#text.length))],
290
+ addToHistory: false
291
+ });
292
+ return true;
293
+ } else {
294
+ return false;
295
+ }
296
+ this.#notify();
297
+ return true;
298
+ }
299
+ copy() {
300
+ this.#assertActive();
301
+ const copied = this.#selections.map((range) => {
302
+ const [start, end] = offsets(this.#text, range);
303
+ const value = this.#text.slice(start, end);
304
+ return this.#masked ? maskText(value) : value;
305
+ }).join(`
306
+ `);
307
+ if (!this.#clipboard)
308
+ return copied;
309
+ return Promise.resolve(this.#clipboard.write(copied)).then(() => copied);
310
+ }
311
+ cut() {
312
+ return cutSelections(this, this.copy());
313
+ }
314
+ paste(value) {
315
+ return pasteSelections(this, this.#clipboard, value);
316
+ }
317
+ undo() {
318
+ return this.#restoreHistory(this.#undo, this.#redo);
319
+ }
320
+ redo() {
321
+ return this.#restoreHistory(this.#redo, this.#undo);
322
+ }
323
+ #restoreHistory(source, destination) {
324
+ this.#assertActive();
325
+ const entry = source.pop();
326
+ if (!entry)
327
+ return false;
328
+ destination.push({ text: this.#text, selections: this.#selections });
329
+ this.#text = entry.text;
330
+ this.#selections = entry.selections;
331
+ this.#version += 1;
332
+ this.#onDocumentChange?.(this.#text);
333
+ this.#notify();
334
+ return true;
335
+ }
336
+ search(query) {
337
+ this.#assertActive();
338
+ if (typeof query === "string" && query.length === 0)
339
+ return [];
340
+ const expression = createGlobalSearchExpression(query);
341
+ const ranges = [];
342
+ for (const match of this.#text.matchAll(expression)) {
343
+ ranges.push(Object.freeze({
344
+ anchor: positionAt(this.#text, match.index),
345
+ head: positionAt(this.#text, match.index + match[0].length)
346
+ }));
347
+ if (match[0].length === 0)
348
+ expression.lastIndex += 1;
349
+ }
350
+ return Object.freeze(ranges);
351
+ }
352
+ replace(query, replacement, all = true) {
353
+ const ranges = this.search(query);
354
+ const selected = all ? ranges : ranges.slice(0, 1);
355
+ if (selected.length === 0)
356
+ return 0;
357
+ this.dispatch({
358
+ changes: selected.map((range) => ({
359
+ range,
360
+ insert: replacement
361
+ }))
362
+ });
363
+ return selected.length;
364
+ }
365
+ serialize(format = "text") {
366
+ const text = this.#exportText();
367
+ return format === "json" ? JSON.stringify(this.#masked ? { type: this.#type, text, masked: true } : { type: this.#type, text }) : text;
368
+ }
369
+ #exportText() {
370
+ return this.#masked ? maskText(this.#text) : this.#text;
371
+ }
372
+ subscribe(observer) {
373
+ this.#assertActive();
374
+ this.#observers.add(observer);
375
+ return () => this.#observers.delete(observer);
376
+ }
377
+ setDecorations(decorations) {
378
+ this.#decorations = Object.freeze([...decorations]);
379
+ this.#notify();
380
+ }
381
+ setDiagnostics(diagnostics) {
382
+ this.#diagnostics = Object.freeze([...diagnostics]);
383
+ this.#notify();
384
+ }
385
+ setMode(mode) {
386
+ this.#mode = mode;
387
+ this.#notify();
388
+ }
389
+ setViewportAnchor(anchor) {
390
+ this.#viewportAnchor = clamp(this.#text, anchor);
391
+ this.#notify();
392
+ }
393
+ dispose() {
394
+ this.#disposed = true;
395
+ this.#observers.clear();
396
+ this.#undo.length = 0;
397
+ this.#redo.length = 0;
398
+ }
399
+ #notify() {
400
+ const snapshot = this.snapshot();
401
+ for (const observer of this.#observers)
402
+ observer(snapshot);
403
+ }
404
+ #assertActive() {
405
+ if (this.#disposed)
406
+ throw new Error("Editor session is disposed");
407
+ }
408
+ }
409
+ function prepareEdits(text, changes) {
410
+ const edits = changes.map((change, index) => ({
411
+ index,
412
+ change,
413
+ offsets: offsets(text, change.range)
414
+ })).sort((left, right) => right.offsets[0] - left.offsets[0]);
415
+ for (let index = 1;index < edits.length; index += 1) {
416
+ const previous = edits[index - 1];
417
+ const current = edits[index];
418
+ if (previous && current && current.offsets[1] > previous.offsets[0]) {
419
+ throw new Error("Editor transaction changes cannot overlap");
420
+ }
421
+ }
422
+ return edits;
423
+ }
424
+ function applyEdits(text, edits) {
425
+ let result = text;
426
+ for (const edit of edits) {
427
+ result = result.slice(0, edit.offsets[0]) + edit.change.insert + result.slice(edit.offsets[1]);
428
+ }
429
+ return result;
430
+ }
431
+ var textBufferProvider = Object.freeze({
432
+ id: "tuil-buffer",
433
+ version: "1",
434
+ capabilities: new Set([
435
+ "single-line",
436
+ "multiline",
437
+ "multiple-selections",
438
+ "history",
439
+ "search",
440
+ "replace",
441
+ "decorations",
442
+ "diagnostics",
443
+ "clipboard",
444
+ "masked",
445
+ "static"
446
+ ]),
447
+ documentTypes: [
448
+ "text/plain",
449
+ "text/markdown",
450
+ "text/code",
451
+ "application/query"
452
+ ],
453
+ staticModes: ["static", "json", "silent"],
454
+ create: (options) => new TextBufferSession(options)
455
+ });
456
+ function insertText(session, value) {
457
+ const changes = session.snapshot().selections.map((range) => ({ range, insert: value }));
458
+ return session.dispatch({ changes });
459
+ }
460
+ export {
461
+ textBufferProvider,
462
+ insertText,
463
+ TextBufferSession
464
+ };
465
+
466
+ //# debugId=362F11AA04103AD264756E2164756E21