@mlightcad/mtext-input-box 0.2.9 → 0.2.11

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.
@@ -1,5 +1,5 @@
1
1
  import type { Box, CursorStyle, SelectionStyle } from '@mlightcad/text-box-cursor';
2
- import type { ColorSettings, MTextColor, MTextParagraphAlignment, TextStyle } from '@mlightcad/mtext-renderer';
2
+ import type { ColorSettings, MTextAttachmentPoint, MTextColor, MTextParagraphAlignment, TextStyle } from '@mlightcad/mtext-renderer';
3
3
  import type * as THREE from 'three';
4
4
  /** Vertical script style for a character run. */
5
5
  export type CharScript = 'normal' | 'superscript' | 'subscript';
@@ -176,6 +176,10 @@ export interface MTextInputBoxOptions {
176
176
  width: number;
177
177
  /** Optional world-space origin of the editor container. */
178
178
  position?: THREE.Vector3;
179
+ /**
180
+ * Initial MTEXT attachment (DXF group 71). Defaults to top-left when omitted.
181
+ */
182
+ initialAttachmentPoint?: MTextAttachmentPoint;
179
183
  /**
180
184
  * Default text style passed to `@mlightcad/mtext-renderer`.
181
185
  *
@@ -1,5 +1,5 @@
1
1
  import { type DebugVisibility } from '@mlightcad/text-box-cursor';
2
- import { type TextStyle } from '@mlightcad/mtext-renderer';
2
+ import { MTextAttachmentPoint, type TextStyle } from '@mlightcad/mtext-renderer';
3
3
  import * as THREE from 'three';
4
4
  import { defaultCharFormat, sameFormat } from './format';
5
5
  import type { CharFormat, CursorLayoutData, CursorDirection, EditorState, MTextInputBoxEvent, MTextInputBoxOptions, MTextToolbarTheme, SelectionDirection } from './types';
@@ -157,6 +157,8 @@ export declare class MTextInputBox {
157
157
  setAttachmentPoint(attachmentPoint: string): void;
158
158
  /** Returns the current attachment as a two-letter ribbon / DXF-style code. */
159
159
  getAttachmentPointCode(): string;
160
+ /** Returns the current attachment as an {@link MTextAttachmentPoint} value (DXF 71). */
161
+ getMTextAttachmentPoint(): MTextAttachmentPoint;
160
162
  /** Toggles selected alphabetic text between upper and lower case. */
161
163
  toggleCase(): void;
162
164
  /** Returns renderer default text style defined by `textStyle`. */
@@ -221,6 +223,13 @@ export declare class MTextInputBox {
221
223
  private ensureFontsLoaded;
222
224
  private collectFontNamesForText;
223
225
  private updateCursorData;
226
+ /**
227
+ * Extends {@link layoutContainer} vertically so empty logical rows (no glyphs)
228
+ * remain inside the chrome bounds. Intentionally ignores non-empty rows: their
229
+ * `LineInfo` may still use inflated renderer line strips, while
230
+ * {@link computeEditorVerticalBounds} already tightened using glyph boxes.
231
+ */
232
+ private unionLayoutContainerWithCursorLines;
224
233
  /**
225
234
  * Editor vertical bounds for the selection box / bounding overlay.
226
235
  * Renderer `layout.lines` strips are often taller than actual glyphs (leading
@@ -236,7 +245,20 @@ export declare class MTextInputBox {
236
245
  private updateBoundingBoxGeometry;
237
246
  private disposeBoundingBox;
238
247
  private replaceRenderedObject;
248
+ /**
249
+ * Removes any previous MTEXT scene roots tagged for this input box. Defensive
250
+ * cleanup when a prior root was not fully detached before the next relayout.
251
+ */
252
+ private removeStrayInputBoxSceneRootsExcept;
239
253
  private forceVisibleMaterialState;
254
+ private disposeDetachedThreeSubtree;
255
+ /**
256
+ * Keeps a single layout root on the MTEXT object. {@link MText.syncDraw} only calls
257
+ * `add()` for the new layout; multiple draws on the same instance would otherwise
258
+ * stack several full copies of the text (e.g. after attachment-point changes).
259
+ */
260
+ private pruneExtraMTextLayoutRoots;
261
+ private disposeMTextRootResources;
240
262
  private disposeRenderedObject;
241
263
  private isExplicitAci;
242
264
  private normalizeColorNumber;
@@ -303,6 +325,11 @@ export declare class MTextInputBox {
303
325
  private toScriptFromStyle;
304
326
  private createDefaultParseContext;
305
327
  private createNormalizedDocument;
328
+ /**
329
+ * World-space point on the layout bounds that matches the given MTEXT
330
+ * attachment (DXF 71), using the same box convention as {@link updateBoundingBoxGeometry}.
331
+ */
332
+ private computeAttachmentAnchorOnBounds;
306
333
  private mapRibbonParagraphAlignment;
307
334
  private mapRibbonAttachmentCode;
308
335
  private attachmentPointToRibbonCode;
@@ -5,6 +5,27 @@ import { DEFAULT_FONT_FAMILY, defaultCharFormat, sameFormat } from './format';
5
5
  import { hasNodeStyle, MTextDocument } from '../model';
6
6
  import { EditorUiAdapter } from '../controller';
7
7
  import { MTextToolbar } from '../ui/toolbar';
8
+ /**
9
+ * Local X of the MTEXT column's left edge relative to the insertion point (DXF 71),
10
+ * matching {@link MText.calculateAnchorPoint} / `mtext-renderer` frame semantics.
11
+ * Uses numeric codes so unit tests can partially mock `@mlightcad/mtext-renderer`.
12
+ */
13
+ function attachmentColumnMinLocal(width, attachment) {
14
+ const w = Math.max(1, width);
15
+ const a = attachment;
16
+ // Left column: 1 TL, 4 ML, 7 BL, 10 baseline-left
17
+ if (a === undefined || a === 1 || a === 4 || a === 7 || a === 10)
18
+ return 0;
19
+ // Center column: 2 TC, 5 MC, 8 BC, 11 baseline-center
20
+ if (a === 2 || a === 5 || a === 8 || a === 11)
21
+ return -w / 2;
22
+ // Right column: 3 TR, 6 MR, 9 BR, 12 baseline-right
23
+ if (a === 3 || a === 6 || a === 9 || a === 12)
24
+ return -w;
25
+ return 0;
26
+ }
27
+ /** Marks MTEXT roots added by {@link MTextInputBox} so stray scene objects can be scavenged. */
28
+ const MTEXT_INPUT_BOX_SCENE_ROOT_KEY = '__mlightcadMTextInputBoxSceneRoot';
8
29
  /**
9
30
  * Three.js based MText editor component with core text editing interaction.
10
31
  */
@@ -245,6 +266,9 @@ export class MTextInputBox {
245
266
  this.colorSettings = options.colorSettings;
246
267
  this.width = Math.max(1, options.width);
247
268
  this.position = options.position?.clone() ?? new THREE.Vector3(0, 0, 0);
269
+ if (options.initialAttachmentPoint !== undefined) {
270
+ this.editorAttachmentPoint = options.initialAttachmentPoint;
271
+ }
248
272
  this.enableWordWrap = options.enableWordWrap ?? true;
249
273
  const textStyle = options.textStyle ?? MTextInputBox.DEFAULT_TEXT_STYLE;
250
274
  const fixedTextHeight = Math.max(1, Number.isFinite(textStyle.fixedTextHeight)
@@ -644,6 +668,38 @@ export class MTextInputBox {
644
668
  const next = this.mapRibbonAttachmentCode(attachmentPoint);
645
669
  if (next === undefined || next === this.editorAttachmentPoint)
646
670
  return;
671
+ // Keep the on-screen text frame fixed: DXF insertion point is the selected
672
+ // attachment location on the bounding box, so changing attachment must move
673
+ // `position` by the delta between the old and new anchor on the same box.
674
+ //
675
+ // Do not gate this on `rendererReady`: while fonts load, `relayout()` still
676
+ // fills `layoutContainer` from the fallback layout. Skipping the move here
677
+ // left `position` at the top-left anchor even after the user chose middle
678
+ // center, so committed MTEXT used the wrong insertion vs attachment (DXF 71).
679
+ if (Number.isFinite(this.layoutContainer.width) &&
680
+ Number.isFinite(this.layoutContainer.height)) {
681
+ const left = this.position.x + this.layoutContainer.x;
682
+ const right = left + this.layoutContainer.width;
683
+ const bottom = this.position.y + this.layoutContainer.y;
684
+ const top = bottom + this.layoutContainer.height;
685
+ if (Number.isFinite(left) &&
686
+ Number.isFinite(right) &&
687
+ Number.isFinite(bottom) &&
688
+ Number.isFinite(top) &&
689
+ right >= left - 1e-9 &&
690
+ top >= bottom - 1e-9) {
691
+ const oldAnchor = this.computeAttachmentAnchorOnBounds(left, right, bottom, top, this.editorAttachmentPoint);
692
+ const newAnchor = this.computeAttachmentAnchorOnBounds(left, right, bottom, top, next);
693
+ this.position.x += newAnchor.x - oldAnchor.x;
694
+ this.position.y += newAnchor.y - oldAnchor.y;
695
+ this.cursorRenderer.setViewTransform({
696
+ x: this.position.x,
697
+ y: this.position.y,
698
+ scaleX: 1,
699
+ scaleY: 1
700
+ });
701
+ }
702
+ }
647
703
  this.editorAttachmentPoint = next;
648
704
  this.relayout();
649
705
  this.emit('change');
@@ -652,6 +708,10 @@ export class MTextInputBox {
652
708
  getAttachmentPointCode() {
653
709
  return this.attachmentPointToRibbonCode(this.editorAttachmentPoint);
654
710
  }
711
+ /** Returns the current attachment as an {@link MTextAttachmentPoint} value (DXF 71). */
712
+ getMTextAttachmentPoint() {
713
+ return this.editorAttachmentPoint;
714
+ }
655
715
  /** Toggles selected alphabetic text between upper and lower case. */
656
716
  toggleCase() {
657
717
  const selection = this.getSelectionRange();
@@ -1210,6 +1270,10 @@ export class MTextInputBox {
1210
1270
  const style = this.createTextStyle();
1211
1271
  const colorSettings = this.resolveRenderColorSettings();
1212
1272
  const object = this.mtextRenderer.syncRenderMText(mtextData, style, colorSettings);
1273
+ // `MText.syncDraw()` appends a fresh layout group without clearing prior children.
1274
+ // If the renderer ever reuses one root for multiple draws, prune stale roots so
1275
+ // attachment / justify changes cannot leave duplicate glyph trees in the scene.
1276
+ this.pruneExtraMTextLayoutRoots(object);
1213
1277
  this.replaceRenderedObject(object);
1214
1278
  const rendered = this.extractBoxesFromRenderedObject(object);
1215
1279
  this.mtextInsertionOffset.set(0, 0, 0);
@@ -1298,6 +1362,57 @@ export class MTextInputBox {
1298
1362
  this.cursorLogic.clearSelection();
1299
1363
  }
1300
1364
  this.syncStateFromCursor();
1365
+ // Renderer-driven vertical bounds can omit a trailing empty row when a single
1366
+ // inflated line strip overlaps all glyphs (we then keep only glyph extents).
1367
+ // Cursor geometry for empty rows still carries those rows (break fallbacks), so
1368
+ // union only empty lines — non-empty rows are already covered by glyph bounds,
1369
+ // and their LineInfo can still reflect oversized strips (reintroducing leading).
1370
+ const expanded = this.unionLayoutContainerWithCursorLines(this.layoutContainer);
1371
+ if (Math.abs(expanded.y - this.layoutContainer.y) > 1e-6 ||
1372
+ Math.abs(expanded.height - this.layoutContainer.height) > 1e-6) {
1373
+ this.layoutContainer = expanded;
1374
+ this.latestCursorLayoutData.containerBox = { ...this.layoutContainer };
1375
+ this.cursorLogic.updateData(this.layoutContainer, charBoxes, lineBreakIndices, lineLayouts);
1376
+ this.cursorLogic.moveTo(nextIndex, pendingLineHint);
1377
+ if (this.selectionStart !== this.selectionEnd) {
1378
+ this.cursorLogic.setSelection(this.selectionStart, this.selectionEnd);
1379
+ }
1380
+ else {
1381
+ this.cursorLogic.clearSelection();
1382
+ }
1383
+ this.syncStateFromCursor();
1384
+ }
1385
+ }
1386
+ /**
1387
+ * Extends {@link layoutContainer} vertically so empty logical rows (no glyphs)
1388
+ * remain inside the chrome bounds. Intentionally ignores non-empty rows: their
1389
+ * `LineInfo` may still use inflated renderer line strips, while
1390
+ * {@link computeEditorVerticalBounds} already tightened using glyph boxes.
1391
+ */
1392
+ unionLayoutContainerWithCursorLines(container) {
1393
+ const lines = this.cursorLogic.getLines();
1394
+ if (lines.length === 0)
1395
+ return container;
1396
+ let low = container.y;
1397
+ let high = container.y + container.height;
1398
+ for (const line of lines) {
1399
+ if (line.charCount !== 0)
1400
+ continue;
1401
+ const lineLo = line.y - line.height / 2;
1402
+ const lineHi = line.y + line.height / 2;
1403
+ if (Number.isFinite(lineLo))
1404
+ low = Math.min(low, lineLo);
1405
+ if (Number.isFinite(lineHi))
1406
+ high = Math.max(high, lineHi);
1407
+ }
1408
+ if (!Number.isFinite(low) || !Number.isFinite(high) || high < low) {
1409
+ return container;
1410
+ }
1411
+ return {
1412
+ ...container,
1413
+ y: low,
1414
+ height: high - low
1415
+ };
1301
1416
  }
1302
1417
  /**
1303
1418
  * Editor vertical bounds for the selection box / bounding overlay.
@@ -1405,13 +1520,11 @@ export class MTextInputBox {
1405
1520
  const local = this.toLocalBox(object.box);
1406
1521
  const { minY: containerTop, maxY: containerBottom } = this.computeEditorVerticalBounds(lineLayouts, charBoxes, local);
1407
1522
  const containerBox = {
1408
- x: local.x,
1523
+ x: attachmentColumnMinLocal(this.width, this.editorAttachmentPoint),
1409
1524
  y: containerTop,
1410
- width: local.width,
1525
+ width: Math.max(1, this.width),
1411
1526
  height: Math.max(0, containerBottom - containerTop)
1412
1527
  };
1413
- containerBox.x = 0;
1414
- containerBox.width = this.width;
1415
1528
  const minHeight = this.getFallbackLineAdvance();
1416
1529
  if (containerBox.height < minHeight) {
1417
1530
  const delta = minHeight - containerBox.height;
@@ -1486,7 +1599,7 @@ export class MTextInputBox {
1486
1599
  }
1487
1600
  return {
1488
1601
  containerBox: {
1489
- x: 0,
1602
+ x: attachmentColumnMinLocal(this.width, this.editorAttachmentPoint),
1490
1603
  y: minY,
1491
1604
  width: this.width,
1492
1605
  height: Math.max(1, -minY)
@@ -1547,10 +1660,30 @@ export class MTextInputBox {
1547
1660
  }
1548
1661
  replaceRenderedObject(object) {
1549
1662
  this.disposeRenderedObject(this.renderedObject);
1663
+ this.removeStrayInputBoxSceneRootsExcept(object);
1550
1664
  this.forceVisibleMaterialState(object);
1665
+ object.userData[MTEXT_INPUT_BOX_SCENE_ROOT_KEY] = this;
1551
1666
  this.renderedObject = object;
1552
1667
  this.scene.add(object);
1553
1668
  }
1669
+ /**
1670
+ * Removes any previous MTEXT scene roots tagged for this input box. Defensive
1671
+ * cleanup when a prior root was not fully detached before the next relayout.
1672
+ */
1673
+ removeStrayInputBoxSceneRootsExcept(keep) {
1674
+ const keepObj = keep;
1675
+ for (let i = this.scene.children.length - 1; i >= 0; i--) {
1676
+ const ch = this.scene.children[i];
1677
+ if (!ch || ch === keepObj)
1678
+ continue;
1679
+ const owner = ch.userData[MTEXT_INPUT_BOX_SCENE_ROOT_KEY];
1680
+ if (owner === this) {
1681
+ this.scene.remove(ch);
1682
+ this.disposeMTextRootResources(ch);
1683
+ delete ch.userData[MTEXT_INPUT_BOX_SCENE_ROOT_KEY];
1684
+ }
1685
+ }
1686
+ }
1554
1687
  forceVisibleMaterialState(object) {
1555
1688
  object.traverse((child) => {
1556
1689
  const meshLike = child;
@@ -1574,16 +1707,8 @@ export class MTextInputBox {
1574
1707
  }
1575
1708
  });
1576
1709
  }
1577
- disposeRenderedObject(object) {
1578
- if (!object)
1579
- return;
1580
- object.removeFromParent();
1581
- const withDispose = object;
1582
- if (typeof withDispose.dispose === 'function') {
1583
- withDispose.dispose();
1584
- return;
1585
- }
1586
- object.traverse((child) => {
1710
+ disposeDetachedThreeSubtree(root) {
1711
+ root.traverse((child) => {
1587
1712
  const mesh = child;
1588
1713
  if (mesh.geometry) {
1589
1714
  mesh.geometry.dispose();
@@ -1597,6 +1722,35 @@ export class MTextInputBox {
1597
1722
  }
1598
1723
  });
1599
1724
  }
1725
+ /**
1726
+ * Keeps a single layout root on the MTEXT object. {@link MText.syncDraw} only calls
1727
+ * `add()` for the new layout; multiple draws on the same instance would otherwise
1728
+ * stack several full copies of the text (e.g. after attachment-point changes).
1729
+ */
1730
+ pruneExtraMTextLayoutRoots(object) {
1731
+ while (object.children.length > 1) {
1732
+ const stale = object.children[0];
1733
+ if (!stale)
1734
+ break;
1735
+ object.remove(stale);
1736
+ this.disposeDetachedThreeSubtree(stale);
1737
+ }
1738
+ }
1739
+ disposeMTextRootResources(object) {
1740
+ const withDispose = object;
1741
+ if (typeof withDispose.dispose === 'function') {
1742
+ withDispose.dispose();
1743
+ return;
1744
+ }
1745
+ this.disposeDetachedThreeSubtree(object);
1746
+ }
1747
+ disposeRenderedObject(object) {
1748
+ if (!object)
1749
+ return;
1750
+ object.removeFromParent();
1751
+ delete object.userData[MTEXT_INPUT_BOX_SCENE_ROOT_KEY];
1752
+ this.disposeMTextRootResources(object);
1753
+ }
1600
1754
  isExplicitAci(aci) {
1601
1755
  return aci !== null && Number.isInteger(aci) && aci > 0 && aci < 256;
1602
1756
  }
@@ -2473,6 +2627,40 @@ export class MTextInputBox {
2473
2627
  }
2474
2628
  return new MTextDocument(normalizedAst);
2475
2629
  }
2630
+ /**
2631
+ * World-space point on the layout bounds that matches the given MTEXT
2632
+ * attachment (DXF 71), using the same box convention as {@link updateBoundingBoxGeometry}.
2633
+ */
2634
+ computeAttachmentAnchorOnBounds(left, right, bottom, top, point) {
2635
+ const midX = (left + right) * 0.5;
2636
+ const midY = (bottom + top) * 0.5;
2637
+ const z = this.position.z;
2638
+ switch (point) {
2639
+ case MTextAttachmentPoint.TopLeft:
2640
+ return new THREE.Vector3(left, top, z);
2641
+ case MTextAttachmentPoint.TopCenter:
2642
+ return new THREE.Vector3(midX, top, z);
2643
+ case MTextAttachmentPoint.TopRight:
2644
+ return new THREE.Vector3(right, top, z);
2645
+ case MTextAttachmentPoint.MiddleLeft:
2646
+ return new THREE.Vector3(left, midY, z);
2647
+ case MTextAttachmentPoint.MiddleCenter:
2648
+ return new THREE.Vector3(midX, midY, z);
2649
+ case MTextAttachmentPoint.MiddleRight:
2650
+ return new THREE.Vector3(right, midY, z);
2651
+ case MTextAttachmentPoint.BottomLeft:
2652
+ case MTextAttachmentPoint.BaselineLeft:
2653
+ return new THREE.Vector3(left, bottom, z);
2654
+ case MTextAttachmentPoint.BottomCenter:
2655
+ case MTextAttachmentPoint.BaselineCenter:
2656
+ return new THREE.Vector3(midX, bottom, z);
2657
+ case MTextAttachmentPoint.BottomRight:
2658
+ case MTextAttachmentPoint.BaselineRight:
2659
+ return new THREE.Vector3(right, bottom, z);
2660
+ default:
2661
+ return new THREE.Vector3(left, top, z);
2662
+ }
2663
+ }
2476
2664
  mapRibbonParagraphAlignment(alignment) {
2477
2665
  switch (alignment) {
2478
2666
  case 'default':
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mlightcad/mtext-input-box",
3
- "version": "0.2.9",
3
+ "version": "0.2.11",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",