@kubohiroya/turbowarp-plus-editor-code-views 0.6.0 → 0.7.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.
@@ -0,0 +1,486 @@
1
+ import { applyPlan, planMerge, planScopeChange, refreshEditor, undoPlan } from "./variable-merge-plan.js";
2
+ export { applyPlan, findVariable, planMerge, planScopeChange, refreshEditor, undoPlan } from "./variable-merge-plan.js";
3
+ const MESSAGES = {
4
+ en: {
5
+ variable: 'variable', list: 'list', stage: 'Stage',
6
+ mergeTitle: (kind) => kind === 'list' ? 'Merge lists' : 'Merge variables',
7
+ mergeLead: (a, b) => `“${b}” already exists. Merge “${a}” into “${b}”?`,
8
+ mergeBody: (a, b, n) => `${n} block${n === 1 ? '' : 's'} using “${a}” will use “${b}”, and “${a}” will be deleted.`,
9
+ perTarget: (target, n) => `${target}: ${n}`,
10
+ values: (a, b, aValue, bValue) => `“${b}” keeps its value ${bValue}. The value of “${a}”, ${aValue}, is discarded.`,
11
+ sensing: (n) => `${n} “( ) of ( )” block${n === 1 ? '' : 's'} will be updated.`,
12
+ makeGlobal: 'Make it for all sprites',
13
+ makeLocal: 'Make it for this sprite only',
14
+ globalLead: (a) => `Make “${a}” usable by all sprites?`,
15
+ localLead: (a, sprite) => `Make “${a}” usable by “${sprite}” only?`,
16
+ warnShare: 'Clones of this sprite kept a value each; afterwards they all share one value.',
17
+ warnSplit: 'Clones of this sprite shared one value; afterwards each clone keeps its own.',
18
+ warnDynamic: '“( ) of ( )” blocks whose sprite is a reporter cannot be updated and may stop finding it.',
19
+ refusedTitle: 'Cannot do this',
20
+ refusals: {
21
+ same: 'There is nothing to change.',
22
+ missing: 'The variable no longer exists.',
23
+ type: 'Only a variable with a variable, or a list with a list, can be merged.',
24
+ cloud: 'Cloud variables cannot be merged or moved.',
25
+ stage: 'The Stage has no variables of its own; choose a sprite first.',
26
+ 'not-visible': (owner, targets) => `That one belongs to “${owner}” only, so it cannot be seen from: ${targets}.`,
27
+ 'used-elsewhere': (sprite, targets) => `It cannot belong to “${sprite}” only, because it is also used in: ${targets}.`,
28
+ 'name-taken': (targets) => `These already have one with the same name: ${targets}.`
29
+ },
30
+ merge: 'Merge', change: 'Change', cancel: 'Cancel', ok: 'OK',
31
+ merged: (a, b) => `Merged “${a}” into “${b}”.`,
32
+ madeGlobal: (a) => `“${a}” is now for all sprites.`,
33
+ madeLocal: (a) => `“${a}” is now for this sprite only.`,
34
+ undo: 'Undo', undone: 'Undone.', close: 'Close', failed: 'The change could not be made.',
35
+ items: (n) => `${n} item${n === 1 ? '' : 's'}`
36
+ },
37
+ ja: {
38
+ variable: '変数', list: 'リスト', stage: 'ステージ',
39
+ mergeTitle: (kind) => kind === 'list' ? 'リストを統合' : '変数を統合',
40
+ mergeLead: (a, b) => `「${b}」は既にあります。「${a}」を「${b}」に統合しますか?`,
41
+ mergeBody: (a, b, n) => `「${a}」を使っているブロック ${n} 個を「${b}」に付け替え、「${a}」を削除します。`,
42
+ perTarget: (target, n) => `${target}: ${n} 個`,
43
+ values: (a, b, aValue, bValue) => `「${b}」の値 ${bValue} を残し、「${a}」の値 ${aValue} は捨てます。`,
44
+ sensing: (n) => `「( ) の ( )」のブロック ${n} 個も書き換えます。`,
45
+ makeGlobal: 'すべてのスプライト用にする',
46
+ makeLocal: 'このスプライトのみにする',
47
+ globalLead: (a) => `「${a}」を、すべてのスプライトで使えるようにしますか?`,
48
+ localLead: (a, sprite) => `「${a}」を、「${sprite}」だけで使えるようにしますか?`,
49
+ warnShare: 'このスプライトのクローンは、これまでそれぞれ別の値を持っていましたが、変更後は1つの値を共有します。',
50
+ warnSplit: 'このスプライトのクローンは、これまで1つの値を共有していましたが、変更後はそれぞれ別の値を持ちます。',
51
+ warnDynamic: '「( ) の ( )」でスプライトをブロックで指定しているものは書き換えられず、値を読めなくなることがあります。',
52
+ refusedTitle: 'この変更はできません',
53
+ refusals: {
54
+ same: '変えるものがありません。',
55
+ missing: 'その変数はもうありません。',
56
+ type: '変数は変数と、リストはリストとだけ統合できます。',
57
+ cloud: 'クラウド変数は統合やスコープの変更ができません。',
58
+ stage: 'ステージだけの変数はありません。先にスプライトを選んでください。',
59
+ 'not-visible': (owner, targets) => `それは「${owner}」だけのものなので、次の場所からは見えません: ${targets}`,
60
+ 'used-elsewhere': (sprite, targets) => `次の場所でも使われているため、「${sprite}」だけのものにはできません: ${targets}`,
61
+ 'name-taken': (targets) => `次の場所に同じ名前のものが既にあります: ${targets}`
62
+ },
63
+ merge: '統合', change: '変更', cancel: 'キャンセル', ok: 'OK',
64
+ merged: (a, b) => `「${a}」を「${b}」に統合しました。`,
65
+ madeGlobal: (a) => `「${a}」をすべてのスプライト用にしました。`,
66
+ madeLocal: (a) => `「${a}」をこのスプライトのみにしました。`,
67
+ undo: '元に戻す', undone: '元に戻しました。', close: '閉じる', failed: '変更できませんでした。',
68
+ items: (n) => `${n} 個の項目`
69
+ },
70
+ 'ja-hira': {
71
+ variable: 'へんすう', list: 'リスト', stage: 'ステージ',
72
+ mergeTitle: (kind) => kind === 'list' ? 'リストをまとめる' : 'へんすうをまとめる',
73
+ mergeLead: (a, b) => `「${b}」は もう あります。「${a}」を「${b}」に まとめますか?`,
74
+ mergeBody: (a, b, n) => `「${a}」を つかっている ブロック ${n}こを「${b}」に つけかえ、「${a}」を けします。`,
75
+ perTarget: (target, n) => `${target}: ${n}こ`,
76
+ values: (a, b, aValue, bValue) => `「${b}」の あたい ${bValue} を のこし、「${a}」の あたい ${aValue} は すてます。`,
77
+ sensing: (n) => `「( ) の ( )」の ブロック ${n}こも かきかえます。`,
78
+ makeGlobal: 'すべての スプライトように する',
79
+ makeLocal: 'この スプライトだけに する',
80
+ globalLead: (a) => `「${a}」を、すべての スプライトで つかえるように しますか?`,
81
+ localLead: (a, sprite) => `「${a}」を、「${sprite}」だけで つかえるように しますか?`,
82
+ warnShare: 'この スプライトの クローンは、いままで べつべつの あたいを もっていましたが、かえたあとは 1つの あたいを いっしょに つかいます。',
83
+ warnSplit: 'この スプライトの クローンは、いままで 1つの あたいを いっしょに つかっていましたが、かえたあとは べつべつの あたいを もちます。',
84
+ warnDynamic: '「( ) の ( )」で スプライトを ブロックで えらんでいる ものは かきかえられず、あたいを よめなく なることが あります。',
85
+ refusedTitle: 'この へんこうは できません',
86
+ refusals: {
87
+ same: 'かえる ものが ありません。',
88
+ missing: 'その へんすうは もう ありません。',
89
+ type: 'へんすうは へんすうと、リストは リストと だけ まとめられます。',
90
+ cloud: 'クラウドへんすうは まとめたり、つかえる はんいを かえたり できません。',
91
+ stage: 'ステージだけの へんすうは ありません。さきに スプライトを えらんでください。',
92
+ 'not-visible': (owner, targets) => `それは「${owner}」だけの ものなので、つぎの ばしょからは みえません: ${targets}`,
93
+ 'used-elsewhere': (sprite, targets) => `つぎの ばしょでも つかわれているので、「${sprite}」だけの ものには できません: ${targets}`,
94
+ 'name-taken': (targets) => `つぎの ばしょに おなじ なまえの ものが もう あります: ${targets}`
95
+ },
96
+ merge: 'まとめる', change: 'かえる', cancel: 'キャンセル', ok: 'OK',
97
+ merged: (a, b) => `「${a}」を「${b}」に まとめました。`,
98
+ madeGlobal: (a) => `「${a}」を すべての スプライトように しました。`,
99
+ madeLocal: (a) => `「${a}」を この スプライトだけに しました。`,
100
+ undo: 'もとに もどす', undone: 'もとに もどしました。', close: 'とじる', failed: 'かえられませんでした。',
101
+ items: (n) => `${n}この こうもく`
102
+ }
103
+ };
104
+ /**
105
+ * Messages for a locale: `ja-Hira` gets hiragana, other `ja` Japanese, anything else English.
106
+ * @param {string} locale The editor's language.
107
+ * @returns {VariableMergeMessages} The messages.
108
+ */
109
+ export const variableMergeMessages = (locale) => {
110
+ if (/^ja-hira/i.test(locale ?? ''))
111
+ return MESSAGES['ja-hira'];
112
+ if (/^ja(?:-|$)/i.test(locale ?? ''))
113
+ return MESSAGES.ja;
114
+ return MESSAGES.en;
115
+ };
116
+ const shorten = (text) => text.length > 40 ? `${text.slice(0, 39)}…` : text;
117
+ const formatValue = (value, list, m) => {
118
+ if (list)
119
+ return Array.isArray(value) ? m.items(value.length) : m.items(0);
120
+ return `“${shorten(String(value ?? ''))}”`;
121
+ };
122
+ /**
123
+ * The sentences a confirmation shows for a plan.
124
+ * @param {Plan} plan The plan.
125
+ * @param {VariableMergeMessages} m The messages.
126
+ * @returns {{title: string, lead: string, details: string[], warnings: string[], confirm: string}} What to show.
127
+ */
128
+ export const describePlan = (plan, m) => {
129
+ const list = plan.source.type === 'list';
130
+ const kind = list ? 'list' : 'variable';
131
+ const a = plan.source.name;
132
+ const b = plan.destination.name;
133
+ const total = plan.references.reduce((sum, { count }) => sum + count, 0);
134
+ const details = [];
135
+ let title;
136
+ let lead;
137
+ let confirm;
138
+ if (plan.kind === 'merge') {
139
+ title = m.mergeTitle(kind);
140
+ lead = m.mergeLead(a, b);
141
+ confirm = m.merge;
142
+ details.push(m.mergeBody(a, b, total));
143
+ details.push(...plan.references.map(({ target, count }) => m.perTarget(target, count)));
144
+ details.push(m.values(a, b, formatValue(plan.source.value, list, m), formatValue(plan.destination.value, list, m)));
145
+ }
146
+ else {
147
+ title = plan.kind === 'global' ? m.makeGlobal : m.makeLocal;
148
+ lead = plan.kind === 'global' ? m.globalLead(a) : m.localLead(a, plan.sprite ?? '');
149
+ confirm = m.change;
150
+ details.push(...plan.references.map(({ target, count }) => m.perTarget(target, count)));
151
+ }
152
+ if (plan.sensingReferences)
153
+ details.push(m.sensing(plan.sensingReferences));
154
+ const warnings = plan.warnings.map(warning => warning === 'clones-share' ? m.warnShare : warning === 'clones-split' ? m.warnSplit : m.warnDynamic);
155
+ return { title, lead, details, warnings, confirm };
156
+ };
157
+ /**
158
+ * The sentence for a refusal.
159
+ * @param {Refusal} refusal Why the change cannot be made.
160
+ * @param {VariableMergeMessages} m The messages.
161
+ * @returns {string} The sentence.
162
+ */
163
+ export const describeRefusal = (refusal, m) => {
164
+ const join = (names) => names.join(', ');
165
+ switch (refusal.code) {
166
+ case 'not-visible': return m.refusals['not-visible'](refusal.owner, join(refusal.targets));
167
+ case 'used-elsewhere': return m.refusals['used-elsewhere'](refusal.sprite, join(refusal.targets));
168
+ case 'name-taken': return m.refusals['name-taken'](join(refusal.targets));
169
+ default: return m.refusals[refusal.code];
170
+ }
171
+ };
172
+ const element = (document, tag, className, text) => {
173
+ const node = document.createElement(tag);
174
+ if (className)
175
+ node.className = className;
176
+ if (text !== undefined)
177
+ node.textContent = text;
178
+ return node;
179
+ };
180
+ /**
181
+ * Ask before a change, or explain why it cannot be made when there is no `onConfirm`.
182
+ * @returns {HTMLDialogElement} The open dialog.
183
+ */
184
+ export const openVariableMergeDialog = (document, { title, lead, details = [], warnings = [], confirm, cancel, onConfirm }) => {
185
+ const dialog = element(document, 'dialog', 'twPlusVariableMergeDialog');
186
+ dialog.setAttribute('aria-label', title);
187
+ const form = element(document, 'form');
188
+ form.method = 'dialog';
189
+ form.append(element(document, 'h2', undefined, title), element(document, 'p', 'twPlusVariableMergeLead', lead));
190
+ if (details.length) {
191
+ const list = element(document, 'ul', 'twPlusVariableMergeDetails');
192
+ for (const line of details)
193
+ list.append(element(document, 'li', undefined, line));
194
+ form.append(list);
195
+ }
196
+ for (const line of warnings) {
197
+ const warning = element(document, 'p', 'twPlusVariableMergeWarning', line);
198
+ warning.setAttribute('role', 'note');
199
+ form.append(warning);
200
+ }
201
+ const footer = element(document, 'footer', 'tw-plus-dialog-actions');
202
+ let cancelButton = null;
203
+ if (onConfirm && cancel) {
204
+ cancelButton = element(document, 'button', undefined, cancel);
205
+ cancelButton.type = 'button';
206
+ cancelButton.dataset.dialogAction = 'cancel';
207
+ footer.append(cancelButton);
208
+ }
209
+ const submit = element(document, 'button', undefined, confirm);
210
+ submit.type = 'submit';
211
+ submit.dataset.dialogAction = 'confirm';
212
+ footer.append(submit);
213
+ form.append(footer);
214
+ dialog.append(form);
215
+ let open = true;
216
+ const close = () => {
217
+ if (!open)
218
+ return;
219
+ open = false;
220
+ if (dialog.open)
221
+ dialog.close();
222
+ dialog.remove();
223
+ };
224
+ cancelButton?.addEventListener('click', close);
225
+ dialog.addEventListener('cancel', event => {
226
+ event.preventDefault();
227
+ close();
228
+ });
229
+ form.addEventListener('submit', event => {
230
+ event.preventDefault();
231
+ close();
232
+ onConfirm?.();
233
+ });
234
+ document.body.append(dialog);
235
+ if (typeof dialog.showModal === 'function')
236
+ dialog.showModal();
237
+ else
238
+ dialog.setAttribute('open', '');
239
+ (cancelButton ?? submit).focus();
240
+ return dialog;
241
+ };
242
+ const SVG = 'http://www.w3.org/2000/svg';
243
+ const closeIcon = (document) => {
244
+ const svg = document.createElementNS(SVG, 'svg');
245
+ svg.setAttribute('viewBox', '0 0 16 16');
246
+ svg.setAttribute('aria-hidden', 'true');
247
+ svg.setAttribute('focusable', 'false');
248
+ const path = document.createElementNS(SVG, 'path');
249
+ path.setAttribute('d', 'M4 4l8 8M12 4l-8 8');
250
+ path.setAttribute('stroke', 'currentColor');
251
+ path.setAttribute('stroke-width', '2');
252
+ path.setAttribute('stroke-linecap', 'round');
253
+ svg.append(path);
254
+ return svg;
255
+ };
256
+ const notices = new WeakMap();
257
+ /**
258
+ * Say what changed, with an Undo button when the change can be undone. One notice per document:
259
+ * a new one replaces the last. It hides after `timeout` ms unless the pointer or focus is on it.
260
+ * @returns {() => void} A function that removes it.
261
+ */
262
+ export const showVariableMergeNotice = (document, text, m, onUndo, timeout = 10000) => {
263
+ notices.get(document)?.();
264
+ const notice = element(document, 'div', 'twPlusVariableMergeNotice');
265
+ notice.setAttribute('role', 'status');
266
+ notice.append(element(document, 'span', undefined, text));
267
+ const view = document.defaultView;
268
+ let timer;
269
+ const remove = () => {
270
+ if (timer !== undefined)
271
+ (view ?? globalThis).clearTimeout(timer);
272
+ timer = undefined;
273
+ notice.remove();
274
+ if (notices.get(document) === remove)
275
+ notices.delete(document);
276
+ };
277
+ if (onUndo) {
278
+ const undo = element(document, 'button', 'twPlusVariableMergeUndo', m.undo);
279
+ undo.type = 'button';
280
+ undo.addEventListener('click', () => {
281
+ remove();
282
+ onUndo();
283
+ });
284
+ notice.append(undo);
285
+ }
286
+ const close = element(document, 'button', 'twPlusVariableMergeClose');
287
+ close.type = 'button';
288
+ close.title = m.close;
289
+ close.setAttribute('aria-label', m.close);
290
+ close.append(closeIcon(document));
291
+ close.addEventListener('click', remove);
292
+ notice.append(close);
293
+ const arm = () => {
294
+ if (timer !== undefined)
295
+ (view ?? globalThis).clearTimeout(timer);
296
+ timer = (view ?? globalThis).setTimeout(remove, timeout);
297
+ };
298
+ const hold = () => {
299
+ if (timer !== undefined)
300
+ (view ?? globalThis).clearTimeout(timer);
301
+ timer = undefined;
302
+ };
303
+ notice.addEventListener('pointerenter', hold);
304
+ notice.addEventListener('focusin', hold);
305
+ notice.addEventListener('pointerleave', arm);
306
+ notice.addEventListener('focusout', arm);
307
+ document.body.append(notice);
308
+ notices.set(document, remove);
309
+ arm();
310
+ return remove;
311
+ };
312
+ /**
313
+ * Patch ScratchBlocks so renames offer merging and the palette offers scope changes.
314
+ * @param {VmLike} vm The VM; its `blockListener` identifies the code area's workspace.
315
+ * @param {object} ScratchBlocks The loaded ScratchBlocks.
316
+ * @param {object} options How to find the document and the language, and where errors go.
317
+ * @returns {() => void} A function that removes the patches.
318
+ */
319
+ export function installVariableMerge(vm, ScratchBlocks, { document: fallbackDocument, locale, onError = error => console.error(error) } = {}) {
320
+ const variables = ScratchBlocks?.Variables;
321
+ if (!variables?.renameVariable || !variables.validateScalarVarOrListName_)
322
+ return () => { };
323
+ const getLocale = () => (typeof locale === 'function' ? locale() : locale) ??
324
+ ScratchBlocks.ScratchMsgs?.currentLocale_ ?? 'en';
325
+ const isCodeWorkspace = (workspace) => {
326
+ const main = workspace?.targetWorkspace ?? workspace;
327
+ if (!main)
328
+ return false;
329
+ if (vm.blockListener && Array.isArray(main.listeners_))
330
+ return main.listeners_.includes(vm.blockListener);
331
+ return main === ScratchBlocks.getMainWorkspace?.();
332
+ };
333
+ const documentOf = (workspace) => {
334
+ const main = workspace?.targetWorkspace ?? workspace;
335
+ return main?.getInjectionDiv?.()?.ownerDocument ?? fallbackDocument ?? globalThis.document;
336
+ };
337
+ const carryOut = (document, plan, done) => {
338
+ const m = variableMergeMessages(getLocale());
339
+ try {
340
+ const record = applyPlan(vm, plan);
341
+ refreshEditor(vm);
342
+ showVariableMergeNotice(document, done, m, () => {
343
+ try {
344
+ undoPlan(vm, record);
345
+ refreshEditor(vm);
346
+ showVariableMergeNotice(document, m.undone, m, undefined, 3000);
347
+ }
348
+ catch (error) {
349
+ onError(error);
350
+ showVariableMergeNotice(document, m.failed, m);
351
+ }
352
+ });
353
+ }
354
+ catch (error) {
355
+ onError(error);
356
+ showVariableMergeNotice(document, m.failed, m);
357
+ }
358
+ };
359
+ const offer = (workspace, result) => {
360
+ const document = documentOf(workspace);
361
+ if (!document)
362
+ return;
363
+ const m = variableMergeMessages(getLocale());
364
+ if ('refusal' in result) {
365
+ openVariableMergeDialog(document, { title: m.refusedTitle, lead: describeRefusal(result.refusal, m), confirm: m.ok });
366
+ return;
367
+ }
368
+ const { plan } = result;
369
+ const text = describePlan(plan, m);
370
+ const done = plan.kind === 'merge' ? m.merged(plan.source.name, plan.destination.name) :
371
+ plan.kind === 'global' ? m.madeGlobal(plan.source.name) : m.madeLocal(plan.source.name);
372
+ openVariableMergeDialog(document, { ...text, cancel: m.cancel, onConfirm: () => carryOut(document, plan, done) });
373
+ };
374
+ // Renaming: the validator refuses a taken name with an alert. When the name belongs to another
375
+ // variable of the same type that this workspace can see, offer to merge into it instead.
376
+ const { renameVariable, createVariable, validateScalarVarOrListName_: validate } = variables;
377
+ let pending = null;
378
+ variables.renameVariable = function (workspace, variable, ...rest) {
379
+ pending = { workspace: workspace, variable: variable };
380
+ return renameVariable.call(this, workspace, variable, ...rest);
381
+ };
382
+ if (createVariable) {
383
+ variables.createVariable = function (...args) {
384
+ pending = null;
385
+ return createVariable.apply(this, args);
386
+ };
387
+ }
388
+ variables.validateScalarVarOrListName_ = function (name, workspace, additionalVars, isCloud, type, ...rest) {
389
+ const rename = pending;
390
+ if (rename && rename.workspace === workspace && rename.variable.type === type) {
391
+ pending = null;
392
+ const ws = workspace;
393
+ const trimmed = typeof name === 'string' ? (variables.trimName_?.(name) ?? name.trim()) : '';
394
+ const full = isCloud ? `${variables.CLOUD_PREFIX ?? ''}${trimmed}` : trimmed;
395
+ const existing = trimmed ? ws.getVariable?.(full, type) : null;
396
+ if (existing && existing.getId() !== rename.variable.getId() && isCodeWorkspace(ws)) {
397
+ const [sourceId, destinationId] = [rename.variable.getId(), existing.getId()];
398
+ // Let the rename prompt finish closing first.
399
+ setTimeout(() => {
400
+ try {
401
+ offer(ws, planMerge(vm, sourceId, destinationId));
402
+ }
403
+ catch (error) {
404
+ onError(error);
405
+ }
406
+ });
407
+ return null;
408
+ }
409
+ }
410
+ return validate.call(this, name, workspace, additionalVars, isCloud, type, ...rest);
411
+ };
412
+ // The palette: the variable and list blocks' context menus get a scope change.
413
+ const data = ScratchBlocks.Constants?.Data;
414
+ const menus = [
415
+ [data?.CUSTOM_CONTEXT_MENU_GET_VARIABLE_MIXIN, 'VARIABLE'],
416
+ [data?.CUSTOM_CONTEXT_MENU_GET_LIST_MIXIN, 'LIST']
417
+ ];
418
+ const restoreMenus = [];
419
+ for (const [mixin, fieldName] of menus) {
420
+ const original = mixin?.customContextMenu;
421
+ if (!mixin || !original)
422
+ continue;
423
+ mixin.customContextMenu = function (options) {
424
+ original.call(this, options);
425
+ try {
426
+ if (!this.isInFlyout || this.isCollapsed?.())
427
+ return;
428
+ const id = this.getField?.(fieldName)?.getVariable?.()?.getId?.();
429
+ const target = vm.editingTarget;
430
+ const workspace = this.workspace;
431
+ if (!id || !target || target.isStage || !isCodeWorkspace(workspace))
432
+ return;
433
+ const global = Object.hasOwn(vm.runtime.getTargetForStage().variables, id);
434
+ const m = variableMergeMessages(getLocale());
435
+ options.push({
436
+ text: global ? m.makeLocal : m.makeGlobal,
437
+ enabled: true,
438
+ callback: () => {
439
+ try {
440
+ offer(workspace, planScopeChange(vm, id, global ? 'local' : 'global', target));
441
+ }
442
+ catch (error) {
443
+ onError(error);
444
+ }
445
+ }
446
+ });
447
+ }
448
+ catch (error) {
449
+ onError(error);
450
+ }
451
+ };
452
+ restoreMenus.push(() => {
453
+ mixin.customContextMenu = original;
454
+ });
455
+ }
456
+ return () => {
457
+ variables.renameVariable = renameVariable;
458
+ if (createVariable)
459
+ variables.createVariable = createVariable;
460
+ variables.validateScalarVarOrListName_ = validate;
461
+ for (const restore of restoreMenus)
462
+ restore();
463
+ };
464
+ }
465
+ /**
466
+ * Install the merge and scope-change entry points once ScratchBlocks has loaded.
467
+ * @param {object} options The VM, how to get ScratchBlocks, and optionally the document and language.
468
+ * @returns {{ready: Promise<void>, dispose(): void}} Resolves once installed; dispose removes the patches.
469
+ */
470
+ export function attachVariableMerge({ vm, getBlockly, document, locale, onError }) {
471
+ let disposed = false;
472
+ let remove = null;
473
+ const ready = Promise.resolve().then(() => getBlockly()).then(ScratchBlocks => {
474
+ if (disposed || !ScratchBlocks)
475
+ return;
476
+ remove = installVariableMerge(vm, ScratchBlocks, { document, locale, onError });
477
+ });
478
+ return {
479
+ ready,
480
+ dispose() {
481
+ disposed = true;
482
+ remove?.();
483
+ remove = null;
484
+ }
485
+ };
486
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubohiroya/turbowarp-plus-editor-code-views",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "Code views for TurboWarp Plus Editor: code in tabs and windows, the detached block palette, script layout and block field editing",
5
5
  "type": "module",
6
6
  "license": "MPL-2.0",
@@ -26,6 +26,10 @@
26
26
  "types": "./dist/variable-references.d.ts",
27
27
  "default": "./dist/variable-references.js"
28
28
  },
29
+ "./variable-merge": {
30
+ "types": "./dist/variable-merge.d.ts",
31
+ "default": "./dist/variable-merge.js"
32
+ },
29
33
  "./target-combobox": {
30
34
  "types": "./dist/target-combobox.d.ts",
31
35
  "default": "./dist/target-combobox.js"
@@ -66,10 +70,26 @@
66
70
  "types": "./dist/block-number-input.d.ts",
67
71
  "default": "./dist/block-number-input.js"
68
72
  },
73
+ "./clean-up-comments": {
74
+ "types": "./dist/clean-up-comments.d.ts",
75
+ "default": "./dist/clean-up-comments.js"
76
+ },
77
+ "./sprite-copy-notice": {
78
+ "types": "./dist/sprite-copy-notice.d.ts",
79
+ "default": "./dist/sprite-copy-notice.js"
80
+ },
69
81
  "./script-layout": {
70
82
  "types": "./dist/script-layout-view.d.ts",
71
83
  "default": "./dist/script-layout-view.js"
72
84
  },
85
+ "./target-undo-history": {
86
+ "types": "./dist/target-undo-history.d.ts",
87
+ "default": "./dist/target-undo-history.js"
88
+ },
89
+ "./sprite-restore-history": {
90
+ "types": "./dist/sprite-restore-history.d.ts",
91
+ "default": "./dist/sprite-restore-history.js"
92
+ },
73
93
  "./asset-edit-session": {
74
94
  "types": "./dist/asset-edit-session.d.ts",
75
95
  "default": "./dist/asset-edit-session.js"
@@ -5,6 +5,10 @@
5
5
  * The vertical renderer sets `MAX_DISPLAY_LENGTH` to Infinity, so a text argument draws every
6
6
  * character and the block grows until it covers its neighbours. This caps what a text argument
7
7
  * shows, and edits a value that no longer fits in a dialog instead of the one-line inline editor.
8
+ *
9
+ * A line break cannot be typed into the inline editor, which is a one-line `<input>` where Enter
10
+ * finishes the edit. Shift+Enter there finishes the inline edit as Enter would, then continues in
11
+ * the dialog with a line break at the caret. The block shows a value up to its first line break.
8
12
  */
9
13
 
10
14
  /** Display budget in half-width columns. A wide character, such as a kanji, takes two. */
@@ -53,10 +57,11 @@ const text = (locale: string) => /^ja(?:-|$)/i.test(locale) ? {
53
57
  * @param {string} value The current value.
54
58
  * @param {string} locale The editor's language.
55
59
  * @param {(value: string) => void} save Called with the edited value when the dialog is saved.
60
+ * @param {number} [caret] Where the caret starts, in UTF-16 units; the end of the value by default.
56
61
  * @returns {HTMLDialogElement} The open dialog.
57
62
  */
58
63
  export const openArgumentTextDialog = (document: Document, value: string, locale: string,
59
- save: (value: string) => void) => {
64
+ save: (value: string) => void, caret = value.length) => {
60
65
  const labels = text(locale);
61
66
  const dialog = document.createElement('dialog');
62
67
  dialog.className = 'twPlusArgumentTextDialog';
@@ -111,10 +116,20 @@ export const openArgumentTextDialog = (document: Document, value: string, locale
111
116
  document.body.append(dialog);
112
117
  dialog.showModal();
113
118
  area.focus();
114
- area.setSelectionRange(area.value.length, area.value.length);
119
+ const at = Math.max(0, Math.min(caret, area.value.length));
120
+ area.setSelectionRange(at, at);
115
121
  return dialog;
116
122
  };
117
123
 
124
+ /**
125
+ * True for Shift+Enter alone, outside an IME composition.
126
+ * @param {KeyboardEvent} event The keydown.
127
+ * @returns {boolean} Whether the key asks for a line break.
128
+ */
129
+ export const isLineBreakKey = (event?: Partial<KeyboardEvent> | null) => !!event &&
130
+ (event.key === 'Enter' || event.keyCode === 13) && !!event.shiftKey &&
131
+ !event.ctrlKey && !event.metaKey && !event.altKey && !event.isComposing && event.keyCode !== 229;
132
+
118
133
  const installed = new WeakSet<object>();
119
134
 
120
135
  /**
@@ -129,7 +144,7 @@ export const installBlockArgumentText = ScratchBlocks => {
129
144
  if (!field?.showEditor_ || !field.getDisplayText_ || installed.has(field)) return;
130
145
  installed.add(field);
131
146
 
132
- const {getDisplayText_: displayText, showEditor_: showEditor} = field;
147
+ const {getDisplayText_: displayText, showEditor_: showEditor, onHtmlInputKeyDown_: keyDown} = field;
133
148
  field.getDisplayText_ = function (...args) {
134
149
  const value = this.text_;
135
150
  const cut = typeof value === 'string' ? argumentTextCut(value) : undefined;
@@ -152,21 +167,52 @@ export const installBlockArgumentText = ScratchBlocks => {
152
167
  }
153
168
  ScratchBlocks.WidgetDiv?.hide?.();
154
169
  ScratchBlocks.DropDownDiv?.hideWithoutAnimation?.();
170
+ openDialog(this, document, this.text_);
171
+ };
172
+
173
+ /**
174
+ * Edit a plain text field's value in the dialog and apply what is saved there.
175
+ * @param {object} self The field.
176
+ * @param {Document} document The editor's document.
177
+ * @param {string} value The value the dialog starts with.
178
+ * @param {number} [caret] Where the caret starts.
179
+ */
180
+ const openDialog = (self, document: Document, value: string, caret?: number) => {
181
+ const block = self.sourceBlock_;
155
182
  const locale = ScratchBlocks.ScratchMsgs?.currentLocale_ ?? document.documentElement.lang ?? 'en';
156
- openArgumentTextDialog(document, this.text_, locale, value => {
157
- if (this.sourceBlock_ !== block || !block.workspace) return;
158
- const validated = this.callValidator(value);
183
+ openArgumentTextDialog(document, value, locale, next => {
184
+ if (self.sourceBlock_ !== block || !block?.workspace) return;
185
+ const validated = self.callValidator(next);
159
186
  if (validated === null) return;
160
187
  const events = ScratchBlocks.Events;
161
188
  events?.setGroup?.(true);
162
189
  try {
163
190
  // Same path as the inline editor's save: one change event, then the render.
164
- this.setText(validated);
165
- this.onFinishEditing_?.(validated);
191
+ self.setText(validated);
192
+ self.onFinishEditing_?.(validated);
166
193
  } finally {
167
194
  events?.setGroup?.(false);
168
195
  }
169
196
  if (block.rendered) block.render();
170
- });
197
+ }, caret);
198
+ };
199
+
200
+ if (!keyDown) return;
201
+ field.onHtmlInputKeyDown_ = function (event, ...rest) {
202
+ const input: HTMLInputElement | null | undefined = FieldTextInput.htmlInput_;
203
+ const document = input?.ownerDocument;
204
+ if (!isLineBreakKey(event) || Object.getPrototypeOf(this) !== field || this.restrictor_ ||
205
+ !input || input.readOnly || !document) {
206
+ return keyDown.call(this, event, ...rest);
207
+ }
208
+ event.preventDefault?.();
209
+ const {value} = input;
210
+ const start = input.selectionStart ?? value.length;
211
+ const end = input.selectionEnd ?? start;
212
+ const next = `${value.slice(0, start)}\n${value.slice(end)}`;
213
+ // Finish the inline edit as Enter does, so the dialog edits a saved value.
214
+ ScratchBlocks.WidgetDiv?.hide?.();
215
+ ScratchBlocks.DropDownDiv?.hideWithoutAnimation?.();
216
+ if (this.sourceBlock_?.workspace) openDialog(this, document, next, start + 1);
171
217
  };
172
218
  };