@mlightcad/mtext-input-box 0.1.3 → 0.2.1

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
@@ -30,6 +30,7 @@ pnpm add @mlightcad/mtext-input-box three @mlightcad/mtext-parser @mlightcad/mte
30
30
  ```ts
31
31
  import * as THREE from 'three';
32
32
  import { MTextInputBox } from '@mlightcad/mtext-input-box';
33
+ import { MTextColor } from '@mlightcad/mtext-renderer';
33
34
 
34
35
  const scene = new THREE.Scene();
35
36
  const camera = new THREE.OrthographicCamera(0, 1000, 600, 0, -1000, 1000);
@@ -42,16 +43,21 @@ const editor = new MTextInputBox({
42
43
  position: new THREE.Vector3(80, 520, 0),
43
44
  initialText: 'Hello\\PWorld',
44
45
  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
46
+ textStyle: {
47
+ name: 'MTextInputBoxStyle',
48
+ standardFlag: 0,
49
+ fixedTextHeight: 24,
50
+ widthFactor: 1,
51
+ obliqueAngle: 0,
52
+ textGenerationFlag: 0,
53
+ lastHeight: 24,
54
+ font: 'simkai',
55
+ bigFont: ''
56
+ },
57
+ colorSettings: {
58
+ byLayerColor: 0xffffff,
59
+ byBlockColor: 0xffffff,
60
+ color: new MTextColor(256)
55
61
  },
56
62
  toolbar: {
57
63
  enabled: true,
@@ -89,8 +95,8 @@ Custom color picker factory context:
89
95
 
90
96
  - `container: HTMLElement`: mount point for your UI.
91
97
  - `theme: 'light' | 'dark'`: current toolbar theme.
92
- - `initialColor: '#RRGGBB'`: initial color.
93
- - `onChange(hexColor)`: call this when user picks a new color.
98
+ - `initialColor: MTextColor`: initial color (ACI or RGB). It reflects the active editor format at toolbar creation time.
99
+ - `onChange(color: MTextColor)`: call this when user picks a new color (ACI or RGB).
94
100
 
95
101
  Custom color picker instance methods:
96
102
 
@@ -102,29 +108,27 @@ Example (mount a Vue color picker):
102
108
 
103
109
  ```ts
104
110
  import { createApp, h, ref } from 'vue';
105
- import { getColorByIndex } from '@mlightcad/mtext-renderer';
106
- import { MTextColor } from '@mlightcad/mtext-parser';
111
+ import { getColorByIndex, MTextColor } from '@mlightcad/mtext-renderer';
107
112
 
108
113
  toolbar: {
109
114
  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
- }
115
+ const toCssColor = (value: MTextColor) => {
115
116
  if (value.isAci && value.aci !== null) {
116
117
  return `#${getColorByIndex(value.aci).toString(16).padStart(6, '0')}`;
117
118
  }
118
- return '#ffffff';
119
+ return value.toCssColor() ?? '#ffffff';
119
120
  };
121
+ const color = ref(toCssColor(initialColor));
120
122
  const app = createApp({
121
123
  render() {
122
124
  return h(MyVueColorPicker, {
123
125
  modelValue: color.value,
124
126
  theme,
125
127
  'onUpdate:modelValue': (next: string) => {
128
+ const nextColor = MTextColor.fromCssColor(next);
129
+ if (!nextColor) return;
126
130
  color.value = next;
127
- onChange(next);
131
+ onChange(nextColor);
128
132
  }
129
133
  });
130
134
  }
@@ -134,7 +138,7 @@ toolbar: {
134
138
 
135
139
  return {
136
140
  setValue(next: MTextColor) {
137
- color.value = toHex(next);
141
+ color.value = toCssColor(next);
138
142
  },
139
143
  setTheme(nextTheme: 'light' | 'dark') {
140
144
  // Optional: forward theme into your picker state if needed.
@@ -163,12 +167,13 @@ Public toolbar-related methods:
163
167
 
164
168
  ## Important Options
165
169
 
166
- - `defaultFormat`: base insert format and renderer fallback style source.
170
+ - `textStyle`: default text style passed to the renderer and used to derive base insert format.
167
171
  - `imeTarget`: element used by built-in IME bridge and built-in pointer interactions.
168
172
  - `enableWordWrap?: boolean`: enable/disable editor-side wrapping behavior.
169
173
  - `showBoundingBox?: boolean`: show editor boundary rectangle.
170
174
  - `boundingBoxStyle?: { color?, opacity?, padding?, zOffset? }`: boundary style overrides.
171
175
  - `workerUrl?: string | URL`: worker URL for renderer initialization.
176
+ - `fontUrl?: string`: optional base URL for font loading (overrides renderer default).
172
177
  - `cursorStyle` / `selectionStyle`: forwarded to cursor renderer.
173
178
  - `toolbar`: built-in toolbar options (`enabled`, `theme`, `fontFamilies`, `colorPicker`, `container`, `offsetY`).
174
179
 
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { MTextInputBox, MTextEditor, defaultCharFormat, sameFormat } from './viewer';
1
+ export { DEFAULT_FONT_FAMILY, MTextInputBox, MTextEditor, defaultCharFormat, sameFormat } from './viewer';
2
2
  export { MTextDocument, parseMTextToAst, buildMTextFromAst, insertTextInAst, deleteRangeInAst, replaceRangeInAst } from './model';
3
3
  export { EditorUiAdapter } from './controller';
4
4
  export { MTextToolbar } from './ui';
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- export { MTextInputBox, MTextEditor, defaultCharFormat, sameFormat } from './viewer';
1
+ export { DEFAULT_FONT_FAMILY, MTextInputBox, MTextEditor, defaultCharFormat, sameFormat } from './viewer';
2
2
  export { MTextDocument, parseMTextToAst, buildMTextFromAst, insertTextInAst, deleteRangeInAst, replaceRangeInAst } from './model';
3
3
  export { EditorUiAdapter } from './controller';
4
4
  export { MTextToolbar } from './ui';
@@ -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,2 +1,3 @@
1
+ export { DEFAULT_FONT_FAMILY } from './format';
1
2
  export { MTextInputBox, MTextEditor, defaultCharFormat, sameFormat } from './viewer';
2
3
  export type { CharFormat, CharScript, EditorState, LayoutCharBox, RendererContainerBox, RendererLineInfo, MTextRendererOutput, CursorLayoutData, MTextBoundingBoxStyle, MTextInputBoxOptions, MTextToolbarColorPickerContext, MTextToolbarColorPickerFactory, MTextToolbarColorPickerInstance, MTextToolbarOptions, MTextToolbarTheme, CursorDirection, SelectionDirection, MTextInputBoxEvent, MTextEditorEvent, MTextEditorOptions } from './types';
@@ -1 +1,2 @@
1
+ export { DEFAULT_FONT_FAMILY } from './format';
1
2
  export { MTextInputBox, MTextEditor, defaultCharFormat, sameFormat } from './viewer';
@@ -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;
@@ -198,11 +204,12 @@ export declare class MTextInputBox {
198
204
  private normalizeColorNumber;
199
205
  private resolveAciColor;
200
206
  private resolveBaseColor;
201
- private resolveFormatColorNumber;
202
- private createDefaultTextStyle;
207
+ private resolveBaseFormatColor;
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, MTextColor } 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,17 @@ 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
+ };
24
35
  width;
25
36
  position;
26
37
  enableWordWrap;
@@ -44,9 +55,12 @@ export class MTextInputBox {
44
55
  boundingBoxPadding = 1;
45
56
  boundingBoxZOffset = 0.01;
46
57
  rendererReady = false;
58
+ pendingFontLoad = null;
59
+ lastFontKey = '';
47
60
  toolbarTheme = 'dark';
48
61
  toolbarOffsetY = 10;
49
62
  debugMode = false;
63
+ colorSettings;
50
64
  debugVisibility = {
51
65
  showCharBoxes: true,
52
66
  showLineIndices: true,
@@ -216,12 +230,28 @@ export class MTextInputBox {
216
230
  this.toolbarContainer = options.toolbar?.container ?? null;
217
231
  this.toolbarFontFamilies = options.toolbar?.fontFamilies ?? null;
218
232
  this.toolbarColorPicker = options.toolbar?.colorPicker;
233
+ this.colorSettings = options.colorSettings;
219
234
  this.width = Math.max(1, options.width);
220
235
  this.position = options.position?.clone() ?? new THREE.Vector3(0, 0, 0);
221
236
  this.enableWordWrap = options.enableWordWrap ?? true;
222
- this.baseFormat = { ...defaultCharFormat(), ...(options.defaultFormat ?? {}) };
237
+ const textStyle = options.textStyle ?? MTextInputBox.DEFAULT_TEXT_STYLE;
238
+ const fixedTextHeight = Math.max(1, Number.isFinite(textStyle.fixedTextHeight)
239
+ ? textStyle.fixedTextHeight
240
+ : MTextInputBox.DEFAULT_TEXT_STYLE.fixedTextHeight);
241
+ const lastHeight = Math.max(1, Number.isFinite(textStyle.lastHeight) ? textStyle.lastHeight : fixedTextHeight);
242
+ this.defaultTextStyle = {
243
+ ...textStyle,
244
+ fixedTextHeight,
245
+ lastHeight,
246
+ widthFactor: Number.isFinite(textStyle.widthFactor) ? textStyle.widthFactor : 1,
247
+ obliqueAngle: Number.isFinite(textStyle.obliqueAngle) ? textStyle.obliqueAngle : 0,
248
+ textGenerationFlag: Number.isFinite(textStyle.textGenerationFlag) ? textStyle.textGenerationFlag : 0,
249
+ standardFlag: Number.isFinite(textStyle.standardFlag) ? textStyle.standardFlag : 0,
250
+ font: textStyle.font || MTextInputBox.DEFAULT_TEXT_STYLE.font,
251
+ bigFont: textStyle.bigFont ?? ''
252
+ };
253
+ this.baseFormat = this.createBaseFormatFromTextStyle(this.defaultTextStyle, this.resolveRenderColorSettings());
223
254
  this.currentFormat = { ...this.baseFormat };
224
- this.defaultTextStyle = this.createDefaultTextStyle();
225
255
  this.document = new MTextDocument();
226
256
  this.uiAdapter = new EditorUiAdapter(this.document);
227
257
  this.mtextRenderer = new UnifiedRenderer('main', {
@@ -229,6 +259,9 @@ export class MTextInputBox {
229
259
  ? options.workerUrl
230
260
  : options.workerUrl?.toString() ?? './assets/mtext-renderer-worker.js'
231
261
  });
262
+ if (options.fontUrl) {
263
+ this.mtextRenderer.setFontUrl(options.fontUrl);
264
+ }
232
265
  this.cursorLogic = new TextBoxCursor({
233
266
  containerBox: { x: 0, y: 0, width: this.width, height: 1 },
234
267
  charBoxes: [],
@@ -526,7 +559,7 @@ export class MTextInputBox {
526
559
  getCurrentFormat() {
527
560
  return { ...this.currentFormat };
528
561
  }
529
- /** Returns renderer default text style derived from `defaultFormat`. */
562
+ /** Returns renderer default text style defined by `textStyle`. */
530
563
  getDefaultTextStyle() {
531
564
  return { ...this.defaultTextStyle };
532
565
  }
@@ -881,7 +914,8 @@ export class MTextInputBox {
881
914
  const toolbarOptions = {
882
915
  ...this.createToolbarSessionOptions(target),
883
916
  container,
884
- theme: this.toolbarTheme
917
+ theme: this.toolbarTheme,
918
+ initialFormat: this.currentFormat
885
919
  };
886
920
  if (this.toolbarFontFamilies) {
887
921
  toolbarOptions.fontFamilies = this.toolbarFontFamilies;
@@ -1013,8 +1047,9 @@ export class MTextInputBox {
1013
1047
  }
1014
1048
  async initializeRenderer() {
1015
1049
  try {
1016
- await this.mtextRenderer.loadFonts(['simkai']);
1050
+ await this.mtextRenderer.loadFonts([DEFAULT_FONT_FAMILY]);
1017
1051
  this.rendererReady = true;
1052
+ this.ensureFontsLoaded();
1018
1053
  this.relayout();
1019
1054
  }
1020
1055
  catch (error) {
@@ -1029,13 +1064,12 @@ export class MTextInputBox {
1029
1064
  this.updateBoundingBoxGeometry();
1030
1065
  return;
1031
1066
  }
1067
+ this.ensureFontsLoaded();
1032
1068
  try {
1033
1069
  const mtextData = this.createMTextData();
1034
1070
  const style = this.createTextStyle();
1035
- const object = this.mtextRenderer.syncRenderMText(mtextData, style, {
1036
- byLayerColor: 0xffffff,
1037
- byBlockColor: 0xffffff
1038
- });
1071
+ const colorSettings = this.resolveRenderColorSettings();
1072
+ const object = this.mtextRenderer.syncRenderMText(mtextData, style, colorSettings);
1039
1073
  this.replaceRenderedObject(object);
1040
1074
  const rendered = this.extractBoxesFromRenderedObject(object);
1041
1075
  this.normalizeRenderedTopAlignment(object, rendered);
@@ -1051,6 +1085,52 @@ export class MTextInputBox {
1051
1085
  this.updateBoundingBoxGeometry();
1052
1086
  }
1053
1087
  }
1088
+ ensureFontsLoaded() {
1089
+ if (this.pendingFontLoad)
1090
+ return;
1091
+ const fonts = this.collectFontNamesForText();
1092
+ const key = fonts.map((font) => font.toLowerCase()).sort().join('|');
1093
+ if (!key || key === this.lastFontKey)
1094
+ return;
1095
+ this.lastFontKey = key;
1096
+ this.pendingFontLoad = this.mtextRenderer
1097
+ .loadFonts(fonts)
1098
+ .then(() => undefined)
1099
+ .catch((error) => {
1100
+ console.warn('[mtext-input-box] Failed to load fonts for MTEXT', error);
1101
+ })
1102
+ .finally(() => {
1103
+ this.pendingFontLoad = null;
1104
+ if (this.rendererReady)
1105
+ this.relayout();
1106
+ });
1107
+ }
1108
+ collectFontNamesForText() {
1109
+ const fonts = new Set();
1110
+ const addFont = (name) => {
1111
+ if (!name)
1112
+ return;
1113
+ const trimmed = name.trim();
1114
+ if (!trimmed)
1115
+ return;
1116
+ fonts.add(trimmed);
1117
+ };
1118
+ addFont(this.defaultTextStyle.font);
1119
+ addFont(this.defaultTextStyle.bigFont);
1120
+ try {
1121
+ const fromContent = MText.getFonts(this.mtextString || '', true);
1122
+ for (const fontName of fromContent) {
1123
+ addFont(fontName);
1124
+ }
1125
+ }
1126
+ catch (error) {
1127
+ console.warn('[mtext-input-box] Failed to parse fonts from MTEXT', error);
1128
+ }
1129
+ if (fonts.size === 0) {
1130
+ fonts.add(DEFAULT_FONT_FAMILY);
1131
+ }
1132
+ return [...fonts];
1133
+ }
1054
1134
  updateCursorData(charBoxes, lineBreakIndices, lineLayouts) {
1055
1135
  this.latestCursorLayoutData = {
1056
1136
  containerBox: { ...this.layoutContainer },
@@ -1312,27 +1392,31 @@ export class MTextInputBox {
1312
1392
  }
1313
1393
  return 0xffffff;
1314
1394
  }
1315
- resolveFormatColorNumber(format) {
1316
- return this.isExplicitAci(format.aci)
1317
- ? this.resolveAciColor(format.aci)
1318
- : format.rgb !== null
1319
- ? this.normalizeColorNumber(format.rgb)
1320
- : 0xffffff;
1395
+ resolveBaseFormatColor(colorSettings) {
1396
+ const color = colorSettings.color;
1397
+ if (color.isRgb && color.rgbValue !== null) {
1398
+ return { aci: null, rgb: this.normalizeColorNumber(color.rgbValue) };
1399
+ }
1400
+ if (color.isAci && color.aci !== null) {
1401
+ const aci = color.aci;
1402
+ if (Number.isInteger(aci) && aci >= 1 && aci <= 255) {
1403
+ return { aci, rgb: null };
1404
+ }
1405
+ if (aci === 0) {
1406
+ return { aci: null, rgb: this.normalizeColorNumber(colorSettings.byBlockColor) };
1407
+ }
1408
+ return { aci: null, rgb: this.normalizeColorNumber(colorSettings.byLayerColor) };
1409
+ }
1410
+ return { aci: null, rgb: this.normalizeColorNumber(colorSettings.byLayerColor) };
1321
1411
  }
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
- };
1412
+ createBaseFormatFromTextStyle(style, colorSettings) {
1413
+ const base = defaultCharFormat();
1414
+ base.fontFamily = style.font || base.fontFamily;
1415
+ base.fontSize = Math.max(1, style.fixedTextHeight);
1416
+ const color = this.resolveBaseFormatColor(colorSettings);
1417
+ base.aci = color.aci;
1418
+ base.rgb = color.rgb;
1419
+ return base;
1336
1420
  }
1337
1421
  createMTextData() {
1338
1422
  return {
@@ -1356,6 +1440,13 @@ export class MTextInputBox {
1356
1440
  createTextStyle() {
1357
1441
  return { ...this.defaultTextStyle };
1358
1442
  }
1443
+ resolveRenderColorSettings() {
1444
+ if (this.colorSettings) {
1445
+ return this.colorSettings;
1446
+ }
1447
+ const base = this.toolbarTheme === 'light' ? 0x000000 : 0xffffff;
1448
+ return { byLayerColor: base, byBlockColor: base, color: new MTextColor(256) };
1449
+ }
1359
1450
  focusImeInput() {
1360
1451
  if (!this.imeInput)
1361
1452
  return;
@@ -1651,7 +1742,7 @@ export class MTextInputBox {
1651
1742
  syncDocumentFromUiState() {
1652
1743
  const selection = this.getSelectionRange();
1653
1744
  if (!selection.isCollapsed) {
1654
- const start = this.toDocumentIndexFromLogicalIndex(selection.start, false);
1745
+ const start = this.toDocumentIndexFromLogicalIndex(selection.start, true);
1655
1746
  const end = this.toDocumentIndexFromLogicalIndex(selection.end, false);
1656
1747
  this.document.setSelection(start, end);
1657
1748
  return;
@@ -1680,7 +1771,7 @@ export class MTextInputBox {
1680
1771
  return;
1681
1772
  this.commitHistoryEdit(() => {
1682
1773
  this.syncDocumentFromUiState();
1683
- const start = this.toDocumentIndexFromLogicalIndex(selection.start, false);
1774
+ const start = this.toDocumentIndexFromLogicalIndex(selection.start, true);
1684
1775
  const end = this.toDocumentIndexFromLogicalIndex(selection.end, false);
1685
1776
  if (end <= start)
1686
1777
  return;
@@ -1734,7 +1825,7 @@ export class MTextInputBox {
1734
1825
  let changed = false;
1735
1826
  this.commitHistoryEdit(() => {
1736
1827
  this.syncDocumentFromUiState();
1737
- const start = this.toDocumentIndexFromLogicalIndex(selection.start, false);
1828
+ const start = this.toDocumentIndexFromLogicalIndex(selection.start, true);
1738
1829
  const end = this.toDocumentIndexFromLogicalIndex(selection.end, false);
1739
1830
  if (end <= start)
1740
1831
  return;
@@ -1921,7 +2012,7 @@ export class MTextInputBox {
1921
2012
  toolbar.setStackActive(false);
1922
2013
  return;
1923
2014
  }
1924
- const start = this.toDocumentIndexFromLogicalIndex(selection.start, false);
2015
+ const start = this.toDocumentIndexFromLogicalIndex(selection.start, true);
1925
2016
  const end = this.toDocumentIndexFromLogicalIndex(selection.end, false);
1926
2017
  const selectedNodes = this.document.ast.nodes.slice(start, end);
1927
2018
  const active = selectedNodes.length === 1 &&
@@ -1952,6 +2043,10 @@ export class MTextInputBox {
1952
2043
  const node = this.getNodeByLogicalCharIndex(anchorIndex);
1953
2044
  if (!node)
1954
2045
  return null;
2046
+ if (node.type === 'stack' && this.isScriptOnlyStack(node)) {
2047
+ const script = node.numerator.trim().length > 0 ? 'superscript' : 'subscript';
2048
+ return { ...this.toCharFormat(node.style), script };
2049
+ }
1955
2050
  return this.toCharFormat(node.style);
1956
2051
  }
1957
2052
  getNodeByLogicalCharIndex(index) {
@@ -2024,11 +2119,16 @@ export class MTextInputBox {
2024
2119
  };
2025
2120
  }
2026
2121
  toScriptFromStyle(style, baseSize, capHeight) {
2027
- if (style.script && style.script !== 'normal') {
2028
- return style.script;
2029
- }
2030
2122
  const reducedThreshold = Math.max(1, baseSize) * 0.9;
2031
2123
  const isReduced = capHeight <= reducedThreshold;
2124
+ if (style.script && style.script !== 'normal') {
2125
+ // Guard against styles that inherit baseline alignment (BOTTOM/TOP) but
2126
+ // are not actual superscript/subscript runs. Only treat non-normal script
2127
+ // as active when the cap height is reduced.
2128
+ if (isReduced)
2129
+ return style.script;
2130
+ return 'normal';
2131
+ }
2032
2132
  if (isReduced && style.align === MTextLineAlignment.TOP) {
2033
2133
  return 'superscript';
2034
2134
  }
@@ -2042,10 +2142,10 @@ export class MTextInputBox {
2042
2142
  context.fontFace.family = this.defaultTextStyle.font || this.baseFormat.fontFamily;
2043
2143
  context.fontFace.style = this.baseFormat.italic ? 'Italic' : 'Regular';
2044
2144
  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 };
2145
+ // Align parser defaults with renderer: absolute cap height based on text style.
2146
+ context.capHeight = { value: this.defaultTextStyle.fixedTextHeight, isRelative: false };
2147
+ context.align = MTextLineAlignment.BOTTOM;
2148
+ context.widthFactor = { value: this.defaultTextStyle.widthFactor ?? 1, isRelative: false };
2049
2149
  if (this.isExplicitAci(this.baseFormat.aci)) {
2050
2150
  context.aci = this.baseFormat.aci;
2051
2151
  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.1",
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.5",
22
21
  "three": "^0.172.0"
23
22
  },
24
23
  "devDependencies": {