@kubohiroya/turbowarp-title-menu 0.2.3 → 0.2.5

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.
@@ -7,1600 +7,1625 @@
7
7
  (function (Scratch) {
8
8
  'use strict';
9
9
 
10
+ //#region node_modules/.pnpm/@kubohiroya+turbowarp-app-shell@0.3.0/node_modules/@kubohiroya/turbowarp-app-shell/dist/index.js
10
11
  function isRecord$1(value) {
11
- return typeof value === "object" && value !== null && !Array.isArray(value);
12
+ return typeof value === "object" && value !== null && !Array.isArray(value);
12
13
  }
13
14
  function requireElement$1(value, name) {
14
- if (!isRecord$1(value) || typeof value["appendChild"] !== "function") {
15
- throw new TypeError(`${name} must be a DOM element.`);
16
- }
17
- return value;
15
+ if (!isRecord$1(value) || typeof value["appendChild"] !== "function") throw new TypeError(`${name} must be a DOM element.`);
16
+ return value;
18
17
  }
19
18
  function requireDocument$1(value) {
20
- if (!isRecord$1(value) || typeof value["createElement"] !== "function") {
21
- throw new TypeError("document must provide the DOM document contract.");
22
- }
23
- return value;
19
+ if (!isRecord$1(value) || typeof value["createElement"] !== "function") throw new TypeError("document must provide the DOM document contract.");
20
+ return value;
24
21
  }
25
22
  function requireString(value, name) {
26
- if (typeof value !== "string" || value.length === 0) {
27
- throw new TypeError(`${name} must be a non-empty string.`);
28
- }
29
- return value;
23
+ if (typeof value !== "string" || value.length === 0) throw new TypeError(`${name} must be a non-empty string.`);
24
+ return value;
30
25
  }
31
26
  function optionalBoolean(value, name, fallback) {
32
- if (value === void 0)
33
- return fallback;
34
- if (typeof value !== "boolean")
35
- throw new TypeError(`${name} must be a boolean.`);
36
- return value;
27
+ if (value === void 0) return fallback;
28
+ if (typeof value !== "boolean") throw new TypeError(`${name} must be a boolean.`);
29
+ return value;
37
30
  }
38
31
  function optionalString(value, name) {
39
- if (value === void 0)
40
- return void 0;
41
- if (typeof value !== "string")
42
- throw new TypeError(`${name} must be a string.`);
43
- return value;
32
+ if (value === void 0) return void 0;
33
+ if (typeof value !== "string") throw new TypeError(`${name} must be a string.`);
34
+ return value;
44
35
  }
45
36
  function requireLocalizedLabels(value, name) {
46
- if (!isRecord$1(value))
47
- throw new TypeError(`${name} must be an object.`);
48
- const entries = Object.entries(value);
49
- if (entries.length === 0)
50
- throw new TypeError(`${name} must include at least one locale.`);
51
- for (const [locale, label] of entries) {
52
- if (typeof label !== "string" || label.length === 0) {
53
- throw new TypeError(`${name}.${locale} must be a non-empty string.`);
54
- }
55
- }
56
- return value;
37
+ if (!isRecord$1(value)) throw new TypeError(`${name} must be an object.`);
38
+ const entries = Object.entries(value);
39
+ if (entries.length === 0) throw new TypeError(`${name} must include at least one locale.`);
40
+ for (const [locale, label] of entries) if (typeof label !== "string" || label.length === 0) throw new TypeError(`${name}.${locale} must be a non-empty string.`);
41
+ return value;
57
42
  }
58
43
  function firstLocale(locales, name) {
59
- const [locale] = Object.keys(locales);
60
- if (locale === void 0)
61
- throw new TypeError(`${name} must include at least one locale.`);
62
- return locale;
44
+ const [locale] = Object.keys(locales);
45
+ if (locale === void 0) throw new TypeError(`${name} must include at least one locale.`);
46
+ return locale;
63
47
  }
64
48
  function resolveInjectedLocale(locales, requested, fallback, name) {
65
- if (requested !== void 0 && Object.hasOwn(locales, requested))
66
- return requested;
67
- if (fallback !== void 0 && Object.hasOwn(locales, fallback))
68
- return fallback;
69
- if (Object.hasOwn(locales, "en"))
70
- return "en";
71
- return firstLocale(locales, name);
49
+ if (requested !== void 0 && Object.hasOwn(locales, requested)) return requested;
50
+ if (fallback !== void 0 && Object.hasOwn(locales, fallback)) return fallback;
51
+ if (Object.hasOwn(locales, "en")) return "en";
52
+ return firstLocale(locales, name);
72
53
  }
73
54
  function localized(locales, locale, fallback, name) {
74
- const resolved = resolveInjectedLocale(locales, locale, fallback, name);
75
- return locales[resolved];
55
+ return locales[resolveInjectedLocale(locales, locale, fallback, name)];
76
56
  }
77
57
  function requireIcon(value, name) {
78
- if (value === void 0)
79
- return void 0;
80
- if (!isRecord$1(value))
81
- throw new TypeError(`${name} must be an object.`);
82
- const url = optionalString(value["url"], `${name}.url`);
83
- const text = optionalString(value["text"], `${name}.text`);
84
- const filter = optionalString(value["filter"], `${name}.filter`);
85
- const size = optionalString(value["size"], `${name}.size`);
86
- const fontSize = optionalString(value["fontSize"], `${name}.fontSize`);
87
- if ((url === void 0 || url.length === 0) && (text === void 0 || text.length === 0)) {
88
- throw new TypeError(`${name} must include a non-empty url or text.`);
89
- }
90
- return {
91
- ...url === void 0 ? {} : { url },
92
- ...text === void 0 ? {} : { text },
93
- ...filter === void 0 ? {} : { filter },
94
- ...size === void 0 ? {} : { size },
95
- ...fontSize === void 0 ? {} : { fontSize }
96
- };
58
+ if (value === void 0) return void 0;
59
+ if (!isRecord$1(value)) throw new TypeError(`${name} must be an object.`);
60
+ const url = optionalString(value["url"], `${name}.url`);
61
+ const text = optionalString(value["text"], `${name}.text`);
62
+ const filter = optionalString(value["filter"], `${name}.filter`);
63
+ const size = optionalString(value["size"], `${name}.size`);
64
+ const fontSize = optionalString(value["fontSize"], `${name}.fontSize`);
65
+ if ((url === void 0 || url.length === 0) && (text === void 0 || text.length === 0)) throw new TypeError(`${name} must include a non-empty url or text.`);
66
+ return {
67
+ ...url === void 0 ? {} : { url },
68
+ ...text === void 0 ? {} : { text },
69
+ ...filter === void 0 ? {} : { filter },
70
+ ...size === void 0 ? {} : { size },
71
+ ...fontSize === void 0 ? {} : { fontSize }
72
+ };
97
73
  }
98
74
  function requireAttributes(value, name) {
99
- if (value === void 0)
100
- return void 0;
101
- if (!isRecord$1(value))
102
- throw new TypeError(`${name} must be an object.`);
103
- for (const [attribute, attributeValue] of Object.entries(value)) {
104
- if (attribute.length === 0)
105
- throw new TypeError(`${name} names must be non-empty.`);
106
- if (typeof attributeValue !== "string") {
107
- throw new TypeError(`${name}.${attribute} must be a string.`);
108
- }
109
- }
110
- return value;
75
+ if (value === void 0) return void 0;
76
+ if (!isRecord$1(value)) throw new TypeError(`${name} must be an object.`);
77
+ for (const [attribute, attributeValue] of Object.entries(value)) {
78
+ if (attribute.length === 0) throw new TypeError(`${name} names must be non-empty.`);
79
+ if (typeof attributeValue !== "string") throw new TypeError(`${name}.${attribute} must be a string.`);
80
+ }
81
+ return value;
111
82
  }
112
83
  function applyAttributes(element, attributes) {
113
- if (attributes === void 0)
114
- return;
115
- for (const [name, value] of Object.entries(attributes))
116
- element.setAttribute(name, value);
84
+ if (attributes === void 0) return;
85
+ for (const [name, value] of Object.entries(attributes)) element.setAttribute(name, value);
117
86
  }
118
87
  function requireRect(value, name) {
119
- if (value === void 0)
120
- return void 0;
121
- if (!isRecord$1(value))
122
- throw new TypeError(`${name} must be an object.`);
123
- const left = optionalString(value["left"], `${name}.left`);
124
- const top = optionalString(value["top"], `${name}.top`);
125
- const width = optionalString(value["width"], `${name}.width`);
126
- const height = optionalString(value["height"], `${name}.height`);
127
- return {
128
- ...left === void 0 ? {} : { left },
129
- ...top === void 0 ? {} : { top },
130
- ...width === void 0 ? {} : { width },
131
- ...height === void 0 ? {} : { height }
132
- };
88
+ if (value === void 0) return void 0;
89
+ if (!isRecord$1(value)) throw new TypeError(`${name} must be an object.`);
90
+ const left = optionalString(value["left"], `${name}.left`);
91
+ const top = optionalString(value["top"], `${name}.top`);
92
+ const width = optionalString(value["width"], `${name}.width`);
93
+ const height = optionalString(value["height"], `${name}.height`);
94
+ return {
95
+ ...left === void 0 ? {} : { left },
96
+ ...top === void 0 ? {} : { top },
97
+ ...width === void 0 ? {} : { width },
98
+ ...height === void 0 ? {} : { height }
99
+ };
133
100
  }
134
101
  function applyRect(element, rect) {
135
- if (rect === void 0)
136
- return;
137
- if (rect.left !== void 0)
138
- element.style.left = rect.left;
139
- if (rect.top !== void 0)
140
- element.style.top = rect.top;
141
- if (rect.width !== void 0)
142
- element.style.width = rect.width;
143
- if (rect.height !== void 0)
144
- element.style.height = rect.height;
102
+ if (rect === void 0) return;
103
+ if (rect.left !== void 0) element.style.left = rect.left;
104
+ if (rect.top !== void 0) element.style.top = rect.top;
105
+ if (rect.width !== void 0) element.style.width = rect.width;
106
+ if (rect.height !== void 0) element.style.height = rect.height;
145
107
  }
146
108
  function requireTestId(value, name) {
147
- if (value === void 0)
148
- return void 0;
149
- if (typeof value !== "string" || value.length === 0) {
150
- throw new TypeError(`${name} must be a non-empty string.`);
151
- }
152
- return value;
109
+ if (value === void 0) return void 0;
110
+ if (typeof value !== "string" || value.length === 0) throw new TypeError(`${name} must be a non-empty string.`);
111
+ return value;
153
112
  }
154
113
  function applyTestId(element, testId) {
155
- if (testId !== void 0)
156
- element.setAttribute("data-testid", testId);
114
+ if (testId !== void 0) element.setAttribute("data-testid", testId);
157
115
  }
158
116
  function restoreableMountPosition(document, mount) {
159
- if (mount === document.body)
160
- return null;
161
- const previous = mount.style.position;
162
- if (previous === void 0 || previous === "" || previous === "static") {
163
- mount.style.position = "relative";
164
- return () => {
165
- mount.style.position = previous ?? "";
166
- };
167
- }
168
- return null;
117
+ if (mount === document.body) return null;
118
+ const previous = mount.style.position;
119
+ if (previous === void 0 || previous === "" || previous === "static") {
120
+ mount.style.position = "relative";
121
+ return () => {
122
+ mount.style.position = previous ?? "";
123
+ };
124
+ }
125
+ return null;
169
126
  }
170
127
  function setButtonEnabled(button, enabled) {
171
- button.disabled = !enabled;
172
- button.setAttribute("aria-disabled", String(!enabled));
173
- button.style.cursor = enabled ? "pointer" : "not-allowed";
174
- button.style.opacity = enabled ? "1" : "0.42";
128
+ button.disabled = !enabled;
129
+ button.setAttribute("aria-disabled", String(!enabled));
130
+ button.style.cursor = enabled ? "pointer" : "not-allowed";
131
+ button.style.opacity = enabled ? "1" : "0.42";
175
132
  }
176
133
  function setElementVisible(element, visible, display) {
177
- element.hidden = !visible;
178
- element.style.display = visible ? display : "none";
134
+ element.hidden = !visible;
135
+ element.style.display = visible ? display : "none";
179
136
  }
180
137
  function reportActionError(onError, error) {
181
- try {
182
- onError?.(error);
183
- } catch {
184
- }
138
+ try {
139
+ onError?.(error);
140
+ } catch {}
185
141
  }
186
142
  function invokeAction(action, onError, event) {
187
- event?.preventDefault();
188
- event?.stopPropagation();
189
- try {
190
- Promise.resolve(action()).catch((error) => {
191
- reportActionError(onError, error);
192
- });
193
- } catch (error) {
194
- reportActionError(onError, error);
195
- }
143
+ event?.preventDefault();
144
+ event?.stopPropagation();
145
+ try {
146
+ Promise.resolve(action()).catch((error) => {
147
+ reportActionError(onError, error);
148
+ });
149
+ } catch (error) {
150
+ reportActionError(onError, error);
151
+ }
196
152
  }
197
153
  function iconCssUrl(url) {
198
- return `url("${url.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}")`;
154
+ return `url("${url.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"")}")`;
199
155
  }
200
156
  function renderIcon(element, icon) {
201
- element.textContent = "";
202
- element.style.backgroundImage = "";
203
- element.style.display = icon === void 0 ? "none" : "inline-flex";
204
- if (icon === void 0)
205
- return;
206
- element.style.filter = icon.filter ?? "";
207
- if (icon.size !== void 0) {
208
- element.style.width = icon.size;
209
- element.style.height = icon.size;
210
- }
211
- if (icon.fontSize !== void 0)
212
- element.style.fontSize = icon.fontSize;
213
- if (icon.url !== void 0) {
214
- element.style.backgroundImage = iconCssUrl(icon.url);
215
- element.style.backgroundPosition = "center";
216
- element.style.backgroundRepeat = "no-repeat";
217
- element.style.backgroundSize = "contain";
218
- return;
219
- }
220
- element.textContent = icon.text ?? "";
157
+ element.textContent = "";
158
+ element.style.backgroundImage = "";
159
+ element.style.display = icon === void 0 ? "none" : "inline-flex";
160
+ if (icon === void 0) return;
161
+ element.style.filter = icon.filter ?? "";
162
+ if (icon.size !== void 0) {
163
+ element.style.width = icon.size;
164
+ element.style.height = icon.size;
165
+ }
166
+ if (icon.fontSize !== void 0) element.style.fontSize = icon.fontSize;
167
+ if (icon.url !== void 0) {
168
+ element.style.backgroundImage = iconCssUrl(icon.url);
169
+ element.style.backgroundPosition = "center";
170
+ element.style.backgroundRepeat = "no-repeat";
171
+ element.style.backgroundSize = "contain";
172
+ return;
173
+ }
174
+ element.textContent = icon.text ?? "";
221
175
  }
222
176
  function loadingTone(tone) {
223
- if (tone === "warning")
224
- return "#805300";
225
- if (tone === "error")
226
- return "#a00020";
227
- if (tone === "info")
228
- return "#176e9f";
229
- return "#35524c";
177
+ if (tone === "warning") return "#805300";
178
+ if (tone === "error") return "#a00020";
179
+ if (tone === "info") return "#176e9f";
180
+ return "#35524c";
230
181
  }
231
182
  function resolveAppShellLocale(input) {
232
- const preferred = globalThis.navigator?.language ?? "";
233
- return /^ja(?:-|$)/iu.test(preferred) ? "ja" : "en";
183
+ const preferred = input?.language ?? input?.languages?.[0] ?? globalThis.navigator?.language ?? "";
184
+ return /^ja(?:-|$)/iu.test(preferred) ? "ja" : "en";
234
185
  }
235
186
  function boundedText(value, limit = 2e3) {
236
- const text = String(value ?? "");
237
- const scalars = [...text];
238
- return scalars.length <= limit ? text : `${scalars.slice(0, limit - 1).join("")}...`;
187
+ const text = String(value ?? "");
188
+ const scalars = [...text];
189
+ return scalars.length <= limit ? text : `${scalars.slice(0, limit - 1).join("")}...`;
239
190
  }
191
+ /**
192
+ * Where the application menu places its actions: two columns of up to two rows, as it always has,
193
+ * and more columns and rows when there are more actions, so that every action stays on the stage.
194
+ * The band starts under the title area and ends above the status row; labels and icons shrink with
195
+ * the cells. An action's own `position` still overrides its cell.
196
+ */
240
197
  function applicationMenuGrid(count) {
241
- const columns = count <= 4 ? 2 : count <= 12 ? 3 : 4;
242
- const rows = Math.ceil(count / columns);
243
- const top = 25.5556;
244
- const bottom = rows <= 2 ? 80 : 90;
245
- const gapX = columns === 2 ? 6.6667 : 3.3333;
246
- const gapY = rows <= 2 ? 5.5556 : 2.7778;
247
- const width = (80 - (columns - 1) * gapX) / columns;
248
- const height = (bottom - top - (rows - 1) * gapY) / rows;
249
- const scale = Math.min(1, width / 36.6667, height / 24.4444);
250
- const percent = (value) => `${Number(value.toFixed(4))}%`;
251
- return {
252
- cell(index) {
253
- const row = Math.floor(index / columns);
254
- const column = index % columns;
255
- if (count <= 4) {
256
- return {
257
- left: column === 0 ? "10%" : "53.3333%",
258
- top: `${25.5556 + row * 30}%`,
259
- width: "36.6667%",
260
- height: "24.4444%"
261
- };
262
- }
263
- return {
264
- left: percent(10 + column * (width + gapX)),
265
- top: percent(top + row * (height + gapY)),
266
- width: percent(width),
267
- height: percent(height)
268
- };
269
- },
270
- cqw(size) {
271
- return `${count <= 4 ? size : Number((size * scale).toFixed(4))}cqw`;
272
- }
273
- };
198
+ const columns = count <= 4 ? 2 : count <= 12 ? 3 : 4;
199
+ const rows = Math.ceil(count / columns);
200
+ const top = 25.5556;
201
+ const bottom = rows <= 2 ? 80 : 90;
202
+ const gapX = columns === 2 ? 6.6667 : 3.3333;
203
+ const gapY = rows <= 2 ? 5.5556 : 2.7778;
204
+ const width = (80 - (columns - 1) * gapX) / columns;
205
+ const height = (bottom - top - (rows - 1) * gapY) / rows;
206
+ const scale = Math.min(1, width / 36.6667, height / 24.4444);
207
+ const percent = (value) => `${Number(value.toFixed(4))}%`;
208
+ return {
209
+ cell(index) {
210
+ const row = Math.floor(index / columns);
211
+ const column = index % columns;
212
+ if (count <= 4) return {
213
+ left: column === 0 ? "10%" : "53.3333%",
214
+ top: `${25.5556 + row * 30}%`,
215
+ width: "36.6667%",
216
+ height: "24.4444%"
217
+ };
218
+ return {
219
+ left: percent(10 + column * (width + gapX)),
220
+ top: percent(top + row * (height + gapY)),
221
+ width: percent(width),
222
+ height: percent(height)
223
+ };
224
+ },
225
+ cqw(size) {
226
+ return `${count <= 4 ? size : Number((size * scale).toFixed(4))}cqw`;
227
+ }
228
+ };
274
229
  }
275
230
  function createAppShellApplicationMenu(options) {
276
- if (!isRecord$1(options))
277
- throw new TypeError("application menu options must be an object.");
278
- const document = requireDocument$1(options.document);
279
- const mount = requireElement$1(options.mount, "mount");
280
- if (!Array.isArray(options.actions) || options.actions.length === 0) {
281
- throw new TypeError("actions must include at least one menu action.");
282
- }
283
- const fallbackLocale = optionalString(options.fallbackLocale, "fallbackLocale");
284
- const rootTestId = requireTestId(options.rootTestId, "rootTestId");
285
- const statusTestId = requireTestId(options.statusTestId, "statusTestId");
286
- const menuAttributes = options.attributes ?? {};
287
- if (!isRecord$1(menuAttributes))
288
- throw new TypeError("attributes must be an object.");
289
- const rootAttributes = requireAttributes(menuAttributes.root, "attributes.root");
290
- const statusAttributes = requireAttributes(menuAttributes.status, "attributes.status");
291
- const root = document.createElement("section");
292
- const status = document.createElement("p");
293
- const restoreMountPosition = restoreableMountPosition(document, mount);
294
- root.setAttribute("data-turbowarp-app-shell-application-menu", "true");
295
- root.setAttribute("aria-label", options.ariaLabel ?? "Application menu");
296
- root.style.cssText = "position:absolute;inset:0;z-index:2147483600;display:none;box-sizing:border-box;overflow:hidden;pointer-events:auto;font-family:sans-serif;container-type:inline-size;";
297
- root.style.position = "absolute";
298
- root.style.display = "none";
299
- root.style.cursor = "pointer";
300
- applyTestId(root, rootTestId);
301
- applyAttributes(root, rootAttributes);
302
- status.setAttribute("data-turbowarp-app-shell-menu-status", "true");
303
- status.setAttribute("role", "status");
304
- status.setAttribute("aria-live", "polite");
305
- status.style.cssText = "position:absolute;left:10%;top:93%;width:80%;margin:0;color:#35524c;font-size:2.7cqw;line-height:1.1;text-align:center;";
306
- applyTestId(status, statusTestId);
307
- applyAttributes(status, statusAttributes);
308
- const buttons = /* @__PURE__ */ new Map();
309
- const seen = /* @__PURE__ */ new Set();
310
- let locale = optionalString(options.initialLocale, "initialLocale") ?? resolveAppShellLocale();
311
- const grid = applicationMenuGrid(options.actions.length);
312
- for (const [index, definition] of options.actions.entries()) {
313
- if (!isRecord$1(definition))
314
- throw new TypeError(`actions.${index} must be an object.`);
315
- const id = requireString(definition.id, `actions.${index}.id`);
316
- if (seen.has(id))
317
- throw new TypeError(`Duplicate application menu action id: ${id}.`);
318
- seen.add(id);
319
- const labels = requireLocalizedLabels(definition.labels, `actions.${index}.labels`);
320
- const icon = requireIcon(definition.icon, `actions.${index}.icon`);
321
- const enabled = optionalBoolean(definition.enabled, `actions.${index}.enabled`, true);
322
- const visible = optionalBoolean(definition.visible, `actions.${index}.visible`, true);
323
- const testId = requireTestId(definition.testId, `actions.${index}.testId`);
324
- const position = requireRect(definition.position, `actions.${index}.position`);
325
- const actionAttributes = requireAttributes(definition.attributes, `actions.${index}.attributes`);
326
- if (typeof definition.onSelect !== "function") {
327
- throw new TypeError(`actions.${index}.onSelect must be a function.`);
328
- }
329
- const onSelect = definition.onSelect;
330
- const button = document.createElement("button");
331
- const iconElement = document.createElement("span");
332
- const label = document.createElement("span");
333
- const cell = grid.cell(index);
334
- button.type = "button";
335
- button.setAttribute("data-turbowarp-app-shell-menu-action", id);
336
- button.style.cssText = `position:absolute;left:${cell.left};top:${cell.top};width:${cell.width};height:${cell.height};display:flex;min-width:0;min-height:0;align-items:center;justify-content:center;flex-direction:column;gap:.4167cqw;border:.4167cqw solid #005f50;border-radius:2.9167cqw;background:#007d66;color:#fff;box-shadow:0 .625cqw 1.6667cqw rgba(0,0,0,.2);cursor:pointer;font:inherit;`;
337
- button.style.cursor = "pointer";
338
- applyTestId(button, testId);
339
- applyAttributes(button, actionAttributes);
340
- iconElement.setAttribute("aria-hidden", "true");
341
- iconElement.style.cssText = `display:inline-flex;width:${grid.cqw(10)};height:${grid.cqw(10)};align-items:center;justify-content:center;line-height:1;font-size:${grid.cqw(6)};`;
342
- label.style.cssText = `font-size:${grid.cqw(3.8)};line-height:1.15;text-align:center;`;
343
- button.appendChild(iconElement);
344
- button.appendChild(label);
345
- const onClick = (event) => {
346
- const current = buttons.get(id);
347
- if (current === void 0 || !current.enabled || !current.visible)
348
- return;
349
- invokeAction(current.onSelect, options.onError, event);
350
- };
351
- button.addEventListener("click", onClick);
352
- buttons.set(id, {
353
- button,
354
- icon: iconElement,
355
- label,
356
- labels,
357
- iconDefinition: icon,
358
- enabled,
359
- visible,
360
- position,
361
- onSelect,
362
- onClick
363
- });
364
- root.appendChild(button);
365
- }
366
- root.appendChild(status);
367
- mount.appendChild(root);
368
- let statusState = {
369
- text: options.status?.text ?? "",
370
- visible: options.status?.visible ?? false,
371
- tone: options.status?.tone ?? "neutral",
372
- color: optionalString(options.status?.color, "status.color")
373
- };
374
- if (typeof statusState.text !== "string")
375
- throw new TypeError("status.text must be a string.");
376
- if (typeof statusState.visible !== "boolean")
377
- throw new TypeError("status.visible must be a boolean.");
378
- if (!["neutral", "info", "warning", "error"].includes(statusState.tone)) {
379
- throw new TypeError("status.tone must be neutral, info, warning, or error.");
380
- }
381
- let disposed = false;
382
- function renderMenu() {
383
- for (const [id, value] of buttons) {
384
- const label = localized(value.labels, locale, fallbackLocale, `menu action ${id} labels`);
385
- value.label.textContent = label;
386
- value.button.setAttribute("aria-label", label);
387
- renderIcon(value.icon, value.iconDefinition);
388
- setButtonEnabled(value.button, value.enabled);
389
- setElementVisible(value.button, value.visible, "flex");
390
- value.button.style.boxShadow = value.enabled ? "0 .625cqw 1.6667cqw rgba(0,0,0,.2)" : "none";
391
- applyRect(value.button, value.position);
392
- }
393
- status.textContent = boundedText(statusState.text, 500);
394
- status.style.color = statusState.color ?? loadingTone(statusState.tone);
395
- setElementVisible(status, statusState.visible && statusState.text.length > 0, "block");
396
- }
397
- function ensureActive() {
398
- if (disposed)
399
- throw new TypeError("application menu is disposed.");
400
- }
401
- renderMenu();
402
- return Object.freeze({
403
- show(nextLocale) {
404
- ensureActive();
405
- locale = optionalString(nextLocale, "nextLocale") ?? locale;
406
- renderMenu();
407
- root.style.display = "block";
408
- return locale;
409
- },
410
- hide() {
411
- if (!disposed)
412
- root.style.display = "none";
413
- },
414
- setLocale(nextLocale) {
415
- ensureActive();
416
- locale = requireString(nextLocale, "nextLocale");
417
- renderMenu();
418
- return locale;
419
- },
420
- setActionState(id, state) {
421
- ensureActive();
422
- const action = buttons.get(requireString(id, "action id"));
423
- if (action === void 0)
424
- throw new TypeError(`Unknown application menu action: ${id}.`);
425
- if (!isRecord$1(state))
426
- throw new TypeError("application menu action state must be an object.");
427
- if (state.enabled !== void 0) {
428
- if (typeof state.enabled !== "boolean")
429
- throw new TypeError("action enabled must be a boolean.");
430
- action.enabled = state.enabled;
431
- }
432
- if (state.visible !== void 0) {
433
- if (typeof state.visible !== "boolean")
434
- throw new TypeError("action visible must be a boolean.");
435
- action.visible = state.visible;
436
- }
437
- if (state.labels !== void 0) {
438
- action.labels = requireLocalizedLabels(state.labels, "action state labels");
439
- }
440
- if (state.icon !== void 0) {
441
- action.iconDefinition = requireIcon(state.icon, "action state icon");
442
- }
443
- if (state.position !== void 0) {
444
- action.position = requireRect(state.position, "action state position");
445
- }
446
- renderMenu();
447
- },
448
- setStatus(nextStatus) {
449
- ensureActive();
450
- if (!isRecord$1(nextStatus))
451
- throw new TypeError("application menu status must be an object.");
452
- const nextToneValue = nextStatus["tone"] ?? statusState.tone;
453
- if (!["neutral", "info", "warning", "error"].includes(String(nextToneValue))) {
454
- throw new TypeError("status.tone must be neutral, info, warning, or error.");
455
- }
456
- const nextTone = nextToneValue;
457
- statusState = {
458
- text: optionalString(nextStatus["text"], "status.text") ?? statusState.text,
459
- visible: optionalBoolean(nextStatus["visible"], "status.visible", statusState.visible),
460
- tone: nextTone,
461
- color: optionalString(nextStatus["color"], "status.color") ?? statusState.color
462
- };
463
- renderMenu();
464
- },
465
- dispose() {
466
- if (disposed)
467
- return;
468
- disposed = true;
469
- for (const { button, onClick } of buttons.values()) {
470
- button.removeEventListener("click", onClick);
471
- }
472
- buttons.clear();
473
- root.remove();
474
- restoreMountPosition?.();
475
- },
476
- get element() {
477
- return root;
478
- }
479
- });
231
+ if (!isRecord$1(options)) throw new TypeError("application menu options must be an object.");
232
+ const document = requireDocument$1(options.document);
233
+ const mount = requireElement$1(options.mount, "mount");
234
+ if (!Array.isArray(options.actions) || options.actions.length === 0) throw new TypeError("actions must include at least one menu action.");
235
+ const fallbackLocale = optionalString(options.fallbackLocale, "fallbackLocale");
236
+ const rootTestId = requireTestId(options.rootTestId, "rootTestId");
237
+ const statusTestId = requireTestId(options.statusTestId, "statusTestId");
238
+ const menuAttributes = options.attributes ?? {};
239
+ if (!isRecord$1(menuAttributes)) throw new TypeError("attributes must be an object.");
240
+ const rootAttributes = requireAttributes(menuAttributes.root, "attributes.root");
241
+ const statusAttributes = requireAttributes(menuAttributes.status, "attributes.status");
242
+ const root = document.createElement("section");
243
+ const status = document.createElement("p");
244
+ const restoreMountPosition = restoreableMountPosition(document, mount);
245
+ root.setAttribute("data-turbowarp-app-shell-application-menu", "true");
246
+ root.setAttribute("aria-label", options.ariaLabel ?? "Application menu");
247
+ root.style.cssText = "position:absolute;inset:0;z-index:2147483600;display:none;box-sizing:border-box;overflow:hidden;pointer-events:auto;font-family:sans-serif;container-type:inline-size;";
248
+ root.style.position = "absolute";
249
+ root.style.display = "none";
250
+ root.style.cursor = "pointer";
251
+ applyTestId(root, rootTestId);
252
+ applyAttributes(root, rootAttributes);
253
+ status.setAttribute("data-turbowarp-app-shell-menu-status", "true");
254
+ status.setAttribute("role", "status");
255
+ status.setAttribute("aria-live", "polite");
256
+ status.style.cssText = "position:absolute;left:10%;top:93%;width:80%;margin:0;color:#35524c;font-size:2.7cqw;line-height:1.1;text-align:center;";
257
+ applyTestId(status, statusTestId);
258
+ applyAttributes(status, statusAttributes);
259
+ const buttons = /* @__PURE__ */ new Map();
260
+ const seen = /* @__PURE__ */ new Set();
261
+ let locale = optionalString(options.initialLocale, "initialLocale") ?? resolveAppShellLocale();
262
+ const grid = applicationMenuGrid(options.actions.length);
263
+ for (const [index, definition] of options.actions.entries()) {
264
+ if (!isRecord$1(definition)) throw new TypeError(`actions.${index} must be an object.`);
265
+ const id = requireString(definition.id, `actions.${index}.id`);
266
+ if (seen.has(id)) throw new TypeError(`Duplicate application menu action id: ${id}.`);
267
+ seen.add(id);
268
+ const labels = requireLocalizedLabels(definition.labels, `actions.${index}.labels`);
269
+ const icon = requireIcon(definition.icon, `actions.${index}.icon`);
270
+ const enabled = optionalBoolean(definition.enabled, `actions.${index}.enabled`, true);
271
+ const visible = optionalBoolean(definition.visible, `actions.${index}.visible`, true);
272
+ const testId = requireTestId(definition.testId, `actions.${index}.testId`);
273
+ const position = requireRect(definition.position, `actions.${index}.position`);
274
+ const actionAttributes = requireAttributes(definition.attributes, `actions.${index}.attributes`);
275
+ if (typeof definition.onSelect !== "function") throw new TypeError(`actions.${index}.onSelect must be a function.`);
276
+ const onSelect = definition.onSelect;
277
+ const button = document.createElement("button");
278
+ const iconElement = document.createElement("span");
279
+ const label = document.createElement("span");
280
+ const cell = grid.cell(index);
281
+ button.type = "button";
282
+ button.setAttribute("data-turbowarp-app-shell-menu-action", id);
283
+ button.style.cssText = `position:absolute;left:${cell.left};top:${cell.top};width:${cell.width};height:${cell.height};display:flex;min-width:0;min-height:0;align-items:center;justify-content:center;flex-direction:column;gap:.4167cqw;border:.4167cqw solid #005f50;border-radius:2.9167cqw;background:#007d66;color:#fff;box-shadow:0 .625cqw 1.6667cqw rgba(0,0,0,.2);cursor:pointer;font:inherit;`;
284
+ button.style.cursor = "pointer";
285
+ applyTestId(button, testId);
286
+ applyAttributes(button, actionAttributes);
287
+ iconElement.setAttribute("aria-hidden", "true");
288
+ iconElement.style.cssText = `display:inline-flex;width:${grid.cqw(10)};height:${grid.cqw(10)};align-items:center;justify-content:center;line-height:1;font-size:${grid.cqw(6)};`;
289
+ label.style.cssText = `font-size:${grid.cqw(3.8)};line-height:1.15;text-align:center;`;
290
+ button.appendChild(iconElement);
291
+ button.appendChild(label);
292
+ const onClick = (event) => {
293
+ const current = buttons.get(id);
294
+ if (current === void 0 || !current.enabled || !current.visible) return;
295
+ invokeAction(current.onSelect, options.onError, event);
296
+ };
297
+ button.addEventListener("click", onClick);
298
+ buttons.set(id, {
299
+ button,
300
+ icon: iconElement,
301
+ label,
302
+ labels,
303
+ iconDefinition: icon,
304
+ enabled,
305
+ visible,
306
+ position,
307
+ onSelect,
308
+ onClick
309
+ });
310
+ root.appendChild(button);
311
+ }
312
+ root.appendChild(status);
313
+ mount.appendChild(root);
314
+ let statusState = {
315
+ text: options.status?.text ?? "",
316
+ visible: options.status?.visible ?? false,
317
+ tone: options.status?.tone ?? "neutral",
318
+ color: optionalString(options.status?.color, "status.color")
319
+ };
320
+ if (typeof statusState.text !== "string") throw new TypeError("status.text must be a string.");
321
+ if (typeof statusState.visible !== "boolean") throw new TypeError("status.visible must be a boolean.");
322
+ if (![
323
+ "neutral",
324
+ "info",
325
+ "warning",
326
+ "error"
327
+ ].includes(statusState.tone)) throw new TypeError("status.tone must be neutral, info, warning, or error.");
328
+ let disposed = false;
329
+ function renderMenu() {
330
+ for (const [id, value] of buttons) {
331
+ const label = localized(value.labels, locale, fallbackLocale, `menu action ${id} labels`);
332
+ value.label.textContent = label;
333
+ value.button.setAttribute("aria-label", label);
334
+ renderIcon(value.icon, value.iconDefinition);
335
+ setButtonEnabled(value.button, value.enabled);
336
+ setElementVisible(value.button, value.visible, "flex");
337
+ value.button.style.boxShadow = value.enabled ? "0 .625cqw 1.6667cqw rgba(0,0,0,.2)" : "none";
338
+ applyRect(value.button, value.position);
339
+ }
340
+ status.textContent = boundedText(statusState.text, 500);
341
+ status.style.color = statusState.color ?? loadingTone(statusState.tone);
342
+ setElementVisible(status, statusState.visible && statusState.text.length > 0, "block");
343
+ }
344
+ function ensureActive() {
345
+ if (disposed) throw new TypeError("application menu is disposed.");
346
+ }
347
+ renderMenu();
348
+ return Object.freeze({
349
+ show(nextLocale) {
350
+ ensureActive();
351
+ locale = optionalString(nextLocale, "nextLocale") ?? locale;
352
+ renderMenu();
353
+ root.style.display = "block";
354
+ return locale;
355
+ },
356
+ hide() {
357
+ if (!disposed) root.style.display = "none";
358
+ },
359
+ setLocale(nextLocale) {
360
+ ensureActive();
361
+ locale = requireString(nextLocale, "nextLocale");
362
+ renderMenu();
363
+ return locale;
364
+ },
365
+ setActionState(id, state) {
366
+ ensureActive();
367
+ const action = buttons.get(requireString(id, "action id"));
368
+ if (action === void 0) throw new TypeError(`Unknown application menu action: ${id}.`);
369
+ if (!isRecord$1(state)) throw new TypeError("application menu action state must be an object.");
370
+ if (state.enabled !== void 0) {
371
+ if (typeof state.enabled !== "boolean") throw new TypeError("action enabled must be a boolean.");
372
+ action.enabled = state.enabled;
373
+ }
374
+ if (state.visible !== void 0) {
375
+ if (typeof state.visible !== "boolean") throw new TypeError("action visible must be a boolean.");
376
+ action.visible = state.visible;
377
+ }
378
+ if (state.labels !== void 0) action.labels = requireLocalizedLabels(state.labels, "action state labels");
379
+ if (state.icon !== void 0) action.iconDefinition = requireIcon(state.icon, "action state icon");
380
+ if (state.position !== void 0) action.position = requireRect(state.position, "action state position");
381
+ renderMenu();
382
+ },
383
+ setStatus(nextStatus) {
384
+ ensureActive();
385
+ if (!isRecord$1(nextStatus)) throw new TypeError("application menu status must be an object.");
386
+ const nextToneValue = nextStatus["tone"] ?? statusState.tone;
387
+ if (![
388
+ "neutral",
389
+ "info",
390
+ "warning",
391
+ "error"
392
+ ].includes(String(nextToneValue))) throw new TypeError("status.tone must be neutral, info, warning, or error.");
393
+ const nextTone = nextToneValue;
394
+ statusState = {
395
+ text: optionalString(nextStatus["text"], "status.text") ?? statusState.text,
396
+ visible: optionalBoolean(nextStatus["visible"], "status.visible", statusState.visible),
397
+ tone: nextTone,
398
+ color: optionalString(nextStatus["color"], "status.color") ?? statusState.color
399
+ };
400
+ renderMenu();
401
+ },
402
+ dispose() {
403
+ if (disposed) return;
404
+ disposed = true;
405
+ for (const { button, onClick } of buttons.values()) button.removeEventListener("click", onClick);
406
+ buttons.clear();
407
+ root.remove();
408
+ restoreMountPosition?.();
409
+ },
410
+ get element() {
411
+ return root;
412
+ }
413
+ });
480
414
  }
481
- const extensionConfig = {
482
- id: "kubohiroyaturbowarptitlemenu",
483
- name: "TurboWarp Title Menu",
484
- homepage: "https://github.com/kubohiroya/turbowarp-title-menu",
485
- docsURI: "https://kubohiroya.github.io/turbowarp-title-menu/",
486
- blockIconURI: "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA0OCA0OCI+PHJlY3QgeD0iNSIgeT0iOCIgd2lkdGg9IjM4IiBoZWlnaHQ9IjMyIiByeD0iNCIgZmlsbD0iIzAwN2Q2NiIvPjxyZWN0IHg9IjkiIHk9IjEyIiB3aWR0aD0iMzAiIGhlaWdodD0iMjQiIHJ4PSIyIiBmaWxsPSIjZjRmZmZiIi8+PHBhdGggZD0iTTE1IDE5aDE4TTE1IDI0aDE4TTE1IDI5aDEyIiBzdHJva2U9IiMwMDdkNjYiIHN0cm9rZS13aWR0aD0iMyIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIi8+PC9zdmc+"
415
+ //#endregion
416
+ //#region src/config.ts
417
+ var extensionConfig = {
418
+ id: "kubohiroyaturbowarptitlemenu",
419
+ slug: "turbowarp-title-menu",
420
+ name: "TurboWarp Title Menu",
421
+ description: "Reusable title, application menu, and DSL source storage controls for TurboWarp.",
422
+ author: "Hiroya Kubo",
423
+ license: "MPL-2.0",
424
+ unsandboxed: true,
425
+ homepage: "https://github.com/kubohiroya/turbowarp-title-menu",
426
+ docsURI: "https://kubohiroya.github.io/turbowarp-title-menu/",
427
+ blockIconURI: "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA0OCA0OCI+PHJlY3QgeD0iNSIgeT0iOCIgd2lkdGg9IjM4IiBoZWlnaHQ9IjMyIiByeD0iNCIgZmlsbD0iIzAwN2Q2NiIvPjxyZWN0IHg9IjkiIHk9IjEyIiB3aWR0aD0iMzAiIGhlaWdodD0iMjQiIHJ4PSIyIiBmaWxsPSIjZjRmZmZiIi8+PHBhdGggZD0iTTE1IDE5aDE4TTE1IDI0aDE4TTE1IDI5aDEyIiBzdHJva2U9IiMwMDdkNjYiIHN0cm9rZS13aWR0aD0iMyIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIi8+PC9zdmc+"
487
428
  };
429
+ //#endregion
430
+ //#region src/dom.ts
488
431
  function isRecord(value) {
489
- return typeof value === "object" && value !== null && !Array.isArray(value);
432
+ return typeof value === "object" && value !== null && !Array.isArray(value);
490
433
  }
491
434
  function requireDocument(value) {
492
- if (!isRecord(value) || typeof value.createElement !== "function") {
493
- throw new TypeError("document must provide createElement");
494
- }
495
- return value;
435
+ if (!isRecord(value) || typeof value.createElement !== "function") throw new TypeError("document must provide createElement");
436
+ return value;
496
437
  }
497
438
  function requireElement(value, name) {
498
- if (!isRecord(value) || typeof value.appendChild !== "function") {
499
- throw new TypeError(`${name} must be a DOM element`);
500
- }
501
- return value;
439
+ if (!isRecord(value) || typeof value.appendChild !== "function") throw new TypeError(`${name} must be a DOM element`);
440
+ return value;
502
441
  }
503
442
  function ensureRelativeMount(mount) {
504
- const previous = mount.style.position;
505
- if (previous === "" || previous === "static") {
506
- mount.style.position = "relative";
507
- return () => {
508
- mount.style.position = previous;
509
- };
510
- }
511
- return () => {
512
- };
443
+ const previous = mount.style.position;
444
+ if (previous === "" || previous === "static") {
445
+ mount.style.position = "relative";
446
+ return () => {
447
+ mount.style.position = previous;
448
+ };
449
+ }
450
+ return () => {};
513
451
  }
514
452
  function invokeSafely(operation, onError) {
515
- try {
516
- Promise.resolve(operation()).catch((error) => onError?.(error));
517
- } catch (error) {
518
- onError?.(error);
519
- }
453
+ try {
454
+ Promise.resolve(operation()).catch((error) => onError?.(error));
455
+ } catch (error) {
456
+ onError?.(error);
457
+ }
520
458
  }
521
- class DslStoreError extends Error {
522
- constructor(code, message, cause) {
523
- super(message, cause === void 0 ? void 0 : { cause });
524
- this.name = "DslStoreError";
525
- this.code = code;
526
- }
527
- }
528
- const defaultDslSort = Object.freeze({ field: "updatedAt", direction: "desc" });
529
- const fileStoreName = "files";
530
- const metaStoreName = "meta";
531
- const lastOpenedKey = "last-opened";
532
- const nameIndexName = "by-name";
533
- const encoder = new TextEncoder();
534
- const maximumNameLength = 200;
459
+ //#endregion
460
+ //#region src/dsl-store.ts
461
+ var DslStoreError = class extends Error {
462
+ constructor(code, message, cause) {
463
+ super(message, cause === void 0 ? void 0 : { cause });
464
+ this.name = "DslStoreError";
465
+ this.code = code;
466
+ }
467
+ };
468
+ var defaultDslSort = Object.freeze({
469
+ field: "updatedAt",
470
+ direction: "desc"
471
+ });
472
+ var fileStoreName = "files";
473
+ var metaStoreName = "meta";
474
+ var lastOpenedKey = "last-opened";
475
+ var nameIndexName = "by-name";
476
+ var encoder = new TextEncoder();
477
+ var maximumNameLength = 200;
478
+ /** Rejects control characters so a name cannot break the dialog's text rendering. */
535
479
  function hasControlCharacter(value) {
536
- for (const character of value) {
537
- const code = character.codePointAt(0) ?? 0;
538
- if (code < 32 || code === 127) return true;
539
- }
540
- return false;
480
+ for (const character of value) {
481
+ const code = character.codePointAt(0) ?? 0;
482
+ if (code < 32 || code === 127) return true;
483
+ }
484
+ return false;
541
485
  }
542
486
  function normalizeName(value) {
543
- if (typeof value !== "string") throw new DslStoreError("invalid-name", "DSL name must be a string.");
544
- const name = value.trim();
545
- if (name.length === 0) throw new DslStoreError("invalid-name", "DSL name must not be empty.");
546
- if (name.length > maximumNameLength) {
547
- throw new DslStoreError("invalid-name", `DSL name must be at most ${maximumNameLength} characters.`);
548
- }
549
- if (hasControlCharacter(name)) {
550
- throw new DslStoreError("invalid-name", "DSL name must not contain control characters.");
551
- }
552
- return name;
487
+ if (typeof value !== "string") throw new DslStoreError("invalid-name", "DSL name must be a string.");
488
+ const name = value.trim();
489
+ if (name.length === 0) throw new DslStoreError("invalid-name", "DSL name must not be empty.");
490
+ if (name.length > maximumNameLength) throw new DslStoreError("invalid-name", `DSL name must be at most ${maximumNameLength} characters.`);
491
+ if (hasControlCharacter(name)) throw new DslStoreError("invalid-name", "DSL name must not contain control characters.");
492
+ return name;
553
493
  }
554
494
  function request(input) {
555
- return new Promise((resolve, reject) => {
556
- input.onsuccess = () => resolve(input.result);
557
- input.onerror = () => reject(toStoreError(input.error));
558
- });
495
+ return new Promise((resolve, reject) => {
496
+ input.onsuccess = () => resolve(input.result);
497
+ input.onerror = () => reject(toStoreError(input.error));
498
+ });
559
499
  }
560
500
  function transactionDone(transaction) {
561
- return new Promise((resolve, reject) => {
562
- transaction.oncomplete = () => resolve();
563
- transaction.onabort = () => reject(toStoreError(transaction.error));
564
- transaction.onerror = () => reject(toStoreError(transaction.error));
565
- });
501
+ return new Promise((resolve, reject) => {
502
+ transaction.oncomplete = () => resolve();
503
+ transaction.onabort = () => reject(toStoreError(transaction.error));
504
+ transaction.onerror = () => reject(toStoreError(transaction.error));
505
+ });
566
506
  }
567
507
  function toStoreError(cause) {
568
- const name = cause?.name;
569
- if (name === "QuotaExceededError") {
570
- return new DslStoreError("quota", "Browser storage is full. Delete a saved DSL file first.", cause);
571
- }
572
- if (name === "ConstraintError") {
573
- return new DslStoreError("name-taken", "A DSL file with that name already exists.", cause);
574
- }
575
- return new DslStoreError("failed", "The DSL storage operation failed.", cause);
508
+ const name = cause?.name;
509
+ if (name === "QuotaExceededError") return new DslStoreError("quota", "Browser storage is full. Delete a saved DSL file first.", cause);
510
+ if (name === "ConstraintError") return new DslStoreError("name-taken", "A DSL file with that name already exists.", cause);
511
+ return new DslStoreError("failed", "The DSL storage operation failed.", cause);
576
512
  }
577
513
  function compareSummaries(sort) {
578
- const direction = sort.direction === "asc" ? 1 : -1;
579
- return (left, right) => {
580
- if (sort.field === "name") {
581
- return direction * left.name.localeCompare(right.name, void 0, { numeric: true });
582
- }
583
- if (sort.field === "byteLength") {
584
- return direction * (left.byteLength - right.byteLength) || left.name.localeCompare(right.name);
585
- }
586
- return direction * left.updatedAt.localeCompare(right.updatedAt) || left.name.localeCompare(right.name);
587
- };
514
+ const direction = sort.direction === "asc" ? 1 : -1;
515
+ return (left, right) => {
516
+ if (sort.field === "name") return direction * left.name.localeCompare(right.name, void 0, { numeric: true });
517
+ if (sort.field === "byteLength") return direction * (left.byteLength - right.byteLength) || left.name.localeCompare(right.name);
518
+ return direction * left.updatedAt.localeCompare(right.updatedAt) || left.name.localeCompare(right.name);
519
+ };
588
520
  }
589
521
  function toSummary(record) {
590
- return {
591
- id: record.id,
592
- name: record.name,
593
- byteLength: record.byteLength,
594
- savedAt: record.savedAt,
595
- updatedAt: record.updatedAt
596
- };
522
+ return {
523
+ id: record.id,
524
+ name: record.name,
525
+ byteLength: record.byteLength,
526
+ savedAt: record.savedAt,
527
+ updatedAt: record.updatedAt
528
+ };
597
529
  }
598
530
  function createDslStore(options = {}) {
599
- const factory = options.indexedDB ?? globalThis.indexedDB;
600
- if (factory === void 0 || typeof factory.open !== "function") {
601
- throw new DslStoreError("unavailable", "IndexedDB is not available in this environment.");
602
- }
603
- const databaseName = options.databaseName ?? "turbowarp-title-menu";
604
- const maxSourceBytes = options.maxSourceBytes ?? 1024 * 1024;
605
- const maxFileCount = options.maxFileCount ?? 64;
606
- const now = options.now ?? (() => /* @__PURE__ */ new Date());
607
- const createId = options.createId ?? defaultCreateId;
608
- let connection = null;
609
- function open() {
610
- connection ?? (connection = new Promise((resolve, reject) => {
611
- const opening = factory.open(databaseName, 1);
612
- opening.onupgradeneeded = () => {
613
- const database = opening.result;
614
- if (!database.objectStoreNames.contains(fileStoreName)) {
615
- const files = database.createObjectStore(fileStoreName, { keyPath: "id" });
616
- files.createIndex(nameIndexName, "name", { unique: true });
617
- }
618
- if (!database.objectStoreNames.contains(metaStoreName)) {
619
- database.createObjectStore(metaStoreName, { keyPath: "key" });
620
- }
621
- };
622
- opening.onsuccess = () => resolve(opening.result);
623
- opening.onerror = () => reject(toStoreError(opening.error));
624
- opening.onblocked = () => reject(new DslStoreError("failed", "Another tab is upgrading the DSL database."));
625
- }));
626
- return connection;
627
- }
628
- async function readAll() {
629
- const database = await open();
630
- const transaction = database.transaction(fileStoreName, "readonly");
631
- const records = await request(
632
- transaction.objectStore(fileStoreName).getAll()
633
- );
634
- await transactionDone(transaction);
635
- return records;
636
- }
637
- async function readOne(id) {
638
- const database = await open();
639
- const transaction = database.transaction(fileStoreName, "readonly");
640
- const record = await request(
641
- transaction.objectStore(fileStoreName).get(id)
642
- );
643
- await transactionDone(transaction);
644
- return record ?? null;
645
- }
646
- return Object.freeze({
647
- databaseName,
648
- async list(sort = defaultDslSort) {
649
- const records = await readAll();
650
- return records.map(toSummary).sort(compareSummaries(sort));
651
- },
652
- async count() {
653
- const database = await open();
654
- const transaction = database.transaction(fileStoreName, "readonly");
655
- const total = await request(transaction.objectStore(fileStoreName).count());
656
- await transactionDone(transaction);
657
- return total;
658
- },
659
- get(id) {
660
- return readOne(id);
661
- },
662
- async save(file) {
663
- const name = normalizeName(file.name);
664
- if (typeof file.source !== "string") {
665
- throw new DslStoreError("invalid-source", "DSL source must be a string.");
666
- }
667
- const byteLength = encoder.encode(file.source).byteLength;
668
- if (byteLength > maxSourceBytes) {
669
- throw new DslStoreError("too-large", `DSL source exceeds ${maxSourceBytes} bytes.`);
670
- }
671
- const database = await open();
672
- const transaction = database.transaction(fileStoreName, "readwrite");
673
- const files = transaction.objectStore(fileStoreName);
674
- const existing = await request(
675
- files.index(nameIndexName).get(name)
676
- );
677
- if (existing === void 0) {
678
- const total = await request(files.count());
679
- if (total >= maxFileCount) {
680
- transaction.abort();
681
- throw new DslStoreError("too-many", `The DSL store already holds ${maxFileCount} files.`);
682
- }
683
- }
684
- const timestamp = now().toISOString();
685
- const record = {
686
- id: existing?.id ?? createId(),
687
- name,
688
- source: file.source,
689
- byteLength,
690
- savedAt: existing?.savedAt ?? timestamp,
691
- updatedAt: timestamp
692
- };
693
- await request(files.put(record));
694
- await transactionDone(transaction);
695
- return record;
696
- },
697
- async rename(id, nextName) {
698
- const name = normalizeName(nextName);
699
- const database = await open();
700
- const transaction = database.transaction(fileStoreName, "readwrite");
701
- const files = transaction.objectStore(fileStoreName);
702
- const existing = await request(
703
- files.get(id)
704
- );
705
- if (existing === void 0) {
706
- transaction.abort();
707
- throw new DslStoreError("not-found", `No DSL file with id ${id}.`);
708
- }
709
- if (existing.name !== name) {
710
- const taken = await request(
711
- files.index(nameIndexName).get(name)
712
- );
713
- if (taken !== void 0) {
714
- transaction.abort();
715
- throw new DslStoreError("name-taken", `A DSL file named ${name} already exists.`);
716
- }
717
- }
718
- const record = { ...existing, name, updatedAt: now().toISOString() };
719
- await request(files.put(record));
720
- await transactionDone(transaction);
721
- return record;
722
- },
723
- async remove(id) {
724
- const database = await open();
725
- const transaction = database.transaction([fileStoreName, metaStoreName], "readwrite");
726
- await request(transaction.objectStore(fileStoreName).delete(id));
727
- const meta = transaction.objectStore(metaStoreName);
728
- const pointer = await request(
729
- meta.get(lastOpenedKey)
730
- );
731
- if (pointer?.id === id) await request(meta.delete(lastOpenedKey));
732
- await transactionDone(transaction);
733
- },
734
- async clear() {
735
- const database = await open();
736
- const transaction = database.transaction([fileStoreName, metaStoreName], "readwrite");
737
- await request(transaction.objectStore(fileStoreName).clear());
738
- await request(transaction.objectStore(metaStoreName).clear());
739
- await transactionDone(transaction);
740
- },
741
- async lastOpened() {
742
- const database = await open();
743
- const transaction = database.transaction(metaStoreName, "readonly");
744
- const pointer = await request(
745
- transaction.objectStore(metaStoreName).get(lastOpenedKey)
746
- );
747
- await transactionDone(transaction);
748
- if (pointer === void 0) return null;
749
- return readOne(pointer.id);
750
- },
751
- async markOpened(id) {
752
- const record = await readOne(id);
753
- if (record === null) throw new DslStoreError("not-found", `No DSL file with id ${id}.`);
754
- const database = await open();
755
- const transaction = database.transaction(metaStoreName, "readwrite");
756
- await request(transaction.objectStore(metaStoreName).put({ key: lastOpenedKey, id }));
757
- await transactionDone(transaction);
758
- },
759
- close() {
760
- const pending = connection;
761
- connection = null;
762
- void pending?.then((database) => database.close()).catch(() => void 0);
763
- }
764
- });
531
+ const factory = options.indexedDB ?? globalThis.indexedDB;
532
+ if (factory === void 0 || typeof factory.open !== "function") throw new DslStoreError("unavailable", "IndexedDB is not available in this environment.");
533
+ const databaseName = options.databaseName ?? "turbowarp-title-menu";
534
+ const maxSourceBytes = options.maxSourceBytes ?? 1048576;
535
+ const maxFileCount = options.maxFileCount ?? 64;
536
+ const now = options.now ?? (() => /* @__PURE__ */ new Date());
537
+ const createId = options.createId ?? defaultCreateId;
538
+ let connection = null;
539
+ function open() {
540
+ connection ?? (connection = new Promise((resolve, reject) => {
541
+ const opening = factory.open(databaseName, 1);
542
+ opening.onupgradeneeded = () => {
543
+ const database = opening.result;
544
+ if (!database.objectStoreNames.contains(fileStoreName)) database.createObjectStore(fileStoreName, { keyPath: "id" }).createIndex(nameIndexName, "name", { unique: true });
545
+ if (!database.objectStoreNames.contains(metaStoreName)) database.createObjectStore(metaStoreName, { keyPath: "key" });
546
+ };
547
+ opening.onsuccess = () => resolve(opening.result);
548
+ opening.onerror = () => reject(toStoreError(opening.error));
549
+ opening.onblocked = () => reject(new DslStoreError("failed", "Another tab is upgrading the DSL database."));
550
+ }));
551
+ return connection;
552
+ }
553
+ async function readAll() {
554
+ const transaction = (await open()).transaction(fileStoreName, "readonly");
555
+ const records = await request(transaction.objectStore(fileStoreName).getAll());
556
+ await transactionDone(transaction);
557
+ return records;
558
+ }
559
+ async function readOne(id) {
560
+ const transaction = (await open()).transaction(fileStoreName, "readonly");
561
+ const record = await request(transaction.objectStore(fileStoreName).get(id));
562
+ await transactionDone(transaction);
563
+ return record ?? null;
564
+ }
565
+ return Object.freeze({
566
+ databaseName,
567
+ async list(sort = defaultDslSort) {
568
+ return (await readAll()).map(toSummary).sort(compareSummaries(sort));
569
+ },
570
+ async count() {
571
+ const transaction = (await open()).transaction(fileStoreName, "readonly");
572
+ const total = await request(transaction.objectStore(fileStoreName).count());
573
+ await transactionDone(transaction);
574
+ return total;
575
+ },
576
+ get(id) {
577
+ return readOne(id);
578
+ },
579
+ async save(file) {
580
+ const name = normalizeName(file.name);
581
+ if (typeof file.source !== "string") throw new DslStoreError("invalid-source", "DSL source must be a string.");
582
+ const byteLength = encoder.encode(file.source).byteLength;
583
+ if (byteLength > maxSourceBytes) throw new DslStoreError("too-large", `DSL source exceeds ${maxSourceBytes} bytes.`);
584
+ const transaction = (await open()).transaction(fileStoreName, "readwrite");
585
+ const files = transaction.objectStore(fileStoreName);
586
+ const existing = await request(files.index(nameIndexName).get(name));
587
+ if (existing === void 0) {
588
+ if (await request(files.count()) >= maxFileCount) {
589
+ transaction.abort();
590
+ throw new DslStoreError("too-many", `The DSL store already holds ${maxFileCount} files.`);
591
+ }
592
+ }
593
+ const timestamp = now().toISOString();
594
+ const record = {
595
+ id: existing?.id ?? createId(),
596
+ name,
597
+ source: file.source,
598
+ byteLength,
599
+ savedAt: existing?.savedAt ?? timestamp,
600
+ updatedAt: timestamp
601
+ };
602
+ await request(files.put(record));
603
+ await transactionDone(transaction);
604
+ return record;
605
+ },
606
+ async rename(id, nextName) {
607
+ const name = normalizeName(nextName);
608
+ const transaction = (await open()).transaction(fileStoreName, "readwrite");
609
+ const files = transaction.objectStore(fileStoreName);
610
+ const existing = await request(files.get(id));
611
+ if (existing === void 0) {
612
+ transaction.abort();
613
+ throw new DslStoreError("not-found", `No DSL file with id ${id}.`);
614
+ }
615
+ if (existing.name !== name) {
616
+ if (await request(files.index(nameIndexName).get(name)) !== void 0) {
617
+ transaction.abort();
618
+ throw new DslStoreError("name-taken", `A DSL file named ${name} already exists.`);
619
+ }
620
+ }
621
+ const record = {
622
+ ...existing,
623
+ name,
624
+ updatedAt: now().toISOString()
625
+ };
626
+ await request(files.put(record));
627
+ await transactionDone(transaction);
628
+ return record;
629
+ },
630
+ async remove(id) {
631
+ const transaction = (await open()).transaction([fileStoreName, metaStoreName], "readwrite");
632
+ await request(transaction.objectStore(fileStoreName).delete(id));
633
+ const meta = transaction.objectStore(metaStoreName);
634
+ if ((await request(meta.get(lastOpenedKey)))?.id === id) await request(meta.delete(lastOpenedKey));
635
+ await transactionDone(transaction);
636
+ },
637
+ async clear() {
638
+ const transaction = (await open()).transaction([fileStoreName, metaStoreName], "readwrite");
639
+ await request(transaction.objectStore(fileStoreName).clear());
640
+ await request(transaction.objectStore(metaStoreName).clear());
641
+ await transactionDone(transaction);
642
+ },
643
+ async lastOpened() {
644
+ const transaction = (await open()).transaction(metaStoreName, "readonly");
645
+ const pointer = await request(transaction.objectStore(metaStoreName).get(lastOpenedKey));
646
+ await transactionDone(transaction);
647
+ if (pointer === void 0) return null;
648
+ return readOne(pointer.id);
649
+ },
650
+ async markOpened(id) {
651
+ if (await readOne(id) === null) throw new DslStoreError("not-found", `No DSL file with id ${id}.`);
652
+ const transaction = (await open()).transaction(metaStoreName, "readwrite");
653
+ await request(transaction.objectStore(metaStoreName).put({
654
+ key: lastOpenedKey,
655
+ id
656
+ }));
657
+ await transactionDone(transaction);
658
+ },
659
+ close() {
660
+ const pending = connection;
661
+ connection = null;
662
+ pending?.then((database) => database.close()).catch(() => void 0);
663
+ }
664
+ });
765
665
  }
766
666
  function defaultCreateId() {
767
- const crypto = globalThis.crypto;
768
- if (typeof crypto?.randomUUID === "function") return crypto.randomUUID();
769
- return `dsl-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
667
+ const crypto = globalThis.crypto;
668
+ if (typeof crypto?.randomUUID === "function") return crypto.randomUUID();
669
+ return `dsl-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
770
670
  }
771
- async function readDslFile(file, maxSourceBytes = 1024 * 1024) {
772
- if (typeof file?.text !== "function") {
773
- throw new DslStoreError("invalid-source", "file must be a browser File.");
774
- }
775
- if (file.size > maxSourceBytes) {
776
- throw new DslStoreError("too-large", `DSL file exceeds ${maxSourceBytes} bytes.`);
777
- }
778
- return { name: file.name, source: await file.text() };
671
+ /** Reads a picked browser file into a record shape the store accepts. */
672
+ async function readDslFile(file, maxSourceBytes = 1048576) {
673
+ if (typeof file?.text !== "function") throw new DslStoreError("invalid-source", "file must be a browser File.");
674
+ if (file.size > maxSourceBytes) throw new DslStoreError("too-large", `DSL file exceeds ${maxSourceBytes} bytes.`);
675
+ return {
676
+ name: file.name,
677
+ source: await file.text()
678
+ };
779
679
  }
780
- const defaultSortDirections = Object.freeze({
781
- name: "asc",
782
- updatedAt: "desc",
783
- byteLength: "desc"
680
+ //#endregion
681
+ //#region src/dsl-files-dialog.ts
682
+ var defaultSortDirections = Object.freeze({
683
+ name: "asc",
684
+ updatedAt: "desc",
685
+ byteLength: "desc"
784
686
  });
785
687
  function requireLocales(value) {
786
- if (!isRecord(value) || Object.keys(value).length === 0) {
787
- throw new TypeError("locales must contain at least one locale");
788
- }
789
- return value;
688
+ if (!isRecord(value) || Object.keys(value).length === 0) throw new TypeError("locales must contain at least one locale");
689
+ return value;
790
690
  }
791
691
  function textFor(locales, locale) {
792
- const text = locales[locale] ?? locales["en"] ?? Object.values(locales)[0];
793
- if (text === void 0) throw new TypeError("locales must contain at least one locale");
794
- return text;
692
+ const text = locales[locale] ?? locales["en"] ?? Object.values(locales)[0];
693
+ if (text === void 0) throw new TypeError("locales must contain at least one locale");
694
+ return text;
795
695
  }
796
696
  function defaultFormatSize(byteLength) {
797
- if (byteLength < 1024) return `${byteLength} B`;
798
- if (byteLength < 1024 * 1024) return `${(byteLength / 1024).toFixed(1)} KB`;
799
- return `${(byteLength / (1024 * 1024)).toFixed(1)} MB`;
697
+ if (byteLength < 1024) return `${byteLength} B`;
698
+ if (byteLength < 1048576) return `${(byteLength / 1024).toFixed(1)} KB`;
699
+ return `${(byteLength / 1048576).toFixed(1)} MB`;
800
700
  }
801
701
  function defaultFormatDate(isoDate) {
802
- const parsed = new Date(isoDate);
803
- if (Number.isNaN(parsed.getTime())) return isoDate;
804
- const pad = (value) => String(value).padStart(2, "0");
805
- return `${parsed.getFullYear()}-${pad(parsed.getMonth() + 1)}-${pad(parsed.getDate())} ${pad(parsed.getHours())}:${pad(parsed.getMinutes())}`;
702
+ const parsed = new Date(isoDate);
703
+ if (Number.isNaN(parsed.getTime())) return isoDate;
704
+ const pad = (value) => String(value).padStart(2, "0");
705
+ return `${parsed.getFullYear()}-${pad(parsed.getMonth() + 1)}-${pad(parsed.getDate())} ${pad(parsed.getHours())}:${pad(parsed.getMinutes())}`;
806
706
  }
807
707
  function defaultDescribeError(error) {
808
- if (error instanceof Error && error.message.length > 0) return error.message;
809
- return String(error);
708
+ if (error instanceof Error && error.message.length > 0) return error.message;
709
+ return String(error);
810
710
  }
811
711
  function createDslFilesDialog(options) {
812
- if (!isRecord(options)) throw new TypeError("DSL files dialog options must be an object");
813
- const document = requireDocument(options.document ?? globalThis.document);
814
- const mount = requireElement(options.mount ?? document.body, "mount");
815
- const locales = requireLocales(options.locales);
816
- const describeError = options.describeError ?? defaultDescribeError;
817
- const formatSize = options.formatSize ?? defaultFormatSize;
818
- const formatDate = options.formatDate ?? defaultFormatDate;
819
- let locale = options.initialLocale ?? "en";
820
- let sort = options.initialSort ?? defaultDslSort;
821
- let summaries = [];
822
- let renamingId = null;
823
- let confirmingRemovalId = null;
824
- let status = "";
825
- let disposed = false;
826
- const root = document.createElement("section");
827
- const panel = document.createElement("div");
828
- const heading = document.createElement("h1");
829
- const closeButton = document.createElement("button");
830
- const toolbar = document.createElement("div");
831
- const addButton = document.createElement("button");
832
- const sortBar = document.createElement("div");
833
- const listElement = document.createElement("div");
834
- const statusElement = document.createElement("p");
835
- root.setAttribute("data-turbowarp-title-menu-dsl-files", "true");
836
- root.style.cssText = "position:absolute;inset:0;z-index:2147483646;align-items:center;justify-content:center;padding:16px;box-sizing:border-box;background:rgba(0,0,0,.6);font-family:sans-serif;";
837
- root.style.display = "none";
838
- panel.style.cssText = "width:min(720px,96%);max-height:90%;display:flex;flex-direction:column;gap:10px;padding:18px;box-sizing:border-box;background:#ffffff;color:#1b1f27;border-radius:10px;box-shadow:0 10px 36px rgba(0,0,0,.45);overflow:hidden;";
839
- heading.style.cssText = "margin:0;font-size:20px;line-height:1.3;";
840
- toolbar.style.cssText = "display:flex;gap:8px;align-items:center;flex-wrap:wrap;";
841
- sortBar.style.cssText = "display:flex;gap:6px;align-items:center;flex-wrap:wrap;";
842
- listElement.style.cssText = "flex:1;min-height:0;overflow:auto;display:flex;flex-direction:column;gap:6px;";
843
- statusElement.style.cssText = "margin:0;min-height:18px;font-size:13px;color:#8a1c1c;";
844
- const headerRow = document.createElement("div");
845
- headerRow.style.cssText = "display:flex;align-items:center;justify-content:space-between;gap:8px;";
846
- headerRow.appendChild(heading);
847
- headerRow.appendChild(closeButton);
848
- panel.appendChild(headerRow);
849
- toolbar.appendChild(addButton);
850
- toolbar.appendChild(sortBar);
851
- panel.appendChild(toolbar);
852
- panel.appendChild(listElement);
853
- panel.appendChild(statusElement);
854
- root.appendChild(panel);
855
- const previousMountPosition = mount.style.position;
856
- if (previousMountPosition === "" || previousMountPosition === "static") {
857
- mount.style.position = "relative";
858
- }
859
- mount.appendChild(root);
860
- function styleButton(button, tone) {
861
- const palette = {
862
- primary: "background:#1f6feb;color:#ffffff;border:1px solid #1f6feb;",
863
- plain: "background:#f2f4f8;color:#1b1f27;border:1px solid #ccd2de;",
864
- danger: "background:#b42318;color:#ffffff;border:1px solid #b42318;",
865
- active: "background:#d7e6ff;color:#0b3a82;border:1px solid #1f6feb;"
866
- }[tone];
867
- button.style.cssText = `${palette}padding:5px 10px;border-radius:6px;font-size:13px;cursor:pointer;`;
868
- }
869
- function run(operation) {
870
- try {
871
- Promise.resolve(operation()).catch(handleFailure);
872
- } catch (error) {
873
- handleFailure(error);
874
- }
875
- }
876
- function handleFailure(error) {
877
- status = describeError(error);
878
- options.onError?.(error);
879
- render();
880
- }
881
- function mutate(operation) {
882
- run(async () => {
883
- status = "";
884
- try {
885
- await operation();
886
- } catch (error) {
887
- status = describeError(error);
888
- options.onError?.(error);
889
- render();
890
- return;
891
- }
892
- await reload();
893
- });
894
- }
895
- async function reload() {
896
- if (disposed) return;
897
- summaries = await options.list(sort);
898
- render();
899
- }
900
- function selectSort(field) {
901
- if (sort.field === field) {
902
- sort = { field, direction: sort.direction === "asc" ? "desc" : "asc" };
903
- } else {
904
- sort = { field, direction: defaultSortDirections[field] };
905
- }
906
- renamingId = null;
907
- confirmingRemovalId = null;
908
- mutate(() => void 0);
909
- }
910
- function createButton(label, tone, onClick) {
911
- const button = document.createElement("button");
912
- button.type = "button";
913
- button.textContent = label;
914
- styleButton(button, tone);
915
- button.addEventListener("click", onClick);
916
- return button;
917
- }
918
- function renderSortBar(text) {
919
- const arrow = sort.direction === "asc" ? " ▲" : " ▼";
920
- const fields = [
921
- ["name", text.sortByName],
922
- ["updatedAt", text.sortByDate],
923
- ["byteLength", text.sortBySize]
924
- ];
925
- for (const [field, label] of fields) {
926
- const active = sort.field === field;
927
- const button = createButton(
928
- active ? `${label}${arrow}` : label,
929
- active ? "active" : "plain",
930
- () => selectSort(field)
931
- );
932
- button.setAttribute("data-sort-field", field);
933
- if (active) button.setAttribute("aria-pressed", "true");
934
- sortBar.appendChild(button);
935
- }
936
- }
937
- function renderRow(summary, text) {
938
- const row = document.createElement("div");
939
- row.setAttribute("data-dsl-file-id", summary.id);
940
- row.style.cssText = "display:flex;align-items:center;gap:8px;padding:8px;border:1px solid #e2e6ee;border-radius:8px;";
941
- if (renamingId === summary.id) {
942
- const input = document.createElement("input");
943
- input.type = "text";
944
- input.value = summary.name;
945
- input.setAttribute("data-rename-input", summary.id);
946
- input.style.cssText = "flex:1;min-width:0;padding:5px 8px;border:1px solid #1f6feb;border-radius:6px;font-size:14px;";
947
- const commit = () => {
948
- const nextName = input.value;
949
- renamingId = null;
950
- mutate(() => options.onRename(summary.id, nextName));
951
- };
952
- input.addEventListener("keydown", (event) => {
953
- const key = event.key;
954
- if (key === "Enter") commit();
955
- if (key === "Escape") {
956
- renamingId = null;
957
- render();
958
- }
959
- });
960
- row.appendChild(input);
961
- row.appendChild(createButton(text.confirm, "primary", commit));
962
- row.appendChild(
963
- createButton(text.cancel, "plain", () => {
964
- renamingId = null;
965
- render();
966
- })
967
- );
968
- return row;
969
- }
970
- const name = document.createElement("span");
971
- name.textContent = summary.name;
972
- name.style.cssText = "flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:14px;";
973
- const date = document.createElement("span");
974
- date.textContent = formatDate(summary.updatedAt);
975
- date.style.cssText = "font-size:12px;color:#5a6172;white-space:nowrap;";
976
- const size = document.createElement("span");
977
- size.textContent = formatSize(summary.byteLength);
978
- size.style.cssText = "font-size:12px;color:#5a6172;white-space:nowrap;min-width:64px;text-align:right;";
979
- row.appendChild(name);
980
- row.appendChild(date);
981
- row.appendChild(size);
982
- if (confirmingRemovalId === summary.id) {
983
- row.appendChild(
984
- createButton(text.confirmRemove, "danger", () => {
985
- confirmingRemovalId = null;
986
- mutate(() => options.onRemove(summary.id));
987
- })
988
- );
989
- row.appendChild(
990
- createButton(text.cancel, "plain", () => {
991
- confirmingRemovalId = null;
992
- render();
993
- })
994
- );
995
- return row;
996
- }
997
- row.appendChild(
998
- createButton(text.open, "primary", () => {
999
- mutate(() => options.onOpen(summary.id));
1000
- })
1001
- );
1002
- row.appendChild(
1003
- createButton(text.rename, "plain", () => {
1004
- renamingId = summary.id;
1005
- confirmingRemovalId = null;
1006
- render();
1007
- })
1008
- );
1009
- row.appendChild(
1010
- createButton(text.remove, "plain", () => {
1011
- confirmingRemovalId = summary.id;
1012
- renamingId = null;
1013
- render();
1014
- })
1015
- );
1016
- return row;
1017
- }
1018
- function render() {
1019
- if (disposed) return;
1020
- const text = textFor(locales, locale);
1021
- heading.textContent = text.title;
1022
- closeButton.textContent = text.close;
1023
- closeButton.setAttribute("aria-label", text.close);
1024
- addButton.textContent = text.add;
1025
- statusElement.textContent = status;
1026
- sortBar.replaceChildren();
1027
- renderSortBar(text);
1028
- listElement.replaceChildren();
1029
- if (summaries.length === 0) {
1030
- const empty = document.createElement("p");
1031
- empty.textContent = text.empty;
1032
- empty.style.cssText = "margin:8px 0;font-size:14px;color:#5a6172;";
1033
- listElement.appendChild(empty);
1034
- } else {
1035
- for (const summary of summaries) listElement.appendChild(renderRow(summary, text));
1036
- }
1037
- }
1038
- styleButton(closeButton, "plain");
1039
- styleButton(addButton, "primary");
1040
- closeButton.type = "button";
1041
- addButton.type = "button";
1042
- closeButton.addEventListener("click", () => hide());
1043
- addButton.addEventListener("click", () => {
1044
- mutate(() => options.onAdd());
1045
- });
1046
- function hide() {
1047
- if (disposed) return;
1048
- renamingId = null;
1049
- confirmingRemovalId = null;
1050
- root.style.display = "none";
1051
- }
1052
- function ensureActive() {
1053
- if (disposed) throw new TypeError("DSL files dialog is disposed");
1054
- }
1055
- render();
1056
- return Object.freeze({
1057
- element: root,
1058
- get locale() {
1059
- return locale;
1060
- },
1061
- get sort() {
1062
- return sort;
1063
- },
1064
- async show(nextLocale) {
1065
- ensureActive();
1066
- if (nextLocale !== void 0) locale = nextLocale;
1067
- status = "";
1068
- root.style.display = "flex";
1069
- await reload();
1070
- return locale;
1071
- },
1072
- hide,
1073
- async refresh() {
1074
- ensureActive();
1075
- await reload();
1076
- },
1077
- setLocale(nextLocale) {
1078
- ensureActive();
1079
- locale = nextLocale;
1080
- render();
1081
- return locale;
1082
- },
1083
- dispose() {
1084
- if (disposed) return;
1085
- disposed = true;
1086
- root.remove();
1087
- if (previousMountPosition === "" || previousMountPosition === "static") {
1088
- mount.style.position = previousMountPosition;
1089
- }
1090
- }
1091
- });
712
+ if (!isRecord(options)) throw new TypeError("DSL files dialog options must be an object");
713
+ const document = requireDocument(options.document ?? globalThis.document);
714
+ const mount = requireElement(options.mount ?? document.body, "mount");
715
+ const locales = requireLocales(options.locales);
716
+ const describeError = options.describeError ?? defaultDescribeError;
717
+ const formatSize = options.formatSize ?? defaultFormatSize;
718
+ const formatDate = options.formatDate ?? defaultFormatDate;
719
+ let locale = options.initialLocale ?? "en";
720
+ let sort = options.initialSort ?? defaultDslSort;
721
+ let summaries = [];
722
+ let renamingId = null;
723
+ let confirmingRemovalId = null;
724
+ let status = "";
725
+ let disposed = false;
726
+ const root = document.createElement("section");
727
+ const panel = document.createElement("div");
728
+ const heading = document.createElement("h1");
729
+ const closeButton = document.createElement("button");
730
+ const toolbar = document.createElement("div");
731
+ const addButton = document.createElement("button");
732
+ const sortBar = document.createElement("div");
733
+ const listElement = document.createElement("div");
734
+ const statusElement = document.createElement("p");
735
+ root.setAttribute("data-turbowarp-title-menu-dsl-files", "true");
736
+ root.style.cssText = "position:absolute;inset:0;z-index:2147483646;align-items:center;justify-content:center;padding:16px;box-sizing:border-box;background:rgba(0,0,0,.6);font-family:sans-serif;";
737
+ root.style.display = "none";
738
+ panel.style.cssText = "width:min(720px,96%);max-height:90%;display:flex;flex-direction:column;gap:10px;padding:18px;box-sizing:border-box;background:#ffffff;color:#1b1f27;border-radius:10px;box-shadow:0 10px 36px rgba(0,0,0,.45);overflow:hidden;";
739
+ heading.style.cssText = "margin:0;font-size:20px;line-height:1.3;";
740
+ toolbar.style.cssText = "display:flex;gap:8px;align-items:center;flex-wrap:wrap;";
741
+ sortBar.style.cssText = "display:flex;gap:6px;align-items:center;flex-wrap:wrap;";
742
+ listElement.style.cssText = "flex:1;min-height:0;overflow:auto;display:flex;flex-direction:column;gap:6px;";
743
+ statusElement.style.cssText = "margin:0;min-height:18px;font-size:13px;color:#8a1c1c;";
744
+ const headerRow = document.createElement("div");
745
+ headerRow.style.cssText = "display:flex;align-items:center;justify-content:space-between;gap:8px;";
746
+ headerRow.appendChild(heading);
747
+ headerRow.appendChild(closeButton);
748
+ panel.appendChild(headerRow);
749
+ toolbar.appendChild(addButton);
750
+ toolbar.appendChild(sortBar);
751
+ panel.appendChild(toolbar);
752
+ panel.appendChild(listElement);
753
+ panel.appendChild(statusElement);
754
+ root.appendChild(panel);
755
+ const previousMountPosition = mount.style.position;
756
+ if (previousMountPosition === "" || previousMountPosition === "static") mount.style.position = "relative";
757
+ mount.appendChild(root);
758
+ function styleButton(button, tone) {
759
+ const palette = {
760
+ primary: "background:#1f6feb;color:#ffffff;border:1px solid #1f6feb;",
761
+ plain: "background:#f2f4f8;color:#1b1f27;border:1px solid #ccd2de;",
762
+ danger: "background:#b42318;color:#ffffff;border:1px solid #b42318;",
763
+ active: "background:#d7e6ff;color:#0b3a82;border:1px solid #1f6feb;"
764
+ }[tone];
765
+ button.style.cssText = `${palette}padding:5px 10px;border-radius:6px;font-size:13px;cursor:pointer;`;
766
+ }
767
+ function run(operation) {
768
+ try {
769
+ Promise.resolve(operation()).catch(handleFailure);
770
+ } catch (error) {
771
+ handleFailure(error);
772
+ }
773
+ }
774
+ function handleFailure(error) {
775
+ status = describeError(error);
776
+ options.onError?.(error);
777
+ render();
778
+ }
779
+ /** Every mutation goes through here so the list and the status line stay in step. */
780
+ function mutate(operation) {
781
+ run(async () => {
782
+ status = "";
783
+ try {
784
+ await operation();
785
+ } catch (error) {
786
+ status = describeError(error);
787
+ options.onError?.(error);
788
+ render();
789
+ return;
790
+ }
791
+ await reload();
792
+ });
793
+ }
794
+ async function reload() {
795
+ if (disposed) return;
796
+ summaries = await options.list(sort);
797
+ render();
798
+ }
799
+ function selectSort(field) {
800
+ if (sort.field === field) sort = {
801
+ field,
802
+ direction: sort.direction === "asc" ? "desc" : "asc"
803
+ };
804
+ else sort = {
805
+ field,
806
+ direction: defaultSortDirections[field]
807
+ };
808
+ renamingId = null;
809
+ confirmingRemovalId = null;
810
+ mutate(() => void 0);
811
+ }
812
+ function createButton(label, tone, onClick) {
813
+ const button = document.createElement("button");
814
+ button.type = "button";
815
+ button.textContent = label;
816
+ styleButton(button, tone);
817
+ button.addEventListener("click", onClick);
818
+ return button;
819
+ }
820
+ function renderSortBar(text) {
821
+ const arrow = sort.direction === "asc" ? " ▲" : " ▼";
822
+ const fields = [
823
+ ["name", text.sortByName],
824
+ ["updatedAt", text.sortByDate],
825
+ ["byteLength", text.sortBySize]
826
+ ];
827
+ for (const [field, label] of fields) {
828
+ const active = sort.field === field;
829
+ const button = createButton(active ? `${label}${arrow}` : label, active ? "active" : "plain", () => selectSort(field));
830
+ button.setAttribute("data-sort-field", field);
831
+ if (active) button.setAttribute("aria-pressed", "true");
832
+ sortBar.appendChild(button);
833
+ }
834
+ }
835
+ function renderRow(summary, text) {
836
+ const row = document.createElement("div");
837
+ row.setAttribute("data-dsl-file-id", summary.id);
838
+ row.style.cssText = "display:flex;align-items:center;gap:8px;padding:8px;border:1px solid #e2e6ee;border-radius:8px;";
839
+ if (renamingId === summary.id) {
840
+ const input = document.createElement("input");
841
+ input.type = "text";
842
+ input.value = summary.name;
843
+ input.setAttribute("data-rename-input", summary.id);
844
+ input.style.cssText = "flex:1;min-width:0;padding:5px 8px;border:1px solid #1f6feb;border-radius:6px;font-size:14px;";
845
+ const commit = () => {
846
+ const nextName = input.value;
847
+ renamingId = null;
848
+ mutate(() => options.onRename(summary.id, nextName));
849
+ };
850
+ input.addEventListener("keydown", (event) => {
851
+ const key = event.key;
852
+ if (key === "Enter") commit();
853
+ if (key === "Escape") {
854
+ renamingId = null;
855
+ render();
856
+ }
857
+ });
858
+ row.appendChild(input);
859
+ row.appendChild(createButton(text.confirm, "primary", commit));
860
+ row.appendChild(createButton(text.cancel, "plain", () => {
861
+ renamingId = null;
862
+ render();
863
+ }));
864
+ return row;
865
+ }
866
+ const name = document.createElement("span");
867
+ name.textContent = summary.name;
868
+ name.style.cssText = "flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:14px;";
869
+ const date = document.createElement("span");
870
+ date.textContent = formatDate(summary.updatedAt);
871
+ date.style.cssText = "font-size:12px;color:#5a6172;white-space:nowrap;";
872
+ const size = document.createElement("span");
873
+ size.textContent = formatSize(summary.byteLength);
874
+ size.style.cssText = "font-size:12px;color:#5a6172;white-space:nowrap;min-width:64px;text-align:right;";
875
+ row.appendChild(name);
876
+ row.appendChild(date);
877
+ row.appendChild(size);
878
+ if (confirmingRemovalId === summary.id) {
879
+ row.appendChild(createButton(text.confirmRemove, "danger", () => {
880
+ confirmingRemovalId = null;
881
+ mutate(() => options.onRemove(summary.id));
882
+ }));
883
+ row.appendChild(createButton(text.cancel, "plain", () => {
884
+ confirmingRemovalId = null;
885
+ render();
886
+ }));
887
+ return row;
888
+ }
889
+ row.appendChild(createButton(text.open, "primary", () => {
890
+ mutate(() => options.onOpen(summary.id));
891
+ }));
892
+ row.appendChild(createButton(text.rename, "plain", () => {
893
+ renamingId = summary.id;
894
+ confirmingRemovalId = null;
895
+ render();
896
+ }));
897
+ row.appendChild(createButton(text.remove, "plain", () => {
898
+ confirmingRemovalId = summary.id;
899
+ renamingId = null;
900
+ render();
901
+ }));
902
+ return row;
903
+ }
904
+ function render() {
905
+ if (disposed) return;
906
+ const text = textFor(locales, locale);
907
+ heading.textContent = text.title;
908
+ closeButton.textContent = text.close;
909
+ closeButton.setAttribute("aria-label", text.close);
910
+ addButton.textContent = text.add;
911
+ statusElement.textContent = status;
912
+ sortBar.replaceChildren();
913
+ renderSortBar(text);
914
+ listElement.replaceChildren();
915
+ if (summaries.length === 0) {
916
+ const empty = document.createElement("p");
917
+ empty.textContent = text.empty;
918
+ empty.style.cssText = "margin:8px 0;font-size:14px;color:#5a6172;";
919
+ listElement.appendChild(empty);
920
+ } else for (const summary of summaries) listElement.appendChild(renderRow(summary, text));
921
+ }
922
+ styleButton(closeButton, "plain");
923
+ styleButton(addButton, "primary");
924
+ closeButton.type = "button";
925
+ addButton.type = "button";
926
+ closeButton.addEventListener("click", () => hide());
927
+ addButton.addEventListener("click", () => {
928
+ mutate(() => options.onAdd());
929
+ });
930
+ function hide() {
931
+ if (disposed) return;
932
+ renamingId = null;
933
+ confirmingRemovalId = null;
934
+ root.style.display = "none";
935
+ }
936
+ function ensureActive() {
937
+ if (disposed) throw new TypeError("DSL files dialog is disposed");
938
+ }
939
+ render();
940
+ return Object.freeze({
941
+ element: root,
942
+ get locale() {
943
+ return locale;
944
+ },
945
+ get sort() {
946
+ return sort;
947
+ },
948
+ async show(nextLocale) {
949
+ ensureActive();
950
+ if (nextLocale !== void 0) locale = nextLocale;
951
+ status = "";
952
+ root.style.display = "flex";
953
+ await reload();
954
+ return locale;
955
+ },
956
+ hide,
957
+ async refresh() {
958
+ ensureActive();
959
+ await reload();
960
+ },
961
+ setLocale(nextLocale) {
962
+ ensureActive();
963
+ locale = nextLocale;
964
+ render();
965
+ return locale;
966
+ },
967
+ dispose() {
968
+ if (disposed) return;
969
+ disposed = true;
970
+ root.remove();
971
+ if (previousMountPosition === "" || previousMountPosition === "static") mount.style.position = previousMountPosition;
972
+ }
973
+ });
1092
974
  }
1093
- const dslOpenEventName = "turbowarp-title-menu:dsl-open";
1094
- const dslReloadEventName = "turbowarp-title-menu:dsl-reload";
975
+ //#endregion
976
+ //#region src/events.ts
977
+ var dslOpenEventName = "turbowarp-title-menu:dsl-open";
978
+ var dslReloadEventName = "turbowarp-title-menu:dsl-reload";
979
+ /**
980
+ * Announces an opened DSL source on the window.
981
+ *
982
+ * The extension also starts a Scratch hat, but a packaged host that embeds this extension may run
983
+ * its own runtime outside the VM, so the DOM event stays the transport that assumes no Scratch.
984
+ */
1095
985
  function dispatchDslSourceEvent(type, record) {
1096
- const target = globalThis;
1097
- if (typeof target.dispatchEvent !== "function") return;
1098
- const event = typeof CustomEvent === "function" ? new CustomEvent(type, { detail: { record } }) : new Event(type);
1099
- if (!("detail" in event)) {
1100
- Object.defineProperty(event, "detail", { value: { record } });
1101
- }
1102
- target.dispatchEvent(event);
986
+ const target = globalThis;
987
+ if (typeof target.dispatchEvent !== "function") return;
988
+ const event = typeof CustomEvent === "function" ? new CustomEvent(type, { detail: { record } }) : new Event(type);
989
+ if (!("detail" in event)) Object.defineProperty(event, "detail", { value: { record } });
990
+ target.dispatchEvent(event);
1103
991
  }
992
+ //#endregion
993
+ //#region src/title-dialog.ts
1104
994
  function requireLocaleText(locales, locale) {
1105
- const text = locales[locale] ?? locales.en ?? Object.values(locales)[0];
1106
- if (!text) throw new TypeError("locales must contain at least one locale");
1107
- for (const key of ["title", "website", "close"]) {
1108
- if (typeof text[key] !== "string" || text[key].length === 0) {
1109
- throw new TypeError(`locales.${locale}.${key} must be a non-empty string`);
1110
- }
1111
- }
1112
- return text;
995
+ const text = locales[locale] ?? locales.en ?? Object.values(locales)[0];
996
+ if (!text) throw new TypeError("locales must contain at least one locale");
997
+ for (const key of [
998
+ "title",
999
+ "website",
1000
+ "close"
1001
+ ]) if (typeof text[key] !== "string" || text[key].length === 0) throw new TypeError(`locales.${locale}.${key} must be a non-empty string`);
1002
+ return text;
1113
1003
  }
1114
1004
  function openWebsite(url) {
1115
- const opener = globalThis.open;
1116
- if (typeof opener === "function") {
1117
- opener(url, "_blank", "noopener,noreferrer");
1118
- } else if (globalThis.location) {
1119
- globalThis.location.href = url;
1120
- }
1005
+ const opener = globalThis.open;
1006
+ if (typeof opener === "function") opener(url, "_blank", "noopener,noreferrer");
1007
+ else if (globalThis.location) globalThis.location.href = url;
1121
1008
  }
1122
1009
  function createTitleDialog(options) {
1123
- const document = requireDocument(options.document ?? globalThis.document);
1124
- const mount = requireElement(options.mount ?? document.body, "mount");
1125
- const locales = options.locales;
1126
- if (!locales || typeof locales !== "object") throw new TypeError("locales must be an object");
1127
- const root = document.createElement("section");
1128
- const panel = document.createElement("div");
1129
- const language = document.createElement("button");
1130
- const close = document.createElement("button");
1131
- const heading = document.createElement("h1");
1132
- const meta = document.createElement("p");
1133
- const website = document.createElement("button");
1134
- root.setAttribute("data-turbowarp-title-dialog", "true");
1135
- root.setAttribute("role", "dialog");
1136
- root.setAttribute("aria-modal", "true");
1137
- root.style.cssText = "position:absolute;inset:0;z-index:2147483647;display:none;align-items:center;justify-content:center;box-sizing:border-box;background:rgba(0,0,0,.35);font-family:sans-serif;";
1138
- panel.style.cssText = "position:relative;box-sizing:border-box;width:min(88%,420px);padding:36px 28px 28px;text-align:center;background:#f4fffb;border:1px solid #007d66;border-radius:12px;box-shadow:0 8px 32px rgba(0,0,0,.3);color:#006b58;";
1139
- language.style.cssText = "position:absolute;top:14px;left:16px;border:0;background:transparent;color:#007d66;font-size:14px;cursor:pointer;";
1140
- close.style.cssText = "position:absolute;top:12px;right:12px;width:32px;height:32px;border:0;border-radius:50%;background:#007d66;color:#fff;font-size:22px;line-height:28px;cursor:pointer;";
1141
- heading.style.cssText = "margin:0 24px 8px;font-size:30px;font-weight:600;line-height:1.15;";
1142
- meta.style.cssText = "margin:0 0 22px;font-size:14px;line-height:1.4;";
1143
- website.style.cssText = "display:inline-flex;align-items:center;justify-content:center;min-height:48px;padding:8px 18px;border:0;border-radius:10px;background:#007d66;color:#fff;font-size:16px;cursor:pointer;";
1144
- language.type = "button";
1145
- close.type = "button";
1146
- website.type = "button";
1147
- close.textContent = "x";
1148
- panel.append(language, close, heading, meta, website);
1149
- root.appendChild(panel);
1150
- const restoreMount = ensureRelativeMount(mount);
1151
- mount.appendChild(root);
1152
- let locale = options.initialLocale ?? (locales.ja ? "ja" : Object.keys(locales)[0] ?? "en");
1153
- let disposed = false;
1154
- const render = () => {
1155
- const text = requireLocaleText(locales, locale);
1156
- heading.textContent = text.title;
1157
- meta.textContent = [text.author, text.license].filter(Boolean).join(" / ");
1158
- meta.hidden = meta.textContent.length === 0;
1159
- website.textContent = text.website;
1160
- website.setAttribute("aria-label", text.website);
1161
- close.setAttribute("aria-label", text.close);
1162
- close.setAttribute("title", text.close);
1163
- language.textContent = text.language ?? locale;
1164
- language.setAttribute("aria-label", text.language ?? locale);
1165
- };
1166
- const handleWebsite = () => {
1167
- if (options.onWebsite) invokeSafely(options.onWebsite, options.onError);
1168
- else if (options.websiteUrl) openWebsite(options.websiteUrl);
1169
- };
1170
- const handleClose = () => {
1171
- hide();
1172
- if (options.onClose) invokeSafely(options.onClose, options.onError);
1173
- };
1174
- const handleLanguage = () => {
1175
- const keys = Object.keys(locales);
1176
- locale = keys[(Math.max(keys.indexOf(locale), 0) + 1) % keys.length] ?? locale;
1177
- render();
1178
- if (options.onLocaleChange) invokeSafely(() => options.onLocaleChange?.(locale), options.onError);
1179
- };
1180
- website.addEventListener("click", handleWebsite);
1181
- close.addEventListener("click", handleClose);
1182
- language.addEventListener("click", handleLanguage);
1183
- function show(nextLocale = locale) {
1184
- if (disposed) throw new TypeError("title dialog is disposed");
1185
- locale = nextLocale;
1186
- render();
1187
- root.style.display = "flex";
1188
- return locale;
1189
- }
1190
- function hide() {
1191
- if (!disposed) root.style.display = "none";
1192
- }
1193
- function setLocale(nextLocale) {
1194
- if (disposed) throw new TypeError("title dialog is disposed");
1195
- locale = nextLocale;
1196
- render();
1197
- return locale;
1198
- }
1199
- function dispose() {
1200
- if (disposed) return;
1201
- disposed = true;
1202
- website.removeEventListener("click", handleWebsite);
1203
- close.removeEventListener("click", handleClose);
1204
- language.removeEventListener("click", handleLanguage);
1205
- root.remove();
1206
- restoreMount();
1207
- }
1208
- render();
1209
- return Object.freeze({
1210
- element: root,
1211
- get locale() {
1212
- return locale;
1213
- },
1214
- show,
1215
- hide,
1216
- setLocale,
1217
- dispose
1218
- });
1010
+ const document = requireDocument(options.document ?? globalThis.document);
1011
+ const mount = requireElement(options.mount ?? document.body, "mount");
1012
+ const locales = options.locales;
1013
+ if (!locales || typeof locales !== "object") throw new TypeError("locales must be an object");
1014
+ const root = document.createElement("section");
1015
+ const panel = document.createElement("div");
1016
+ const language = document.createElement("button");
1017
+ const close = document.createElement("button");
1018
+ const heading = document.createElement("h1");
1019
+ const meta = document.createElement("p");
1020
+ const website = document.createElement("button");
1021
+ root.setAttribute("data-turbowarp-title-dialog", "true");
1022
+ root.setAttribute("role", "dialog");
1023
+ root.setAttribute("aria-modal", "true");
1024
+ root.style.cssText = "position:absolute;inset:0;z-index:2147483647;display:none;align-items:center;justify-content:center;box-sizing:border-box;background:rgba(0,0,0,.35);font-family:sans-serif;";
1025
+ panel.style.cssText = "position:relative;box-sizing:border-box;width:min(88%,420px);padding:36px 28px 28px;text-align:center;background:#f4fffb;border:1px solid #007d66;border-radius:12px;box-shadow:0 8px 32px rgba(0,0,0,.3);color:#006b58;";
1026
+ language.style.cssText = "position:absolute;top:14px;left:16px;border:0;background:transparent;color:#007d66;font-size:14px;cursor:pointer;";
1027
+ close.style.cssText = "position:absolute;top:12px;right:12px;width:32px;height:32px;border:0;border-radius:50%;background:#007d66;color:#fff;font-size:22px;line-height:28px;cursor:pointer;";
1028
+ heading.style.cssText = "margin:0 24px 8px;font-size:30px;font-weight:600;line-height:1.15;";
1029
+ meta.style.cssText = "margin:0 0 22px;font-size:14px;line-height:1.4;";
1030
+ website.style.cssText = "display:inline-flex;align-items:center;justify-content:center;min-height:48px;padding:8px 18px;border:0;border-radius:10px;background:#007d66;color:#fff;font-size:16px;cursor:pointer;";
1031
+ language.type = "button";
1032
+ close.type = "button";
1033
+ website.type = "button";
1034
+ close.textContent = "x";
1035
+ panel.append(language, close, heading, meta, website);
1036
+ root.appendChild(panel);
1037
+ const restoreMount = ensureRelativeMount(mount);
1038
+ mount.appendChild(root);
1039
+ let locale = options.initialLocale ?? (locales.ja ? "ja" : Object.keys(locales)[0] ?? "en");
1040
+ let disposed = false;
1041
+ const render = () => {
1042
+ const text = requireLocaleText(locales, locale);
1043
+ heading.textContent = text.title;
1044
+ meta.textContent = [text.author, text.license].filter(Boolean).join(" / ");
1045
+ meta.hidden = meta.textContent.length === 0;
1046
+ website.textContent = text.website;
1047
+ website.setAttribute("aria-label", text.website);
1048
+ close.setAttribute("aria-label", text.close);
1049
+ close.setAttribute("title", text.close);
1050
+ language.textContent = text.language ?? locale;
1051
+ language.setAttribute("aria-label", text.language ?? locale);
1052
+ };
1053
+ const handleWebsite = () => {
1054
+ if (options.onWebsite) invokeSafely(options.onWebsite, options.onError);
1055
+ else if (options.websiteUrl) openWebsite(options.websiteUrl);
1056
+ };
1057
+ const handleClose = () => {
1058
+ hide();
1059
+ if (options.onClose) invokeSafely(options.onClose, options.onError);
1060
+ };
1061
+ const handleLanguage = () => {
1062
+ const keys = Object.keys(locales);
1063
+ locale = keys[(Math.max(keys.indexOf(locale), 0) + 1) % keys.length] ?? locale;
1064
+ render();
1065
+ if (options.onLocaleChange) invokeSafely(() => options.onLocaleChange?.(locale), options.onError);
1066
+ };
1067
+ website.addEventListener("click", handleWebsite);
1068
+ close.addEventListener("click", handleClose);
1069
+ language.addEventListener("click", handleLanguage);
1070
+ function show(nextLocale = locale) {
1071
+ if (disposed) throw new TypeError("title dialog is disposed");
1072
+ locale = nextLocale;
1073
+ render();
1074
+ root.style.display = "flex";
1075
+ return locale;
1076
+ }
1077
+ function hide() {
1078
+ if (!disposed) root.style.display = "none";
1079
+ }
1080
+ function setLocale(nextLocale) {
1081
+ if (disposed) throw new TypeError("title dialog is disposed");
1082
+ locale = nextLocale;
1083
+ render();
1084
+ return locale;
1085
+ }
1086
+ function dispose() {
1087
+ if (disposed) return;
1088
+ disposed = true;
1089
+ website.removeEventListener("click", handleWebsite);
1090
+ close.removeEventListener("click", handleClose);
1091
+ language.removeEventListener("click", handleLanguage);
1092
+ root.remove();
1093
+ restoreMount();
1094
+ }
1095
+ render();
1096
+ return Object.freeze({
1097
+ element: root,
1098
+ get locale() {
1099
+ return locale;
1100
+ },
1101
+ show,
1102
+ hide,
1103
+ setLocale,
1104
+ dispose
1105
+ });
1219
1106
  }
1220
- const extensionName = "TurboWarp Title Menu";
1221
- const menus = { "menuActions": { "acceptReporters": false, "items": "menuActionItems" } };
1222
- const blocks = [{ "opcode": "showTitle", "blockType": "COMMAND", "text": "show title dialog", "description": "Shows the configured title dialog above the TurboWarp stage." }, { "opcode": "showMenu", "blockType": "COMMAND", "text": "show application menu", "description": "Shows the application menu above the TurboWarp stage." }, { "opcode": "addAppMenuAction", "blockType": "COMMAND", "text": "add app menu action [ACTION] labelled [LABEL]", "description": "Adds an application menu action this project owns, or relabels one it already added.", "arguments": { "ACTION": { "type": "STRING", "defaultValue": "start" }, "LABEL": { "type": "STRING", "defaultValue": "Start" } } }, { "opcode": "clearAppMenuActions", "blockType": "COMMAND", "text": "clear app menu actions", "description": "Removes every application menu action, including the built-in ones, so a project can define its own set." }, { "opcode": "setAppMenuActionEnabled", "blockType": "COMMAND", "text": "set app menu action [ACTION] enabled [ENABLED]", "description": "Enables or disables one application menu action.", "arguments": { "ACTION": { "type": "STRING", "menu": "menuActions" }, "ENABLED": { "type": "BOOLEAN", "defaultValue": true } } }, { "opcode": "whenAppMenuActionSelected", "blockType": "HAT", "text": "when app menu action [ACTION] selected", "description": "Runs when the operator selects the named application menu action.", "arguments": { "ACTION": { "type": "STRING", "menu": "menuActions" } } }, { "opcode": "showDslFiles", "blockType": "COMMAND", "text": "show DSL file manager", "description": "Shows the dialog that adds, opens, renames, deletes, and sorts stored DSL files." }, { "opcode": "whenDslSourceOpened", "blockType": "HAT", "text": "when a DSL source is opened", "description": "Runs after the operator opens a stored DSL file, or after the opened source is announced again." }, { "opcode": "reloadOpenedDsl", "blockType": "COMMAND", "text": "reload the opened DSL source", "description": "Announces the currently opened DSL source again without showing a dialog." }, { "opcode": "openedDslName", "blockType": "REPORTER", "text": "opened DSL file name", "description": "Returns the name of the DSL file that is currently open, or an empty string." }, { "opcode": "openedDslSource", "blockType": "REPORTER", "text": "opened DSL source", "description": "Returns the text of the DSL file that is currently open, or an empty string." }, { "opcode": "hasSavedDsl", "blockType": "BOOLEAN", "text": "has a saved DSL file?", "description": "Reports whether at least one DSL file is stored in IndexedDB." }, { "opcode": "savedDslCount", "blockType": "REPORTER", "text": "saved DSL file count", "description": "Returns how many DSL files are stored in IndexedDB." }, { "opcode": "lastDslError", "blockType": "REPORTER", "text": "last DSL storage error", "description": "Returns the most recent DSL storage failure in the interface language, or an empty string." }];
1223
- const definitions = {
1224
- extensionName,
1225
- menus,
1226
- blocks
1107
+ var block_definitions_default = {
1108
+ extensionName: "TurboWarp Title Menu",
1109
+ menus: { "menuActions": {
1110
+ "acceptReporters": false,
1111
+ "items": "menuActionItems"
1112
+ } },
1113
+ blocks: [
1114
+ {
1115
+ "opcode": "showTitle",
1116
+ "blockType": "COMMAND",
1117
+ "text": "show title dialog",
1118
+ "description": "Shows the configured title dialog above the TurboWarp stage."
1119
+ },
1120
+ {
1121
+ "opcode": "showMenu",
1122
+ "blockType": "COMMAND",
1123
+ "text": "show application menu",
1124
+ "description": "Shows the application menu above the TurboWarp stage."
1125
+ },
1126
+ {
1127
+ "opcode": "addAppMenuAction",
1128
+ "blockType": "COMMAND",
1129
+ "text": "add app menu action [ACTION] labelled [LABEL]",
1130
+ "description": "Adds an application menu action this project owns, or relabels one it already added.",
1131
+ "arguments": {
1132
+ "ACTION": {
1133
+ "type": "STRING",
1134
+ "defaultValue": "start"
1135
+ },
1136
+ "LABEL": {
1137
+ "type": "STRING",
1138
+ "defaultValue": "Start"
1139
+ }
1140
+ }
1141
+ },
1142
+ {
1143
+ "opcode": "clearAppMenuActions",
1144
+ "blockType": "COMMAND",
1145
+ "text": "clear app menu actions",
1146
+ "description": "Removes every application menu action, including the built-in ones, so a project can define its own set."
1147
+ },
1148
+ {
1149
+ "opcode": "setAppMenuActionEnabled",
1150
+ "blockType": "COMMAND",
1151
+ "text": "set app menu action [ACTION] enabled [ENABLED]",
1152
+ "description": "Enables or disables one application menu action.",
1153
+ "arguments": {
1154
+ "ACTION": {
1155
+ "type": "STRING",
1156
+ "menu": "menuActions"
1157
+ },
1158
+ "ENABLED": {
1159
+ "type": "BOOLEAN",
1160
+ "defaultValue": true
1161
+ }
1162
+ }
1163
+ },
1164
+ {
1165
+ "opcode": "whenAppMenuActionSelected",
1166
+ "blockType": "HAT",
1167
+ "text": "when app menu action [ACTION] selected",
1168
+ "description": "Runs when the operator selects the named application menu action.",
1169
+ "arguments": { "ACTION": {
1170
+ "type": "STRING",
1171
+ "menu": "menuActions"
1172
+ } }
1173
+ },
1174
+ {
1175
+ "opcode": "showDslFiles",
1176
+ "blockType": "COMMAND",
1177
+ "text": "show DSL file manager",
1178
+ "description": "Shows the dialog that adds, opens, renames, deletes, and sorts stored DSL files."
1179
+ },
1180
+ {
1181
+ "opcode": "whenDslSourceOpened",
1182
+ "blockType": "HAT",
1183
+ "text": "when a DSL source is opened",
1184
+ "description": "Runs after the operator opens a stored DSL file, or after the opened source is announced again."
1185
+ },
1186
+ {
1187
+ "opcode": "reloadOpenedDsl",
1188
+ "blockType": "COMMAND",
1189
+ "text": "reload the opened DSL source",
1190
+ "description": "Announces the currently opened DSL source again without showing a dialog."
1191
+ },
1192
+ {
1193
+ "opcode": "openedDslName",
1194
+ "blockType": "REPORTER",
1195
+ "text": "opened DSL file name",
1196
+ "description": "Returns the name of the DSL file that is currently open, or an empty string."
1197
+ },
1198
+ {
1199
+ "opcode": "openedDslSource",
1200
+ "blockType": "REPORTER",
1201
+ "text": "opened DSL source",
1202
+ "description": "Returns the text of the DSL file that is currently open, or an empty string."
1203
+ },
1204
+ {
1205
+ "opcode": "hasSavedDsl",
1206
+ "blockType": "BOOLEAN",
1207
+ "text": "has a saved DSL file?",
1208
+ "description": "Reports whether at least one DSL file is stored in IndexedDB."
1209
+ },
1210
+ {
1211
+ "opcode": "savedDslCount",
1212
+ "blockType": "REPORTER",
1213
+ "text": "saved DSL file count",
1214
+ "description": "Returns how many DSL files are stored in IndexedDB."
1215
+ },
1216
+ {
1217
+ "opcode": "lastDslError",
1218
+ "blockType": "REPORTER",
1219
+ "text": "last DSL storage error",
1220
+ "description": "Returns the most recent DSL storage failure in the interface language, or an empty string."
1221
+ }
1222
+ ]
1227
1223
  };
1228
- const titleLocales = Object.freeze({
1229
- en: {
1230
- title: "TurboWarp Title Menu",
1231
- author: "Author: Hiroya Kubo",
1232
- license: "License: MPL-2.0",
1233
- website: "Official Website",
1234
- close: "Close"
1235
- },
1236
- ja: {
1237
- title: "TurboWarp Title Menu",
1238
- author: "作者: Hiroya Kubo",
1239
- license: "ライセンス: MPL-2.0",
1240
- website: "公式Webサイト",
1241
- close: "閉じる"
1242
- }
1224
+ //#endregion
1225
+ //#region src/locales.ts
1226
+ var titleLocales = Object.freeze({
1227
+ en: {
1228
+ title: "TurboWarp Title Menu",
1229
+ author: "Author: Hiroya Kubo",
1230
+ license: "License: MPL-2.0",
1231
+ website: "Official Website",
1232
+ close: "Close"
1233
+ },
1234
+ ja: {
1235
+ title: "TurboWarp Title Menu",
1236
+ author: "作者: Hiroya Kubo",
1237
+ license: "ライセンス: MPL-2.0",
1238
+ website: "公式Webサイト",
1239
+ close: "閉じる"
1240
+ }
1243
1241
  });
1244
- const menuLocales = Object.freeze({
1245
- en: { files: "DSL files", reload: "Reload DSL", about: "About", close: "Close" },
1246
- ja: { files: "DSLファイル", reload: "DSLを再読み込み", about: "情報", close: "閉じる" }
1242
+ var menuLocales = Object.freeze({
1243
+ en: {
1244
+ files: "DSL files",
1245
+ reload: "Reload DSL",
1246
+ about: "About",
1247
+ close: "Close"
1248
+ },
1249
+ ja: {
1250
+ files: "DSLファイル",
1251
+ reload: "DSLを再読み込み",
1252
+ about: "情報",
1253
+ close: "閉じる"
1254
+ }
1247
1255
  });
1248
- const dslFilesLocales = Object.freeze({
1249
- en: {
1250
- title: "DSL files",
1251
- add: "Add file",
1252
- open: "Open",
1253
- rename: "Rename",
1254
- remove: "Delete",
1255
- confirmRemove: "Delete for good?",
1256
- confirm: "OK",
1257
- cancel: "Cancel",
1258
- close: "Close",
1259
- sortByName: "Name",
1260
- sortByDate: "Updated",
1261
- sortBySize: "Size",
1262
- empty: "No DSL file is saved yet. Use Add file to store one."
1263
- },
1264
- ja: {
1265
- title: "DSLファイル",
1266
- add: "ファイルを追加",
1267
- open: "開く",
1268
- rename: "名前を変える",
1269
- remove: "削除",
1270
- confirmRemove: "本当に削除?",
1271
- confirm: "OK",
1272
- cancel: "やめる",
1273
- close: "閉じる",
1274
- sortByName: "名前",
1275
- sortByDate: "更新日時",
1276
- sortBySize: "サイズ",
1277
- empty: "保存されたDSLファイルはありません。「ファイルを追加」から保存してください。"
1278
- }
1256
+ var dslFilesLocales = Object.freeze({
1257
+ en: {
1258
+ title: "DSL files",
1259
+ add: "Add file",
1260
+ open: "Open",
1261
+ rename: "Rename",
1262
+ remove: "Delete",
1263
+ confirmRemove: "Delete for good?",
1264
+ confirm: "OK",
1265
+ cancel: "Cancel",
1266
+ close: "Close",
1267
+ sortByName: "Name",
1268
+ sortByDate: "Updated",
1269
+ sortBySize: "Size",
1270
+ empty: "No DSL file is saved yet. Use Add file to store one."
1271
+ },
1272
+ ja: {
1273
+ title: "DSLファイル",
1274
+ add: "ファイルを追加",
1275
+ open: "開く",
1276
+ rename: "名前を変える",
1277
+ remove: "削除",
1278
+ confirmRemove: "本当に削除?",
1279
+ confirm: "OK",
1280
+ cancel: "やめる",
1281
+ close: "閉じる",
1282
+ sortByName: "名前",
1283
+ sortByDate: "更新日時",
1284
+ sortBySize: "サイズ",
1285
+ empty: "保存されたDSLファイルはありません。「ファイルを追加」から保存してください。"
1286
+ }
1279
1287
  });
1280
- const storeErrorMessages = Object.freeze({
1281
- en: {
1282
- unavailable: "Browser storage is unavailable, so DSL files cannot be saved.",
1283
- "invalid-name": "That file name cannot be used.",
1284
- "invalid-source": "That file could not be read as text.",
1285
- "name-taken": "Another DSL file already uses that name.",
1286
- "too-large": "That DSL file is too large to store.",
1287
- "too-many": "The DSL store is full. Delete a file before adding another.",
1288
- "not-found": "That DSL file is no longer stored.",
1289
- quota: "Browser storage is full. Delete a DSL file and try again.",
1290
- failed: "The DSL storage operation failed."
1291
- },
1292
- ja: {
1293
- unavailable: "ブラウザの保存領域が使えないため、DSLファイルを保存できません。",
1294
- "invalid-name": "そのファイル名は使えません。",
1295
- "invalid-source": "そのファイルをテキストとして読み込めませんでした。",
1296
- "name-taken": "同じ名前のDSLファイルがすでにあります。",
1297
- "too-large": "そのDSLファイルは大きすぎて保存できません。",
1298
- "too-many": "保存できる数に達しています。どれかを削除してから追加してください。",
1299
- "not-found": "そのDSLファイルは保存されていません。",
1300
- quota: "ブラウザの保存領域がいっぱいです。DSLファイルを削除してからやり直してください。",
1301
- failed: "DSLファイルの操作に失敗しました。"
1302
- }
1288
+ var storeErrorMessages = Object.freeze({
1289
+ en: {
1290
+ unavailable: "Browser storage is unavailable, so DSL files cannot be saved.",
1291
+ "invalid-name": "That file name cannot be used.",
1292
+ "invalid-source": "That file could not be read as text.",
1293
+ "name-taken": "Another DSL file already uses that name.",
1294
+ "too-large": "That DSL file is too large to store.",
1295
+ "too-many": "The DSL store is full. Delete a file before adding another.",
1296
+ "not-found": "That DSL file is no longer stored.",
1297
+ quota: "Browser storage is full. Delete a DSL file and try again.",
1298
+ failed: "The DSL storage operation failed."
1299
+ },
1300
+ ja: {
1301
+ unavailable: "ブラウザの保存領域が使えないため、DSLファイルを保存できません。",
1302
+ "invalid-name": "そのファイル名は使えません。",
1303
+ "invalid-source": "そのファイルをテキストとして読み込めませんでした。",
1304
+ "name-taken": "同じ名前のDSLファイルがすでにあります。",
1305
+ "too-large": "そのDSLファイルは大きすぎて保存できません。",
1306
+ "too-many": "保存できる数に達しています。どれかを削除してから追加してください。",
1307
+ "not-found": "そのDSLファイルは保存されていません。",
1308
+ quota: "ブラウザの保存領域がいっぱいです。DSLファイルを削除してからやり直してください。",
1309
+ failed: "DSLファイルの操作に失敗しました。"
1310
+ }
1303
1311
  });
1312
+ /** Turns a store error code into operator-facing text, falling back to the raw message. */
1304
1313
  function describeStoreError(locale, error) {
1305
- const code = error?.code;
1306
- const messages = storeErrorMessages[locale] ?? storeErrorMessages.en;
1307
- if (code !== void 0 && code in messages) return messages[code];
1308
- if (error instanceof Error && error.message.length > 0) return error.message;
1309
- return String(error);
1314
+ const code = error?.code;
1315
+ const messages = storeErrorMessages[locale] ?? storeErrorMessages.en;
1316
+ if (code !== void 0 && code in messages) return messages[code];
1317
+ if (error instanceof Error && error.message.length > 0) return error.message;
1318
+ return String(error);
1310
1319
  }
1311
- const blockDefinitions = definitions.blocks;
1312
- const dslFileAccept = ".txt,.yaml,.yml,.json,.k4,.kamishibai";
1313
- const builtinActionIds = ["files", "reload", "about", "close"];
1320
+ //#endregion
1321
+ //#region src/extension.ts
1322
+ var blockDefinitions = block_definitions_default.blocks;
1323
+ var dslFileAccept = ".txt,.yaml,.yml,.json,.k4,.kamishibai";
1324
+ /** Reserved action IDs the extension handles itself. A project may still remove or relabel them. */
1325
+ var builtinActionIds = [
1326
+ "files",
1327
+ "reload",
1328
+ "about",
1329
+ "close"
1330
+ ];
1314
1331
  function stageMount() {
1315
- return Scratch.vm?.renderer?.canvas?.parentElement ?? globalThis.document?.body;
1332
+ return Scratch.vm?.renderer?.canvas?.parentElement ?? globalThis.document?.body;
1316
1333
  }
1317
- class TurboWarpTitleMenuExtension {
1318
- constructor() {
1319
- this.titleDialog = null;
1320
- this.applicationMenu = null;
1321
- this.filesDialog = null;
1322
- this.store = null;
1323
- this.openedRecord = null;
1324
- this.lastError = "";
1325
- this.menuActions = builtinActionIds.map((id) => ({
1326
- id,
1327
- labels: { en: menuLocales.en[id], ja: menuLocales.ja[id] },
1328
- enabled: true
1329
- }));
1330
- this.menuVisible = false;
1331
- }
1332
- getInfo() {
1333
- return {
1334
- id: extensionConfig.id,
1335
- name: Scratch.translate(definitions.extensionName),
1336
- docsURI: extensionConfig.docsURI,
1337
- blockIconURI: extensionConfig.blockIconURI,
1338
- blocks: blockDefinitions.map((block) => this.toScratchBlock(block)),
1339
- menus: definitions.menus
1340
- };
1341
- }
1342
- showTitle() {
1343
- this.ensureTitleDialog().show(this.locale());
1344
- }
1345
- /**
1346
- * Shows the application menu.
1347
- *
1348
- * An empty registry does nothing: the underlying primitive requires at least one action, and a
1349
- * project that cleared the actions to install its own should not be interrupted by an error
1350
- * between the two steps.
1351
- */
1352
- showMenu() {
1353
- if (this.menuActions.length === 0) return;
1354
- this.ensureApplicationMenu().show(this.locale());
1355
- this.menuVisible = true;
1356
- }
1357
- /**
1358
- * Backs the dynamic `menuActions` dropdown, so it always lists what the project registered.
1359
- *
1360
- * The menu must refuse reporters. Scratch turns a reporter-accepting menu argument into an input
1361
- * holding a shadow block, and `startHats` matches a hat against its *fields*, so the action hat
1362
- * would never fire for a specific action. Refusing reporters keeps the argument an inline
1363
- * dropdown, which is what the match reads.
1364
- */
1365
- menuActionItems() {
1366
- if (this.menuActions.length === 0) return [{ text: "—", value: "" }];
1367
- const locale = this.locale();
1368
- return this.menuActions.map((action) => ({ text: action.labels[locale], value: action.id }));
1369
- }
1370
- addAppMenuAction(args) {
1371
- const id = Scratch.Cast.toString(args.ACTION).trim();
1372
- if (id.length === 0) return;
1373
- const label = Scratch.Cast.toString(args.LABEL);
1374
- const existing = this.menuActions.find((action) => action.id === id);
1375
- if (existing === void 0) {
1376
- this.menuActions.push({ id, labels: { en: label, ja: label }, enabled: true });
1377
- } else {
1378
- existing.labels = { en: label, ja: label };
1379
- }
1380
- this.rebuildMenu();
1381
- }
1382
- clearAppMenuActions() {
1383
- this.menuActions = [];
1384
- this.rebuildMenu();
1385
- }
1386
- setAppMenuActionEnabled(args) {
1387
- const id = Scratch.Cast.toString(args.ACTION);
1388
- const action = this.menuActions.find((entry) => entry.id === id);
1389
- if (action === void 0) return;
1390
- action.enabled = Scratch.Cast.toBoolean(args.ENABLED);
1391
- this.applicationMenu?.setActionState(id, { enabled: action.enabled });
1392
- }
1393
- /** Started by the menu callback, so the handler only has to accept the match. */
1394
- whenAppMenuActionSelected() {
1395
- return true;
1396
- }
1397
- showDslFiles() {
1398
- return this.ensureFilesDialog().show(this.locale());
1399
- }
1400
- /** The hat is started by the open path, so its own handler only has to accept the match. */
1401
- whenDslSourceOpened() {
1402
- return true;
1403
- }
1404
- reloadOpenedDsl() {
1405
- if (this.openedRecord === null) return;
1406
- this.announce(dslReloadEventName, this.openedRecord);
1407
- }
1408
- openedDslName() {
1409
- return this.openedRecord?.name ?? "";
1410
- }
1411
- openedDslSource() {
1412
- return this.openedRecord?.source ?? "";
1413
- }
1414
- async hasSavedDsl() {
1415
- return await this.savedDslCount() > 0;
1416
- }
1417
- async savedDslCount() {
1418
- try {
1419
- return await this.requireStore().count();
1420
- } catch (error) {
1421
- this.recordFailure(error);
1422
- return 0;
1423
- }
1424
- }
1425
- lastDslError() {
1426
- return this.lastError;
1427
- }
1428
- locale() {
1429
- return resolveAppShellLocale() === "ja" ? "ja" : "en";
1430
- }
1431
- /**
1432
- * Opens the store on first use.
1433
- *
1434
- * A browser without IndexedDB, or one with storage blocked, fails here rather than at extension
1435
- * load: the title and menu blocks stay usable even when nothing can be stored.
1436
- */
1437
- requireStore() {
1438
- this.store ?? (this.store = createDslStore({ databaseName: extensionConfig.id }));
1439
- return this.store;
1440
- }
1441
- recordFailure(error) {
1442
- this.lastError = describeStoreError(this.locale(), error);
1443
- }
1444
- /**
1445
- * Rebuilds the menu after its action list changed.
1446
- *
1447
- * The app-shell primitive fixes its actions at construction, so a changed list means a new menu.
1448
- * A menu that was on screen is shown again, because a project that adds an action while the menu
1449
- * is open should not have it silently disappear. Clearing every action closes the menu instead,
1450
- * because the primitive refuses to build one with no actions.
1451
- */
1452
- rebuildMenu() {
1453
- this.applicationMenu?.dispose();
1454
- this.applicationMenu = null;
1455
- if (!this.menuVisible) return;
1456
- if (this.menuActions.length === 0) {
1457
- this.menuVisible = false;
1458
- return;
1459
- }
1460
- this.showMenu();
1461
- }
1462
- selectMenuAction(id) {
1463
- Scratch.vm?.runtime?.startHats?.(`${extensionConfig.id}_whenAppMenuActionSelected`, { ACTION: id });
1464
- if (!builtinActionIds.includes(id)) return;
1465
- if (id === "files") void this.showDslFiles();
1466
- if (id === "reload") this.reloadOpenedDsl();
1467
- if (id === "about") this.showTitle();
1468
- if (id === "close") this.hideMenu();
1469
- }
1470
- hideMenu() {
1471
- this.applicationMenu?.hide();
1472
- this.menuVisible = false;
1473
- }
1474
- announce(eventName, record) {
1475
- dispatchDslSourceEvent(eventName, record);
1476
- Scratch.vm?.runtime?.startHats?.(`${extensionConfig.id}_whenDslSourceOpened`);
1477
- }
1478
- ensureTitleDialog() {
1479
- if (this.titleDialog) return this.titleDialog;
1480
- const mount = stageMount();
1481
- this.titleDialog = createTitleDialog({
1482
- document: globalThis.document,
1483
- ...mount ? { mount } : {},
1484
- locales: titleLocales,
1485
- initialLocale: this.locale(),
1486
- websiteUrl: extensionConfig.homepage
1487
- });
1488
- return this.titleDialog;
1489
- }
1490
- /**
1491
- * Builds the menu from the shared app-shell primitive.
1492
- *
1493
- * The actions below are this extension's own vocabulary, not the primitive's: a host application
1494
- * that needs different actions composes `createAppShellApplicationMenu` itself through the
1495
- * composition API instead of being limited to these four.
1496
- */
1497
- ensureApplicationMenu() {
1498
- if (this.applicationMenu) return this.applicationMenu;
1499
- const mount = stageMount();
1500
- if (mount === void 0) throw new TypeError("a stage container is required to show the menu");
1501
- this.applicationMenu = createAppShellApplicationMenu({
1502
- document: globalThis.document,
1503
- mount,
1504
- initialLocale: this.locale(),
1505
- actions: this.menuActions.map((action) => ({
1506
- id: action.id,
1507
- labels: action.labels,
1508
- enabled: action.enabled,
1509
- onSelect: () => this.selectMenuAction(action.id)
1510
- }))
1511
- });
1512
- return this.applicationMenu;
1513
- }
1514
- ensureFilesDialog() {
1515
- if (this.filesDialog) return this.filesDialog;
1516
- const mount = stageMount();
1517
- this.filesDialog = createDslFilesDialog({
1518
- document: globalThis.document,
1519
- ...mount ? { mount } : {},
1520
- locales: dslFilesLocales,
1521
- initialLocale: this.locale(),
1522
- list: (sort) => this.requireStore().list(sort),
1523
- onAdd: () => this.addDslFile(),
1524
- onOpen: (id) => this.openDslFile(id),
1525
- onRename: (id, name) => this.requireStore().rename(id, name),
1526
- onRemove: (id) => this.removeDslFile(id),
1527
- describeError: (error) => describeStoreError(this.locale(), error),
1528
- onError: (error) => this.recordFailure(error)
1529
- });
1530
- return this.filesDialog;
1531
- }
1532
- async addDslFile() {
1533
- const chosen = await this.pickDslFile();
1534
- if (chosen === null) return;
1535
- await this.requireStore().save(await readDslFile(chosen));
1536
- this.lastError = "";
1537
- }
1538
- async openDslFile(id) {
1539
- const store = this.requireStore();
1540
- const record = await store.get(id);
1541
- if (record === null) return;
1542
- await store.markOpened(id);
1543
- this.openedRecord = record;
1544
- this.lastError = "";
1545
- this.announce(dslOpenEventName, record);
1546
- }
1547
- async removeDslFile(id) {
1548
- await this.requireStore().remove(id);
1549
- if (this.openedRecord?.id === id) this.openedRecord = null;
1550
- this.lastError = "";
1551
- }
1552
- pickDslFile() {
1553
- const document = globalThis.document;
1554
- if (!document) throw new TypeError("document is required to open a DSL file");
1555
- const input = document.createElement("input");
1556
- input.type = "file";
1557
- input.accept = dslFileAccept;
1558
- return new Promise((resolve) => {
1559
- input.addEventListener(
1560
- "change",
1561
- () => {
1562
- resolve(input.files?.[0] ?? null);
1563
- },
1564
- { once: true }
1565
- );
1566
- input.click();
1567
- });
1568
- }
1569
- toScratchBlock(block) {
1570
- const scratchBlock = {
1571
- opcode: block.opcode,
1572
- blockType: Scratch.BlockType[block.blockType],
1573
- text: Scratch.translate(block.text),
1574
- arguments: Object.fromEntries(
1575
- Object.entries(block.arguments ?? {}).map(([name, argument]) => [
1576
- name,
1577
- {
1578
- type: Scratch.ArgumentType[argument.type],
1579
- ...argument.defaultValue === void 0 ? {} : { defaultValue: argument.defaultValue },
1580
- ...argument.menu === void 0 ? {} : { menu: argument.menu }
1581
- }
1582
- ])
1583
- )
1584
- };
1585
- if (block.blockType === "HAT") scratchBlock["isEdgeActivated"] = false;
1586
- return scratchBlock;
1587
- }
1588
- }
1589
- const publicApi = Object.freeze({
1590
- createApplicationMenu: createAppShellApplicationMenu,
1591
- createDslFilesDialog,
1592
- createDslStore,
1593
- createTitleDialog,
1594
- dslOpenEventName,
1595
- dslReloadEventName
1334
+ var TurboWarpTitleMenuExtension = class {
1335
+ constructor() {
1336
+ this.titleDialog = null;
1337
+ this.applicationMenu = null;
1338
+ this.filesDialog = null;
1339
+ this.store = null;
1340
+ this.openedRecord = null;
1341
+ this.lastError = "";
1342
+ this.menuActions = builtinActionIds.map((id) => ({
1343
+ id,
1344
+ labels: {
1345
+ en: menuLocales.en[id],
1346
+ ja: menuLocales.ja[id]
1347
+ },
1348
+ enabled: true
1349
+ }));
1350
+ this.menuVisible = false;
1351
+ }
1352
+ getInfo() {
1353
+ return {
1354
+ id: extensionConfig.id,
1355
+ name: Scratch.translate(block_definitions_default.extensionName),
1356
+ docsURI: extensionConfig.docsURI,
1357
+ blockIconURI: extensionConfig.blockIconURI,
1358
+ blocks: blockDefinitions.map((block) => this.toScratchBlock(block)),
1359
+ menus: block_definitions_default.menus
1360
+ };
1361
+ }
1362
+ showTitle() {
1363
+ this.ensureTitleDialog().show(this.locale());
1364
+ }
1365
+ /**
1366
+ * Shows the application menu.
1367
+ *
1368
+ * An empty registry does nothing: the underlying primitive requires at least one action, and a
1369
+ * project that cleared the actions to install its own should not be interrupted by an error
1370
+ * between the two steps.
1371
+ */
1372
+ showMenu() {
1373
+ if (this.menuActions.length === 0) return;
1374
+ this.ensureApplicationMenu().show(this.locale());
1375
+ this.menuVisible = true;
1376
+ }
1377
+ /**
1378
+ * Backs the dynamic `menuActions` dropdown, so it always lists what the project registered.
1379
+ *
1380
+ * The menu must refuse reporters. Scratch turns a reporter-accepting menu argument into an input
1381
+ * holding a shadow block, and `startHats` matches a hat against its *fields*, so the action hat
1382
+ * would never fire for a specific action. Refusing reporters keeps the argument an inline
1383
+ * dropdown, which is what the match reads.
1384
+ */
1385
+ menuActionItems() {
1386
+ if (this.menuActions.length === 0) return [{
1387
+ text: "—",
1388
+ value: ""
1389
+ }];
1390
+ const locale = this.locale();
1391
+ return this.menuActions.map((action) => ({
1392
+ text: action.labels[locale],
1393
+ value: action.id
1394
+ }));
1395
+ }
1396
+ addAppMenuAction(args) {
1397
+ const id = Scratch.Cast.toString(args.ACTION).trim();
1398
+ if (id.length === 0) return;
1399
+ const label = Scratch.Cast.toString(args.LABEL);
1400
+ const existing = this.menuActions.find((action) => action.id === id);
1401
+ if (existing === void 0) this.menuActions.push({
1402
+ id,
1403
+ labels: {
1404
+ en: label,
1405
+ ja: label
1406
+ },
1407
+ enabled: true
1408
+ });
1409
+ else existing.labels = {
1410
+ en: label,
1411
+ ja: label
1412
+ };
1413
+ this.rebuildMenu();
1414
+ }
1415
+ clearAppMenuActions() {
1416
+ this.menuActions = [];
1417
+ this.rebuildMenu();
1418
+ }
1419
+ setAppMenuActionEnabled(args) {
1420
+ const id = Scratch.Cast.toString(args.ACTION);
1421
+ const action = this.menuActions.find((entry) => entry.id === id);
1422
+ if (action === void 0) return;
1423
+ action.enabled = Scratch.Cast.toBoolean(args.ENABLED);
1424
+ this.applicationMenu?.setActionState(id, { enabled: action.enabled });
1425
+ }
1426
+ /** Started by the menu callback, so the handler only has to accept the match. */
1427
+ whenAppMenuActionSelected() {
1428
+ return true;
1429
+ }
1430
+ showDslFiles() {
1431
+ return this.ensureFilesDialog().show(this.locale());
1432
+ }
1433
+ /** The hat is started by the open path, so its own handler only has to accept the match. */
1434
+ whenDslSourceOpened() {
1435
+ return true;
1436
+ }
1437
+ reloadOpenedDsl() {
1438
+ if (this.openedRecord === null) return;
1439
+ this.announce(dslReloadEventName, this.openedRecord);
1440
+ }
1441
+ openedDslName() {
1442
+ return this.openedRecord?.name ?? "";
1443
+ }
1444
+ openedDslSource() {
1445
+ return this.openedRecord?.source ?? "";
1446
+ }
1447
+ async hasSavedDsl() {
1448
+ return await this.savedDslCount() > 0;
1449
+ }
1450
+ async savedDslCount() {
1451
+ try {
1452
+ return await this.requireStore().count();
1453
+ } catch (error) {
1454
+ this.recordFailure(error);
1455
+ return 0;
1456
+ }
1457
+ }
1458
+ lastDslError() {
1459
+ return this.lastError;
1460
+ }
1461
+ locale() {
1462
+ return resolveAppShellLocale() === "ja" ? "ja" : "en";
1463
+ }
1464
+ /**
1465
+ * Opens the store on first use.
1466
+ *
1467
+ * A browser without IndexedDB, or one with storage blocked, fails here rather than at extension
1468
+ * load: the title and menu blocks stay usable even when nothing can be stored.
1469
+ */
1470
+ requireStore() {
1471
+ this.store ?? (this.store = createDslStore({ databaseName: extensionConfig.id }));
1472
+ return this.store;
1473
+ }
1474
+ recordFailure(error) {
1475
+ this.lastError = describeStoreError(this.locale(), error);
1476
+ }
1477
+ /**
1478
+ * Rebuilds the menu after its action list changed.
1479
+ *
1480
+ * The app-shell primitive fixes its actions at construction, so a changed list means a new menu.
1481
+ * A menu that was on screen is shown again, because a project that adds an action while the menu
1482
+ * is open should not have it silently disappear. Clearing every action closes the menu instead,
1483
+ * because the primitive refuses to build one with no actions.
1484
+ */
1485
+ rebuildMenu() {
1486
+ this.applicationMenu?.dispose();
1487
+ this.applicationMenu = null;
1488
+ if (!this.menuVisible) return;
1489
+ if (this.menuActions.length === 0) {
1490
+ this.menuVisible = false;
1491
+ return;
1492
+ }
1493
+ this.showMenu();
1494
+ }
1495
+ selectMenuAction(id) {
1496
+ Scratch.vm?.runtime?.startHats?.(`${extensionConfig.id}_whenAppMenuActionSelected`, { ACTION: id });
1497
+ if (!builtinActionIds.includes(id)) return;
1498
+ if (id === "files") this.showDslFiles();
1499
+ if (id === "reload") this.reloadOpenedDsl();
1500
+ if (id === "about") this.showTitle();
1501
+ if (id === "close") this.hideMenu();
1502
+ }
1503
+ hideMenu() {
1504
+ this.applicationMenu?.hide();
1505
+ this.menuVisible = false;
1506
+ }
1507
+ announce(eventName, record) {
1508
+ dispatchDslSourceEvent(eventName, record);
1509
+ Scratch.vm?.runtime?.startHats?.(`${extensionConfig.id}_whenDslSourceOpened`);
1510
+ }
1511
+ ensureTitleDialog() {
1512
+ if (this.titleDialog) return this.titleDialog;
1513
+ const mount = stageMount();
1514
+ this.titleDialog = createTitleDialog({
1515
+ document: globalThis.document,
1516
+ ...mount ? { mount } : {},
1517
+ locales: titleLocales,
1518
+ initialLocale: this.locale(),
1519
+ websiteUrl: extensionConfig.homepage
1520
+ });
1521
+ return this.titleDialog;
1522
+ }
1523
+ /**
1524
+ * Builds the menu from the shared app-shell primitive.
1525
+ *
1526
+ * The actions below are this extension's own vocabulary, not the primitive's: a host application
1527
+ * that needs different actions composes `createAppShellApplicationMenu` itself through the
1528
+ * composition API instead of being limited to these four.
1529
+ */
1530
+ ensureApplicationMenu() {
1531
+ if (this.applicationMenu) return this.applicationMenu;
1532
+ const mount = stageMount();
1533
+ if (mount === void 0) throw new TypeError("a stage container is required to show the menu");
1534
+ this.applicationMenu = createAppShellApplicationMenu({
1535
+ document: globalThis.document,
1536
+ mount,
1537
+ initialLocale: this.locale(),
1538
+ actions: this.menuActions.map((action) => ({
1539
+ id: action.id,
1540
+ labels: action.labels,
1541
+ enabled: action.enabled,
1542
+ onSelect: () => this.selectMenuAction(action.id)
1543
+ }))
1544
+ });
1545
+ return this.applicationMenu;
1546
+ }
1547
+ ensureFilesDialog() {
1548
+ if (this.filesDialog) return this.filesDialog;
1549
+ const mount = stageMount();
1550
+ this.filesDialog = createDslFilesDialog({
1551
+ document: globalThis.document,
1552
+ ...mount ? { mount } : {},
1553
+ locales: dslFilesLocales,
1554
+ initialLocale: this.locale(),
1555
+ list: (sort) => this.requireStore().list(sort),
1556
+ onAdd: () => this.addDslFile(),
1557
+ onOpen: (id) => this.openDslFile(id),
1558
+ onRename: (id, name) => this.requireStore().rename(id, name),
1559
+ onRemove: (id) => this.removeDslFile(id),
1560
+ describeError: (error) => describeStoreError(this.locale(), error),
1561
+ onError: (error) => this.recordFailure(error)
1562
+ });
1563
+ return this.filesDialog;
1564
+ }
1565
+ async addDslFile() {
1566
+ const chosen = await this.pickDslFile();
1567
+ if (chosen === null) return;
1568
+ await this.requireStore().save(await readDslFile(chosen));
1569
+ this.lastError = "";
1570
+ }
1571
+ async openDslFile(id) {
1572
+ const store = this.requireStore();
1573
+ const record = await store.get(id);
1574
+ if (record === null) return;
1575
+ await store.markOpened(id);
1576
+ this.openedRecord = record;
1577
+ this.lastError = "";
1578
+ this.announce(dslOpenEventName, record);
1579
+ }
1580
+ async removeDslFile(id) {
1581
+ await this.requireStore().remove(id);
1582
+ if (this.openedRecord?.id === id) this.openedRecord = null;
1583
+ this.lastError = "";
1584
+ }
1585
+ pickDslFile() {
1586
+ const document = globalThis.document;
1587
+ if (!document) throw new TypeError("document is required to open a DSL file");
1588
+ const input = document.createElement("input");
1589
+ input.type = "file";
1590
+ input.accept = dslFileAccept;
1591
+ return new Promise((resolve) => {
1592
+ input.addEventListener("change", () => {
1593
+ resolve(input.files?.[0] ?? null);
1594
+ }, { once: true });
1595
+ input.click();
1596
+ });
1597
+ }
1598
+ toScratchBlock(block) {
1599
+ const scratchBlock = {
1600
+ opcode: block.opcode,
1601
+ blockType: Scratch.BlockType[block.blockType],
1602
+ text: Scratch.translate(block.text),
1603
+ arguments: Object.fromEntries(Object.entries(block.arguments ?? {}).map(([name, argument]) => [name, {
1604
+ type: Scratch.ArgumentType[argument.type],
1605
+ ...argument.defaultValue === void 0 ? {} : { defaultValue: argument.defaultValue },
1606
+ ...argument.menu === void 0 ? {} : { menu: argument.menu }
1607
+ }]))
1608
+ };
1609
+ if (block.blockType === "HAT") scratchBlock["isEdgeActivated"] = false;
1610
+ return scratchBlock;
1611
+ }
1612
+ };
1613
+ //#endregion
1614
+ //#region src/index.ts
1615
+ var publicApi = Object.freeze({
1616
+ createApplicationMenu: createAppShellApplicationMenu,
1617
+ createDslFilesDialog,
1618
+ createDslStore,
1619
+ createTitleDialog,
1620
+ dslOpenEventName,
1621
+ dslReloadEventName
1596
1622
  });
1597
1623
  Object.defineProperty(globalThis, "TurboWarpTitleMenu", {
1598
- value: publicApi,
1599
- configurable: true
1624
+ value: publicApi,
1625
+ configurable: true
1600
1626
  });
1601
- if (!Scratch.extensions.unsandboxed) {
1602
- throw new Error(`${extensionConfig.name} must run unsandboxed.`);
1603
- }
1627
+ if (extensionConfig.unsandboxed && !Scratch.extensions.unsandboxed) throw new Error(`${extensionConfig.name} must run unsandboxed.`);
1604
1628
  Scratch.extensions.register(new TurboWarpTitleMenuExtension());
1629
+ //#endregion
1605
1630
 
1606
1631
  })(Scratch);