@mlightcad/mtext-input-box 0.1.2 → 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,25 +90,40 @@ 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).
95
+
96
+ Custom color picker instance methods:
97
+
98
+ - `setValue(color: MTextColor)`: sync when editor format changes (color may be ACI or RGB).
99
+ - `setTheme(theme)`: optional hook for theme changes.
100
+ - `dispose()`: cleanup any mounted resources.
94
101
 
95
102
  Example (mount a Vue color picker):
96
103
 
97
104
  ```ts
98
105
  import { createApp, h, ref } from 'vue';
106
+ import { getColorByIndex, MTextColor } from '@mlightcad/mtext-renderer';
99
107
 
100
108
  toolbar: {
101
109
  colorPicker: ({ container, initialColor, theme, onChange }) => {
102
- const color = ref(initialColor);
110
+ const toCssColor = (value: MTextColor) => {
111
+ if (value.isAci && value.aci !== null) {
112
+ return `#${getColorByIndex(value.aci).toString(16).padStart(6, '0')}`;
113
+ }
114
+ return value.toCssColor() ?? '#ffffff';
115
+ };
116
+ const color = ref(toCssColor(initialColor));
103
117
  const app = createApp({
104
118
  render() {
105
119
  return h(MyVueColorPicker, {
106
120
  modelValue: color.value,
107
121
  theme,
108
122
  'onUpdate:modelValue': (next: string) => {
123
+ const nextColor = MTextColor.fromCssColor(next);
124
+ if (!nextColor) return;
109
125
  color.value = next;
110
- onChange(next);
126
+ onChange(nextColor);
111
127
  }
112
128
  });
113
129
  }
@@ -116,8 +132,8 @@ toolbar: {
116
132
  app.mount(container);
117
133
 
118
134
  return {
119
- setValue(next: string) {
120
- color.value = next;
135
+ setValue(next: MTextColor) {
136
+ color.value = toCssColor(next);
121
137
  },
122
138
  setTheme(nextTheme: 'light' | 'dark') {
123
139
  // Optional: forward theme into your picker state if needed.
@@ -146,12 +162,13 @@ Public toolbar-related methods:
146
162
 
147
163
  ## Important Options
148
164
 
149
- - `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.
150
166
  - `imeTarget`: element used by built-in IME bridge and built-in pointer interactions.
151
167
  - `enableWordWrap?: boolean`: enable/disable editor-side wrapping behavior.
152
168
  - `showBoundingBox?: boolean`: show editor boundary rectangle.
153
169
  - `boundingBoxStyle?: { color?, opacity?, padding?, zOffset? }`: boundary style overrides.
154
170
  - `workerUrl?: string | URL`: worker URL for renderer initialization.
171
+ - `fontUrl?: string`: optional base URL for font loading (overrides renderer default).
155
172
  - `cursorStyle` / `selectionStyle`: forwarded to cursor renderer.
156
173
  - `toolbar`: built-in toolbar options (`enabled`, `theme`, `fontFamilies`, `colorPicker`, `container`, `offsetY`).
157
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,3 +1,5 @@
1
+ import { getColorByIndex } from '@mlightcad/mtext-renderer';
2
+ import { MTextColor } from '@mlightcad/mtext-renderer';
1
3
  import { toolbarIcons } from './icons';
2
4
  const STYLE_ID = 'mlightcad-mtext-toolbar-style';
3
5
  const DEFAULT_FONT_FAMILIES = [
@@ -98,6 +100,9 @@ function ensureToolbarStyles() {
98
100
  .ml-mtext-toolbar__color {
99
101
  width: 40px;
100
102
  padding: 2px;
103
+ display: flex;
104
+ align-items: center;
105
+ justify-content: center;
101
106
  }
102
107
  .ml-mtext-toolbar__btn {
103
108
  width: 34px;
@@ -147,6 +152,33 @@ function hexToColorNumber(hex) {
147
152
  return 0xffffff;
148
153
  return Number.parseInt(hex.slice(1), 16);
149
154
  }
155
+ function mtextColorToHex(color) {
156
+ if (color.isRgb && color.rgbValue !== null) {
157
+ return colorNumberToHex(color.rgbValue);
158
+ }
159
+ if (color.isAci && color.aci !== null) {
160
+ return colorNumberToHex(getColorByIndex(color.aci));
161
+ }
162
+ return '#ffffff';
163
+ }
164
+ function hexToMTextColor(hex) {
165
+ const color = new MTextColor();
166
+ color.rgbValue = hexToColorNumber(hex);
167
+ return color;
168
+ }
169
+ function formatToMTextColor(format) {
170
+ const color = new MTextColor();
171
+ if (format.aci !== null && Number.isFinite(format.aci)) {
172
+ color.aci = format.aci;
173
+ return color;
174
+ }
175
+ if (format.rgb !== null) {
176
+ color.rgbValue = normalizeColorNumber(format.rgb);
177
+ return color;
178
+ }
179
+ color.rgbValue = 0xffffff;
180
+ return color;
181
+ }
150
182
  function normalizeHexColor(hex) {
151
183
  const normalized = hex.trim().toLowerCase();
152
184
  if (/^#[0-9a-f]{6}$/.test(normalized))
@@ -214,7 +246,7 @@ export class MTextToolbar {
214
246
  fontSize.min = '1';
215
247
  fontSize.max = '1024';
216
248
  fontSize.step = '1';
217
- this.colorPicker = this.createColorPicker(options.colorPicker);
249
+ this.colorPicker = this.createColorPicker(options.colorPicker, options.initialFormat);
218
250
  typographyGroup.append(fontFamily, fontSize, this.colorPicker.host);
219
251
  const separator1 = document.createElement('div');
220
252
  separator1.className = 'ml-mtext-toolbar__separator';
@@ -279,8 +311,8 @@ export class MTextToolbar {
279
311
  setFormat(format) {
280
312
  this.ensureSelectValue(format.fontFamily);
281
313
  this.controls.fontSize.value = String(Math.max(1, Math.round(format.fontSize)));
282
- const color = format.rgb !== null ? format.rgb : 0xffffff;
283
- this.colorPicker.setValue(colorNumberToHex(color));
314
+ const color = formatToMTextColor(format);
315
+ this.colorPicker.setValue(color);
284
316
  this.setToggleState(this.controls.boldBtn, format.bold);
285
317
  this.setToggleState(this.controls.italicBtn, format.italic);
286
318
  this.setToggleState(this.controls.underlineBtn, format.underline);
@@ -370,19 +402,19 @@ export class MTextToolbar {
370
402
  this.anchorElement.focus({ preventScroll: true });
371
403
  });
372
404
  }
373
- createColorPicker(factory) {
405
+ createColorPicker(factory, initialFormat) {
374
406
  if (!factory) {
375
407
  const input = document.createElement('input');
376
408
  input.className = 'ml-mtext-toolbar__color';
377
409
  input.type = 'color';
378
410
  input.dataset.mlMtextToolbarInteractive = 'true';
379
411
  input.addEventListener('input', () => {
380
- this.applyColorChange(input.value);
412
+ this.applyColorChange(hexToMTextColor(input.value));
381
413
  });
382
414
  return {
383
415
  host: input,
384
- setValue: (hex) => {
385
- const normalized = normalizeHexColor(hex);
416
+ setValue: (color) => {
417
+ const normalized = normalizeHexColor(mtextColorToHex(color));
386
418
  if (normalized)
387
419
  input.value = normalized;
388
420
  },
@@ -393,22 +425,20 @@ export class MTextToolbar {
393
425
  const host = document.createElement('div');
394
426
  host.className = 'ml-mtext-toolbar__color';
395
427
  host.dataset.mlMtextToolbarInteractive = 'true';
428
+ const initialColor = initialFormat ? formatToMTextColor(initialFormat) : hexToMTextColor('#ffffff');
396
429
  const instance = factory({
397
430
  container: host,
398
431
  theme: this.theme,
399
- initialColor: '#ffffff',
400
- onChange: (hex) => {
401
- this.applyColorChange(hex);
432
+ initialColor,
433
+ onChange: (color) => {
434
+ this.applyColorChange(color);
402
435
  }
403
436
  });
404
437
  const typed = (instance ?? {});
405
438
  return {
406
439
  host,
407
- setValue: (hex) => {
408
- const normalized = normalizeHexColor(hex);
409
- if (!normalized)
410
- return;
411
- typed.setValue?.(normalized);
440
+ setValue: (color) => {
441
+ typed.setValue?.(color);
412
442
  },
413
443
  setTheme: (theme) => {
414
444
  typed.setTheme?.(theme);
@@ -418,13 +448,23 @@ export class MTextToolbar {
418
448
  }
419
449
  };
420
450
  }
421
- applyColorChange(hex) {
422
- const normalized = normalizeHexColor(hex);
423
- if (!normalized)
451
+ applyColorChange(color) {
452
+ if (color.isAci && color.aci !== null) {
453
+ this.onFormatChange({
454
+ aci: color.aci
455
+ });
424
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
+ }
425
465
  this.onFormatChange({
426
466
  aci: null,
427
- rgb: hexToColorNumber(normalized)
467
+ rgb: 0xffffff
428
468
  });
429
469
  }
430
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,4 +1,5 @@
1
1
  import type { Box, CursorStyle, SelectionStyle } from '@mlightcad/text-box-cursor';
2
+ import type { ColorSettings, MTextColor, TextStyle } from '@mlightcad/mtext-renderer';
2
3
  import type * as THREE from 'three';
3
4
  /** Vertical script style for a character run. */
4
5
  export type CharScript = 'normal' | 'superscript' | 'subscript';
@@ -117,15 +118,15 @@ export interface MTextToolbarColorPickerContext {
117
118
  container: HTMLElement;
118
119
  /** Current toolbar theme. */
119
120
  theme: MTextToolbarTheme;
120
- /** Initial color as hex string (`#RRGGBB`). */
121
- initialColor: string;
122
- /** Call when user picks a new color. */
123
- 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;
124
125
  }
125
126
  /** Lifecycle hooks for a custom toolbar color picker. */
126
127
  export interface MTextToolbarColorPickerInstance {
127
- /** Sync picker UI when editor format changes. */
128
- setValue?: (hexColor: string) => void;
128
+ /** Sync picker UI when editor format changes (color may be ACI or RGB). */
129
+ setValue?: (color: MTextColor) => void;
129
130
  /** Sync picker UI when toolbar theme changes. */
130
131
  setTheme?: (theme: MTextToolbarTheme) => void;
131
132
  /** Cleanup mounted resources when toolbar is disposed. */
@@ -160,13 +161,13 @@ export interface MTextInputBoxOptions {
160
161
  /** Optional world-space origin of the editor container. */
161
162
  position?: THREE.Vector3;
162
163
  /**
163
- * Single default style source for the component.
164
+ * Default text style passed to `@mlightcad/mtext-renderer`.
164
165
  *
165
166
  * It is used for:
166
- * - insertion format of newly typed characters
167
- * - 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
168
169
  */
169
- defaultFormat?: Partial<CharFormat>;
170
+ textStyle?: TextStyle;
170
171
  /** Partial cursor style overrides forwarded to cursor renderer. */
171
172
  cursorStyle?: Partial<CursorStyle>;
172
173
  /** Partial selection style overrides forwarded to cursor renderer. */
@@ -175,6 +176,8 @@ export interface MTextInputBoxOptions {
175
176
  enableWordWrap?: boolean;
176
177
  /** Optional worker URL used by renderer implementations that support workers. */
177
178
  workerUrl?: string | URL;
179
+ /** Optional base URL for font loading (overrides renderer default). */
180
+ fontUrl?: string;
178
181
  /** Element used for built-in IME bridge attachment. */
179
182
  imeTarget: HTMLElement;
180
183
  /** Whether to render a visible editor bounding box overlay. */
@@ -183,6 +186,8 @@ export interface MTextInputBoxOptions {
183
186
  boundingBoxStyle?: MTextBoundingBoxStyle;
184
187
  /** Built-in toolbar configuration (DOM overlay). */
185
188
  toolbar?: MTextToolbarOptions;
189
+ /** Optional ACI color settings for byLayer (256) and byBlock (0). */
190
+ colorSettings?: ColorSettings;
186
191
  }
187
192
  /** Directional cursor movement commands. */
188
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.2",
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": {