@mlightcad/mtext-input-box 0.3.4 → 0.3.6

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,6 +1,6 @@
1
1
  import type { Box, CursorStyle, SelectionStyle } from '@mlightcad/text-box-cursor';
2
2
  import type { MTextColor, MTextParagraphAlignment } from '@mlightcad/mtext-parser';
3
- import type { ColorSettings, MTextAttachmentPoint, TextStyle } from '@mlightcad/mtext-renderer';
3
+ import type { ColorSettings, MTextAttachmentPoint, MTextFlowDirection, TextStyle } from '@mlightcad/mtext-renderer';
4
4
  import type * as THREE from 'three';
5
5
  /** Vertical script style for a character run. */
6
6
  export type CharScript = 'normal' | 'superscript' | 'subscript';
@@ -173,14 +173,36 @@ export interface MTextInputBoxOptions {
173
173
  camera: THREE.Camera;
174
174
  /** Optional initial MTEXT source string. */
175
175
  initialText?: string;
176
- /** Preferred editor width. */
176
+ /**
177
+ * Preferred editor wrap width in world units (DXF group 41).
178
+ * Values `<= 0` mean no defined wrap column (same as AutoCAD / mtext-renderer).
179
+ */
177
180
  width: number;
178
181
  /** Optional world-space origin of the editor container. */
179
182
  position?: THREE.Vector3;
180
183
  /**
181
184
  * Initial MTEXT attachment (DXF group 71). Defaults to top-left when omitted.
185
+ * The editor {@link position} is the DXF insertion point for this attachment
186
+ * (not always the top-left corner of the text box).
182
187
  */
183
188
  initialAttachmentPoint?: MTextAttachmentPoint;
189
+ /**
190
+ * MTEXT drawing / flow direction (DXF group 72). Defaults to left-to-right.
191
+ */
192
+ initialDrawingDirection?: MTextFlowDirection;
193
+ /** Optional rotation in radians (DXF group 50). */
194
+ rotation?: number;
195
+ /** Optional text direction vector; takes precedence over {@link rotation} when set. */
196
+ directionVector?: {
197
+ x: number;
198
+ y: number;
199
+ z?: number;
200
+ };
201
+ /**
202
+ * Initial MTEXT line spacing factor (DXF group 44) forwarded to the renderer.
203
+ * When omitted, the renderer default is used (same as drawing display).
204
+ */
205
+ initialLineSpaceFactor?: number;
184
206
  /**
185
207
  * Default text style passed to `@mlightcad/mtext-renderer`.
186
208
  *
@@ -20,6 +20,13 @@ export declare class MTextInputBox {
20
20
  private readonly cursorRenderer;
21
21
  private static readonly FALLBACK_LINE_ADVANCE_RATIO;
22
22
  private static readonly DEFAULT_TEXT_STYLE;
23
+ /**
24
+ * Declared MTEXT column width from the host (DXF group 41). Values `<= 0`
25
+ * mean no wrap column; layout then follows {@link resolveMTextWrapWidth} /
26
+ * rendered content bounds so the editor chrome matches the drawing.
27
+ */
28
+ private declaredWidth;
29
+ /** Effective wrap / chrome width used for hit-testing and the bounding box. */
23
30
  private width;
24
31
  private position;
25
32
  private mtextInsertionOffset;
@@ -33,9 +40,16 @@ export declare class MTextInputBox {
33
40
  /**
34
41
  * MTEXT attachment (DXF group 71) for the editor box relative to
35
42
  * {@link position}. Drives {@link createMTextData} and contextual ribbon
36
- * "Justify" / attachment controls.
43
+ * "Justify" / attachment controls. {@link position} is the DXF insertion
44
+ * point for this attachment (not always the box top-left).
37
45
  */
38
46
  private editorAttachmentPoint;
47
+ /** MTEXT flow direction (DXF group 72). */
48
+ private editorDrawingDirection;
49
+ /** Optional rotation in radians forwarded to the renderer. */
50
+ private editorRotation;
51
+ /** Optional direction vector forwarded to the renderer when set. */
52
+ private editorDirectionVector;
39
53
  private static readonly DEFAULT_LINE_SPACE_FACTOR;
40
54
  private cursorIndex;
41
55
  private selectionStart;
@@ -238,9 +252,19 @@ export declare class MTextInputBox {
238
252
  */
239
253
  private computeEditorVerticalBounds;
240
254
  private extractBoxesFromRenderedObject;
255
+ /**
256
+ * @deprecated No longer shifts rendered content to top-left. Attachment is
257
+ * handled by `@mlightcad/mtext-renderer` relative to the insertion point.
258
+ * Kept for tests that still call the method on the prototype.
259
+ */
241
260
  private normalizeRenderedTopAlignment;
242
261
  private toLocalBox;
243
262
  private createFallbackCharBoxes;
263
+ /**
264
+ * Translation that pins the attachment edge/center of a local axis-aligned
265
+ * box `[minY, maxY]` onto local y = 0 (the insertion point).
266
+ */
267
+ private attachmentVerticalOffsetForLocalBox;
244
268
  private createBoundingBox;
245
269
  private updateBoundingBoxGeometry;
246
270
  private disposeBoundingBox;
@@ -266,6 +290,13 @@ export declare class MTextInputBox {
266
290
  private resolveBaseColor;
267
291
  private resolveBaseFormatColor;
268
292
  private createBaseFormatFromTextStyle;
293
+ /**
294
+ * Resolves the wrap/chrome width the editor should use so layout matches
295
+ * `@mlightcad/mtext-renderer` (including tiny/corrupt DXF group-41 values).
296
+ * When the declared width is `<= 0`, returns a content-based estimate for the
297
+ * bounding box only; {@link createMTextData} still passes `0` to the renderer.
298
+ */
299
+ private resolveEditorChromeWidth;
269
300
  private createMTextData;
270
301
  /**
271
302
  * Line spacing factor used for layout and returned when the host commits the editor.
@@ -1,5 +1,5 @@
1
1
  import { CursorRenderer, TextBoxCursor, ThreeJsRendererAdapter } from '@mlightcad/text-box-cursor';
2
- import { getColorByIndex, LINE_SPACING_SCALE_FACTOR, MText, MTextAttachmentPoint, MTextFlowDirection, UnifiedRenderer } from '@mlightcad/mtext-renderer';
2
+ import { estimateMTextWrapWidth, getColorByIndex, LINE_SPACING_SCALE_FACTOR, MText, MTextAttachmentPoint, MTextFlowDirection, resolveMTextWrapWidth, UnifiedRenderer } from '@mlightcad/mtext-renderer';
3
3
  import { MTextColor, MTextContext, MTextLineAlignment, MTextParagraphAlignment } from '@mlightcad/mtext-parser';
4
4
  import * as THREE from 'three';
5
5
  import { DEFAULT_FONT_FAMILY, defaultCharFormat, sameFormat } from './format';
@@ -12,7 +12,7 @@ import { MTextToolbar } from '../ui/toolbar';
12
12
  * Uses numeric codes so unit tests can partially mock `@mlightcad/mtext-renderer`.
13
13
  */
14
14
  function attachmentColumnMinLocal(width, attachment) {
15
- const w = Math.max(1, width);
15
+ const w = Math.max(Number.EPSILON, width);
16
16
  const a = attachment;
17
17
  // Left column: 1 TL, 4 ML, 7 BL, 10 baseline-left
18
18
  if (a === undefined || a === 1 || a === 4 || a === 7 || a === 10)
@@ -53,6 +53,13 @@ export class MTextInputBox {
53
53
  font: DEFAULT_FONT_FAMILY,
54
54
  bigFont: ''
55
55
  };
56
+ /**
57
+ * Declared MTEXT column width from the host (DXF group 41). Values `<= 0`
58
+ * mean no wrap column; layout then follows {@link resolveMTextWrapWidth} /
59
+ * rendered content bounds so the editor chrome matches the drawing.
60
+ */
61
+ declaredWidth;
62
+ /** Effective wrap / chrome width used for hit-testing and the bounding box. */
56
63
  width;
57
64
  position;
58
65
  mtextInsertionOffset = new THREE.Vector3(0, 0, 0);
@@ -66,9 +73,16 @@ export class MTextInputBox {
66
73
  /**
67
74
  * MTEXT attachment (DXF group 71) for the editor box relative to
68
75
  * {@link position}. Drives {@link createMTextData} and contextual ribbon
69
- * "Justify" / attachment controls.
76
+ * "Justify" / attachment controls. {@link position} is the DXF insertion
77
+ * point for this attachment (not always the box top-left).
70
78
  */
71
79
  editorAttachmentPoint = MTextAttachmentPoint.TopLeft;
80
+ /** MTEXT flow direction (DXF group 72). */
81
+ editorDrawingDirection = MTextFlowDirection.LEFT_TO_RIGHT;
82
+ /** Optional rotation in radians forwarded to the renderer. */
83
+ editorRotation = 0;
84
+ /** Optional direction vector forwarded to the renderer when set. */
85
+ editorDirectionVector = null;
72
86
  static DEFAULT_LINE_SPACE_FACTOR = 0.3;
73
87
  cursorIndex = 0;
74
88
  selectionStart = 0;
@@ -265,17 +279,38 @@ export class MTextInputBox {
265
279
  this.toolbarFontFamilies = options.toolbar?.fontFamilies ?? null;
266
280
  this.toolbarColorPicker = options.toolbar?.colorPicker;
267
281
  this.colorSettings = options.colorSettings;
268
- this.width = Math.max(1, options.width);
269
282
  this.position = options.position?.clone() ?? new THREE.Vector3(0, 0, 0);
270
283
  if (options.initialAttachmentPoint !== undefined) {
271
284
  this.editorAttachmentPoint = options.initialAttachmentPoint;
272
285
  }
286
+ if (options.initialDrawingDirection !== undefined) {
287
+ this.editorDrawingDirection = options.initialDrawingDirection;
288
+ }
289
+ if (typeof options.rotation === 'number' && Number.isFinite(options.rotation)) {
290
+ this.editorRotation = options.rotation;
291
+ }
292
+ if (options.directionVector &&
293
+ Number.isFinite(options.directionVector.x) &&
294
+ Number.isFinite(options.directionVector.y)) {
295
+ this.editorDirectionVector = {
296
+ x: options.directionVector.x,
297
+ y: options.directionVector.y,
298
+ z: Number.isFinite(options.directionVector.z) ? options.directionVector.z : 0
299
+ };
300
+ }
301
+ if (typeof options.initialLineSpaceFactor === 'number' &&
302
+ Number.isFinite(options.initialLineSpaceFactor) &&
303
+ options.initialLineSpaceFactor > 0) {
304
+ this.editorLineSpaceFactor = options.initialLineSpaceFactor;
305
+ }
273
306
  this.enableWordWrap = options.enableWordWrap ?? true;
274
307
  const textStyle = options.textStyle ?? MTextInputBox.DEFAULT_TEXT_STYLE;
275
- const fixedTextHeight = Math.max(1, Number.isFinite(textStyle.fixedTextHeight)
308
+ const fixedTextHeight = Math.max(Number.EPSILON, Number.isFinite(textStyle.fixedTextHeight)
276
309
  ? textStyle.fixedTextHeight
277
310
  : MTextInputBox.DEFAULT_TEXT_STYLE.fixedTextHeight);
278
- const lastHeight = Math.max(1, Number.isFinite(textStyle.lastHeight) ? textStyle.lastHeight : fixedTextHeight);
311
+ this.declaredWidth = Number.isFinite(options.width) ? options.width : 0;
312
+ this.width = this.resolveEditorChromeWidth(options.initialText ?? '', fixedTextHeight);
313
+ const lastHeight = Math.max(Number.EPSILON, Number.isFinite(textStyle.lastHeight) ? textStyle.lastHeight : fixedTextHeight);
279
314
  this.defaultTextStyle = {
280
315
  ...textStyle,
281
316
  fixedTextHeight,
@@ -330,9 +365,12 @@ export class MTextInputBox {
330
365
  scaleY: 1
331
366
  });
332
367
  this.createBoundingBox(options.showBoundingBox ?? true, options.boundingBoxStyle);
333
- this.setText(options.initialText ?? '');
368
+ // Hide chrome until the first font-correct layout; otherwise a fallback
369
+ // wrap box flashes at the insertion point (often looking like BL attachment).
370
+ if (this.boundingBoxObject)
371
+ this.boundingBoxObject.visible = false;
334
372
  this.attachIme(options.imeTarget);
335
- void this.initializeRenderer();
373
+ void this.initializeRenderer(options.initialText ?? '');
336
374
  }
337
375
  /** Sets full text and rebuilds model/layout state. */
338
376
  setText(text) {
@@ -1029,8 +1067,10 @@ export class MTextInputBox {
1029
1067
  this.attachImeBridge(target);
1030
1068
  }
1031
1069
  this.cursorRenderer.show();
1032
- if (this.boundingBoxObject)
1033
- this.boundingBoxObject.visible = true;
1070
+ // Keep the box hidden until the first font-correct layout finishes.
1071
+ if (this.boundingBoxObject) {
1072
+ this.boundingBoxObject.visible = this.rendererReady;
1073
+ }
1034
1074
  if (target && this.toolbarEnabled) {
1035
1075
  this.mountToolbar(target);
1036
1076
  }
@@ -1245,15 +1285,41 @@ export class MTextInputBox {
1245
1285
  const bottom = box.y + box.height;
1246
1286
  return x >= box.x && x <= right && y >= box.y && y <= bottom;
1247
1287
  }
1248
- async initializeRenderer() {
1288
+ async initializeRenderer(initialText = '') {
1249
1289
  try {
1250
- await this.mtextRenderer.loadFonts([DEFAULT_FONT_FAMILY]);
1290
+ // Seed string + document so font collection sees style and `\f` content
1291
+ // fonts, but do not layout yet — fallback metrics wrap incorrectly vs
1292
+ // the drawing.
1293
+ this.mtextString = initialText;
1294
+ this.document = this.createNormalizedDocument(initialText);
1295
+ this.document.cursor = 0;
1296
+ this.uiAdapter = new EditorUiAdapter(this.document);
1297
+ this.clearHistory();
1298
+ this.syncUiStateFromDocument();
1299
+ // Load the fonts actually required by the initial content/style before the
1300
+ // first layout. Rendering with only the default family first produces wrong
1301
+ // CJK advances (wrap + attachment drift); a later font reload then "fixes"
1302
+ // the box on the second open once fonts are cached.
1303
+ const fonts = this.collectFontNamesForText(initialText);
1304
+ const toLoad = fonts.length > 0 ? fonts : [DEFAULT_FONT_FAMILY];
1305
+ await this.mtextRenderer.loadFonts(toLoad);
1306
+ this.lastFontKey = toLoad
1307
+ .map((font) => font.toLowerCase())
1308
+ .sort()
1309
+ .join('|');
1251
1310
  this.rendererReady = true;
1252
- this.ensureFontsLoaded();
1253
- this.relayout();
1311
+ this.setText(initialText);
1312
+ if (this.boundingBoxObject && this.isActiveEditor()) {
1313
+ this.boundingBoxObject.visible = true;
1314
+ }
1254
1315
  }
1255
1316
  catch (error) {
1256
1317
  console.error('[mtext-input-box] Failed to initialize mtext renderer fonts', error);
1318
+ this.rendererReady = true;
1319
+ this.setText(initialText);
1320
+ if (this.boundingBoxObject && this.isActiveEditor()) {
1321
+ this.boundingBoxObject.visible = true;
1322
+ }
1257
1323
  }
1258
1324
  }
1259
1325
  relayout() {
@@ -1277,8 +1343,10 @@ export class MTextInputBox {
1277
1343
  this.pruneExtraMTextLayoutRoots(object);
1278
1344
  this.replaceRenderedObject(object);
1279
1345
  const rendered = this.extractBoxesFromRenderedObject(object);
1346
+ // Keep the renderer attachment anchor: `position` is the DXF insertion
1347
+ // point. Do not force top-left by shifting glyphs (that misaligned
1348
+ // bottom/middle/center attachments vs the original entity).
1280
1349
  this.mtextInsertionOffset.set(0, 0, 0);
1281
- this.normalizeRenderedTopAlignment(object, rendered);
1282
1350
  this.layoutContainer = rendered.containerBox;
1283
1351
  this.updateCursorData(rendered.charBoxes, rendered.lineBreakIndices, rendered.lineLayouts);
1284
1352
  this.updateBoundingBoxGeometry();
@@ -1315,7 +1383,7 @@ export class MTextInputBox {
1315
1383
  this.relayout();
1316
1384
  });
1317
1385
  }
1318
- collectFontNamesForText() {
1386
+ collectFontNamesForText(text = this.mtextString) {
1319
1387
  const fonts = new Set();
1320
1388
  const addFont = (name) => {
1321
1389
  if (!name)
@@ -1328,7 +1396,7 @@ export class MTextInputBox {
1328
1396
  addFont(this.defaultTextStyle.font);
1329
1397
  addFont(this.defaultTextStyle.bigFont);
1330
1398
  try {
1331
- const fromContent = MText.getFonts(this.mtextString || '', true);
1399
+ const fromContent = MText.getFonts(text || '', true);
1332
1400
  for (const fontName of fromContent) {
1333
1401
  addFont(fontName);
1334
1402
  }
@@ -1500,7 +1568,7 @@ export class MTextInputBox {
1500
1568
  .filter((line) => Number.isFinite(line.y) && Number.isFinite(line.height))
1501
1569
  .map((line) => ({
1502
1570
  y: line.y - this.position.y,
1503
- height: Math.max(1, line.height)
1571
+ height: Math.max(Number.EPSILON, line.height)
1504
1572
  }));
1505
1573
  for (const entry of layout?.chars ?? []) {
1506
1574
  const localBox = entry.box ? this.toLocalBox(entry.box) : undefined;
@@ -1520,10 +1588,24 @@ export class MTextInputBox {
1520
1588
  .filter((value) => value >= 0 && value <= charBoxes.length);
1521
1589
  const local = this.toLocalBox(object.box);
1522
1590
  const { minY: containerTop, maxY: containerBottom } = this.computeEditorVerticalBounds(lineLayouts, charBoxes, local);
1591
+ // Prefer the rendered glyph span when DXF width is undefined (no wrap), so
1592
+ // the blue editor box matches the on-drawing text instead of a 1-unit stub.
1593
+ const boxWidth = this.declaredWidth > 0
1594
+ ? Math.max(Number.EPSILON, this.resolveEditorChromeWidth(this.mtextString, this.defaultTextStyle.fixedTextHeight))
1595
+ : Math.max(local?.width ?? 0, this.getFallbackLineAdvance() * 0.6, Number.EPSILON);
1596
+ this.width = boxWidth;
1597
+ // For a defined wrap column, pin chrome to the attachment column. For
1598
+ // no-wrap content, follow the actual glyph AABB so a baseline/middle
1599
+ // insertion grip stays aligned with the drawing (not forced to BL/TL).
1600
+ const columnMinX = this.declaredWidth > 0
1601
+ ? attachmentColumnMinLocal(boxWidth, this.editorAttachmentPoint)
1602
+ : Number.isFinite(local?.x)
1603
+ ? local.x
1604
+ : attachmentColumnMinLocal(boxWidth, this.editorAttachmentPoint);
1523
1605
  const containerBox = {
1524
- x: attachmentColumnMinLocal(this.width, this.editorAttachmentPoint),
1606
+ x: columnMinX,
1525
1607
  y: containerTop,
1526
- width: Math.max(1, this.width),
1608
+ width: boxWidth,
1527
1609
  height: Math.max(0, containerBottom - containerTop)
1528
1610
  };
1529
1611
  const minHeight = this.getFallbackLineAdvance();
@@ -1539,21 +1621,14 @@ export class MTextInputBox {
1539
1621
  ...(lineLayouts.length > 0 ? { lineLayouts } : {})
1540
1622
  };
1541
1623
  }
1542
- normalizeRenderedTopAlignment(object, rendered) {
1543
- const topY = rendered.containerBox.y + rendered.containerBox.height;
1544
- const dy = -topY;
1545
- if (!Number.isFinite(dy) || Math.abs(dy) < 1e-8)
1546
- return;
1547
- this.mtextInsertionOffset.set(0, dy, 0);
1548
- object.position.y += dy;
1549
- object.updateMatrixWorld(true);
1550
- rendered.containerBox.y += dy;
1551
- rendered.charBoxes.forEach((box) => {
1552
- box.y += dy;
1553
- });
1554
- rendered.lineLayouts?.forEach((line) => {
1555
- line.y += dy;
1556
- });
1624
+ /**
1625
+ * @deprecated No longer shifts rendered content to top-left. Attachment is
1626
+ * handled by `@mlightcad/mtext-renderer` relative to the insertion point.
1627
+ * Kept for tests that still call the method on the prototype.
1628
+ */
1629
+ normalizeRenderedTopAlignment(..._args) {
1630
+ void _args;
1631
+ this.mtextInsertionOffset.set(0, 0, 0);
1557
1632
  }
1558
1633
  toLocalBox(worldBox) {
1559
1634
  const minX = worldBox.min.x - this.position.x;
@@ -1574,23 +1649,29 @@ export class MTextInputBox {
1574
1649
  const charBoxes = [];
1575
1650
  const lineBreakIndices = [];
1576
1651
  const lineLayouts = [];
1577
- let x = 0;
1652
+ const columnMinX = attachmentColumnMinLocal(this.width, this.editorAttachmentPoint);
1653
+ // Lay out as if top-left were at local y=0, then shift so the attachment
1654
+ // point of the box sits on the insertion origin (matching the renderer).
1655
+ let x = columnMinX;
1578
1656
  let lineTop = 0;
1579
1657
  let minY = -lineHeight;
1580
1658
  lineLayouts.push({ y: lineTop - lineHeight / 2, height: lineHeight });
1581
1659
  for (const char of this.getChars()) {
1582
1660
  if (char === '\n') {
1583
1661
  lineBreakIndices.push(charBoxes.length);
1584
- x = 0;
1662
+ x = columnMinX;
1585
1663
  lineTop -= lineHeight;
1586
1664
  minY = Math.min(minY, lineTop - lineHeight);
1587
1665
  lineLayouts.push({ y: lineTop - lineHeight / 2, height: lineHeight });
1588
1666
  continue;
1589
1667
  }
1590
- const width = Math.max(1, this.currentFormat.fontSize * 0.6);
1591
- if (this.enableWordWrap && x > 0 && x + width > this.width) {
1668
+ const width = Math.max(Number.EPSILON, this.currentFormat.fontSize * 0.6);
1669
+ if (this.enableWordWrap &&
1670
+ this.declaredWidth > 0 &&
1671
+ x > columnMinX &&
1672
+ x + width > columnMinX + this.width) {
1592
1673
  lineBreakIndices.push(charBoxes.length);
1593
- x = 0;
1674
+ x = columnMinX;
1594
1675
  lineTop -= lineHeight;
1595
1676
  minY = Math.min(minY, lineTop - lineHeight);
1596
1677
  lineLayouts.push({ y: lineTop - lineHeight / 2, height: lineHeight });
@@ -1598,18 +1679,42 @@ export class MTextInputBox {
1598
1679
  charBoxes.push({ x, y: lineTop - lineHeight / 2, width, height: lineHeight });
1599
1680
  x += width;
1600
1681
  }
1682
+ const maxY = 0;
1683
+ const boxHeight = Math.max(Number.EPSILON, maxY - minY);
1684
+ const dy = this.attachmentVerticalOffsetForLocalBox(minY, maxY);
1685
+ if (dy !== 0) {
1686
+ minY += dy;
1687
+ for (const box of charBoxes)
1688
+ box.y += dy;
1689
+ for (const line of lineLayouts)
1690
+ line.y += dy;
1691
+ }
1601
1692
  return {
1602
1693
  containerBox: {
1603
- x: attachmentColumnMinLocal(this.width, this.editorAttachmentPoint),
1694
+ x: columnMinX,
1604
1695
  y: minY,
1605
1696
  width: this.width,
1606
- height: Math.max(1, -minY)
1697
+ height: boxHeight
1607
1698
  },
1608
1699
  charBoxes,
1609
1700
  lineBreakIndices,
1610
1701
  lineLayouts
1611
1702
  };
1612
1703
  }
1704
+ /**
1705
+ * Translation that pins the attachment edge/center of a local axis-aligned
1706
+ * box `[minY, maxY]` onto local y = 0 (the insertion point).
1707
+ */
1708
+ attachmentVerticalOffsetForLocalBox(minY, maxY) {
1709
+ const midY = (minY + maxY) / 2;
1710
+ const a = this.editorAttachmentPoint;
1711
+ if (a === undefined || a === 1 || a === 2 || a === 3)
1712
+ return -maxY;
1713
+ if (a === 4 || a === 5 || a === 6)
1714
+ return -midY;
1715
+ // Bottom / baseline rows (7–12)
1716
+ return -minY;
1717
+ }
1613
1718
  createBoundingBox(enabled, style) {
1614
1719
  if (!enabled)
1615
1720
  return;
@@ -1791,7 +1896,7 @@ export class MTextInputBox {
1791
1896
  createBaseFormatFromTextStyle(style, colorSettings) {
1792
1897
  const base = defaultCharFormat();
1793
1898
  base.fontFamily = style.font || base.fontFamily;
1794
- base.fontSize = Math.max(1, style.fixedTextHeight);
1899
+ base.fontSize = Math.max(Number.EPSILON, style.fixedTextHeight);
1795
1900
  const color = this.resolveBaseFormatColor(colorSettings);
1796
1901
  base.aci = color.aci;
1797
1902
  base.rgb = color.rgb;
@@ -1802,21 +1907,60 @@ export class MTextInputBox {
1802
1907
  base.tracking = 1;
1803
1908
  return base;
1804
1909
  }
1910
+ /**
1911
+ * Resolves the wrap/chrome width the editor should use so layout matches
1912
+ * `@mlightcad/mtext-renderer` (including tiny/corrupt DXF group-41 values).
1913
+ * When the declared width is `<= 0`, returns a content-based estimate for the
1914
+ * bounding box only; {@link createMTextData} still passes `0` to the renderer.
1915
+ */
1916
+ resolveEditorChromeWidth(text, height) {
1917
+ const safeHeight = Math.max(Number.EPSILON, height);
1918
+ const resolved = resolveMTextWrapWidth({
1919
+ text,
1920
+ height: safeHeight,
1921
+ width: this.declaredWidth
1922
+ });
1923
+ if (typeof resolved === 'number' && Number.isFinite(resolved) && resolved > 0) {
1924
+ return resolved;
1925
+ }
1926
+ return Math.max(estimateMTextWrapWidth(text, safeHeight), safeHeight * 1.5, Number.EPSILON);
1927
+ }
1805
1928
  createMTextData() {
1929
+ const height = Math.max(Number.EPSILON, this.defaultTextStyle.fixedTextHeight);
1930
+ // Keep DXF "no wrap" (width <= 0) and let the renderer expand absurdly small
1931
+ // positive widths via resolveMTextWrapWidth — same rules as drawing display.
1932
+ const renderWidth = this.declaredWidth <= 0
1933
+ ? 0
1934
+ : resolveMTextWrapWidth({
1935
+ text: this.mtextString,
1936
+ height,
1937
+ width: this.declaredWidth
1938
+ });
1806
1939
  const data = {
1807
1940
  text: this.mtextString,
1808
- height: Math.max(1, this.defaultTextStyle.fixedTextHeight),
1809
- width: this.width,
1941
+ height,
1942
+ width: typeof renderWidth === 'number' && Number.isFinite(renderWidth)
1943
+ ? renderWidth
1944
+ : this.declaredWidth,
1810
1945
  position: {
1811
1946
  x: this.position.x,
1812
1947
  y: this.position.y,
1813
1948
  z: this.position.z
1814
1949
  },
1815
1950
  attachmentPoint: this.editorAttachmentPoint,
1816
- drawingDirection: MTextFlowDirection.LEFT_TO_RIGHT,
1817
- widthFactor: 1,
1951
+ drawingDirection: this.editorDrawingDirection,
1952
+ // Match AcDbMText.subWorldDraw: do not force widthFactor on MTextData.
1953
+ // Renderer uses `mtextData.widthFactor || style.widthFactor`; a hardcoded
1954
+ // `1` here would ignore TEXTSTYLE widthFactor and inflate CJK advances
1955
+ // (false wrap + attachment drift vs the drawing).
1818
1956
  collectCharBoxes: true
1819
1957
  };
1958
+ if (this.editorDirectionVector) {
1959
+ data.directionVector = { ...this.editorDirectionVector };
1960
+ }
1961
+ else if (this.editorRotation !== 0) {
1962
+ data.rotation = this.editorRotation;
1963
+ }
1820
1964
  if (this.editorLineSpaceFactor != null && Number.isFinite(this.editorLineSpaceFactor)) {
1821
1965
  data.lineSpaceFactor = this.editorLineSpaceFactor;
1822
1966
  }
@@ -1851,7 +1995,7 @@ export class MTextInputBox {
1851
1995
  this.emit('change');
1852
1996
  }
1853
1997
  getFallbackLineAdvance() {
1854
- return Math.max(1, this.currentFormat.fontSize * MTextInputBox.FALLBACK_LINE_ADVANCE_RATIO);
1998
+ return Math.max(Number.EPSILON, this.currentFormat.fontSize * MTextInputBox.FALLBACK_LINE_ADVANCE_RATIO);
1855
1999
  }
1856
2000
  createTextStyle() {
1857
2001
  return { ...this.defaultTextStyle };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mlightcad/mtext-input-box",
3
- "version": "0.3.4",
3
+ "version": "0.3.6",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -23,21 +23,21 @@
23
23
  "@mlightcad/text-box-cursor": "0.1.1"
24
24
  },
25
25
  "peerDependencies": {
26
- "@mlightcad/mtext-parser": "^1.5.4",
27
- "@mlightcad/mtext-renderer": "^0.13.3",
28
- "three": "^0.172.0"
26
+ "@mlightcad/mtext-parser": "^1.5.5",
27
+ "@mlightcad/mtext-renderer": "^0.13.6",
28
+ "three": "^0.186.1"
29
29
  },
30
30
  "devDependencies": {
31
31
  "@eslint/js": "^9.34.0",
32
- "@mlightcad/mtext-parser": "^1.5.4",
33
- "@mlightcad/mtext-renderer": "^0.13.3",
32
+ "@mlightcad/mtext-parser": "^1.5.5",
33
+ "@mlightcad/mtext-renderer": "^0.13.6",
34
34
  "@types/node": "^24.4.0",
35
- "@types/three": "^0.172.0",
35
+ "@types/three": "^0.186.0",
36
36
  "@typescript-eslint/eslint-plugin": "^8.41.0",
37
37
  "@typescript-eslint/parser": "^8.41.0",
38
38
  "eslint": "^9.34.0",
39
39
  "eslint-config-prettier": "^10.1.8",
40
- "three": "^0.172.0",
40
+ "three": "^0.186.1",
41
41
  "typescript": "^5.9.2",
42
42
  "typescript-eslint": "^8.41.0",
43
43
  "vitest": "^3.2.4"