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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,263 @@
1
+ import {isJapanese} from './drawer-views.ts';
2
+
3
+ export interface DesktopAgentDraft {
4
+ id: string;
5
+ name: string;
6
+ args: string[];
7
+ cwd: string;
8
+ selection?: string;
9
+ url?: string;
10
+ }
11
+
12
+ export interface DesktopAgent extends DesktopAgentDraft {
13
+ application: string;
14
+ }
15
+
16
+ type AgentContext = Record<'projectFolder' | 'repository' | 'branch', string | null>;
17
+ type AgentList = {revision: string | null; entries: DesktopAgent[]};
18
+ type Result<T> = {ok: true; value: T} | {ok: false; code: string};
19
+
20
+ /** The Desktop host owns the executable paths, confirmations and launch settings. */
21
+ export interface DesktopAiAgentsPort {
22
+ list(): Promise<Result<AgentList>>;
23
+ context(): Promise<Result<AgentContext>>;
24
+ chooseContext(kind: 'project' | 'repository'): Promise<Result<AgentContext | null>>;
25
+ chooseApp(): Promise<Result<{selection: string; application: string} | null>>;
26
+ save(revision: string | null, entries: DesktopAgentDraft[]): Promise<Result<AgentList>>;
27
+ launch(id: string): Promise<Result<null>>;
28
+ }
29
+
30
+ const defaultDirectory = '{projectFolder}';
31
+ const variables = /\{(projectFolder|repository|branch)\}/gu;
32
+ const strings = {
33
+ section: ['Desktop applications', 'デスクトップアプリ'],
34
+ opensApp: ['Launches a desktop application', 'デスクトップアプリを起動します'],
35
+ add: ['Add an application', 'アプリを追加'],
36
+ name: ['Name', '名前'],
37
+ application: ['Application', 'アプリ'],
38
+ choose: ['Choose…', '選択…'],
39
+ unselected: ['No application selected', 'アプリが選択されていません'],
40
+ args: ['Arguments (one per line)', '引数(1 行に 1 つ)'],
41
+ cwd: ['Working directory', '作業ディレクトリ'],
42
+ url: ['Fallback website (optional)', '代わりに開く Web サイト(任意)'],
43
+ openFallback: ['Open the website', 'Web サイトを開く'],
44
+ 'invalid-url': ['Enter an HTTPS address for the fallback website.', '代わりに開く Web サイトには HTTPS の URL を入力してください。'],
45
+ variables: ['Available placeholders: {projectFolder}, {repository}, {branch}.', '使える置き換えは {projectFolder}・{repository}・{branch} です。'],
46
+ chooseProject: ['Choose project folder…', 'プロジェクトフォルダを選択…'],
47
+ chooseRepository: ['Choose Git repository…', 'Git リポジトリを選択…'],
48
+ projectFolder: ['Project folder', 'プロジェクトフォルダ'],
49
+ repository: ['Git repository', 'Git リポジトリ'],
50
+ branch: ['Branch', 'ブランチ'],
51
+ preview: ['Expanded arguments', '置き換え後の引数'],
52
+ up: ['Move up', '上へ移動'],
53
+ down: ['Move down', '下へ移動'],
54
+ remove: ['Remove application', 'アプリを削除'],
55
+ save: ['Save applications', 'アプリの設定を保存'],
56
+ saved: ['Application settings saved.', 'アプリの設定を保存しました。'],
57
+ test: ['Try launching', '試しに起動'],
58
+ saveFirst: ['Save the application before trying it.', '試しに起動するには、先にアプリの設定を保存してください。'],
59
+ launched: ['Launch requested.', 'アプリを起動しました。'],
60
+ invalid: ['Enter a name and choose an application for each entry.', '各項目の名前を入力し、アプリを選択してください。'],
61
+ conflict: ['The application settings changed. Reopen the settings and try again.', 'アプリの設定が変更されました。設定を開き直してからやり直してください。'],
62
+ busy: ['Another application operation is in progress.', '別のアプリ操作を実行中です。'],
63
+ cancelled: ['The operation was cancelled.', '操作をキャンセルしました。'],
64
+ unknown: ['This application is no longer registered.', 'このアプリは登録されていません。'],
65
+ 'missing-context': ['Choose the folder or repository used by the launch arguments. A branch is required for {branch}.',
66
+ '引数で使うフォルダまたはリポジトリを選択してください。{branch} にはブランチが必要です。'],
67
+ 'invalid-directory': ['The working directory is unavailable.', '作業ディレクトリを利用できません。'],
68
+ 'app-missing': ['The selected application is missing or cannot run.', '選択したアプリが見つからないか、起動できません。'],
69
+ 'launch-failed': ['The application could not start.', 'アプリを起動できませんでした。'],
70
+ unavailable: ['Desktop application settings are unavailable.', 'デスクトップアプリの設定を利用できません。']
71
+ } as const;
72
+
73
+ export const desktopAgentText = (key: keyof typeof strings, locale: string) => strings[key][isJapanese(locale) ? 1 : 0];
74
+ export const desktopAgentError = (code: string, locale: string) =>
75
+ desktopAgentText(Object.hasOwn(strings, code) ? code as keyof typeof strings : 'unavailable', locale);
76
+
77
+ export async function agentRequest<T>(request: () => Promise<Result<T>>): Promise<Result<T>> {
78
+ try {
79
+ return await request();
80
+ } catch {
81
+ return {ok: false, code: 'unavailable'};
82
+ }
83
+ }
84
+
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>) {
87
+ const text = (key: keyof typeof strings) => desktopAgentText(key, locale);
88
+ const make = <K extends keyof HTMLElementTagNameMap>(tag: K, className?: string, content?: string) => {
89
+ const node = doc.createElement(tag);
90
+ if (className) node.className = className;
91
+ if (content) node.textContent = content;
92
+ return node;
93
+ };
94
+ const button = (key: keyof typeof strings, action: () => void) => {
95
+ const node = make('button', styles.aiAgentDialogButton, text(key));
96
+ node.type = 'button';
97
+ node.addEventListener('click', action);
98
+ return node;
99
+ };
100
+ const field = (key: keyof typeof strings, input: HTMLElement) => {
101
+ const label = make('label', styles.aiAgentDialogField, text(key));
102
+ label.append(input);
103
+ return label;
104
+ };
105
+ const list = make('div', styles.aiAgentDialogList);
106
+ const status = make('p', styles.aiAgentDialogNote);
107
+ status.setAttribute('role', 'status');
108
+ const section = make('fieldset', styles.aiAgentDialogSection);
109
+ let entries: DesktopAgent[] = [];
110
+ let saved: AgentList = {revision: null, entries: []};
111
+ let context: AgentContext | null = null;
112
+ const previews = new Map<string, () => void>();
113
+
114
+ const run = async <T,>(request: () => Promise<Result<T>>, done: (value: T) => void) => {
115
+ const focused = doc.activeElement as HTMLElement | null;
116
+ section.disabled = true;
117
+ status.textContent = '';
118
+ const result = await agentRequest(request);
119
+ if (!section.isConnected) return;
120
+ section.disabled = false;
121
+ if ('code' in result) status.textContent = desktopAgentError(result.code, locale);
122
+ else done(result.value);
123
+ if (doc.activeElement === doc.body && focused?.isConnected && section.contains(focused)) focused.focus();
124
+ };
125
+ const contextSummary = make('p', styles.aiAgentDialogNote);
126
+ contextSummary.style.overflowWrap = 'anywhere';
127
+ const refreshPreviews = () => {
128
+ contextSummary.textContent = (['projectFolder', 'repository', 'branch'] as const)
129
+ .map(key => `${text(key)} ${context?.[key] ?? '—'}`).join(' · ');
130
+ previews.forEach(render => render());
131
+ };
132
+ const chooseContext = (kind: 'project' | 'repository') => {
133
+ void run(() => port.chooseContext(kind), value => {
134
+ if (value) context = value;
135
+ refreshPreviews();
136
+ });
137
+ };
138
+ const add = button('add', () => {
139
+ const entry = {id: globalThis.crypto.randomUUID(), name: '', application: '', args: [], cwd: defaultDirectory};
140
+ entries.push(entry);
141
+ render();
142
+ list.lastElementChild?.querySelector('input')?.focus();
143
+ });
144
+ const toDraft = ({id, name, args, cwd, selection, url}: DesktopAgent): DesktopAgentDraft =>
145
+ ({id, name, args, cwd, ...(selection ? {selection} : {}), ...(url?.trim() ? {url: url.trim()} : {})});
146
+ const save = button('save', () => {
147
+ if (entries.some(entry => !entry.name.trim() || !entry.application)) {
148
+ status.textContent = text('invalid');
149
+ return;
150
+ }
151
+ void run(() => port.save(saved.revision, entries.map(toDraft)), value => {
152
+ saved = value;
153
+ entries = value.entries.map(entry => ({...entry}));
154
+ render();
155
+ status.textContent = text('saved');
156
+ });
157
+ });
158
+
159
+ function render() {
160
+ previews.clear();
161
+ list.replaceChildren();
162
+ for (const [index, entry] of entries.entries()) {
163
+ const row = make('div', styles.aiAgentDialogRow);
164
+ row.setAttribute('role', 'group');
165
+ row.setAttribute('aria-label', entry.name || text('application'));
166
+ const name = make('input');
167
+ name.maxLength = 120;
168
+ name.value = entry.name;
169
+ name.oninput = () => {
170
+ entry.name = name.value;
171
+ row.setAttribute('aria-label', entry.name || text('application'));
172
+ };
173
+ const application = make('p', styles.aiAgentDialogNote, entry.application || text('unselected'));
174
+ const choose = button('choose', () => {
175
+ void run(() => port.chooseApp(), value => {
176
+ if (value) Object.assign(entry, value);
177
+ application.textContent = entry.application || text('unselected');
178
+ });
179
+ });
180
+ choose.setAttribute('aria-label', `${text('application')} ${text('choose')}`);
181
+ const args = make('textarea');
182
+ args.rows = 3;
183
+ args.value = entry.args.join('\n');
184
+ const cwd = make('input');
185
+ cwd.placeholder = defaultDirectory;
186
+ cwd.maxLength = 1024;
187
+ cwd.value = entry.cwd;
188
+ const url = make('input');
189
+ url.type = 'url';
190
+ url.maxLength = 2048;
191
+ url.value = entry.url ?? '';
192
+ url.oninput = () => { entry.url = url.value; };
193
+ const preview = make('p', styles.aiAgentDialogNote);
194
+ const updatePreview = () => {
195
+ const expand = (value: string) => value.replace(variables, (match, key: keyof AgentContext) => context?.[key] ?? match);
196
+ const directory = (entry.cwd.trim() || defaultDirectory);
197
+ preview.textContent = `${text('preview')} ${JSON.stringify(entry.args.map(expand))}\n${text('cwd')} ${
198
+ directory === defaultDirectory && !context?.projectFolder ? '—' : expand(directory)}`;
199
+ };
200
+ preview.style.whiteSpace = 'pre-wrap';
201
+ preview.style.overflowWrap = 'anywhere';
202
+ previews.set(entry.id, updatePreview);
203
+ updatePreview();
204
+ args.oninput = () => {
205
+ entry.args = args.value ? args.value.split('\n') : [];
206
+ updatePreview();
207
+ };
208
+ cwd.oninput = () => {
209
+ entry.cwd = cwd.value;
210
+ updatePreview();
211
+ };
212
+ const move = (offset: number) => {
213
+ entries.splice(index, 1);
214
+ entries.splice(index + offset, 0, entry);
215
+ render();
216
+ list.children[index + offset].querySelector('input')?.focus();
217
+ };
218
+ const up = button('up', () => move(-1));
219
+ const down = button('down', () => move(1));
220
+ up.disabled = index === 0;
221
+ down.disabled = index === entries.length - 1;
222
+ const remove = button('remove', () => {
223
+ entries.splice(index, 1);
224
+ render();
225
+ (list.children[Math.min(index, entries.length - 1)]?.querySelector('input') ?? add).focus();
226
+ });
227
+ const tryLaunch = button('test', () => {
228
+ const original = saved.entries.find(item => item.id === entry.id);
229
+ if (!original || JSON.stringify(toDraft(original)) !== JSON.stringify(toDraft(entry))) {
230
+ status.textContent = text('saveFirst');
231
+ return;
232
+ }
233
+ void run(() => port.launch(entry.id), () => { status.textContent = text('launched'); });
234
+ });
235
+ row.append(field('name', name), application, choose, field('args', args), field('cwd', cwd), preview, field('url', url),
236
+ up, down, remove, tryLaunch);
237
+ list.append(row);
238
+ }
239
+ }
240
+
241
+ section.addEventListener('keydown', event => {
242
+ if (event.key === 'Enter' && (event.target as HTMLElement).tagName === 'INPUT') event.preventDefault();
243
+ });
244
+ section.append(make('legend', undefined, text('section')), make('p', styles.aiAgentDialogNote, text('variables')),
245
+ button('chooseProject', () => chooseContext('project')), button('chooseRepository', () => chooseContext('repository')),
246
+ contextSummary, list, add, save, status);
247
+ section.disabled = true;
248
+ // The dialog attaches this section to the document before the requests resolve.
249
+ void Promise.all([agentRequest(() => port.list()), agentRequest(() => port.context())]).then(([settings, current]) => {
250
+ if (!section.isConnected) return;
251
+ if ('code' in settings) {
252
+ status.textContent = desktopAgentError(settings.code, locale);
253
+ return;
254
+ }
255
+ saved = settings.value;
256
+ entries = saved.entries.map(entry => ({...entry}));
257
+ if ('value' in current) context = current.value;
258
+ refreshPreviews();
259
+ section.disabled = false;
260
+ render();
261
+ });
262
+ return section;
263
+ }
@@ -37,8 +37,9 @@ export function useDockviewStage(enabled: boolean, locale: string) {
37
37
  const previous = savedDrawer.current;
38
38
  const next = {open: false, selected: false, ...previous, ...patch};
39
39
  if (next.open === Boolean(previous?.open) && next.selected === Boolean(previous?.selected) &&
40
- next.position === previous?.position && next.width === previous?.width) return;
41
- restoreDrawer(next.open || next.selected || next.position || next.width ? next : undefined);
40
+ next.pinned === previous?.pinned && next.position === previous?.position && next.width === previous?.width) return;
41
+ restoreDrawer(next.open || next.selected || next.pinned !== undefined || next.position || next.width ?
42
+ next : undefined);
42
43
  for (const listener of drawerListeners) listener();
43
44
  }, [drawerListeners, restoreDrawer]);
44
45
  const resetDrawerPresentation = React.useCallback(() => updateDrawer({open: false, selected: false}),
@@ -59,6 +59,13 @@ export const agentsIconPath = 'M8 1.5 9.4 6.6 14.5 8 9.4 9.4 8 14.5 6.6 9.4 1.5
59
59
  export const isJapanese =(locale: string) => /^ja(?:-|$)/i.test(locale ?? '');
60
60
  export const drawerLabel = (id: keyof typeof names, locale: string) => names[id][isJapanese(locale) ? 0 : 1];
61
61
 
62
+ export function drawerPinIcon(element: typeof import('react').createElement, pinned: boolean) {
63
+ return element('svg', {'aria-hidden': true, width: 14, height: 14, viewBox: '0 0 16 16',
64
+ fill: pinned ? 'currentColor' : 'none', stroke: 'currentColor', strokeWidth: 1.2, strokeLinejoin: 'round'},
65
+ element('path', {d: 'M9 2 14 7 12 8l-2 3-5-5 3-2 1-2Z'}), element('path', {d: 'm7.5 8.5-4 4'}),
66
+ !pinned && element('path', {d: 'M2 2l12 12', strokeLinecap: 'round'}));
67
+ }
68
+
62
69
  /** The supported host views in button order, without unknown or repeated ids. */
63
70
  export function availableDrawerViews(drawerViews: DrawerViews | undefined): DrawerView[] {
64
71
  const views = drawerViews?.views ?? [];
package/src/editor.css CHANGED
@@ -940,7 +940,8 @@ details.layout-menu button {
940
940
  gap: 0.125rem;
941
941
  }
942
942
 
943
- .ai-agent-dialog-field input {
943
+ .ai-agent-dialog-field input,
944
+ .ai-agent-dialog-field textarea {
944
945
  box-sizing: border-box;
945
946
  inline-size: 100%;
946
947
  padding: 0.375rem 0.5rem;
@@ -1,4 +1,5 @@
1
1
  import React, {createElement as element, type ComponentType} from 'react';
2
+ import {drawerPinIcon} from './drawer-views.ts';
2
3
 
3
4
  const labels = {
4
5
  ja: {
@@ -6,14 +7,18 @@ const labels = {
6
7
  menu: 'ステージの開き方',
7
8
  window: '別ウィンドウで表示',
8
9
  tab: 'タブで表示',
9
- drawer: '引出しで表示'
10
+ drawer: '引出しで表示',
11
+ pinDrawer: '引出しを常時表示する',
12
+ autoHideDrawer: '引出しを自動的に隠す'
10
13
  },
11
14
  en: {
12
15
  open: 'Open stage',
13
16
  menu: 'Stage opening options',
14
17
  window: 'Show in a separate window',
15
18
  tab: 'Show in a tab',
16
- drawer: 'Show in the drawer'
19
+ drawer: 'Show in the drawer',
20
+ pinDrawer: 'Keep the drawer open',
21
+ autoHideDrawer: 'Automatically hide the drawer'
17
22
  }
18
23
  };
19
24
 
@@ -36,6 +41,16 @@ export function stagePresentationItems(locale: string, current: StageMode | null
36
41
  }));
37
42
  }
38
43
 
44
+ export function stageDrawerPinItem(locale: string, pinned: boolean, setPinned: (pinned: boolean) => void) {
45
+ const text = textFor(locale);
46
+ return {
47
+ id: 'drawer-pin',
48
+ label: pinned ? text.autoHideDrawer : text.pinDrawer,
49
+ icon: drawerPinIcon(element, !pinned),
50
+ onSelect: () => setPinned(!pinned)
51
+ };
52
+ }
53
+
39
54
  export function useStageDocumentFullscreen(doc?: Document) {
40
55
  const [fullscreenDocument, setFullscreenDocument] = React.useState<Document>();
41
56
  React.useLayoutEffect(() => {
@@ -5,7 +5,7 @@ import {createDockview, themeLight} from 'dockview';
5
5
  import {StageLauncher, type StageDockAction, type StageLauncherOptions} from './stage-launcher.ts';
6
6
 
7
7
  export type {StageDockAction, StageLauncherOptions} from './stage-launcher.ts';
8
- export {stagePresentationItems, useStageDocumentFullscreen} from './stage-launcher.ts';
8
+ export {stageDrawerPinItem, stagePresentationItems, useStageDocumentFullscreen} from './stage-launcher.ts';
9
9
  export {StageResizeHandle} from './stage-resize-handle.ts';
10
10
 
11
11
  interface StageWindowConnection<Target> {
@@ -112,6 +112,7 @@ export function createStageSurface(React: typeof import('react'), {
112
112
  context: Context<{
113
113
  locale: string;
114
114
  stageDrawer?: boolean;
115
+ stageDrawerPinned?: boolean;
115
116
  stageHidden?: boolean;
116
117
  setStageDrawerOpen?(open: boolean): void;
117
118
  setStageVisible?(visible: boolean): void;
@@ -129,7 +130,8 @@ export function createStageSurface(React: typeof import('react'), {
129
130
  editorFullscreen?: boolean;
130
131
  [key: string]: any;
131
132
  }) {
132
- const {locale, stageDrawer, stageHidden, setStageDrawerOpen, setStageVisible} = React.useContext(context);
133
+ const {locale, stageDrawer, stageDrawerPinned = true, stageHidden, setStageDrawerOpen, setStageVisible} =
134
+ React.useContext(context);
133
135
  const [drawerOpen, setDrawerOpen] = React.useState(false);
134
136
  const localDrawerRef = React.useRef<() => void>(null);
135
137
  const focusDrawer = openDrawerRef ?? localDrawerRef;
@@ -163,6 +165,7 @@ export function createStageSurface(React: typeof import('react'), {
163
165
  const dock = stageDrawer ? React.createElement(EdgeDrawer, {
164
166
  edge: 'right',
165
167
  movableStage: true,
168
+ keepOpenOnBlur: stageDrawerPinned,
166
169
  available: !placement?.docked && (!dockAction || dockAction.kind === 'docked'),
167
170
  stageDrawerLayout: drawerLayout,
168
171
  updateStageDrawer: updateDrawer,
@@ -1,7 +1,7 @@
1
1
  import {createLayout, createSplitter, splitAxis} from './index.ts';
2
2
  import {createTargetList} from './targets.ts';
3
3
  import type {DrawerViews} from './drawer-views.ts';
4
- import {availableDrawerViews, createDrawerViewBar, hasDrawerBar, readDrawerView, writeDrawerView} from './drawer-views.ts';
4
+ import {availableDrawerViews, createDrawerViewBar, drawerPinIcon, hasDrawerBar, readDrawerView, writeDrawerView} from './drawer-views.ts';
5
5
  import {attachStageDrawerDrag} from './stage-drawer-drag.ts';
6
6
  import type {StageDrawerLayout, StageDrawerPosition} from './workspace-layout.ts';
7
7
 
@@ -34,6 +34,7 @@ export function createStandardLayout(React, {styles, targetStyles, context, Layo
34
34
  const [targetsPinned, setTargetsPinned] = useState(true);
35
35
  const [showStage, setShowStage] = useState(true);
36
36
  const [stageDrawerOpen, setStageDrawerOpen] = useState(false);
37
+ const [localStageDrawerPinned, setLocalStageDrawerPinned] = useState(true);
37
38
  const [size, setSize] = useState(null);
38
39
  const [targetRatio, setTargetRatio] = useState(null);
39
40
  const [viewRatio, setViewRatio] = useState(null);
@@ -50,6 +51,11 @@ export function createStandardLayout(React, {styles, targetStyles, context, Layo
50
51
  const body = useRef(null);
51
52
  const plusLayout = enabled && !props.fullscreen;
52
53
  const stageHidden = plusLayout && !showStage;
54
+ const stageDrawerPinned = updateStageDrawer ? stageDrawerLayout?.pinned !== false : localStageDrawerPinned;
55
+ const setStageDrawerPinned = (pinned: boolean) => {
56
+ if (updateStageDrawer) updateStageDrawer({pinned});
57
+ else setLocalStageDrawerPinned(pinned);
58
+ };
53
59
  const japanese = isJapanese(props.locale);
54
60
  const undockLabel = japanese ? 'アンドックボタンを表示' : 'Show undock buttons';
55
61
  const layoutMenuLabel = japanese ? '配置メニュー' : 'Layout options';
@@ -188,7 +194,8 @@ export function createStandardLayout(React, {styles, targetStyles, context, Layo
188
194
  });
189
195
  return element(context.Provider, {value: {
190
196
  showUndock, plusLayout, targetsPinned, setTargetsPinned, stageHidden, setStageVisible: setShowStage, stageResize, stageActionMount,
191
- stageDrawer: plusLayout && stageDrawer, setStageDrawerOpen, locale: props.locale,
197
+ stageDrawer: plusLayout && stageDrawer, stageDrawerPinned, setStageDrawerPinned, setStageDrawerOpen,
198
+ locale: props.locale,
192
199
  drawerViews, drawerView, selectDrawerView
193
200
  }},
194
201
  Container ? element(Container, {locale: props.locale}, layout) : layout);
@@ -196,7 +203,8 @@ export function createStandardLayout(React, {styles, targetStyles, context, Layo
196
203
 
197
204
  function EdgeDrawer({edge, label, pinned = false, onOpenChange, portalContent = false, holdOpenSelector = '',
198
205
  focusPanelRef = undefined, closePanelRef = undefined, focusBoundary = undefined, showTrigger = true,
199
- movableStage = false, available = true, stageDrawerLayout = undefined as StageDrawerLayout | undefined,
206
+ movableStage = false, available = true, keepOpenOnBlur = false,
207
+ stageDrawerLayout = undefined as StageDrawerLayout | undefined,
200
208
  updateStageDrawer = undefined as ((patch: Partial<StageDrawerLayout>) => void) | undefined, children}) {
201
209
  const [hovered, setHovered] = useState(false);
202
210
  const [localEngaged, setLocalEngaged] = useState(false);
@@ -272,6 +280,7 @@ export function createStandardLayout(React, {styles, targetStyles, context, Layo
272
280
  if (panel.current.contains(event.target as Node)) setEngaged(true);
273
281
  };
274
282
  const blur = (event: FocusEvent) => {
283
+ if (keepOpenOnBlur) return;
275
284
  const target = event.relatedTarget as Node;
276
285
  const source = event.target as HTMLButtonElement;
277
286
  // Opening the stage disables the launcher before focus moves into the drawer.
@@ -317,7 +326,7 @@ export function createStandardLayout(React, {styles, targetStyles, context, Layo
317
326
  if (!focusBoundary) return;
318
327
  focusBoundary.addEventListener('focusout', blur);
319
328
  return () => focusBoundary.removeEventListener('focusout', blur);
320
- }, [focusBoundary, setEngaged]);
329
+ }, [focusBoundary, keepOpenOnBlur, setEngaged]);
321
330
 
322
331
  useLayoutEffect(() => {
323
332
  if (!portalContent) return;
@@ -333,7 +342,21 @@ export function createStandardLayout(React, {styles, targetStyles, context, Layo
333
342
  node.removeEventListener('focusin', focus);
334
343
  node.removeEventListener('focusout', blur);
335
344
  };
336
- }, [portalContent, focusBoundary, open, showTrigger, movableStage, setEngaged]);
345
+ }, [portalContent, focusBoundary, open, showTrigger, movableStage, keepOpenOnBlur, setEngaged]);
346
+
347
+ useLayoutEffect(() => {
348
+ if (!movableStage || keepOpenOnBlur || !open) return;
349
+ const node = drawer.current as HTMLElement;
350
+ const dismiss = (event: PointerEvent) => {
351
+ const target = event.target as Node;
352
+ if (node.contains(target) || focusBoundary?.contains(target)) return;
353
+ setHovered(false);
354
+ setEngaged(false);
355
+ };
356
+ // The restored drawer may be open without having received focus.
357
+ node.ownerDocument.addEventListener('pointerdown', dismiss, true);
358
+ return () => node.ownerDocument.removeEventListener('pointerdown', dismiss, true);
359
+ }, [movableStage, keepOpenOnBlur, open, focusBoundary, setEngaged]);
337
360
 
338
361
  useLayoutEffect(() => {
339
362
  if (!portalContent || !movableStage || !open) return;
@@ -443,10 +466,7 @@ export function createStandardLayout(React, {styles, targetStyles, context, Layo
443
466
  const {targetsPinned, setTargetsPinned} = useContext(context);
444
467
  return element('button', {type: 'button', className: styles.drawerPin, 'aria-label': label, 'aria-pressed': targetsPinned,
445
468
  title: label, onClick: () => setTargetsPinned(value => !value)},
446
- element('svg', {'aria-hidden': true, width: 14, height: 14, viewBox: '0 0 16 16',
447
- fill: targetsPinned ? 'currentColor' : 'none', stroke: 'currentColor', strokeWidth: 1.2, strokeLinejoin: 'round'},
448
- element('path', {d: 'M9 2 14 7 12 8l-2 3-5-5 3-2 1-2Z'}), element('path', {d: 'm7.5 8.5-4 4'}),
449
- !targetsPinned && element('path', {d: 'M2 2l12 12', strokeLinecap: 'round'})));
469
+ drawerPinIcon(element, targetsPinned));
450
470
  }
451
471
 
452
472
  function useSpriteListTools() {
@@ -21,6 +21,8 @@ export interface StageDrawerLayout {
21
21
  open: boolean;
22
22
  /** Keep the drawer selected after it folds into the edge. */
23
23
  selected: boolean;
24
+ /** Missing in older records, which use the default pinned behavior. */
25
+ pinned?: boolean;
24
26
  position?: StageDrawerPosition;
25
27
  width?: number;
26
28
  }
@@ -212,12 +214,13 @@ export function readWorkspaceLayout(raw: string, project?: string): WorkspaceLay
212
214
 
213
215
  function readStageDrawer(input: unknown): StageDrawerLayout | undefined {
214
216
  if (!record(input) || typeof input.open !== 'boolean' || typeof input.selected !== 'boolean') return;
215
- const {position, width} = input;
217
+ const {position, width, pinned} = input;
216
218
  const fraction = (value: unknown): value is number => size(value) && value <= 1;
217
219
  const edge = (value: number) => value === 0 || value === 1;
218
220
  return {
219
221
  open: input.open,
220
222
  selected: input.open || input.selected,
223
+ ...(typeof pinned === 'boolean' && {pinned}),
221
224
  ...(size(width) && width > 0 && {width}),
222
225
  ...(record(position) && fraction(position.x) && fraction(position.y) &&
223
226
  (edge(position.x) || edge(position.y)) && {position: {x: position.x, y: position.y}})