@bnviking/dsh-bnv-workspace 0.0.0-stage → 1.0.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/client.js ADDED
@@ -0,0 +1,1268 @@
1
+ /**
2
+ * Browser half: per-row icons, permanent deletion, and one Settings section
3
+ * with the shared label styling for every chat and every project. All visible
4
+ * text comes from this package's `bnv-workspace` locale namespace: Russian
5
+ * when the active locale is Russian, English for every other language (the
6
+ * locale service falls back through the active language chain to English).
7
+ */
8
+ window.__ModuleLoader__.load({
9
+ id: '@bnviking/dsh-bnv-workspace',
10
+ factory(require) {
11
+ const React = require('react')
12
+ const h = React.createElement
13
+
14
+ const STYLE_KEY = 'dsh.bnv-workspace.styles.v2'
15
+ const ICON_KEY = 'dsh.bnv-workspace.icons.v1'
16
+ const COLOR_KEY = 'dsh.bnv-workspace.item-colors.v1'
17
+ const TOPBAR_KEY = 'dsh.bnv-workspace.general.v2'
18
+ const DEFAULTS = Object.freeze({
19
+ case: 'none', font: 'none', weight: 'none', color: 'none', colorCustom: '#c7c9d1', size: '100', tracking: 'none',
20
+ })
21
+ const SIZE_OPTIONS = [60, 70, 80, 90, 100, 110, 120, 130].map(value => [String(value), `${value}%`])
22
+ const FAMILY_PREFIX = 'family:'
23
+ const FONT_FALLBACK = [
24
+ 'Arial', 'Times New Roman', 'Georgia', 'Verdana', 'Tahoma', 'Trebuchet MS',
25
+ 'Segoe UI', 'Calibri', 'Courier New', 'Helvetica', 'Garamond', 'Palatino Linotype',
26
+ ]
27
+ const GROUPS = [
28
+ { key: 'case', label: 'group.case', options: [['none', 'opt.case.default'], ['upper', 'opt.case.upper'], ['lower', 'opt.case.lower'], ['capitalize', 'opt.case.capitalize']] },
29
+ { key: 'font', label: 'group.font', options: [['none', 'opt.font.default'], ['mono', 'opt.font.mono'], ['serif', 'opt.font.serif']] },
30
+ { key: 'weight', label: 'group.weight', options: [['none', 'opt.weight.default'], ['medium', 'opt.weight.medium'], ['bold', 'opt.weight.bold']] },
31
+ { key: 'color', label: 'group.color', options: [['none', 'opt.color.default'], ['accent', 'opt.color.accent'], ['muted', 'opt.color.muted']] },
32
+ { key: 'size', label: 'group.size', options: SIZE_OPTIONS, literal: true },
33
+ { key: 'tracking', label: 'group.tracking', options: [['none', 'opt.tracking.default'], ['narrow', 'opt.tracking.narrow'], ['wide', 'opt.tracking.wide']] },
34
+ ]
35
+ const TABS = [
36
+ { key: 'general', label: 'settings.tab.general', icon: 'M12 9a3 3 0 100 6 3 3 0 000-6zM19.4 15a1.7 1.7 0 00.3 1.9l.1.1a2 2 0 01-2.8 2.8l-.1-.1a1.7 1.7 0 00-1.9-.3 1.7 1.7 0 00-1 1.5V21a2 2 0 01-4 0v-.1a1.7 1.7 0 00-1.1-1.5 1.7 1.7 0 00-1.9.3l-.1.1a2 2 0 01-2.8-2.8l.1-.1a1.7 1.7 0 00.3-1.9 1.7 1.7 0 00-1.5-1H3a2 2 0 010-4h.1a1.7 1.7 0 001.5-1.1 1.7 1.7 0 00-.3-1.9l-.1-.1a2 2 0 012.8-2.8l.1.1a1.7 1.7 0 001.9.3H9a1.7 1.7 0 001-1.5V3a2 2 0 014 0v.1a1.7 1.7 0 001 1.5 1.7 1.7 0 001.9-.3l.1-.1a2 2 0 012.8 2.8l-.1.1a1.7 1.7 0 00-.3 1.9V9a1.7 1.7 0 001.5 1H21a2 2 0 010 4h-.1a1.7 1.7 0 00-1.5 1z' },
37
+ { key: 'project', label: 'settings.tab.projects', icon: 'M3 7a2 2 0 012-2h4l2 2h8a2 2 0 012 2v8a2 2 0 01-2 2H5a2 2 0 01-2-2z' },
38
+ { key: 'chat', label: 'settings.tab.chats', icon: 'M21 12a8 8 0 01-11.6 7.1L4 21l1.9-5.4A8 8 0 1121 12z' },
39
+ ]
40
+ const EN = {
41
+ 'settings.label': 'BNV WorkSpace',
42
+ 'settings.title': 'BNV WorkSpace',
43
+ 'settings.intro': 'Shared settings: they apply to every chat and every project in the sidebar.',
44
+ 'settings.tab.projects': 'Projects',
45
+ 'settings.tab.chats': 'Chats',
46
+ 'settings.tab.general': 'General',
47
+ 'settings.reset.projects': 'Reset project display settings',
48
+ 'settings.reset.chats': 'Reset chat display settings',
49
+ 'settings.err.storage': 'Could not save the settings in the browser.',
50
+ 'general.topbar.label': 'Top menu',
51
+ 'general.topbar.default': 'Default',
52
+ 'general.topbar.compact': 'Compact',
53
+ 'general.topbar.hint': 'Compact puts New session and the panel section icons in one row next to the logo; Projects follows below.',
54
+ 'general.newSession': 'New session',
55
+ 'general.settings': 'Settings',
56
+ 'workspace.renamed': 'Projects',
57
+ 'reset.title.projects': 'Reset project display settings?',
58
+ 'reset.title.chats': 'Reset chat display settings?',
59
+ 'reset.cancel': 'Cancel',
60
+ 'reset.confirm': 'Reset',
61
+ 'group.case': 'Case',
62
+ 'group.font': 'Font',
63
+ 'group.weight': 'Weight',
64
+ 'group.color': 'Color',
65
+ 'group.size': 'Size',
66
+ 'group.tracking': 'Letter spacing',
67
+ 'opt.case.default': 'Default',
68
+ 'opt.case.upper': 'UPPERCASE',
69
+ 'opt.case.lower': 'lowercase',
70
+ 'opt.case.capitalize': 'Capitalize',
71
+ 'opt.font.default': 'DSH default',
72
+ 'opt.font.mono': 'Monospace',
73
+ 'opt.font.serif': 'Serif',
74
+ 'opt.weight.default': 'Default',
75
+ 'opt.weight.medium': 'Medium',
76
+ 'opt.weight.bold': 'Bold',
77
+ 'opt.color.default': 'DSH default',
78
+ 'opt.color.accent': 'Accent',
79
+ 'opt.color.muted': 'Muted',
80
+ 'opt.color.custom': 'Custom color',
81
+ 'opt.tracking.default': 'Default',
82
+ 'opt.tracking.narrow': 'Narrow',
83
+ 'opt.tracking.wide': 'Wide',
84
+ 'menu.customize': 'Customize view…',
85
+ 'menu.delete': 'Delete permanently…',
86
+ 'icon.title': 'Customize view',
87
+ 'icon.aria': 'Customize view',
88
+ 'icon.chatTarget': 'Chat “{name}”',
89
+ 'icon.projectTarget': 'Project “{name}”',
90
+ 'icon.label': 'Icon',
91
+ 'icon.upload': 'Upload…',
92
+ 'icon.remove': 'No icon',
93
+ 'icon.done': 'Done',
94
+ 'icon.untitled': 'Untitled',
95
+ 'icon.err.storage': 'Could not save the icon: browser storage is full.',
96
+ 'icon.err.notImage': 'Choose an image file.',
97
+ 'icon.err.read': 'Could not read the image.',
98
+ 'icon.color.label': 'Color',
99
+ 'icon.color.clear': 'No color',
100
+ 'delete.chat.title': 'Delete chat permanently?',
101
+ 'delete.project.title': 'Delete project permanently?',
102
+ 'delete.chat.body': 'Chat “{name}” and its entire history will be erased from disk. This cannot be undone.',
103
+ 'delete.project.body': 'Project “{name}” and every chat inside{count} will be erased from disk. The project folder stays. This cannot be undone.',
104
+ 'delete.count.one': ' ({n} chat)',
105
+ 'delete.count.few': ' ({n} chats)',
106
+ 'delete.count.many': ' ({n} chats)',
107
+ 'delete.cancel': 'Cancel',
108
+ 'delete.confirm': 'Delete permanently',
109
+ 'delete.busy': 'Deleting…',
110
+ 'delete.aria': 'Permanent deletion',
111
+ 'delete.offline': 'The DSH connection is unavailable.',
112
+ 'delete.notActive': 'The plugin is not active.',
113
+ 'delete.needOpenChat': 'Open any chat first and try the deletion again.',
114
+ 'delete.openChat': 'This chat is open right now. Switch to another chat and try again.',
115
+ 'delete.openProject': 'A chat from this project is open. Switch to a chat from another project and try again.',
116
+ 'delete.failed': 'The deletion could not be completed.',
117
+ }
118
+ const RU = {
119
+ 'settings.label': 'BNV WorkSpace',
120
+ 'settings.title': 'BNV WorkSpace',
121
+ 'settings.intro': 'Общие настройки: применяются ко всем чатам и ко всем проектам в боковой панели.',
122
+ 'settings.tab.projects': 'Проекты',
123
+ 'settings.tab.chats': 'Чаты',
124
+ 'settings.tab.general': 'Общие',
125
+ 'settings.reset.projects': 'Сбросить настройки отображения проектов',
126
+ 'settings.reset.chats': 'Сбросить настройки отображения чатов',
127
+ 'settings.err.storage': 'Не удалось сохранить настройки в браузере.',
128
+ 'general.topbar.label': 'Верхнее меню',
129
+ 'general.topbar.default': 'Обычное',
130
+ 'general.topbar.compact': 'Компактное',
131
+ 'general.topbar.hint': 'Компактное: «Новая сессия» и иконки разделов панели стоят одной строкой рядом с логотипом, ниже идут проекты.',
132
+ 'general.newSession': 'Новая сессия',
133
+ 'general.settings': 'Настройки',
134
+ 'workspace.renamed': 'Проекты',
135
+ 'reset.title.projects': 'Сбросить настройки отображения проектов?',
136
+ 'reset.title.chats': 'Сбросить настройки отображения чатов?',
137
+ 'reset.cancel': 'Отмена',
138
+ 'reset.confirm': 'Сбросить',
139
+ 'group.case': 'Регистр',
140
+ 'group.font': 'Шрифт',
141
+ 'group.weight': 'Толщина',
142
+ 'group.color': 'Цвет',
143
+ 'group.size': 'Размер',
144
+ 'group.tracking': 'Интервал',
145
+ 'opt.case.default': 'Обычный',
146
+ 'opt.case.upper': 'ВЕРХНИЙ',
147
+ 'opt.case.lower': 'нижний',
148
+ 'opt.case.capitalize': 'С Заглавных',
149
+ 'opt.font.default': 'Как в DSH',
150
+ 'opt.font.mono': 'Моноширинный',
151
+ 'opt.font.serif': 'С засечками',
152
+ 'opt.weight.default': 'Обычная',
153
+ 'opt.weight.medium': 'Средняя',
154
+ 'opt.weight.bold': 'Жирная',
155
+ 'opt.color.default': 'Как в DSH',
156
+ 'opt.color.accent': 'Акцент',
157
+ 'opt.color.muted': 'Приглушённый',
158
+ 'opt.color.custom': 'Свой цвет',
159
+ 'opt.tracking.default': 'Обычный',
160
+ 'opt.tracking.narrow': 'Узкий',
161
+ 'opt.tracking.wide': 'Широкий',
162
+ 'menu.customize': 'Настроить вид…',
163
+ 'menu.delete': 'Удалить навсегда…',
164
+ 'icon.title': 'Настроить вид',
165
+ 'icon.aria': 'Настроить вид',
166
+ 'icon.chatTarget': 'Чат «{name}»',
167
+ 'icon.projectTarget': 'Проект «{name}»',
168
+ 'icon.label': 'Иконка',
169
+ 'icon.upload': 'Загрузить…',
170
+ 'icon.remove': 'Без иконки',
171
+ 'icon.done': 'Готово',
172
+ 'icon.untitled': 'Без названия',
173
+ 'icon.err.storage': 'Не удалось сохранить иконку: хранилище браузера переполнено.',
174
+ 'icon.err.notImage': 'Выберите файл изображения.',
175
+ 'icon.err.read': 'Не удалось прочитать изображение.',
176
+ 'icon.color.label': 'Цвет',
177
+ 'icon.color.clear': 'Без цвета',
178
+ 'delete.chat.title': 'Удалить чат навсегда?',
179
+ 'delete.project.title': 'Удалить проект навсегда?',
180
+ 'delete.chat.body': 'Чат «{name}» и вся его история будут стёрты с диска. Восстановить нельзя.',
181
+ 'delete.project.body': 'Проект «{name}» и все чаты внутри{count} будут стёрты с диска. Папка проекта останется. Восстановить нельзя.',
182
+ 'delete.count.one': ' ({n} чат)',
183
+ 'delete.count.few': ' ({n} чата)',
184
+ 'delete.count.many': ' ({n} чатов)',
185
+ 'delete.cancel': 'Отмена',
186
+ 'delete.confirm': 'Удалить навсегда',
187
+ 'delete.busy': 'Удаляю…',
188
+ 'delete.aria': 'Удаление навсегда',
189
+ 'delete.offline': 'Соединение с DSH недоступно.',
190
+ 'delete.notActive': 'Плагин не активирован.',
191
+ 'delete.needOpenChat': 'Откройте любой чат и повторите удаление.',
192
+ 'delete.openChat': 'Этот чат сейчас открыт. Переключитесь на другой чат и повторите.',
193
+ 'delete.openProject': 'В этом проекте открыт чат. Переключитесь на чат другого проекта и повторите.',
194
+ 'delete.failed': 'Не удалось выполнить удаление.',
195
+ }
196
+ const BUILTIN = [
197
+ { id: 'star', title: { en: 'Star', ru: 'Звезда' }, d: 'M12 3.5l2.7 5.5 6 .9-4.3 4.2 1 6-5.4-2.8-5.4 2.8 1-6L3.3 9.9l6-.9z' },
198
+ { id: 'bug', title: { en: 'Bug', ru: 'Баг' }, d: 'M12 6a5 5 0 015 5v4a5 5 0 01-10 0v-4a5 5 0 015-5zM9 4.5h6M12 3v3M6 9h2M16 9h2M7 13H5M19 13h-2M8 21h8' },
199
+ { id: 'book', title: { en: 'Book', ru: 'Книга' }, d: 'M4 4.5h9a3 3 0 013 3V20H7a3 3 0 01-3-3zM4 17a3 3 0 013-3h9' },
200
+ { id: 'rocket', title: { en: 'Rocket', ru: 'Ракета' }, d: 'M12 3c3 2 5 5 5 9l-3 3H10l-3-3c0-4 2-7 5-9zM9 15l-2 5 4-2M15 15l2 5-4-2M12 8.5v3' },
201
+ { id: 'heart', title: { en: 'Heart', ru: 'Сердце' }, d: 'M12 20s-7-4.4-7-9.3A4.2 4.2 0 0112 8a4.2 4.2 0 017 2.7C19 15.6 12 20 12 20z' },
202
+ { id: 'bolt', title: { en: 'Bolt', ru: 'Молния' }, d: 'M13 2L4 14h6l-1 8 9-12h-6z' },
203
+ { id: 'flag', title: { en: 'Flag', ru: 'Флаг' }, d: 'M6 21V4M6 4h10l-2 4 2 4H6' },
204
+ { id: 'bulb', title: { en: 'Idea', ru: 'Идея' }, d: 'M9 18h6M10 21h4M12 3a6 6 0 00-3.5 10.9V16h7v-2.1A6 6 0 0012 3z' },
205
+ ]
206
+ const GEAR = 'M12 9a3 3 0 100 6 3 3 0 000-6zM19.4 15a1.7 1.7 0 00.3 1.9l.1.1a2 2 0 01-2.8 2.8l-.1-.1a1.7 1.7 0 00-1.9-.3 1.7 1.7 0 00-1 1.5V21a2 2 0 01-4 0v-.1a1.7 1.7 0 00-1.1-1.5 1.7 1.7 0 00-1.9.3l-.1.1a2 2 0 01-2.8-2.8l.1-.1a1.7 1.7 0 00.3-1.9 1.7 1.7 0 00-1.5-1H3a2 2 0 010-4h.1a1.7 1.7 0 001.5-1.1 1.7 1.7 0 00-.3-1.9l-.1-.1a2 2 0 012.8-2.8l.1.1a1.7 1.7 0 001.9.3H9a1.7 1.7 0 001-1.5V3a2 2 0 014 0v.1a1.7 1.7 0 001 1.5 1.7 1.7 0 001.9-.3l.1-.1a2 2 0 012.8 2.8l-.1.1a1.7 1.7 0 00-.3 1.9V9a1.7 1.7 0 001.5 1H21a2 2 0 010 4h-.1a1.7 1.7 0 00-1.5 1z'
207
+
208
+ /** @type {any} */
209
+ let runtime = null
210
+ /** @type {((key: string, vars?: Record<string, string | number>) => string) | null} */
211
+ let translate = null
212
+ /** @type {any} */
213
+ let localeService = null
214
+ let settingsOpener = null
215
+
216
+ function interpolate(template, vars) {
217
+ if (vars === undefined) return template
218
+ let text = template
219
+ for (const [name, value] of Object.entries(vars)) text = text.split(`{${name}}`).join(String(value))
220
+ return text
221
+ }
222
+
223
+ function browserLanguage() {
224
+ const raw = typeof navigator === 'undefined' ? 'en' : String(navigator.language || 'en')
225
+ return raw.toLowerCase().startsWith('ru') ? 'ru' : 'en'
226
+ }
227
+
228
+ function currentLanguage() {
229
+ const active = localeService?.getSnapshot?.().active
230
+ if (typeof active === 'string' && active.length > 0) {
231
+ return active.toLowerCase().startsWith('ru') ? 'ru' : 'en'
232
+ }
233
+ return browserLanguage()
234
+ }
235
+
236
+ function t(key, vars) {
237
+ if (translate !== null) return translate(key, vars)
238
+ return interpolate((currentLanguage() === 'ru' ? RU : EN)[key] ?? EN[key] ?? key, vars)
239
+ }
240
+
241
+ function loadJson(key) {
242
+ try {
243
+ const parsed = JSON.parse(localStorage.getItem(key) ?? 'null')
244
+ return parsed !== null && typeof parsed === 'object' ? parsed : null
245
+ } catch {
246
+ return null
247
+ }
248
+ }
249
+
250
+ function normalizeStyle(saved) {
251
+ const style = { ...DEFAULTS, ...(saved ?? {}) }
252
+ const legacy = { none: '100', small: '90', large: '110' }
253
+ if (legacy[style.size] !== undefined) style.size = legacy[style.size]
254
+ const size = Number(style.size)
255
+ if (!Number.isFinite(size) || size < 60 || size > 130) style.size = '100'
256
+ if (!/^#[0-9a-f]{6}$/i.test(String(style.colorCustom))) style.colorCustom = DEFAULTS.colorCustom
257
+ if (style.color !== 'none' && style.color !== 'accent' && style.color !== 'muted' && !/^#[0-9a-f]{6}$/i.test(String(style.color))) {
258
+ style.color = 'none'
259
+ }
260
+ const family = typeof style.font === 'string' ? style.font.slice(FAMILY_PREFIX.length).trim() : ''
261
+ const knownFont = style.font === 'none' || style.font === 'mono' || style.font === 'serif'
262
+ if (!knownFont && !(typeof style.font === 'string' && style.font.startsWith(FAMILY_PREFIX) && family.length > 0)) {
263
+ style.font = 'none'
264
+ }
265
+ return style
266
+ }
267
+
268
+ function loadStyles() {
269
+ const saved = loadJson(STYLE_KEY)
270
+ return {
271
+ chat: normalizeStyle(saved?.chat),
272
+ project: normalizeStyle(saved?.project),
273
+ }
274
+ }
275
+
276
+ function loadIcons() {
277
+ const saved = loadJson(ICON_KEY)
278
+ return {
279
+ sessions: { ...(saved?.sessions ?? {}) },
280
+ projects: { ...(saved?.projects ?? {}) },
281
+ }
282
+ }
283
+
284
+ function loadItemColors() {
285
+ const saved = loadJson(COLOR_KEY)
286
+ const clean = (map) => Object.fromEntries(
287
+ Object.entries(map ?? {}).filter(([, value]) => /^#[0-9a-f]{6}$/i.test(String(value))),
288
+ )
289
+ return { sessions: clean(saved?.sessions), projects: clean(saved?.projects) }
290
+ }
291
+
292
+ function loadTopbar() {
293
+ const saved = loadJson(TOPBAR_KEY)
294
+ return saved?.topbar === 'default' ? 'default' : 'compact'
295
+ }
296
+
297
+ const store = {
298
+ styles: loadStyles(),
299
+ icons: loadIcons(),
300
+ itemColors: loadItemColors(),
301
+ topbar: loadTopbar(),
302
+ dialog: null,
303
+ notice: null,
304
+ }
305
+ const listeners = new Set()
306
+
307
+ function update(patch) {
308
+ Object.assign(store, patch)
309
+ for (const listener of [...listeners]) listener()
310
+ }
311
+
312
+ function useSnapshot() {
313
+ const [, force] = React.useState(0)
314
+ React.useEffect(() => {
315
+ const listener = () => force(value => value + 1)
316
+ listeners.add(listener)
317
+ return () => { listeners.delete(listener) }
318
+ }, [])
319
+ return store
320
+ }
321
+
322
+ function persist(key, value) {
323
+ try {
324
+ localStorage.setItem(key, JSON.stringify(value))
325
+ return true
326
+ } catch {
327
+ return false
328
+ }
329
+ }
330
+
331
+ function saveStyles(next) {
332
+ if (!persist(STYLE_KEY, next)) {
333
+ update({ notice: { id: Date.now(), text: t('settings.err.storage') } })
334
+ return
335
+ }
336
+ update({ styles: next })
337
+ }
338
+
339
+ function saveIcons(next) {
340
+ if (!persist(ICON_KEY, next)) {
341
+ update({ notice: { id: Date.now(), text: t('icon.err.storage') } })
342
+ return false
343
+ }
344
+ update({ icons: next })
345
+ return true
346
+ }
347
+
348
+ function saveItemColors(next) {
349
+ if (!persist(COLOR_KEY, next)) {
350
+ update({ notice: { id: Date.now(), text: t('settings.err.storage') } })
351
+ return false
352
+ }
353
+ update({ itemColors: next })
354
+ return true
355
+ }
356
+
357
+ function itemColorOf(itemColors, scope, id) {
358
+ return scope === 'project' ? itemColors.projects[id] : itemColors.sessions[id]
359
+ }
360
+
361
+ function setItemColor(scope, id, color) {
362
+ const key = scope === 'project' ? 'projects' : 'sessions'
363
+ return saveItemColors({ ...store.itemColors, [key]: { ...store.itemColors[key], [id]: color } })
364
+ }
365
+
366
+ function clearItemColor(scope, id) {
367
+ const key = scope === 'project' ? 'projects' : 'sessions'
368
+ if (store.itemColors[key][id] === undefined) return
369
+ const next = { ...store.itemColors[key] }
370
+ delete next[id]
371
+ saveItemColors({ ...store.itemColors, [key]: next })
372
+ }
373
+
374
+ function saveTopbar(value) {
375
+ if (!persist(TOPBAR_KEY, { topbar: value })) {
376
+ update({ notice: { id: Date.now(), text: t('settings.err.storage') } })
377
+ return
378
+ }
379
+ update({ topbar: value })
380
+ }
381
+
382
+ function panelEntries() {
383
+ if (runtime === null) return []
384
+ const slots = runtime.get('slots')
385
+ if (slots === undefined || slots === null || typeof slots.entriesOfSlot !== 'function') return []
386
+ try {
387
+ return slots.entriesOfSlot('sidebar.panellist')
388
+ .map((entry) => {
389
+ const rawLabel = entry.options?.label
390
+ return { id: entry.options?.id, label: typeof rawLabel === 'function' ? rawLabel() : rawLabel }
391
+ })
392
+ .filter(entry => typeof entry.id === 'string' && typeof entry.label === 'string')
393
+ } catch {
394
+ return []
395
+ }
396
+ }
397
+
398
+ function notify(text) {
399
+ update({ notice: { id: Date.now(), text } })
400
+ }
401
+
402
+ function requestIcon(scope, targetId, targetName) {
403
+ update({ dialog: { kind: 'icon', scope, targetId, targetName } })
404
+ }
405
+
406
+ function requestDelete(targetKind, id, title, count) {
407
+ update({ dialog: { kind: 'delete', target: targetKind, id, title, count } })
408
+ }
409
+
410
+ function closeDialog() {
411
+ update({ dialog: null })
412
+ }
413
+
414
+ function builtin(id) {
415
+ return BUILTIN.find(icon => icon.id === id)
416
+ }
417
+
418
+ function builtinDataUrl(id) {
419
+ const icon = builtin(id)
420
+ if (icon === undefined) return null
421
+ const svg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" '
422
+ + `stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="${icon.d}"/></svg>`
423
+ return `data:image/svg+xml,${encodeURIComponent(svg)}`
424
+ }
425
+
426
+ function iconSpec(icons, scope, id) {
427
+ return scope === 'project' ? icons.projects[id] : icons.sessions[id]
428
+ }
429
+
430
+ function setIcon(scope, id, spec) {
431
+ const key = scope === 'project' ? 'projects' : 'sessions'
432
+ const icons = { ...store.icons, [key]: { ...store.icons[key], [id]: spec } }
433
+ return saveIcons(icons)
434
+ }
435
+
436
+ function removeIcon(scope, id) {
437
+ const key = scope === 'project' ? 'projects' : 'sessions'
438
+ if (store.icons[key][id] === undefined) return
439
+ const next = { ...store.icons[key] }
440
+ delete next[id]
441
+ saveIcons({ ...store.icons, [key]: next })
442
+ }
443
+
444
+ function glyph(spec, size) {
445
+ if (typeof spec !== 'string') return null
446
+ if (spec.startsWith('builtin:')) {
447
+ const icon = builtin(spec.slice('builtin:'.length))
448
+ if (icon === undefined) return null
449
+ return h('svg', {
450
+ width: size, height: size, viewBox: '0 0 24 24', 'aria-hidden': true, fill: 'none',
451
+ stroke: 'currentColor', strokeWidth: 2, strokeLinecap: 'round', strokeLinejoin: 'round',
452
+ }, h('path', { d: icon.d }))
453
+ }
454
+ if (spec.startsWith('data:')) {
455
+ return h('img', { src: spec.slice('data:'.length), width: size, height: size, alt: '' })
456
+ }
457
+ return null
458
+ }
459
+
460
+ function nameCss(styles) {
461
+ const build = (scope) => {
462
+ const style = styles[scope]
463
+ const rules = []
464
+ if (style.case === 'upper') rules.push('text-transform:uppercase')
465
+ if (style.case === 'lower') rules.push('text-transform:lowercase')
466
+ if (style.case === 'capitalize') rules.push('text-transform:capitalize')
467
+ if (style.font === 'mono') rules.push("font-family:ui-monospace,'Cascadia Mono',Consolas,monospace")
468
+ else if (style.font === 'serif') rules.push("font-family:Georgia,'Times New Roman',serif")
469
+ else if (typeof style.font === 'string' && style.font.startsWith(FAMILY_PREFIX)) {
470
+ const family = style.font.slice(FAMILY_PREFIX.length).replace(/["'\\]/g, '').trim()
471
+ if (family.length > 0) rules.push(`font-family:"${family}"`)
472
+ }
473
+ if (style.weight === 'medium') rules.push('font-weight:500')
474
+ if (style.weight === 'bold') rules.push('font-weight:700')
475
+ if (style.color === 'accent') rules.push('color:var(--dsw-alias-brand-primary)')
476
+ else if (style.color === 'muted') rules.push('color:var(--dsw-alias-label-secondary)')
477
+ else if (/^#[0-9a-f]{6}$/i.test(String(style.color))) rules.push(`color:${style.color}`)
478
+ const size = Number(style.size)
479
+ if (Number.isFinite(size) && size >= 60 && size <= 130 && size !== 100) rules.push(`font-size:${size}%`)
480
+ if (style.tracking === 'narrow') rules.push('letter-spacing:-0.02em')
481
+ if (style.tracking === 'wide') rules.push('letter-spacing:0.04em')
482
+ if (rules.length === 0) return ''
483
+ const selector = scope === 'chat'
484
+ ? '[data-row-key^="session:"] > span:nth-child(2)'
485
+ : '[data-row-key^="workspace:"] > span:nth-child(3)'
486
+ return `${selector}{${rules.join(';')}}`
487
+ }
488
+ return build('chat') + build('project')
489
+ }
490
+
491
+ function projectIconCss(icons) {
492
+ const rules = []
493
+ for (const [id, spec] of Object.entries(icons.projects)) {
494
+ if (!/^[A-Za-z0-9_-]+$/.test(id)) continue
495
+ const cell = `[data-row-key="workspace:${id}"]>span:nth-child(1)`
496
+ if (typeof spec !== 'string') continue
497
+ if (spec.startsWith('builtin:')) {
498
+ const url = builtinDataUrl(spec.slice('builtin:'.length))
499
+ if (url === null) continue
500
+ rules.push(`${cell}>svg{display:none}`)
501
+ rules.push(`${cell}::before{content:'';display:inline-block;width:16px;height:16px;`
502
+ + `background-color:currentColor;-webkit-mask:url("${url}") center/contain no-repeat;`
503
+ + `mask:url("${url}") center/contain no-repeat}`)
504
+ } else if (spec.startsWith('data:')) {
505
+ const url = spec.slice('data:'.length)
506
+ rules.push(`${cell}>svg{display:none}`)
507
+ rules.push(`${cell}::before{content:'';display:inline-block;width:16px;height:16px;`
508
+ + `background:url("${url}") center/contain no-repeat}`)
509
+ }
510
+ }
511
+ return rules.join('')
512
+ }
513
+
514
+ function itemColorCss(itemColors) {
515
+ const rules = []
516
+ for (const [id, color] of Object.entries(itemColors.sessions)) {
517
+ if (!/^[A-Za-z0-9_-]+$/.test(id) || !/^#[0-9a-f]{6}$/i.test(String(color))) continue
518
+ rules.push(`[data-row-key="session:${id}"]>span:nth-child(2){color:${color}}`)
519
+ }
520
+ for (const [id, color] of Object.entries(itemColors.projects)) {
521
+ if (!/^[A-Za-z0-9_-]+$/.test(id) || !/^#[0-9a-f]{6}$/i.test(String(color))) continue
522
+ rules.push(`[data-row-key="workspace:${id}"]>span:nth-child(3){color:${color}}`)
523
+ }
524
+ return rules.join('')
525
+ }
526
+
527
+ const CSS = `
528
+ .bnv-menu-row{display:flex;align-items:center;gap:8px;width:100%;padding:6px 10px;margin:0;border:0;border-radius:6px;background:transparent;color:var(--dsw-alias-label-primary);font:inherit;font-size:13px;text-align:left;cursor:pointer}
529
+ .bnv-menu-row:hover{background:color-mix(in srgb,var(--dsw-alias-label-primary) 9%,transparent)}
530
+ .bnv-menu-danger{color:var(--dsw-alias-state-error-primary)}
531
+ .bnv-menu-danger:hover{background:color-mix(in srgb,var(--dsw-alias-state-error-primary) 12%,transparent)}
532
+ .bnv-brand-actions{display:flex;align-items:center;gap:4px}
533
+ .bnv-brand-actions .bnv-panel-btn{width:26px;height:26px}
534
+ .bnv-brand-actions .bnv-brand-new{margin-left:0}
535
+ html[data-bnv-topbar="compact"] *:has(> div > .bnv-row-marker){display:none}
536
+ .bnv-panel-btn{display:inline-flex;align-items:center;justify-content:center;width:30px;height:30px;padding:0;border:0;border-radius:7px;background:transparent;color:var(--dsw-alias-label-secondary);cursor:pointer;flex-shrink:0}
537
+ .bnv-panel-btn:hover{background:color-mix(in srgb,var(--dsw-alias-label-primary) 9%,transparent);color:var(--dsw-alias-label-primary)}
538
+ .bnv-panel-btn-active{background:color-mix(in srgb,var(--dsw-alias-brand-primary) 16%,transparent);color:var(--dsw-alias-label-primary)}
539
+ .bnv-brand-new{display:inline-flex;align-items:center;justify-content:center;width:26px;height:26px;margin-left:8px;padding:0;border:1px solid var(--dsw-alias-border-l1);border-radius:7px;background:color-mix(in srgb,var(--dsw-alias-brand-primary) 14%,transparent);color:var(--dsw-alias-label-primary);vertical-align:middle;cursor:pointer}
540
+ .bnv-brand-new:hover{background:color-mix(in srgb,var(--dsw-alias-brand-primary) 22%,transparent)}
541
+ html[data-bnv-topbar="compact"] [data-sidebar-scrollport] nav{display:none}
542
+ html[data-bnv-topbar="compact"]:not([data-windows-titlebar]) [data-sidebar-collapsed]:not([data-sidebar-drawer]) [data-sidebar-scrollport] nav{display:flex}
543
+ .bnv-backdrop{position:fixed;inset:0;z-index:2147483000;display:flex;align-items:center;justify-content:center;padding:24px;background:rgba(0,0,0,.38);pointer-events:auto}
544
+ .bnv-dialog{width:min(470px,calc(100vw - 32px));max-height:calc(100vh - 48px);overflow:auto;display:flex;flex-direction:column;gap:12px;padding:18px;border:1px solid var(--dsw-alias-border-l1);border-radius:14px;background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary);box-shadow:0 18px 48px rgba(0,0,0,.28);font:13px/1.5 inherit}
545
+ .bnv-dialog h2{margin:0;font-size:15px;font-weight:600;line-height:1.35}
546
+ .bnv-dialog p{margin:0;color:var(--dsw-alias-label-secondary)}
547
+ .bnv-dialog strong{color:var(--dsw-alias-label-primary);font-weight:600}
548
+ .bnv-error{margin:0;padding:8px 10px;border-radius:8px;background:color-mix(in srgb,var(--dsw-alias-state-error-primary) 14%,transparent);color:var(--dsw-alias-state-error-primary)}
549
+ .bnv-actions{display:flex;justify-content:flex-end;gap:8px;margin-top:4px}
550
+ .bnv-btn{padding:6px 14px;border:1px solid var(--dsw-alias-border-l2);border-radius:8px;background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-primary);font:inherit;cursor:pointer}
551
+ .bnv-btn:hover{border-color:var(--dsw-alias-label-secondary)}
552
+ .bnv-btn:disabled{opacity:.55;cursor:default}
553
+ .bnv-btn-danger{border-color:transparent;background:var(--dsw-alias-state-error-primary);color:#fff}
554
+ .bnv-btn-danger:hover{border-color:transparent;filter:brightness(1.06)}
555
+ .bnv-chips{display:flex;flex-wrap:wrap;gap:6px}
556
+ .bnv-chip{padding:4px 10px;border:1px solid var(--dsw-alias-border-l1);border-radius:999px;background:transparent;color:var(--dsw-alias-label-primary);font:inherit;font-size:12px;cursor:pointer}
557
+ .bnv-chip:hover{border-color:var(--dsw-alias-label-secondary)}
558
+ .bnv-chip[aria-pressed="true"]{border-color:var(--dsw-alias-brand-primary);background:color-mix(in srgb,var(--dsw-alias-brand-primary) 18%,transparent);color:var(--dsw-alias-label-primary);font-weight:500}
559
+ .bnv-color{width:32px;height:24px;padding:0;border:1px solid var(--dsw-alias-border-l1);border-radius:8px;background:transparent;cursor:pointer}
560
+ .bnv-color[data-active="true"]{border-color:var(--dsw-alias-brand-primary)}
561
+ .bnv-select{max-width:240px;padding:5px 8px;border:1px solid var(--dsw-alias-border-l2);border-radius:8px;background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-primary);font:inherit;font-size:12px;cursor:pointer}
562
+ .bnv-icon-block{display:flex;flex-direction:column;gap:8px;padding-top:10px;border-top:1px solid var(--dsw-alias-border-l1)}
563
+ .bnv-group-label{font-size:11px;letter-spacing:.04em;text-transform:uppercase;color:var(--dsw-alias-label-secondary)}
564
+ .bnv-icon-grid{display:flex;flex-wrap:wrap;gap:6px}
565
+ .bnv-icon-choice{display:inline-flex;align-items:center;justify-content:center;width:32px;height:32px;border:1px solid var(--dsw-alias-border-l1);border-radius:8px;background:transparent;color:var(--dsw-alias-label-primary);cursor:pointer}
566
+ .bnv-icon-choice:hover{border-color:var(--dsw-alias-label-secondary)}
567
+ .bnv-icon-choice[aria-pressed="true"]{border-color:var(--dsw-alias-brand-primary);background:color-mix(in srgb,var(--dsw-alias-brand-primary) 18%,transparent);color:var(--dsw-alias-label-primary)}
568
+ .bnv-icon-choice-danger{width:auto;padding:0 10px;color:var(--dsw-alias-state-error-primary)}
569
+ .bnv-icon-choice-danger[aria-pressed="true"]{background:transparent;color:var(--dsw-alias-state-error-primary)}
570
+ .bnv-upload{display:inline-flex;align-items:center;justify-content:center;height:32px;padding:0 10px;border:1px solid var(--dsw-alias-border-l1);border-radius:8px;color:var(--dsw-alias-label-primary);cursor:pointer}
571
+ .bnv-upload:hover{border-color:var(--dsw-alias-label-secondary)}
572
+ .bnv-upload input{display:none}
573
+ .bnv-row-icon{display:inline-flex;align-items:center;justify-content:center;width:16px;height:16px;color:var(--dsw-alias-label-secondary)}
574
+ .bnv-row-icon img{display:block;border-radius:4px}
575
+ .bnv-settings{display:flex;flex-direction:column;gap:16px;max-width:720px;color:var(--dsw-alias-label-primary)}
576
+ .bnv-settings-title{margin:0;font-size:16px;line-height:24px;font-weight:500;color:var(--dsw-alias-label-primary)}
577
+ .bnv-settings-intro{margin:0;font-size:14px;line-height:22px;color:var(--dsw-alias-label-secondary)}
578
+ .bnv-tabs{display:flex;align-items:stretch;gap:24px;padding:0 2px;border-bottom:1px solid var(--dsw-alias-border-l1);flex-shrink:0}
579
+ .bnv-tab{position:relative;display:inline-flex;align-items:center;gap:7px;height:38px;padding:0 4px;border:0;background:transparent;font:inherit;font-size:14px;line-height:38px;white-space:nowrap;flex-shrink:0;color:var(--dsw-alias-label-secondary);cursor:pointer;transition:color 120ms ease}
580
+ .bnv-tab:hover{color:var(--dsw-alias-label-primary)}
581
+ .bnv-tab[aria-selected="true"]{color:var(--dsw-alias-label-primary);font-weight:600}
582
+ .bnv-tab[aria-selected="true"]::after{content:'';position:absolute;left:0;right:0;bottom:-1px;height:2px;border-radius:1px;background:var(--dsw-alias-brand-primary)}
583
+ .bnv-tab-icon{display:inline-flex;align-items:center;flex-shrink:0}
584
+ .bnv-settings-scope{display:flex;flex-direction:column;gap:2px}
585
+ .bnv-settings-row{display:flex;align-items:center;justify-content:space-between;gap:16px;flex-wrap:wrap;padding:10px 0;border-bottom:0.5px solid var(--dsw-alias-border-l2)}
586
+ .bnv-settings-row:last-child{border-bottom:none}
587
+ .bnv-settings-label{font-size:13px;line-height:20px;color:var(--dsw-alias-label-secondary)}
588
+ .bnv-settings-hint{margin:0;font-size:12px;line-height:18px;color:var(--dsw-alias-label-secondary)}
589
+ .bnv-settings-footer{display:flex;align-items:center;justify-content:flex-end;flex-wrap:wrap;gap:12px;padding-top:12px;border-top:1px solid var(--dsw-alias-border-l1)}
590
+ .bnv-confirm-text{font-size:13px;line-height:20px;color:var(--dsw-alias-label-primary)}
591
+ .bnv-confirm-actions{display:flex;gap:8px}
592
+ .bnv-toast{position:fixed;left:50%;bottom:24px;z-index:2147483001;transform:translateX(-50%);max-width:min(520px,calc(100vw - 32px));padding:8px 14px;border:1px solid var(--dsw-alias-border-l1);border-radius:10px;background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-primary);box-shadow:0 10px 28px rgba(0,0,0,.22);font:13px/1.4 inherit;pointer-events:auto}
593
+ `
594
+
595
+ function strokeGlyph(d, size = 14) {
596
+ return h('svg', {
597
+ width: size, height: size, viewBox: '0 0 24 24', 'aria-hidden': true, fill: 'none',
598
+ stroke: 'currentColor', strokeWidth: 2, strokeLinecap: 'round', strokeLinejoin: 'round',
599
+ }, h('path', { d }))
600
+ }
601
+
602
+ const Trash = () => strokeGlyph('M3 6h18M8 6V4h8v2M5 6l1 15h12l1-15M10 11v6M14 11v6')
603
+ const Gear = () => strokeGlyph(GEAR)
604
+
605
+ function useEscape(handler) {
606
+ React.useEffect(() => {
607
+ const onKey = (event) => {
608
+ if (event.key !== 'Escape') return
609
+ event.stopPropagation()
610
+ handler()
611
+ }
612
+ window.addEventListener('keydown', onKey)
613
+ return () => window.removeEventListener('keydown', onKey)
614
+ }, [handler])
615
+ }
616
+
617
+ function SessionAppearanceItem(props) {
618
+ const callMenuHook = props.useMenuOpenState ?? (() => [false, () => {}])
619
+ const [, setMenuOpen] = callMenuHook()
620
+ return h('button', {
621
+ type: 'button',
622
+ role: 'menuitem',
623
+ className: 'bnv-menu-row',
624
+ onClick: (event) => {
625
+ event.stopPropagation()
626
+ setMenuOpen(false)
627
+ requestIcon('chat', props.sessionId, props.displayTitle || '')
628
+ },
629
+ }, Gear(), h('span', null, t('menu.customize')))
630
+ }
631
+
632
+ function SessionDeleteItem(props) {
633
+ const callMenuHook = props.useMenuOpenState ?? (() => [false, () => {}])
634
+ const [, setMenuOpen] = callMenuHook()
635
+ return h('button', {
636
+ type: 'button',
637
+ role: 'menuitem',
638
+ className: 'bnv-menu-row bnv-menu-danger',
639
+ onClick: (event) => {
640
+ event.stopPropagation()
641
+ setMenuOpen(false)
642
+ requestDelete('session', props.sessionId, props.displayTitle || '')
643
+ },
644
+ }, Trash(), h('span', null, t('menu.delete')))
645
+ }
646
+
647
+ function ChatIcon(props) {
648
+ const snapshot = useSnapshot()
649
+ const spec = snapshot.icons.sessions[props.sessionId]
650
+ if (spec === undefined) return null
651
+ const content = glyph(spec, 14)
652
+ if (content === null) return null
653
+ return h('span', { className: 'bnv-row-icon', 'aria-hidden': true }, content)
654
+ }
655
+
656
+ function PanelIconButton({ item, renderFactorySlot, usePanelInfo, onPick }) {
657
+ const active = typeof usePanelInfo === 'function'
658
+ ? usePanelInfo(info => info.activePanelId === item.id)
659
+ : false
660
+ return h('button', {
661
+ type: 'button',
662
+ className: active ? 'bnv-panel-btn bnv-panel-btn-active' : 'bnv-panel-btn',
663
+ title: item.label,
664
+ 'aria-label': item.label,
665
+ 'aria-current': active ? 'page' : undefined,
666
+ onClick: (event) => { event.stopPropagation(); onPick(item.id) },
667
+ }, typeof renderFactorySlot === 'function'
668
+ ? renderFactorySlot('sidebar.panel.icon', { id: item.id, size: 16, active })
669
+ : null)
670
+ }
671
+
672
+ function NewSessionAction(props) {
673
+ const snapshot = useSnapshot()
674
+ if (snapshot.topbar !== 'compact' || props.wide === false) return props.children
675
+ return h('span', { className: 'bnv-row-marker', 'aria-hidden': true })
676
+ }
677
+
678
+ function usePanelEntries() {
679
+ const [items, setItems] = React.useState([])
680
+ React.useEffect(() => {
681
+ const slots = runtime === null ? undefined : runtime.get('slots')
682
+ if (slots === undefined || slots === null || typeof slots.subscribe !== 'function') {
683
+ setItems(panelEntries())
684
+ return undefined
685
+ }
686
+ const refresh = () => setItems(panelEntries())
687
+ refresh()
688
+ return slots.subscribe('sidebar.panellist', refresh)
689
+ }, [])
690
+ return items
691
+ }
692
+
693
+ function BrandCompactActions(props) {
694
+ const items = usePanelEntries()
695
+ const layout = runtime === null ? undefined : runtime.get('layout')
696
+ const actionsRef = React.useRef(null)
697
+ React.useLayoutEffect(() => {
698
+ const alignRight = () => {
699
+ const element = actionsRef.current
700
+ if (element === null) return
701
+ const button = element.closest('button')
702
+ if (button === null) return
703
+ element.style.transform = 'none'
704
+ const target = button.getBoundingClientRect().right - 8
705
+ const current = element.getBoundingClientRect().right
706
+ const shift = Math.round(target - current)
707
+ element.style.transform = shift > 0 ? `translateX(${shift}px)` : 'none'
708
+ }
709
+ alignRight()
710
+ const observer = typeof ResizeObserver === 'function' ? new ResizeObserver(alignRight) : null
711
+ if (observer !== null) observer.observe(document.body)
712
+ window.addEventListener('resize', alignRight)
713
+ return () => {
714
+ if (observer !== null) observer.disconnect()
715
+ window.removeEventListener('resize', alignRight)
716
+ }
717
+ }, [items.length])
718
+ return h('span', { ref: actionsRef, className: 'bnv-brand-actions' },
719
+ h('button', {
720
+ type: 'button',
721
+ className: 'bnv-brand-new',
722
+ title: t('general.newSession'),
723
+ 'aria-label': t('general.newSession'),
724
+ onClick: (event) => {
725
+ event.stopPropagation()
726
+ const ui = runtime === null ? undefined : runtime.get('uiWorkspace')
727
+ if (ui !== undefined && ui !== null) ui.startSession()
728
+ },
729
+ }, strokeGlyph('M21 12a8 8 0 01-11.6 7.1L4 21l1.9-5.4A8 8 0 1121 12zM12 9v6M9 12h6', 16)),
730
+ ...items.map(item => h(PanelIconButton, {
731
+ key: item.id,
732
+ item,
733
+ renderFactorySlot: props.renderFactorySlot,
734
+ usePanelInfo: props.usePanelInfo,
735
+ onPick: (id) => { if (layout !== undefined && layout !== null) layout.selectPanel(id) },
736
+ })),
737
+ h('button', {
738
+ type: 'button',
739
+ className: 'bnv-panel-btn',
740
+ title: t('general.settings'),
741
+ 'aria-label': t('general.settings'),
742
+ onClick: (event) => { event.stopPropagation(); if (settingsOpener !== null) settingsOpener() },
743
+ }, strokeGlyph(GEAR, 16)))
744
+ }
745
+
746
+ function SettingsLauncherCapture(props) {
747
+ React.useEffect(() => {
748
+ settingsOpener = typeof props.openSettings === 'function' ? props.openSettings : null
749
+ return () => { settingsOpener = null }
750
+ }, [])
751
+ return null
752
+ }
753
+
754
+ function SettingsSection() {
755
+ const snapshot = useSnapshot()
756
+ const [tab, setTab] = React.useState('project')
757
+ const [confirming, setConfirming] = React.useState(false)
758
+ const [fonts, setFonts] = React.useState(FONT_FALLBACK)
759
+ React.useEffect(() => {
760
+ let alive = true
761
+ const api = typeof window === 'undefined' ? undefined : window.queryLocalFonts
762
+ if (typeof api !== 'function') return undefined
763
+ api.call(window).then((list) => {
764
+ if (!alive) return
765
+ const families = [...new Set((list ?? [])
766
+ .map(entry => entry.family)
767
+ .filter(name => typeof name === 'string' && name.length > 0))]
768
+ .sort((a, b) => a.localeCompare(b))
769
+ setFonts([...new Set([...FONT_FALLBACK, ...families])])
770
+ }).catch(() => {})
771
+ return () => { alive = false }
772
+ }, [])
773
+ const style = snapshot.styles[tab] ?? { ...DEFAULTS }
774
+ const set = (key, value) => saveStyles({ ...snapshot.styles, [tab]: { ...style, [key]: value } })
775
+ const pickTab = (key) => { setTab(key); setConfirming(false) }
776
+ const tabs = h('div', { className: 'bnv-tabs', role: 'tablist' },
777
+ ...TABS.map(entry => h('button', {
778
+ key: entry.key,
779
+ type: 'button',
780
+ role: 'tab',
781
+ className: 'bnv-tab',
782
+ 'aria-selected': tab === entry.key ? 'true' : 'false',
783
+ onClick: () => pickTab(entry.key),
784
+ },
785
+ h('span', { className: 'bnv-tab-icon', 'aria-hidden': true }, strokeGlyph(entry.icon, 16)),
786
+ t(entry.label))))
787
+ const fontChoices = [
788
+ ['none', t('opt.font.default')],
789
+ ['mono', t('opt.font.mono')],
790
+ ['serif', t('opt.font.serif')],
791
+ ...fonts.map(name => [FAMILY_PREFIX + name, name]),
792
+ ]
793
+ if (!fontChoices.some(([value]) => value === style.font)) {
794
+ fontChoices.push([style.font, String(style.font).slice(FAMILY_PREFIX.length)])
795
+ }
796
+ const styleRows = h('div', { className: 'bnv-settings-scope' },
797
+ ...GROUPS.map(group => h('div', { className: 'bnv-settings-row', key: group.key },
798
+ h('span', { className: 'bnv-settings-label' }, t(group.label)),
799
+ group.key === 'font'
800
+ ? h('select', {
801
+ className: 'bnv-select',
802
+ 'aria-label': t('group.font'),
803
+ value: style.font,
804
+ onChange: (event) => set('font', event.target.value),
805
+ }, ...fontChoices.map(([value, label]) => h('option', { key: value, value }, label)))
806
+ : h('div', { className: 'bnv-chips' },
807
+ ...group.options.map(([value, label]) => h('button', {
808
+ key: value,
809
+ type: 'button',
810
+ className: 'bnv-chip',
811
+ 'aria-pressed': style[group.key] === value ? 'true' : 'false',
812
+ onClick: () => set(group.key, value),
813
+ }, group.literal === true ? label : t(label))),
814
+ group.key === 'color' ? h('input', {
815
+ key: 'color-custom',
816
+ type: 'color',
817
+ className: 'bnv-color',
818
+ title: t('opt.color.custom'),
819
+ 'aria-label': t('opt.color.custom'),
820
+ 'data-active': /^#[0-9a-f]{6}$/i.test(style.color) ? 'true' : 'false',
821
+ value: style.colorCustom,
822
+ onChange: (event) => saveStyles({
823
+ ...snapshot.styles,
824
+ [tab]: { ...style, color: event.target.value, colorCustom: event.target.value },
825
+ }),
826
+ }) : null))))
827
+ const generalRows = h('div', { className: 'bnv-settings-scope' },
828
+ h('div', { className: 'bnv-settings-row' },
829
+ h('span', { className: 'bnv-settings-label' }, t('general.topbar.label')),
830
+ h('div', { className: 'bnv-chips' },
831
+ ...['default', 'compact'].map(value => h('button', {
832
+ key: value,
833
+ type: 'button',
834
+ className: 'bnv-chip',
835
+ 'aria-pressed': snapshot.topbar === value ? 'true' : 'false',
836
+ onClick: () => saveTopbar(value),
837
+ }, t(value === 'compact' ? 'general.topbar.compact' : 'general.topbar.default'))))),
838
+ h('p', { className: 'bnv-settings-hint' }, t('general.topbar.hint')))
839
+ const reset = tab === 'general' ? null : h('div', { className: 'bnv-settings-footer' },
840
+ confirming
841
+ ? h(React.Fragment, null,
842
+ h('span', { className: 'bnv-confirm-text', role: 'alert' },
843
+ t(tab === 'project' ? 'reset.title.projects' : 'reset.title.chats')),
844
+ h('div', { className: 'bnv-confirm-actions' },
845
+ h('button', { type: 'button', className: 'bnv-btn', onClick: () => setConfirming(false) }, t('reset.cancel')),
846
+ h('button', {
847
+ type: 'button',
848
+ className: 'bnv-btn',
849
+ onClick: () => {
850
+ saveStyles({ ...snapshot.styles, [tab]: { ...DEFAULTS } })
851
+ setConfirming(false)
852
+ },
853
+ }, t('reset.confirm'))))
854
+ : h('button', {
855
+ type: 'button',
856
+ className: 'bnv-btn',
857
+ onClick: () => setConfirming(true),
858
+ }, t(tab === 'project' ? 'settings.reset.projects' : 'settings.reset.chats')))
859
+ return h('div', { className: 'bnv-settings' },
860
+ h('h2', { className: 'bnv-settings-title' }, t('settings.title')),
861
+ h('p', { className: 'bnv-settings-intro' }, t('settings.intro')),
862
+ tabs,
863
+ tab === 'general' ? generalRows : styleRows,
864
+ reset)
865
+ }
866
+
867
+ function SectionIcon(props) {
868
+ const size = typeof props?.size === 'number' ? props.size : 16
869
+ return strokeGlyph(GEAR, size)
870
+ }
871
+
872
+ function Overlay() {
873
+ const snapshot = useSnapshot()
874
+ const dialog = snapshot.dialog
875
+ React.useEffect(() => {
876
+ const root = document.documentElement
877
+ if (snapshot.topbar === 'compact') root.setAttribute('data-bnv-topbar', 'compact')
878
+ else root.removeAttribute('data-bnv-topbar')
879
+ return () => root.removeAttribute('data-bnv-topbar')
880
+ }, [snapshot.topbar])
881
+ return h(React.Fragment, null,
882
+ h('style', { key: 'bnv-style' }, CSS + nameCss(snapshot.styles) + projectIconCss(snapshot.icons)
883
+ + itemColorCss(snapshot.itemColors)),
884
+ dialog === null ? null : h('div', {
885
+ key: 'bnv-backdrop',
886
+ className: 'bnv-backdrop',
887
+ onMouseDown: (event) => { if (event.target === event.currentTarget && dialog.kind === 'delete') closeDialog() },
888
+ }, dialog.kind === 'icon' ? h(IconDialog, { key: 'icon' }) : h(DeleteDialog, { key: 'delete', dialog })),
889
+ snapshot.notice === null ? null : h(Toast, { key: snapshot.notice.id, notice: snapshot.notice }))
890
+ }
891
+
892
+ function IconDialog() {
893
+ const snapshot = useSnapshot()
894
+ const dialog = snapshot.dialog
895
+ const [error, setError] = React.useState(null)
896
+ useEscape(closeDialog)
897
+ const current = iconSpec(snapshot.icons, dialog.scope, dialog.targetId)
898
+ const itemColor = itemColorOf(snapshot.itemColors, dialog.scope, dialog.targetId)
899
+ const name = dialog.targetName || t('icon.untitled')
900
+ const choose = (spec) => {
901
+ setError(null)
902
+ if (!setIcon(dialog.scope, dialog.targetId, spec)) setError(t('icon.err.storage'))
903
+ }
904
+ const upload = async (file) => {
905
+ if (file === undefined) return
906
+ if (!file.type.startsWith('image/')) {
907
+ setError(t('icon.err.notImage'))
908
+ return
909
+ }
910
+ try {
911
+ choose(`data:${await downscale(file)}`)
912
+ } catch {
913
+ setError(t('icon.err.read'))
914
+ }
915
+ }
916
+ return h('div', { className: 'bnv-dialog', role: 'dialog', 'aria-modal': 'true', 'aria-label': t('icon.aria') },
917
+ h('h2', null, t('icon.title')),
918
+ h('p', null, t(dialog.scope === 'project' ? 'icon.projectTarget' : 'icon.chatTarget', { name })),
919
+ h('div', { className: 'bnv-icon-block' },
920
+ h('span', { className: 'bnv-group-label' }, t('icon.label')),
921
+ h('div', { className: 'bnv-icon-grid' },
922
+ ...(current === undefined ? [] : [h('span', { key: 'current', className: 'bnv-icon-choice', 'aria-hidden': true }, glyph(current, 16))]),
923
+ ...BUILTIN.map(icon => h('button', {
924
+ key: icon.id,
925
+ type: 'button',
926
+ className: 'bnv-icon-choice',
927
+ title: icon.title[currentLanguage()],
928
+ 'aria-label': icon.title[currentLanguage()],
929
+ 'aria-pressed': current === `builtin:${icon.id}` ? 'true' : 'false',
930
+ onClick: () => choose(`builtin:${icon.id}`),
931
+ }, glyph(`builtin:${icon.id}`, 16))),
932
+ h('label', { className: 'bnv-upload' }, t('icon.upload'),
933
+ h('input', {
934
+ type: 'file',
935
+ accept: 'image/*',
936
+ onChange: (event) => { void upload(event.target.files?.[0]); event.target.value = '' },
937
+ })),
938
+ ...(current === undefined ? [] : [h('button', {
939
+ key: 'clear',
940
+ type: 'button',
941
+ className: 'bnv-icon-choice bnv-icon-choice-danger',
942
+ onClick: () => { setError(null); removeIcon(dialog.scope, dialog.targetId) },
943
+ }, t('icon.remove'))])),
944
+ error === null ? null : h('p', { className: 'bnv-error', role: 'alert' }, error)),
945
+ h('div', { className: 'bnv-icon-block' },
946
+ h('span', { className: 'bnv-group-label' }, t('icon.color.label')),
947
+ h('div', { className: 'bnv-icon-grid' },
948
+ h('input', {
949
+ type: 'color',
950
+ className: 'bnv-color',
951
+ title: t('icon.color.label'),
952
+ 'aria-label': t('icon.color.label'),
953
+ value: itemColor ?? '#c7c9d1',
954
+ onChange: (event) => setItemColor(dialog.scope, dialog.targetId, event.target.value),
955
+ }),
956
+ ...(itemColor === undefined ? [] : [h('button', {
957
+ key: 'clear-color',
958
+ type: 'button',
959
+ className: 'bnv-icon-choice bnv-icon-choice-danger',
960
+ onClick: () => clearItemColor(dialog.scope, dialog.targetId),
961
+ }, t('icon.color.clear'))]))),
962
+ h('div', { className: 'bnv-actions' },
963
+ h('button', { type: 'button', className: 'bnv-btn', onClick: closeDialog }, t('icon.done'))))
964
+ }
965
+
966
+ function countSuffix(count) {
967
+ if (typeof count !== 'number' || count <= 0) return ''
968
+ if (currentLanguage() === 'ru') {
969
+ const mod10 = count % 10
970
+ const mod100 = count % 100
971
+ const key = mod10 === 1 && mod100 !== 11
972
+ ? 'delete.count.one'
973
+ : mod10 >= 2 && mod10 <= 4 && (mod100 < 12 || mod100 > 14) ? 'delete.count.few' : 'delete.count.many'
974
+ return t(key, { n: count })
975
+ }
976
+ return t(count === 1 ? 'delete.count.one' : 'delete.count.many', { n: count })
977
+ }
978
+
979
+ function DeleteDialog({ dialog }) {
980
+ const [busy, setBusy] = React.useState(false)
981
+ const [error, setError] = React.useState(null)
982
+ const cancelRef = React.useRef(null)
983
+ React.useEffect(() => { cancelRef.current?.focus() }, [])
984
+ useEscape(() => { if (!busy) closeDialog() })
985
+ const isProject = dialog.target === 'workspace'
986
+ const name = dialog.title || t('icon.untitled')
987
+ const confirm = async () => {
988
+ setBusy(true)
989
+ setError(null)
990
+ const outcome = await runDelete(dialog)
991
+ if (outcome.error !== undefined) {
992
+ setError(outcome.error)
993
+ setBusy(false)
994
+ return
995
+ }
996
+ removeIcon(dialog.target === 'workspace' ? 'project' : 'chat', dialog.id)
997
+ clearItemColor(dialog.target === 'workspace' ? 'project' : 'chat', dialog.id)
998
+ closeDialog()
999
+ notify(outcome.text)
1000
+ }
1001
+ return h('div', { className: 'bnv-dialog', role: 'dialog', 'aria-modal': 'true', 'aria-label': t('delete.aria') },
1002
+ h('h2', null, t(isProject ? 'delete.project.title' : 'delete.chat.title')),
1003
+ h('p', null, isProject
1004
+ ? t('delete.project.body', { name, count: countSuffix(dialog.count) })
1005
+ : t('delete.chat.body', { name })),
1006
+ error === null ? null : h('p', { className: 'bnv-error', role: 'alert' }, error),
1007
+ h('div', { className: 'bnv-actions' },
1008
+ h('button', { ref: cancelRef, type: 'button', className: 'bnv-btn', disabled: busy, onClick: closeDialog }, t('delete.cancel')),
1009
+ h('button', { type: 'button', className: 'bnv-btn bnv-btn-danger', disabled: busy, onClick: confirm }, busy ? t('delete.busy') : t('delete.confirm'))))
1010
+ }
1011
+
1012
+ function Toast({ notice }) {
1013
+ React.useEffect(() => {
1014
+ const timer = setTimeout(() => update({ notice: null }), 5000)
1015
+ return () => clearTimeout(timer)
1016
+ }, [])
1017
+ return h('div', { className: 'bnv-toast', role: 'status' }, notice.text)
1018
+ }
1019
+
1020
+ function downscale(file) {
1021
+ return new Promise((resolve, reject) => {
1022
+ const reader = new FileReader()
1023
+ reader.onerror = () => reject(new Error('read'))
1024
+ reader.onload = () => {
1025
+ const image = new Image()
1026
+ image.onerror = () => reject(new Error('decode'))
1027
+ image.onload = () => {
1028
+ const limit = 64
1029
+ const scale = Math.min(1, limit / Math.max(image.width, image.height))
1030
+ const canvas = document.createElement('canvas')
1031
+ canvas.width = Math.max(1, Math.round(image.width * scale))
1032
+ canvas.height = Math.max(1, Math.round(image.height * scale))
1033
+ const context = canvas.getContext('2d')
1034
+ if (context === null) {
1035
+ reject(new Error('canvas'))
1036
+ return
1037
+ }
1038
+ context.drawImage(image, 0, 0, canvas.width, canvas.height)
1039
+ resolve(canvas.toDataURL('image/png'))
1040
+ }
1041
+ image.src = String(reader.result)
1042
+ }
1043
+ reader.readAsDataURL(file)
1044
+ })
1045
+ }
1046
+
1047
+ function workspaceSnapshot() {
1048
+ if (runtime === null) return undefined
1049
+ const workspaces = runtime.get('workspaces')
1050
+ if (workspaces === undefined || workspaces === null || workspaces.list === undefined) return undefined
1051
+ return workspaces.list.getSnapshot()
1052
+ }
1053
+
1054
+ function workspaceOf(workspaceId) {
1055
+ const snapshot = workspaceSnapshot()
1056
+ if (snapshot === undefined || !Array.isArray(snapshot.items)) return undefined
1057
+ return snapshot.items.find(item => item.workspaceId === workspaceId)
1058
+ }
1059
+
1060
+ async function runDelete(dialog) {
1061
+ if (runtime === null) return { error: t('delete.notActive') }
1062
+ const remote = runtime.get('remote')
1063
+ const sessions = runtime.get('sessions')
1064
+ if (remote === undefined || remote === null || sessions === undefined || sessions === null || sessions.list === undefined) {
1065
+ return { error: t('delete.offline') }
1066
+ }
1067
+ const list = sessions.list.getSnapshot()
1068
+ const receiver = list.ids.find(id => ((list.byId[id]?.retainedBy?.mainView) ?? 0) > 0)
1069
+ if (receiver === undefined) return { error: t('delete.needOpenChat') }
1070
+ if (dialog.target === 'session' && receiver === dialog.id) return { error: t('delete.openChat') }
1071
+ if (dialog.target === 'workspace') {
1072
+ const workspace = workspaceOf(dialog.id)
1073
+ if (workspace !== undefined && Array.isArray(workspace.sessionIds) && workspace.sessionIds.includes(receiver)) {
1074
+ return { error: t('delete.openProject') }
1075
+ }
1076
+ }
1077
+ const line = `/bnv-delete ${dialog.target === 'workspace' ? 'project' : 'session'} ${dialog.id} ${currentLanguage()}`
1078
+ try {
1079
+ const result = await remote.commands.execute(receiver, line, [])
1080
+ if (result === undefined || result === null || result.ok === false) {
1081
+ const message = result?.error?.message
1082
+ return { error: typeof message === 'string' && message.length > 0 ? message : t('delete.failed') }
1083
+ }
1084
+ const commandResult = result.value?.result
1085
+ if (commandResult?.kind === 'error') return { error: commandResult.text || t('delete.failed') }
1086
+ return { text: commandResult?.text || t('icon.done') }
1087
+ } catch (error) {
1088
+ return { error: String(error instanceof Error ? error.message : error) }
1089
+ }
1090
+ }
1091
+
1092
+ return {
1093
+ inject: ['slots', 'remote', 'remote.commands'],
1094
+ apply(ctx) {
1095
+ runtime = ctx
1096
+ const slots = ctx.get('slots')
1097
+ if (slots === undefined || slots === null) return
1098
+
1099
+ const setupLocale = (locale) => {
1100
+ if (locale === undefined || locale === null || localeService === locale) return
1101
+ localeService = locale
1102
+ try { locale.register('bnv-workspace', 'en', EN) } catch { /* already registered by an earlier generation */ }
1103
+ try { locale.register('bnv-workspace', 'ru', RU) } catch { /* already registered by an earlier generation */ }
1104
+ translate = locale.bind('bnv-workspace')
1105
+ ctx.effect(() => locale.subscribe(() => update({})), 'bnv-workspace: locale change')
1106
+ ctx.effect(() => {
1107
+ const workspaceT = locale.bind('workspace')
1108
+ const labelNode = () => {
1109
+ const header = document.querySelector('[data-sidebar-workspace-header]')
1110
+ if (header === null) return null
1111
+ const source = workspaceT('section.workspaces')
1112
+ if (typeof source !== 'string' || source.length === 0) return null
1113
+ for (const node of header.querySelectorAll('span')) {
1114
+ if (node.childElementCount === 0 && node.textContent === source) return node
1115
+ }
1116
+ return null
1117
+ }
1118
+ const applyLabel = () => {
1119
+ const label = labelNode()
1120
+ if (label === null) return
1121
+ const target = t('workspace.renamed')
1122
+ if (target !== workspaceT('section.workspaces')) label.textContent = target
1123
+ }
1124
+ const timer = setInterval(applyLabel, 300)
1125
+ applyLabel()
1126
+ return () => {
1127
+ clearInterval(timer)
1128
+ const label = labelNode()
1129
+ if (label === null) return
1130
+ if (label.textContent === t('workspace.renamed')) label.textContent = workspaceT('section.workspaces')
1131
+ }
1132
+ }, 'bnv-workspace: workspaces section label')
1133
+ }
1134
+ const localeNow = ctx.get('locale')
1135
+ if (localeNow !== undefined && localeNow !== null) setupLocale(localeNow)
1136
+ else {
1137
+ let attempts = 0
1138
+ const timer = setInterval(() => {
1139
+ const locale = ctx.get('locale')
1140
+ if (locale !== undefined && locale !== null) {
1141
+ clearInterval(timer)
1142
+ setupLocale(locale)
1143
+ } else if (++attempts >= 20) clearInterval(timer)
1144
+ }, 300)
1145
+ }
1146
+
1147
+ slots.inject('sidebar.brand.name', () => {
1148
+ let disposer = null
1149
+ const sync = () => {
1150
+ const want = store.topbar === 'compact'
1151
+ if (want && disposer === null) {
1152
+ try {
1153
+ disposer = slots.register({
1154
+ name: 'sidebar.brand.name', priority: -1,
1155
+ }, BrandCompactActions)
1156
+ } catch {
1157
+ disposer = null
1158
+ }
1159
+ } else if (!want && disposer !== null) {
1160
+ disposer()
1161
+ disposer = null
1162
+ }
1163
+ }
1164
+ listeners.add(sync)
1165
+ sync()
1166
+ return () => {
1167
+ listeners.delete(sync)
1168
+ if (disposer !== null) {
1169
+ disposer()
1170
+ disposer = null
1171
+ }
1172
+ }
1173
+ })
1174
+
1175
+ slots.inject('settings.launcher', () => {
1176
+ let disposer = null
1177
+ const sync = () => {
1178
+ const want = store.topbar === 'compact'
1179
+ if (want && disposer === null) {
1180
+ try {
1181
+ disposer = slots.register({ name: 'settings.launcher', priority: -1 }, SettingsLauncherCapture)
1182
+ } catch {
1183
+ disposer = null
1184
+ }
1185
+ } else if (!want && disposer !== null) {
1186
+ disposer()
1187
+ disposer = null
1188
+ }
1189
+ }
1190
+ listeners.add(sync)
1191
+ sync()
1192
+ return () => {
1193
+ listeners.delete(sync)
1194
+ if (disposer !== null) {
1195
+ disposer()
1196
+ disposer = null
1197
+ }
1198
+ }
1199
+ })
1200
+
1201
+ slots.inject('shell.overlay', () => slots.register({
1202
+ name: 'shell.overlay', id: 'bnv-overlay', order: 100,
1203
+ }, Overlay))
1204
+ slots.inject('settings.section', () => slots.register({
1205
+ name: 'settings.section', id: 'bnv-workspace-appearance', order: 35, label: () => t('settings.label'),
1206
+ }, SettingsSection))
1207
+ slots.inject('settings.section.icon', () => slots.register({
1208
+ name: 'settings.section.icon', id: 'bnv-workspace-appearance', order: 0,
1209
+ }, SectionIcon))
1210
+ slots.inject('sidebar.session.row.leading', () => slots.register({
1211
+ name: 'sidebar.session.row.leading', id: 'bnv-chat-icon', order: 10,
1212
+ }, ChatIcon))
1213
+ slots.inject('sidebar.session.action', () => slots.register({
1214
+ name: 'sidebar.session.action', id: 'bnv-compact-topbar', order: 0,
1215
+ }, NewSessionAction))
1216
+ slots.inject('sidebar.workspaces.session.menu.item', () => slots.register({
1217
+ name: 'sidebar.workspaces.session.menu.item', id: 'bnv-appearance-session', order: 850,
1218
+ }, SessionAppearanceItem))
1219
+ slots.inject('sidebar.workspaces.session.menu.item', () => slots.register({
1220
+ name: 'sidebar.workspaces.session.menu.item', id: 'bnv-delete-forever', order: 900,
1221
+ }, SessionDeleteItem))
1222
+
1223
+ const setupMenus = (attempt = 0) => {
1224
+ const menus = ctx.get('contextMenus')
1225
+ if (menus === undefined || menus === null) {
1226
+ if (attempt < 20) setTimeout(() => setupMenus(attempt + 1), 250)
1227
+ return
1228
+ }
1229
+ slots.inject('contextMenu.icon', () => slots.register({
1230
+ name: 'contextMenu.icon', key: 'bnv-workspace.appearance',
1231
+ }, Gear))
1232
+ slots.inject('contextMenu.icon', () => slots.register({
1233
+ name: 'contextMenu.icon', key: 'bnv-workspace.trash',
1234
+ }, Trash))
1235
+ ctx.effect(() => menus.register({
1236
+ id: 'bnv-workspace.row-actions',
1237
+ target: 'workspace',
1238
+ order: 680,
1239
+ resolve: (target) => {
1240
+ const workspace = workspaceOf(target.workspaceId)
1241
+ return [
1242
+ {
1243
+ id: 'bnv-appearance-workspace',
1244
+ label: t('menu.customize'),
1245
+ icon: { key: 'bnv-workspace.appearance' },
1246
+ run: () => requestIcon('project', target.workspaceId, target.displayTitle),
1247
+ },
1248
+ {
1249
+ id: 'bnv-delete-workspace',
1250
+ label: t('menu.delete'),
1251
+ icon: { key: 'bnv-workspace.trash' },
1252
+ separatorBefore: true,
1253
+ run: () => requestDelete(
1254
+ 'workspace',
1255
+ target.workspaceId,
1256
+ target.displayTitle,
1257
+ workspace?.sessionIds?.length,
1258
+ ),
1259
+ },
1260
+ ]
1261
+ },
1262
+ }), 'bnv-workspace: project menu')
1263
+ }
1264
+ setupMenus()
1265
+ },
1266
+ }
1267
+ },
1268
+ })