@kubohiroya/turbowarp-plus-editor-code-views 0.2.0 → 0.3.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.
- package/README.ja.md +25 -0
- package/README.md +25 -0
- package/dist/code-pane.d.ts +2 -2
- package/dist/palette-category-visibility.d.ts +90 -0
- package/dist/palette-category-visibility.js +263 -0
- package/dist/palette-visibility-dialog.d.ts +68 -0
- package/dist/palette-visibility-dialog.js +176 -0
- package/package.json +13 -1
- package/src/code-pane.ts +3 -2
- package/src/palette-category-visibility.ts +300 -0
- package/src/palette-visibility-dialog.tsx +250 -0
- package/src/styles.css +197 -0
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import React from 'react';
|
|
2
|
+
import ReactDOM from 'react-dom';
|
|
3
|
+
import { ExtensionRow } from '@kubohiroya/turbowarp-extension-security-dialog/react';
|
|
4
|
+
import { standardGroups } from "./palette-category-visibility.js";
|
|
5
|
+
const standardNames = {
|
|
6
|
+
en: { motion: 'Motion', looks: 'Looks', sound: 'Sound', events: 'Events', control: 'Control', sensing: 'Sensing',
|
|
7
|
+
operators: 'Operators', variables: 'Variables', lists: 'Lists', myBlocks: 'My Blocks' },
|
|
8
|
+
ja: { motion: '動き', looks: '見た目', sound: '音', events: 'イベント', control: '制御', sensing: '調べる',
|
|
9
|
+
operators: '演算', variables: '変数', lists: 'リスト', myBlocks: 'ブロック定義' }
|
|
10
|
+
};
|
|
11
|
+
const standardColors = {
|
|
12
|
+
motion: '#4C97FF', looks: '#9966FF', sound: '#CF63CF', events: '#FFBF00', control: '#FFAB19', sensing: '#5CB1D6',
|
|
13
|
+
operators: '#59C059', variables: '#FF8C1A', lists: '#FF661A', myBlocks: '#FF6680'
|
|
14
|
+
};
|
|
15
|
+
const messages = {
|
|
16
|
+
en: {
|
|
17
|
+
title: 'Block groups shown in the palette', sprite: (name) => `Sprite “${name}”`, stage: 'Stage',
|
|
18
|
+
sets: 'Applicable sets', addSet: 'Add applicable set', setName: 'Set name', add: 'Add',
|
|
19
|
+
standard: 'Standard block groups', extensions: 'Extension block groups', used: (count) => `In use ${count}`,
|
|
20
|
+
hiddenInUse: (count) => `Hidden and in use: ${count}`, cancel: 'Cancel', apply: 'Apply', close: 'Close'
|
|
21
|
+
},
|
|
22
|
+
ja: {
|
|
23
|
+
title: 'パレット内のブロックグループの表示・非表示の設定', sprite: (name) => `スプライト「${name}」`, stage: '背景',
|
|
24
|
+
sets: '適用可能なセット', addSet: '適用可能なセットを追加', setName: 'セットの名前', add: '追加',
|
|
25
|
+
standard: '標準のブロックグループ', extensions: '機能拡張のブロックグループ', used: (count) => `使用中 ${count}`,
|
|
26
|
+
hiddenInUse: (count) => `非表示中・使用中 ${count} 件`, cancel: 'キャンセル', apply: '適用', close: '閉じる'
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
const isJapanese = (locale) => /^ja(?:-|$)/i.test(locale ?? '');
|
|
30
|
+
/**
|
|
31
|
+
* The screen that chooses which block groups the palette shows for one sprite or the stage: sets that
|
|
32
|
+
* switch several groups at once, the standard groups, and one row per extension drawn the same way as the
|
|
33
|
+
* extension review.
|
|
34
|
+
*/
|
|
35
|
+
export class PaletteVisibilityDialog extends React.PureComponent {
|
|
36
|
+
constructor(props) {
|
|
37
|
+
super(props);
|
|
38
|
+
this.state = { shown: new Set(props.initial), addedSets: [], naming: false, setName: '' };
|
|
39
|
+
}
|
|
40
|
+
get text() {
|
|
41
|
+
return isJapanese(this.props.locale) ? messages.ja : messages.en;
|
|
42
|
+
}
|
|
43
|
+
standard() {
|
|
44
|
+
// The stage has no motion blocks.
|
|
45
|
+
return standardGroups.filter(group => !(this.props.isStage && group === 'motion'));
|
|
46
|
+
}
|
|
47
|
+
available(groups) {
|
|
48
|
+
const offered = new Set([...this.standard(), ...this.props.extensions.map(extension => extension.id)]);
|
|
49
|
+
return groups.filter(group => offered.has(group));
|
|
50
|
+
}
|
|
51
|
+
toggle(group) {
|
|
52
|
+
this.setState(({ shown }) => {
|
|
53
|
+
const next = new Set(shown);
|
|
54
|
+
if (next.has(group))
|
|
55
|
+
next.delete(group);
|
|
56
|
+
else
|
|
57
|
+
next.add(group);
|
|
58
|
+
return { shown: next };
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
toggleSet(set) {
|
|
62
|
+
const groups = this.available(set.groups);
|
|
63
|
+
this.setState(({ shown }) => {
|
|
64
|
+
const next = new Set(shown);
|
|
65
|
+
const all = groups.every(group => next.has(group));
|
|
66
|
+
for (const group of groups) {
|
|
67
|
+
if (all)
|
|
68
|
+
next.delete(group);
|
|
69
|
+
else
|
|
70
|
+
next.add(group);
|
|
71
|
+
}
|
|
72
|
+
return { shown: next };
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
addSet() {
|
|
76
|
+
const name = this.state.setName.trim();
|
|
77
|
+
if (!name)
|
|
78
|
+
return;
|
|
79
|
+
const taken = new Set([...this.props.sets, ...this.state.addedSets].map(set => set.id));
|
|
80
|
+
let id = name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'set';
|
|
81
|
+
for (let index = 2; taken.has(id); index++)
|
|
82
|
+
id = `${id.replace(/-\d+$/, '')}-${index}`;
|
|
83
|
+
const groups = [...this.standard(), ...this.props.extensions.map(extension => extension.id)]
|
|
84
|
+
.filter(group => this.state.shown.has(group));
|
|
85
|
+
this.setState(({ addedSets }) => ({ addedSets: [...addedSets, { id, name, groups }], naming: false, setName: '' }));
|
|
86
|
+
}
|
|
87
|
+
apply() {
|
|
88
|
+
const order = [...this.standard(), ...this.props.extensions.map(extension => extension.id)];
|
|
89
|
+
this.props.onApply({ groups: order.filter(group => this.state.shown.has(group)), addedSets: this.state.addedSets });
|
|
90
|
+
}
|
|
91
|
+
render() {
|
|
92
|
+
const { locale, targetName, isStage, used, extensions, onCancel } = this.props;
|
|
93
|
+
const { shown, naming, setName } = this.state;
|
|
94
|
+
const text = this.text;
|
|
95
|
+
const names = isJapanese(locale) ? standardNames.ja : standardNames.en;
|
|
96
|
+
const sets = [...this.props.sets, ...this.state.addedSets];
|
|
97
|
+
const hiddenInUse = [...used].filter(([group, count]) => count > 0 && !shown.has(group)).length;
|
|
98
|
+
const usedBadge = (group) => !shown.has(group) && (used.get(group) ?? 0) > 0 && (React.createElement("span", { className: "tw-palette-visibility-used" }, text.used(used.get(group))));
|
|
99
|
+
return (React.createElement("div", { className: "tw-palette-visibility" },
|
|
100
|
+
React.createElement("header", { className: "tw-palette-visibility-header" },
|
|
101
|
+
React.createElement("div", null,
|
|
102
|
+
React.createElement("h2", null, text.title),
|
|
103
|
+
React.createElement("p", null, isStage ? text.stage : text.sprite(targetName))),
|
|
104
|
+
React.createElement("button", { type: "button", className: "tw-palette-visibility-close", "aria-label": text.close, title: text.close, onClick: onCancel }, "\u00D7")),
|
|
105
|
+
React.createElement("section", { "aria-label": text.sets },
|
|
106
|
+
React.createElement("h3", null, text.sets),
|
|
107
|
+
React.createElement("div", { className: "tw-palette-visibility-sets" },
|
|
108
|
+
sets.map(set => {
|
|
109
|
+
const groups = this.available(set.groups);
|
|
110
|
+
const all = groups.length > 0 && groups.every(group => shown.has(group));
|
|
111
|
+
return (React.createElement("button", { key: set.id, type: "button", "aria-pressed": all, "data-set": set.id, onClick: () => this.toggleSet(set) },
|
|
112
|
+
set.name,
|
|
113
|
+
all ? ' ✓' : ''));
|
|
114
|
+
}),
|
|
115
|
+
naming ? (React.createElement("span", { className: "tw-palette-visibility-naming" },
|
|
116
|
+
React.createElement("input", { type: "text", "aria-label": text.setName, placeholder: text.setName, value: setName, autoFocus: true, onChange: event => this.setState({ setName: event.currentTarget.value }), onKeyDown: event => { if (event.key === 'Enter')
|
|
117
|
+
this.addSet(); } }),
|
|
118
|
+
React.createElement("button", { type: "button", onClick: () => this.addSet() }, text.add))) : (React.createElement("button", { type: "button", className: "tw-palette-visibility-add-set", onClick: () => this.setState({ naming: true }) },
|
|
119
|
+
"\uFF0B",
|
|
120
|
+
text.addSet)))),
|
|
121
|
+
React.createElement("section", { "aria-label": text.standard },
|
|
122
|
+
React.createElement("h3", null, text.standard),
|
|
123
|
+
React.createElement("div", { className: "tw-palette-visibility-standard" }, this.standard().map(group => (React.createElement("label", { key: group, "data-group": group },
|
|
124
|
+
React.createElement("input", { type: "checkbox", checked: shown.has(group), onChange: () => this.toggle(group) }),
|
|
125
|
+
React.createElement("span", { className: "tw-palette-visibility-swatch", style: { color: standardColors[group] }, "aria-hidden": "true" }, "\u25CF"),
|
|
126
|
+
names[group],
|
|
127
|
+
usedBadge(group)))))),
|
|
128
|
+
extensions.length > 0 && (React.createElement("section", { "aria-label": text.extensions },
|
|
129
|
+
React.createElement("h3", null, text.extensions),
|
|
130
|
+
React.createElement("div", { className: "twextsec-review" },
|
|
131
|
+
React.createElement("ul", { className: "twextsec-rows" }, extensions.map(extension => (React.createElement(ExtensionRow, { key: extension.id, metadata: extension.metadata, ids: [extension.id], locale: locale, itemProps: { 'data-group': extension.id }, pick: { checked: shown.has(extension.id), onToggle: () => this.toggle(extension.id) } }, usedBadge(extension.id)))))))),
|
|
132
|
+
React.createElement("footer", { className: "tw-palette-visibility-footer" },
|
|
133
|
+
React.createElement("span", { role: "status" }, hiddenInUse > 0 ? text.hiddenInUse(hiddenInUse) : ''),
|
|
134
|
+
React.createElement("span", null,
|
|
135
|
+
React.createElement("button", { type: "button", onClick: onCancel }, text.cancel),
|
|
136
|
+
React.createElement("button", { type: "button", className: "tw-palette-visibility-apply", onClick: () => this.apply() }, text.apply)))));
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
/** Opens the screen as a modal `<dialog>` in `document`. Returns the function that closes it. */
|
|
140
|
+
export function openPaletteVisibilityDialog(document, props) {
|
|
141
|
+
const dialog = document.createElement('dialog');
|
|
142
|
+
dialog.className = 'tw-palette-visibility-dialog';
|
|
143
|
+
dialog.setAttribute('aria-label', (isJapanese(props.locale) ? messages.ja : messages.en).title);
|
|
144
|
+
document.body.append(dialog);
|
|
145
|
+
let open = true;
|
|
146
|
+
const close = () => {
|
|
147
|
+
if (!open)
|
|
148
|
+
return;
|
|
149
|
+
open = false;
|
|
150
|
+
ReactDOM.unmountComponentAtNode(dialog);
|
|
151
|
+
if (dialog.open && typeof dialog.close === 'function')
|
|
152
|
+
dialog.close();
|
|
153
|
+
dialog.remove();
|
|
154
|
+
};
|
|
155
|
+
dialog.addEventListener('cancel', event => {
|
|
156
|
+
event.preventDefault();
|
|
157
|
+
props.onCancel();
|
|
158
|
+
close();
|
|
159
|
+
});
|
|
160
|
+
ReactDOM.render(React.createElement(PaletteVisibilityDialog, {
|
|
161
|
+
...props,
|
|
162
|
+
onApply: choice => {
|
|
163
|
+
close();
|
|
164
|
+
props.onApply(choice);
|
|
165
|
+
},
|
|
166
|
+
onCancel: () => {
|
|
167
|
+
close();
|
|
168
|
+
props.onCancel();
|
|
169
|
+
}
|
|
170
|
+
}), dialog);
|
|
171
|
+
if (typeof dialog.showModal === 'function')
|
|
172
|
+
dialog.showModal();
|
|
173
|
+
else
|
|
174
|
+
dialog.setAttribute('open', '');
|
|
175
|
+
return close;
|
|
176
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kubohiroya/turbowarp-plus-editor-code-views",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.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",
|
|
@@ -50,6 +50,14 @@
|
|
|
50
50
|
"types": "./dist/palette-dropdown-resize.d.ts",
|
|
51
51
|
"default": "./dist/palette-dropdown-resize.js"
|
|
52
52
|
},
|
|
53
|
+
"./palette-category-visibility": {
|
|
54
|
+
"types": "./dist/palette-category-visibility.d.ts",
|
|
55
|
+
"default": "./dist/palette-category-visibility.js"
|
|
56
|
+
},
|
|
57
|
+
"./palette-visibility-dialog": {
|
|
58
|
+
"types": "./dist/palette-visibility-dialog.d.ts",
|
|
59
|
+
"default": "./dist/palette-visibility-dialog.js"
|
|
60
|
+
},
|
|
53
61
|
"./block-argument-text": {
|
|
54
62
|
"types": "./dist/block-argument-text.d.ts",
|
|
55
63
|
"default": "./dist/block-argument-text.js"
|
|
@@ -86,11 +94,15 @@
|
|
|
86
94
|
"@kubohiroya/turbowarp-script-transfer": "0.1.5"
|
|
87
95
|
},
|
|
88
96
|
"peerDependencies": {
|
|
97
|
+
"@kubohiroya/sb3-toolchain": ">=0.25.1 <0.26.0",
|
|
98
|
+
"@kubohiroya/turbowarp-extension-security-dialog": ">=0.9.0 <0.10.0",
|
|
89
99
|
"@kubohiroya/turbowarp-plus-editor-windows": ">=0.2.0 <0.3.0",
|
|
90
100
|
"react": ">=16.14",
|
|
91
101
|
"react-dom": ">=16.14"
|
|
92
102
|
},
|
|
93
103
|
"devDependencies": {
|
|
104
|
+
"@kubohiroya/sb3-toolchain": "0.25.1",
|
|
105
|
+
"@kubohiroya/turbowarp-extension-security-dialog": "0.9.0",
|
|
94
106
|
"@kubohiroya/turbowarp-plus-editor-windows": "0.2.0",
|
|
95
107
|
"@types/react": "18.3.31",
|
|
96
108
|
"@types/react-dom": "18.3.7",
|
package/src/code-pane.ts
CHANGED
|
@@ -7,12 +7,13 @@ type Bridge = NonNullable<ReturnType<typeof getCodeSession>['bridge']>;
|
|
|
7
7
|
type Presentation = NonNullable<ReturnType<Bridge['capturePane']>>;
|
|
8
8
|
|
|
9
9
|
/** The code area of a tab as a saved workspace keeps it: zoom, scroll position and script view. */
|
|
10
|
-
|
|
10
|
+
// A type alias, not an interface, so it fits the workbench's `Record<string, unknown>` for a serialized pane.
|
|
11
|
+
export type SavedCodePane = {
|
|
11
12
|
scale: number;
|
|
12
13
|
x: number;
|
|
13
14
|
y: number;
|
|
14
15
|
scriptView?: ScriptView;
|
|
15
|
-
}
|
|
16
|
+
};
|
|
16
17
|
|
|
17
18
|
const scriptViews: readonly ScriptView[] = ['free', 'z', 'n'];
|
|
18
19
|
const finite = (value: unknown, limit: number): value is number =>
|
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
import {blockPaletteCommentMarker, formatBlockPaletteComment} from '@kubohiroya/sb3-toolchain/browser';
|
|
2
|
+
import type {BlockPaletteDocument, BlockPaletteSet} from '@kubohiroya/sb3-toolchain/browser';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Which block groups the palette shows for each sprite and the stage.
|
|
6
|
+
*
|
|
7
|
+
* The setting lives where sb3-toolchain source format 2 keeps it: one palette comment per sprite or
|
|
8
|
+
* stage (`block-palette.json` in a project folder). It changes only what the palette offers; blocks
|
|
9
|
+
* already in the code stay visible and editable.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/** The standard groups, by the palette's category IDs. `lists` is Plus's own split of `variables`. */
|
|
13
|
+
export const standardGroups = ['motion', 'looks', 'sound', 'events', 'control', 'sensing', 'operators', 'variables', 'lists',
|
|
14
|
+
'myBlocks'] as const;
|
|
15
|
+
|
|
16
|
+
export interface PaletteGroupSet {
|
|
17
|
+
id: string;
|
|
18
|
+
name: string;
|
|
19
|
+
groups: readonly string[];
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const builtinSetNames: Record<string, {en: string; ja: string}> = {
|
|
23
|
+
standard: {en: 'Standard', ja: '標準'},
|
|
24
|
+
expression: {en: 'Expression', ja: '表現'},
|
|
25
|
+
data: {en: 'Variables and lists', ja: '変数・リスト'},
|
|
26
|
+
basics: {en: 'Basic control', ja: '基本の制御'}
|
|
27
|
+
};
|
|
28
|
+
const builtinSetGroups: Record<string, readonly string[]> = {
|
|
29
|
+
standard: standardGroups,
|
|
30
|
+
expression: ['motion', 'looks', 'sound', 'sensing'],
|
|
31
|
+
data: ['variables', 'lists'],
|
|
32
|
+
basics: ['events', 'control', 'operators']
|
|
33
|
+
};
|
|
34
|
+
const japanese = (locale?: string) => /^ja(?:-|$)/i.test(locale ?? '');
|
|
35
|
+
|
|
36
|
+
/** The sets every project has, then the project's own sets from its stage palette comment. */
|
|
37
|
+
export function paletteGroupSets(locale?: string, projectSets: Record<string, BlockPaletteSet> = {}): PaletteGroupSet[] {
|
|
38
|
+
const builtin = Object.keys(builtinSetGroups).map(id => ({
|
|
39
|
+
id, name: builtinSetNames[id][japanese(locale) ? 'ja' : 'en'], groups: builtinSetGroups[id]
|
|
40
|
+
}));
|
|
41
|
+
return builtin.concat(Object.entries(projectSets).map(([id, set]) => ({id, name: set.name, groups: set.groups})));
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const standardPrefixes: Record<string, string> = {
|
|
45
|
+
motion: 'motion', looks: 'looks', sound: 'sound', event: 'events', control: 'control', sensing: 'sensing',
|
|
46
|
+
operator: 'operators', procedures: 'myBlocks', argument: 'myBlocks'
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
/** The group a block belongs to, or null for a block no palette group offers. */
|
|
50
|
+
export function groupOfOpcode(opcode: string): string | null {
|
|
51
|
+
const separator = opcode.indexOf('_');
|
|
52
|
+
if (separator <= 0) return null;
|
|
53
|
+
const prefix = opcode.slice(0, separator);
|
|
54
|
+
if (prefix === 'data') return /list/i.test(opcode.slice(separator + 1)) ? 'lists' : 'variables';
|
|
55
|
+
return standardPrefixes[prefix] ?? prefix;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
type BlockLike = {opcode?: string; shadow?: boolean};
|
|
59
|
+
type CommentLike = {text?: string; id?: string};
|
|
60
|
+
/** The parts of a VM target this module reads and writes. */
|
|
61
|
+
export interface PaletteTarget {
|
|
62
|
+
isStage: boolean;
|
|
63
|
+
getName(): string;
|
|
64
|
+
blocks?: {_blocks?: Record<string, BlockLike>};
|
|
65
|
+
comments: Record<string, CommentLike>;
|
|
66
|
+
createComment?(id: string, blockId: string | null, text: string, x: number, y: number, width: number, height: number,
|
|
67
|
+
minimized: boolean): void;
|
|
68
|
+
deleteComment?(id: string): void;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** How many blocks of each group the target's code uses. Menus and other shadow blocks are not counted. */
|
|
72
|
+
export function usedGroups(target: Pick<PaletteTarget, 'blocks'>): Map<string, number> {
|
|
73
|
+
const counts = new Map<string, number>();
|
|
74
|
+
for (const block of Object.values(target.blocks?._blocks ?? {})) {
|
|
75
|
+
if (!block || block.shadow || typeof block.opcode !== 'string') continue;
|
|
76
|
+
const group = groupOfOpcode(block.opcode);
|
|
77
|
+
if (group) counts.set(group, (counts.get(group) ?? 0) + 1);
|
|
78
|
+
}
|
|
79
|
+
return counts;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export interface TargetPalette {
|
|
83
|
+
/** The comment that holds the setting. */
|
|
84
|
+
commentId: string;
|
|
85
|
+
groups?: string[];
|
|
86
|
+
/** Present on the stage's comment only. */
|
|
87
|
+
order?: string[];
|
|
88
|
+
sets?: Record<string, BlockPaletteSet>;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const markedLine = (text: string) => text.split('\n').find(line => line.endsWith(blockPaletteCommentMarker));
|
|
92
|
+
|
|
93
|
+
/** The palette setting a target carries in its palette comment, or null when it has none or it cannot be read. */
|
|
94
|
+
export function readTargetPalette(target: Pick<PaletteTarget, 'comments'>): TargetPalette | null {
|
|
95
|
+
for (const [commentId, comment] of Object.entries(target.comments ?? {})) {
|
|
96
|
+
const line = typeof comment?.text === 'string' ? markedLine(comment.text) : undefined;
|
|
97
|
+
if (!line) continue;
|
|
98
|
+
try {
|
|
99
|
+
const value = JSON.parse(line.slice(0, -blockPaletteCommentMarker.length));
|
|
100
|
+
if (!value || typeof value !== 'object') return null;
|
|
101
|
+
const strings = (list: unknown) => Array.isArray(list) && list.every(item => typeof item === 'string') ?
|
|
102
|
+
list as string[] : undefined;
|
|
103
|
+
return {
|
|
104
|
+
commentId,
|
|
105
|
+
groups: strings(value.groups),
|
|
106
|
+
order: strings(value.order),
|
|
107
|
+
sets: value.sets && typeof value.sets === 'object' ? value.sets : undefined
|
|
108
|
+
};
|
|
109
|
+
} catch {
|
|
110
|
+
return null;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
return null;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* The groups shown when a target has no setting of its own: every standard group, and the groups of
|
|
118
|
+
* the extensions its code already uses, so an existing project opens with nothing missing.
|
|
119
|
+
*/
|
|
120
|
+
export function defaultVisibleGroups(target: Pick<PaletteTarget, 'blocks'>, extensionIds: readonly string[]): string[] {
|
|
121
|
+
const used = usedGroups(target);
|
|
122
|
+
return [...standardGroups, ...extensionIds.filter(id => used.has(id))];
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** The groups the palette shows for the target. */
|
|
126
|
+
export function visibleGroups(target: Pick<PaletteTarget, 'blocks' | 'comments'>, extensionIds: readonly string[]): Set<string> {
|
|
127
|
+
const groups = readTargetPalette(target)?.groups;
|
|
128
|
+
return new Set(groups ?? defaultVisibleGroups(target, extensionIds));
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Removes the categories the target does not show from a parsed toolbox, before the palette is drawn from it. */
|
|
132
|
+
export function filterToolboxTree(tree: Element | null | undefined, visible: ReadonlySet<string>): void {
|
|
133
|
+
if (!tree) return;
|
|
134
|
+
for (const category of Array.from(tree.querySelectorAll(':scope > category'))) {
|
|
135
|
+
const id = category.getAttribute('id');
|
|
136
|
+
if (id && !visible.has(id)) category.remove();
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const newCommentId = () => `twplus-palette-${Math.random().toString(36).slice(2, 10)}`;
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Stores the target's palette setting in its palette comment, as sb3-toolchain source format 2 reads it.
|
|
144
|
+
* A sprite whose groups equal its default gets no comment; the stage keeps one while it carries the
|
|
145
|
+
* project's group order or sets.
|
|
146
|
+
*/
|
|
147
|
+
export function writeTargetPalette(target: PaletteTarget, groups: readonly string[], {extensionIds = [], order, sets}: {
|
|
148
|
+
extensionIds?: readonly string[];
|
|
149
|
+
order?: readonly string[];
|
|
150
|
+
sets?: Record<string, BlockPaletteSet>;
|
|
151
|
+
} = {}): void {
|
|
152
|
+
const current = readTargetPalette(target);
|
|
153
|
+
const name = target.getName();
|
|
154
|
+
const isDefault = sameGroups(groups, defaultVisibleGroups(target, extensionIds));
|
|
155
|
+
const projectOrder = target.isStage ? order ?? current?.order : undefined;
|
|
156
|
+
const projectSets = target.isStage ? sets ?? current?.sets : undefined;
|
|
157
|
+
const keepsProjectSettings = (projectOrder && projectOrder.length > 0) ||
|
|
158
|
+
(projectSets && Object.keys(projectSets).length > 0);
|
|
159
|
+
if (isDefault && !keepsProjectSettings) {
|
|
160
|
+
if (current) target.deleteComment?.(current.commentId);
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
const document: BlockPaletteDocument = {formatVersion: 1};
|
|
164
|
+
if (projectOrder?.length) document.order = [...projectOrder];
|
|
165
|
+
if (projectSets && Object.keys(projectSets).length) document.sets = projectSets;
|
|
166
|
+
if (target.isStage) {
|
|
167
|
+
if (!isDefault) document.stage = {groups: [...groups]};
|
|
168
|
+
} else {
|
|
169
|
+
document.sprites = {[name]: {groups: [...groups]}};
|
|
170
|
+
}
|
|
171
|
+
const text = formatBlockPaletteComment(document, {isStage: target.isStage, name});
|
|
172
|
+
if (current) {
|
|
173
|
+
target.comments[current.commentId].text = text;
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
target.createComment?.(newCommentId(), null, text, 0, 0, 200, 200, true);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
const sameGroups = (left: readonly string[], right: readonly string[]) =>
|
|
180
|
+
left.length === right.length && new Set(left).size === left.length && left.every(group => right.includes(group));
|
|
181
|
+
|
|
182
|
+
/** The menu item that opens the group settings. */
|
|
183
|
+
export const paletteVisibilityMenuLabel = (locale: string) => japanese(locale) ? 'ブロックグループの表示・非表示の設定' :
|
|
184
|
+
'Show or hide block groups';
|
|
185
|
+
|
|
186
|
+
export interface PaletteMenuItem {
|
|
187
|
+
label: string;
|
|
188
|
+
onSelect(): void;
|
|
189
|
+
/** Draws a separator above the item. */
|
|
190
|
+
separated?: boolean;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
const menuButtonLabel = (locale: string) => japanese(locale) ? 'パレットのメニュー' : 'Palette menu';
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Adds a ▼ button at the end of the palette's category menu: after the categories, so it sits at the
|
|
197
|
+
* right end of a horizontal palette and at the bottom of a vertical one. Pressing it lists the items
|
|
198
|
+
* the host gives — the group settings and the host's extension items — and runs the one chosen.
|
|
199
|
+
*/
|
|
200
|
+
export function attachPaletteMenuButton(menu: HTMLElement, getLocale: () => string,
|
|
201
|
+
getItems: (locale: string) => readonly PaletteMenuItem[]) {
|
|
202
|
+
const doc = menu.ownerDocument;
|
|
203
|
+
const button = doc.createElement('button');
|
|
204
|
+
button.type = 'button';
|
|
205
|
+
button.className = 'tw-palette-menu-button';
|
|
206
|
+
button.textContent = '▼';
|
|
207
|
+
button.setAttribute('aria-haspopup', 'menu');
|
|
208
|
+
button.setAttribute('aria-expanded', 'false');
|
|
209
|
+
const label = () => {
|
|
210
|
+
const text = menuButtonLabel(getLocale());
|
|
211
|
+
button.setAttribute('aria-label', text);
|
|
212
|
+
button.title = text;
|
|
213
|
+
};
|
|
214
|
+
label();
|
|
215
|
+
let popup: HTMLElement | null = null;
|
|
216
|
+
const closeMenu = (focusButton = false) => {
|
|
217
|
+
if (!popup) return;
|
|
218
|
+
popup.remove();
|
|
219
|
+
popup = null;
|
|
220
|
+
button.setAttribute('aria-expanded', 'false');
|
|
221
|
+
doc.removeEventListener('pointerdown', outside, true);
|
|
222
|
+
doc.removeEventListener('keydown', keys, true);
|
|
223
|
+
if (focusButton) button.focus();
|
|
224
|
+
};
|
|
225
|
+
const outside = (event: Event) => {
|
|
226
|
+
if (popup && !popup.contains(event.target as Node) && event.target !== button) closeMenu();
|
|
227
|
+
};
|
|
228
|
+
const keys = (event: KeyboardEvent) => {
|
|
229
|
+
if (!popup) return;
|
|
230
|
+
const items = Array.from(popup.querySelectorAll<HTMLButtonElement>('[role="menuitem"]'));
|
|
231
|
+
const index = items.indexOf(doc.activeElement as HTMLButtonElement);
|
|
232
|
+
if (event.key === 'Escape') {
|
|
233
|
+
event.preventDefault();
|
|
234
|
+
closeMenu(true);
|
|
235
|
+
} else if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
|
|
236
|
+
event.preventDefault();
|
|
237
|
+
const step = event.key === 'ArrowDown' ? 1 : -1;
|
|
238
|
+
items[(index + step + items.length) % items.length]?.focus();
|
|
239
|
+
}
|
|
240
|
+
};
|
|
241
|
+
const openMenu = () => {
|
|
242
|
+
const locale = getLocale();
|
|
243
|
+
const items = getItems(locale);
|
|
244
|
+
if (!items.length) return;
|
|
245
|
+
popup = doc.createElement('div');
|
|
246
|
+
popup.className = 'tw-palette-menu';
|
|
247
|
+
popup.setAttribute('role', 'menu');
|
|
248
|
+
popup.setAttribute('aria-label', menuButtonLabel(locale));
|
|
249
|
+
for (const item of items) {
|
|
250
|
+
if (item.separated && popup.childElementCount) {
|
|
251
|
+
const separator = doc.createElement('div');
|
|
252
|
+
separator.setAttribute('role', 'separator');
|
|
253
|
+
popup.append(separator);
|
|
254
|
+
}
|
|
255
|
+
const entry = doc.createElement('button');
|
|
256
|
+
entry.type = 'button';
|
|
257
|
+
entry.setAttribute('role', 'menuitem');
|
|
258
|
+
entry.textContent = item.label;
|
|
259
|
+
entry.addEventListener('click', event => {
|
|
260
|
+
event.stopPropagation();
|
|
261
|
+
closeMenu();
|
|
262
|
+
item.onSelect();
|
|
263
|
+
});
|
|
264
|
+
popup.append(entry);
|
|
265
|
+
}
|
|
266
|
+
const rect = button.getBoundingClientRect();
|
|
267
|
+
const view = doc.defaultView;
|
|
268
|
+
popup.style.position = 'fixed';
|
|
269
|
+
popup.style.top = `${rect.bottom + 4}px`;
|
|
270
|
+
popup.style.right = `${Math.max(4, (view?.innerWidth ?? rect.right) - rect.right)}px`;
|
|
271
|
+
doc.body.append(popup);
|
|
272
|
+
button.setAttribute('aria-expanded', 'true');
|
|
273
|
+
doc.addEventListener('pointerdown', outside, true);
|
|
274
|
+
doc.addEventListener('keydown', keys, true);
|
|
275
|
+
popup.querySelector<HTMLButtonElement>('[role="menuitem"]')?.focus();
|
|
276
|
+
};
|
|
277
|
+
// The category menu reacts to presses on its items; this one only opens its own menu.
|
|
278
|
+
const press = (event: Event) => event.stopPropagation();
|
|
279
|
+
button.addEventListener('mousedown', press);
|
|
280
|
+
button.addEventListener('pointerdown', press);
|
|
281
|
+
button.addEventListener('click', event => {
|
|
282
|
+
event.stopPropagation();
|
|
283
|
+
if (popup) closeMenu();
|
|
284
|
+
else openMenu();
|
|
285
|
+
});
|
|
286
|
+
menu.append(button);
|
|
287
|
+
return {
|
|
288
|
+
button,
|
|
289
|
+
/** Puts the button back at the end after the host rebuilds the menu, and follows the locale. */
|
|
290
|
+
update() {
|
|
291
|
+
label();
|
|
292
|
+
if (button.parentElement !== menu || menu.lastElementChild !== button) menu.append(button);
|
|
293
|
+
},
|
|
294
|
+
close: () => closeMenu(),
|
|
295
|
+
dispose() {
|
|
296
|
+
closeMenu();
|
|
297
|
+
button.remove();
|
|
298
|
+
}
|
|
299
|
+
};
|
|
300
|
+
}
|