@kubohiroya/turbowarp-plus-editor-workbench 0.10.0 → 0.11.1

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.
@@ -5,6 +5,7 @@ import { createSpriteLayoutMenu } from "./sprite-layout-menu.js";
5
5
  import { NativeAssetPanel, SpriteAssetPane } from '@kubohiroya/turbowarp-plus-editor-sprite-panes/sprite-asset-pane';
6
6
  import { SpriteEditorToolbar, spriteEditorSections } from '@kubohiroya/turbowarp-plus-editor-sprite-panes/sprite-editor-toolbar';
7
7
  import { documentPanelTitle, getDocumentWorkspace } from "./document-workspace.js";
8
+ import { projectFolderIconPath } from "./drawer-views.js";
8
9
  import { dockPopoutGroups, positionOnScreen, readWorkspaceLayout, workspaceWithoutTransientPanels } from "./workspace-layout.js";
9
10
  import { createWorkspaceLayoutStore } from "./workspace-layout-store.js";
10
11
  import { SpriteMessagePane } from '@kubohiroya/turbowarp-plus-editor-sprite-panes/sprite-message-pane';
@@ -70,12 +71,27 @@ const projectSignature = (targets) => JSON.stringify(targets
70
71
  .sort());
71
72
  class SpriteTab extends DefaultTab {
72
73
  icon;
74
+ folderIcon;
73
75
  constructor(document) {
74
76
  super();
75
77
  this.icon = document.createElement('img');
76
78
  this.icon.className = 'tw-plus-sprite-tab-icon';
77
79
  this.icon.alt = '';
78
80
  this.icon.draggable = false;
81
+ const svg = 'http://www.w3.org/2000/svg';
82
+ this.folderIcon = document.createElementNS(svg, 'svg');
83
+ this.folderIcon.classList.add('tw-plus-sprite-tab-icon', 'tw-plus-folder-tab-icon');
84
+ this.folderIcon.setAttribute('viewBox', '0 0 16 16');
85
+ this.folderIcon.setAttribute('fill', 'none');
86
+ this.folderIcon.setAttribute('stroke', 'currentColor');
87
+ this.folderIcon.setAttribute('stroke-width', '1.3');
88
+ this.folderIcon.setAttribute('stroke-linecap', 'round');
89
+ this.folderIcon.setAttribute('stroke-linejoin', 'round');
90
+ this.folderIcon.setAttribute('aria-hidden', 'true');
91
+ const path = document.createElementNS(svg, 'path');
92
+ path.setAttribute('d', projectFolderIconPath);
93
+ this.folderIcon.append(path);
94
+ this.element.prepend(this.folderIcon);
79
95
  this.element.prepend(this.icon);
80
96
  }
81
97
  init(options) {
@@ -83,6 +99,10 @@ class SpriteTab extends DefaultTab {
83
99
  this.update(options);
84
100
  }
85
101
  update({ params }) {
102
+ this.element.toggleAttribute('data-fixed-project-tab', Boolean(params.fixedProjectTab));
103
+ const close = this.element.querySelector('.dv-default-tab-action');
104
+ if (close)
105
+ close.style.display = params.fixedProjectTab ? 'none' : '';
86
106
  this.icon.hidden = !params.icon;
87
107
  if (params.icon)
88
108
  this.icon.src = params.icon;
@@ -133,7 +153,7 @@ export function mountSpriteTabs(root, content, options) {
133
153
  let initialShape;
134
154
  let disposed = false;
135
155
  const window = document.defaultView;
136
- const documentWorkspace = multiView && getDocumentWorkspace(vm);
156
+ const documentWorkspace = multiView ? getDocumentWorkspace(vm) : undefined;
137
157
  let pendingRestore = Boolean(persistence);
138
158
  let drawerEditedDuringRestore = false;
139
159
  let restoreFrame;
@@ -168,7 +188,7 @@ export function mountSpriteTabs(root, content, options) {
168
188
  } },
169
189
  { label: chipText.closeAll, action: () => {
170
190
  for (const panel of [...group.panels])
171
- if (documents.has(panel.id))
191
+ if (documents.has(panel.id) && !fixedProjectTab(panel.id))
172
192
  panel.api.close();
173
193
  } }
174
194
  ],
@@ -206,7 +226,8 @@ export function mountSpriteTabs(root, content, options) {
206
226
  const item = documents.get(componentId);
207
227
  element.dataset.providerId = item.request.reference.providerId;
208
228
  element.dataset.documentId = item.request.reference.documentId;
209
- item.session = item.request.mount(element, () => api.close());
229
+ item.session = item.request.mount(element, () => api.close(), documentWorkspace?.notifySave);
230
+ documentWorkspace?.notifySave();
210
231
  } };
211
232
  }
212
233
  if (name === stagePanelId) {
@@ -295,14 +316,17 @@ export function mountSpriteTabs(root, content, options) {
295
316
  preventSplit(event);
296
317
  return;
297
318
  }
298
- if (event.group?.api.location.type !== 'popout')
299
- return;
300
319
  const transfer = event.getData();
301
320
  const ids = transfer?.panelId ? [transfer.panelId] :
302
321
  dockview.groups.find(group => group.id === transfer?.groupId)?.panels.map(panel => panel.id) ?? [];
303
- if (ids.some(id => documents.has(id)))
322
+ if (ids.some(fixedProjectTab) ||
323
+ event.group?.api.location.type === 'popout' && ids.some(id => documents.has(id)))
304
324
  event.preventDefault();
305
325
  });
326
+ const dragFixedTab = dockview.onWillDragPanel(({ panel, nativeEvent }) => {
327
+ if (fixedProjectTab(panel.id))
328
+ nativeEvent.preventDefault();
329
+ });
306
330
  function createLayoutMenu(group) {
307
331
  const popouts = options.popouts;
308
332
  const canOpenPanel = () => group.api.location.type === 'grid' &&
@@ -636,7 +660,40 @@ export function mountSpriteTabs(root, content, options) {
636
660
  select(target.id);
637
661
  }
638
662
  }
663
+ function fixedProjectTab(id) {
664
+ return documentWorkspace?.saveScope === 'tab' && documents.get(id)?.request.pinWithProjectFolder === true;
665
+ }
666
+ function leftmostGroup() {
667
+ return dockview.groups.filter(group => group.api.location.type === 'grid')
668
+ .map(group => ({ group, rect: group.element.getBoundingClientRect() }))
669
+ .sort((a, b) => a.rect.left - b.rect.left || a.rect.top - b.rect.top)[0]?.group;
670
+ }
671
+ function syncFixedProjectTab() {
672
+ if (disposed || syncing)
673
+ return;
674
+ for (const [id, { request }] of documents) {
675
+ if (!request.pinWithProjectFolder)
676
+ continue;
677
+ const panel = dockview.getPanel(id);
678
+ if (!panel)
679
+ continue;
680
+ const fixed = fixedProjectTab(id);
681
+ if (panel.api.getParameters().fixedProjectTab !== fixed)
682
+ panel.api.updateParameters({ fixedProjectTab: fixed });
683
+ const group = fixed && leftmostGroup();
684
+ if (group && group.panels[0]?.id !== id)
685
+ panel.api.moveTo({ group, index: 0, skipSetActive: !panel.api.isActive });
686
+ }
687
+ }
639
688
  function openDocument(request) {
689
+ // An automatically opened utility must not interrupt a project's saved layout restoration.
690
+ if (pendingRestore && request.inactive && request.pinWithProjectFolder) {
691
+ void layoutSettled().then(() => {
692
+ if (!disposed && documentWorkspace?.saveScope === 'tab')
693
+ openDocument(request);
694
+ });
695
+ return;
696
+ }
640
697
  if (pendingRestore)
641
698
  finishRestore();
642
699
  const { providerId, documentId } = request.reference;
@@ -652,11 +709,13 @@ export function mountSpriteTabs(root, content, options) {
652
709
  id = 'document-view-' + ++nextView;
653
710
  } while (views.has(id) || documents.has(id) || vm.runtime.targets.some(target => target.id === id));
654
711
  const title = documentPanelTitle(request);
655
- const position = documentPosition(request);
712
+ const fixed = request.pinWithProjectFolder && documentWorkspace?.saveScope === 'tab';
713
+ const group = fixed && leftmostGroup();
714
+ const position = group ? { referenceGroup: group, index: 0 } : documentPosition(request);
656
715
  documents.set(id, { request });
657
716
  try {
658
717
  dockview.addPanel({ id, title, component: documentComponent, renderer: 'always',
659
- inactive: request.inactive, ...(position && { position }) });
718
+ inactive: request.inactive, params: { fixedProjectTab: Boolean(fixed) }, ...(position && { position }) });
660
719
  }
661
720
  catch (error) {
662
721
  documents.get(id)?.session?.dispose();
@@ -693,7 +752,10 @@ export function mountSpriteTabs(root, content, options) {
693
752
  function guardDocumentClose(event) {
694
753
  const element = event.target;
695
754
  const tab = element.closest('[data-tab-panel-id]');
696
- const item = documents.get(tab?.dataset.tabPanelId);
755
+ const id = tab?.dataset.tabPanelId;
756
+ if (!id)
757
+ return;
758
+ const item = documents.get(id);
697
759
  if (!item)
698
760
  return;
699
761
  const close = event.type === 'click' ? Boolean(element.closest('.dv-default-tab-action')) :
@@ -702,7 +764,8 @@ export function mountSpriteTabs(root, content, options) {
702
764
  return;
703
765
  event.preventDefault();
704
766
  event.stopPropagation();
705
- item.session?.requestClose();
767
+ if (!fixedProjectTab(id))
768
+ item.session?.requestClose();
706
769
  }
707
770
  function canCloseGroup(group) {
708
771
  return dockview.groups.length > 1 && group.panels.every(panel => !documents.has(panel.id));
@@ -1124,6 +1187,7 @@ export function mountSpriteTabs(root, content, options) {
1124
1187
  views.delete(view.id);
1125
1188
  }
1126
1189
  const selection = dockview.onDidActivePanelChange(({ panel }) => {
1190
+ documentWorkspace?.notifySave();
1127
1191
  if (syncing)
1128
1192
  return;
1129
1193
  syncing = true;
@@ -1140,6 +1204,7 @@ export function mountSpriteTabs(root, content, options) {
1140
1204
  if (item) {
1141
1205
  documents.delete(panel.id);
1142
1206
  item.session?.dispose();
1207
+ documentWorkspace?.notifySave();
1143
1208
  return;
1144
1209
  }
1145
1210
  if (panel.id === stagePanelId) {
@@ -1156,10 +1221,20 @@ export function mountSpriteTabs(root, content, options) {
1156
1221
  closed.add(view.target);
1157
1222
  });
1158
1223
  const layout = multiView && dockview.onDidLayoutChange(() => {
1224
+ syncFixedProjectTab();
1159
1225
  refreshSurfaces();
1160
1226
  scheduleSave();
1161
1227
  });
1162
- const disconnectDocuments = documentWorkspace && documentWorkspace.connect(openDocument);
1228
+ const disconnectDocuments = documentWorkspace && documentWorkspace.connect(openDocument, () => documents.get(dockview.activePanel?.id)?.session, function* () { for (const item of documents.values())
1229
+ yield item.session; });
1230
+ let previousScope = documentWorkspace?.saveScope;
1231
+ const unsubscribeFixedProjectTab = documentWorkspace?.subscribeSave(() => {
1232
+ const scope = documentWorkspace.saveScope;
1233
+ if (scope === previousScope)
1234
+ return;
1235
+ previousScope = scope;
1236
+ syncFixedProjectTab();
1237
+ });
1163
1238
  const unsubscribeDocuments = persistence && documentWorkspace && documentWorkspace.subscribe(scheduleRestore);
1164
1239
  projectLoading = Boolean(persistence && persistence.isProjectLoading?.());
1165
1240
  const unsubscribeProject = persistence && persistence.subscribeProject?.(projectChanged);
@@ -1208,6 +1283,7 @@ export function mountSpriteTabs(root, content, options) {
1208
1283
  window.removeEventListener('pagehide', flushLayout);
1209
1284
  if (unsubscribeDocuments)
1210
1285
  unsubscribeDocuments();
1286
+ unsubscribeFixedProjectTab?.();
1211
1287
  if (unsubscribeProject)
1212
1288
  unsubscribeProject();
1213
1289
  if (unsubscribeDrawer)
@@ -1228,6 +1304,7 @@ export function mountSpriteTabs(root, content, options) {
1228
1304
  if (overlay)
1229
1305
  overlay.dispose();
1230
1306
  drop.dispose();
1307
+ dragFixedTab.dispose();
1231
1308
  if (layout)
1232
1309
  layout.dispose();
1233
1310
  for (const view of views.values())
@@ -1404,7 +1481,7 @@ function SpriteTabs(props) {
1404
1481
  props.openCodeSearchResult?.(view.targetId, result.id);
1405
1482
  else if (section === 'variables') {
1406
1483
  const field = assetPreviewSlots.find(slot => slot.id === view.id)?.element;
1407
- [...(field?.querySelectorAll('input[data-variable-id]') ?? [])]
1484
+ [...(field?.querySelectorAll('[data-variable-id]') ?? [])]
1408
1485
  .find(input => input.dataset.variableId === result.id)?.focus();
1409
1486
  }
1410
1487
  else if (section === 'messages') {
@@ -1428,22 +1505,27 @@ function SpriteTabs(props) {
1428
1505
  workspace?.refreshSurfaces();
1429
1506
  return result;
1430
1507
  })
1431
- }) : kind === 'variables' ? React.createElement(SpriteAssetPane, {
1432
- kind, locale: props.locale, editable, variables: props.getVariables?.(targetId) ?? [],
1433
- properties: props.getProperties?.(targetId),
1434
- targetId,
1435
- onWriteProperties(id, patch) {
1436
- props.writeProperties?.(id, patch);
1437
- workspace?.refreshSurfaces();
1438
- },
1439
- onWrite(variableId, value) {
1440
- props.writeVariable?.(targetId, variableId, value);
1441
- workspace?.refreshSurfaces();
1442
- },
1443
- onEdit: props.editVariable && (edit => props.editVariable(targetId, edit))
1444
- }) : props.getAssetPreview && React.createElement(AssetPreview, {
1445
- locale: props.locale, kind, selected, renderLayout, scrollTop, data: props.getAssetPreview(targetId, kind)
1446
- }), element, id)));
1508
+ }) : kind === 'variables' ? renderVariablePane(id, targetId, editable) :
1509
+ props.getAssetPreview && React.createElement(AssetPreview, {
1510
+ locale: props.locale, kind, selected, renderLayout, scrollTop, data: props.getAssetPreview(targetId, kind)
1511
+ }), element, id)));
1512
+ function renderVariablePane(id, targetId, editable) {
1513
+ const pane = React.createElement(SpriteAssetPane, {
1514
+ kind: 'variables', locale: props.locale, editable, variables: props.getVariables?.(targetId) ?? [],
1515
+ properties: props.getProperties?.(targetId),
1516
+ targetId,
1517
+ onWriteProperties(id, patch) {
1518
+ props.writeProperties?.(id, patch);
1519
+ workspace?.refreshSurfaces();
1520
+ },
1521
+ onWrite(variableId, value) {
1522
+ props.writeVariable?.(targetId, variableId, value);
1523
+ workspace?.refreshSurfaces();
1524
+ },
1525
+ onEdit: props.editVariable && (edit => props.editVariable(targetId, edit))
1526
+ });
1527
+ return props.wrapVariablePane?.(id, targetId, editable, pane) ?? pane;
1528
+ }
1447
1529
  }
1448
1530
  export function useSpriteTabs({ available, enabled, locale, ...props }) {
1449
1531
  const controller = React.useRef(null);
@@ -1,11 +1,20 @@
1
- import type { DrawerViews } from './drawer-views.ts';
1
+ import type { DrawerView, DrawerViews } from './drawer-views.ts';
2
2
  import type { StageDrawerLayout } from './workspace-layout.ts';
3
3
  export type { DrawerMenu, DrawerMenuRenderProps, DrawerRenderProps, DrawerView, DrawerViewId, DrawerViews, HostDrawerViewId } from './drawer-views.ts';
4
- export declare function createStandardLayout(React: any, { styles, targetStyles, context, LayoutMenu }: {
4
+ type DrawerPanel = (props: {
5
+ id: DrawerView['id'];
6
+ title: string;
7
+ locale: string;
8
+ dockRequest: number;
9
+ renderHeading(undock: import('react').ReactNode): import('react').ReactNode;
10
+ renderContent(detached: boolean): import('react').ReactNode;
11
+ }) => import('react').ReactNode;
12
+ export declare function createStandardLayout(React: any, { styles, targetStyles, context, LayoutMenu, DrawerPanel }: {
5
13
  styles: any;
6
14
  targetStyles: any;
7
15
  context: any;
8
16
  LayoutMenu: any;
17
+ DrawerPanel?: DrawerPanel;
9
18
  }): {
10
19
  StandardLayout: ({ enabled, splitter, windowLayout, stageActionEnabled, stageDrawer, onPaletteModeChange, windowTools, Container, render, drawerViews, stageDrawerLayout, updateStageDrawer, ...props }: {
11
20
  [x: string]: any;
@@ -1,6 +1,6 @@
1
1
  import { createLayout, createSplitter, splitAxis } from "./index.js";
2
2
  import { createTargetList } from "./targets.js";
3
- import { availableDrawerViews, createDrawerViewBar, drawerPinIcon, hasDrawerBar, readDrawerView, writeDrawerView } from "./drawer-views.js";
3
+ import { availableDrawerViews, createDrawerViewBar, drawerLabel, drawerPinIcon, hasDrawerBar, readDrawerView, writeDrawerView } from "./drawer-views.js";
4
4
  import { attachStageDrawerDrag } from "./stage-drawer-drag.js";
5
5
  const isJapanese = locale => /^ja(?:-|$)/i.test(locale);
6
6
  const singleColumnTargetWidth = 108;
@@ -8,7 +8,7 @@ const singleColumnTargetWidth = 108;
8
8
  const drawerViewWidth = 300;
9
9
  const minimumDrawerViewWidth = 160;
10
10
  const minimumStandardEditor = 380;
11
- export function createStandardLayout(React, { styles, targetStyles, context, LayoutMenu }) {
11
+ export function createStandardLayout(React, { styles, targetStyles, context, LayoutMenu, DrawerPanel = undefined }) {
12
12
  const { createElement: element, useContext, useLayoutEffect, useRef, useState } = React;
13
13
  const SplitLayout = createLayout(React);
14
14
  const Splitter = createSplitter(React);
@@ -31,12 +31,17 @@ export function createStandardLayout(React, { styles, targetStyles, context, Lay
31
31
  const hostDrawerViews = availableDrawerViews(drawerViews);
32
32
  // A view saved earlier comes back once the host supplies it again.
33
33
  const drawerView = hostDrawerViews.some(view => view.id === preferredDrawerView) ? preferredDrawerView : 'sprites';
34
- const selectDrawerView = view => {
34
+ const selectDrawerView = React.useCallback(view => {
35
35
  setPreferredDrawerView(view);
36
36
  writeDrawerView(props.storage, props.storageKey, view);
37
- };
37
+ }, [props.storage, props.storageKey]);
38
38
  const body = useRef(null);
39
39
  const plusLayout = enabled && !props.fullscreen;
40
+ const reportDrawerSelection = drawerViews?.onSelectionChange;
41
+ useLayoutEffect(() => {
42
+ reportDrawerSelection?.(plusLayout ? drawerView : 'sprites');
43
+ return () => reportDrawerSelection?.('sprites');
44
+ }, [reportDrawerSelection, plusLayout, drawerView]);
40
45
  const stageHidden = plusLayout && !showStage;
41
46
  const stageDrawerPinned = updateStageDrawer ? stageDrawerLayout?.pinned !== false : localStageDrawerPinned;
42
47
  const setStageDrawerPinned = (pinned) => {
@@ -385,12 +390,23 @@ export function createStandardLayout(React, { styles, targetStyles, context, Lay
385
390
  function TargetLayout({ compact, render }) {
386
391
  const { plusLayout, targetsPinned, locale, drawerViews, drawerView = 'sprites', selectDrawerView } = useContext(context);
387
392
  const tools = useState(null);
393
+ const focusDrawer = useRef(null);
394
+ const [reveal, setReveal] = useState(null);
395
+ useLayoutEffect(() => {
396
+ if (!plusLayout)
397
+ return;
398
+ return drawerViews?.registerReveal?.(id => {
399
+ selectDrawerView(id);
400
+ setReveal(previous => ({ id, request: (previous?.request ?? 0) + 1 }));
401
+ focusDrawer.current?.();
402
+ });
403
+ }, [plusLayout, drawerViews, selectDrawerView]);
388
404
  const panel = render(plusLayout || compact);
389
405
  if (!plusLayout)
390
406
  return panel;
391
407
  const content = element(targetTools.Provider, { value: tools }, panel);
392
408
  const drawer = children => element(EdgeDrawer, {
393
- edge: 'left', pinned: targetsPinned,
409
+ edge: 'left', pinned: targetsPinned, focusPanelRef: focusDrawer,
394
410
  label: isJapanese(locale) ? 'スプライト一覧を展開' : 'Reveal sprite list'
395
411
  }, children);
396
412
  // Without host views the drawer keeps the sprite list as its only, unwrapped content.
@@ -400,10 +416,9 @@ export function createStandardLayout(React, { styles, targetStyles, context, Lay
400
416
  const active = views.find(view => view.id === drawerView);
401
417
  return drawer(element(React.Fragment, null, element(DrawerViewBar, { locale, views, agents: drawerViews.agents, selected: active ? active.id : 'sprites',
402
418
  onSelect: selectDrawerView }),
403
- // Pinning belongs to the drawer, so every view keeps the pin button the sprite list shows.
404
- active && element('div', { className: styles.drawerViewTools }, active.tools?.({ locale }), element(DrawerPinButton, { label: isJapanese(locale) ? 'このパネルを固定表示' : 'Pin this panel' })),
405
419
  // The GUI's target pane stays mounted, so its file inputs and library keep working while hidden.
406
- element('div', { className: styles.drawerSprites, hidden: Boolean(active) }, content), active && element('div', { className: styles.drawerViewContent, 'data-drawer-content': active.id }, active.render({ locale }))));
420
+ element('div', { className: styles.drawerSprites, hidden: Boolean(active) }, content), views.map(view => element(HostDrawerView, { key: view.id, view, locale, active: view === active,
421
+ dockRequest: reveal?.id === view.id ? reveal.request : 0 }))));
407
422
  }
408
423
  function SpriteGrid(props) {
409
424
  const { plusLayout } = useContext(context);
@@ -443,16 +458,11 @@ export function createStandardLayout(React, { styles, targetStyles, context, Lay
443
458
  return element('button', { type: 'button', className: styles.drawerPin, 'aria-label': label, 'aria-pressed': targetsPinned,
444
459
  title: label, onClick: () => setTargetsPinned(value => !value) }, drawerPinIcon(element, targetsPinned));
445
460
  }
446
- function useSpriteListTools() {
447
- const { locale } = useContext(context);
448
- const [mount] = useContext(targetTools) ?? [];
461
+ function useDrawerTools(searchLabel) {
449
462
  const [searching, setSearching] = useState(false);
450
463
  const [query, setQuery] = useState('');
451
464
  const searchButton = useRef(null);
452
465
  const searchInput = useRef(null);
453
- const japanese = isJapanese(locale);
454
- const pinLabel = japanese ? 'スプライト一覧を固定表示' : 'Pin sprite list';
455
- const searchLabel = japanese ? 'スプライトを検索' : 'Search sprites';
456
466
  useLayoutEffect(() => {
457
467
  if (searching)
458
468
  searchInput.current?.focus({ preventScroll: true });
@@ -462,11 +472,10 @@ export function createStandardLayout(React, { styles, targetStyles, context, Lay
462
472
  setQuery('');
463
473
  searchButton.current?.focus();
464
474
  };
465
- const renderTools = openAction => element(React.Fragment, null, element('div', { className: styles.targetListTools, role: 'group',
466
- 'aria-label': japanese ? 'スプライト一覧の操作' : 'Sprite list tools' }, element('button', { type: 'button', ref: searchButton, 'aria-label': searchLabel, 'aria-expanded': searching,
467
- title: searchLabel, onClick: () => searching ? closeSearch() : setSearching(true) }, element('svg', { 'aria-hidden': true, width: 14, height: 14, viewBox: '0 0 16 16',
468
- fill: 'none', stroke: 'currentColor', strokeWidth: 1.4, strokeLinecap: 'round' }, element('circle', { cx: 6.5, cy: 6.5, r: 4 }), element('path', { d: 'm9.5 9.5 4 4' }))), element(DrawerPinButton, { label: pinLabel }), openAction), searching && element('input', { type: 'search', className: styles.targetListSearch, 'aria-label': searchLabel,
469
- ref: searchInput, placeholder: japanese ? '名前' : 'Name', value: query,
475
+ const render = ({ label, pinLabel, openAction, tools }) => element(React.Fragment, null, element('div', { className: styles.targetListTools, role: 'group', 'aria-label': label }, tools, searchLabel && element('button', { type: 'button', ref: searchButton, 'aria-label': searchLabel,
476
+ 'aria-expanded': searching, title: searchLabel, onClick: () => searching ? closeSearch() : setSearching(true) }, element('svg', { 'aria-hidden': true, width: 14, height: 14, viewBox: '0 0 16 16',
477
+ fill: 'none', stroke: 'currentColor', strokeWidth: 1.4, strokeLinecap: 'round' }, element('circle', { cx: 6.5, cy: 6.5, r: 4 }), element('path', { d: 'm9.5 9.5 4 4' }))), pinLabel && element(DrawerPinButton, { label: pinLabel }), openAction), searching && element('input', { type: 'search', className: styles.targetListSearch,
478
+ 'aria-label': searchLabel, ref: searchInput, placeholder: searchLabel, value: query,
470
479
  onChange: event => setQuery(event.currentTarget.value),
471
480
  onKeyDown: event => {
472
481
  if (event.key === 'Escape') {
@@ -474,8 +483,40 @@ export function createStandardLayout(React, { styles, targetStyles, context, Lay
474
483
  closeSearch();
475
484
  }
476
485
  } }));
486
+ return { query, render };
487
+ }
488
+ function HostDrawerView({ view, locale, active, dockRequest }) {
489
+ const title = view.label ?? drawerLabel(view.id, locale);
490
+ const japanese = isJapanese(locale);
491
+ const label = japanese ? `${title}の操作` : `${title} tools`;
492
+ const { query, render } = useDrawerTools(view.searchLabel?.(locale));
493
+ const renderHeading = openAction => render({
494
+ label,
495
+ pinLabel: japanese ? 'このパネルを固定表示' : 'Pin this panel',
496
+ openAction,
497
+ tools: view.tools?.({ locale, query })
498
+ });
499
+ const renderContent = detached => (active || detached) && element('div', {
500
+ className: styles.drawerViewContent, 'data-drawer-content': view.id
501
+ }, detached && view.searchLabel && render({ label }), view.render({ locale, query }));
502
+ if (!DrawerPanel && !active)
503
+ return null;
504
+ return element('div', { className: styles.drawerHostView, hidden: !active }, DrawerPanel ?
505
+ element(DrawerPanel, { id: view.id, title, locale, dockRequest, renderHeading, renderContent }) :
506
+ element(React.Fragment, null, renderHeading(null), renderContent(false)));
507
+ }
508
+ function useSpriteListTools() {
509
+ const { locale } = useContext(context);
510
+ const [mount] = useContext(targetTools) ?? [];
511
+ const japanese = isJapanese(locale);
512
+ const { query, render } = useDrawerTools(japanese ? 'スプライトを検索' : 'Search sprites');
477
513
  return {
478
- mount, query, renderTools,
514
+ mount, query,
515
+ renderTools: openAction => render({
516
+ label: japanese ? 'スプライト一覧の操作' : 'Sprite list tools',
517
+ pinLabel: japanese ? 'スプライト一覧を固定表示' : 'Pin sprite list',
518
+ openAction
519
+ }),
479
520
  title: japanese ? 'スプライト一覧' : 'Sprite list',
480
521
  openLabel: japanese ? 'アンドック' : 'Undock sprite list'
481
522
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubohiroya/turbowarp-plus-editor-workbench",
3
- "version": "0.10.0",
3
+ "version": "0.11.1",
4
4
  "description": "The TurboWarp Plus Editor workbench: layout, dockable sprite tabs, stage, debugger tab and file menu",
5
5
  "type": "module",
6
6
  "license": "MPL-2.0",
@@ -176,6 +176,7 @@ export interface AgentSettingsDialogOptions {
176
176
  returnFocus?: HTMLElement | null;
177
177
  onSave?(settings: AgentSettings): void;
178
178
  desktop?: DesktopAiAgentsPort | null;
179
+ onDesktopSave?(): void;
179
180
  }
180
181
 
181
182
  export interface AgentSettingsDialog {
@@ -201,7 +202,7 @@ const urlProblems = {empty: 'urlEmpty', invalid: 'urlInvalid', 'not-https': 'url
201
202
  * user's own services. It is plain DOM so that any part of the Editor can open it, with or without React.
202
203
  */
203
204
  export function openAgentSettingsDialog({document: doc = globalThis.document, locale, styles = {}, storage = browserStorage(),
204
- storageKey = agentSettingsKey, returnFocus, onSave, desktop}: AgentSettingsDialogOptions): AgentSettingsDialog {
205
+ storageKey = agentSettingsKey, returnFocus, onSave, desktop, onDesktopSave}: AgentSettingsDialogOptions): AgentSettingsDialog {
205
206
  if (openDialog?.element.isConnected) {
206
207
  (openDialog.element.querySelector(focusable) as HTMLElement)?.focus();
207
208
  return openDialog;
@@ -306,7 +307,7 @@ export function openAgentSettingsDialog({document: doc = globalThis.document, lo
306
307
  const save = make('button', {type: 'submit', class: `${styles.aiAgentDialogButton ?? ''} ${styles.aiAgentDialogPrimary ?? ''}`.trim()},
307
308
  text('save'));
308
309
  const form = make('form', {novalidate: '', class: styles.aiAgentDialogForm}, presetGroup, customGroup,
309
- desktop && desktopAgentSettings(doc, desktop, locale, styles), status,
310
+ desktop && desktopAgentSettings(doc, desktop, locale, styles, onDesktopSave), status,
310
311
  make('div', {class: styles.aiAgentDialogActions}, cancel, save));
311
312
  const element = make('div', {
312
313
  role: 'dialog', 'aria-modal': 'true', 'aria-labelledby': `${prefix}-title`,
package/src/ai-agents.ts CHANGED
@@ -48,21 +48,28 @@ export function createAiAgents(React, {styles = {}, storage = browserStorage(),
48
48
  };
49
49
  const settingsIcon = () => svg(element('path', {d: agentsIconPath}));
50
50
 
51
- const openSettings = ({locale, returnFocus}: {locale: string; returnFocus?: HTMLElement | null}) =>
52
- openAgentSettingsDialog({document, locale, styles, storage, storageKey, returnFocus, desktop});
51
+ const openSettings = ({locale, returnFocus, onSave, onDesktopSave}: {
52
+ locale: string; returnFocus?: HTMLElement | null; onSave?: () => void; onDesktopSave?: () => void;
53
+ }) => openAgentSettingsDialog({document: returnFocus?.ownerDocument ?? document, locale, styles, storage,
54
+ storageKey, returnFocus, onSave, desktop, onDesktopSave});
53
55
 
54
- function AgentMenu({locale, close}: DrawerMenuRenderProps) {
55
- const [services] = useState(() => enabledAgentServices(readAgentSettings(storage, storageKey)));
56
+ function AgentList({locale, close}: Omit<DrawerMenuRenderProps, 'close'> & {close?: () => void}) {
57
+ const [services, setServices] = useState(() => enabledAgentServices(readAgentSettings(storage, storageKey)));
56
58
  const [applications, setApplications] = useState([] as DesktopAgent[]);
57
59
  const [error, setError] = useState(null as {code: string; url?: string} | null);
58
60
  const active = useRef(true);
61
+ const refreshApplications = async () => {
62
+ if (!desktop) return;
63
+ const result = await agentRequest(() => desktop.list());
64
+ if (!active.current) return;
65
+ if ('value' in result) {
66
+ setApplications(result.value.entries);
67
+ setError(null);
68
+ } else setError({code: result.code});
69
+ };
59
70
  useEffect(() => {
60
71
  active.current = true;
61
- if (desktop) void agentRequest(() => desktop.list()).then(result => {
62
- if (!active.current) return;
63
- if ('value' in result) setApplications(result.value.entries);
64
- else setError({code: result.code});
65
- });
72
+ void refreshApplications();
66
73
  return () => { active.current = false; };
67
74
  }, []);
68
75
  const list = useRef(null);
@@ -83,14 +90,14 @@ export function createAiAgents(React, {styles = {}, storage = browserStorage(),
83
90
  items[next]?.focus();
84
91
  };
85
92
  const item = (key: string, icon, text: string, onClick: () => void, title?: string) => element('button', {
86
- key, type: 'button', role: 'menuitem', tabIndex: -1, className: styles.aiAgentMenuItem, title, onClick
93
+ key, type: 'button', role: close ? 'menuitem' : undefined, tabIndex: close ? -1 : undefined, className: styles.aiAgentMenuItem, title, onClick
87
94
  }, icon, element('span', null, text));
88
95
  const hasEntries = services.length + applications.length > 0;
89
96
  const launch = async (application: DesktopAgent) => {
90
97
  setError(null);
91
98
  const result = await agentRequest(() => desktop.launch(application.id));
92
99
  if (!active.current) return;
93
- if ('value' in result) close();
100
+ if ('value' in result) close?.();
94
101
  else {
95
102
  const checked = checkAgentUrl(application.url);
96
103
  setError({code: result.code, ...('url' in checked ? checked : {})});
@@ -100,30 +107,35 @@ export function createAiAgents(React, {styles = {}, storage = browserStorage(),
100
107
  error && element('p', {role: 'alert', className: styles.aiAgentMenuHint}, desktopAgentError(error.code, locale)),
101
108
  !hasEntries && element('p', {id: hintId.current, className: styles.aiAgentMenuHint}, agentText('empty', locale)),
102
109
  element('div', {
103
- role: 'menu', 'aria-label': label, ref: list, className: styles.aiAgentMenu, onKeyDown: move,
110
+ role: close ? 'menu' : 'group', 'aria-label': label, ref: list, className: styles.aiAgentMenu,
111
+ onKeyDown: close ? move : undefined,
104
112
  'aria-describedby': hasEntries ? undefined : hintId.current
105
113
  },
106
114
  services.map(service => item(service.id, serviceIcon(service), service.name, () => {
107
115
  openAgentService(service, open);
108
- close();
116
+ close?.();
109
117
  }, newTab)),
110
118
  applications.map(application => item(`desktop-${application.id}`, settingsIcon(), application.name,
111
119
  () => void launch(application), desktopAgentText('opensApp', locale))),
112
120
  error?.url && item('fallback', serviceIcon(), desktopAgentText('openFallback', locale), () => {
113
121
  open(error.url, '_blank', 'noopener,noreferrer');
114
- close();
122
+ close?.();
115
123
  }, newTab),
116
124
  hasEntries && element('div', {role: 'separator', className: styles.aiAgentMenuSeparator}),
117
125
  item('settings', settingsIcon(), agentText('settings', locale), () => {
118
- close();
119
- openSettings({locale, returnFocus: document.activeElement as HTMLElement});
126
+ const doc = list.current.ownerDocument;
127
+ close?.();
128
+ openSettings({locale, returnFocus: doc.activeElement as HTMLElement,
129
+ onSave: close ? undefined : () => setServices(enabledAgentServices(readAgentSettings(storage, storageKey))),
130
+ onDesktopSave: close ? undefined : () => { void refreshApplications(); }});
120
131
  })));
121
132
  }
122
133
 
123
134
  const drawerMenu: DrawerMenu = {
124
- renderMenu: props => element(AgentMenu, props)
135
+ renderMenu: props => element(AgentList, props)
125
136
  };
126
- return {drawerMenu, openSettings, settingsIcon, serviceIcon};
137
+ return {drawerMenu, renderPanel: ({locale}: {locale: string}) => element(AgentList, {locale}),
138
+ openSettings, settingsIcon, serviceIcon};
127
139
  }
128
140
 
129
141
  let nextId = 0;
@@ -83,7 +83,8 @@ export async function agentRequest<T>(request: () => Promise<Result<T>>): Promis
83
83
  }
84
84
 
85
85
  /** An optional section of the existing settings dialog. Its changes are saved by the Desktop host. */
86
- export function desktopAgentSettings(doc: Document, port: DesktopAiAgentsPort, locale: string, styles: Record<string, string>) {
86
+ export function desktopAgentSettings(doc: Document, port: DesktopAiAgentsPort, locale: string,
87
+ styles: Record<string, string>, onSave?: () => void) {
87
88
  const text = (key: keyof typeof strings) => desktopAgentText(key, locale);
88
89
  const make = <K extends keyof HTMLElementTagNameMap>(tag: K, className?: string, content?: string) => {
89
90
  const node = doc.createElement(tag);
@@ -153,6 +154,7 @@ export function desktopAgentSettings(doc: Document, port: DesktopAiAgentsPort, l
153
154
  entries = value.entries.map(entry => ({...entry}));
154
155
  render();
155
156
  status.textContent = text('saved');
157
+ onSave?.();
156
158
  });
157
159
  });
158
160