@mlightcad/mtext-input-box 0.1.0 → 0.1.2

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
@@ -1,149 +1,203 @@
1
- # @mlightcad/mtext-input-box - Three.js Rich Text Editor
2
-
3
- Three.js-based MTEXT editor component with built-in IME bridge, cursor/selection rendering, and floating toolbar.
4
-
5
- ## Purpose
6
-
7
- - MTEXT-style editing in Three.js.
8
- - Keyboard/mouse/IME editing, selection, formatting, undo/redo.
9
- - Built-in toolbar (theme/font list/container/offset configurable).
10
- - Integrates `@mlightcad/mtext-renderer` and `@mlightcad/text-box-cursor`.
11
-
12
- ## Install
13
-
14
- ```bash
15
- pnpm add @mlightcad/mtext-input-box three @mlightcad/mtext-parser @mlightcad/mtext-renderer
16
- ```
17
-
18
- `@mlightcad/mtext-parser` and `@mlightcad/mtext-renderer` are peer dependencies of `@mlightcad/mtext-input-box`, so your app should install them directly.
19
-
20
- ## Basic Usage
21
-
22
- ```ts
23
- import * as THREE from 'three';
24
- import { MTextInputBox } from '@mlightcad/mtext-input-box';
25
-
26
- const scene = new THREE.Scene();
27
- const camera = new THREE.OrthographicCamera(0, 1000, 600, 0, -1000, 1000);
28
- const canvas = document.querySelector<HTMLCanvasElement>('#stage')!;
29
-
30
- const editor = new MTextInputBox({
31
- scene,
32
- camera,
33
- width: 800,
34
- position: new THREE.Vector3(80, 520, 0),
35
- initialText: 'Hello\\PWorld',
36
- imeTarget: canvas,
37
- defaultFormat: {
38
- fontFamily: 'monospace',
39
- fontSize: 24,
40
- bold: false,
41
- italic: false,
42
- underline: false,
43
- overline: false,
44
- strike: false,
45
- aci: null,
46
- rgb: 0xffffff
47
- },
48
- toolbar: {
49
- enabled: true,
50
- theme: 'dark',
51
- offsetY: 12
52
- }
53
- });
54
-
55
- function animate() {
56
- requestAnimationFrame(animate);
57
- editor.update();
58
- }
59
- animate();
60
- ```
61
-
62
- Notes:
63
-
64
- - `imeTarget` is required for text input/IME and built-in mouse interactions.
65
- - For multi-editor scenes, each editor instance can share the same canvas `imeTarget`.
66
-
67
- ## Toolbar
68
-
69
- The built-in toolbar is a DOM overlay mounted above the active editor and updated automatically when camera/viewport changes.
70
-
71
- `toolbar` options:
72
-
73
- - `enabled?: boolean` (default `true`)
74
- - `theme?: 'light' | 'dark'` (default `dark`)
75
- - `fontFamilies?: string[]` (default `['Arial', 'Helvetica', 'Verdana', 'Tahoma', 'Trebuchet MS', 'Times New Roman', 'Georgia', 'Courier New', 'system-ui', 'sans-serif', 'serif', 'monospace']`)
76
- - `container?: HTMLElement` (default `document.body`)
77
- - `offsetY?: number` (default `10`)
78
-
79
- Public toolbar-related methods:
80
-
81
- - `setToolbarTheme('light' | 'dark')`
82
- - `getToolbarTheme()`
83
-
84
- ## Editor Visibility And Activation
85
-
86
- - Click inside editor bounds: activate editor and start editing.
87
- - Click outside active editor bounds: editor closes (`closeEditor()` behavior).
88
- - Double-click rendered text of a closed editor: re-open (`showEditor()` behavior).
89
- - Programmatic control:
90
- - `closeEditor(): void`
91
- - `showEditor(): boolean`
92
-
93
- ## Important Options
94
-
95
- - `defaultFormat`: base insert format and renderer fallback style source.
96
- - `imeTarget`: element used by built-in IME bridge and built-in pointer interactions.
97
- - `enableWordWrap?: boolean`: enable/disable editor-side wrapping behavior.
98
- - `showBoundingBox?: boolean`: show editor boundary rectangle.
99
- - `boundingBoxStyle?: { color?, opacity?, padding?, zOffset? }`: boundary style overrides.
100
- - `workerUrl?: string | URL`: worker URL for renderer initialization.
101
- - `cursorStyle` / `selectionStyle`: forwarded to cursor renderer.
102
- - `toolbar`: built-in toolbar options (`enabled`, `theme`, `fontFamilies`, `container`, `offsetY`).
103
-
104
- ## Input And Interaction
105
-
106
- Built-in handling:
107
-
108
- - Keyboard editing (including macOS/Windows shortcut variants)
109
- - IME composition (via hidden textarea bridge)
110
- - Mouse selection and word-select:
111
- - `mousedown`: place cursor / shift-select
112
- - `mousemove` during drag: update selection
113
- - `mouseup`: stop drag
114
- - `dblclick`: select word
115
-
116
- Advanced control:
117
-
118
- - `attachIme(target)` / `detachIme()`
119
- - `attachPointerInteractions(target)` / `detachPointerInteractions()`
120
-
121
- ## Events
122
-
123
- - `change`
124
- - `selectionChange`
125
- - `cursorMove`
126
- - `show`
127
- - `close`
128
-
129
- ## Undo / Redo
130
-
131
- - API:
132
- - `undo(): boolean`
133
- - `redo(): boolean`
134
- - Keyboard:
135
- - `Ctrl/Cmd + Z`: undo
136
- - `Ctrl/Cmd + Y`: redo
137
- - `Ctrl/Cmd + Shift + Z`: redo
138
-
139
- ## Lifecycle
140
-
141
- - Call `editor.update()` inside your render loop.
142
- - Call `editor.dispose()` when unmounting to release renderer, cursor, IME, toolbar, and pointer listeners.
143
-
144
- ## Development
145
-
146
- ```bash
147
- pnpm --filter @mlightcad/mtext-input-box lint
148
- pnpm --filter @mlightcad/mtext-input-box build
149
- ```
1
+ # Three.js Rich Text Editor
2
+
3
+ Three.js-based MTEXT editor component with built-in IME bridge, cursor/selection rendering, and floating toolbar.
4
+
5
+ ![MText Editor](../../docs/mtext-editor.webp)
6
+
7
+ ## Purpose
8
+
9
+ - MTEXT-style editing in Three.js
10
+ - Keyboard/mouse/IME editing, selection, formatting, and undo/redo
11
+ - Built-in toolbar (configurable theme, font list, container, and offset)
12
+ - Integration with `@mlightcad/mtext-renderer` and `@mlightcad/text-box-cursor`
13
+
14
+ ## Technical Details
15
+
16
+ - Medium article: [Building a Three.js Rich Text Editor](https://medium.com/@mlightcad/building-a-three-js-rich-text-editor-b7283126ee97)
17
+
18
+ ![arch diagram](../../docs/architecture.svg)
19
+
20
+ ## Install
21
+
22
+ ```bash
23
+ pnpm add @mlightcad/mtext-input-box three @mlightcad/mtext-parser @mlightcad/mtext-renderer
24
+ ```
25
+
26
+ `@mlightcad/mtext-parser` and `@mlightcad/mtext-renderer` are peer dependencies of `@mlightcad/mtext-input-box`, so your app should install them directly.
27
+
28
+ ## Basic Usage
29
+
30
+ ```ts
31
+ import * as THREE from 'three';
32
+ import { MTextInputBox } from '@mlightcad/mtext-input-box';
33
+
34
+ const scene = new THREE.Scene();
35
+ const camera = new THREE.OrthographicCamera(0, 1000, 600, 0, -1000, 1000);
36
+ const canvas = document.querySelector<HTMLCanvasElement>('#stage')!;
37
+
38
+ const editor = new MTextInputBox({
39
+ scene,
40
+ camera,
41
+ width: 800,
42
+ position: new THREE.Vector3(80, 520, 0),
43
+ initialText: 'Hello\\PWorld',
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
55
+ },
56
+ toolbar: {
57
+ enabled: true,
58
+ theme: 'dark',
59
+ offsetY: 12
60
+ }
61
+ });
62
+
63
+ function animate() {
64
+ requestAnimationFrame(animate);
65
+ editor.update();
66
+ }
67
+ animate();
68
+ ```
69
+
70
+ Notes:
71
+
72
+ - `imeTarget` is required for text input/IME and built-in mouse interactions.
73
+ - For multi-editor scenes, each editor instance can share the same canvas `imeTarget`.
74
+
75
+ ## Toolbar
76
+
77
+ The built-in toolbar is a DOM overlay mounted above the active editor and updated automatically when the camera or viewport changes.
78
+
79
+ `toolbar` options:
80
+
81
+ - `enabled?: boolean` (default `true`)
82
+ - `theme?: 'light' | 'dark'` (default `dark`)
83
+ - `fontFamilies?: string[]` (default `['Arial', 'Helvetica', 'Verdana', 'Tahoma', 'Trebuchet MS', 'Times New Roman', 'Georgia', 'Courier New', 'system-ui', 'sans-serif', 'serif', 'monospace']`)
84
+ - `colorPicker?: (context) => { setValue?, setTheme?, dispose? }` (optional custom picker factory)
85
+ - `container?: HTMLElement` (default `document.body`)
86
+ - `offsetY?: number` (default `10`)
87
+
88
+ Custom color picker factory context:
89
+
90
+ - `container: HTMLElement`: mount point for your UI.
91
+ - `theme: 'light' | 'dark'`: current toolbar theme.
92
+ - `initialColor: '#RRGGBB'`: initial color.
93
+ - `onChange(hexColor)`: call this when user picks a new color.
94
+
95
+ Example (mount a Vue color picker):
96
+
97
+ ```ts
98
+ import { createApp, h, ref } from 'vue';
99
+
100
+ toolbar: {
101
+ colorPicker: ({ container, initialColor, theme, onChange }) => {
102
+ const color = ref(initialColor);
103
+ const app = createApp({
104
+ render() {
105
+ return h(MyVueColorPicker, {
106
+ modelValue: color.value,
107
+ theme,
108
+ 'onUpdate:modelValue': (next: string) => {
109
+ color.value = next;
110
+ onChange(next);
111
+ }
112
+ });
113
+ }
114
+ });
115
+
116
+ app.mount(container);
117
+
118
+ return {
119
+ setValue(next: string) {
120
+ color.value = next;
121
+ },
122
+ setTheme(nextTheme: 'light' | 'dark') {
123
+ // Optional: forward theme into your picker state if needed.
124
+ },
125
+ dispose() {
126
+ app.unmount();
127
+ }
128
+ };
129
+ }
130
+ }
131
+ ```
132
+
133
+ Public toolbar-related methods:
134
+
135
+ - `setToolbarTheme('light' | 'dark')`
136
+ - `getToolbarTheme()`
137
+
138
+ ## Editor Visibility And Activation
139
+
140
+ - Click inside editor bounds: activate editor and start editing.
141
+ - Click outside active editor bounds: editor closes (`closeEditor()` behavior).
142
+ - Double-click rendered text of a closed editor: re-open (`showEditor()` behavior).
143
+ - Programmatic control:
144
+ - `closeEditor(): void`
145
+ - `showEditor(): boolean`
146
+
147
+ ## Important Options
148
+
149
+ - `defaultFormat`: base insert format and renderer fallback style source.
150
+ - `imeTarget`: element used by built-in IME bridge and built-in pointer interactions.
151
+ - `enableWordWrap?: boolean`: enable/disable editor-side wrapping behavior.
152
+ - `showBoundingBox?: boolean`: show editor boundary rectangle.
153
+ - `boundingBoxStyle?: { color?, opacity?, padding?, zOffset? }`: boundary style overrides.
154
+ - `workerUrl?: string | URL`: worker URL for renderer initialization.
155
+ - `cursorStyle` / `selectionStyle`: forwarded to cursor renderer.
156
+ - `toolbar`: built-in toolbar options (`enabled`, `theme`, `fontFamilies`, `colorPicker`, `container`, `offsetY`).
157
+
158
+ ## Input And Interaction
159
+
160
+ Built-in handling:
161
+
162
+ - Keyboard editing (including macOS/Windows shortcut variants)
163
+ - IME composition (via hidden textarea bridge)
164
+ - Mouse selection and word-select:
165
+ - `mousedown`: place cursor / shift-select
166
+ - `mousemove` during drag: update selection
167
+ - `mouseup`: stop drag
168
+ - `dblclick`: select word
169
+
170
+ Advanced control:
171
+
172
+ - `attachIme(target)` / `detachIme()`
173
+ - `attachPointerInteractions(target)` / `detachPointerInteractions()`
174
+
175
+ ## Events
176
+
177
+ - `change`
178
+ - `selectionChange`
179
+ - `cursorMove`
180
+ - `show`
181
+ - `close`
182
+
183
+ ## Undo / Redo
184
+
185
+ - API:
186
+ - `undo(): boolean`
187
+ - `redo(): boolean`
188
+ - Keyboard:
189
+ - `Ctrl/Cmd + Z`: undo
190
+ - `Ctrl/Cmd + Y`: redo
191
+ - `Ctrl/Cmd + Shift + Z`: redo
192
+
193
+ ## Lifecycle
194
+
195
+ - Call `editor.update()` inside your render loop.
196
+ - Call `editor.dispose()` when unmounting to release renderer, cursor, IME, toolbar, and pointer listeners.
197
+
198
+ ## Development
199
+
200
+ ```bash
201
+ pnpm --filter @mlightcad/mtext-input-box lint
202
+ pnpm --filter @mlightcad/mtext-input-box build
203
+ ```
package/dist/index.d.ts CHANGED
@@ -2,6 +2,6 @@ export { MTextInputBox, MTextEditor, defaultCharFormat, sameFormat } from './vie
2
2
  export { MTextDocument, parseMTextToAst, buildMTextFromAst, insertTextInAst, deleteRangeInAst, replaceRangeInAst } from './model';
3
3
  export { EditorUiAdapter } from './controller';
4
4
  export { MTextToolbar } from './ui';
5
- export type { CharFormat, CharScript, CursorDirection, EditorState, LayoutCharBox, CursorLayoutData, MTextBoundingBoxStyle, MTextInputBoxEvent, MTextInputBoxOptions, MTextToolbarOptions, MTextToolbarTheme, MTextEditorEvent, MTextEditorOptions, MTextRendererOutput, SelectionDirection } from './viewer';
5
+ export type { CharFormat, CharScript, CursorDirection, EditorState, LayoutCharBox, CursorLayoutData, MTextBoundingBoxStyle, MTextInputBoxEvent, MTextInputBoxOptions, MTextToolbarColorPickerContext, MTextToolbarColorPickerFactory, MTextToolbarColorPickerInstance, MTextToolbarOptions, MTextToolbarTheme, MTextEditorEvent, MTextEditorOptions, MTextRendererOutput, SelectionDirection } from './viewer';
6
6
  export type { MTextScript, MTextStyle, MTextAst, MTextAstNode, EditorSelection } from './model';
7
7
  export type { EditorCommand, EditorKeyEventLike } from './controller';
@@ -1,15 +1,16 @@
1
- import type { CharFormat, MTextToolbarTheme } from '../viewer/types';
1
+ import type { CharFormat, MTextToolbarColorPickerFactory, MTextToolbarTheme } from '../viewer/types';
2
2
  export interface ToolbarOptions {
3
3
  anchorElement: HTMLElement;
4
4
  container?: HTMLElement;
5
5
  theme: MTextToolbarTheme;
6
6
  fontFamilies?: string[];
7
+ colorPicker?: MTextToolbarColorPickerFactory;
7
8
  onFormatChange: (partial: Partial<CharFormat>) => void;
8
9
  onToggleStack: () => void;
9
10
  onToggleSuperscript?: () => boolean;
10
11
  onToggleSubscript?: () => boolean;
11
12
  }
12
- export type ToolbarSessionOptions = Omit<ToolbarOptions, 'container' | 'theme' | 'fontFamilies'>;
13
+ export type ToolbarSessionOptions = Omit<ToolbarOptions, 'container' | 'theme' | 'fontFamilies' | 'colorPicker'>;
13
14
  export declare class MTextToolbar {
14
15
  private anchorElement;
15
16
  private readonly root;
@@ -19,6 +20,7 @@ export declare class MTextToolbar {
19
20
  private onToggleSuperscript;
20
21
  private onToggleSubscript;
21
22
  private theme;
23
+ private readonly colorPicker;
22
24
  constructor(options: ToolbarOptions);
23
25
  setTheme(theme: MTextToolbarTheme): void;
24
26
  getTheme(): MTextToolbarTheme;
@@ -31,4 +33,6 @@ export declare class MTextToolbar {
31
33
  private setToggleState;
32
34
  private ensureSelectValue;
33
35
  private bindEvents;
36
+ private createColorPicker;
37
+ private applyColorChange;
34
38
  }
@@ -19,119 +19,119 @@ function ensureToolbarStyles() {
19
19
  return;
20
20
  const style = document.createElement('style');
21
21
  style.id = STYLE_ID;
22
- style.textContent = `
23
- .mlc-mtext-toolbar {
24
- position: fixed;
25
- left: 0;
26
- top: 0;
27
- z-index: 2147483000;
28
- display: inline-flex;
29
- align-items: center;
30
- gap: 10px;
31
- border-radius: 8px;
32
- border: 1px solid;
33
- padding: 8px;
34
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif;
35
- font-size: 12px;
36
- line-height: 1;
37
- box-shadow: 0 8px 24px rgba(0, 0, 0, 0.24);
38
- user-select: none;
39
- }
40
- .mlc-mtext-toolbar[data-theme='dark'] {
41
- background: linear-gradient(180deg, #2a2d33 0%, #1d2025 100%);
42
- border-color: #444b58;
43
- color: #e8ecf4;
44
- }
45
- .mlc-mtext-toolbar[data-theme='light'] {
46
- background: linear-gradient(180deg, #ffffff 0%, #f2f4f8 100%);
47
- border-color: #cfd5df;
48
- color: #1e2430;
49
- }
50
- .mlc-mtext-toolbar__group {
51
- display: inline-flex;
52
- align-items: center;
53
- gap: 4px;
54
- }
55
- .mlc-mtext-toolbar__separator {
56
- width: 1px;
57
- height: 24px;
58
- opacity: 0.35;
59
- }
60
- .mlc-mtext-toolbar[data-theme='dark'] .mlc-mtext-toolbar__separator {
61
- background: #576177;
62
- }
63
- .mlc-mtext-toolbar[data-theme='light'] .mlc-mtext-toolbar__separator {
64
- background: #b8c0ce;
65
- }
66
- .mlc-mtext-toolbar__select,
67
- .mlc-mtext-toolbar__input,
68
- .mlc-mtext-toolbar__color,
69
- .mlc-mtext-toolbar__btn {
70
- border: 1px solid;
71
- border-radius: 6px;
72
- height: 34px;
73
- }
74
- .mlc-mtext-toolbar[data-theme='dark'] .mlc-mtext-toolbar__select,
75
- .mlc-mtext-toolbar[data-theme='dark'] .mlc-mtext-toolbar__input,
76
- .mlc-mtext-toolbar[data-theme='dark'] .mlc-mtext-toolbar__color,
77
- .mlc-mtext-toolbar[data-theme='dark'] .mlc-mtext-toolbar__btn {
78
- background: #12161d;
79
- border-color: #454d5f;
80
- color: #f2f5fb;
81
- }
82
- .mlc-mtext-toolbar[data-theme='light'] .mlc-mtext-toolbar__select,
83
- .mlc-mtext-toolbar[data-theme='light'] .mlc-mtext-toolbar__input,
84
- .mlc-mtext-toolbar[data-theme='light'] .mlc-mtext-toolbar__color,
85
- .mlc-mtext-toolbar[data-theme='light'] .mlc-mtext-toolbar__btn {
86
- background: #ffffff;
87
- border-color: #c7cdd8;
88
- color: #1f2632;
89
- }
90
- .mlc-mtext-toolbar__select {
91
- min-width: 140px;
92
- padding: 0 8px;
93
- }
94
- .mlc-mtext-toolbar__input {
95
- width: 64px;
96
- padding: 0 8px;
97
- }
98
- .mlc-mtext-toolbar__color {
99
- width: 40px;
100
- padding: 2px;
101
- }
102
- .mlc-mtext-toolbar__btn {
103
- width: 34px;
104
- display: inline-flex;
105
- align-items: center;
106
- justify-content: center;
107
- cursor: pointer;
108
- transition: border-color 0.14s ease, background 0.14s ease, color 0.14s ease;
109
- }
110
- .mlc-mtext-toolbar__btn svg {
111
- width: 24px;
112
- height: 24px;
113
- fill: currentColor;
114
- }
115
- .mlc-mtext-toolbar__btn.is-active {
116
- border-color: #2f9dff;
117
- color: #2f9dff;
118
- }
119
- .mlc-mtext-toolbar[data-theme='dark'] .mlc-mtext-toolbar__btn.is-active {
120
- background: linear-gradient(180deg, #123252 0%, #0c243d 100%);
121
- color: #8fcbff;
122
- box-shadow: inset 0 0 0 1px rgba(143, 203, 255, 0.18);
123
- }
124
- .mlc-mtext-toolbar[data-theme='light'] .mlc-mtext-toolbar__btn.is-active {
125
- background: linear-gradient(180deg, #dcebff 0%, #cfe3ff 100%);
126
- color: #1d67ad;
127
- box-shadow: inset 0 0 0 1px rgba(29, 103, 173, 0.16);
128
- }
129
- .mlc-mtext-toolbar[data-theme='dark'] .mlc-mtext-toolbar__btn:hover {
130
- background: #1f2530;
131
- }
132
- .mlc-mtext-toolbar[data-theme='light'] .mlc-mtext-toolbar__btn:hover {
133
- background: #edf3ff;
134
- }
22
+ style.textContent = `
23
+ .ml-mtext-toolbar {
24
+ position: fixed;
25
+ left: 0;
26
+ top: 0;
27
+ z-index: 2147483000;
28
+ display: inline-flex;
29
+ align-items: center;
30
+ gap: 10px;
31
+ border-radius: 8px;
32
+ border: 1px solid;
33
+ padding: 8px;
34
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif;
35
+ font-size: 12px;
36
+ line-height: 1;
37
+ box-shadow: 0 8px 24px rgba(0, 0, 0, 0.24);
38
+ user-select: none;
39
+ }
40
+ .ml-mtext-toolbar[data-theme='dark'] {
41
+ background: linear-gradient(180deg, #2a2d33 0%, #1d2025 100%);
42
+ border-color: #444b58;
43
+ color: #e8ecf4;
44
+ }
45
+ .ml-mtext-toolbar[data-theme='light'] {
46
+ background: linear-gradient(180deg, #ffffff 0%, #f2f4f8 100%);
47
+ border-color: #cfd5df;
48
+ color: #1e2430;
49
+ }
50
+ .ml-mtext-toolbar__group {
51
+ display: inline-flex;
52
+ align-items: center;
53
+ gap: 4px;
54
+ }
55
+ .ml-mtext-toolbar__separator {
56
+ width: 1px;
57
+ height: 24px;
58
+ opacity: 0.35;
59
+ }
60
+ .ml-mtext-toolbar[data-theme='dark'] .ml-mtext-toolbar__separator {
61
+ background: #576177;
62
+ }
63
+ .ml-mtext-toolbar[data-theme='light'] .ml-mtext-toolbar__separator {
64
+ background: #b8c0ce;
65
+ }
66
+ .ml-mtext-toolbar__select,
67
+ .ml-mtext-toolbar__input,
68
+ .ml-mtext-toolbar__color,
69
+ .ml-mtext-toolbar__btn {
70
+ border: 1px solid;
71
+ border-radius: 6px;
72
+ height: 34px;
73
+ }
74
+ .ml-mtext-toolbar[data-theme='dark'] .ml-mtext-toolbar__select,
75
+ .ml-mtext-toolbar[data-theme='dark'] .ml-mtext-toolbar__input,
76
+ .ml-mtext-toolbar[data-theme='dark'] .ml-mtext-toolbar__color,
77
+ .ml-mtext-toolbar[data-theme='dark'] .ml-mtext-toolbar__btn {
78
+ background: #12161d;
79
+ border-color: #454d5f;
80
+ color: #f2f5fb;
81
+ }
82
+ .ml-mtext-toolbar[data-theme='light'] .ml-mtext-toolbar__select,
83
+ .ml-mtext-toolbar[data-theme='light'] .ml-mtext-toolbar__input,
84
+ .ml-mtext-toolbar[data-theme='light'] .ml-mtext-toolbar__color,
85
+ .ml-mtext-toolbar[data-theme='light'] .ml-mtext-toolbar__btn {
86
+ background: #ffffff;
87
+ border-color: #c7cdd8;
88
+ color: #1f2632;
89
+ }
90
+ .ml-mtext-toolbar__select {
91
+ min-width: 140px;
92
+ padding: 0 8px;
93
+ }
94
+ .ml-mtext-toolbar__input {
95
+ width: 64px;
96
+ padding: 0 8px;
97
+ }
98
+ .ml-mtext-toolbar__color {
99
+ width: 40px;
100
+ padding: 2px;
101
+ }
102
+ .ml-mtext-toolbar__btn {
103
+ width: 34px;
104
+ display: inline-flex;
105
+ align-items: center;
106
+ justify-content: center;
107
+ cursor: pointer;
108
+ transition: border-color 0.14s ease, background 0.14s ease, color 0.14s ease;
109
+ }
110
+ .ml-mtext-toolbar__btn svg {
111
+ width: 24px;
112
+ height: 24px;
113
+ fill: currentColor;
114
+ }
115
+ .ml-mtext-toolbar__btn.is-active {
116
+ border-color: #2f9dff;
117
+ color: #2f9dff;
118
+ }
119
+ .ml-mtext-toolbar[data-theme='dark'] .ml-mtext-toolbar__btn.is-active {
120
+ background: linear-gradient(180deg, #123252 0%, #0c243d 100%);
121
+ color: #8fcbff;
122
+ box-shadow: inset 0 0 0 1px rgba(143, 203, 255, 0.18);
123
+ }
124
+ .ml-mtext-toolbar[data-theme='light'] .ml-mtext-toolbar__btn.is-active {
125
+ background: linear-gradient(180deg, #dcebff 0%, #cfe3ff 100%);
126
+ color: #1d67ad;
127
+ box-shadow: inset 0 0 0 1px rgba(29, 103, 173, 0.16);
128
+ }
129
+ .ml-mtext-toolbar[data-theme='dark'] .ml-mtext-toolbar__btn:hover {
130
+ background: #1f2530;
131
+ }
132
+ .ml-mtext-toolbar[data-theme='light'] .ml-mtext-toolbar__btn:hover {
133
+ background: #edf3ff;
134
+ }
135
135
  `;
136
136
  document.head.appendChild(style);
137
137
  }
@@ -147,10 +147,18 @@ function hexToColorNumber(hex) {
147
147
  return 0xffffff;
148
148
  return Number.parseInt(hex.slice(1), 16);
149
149
  }
150
+ function normalizeHexColor(hex) {
151
+ const normalized = hex.trim().toLowerCase();
152
+ if (/^#[0-9a-f]{6}$/.test(normalized))
153
+ return normalized;
154
+ if (/^[0-9a-f]{6}$/.test(normalized))
155
+ return `#${normalized}`;
156
+ return null;
157
+ }
150
158
  function createIconButton(title, icon) {
151
159
  const btn = document.createElement('button');
152
160
  btn.type = 'button';
153
- btn.className = 'mlc-mtext-toolbar__btn';
161
+ btn.className = 'ml-mtext-toolbar__btn';
154
162
  btn.title = title;
155
163
  btn.setAttribute('aria-label', title);
156
164
  btn.setAttribute('aria-pressed', 'false');
@@ -179,6 +187,7 @@ export class MTextToolbar {
179
187
  onToggleSuperscript;
180
188
  onToggleSubscript;
181
189
  theme;
190
+ colorPicker;
182
191
  constructor(options) {
183
192
  ensureToolbarStyles();
184
193
  this.anchorElement = options.anchorElement;
@@ -188,11 +197,11 @@ export class MTextToolbar {
188
197
  this.onToggleSubscript = options.onToggleSubscript ?? (() => false);
189
198
  this.theme = options.theme;
190
199
  this.root = document.createElement('div');
191
- this.root.className = 'mlc-mtext-toolbar';
200
+ this.root.className = 'ml-mtext-toolbar';
192
201
  const typographyGroup = document.createElement('div');
193
- typographyGroup.className = 'mlc-mtext-toolbar__group';
202
+ typographyGroup.className = 'ml-mtext-toolbar__group';
194
203
  const fontFamily = document.createElement('select');
195
- fontFamily.className = 'mlc-mtext-toolbar__select';
204
+ fontFamily.className = 'ml-mtext-toolbar__select';
196
205
  for (const family of resolveFontFamilies(options.fontFamilies)) {
197
206
  const option = document.createElement('option');
198
207
  option.value = family;
@@ -200,19 +209,17 @@ export class MTextToolbar {
200
209
  fontFamily.appendChild(option);
201
210
  }
202
211
  const fontSize = document.createElement('input');
203
- fontSize.className = 'mlc-mtext-toolbar__input';
212
+ fontSize.className = 'ml-mtext-toolbar__input';
204
213
  fontSize.type = 'number';
205
214
  fontSize.min = '1';
206
215
  fontSize.max = '1024';
207
216
  fontSize.step = '1';
208
- const fontColor = document.createElement('input');
209
- fontColor.className = 'mlc-mtext-toolbar__color';
210
- fontColor.type = 'color';
211
- typographyGroup.append(fontFamily, fontSize, fontColor);
217
+ this.colorPicker = this.createColorPicker(options.colorPicker);
218
+ typographyGroup.append(fontFamily, fontSize, this.colorPicker.host);
212
219
  const separator1 = document.createElement('div');
213
- separator1.className = 'mlc-mtext-toolbar__separator';
220
+ separator1.className = 'ml-mtext-toolbar__separator';
214
221
  const styleGroup = document.createElement('div');
215
- styleGroup.className = 'mlc-mtext-toolbar__group';
222
+ styleGroup.className = 'ml-mtext-toolbar__group';
216
223
  const boldBtn = createIconButton('Bold', 'bold');
217
224
  const italicBtn = createIconButton('Italic', 'italic');
218
225
  const underlineBtn = createIconButton('Underline', 'underline');
@@ -226,7 +233,6 @@ export class MTextToolbar {
226
233
  this.controls = {
227
234
  fontFamily,
228
235
  fontSize,
229
- fontColor,
230
236
  boldBtn,
231
237
  italicBtn,
232
238
  underlineBtn,
@@ -243,6 +249,7 @@ export class MTextToolbar {
243
249
  setTheme(theme) {
244
250
  this.theme = theme;
245
251
  this.root.dataset.theme = theme;
252
+ this.colorPicker.setTheme(theme);
246
253
  }
247
254
  getTheme() {
248
255
  return this.theme;
@@ -273,7 +280,7 @@ export class MTextToolbar {
273
280
  this.ensureSelectValue(format.fontFamily);
274
281
  this.controls.fontSize.value = String(Math.max(1, Math.round(format.fontSize)));
275
282
  const color = format.rgb !== null ? format.rgb : 0xffffff;
276
- this.controls.fontColor.value = colorNumberToHex(color);
283
+ this.colorPicker.setValue(colorNumberToHex(color));
277
284
  this.setToggleState(this.controls.boldBtn, format.bold);
278
285
  this.setToggleState(this.controls.italicBtn, format.italic);
279
286
  this.setToggleState(this.controls.underlineBtn, format.underline);
@@ -283,6 +290,7 @@ export class MTextToolbar {
283
290
  this.setToggleState(this.controls.subscriptBtn, format.script === 'subscript');
284
291
  }
285
292
  dispose() {
293
+ this.colorPicker.dispose();
286
294
  this.root.remove();
287
295
  }
288
296
  setStackActive(active) {
@@ -320,12 +328,6 @@ export class MTextToolbar {
320
328
  this.anchorElement.focus({ preventScroll: true });
321
329
  }
322
330
  });
323
- this.controls.fontColor.addEventListener('input', () => {
324
- this.onFormatChange({
325
- aci: null,
326
- rgb: hexToColorNumber(this.controls.fontColor.value)
327
- });
328
- });
329
331
  this.controls.boldBtn.addEventListener('click', () => {
330
332
  this.onFormatChange({ bold: !this.controls.boldBtn.classList.contains('is-active') });
331
333
  });
@@ -360,10 +362,69 @@ export class MTextToolbar {
360
362
  const target = event.target;
361
363
  if (!target)
362
364
  return;
365
+ if (target.closest('[data-ml-mtext-toolbar-interactive="true"]'))
366
+ return;
363
367
  if (target.tagName === 'INPUT' || target.tagName === 'SELECT' || target.tagName === 'OPTION')
364
368
  return;
365
369
  event.preventDefault();
366
370
  this.anchorElement.focus({ preventScroll: true });
367
371
  });
368
372
  }
373
+ createColorPicker(factory) {
374
+ if (!factory) {
375
+ const input = document.createElement('input');
376
+ input.className = 'ml-mtext-toolbar__color';
377
+ input.type = 'color';
378
+ input.dataset.mlMtextToolbarInteractive = 'true';
379
+ input.addEventListener('input', () => {
380
+ this.applyColorChange(input.value);
381
+ });
382
+ return {
383
+ host: input,
384
+ setValue: (hex) => {
385
+ const normalized = normalizeHexColor(hex);
386
+ if (normalized)
387
+ input.value = normalized;
388
+ },
389
+ setTheme: () => { },
390
+ dispose: () => { }
391
+ };
392
+ }
393
+ const host = document.createElement('div');
394
+ host.className = 'ml-mtext-toolbar__color';
395
+ host.dataset.mlMtextToolbarInteractive = 'true';
396
+ const instance = factory({
397
+ container: host,
398
+ theme: this.theme,
399
+ initialColor: '#ffffff',
400
+ onChange: (hex) => {
401
+ this.applyColorChange(hex);
402
+ }
403
+ });
404
+ const typed = (instance ?? {});
405
+ return {
406
+ host,
407
+ setValue: (hex) => {
408
+ const normalized = normalizeHexColor(hex);
409
+ if (!normalized)
410
+ return;
411
+ typed.setValue?.(normalized);
412
+ },
413
+ setTheme: (theme) => {
414
+ typed.setTheme?.(theme);
415
+ },
416
+ dispose: () => {
417
+ typed.dispose?.();
418
+ }
419
+ };
420
+ }
421
+ applyColorChange(hex) {
422
+ const normalized = normalizeHexColor(hex);
423
+ if (!normalized)
424
+ return;
425
+ this.onFormatChange({
426
+ aci: null,
427
+ rgb: hexToColorNumber(normalized)
428
+ });
429
+ }
369
430
  }
@@ -1,2 +1,2 @@
1
1
  export { MTextInputBox, MTextEditor, defaultCharFormat, sameFormat } from './viewer';
2
- export type { CharFormat, CharScript, EditorState, LayoutCharBox, RendererContainerBox, RendererLineInfo, MTextRendererOutput, CursorLayoutData, MTextBoundingBoxStyle, MTextInputBoxOptions, MTextToolbarOptions, MTextToolbarTheme, CursorDirection, SelectionDirection, MTextInputBoxEvent, MTextEditorEvent, MTextEditorOptions } from './types';
2
+ export type { CharFormat, CharScript, EditorState, LayoutCharBox, RendererContainerBox, RendererLineInfo, MTextRendererOutput, CursorLayoutData, MTextBoundingBoxStyle, MTextInputBoxOptions, MTextToolbarColorPickerContext, MTextToolbarColorPickerFactory, MTextToolbarColorPickerInstance, MTextToolbarOptions, MTextToolbarTheme, CursorDirection, SelectionDirection, MTextInputBoxEvent, MTextEditorEvent, MTextEditorOptions } from './types';
@@ -111,6 +111,28 @@ export interface MTextBoundingBoxStyle {
111
111
  }
112
112
  /** Construction options for `MTextInputBox`. */
113
113
  export type MTextToolbarTheme = 'light' | 'dark';
114
+ /** Context passed to custom toolbar color picker factory. */
115
+ export interface MTextToolbarColorPickerContext {
116
+ /** Host element where custom UI should be mounted. */
117
+ container: HTMLElement;
118
+ /** Current toolbar theme. */
119
+ 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;
124
+ }
125
+ /** Lifecycle hooks for a custom toolbar color picker. */
126
+ export interface MTextToolbarColorPickerInstance {
127
+ /** Sync picker UI when editor format changes. */
128
+ setValue?: (hexColor: string) => void;
129
+ /** Sync picker UI when toolbar theme changes. */
130
+ setTheme?: (theme: MTextToolbarTheme) => void;
131
+ /** Cleanup mounted resources when toolbar is disposed. */
132
+ dispose?: () => void;
133
+ }
134
+ /** Factory used to mount custom toolbar color picker UI (for example a Vue component). */
135
+ export type MTextToolbarColorPickerFactory = (context: MTextToolbarColorPickerContext) => MTextToolbarColorPickerInstance | void;
114
136
  /** Toolbar options for built-in editor toolbar UI. */
115
137
  export interface MTextToolbarOptions {
116
138
  /** Enables the built-in toolbar. Defaults to true. */
@@ -119,6 +141,8 @@ export interface MTextToolbarOptions {
119
141
  theme?: MTextToolbarTheme;
120
142
  /** Available font family options shown in toolbar dropdown. */
121
143
  fontFamilies?: string[];
144
+ /** Custom color picker factory used instead of native `<input type="color">`. */
145
+ colorPicker?: MTextToolbarColorPickerFactory;
122
146
  /** Custom DOM container to mount toolbar. Defaults to document.body. */
123
147
  container?: HTMLElement;
124
148
  /** Vertical offset in pixels above editor top edge. Defaults to 10. */
@@ -11,6 +11,7 @@ export declare class MTextInputBox {
11
11
  private static sharedToolbar;
12
12
  private static sharedToolbarContainer;
13
13
  private static sharedToolbarFontFamiliesKey;
14
+ private static sharedToolbarColorPickerFactory;
14
15
  private static readonly instances;
15
16
  private readonly scene;
16
17
  private readonly camera;
@@ -57,6 +58,7 @@ export declare class MTextInputBox {
57
58
  private toolbarEnabled;
58
59
  private toolbarContainer;
59
60
  private toolbarFontFamilies;
61
+ private toolbarColorPicker;
60
62
  private readonly onImeKeyDown;
61
63
  private readonly onWindowKeyDown;
62
64
  private readonly onImeBeforeInput;
@@ -14,6 +14,7 @@ export class MTextInputBox {
14
14
  static sharedToolbar = null;
15
15
  static sharedToolbarContainer = null;
16
16
  static sharedToolbarFontFamiliesKey = '';
17
+ static sharedToolbarColorPickerFactory = null;
17
18
  static instances = new Set();
18
19
  scene;
19
20
  camera;
@@ -70,6 +71,7 @@ export class MTextInputBox {
70
71
  toolbarEnabled = true;
71
72
  toolbarContainer = null;
72
73
  toolbarFontFamilies = null;
74
+ toolbarColorPicker;
73
75
  onImeKeyDown = (event) => {
74
76
  if (!this.isActiveEditor())
75
77
  return;
@@ -213,6 +215,7 @@ export class MTextInputBox {
213
215
  this.toolbarEnabled = options.toolbar?.enabled ?? true;
214
216
  this.toolbarContainer = options.toolbar?.container ?? null;
215
217
  this.toolbarFontFamilies = options.toolbar?.fontFamilies ?? null;
218
+ this.toolbarColorPicker = options.toolbar?.colorPicker;
216
219
  this.width = Math.max(1, options.width);
217
220
  this.position = options.position?.clone() ?? new THREE.Vector3(0, 0, 0);
218
221
  this.enableWordWrap = options.enableWordWrap ?? true;
@@ -533,6 +536,10 @@ export class MTextInputBox {
533
536
  if (event.isComposing || event.key === 'Process') {
534
537
  return false;
535
538
  }
539
+ if (event.key === 'Escape') {
540
+ this.closeEditor();
541
+ return true;
542
+ }
536
543
  const isMac = this.isMacPlatform();
537
544
  const primaryModifier = isMac ? event.metaKey : event.ctrlKey;
538
545
  const wordNavModifier = isMac ? event.altKey : event.ctrlKey;
@@ -695,6 +702,7 @@ export class MTextInputBox {
695
702
  MTextInputBox.sharedToolbar = null;
696
703
  MTextInputBox.sharedToolbarContainer = null;
697
704
  MTextInputBox.sharedToolbarFontFamiliesKey = '';
705
+ MTextInputBox.sharedToolbarColorPickerFactory = null;
698
706
  MTextInputBox.activeEditor = null;
699
707
  }
700
708
  }
@@ -866,7 +874,8 @@ export class MTextInputBox {
866
874
  const fontFamiliesKey = this.toolbarFontFamilies?.join('\u0000') ?? '';
867
875
  const shouldRecreate = !MTextInputBox.sharedToolbar ||
868
876
  MTextInputBox.sharedToolbarContainer !== container ||
869
- MTextInputBox.sharedToolbarFontFamiliesKey !== fontFamiliesKey;
877
+ MTextInputBox.sharedToolbarFontFamiliesKey !== fontFamiliesKey ||
878
+ MTextInputBox.sharedToolbarColorPickerFactory !== (this.toolbarColorPicker ?? null);
870
879
  if (shouldRecreate) {
871
880
  MTextInputBox.sharedToolbar?.dispose();
872
881
  const toolbarOptions = {
@@ -877,9 +886,13 @@ export class MTextInputBox {
877
886
  if (this.toolbarFontFamilies) {
878
887
  toolbarOptions.fontFamilies = this.toolbarFontFamilies;
879
888
  }
889
+ if (this.toolbarColorPicker) {
890
+ toolbarOptions.colorPicker = this.toolbarColorPicker;
891
+ }
880
892
  MTextInputBox.sharedToolbar = new MTextToolbar(toolbarOptions);
881
893
  MTextInputBox.sharedToolbarContainer = container;
882
894
  MTextInputBox.sharedToolbarFontFamiliesKey = fontFamiliesKey;
895
+ MTextInputBox.sharedToolbarColorPickerFactory = this.toolbarColorPicker ?? null;
883
896
  }
884
897
  const toolbar = MTextInputBox.sharedToolbar;
885
898
  if (!toolbar) {
@@ -1445,9 +1458,39 @@ export class MTextInputBox {
1445
1458
  const index = this.cursorLogic.getCurrentIndex();
1446
1459
  const line = this.cursorLogic.getCurrentLineInfo();
1447
1460
  if (boxes.length === 0) {
1461
+ // Empty-content bootstrap path.
1462
+ //
1463
+ // Why this exists:
1464
+ // - For a brand new/empty MTEXT, there are no glyph boxes yet.
1465
+ // - In that state, TextBoxCursor falls back to its container line info.
1466
+ // - Depending on renderer output, that fallback Y can represent the whole
1467
+ // container center instead of the first editable line center, so the
1468
+ // caret appears visually lower than the top line area.
1469
+ //
1470
+ // Goal:
1471
+ // - Anchor caret to the first editable line, not to the entire empty box.
1472
+ // - Keep X from cursor logic (fallbackPosition.x), only correct Y/height.
1473
+ const firstLine = this.latestCursorLayoutData.lineLayouts?.[0];
1474
+ if (firstLine && Number.isFinite(firstLine.y) && Number.isFinite(firstLine.height)) {
1475
+ const lineHeight = Math.max(1, firstLine.height);
1476
+ return {
1477
+ // Best source: renderer-provided line layout already represents
1478
+ // the actual first-line center in editor local coordinates.
1479
+ position: { x: fallbackPosition.x, y: firstLine.y },
1480
+ height: Math.max(1, lineHeight * 0.8)
1481
+ };
1482
+ }
1483
+ const inferredLineHeight = Math.max(1, this.getFallbackLineAdvance());
1448
1484
  return {
1449
- position: fallbackPosition,
1450
- height: Math.max(1, fallbackHeight)
1485
+ position: {
1486
+ x: fallbackPosition.x,
1487
+ // When explicit line layout is unavailable, infer first-line center
1488
+ // from top-left container coordinates:
1489
+ // lineCenterY = containerTopY + lineHeight / 2
1490
+ // This keeps caret aligned with the top row for empty MTEXT.
1491
+ y: this.layoutContainer.y + inferredLineHeight / 2
1492
+ },
1493
+ height: Math.max(1, inferredLineHeight * 0.8)
1451
1494
  };
1452
1495
  }
1453
1496
  // At a line-start gap (including wrapped/paragraph boundaries), rely on
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mlightcad/mtext-input-box",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -14,11 +14,11 @@
14
14
  "dist"
15
15
  ],
16
16
  "dependencies": {
17
- "@mlightcad/text-box-cursor": "0.1.0"
17
+ "@mlightcad/text-box-cursor": "0.1.1"
18
18
  },
19
19
  "peerDependencies": {
20
- "@mlightcad/mtext-parser": "^1.3.2",
21
- "@mlightcad/mtext-renderer": "^0.10.1",
20
+ "@mlightcad/mtext-parser": "^1.3.3",
21
+ "@mlightcad/mtext-renderer": "^0.10.2",
22
22
  "three": "^0.172.0"
23
23
  },
24
24
  "devDependencies": {