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