-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathexampleFontManager.ts
More file actions
296 lines (266 loc) · 10.3 KB
/
Copy pathexampleFontManager.ts
File metadata and controls
296 lines (266 loc) · 10.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
import {
DefaultFontsPreset,
FontInfo,
FontManager,
UnifiedRenderer
} from '@mlightcad/mtext-renderer'
/**
* Manages font discovery, preset application, local caching, and `<select>` UI
* for the interactive MText renderer example.
*
* @remarks
* Wraps {@link UnifiedRenderer} font APIs and synchronizes the text-style and SHAPE
* font dropdowns with {@link refreshAvailableFonts}. Status messages are written
* directly to the shared `#status` element passed at construction time.
*/
export class ExampleFontManager {
/** File extensions accepted by {@link cacheSelectedFontFile}. */
private readonly supportedFontExtensions = new Set([
'.shx',
'.ttf',
'.otf',
'.woff'
])
/**
* @param unifiedRenderer - Renderer whose font registry is queried and updated.
* @param statusDiv - `#status` element for user-facing progress and error text.
* @param fontSelect - Text-style font `<select>` (`#font-select`).
* @param shapeFontSelect - SHAPE font `<select>` (`#shape-font-select`); SHX fonts only.
* @param defaultFontsPresetSelect - Default-fonts preset `<select>`.
* @param fontCacheInput - File input for local font caching.
* @param fontCacheBtn - Button that triggers {@link cacheSelectedFontFile}.
*/
constructor(
private readonly unifiedRenderer: UnifiedRenderer,
private readonly statusDiv: HTMLDivElement,
private readonly fontSelect: HTMLSelectElement,
private readonly shapeFontSelect: HTMLSelectElement,
private readonly defaultFontsPresetSelect: HTMLSelectElement,
private readonly fontCacheInput: HTMLInputElement,
private readonly fontCacheBtn: HTMLButtonElement
) {}
/** @returns Currently selected primary text font from `#font-select`. */
getSelectedTextFont(): string {
return this.fontSelect.value
}
/** @returns Currently selected SHX font for SHAPE rendering. */
getSelectedShapeFont(): string {
return this.shapeFontSelect.value
}
/** @returns Active default-fonts preset identifier from the UI. */
getSelectedDefaultFontsPreset(): DefaultFontsPreset {
return this.defaultFontsPresetSelect.value as DefaultFontsPreset
}
/** @returns Whether {@link FontManager.lazyFontLoading} is currently enabled. */
isLazyFontLoading(): boolean {
return FontManager.instance.lazyFontLoading
}
/**
* @returns Whether {@link FontManager.awaitFontsBeforeDraw} is currently
* enabled.
*/
isAwaitFontsBeforeDraw(): boolean {
return FontManager.instance.awaitFontsBeforeDraw
}
/**
* Mirrors the UI checkbox onto {@link FontManager.lazyFontLoading} and any
* existing worker pool.
*
* @param enabled - When true, fonts load in the background during draw.
*/
async setLazyFontLoading(enabled: boolean): Promise<void> {
await this.unifiedRenderer.setLazyFontLoading(enabled)
}
/**
* Mirrors the UI checkbox onto {@link FontManager.awaitFontsBeforeDraw} and
* any existing worker pool.
*
* @param enabled - When true with lazy loading, draw waits for referenced fonts.
*/
async setAwaitFontsBeforeDraw(enabled: boolean): Promise<void> {
await this.unifiedRenderer.setAwaitFontsBeforeDraw(enabled)
}
/**
* Fonts that non-lazy mode should preload for the active preset and selects.
*/
getFontsToPreload(): string[] {
const preset = this.getSelectedDefaultFontsPreset()
const textChain = this.unifiedRenderer.getDefaultFontsPreset(preset)
const symbolChain = this.unifiedRenderer.getSymbolFontsPreset(preset)
return [
...new Set([
...textChain,
...symbolChain,
this.fontSelect.value,
this.shapeFontSelect.value
])
].filter(Boolean)
}
/**
* Bootstraps font lists and applies the current preset.
*
* @param isResetAvailableFonts - When true, repopulates selects from the renderer first.
* @throws Rethrows errors from font loading so the caller can show a fatal status message.
*/
async initialize(isResetAvailableFonts = true): Promise<void> {
if (isResetAvailableFonts) {
await this.refreshAvailableFonts()
}
await this.applyDefaultFontsPreset()
}
/**
* Applies the selected preset. In non-lazy mode, also preloads the text/symbol
* chains and the currently selected fonts. In lazy mode, only configures the
* fallback chains so the next render can fetch fonts on demand.
*/
async applyDefaultFontsPreset(): Promise<void> {
const preset = this.getSelectedDefaultFontsPreset()
await this.unifiedRenderer.setDefaultFonts(preset)
const textChain = this.unifiedRenderer.getDefaultFontsPreset(preset)
const symbolChain = this.unifiedRenderer.getSymbolFontsPreset(preset)
const fontsToLoad = this.getFontsToPreload()
if (!this.isLazyFontLoading()) {
await this.unifiedRenderer.loadFonts(fontsToLoad)
this.statusDiv.textContent = `Preset "${preset}" (non-lazy): preloaded ${fontsToLoad.join(', ')}`
} else {
this.statusDiv.textContent = `Preset "${preset}" (lazy): text ${textChain.join(' → ')} | symbol ${symbolChain.join(' → ')} — fonts load on render`
}
this.statusDiv.style.color = '#0f0'
}
/**
* Refreshes both font `<select>` elements from {@link UnifiedRenderer.getAvailableFonts}.
*
* @param selectedTextFont - Optional text font to preserve after repopulating.
* @param selectedShapeFont - Optional SHAPE font to preserve after repopulating.
* @returns Full font metadata list returned by the renderer.
*/
async refreshAvailableFonts(
selectedTextFont?: string,
selectedShapeFont?: string
): Promise<FontInfo[]> {
const result = await this.unifiedRenderer.getAvailableFonts()
const fonts = result.fonts as FontInfo[]
this.populateFontSelects(fonts, selectedTextFont, selectedShapeFont)
return fonts
}
/**
* Caches the file chosen in `#font-cache-input`, refreshes UI, and re-renders.
*
* @param onCached - Async callback invoked after a successful cache (typically re-render).
*/
async cacheSelectedFontFile(onCached: () => Promise<void>): Promise<void> {
const file = this.fontCacheInput.files?.[0]
if (!file) {
this.statusDiv.textContent = 'Select a font file to cache'
this.statusDiv.style.color = '#f00'
return
}
if (!this.isSupportedFontFile(file)) {
this.statusDiv.textContent =
'Unsupported font type. Use .shx, .ttf, .otf, or .woff'
this.statusDiv.style.color = '#f00'
return
}
try {
this.statusDiv.textContent = `Caching ${file.name}...`
this.statusDiv.style.color = '#ffa500'
this.fontCacheBtn.disabled = true
const status = await this.unifiedRenderer.cacheFont(file)
if (status.status !== 'Success') {
this.statusDiv.textContent = `Failed to cache ${file.name}`
this.statusDiv.style.color = '#f00'
return
}
await this.refreshAvailableFonts(status.fontName, status.fontName)
await this.applyDefaultFontsPreset()
await onCached()
this.statusDiv.textContent = `Cached and loaded ${file.name} (${status.fontName})`
this.statusDiv.style.color = '#0f0'
this.fontCacheInput.value = ''
} catch (error) {
console.error('Error caching font:', error)
this.statusDiv.textContent = 'Error caching font'
this.statusDiv.style.color = '#f00'
} finally {
this.fontCacheBtn.disabled = !this.fontCacheInput.files?.[0]
}
}
/** Enables or disables the cache button based on whether a file is selected. */
updateCacheButtonState(): void {
this.fontCacheBtn.disabled = !this.fontCacheInput.files?.[0]
}
/** @returns Lowercase extension including the dot, or empty string when absent. */
private getFontExtension(fileName: string): string {
const dotIndex = fileName.lastIndexOf('.')
if (dotIndex < 0) {
return ''
}
return fileName.slice(dotIndex).toLowerCase()
}
/** @returns Whether `file` has an extension listed in {@link supportedFontExtensions}. */
private isSupportedFontFile(file: File): boolean {
return this.supportedFontExtensions.has(this.getFontExtension(file.name))
}
/**
* Formats a font entry for `<option>` display.
*
* @param font - Font metadata from the renderer registry.
* @returns Primary name, suffixed with `[cached]` when loaded from IndexedDB.
*/
private formatFontLabel(font: FontInfo): string {
const label = font.name[0]
return font.source === 'cache' ? `${label} [cached]` : label
}
/**
* Rebuilds `#font-select` and `#shape-font-select` from available fonts.
*
* @param fonts - Complete font list from the renderer.
* @param selectedTextFont - Preferred text font; falls back to `simsun` when unmatched.
* @param selectedShapeFont - Preferred SHAPE font; falls back to `complex` when unmatched.
*/
private populateFontSelects(
fonts: FontInfo[],
selectedTextFont?: string,
selectedShapeFont?: string
): void {
const previousTextFont = selectedTextFont ?? this.fontSelect.value
const previousShapeFont = selectedShapeFont ?? this.shapeFontSelect.value
this.fontSelect.innerHTML = ''
this.shapeFontSelect.innerHTML = ''
let textFontMatched = false
let shapeFontMatched = false
const matchesSelection = (
font: FontInfo,
selectedName: string
): boolean =>
font.name.some(
name => name.toLowerCase() === selectedName.toLowerCase()
)
fonts.forEach(font => {
const option = document.createElement('option')
option.value = font.name[0]
option.textContent = this.formatFontLabel(font)
if (matchesSelection(font, previousTextFont)) {
option.selected = true
textFontMatched = true
} else if (!textFontMatched && font.name[0] === 'simsun') {
option.selected = true
textFontMatched = true
}
this.fontSelect.appendChild(option)
if (font.type === 'shx' || font.file.toLowerCase().endsWith('.shx')) {
const shapeOption = document.createElement('option')
shapeOption.value = font.name[0]
shapeOption.textContent = this.formatFontLabel(font)
if (matchesSelection(font, previousShapeFont)) {
shapeOption.selected = true
shapeFontMatched = true
} else if (!shapeFontMatched && font.name[0] === 'complex') {
shapeOption.selected = true
shapeFontMatched = true
}
this.shapeFontSelect.appendChild(shapeOption)
}
})
}
}