@mlightcad/mtext-input-box 0.1.3 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -42,16 +42,17 @@ const editor = new MTextInputBox({
42
42
  position: new THREE.Vector3(80, 520, 0),
43
43
  initialText: 'Hello\\PWorld',
44
44
  imeTarget: canvas,
45
- defaultFormat: {
46
- fontFamily: 'monospace',
47
- fontSize: 24,
48
- bold: false,
49
- italic: false,
50
- underline: false,
51
- overline: false,
52
- strike: false,
53
- aci: null,
54
- rgb: 0xffffff
45
+ textStyle: {
46
+ name: 'MTextInputBoxStyle',
47
+ standardFlag: 0,
48
+ fixedTextHeight: 24,
49
+ widthFactor: 1,
50
+ obliqueAngle: 0,
51
+ textGenerationFlag: 0,
52
+ lastHeight: 24,
53
+ font: 'simkai',
54
+ bigFont: '',
55
+ color: 0xffffff
55
56
  },
56
57
  toolbar: {
57
58
  enabled: true,
@@ -89,8 +90,8 @@ Custom color picker factory context:
89
90
 
90
91
  - `container: HTMLElement`: mount point for your UI.
91
92
  - `theme: 'light' | 'dark'`: current toolbar theme.
92
- - `initialColor: '#RRGGBB'`: initial color.
93
- - `onChange(hexColor)`: call this when user picks a new color.
93
+ - `initialColor: MTextColor`: initial color (ACI or RGB). It reflects the active editor format at toolbar creation time.
94
+ - `onChange(color: MTextColor)`: call this when user picks a new color (ACI or RGB).
94
95
 
95
96
  Custom color picker instance methods:
96
97
 
@@ -102,29 +103,27 @@ Example (mount a Vue color picker):
102
103
 
103
104
  ```ts
104
105
  import { createApp, h, ref } from 'vue';
105
- import { getColorByIndex } from '@mlightcad/mtext-renderer';
106
- import { MTextColor } from '@mlightcad/mtext-parser';
106
+ import { getColorByIndex, MTextColor } from '@mlightcad/mtext-renderer';
107
107
 
108
108
  toolbar: {
109
109
  colorPicker: ({ container, initialColor, theme, onChange }) => {
110
- const color = ref(initialColor);
111
- const toHex = (value: MTextColor) => {
112
- if (value.isRgb && value.rgbValue !== null) {
113
- return `#${value.rgbValue.toString(16).padStart(6, '0')}`;
114
- }
110
+ const toCssColor = (value: MTextColor) => {
115
111
  if (value.isAci && value.aci !== null) {
116
112
  return `#${getColorByIndex(value.aci).toString(16).padStart(6, '0')}`;
117
113
  }
118
- return '#ffffff';
114
+ return value.toCssColor() ?? '#ffffff';
119
115
  };
116
+ const color = ref(toCssColor(initialColor));
120
117
  const app = createApp({
121
118
  render() {
122
119
  return h(MyVueColorPicker, {
123
120
  modelValue: color.value,
124
121
  theme,
125
122
  'onUpdate:modelValue': (next: string) => {
123
+ const nextColor = MTextColor.fromCssColor(next);
124
+ if (!nextColor) return;
126
125
  color.value = next;
127
- onChange(next);
126
+ onChange(nextColor);
128
127
  }
129
128
  });
130
129
  }
@@ -134,7 +133,7 @@ toolbar: {
134
133
 
135
134
  return {
136
135
  setValue(next: MTextColor) {
137
- color.value = toHex(next);
136
+ color.value = toCssColor(next);
138
137
  },
139
138
  setTheme(nextTheme: 'light' | 'dark') {
140
139
  // Optional: forward theme into your picker state if needed.
@@ -163,12 +162,13 @@ Public toolbar-related methods:
163
162
 
164
163
  ## Important Options
165
164
 
166
- - `defaultFormat`: base insert format and renderer fallback style source.
165
+ - `textStyle`: default text style passed to the renderer and used to derive base insert format.
167
166
  - `imeTarget`: element used by built-in IME bridge and built-in pointer interactions.
168
167
  - `enableWordWrap?: boolean`: enable/disable editor-side wrapping behavior.
169
168
  - `showBoundingBox?: boolean`: show editor boundary rectangle.
170
169
  - `boundingBoxStyle?: { color?, opacity?, padding?, zOffset? }`: boundary style overrides.
171
170
  - `workerUrl?: string | URL`: worker URL for renderer initialization.
171
+ - `fontUrl?: string`: optional base URL for font loading (overrides renderer default).
172
172
  - `cursorStyle` / `selectionStyle`: forwarded to cursor renderer.
173
173
  - `toolbar`: built-in toolbar options (`enabled`, `theme`, `fontFamilies`, `colorPicker`, `container`, `offsetY`).
174
174
 
@@ -1,4 +1,4 @@
1
- import { MTextContext, type MTextParserOptions } from '@mlightcad/mtext-parser';
1
+ import { MTextContext, type MTextParserOptions } from '@mlightcad/mtext-renderer';
2
2
  import type { MTextAst, MTextStyle } from './types';
3
3
  /** Parse mtext into a character-level AST suitable for insert/delete/replace workflows. */
4
4
  export declare function parseMTextToAst(content: string, ctx?: MTextContext, options?: Omit<MTextParserOptions, 'yieldPropertyCommands'>): MTextAst;
package/dist/model/ast.js CHANGED
@@ -1,4 +1,4 @@
1
- import { MTextContext, MTextParser, TokenType } from '@mlightcad/mtext-parser';
1
+ import { MTextContext, MTextParser, TokenType } from '@mlightcad/mtext-renderer';
2
2
  import { cloneStyle, contextToStyle, hasNodeStyle, serializeStyleDelta } from './style';
3
3
  /** Parse mtext into a character-level AST suitable for insert/delete/replace workflows. */
4
4
  export function parseMTextToAst(content, ctx, options = {}) {
@@ -1,4 +1,4 @@
1
- import { MTextContext } from '@mlightcad/mtext-parser';
1
+ import { MTextContext } from '@mlightcad/mtext-renderer';
2
2
  import type { EditorSelection, MTextAst, MTextStyle } from './types';
3
3
  /** Minimal mtext editor document wrapper on top of AST. */
4
4
  export declare class MTextDocument {
@@ -1,4 +1,4 @@
1
- import { MTextContext } from '@mlightcad/mtext-parser';
1
+ import { MTextContext } from '@mlightcad/mtext-renderer';
2
2
  import { buildMTextFromAst, deleteRangeInAst, inferInsertStyle, parseMTextToAst, replaceRangeInAst } from './ast';
3
3
  import { cloneStyle, contextToStyle } from './style';
4
4
  /** Minimal mtext editor document wrapper on top of AST. */
@@ -1,4 +1,4 @@
1
- import { MTextContext } from '@mlightcad/mtext-parser';
1
+ import { MTextContext } from '@mlightcad/mtext-renderer';
2
2
  import type { MTextAstCharNode, MTextAstColumnBreakNode, MTextAstNode, MTextAstParagraphBreakNode, MTextAstStackNode, MTextAstWrapAtDimLineNode, MTextStyle } from './types';
3
3
  export declare function contextToStyle(ctx: MTextContext): MTextStyle;
4
4
  export declare function cloneStyle(style: MTextStyle): MTextStyle;
@@ -1,4 +1,4 @@
1
- import { MTextContext, MTextLineAlignment, MTextParagraphAlignment, rgb2int } from '@mlightcad/mtext-parser';
1
+ import { MTextContext, MTextLineAlignment, MTextParagraphAlignment, rgb2int } from '@mlightcad/mtext-renderer';
2
2
  function scriptFromAlign(align) {
3
3
  if (align === MTextLineAlignment.TOP)
4
4
  return 'superscript';
@@ -1,4 +1,4 @@
1
- import type { FactorValue, FontFace, MTextLineAlignment, ParagraphProperties, RGB } from '@mlightcad/mtext-parser';
1
+ import type { FactorValue, FontFace, MTextLineAlignment, ParagraphProperties, RGB } from '@mlightcad/mtext-renderer';
2
2
  export type MTextScript = 'normal' | 'superscript' | 'subscript';
3
3
  /** Snapshot of resolved text style for editable AST nodes. */
4
4
  export interface MTextStyle {
@@ -5,12 +5,13 @@ export interface ToolbarOptions {
5
5
  theme: MTextToolbarTheme;
6
6
  fontFamilies?: string[];
7
7
  colorPicker?: MTextToolbarColorPickerFactory;
8
+ initialFormat?: CharFormat;
8
9
  onFormatChange: (partial: Partial<CharFormat>) => void;
9
10
  onToggleStack: () => void;
10
11
  onToggleSuperscript?: () => boolean;
11
12
  onToggleSubscript?: () => boolean;
12
13
  }
13
- export type ToolbarSessionOptions = Omit<ToolbarOptions, 'container' | 'theme' | 'fontFamilies' | 'colorPicker'>;
14
+ export type ToolbarSessionOptions = Omit<ToolbarOptions, 'container' | 'theme' | 'fontFamilies' | 'colorPicker' | 'initialFormat'>;
14
15
  export declare class MTextToolbar {
15
16
  private anchorElement;
16
17
  private readonly root;
@@ -1,5 +1,5 @@
1
1
  import { getColorByIndex } from '@mlightcad/mtext-renderer';
2
- import { MTextColor } from '@mlightcad/mtext-parser';
2
+ import { MTextColor } from '@mlightcad/mtext-renderer';
3
3
  import { toolbarIcons } from './icons';
4
4
  const STYLE_ID = 'mlightcad-mtext-toolbar-style';
5
5
  const DEFAULT_FONT_FAMILIES = [
@@ -100,6 +100,9 @@ function ensureToolbarStyles() {
100
100
  .ml-mtext-toolbar__color {
101
101
  width: 40px;
102
102
  padding: 2px;
103
+ display: flex;
104
+ align-items: center;
105
+ justify-content: center;
103
106
  }
104
107
  .ml-mtext-toolbar__btn {
105
108
  width: 34px;
@@ -158,6 +161,11 @@ function mtextColorToHex(color) {
158
161
  }
159
162
  return '#ffffff';
160
163
  }
164
+ function hexToMTextColor(hex) {
165
+ const color = new MTextColor();
166
+ color.rgbValue = hexToColorNumber(hex);
167
+ return color;
168
+ }
161
169
  function formatToMTextColor(format) {
162
170
  const color = new MTextColor();
163
171
  if (format.aci !== null && Number.isFinite(format.aci)) {
@@ -238,7 +246,7 @@ export class MTextToolbar {
238
246
  fontSize.min = '1';
239
247
  fontSize.max = '1024';
240
248
  fontSize.step = '1';
241
- this.colorPicker = this.createColorPicker(options.colorPicker);
249
+ this.colorPicker = this.createColorPicker(options.colorPicker, options.initialFormat);
242
250
  typographyGroup.append(fontFamily, fontSize, this.colorPicker.host);
243
251
  const separator1 = document.createElement('div');
244
252
  separator1.className = 'ml-mtext-toolbar__separator';
@@ -394,14 +402,14 @@ export class MTextToolbar {
394
402
  this.anchorElement.focus({ preventScroll: true });
395
403
  });
396
404
  }
397
- createColorPicker(factory) {
405
+ createColorPicker(factory, initialFormat) {
398
406
  if (!factory) {
399
407
  const input = document.createElement('input');
400
408
  input.className = 'ml-mtext-toolbar__color';
401
409
  input.type = 'color';
402
410
  input.dataset.mlMtextToolbarInteractive = 'true';
403
411
  input.addEventListener('input', () => {
404
- this.applyColorChange(input.value);
412
+ this.applyColorChange(hexToMTextColor(input.value));
405
413
  });
406
414
  return {
407
415
  host: input,
@@ -417,12 +425,13 @@ export class MTextToolbar {
417
425
  const host = document.createElement('div');
418
426
  host.className = 'ml-mtext-toolbar__color';
419
427
  host.dataset.mlMtextToolbarInteractive = 'true';
428
+ const initialColor = initialFormat ? formatToMTextColor(initialFormat) : hexToMTextColor('#ffffff');
420
429
  const instance = factory({
421
430
  container: host,
422
431
  theme: this.theme,
423
- initialColor: '#ffffff',
424
- onChange: (hex) => {
425
- this.applyColorChange(hex);
432
+ initialColor,
433
+ onChange: (color) => {
434
+ this.applyColorChange(color);
426
435
  }
427
436
  });
428
437
  const typed = (instance ?? {});
@@ -439,13 +448,23 @@ export class MTextToolbar {
439
448
  }
440
449
  };
441
450
  }
442
- applyColorChange(hex) {
443
- const normalized = normalizeHexColor(hex);
444
- if (!normalized)
451
+ applyColorChange(color) {
452
+ if (color.isAci && color.aci !== null) {
453
+ this.onFormatChange({
454
+ aci: color.aci
455
+ });
445
456
  return;
457
+ }
458
+ if (color.isRgb && color.rgbValue !== null) {
459
+ this.onFormatChange({
460
+ aci: null,
461
+ rgb: normalizeColorNumber(color.rgbValue)
462
+ });
463
+ return;
464
+ }
446
465
  this.onFormatChange({
447
466
  aci: null,
448
- rgb: hexToColorNumber(normalized)
467
+ rgb: 0xffffff
449
468
  });
450
469
  }
451
470
  }
@@ -1,4 +1,5 @@
1
1
  import type { CharFormat } from './types';
2
+ export declare const DEFAULT_FONT_FAMILY = "simkai";
2
3
  /** Returns default character format. */
3
4
  export declare function defaultCharFormat(): CharFormat;
4
5
  /** Compares two formats. */
@@ -1,7 +1,8 @@
1
+ export const DEFAULT_FONT_FAMILY = 'simkai';
1
2
  /** Returns default character format. */
2
3
  export function defaultCharFormat() {
3
4
  return {
4
- fontFamily: 'monospace',
5
+ fontFamily: DEFAULT_FONT_FAMILY,
5
6
  fontSize: 24,
6
7
  bold: false,
7
8
  italic: false,
@@ -1,5 +1,5 @@
1
1
  import type { Box, CursorStyle, SelectionStyle } from '@mlightcad/text-box-cursor';
2
- import type { MTextColor } from '@mlightcad/mtext-parser';
2
+ import type { ColorSettings, MTextColor, 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';
@@ -118,10 +118,10 @@ export interface MTextToolbarColorPickerContext {
118
118
  container: HTMLElement;
119
119
  /** Current toolbar theme. */
120
120
  theme: MTextToolbarTheme;
121
- /** Initial color as hex string (`#RRGGBB`). */
122
- initialColor: string;
123
- /** Call when user picks a new color. */
124
- onChange: (hexColor: string) => void;
121
+ /** Initial color (may be ACI or RGB). */
122
+ initialColor: MTextColor;
123
+ /** Call when user picks a new color (ACI or RGB). */
124
+ onChange: (color: MTextColor) => void;
125
125
  }
126
126
  /** Lifecycle hooks for a custom toolbar color picker. */
127
127
  export interface MTextToolbarColorPickerInstance {
@@ -161,13 +161,13 @@ export interface MTextInputBoxOptions {
161
161
  /** Optional world-space origin of the editor container. */
162
162
  position?: THREE.Vector3;
163
163
  /**
164
- * Single default style source for the component.
164
+ * Default text style passed to `@mlightcad/mtext-renderer`.
165
165
  *
166
166
  * It is used for:
167
- * - insertion format of newly typed characters
168
- * - derived fallback text style passed to `@mlightcad/mtext-renderer`
167
+ * - fallback text style passed to the renderer
168
+ * - base insertion format derived from the style
169
169
  */
170
- defaultFormat?: Partial<CharFormat>;
170
+ textStyle?: TextStyle;
171
171
  /** Partial cursor style overrides forwarded to cursor renderer. */
172
172
  cursorStyle?: Partial<CursorStyle>;
173
173
  /** Partial selection style overrides forwarded to cursor renderer. */
@@ -176,6 +176,8 @@ export interface MTextInputBoxOptions {
176
176
  enableWordWrap?: boolean;
177
177
  /** Optional worker URL used by renderer implementations that support workers. */
178
178
  workerUrl?: string | URL;
179
+ /** Optional base URL for font loading (overrides renderer default). */
180
+ fontUrl?: string;
179
181
  /** Element used for built-in IME bridge attachment. */
180
182
  imeTarget: HTMLElement;
181
183
  /** Whether to render a visible editor bounding box overlay. */
@@ -184,6 +186,8 @@ export interface MTextInputBoxOptions {
184
186
  boundingBoxStyle?: MTextBoundingBoxStyle;
185
187
  /** Built-in toolbar configuration (DOM overlay). */
186
188
  toolbar?: MTextToolbarOptions;
189
+ /** Optional ACI color settings for byLayer (256) and byBlock (0). */
190
+ colorSettings?: ColorSettings;
187
191
  }
188
192
  /** Directional cursor movement commands. */
189
193
  export type CursorDirection = 'left' | 'right' | 'up' | 'down' | 'lineStart' | 'lineEnd' | 'wordPrev' | 'wordNext';
@@ -18,6 +18,7 @@ export declare class MTextInputBox {
18
18
  private readonly mtextRenderer;
19
19
  private readonly cursorRenderer;
20
20
  private static readonly FALLBACK_LINE_ADVANCE_RATIO;
21
+ private static readonly DEFAULT_TEXT_STYLE;
21
22
  private width;
22
23
  private position;
23
24
  private enableWordWrap;
@@ -38,9 +39,12 @@ export declare class MTextInputBox {
38
39
  private boundingBoxPadding;
39
40
  private boundingBoxZOffset;
40
41
  private rendererReady;
42
+ private pendingFontLoad;
43
+ private lastFontKey;
41
44
  private toolbarTheme;
42
45
  private toolbarOffsetY;
43
46
  private debugMode;
47
+ private readonly colorSettings;
44
48
  private debugVisibility;
45
49
  private readonly maxHistorySize;
46
50
  private undoStack;
@@ -126,7 +130,7 @@ export declare class MTextInputBox {
126
130
  setCurrentFormat(format: Partial<CharFormat>): void;
127
131
  /** Returns current insertion format. */
128
132
  getCurrentFormat(): CharFormat;
129
- /** Returns renderer default text style derived from `defaultFormat`. */
133
+ /** Returns renderer default text style defined by `textStyle`. */
130
134
  getDefaultTextStyle(): TextStyle;
131
135
  /** Keyboard event handler. Returns true when consumed. */
132
136
  handleKeyDown(event: KeyboardEvent): boolean;
@@ -183,6 +187,8 @@ export declare class MTextInputBox {
183
187
  private isPointInContainer;
184
188
  private initializeRenderer;
185
189
  private relayout;
190
+ private ensureFontsLoaded;
191
+ private collectFontNamesForText;
186
192
  private updateCursorData;
187
193
  private extractBoxesFromRenderedObject;
188
194
  private normalizeRenderedTopAlignment;
@@ -199,10 +205,11 @@ export declare class MTextInputBox {
199
205
  private resolveAciColor;
200
206
  private resolveBaseColor;
201
207
  private resolveFormatColorNumber;
202
- private createDefaultTextStyle;
208
+ private createBaseFormatFromTextStyle;
203
209
  private createMTextData;
204
210
  private getFallbackLineAdvance;
205
211
  private createTextStyle;
212
+ private resolveRenderColorSettings;
206
213
  private focusImeInput;
207
214
  private refocusImeInputSoon;
208
215
  private updateImeAnchorPosition;
@@ -1,8 +1,8 @@
1
1
  import { CursorRenderer, TextBoxCursor, ThreeJsRendererAdapter } from '@mlightcad/text-box-cursor';
2
- import { getColorByIndex, UnifiedRenderer, MTextAttachmentPoint, MTextFlowDirection } from '@mlightcad/mtext-renderer';
2
+ import { getColorByIndex, UnifiedRenderer, MTextAttachmentPoint, MTextFlowDirection, MText } from '@mlightcad/mtext-renderer';
3
3
  import * as THREE from 'three';
4
- import { MTextContext, MTextLineAlignment } from '@mlightcad/mtext-parser';
5
- import { defaultCharFormat, sameFormat } from './format';
4
+ import { MTextContext, MTextLineAlignment } from '@mlightcad/mtext-renderer';
5
+ import { DEFAULT_FONT_FAMILY, defaultCharFormat, sameFormat } from './format';
6
6
  import { MTextDocument } from '../model';
7
7
  import { EditorUiAdapter } from '../controller';
8
8
  import { MTextToolbar } from '../ui/toolbar';
@@ -21,6 +21,18 @@ export class MTextInputBox {
21
21
  mtextRenderer;
22
22
  cursorRenderer;
23
23
  static FALLBACK_LINE_ADVANCE_RATIO = 1.5;
24
+ static DEFAULT_TEXT_STYLE = {
25
+ name: 'MTextInputBoxStyle',
26
+ standardFlag: 0,
27
+ fixedTextHeight: 24,
28
+ widthFactor: 1,
29
+ obliqueAngle: 0,
30
+ textGenerationFlag: 0,
31
+ lastHeight: 24,
32
+ font: DEFAULT_FONT_FAMILY,
33
+ bigFont: '',
34
+ color: 0xffffff
35
+ };
24
36
  width;
25
37
  position;
26
38
  enableWordWrap;
@@ -44,9 +56,12 @@ export class MTextInputBox {
44
56
  boundingBoxPadding = 1;
45
57
  boundingBoxZOffset = 0.01;
46
58
  rendererReady = false;
59
+ pendingFontLoad = null;
60
+ lastFontKey = '';
47
61
  toolbarTheme = 'dark';
48
62
  toolbarOffsetY = 10;
49
63
  debugMode = false;
64
+ colorSettings;
50
65
  debugVisibility = {
51
66
  showCharBoxes: true,
52
67
  showLineIndices: true,
@@ -216,12 +231,32 @@ export class MTextInputBox {
216
231
  this.toolbarContainer = options.toolbar?.container ?? null;
217
232
  this.toolbarFontFamilies = options.toolbar?.fontFamilies ?? null;
218
233
  this.toolbarColorPicker = options.toolbar?.colorPicker;
234
+ this.colorSettings = options.colorSettings;
219
235
  this.width = Math.max(1, options.width);
220
236
  this.position = options.position?.clone() ?? new THREE.Vector3(0, 0, 0);
221
237
  this.enableWordWrap = options.enableWordWrap ?? true;
222
- this.baseFormat = { ...defaultCharFormat(), ...(options.defaultFormat ?? {}) };
238
+ const textStyle = options.textStyle ?? MTextInputBox.DEFAULT_TEXT_STYLE;
239
+ const fixedTextHeight = Math.max(1, Number.isFinite(textStyle.fixedTextHeight)
240
+ ? textStyle.fixedTextHeight
241
+ : MTextInputBox.DEFAULT_TEXT_STYLE.fixedTextHeight);
242
+ const lastHeight = Math.max(1, Number.isFinite(textStyle.lastHeight) ? textStyle.lastHeight : fixedTextHeight);
243
+ const color = Number.isFinite(textStyle.color)
244
+ ? textStyle.color
245
+ : MTextInputBox.DEFAULT_TEXT_STYLE.color;
246
+ this.defaultTextStyle = {
247
+ ...textStyle,
248
+ fixedTextHeight,
249
+ lastHeight,
250
+ widthFactor: Number.isFinite(textStyle.widthFactor) ? textStyle.widthFactor : 1,
251
+ obliqueAngle: Number.isFinite(textStyle.obliqueAngle) ? textStyle.obliqueAngle : 0,
252
+ textGenerationFlag: Number.isFinite(textStyle.textGenerationFlag) ? textStyle.textGenerationFlag : 0,
253
+ standardFlag: Number.isFinite(textStyle.standardFlag) ? textStyle.standardFlag : 0,
254
+ font: textStyle.font || MTextInputBox.DEFAULT_TEXT_STYLE.font,
255
+ bigFont: textStyle.bigFont ?? '',
256
+ color: this.normalizeColorNumber(color)
257
+ };
258
+ this.baseFormat = this.createBaseFormatFromTextStyle(this.defaultTextStyle);
223
259
  this.currentFormat = { ...this.baseFormat };
224
- this.defaultTextStyle = this.createDefaultTextStyle();
225
260
  this.document = new MTextDocument();
226
261
  this.uiAdapter = new EditorUiAdapter(this.document);
227
262
  this.mtextRenderer = new UnifiedRenderer('main', {
@@ -229,6 +264,9 @@ export class MTextInputBox {
229
264
  ? options.workerUrl
230
265
  : options.workerUrl?.toString() ?? './assets/mtext-renderer-worker.js'
231
266
  });
267
+ if (options.fontUrl) {
268
+ this.mtextRenderer.setFontUrl(options.fontUrl);
269
+ }
232
270
  this.cursorLogic = new TextBoxCursor({
233
271
  containerBox: { x: 0, y: 0, width: this.width, height: 1 },
234
272
  charBoxes: [],
@@ -526,7 +564,7 @@ export class MTextInputBox {
526
564
  getCurrentFormat() {
527
565
  return { ...this.currentFormat };
528
566
  }
529
- /** Returns renderer default text style derived from `defaultFormat`. */
567
+ /** Returns renderer default text style defined by `textStyle`. */
530
568
  getDefaultTextStyle() {
531
569
  return { ...this.defaultTextStyle };
532
570
  }
@@ -881,7 +919,8 @@ export class MTextInputBox {
881
919
  const toolbarOptions = {
882
920
  ...this.createToolbarSessionOptions(target),
883
921
  container,
884
- theme: this.toolbarTheme
922
+ theme: this.toolbarTheme,
923
+ initialFormat: this.currentFormat
885
924
  };
886
925
  if (this.toolbarFontFamilies) {
887
926
  toolbarOptions.fontFamilies = this.toolbarFontFamilies;
@@ -1013,8 +1052,9 @@ export class MTextInputBox {
1013
1052
  }
1014
1053
  async initializeRenderer() {
1015
1054
  try {
1016
- await this.mtextRenderer.loadFonts(['simkai']);
1055
+ await this.mtextRenderer.loadFonts([DEFAULT_FONT_FAMILY]);
1017
1056
  this.rendererReady = true;
1057
+ this.ensureFontsLoaded();
1018
1058
  this.relayout();
1019
1059
  }
1020
1060
  catch (error) {
@@ -1029,13 +1069,12 @@ export class MTextInputBox {
1029
1069
  this.updateBoundingBoxGeometry();
1030
1070
  return;
1031
1071
  }
1072
+ this.ensureFontsLoaded();
1032
1073
  try {
1033
1074
  const mtextData = this.createMTextData();
1034
1075
  const style = this.createTextStyle();
1035
- const object = this.mtextRenderer.syncRenderMText(mtextData, style, {
1036
- byLayerColor: 0xffffff,
1037
- byBlockColor: 0xffffff
1038
- });
1076
+ const colorSettings = this.resolveRenderColorSettings();
1077
+ const object = this.mtextRenderer.syncRenderMText(mtextData, style, colorSettings);
1039
1078
  this.replaceRenderedObject(object);
1040
1079
  const rendered = this.extractBoxesFromRenderedObject(object);
1041
1080
  this.normalizeRenderedTopAlignment(object, rendered);
@@ -1051,6 +1090,52 @@ export class MTextInputBox {
1051
1090
  this.updateBoundingBoxGeometry();
1052
1091
  }
1053
1092
  }
1093
+ ensureFontsLoaded() {
1094
+ if (this.pendingFontLoad)
1095
+ return;
1096
+ const fonts = this.collectFontNamesForText();
1097
+ const key = fonts.map((font) => font.toLowerCase()).sort().join('|');
1098
+ if (!key || key === this.lastFontKey)
1099
+ return;
1100
+ this.lastFontKey = key;
1101
+ this.pendingFontLoad = this.mtextRenderer
1102
+ .loadFonts(fonts)
1103
+ .then(() => undefined)
1104
+ .catch((error) => {
1105
+ console.warn('[mtext-input-box] Failed to load fonts for MTEXT', error);
1106
+ })
1107
+ .finally(() => {
1108
+ this.pendingFontLoad = null;
1109
+ if (this.rendererReady)
1110
+ this.relayout();
1111
+ });
1112
+ }
1113
+ collectFontNamesForText() {
1114
+ const fonts = new Set();
1115
+ const addFont = (name) => {
1116
+ if (!name)
1117
+ return;
1118
+ const trimmed = name.trim();
1119
+ if (!trimmed)
1120
+ return;
1121
+ fonts.add(trimmed);
1122
+ };
1123
+ addFont(this.defaultTextStyle.font);
1124
+ addFont(this.defaultTextStyle.bigFont);
1125
+ try {
1126
+ const fromContent = MText.getFonts(this.mtextString || '', true);
1127
+ for (const fontName of fromContent) {
1128
+ addFont(fontName);
1129
+ }
1130
+ }
1131
+ catch (error) {
1132
+ console.warn('[mtext-input-box] Failed to parse fonts from MTEXT', error);
1133
+ }
1134
+ if (fonts.size === 0) {
1135
+ fonts.add(DEFAULT_FONT_FAMILY);
1136
+ }
1137
+ return [...fonts];
1138
+ }
1054
1139
  updateCursorData(charBoxes, lineBreakIndices, lineLayouts) {
1055
1140
  this.latestCursorLayoutData = {
1056
1141
  containerBox: { ...this.layoutContainer },
@@ -1319,20 +1404,13 @@ export class MTextInputBox {
1319
1404
  ? this.normalizeColorNumber(format.rgb)
1320
1405
  : 0xffffff;
1321
1406
  }
1322
- createDefaultTextStyle() {
1323
- const baseSize = Math.max(1, this.baseFormat.fontSize);
1324
- return {
1325
- name: 'MTextInputBoxStyle',
1326
- standardFlag: 0,
1327
- fixedTextHeight: baseSize,
1328
- widthFactor: 1,
1329
- obliqueAngle: 0,
1330
- textGenerationFlag: 0,
1331
- lastHeight: baseSize,
1332
- font: this.baseFormat.fontFamily || 'simkai',
1333
- bigFont: '',
1334
- color: this.resolveFormatColorNumber(this.baseFormat)
1335
- };
1407
+ createBaseFormatFromTextStyle(style) {
1408
+ const base = defaultCharFormat();
1409
+ base.fontFamily = style.font || base.fontFamily;
1410
+ base.fontSize = Math.max(1, style.fixedTextHeight);
1411
+ base.rgb = this.normalizeColorNumber(style.color);
1412
+ base.aci = null;
1413
+ return base;
1336
1414
  }
1337
1415
  createMTextData() {
1338
1416
  return {
@@ -1356,6 +1434,13 @@ export class MTextInputBox {
1356
1434
  createTextStyle() {
1357
1435
  return { ...this.defaultTextStyle };
1358
1436
  }
1437
+ resolveRenderColorSettings() {
1438
+ if (this.colorSettings) {
1439
+ return this.colorSettings;
1440
+ }
1441
+ const base = this.toolbarTheme === 'light' ? 0x000000 : 0xffffff;
1442
+ return { byLayerColor: base, byBlockColor: base };
1443
+ }
1359
1444
  focusImeInput() {
1360
1445
  if (!this.imeInput)
1361
1446
  return;
@@ -2042,10 +2127,10 @@ export class MTextInputBox {
2042
2127
  context.fontFace.family = this.defaultTextStyle.font || this.baseFormat.fontFamily;
2043
2128
  context.fontFace.style = this.baseFormat.italic ? 'Italic' : 'Regular';
2044
2129
  context.fontFace.weight = this.baseFormat.bold ? 700 : 400;
2045
- // Relative cap height keeps parser defaults aligned with editor base text height.
2046
- context.capHeight = { value: 1, isRelative: true };
2047
- context.align = MTextLineAlignment.MIDDLE;
2048
- context.widthFactor = { value: this.defaultTextStyle.widthFactor ?? 1, isRelative: true };
2130
+ // Align parser defaults with renderer: absolute cap height based on text style.
2131
+ context.capHeight = { value: this.defaultTextStyle.fixedTextHeight, isRelative: false };
2132
+ context.align = MTextLineAlignment.BOTTOM;
2133
+ context.widthFactor = { value: this.defaultTextStyle.widthFactor ?? 1, isRelative: false };
2049
2134
  if (this.isExplicitAci(this.baseFormat.aci)) {
2050
2135
  context.aci = this.baseFormat.aci;
2051
2136
  context.rgb = null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mlightcad/mtext-input-box",
3
- "version": "0.1.3",
3
+ "version": "0.2.0",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -17,8 +17,7 @@
17
17
  "@mlightcad/text-box-cursor": "0.1.1"
18
18
  },
19
19
  "peerDependencies": {
20
- "@mlightcad/mtext-parser": "^1.3.3",
21
- "@mlightcad/mtext-renderer": "^0.10.2",
20
+ "@mlightcad/mtext-renderer": "^0.10.4",
22
21
  "three": "^0.172.0"
23
22
  },
24
23
  "devDependencies": {