@kubohiroya/turbowarp-plus-editor-code-views 0.9.0 → 0.11.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.
@@ -16,18 +16,18 @@ const messages = {
16
16
  en: {
17
17
  title: 'Block groups shown in the palette', sprite: (name) => `Sprite “${name}”`, stage: 'Stage',
18
18
  newSprite: (name) => `New sprite “${name}”`,
19
- copyFrom: 'Copy from an existing sprite', copyApply: 'Copy and apply',
20
- sets: 'Applicable sets', addSet: 'Add applicable set', setName: 'Set name', add: 'Add',
19
+ quick: 'Choose several at once', copyFrom: 'Copy settings from', copy: 'Copy', chooseSprite: 'Choose a sprite',
20
+ sets: 'Setting shortcuts', addSet: 'Add setting shortcut', setName: 'Shortcut name', add: 'Add',
21
21
  standard: 'Standard block groups', extensions: 'Extension block groups', used: (count) => `In use ${count}`,
22
- hiddenInUse: (count) => `Hidden and in use: ${count}`, cancel: 'Cancel', apply: 'Apply', close: 'Close'
22
+ hiddenInUse: (count) => `Hidden and in use: ${count}`, otherBlocks: 'Other blocks', cancel: 'Cancel', confirm: 'Confirm', close: 'Close'
23
23
  },
24
24
  ja: {
25
25
  title: 'パレット内のブロックグループの表示・非表示の設定', sprite: (name) => `スプライト「${name}」`, stage: '背景',
26
26
  newSprite: (name) => `新しいスプライト「${name}」`,
27
- copyFrom: '作成済みのスプライトからコピー', copyApply: 'コピーして適用',
28
- sets: '適用可能なセット', addSet: '適用可能なセットを追加', setName: 'セットの名前', add: '追加',
27
+ quick: 'まとめて選ぶ', copyFrom: '設定のコピー元', copy: 'コピー', chooseSprite: 'スプライトを選ぶ',
28
+ sets: '設定のショートカット', addSet: '設定のショートカットを追加', setName: 'ショートカットの名前', add: '追加',
29
29
  standard: '標準のブロックグループ', extensions: '機能拡張のブロックグループ', used: (count) => `使用中 ${count}`,
30
- hiddenInUse: (count) => `非表示中・使用中 ${count} 件`, cancel: 'キャンセル', apply: '適用', close: '閉じる'
30
+ hiddenInUse: (count) => `非表示中・使用中 ${count} 件`, otherBlocks: 'そのほかのブロック', cancel: 'キャンセル', confirm: '確定', close: '閉じる'
31
31
  }
32
32
  };
33
33
  const isJapanese = (locale) => /^ja(?:-|$)/i.test(locale ?? '');
@@ -39,7 +39,7 @@ const isJapanese = (locale) => /^ja(?:-|$)/i.test(locale ?? '');
39
39
  export class PaletteVisibilityDialog extends React.PureComponent {
40
40
  constructor(props) {
41
41
  super(props);
42
- this.state = { shown: new Set(props.initial), addedSets: [], naming: false, setName: '', copySource: 0 };
42
+ this.state = { shown: new Set(props.initial), addedSets: [], naming: false, setName: '', copySource: null, highlight: null };
43
43
  }
44
44
  get text() {
45
45
  return isJapanese(this.props.locale) ? messages.ja : messages.en;
@@ -48,8 +48,12 @@ export class PaletteVisibilityDialog extends React.PureComponent {
48
48
  // The stage has no motion blocks.
49
49
  return standardGroups.filter(group => !(this.props.isStage && group === 'motion'));
50
50
  }
51
+ /** Every group on offer, in the order the screen lists them. */
52
+ offered() {
53
+ return [...this.standard(), ...this.props.extensions.flatMap(extension => extension.groups ? extension.groups.map(group => group.id) : [extension.id])];
54
+ }
51
55
  available(groups) {
52
- const offered = new Set([...this.standard(), ...this.props.extensions.map(extension => extension.id)]);
56
+ const offered = new Set(this.offered());
53
57
  return groups.filter(group => offered.has(group));
54
58
  }
55
59
  toggle(group) {
@@ -84,22 +88,25 @@ export class PaletteVisibilityDialog extends React.PureComponent {
84
88
  let id = name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'set';
85
89
  for (let index = 2; taken.has(id); index++)
86
90
  id = `${id.replace(/-\d+$/, '')}-${index}`;
87
- const groups = [...this.standard(), ...this.props.extensions.map(extension => extension.id)]
88
- .filter(group => this.state.shown.has(group));
91
+ const groups = this.offered().filter(group => this.state.shown.has(group));
89
92
  this.setState(({ addedSets }) => ({ addedSets: [...addedSets, { id, name, groups }], naming: false, setName: '' }));
90
93
  }
91
- /** Apply the groups another sprite shows, as far as this one is offered them. */
92
- copyAndApply() {
93
- const source = this.props.copySources?.[this.state.copySource];
94
- if (!source)
94
+ /**
95
+ * Choose the groups another sprite shows, as far as this one is offered them. The screen stays open, so the
96
+ * person sees the copy, adds or removes checks, and applies.
97
+ */
98
+ copy() {
99
+ if (this.state.copySource === null || !this.props.copySources?.[this.state.copySource])
95
100
  return;
96
- const order = [...this.standard(), ...this.props.extensions.map(extension => extension.id)];
97
- const groups = new Set(source.groups);
98
- this.props.onApply({ groups: order.filter(group => groups.has(group)), addedSets: this.state.addedSets });
101
+ this.setState({ shown: new Set(this.copyGroups()) });
102
+ }
103
+ /** The groups of the chosen copy source this sprite can show, or none before one is chosen. */
104
+ copyGroups() {
105
+ const source = this.state.copySource === null ? undefined : this.props.copySources?.[this.state.copySource];
106
+ return source ? this.available(source.groups) : [];
99
107
  }
100
108
  apply() {
101
- const order = [...this.standard(), ...this.props.extensions.map(extension => extension.id)];
102
- this.props.onApply({ groups: order.filter(group => this.state.shown.has(group)), addedSets: this.state.addedSets });
109
+ this.props.onApply({ groups: this.offered().filter(group => this.state.shown.has(group)), addedSets: this.state.addedSets });
103
110
  }
104
111
  render() {
105
112
  const { locale, targetName, isStage, used, extensions, onCancel } = this.props;
@@ -108,6 +115,17 @@ export class PaletteVisibilityDialog extends React.PureComponent {
108
115
  const names = isJapanese(locale) ? standardNames.ja : standardNames.en;
109
116
  const sets = [...this.props.sets, ...this.state.addedSets];
110
117
  const hiddenInUse = [...used].filter(([group, count]) => count > 0 && !shown.has(group)).length;
118
+ // Under the pointer or focus first; otherwise, while a copy source is chosen, the groups it would choose.
119
+ const highlight = this.state.highlight ?? (this.state.copySource !== null ? new Set(this.copyGroups()) : null);
120
+ const highlighted = (group) => highlight?.has(group) ? 'true' : undefined;
121
+ // Pointing at or focusing a shortcut or the copy source marks the groups it would choose, as hovering them does.
122
+ const highlighting = (groups) => {
123
+ const on = () => this.setState({ highlight: new Set(groups) });
124
+ const off = () => this.setState({ highlight: null });
125
+ return { onMouseEnter: on, onMouseLeave: off, onFocus: on, onBlur: off };
126
+ };
127
+ const copying = Boolean(this.props.newSprite && this.props.copySources?.length);
128
+ const copyGroups = copying ? this.copyGroups() : [];
111
129
  const usedBadge = (group) => !shown.has(group) && (used.get(group) ?? 0) > 0 && (React.createElement("span", { className: "tw-palette-visibility-used" }, text.used(used.get(group))));
112
130
  return (React.createElement("div", { className: "tw-palette-visibility" },
113
131
  React.createElement("header", { className: "tw-palette-visibility-header" },
@@ -115,30 +133,38 @@ export class PaletteVisibilityDialog extends React.PureComponent {
115
133
  React.createElement("h2", null, text.title),
116
134
  React.createElement("p", null, isStage ? text.stage : this.props.newSprite ? text.newSprite(targetName) : text.sprite(targetName))),
117
135
  React.createElement("button", { type: "button", className: "tw-palette-visibility-close", "aria-label": text.close, title: text.close, onClick: onCancel }, "\u00D7")),
118
- this.props.newSprite && (this.props.copySources?.length ?? 0) > 0 && (React.createElement("section", { "aria-label": text.copyFrom },
119
- React.createElement("h3", null, text.copyFrom),
120
- React.createElement("div", { className: "tw-palette-visibility-copy" },
121
- React.createElement("select", { "aria-label": text.copyFrom, value: this.state.copySource, onChange: event => this.setState({ copySource: Number(event.currentTarget.value) }) }, this.props.copySources.map((source, index) => (React.createElement("option", { key: index, value: index }, source.name)))),
122
- React.createElement("button", { type: "button", className: "tw-palette-visibility-copy-apply", onClick: () => this.copyAndApply() }, text.copyApply)))),
123
- React.createElement("section", { "aria-label": text.sets },
124
- React.createElement("h3", null, text.sets),
125
- React.createElement("div", { className: "tw-palette-visibility-sets" },
126
- sets.map(set => {
127
- const groups = this.available(set.groups);
128
- const all = groups.length > 0 && groups.every(group => shown.has(group));
129
- return (React.createElement("button", { key: set.id, type: "button", "aria-pressed": all, "data-set": set.id, onClick: () => this.toggleSet(set) },
130
- set.name,
131
- all ? ' ✓' : ''));
132
- }),
133
- naming ? (React.createElement("span", { className: "tw-palette-visibility-naming" },
134
- 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')
135
- this.addSet(); } }),
136
- 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 }) },
137
- "\uFF0B",
138
- text.addSet)))),
136
+ React.createElement("section", { "aria-label": text.quick },
137
+ React.createElement("h3", null, text.quick),
138
+ React.createElement("div", { className: "tw-palette-visibility-quick", "data-columns": copying ? '2' : '1' },
139
+ React.createElement("div", { className: "tw-palette-visibility-panel", "aria-label": text.sets, role: "group" },
140
+ React.createElement("h4", null, text.sets),
141
+ React.createElement("div", { className: "tw-palette-visibility-sets" },
142
+ sets.map(set => {
143
+ const groups = this.available(set.groups);
144
+ const all = groups.length > 0 && groups.every(group => shown.has(group));
145
+ return (React.createElement("button", { key: set.id, type: "button", "aria-pressed": all, "data-set": set.id, ...highlighting(groups), onClick: () => this.toggleSet(set) },
146
+ set.name,
147
+ all ? ' ✓' : ''));
148
+ }),
149
+ naming ? (React.createElement("span", { className: "tw-palette-visibility-naming" },
150
+ 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')
151
+ this.addSet(); } }),
152
+ 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 }) },
153
+ "\uFF0B",
154
+ text.addSet)))),
155
+ copying && (React.createElement("div", { className: "tw-palette-visibility-panel", "aria-label": text.copyFrom, role: "group", ...highlighting(copyGroups) },
156
+ React.createElement("h4", null, text.copyFrom),
157
+ React.createElement("div", { className: "tw-palette-visibility-copy" },
158
+ React.createElement("select", { "aria-label": text.copyFrom, value: this.state.copySource ?? '', onChange: event => {
159
+ const value = event.currentTarget.value;
160
+ this.setState({ copySource: value === '' ? null : Number(value), highlight: null });
161
+ } },
162
+ React.createElement("option", { value: "" }, text.chooseSprite),
163
+ this.props.copySources.map((source, index) => (React.createElement("option", { key: index, value: index }, source.name)))),
164
+ React.createElement("button", { type: "button", className: "tw-palette-visibility-copy-button", disabled: this.state.copySource === null, onClick: () => this.copy() }, text.copy)))))),
139
165
  React.createElement("section", { "aria-label": text.standard },
140
166
  React.createElement("h3", null, text.standard),
141
- React.createElement("div", { className: "tw-palette-visibility-standard" }, this.standard().map(group => (React.createElement("label", { key: group, "data-group": group },
167
+ React.createElement("div", { className: "tw-palette-visibility-standard" }, this.standard().map(group => (React.createElement("label", { key: group, "data-group": group, "data-highlighted": highlighted(group) },
142
168
  React.createElement("input", { type: "checkbox", checked: shown.has(group), onChange: () => this.toggle(group) }),
143
169
  React.createElement("span", { className: "tw-palette-visibility-swatch", style: { color: standardColors[group] }, "aria-hidden": "true" }, "\u25CF"),
144
170
  names[group],
@@ -146,12 +172,17 @@ export class PaletteVisibilityDialog extends React.PureComponent {
146
172
  extensions.length > 0 && (React.createElement("section", { "aria-label": text.extensions },
147
173
  React.createElement("h3", null, text.extensions),
148
174
  React.createElement("div", { className: "twextsec-review" },
149
- 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)))))))),
175
+ React.createElement("ul", { className: "twextsec-rows" }, extensions.map(extension => extension.groups ? (React.createElement(ExtensionRow, { key: extension.id, metadata: extension.metadata, ids: [extension.id], locale: locale, itemProps: { 'data-extension': extension.id } },
176
+ React.createElement("div", { className: "tw-palette-visibility-extension-groups" }, extension.groups.map(group => (React.createElement("label", { key: group.id, "data-group": group.id, "data-highlighted": highlighted(group.id) },
177
+ React.createElement("input", { type: "checkbox", checked: shown.has(group.id), onChange: () => this.toggle(group.id) }),
178
+ React.createElement("span", { className: "tw-palette-visibility-swatch", "aria-hidden": "true", style: { color: group.color } }, "\u25CF"),
179
+ group.id === extension.id ? text.otherBlocks : group.name,
180
+ usedBadge(group.id))))))) : (React.createElement(ExtensionRow, { key: extension.id, metadata: extension.metadata, ids: [extension.id], locale: locale, itemProps: { 'data-group': extension.id, 'data-highlighted': highlighted(extension.id) }, pick: { checked: shown.has(extension.id), onToggle: () => this.toggle(extension.id) } }, usedBadge(extension.id)))))))),
150
181
  React.createElement("footer", { className: "tw-palette-visibility-footer" },
151
182
  React.createElement("span", { role: "status" }, hiddenInUse > 0 ? text.hiddenInUse(hiddenInUse) : ''),
152
183
  React.createElement("span", null,
153
184
  React.createElement("button", { type: "button", onClick: onCancel }, text.cancel),
154
- React.createElement("button", { type: "button", className: "tw-palette-visibility-apply", onClick: () => this.apply() }, text.apply)))));
185
+ React.createElement("button", { type: "button", className: "tw-palette-visibility-apply", onClick: () => this.apply() }, text.confirm)))));
155
186
  }
156
187
  }
157
188
  /** Opens the screen as a modal `<dialog>` in `document`. Returns the function that closes it. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubohiroya/turbowarp-plus-editor-code-views",
3
- "version": "0.9.0",
3
+ "version": "0.11.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,8 +50,140 @@ const standardPrefixes: Record<string, string> = {
50
50
  operator: 'operators', procedures: 'myBlocks', argument: 'myBlocks'
51
51
  };
52
52
 
53
+ /**
54
+ * One block group an extension offers. An extension that declares no groups offers one, named and identified like
55
+ * the extension. One that declares `groups: [{id, name, color1?, color2?, color3?, menuIconURI?}]` in `getInfo()` and
56
+ * marks blocks with `paletteGroup` offers each group as `extensionId/groupId`, and its unmarked blocks as one more
57
+ * group with the extension's ID. Standard TurboWarp ignores both fields and shows the extension as one category.
58
+ */
59
+ export interface ExtensionPaletteGroup {
60
+ id: string;
61
+ extensionId: string;
62
+ /** The group's own name; for the unmarked blocks, the extension's name. */
63
+ name: string;
64
+ extensionName: string;
65
+ /** Whether this is a group the extension declares, rather than its unmarked blocks. */
66
+ declared: boolean;
67
+ color1?: string;
68
+ color2?: string;
69
+ menuIconURI?: string;
70
+ }
71
+
72
+ /** The extension groups the project's extensions offer, and which group each of their blocks belongs to. */
73
+ export interface PaletteGroupCatalog {
74
+ groups: readonly ExtensionPaletteGroup[];
75
+ /** Block opcode to group ID, for the blocks of declared groups. */
76
+ groupOf: ReadonlyMap<string, string>;
77
+ }
78
+
79
+ /** A declared group as kept on the VM's category info. */
80
+ interface DeclaredGroup {
81
+ id: string;
82
+ name: string;
83
+ color1?: string;
84
+ color2?: string;
85
+ color3?: string;
86
+ menuIconURI?: string;
87
+ }
88
+ /** The parts of the VM's category info (`runtime._blockInfo`) this module reads. */
89
+ export interface PaletteCategoryInfo {
90
+ id: string;
91
+ name?: string;
92
+ color1?: string;
93
+ color2?: string;
94
+ menuIconURI?: string;
95
+ blockIconURI?: string;
96
+ /** The groups the extension declares, kept by {@link installExtensionPaletteGroups}. */
97
+ paletteGroups?: unknown;
98
+ blocks?: readonly {info?: {paletteGroup?: unknown}; json?: {type?: unknown} | null}[];
99
+ }
100
+
101
+ const groupIdPattern = /^[A-Za-z0-9_-]+$/;
102
+ const optionalString = (value: unknown) => typeof value === 'string' && value ? value : undefined;
103
+ /** The groups `getInfo()` declares, leaving out any that are not well formed or repeat an ID. */
104
+ function declaredGroups(value: unknown): DeclaredGroup[] {
105
+ if (!Array.isArray(value)) return [];
106
+ const groups: DeclaredGroup[] = [];
107
+ for (const item of value) {
108
+ if (!item || typeof item !== 'object') continue;
109
+ const {id, name} = item as Record<string, unknown>;
110
+ if (typeof id !== 'string' || !groupIdPattern.test(id) || groups.some(group => group.id === id)) continue;
111
+ const entry = item as Record<string, unknown>;
112
+ groups.push({id, name: typeof name === 'string' && name ? name : id, color1: optionalString(entry.color1),
113
+ color2: optionalString(entry.color2), color3: optionalString(entry.color3),
114
+ menuIconURI: optionalString(entry.menuIconURI)});
115
+ }
116
+ return groups;
117
+ }
118
+
119
+ /**
120
+ * Keeps the groups each extension declares on its category info, where {@link extensionPaletteCatalog} reads them,
121
+ * and draws the blocks of a group with a colour of its own in the group's colours. Install it before extensions load.
122
+ * Returns the function that removes it.
123
+ */
124
+ export function installExtensionPaletteGroups(runtime: {_fillExtensionCategory?: (...args: any[]) => unknown}): () => void {
125
+ const original = runtime._fillExtensionCategory;
126
+ if (typeof original !== 'function') return () => {};
127
+ const wrapped = function (this: unknown, categoryInfo: any, extensionInfo: any, ...rest: unknown[]) {
128
+ const result = original.call(this, categoryInfo, extensionInfo, ...rest);
129
+ const groups = declaredGroups(extensionInfo?.groups);
130
+ if (categoryInfo && typeof categoryInfo === 'object') {
131
+ categoryInfo.paletteGroups = groups;
132
+ for (const block of Array.isArray(categoryInfo.blocks) ? categoryInfo.blocks : []) {
133
+ const group = groups.find(item => item.id === block?.info?.paletteGroup);
134
+ if (!group?.color1 || !block.json || block.info.color1 !== undefined) continue;
135
+ block.json.colour = group.color1;
136
+ if (group.color2) block.json.colourSecondary = group.color2;
137
+ if (group.color3) block.json.colourTertiary = group.color3;
138
+ }
139
+ }
140
+ return result;
141
+ };
142
+ runtime._fillExtensionCategory = wrapped;
143
+ return () => {
144
+ if (runtime._fillExtensionCategory === wrapped) runtime._fillExtensionCategory = original;
145
+ };
146
+ }
147
+
148
+ /** The groups of the loaded extensions, in palette order, from the VM's category info. */
149
+ export function extensionPaletteCatalog(categories: readonly PaletteCategoryInfo[] = []): PaletteGroupCatalog {
150
+ const groups: ExtensionPaletteGroup[] = [];
151
+ const groupOf = new Map<string, string>();
152
+ for (const category of categories) {
153
+ const extensionName = category.name || category.id;
154
+ const declared = declaredGroups(category.paletteGroups);
155
+ const used = new Set<string>();
156
+ let unmarked = declared.length === 0;
157
+ for (const block of category.blocks ?? []) {
158
+ const opcode = block?.json?.type;
159
+ if (typeof opcode !== 'string') continue;
160
+ const group = declared.find(item => item.id === block.info?.paletteGroup);
161
+ if (!group) {
162
+ unmarked = true;
163
+ continue;
164
+ }
165
+ groupOf.set(opcode, `${category.id}/${group.id}`);
166
+ used.add(group.id);
167
+ }
168
+ const menuIconURI = category.menuIconURI || category.blockIconURI || undefined;
169
+ if (unmarked) {
170
+ groups.push({id: category.id, extensionId: category.id, name: extensionName, extensionName, declared: false,
171
+ color1: category.color1, color2: category.color2, menuIconURI});
172
+ }
173
+ for (const group of declared) {
174
+ if (!used.has(group.id)) continue;
175
+ groups.push({id: `${category.id}/${group.id}`, extensionId: category.id, name: group.name, extensionName,
176
+ declared: true, color1: group.color1 ?? category.color1, color2: group.color2 ?? category.color2,
177
+ menuIconURI: group.menuIconURI ?? menuIconURI});
178
+ }
179
+ }
180
+ return {groups, groupOf};
181
+ }
182
+
53
183
  /** The group a block belongs to, or null for a block no palette group offers. */
54
- export function groupOfOpcode(opcode: string): string | null {
184
+ export function groupOfOpcode(opcode: string, catalog?: PaletteGroupCatalog): string | null {
185
+ const declared = catalog?.groupOf.get(opcode);
186
+ if (declared) return declared;
55
187
  const separator = opcode.indexOf('_');
56
188
  if (separator <= 0) return null;
57
189
  const prefix = opcode.slice(0, separator);
@@ -69,11 +201,11 @@ export interface PaletteTarget {
69
201
  }
70
202
 
71
203
  /** 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> {
204
+ export function usedGroups(target: Pick<PaletteTarget, 'blocks'>, catalog?: PaletteGroupCatalog): Map<string, number> {
73
205
  const counts = new Map<string, number>();
74
206
  for (const block of Object.values(target.blocks?._blocks ?? {})) {
75
207
  if (!block || block.shadow || typeof block.opcode !== 'string') continue;
76
- const group = groupOfOpcode(block.opcode);
208
+ const group = groupOfOpcode(block.opcode, catalog);
77
209
  if (group) counts.set(group, (counts.get(group) ?? 0) + 1);
78
210
  }
79
211
  return counts;
@@ -81,16 +213,64 @@ export function usedGroups(target: Pick<PaletteTarget, 'blocks'>): Map<string, n
81
213
 
82
214
  /**
83
215
  * The groups shown when a target has no setting of its own: every standard group, and the groups of
84
- * the extensions its code already uses, so a project opens with nothing missing.
216
+ * the extension groups its code already uses, so a project opens with nothing missing. `extensionGroups` are the
217
+ * IDs of the extension groups on offer: the extension IDs, or with a catalog, its group IDs.
85
218
  */
86
- export function defaultVisibleGroups(target: Pick<PaletteTarget, 'blocks'>, extensionIds: readonly string[]): string[] {
87
- const used = usedGroups(target);
88
- return [...standardGroups, ...extensionIds.filter(id => used.has(id))];
219
+ export function defaultVisibleGroups(target: Pick<PaletteTarget, 'blocks'>, extensionGroups: readonly string[],
220
+ catalog?: PaletteGroupCatalog): string[] {
221
+ const used = usedGroups(target, catalog);
222
+ return [...standardGroups, ...extensionGroups.filter(id => used.has(id))];
89
223
  }
90
224
 
91
- /** Removes the categories the target does not show from a parsed toolbox, before the palette is drawn from it. */
92
- export function filterToolboxTree(tree: Element | null | undefined, visible: ReadonlySet<string>): void {
225
+ /**
226
+ * Splits each extension category whose extension declares groups into one category per group, in the catalog's
227
+ * order. A label, separator or button goes with the block after it, or with the last block when none follows.
228
+ */
229
+ export function splitExtensionCategories(tree: Element, catalog: PaletteGroupCatalog): void {
230
+ for (const category of Array.from(tree.querySelectorAll(':scope > category'))) {
231
+ const extensionId = category.getAttribute('id');
232
+ const groups = catalog.groups.filter(group => group.extensionId === extensionId);
233
+ if (!extensionId || !groups.some(group => group.declared)) continue;
234
+ const items = new Map<string, Element[]>();
235
+ let pending: Element[] = [];
236
+ let last = extensionId;
237
+ for (const child of Array.from(category.children)) {
238
+ if (child.tagName.toLowerCase() !== 'block') {
239
+ pending.push(child);
240
+ continue;
241
+ }
242
+ last = catalog.groupOf.get(child.getAttribute('type') ?? '') ?? extensionId;
243
+ items.set(last, [...items.get(last) ?? [], ...pending, child]);
244
+ pending = [];
245
+ }
246
+ if (pending.length) items.set(last, [...items.get(last) ?? [], ...pending]);
247
+ let first = true;
248
+ for (const group of groups) {
249
+ const children = items.get(group.id);
250
+ if (!children) continue;
251
+ const part = category.cloneNode(false) as Element;
252
+ part.setAttribute('id', group.id);
253
+ part.setAttribute('name', group.name);
254
+ if (group.color1) part.setAttribute('colour', group.color1);
255
+ if (group.color2) part.setAttribute('secondaryColour', group.color2);
256
+ if (group.menuIconURI) part.setAttribute('iconURI', group.menuIconURI);
257
+ if (!first) part.removeAttribute('showStatusButton');
258
+ first = false;
259
+ part.append(...children);
260
+ category.before(part);
261
+ }
262
+ category.remove();
263
+ }
264
+ }
265
+
266
+ /**
267
+ * Removes the categories the target does not show from a parsed toolbox, before the palette is drawn from it.
268
+ * With a catalog, an extension that declares groups is first split into a category per group.
269
+ */
270
+ export function filterToolboxTree(tree: Element | null | undefined, visible: ReadonlySet<string>,
271
+ catalog?: PaletteGroupCatalog): void {
93
272
  if (!tree) return;
273
+ if (catalog) splitExtensionCategories(tree, catalog);
94
274
  for (const category of Array.from(tree.querySelectorAll(':scope > category'))) {
95
275
  const id = category.getAttribute('id');
96
276
  if (id && !visible.has(id)) category.remove();
@@ -112,7 +292,10 @@ const sameGroups = (left: readonly string[], right: readonly string[]) =>
112
292
  left.length === right.length && new Set(left).size === left.length && left.every(group => right.includes(group));
113
293
 
114
294
  export interface PaletteVisibilityStore {
115
- /** The groups the palette shows for the target. */
295
+ /**
296
+ * The groups the palette shows for the target. `extensionIds` are the extension groups on offer: the extension
297
+ * IDs, or the group IDs of a catalog when the store was given one.
298
+ */
116
299
  visible(target: PaletteTarget, extensionIds: readonly string[]): Set<string>;
117
300
  /** Keeps the target's groups. Groups equal to its default leave it without a setting of its own. */
118
301
  set(target: PaletteTarget, groups: readonly string[], extensionIds: readonly string[]): void;
@@ -130,15 +313,20 @@ export interface PaletteVisibilityStore {
130
313
  }
131
314
 
132
315
  /** The settings of one project, by runtime target ID, so a renamed sprite keeps its setting. */
133
- export function createPaletteVisibilityStore(): PaletteVisibilityStore {
316
+ export function createPaletteVisibilityStore({catalog}: {
317
+ /** The extension groups on offer now, so the default counts the blocks of declared groups. */
318
+ catalog?: () => PaletteGroupCatalog | undefined;
319
+ } = {}): PaletteVisibilityStore {
320
+ const defaults = (target: PaletteTarget, extensionIds: readonly string[]) =>
321
+ defaultVisibleGroups(target, extensionIds, catalog?.());
134
322
  let groups = new Map<string, string[]>();
135
323
  let projectSets: Record<string, SavedGroupSet> = {};
136
324
  return {
137
325
  visible(target, extensionIds) {
138
- return new Set(groups.get(target.id) ?? defaultVisibleGroups(target, extensionIds));
326
+ return new Set(groups.get(target.id) ?? defaults(target, extensionIds));
139
327
  },
140
328
  set(target, chosen, extensionIds) {
141
- if (sameGroups(chosen, defaultVisibleGroups(target, extensionIds))) groups.delete(target.id);
329
+ if (sameGroups(chosen, defaults(target, extensionIds))) groups.delete(target.id);
142
330
  else groups.set(target.id, [...chosen]);
143
331
  },
144
332
  copy(from, to) {