@kubohiroya/turbowarp-plus-editor-code-views 0.15.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,10 +16,10 @@ 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` では、子ブロックパレットの要素を長押しして、同じグループの要素の中で並べ替えられる(別のグループや階層へは動かさない)。順番はパレットを描き直しても保ち、`arrange(categories, rank)` がツールボックスの category をそれに合わせて、グループの後にその要素が続くように並べる。`splitExtensionCategories(tree, catalog, {nested: true})` は、グループを宣言した機能拡張をこのグループにする |
22
- | `./palette-category-visibility`・`./palette-visibility-dialog` | スプライト・背景ごとに、パレットに出すブロックグループを選ぶ。設定はエディターの画面状態として保存し、選ぶ画面を持つ |
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
+ | `./palette-category-visibility`・`./palette-visibility-dialog` | スプライト・背景ごとに、パレットに出すブロックグループを選ぶ。設定はエディターの画面状態として保存し、選ぶ画面を持つ。ストアの `order`(`createPaletteOrder`)は、パレットのカテゴリーと各グループの要素を並べ替えた順番を保ち、同じ設定と一緒に保存する |
23
23
  | `./block-argument-text` | 長いテキストの引数を短く表示し、ダイアログで編集する。テキストの引数で Shift+Enter を押すと、改行を入れてダイアログで編集を続ける |
24
24
  | `./block-number-input` | 数値の引数に入力した全角の数字・記号を半角にする |
25
25
  | `./clean-up-comments` | 「きれいにする」でコメントをスクリプトについて動かす。ブロックのコメントはブロックとの相対位置を保ち、コメントを含めたスクリプト同士が重ならないようにし、スクリプトに重なるワークスペースのコメントはスクリプトの横へ移す(`installCleanUpComments(ScratchBlocks)`) |
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 |
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 |
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
+ | `./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, 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 = [];
@@ -1,4 +1,4 @@
1
- import type { PaletteGroupCatalog } from './palette-category-visibility.ts';
1
+ import type { PaletteGroupCatalog, PaletteOrder } from './palette-category-visibility.ts';
2
2
  /**
3
3
  * Block palette groups: a category of the toolbox XML that holds other categories is a group. Scratch Blocks
4
4
  * reads only the top-level categories and drops nested ones, so the tree is flattened before it is drawn:
@@ -62,14 +62,43 @@ export interface PaletteCategoryGroupsOptions {
62
62
  reorder?: boolean;
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
+ /**
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.
69
+ */
70
+ order?(): PaletteGroupsOrder | undefined;
71
+ /** The locale the pin buttons are labelled in. By default, the document's language. */
72
+ locale?(): string;
65
73
  }
74
+ /** The part of a {@link PaletteOrder} the child palettes use. */
75
+ export type PaletteGroupsOrder = Pick<PaletteOrder, 'members' | 'setMembers' | 'isPinned' | 'setPinned' | 'subscribe'>;
66
76
  export interface PaletteCategoryGroupsController {
77
+ /**
78
+ * Prepares a toolbox tree as {@link prepareGroupedToolboxTree} does, and puts each group's members in the order
79
+ * they were dragged into, so the palette is drawn in that order. Pass the groups returned to `update`.
80
+ */
81
+ prepare(tree: Element, options?: {
82
+ catalog?: PaletteGroupCatalog;
83
+ visible?: ReadonlySet<string> | null;
84
+ }): PaletteGroups;
67
85
  /** Takes the groups of the toolbox just drawn: hides their members' icons and marks the groups' icons. */
68
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. */
69
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;
70
96
  /** The id of the outermost group the category is in, or its own id when it is in none. */
71
97
  topLevelId(id: string): string;
72
- /** 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
+ */
73
102
  toggle(category: PaletteCategory, focus?: boolean): void;
74
103
  isOpen(): boolean;
75
104
  /** The icon the palette shows for the category: its own, or that of the group it is in. */
@@ -1,4 +1,5 @@
1
1
  import { filterToolboxTree, splitExtensionCategories } from "./palette-category-visibility.js";
2
+ import { createPaletteOrder } from "./palette-category-visibility.js";
2
3
  import { attachPaletteCategoryReorder } from "./palette-category-reorder.js";
3
4
  /**
4
5
  * Block palette groups: a category of the toolbox XML that holds other categories is a group. Scratch Blocks
@@ -133,19 +134,28 @@ export const attachPaletteCategoryGroups = (menu, options) => {
133
134
  // The open child palettes, outermost first, with the icon each opened from.
134
135
  const stack = [];
135
136
  // The order members were dragged into, by group, kept while the toolbox is drawn again.
136
- const memberOrder = new Map();
137
- const applyMemberOrder = () => {
138
- for (const [id, members] of groups.members) {
139
- const saved = memberOrder.get(id);
137
+ const ownOrder = createPaletteOrder();
138
+ const memberOrder = () => options.order?.() ?? ownOrder;
139
+ const applyMemberOrder = (target) => {
140
+ for (const [id, members] of target.members) {
141
+ const saved = memberOrder().members(id);
140
142
  if (!saved)
141
143
  continue;
142
144
  const rank = (member) => {
143
145
  const index = saved.indexOf(member);
144
146
  return index < 0 ? saved.length : index;
145
147
  };
146
- groups.members.set(id, members.slice().sort((a, b) => rank(a) - rank(b)));
148
+ target.members.set(id, members.slice().sort((a, b) => rank(a) - rank(b)));
147
149
  }
148
150
  };
151
+ const useGroups = (next) => {
152
+ groups = next;
153
+ applyMemberOrder(groups);
154
+ parentOf.clear();
155
+ for (const [id, members] of groups.members)
156
+ for (const member of members)
157
+ parentOf.set(member, id);
158
+ };
149
159
  let selected = null;
150
160
  const categoryById = (id) => options.categories().find(category => category.id_ === id);
151
161
  const topLevelOf = (id) => {
@@ -154,14 +164,68 @@ export const attachPaletteCategoryGroups = (menu, options) => {
154
164
  current = parentOf.get(current);
155
165
  return current;
156
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
+ };
157
221
  const markSelection = () => {
158
222
  for (const [id] of groups.members) {
159
- if (parentOf.has(id))
223
+ if (!inPalette(id))
160
224
  continue;
161
225
  const item = categoryById(id)?.item_;
162
226
  if (!item)
163
227
  continue;
164
- const current = selected !== null && selected !== id && topLevelOf(selected) === id;
228
+ const current = selected !== null && selected !== id && shownAs(selected) === id;
165
229
  item.toggleAttribute('data-palette-group-current', current);
166
230
  if (current)
167
231
  item.classList.add(selectedClass);
@@ -204,13 +268,16 @@ export const attachPaletteCategoryGroups = (menu, options) => {
204
268
  popup.style.top = `${Math.min(Math.max(0, top), maxTop)}px`;
205
269
  };
206
270
  const activate = (category, entry, depth, focus, self) => {
207
- if (!self && groups.members.has(category.id_)) {
271
+ if (!self && groups.members.has(category.id_) && !isPinned(category.id_)) {
208
272
  if (stack[depth]?.id === category.id_)
209
273
  closeFrom(depth);
210
274
  else
211
275
  open(category, entry, depth, focus);
212
276
  return;
213
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;
214
281
  close();
215
282
  options.choose(category);
216
283
  };
@@ -221,10 +288,21 @@ export const attachPaletteCategoryGroups = (menu, options) => {
221
288
  entry.setAttribute('data-palette-group-item', category.id_);
222
289
  entry.setAttribute('role', 'menuitem');
223
290
  entry.tabIndex = -1;
224
- for (const child of Array.from(category.item_.children))
225
- 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
+ }
226
296
  const isGroup = !self && groups.members.has(category.id_);
227
- 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) {
228
306
  entry.setAttribute('aria-haspopup', 'true');
229
307
  entry.setAttribute('aria-expanded', 'false');
230
308
  }
@@ -247,7 +325,7 @@ export const attachPaletteCategoryGroups = (menu, options) => {
247
325
  if (event.key !== forward && event.key !== backward)
248
326
  return;
249
327
  event.preventDefault();
250
- const entries = Array.from(entry.parentElement.children);
328
+ const entries = Array.from(entry.parentElement.querySelectorAll(':scope > [data-palette-group-item]'));
251
329
  const index = entries.indexOf(entry) + (event.key === forward ? 1 : -1);
252
330
  entries[(index + entries.length) % entries.length].focus();
253
331
  }, { signal: events.signal });
@@ -277,10 +355,27 @@ export const attachPaletteCategoryGroups = (menu, options) => {
277
355
  popup.style.fontFamily = look.fontFamily;
278
356
  if (options.rtl)
279
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)));
280
360
  if (groups.withOwnContents.has(group.id_))
281
361
  popup.append(createEntry(group, depth, true));
282
- const entries = members.map(member => createEntry(member, depth + 1));
283
- 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);
284
379
  (menu.parentElement ?? doc.body).append(popup);
285
380
  place(popup, anchor);
286
381
  anchor.setAttribute('aria-expanded', 'true');
@@ -288,7 +383,7 @@ export const attachPaletteCategoryGroups = (menu, options) => {
288
383
  const reorder = options.reorder ? attachPaletteCategoryReorder(popup, () => entries, (from, to) => {
289
384
  const order = members.map(member => member.id_);
290
385
  order.splice(to, 0, order.splice(from, 1)[0]);
291
- memberOrder.set(group.id_, order);
386
+ quietly(() => memberOrder().setMembers(group.id_, order));
292
387
  groups.members.set(group.id_, order);
293
388
  open(group, anchor, depth, false);
294
389
  options.onReorder?.();
@@ -299,16 +394,96 @@ export const attachPaletteCategoryGroups = (menu, options) => {
299
394
  popup.firstElementChild?.focus();
300
395
  };
301
396
  const toggle = (category, focus = false) => {
302
- 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_)
303
403
  close();
304
404
  else
305
405
  open(category, category.item_, 0, focus);
306
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
+ };
307
479
  const groupItem = (target) => {
308
480
  if (!(target instanceof doc.defaultView.Node))
309
481
  return null;
482
+ // A pin button handles its own press.
483
+ if (target.closest?.('[data-palette-group-pin]'))
484
+ return null;
310
485
  return options.categories().find(category => groups.members.has(category.id_) &&
311
- !parentOf.has(category.id_) && category.item_.contains(target)) ?? null;
486
+ inPalette(category.id_) && category.item_.contains(target)) ?? null;
312
487
  };
313
488
  // Scratch Blocks opens a category on mouseup (touchend on touch screens); a group opens its child palette on click.
314
489
  for (const type of ['mouseup', 'touchend']) {
@@ -348,26 +523,43 @@ export const attachPaletteCategoryGroups = (menu, options) => {
348
523
  menu.addEventListener('scroll', close, { signal: events.signal });
349
524
  doc.defaultView.addEventListener('resize', close, { signal: events.signal });
350
525
  return {
526
+ prepare(tree, prepareOptions) {
527
+ const prepared = prepareGroupedToolboxTree(tree, prepareOptions);
528
+ close();
529
+ useGroups(prepared);
530
+ // Each group is followed by its members, each with its own members, in their order.
531
+ const elements = Array.from(tree.children).filter(isCategory);
532
+ const byId = new Map(elements.map(element => [element.getAttribute('id'), element]));
533
+ const ordered = [];
534
+ const visit = (element) => {
535
+ ordered.push(element);
536
+ for (const member of groups.members.get(element.getAttribute('id')) ?? []) {
537
+ const child = byId.get(member);
538
+ if (child)
539
+ visit(child);
540
+ }
541
+ };
542
+ for (const element of elements)
543
+ if (!element.hasAttribute(groupParentAttribute))
544
+ visit(element);
545
+ const slots = elements.map(element => {
546
+ const slot = tree.ownerDocument.createComment('palette-category');
547
+ element.replaceWith(slot);
548
+ return slot;
549
+ });
550
+ slots.forEach((slot, index) => {
551
+ if (ordered[index])
552
+ slot.replaceWith(ordered[index]);
553
+ else
554
+ slot.remove();
555
+ });
556
+ return prepared;
557
+ },
351
558
  update(next) {
352
559
  close();
353
- groups = next;
354
- applyMemberOrder();
355
- parentOf.clear();
356
- for (const [id, members] of groups.members)
357
- for (const member of members)
358
- parentOf.set(member, id);
560
+ useGroups(next);
561
+ watchOrder();
359
562
  for (const category of options.categories()) {
360
- const member = parentOf.has(category.id_);
361
- const row = category.item_.parentElement;
362
- if (row && row !== menu)
363
- row.hidden = member;
364
- const group = groups.members.has(category.id_) && !member;
365
- if (group) {
366
- category.item_.setAttribute('aria-haspopup', 'true');
367
- category.item_.setAttribute('aria-expanded', 'false');
368
- category.item_.setAttribute('data-palette-group', '');
369
- category.item_.classList.add('tw-palette-group');
370
- }
371
563
  const { setSelected } = category;
372
564
  category.setSelected = function (value) {
373
565
  setSelected.call(this, value);
@@ -380,13 +572,15 @@ export const attachPaletteCategoryGroups = (menu, options) => {
380
572
  if (category.item_.classList.contains(selectedClass))
381
573
  selected = category.id_;
382
574
  }
383
- markSelection();
575
+ applyVisibility();
384
576
  },
385
- isGroup: id => groups.members.has(id) && !parentOf.has(id),
577
+ current: () => groups,
578
+ isGroup: id => groups.members.has(id) && inPalette(id),
579
+ shownAs,
386
580
  topLevelId: topLevelOf,
387
581
  toggle,
388
582
  isOpen: () => stack.length > 0,
389
- anchorOf: category => categoryById(topLevelOf(category.id_))?.item_ ?? category.item_,
583
+ anchorOf: category => categoryById(shownAs(category.id_))?.item_ ?? category.item_,
390
584
  arrange(categories, rank) {
391
585
  const position = new Map();
392
586
  const visit = (id) => {
@@ -424,7 +618,7 @@ export const attachPaletteCategoryGroups = (menu, options) => {
424
618
  syncButtons(openId) {
425
619
  const horizontal = options.horizontal();
426
620
  for (const category of options.categories()) {
427
- if (!groups.members.has(category.id_) || parentOf.has(category.id_))
621
+ if (!groups.members.has(category.id_) || !inPalette(category.id_))
428
622
  continue;
429
623
  const item = category.item_;
430
624
  if (horizontal)
@@ -433,13 +627,14 @@ export const attachPaletteCategoryGroups = (menu, options) => {
433
627
  item.removeAttribute('tabindex');
434
628
  item.setAttribute('role', 'button');
435
629
  item.toggleAttribute('data-palette-group-shown', horizontal && openId !== null && openId !== category.id_ &&
436
- topLevelOf(openId) === category.id_);
630
+ shownAs(openId) === category.id_);
437
631
  }
438
632
  },
439
633
  contains,
440
634
  close,
441
635
  dispose() {
442
636
  close();
637
+ unwatch?.();
443
638
  events.abort();
444
639
  }
445
640
  };