@kubohiroya/turbowarp-plus-editor-code-views 0.16.0 → 0.17.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 CHANGED
@@ -16,9 +16,9 @@ TurboWarp Plus Editor のコードの画面。1つの作品と1つの取り消
16
16
  | `./variable-references` | 編集中の対象に絞った変数の参照 |
17
17
  | `./variable-merge` | 名前の変更で変数・リストを既存のものに統合し、パレットから「このスプライトのみ」と「すべてのスプライト用」を切り替える |
18
18
  | `./target-combobox` | コードの窓の対象の選択 |
19
- | `./detached-block-palette` | 別窓のブロックパレット |
19
+ | `./detached-block-palette` | 別窓のブロックパレット。パレットの `grouping` を渡すと、パレットと同じくグループを子ブロックパレットで開き、固定できる |
20
20
  | `./palette-category-reorder`・`./palette-category-search`・`./palette-dropdown-resize` | パレットのカテゴリの並べ替えと検索、パレットのドロップダウンの大きさの変更 |
21
- | `./palette-category-groups` | ツールボックスで別の category を含む category をグループとして表示する。アイコンをクリックすると、要素を並べた子ブロックパレットを影つきで重ねて開く(横配置のパレットではアイコンの右に横並び、縦配置では下に縦並び)。外側をクリックすると閉じる。Scratch Blocks は入れ子の category を捨てるので、`flattenCategoryGroups(tree)` と `filterGroupedToolboxTree(tree, groups, filter)` で木を整え、`prepareGroupedToolboxTree(tree, {catalog, visible})` は、機能拡張が宣言したグループの入れ子化と表示するグループの絞り込みを含めて、これを一度に行う。`hasCategoryGroups(tree)` は木が category を入れ子にしているかを返す。`attachPaletteCategoryGroups(menu, options)` で子ブロックパレットを開く。その `selectionTarget(id)` は、自分のブロックを持たないグループの代わりに選ぶ category を返し、`syncButtons(openId)` はグループのアイコンの状態を付け直す。`reorder: true` では、子ブロックパレットの要素を長押しして、同じグループの要素の中で並べ替えられる(別のグループや階層へは動かさない)。順番はパレットを描き直しても保ち(`order` を渡せば、プロジェクトと一緒に保存するパレットの設定に保つ)、`prepare(tree, options)` はツールボックスをその順番で描かせ、`arrange(categories, rank)` がツールボックスの category をそれに合わせて、グループの後にその要素が続くように並べる。`splitExtensionCategories(tree, catalog, {nested: true})` は、グループを宣言した機能拡張をこのグループにする |
21
+ | `./palette-category-groups` | ツールボックスで別の category を含む category をグループとして表示する。アイコンをクリックすると、要素を並べた子ブロックパレットを影つきで重ねて開く(横配置のパレットではアイコンの右に横並び、縦配置では下に縦並び)。外側をクリックすると閉じる。Scratch Blocks は入れ子の category を捨てるので、`flattenCategoryGroups(tree)` と `filterGroupedToolboxTree(tree, groups, filter)` で木を整え、`prepareGroupedToolboxTree(tree, {catalog, visible})` は、機能拡張が宣言したグループの入れ子化と表示するグループの絞り込みを含めて、これを一度に行う。`hasCategoryGroups(tree)` は木が category を入れ子にしているかを返す。`attachPaletteCategoryGroups(menu, options)` で子ブロックパレットを開く。その `selectionTarget(id)` は、自分のブロックを持たないグループの代わりに選ぶ category を返し、`syncButtons(openId)` はグループのアイコンの状態を付け直す。`reorder: true` では、子ブロックパレットの要素を長押しして、同じグループの要素の中で並べ替えられる(別のグループや階層へは動かさない)。順番はパレットを描き直しても保ち(`order` を渡せば、プロジェクトと一緒に保存するパレットの設定に保つ)、`prepare(tree, options)` はツールボックスをその順番で描かせ、`arrange(categories, rank)` がツールボックスの category をそれに合わせて、グループの後にその要素が続くように並べる。子ブロックパレットの右上にはピンがあり、押すとグループの要素を、そのグループを表示していたパレットのそのグループの直後に広げて固定する。固定したグループのアイコンにはピンが付き、押すと元のようにたたむ。固定は同じ `order` に保つので、それを渡したパレット同士は揃う。`splitExtensionCategories(tree, catalog, {nested: true})` は、グループを宣言した機能拡張をこのグループにする |
22
22
  | `./palette-category-visibility`・`./palette-visibility-dialog` | スプライト・背景ごとに、パレットに出すブロックグループを選ぶ。設定はエディターの画面状態として保存し、選ぶ画面を持つ。ストアの `order`(`createPaletteOrder`)は、パレットのカテゴリーと各グループの要素を並べ替えた順番を保ち、同じ設定と一緒に保存する |
23
23
  | `./block-argument-text` | 長いテキストの引数を短く表示し、ダイアログで編集する。テキストの引数で Shift+Enter を押すと、改行を入れてダイアログで編集を続ける |
24
24
  | `./block-number-input` | 数値の引数に入力した全角の数字・記号を半角にする |
package/README.md CHANGED
@@ -16,10 +16,10 @@ The code views of TurboWarp Plus Editor: code in tabs and windows that share one
16
16
  | `./variable-references` | Variable references scoped to the edited target |
17
17
  | `./variable-merge` | Merges a variable or list into another one on rename, and moves one between this sprite and all sprites from the palette |
18
18
  | `./target-combobox` | The target picker of a code window |
19
- | `./detached-block-palette` | The block palette in its own window |
19
+ | `./detached-block-palette` | The block palette in its own window. Given the palette's `grouping`, it opens groups in child palettes and pins them as the palette does |
20
20
  | `./palette-category-visibility`, `./palette-visibility-dialog` | Choose which block groups the palette shows for each sprite and the stage. The setting is saved with the editor's screen state, with a screen to choose. The store's `order` (`createPaletteOrder`) keeps the order the palette's categories and each group's members were dragged into, saved with the same settings |
21
21
  | `./palette-category-reorder`, `./palette-category-search`, `./palette-dropdown-resize` | Reordering and searching palette categories, and resizing palette dropdowns |
22
- | `./palette-category-groups` | Shows a category of the toolbox that holds other categories as a group: clicking its icon opens a child palette of its members, floating with a shadow — a row to the right of the icon in a horizontal palette, a column below it in a vertical one — and a click outside closes it. `flattenCategoryGroups(tree)` and `filterGroupedToolboxTree(tree, groups, filter)` prepare the tree, which Scratch Blocks would otherwise drop nested categories from; `prepareGroupedToolboxTree(tree, {catalog, visible})` does both in one step, also nesting the groups extensions declare and keeping only the groups to show, and `hasCategoryGroups(tree)` tells whether a tree nests categories. `attachPaletteCategoryGroups(menu, options)` opens the child palettes; its `selectionTarget(id)` gives the category to select for a group without blocks of its own, and `syncButtons(openId)` marks the groups' icons. With `reorder: true`, a long press on a member of a child palette drags it among the members of the same group (not to another group or level); the order is kept while the palette is drawn again (in the `order` given, such as the palette settings saved with the project), `prepare(tree, options)` draws the toolbox in it, and `arrange(categories, rank)` orders the toolbox's categories to match, each group followed by its members. `splitExtensionCategories(tree, catalog, {nested: true})` makes an extension that declares groups such a group |
22
+ | `./palette-category-groups` | Shows a category of the toolbox that holds other categories as a group: clicking its icon opens a child palette of its members, floating with a shadow — a row to the right of the icon in a horizontal palette, a column below it in a vertical one — and a click outside closes it. `flattenCategoryGroups(tree)` and `filterGroupedToolboxTree(tree, groups, filter)` prepare the tree, which Scratch Blocks would otherwise drop nested categories from; `prepareGroupedToolboxTree(tree, {catalog, visible})` does both in one step, also nesting the groups extensions declare and keeping only the groups to show, and `hasCategoryGroups(tree)` tells whether a tree nests categories. `attachPaletteCategoryGroups(menu, options)` opens the child palettes; its `selectionTarget(id)` gives the category to select for a group without blocks of its own, and `syncButtons(openId)` marks the groups' icons. With `reorder: true`, a long press on a member of a child palette drags it among the members of the same group (not to another group or level); the order is kept while the palette is drawn again (in the `order` given, such as the palette settings saved with the project), `prepare(tree, options)` draws the toolbox in it, and `arrange(categories, rank)` orders the toolbox's categories to match, each group followed by its members. A child palette has a pin at its top right: pinning the group shows its members in the palette that showed the group, right after it, and the pinned group's icon shows a pin that folds them back. The pins are kept in the same `order`, so palettes given it follow each other. `splitExtensionCategories(tree, catalog, {nested: true})` makes an extension that declares groups such a group |
23
23
  | `./block-argument-text` | Shortens long text arguments and edits them in a dialog. Shift+Enter in a text argument continues in the dialog with a line break |
24
24
  | `./block-number-input` | Converts full-width digits and signs typed into number arguments to half-width |
25
25
  | `./clean-up-comments` | Keeps comments with their scripts in "Clean up blocks": block comments keep their offset from the block, scripts with their comments do not cover one another, and workspace comments that cover a script move beside the scripts (`installCleanUpComments(ScratchBlocks)`) |
@@ -1,5 +1,7 @@
1
1
  import React from 'react';
2
2
  import { IconMenuButton } from '@kubohiroya/turbowarp-plus-editor-windows';
3
+ import { attachPaletteCategoryGroups } from "./palette-category-groups.js";
4
+ const noGroups = { members: new Map(), withOwnContents: new Set() };
3
5
  const horizontalLayoutIconPath = 'M2 5h5v6H2zm7 0h5v6H9z';
4
6
  const verticalLayoutIconPath = 'M5 2h6v5H5zm0 7h6v5H5z';
5
7
  function BlockPreview({ svg }) {
@@ -25,6 +27,45 @@ export default function Palette({ source, locale, categoryIcons, close, startDra
25
27
  const selected = categories.find(category => category.id === categoryId) ?? categories[0];
26
28
  const selectedId = selected?.id;
27
29
  React.useLayoutEffect(() => source.subscribe(refresh), [source]);
30
+ // The editor's groups open in child palettes here too, and pinning one shows its members in this list.
31
+ const list = React.useRef(null);
32
+ const groupsControl = React.useRef(null);
33
+ const layout = React.useRef(vertical);
34
+ layout.current = vertical;
35
+ const grouping = source.grouping?.();
36
+ // Opening a child palette or pinning a group only draws the list again; the blocks shown stay as they are.
37
+ const [, redraw] = React.useReducer(value => value + 1, 0);
38
+ React.useLayoutEffect(() => {
39
+ const menu = list.current;
40
+ const controller = attachPaletteCategoryGroups(menu, {
41
+ categories: () => source.categories().map(({ id, label }) => ({
42
+ id_: id, name_: label, setSelected() { },
43
+ item_: menu.querySelector(`button[data-category-id="${CSS.escape(id)}"]`)
44
+ })).filter(category => category.item_),
45
+ // A row of categories, when the blocks are laid out below them.
46
+ horizontal: () => layout.current,
47
+ choose: category => {
48
+ setCategory(category.id_);
49
+ setTooltip(null);
50
+ },
51
+ order: () => source.grouping?.()?.order,
52
+ locale: () => locale,
53
+ onChange: redraw
54
+ });
55
+ groupsControl.current = controller;
56
+ return () => {
57
+ groupsControl.current = null;
58
+ controller.dispose();
59
+ };
60
+ }, [source, locale]);
61
+ const categoryKey = categories.map(category => category.id).join('\n');
62
+ React.useLayoutEffect(() => {
63
+ groupsControl.current?.update(grouping?.groups ?? noGroups);
64
+ }, [categoryKey, grouping?.groups, vertical]);
65
+ React.useLayoutEffect(() => grouping?.order.subscribe(redraw), [grouping?.order]);
66
+ // A group stands for the selected category while its child palette holds it.
67
+ const pressed = (id) => id === selectedId ||
68
+ (!!selectedId && groupsControl.current?.isGroup(id) && groupsControl.current.shownAs(selectedId) === id);
28
69
  React.useLayoutEffect(() => {
29
70
  setItems(selectedId ? source.read(selectedId) : []);
30
71
  }, [source, selectedId, revision]);
@@ -39,15 +80,17 @@ export default function Palette({ source, locale, categoryIcons, close, startDra
39
80
  }
40
81
  return React.createElement("main", { className: "tw-detached-palette", "data-palette-orientation": vertical ? 'vertical' : 'horizontal' },
41
82
  React.createElement("div", { className: "tw-detached-palette__content" },
42
- React.createElement("div", { className: "tw-detached-palette__categories", role: "group", "aria-label": ja ? 'ブロックのカテゴリ' : 'Block categories', onScroll: () => setTooltip(null) }, categories.map(({ id, label, color, image }) => {
83
+ React.createElement("div", { ref: list, className: "tw-detached-palette__categories", role: "group", "aria-label": ja ? 'ブロックのカテゴリ' : 'Block categories', onScroll: () => setTooltip(null) }, categories.map(({ id, label, color, image }) => {
43
84
  const artwork = categoryIcons[id];
44
85
  const backgroundImage = image || (artwork ? `url("${artwork}")` : undefined);
45
- return React.createElement("button", { key: id, type: "button", "aria-label": label, "aria-pressed": id === selectedId, onMouseEnter: event => showLabel(event.currentTarget, label), onMouseLeave: () => setTooltip(null), onFocus: event => showLabel(event.currentTarget, label), onBlur: () => setTooltip(null), onKeyDown: event => { if (event.key === 'Escape')
46
- setTooltip(null); }, onClick: () => {
47
- setCategory(id);
48
- setTooltip(null);
49
- } },
50
- React.createElement("span", { "aria-hidden": "true", className: "tw-detached-palette__category-icon", style: { backgroundColor: color, backgroundImage } }, !backgroundImage && React.createElement(LayoutIcon, { path: "M2 4h5V2h3v2h4v8H2z" })));
86
+ // Each category sits in a row of its own, which a group hides while it holds the category.
87
+ return React.createElement("span", { key: id, className: "tw-detached-palette__category" },
88
+ React.createElement("button", { type: "button", "data-category-id": id, "aria-label": label, "aria-pressed": Boolean(pressed(id)), onMouseEnter: event => showLabel(event.currentTarget, label), onMouseLeave: () => setTooltip(null), onFocus: event => showLabel(event.currentTarget, label), onBlur: () => setTooltip(null), onKeyDown: event => { if (event.key === 'Escape')
89
+ setTooltip(null); }, onClick: () => {
90
+ setCategory(id);
91
+ setTooltip(null);
92
+ } },
93
+ React.createElement("span", { "aria-hidden": "true", className: "tw-detached-palette__category-icon", style: { backgroundColor: color, backgroundImage } }, !backgroundImage && React.createElement(LayoutIcon, { path: "M2 4h5V2h3v2h4v8H2z" }))));
51
94
  })),
52
95
  React.createElement("div", { className: "tw-detached-palette__blocks", role: "group", "aria-label": selected?.label }, items.map((item, index) => item.insert ? React.createElement("button", { key: index, type: "button", "aria-label": item.label, title: item.label, disabled: item.disabled, draggable: Boolean(item.preview && !item.disabled), onDragStart: event => startDrag(item, event.dataTransfer), onDragEnd: endDrag, onClick: () => item.insert() }, item.preview ? React.createElement(BlockPreview, { svg: item.preview }) : item.label) : React.createElement("span", { key: index }, item.label)))),
53
96
  tooltip && React.createElement("div", { className: "tw-detached-palette__tooltip", role: "tooltip", style: tooltip.position }, tooltip.label),
@@ -1,3 +1,4 @@
1
+ import type { PaletteGroups, PaletteGroupsOrder } from './palette-category-groups.ts';
1
2
  type Point = {
2
3
  x: number;
3
4
  y: number;
@@ -14,9 +15,15 @@ export type PaletteItem = {
14
15
  disabled?: boolean;
15
16
  insert?(point?: Point): void;
16
17
  };
18
+ /** The groups of the editor's palette, which the detached one shows the same way, and the order and pins they share. */
19
+ export type PaletteGrouping = {
20
+ groups: PaletteGroups;
21
+ order: PaletteGroupsOrder;
22
+ };
17
23
  export type PaletteSource = {
18
24
  surface: SVGSVGElement;
19
25
  categories(): PaletteCategory[];
26
+ grouping?(): PaletteGrouping | undefined;
20
27
  read(id: string): PaletteItem[];
21
28
  subscribe(refresh: () => void): () => void;
22
29
  setDetached(detached: boolean): void;
@@ -27,12 +34,15 @@ type PaletteWindowOptions = {
27
34
  decorate(document: Document): () => void;
28
35
  };
29
36
  export declare function openDetachedBlockPalette(workspace: object, { locale, categoryIcons, decorate }: PaletteWindowOptions): void;
30
- export declare function connectDetachedBlockPalette({ blocks, workspace, flyout, menu, categories, show, setDetached }: {
37
+ export declare function connectDetachedBlockPalette({ blocks, workspace, flyout, menu, categories, grouping, show, setDetached }: {
31
38
  blocks: any;
32
39
  workspace: any;
33
40
  flyout: any;
34
41
  menu: HTMLElement;
42
+ /** Every category, members of groups included, in the palette's order. */
35
43
  categories(): PaletteCategory[];
44
+ /** The palette's groups, so the detached palette opens them in child palettes too. */
45
+ grouping?(): PaletteGrouping | undefined;
36
46
  show(id: string): void;
37
47
  setDetached(detached: boolean): void;
38
48
  }): () => void;
@@ -76,7 +76,7 @@ function registerDetachedBlockPalette(workspace, source) {
76
76
  sources.delete(workspace);
77
77
  };
78
78
  }
79
- export function connectDetachedBlockPalette({ blocks, workspace, flyout, menu, categories, show, setDetached }) {
79
+ export function connectDetachedBlockPalette({ blocks, workspace, flyout, menu, categories, grouping, show, setDetached }) {
80
80
  const surface = workspace.getParentSvg();
81
81
  const ns = 'http://www.w3.org/2000/svg';
82
82
  const win = surface.ownerDocument.defaultView;
@@ -91,7 +91,7 @@ export function connectDetachedBlockPalette({ blocks, workspace, flyout, menu, c
91
91
  return position.matrixTransform(matrix.inverse());
92
92
  };
93
93
  return registerDetachedBlockPalette(workspace, {
94
- surface, categories, setDetached,
94
+ surface, categories, grouping, setDetached,
95
95
  read(id) {
96
96
  show(id);
97
97
  const items = [];
@@ -63,11 +63,16 @@ export interface PaletteCategoryGroupsOptions {
63
63
  /** Called after the members of a group were reordered, so the host can lay out its categories with `arrange`. */
64
64
  onReorder?(): void;
65
65
  /**
66
- * Where the members' order is kept, such as the palette settings saved with the project. By default the order
67
- * lasts while the palette does.
66
+ * Where the members' order and the pinned groups are kept, such as the palette settings saved with the project.
67
+ * Palettes given the same one, such as the editor's and the detached one, follow each other. By default they last
68
+ * while the palette does.
68
69
  */
69
- order?(): Pick<PaletteOrder, 'members' | 'setMembers'> | undefined;
70
+ order?(): PaletteGroupsOrder | undefined;
71
+ /** The locale the pin buttons are labelled in. By default, the document's language. */
72
+ locale?(): string;
70
73
  }
74
+ /** The part of a {@link PaletteOrder} the child palettes use. */
75
+ export type PaletteGroupsOrder = Pick<PaletteOrder, 'members' | 'setMembers' | 'isPinned' | 'setPinned' | 'subscribe'>;
71
76
  export interface PaletteCategoryGroupsController {
72
77
  /**
73
78
  * Prepares a toolbox tree as {@link prepareGroupedToolboxTree} does, and puts each group's members in the order
@@ -79,10 +84,21 @@ export interface PaletteCategoryGroupsController {
79
84
  }): PaletteGroups;
80
85
  /** Takes the groups of the toolbox just drawn: hides their members' icons and marks the groups' icons. */
81
86
  update(groups: PaletteGroups): void;
87
+ /** The groups the palette was last drawn with, members in their order, to show another palette the same way. */
88
+ current(): PaletteGroups;
89
+ /** Whether the category is a group the palette shows, whose icon opens a child palette. */
82
90
  isGroup(id: string): boolean;
91
+ /**
92
+ * The category whose icon stands for the id in the palette: its own, when the palette shows it, or that of the
93
+ * nearest group the palette shows. A pinned group's members are shown in the palette that shows the group.
94
+ */
95
+ shownAs(id: string): string;
83
96
  /** The id of the outermost group the category is in, or its own id when it is in none. */
84
97
  topLevelId(id: string): string;
85
- /** Opens the group's child palette from its icon, or closes it if it is open. */
98
+ /**
99
+ * Opens the group's child palette from its icon, or closes it if it is open. A pinned group shows its members in
100
+ * place, so its icon only opens its own blocks, if it has any.
101
+ */
86
102
  toggle(category: PaletteCategory, focus?: boolean): void;
87
103
  isOpen(): boolean;
88
104
  /** The icon the palette shows for the category: its own, or that of the group it is in. */
@@ -164,14 +164,68 @@ export const attachPaletteCategoryGroups = (menu, options) => {
164
164
  current = parentOf.get(current);
165
165
  return current;
166
166
  };
167
+ const isPinned = (id) => groups.members.has(id) && memberOrder().isPinned(id);
168
+ // A category is in the palette when every group it is in is pinned open.
169
+ const inPalette = (id) => {
170
+ for (let parent = parentOf.get(id); parent !== undefined; parent = parentOf.get(parent)) {
171
+ if (!isPinned(parent))
172
+ return false;
173
+ }
174
+ return true;
175
+ };
176
+ const shownAs = (id) => {
177
+ let current = id;
178
+ while (!inPalette(current))
179
+ current = parentOf.get(current);
180
+ return current;
181
+ };
182
+ // Changes this palette makes itself, which it does not need to hear back about.
183
+ let writing = false;
184
+ const quietly = (write) => {
185
+ writing = true;
186
+ try {
187
+ write();
188
+ }
189
+ finally {
190
+ writing = false;
191
+ }
192
+ };
193
+ const japanese = () => /^ja(?:-|$)/i.test(options.locale?.() ?? doc.documentElement.lang);
194
+ /** A pin button: pinned, it folds the group back; unpinned, it pins the group open. */
195
+ const pinButton = (pinned, press) => {
196
+ const button = doc.createElement('span');
197
+ button.className = 'tw-palette-group-pin';
198
+ button.setAttribute('data-palette-group-pin', pinned ? 'pinned' : 'unpinned');
199
+ button.setAttribute('role', 'button');
200
+ button.tabIndex = 0;
201
+ const label = pinned ? (japanese() ? 'グループの固定を外して、たたむ' : 'Unpin and fold the group') :
202
+ (japanese() ? 'グループをパレットに広げて固定する' : 'Pin the group open in the palette');
203
+ button.setAttribute('aria-label', label);
204
+ button.title = label;
205
+ const pressed = (event) => {
206
+ event.preventDefault();
207
+ event.stopPropagation();
208
+ press();
209
+ };
210
+ button.addEventListener('click', pressed, { signal: events.signal });
211
+ button.addEventListener('keydown', event => {
212
+ if (event.key === 'Enter' || event.key === ' ')
213
+ pressed(event);
214
+ }, { signal: events.signal });
215
+ // Scratch Blocks would open the category the button sits on.
216
+ for (const type of ['mouseup', 'touchend']) {
217
+ button.addEventListener(type, event => event.stopPropagation(), { signal: events.signal });
218
+ }
219
+ return button;
220
+ };
167
221
  const markSelection = () => {
168
222
  for (const [id] of groups.members) {
169
- if (parentOf.has(id))
223
+ if (!inPalette(id))
170
224
  continue;
171
225
  const item = categoryById(id)?.item_;
172
226
  if (!item)
173
227
  continue;
174
- const current = selected !== null && selected !== id && topLevelOf(selected) === id;
228
+ const current = selected !== null && selected !== id && shownAs(selected) === id;
175
229
  item.toggleAttribute('data-palette-group-current', current);
176
230
  if (current)
177
231
  item.classList.add(selectedClass);
@@ -214,13 +268,16 @@ export const attachPaletteCategoryGroups = (menu, options) => {
214
268
  popup.style.top = `${Math.min(Math.max(0, top), maxTop)}px`;
215
269
  };
216
270
  const activate = (category, entry, depth, focus, self) => {
217
- if (!self && groups.members.has(category.id_)) {
271
+ if (!self && groups.members.has(category.id_) && !isPinned(category.id_)) {
218
272
  if (stack[depth]?.id === category.id_)
219
273
  closeFrom(depth);
220
274
  else
221
275
  open(category, entry, depth, focus);
222
276
  return;
223
277
  }
278
+ // A pinned group without blocks of its own shows its members where it is, so there is nothing to open.
279
+ if (!self && groups.members.has(category.id_) && !groups.withOwnContents.has(category.id_))
280
+ return;
224
281
  close();
225
282
  options.choose(category);
226
283
  };
@@ -231,10 +288,21 @@ export const attachPaletteCategoryGroups = (menu, options) => {
231
288
  entry.setAttribute('data-palette-group-item', category.id_);
232
289
  entry.setAttribute('role', 'menuitem');
233
290
  entry.tabIndex = -1;
234
- for (const child of Array.from(category.item_.children))
235
- entry.append(child.cloneNode(true));
291
+ entry.title = category.item_.textContent?.trim() || category.item_.getAttribute('aria-label') || '';
292
+ for (const child of Array.from(category.item_.children)) {
293
+ if (!child.hasAttribute('data-palette-group-pin'))
294
+ entry.append(child.cloneNode(true));
295
+ }
236
296
  const isGroup = !self && groups.members.has(category.id_);
237
- if (isGroup) {
297
+ if (isGroup && isPinned(category.id_)) {
298
+ entry.setAttribute('data-palette-group-pinned', '');
299
+ // Folding the group back draws this child palette again.
300
+ entry.append(pinButton(true, () => {
301
+ quietly(() => memberOrder().setPinned(category.id_, false));
302
+ reopen(depth - 1);
303
+ }));
304
+ }
305
+ else if (isGroup) {
238
306
  entry.setAttribute('aria-haspopup', 'true');
239
307
  entry.setAttribute('aria-expanded', 'false');
240
308
  }
@@ -257,7 +325,7 @@ export const attachPaletteCategoryGroups = (menu, options) => {
257
325
  if (event.key !== forward && event.key !== backward)
258
326
  return;
259
327
  event.preventDefault();
260
- const entries = Array.from(entry.parentElement.children);
328
+ const entries = Array.from(entry.parentElement.querySelectorAll(':scope > [data-palette-group-item]'));
261
329
  const index = entries.indexOf(entry) + (event.key === forward ? 1 : -1);
262
330
  entries[(index + entries.length) % entries.length].focus();
263
331
  }, { signal: events.signal });
@@ -287,10 +355,27 @@ export const attachPaletteCategoryGroups = (menu, options) => {
287
355
  popup.style.fontFamily = look.fontFamily;
288
356
  if (options.rtl)
289
357
  popup.dir = 'rtl';
358
+ // Pinning the group shows its members in the palette that shows the group.
359
+ popup.append(pinButton(false, () => pinFrom(depth)));
290
360
  if (groups.withOwnContents.has(group.id_))
291
361
  popup.append(createEntry(group, depth, true));
292
- const entries = members.map(member => createEntry(member, depth + 1));
293
- popup.append(...entries);
362
+ const entries = [];
363
+ // A pinned member group is followed by its own members, here rather than in a child palette of its own.
364
+ const add = (member, direct) => {
365
+ const entry = createEntry(member, depth + 1);
366
+ if (direct)
367
+ entries.push(entry);
368
+ popup.append(entry);
369
+ if (!isPinned(member.id_))
370
+ return;
371
+ for (const id of groups.members.get(member.id_) ?? []) {
372
+ const inner = categoryById(id);
373
+ if (inner)
374
+ add(inner, false);
375
+ }
376
+ };
377
+ for (const member of members)
378
+ add(member, true);
294
379
  (menu.parentElement ?? doc.body).append(popup);
295
380
  place(popup, anchor);
296
381
  anchor.setAttribute('aria-expanded', 'true');
@@ -298,7 +383,7 @@ export const attachPaletteCategoryGroups = (menu, options) => {
298
383
  const reorder = options.reorder ? attachPaletteCategoryReorder(popup, () => entries, (from, to) => {
299
384
  const order = members.map(member => member.id_);
300
385
  order.splice(to, 0, order.splice(from, 1)[0]);
301
- memberOrder().setMembers(group.id_, order);
386
+ quietly(() => memberOrder().setMembers(group.id_, order));
302
387
  groups.members.set(group.id_, order);
303
388
  open(group, anchor, depth, false);
304
389
  options.onReorder?.();
@@ -309,16 +394,96 @@ export const attachPaletteCategoryGroups = (menu, options) => {
309
394
  popup.firstElementChild?.focus();
310
395
  };
311
396
  const toggle = (category, focus = false) => {
312
- if (stack[0]?.id === category.id_)
397
+ if (isPinned(category.id_)) {
398
+ close();
399
+ if (groups.withOwnContents.has(category.id_))
400
+ options.choose(category);
401
+ }
402
+ else if (stack[0]?.id === category.id_)
313
403
  close();
314
404
  else
315
405
  open(category, category.item_, 0, focus);
316
406
  };
407
+ // Draws the child palette at the depth again, or the palette itself.
408
+ function reopen(depth) {
409
+ if (depth < 0 || !stack[depth]) {
410
+ close();
411
+ applyVisibility();
412
+ return;
413
+ }
414
+ const { id, anchor } = stack[depth];
415
+ const group = categoryById(id);
416
+ if (group)
417
+ open(group, anchor, depth, false);
418
+ else
419
+ closeFrom(depth);
420
+ }
421
+ // Pins open the group of the child palette at the depth: its members join the palette it opened from.
422
+ function pinFrom(depth) {
423
+ const { id } = stack[depth];
424
+ quietly(() => memberOrder().setPinned(id, true));
425
+ closeFrom(depth);
426
+ if (depth > 0)
427
+ reopen(depth - 1);
428
+ else
429
+ applyVisibility();
430
+ }
431
+ // Shows the categories every group of which is pinned open, hides the others, and marks the groups shown.
432
+ function applyVisibility() {
433
+ for (const category of options.categories()) {
434
+ const id = category.id_;
435
+ const item = category.item_;
436
+ const row = item.parentElement;
437
+ if (row && row !== menu)
438
+ row.hidden = !inPalette(id);
439
+ const group = groups.members.has(id) && inPalette(id);
440
+ if (group) {
441
+ item.setAttribute('aria-haspopup', 'true');
442
+ if (!item.hasAttribute('aria-expanded'))
443
+ item.setAttribute('aria-expanded', 'false');
444
+ item.setAttribute('data-palette-group', '');
445
+ item.classList.add('tw-palette-group');
446
+ }
447
+ const pinned = group && isPinned(id);
448
+ item.toggleAttribute('data-palette-group-pinned', pinned);
449
+ const button = item.querySelector(':scope > [data-palette-group-pin]');
450
+ if (pinned && !button) {
451
+ item.append(pinButton(true, () => {
452
+ quietly(() => memberOrder().setPinned(id, false));
453
+ close();
454
+ applyVisibility();
455
+ }));
456
+ }
457
+ else if (!pinned)
458
+ button?.remove();
459
+ }
460
+ markSelection();
461
+ options.onChange?.();
462
+ }
463
+ // Another palette given the same order, or a project loaded, may pin or fold groups.
464
+ let watched;
465
+ let unwatch;
466
+ const watchOrder = () => {
467
+ const order = memberOrder();
468
+ if (order === watched)
469
+ return;
470
+ unwatch?.();
471
+ watched = order;
472
+ unwatch = order.subscribe(() => {
473
+ if (writing)
474
+ return;
475
+ close();
476
+ applyVisibility();
477
+ });
478
+ };
317
479
  const groupItem = (target) => {
318
480
  if (!(target instanceof doc.defaultView.Node))
319
481
  return null;
482
+ // A pin button handles its own press.
483
+ if (target.closest?.('[data-palette-group-pin]'))
484
+ return null;
320
485
  return options.categories().find(category => groups.members.has(category.id_) &&
321
- !parentOf.has(category.id_) && category.item_.contains(target)) ?? null;
486
+ inPalette(category.id_) && category.item_.contains(target)) ?? null;
322
487
  };
323
488
  // Scratch Blocks opens a category on mouseup (touchend on touch screens); a group opens its child palette on click.
324
489
  for (const type of ['mouseup', 'touchend']) {
@@ -393,18 +558,8 @@ export const attachPaletteCategoryGroups = (menu, options) => {
393
558
  update(next) {
394
559
  close();
395
560
  useGroups(next);
561
+ watchOrder();
396
562
  for (const category of options.categories()) {
397
- const member = parentOf.has(category.id_);
398
- const row = category.item_.parentElement;
399
- if (row && row !== menu)
400
- row.hidden = member;
401
- const group = groups.members.has(category.id_) && !member;
402
- if (group) {
403
- category.item_.setAttribute('aria-haspopup', 'true');
404
- category.item_.setAttribute('aria-expanded', 'false');
405
- category.item_.setAttribute('data-palette-group', '');
406
- category.item_.classList.add('tw-palette-group');
407
- }
408
563
  const { setSelected } = category;
409
564
  category.setSelected = function (value) {
410
565
  setSelected.call(this, value);
@@ -417,13 +572,15 @@ export const attachPaletteCategoryGroups = (menu, options) => {
417
572
  if (category.item_.classList.contains(selectedClass))
418
573
  selected = category.id_;
419
574
  }
420
- markSelection();
575
+ applyVisibility();
421
576
  },
422
- isGroup: id => groups.members.has(id) && !parentOf.has(id),
577
+ current: () => groups,
578
+ isGroup: id => groups.members.has(id) && inPalette(id),
579
+ shownAs,
423
580
  topLevelId: topLevelOf,
424
581
  toggle,
425
582
  isOpen: () => stack.length > 0,
426
- anchorOf: category => categoryById(topLevelOf(category.id_))?.item_ ?? category.item_,
583
+ anchorOf: category => categoryById(shownAs(category.id_))?.item_ ?? category.item_,
427
584
  arrange(categories, rank) {
428
585
  const position = new Map();
429
586
  const visit = (id) => {
@@ -461,7 +618,7 @@ export const attachPaletteCategoryGroups = (menu, options) => {
461
618
  syncButtons(openId) {
462
619
  const horizontal = options.horizontal();
463
620
  for (const category of options.categories()) {
464
- if (!groups.members.has(category.id_) || parentOf.has(category.id_))
621
+ if (!groups.members.has(category.id_) || !inPalette(category.id_))
465
622
  continue;
466
623
  const item = category.item_;
467
624
  if (horizontal)
@@ -470,13 +627,14 @@ export const attachPaletteCategoryGroups = (menu, options) => {
470
627
  item.removeAttribute('tabindex');
471
628
  item.setAttribute('role', 'button');
472
629
  item.toggleAttribute('data-palette-group-shown', horizontal && openId !== null && openId !== category.id_ &&
473
- topLevelOf(openId) === category.id_);
630
+ shownAs(openId) === category.id_);
474
631
  }
475
632
  },
476
633
  contains,
477
634
  close,
478
635
  dispose() {
479
636
  close();
637
+ unwatch?.();
480
638
  events.abort();
481
639
  }
482
640
  };
@@ -130,10 +130,14 @@ export interface SavedPaletteVisibility {
130
130
  sets?: Record<string, SavedGroupSet>;
131
131
  order?: SavedPaletteOrder;
132
132
  }
133
- /** The order the palette's categories were dragged into: the top level, and the members of each group, by ID. */
133
+ /**
134
+ * The order the palette's categories were dragged into: the top level, and the members of each group, by ID; and the
135
+ * groups pinned open, whose members the palette shows in place of the group's child palette.
136
+ */
134
137
  export interface SavedPaletteOrder {
135
138
  categories?: string[];
136
139
  groups?: Record<string, string[]>;
140
+ pinned?: string[];
137
141
  }
138
142
  /** The order the palette's categories were dragged into, for the whole project. */
139
143
  export interface PaletteOrder {
@@ -143,7 +147,12 @@ export interface PaletteOrder {
143
147
  /** A group's members, by ID, in order, or nothing when they were never reordered. */
144
148
  members(groupId: string): string[] | undefined;
145
149
  setMembers(groupId: string, ids: readonly string[]): void;
146
- /** The order to save, or nothing when nothing was reordered. */
150
+ /** Whether the group is pinned open, its members shown in the palette that shows the group. */
151
+ isPinned(groupId: string): boolean;
152
+ setPinned(groupId: string, pinned: boolean): void;
153
+ /** Calls `listener` after anything changes, including a loaded or forgotten order. Returns the function that stops. */
154
+ subscribe(listener: () => void): () => void;
155
+ /** The order to save, or nothing when nothing was reordered or pinned. */
147
156
  capture(): SavedPaletteOrder | undefined;
148
157
  /** Takes a saved order. A value that is not one leaves the palette in its own order. */
149
158
  apply(value: unknown): void;