@mlightcad/mtext-input-box 0.1.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.
@@ -0,0 +1,2153 @@
1
+ import { CursorRenderer, TextBoxCursor, ThreeJsRendererAdapter } from '@mlightcad/text-box-cursor';
2
+ import { getColorByIndex, UnifiedRenderer, MTextAttachmentPoint, MTextFlowDirection } from '@mlightcad/mtext-renderer';
3
+ import * as THREE from 'three';
4
+ import { MTextContext, MTextLineAlignment } from '@mlightcad/mtext-parser';
5
+ import { defaultCharFormat, sameFormat } from './format';
6
+ import { MTextDocument } from '../model';
7
+ import { EditorUiAdapter } from '../controller';
8
+ import { MTextToolbar } from '../ui/toolbar';
9
+ /**
10
+ * Three.js based MText editor component with core text editing interaction.
11
+ */
12
+ export class MTextInputBox {
13
+ static activeEditor = null;
14
+ static sharedToolbar = null;
15
+ static sharedToolbarContainer = null;
16
+ static sharedToolbarFontFamiliesKey = '';
17
+ static instances = new Set();
18
+ scene;
19
+ camera;
20
+ mtextRenderer;
21
+ cursorRenderer;
22
+ static FALLBACK_LINE_ADVANCE_RATIO = 1.5;
23
+ width;
24
+ position;
25
+ enableWordWrap;
26
+ mtextString = '';
27
+ cursorIndex = 0;
28
+ selectionStart = 0;
29
+ selectionEnd = 0;
30
+ baseFormat;
31
+ currentFormat;
32
+ defaultTextStyle;
33
+ cursorLogic;
34
+ layoutContainer = { x: 0, y: 0, width: 1, height: 1 };
35
+ isDragging = false;
36
+ pendingCursorLineHint = null;
37
+ latestCursorLayoutData = {
38
+ containerBox: { x: 0, y: 0, width: 1, height: 1 },
39
+ charBoxes: []
40
+ };
41
+ renderedObject = null;
42
+ boundingBoxObject = null;
43
+ boundingBoxPadding = 1;
44
+ boundingBoxZOffset = 0.01;
45
+ rendererReady = false;
46
+ toolbarTheme = 'dark';
47
+ toolbarOffsetY = 10;
48
+ debugMode = false;
49
+ debugVisibility = {
50
+ showCharBoxes: true,
51
+ showLineIndices: true,
52
+ showCharIndices: true,
53
+ showChars: true
54
+ };
55
+ maxHistorySize = 100;
56
+ undoStack = [];
57
+ redoStack = [];
58
+ // MVC model/controller
59
+ document;
60
+ uiAdapter;
61
+ // IME bridge (encapsulated in component)
62
+ imeInput = null;
63
+ imeTarget = null;
64
+ lastImeTarget = null;
65
+ reopenTarget = null;
66
+ pointerTarget = null;
67
+ imeComposing = false;
68
+ imeFocusTimer = null;
69
+ closed = false;
70
+ toolbarEnabled = true;
71
+ toolbarContainer = null;
72
+ toolbarFontFamilies = null;
73
+ onImeKeyDown = (event) => {
74
+ if (!this.isActiveEditor())
75
+ return;
76
+ const ctrl = event.ctrlKey || event.metaKey;
77
+ const isPrintable = !ctrl && !event.altKey && event.key.length === 1;
78
+ if (isPrintable || event.isComposing || event.key === 'Process')
79
+ return;
80
+ const handled = this.handleKeyDown(event);
81
+ if (handled)
82
+ event.preventDefault();
83
+ };
84
+ onWindowKeyDown = (event) => {
85
+ if (!this.isActiveEditor())
86
+ return;
87
+ if (event.defaultPrevented)
88
+ return;
89
+ const target = event.target;
90
+ const tagName = target?.tagName ?? '';
91
+ const isNativeEditable = tagName === 'INPUT' ||
92
+ tagName === 'TEXTAREA' ||
93
+ tagName === 'SELECT' ||
94
+ Boolean(target?.isContentEditable);
95
+ if (isNativeEditable && target !== this.imeInput)
96
+ return;
97
+ const ctrl = event.ctrlKey || event.metaKey;
98
+ const isPrintable = !ctrl && !event.altKey && event.key.length === 1;
99
+ if (isPrintable || this.imeComposing || event.isComposing || event.key === 'Process') {
100
+ this.refocusImeInputSoon();
101
+ return;
102
+ }
103
+ const handled = this.handleKeyDown(event);
104
+ if (handled) {
105
+ event.preventDefault();
106
+ this.refocusImeInputSoon();
107
+ }
108
+ };
109
+ onImeBeforeInput = (event) => {
110
+ if (!this.isActiveEditor())
111
+ return;
112
+ if (event.isComposing)
113
+ return;
114
+ const inputType = event.inputType;
115
+ if (inputType === 'insertText' || inputType === 'insertCompositionText') {
116
+ const handled = this.handleTextInput(event.data ?? '');
117
+ if (handled)
118
+ event.preventDefault();
119
+ return;
120
+ }
121
+ if (inputType === 'insertParagraph') {
122
+ const handled = this.handleTextInput('\n');
123
+ if (handled)
124
+ event.preventDefault();
125
+ }
126
+ };
127
+ onImeCompositionStart = () => {
128
+ if (!this.isActiveEditor())
129
+ return;
130
+ this.imeComposing = true;
131
+ this.updateImeAnchorPosition();
132
+ this.refocusImeInputSoon();
133
+ };
134
+ onImeCompositionEnd = (event) => {
135
+ if (!this.isActiveEditor())
136
+ return;
137
+ this.imeComposing = false;
138
+ const data = event.data ?? '';
139
+ const handled = this.handleTextInput(data);
140
+ if (handled && this.imeInput) {
141
+ this.imeInput.value = '';
142
+ }
143
+ this.refocusImeInputSoon();
144
+ };
145
+ onImeTargetMouseDown = () => {
146
+ if (!this.isActiveEditor())
147
+ return;
148
+ this.refocusImeInputSoon();
149
+ };
150
+ onPointerMouseDown = (event) => {
151
+ if (this.closed)
152
+ return;
153
+ if (event.altKey || event.button === 1)
154
+ return;
155
+ const local = this.pointerEventToEditorLocal(event);
156
+ if (!local)
157
+ return;
158
+ const insideEditor = this.isPointInContainer(local.x, local.y);
159
+ if (!insideEditor) {
160
+ if (this.isActiveEditor()) {
161
+ this.closeEditor();
162
+ }
163
+ return;
164
+ }
165
+ this.activateEditor();
166
+ this.handleMouseDown(local.x, local.y, event.shiftKey);
167
+ this.refocusImeInputSoon();
168
+ };
169
+ onPointerMouseMove = (event) => {
170
+ if (!this.isActiveEditor())
171
+ return;
172
+ if (event.buttons === 0 || !this.isDragging)
173
+ return;
174
+ const local = this.pointerEventToEditorLocal(event);
175
+ if (!local)
176
+ return;
177
+ this.handleMouseMove(local.x, local.y);
178
+ };
179
+ onPointerMouseUp = () => {
180
+ if (!this.isActiveEditor())
181
+ return;
182
+ this.handleMouseUp();
183
+ };
184
+ onPointerDoubleClick = (event) => {
185
+ if (!this.isActiveEditor())
186
+ return;
187
+ const local = this.pointerEventToEditorLocal(event);
188
+ if (!local)
189
+ return;
190
+ this.handleDoubleClick(local.x, local.y);
191
+ this.refocusImeInputSoon();
192
+ };
193
+ onReopenDoubleClick = (event) => {
194
+ if (!this.closed)
195
+ return;
196
+ if (!this.shouldReopenFromDoubleClick(event))
197
+ return;
198
+ this.showEditor();
199
+ };
200
+ handlers = {
201
+ change: new Set(),
202
+ selectionChange: new Set(),
203
+ cursorMove: new Set(),
204
+ show: new Set(),
205
+ close: new Set()
206
+ };
207
+ constructor(options) {
208
+ MTextInputBox.instances.add(this);
209
+ this.scene = options.scene;
210
+ this.camera = options.camera;
211
+ this.toolbarTheme = options.toolbar?.theme ?? 'dark';
212
+ this.toolbarOffsetY = Math.max(0, options.toolbar?.offsetY ?? 10);
213
+ this.toolbarEnabled = options.toolbar?.enabled ?? true;
214
+ this.toolbarContainer = options.toolbar?.container ?? null;
215
+ this.toolbarFontFamilies = options.toolbar?.fontFamilies ?? null;
216
+ this.width = Math.max(1, options.width);
217
+ this.position = options.position?.clone() ?? new THREE.Vector3(0, 0, 0);
218
+ this.enableWordWrap = options.enableWordWrap ?? true;
219
+ this.baseFormat = { ...defaultCharFormat(), ...(options.defaultFormat ?? {}) };
220
+ this.currentFormat = { ...this.baseFormat };
221
+ this.defaultTextStyle = this.createDefaultTextStyle();
222
+ this.document = new MTextDocument();
223
+ this.uiAdapter = new EditorUiAdapter(this.document);
224
+ this.mtextRenderer = new UnifiedRenderer('main', {
225
+ workerUrl: typeof options.workerUrl === 'string'
226
+ ? options.workerUrl
227
+ : options.workerUrl?.toString() ?? './assets/mtext-renderer-worker.js'
228
+ });
229
+ this.cursorLogic = new TextBoxCursor({
230
+ containerBox: { x: 0, y: 0, width: this.width, height: 1 },
231
+ charBoxes: [],
232
+ lineTolerance: 4
233
+ });
234
+ const cursorStyle = { ...(options.cursorStyle ?? {}) };
235
+ cursorStyle.color ??= '#ffffff';
236
+ cursorStyle.glowColor ??= '#ffffff';
237
+ this.cursorRenderer = new CursorRenderer({
238
+ renderer: new ThreeJsRendererAdapter({ scene: this.scene, camera: this.camera }),
239
+ cursorStyle,
240
+ selectionStyle: options.selectionStyle,
241
+ enableDebug: false,
242
+ enableSelection: true,
243
+ debugYAxisUp: this.camera instanceof THREE.OrthographicCamera ? this.camera.top >= this.camera.bottom : true,
244
+ debugVisibility: this.debugVisibility
245
+ });
246
+ this.cursorRenderer.setViewTransform({ x: this.position.x, y: this.position.y, scaleX: 1, scaleY: 1 });
247
+ this.createBoundingBox(options.showBoundingBox ?? true, options.boundingBoxStyle);
248
+ this.setText(options.initialText ?? '');
249
+ this.attachIme(options.imeTarget);
250
+ void this.initializeRenderer();
251
+ }
252
+ /** Sets full text and rebuilds model/layout state. */
253
+ setText(text) {
254
+ this.document = this.createNormalizedDocument(text);
255
+ this.document.cursor = 0;
256
+ this.uiAdapter = new EditorUiAdapter(this.document);
257
+ this.clearHistory();
258
+ this.syncUiStateFromDocument();
259
+ this.relayout();
260
+ this.emit('change');
261
+ }
262
+ /** Returns current MTEXT source string. */
263
+ getText() {
264
+ this.syncUiStateFromDocument();
265
+ return this.mtextString;
266
+ }
267
+ /** Returns plain text resolved from document AST. */
268
+ getPlainText() {
269
+ return this.getChars().join('');
270
+ }
271
+ /** Inserts text at cursor; replaces selection when present. */
272
+ insertText(text) {
273
+ if (text.length === 0)
274
+ return;
275
+ if (text === '\n') {
276
+ const currentLineIndex = this.cursorLogic.getCursorState().lineIndex;
277
+ this.pendingCursorLineHint = currentLineIndex >= 0 ? currentLineIndex + 1 : 0;
278
+ }
279
+ this.commitHistoryEdit(() => {
280
+ this.syncDocumentFromUiState();
281
+ this.uiAdapter.execute({
282
+ type: 'insertText',
283
+ text,
284
+ style: this.toDocumentStyle(this.currentFormat)
285
+ });
286
+ this.syncUiStateFromDocument();
287
+ this.relayout();
288
+ });
289
+ }
290
+ /** Backspace behavior: remove selection or previous character. */
291
+ deleteBackward() {
292
+ this.commitHistoryEdit(() => {
293
+ this.syncDocumentFromUiState();
294
+ this.uiAdapter.execute({ type: 'backspace' });
295
+ this.syncUiStateFromDocument();
296
+ this.relayout();
297
+ });
298
+ }
299
+ /** Delete behavior: remove selection or next character. */
300
+ deleteForward() {
301
+ this.commitHistoryEdit(() => {
302
+ this.syncDocumentFromUiState();
303
+ this.uiAdapter.execute({ type: 'delete' });
304
+ this.syncUiStateFromDocument();
305
+ this.relayout();
306
+ });
307
+ }
308
+ /** Restores previous text-editing state. Returns true when successful. */
309
+ undo() {
310
+ const snapshot = this.undoStack.pop();
311
+ if (!snapshot)
312
+ return false;
313
+ this.redoStack.push(this.createHistorySnapshot());
314
+ this.restoreHistorySnapshot(snapshot);
315
+ return true;
316
+ }
317
+ /** Restores next text-editing state from redo history. Returns true when successful. */
318
+ redo() {
319
+ const snapshot = this.redoStack.pop();
320
+ if (!snapshot)
321
+ return false;
322
+ this.undoStack.push(this.createHistorySnapshot());
323
+ this.restoreHistorySnapshot(snapshot);
324
+ return true;
325
+ }
326
+ /** Moves cursor and clears selection. */
327
+ moveCursor(direction) {
328
+ switch (direction) {
329
+ case 'left':
330
+ this.cursorLogic.moveLeft();
331
+ break;
332
+ case 'right':
333
+ this.cursorLogic.moveRight();
334
+ break;
335
+ case 'up':
336
+ this.cursorLogic.moveUp();
337
+ break;
338
+ case 'down':
339
+ this.cursorLogic.moveDown();
340
+ break;
341
+ case 'lineStart':
342
+ this.cursorLogic.moveToLineStart();
343
+ break;
344
+ case 'lineEnd':
345
+ this.cursorLogic.moveToLineEnd();
346
+ break;
347
+ case 'wordPrev':
348
+ this.cursorLogic.moveTo(this.findPrevWordStart(this.cursorLogic.getCurrentIndex()));
349
+ break;
350
+ case 'wordNext':
351
+ this.cursorLogic.moveTo(this.findNextWordStart(this.cursorLogic.getCurrentIndex()));
352
+ break;
353
+ default:
354
+ break;
355
+ }
356
+ this.cursorLogic.clearSelection();
357
+ this.syncStateFromCursor();
358
+ this.emit('cursorMove');
359
+ this.emit('selectionChange');
360
+ }
361
+ /** Extends selection toward direction. */
362
+ extendSelection(direction) {
363
+ const selection = this.cursorLogic.getSelection();
364
+ const anchor = selection ? selection.anchor : this.cursorLogic.getCurrentIndex();
365
+ this.cursorLogic.clearSelection();
366
+ this.cursorLogic.moveTo(this.cursorIndex);
367
+ switch (direction) {
368
+ case 'left':
369
+ this.cursorLogic.moveTo(this.cursorLogic.getCurrentIndex() - 1);
370
+ break;
371
+ case 'right':
372
+ this.cursorLogic.moveTo(this.cursorLogic.getCurrentIndex() + 1);
373
+ break;
374
+ case 'up':
375
+ this.cursorLogic.moveUp();
376
+ break;
377
+ case 'down':
378
+ this.cursorLogic.moveDown();
379
+ break;
380
+ case 'lineStart':
381
+ this.cursorLogic.moveToLineStart();
382
+ break;
383
+ case 'lineEnd':
384
+ this.cursorLogic.moveToLineEnd();
385
+ break;
386
+ default:
387
+ break;
388
+ }
389
+ this.cursorLogic.setSelectionWithDirection(anchor, this.cursorLogic.getCurrentIndex());
390
+ this.syncStateFromCursor();
391
+ this.emit('selectionChange');
392
+ }
393
+ /** Selects all text. */
394
+ selectAll() {
395
+ this.cursorLogic.selectAll();
396
+ this.syncStateFromCursor();
397
+ this.emit('selectionChange');
398
+ }
399
+ /** Clears current selection. */
400
+ clearSelection() {
401
+ this.cursorLogic.clearSelection();
402
+ this.syncStateFromCursor();
403
+ this.emit('selectionChange');
404
+ }
405
+ /** Enables/disables debug overlay rendering. */
406
+ setDebugMode(enabled) {
407
+ this.debugMode = enabled;
408
+ this.cursorRenderer.setDebugMode(enabled);
409
+ }
410
+ /** Returns current debug mode flag. */
411
+ isDebugMode() {
412
+ return this.debugMode;
413
+ }
414
+ /** Partially overrides visibility of debug sub-layers. */
415
+ setDebugVisibility(visibility) {
416
+ this.debugVisibility = { ...this.debugVisibility, ...visibility };
417
+ this.cursorRenderer.setDebugVisibility(visibility);
418
+ }
419
+ /** Returns current debug sub-layer visibility flags. */
420
+ getDebugVisibility() {
421
+ return { ...this.debugVisibility };
422
+ }
423
+ /** Sets built-in toolbar theme. */
424
+ setToolbarTheme(theme) {
425
+ this.toolbarTheme = theme;
426
+ if (this.isActiveEditor()) {
427
+ this.getActiveToolbar()?.setTheme(theme);
428
+ }
429
+ }
430
+ /** Returns built-in toolbar theme. */
431
+ getToolbarTheme() {
432
+ return this.toolbarTheme;
433
+ }
434
+ /** Attaches IME/input bridge to a target element (typically the render canvas). */
435
+ attachIme(target) {
436
+ const wasClosed = this.closed;
437
+ this.lastImeTarget = target;
438
+ this.bindReopenDoubleClick(target);
439
+ this.imeTarget = target;
440
+ this.attachPointerInteractions(target);
441
+ this.closed = false;
442
+ if (!MTextInputBox.activeEditor) {
443
+ this.activateEditor();
444
+ }
445
+ else if (MTextInputBox.activeEditor === this) {
446
+ this.activateEditor();
447
+ }
448
+ else {
449
+ this.cursorRenderer.hide();
450
+ if (this.boundingBoxObject)
451
+ this.boundingBoxObject.visible = false;
452
+ }
453
+ if (wasClosed)
454
+ this.emit('show');
455
+ }
456
+ /** Detaches and destroys IME/input bridge. */
457
+ detachIme() {
458
+ if (!this.imeInput) {
459
+ return;
460
+ }
461
+ this.imeInput.removeEventListener('keydown', this.onImeKeyDown);
462
+ this.imeInput.removeEventListener('beforeinput', this.onImeBeforeInput);
463
+ this.imeInput.removeEventListener('compositionstart', this.onImeCompositionStart);
464
+ this.imeInput.removeEventListener('compositionend', this.onImeCompositionEnd);
465
+ window.removeEventListener('keydown', this.onWindowKeyDown);
466
+ if (this.imeTarget) {
467
+ this.imeTarget.removeEventListener('mousedown', this.onImeTargetMouseDown);
468
+ }
469
+ this.imeInput.remove();
470
+ this.imeInput = null;
471
+ this.imeComposing = false;
472
+ if (this.imeFocusTimer !== null) {
473
+ window.clearTimeout(this.imeFocusTimer);
474
+ this.imeFocusTimer = null;
475
+ }
476
+ }
477
+ /** Returns cursor index. */
478
+ getCursorIndex() {
479
+ return this.cursorIndex;
480
+ }
481
+ /** Returns normalized selection range. */
482
+ getSelectionRange() {
483
+ const start = Math.min(this.selectionStart, this.selectionEnd);
484
+ const end = Math.max(this.selectionStart, this.selectionEnd);
485
+ return { start, end, isCollapsed: start === end };
486
+ }
487
+ /** Returns the latest geometry payload forwarded to `TextBoxCursor.updateData`. */
488
+ getCursorLayoutData() {
489
+ const snapshot = {
490
+ containerBox: { ...this.latestCursorLayoutData.containerBox },
491
+ charBoxes: this.latestCursorLayoutData.charBoxes.map((box) => ({ ...box }))
492
+ };
493
+ if (this.latestCursorLayoutData.lineBreakIndices) {
494
+ snapshot.lineBreakIndices = [...this.latestCursorLayoutData.lineBreakIndices];
495
+ }
496
+ if (this.latestCursorLayoutData.lineLayouts) {
497
+ snapshot.lineLayouts = this.latestCursorLayoutData.lineLayouts.map((line) => ({ ...line }));
498
+ }
499
+ console.log(snapshot);
500
+ return snapshot;
501
+ }
502
+ /** Sets current insertion format. */
503
+ setCurrentFormat(format) {
504
+ const next = this.mergeCharFormat(this.currentFormat, format);
505
+ this.currentFormat = next;
506
+ const selection = this.getSelectionRange();
507
+ if (!selection.isCollapsed) {
508
+ this.commitHistoryEdit(() => {
509
+ this.syncDocumentFromUiState();
510
+ const nodesToUpdate = this.getNodesByLogicalRange(selection.start, selection.end);
511
+ for (const node of nodesToUpdate) {
512
+ const nodeFormat = this.toCharFormat(node.style);
513
+ const mergedNodeFormat = this.mergeCharFormat(nodeFormat, format);
514
+ node.style = this.toDocumentStyle(mergedNodeFormat);
515
+ }
516
+ this.syncUiStateFromDocument();
517
+ this.relayout();
518
+ });
519
+ }
520
+ this.getActiveToolbar()?.setFormat(this.currentFormat);
521
+ }
522
+ /** Returns current insertion format. */
523
+ getCurrentFormat() {
524
+ return { ...this.currentFormat };
525
+ }
526
+ /** Returns renderer default text style derived from `defaultFormat`. */
527
+ getDefaultTextStyle() {
528
+ return { ...this.defaultTextStyle };
529
+ }
530
+ /** Keyboard event handler. Returns true when consumed. */
531
+ handleKeyDown(event) {
532
+ // IME composition uses beforeinput/composition events for committed text.
533
+ if (event.isComposing || event.key === 'Process') {
534
+ return false;
535
+ }
536
+ const isMac = this.isMacPlatform();
537
+ const primaryModifier = isMac ? event.metaKey : event.ctrlKey;
538
+ const wordNavModifier = isMac ? event.altKey : event.ctrlKey;
539
+ if (primaryModifier && event.key.toLowerCase() === 'a') {
540
+ this.selectAll();
541
+ return true;
542
+ }
543
+ if (primaryModifier && event.key.toLowerCase() === 'z') {
544
+ return event.shiftKey ? this.redo() : this.undo();
545
+ }
546
+ if (!isMac && primaryModifier && event.key.toLowerCase() === 'y') {
547
+ return this.redo();
548
+ }
549
+ if (event.shiftKey) {
550
+ if (event.key === 'ArrowLeft')
551
+ return this.consumeExtend('left');
552
+ if (event.key === 'ArrowRight')
553
+ return this.consumeExtend('right');
554
+ if (event.key === 'ArrowUp')
555
+ return this.consumeExtend('up');
556
+ if (event.key === 'ArrowDown')
557
+ return this.consumeExtend('down');
558
+ if (event.key === 'Home')
559
+ return this.consumeExtend('lineStart');
560
+ if (event.key === 'End')
561
+ return this.consumeExtend('lineEnd');
562
+ }
563
+ if (isMac && event.metaKey && event.key === 'ArrowLeft')
564
+ return this.consumeMove('lineStart');
565
+ if (isMac && event.metaKey && event.key === 'ArrowRight')
566
+ return this.consumeMove('lineEnd');
567
+ if (event.key === 'ArrowLeft')
568
+ return this.consumeMove(wordNavModifier ? 'wordPrev' : 'left');
569
+ if (event.key === 'ArrowRight')
570
+ return this.consumeMove(wordNavModifier ? 'wordNext' : 'right');
571
+ if (event.key === 'ArrowUp')
572
+ return this.consumeMove('up');
573
+ if (event.key === 'ArrowDown')
574
+ return this.consumeMove('down');
575
+ if (event.key === 'Home')
576
+ return this.consumeMove('lineStart');
577
+ if (event.key === 'End')
578
+ return this.consumeMove('lineEnd');
579
+ if (event.key === 'Backspace') {
580
+ this.deleteBackward();
581
+ return true;
582
+ }
583
+ if (event.key === 'Delete') {
584
+ this.deleteForward();
585
+ return true;
586
+ }
587
+ if (event.key === 'Enter') {
588
+ this.insertText('\n');
589
+ return true;
590
+ }
591
+ if (!primaryModifier && !event.altKey && event.key.length === 1) {
592
+ this.insertText(event.key);
593
+ return true;
594
+ }
595
+ return false;
596
+ }
597
+ /** Inserts committed text from IME/beforeinput events. Returns true when consumed. */
598
+ handleTextInput(text) {
599
+ if (!text)
600
+ return false;
601
+ this.insertText(text);
602
+ return true;
603
+ }
604
+ /** Handles pointer down in editor local coordinates. */
605
+ handleMouseDown(x, y, shiftKey) {
606
+ if (shiftKey) {
607
+ const index = this.cursorLogic.hitTest(x, y);
608
+ if (index < 0)
609
+ return;
610
+ this.cursorLogic.setSelectionWithDirection(this.selectionStart, index);
611
+ }
612
+ else {
613
+ if (!this.cursorLogic.moveToClick(x, y))
614
+ return;
615
+ }
616
+ this.isDragging = true;
617
+ this.syncStateFromCursor();
618
+ this.emit('cursorMove');
619
+ this.emit('selectionChange');
620
+ }
621
+ /** Handles pointer move during drag selection. */
622
+ handleMouseMove(x, y) {
623
+ if (!this.isDragging)
624
+ return;
625
+ this.cursorLogic.updateSelectionDrag(x, y);
626
+ this.syncStateFromCursor();
627
+ this.emit('selectionChange');
628
+ }
629
+ /** Handles pointer release. */
630
+ handleMouseUp() {
631
+ this.isDragging = false;
632
+ }
633
+ /** Handles double click to select current word. */
634
+ handleDoubleClick(x, y) {
635
+ const index = this.cursorLogic.hitTest(x, y);
636
+ if (index < 0)
637
+ return;
638
+ const chars = this.getChars();
639
+ let start = index;
640
+ let end = index;
641
+ while (start > 0 && !/\s/.test(chars[start - 1] ?? ''))
642
+ start -= 1;
643
+ while (end < chars.length && !/\s/.test(chars[end] ?? ''))
644
+ end += 1;
645
+ this.cursorLogic.setSelection(start, end);
646
+ this.cursorLogic.moveTo(end);
647
+ this.syncStateFromCursor();
648
+ this.emit('selectionChange');
649
+ }
650
+ /** Per-frame update. Call in animation loop. */
651
+ update() {
652
+ const cursorState = this.cursorLogic.getCursorState();
653
+ const selection = this.cursorLogic.getSelection();
654
+ const cursorRenderState = this.getActiveCursorRenderState(cursorState.position, cursorState.lineInfo.height);
655
+ const selectedBoxes = this.cursorLogic.getSelectedCharBoxes();
656
+ this.cursorRenderer.updateCursor(cursorRenderState.position, cursorRenderState.height);
657
+ this.cursorRenderer.updateSelection(selectedBoxes);
658
+ this.cursorRenderer.updateDebugInfo({
659
+ containerBox: this.layoutContainer,
660
+ charBoxes: this.cursorLogic.getCharBoxes(),
661
+ chars: this.getChars(),
662
+ lines: this.cursorLogic.getLines()
663
+ });
664
+ this.cursorRenderer.setSelectionStyle({
665
+ fillColor: selection?.isBackwards ? 'rgba(150,0,255,0.25)' : 'rgba(0,120,255,0.30)'
666
+ });
667
+ this.cursorRenderer.render();
668
+ this.updateImeAnchorPosition();
669
+ this.updateToolbarPosition();
670
+ }
671
+ /** Releases all allocated resources. */
672
+ dispose() {
673
+ if (MTextInputBox.activeEditor === this) {
674
+ this.deactivateEditor();
675
+ }
676
+ else {
677
+ this.detachIme();
678
+ }
679
+ this.detachPointerInteractions();
680
+ this.unbindReopenDoubleClick();
681
+ this.disposeRenderedObject(this.renderedObject);
682
+ this.renderedObject = null;
683
+ this.disposeBoundingBox();
684
+ this.mtextRenderer.destroy();
685
+ this.cursorRenderer.dispose();
686
+ this.cursorLogic.destroy();
687
+ this.handlers.change.clear();
688
+ this.handlers.selectionChange.clear();
689
+ this.handlers.cursorMove.clear();
690
+ this.handlers.show.clear();
691
+ this.handlers.close.clear();
692
+ MTextInputBox.instances.delete(this);
693
+ if (MTextInputBox.instances.size === 0) {
694
+ MTextInputBox.sharedToolbar?.dispose();
695
+ MTextInputBox.sharedToolbar = null;
696
+ MTextInputBox.sharedToolbarContainer = null;
697
+ MTextInputBox.sharedToolbarFontFamiliesKey = '';
698
+ MTextInputBox.activeEditor = null;
699
+ }
700
+ }
701
+ /** Closes editing interactions and destroys toolbar while keeping rendered text object. */
702
+ closeEditor() {
703
+ if (this.closed)
704
+ return;
705
+ this.closed = true;
706
+ this.detachPointerInteractions();
707
+ this.deactivateEditor();
708
+ this.emit('close');
709
+ }
710
+ /** Re-opens a closed editor and restores IME/pointer interactions and toolbar. */
711
+ showEditor() {
712
+ const target = this.lastImeTarget;
713
+ if (!target)
714
+ return false;
715
+ const wasClosed = this.closed;
716
+ this.closed = false;
717
+ this.attachPointerInteractions(target);
718
+ this.activateEditor();
719
+ if (wasClosed)
720
+ this.emit('show');
721
+ return true;
722
+ }
723
+ /** Binds built-in mouse interactions using the editor target element. */
724
+ attachPointerInteractions(target) {
725
+ this.detachPointerInteractions();
726
+ this.pointerTarget = target;
727
+ target.addEventListener('mousedown', this.onPointerMouseDown);
728
+ target.addEventListener('mousemove', this.onPointerMouseMove);
729
+ target.addEventListener('dblclick', this.onPointerDoubleClick);
730
+ window.addEventListener('mouseup', this.onPointerMouseUp);
731
+ }
732
+ /** Unbinds built-in mouse interactions. */
733
+ detachPointerInteractions() {
734
+ if (!this.pointerTarget)
735
+ return;
736
+ this.pointerTarget.removeEventListener('mousedown', this.onPointerMouseDown);
737
+ this.pointerTarget.removeEventListener('mousemove', this.onPointerMouseMove);
738
+ this.pointerTarget.removeEventListener('dblclick', this.onPointerDoubleClick);
739
+ window.removeEventListener('mouseup', this.onPointerMouseUp);
740
+ this.pointerTarget = null;
741
+ }
742
+ /** Registers event handler. */
743
+ on(event, handler) {
744
+ this.handlers[event].add(handler);
745
+ }
746
+ /** Removes event handler. */
747
+ off(event, handler) {
748
+ if (event === 'change' ||
749
+ event === 'selectionChange' ||
750
+ event === 'cursorMove' ||
751
+ event === 'show' ||
752
+ event === 'close') {
753
+ this.handlers[event].delete(handler);
754
+ }
755
+ }
756
+ /** Returns cursor world position for IME/caret anchoring. */
757
+ getCursorWorldPosition() {
758
+ const cursor = this.cursorLogic.getCursorState().position;
759
+ return {
760
+ x: this.position.x + cursor.x,
761
+ y: this.position.y + cursor.y,
762
+ z: this.position.z
763
+ };
764
+ }
765
+ /** Returns current internal state snapshot. */
766
+ getState() {
767
+ return {
768
+ mtextString: this.getText(),
769
+ cursorIndex: this.cursorIndex,
770
+ selectionStart: this.selectionStart,
771
+ selectionEnd: this.selectionEnd,
772
+ currentFormat: this.getCurrentFormat()
773
+ };
774
+ }
775
+ isActiveEditor() {
776
+ return MTextInputBox.activeEditor === this;
777
+ }
778
+ activateEditor() {
779
+ if (this.closed)
780
+ return;
781
+ const currentActive = MTextInputBox.activeEditor;
782
+ if (currentActive && currentActive !== this) {
783
+ currentActive.deactivateEditor();
784
+ }
785
+ MTextInputBox.activeEditor = this;
786
+ const target = this.imeTarget ?? this.lastImeTarget;
787
+ if (target) {
788
+ this.attachImeBridge(target);
789
+ }
790
+ this.cursorRenderer.show();
791
+ if (this.boundingBoxObject)
792
+ this.boundingBoxObject.visible = true;
793
+ if (target && this.toolbarEnabled) {
794
+ this.mountToolbar(target);
795
+ }
796
+ else {
797
+ MTextInputBox.sharedToolbar?.setVisible(false);
798
+ }
799
+ }
800
+ deactivateEditor() {
801
+ this.isDragging = false;
802
+ this.detachIme();
803
+ this.cursorRenderer.hide();
804
+ if (this.boundingBoxObject)
805
+ this.boundingBoxObject.visible = false;
806
+ if (MTextInputBox.activeEditor === this) {
807
+ MTextInputBox.activeEditor = null;
808
+ MTextInputBox.sharedToolbar?.setVisible(false);
809
+ }
810
+ }
811
+ attachImeBridge(target) {
812
+ this.detachIme();
813
+ this.imeTarget = target;
814
+ const imeInput = document.createElement('textarea');
815
+ imeInput.setAttribute('aria-hidden', 'true');
816
+ imeInput.autocapitalize = 'off';
817
+ imeInput.autocomplete = 'off';
818
+ imeInput.spellcheck = false;
819
+ imeInput.style.position = 'fixed';
820
+ imeInput.style.left = '0px';
821
+ imeInput.style.top = '0px';
822
+ imeInput.style.width = '2px';
823
+ imeInput.style.height = '2px';
824
+ imeInput.style.opacity = '0';
825
+ imeInput.style.pointerEvents = 'none';
826
+ imeInput.style.zIndex = '2147483647';
827
+ document.body.appendChild(imeInput);
828
+ this.imeInput = imeInput;
829
+ imeInput.addEventListener('keydown', this.onImeKeyDown);
830
+ imeInput.addEventListener('beforeinput', this.onImeBeforeInput);
831
+ imeInput.addEventListener('compositionstart', this.onImeCompositionStart);
832
+ imeInput.addEventListener('compositionend', this.onImeCompositionEnd);
833
+ window.addEventListener('keydown', this.onWindowKeyDown);
834
+ target.addEventListener('mousedown', this.onImeTargetMouseDown);
835
+ this.updateImeAnchorPosition();
836
+ this.focusImeInput();
837
+ }
838
+ getActiveToolbar() {
839
+ if (!this.isActiveEditor())
840
+ return null;
841
+ const toolbar = MTextInputBox.sharedToolbar;
842
+ if (!toolbar) {
843
+ throw new Error('[mtext-input-box] Failed to create shared toolbar');
844
+ }
845
+ return toolbar;
846
+ }
847
+ createToolbarSessionOptions(target) {
848
+ return {
849
+ anchorElement: target,
850
+ onFormatChange: (partial) => {
851
+ this.setCurrentFormat(partial);
852
+ },
853
+ onToggleStack: () => {
854
+ this.toggleStackSelection();
855
+ },
856
+ onToggleSuperscript: () => {
857
+ return this.toggleScriptSelection('superscript');
858
+ },
859
+ onToggleSubscript: () => {
860
+ return this.toggleScriptSelection('subscript');
861
+ }
862
+ };
863
+ }
864
+ ensureSharedToolbar(target) {
865
+ const container = this.toolbarContainer ?? document.body;
866
+ const fontFamiliesKey = this.toolbarFontFamilies?.join('\u0000') ?? '';
867
+ const shouldRecreate = !MTextInputBox.sharedToolbar ||
868
+ MTextInputBox.sharedToolbarContainer !== container ||
869
+ MTextInputBox.sharedToolbarFontFamiliesKey !== fontFamiliesKey;
870
+ if (shouldRecreate) {
871
+ MTextInputBox.sharedToolbar?.dispose();
872
+ const toolbarOptions = {
873
+ ...this.createToolbarSessionOptions(target),
874
+ container,
875
+ theme: this.toolbarTheme
876
+ };
877
+ if (this.toolbarFontFamilies) {
878
+ toolbarOptions.fontFamilies = this.toolbarFontFamilies;
879
+ }
880
+ MTextInputBox.sharedToolbar = new MTextToolbar(toolbarOptions);
881
+ MTextInputBox.sharedToolbarContainer = container;
882
+ MTextInputBox.sharedToolbarFontFamiliesKey = fontFamiliesKey;
883
+ }
884
+ const toolbar = MTextInputBox.sharedToolbar;
885
+ if (!toolbar) {
886
+ throw new Error('[mtext-input-box] Failed to create shared toolbar');
887
+ }
888
+ return toolbar;
889
+ }
890
+ mountToolbar(target) {
891
+ if (!this.toolbarEnabled || !this.isActiveEditor())
892
+ return;
893
+ const toolbar = this.ensureSharedToolbar(target);
894
+ toolbar.setTheme(this.toolbarTheme);
895
+ toolbar.setSession(this.createToolbarSessionOptions(target));
896
+ toolbar.setVisible(true);
897
+ toolbar.setFormat(this.currentFormat);
898
+ this.updateToolbarStackState();
899
+ this.updateToolbarPosition();
900
+ }
901
+ updateToolbarPosition() {
902
+ if (!this.toolbarEnabled || !this.isActiveEditor() || !this.imeTarget)
903
+ return;
904
+ const toolbar = this.getActiveToolbar();
905
+ if (!toolbar)
906
+ return;
907
+ const bounds = this.getEditorScreenBounds();
908
+ if (!bounds)
909
+ return;
910
+ toolbar.setAnchor(bounds.minX, bounds.minY - this.toolbarOffsetY);
911
+ }
912
+ getEditorScreenBounds() {
913
+ if (!this.imeTarget)
914
+ return null;
915
+ const rect = this.imeTarget.getBoundingClientRect();
916
+ const x0 = this.position.x + this.layoutContainer.x;
917
+ const x1 = x0 + this.layoutContainer.width;
918
+ const y0 = this.position.y + this.layoutContainer.y;
919
+ const y1 = y0 + this.layoutContainer.height;
920
+ const corners = [
921
+ new THREE.Vector3(x0, y0, this.position.z),
922
+ new THREE.Vector3(x1, y0, this.position.z),
923
+ new THREE.Vector3(x0, y1, this.position.z),
924
+ new THREE.Vector3(x1, y1, this.position.z)
925
+ ];
926
+ let minX = Number.POSITIVE_INFINITY;
927
+ let maxX = Number.NEGATIVE_INFINITY;
928
+ let minY = Number.POSITIVE_INFINITY;
929
+ let maxY = Number.NEGATIVE_INFINITY;
930
+ for (const corner of corners) {
931
+ const projected = corner.clone().project(this.camera);
932
+ const sx = rect.left + ((projected.x + 1) * 0.5) * rect.width;
933
+ const sy = rect.top + ((1 - projected.y) * 0.5) * rect.height;
934
+ minX = Math.min(minX, sx);
935
+ maxX = Math.max(maxX, sx);
936
+ minY = Math.min(minY, sy);
937
+ maxY = Math.max(maxY, sy);
938
+ }
939
+ if (!Number.isFinite(minX) || !Number.isFinite(minY))
940
+ return null;
941
+ return { minX, maxX, minY, maxY };
942
+ }
943
+ pointerEventToEditorLocal(event) {
944
+ const target = this.pointerTarget ?? this.imeTarget;
945
+ return this.pointerEventToEditorLocalByTarget(event, target);
946
+ }
947
+ pointerEventToEditorLocalByTarget(event, target) {
948
+ if (!target)
949
+ return null;
950
+ const rect = target.getBoundingClientRect();
951
+ if (rect.width <= 0 || rect.height <= 0)
952
+ return null;
953
+ const ndcX = ((event.clientX - rect.left) / rect.width) * 2 - 1;
954
+ const ndcY = -((event.clientY - rect.top) / rect.height) * 2 + 1;
955
+ const nearPoint = new THREE.Vector3(ndcX, ndcY, -1).unproject(this.camera);
956
+ const farPoint = new THREE.Vector3(ndcX, ndcY, 1).unproject(this.camera);
957
+ const rayDir = farPoint.sub(nearPoint);
958
+ if (Math.abs(rayDir.z) < 1e-8)
959
+ return null;
960
+ const t = (this.position.z - nearPoint.z) / rayDir.z;
961
+ const world = nearPoint.add(rayDir.multiplyScalar(t));
962
+ return {
963
+ x: world.x - this.position.x,
964
+ y: world.y - this.position.y
965
+ };
966
+ }
967
+ shouldReopenFromDoubleClick(event) {
968
+ return this.hitTestRenderedObject(event);
969
+ }
970
+ hitTestRenderedObject(event) {
971
+ if (!this.renderedObject || !this.reopenTarget)
972
+ return false;
973
+ const rect = this.reopenTarget.getBoundingClientRect();
974
+ if (rect.width <= 0 || rect.height <= 0)
975
+ return false;
976
+ const ndcX = ((event.clientX - rect.left) / rect.width) * 2 - 1;
977
+ const ndcY = -((event.clientY - rect.top) / rect.height) * 2 + 1;
978
+ const raycaster = new THREE.Raycaster();
979
+ raycaster.setFromCamera(new THREE.Vector2(ndcX, ndcY), this.camera);
980
+ return raycaster.intersectObject(this.renderedObject, true).length > 0;
981
+ }
982
+ bindReopenDoubleClick(target) {
983
+ if (this.reopenTarget === target)
984
+ return;
985
+ this.unbindReopenDoubleClick();
986
+ this.reopenTarget = target;
987
+ target.addEventListener('dblclick', this.onReopenDoubleClick);
988
+ }
989
+ unbindReopenDoubleClick() {
990
+ if (!this.reopenTarget)
991
+ return;
992
+ this.reopenTarget.removeEventListener('dblclick', this.onReopenDoubleClick);
993
+ this.reopenTarget = null;
994
+ }
995
+ isPointInContainer(x, y) {
996
+ const box = this.layoutContainer;
997
+ const right = box.x + box.width;
998
+ const bottom = box.y + box.height;
999
+ return x >= box.x && x <= right && y >= box.y && y <= bottom;
1000
+ }
1001
+ async initializeRenderer() {
1002
+ try {
1003
+ await this.mtextRenderer.loadFonts(['simkai']);
1004
+ this.rendererReady = true;
1005
+ this.relayout();
1006
+ }
1007
+ catch (error) {
1008
+ console.error('[mtext-input-box] Failed to initialize mtext renderer fonts', error);
1009
+ }
1010
+ }
1011
+ relayout() {
1012
+ if (!this.rendererReady) {
1013
+ const fallback = this.createFallbackCharBoxes();
1014
+ this.layoutContainer = fallback.containerBox;
1015
+ this.updateCursorData(fallback.charBoxes, fallback.lineBreakIndices, fallback.lineLayouts);
1016
+ this.updateBoundingBoxGeometry();
1017
+ return;
1018
+ }
1019
+ try {
1020
+ const mtextData = this.createMTextData();
1021
+ const style = this.createTextStyle();
1022
+ const object = this.mtextRenderer.syncRenderMText(mtextData, style, {
1023
+ byLayerColor: 0xffffff,
1024
+ byBlockColor: 0xffffff
1025
+ });
1026
+ this.replaceRenderedObject(object);
1027
+ const rendered = this.extractBoxesFromRenderedObject(object);
1028
+ this.normalizeRenderedTopAlignment(object, rendered);
1029
+ this.layoutContainer = rendered.containerBox;
1030
+ this.updateCursorData(rendered.charBoxes, rendered.lineBreakIndices, rendered.lineLayouts);
1031
+ this.updateBoundingBoxGeometry();
1032
+ }
1033
+ catch (error) {
1034
+ console.error('[mtext-input-box] Failed to sync render MTEXT', error);
1035
+ const fallback = this.createFallbackCharBoxes();
1036
+ this.layoutContainer = fallback.containerBox;
1037
+ this.updateCursorData(fallback.charBoxes, fallback.lineBreakIndices, fallback.lineLayouts);
1038
+ this.updateBoundingBoxGeometry();
1039
+ }
1040
+ }
1041
+ updateCursorData(charBoxes, lineBreakIndices, lineLayouts) {
1042
+ this.latestCursorLayoutData = {
1043
+ containerBox: { ...this.layoutContainer },
1044
+ charBoxes: charBoxes.map((box) => ({ ...box })),
1045
+ ...(lineBreakIndices ? { lineBreakIndices: [...lineBreakIndices] } : {}),
1046
+ ...(lineLayouts ? { lineLayouts: lineLayouts.map((line) => ({ ...line })) } : {})
1047
+ };
1048
+ this.cursorLogic.updateData(this.layoutContainer, charBoxes, lineBreakIndices, lineLayouts);
1049
+ const nextIndex = Math.min(this.cursorIndex, this.charCount());
1050
+ const maxLineIndex = Math.max(0, this.cursorLogic.getLineCount() - 1);
1051
+ const pendingLineHint = this.pendingCursorLineHint === null ? null : Math.max(0, Math.min(this.pendingCursorLineHint, maxLineIndex));
1052
+ this.pendingCursorLineHint = null;
1053
+ this.cursorLogic.moveTo(nextIndex, pendingLineHint);
1054
+ if (this.selectionStart !== this.selectionEnd) {
1055
+ this.cursorLogic.setSelection(this.selectionStart, this.selectionEnd);
1056
+ }
1057
+ else {
1058
+ this.cursorLogic.clearSelection();
1059
+ }
1060
+ this.syncStateFromCursor();
1061
+ }
1062
+ extractBoxesFromRenderedObject(object) {
1063
+ const layout = object.createLayoutData();
1064
+ const charBoxes = [];
1065
+ const lineLayouts = (layout?.lines ?? [])
1066
+ .filter((line) => Number.isFinite(line.y) && Number.isFinite(line.height))
1067
+ .map((line) => ({
1068
+ y: line.y - this.position.y,
1069
+ height: Math.max(1, line.height)
1070
+ }));
1071
+ for (const entry of layout?.chars ?? []) {
1072
+ const localBox = entry.box ? this.toLocalBox(entry.box) : undefined;
1073
+ if (!localBox)
1074
+ continue;
1075
+ const isFiniteBox = Number.isFinite(localBox.x) &&
1076
+ Number.isFinite(localBox.y) &&
1077
+ Number.isFinite(localBox.width) &&
1078
+ Number.isFinite(localBox.height);
1079
+ if (!isFiniteBox)
1080
+ continue;
1081
+ charBoxes.push(localBox);
1082
+ }
1083
+ const lineBreakIndices = (layout.lines ?? [])
1084
+ .map((line) => line.breakIndex)
1085
+ .filter((value) => Number.isInteger(value))
1086
+ .filter((value) => value >= 0 && value <= charBoxes.length);
1087
+ const local = this.toLocalBox(object.box);
1088
+ let containerTop = local.y - local.height / 2;
1089
+ let containerBottom = local.y + local.height / 2;
1090
+ if (lineLayouts.length > 0) {
1091
+ for (const line of lineLayouts) {
1092
+ const top = line.y - line.height / 2;
1093
+ const bottom = line.y + line.height / 2;
1094
+ containerTop = Math.min(containerTop, top);
1095
+ containerBottom = Math.max(containerBottom, bottom);
1096
+ }
1097
+ }
1098
+ const containerBox = {
1099
+ x: local.x,
1100
+ y: containerTop,
1101
+ width: local.width,
1102
+ height: Math.max(0, containerBottom - containerTop)
1103
+ };
1104
+ containerBox.x = 0;
1105
+ containerBox.width = this.width;
1106
+ containerBox.height = Math.max(containerBox.height, this.getFallbackLineAdvance());
1107
+ return {
1108
+ containerBox,
1109
+ charBoxes,
1110
+ ...(lineBreakIndices.length > 0 ? { lineBreakIndices } : {}),
1111
+ ...(lineLayouts.length > 0 ? { lineLayouts } : {})
1112
+ };
1113
+ }
1114
+ normalizeRenderedTopAlignment(object, rendered) {
1115
+ const dy = -rendered.containerBox.y;
1116
+ if (!Number.isFinite(dy) || Math.abs(dy) < 1e-8)
1117
+ return;
1118
+ object.position.y += dy;
1119
+ object.updateMatrixWorld(true);
1120
+ rendered.containerBox.y += dy;
1121
+ rendered.charBoxes.forEach((box) => {
1122
+ box.y += dy;
1123
+ });
1124
+ rendered.lineLayouts?.forEach((line) => {
1125
+ line.y += dy;
1126
+ });
1127
+ }
1128
+ toLocalBox(worldBox) {
1129
+ const minX = worldBox.min.x - this.position.x;
1130
+ const maxX = worldBox.max.x - this.position.x;
1131
+ const minY = worldBox.min.y - this.position.y;
1132
+ const maxY = worldBox.max.y - this.position.y;
1133
+ const width = Math.max(0, maxX - minX);
1134
+ const height = Math.max(0, maxY - minY);
1135
+ return {
1136
+ x: minX,
1137
+ y: minY + height / 2,
1138
+ width,
1139
+ height
1140
+ };
1141
+ }
1142
+ createFallbackCharBoxes() {
1143
+ const lineHeight = this.getFallbackLineAdvance();
1144
+ const charBoxes = [];
1145
+ const lineBreakIndices = [];
1146
+ const lineLayouts = [];
1147
+ let x = 0;
1148
+ let y = 0;
1149
+ let maxY = lineHeight;
1150
+ lineLayouts.push({ y: y + lineHeight / 2, height: lineHeight });
1151
+ for (const char of this.getChars()) {
1152
+ if (char === '\n') {
1153
+ lineBreakIndices.push(charBoxes.length);
1154
+ x = 0;
1155
+ y += lineHeight;
1156
+ maxY = Math.max(maxY, y + lineHeight);
1157
+ lineLayouts.push({ y: y + lineHeight / 2, height: lineHeight });
1158
+ continue;
1159
+ }
1160
+ const width = Math.max(1, this.currentFormat.fontSize * 0.6);
1161
+ if (this.enableWordWrap && x > 0 && x + width > this.width) {
1162
+ lineBreakIndices.push(charBoxes.length);
1163
+ x = 0;
1164
+ y += lineHeight;
1165
+ }
1166
+ charBoxes.push({ x, y: y + lineHeight / 2, width, height: lineHeight });
1167
+ x += width;
1168
+ maxY = Math.max(maxY, y + lineHeight);
1169
+ }
1170
+ return {
1171
+ containerBox: {
1172
+ x: 0,
1173
+ y: 0,
1174
+ width: this.width,
1175
+ height: Math.max(1, maxY)
1176
+ },
1177
+ charBoxes,
1178
+ lineBreakIndices,
1179
+ lineLayouts
1180
+ };
1181
+ }
1182
+ createBoundingBox(enabled, style) {
1183
+ if (!enabled)
1184
+ return;
1185
+ const color = typeof style?.color === 'number' ? style.color : new THREE.Color(style?.color ?? '#58a6ff');
1186
+ this.boundingBoxPadding = Math.max(0, style?.padding ?? 1);
1187
+ this.boundingBoxZOffset = style?.zOffset ?? 0.01;
1188
+ const material = new THREE.LineBasicMaterial({
1189
+ color,
1190
+ transparent: true,
1191
+ opacity: style?.opacity ?? 0.9,
1192
+ depthTest: false,
1193
+ depthWrite: false
1194
+ });
1195
+ const geometry = new THREE.BufferGeometry();
1196
+ this.boundingBoxObject = new THREE.LineLoop(geometry, material);
1197
+ this.boundingBoxObject.position.z = this.boundingBoxZOffset;
1198
+ this.scene.add(this.boundingBoxObject);
1199
+ }
1200
+ updateBoundingBoxGeometry() {
1201
+ if (!this.boundingBoxObject)
1202
+ return;
1203
+ const existing = this.boundingBoxObject.geometry;
1204
+ existing.dispose();
1205
+ const padding = this.boundingBoxPadding;
1206
+ const minX = this.position.x + this.layoutContainer.x - padding;
1207
+ const minY = this.position.y + this.layoutContainer.y - padding;
1208
+ const maxX = this.position.x + this.layoutContainer.x + this.layoutContainer.width + padding;
1209
+ const maxY = this.position.y + this.layoutContainer.y + this.layoutContainer.height + padding;
1210
+ const z = this.position.z;
1211
+ this.boundingBoxObject.geometry = new THREE.BufferGeometry().setFromPoints([
1212
+ new THREE.Vector3(minX, minY, z),
1213
+ new THREE.Vector3(maxX, minY, z),
1214
+ new THREE.Vector3(maxX, maxY, z),
1215
+ new THREE.Vector3(minX, maxY, z)
1216
+ ]);
1217
+ }
1218
+ disposeBoundingBox() {
1219
+ if (!this.boundingBoxObject)
1220
+ return;
1221
+ this.boundingBoxObject.removeFromParent();
1222
+ this.boundingBoxObject.geometry.dispose();
1223
+ const materials = Array.isArray(this.boundingBoxObject.material)
1224
+ ? this.boundingBoxObject.material
1225
+ : [this.boundingBoxObject.material];
1226
+ for (const material of materials) {
1227
+ material.dispose();
1228
+ }
1229
+ this.boundingBoxObject = null;
1230
+ }
1231
+ replaceRenderedObject(object) {
1232
+ this.disposeRenderedObject(this.renderedObject);
1233
+ this.forceVisibleMaterialState(object);
1234
+ this.renderedObject = object;
1235
+ this.scene.add(object);
1236
+ }
1237
+ forceVisibleMaterialState(object) {
1238
+ object.traverse((child) => {
1239
+ const meshLike = child;
1240
+ const materials = (meshLike.material
1241
+ ? Array.isArray(meshLike.material)
1242
+ ? meshLike.material
1243
+ : [meshLike.material]
1244
+ : []);
1245
+ for (const mat of materials) {
1246
+ const m = mat;
1247
+ if (typeof m.side !== "undefined")
1248
+ m.side = THREE.DoubleSide;
1249
+ if (typeof m.depthTest !== "undefined")
1250
+ m.depthTest = false;
1251
+ if (typeof m.depthWrite !== "undefined")
1252
+ m.depthWrite = false;
1253
+ if (typeof m.transparent !== "undefined" && typeof m.opacity !== "undefined") {
1254
+ m.transparent = m.opacity < 1;
1255
+ }
1256
+ m.needsUpdate = true;
1257
+ }
1258
+ });
1259
+ }
1260
+ disposeRenderedObject(object) {
1261
+ if (!object)
1262
+ return;
1263
+ object.removeFromParent();
1264
+ const withDispose = object;
1265
+ if (typeof withDispose.dispose === 'function') {
1266
+ withDispose.dispose();
1267
+ return;
1268
+ }
1269
+ object.traverse((child) => {
1270
+ const mesh = child;
1271
+ if (mesh.geometry) {
1272
+ mesh.geometry.dispose();
1273
+ }
1274
+ const materials = (mesh.material ? (Array.isArray(mesh.material) ? mesh.material : [mesh.material]) : []);
1275
+ for (const material of materials) {
1276
+ const withMap = material;
1277
+ if (withMap.map)
1278
+ withMap.map.dispose();
1279
+ material.dispose();
1280
+ }
1281
+ });
1282
+ }
1283
+ isExplicitAci(aci) {
1284
+ return aci !== null && Number.isInteger(aci) && aci > 0 && aci < 256;
1285
+ }
1286
+ normalizeColorNumber(color) {
1287
+ return Math.max(0, Math.min(0xffffff, Math.round(color)));
1288
+ }
1289
+ resolveAciColor(aci) {
1290
+ const value = getColorByIndex(aci);
1291
+ return this.normalizeColorNumber(Number.isFinite(value) ? value : 0xffffff);
1292
+ }
1293
+ resolveBaseColor() {
1294
+ if (this.isExplicitAci(this.baseFormat.aci)) {
1295
+ return this.resolveAciColor(this.baseFormat.aci);
1296
+ }
1297
+ if (this.baseFormat.rgb !== null) {
1298
+ return this.normalizeColorNumber(this.baseFormat.rgb);
1299
+ }
1300
+ return 0xffffff;
1301
+ }
1302
+ resolveFormatColorNumber(format) {
1303
+ return this.isExplicitAci(format.aci)
1304
+ ? this.resolveAciColor(format.aci)
1305
+ : format.rgb !== null
1306
+ ? this.normalizeColorNumber(format.rgb)
1307
+ : 0xffffff;
1308
+ }
1309
+ createDefaultTextStyle() {
1310
+ const baseSize = Math.max(1, this.baseFormat.fontSize);
1311
+ return {
1312
+ name: 'MTextInputBoxStyle',
1313
+ standardFlag: 0,
1314
+ fixedTextHeight: baseSize,
1315
+ widthFactor: 1,
1316
+ obliqueAngle: 0,
1317
+ textGenerationFlag: 0,
1318
+ lastHeight: baseSize,
1319
+ font: this.baseFormat.fontFamily || 'simkai',
1320
+ bigFont: '',
1321
+ color: this.resolveFormatColorNumber(this.baseFormat)
1322
+ };
1323
+ }
1324
+ createMTextData() {
1325
+ return {
1326
+ text: this.mtextString,
1327
+ height: Math.max(1, this.defaultTextStyle.fixedTextHeight),
1328
+ width: this.width,
1329
+ position: {
1330
+ x: this.position.x,
1331
+ y: this.position.y,
1332
+ z: this.position.z
1333
+ },
1334
+ attachmentPoint: MTextAttachmentPoint.TopLeft,
1335
+ drawingDirection: MTextFlowDirection.LEFT_TO_RIGHT,
1336
+ widthFactor: 1,
1337
+ collectCharBoxes: true
1338
+ };
1339
+ }
1340
+ getFallbackLineAdvance() {
1341
+ return Math.max(1, this.currentFormat.fontSize * MTextInputBox.FALLBACK_LINE_ADVANCE_RATIO);
1342
+ }
1343
+ createTextStyle() {
1344
+ return { ...this.defaultTextStyle };
1345
+ }
1346
+ focusImeInput() {
1347
+ if (!this.imeInput)
1348
+ return;
1349
+ this.imeInput.focus({ preventScroll: true });
1350
+ }
1351
+ refocusImeInputSoon() {
1352
+ if (!this.imeInput)
1353
+ return;
1354
+ if (this.imeFocusTimer !== null) {
1355
+ window.clearTimeout(this.imeFocusTimer);
1356
+ }
1357
+ this.imeFocusTimer = window.setTimeout(() => {
1358
+ this.focusImeInput();
1359
+ this.imeFocusTimer = null;
1360
+ }, 0);
1361
+ }
1362
+ updateImeAnchorPosition() {
1363
+ if (!this.imeInput || !this.imeTarget)
1364
+ return;
1365
+ const cursorWorld = this.getCursorWorldPosition();
1366
+ const world = new THREE.Vector3(cursorWorld.x, cursorWorld.y, cursorWorld.z);
1367
+ const projected = world.project(this.camera);
1368
+ const rect = this.imeTarget.getBoundingClientRect();
1369
+ const x = rect.left + ((projected.x + 1) * 0.5) * rect.width;
1370
+ const y = rect.top + ((1 - projected.y) * 0.5) * rect.height;
1371
+ this.imeInput.style.left = `${Math.round(x)}px`;
1372
+ this.imeInput.style.top = `${Math.round(y)}px`;
1373
+ }
1374
+ syncStateFromCursor() {
1375
+ this.cursorIndex = this.cursorLogic.getCurrentIndex();
1376
+ const selection = this.cursorLogic.getSelection();
1377
+ if (!selection) {
1378
+ this.selectionStart = this.cursorIndex;
1379
+ this.selectionEnd = this.cursorIndex;
1380
+ }
1381
+ else {
1382
+ this.selectionStart = selection.start;
1383
+ this.selectionEnd = selection.end;
1384
+ }
1385
+ this.syncDocumentFromUiState();
1386
+ this.refreshCurrentFormatFromDocument();
1387
+ }
1388
+ consumeMove(direction) {
1389
+ this.moveCursor(direction);
1390
+ return true;
1391
+ }
1392
+ consumeExtend(direction) {
1393
+ this.extendSelection(direction);
1394
+ return true;
1395
+ }
1396
+ isMacPlatform() {
1397
+ if (typeof navigator === 'undefined')
1398
+ return false;
1399
+ return /Mac|iPhone|iPad|iPod/i.test(navigator.platform);
1400
+ }
1401
+ emit(event) {
1402
+ for (const handler of this.handlers[event])
1403
+ handler();
1404
+ }
1405
+ findPrevWordStart(index) {
1406
+ const chars = this.getChars();
1407
+ let i = Math.max(0, index - 1);
1408
+ while (i > 0 && /\s/.test(chars[i] ?? ''))
1409
+ i -= 1;
1410
+ while (i > 0 && !/\s/.test(chars[i - 1] ?? ''))
1411
+ i -= 1;
1412
+ return i;
1413
+ }
1414
+ findNextWordStart(index) {
1415
+ const chars = this.getChars();
1416
+ let i = Math.min(chars.length, index);
1417
+ while (i < chars.length && !/\s/.test(chars[i] ?? ''))
1418
+ i += 1;
1419
+ while (i < chars.length && /\s/.test(chars[i] ?? ''))
1420
+ i += 1;
1421
+ return i;
1422
+ }
1423
+ getChars() {
1424
+ const chars = [];
1425
+ for (const node of this.document.ast.nodes) {
1426
+ if (node.type === 'char') {
1427
+ chars.push(node.value);
1428
+ continue;
1429
+ }
1430
+ if (node.type === 'stack') {
1431
+ chars.push('');
1432
+ continue;
1433
+ }
1434
+ if (node.type === 'paragraphBreak' || node.type === 'columnBreak' || node.type === 'wrapAtDimLine') {
1435
+ chars.push('\n');
1436
+ }
1437
+ }
1438
+ return chars;
1439
+ }
1440
+ charCount() {
1441
+ return this.getChars().length;
1442
+ }
1443
+ getActiveCursorRenderState(fallbackPosition, fallbackHeight) {
1444
+ const boxes = this.cursorLogic.getCharBoxes();
1445
+ const index = this.cursorLogic.getCurrentIndex();
1446
+ const line = this.cursorLogic.getCurrentLineInfo();
1447
+ if (boxes.length === 0) {
1448
+ return {
1449
+ position: fallbackPosition,
1450
+ height: Math.max(1, fallbackHeight)
1451
+ };
1452
+ }
1453
+ // At a line-start gap (including wrapped/paragraph boundaries), rely on
1454
+ // cursor logic line-hint rather than previous glyph box.
1455
+ if (index <= 0 || index === line.startIndex) {
1456
+ const isEmptyLine = line.charCount <= 0 || line.endIndex < line.startIndex;
1457
+ if (!isEmptyLine) {
1458
+ const firstIndex = Math.max(0, Math.min(line.startIndex, boxes.length - 1));
1459
+ const first = boxes[firstIndex];
1460
+ if (first) {
1461
+ return {
1462
+ position: { x: fallbackPosition.x, y: first.y },
1463
+ height: Math.max(1, first.height)
1464
+ };
1465
+ }
1466
+ }
1467
+ const emptyLineHeight = (line.height ?? fallbackHeight) * 0.8;
1468
+ return {
1469
+ position: { x: fallbackPosition.x, y: line.y ?? fallbackPosition.y },
1470
+ height: Math.max(1, emptyLineHeight)
1471
+ };
1472
+ }
1473
+ const prev = boxes[Math.min(index - 1, boxes.length - 1)];
1474
+ if (!prev) {
1475
+ return {
1476
+ position: fallbackPosition,
1477
+ height: Math.max(1, fallbackHeight)
1478
+ };
1479
+ }
1480
+ return {
1481
+ position: { x: prev.x + prev.width, y: prev.y },
1482
+ height: Math.max(1, prev.height)
1483
+ };
1484
+ }
1485
+ getNodeLogicalSpan(node) {
1486
+ switch (node.type) {
1487
+ case "char":
1488
+ return 1;
1489
+ case "stack":
1490
+ return 1;
1491
+ case "paragraphBreak":
1492
+ case "columnBreak":
1493
+ case "wrapAtDimLine":
1494
+ // Structural line-break nodes do not have a visual char box, so
1495
+ // they must not consume logical cursor positions.
1496
+ return 0;
1497
+ default:
1498
+ return 0;
1499
+ }
1500
+ }
1501
+ toLogicalIndexFromDocumentIndex(documentIndex) {
1502
+ const safeIndex = Math.max(0, Math.min(documentIndex, this.document.ast.nodes.length));
1503
+ let logical = 0;
1504
+ for (let i = 0; i < safeIndex; i += 1) {
1505
+ const node = this.document.ast.nodes[i];
1506
+ if (!node)
1507
+ continue;
1508
+ logical += this.getNodeLogicalSpan(node);
1509
+ }
1510
+ return logical;
1511
+ }
1512
+ toDocumentIndexFromLogicalIndex(logicalIndex, preferAfterZeroSpan = true, lineIndexHint) {
1513
+ const nodes = this.document.ast.nodes;
1514
+ if (nodes.length === 0)
1515
+ return 0;
1516
+ const maxLogical = this.charCount();
1517
+ const targetLogical = Math.max(0, Math.min(logicalIndex, maxLogical));
1518
+ const candidates = [];
1519
+ let logical = 0;
1520
+ let lineIndex = 0;
1521
+ for (let i = 0; i <= nodes.length; i += 1) {
1522
+ if (logical === targetLogical) {
1523
+ candidates.push({ index: i, lineIndex });
1524
+ }
1525
+ if (i === nodes.length)
1526
+ break;
1527
+ const node = nodes[i];
1528
+ if (!node)
1529
+ continue;
1530
+ const span = this.getNodeLogicalSpan(node);
1531
+ if (span === 0) {
1532
+ lineIndex += 1;
1533
+ }
1534
+ else {
1535
+ logical += span;
1536
+ }
1537
+ }
1538
+ if (candidates.length === 0)
1539
+ return nodes.length;
1540
+ if (lineIndexHint !== undefined && Number.isFinite(lineIndexHint)) {
1541
+ const self = this;
1542
+ const resolveCandidateByVisualLineHint = typeof self.resolveCandidateByVisualLineHint === 'function'
1543
+ ? self.resolveCandidateByVisualLineHint
1544
+ : MTextInputBox.prototype.resolveCandidateByVisualLineHint;
1545
+ const visualMatch = resolveCandidateByVisualLineHint.call(this, candidates, targetLogical, lineIndexHint);
1546
+ if (visualMatch !== undefined) {
1547
+ return visualMatch;
1548
+ }
1549
+ const minCandidateLine = candidates[0]?.lineIndex ?? 0;
1550
+ const maxCandidateLine = candidates[candidates.length - 1]?.lineIndex ?? 0;
1551
+ if (lineIndexHint < minCandidateLine || lineIndexHint > maxCandidateLine) {
1552
+ return preferAfterZeroSpan ? candidates[candidates.length - 1].index : candidates[0].index;
1553
+ }
1554
+ let best = candidates[0];
1555
+ let bestDist = Math.abs(best.lineIndex - lineIndexHint);
1556
+ for (let i = 1; i < candidates.length; i += 1) {
1557
+ const candidate = candidates[i];
1558
+ const dist = Math.abs(candidate.lineIndex - lineIndexHint);
1559
+ if (dist < bestDist) {
1560
+ best = candidate;
1561
+ bestDist = dist;
1562
+ }
1563
+ }
1564
+ return best.index;
1565
+ }
1566
+ return preferAfterZeroSpan ? candidates[candidates.length - 1].index : candidates[0].index;
1567
+ }
1568
+ resolveCandidateByVisualLineHint(candidates, logicalIndex, lineIndexHint) {
1569
+ if (candidates.length <= 1)
1570
+ return undefined;
1571
+ if (this.cursorLogic == null || typeof this.cursorLogic.getLines !== 'function')
1572
+ return undefined;
1573
+ const lines = this.cursorLogic.getLines();
1574
+ if (!Array.isArray(lines) || lines.length === 0)
1575
+ return undefined;
1576
+ const visualMatches = [];
1577
+ for (let i = 0; i < lines.length; i += 1) {
1578
+ const line = lines[i];
1579
+ if (!line)
1580
+ continue;
1581
+ if (logicalIndex >= line.startIndex && logicalIndex <= line.endIndex + 1) {
1582
+ visualMatches.push(i);
1583
+ }
1584
+ }
1585
+ if (visualMatches.length !== candidates.length)
1586
+ return undefined;
1587
+ const rank = visualMatches.indexOf(lineIndexHint);
1588
+ if (rank < 0)
1589
+ return undefined;
1590
+ const candidate = candidates[rank];
1591
+ return candidate?.index;
1592
+ }
1593
+ syncUiStateFromDocument() {
1594
+ this.mtextString = this.document.toMText();
1595
+ const logicalLength = this.charCount();
1596
+ this.cursorIndex = Math.min(this.toLogicalIndexFromDocumentIndex(this.document.cursor), logicalLength);
1597
+ const selection = this.document.selection;
1598
+ if (selection) {
1599
+ this.selectionStart = this.toLogicalIndexFromDocumentIndex(selection.start);
1600
+ this.selectionEnd = this.toLogicalIndexFromDocumentIndex(selection.end);
1601
+ }
1602
+ else {
1603
+ this.selectionStart = this.cursorIndex;
1604
+ this.selectionEnd = this.cursorIndex;
1605
+ }
1606
+ this.refreshCurrentFormatFromDocument();
1607
+ }
1608
+ syncDocumentFromUiState() {
1609
+ const selection = this.getSelectionRange();
1610
+ if (!selection.isCollapsed) {
1611
+ const start = this.toDocumentIndexFromLogicalIndex(selection.start, false);
1612
+ const end = this.toDocumentIndexFromLogicalIndex(selection.end, false);
1613
+ this.document.setSelection(start, end);
1614
+ return;
1615
+ }
1616
+ this.document.clearSelection();
1617
+ const cursorState = this.cursorLogic.getCursorState();
1618
+ const lineIndexHint = cursorState.lineIndex;
1619
+ const preferAfterZeroSpan = cursorState.isAtLineEnd && !cursorState.isAtLineStart ? false : true;
1620
+ this.document.cursor = this.toDocumentIndexFromLogicalIndex(this.cursorIndex, preferAfterZeroSpan, lineIndexHint >= 0 ? lineIndexHint : undefined);
1621
+ }
1622
+ refreshCurrentFormatFromDocument() {
1623
+ const inferred = this.inferCurrentFormatFromDocument();
1624
+ this.updateToolbarStackState();
1625
+ if (!inferred) {
1626
+ this.getActiveToolbar()?.setFormat(this.currentFormat);
1627
+ return;
1628
+ }
1629
+ if (!sameFormat(this.currentFormat, inferred)) {
1630
+ this.currentFormat = inferred;
1631
+ }
1632
+ this.getActiveToolbar()?.setFormat(this.currentFormat);
1633
+ }
1634
+ toggleStackSelection() {
1635
+ const selection = this.getSelectionRange();
1636
+ if (selection.isCollapsed)
1637
+ return;
1638
+ this.commitHistoryEdit(() => {
1639
+ this.syncDocumentFromUiState();
1640
+ const start = this.toDocumentIndexFromLogicalIndex(selection.start, false);
1641
+ const end = this.toDocumentIndexFromLogicalIndex(selection.end, false);
1642
+ if (end <= start)
1643
+ return;
1644
+ const selectedNodes = this.document.ast.nodes.slice(start, end);
1645
+ if (selectedNodes.length === 1 && selectedNodes[0]?.type === 'stack') {
1646
+ const stackNode = selectedNodes[0];
1647
+ const plainText = this.stackNodeToPlainText(stackNode.numerator, stackNode.denominator, stackNode.divider);
1648
+ const plainNodes = Array.from(plainText).map((char) => ({
1649
+ type: 'char',
1650
+ value: char,
1651
+ style: this.cloneDocumentStyle(stackNode.style)
1652
+ }));
1653
+ if (plainNodes.length === 0)
1654
+ return;
1655
+ this.document.transaction((doc) => {
1656
+ doc.ast.nodes.splice(start, 1, ...plainNodes);
1657
+ doc.setSelection(start, start + plainNodes.length);
1658
+ });
1659
+ this.syncUiStateFromDocument();
1660
+ this.relayout();
1661
+ return;
1662
+ }
1663
+ if (!selectedNodes.every((node) => node?.type === 'char'))
1664
+ return;
1665
+ const plainText = selectedNodes.map((node) => node.value).join('');
1666
+ const stackParts = this.parseStackParts(plainText);
1667
+ if (!stackParts)
1668
+ return;
1669
+ const first = selectedNodes[0];
1670
+ if (!first)
1671
+ return;
1672
+ const stackNode = {
1673
+ type: 'stack',
1674
+ numerator: stackParts.numerator,
1675
+ denominator: stackParts.denominator,
1676
+ divider: stackParts.divider,
1677
+ style: this.cloneDocumentStyle(first.style)
1678
+ };
1679
+ this.document.transaction((doc) => {
1680
+ doc.ast.nodes.splice(start, end - start, stackNode);
1681
+ doc.setSelection(start, start + 1);
1682
+ });
1683
+ this.syncUiStateFromDocument();
1684
+ this.relayout();
1685
+ });
1686
+ }
1687
+ toggleScriptSelection(script) {
1688
+ const selection = this.getSelectionRange();
1689
+ if (selection.isCollapsed)
1690
+ return false;
1691
+ let changed = false;
1692
+ this.commitHistoryEdit(() => {
1693
+ this.syncDocumentFromUiState();
1694
+ const start = this.toDocumentIndexFromLogicalIndex(selection.start, false);
1695
+ const end = this.toDocumentIndexFromLogicalIndex(selection.end, false);
1696
+ if (end <= start)
1697
+ return;
1698
+ const selectedNodes = this.document.ast.nodes.slice(start, end);
1699
+ if (selectedNodes.length === 1 && selectedNodes[0]?.type === 'stack') {
1700
+ const stackNode = selectedNodes[0];
1701
+ const plainText = this.scriptStackToPlainText(stackNode.numerator, stackNode.denominator, stackNode.divider);
1702
+ if (!plainText)
1703
+ return;
1704
+ const plainStyle = this.cloneDocumentStyle(stackNode.style);
1705
+ plainStyle.script = 'normal';
1706
+ plainStyle.align = MTextLineAlignment.MIDDLE;
1707
+ const plainNodes = Array.from(plainText).map((char) => ({
1708
+ type: 'char',
1709
+ value: char,
1710
+ style: this.cloneDocumentStyle(plainStyle)
1711
+ }));
1712
+ if (plainNodes.length === 0)
1713
+ return;
1714
+ this.document.transaction((doc) => {
1715
+ doc.ast.nodes.splice(start, 1, ...plainNodes);
1716
+ doc.setSelection(start, start + plainNodes.length);
1717
+ });
1718
+ this.syncUiStateFromDocument();
1719
+ this.relayout();
1720
+ changed = true;
1721
+ return;
1722
+ }
1723
+ if (!selectedNodes.every((node) => node?.type === 'char'))
1724
+ return;
1725
+ const plainText = selectedNodes.map((node) => node.value).join('');
1726
+ if (plainText.length === 0)
1727
+ return;
1728
+ const first = selectedNodes[0];
1729
+ if (!first)
1730
+ return;
1731
+ const scriptStyle = this.cloneDocumentStyle(first.style);
1732
+ scriptStyle.script = script;
1733
+ scriptStyle.align = script === 'superscript' ? MTextLineAlignment.TOP : MTextLineAlignment.BOTTOM;
1734
+ const stackNode = {
1735
+ type: 'stack',
1736
+ numerator: script === 'superscript' ? plainText : '',
1737
+ denominator: script === 'subscript' ? plainText : '',
1738
+ divider: '^',
1739
+ style: this.cloneDocumentStyle(scriptStyle)
1740
+ };
1741
+ this.document.transaction((doc) => {
1742
+ doc.ast.nodes.splice(start, end - start, stackNode);
1743
+ doc.setSelection(start, start + 1);
1744
+ });
1745
+ this.syncUiStateFromDocument();
1746
+ this.relayout();
1747
+ changed = true;
1748
+ });
1749
+ return changed;
1750
+ }
1751
+ commitHistoryEdit(edit) {
1752
+ const before = this.createHistorySnapshot();
1753
+ edit();
1754
+ if (this.isSameAsCurrent(before))
1755
+ return;
1756
+ this.undoStack.push(before);
1757
+ if (this.undoStack.length > this.maxHistorySize) {
1758
+ this.undoStack.splice(0, this.undoStack.length - this.maxHistorySize);
1759
+ }
1760
+ this.redoStack = [];
1761
+ this.emit('change');
1762
+ this.emit('selectionChange');
1763
+ this.emit('cursorMove');
1764
+ }
1765
+ createHistorySnapshot() {
1766
+ return {
1767
+ ast: this.cloneAst(this.document.ast),
1768
+ cursor: this.document.cursor,
1769
+ selection: this.document.selection ? { ...this.document.selection } : null,
1770
+ currentFormat: { ...this.currentFormat }
1771
+ };
1772
+ }
1773
+ restoreHistorySnapshot(snapshot) {
1774
+ this.document = new MTextDocument(this.cloneAst(snapshot.ast));
1775
+ if (snapshot.selection) {
1776
+ this.document.setSelection(snapshot.selection.start, snapshot.selection.end);
1777
+ }
1778
+ else {
1779
+ this.document.cursor = snapshot.cursor;
1780
+ this.document.clearSelection();
1781
+ }
1782
+ this.uiAdapter = new EditorUiAdapter(this.document);
1783
+ this.currentFormat = { ...snapshot.currentFormat };
1784
+ this.syncUiStateFromDocument();
1785
+ this.relayout();
1786
+ this.emit('change');
1787
+ this.emit('selectionChange');
1788
+ this.emit('cursorMove');
1789
+ }
1790
+ isSameAsCurrent(snapshot) {
1791
+ if (snapshot.cursor !== this.document.cursor)
1792
+ return false;
1793
+ const selection = this.document.selection;
1794
+ if (!!snapshot.selection !== !!selection)
1795
+ return false;
1796
+ if (snapshot.selection && selection) {
1797
+ if (snapshot.selection.start !== selection.start || snapshot.selection.end !== selection.end) {
1798
+ return false;
1799
+ }
1800
+ }
1801
+ if (!sameFormat(snapshot.currentFormat, this.currentFormat))
1802
+ return false;
1803
+ return this.document.toMText() === this.buildMTextFromAst(snapshot.ast);
1804
+ }
1805
+ buildMTextFromAst(ast) {
1806
+ return new MTextDocument(this.cloneAst(ast)).toMText();
1807
+ }
1808
+ clearHistory() {
1809
+ this.undoStack = [];
1810
+ this.redoStack = [];
1811
+ }
1812
+ cloneAst(ast) {
1813
+ return {
1814
+ nodes: ast.nodes.map((node) => {
1815
+ if (node.type === 'char') {
1816
+ return { ...node, style: this.cloneDocumentStyle(node.style) };
1817
+ }
1818
+ if (node.type === 'stack') {
1819
+ return { ...node, style: this.cloneDocumentStyle(node.style) };
1820
+ }
1821
+ return { ...node, style: this.cloneDocumentStyle(node.style) };
1822
+ })
1823
+ };
1824
+ }
1825
+ stackNodeToPlainText(numerator, denominator, divider) {
1826
+ if (divider === '^') {
1827
+ if (numerator.length === 0 && denominator.length > 0) {
1828
+ return `^${denominator.trimStart()}`;
1829
+ }
1830
+ if (numerator.length > 0 && denominator.length === 0) {
1831
+ return `${numerator.trimEnd()}^`;
1832
+ }
1833
+ }
1834
+ return `${numerator}${divider}${denominator}`;
1835
+ }
1836
+ scriptStackToPlainText(numerator, denominator, divider) {
1837
+ if (divider !== '^')
1838
+ return null;
1839
+ const hasNumerator = numerator.trim().length > 0;
1840
+ const hasDenominator = denominator.trim().length > 0;
1841
+ if (hasNumerator === hasDenominator)
1842
+ return null;
1843
+ return hasNumerator ? numerator.trim() : denominator.trim();
1844
+ }
1845
+ parseStackParts(plainText) {
1846
+ const dividerIndices = [];
1847
+ for (let i = 0; i < plainText.length; i += 1) {
1848
+ const char = plainText[i];
1849
+ if (char === '/' || char === '#' || char === '^') {
1850
+ dividerIndices.push({ index: i, divider: char });
1851
+ }
1852
+ }
1853
+ if (dividerIndices.length !== 1)
1854
+ return null;
1855
+ const dividerInfo = dividerIndices[0];
1856
+ if (!dividerInfo)
1857
+ return null;
1858
+ const { index, divider } = dividerInfo;
1859
+ const numerator = plainText.slice(0, index);
1860
+ const denominator = plainText.slice(index + 1);
1861
+ if (divider === '^') {
1862
+ const hasNumerator = numerator.trim().length > 0;
1863
+ const hasDenominator = denominator.trim().length > 0;
1864
+ if (!hasNumerator && !hasDenominator)
1865
+ return null;
1866
+ return { numerator, denominator, divider };
1867
+ }
1868
+ if (numerator.trim().length === 0 || denominator.trim().length === 0)
1869
+ return null;
1870
+ return { numerator, denominator, divider };
1871
+ }
1872
+ updateToolbarStackState() {
1873
+ const toolbar = this.getActiveToolbar();
1874
+ if (!toolbar)
1875
+ return;
1876
+ const selection = this.getSelectionRange();
1877
+ if (selection.isCollapsed) {
1878
+ toolbar.setStackActive(false);
1879
+ return;
1880
+ }
1881
+ const start = this.toDocumentIndexFromLogicalIndex(selection.start, false);
1882
+ const end = this.toDocumentIndexFromLogicalIndex(selection.end, false);
1883
+ const selectedNodes = this.document.ast.nodes.slice(start, end);
1884
+ const active = selectedNodes.length === 1 &&
1885
+ selectedNodes[0]?.type === 'stack' &&
1886
+ !this.isScriptOnlyStack(selectedNodes[0]);
1887
+ toolbar.setStackActive(active);
1888
+ }
1889
+ isScriptOnlyStack(node) {
1890
+ if (node.divider !== '^')
1891
+ return false;
1892
+ const hasNumerator = node.numerator.trim().length > 0;
1893
+ const hasDenominator = node.denominator.trim().length > 0;
1894
+ return hasNumerator !== hasDenominator;
1895
+ }
1896
+ inferCurrentFormatFromDocument() {
1897
+ const nodes = this.document.ast.nodes;
1898
+ if (nodes.length === 0)
1899
+ return null;
1900
+ const logicalLength = this.getChars().length;
1901
+ if (logicalLength === 0)
1902
+ return null;
1903
+ const hasSelection = this.selectionStart !== this.selectionEnd;
1904
+ const anchorIndex = hasSelection
1905
+ ? Math.min(this.selectionStart, this.selectionEnd)
1906
+ : this.cursorIndex > 0
1907
+ ? this.cursorIndex - 1
1908
+ : 0;
1909
+ const node = this.getNodeByLogicalCharIndex(anchorIndex);
1910
+ if (!node)
1911
+ return null;
1912
+ return this.toCharFormat(node.style);
1913
+ }
1914
+ getNodeByLogicalCharIndex(index) {
1915
+ const nodes = this.document.ast.nodes;
1916
+ if (nodes.length === 0)
1917
+ return null;
1918
+ let offset = 0;
1919
+ const safeIndex = Math.max(0, index);
1920
+ for (const node of nodes) {
1921
+ const span = this.getNodeLogicalSpan(node);
1922
+ if (safeIndex < offset + span) {
1923
+ return node;
1924
+ }
1925
+ offset += span;
1926
+ }
1927
+ return nodes[nodes.length - 1] ?? null;
1928
+ }
1929
+ getNodesByLogicalRange(start, end) {
1930
+ const nodes = this.document.ast.nodes;
1931
+ if (nodes.length === 0)
1932
+ return [];
1933
+ const rangeStart = Math.max(0, Math.min(start, end));
1934
+ const rangeEnd = Math.max(rangeStart, Math.max(start, end));
1935
+ if (rangeStart === rangeEnd)
1936
+ return [];
1937
+ const selected = [];
1938
+ let offset = 0;
1939
+ for (const node of nodes) {
1940
+ const span = this.getNodeLogicalSpan(node);
1941
+ const nodeStart = offset;
1942
+ const nodeEnd = offset + span;
1943
+ if (span > 0 && nodeStart < rangeEnd && nodeEnd > rangeStart) {
1944
+ selected.push(node);
1945
+ }
1946
+ offset = nodeEnd;
1947
+ }
1948
+ return selected;
1949
+ }
1950
+ toCharFormat(style) {
1951
+ const baseSize = Math.max(1, this.defaultTextStyle.fixedTextHeight);
1952
+ const capHeight = style.capHeight.isRelative
1953
+ ? baseSize * Math.max(0, style.capHeight.value)
1954
+ : style.capHeight.value;
1955
+ const defaultFontFamily = this.defaultTextStyle.font || this.baseFormat.fontFamily;
1956
+ const resolvedColor = style.rgb
1957
+ ? this.rgbArrayToColorNumber(style.rgb)
1958
+ : this.isExplicitAci(style.aci)
1959
+ ? this.resolveAciColor(style.aci)
1960
+ : this.resolveBaseColor();
1961
+ const resolvedAci = this.isExplicitAci(style.aci)
1962
+ ? style.aci
1963
+ : this.isExplicitAci(this.baseFormat.aci)
1964
+ ? this.baseFormat.aci
1965
+ : null;
1966
+ const script = this.toScriptFromStyle(style, baseSize, capHeight);
1967
+ const reducedThreshold = Math.max(1, baseSize) * 0.9;
1968
+ const isReducedScriptCapHeight = capHeight <= reducedThreshold;
1969
+ const logicalFontSize = script === 'normal' ? capHeight : isReducedScriptCapHeight ? capHeight / 0.7 : capHeight;
1970
+ return {
1971
+ fontFamily: style.fontFace.family || defaultFontFamily,
1972
+ fontSize: Math.max(1, logicalFontSize || baseSize),
1973
+ bold: style.fontFace.weight >= 700,
1974
+ italic: style.fontFace.style === 'Italic',
1975
+ underline: style.underline,
1976
+ overline: style.overline,
1977
+ strike: style.strikeThrough,
1978
+ script,
1979
+ aci: resolvedAci,
1980
+ rgb: resolvedColor
1981
+ };
1982
+ }
1983
+ toScriptFromStyle(style, baseSize, capHeight) {
1984
+ if (style.script && style.script !== 'normal') {
1985
+ return style.script;
1986
+ }
1987
+ const reducedThreshold = Math.max(1, baseSize) * 0.9;
1988
+ const isReduced = capHeight <= reducedThreshold;
1989
+ if (isReduced && style.align === MTextLineAlignment.TOP) {
1990
+ return 'superscript';
1991
+ }
1992
+ if (isReduced && style.align === MTextLineAlignment.BOTTOM) {
1993
+ return 'subscript';
1994
+ }
1995
+ return 'normal';
1996
+ }
1997
+ createDefaultParseContext() {
1998
+ const context = new MTextContext();
1999
+ context.fontFace.family = this.defaultTextStyle.font || this.baseFormat.fontFamily;
2000
+ context.fontFace.style = this.baseFormat.italic ? 'Italic' : 'Regular';
2001
+ context.fontFace.weight = this.baseFormat.bold ? 700 : 400;
2002
+ // Relative cap height keeps parser defaults aligned with editor base text height.
2003
+ context.capHeight = { value: 1, isRelative: true };
2004
+ context.align = MTextLineAlignment.MIDDLE;
2005
+ context.widthFactor = { value: this.defaultTextStyle.widthFactor ?? 1, isRelative: true };
2006
+ if (this.isExplicitAci(this.baseFormat.aci)) {
2007
+ context.aci = this.baseFormat.aci;
2008
+ context.rgb = null;
2009
+ }
2010
+ else {
2011
+ const color = this.resolveBaseColor();
2012
+ context.rgb = this.colorNumberToRgbArray(color);
2013
+ context.aci = 256;
2014
+ }
2015
+ return context;
2016
+ }
2017
+ createNormalizedDocument(text) {
2018
+ const base = MTextDocument.fromMText(text, this.createDefaultParseContext());
2019
+ const normalizedAst = { nodes: [] };
2020
+ for (const node of base.ast.nodes) {
2021
+ switch (node.type) {
2022
+ case 'char':
2023
+ normalizedAst.nodes.push({
2024
+ type: 'char',
2025
+ value: node.value,
2026
+ style: this.cloneDocumentStyle(node.style)
2027
+ });
2028
+ break;
2029
+ case 'stack':
2030
+ normalizedAst.nodes.push({
2031
+ type: 'stack',
2032
+ numerator: node.numerator,
2033
+ denominator: node.denominator,
2034
+ divider: node.divider,
2035
+ style: this.cloneDocumentStyle(node.style)
2036
+ });
2037
+ break;
2038
+ case 'paragraphBreak':
2039
+ normalizedAst.nodes.push({
2040
+ type: 'paragraphBreak',
2041
+ style: this.cloneDocumentStyle(node.style)
2042
+ });
2043
+ break;
2044
+ case 'columnBreak':
2045
+ case 'wrapAtDimLine':
2046
+ normalizedAst.nodes.push({
2047
+ type: 'paragraphBreak',
2048
+ style: this.cloneDocumentStyle(node.style)
2049
+ });
2050
+ break;
2051
+ default:
2052
+ break;
2053
+ }
2054
+ }
2055
+ return new MTextDocument(normalizedAst);
2056
+ }
2057
+ mergeCharFormat(base, patch) {
2058
+ const next = { ...base, ...patch };
2059
+ if (patch.aci !== undefined) {
2060
+ if (!this.isExplicitAci(patch.aci)) {
2061
+ next.aci = null;
2062
+ }
2063
+ else {
2064
+ const aciColor = this.resolveAciColor(patch.aci);
2065
+ next.aci = patch.aci;
2066
+ next.rgb = aciColor;
2067
+ }
2068
+ }
2069
+ if (patch.rgb !== undefined) {
2070
+ if (patch.rgb === null) {
2071
+ next.rgb = null;
2072
+ }
2073
+ else {
2074
+ next.rgb = this.normalizeColorNumber(patch.rgb);
2075
+ if (patch.aci === undefined)
2076
+ next.aci = null;
2077
+ }
2078
+ }
2079
+ return next;
2080
+ }
2081
+ cloneDocumentStyle(style) {
2082
+ return {
2083
+ underline: style.underline,
2084
+ overline: style.overline,
2085
+ strikeThrough: style.strikeThrough,
2086
+ script: style.script,
2087
+ aci: style.aci,
2088
+ rgb: style.rgb ? [...style.rgb] : null,
2089
+ align: style.align,
2090
+ fontFace: { ...style.fontFace },
2091
+ capHeight: { ...style.capHeight },
2092
+ widthFactor: { ...style.widthFactor },
2093
+ charTrackingFactor: { ...style.charTrackingFactor },
2094
+ oblique: style.oblique,
2095
+ paragraph: {
2096
+ indent: style.paragraph.indent,
2097
+ left: style.paragraph.left,
2098
+ right: style.paragraph.right,
2099
+ align: style.paragraph.align,
2100
+ tabs: [...style.paragraph.tabs]
2101
+ }
2102
+ };
2103
+ }
2104
+ toDocumentStyle(format) {
2105
+ const explicitAci = this.isExplicitAci(format.aci) ? format.aci : null;
2106
+ const rgbColor = explicitAci !== null
2107
+ ? null
2108
+ : this.colorNumberToRgbArray(format.rgb !== null ? format.rgb : this.resolveBaseColor());
2109
+ const isScript = format.script !== 'normal';
2110
+ const capHeight = Math.max(1, format.fontSize * (isScript ? 0.7 : 1));
2111
+ const align = format.script === 'superscript'
2112
+ ? MTextLineAlignment.TOP
2113
+ : format.script === 'subscript'
2114
+ ? MTextLineAlignment.BOTTOM
2115
+ : MTextLineAlignment.MIDDLE;
2116
+ return {
2117
+ underline: format.underline,
2118
+ overline: format.overline,
2119
+ strikeThrough: format.strike,
2120
+ script: format.script,
2121
+ aci: explicitAci,
2122
+ rgb: rgbColor,
2123
+ align,
2124
+ fontFace: {
2125
+ family: format.fontFamily,
2126
+ style: format.italic ? 'Italic' : 'Regular',
2127
+ weight: format.bold ? 700 : 400
2128
+ },
2129
+ capHeight: { value: capHeight, isRelative: false },
2130
+ widthFactor: { value: 1, isRelative: false },
2131
+ charTrackingFactor: { value: 1, isRelative: false },
2132
+ oblique: 0,
2133
+ paragraph: {
2134
+ indent: 0,
2135
+ left: 0,
2136
+ right: 0,
2137
+ align: 0,
2138
+ tabs: []
2139
+ }
2140
+ };
2141
+ }
2142
+ colorNumberToRgbArray(color) {
2143
+ const c = this.normalizeColorNumber(color);
2144
+ return [(c >> 16) & 0xff, (c >> 8) & 0xff, c & 0xff];
2145
+ }
2146
+ rgbArrayToColorNumber(rgb) {
2147
+ const r = Math.max(0, Math.min(255, Math.round(rgb[0])));
2148
+ const g = Math.max(0, Math.min(255, Math.round(rgb[1])));
2149
+ const b = Math.max(0, Math.min(255, Math.round(rgb[2])));
2150
+ return (r << 16) | (g << 8) | b;
2151
+ }
2152
+ }
2153
+ export { MTextInputBox as MTextEditor, defaultCharFormat, sameFormat };