@kubohiroya/turbowarp-plus-editor-code-views 0.10.0 → 0.12.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,378 @@
1
+ /**
2
+ * Block palette groups: a category of the toolbox XML that holds other categories is a group. Scratch Blocks
3
+ * reads only the top-level categories and drops nested ones, so the tree is flattened before it is drawn:
4
+ * each nested category becomes a top-level one right after its group, and the menu hides it. Clicking the
5
+ * group's icon then shows its members in a child palette laid out like the palette it opens from — a row to the
6
+ * right of the icon for a horizontal palette, a column below it for a vertical one — and a member that is itself
7
+ * a group opens the next level the same way. A click outside the child palettes closes them.
8
+ */
9
+
10
+ /** The attribute a flattened category keeps with the id of the group it was nested in. */
11
+ export const groupParentAttribute = 'palette-group-parent';
12
+
13
+ export interface PaletteGroups {
14
+ /** Each group's members, in order, by category id. A member may itself be a group. */
15
+ members: Map<string, string[]>;
16
+ /** The groups that also hold blocks of their own, which their child palette offers first. */
17
+ withOwnContents: Set<string>;
18
+ }
19
+
20
+ const isCategory = (node: Node): node is Element =>
21
+ node.nodeType === 1 && (node as Element).tagName.toLowerCase() === 'category';
22
+ const ownsContents = (category: Element) => Array.from(category.children).some(child => !isCategory(child));
23
+
24
+ /**
25
+ * Moves every nested category of the toolbox tree to the top level, right after the group that held it, depth
26
+ * first, so Scratch Blocks makes a category of each. Returns the groups found. A nested category without an id
27
+ * gets one from its group's id and its position.
28
+ */
29
+ export const flattenCategoryGroups = (tree: Element | null | undefined): PaletteGroups => {
30
+ const groups: PaletteGroups = {members: new Map(), withOwnContents: new Set()};
31
+ if (!tree) return groups;
32
+ const used = new Set(Array.from(tree.querySelectorAll('category[id]'), category => category.getAttribute('id')));
33
+ const flatten = (category: Element, after: Element): Element => {
34
+ const nested = Array.from(category.children).filter(isCategory);
35
+ if (!nested.length) return after;
36
+ const id = category.getAttribute('id')!;
37
+ groups.members.set(id, []);
38
+ if (ownsContents(category)) groups.withOwnContents.add(id);
39
+ let last = after;
40
+ nested.forEach((child, index) => {
41
+ if (!child.getAttribute('id')) {
42
+ let generated = `${id}/${index}`;
43
+ while (used.has(generated)) generated += '_';
44
+ used.add(generated);
45
+ child.setAttribute('id', generated);
46
+ }
47
+ child.setAttribute(groupParentAttribute, id);
48
+ groups.members.get(id)!.push(child.getAttribute('id')!);
49
+ last.after(child);
50
+ last = flatten(child, child);
51
+ });
52
+ return last;
53
+ };
54
+ for (const category of Array.from(tree.children).filter(isCategory)) {
55
+ if (!category.getAttribute('id')) continue;
56
+ flatten(category, category);
57
+ }
58
+ return groups;
59
+ };
60
+
61
+ /**
62
+ * Runs a filter that removes top-level categories by id, such as the palette's group settings, on a flattened tree.
63
+ * A group the filter removes still stays, without blocks of its own, while one of its members stays; a group left
64
+ * with neither members nor blocks of its own is removed with its members. Returns the groups that remain.
65
+ */
66
+ export const filterGroupedToolboxTree = (tree: Element, groups: PaletteGroups, filter: (tree: Element) => void):
67
+ PaletteGroups => {
68
+ const elements = new Map<string, Element>();
69
+ const markers = new Map<string, Comment>();
70
+ for (const category of Array.from(tree.children).filter(isCategory)) {
71
+ const id = category.getAttribute('id')!;
72
+ if (!groups.members.has(id)) continue;
73
+ const marker = tree.ownerDocument.createComment('palette-group');
74
+ category.before(marker);
75
+ elements.set(id, category);
76
+ markers.set(id, marker);
77
+ }
78
+ filter(tree);
79
+ const present = (element: Element | undefined) => !!element && element.parentNode === tree;
80
+ const remaining: PaletteGroups = {members: new Map(), withOwnContents: new Set()};
81
+ const keep = (id: string): boolean => {
82
+ const members = groups.members.get(id);
83
+ if (!members) return present(Array.from(tree.children).find(child => isCategory(child) && child.getAttribute('id') === id));
84
+ const kept = members.filter(keep);
85
+ const ownShown = groups.withOwnContents.has(id) && present(elements.get(id));
86
+ if (!kept.length && !ownShown) return false;
87
+ remaining.members.set(id, kept);
88
+ if (ownShown) remaining.withOwnContents.add(id);
89
+ return true;
90
+ };
91
+ for (const [id, element] of elements) {
92
+ if (!element.hasAttribute(groupParentAttribute)) keep(id);
93
+ }
94
+ for (const [id, element] of elements) {
95
+ if (!remaining.members.has(id)) element.remove();
96
+ else if (!present(element)) {
97
+ // Shown only as the way to its members.
98
+ element.replaceChildren();
99
+ markers.get(id)!.after(element);
100
+ }
101
+ }
102
+ for (const marker of markers.values()) marker.remove();
103
+ // A member whose group is gone goes with it.
104
+ for (const category of Array.from(tree.children).filter(isCategory)) {
105
+ const parent = category.getAttribute(groupParentAttribute);
106
+ if (parent && !remaining.members.has(parent)) category.remove();
107
+ }
108
+ return remaining;
109
+ };
110
+
111
+ /** The part of a Scratch Blocks toolbox category the child palettes use. */
112
+ export interface PaletteCategory {
113
+ id_: string;
114
+ name_: string;
115
+ item_: HTMLElement;
116
+ setSelected(selected: boolean): void;
117
+ }
118
+
119
+ export interface PaletteCategoryGroupsOptions {
120
+ /** The toolbox's categories, top level and flattened members alike. */
121
+ categories(): PaletteCategory[];
122
+ /** Whether the palette is laid out in a row. */
123
+ horizontal(): boolean;
124
+ rtl?: boolean;
125
+ /** Opens a category that is not a group, as clicking its icon in the palette would. */
126
+ choose(category: PaletteCategory): void;
127
+ /** Called when a child palette opens or the last one closes. */
128
+ onChange?(): void;
129
+ }
130
+
131
+ export interface PaletteCategoryGroupsController {
132
+ /** Takes the groups of the toolbox just drawn: hides their members' icons and marks the groups' icons. */
133
+ update(groups: PaletteGroups): void;
134
+ isGroup(id: string): boolean;
135
+ /** The id of the outermost group the category is in, or its own id when it is in none. */
136
+ topLevelId(id: string): string;
137
+ /** Opens the group's child palette from its icon, or closes it if it is open. */
138
+ toggle(category: PaletteCategory, focus?: boolean): void;
139
+ isOpen(): boolean;
140
+ /** The icon the palette shows for the category: its own, or that of the group it is in. */
141
+ anchorOf(category: PaletteCategory): HTMLElement;
142
+ /** Whether the node is in a child palette. */
143
+ contains(node: Node | null): boolean;
144
+ close(): void;
145
+ dispose(): void;
146
+ }
147
+
148
+ const selectedClass = 'categorySelected';
149
+
150
+ /** Makes clicking a group's icon in the palette menu open its child palette. */
151
+ export const attachPaletteCategoryGroups = (menu: HTMLElement, options: PaletteCategoryGroupsOptions):
152
+ PaletteCategoryGroupsController => {
153
+ const doc = menu.ownerDocument;
154
+ const events = new doc.defaultView!.AbortController();
155
+ const capture = {capture: true, signal: events.signal};
156
+ let groups: PaletteGroups = {members: new Map(), withOwnContents: new Set()};
157
+ const parentOf = new Map<string, string>();
158
+ // The open child palettes, outermost first, with the icon each opened from.
159
+ const stack: {id: string; anchor: HTMLElement; popup: HTMLElement}[] = [];
160
+ let selected: string | null = null;
161
+
162
+ const categoryById = (id: string) => options.categories().find(category => category.id_ === id);
163
+ const topLevelOf = (id: string) => {
164
+ let current = id;
165
+ while (parentOf.has(current)) current = parentOf.get(current)!;
166
+ return current;
167
+ };
168
+
169
+ const markSelection = () => {
170
+ for (const [id] of groups.members) {
171
+ if (parentOf.has(id)) continue;
172
+ const item = categoryById(id)?.item_;
173
+ if (!item) continue;
174
+ const current = selected !== null && selected !== id && topLevelOf(selected) === id;
175
+ item.toggleAttribute('data-palette-group-current', current);
176
+ if (current) item.classList.add(selectedClass);
177
+ else if (selected !== id) item.classList.remove(selectedClass);
178
+ }
179
+ };
180
+
181
+ const closeFrom = (depth: number) => {
182
+ let changed = false;
183
+ while (stack.length > depth) {
184
+ const {anchor, popup} = stack.pop()!;
185
+ anchor.setAttribute('aria-expanded', 'false');
186
+ popup.remove();
187
+ changed = true;
188
+ }
189
+ if (changed) options.onChange?.();
190
+ };
191
+ const close = () => closeFrom(0);
192
+
193
+ const place = (popup: HTMLElement, anchor: HTMLElement) => {
194
+ const container = popup.offsetParent as HTMLElement | null ?? popup.parentElement!;
195
+ const bounds = container.getBoundingClientRect();
196
+ const rect = anchor.getBoundingClientRect();
197
+ const width = popup.offsetWidth;
198
+ const height = popup.offsetHeight;
199
+ const maxLeft = Math.max(0, container.clientWidth - width);
200
+ const maxTop = Math.max(0, container.clientHeight - height);
201
+ let left: number;
202
+ let top: number;
203
+ if (options.horizontal()) {
204
+ left = (options.rtl ? rect.left - width : rect.right) - bounds.left;
205
+ top = rect.top - bounds.top;
206
+ } else {
207
+ left = (options.rtl ? rect.right - width : rect.left) - bounds.left;
208
+ top = rect.bottom - bounds.top;
209
+ }
210
+ popup.style.left = `${Math.min(Math.max(0, left), maxLeft)}px`;
211
+ popup.style.top = `${Math.min(Math.max(0, top), maxTop)}px`;
212
+ };
213
+
214
+ const activate = (category: PaletteCategory, entry: HTMLElement, depth: number, focus: boolean, self: boolean) => {
215
+ if (!self && groups.members.has(category.id_)) {
216
+ if (stack[depth]?.id === category.id_) closeFrom(depth);
217
+ else open(category, entry, depth, focus);
218
+ return;
219
+ }
220
+ close();
221
+ options.choose(category);
222
+ };
223
+
224
+ const createEntry = (category: PaletteCategory, depth: number, self = false) => {
225
+ const entry = doc.createElement('div');
226
+ entry.className = `scratchCategoryMenuItem scratchCategoryId-${category.id_}`;
227
+ entry.classList.add('tw-palette-group-item');
228
+ entry.setAttribute('data-palette-group-item', category.id_);
229
+ entry.setAttribute('role', 'menuitem');
230
+ entry.tabIndex = -1;
231
+ for (const child of Array.from(category.item_.children)) entry.append(child.cloneNode(true));
232
+ const isGroup = !self && groups.members.has(category.id_);
233
+ if (isGroup) {
234
+ entry.setAttribute('aria-haspopup', 'true');
235
+ entry.setAttribute('aria-expanded', 'false');
236
+ }
237
+ if (selected === category.id_ || (isGroup && selected !== null && isInside(selected, category.id_))) {
238
+ entry.classList.add(selectedClass);
239
+ }
240
+ entry.addEventListener('click', event => {
241
+ event.stopPropagation();
242
+ activate(category, entry, depth, false, self);
243
+ }, {signal: events.signal});
244
+ entry.addEventListener('keydown', event => {
245
+ if (event.key === 'Enter' || event.key === ' ') {
246
+ event.preventDefault();
247
+ event.stopPropagation();
248
+ activate(category, entry, depth, true, self);
249
+ return;
250
+ }
251
+ const forward = options.horizontal() ? (options.rtl ? 'ArrowLeft' : 'ArrowRight') : 'ArrowDown';
252
+ const backward = options.horizontal() ? (options.rtl ? 'ArrowRight' : 'ArrowLeft') : 'ArrowUp';
253
+ if (event.key !== forward && event.key !== backward) return;
254
+ event.preventDefault();
255
+ const entries = Array.from(entry.parentElement!.children) as HTMLElement[];
256
+ const index = entries.indexOf(entry) + (event.key === forward ? 1 : -1);
257
+ entries[(index + entries.length) % entries.length].focus();
258
+ }, {signal: events.signal});
259
+ return entry;
260
+ };
261
+
262
+ const isInside = (id: string, groupId: string) => {
263
+ for (let current: string | undefined = id; current !== undefined; current = parentOf.get(current)) {
264
+ if (current === groupId) return true;
265
+ }
266
+ return false;
267
+ };
268
+
269
+ const open = (group: PaletteCategory, anchor: HTMLElement, depth: number, focus: boolean) => {
270
+ closeFrom(depth);
271
+ const members = (groups.members.get(group.id_) ?? []).map(categoryById).filter(Boolean) as PaletteCategory[];
272
+ const popup = doc.createElement('div');
273
+ popup.className = 'tw-palette-group-popup';
274
+ popup.setAttribute('data-palette-group-popup', group.id_);
275
+ popup.setAttribute('role', 'menu');
276
+ popup.setAttribute('aria-label', anchor.textContent?.trim() || group.id_);
277
+ popup.toggleAttribute('data-horizontal', options.horizontal());
278
+ // The child palette is drawn in the palette's own colours and type.
279
+ const look = doc.defaultView!.getComputedStyle(menu.querySelector('.scratchCategoryMenu, .scratchCategoryMenuHorizontal') ?? menu);
280
+ popup.style.setProperty('--palette-group-background', look.backgroundColor);
281
+ popup.style.color = look.color;
282
+ popup.style.fontSize = look.fontSize;
283
+ popup.style.fontFamily = look.fontFamily;
284
+ if (groups.withOwnContents.has(group.id_)) popup.append(createEntry(group, depth, true));
285
+ for (const member of members) popup.append(createEntry(member, depth + 1));
286
+ (menu.parentElement ?? doc.body).append(popup);
287
+ place(popup, anchor);
288
+ anchor.setAttribute('aria-expanded', 'true');
289
+ stack.push({id: group.id_, anchor, popup});
290
+ options.onChange?.();
291
+ if (focus) (popup.firstElementChild as HTMLElement | null)?.focus();
292
+ };
293
+
294
+ const toggle = (category: PaletteCategory, focus = false) => {
295
+ if (stack[0]?.id === category.id_) close();
296
+ else open(category, category.item_, 0, focus);
297
+ };
298
+
299
+ const groupItem = (target: EventTarget | null) => {
300
+ if (!(target instanceof doc.defaultView!.Node)) return null;
301
+ return options.categories().find(category => groups.members.has(category.id_) &&
302
+ !parentOf.has(category.id_) && category.item_.contains(target as Node)) ?? null;
303
+ };
304
+ // Scratch Blocks opens a category on mouseup (touchend on touch screens); a group opens its child palette on click.
305
+ for (const type of ['mouseup', 'touchend']) {
306
+ menu.addEventListener(type, event => {
307
+ if (groupItem(event.target)) event.stopPropagation();
308
+ }, capture);
309
+ }
310
+ menu.addEventListener('click', event => {
311
+ const category = groupItem(event.target);
312
+ if (!category) return;
313
+ event.stopPropagation();
314
+ toggle(category);
315
+ }, capture);
316
+
317
+ const contains = (node: Node | null) => !!node && stack.some(({popup}) => popup.contains(node));
318
+ const onPointerDown = (event: PointerEvent) => {
319
+ if (!stack.length) return;
320
+ const target = event.target as Node | null;
321
+ if (contains(target) || stack[0].anchor.contains(target)) return;
322
+ close();
323
+ };
324
+ const onKeyDown = (event: KeyboardEvent) => {
325
+ if (event.key !== 'Escape' || event.isComposing || !stack.length) return;
326
+ event.preventDefault();
327
+ // The palette's own Escape would close the block list as well.
328
+ event.stopImmediatePropagation();
329
+ const {anchor} = stack[stack.length - 1];
330
+ closeFrom(stack.length - 1);
331
+ anchor.focus();
332
+ };
333
+ doc.addEventListener('pointerdown', onPointerDown, capture);
334
+ doc.addEventListener('keydown', onKeyDown, capture);
335
+ menu.addEventListener('scroll', close, {signal: events.signal});
336
+ doc.defaultView!.addEventListener('resize', close, {signal: events.signal});
337
+
338
+ return {
339
+ update(next) {
340
+ close();
341
+ groups = next;
342
+ parentOf.clear();
343
+ for (const [id, members] of groups.members) for (const member of members) parentOf.set(member, id);
344
+ for (const category of options.categories()) {
345
+ const member = parentOf.has(category.id_);
346
+ const row = category.item_.parentElement;
347
+ if (row && row !== menu) row.hidden = member;
348
+ const group = groups.members.has(category.id_) && !member;
349
+ if (group) {
350
+ category.item_.setAttribute('aria-haspopup', 'true');
351
+ category.item_.setAttribute('aria-expanded', 'false');
352
+ category.item_.setAttribute('data-palette-group', '');
353
+ category.item_.classList.add('tw-palette-group');
354
+ }
355
+ const {setSelected} = category;
356
+ category.setSelected = function (value: boolean) {
357
+ setSelected.call(this, value);
358
+ if (value) selected = category.id_;
359
+ else if (selected === category.id_) selected = null;
360
+ markSelection();
361
+ };
362
+ if (category.item_.classList.contains(selectedClass)) selected = category.id_;
363
+ }
364
+ markSelection();
365
+ },
366
+ isGroup: id => groups.members.has(id) && !parentOf.has(id),
367
+ topLevelId: topLevelOf,
368
+ toggle,
369
+ isOpen: () => stack.length > 0,
370
+ anchorOf: category => categoryById(topLevelOf(category.id_))?.item_ ?? category.item_,
371
+ contains,
372
+ close,
373
+ dispose() {
374
+ close();
375
+ events.abort();
376
+ }
377
+ };
378
+ };
@@ -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,84 @@ 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))];
223
+ }
224
+
225
+ /** A category for one group of an extension, drawn like the extension's own unless the group has its own look. */
226
+ function groupCategory(category: Element, group: ExtensionPaletteGroup, children: Element[]): Element {
227
+ const part = category.cloneNode(false) as Element;
228
+ part.setAttribute('id', group.id);
229
+ part.setAttribute('name', group.name);
230
+ if (group.color1) part.setAttribute('colour', group.color1);
231
+ if (group.color2) part.setAttribute('secondaryColour', group.color2);
232
+ if (group.menuIconURI) part.setAttribute('iconURI', group.menuIconURI);
233
+ part.append(...children);
234
+ return part;
89
235
  }
90
236
 
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 {
237
+ /**
238
+ * Splits each extension category whose extension declares groups into one category per group, in the catalog's
239
+ * order. A label, separator or button goes with the block after it, or with the last block when none follows.
240
+ * With `nested`, the extension's category stays, with its unmarked blocks, and holds the categories of its declared
241
+ * groups, so the palette can show it as a group that opens them (see `./palette-category-groups`).
242
+ */
243
+ export function splitExtensionCategories(tree: Element, catalog: PaletteGroupCatalog,
244
+ {nested = false}: {nested?: boolean} = {}): void {
245
+ for (const category of Array.from(tree.querySelectorAll(':scope > category'))) {
246
+ const extensionId = category.getAttribute('id');
247
+ const groups = catalog.groups.filter(group => group.extensionId === extensionId);
248
+ if (!extensionId || !groups.some(group => group.declared)) continue;
249
+ const items = new Map<string, Element[]>();
250
+ let pending: Element[] = [];
251
+ let last = extensionId;
252
+ for (const child of Array.from(category.children)) {
253
+ if (child.tagName.toLowerCase() !== 'block') {
254
+ pending.push(child);
255
+ continue;
256
+ }
257
+ last = catalog.groupOf.get(child.getAttribute('type') ?? '') ?? extensionId;
258
+ items.set(last, [...items.get(last) ?? [], ...pending, child]);
259
+ pending = [];
260
+ }
261
+ if (pending.length) items.set(last, [...items.get(last) ?? [], ...pending]);
262
+ if (nested) {
263
+ category.replaceChildren(...items.get(extensionId) ?? []);
264
+ for (const group of groups) {
265
+ const children = items.get(group.id);
266
+ if (!group.declared || !children) continue;
267
+ const part = groupCategory(category, group, children);
268
+ part.removeAttribute('showStatusButton');
269
+ category.append(part);
270
+ }
271
+ continue;
272
+ }
273
+ let first = true;
274
+ for (const group of groups) {
275
+ const children = items.get(group.id);
276
+ if (!children) continue;
277
+ const part = groupCategory(category, group, children);
278
+ if (!first) part.removeAttribute('showStatusButton');
279
+ first = false;
280
+ category.before(part);
281
+ }
282
+ category.remove();
283
+ }
284
+ }
285
+
286
+ /**
287
+ * Removes the categories the target does not show from a parsed toolbox, before the palette is drawn from it.
288
+ * With a catalog, an extension that declares groups is first split into a category per group.
289
+ */
290
+ export function filterToolboxTree(tree: Element | null | undefined, visible: ReadonlySet<string>,
291
+ catalog?: PaletteGroupCatalog): void {
93
292
  if (!tree) return;
293
+ if (catalog) splitExtensionCategories(tree, catalog);
94
294
  for (const category of Array.from(tree.querySelectorAll(':scope > category'))) {
95
295
  const id = category.getAttribute('id');
96
296
  if (id && !visible.has(id)) category.remove();
@@ -112,7 +312,10 @@ const sameGroups = (left: readonly string[], right: readonly string[]) =>
112
312
  left.length === right.length && new Set(left).size === left.length && left.every(group => right.includes(group));
113
313
 
114
314
  export interface PaletteVisibilityStore {
115
- /** The groups the palette shows for the target. */
315
+ /**
316
+ * The groups the palette shows for the target. `extensionIds` are the extension groups on offer: the extension
317
+ * IDs, or the group IDs of a catalog when the store was given one.
318
+ */
116
319
  visible(target: PaletteTarget, extensionIds: readonly string[]): Set<string>;
117
320
  /** Keeps the target's groups. Groups equal to its default leave it without a setting of its own. */
118
321
  set(target: PaletteTarget, groups: readonly string[], extensionIds: readonly string[]): void;
@@ -130,15 +333,20 @@ export interface PaletteVisibilityStore {
130
333
  }
131
334
 
132
335
  /** The settings of one project, by runtime target ID, so a renamed sprite keeps its setting. */
133
- export function createPaletteVisibilityStore(): PaletteVisibilityStore {
336
+ export function createPaletteVisibilityStore({catalog}: {
337
+ /** The extension groups on offer now, so the default counts the blocks of declared groups. */
338
+ catalog?: () => PaletteGroupCatalog | undefined;
339
+ } = {}): PaletteVisibilityStore {
340
+ const defaults = (target: PaletteTarget, extensionIds: readonly string[]) =>
341
+ defaultVisibleGroups(target, extensionIds, catalog?.());
134
342
  let groups = new Map<string, string[]>();
135
343
  let projectSets: Record<string, SavedGroupSet> = {};
136
344
  return {
137
345
  visible(target, extensionIds) {
138
- return new Set(groups.get(target.id) ?? defaultVisibleGroups(target, extensionIds));
346
+ return new Set(groups.get(target.id) ?? defaults(target, extensionIds));
139
347
  },
140
348
  set(target, chosen, extensionIds) {
141
- if (sameGroups(chosen, defaultVisibleGroups(target, extensionIds))) groups.delete(target.id);
349
+ if (sameGroups(chosen, defaults(target, extensionIds))) groups.delete(target.id);
142
350
  else groups.set(target.id, [...chosen]);
143
351
  },
144
352
  copy(from, to) {