@kubohiroya/turbowarp-plus-editor-workbench 0.14.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/NOTICE +26 -0
  2. package/README.ja.md +22 -0
  3. package/README.md +22 -0
  4. package/dist/backpack-script.d.ts +2 -0
  5. package/dist/backpack-script.js +23 -0
  6. package/dist/backpack.d.ts +60 -0
  7. package/dist/backpack.js +226 -0
  8. package/dist/browser-tab-title.d.ts +2 -0
  9. package/dist/browser-tab-title.js +5 -0
  10. package/dist/busy-cursor.d.ts +22 -0
  11. package/dist/busy-cursor.js +107 -0
  12. package/dist/edit-menu.d.ts +57 -0
  13. package/dist/edit-menu.js +99 -0
  14. package/dist/info-menu.d.ts +39 -0
  15. package/dist/info-menu.js +157 -0
  16. package/dist/project-file-dialogs.d.ts +70 -0
  17. package/dist/project-file-dialogs.js +625 -0
  18. package/dist/project-file-menu.d.ts +43 -0
  19. package/dist/project-file-menu.js +90 -0
  20. package/dist/project-load-progress-view.d.ts +6 -0
  21. package/dist/project-load-progress-view.js +66 -0
  22. package/dist/project-load-progress.d.ts +26 -0
  23. package/dist/project-load-progress.js +104 -0
  24. package/dist/project-search-box.d.ts +43 -0
  25. package/dist/project-search-box.js +437 -0
  26. package/dist/project-size-approval.d.ts +10 -0
  27. package/dist/project-size-approval.js +64 -0
  28. package/dist/stage-controls-view.d.ts +45 -0
  29. package/dist/stage-controls-view.js +127 -0
  30. package/dist/stage-controls.d.ts +98 -0
  31. package/dist/stage-controls.js +110 -0
  32. package/package.json +97 -28
  33. package/src/backpack-script.ts +21 -0
  34. package/src/backpack.tsx +260 -0
  35. package/src/browser-tab-title.ts +6 -0
  36. package/src/busy-cursor.ts +108 -0
  37. package/src/edit-menu.css +42 -0
  38. package/src/edit-menu.tsx +139 -0
  39. package/src/info-menu.css +172 -0
  40. package/src/info-menu.tsx +221 -0
  41. package/src/project-file-dialogs.ts +654 -0
  42. package/src/project-file-menu.css +94 -0
  43. package/src/project-file-menu.tsx +137 -0
  44. package/src/project-load-progress-view.tsx +75 -0
  45. package/src/project-load-progress.css +57 -0
  46. package/src/project-load-progress.ts +118 -0
  47. package/src/project-search-box.tsx +469 -0
  48. package/src/project-search.css +116 -0
  49. package/src/project-size-approval.ts +74 -0
  50. package/src/sprite-layout-menu.css +2 -1
  51. package/src/stage-controls-view.tsx +178 -0
  52. package/src/stage-controls.css +192 -0
  53. package/src/stage-controls.ts +124 -0
@@ -0,0 +1,437 @@
1
+ import React from 'react';
2
+ import { createPortal } from 'react-dom';
3
+ import { searchProject, searchYamlDocuments, variableAccessLabels } from '@kubohiroya/turbowarp-plus-editor-project-model/project-search';
4
+ import { activateTargetView, connectProjectReplaceOpener, connectVariableSearchOpener, connectionFor, projectReplaceShortcut } from '@kubohiroya/turbowarp-plus-editor-project-model/project-search-connections';
5
+ import { applyProjectSearchReplacement, replacementText } from '@kubohiroya/turbowarp-plus-editor-project-model/project-search-replace';
6
+ const pageSize = 60;
7
+ const filters = [
8
+ { kinds: ['block'], label: ['ブロック名', 'Block names'] },
9
+ { kinds: ['variable', 'list'], label: ['変数・リスト名', 'Variable and list names'] },
10
+ { kinds: ['message'], label: ['メッセージ名', 'Broadcast names'] },
11
+ { kinds: ['argument'], label: ['引数の値', 'Argument values'] },
12
+ { kinds: ['extension'], label: ['機能拡張名', 'Extension names'] },
13
+ { kinds: ['comment'], label: ['コメント文', 'Comments'] },
14
+ { kinds: ['yaml'], label: ['YAML 本文', 'YAML text'] },
15
+ { kinds: ['costume', 'backdrop', 'sound'], label: ['素材名', 'Asset names'] }
16
+ ];
17
+ const pickMatch = ['置換する項目を一覧から選んでください。', 'Select a match in the list to replace.'];
18
+ const replaceMessages = {
19
+ applied: ['置換しました。', 'Replaced.'],
20
+ staged: ['YAML の置換内容を確認してください。', 'Review the replacement in the YAML preview.'],
21
+ stale: ['対象が変更されました。もう一度検索してください。', 'The match changed. Search again.'],
22
+ conflict: ['同じ名前が既に使われています。', 'That name is already in use.'],
23
+ invalid: ['この項目に使える値を入力してください。', 'Enter a value this item accepts.'],
24
+ 'read-only': ['この項目は置換できません。', 'This result cannot be replaced.']
25
+ };
26
+ function ProjectSearchBox({ locale, project, getMessages, documents, select, replace }) {
27
+ const japanese = /^ja(?:-|$)/i.test(locale);
28
+ const [query, setQuery] = React.useState('');
29
+ const [open, setOpen] = React.useState(false);
30
+ const [replacement, setReplacement] = React.useState('');
31
+ const [outcome, setOutcome] = React.useState();
32
+ const [replacing, setReplacing] = React.useState(false);
33
+ const [revision, setRevision] = React.useState(0);
34
+ const [limit, setLimit] = React.useState(pageSize);
35
+ const [active, setActive] = React.useState();
36
+ const [variableSearch, setVariableSearch] = React.useState();
37
+ const [kinds, setKinds] = React.useState(() => new Set(filters.flatMap(filter => filter.kinds)));
38
+ const input = React.useRef();
39
+ const box = React.useRef();
40
+ const popup = React.useRef();
41
+ const replaceField = React.useRef();
42
+ const replacingMatch = React.useRef(false);
43
+ const revealing = React.useRef(0);
44
+ const searchYaml = open && !variableSearch && kinds.has('yaml') && Boolean(query.trim());
45
+ const yamlDocuments = React.useMemo(() => searchYaml ? documents?.getSearchableYamlDocuments() ?? [] : [], [searchYaml, documents, revision]);
46
+ const groups = React.useMemo(() => {
47
+ if (!open)
48
+ return [];
49
+ const groups = searchProject(project, getMessages(), query, japanese, kinds, variableSearch);
50
+ const yaml = searchYamlDocuments(yamlDocuments, query, japanese);
51
+ if (yaml.length)
52
+ groups.push({ kind: 'yaml', title: japanese ? 'YAML 本文' : 'YAML text', results: yaml });
53
+ return groups;
54
+ }, [open, project, getMessages, query, japanese, kinds, yamlDocuments, revision, variableSearch]);
55
+ const visible = groups.flatMap(group => group.results.slice(0, limit));
56
+ const activeIndex = visible.indexOf(active);
57
+ const show = open;
58
+ const more = groups.some(group => group.results.length > limit);
59
+ const listId = 'tw-plus-project-search-results';
60
+ const optionId = (index) => `${listId}-${index}`;
61
+ const canEdit = (result) => result.kind === 'yaml' ? Boolean(documents?.stageYamlReplacement) : Boolean(result.edit);
62
+ const proposed = active && canEdit(active) ? replacementText(active, query, replacement) : undefined;
63
+ React.useLayoutEffect(() => {
64
+ const field = input.current;
65
+ const win = field.ownerDocument.defaultView;
66
+ const focusSearch = () => {
67
+ field.focus();
68
+ field.select();
69
+ };
70
+ const openReplace = () => {
71
+ setVariableSearch(undefined);
72
+ setOpen(true);
73
+ if (!field.value.trim()) {
74
+ focusSearch();
75
+ return;
76
+ }
77
+ // The popup may mount in this update, so wait for it before reaching into it.
78
+ const focusReplacement = (retries) => {
79
+ const target = replaceField.current;
80
+ if (!target) {
81
+ if (retries)
82
+ win.requestAnimationFrame(() => focusReplacement(retries - 1));
83
+ else
84
+ focusSearch();
85
+ return;
86
+ }
87
+ target.focus();
88
+ target.select();
89
+ };
90
+ win.requestAnimationFrame(() => focusReplacement(2));
91
+ };
92
+ const disconnectReplace = connectProjectReplaceOpener(project, openReplace);
93
+ const disconnectVariable = connectVariableSearchOpener(project, filter => {
94
+ const owner = project.targets.find(target => target.id === filter.ownerId && target.isOriginal);
95
+ const variable = owner?.variables[filter.variableId];
96
+ if (!variable)
97
+ return;
98
+ setQuery(variable.name);
99
+ setVariableSearch(filter);
100
+ setLimit(pageSize);
101
+ setActive(undefined);
102
+ setOutcome(undefined);
103
+ setOpen(true);
104
+ focusSearch();
105
+ });
106
+ const shortcut = (event) => {
107
+ const replace = projectReplaceShortcut.matches(event);
108
+ const find = (event.metaKey || event.ctrlKey) && !event.shiftKey && !event.altKey &&
109
+ event.key.toLowerCase() === 'f';
110
+ if (!field.offsetWidth || (!find && !replace))
111
+ return;
112
+ event.preventDefault();
113
+ event.stopPropagation();
114
+ if (find)
115
+ focusSearch();
116
+ else if (!event.repeat)
117
+ openReplace();
118
+ };
119
+ win.addEventListener('keydown', shortcut, true);
120
+ return () => {
121
+ win.removeEventListener('keydown', shortcut, true);
122
+ disconnectReplace();
123
+ disconnectVariable();
124
+ };
125
+ }, [project]);
126
+ React.useEffect(() => {
127
+ if (!open || !variableSearch)
128
+ return;
129
+ const refresh = () => setRevision(value => value + 1);
130
+ project.on?.('PROJECT_CHANGED', refresh);
131
+ return () => project.removeListener?.('PROJECT_CHANGED', refresh);
132
+ }, [open, project, variableSearch]);
133
+ React.useLayoutEffect(() => {
134
+ if (!show)
135
+ return;
136
+ const field = input.current;
137
+ const panel = popup.current;
138
+ const win = field.ownerDocument.defaultView;
139
+ const place = () => {
140
+ const rect = field.getBoundingClientRect();
141
+ const width = Math.min(430, win.innerWidth - 16);
142
+ const below = win.innerHeight - rect.bottom - 12;
143
+ const above = rect.top - 12;
144
+ const placeBelow = below >= 160 || below >= above;
145
+ panel.style.width = `${width}px`;
146
+ panel.style.left = `${Math.max(8, Math.min(rect.right - width, win.innerWidth - width - 8))}px`;
147
+ panel.style.top = placeBelow ? `${rect.bottom + 4}px` : 'auto';
148
+ panel.style.bottom = placeBelow ? 'auto' : `${win.innerHeight - rect.top + 4}px`;
149
+ panel.style.maxHeight = `${Math.min(450, placeBelow ? below : above)}px`;
150
+ };
151
+ place();
152
+ if (panel.showPopover && !panel.matches(':popover-open'))
153
+ panel.showPopover();
154
+ // Revealing a result keeps the panel open, so a press anywhere else has to dismiss it:
155
+ // blur cannot tell the editor taking focus from the reader turning to something else.
156
+ const dismiss = (event) => {
157
+ const target = event.target;
158
+ if (box.current?.contains(target) || panel.contains(target))
159
+ return;
160
+ close();
161
+ };
162
+ const observer = new win.ResizeObserver(place);
163
+ observer.observe(field);
164
+ win.addEventListener('pointerdown', dismiss, true);
165
+ win.addEventListener('resize', place);
166
+ win.addEventListener('scroll', place, true);
167
+ return () => {
168
+ observer.disconnect();
169
+ win.removeEventListener('pointerdown', dismiss, true);
170
+ win.removeEventListener('resize', place);
171
+ win.removeEventListener('scroll', place, true);
172
+ };
173
+ }, [show]);
174
+ React.useLayoutEffect(() => {
175
+ if (activeIndex >= 0)
176
+ input.current.ownerDocument.getElementById(optionId(activeIndex))?.scrollIntoView({ block: 'nearest' });
177
+ }, [activeIndex]);
178
+ function close() {
179
+ setOpen(false);
180
+ setActive(undefined);
181
+ }
182
+ function reveal(result) {
183
+ const win = input.current.ownerDocument.defaultView;
184
+ // Revealing a result moves the editor, and a YAML preview takes focus when it opens. Keep
185
+ // the panel open through that so the same result is still the one the replacement applies
186
+ // to, and leave focus wherever the destination put it.
187
+ revealing.current += 1;
188
+ select(result);
189
+ win.setTimeout(() => { revealing.current -= 1; }, 1000);
190
+ }
191
+ function choose(result) {
192
+ setActive(result);
193
+ setOutcome(undefined);
194
+ reveal(result);
195
+ }
196
+ function jump(result) {
197
+ close();
198
+ select(result);
199
+ }
200
+ async function replaceSelected() {
201
+ if (replacingMatch.current || !active || proposed === undefined)
202
+ return;
203
+ replacingMatch.current = true;
204
+ setReplacing(true);
205
+ setOutcome(undefined);
206
+ try {
207
+ const result = await replace(active, proposed);
208
+ setOutcome(result);
209
+ if (result === 'staged')
210
+ close();
211
+ if (result === 'applied' || result === 'stale') {
212
+ setActive(undefined);
213
+ setRevision(value => value + 1);
214
+ }
215
+ if (result !== 'staged' && !popup.current?.contains(input.current?.ownerDocument.activeElement)) {
216
+ input.current?.focus({ preventScroll: true });
217
+ }
218
+ }
219
+ catch {
220
+ setOutcome('invalid');
221
+ }
222
+ finally {
223
+ replacingMatch.current = false;
224
+ setReplacing(false);
225
+ }
226
+ }
227
+ return React.createElement("div", { ref: box, className: "tw-project-search__field", onBlur: event => {
228
+ if (!replacingMatch.current && !revealing.current && !event.currentTarget.contains(event.relatedTarget) &&
229
+ !popup.current?.contains(event.relatedTarget))
230
+ close();
231
+ } },
232
+ React.createElement("input", { ref: input, type: "search", role: "combobox", autoComplete: "off", "aria-autocomplete": "list", placeholder: japanese ? '検索' : 'Search', "aria-label": japanese ? '作品全体を検索' : 'Search project', "aria-expanded": show, "aria-controls": show ? listId : undefined, "aria-activedescendant": activeIndex >= 0 ? optionId(activeIndex) : undefined, value: query, onFocus: () => setOpen(true), onPointerDown: event => {
233
+ event.stopPropagation();
234
+ setOpen(true);
235
+ }, onChange: event => {
236
+ setQuery(event.currentTarget.value);
237
+ setVariableSearch(undefined);
238
+ setOutcome(undefined);
239
+ setLimit(pageSize);
240
+ setActive(undefined);
241
+ setOpen(true);
242
+ if (popup.current)
243
+ popup.current.scrollTop = 0;
244
+ }, onKeyDown: event => {
245
+ event.stopPropagation();
246
+ if (event.nativeEvent.isComposing)
247
+ return;
248
+ if (event.key === 'Escape' && open) {
249
+ event.preventDefault();
250
+ close();
251
+ }
252
+ else if (event.key === 'Tab' && !event.shiftKey && open) {
253
+ const first = popup.current?.querySelector('input, button');
254
+ if (first) {
255
+ event.preventDefault();
256
+ first.focus();
257
+ }
258
+ }
259
+ else if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
260
+ event.preventDefault();
261
+ setOpen(true);
262
+ if (activeIndex === visible.length - 1 && more && event.key === 'ArrowDown') {
263
+ setLimit(limit + pageSize);
264
+ }
265
+ else if (visible.length) {
266
+ const next = event.key === 'ArrowDown' ? activeIndex + 1 : (activeIndex < 0 ? -1 : activeIndex - 1);
267
+ setActive(visible[(next + visible.length) % visible.length]);
268
+ }
269
+ }
270
+ else if (event.key === 'Enter' && visible.length) {
271
+ event.preventDefault();
272
+ jump(active ?? visible[0]);
273
+ }
274
+ } }),
275
+ show && input.current && createPortal(React.createElement("div", { ref: popup, className: "tw-project-search__popup", ...(typeof input.current.showPopover === 'function' ? { popover: 'manual' } : {}), onKeyDown: event => {
276
+ const backToSearch = event.key === 'Tab' && event.shiftKey &&
277
+ event.target === popup.current.querySelector('input, button');
278
+ if (event.key !== 'Escape' && !backToSearch)
279
+ return;
280
+ event.preventDefault();
281
+ event.stopPropagation();
282
+ input.current.focus();
283
+ if (!backToSearch)
284
+ close();
285
+ }, onScroll: event => {
286
+ const panel = event.currentTarget;
287
+ if (more && panel.scrollHeight - panel.clientHeight - panel.scrollTop < 30) {
288
+ setLimit(limit + pageSize);
289
+ }
290
+ } },
291
+ !variableSearch && React.createElement("div", { className: "tw-project-search__replace-tools" },
292
+ React.createElement("input", { ref: replaceField, type: "text", autoComplete: "off", value: replacement, placeholder: japanese ? '置換後の文字列' : 'Replace with', "aria-label": japanese ? '置換後の文字列' : 'Replace with', onChange: event => { setReplacement(event.currentTarget.value); setOutcome(undefined); } }),
293
+ React.createElement("button", { type: "button", disabled: replacing || proposed === undefined, onClick: () => void replaceSelected() }, active?.kind === 'yaml' ? (japanese ? 'プレビューで置換' : 'Replace in preview') :
294
+ (japanese ? '選択箇所を置換' : 'Replace selected match'))),
295
+ !variableSearch && (outcome ? React.createElement("div", { className: "tw-project-search__empty", role: "status" }, replaceMessages[outcome][japanese ? 0 : 1]) :
296
+ replacement && !active ?
297
+ React.createElement("div", { className: "tw-project-search__empty", role: "status" }, pickMatch[japanese ? 0 : 1]) : null),
298
+ variableSearch ? React.createElement("fieldset", { className: "tw-project-search__filters" },
299
+ React.createElement("legend", null, japanese ? '変数へのアクセス' : 'Variable access'),
300
+ ['read', 'write'].map(access => React.createElement("button", { key: access, type: "button", "aria-pressed": variableSearch.access === access, onClick: () => {
301
+ setVariableSearch({ ...variableSearch, access });
302
+ setLimit(pageSize);
303
+ setActive(undefined);
304
+ } }, variableAccessLabels[access][japanese ? 0 : 1])),
305
+ React.createElement("button", { type: "button", onClick: () => {
306
+ setVariableSearch(undefined);
307
+ setLimit(pageSize);
308
+ setActive(undefined);
309
+ } }, japanese ? 'すべての検索に戻る' : 'Return to all search results')) : React.createElement("fieldset", { className: "tw-project-search__filters" },
310
+ React.createElement("legend", null, japanese ? '検索対象' : 'Search in'),
311
+ filters.filter(filter => documents || !filter.kinds.includes('yaml')).map(filter => React.createElement("label", { key: filter.kinds[0] },
312
+ React.createElement("input", { type: "checkbox", checked: kinds.has(filter.kinds[0]), onChange: event => {
313
+ const checked = event.currentTarget.checked;
314
+ const next = new Set(kinds);
315
+ filter.kinds.forEach(kind => checked ? next.add(kind) : next.delete(kind));
316
+ setKinds(next);
317
+ setLimit(pageSize);
318
+ setActive(undefined);
319
+ } }),
320
+ filter.label[japanese ? 0 : 1]))),
321
+ React.createElement("div", { role: "listbox", id: listId, "aria-label": japanese ? '検索結果' : 'Search results' }, groups.map(group => React.createElement("div", { key: group.kind, role: "group", "aria-labelledby": `${listId}-${group.kind}` },
322
+ React.createElement("div", { id: `${listId}-${group.kind}`, className: "tw-project-search__heading" },
323
+ group.title,
324
+ " ",
325
+ React.createElement("span", null, group.results.length)),
326
+ group.results.slice(0, limit).map(result => {
327
+ const index = visible.indexOf(result);
328
+ const name = result.kind === 'yaml' ? result.document.filename :
329
+ result.target.isStage ? (japanese ? 'ステージ' : 'Stage') : result.target.getName();
330
+ const access = 'variableAccess' in result && result.variableAccess;
331
+ return React.createElement("div", { key: index, id: optionId(index), role: "option", className: "tw-project-search__option", "aria-selected": result === active, onPointerDown: event => event.preventDefault(), onClick: () => choose(result) },
332
+ React.createElement("span", null, result.label),
333
+ React.createElement("small", null, [name, result.detail, access && variableAccessLabels[access][japanese ? 0 : 1], !canEdit(result) &&
334
+ (japanese ? '閲覧専用' : 'Read only')].filter(Boolean).join(' · ')));
335
+ })))),
336
+ query.trim() && !groups.length &&
337
+ React.createElement("div", { className: "tw-project-search__empty", role: "status" }, japanese ? '一致する項目がありません' : 'No matches')), input.current.ownerDocument.body));
338
+ }
339
+ export function centerProjectComment(workspace, id, blockId) {
340
+ if (!workspace?.scrollbar)
341
+ return;
342
+ const comment = blockId ? workspace.getBlockById(blockId)?.comment : workspace.getCommentById(id);
343
+ if (!comment)
344
+ return;
345
+ comment.setVisible?.(true);
346
+ const { topLeft, bottomRight } = comment.getBoundingRectangle();
347
+ const { contentLeft, contentTop, viewWidth, viewHeight } = workspace.getMetrics();
348
+ workspace.scrollbar.set((topLeft.x + bottomRight.x) * workspace.scale / 2 - contentLeft - viewWidth / 2, (topLeft.y + bottomRight.y) * workspace.scale / 2 - contentTop - viewHeight / 2);
349
+ comment.select?.();
350
+ }
351
+ export function ProjectSearch(search) {
352
+ const connection = connectionFor(search.project);
353
+ const [navigation, setNavigation] = React.useState(connection.navigation);
354
+ const [documents, setDocuments] = React.useState(connection.documents);
355
+ const frame = React.useRef();
356
+ React.useLayoutEffect(() => {
357
+ const update = () => {
358
+ setNavigation(connection.navigation);
359
+ setDocuments(connection.documents);
360
+ };
361
+ connection.listeners.add(update);
362
+ update();
363
+ return () => { connection.listeners.delete(update); };
364
+ }, [connection]);
365
+ React.useLayoutEffect(() => () => window.cancelAnimationFrame(frame.current), [navigation]);
366
+ if (!navigation)
367
+ return null;
368
+ const moveToResult = (result) => {
369
+ const { target } = result;
370
+ if (navigation.getTarget(target.id) !== target)
371
+ return;
372
+ const moved = activateTargetView(navigation, target.id, result.kind === 'sound' ? 2 : 'asset' in result ? 1 : 0);
373
+ if (!moved)
374
+ return;
375
+ return () => {
376
+ const current = moved.views.currentView();
377
+ return connection.navigation === navigation && navigation.getViews() === moved.views &&
378
+ navigation.getEditingTarget() === target && current?.id === moved.viewId &&
379
+ current.section === moved.section;
380
+ };
381
+ };
382
+ const select = (result) => {
383
+ if (result.kind === 'yaml') {
384
+ documents?.openYamlPreview(result.document.reference, result.range);
385
+ return;
386
+ }
387
+ const { target } = result;
388
+ const isDestination = moveToResult(result);
389
+ if (!isDestination)
390
+ return;
391
+ window.cancelAnimationFrame(frame.current);
392
+ frame.current = window.requestAnimationFrame(() => {
393
+ if (!isDestination())
394
+ return;
395
+ if ('asset' in result) {
396
+ const kind = result.kind === 'sound' ? 'sounds' : 'costumes';
397
+ const assets = kind === 'sounds' ? target.getSounds() : target.getCostumes();
398
+ const index = assets.indexOf(result.asset);
399
+ if (index >= 0) {
400
+ const views = navigation.getViews();
401
+ views.selectAsset(views.currentView().id, kind, index);
402
+ }
403
+ }
404
+ else if (result.kind === 'comment') {
405
+ if (target.comments?.[result.commentId] === result.comment) {
406
+ navigation.centerComment(result.commentId, result.comment.blockId);
407
+ }
408
+ }
409
+ else if (target.blocks.getBlock(result.block.id) === result.block) {
410
+ navigation.centerBlock(result.block.id);
411
+ }
412
+ });
413
+ };
414
+ const replace = async (result, value) => {
415
+ if (result.kind === 'yaml') {
416
+ return documents?.stageYamlReplacement?.(result.document.reference, result.range, result.document.source, value) ?
417
+ 'staged' : 'stale';
418
+ }
419
+ if (!result.edit)
420
+ return 'read-only';
421
+ const isDestination = moveToResult(result);
422
+ if (!isDestination)
423
+ return 'stale';
424
+ await new Promise(resolve => window.requestAnimationFrame(resolve));
425
+ if (!isDestination())
426
+ return 'stale';
427
+ const context = navigation.replacementContext?.();
428
+ if (!context)
429
+ return 'read-only';
430
+ const outcome = applyProjectSearchReplacement(search.project, context.workspace, context.Blockly, result, value);
431
+ // Let the workspace deliver its change event to the VM before querying it again.
432
+ if (outcome === 'applied')
433
+ await new Promise(resolve => window.setTimeout(resolve, 0));
434
+ return outcome;
435
+ };
436
+ return React.createElement(ProjectSearchBox, { ...search, documents, select, replace });
437
+ }
@@ -0,0 +1,10 @@
1
+ export interface ProjectSizeQuestion {
2
+ /** The bytes the project expands to. */
3
+ bytes: number;
4
+ /** The standard limit it is over. */
5
+ limit: number;
6
+ }
7
+ export declare function confirmLargeProject(document: Document | undefined, locale: string | undefined, { bytes, limit }: ProjectSizeQuestion, { className, signal }?: {
8
+ className?: string;
9
+ signal?: AbortSignal;
10
+ }): Promise<boolean>;
@@ -0,0 +1,64 @@
1
+ import { dialogAction, dialogActions } from '@kubohiroya/turbowarp-plus-editor-windows';
2
+ /**
3
+ * Ask whether to open a project larger than the Editor's standard limit (issue #428).
4
+ *
5
+ * The person sees how large the project is before anything is expanded, and decides for this one
6
+ * load. Nothing is remembered. Without a document to show the question in, or once the load is
7
+ * cancelled, the answer is no.
8
+ */
9
+ const MiB = 1024 * 1024;
10
+ const formatMiB = (bytes) => {
11
+ const value = bytes / MiB;
12
+ return value >= 10 ? Math.round(value).toString() : value.toFixed(1);
13
+ };
14
+ export function confirmLargeProject(document, locale, { bytes, limit }, { className, signal } = {}) {
15
+ if (!document?.body || signal?.aborted)
16
+ return Promise.resolve(false);
17
+ const ja = (locale || document.documentElement.lang || '').startsWith('ja');
18
+ return new Promise(resolve => {
19
+ const dialog = document.createElement('dialog');
20
+ if (typeof dialog.showModal !== 'function') {
21
+ resolve(false);
22
+ return;
23
+ }
24
+ const title = document.createElement('h2');
25
+ title.textContent = ja ? '大きな作品を開く' : 'Open a Large Project';
26
+ dialog.setAttribute('aria-label', title.textContent);
27
+ dialog.setAttribute('data-project-size-approval', '');
28
+ if (className)
29
+ dialog.className = className;
30
+ const message = document.createElement('p');
31
+ message.textContent = ja ?
32
+ `この作品は展開すると約 ${formatMiB(bytes)} MiB になり、標準の上限(${formatMiB(limit)} MiB)を超えています。` +
33
+ '開くと大量のメモリを使い、このタブが応答しなくなったり閉じたりすることがあります。' :
34
+ `This project expands to about ${formatMiB(bytes)} MiB, over the standard limit of ${formatMiB(limit)} MiB. ` +
35
+ 'Opening it uses a lot of memory and may make this tab stop responding or close.';
36
+ const advice = document.createElement('p');
37
+ advice.textContent = ja ?
38
+ '作成者や入手元に心当たりがない場合は、開かないでください。' :
39
+ 'Do not open it unless you know who made it or where it came from.';
40
+ const finish = (answer) => {
41
+ signal?.removeEventListener('abort', cancel);
42
+ if (dialog.open)
43
+ dialog.close();
44
+ dialog.remove();
45
+ resolve(answer);
46
+ };
47
+ const cancel = () => finish(false);
48
+ const button = (label, answer) => {
49
+ const node = document.createElement('button');
50
+ node.type = 'button';
51
+ node.textContent = label;
52
+ node.addEventListener('click', () => finish(answer));
53
+ return node;
54
+ };
55
+ const decline = button(ja ? '開かない' : 'Don’t Open', false);
56
+ dialog.addEventListener('cancel', event => { event.preventDefault(); cancel(); });
57
+ signal?.addEventListener('abort', cancel, { once: true });
58
+ dialog.append(title, message, advice, dialogActions(document, dialogAction(decline, 'cancel'), dialogAction(button(ja ? '開く' : 'Open', true), 'confirm')));
59
+ document.body.append(dialog);
60
+ dialog.showModal();
61
+ // The safe answer has the focus, so Enter alone does not open the project.
62
+ decline.focus();
63
+ });
64
+ }
@@ -0,0 +1,45 @@
1
+ import React from 'react';
2
+ import type { createStageControlsService } from './stage-controls.js';
3
+ /** The distribution owns both the registered controls and the view of their service. */
4
+ type Service = ReturnType<typeof createStageControlsService>;
5
+ interface StageControlsProps {
6
+ service: Service;
7
+ isSmall?: boolean;
8
+ menuLocale?: string;
9
+ }
10
+ interface StageControlsState {
11
+ controls: ReturnType<Service['snapshot']>;
12
+ panel: HTMLElement | null;
13
+ debuggerButton: HTMLElement | null;
14
+ recordButton: ReturnType<Service['recordButton']>;
15
+ }
16
+ declare class StageControlsView extends React.PureComponent<StageControlsProps, StageControlsState> {
17
+ unsubscribe?: () => void;
18
+ panelRoot?: HTMLElement | null;
19
+ mountedPanel?: HTMLElement | null;
20
+ constructor(props: StageControlsProps);
21
+ readService(): {
22
+ controls: {
23
+ visible: boolean;
24
+ expanded: boolean;
25
+ element: HTMLButtonElement | null;
26
+ ref(element: HTMLButtonElement | null): void;
27
+ id: string;
28
+ label: string;
29
+ text: string;
30
+ icon: string;
31
+ onClick: () => void;
32
+ }[];
33
+ panel: HTMLElement;
34
+ debuggerButton: HTMLElement;
35
+ recordButton: import("./stage-controls.js").RecordButton;
36
+ };
37
+ bindService(): void;
38
+ componentDidMount(): void;
39
+ componentDidUpdate(previous: StageControlsProps): void;
40
+ componentWillUnmount(): void;
41
+ handleChange(): void;
42
+ mountPanel(node: HTMLElement | null): void;
43
+ render(): React.JSX.Element;
44
+ }
45
+ export default StageControlsView;