diff --git a/CHANGELOG.md b/CHANGELOG.md index d123b6da..f7fe5dd6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,13 @@ - 🪟 **桌面壳里开启沙箱的 HTML 预览不再空白(403)**:壳只给 origin 为 `dsh-app://app` 的子帧注入转发标记,沙箱 iframe 是不透明源,主文档导航直接被壳拒绝。现在顶层可信帧取回 HTML 与同源静态资源,内联成自包含文档后交给 sandboxed `blob:` iframe;相对 CSS/JS/图片/字体正常,iframe 仍无 `allow-same-origin`,浏览器与“关闭沙箱”路径不变。嵌套 iframe / Worker / 脚本运行时相对请求仍受壳限制。 - 🧪 测试:`tests/html-preview-frame.spec.tsx`、`tests/html-preview-inline.spec.ts`、`tests/sandbox-views.spec.tsx`、`test:mount` 的本地图片断言。 +- 🧭 **开始页由插件接管,支持两列自适应、可配置行数和「更多」收纳**:右侧栏展开时不再用宿主自带的单列卡片页。宽屏(≥520px)每行两张、窄屏一张;默认最多 6 行(可在设置中改为 ≥1 行),超出容量的入口收进「更多」卡片,菜单里可直接打开,也可打开「调整顺序」。开始页卡片点击后用新页面替换指南页,和宿主原行为一致。 + - 🧪 测试:`tests/guide-layout.spec.ts`(排序 / 隐藏 / 列数与容量 / More 占格 / 最小容量)、`tests/native-guide.spec.tsx`(卡片、More、终端 Shell 菜单、catalog 订阅、chain 注册与释放)。 +- 🗂 **设置里的「开始页」清单接管所有已注册到官方侧边栏的入口**:本插件、宿主终端和第三方 tab 都按 `providerId::entryId` 列出,默认显示;开关只隐藏开始页卡片,不注销 tab 类型,也不影响快捷键、资源打开或已打开页签。Better Sidebar 自己的功能开关语义不变。支持上移/下移和恢复默认顺序,排序持久化。 + - 🧪 测试:`tests/side-card-section.spec.tsx`(原生入口清单、默认开启、顺序与隐藏状态)、`tests/prefs.spec.ts`(行数 / 顺序 / 可见性校验)。 +- 🖥 **终端卡片保留原生 Shell 菜单**:开始页的终端卡片右侧有「…」,菜单通过宿主 `webTerminals.launchShells` 读取 Shell 列表,选择后写入宿主偏好并以该 Shell 打开终端;宿主没有这些能力时卡片退化为普通入口。其他第三方自定义开始页卡片组件无法在 chain 接管页中复用,会显示为通用卡片(原因见 `docs/host-contracts.md` §9)。 +- 🧪 挂载冒烟新增真实宿主断言:开始页由插件接管(`data-dsh-guide-grid`)、列数跟随面板宽度、终端卡片提供 Shell 菜单;现有 guide 选择器与条目断言保持不变。 + - 🐞 **GBK 文件里的欧元符号不再被写成 ICU 拒绝的单字节 `0x80`**:改用标准两字节 `0xA2E3`,修复 Node 24.21 / ICU 78 下保存后重开变乱码;新增字面量测试钉住编码与回读。 - 🧵 **fork 块改成默认折叠的原生 disclosure:折叠时只剩那条「分支前的主会话」分割线,展开才看到继承的问答**:`data-sidechat-fork-point` 现在是受控的 `
`(默认 closed),`` 就是开头那条分割线(`sideChatForkDivider` 文案 + 展开 chevron,不含任何继承正文),body 展开后仍是原顺序「提问 → 回答 → 结尾分割线」,没有回答时只有提问与结尾线;折叠/展开不改变转录行数,块内除 summary 外没有任何 `button` / `a`。 diff --git a/CHANGELOG_EN.md b/CHANGELOG_EN.md index b7a22f4a..90d46a0d 100644 --- a/CHANGELOG_EN.md +++ b/CHANGELOG_EN.md @@ -16,6 +16,13 @@ - 🪟 **A sandboxed HTML preview in the desktop shell no longer renders blank (403).** The shell injects its forwarding marker only into subframes whose origin is `dsh-app://app`; a sandboxed iframe is an opaque origin, so its main navigation is rejected before reaching the plugin. The trusted top frame now fetches the HTML and its same-origin static assets and frames a self-contained `blob:` document; relative CSS/JS/images/fonts work, the iframe still has no `allow-same-origin`, and the browser / explicitly-unsandboxed paths are unchanged. Nested iframes, Workers and relative requests made by previewed scripts at runtime remain subject to the shell's restriction. - 🧪 `tests/html-preview-frame.spec.tsx`, `tests/html-preview-inline.spec.ts`, `tests/sandbox-views.spec.tsx`, and the local-image assertion in `test:mount`. +- 🧭 **The start page is now plugin-owned, with a responsive two-column grid, a configurable row budget, and a More card for overflow.** Expanding the right sidebar no longer shows the host's single-column card page. Wide panes (>= 520px) put two cards on a row and narrow panes one; 6 rows by default (configurable to any value >= 1 in settings), and entries beyond the budget move into a More card whose menu opens them directly or opens "Reorder". Picking a card replaces the guide tab with the chosen page, exactly like the host did. + - 🧪 Tests: `tests/guide-layout.spec.ts` (ordering / visibility / columns and capacity / More occupancy / minimum capacity) and `tests/native-guide.spec.tsx` (cards, More, the terminal shell menu, catalog subscription, chain registration and release). +- 🗂 **The settings "Start page" inventory now covers every entry registered with the official sidebar.** Plugin tabs, the host terminal, and third-party tabs are listed by `providerId::entryId`, visible by default; a switch only hides the start-page card and never unregisters a tab type, affects shortcuts, resource opens, or already-open tabs. Better Sidebar's own feature switches keep their meaning. Move up/down and reset order are supported and persisted. + - 🧪 Tests: `tests/side-card-section.spec.tsx` (native inventory, default-on, order and visibility) and `tests/prefs.spec.ts` (rows / order / visibility validation). +- 🖥 **The terminal card keeps its native shell menu.** The start page's terminal card has a "..." trigger whose menu reads the shell list through the host's `webTerminals.launchShells`, remembers the choice through the host, and opens the terminal with that shell; without those host capabilities the card degrades to a plain entry. Other third-party custom start-page card components cannot be reused inside a chain takeover and render as generic cards (see `docs/host-contracts.md` §9 for why). +- 🧪 The mount smoke lane now asserts the real host: the plugin-owned start page (`data-dsh-guide-grid`), a column count that follows the pane width, and the terminal shell menu; all existing guide selectors and entry assertions stay unchanged. + - 🐞 **The euro sign in a GBK file is no longer written as the single byte `0x80` that current ICU rejects**: it uses the canonical two-byte `0xA2E3` spelling, so saving and reopening no longer produces mojibake on Node 24.21 / ICU 78; a literal encoding/decoding test pins it. - 🧵 **The fork point is a native disclosure, collapsed by default: one "Before the fork" divider line until the reader expands it.** `data-sidechat-fork-point` is a controlled `
` (closed on first render), its `` IS the opening divider (`sideChatForkDivider` copy plus the expand chevron, no inherited text at all), and the body still reads question → answer → closing divider; with no answer it is the question and the closing divider only. Collapsing or expanding changes no transcript row, and the block holds no `button` / `a` beyond the summary. diff --git a/docs/external-plugin-guide.md b/docs/external-plugin-guide.md index 54d334df..6d5a8168 100644 --- a/docs/external-plugin-guide.md +++ b/docs/external-plugin-guide.md @@ -42,6 +42,7 @@ | 底部终端的恢复语义(#774) | 刷新后重新上屏同一页签时,页面用**同一份 `(sessionId, key, contentId)`** 再次调用宿主的 `webTerminals.view()`:宿主持久化在 localStorage 的 `(sessionId, contentId) → 终端 id` 绑定因此把**同一个** PTY 认回来(`contentId` 是 `dsh-better-sidebar:terminal-bottom:`——**每个页签一个实例,不再是恒定值**,#926)。插件**不把 terminalId 写进 `tab.meta`**:`view()` 显式传 terminalId 会关掉宿主的「缺了就建」分支,一个过期的 id 会把页签永久卡在 `missingTerminal` 上。DSH 重启后 PTY 全没了而 localStorage 绑定还在,所以「新建终端」按钮把 `tab.meta.terminalRun` +1 换一代 `contentId`,让宿主另铸一个进程,而不是反复认领死绑定 | | 底部工作台的开合 | 落到底部工作台的打开一律展开它(新建与聚焦都算),因此 `openTab` 的落点永远可见;开合按钮注册在 DSH 会话头的 utilities 槽(`conversation.session.header.utilities`),不在插件自己的宿主里 | | 在侧边打开(`target: 'side'`,v0.22.0+) | 原生栏里的 tab **不在插件底部工作台的分栏树里**,所以「在侧边打开」不能写 `bottomSplits`(那样会落到用户没展开的底部工作台 = 点了没反应)。服务改为把这一步交给宿主:带 path 的 `editor` seed 走 `openResource(address, { preferNewPane: true, revealIfOpened: false })`——宿主先按自己的两格上限与空间规则尝试分栏,分不了才回退到当前格;`revealIfOpened: false` 允许与已打开的同名资源并存,因此对同一个文件再点一次也会新开一格。其余类型若传 `target: 'side'`,同样以 `preferNewPane` 落原生栏(组件型 tab 的 path 仍是组件种子)——**唯一的例外是 `bottomOnly` 类型**(#774):它没有原生承载面可落,`target: 'side'` 被改道回 `'bottom'`。path-less 的 `editor`(文件页)与 `'bottom'` 行为不变 | +| 开始页接管(v0.31 起) | 插件在 `sidebar.right.tab.guide` 注册一个恒选中的 chain 条目,自己绘制开始页:宽屏每行两张、窄屏一张,行数可配置(默认 6,最小 1),超出容量的卡片收进「更多」。设置页「侧边栏内容 → 开始页」列出**当前注册到官方的全部开始页入口**(本插件、宿主终端、第三方),默认全部显示;开关只隐藏开始页卡片,不注销 tab 类型。排序按 `providerId::entryId` 持久化。**第三方 guide 条目仍会出现,但其自定义卡片组件不会被复用**:`sidebar.right.tab.guide.entry` 由宿主 guide body 独占声明,chain 条目拿不到 `renderSlot`。当前官方只有终端的 TerminalGuide 是自定义卡片,插件通过 `ctx.webTerminals.launchShells` / `selectShell` 复刻其 Shell 菜单;其他自定义卡片显示为通用卡片。宿主 `MAX_DESCRIBED_ENTRIES` 的描述隐藏逻辑不再适用,插件卡片始终显示描述。 | 新建标签页列表 | 每个 tab 类型在原生 guide 里占一行:标题取 `title` + 图标取 `icon`(缺图标时宿主补一个方块占位),说明取可选的 `description`——**宿主只在 guide 列出的条目 ≤ 4 条时渲染说明**(上游 `MAX_DESCRIBED_ENTRIES = 4`),更长的列表整列丢掉所有说明;未声明 `description` 的条目渲染成单行「图标 + 标题」(rc.1 起 `description` 回到宿主契约,但**宿主与插件都没有兜底句**,所以插件恢复字段而不恢复旧的通用句);`hidden: true` 的类型不占行,**`bottomOnly: true` 的类型同样不占行**(#774:它只活在插件自己的底部 `+` 菜单里)。插件的 `editor` 类型不再单独占行(它认领的文件资源由 `files` 接管页承载同一视图)。**本插件默认贡献 4 个 guide 条目**(文件 / Git / 任务管理 / 侧边对话,恰好在上限内),**但宿主的终端条目也占一行**——装了宿主终端即是 5 条,说明整列不渲染;要让说明回来,需在插件设置页关掉足够多的 tab 类型把总数压到 ≤ 4 条 | | 新建面板的种子(alpha.2) | 在新会话打开原生新面板时,宿主从已注册的 guide 条目里播种:恰好 1 个条目 → 直接打开那一页;0 或 ≥2 个条目 → 打开指南。`revealIfOpened` 打开的「页面」在**同一 pane 内**强制去重(已在该 pane 就不再新建);由已有 tab 地址驱动的打开不受该去重影响 | | alpha.2 全局面板(不接入) | 插件**不采用** alpha.2 引入的全局主面板模型——根级 keyed `main` 槽(预留 key `conversation`,由 ui-conversation 注册为 `main.conversation`)、根级 `sidebar.panellist` 列表槽(`SidebarPanelMetadata` / `SidebarPanelIconOwnerProps`)、`ctx.layout.selectPanel(MainPanelId|null)` / `beginNavigation()` / `dispose()`、全局标准 prop `usePanelInfo`,以及改根级并新增会话级 `rightbar.session` 子槽的 `rightbar`——这些只作兼容保留,不向其迁移 | diff --git a/docs/host-contracts.md b/docs/host-contracts.md index 110ca474..79d43ecf 100644 --- a/docs/host-contracts.md +++ b/docs/host-contracts.md @@ -42,6 +42,8 @@ - `tab.visible` 语义是 `active && (...)`(全局面板 / 后台会话时 body 不挂载);持久化校验也收紧(非根 / 列轴 / 嵌套 / 3+ docked pane 的 split 一律判非法**整份丢弃**)。全局面板(根级 `main` keyed 槽 + `sidebar.panellist` + `ctx.layout.selectPanel/beginNavigation`、`rightbar` 改根级并新增 `rightbar.session`)插件**不接入**,只做兼容。底部工作台的中心列锚点认 `[data-slot="main.conversation"]`(并跳过 `display: contents` 祖先,同时保留 `[data-slot="conversation"]`)。原生 tab 体宿主 `.paneBody` 是**有确定高度的块级滚动容器**(非 flex 容器),native 适配层因此给每个 tab 体包一层 `height:100%` 的列 flex 宿主(`sidebar.module.css` 的 `.nativeTabHost`),tab 组件根继续用 `flex:1` / `height:100%`。 - **原生注册账本的两条不变量**(`tests/native-registration.spec.ts` 守护):① `live` 里同时装着描述符类型(键 = descriptor id)与 `files` 接管(键 = `FILES_KIND`,**永远不在 `wanted` 里**),清理循环必须**跳过 `FILES_KIND`**——它只由编辑器类型的 `wantsFiles/hasFiles` 开关分支与 seat disposer 管理;否则每次通知都会把它拆掉再重建,而 teardown 期间的那次重建会把 id 孤儿化:`tabs.register` 建在**宿主** ctx 上(宿主 ctx 此时仍活着)所以照样成功,紧随的 `ctx.slots.inject` 建在**插件** ctx 上却抛 `cannot create effect on inactive context`,`live.set` 永不执行 → 该 id 在整页生命周期内不可再注册(真机表现:`native register files error: … already registered` 刷屏 + 文件树落到宿主空态,只有刷新页面才恢复;实证见 [docs/plans/2026-09-28-native-files-takeover-reload-leak.md](plans/2026-09-28-native-files-takeover-reload-leak.md))。② 因此「注册成功一半」是**可达状态**:任何在宿主取走 id **之后**失败的注册(槽位注册抛错等)必须**回滚释放该 type** 并释放已经建好的槽位,插件侧只留一个下次通知可以重试的失败,绝不留下无处释放的 id。相关断言必须写在注册表的**事件日志**上而不是「活着的 id 集合」上:孤儿 id 会让键集合看起来完全正常,键集合断言在未修复代码上同样通过。 - **原生 tab 的状态保留(已采纳 `keepMounted: true`)**:宿主因此把访问过的 body 挂住,同会话切 tab 不再卸载,组件态(树滚动、未保存草稿、chip 重命名)随之免费保留,**不需要**任何 module-level 记忆。三条必须同时成立的配套事实:(a) **记录不能随卸载删除**(只由 `surface.close` 与「会话消失」回收),而「切回会话清零」那一路(真机日志里 `DISPOSE type …:files` → `register`、同键 `drop`+`mint`)已由上面的 `FILES_KIND` 守卫挡掉(真机 e2e 现断言跨会话 `scrollTop` 复原);(b) 原生 tab id **每会话各自计数**(`tab1`…)且多会话同号并存,记录与写面一律按 `sessionId::tabId` 记账,`Surface.update/has/activate` 的 `sessionId` 缺省按 `sidebarRight.mounted` 解析,多会话同名时**拒绝而不是猜**;(c) **展开集的权威在插件 store 的会话状态里**(`attachStore` + `syncExpanded` + `getSessionStates().expanded`,由 `native/index.ts` 绑定),记录只负责**身份**与投影——两套持久化会互相打架,插件不自持「每记录的展开集」。设计过程与实测见 [docs/plans/2026-09-25-native-tab-state-retention-keepmounted.md](plans/2026-09-25-native-tab-state-retention-keepmounted.md)。 + - **开始页接管(v0.31 起)**:插件注册 `sidebar.right.tab.guide` 的 chain 条目并恒选中,替换宿主 `GuideBody` 的卡片页;每个卡片保留 `data-sidebar-right-guide` / `data-sidebar-right-guide-entry` 选择器,另加 `data-dsh-guide-grid` 供真实宿主验收。chain 条目**无法**取得 `sidebar.right.tab.guide.entry` 的 `renderSlot`:该槽由宿主的 guide body 独占声明(一个 child key 只能有一个 declarer),所以宿主/第三方注册的自定义卡片组件不能在插件页面里复用。当前官方只有终端的 TerminalGuide 是自定义卡片,插件通过公开的 `ctx.webTerminals.launchShells` / `selectShell` 复刻其 Shell 菜单;其他自定义卡片降级为通用卡片。宿主 guide 的 compass hero、pin/More 行为与 `MAX_DESCRIBED_ENTRIES` 描述隐藏逻辑随接管失效,由插件自己的行数/可见性/排序取代。 + 10. **自定义种子必须带 fork 标记对(`meta.isSeeded: true` + `inheritedEventCount`),且 create 后必须 `inbox.clear()`、冷恢复必须按 id 精确清扫——标记对必要但不充分**:dsh-session 契约规定「只给 seed 不标 isSeeded,种子算重放历史而非继承前缀」——缺标记时 `Session.ownEvents()` 含整个种子,子会话的 inbox 折重放种子里的 `agent/inbox/spliced`,**继承父会话切割时刻未领取的 inbox 输入**。**但运行时 inbox 不走 `ownEvents()`**:`ReactLoopInbox.current()` → `ctx.sessionProjections.stateOf()` → `SessionProjectionRegistry.cellFor` 折的是 `snapshotEvents()` **全量日志(含继承种子前缀)**,且标准 inbox 投影的 `init` 忽略 `inheritedEventCount`、注册表 `session/created` 急切初始化跳过一切种子会话(seq ≠ 0)——种子里的 `agent/inbox/spliced` 会原样重放进子会话 live inbox。因此 sidechat 宿主 `agents.create` 成功后、任何 inject/followup 之前必须 `handle.agent.inbox.clear()`(durable 补偿 splice 是 own 事件,冷恢复折存储日志同样归零)。**幽灵的来源比「父会话排队」更宽**:父会话 mid-turn 且工具有未返回调用时,种子被截断在 `turn/start` 之前,而 inbox 的「领取」splice 发生在 `turn/start` **之后** → **父会话本轮开头已领取的输入**在种子折叠里仍是 pending;`clear()` 是唯一能一次清干净的硬围栏(create 时本线程自己不可能有排队输入)。**冷恢复不能沿用 `clear()`**(会误杀「用户在线程里排队、宿主重启后尚未领取」的合法输入):改为 `dropInheritedGhosts`——`inheritedPendingIds(log, inheritedEventCount)` 只折继承前缀得到幽灵 id 集合,再逐个 `agent.inbox.remove(id)`,精确且幂等(`src/sidechat-core.ts` 纯函数,`tests/sidechat-core.spec.ts` / `tests/sidechat-routes.spec.ts` 守护)。宿主 `session.fork`(api-session-controller)的调用即规范形态(注意:宿主自己的 `fork` **没有**这一步补偿,同窗口有同样的暴露面);回归由 `tests/sidechat-seed-validation.spec.ts`(真实 `Session.create` + 对 `ownEvents()` 跑 inbox 折 + **真实 `SessionProjectionRegistry`** 折全量日志钉住上游洞与 clear 补偿)守护。**压缩种子的重编号必须连绝对 seq 引用一起重映射**:`session-log-deepseek/delivery-accepted` 的 `throughSeq` 是绝对 seq,v4 读取器要求它早于自己的标记(`delivery throughSeq must precede its marker`),漏映射会让子会话日志永久不可读、连带父会话 `includeDescendants` 导出失败(#1109);水位线落在被丢弃区间时整条记录丢弃(`src/sidechat-core.ts` 的 `rebaseEvent`,`tests/sidechat-compaction-seed.spec.ts` 守护)。**模型选择同为 agent 作用域**:`sidechat.model` 必须同时落 `session.append('model/selection', …)`(宿主 `selectForNextRequest` 的同一形状)与 `installModelSelection(agent.ctx, ref)`(`@deepseek-ai/dsh-agent` 公开导出),否则控制器缓存的 per-agent selection 永不回读投影;resume 后也要按日志里的有效选择重装(`src/sidechat-routes.ts` 的 `ensureModelSelection`)。**上游 0.2.0 新增的 `buildForkSeed` 与本插件手工的 `buildSidechatInheritance` 职责重叠,但收益不明确**(插件另有 dangling-tool-call 退回结构化快照的自有需求),暂不替换。 11. **`dsh.plugin.json` 从来不是 DSH 契约**(全树 grep 0 命中):DSH 真正读的是 `package.json` 的 `dsh.bundle.patch` + `dsh.client`(`platform`/`inject`/`immediately`/`external`)+ `exports["./client"]`。`dsh.plugin.json` 与 `lib/client-registry.js` 只服务第三方 registry(社区市场)通道,`tests/manifest-consistency.spec.ts` 守护的是这条通道的形状,不是 DSH 契约。**不要混淆两个 manifest 的 `engines.dsh`**:当前宿主的兼容性检查优先读取 `package.json#engines.dsh`,存在时由它独立裁决;本插件未声明此字段,仍由 14 条 DSH peer 决定兼容性。`dsh.plugin.json#engines.dsh` 只是第三方 registry 元数据,不能替代 package 字段;`dsh.manifestVersion` 也不是版本兼容性开关。`dsh.bundle.patch` 有形状校验(非法值会 `throw`,引导期跳过该 bundle),本插件是合法的单字符串。 **插件展示元数据**(Plugins 页与 `plugin_manager` 列表,v0.21.1 起已采纳)三条硬规则:`package.json#icon` 必须是**包内相对路径**且写进 `files`(36×36、纯填充无描边、**双色渐变**——与 DSH 自带 `PluginArtwork*` 同风格,单色版在 30px 行内尺寸下会读成一块纯色板);`locale/en.json` 是发现基线(缺它整个目录都不读,`meta.title` / `description` 在这里);`exports` 必须暴露 `./locale/*.json` 与 `./package.json`。**所有失败都是静默的**——元数据有问题只会退化成一行纯文字,没有任何报错;`tests/plugin-meta.spec.ts` 守护「声明了就必须发布出去」。plugin-manager 侧另有**多 registry 回退**(配置源 → `fallbackRegistries`,默认含 `registry.npmmirror.com`;`network`/`timeout`/`not-found`/`no-matching-version` 会自动问下一个源;`registry` 入参只存在于 Web 对话框与 `plugin_manager` 工具,**CLI 没有 registry flag**)。 diff --git a/src/client/SideCardSection.module.css b/src/client/SideCardSection.module.css index 42c64e94..29bdd383 100644 --- a/src/client/SideCardSection.module.css +++ b/src/client/SideCardSection.module.css @@ -71,6 +71,57 @@ color: var(--dsw-alias-label-primary); } +/* A one-line explanation inside a group card. */ +.groupHint { + margin: 0; + padding: 0 2px 4px; + color: var(--dsw-alias-label-tertiary); + font-size: 12px; + line-height: 18px; +} + +/* The start-page order list's header: section label plus the reset action. */ +.guideOrderHeader { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + padding: 8px 2px 2px; + color: var(--dsw-alias-label-secondary); + font-size: 12px; + line-height: 18px; + font-weight: 600; +} + +.guideReset { + padding: 2px 8px; + border: 1px solid var(--dsw-alias-border-l2); + border-radius: 6px; + background: transparent; + color: var(--dsw-alias-label-secondary); + font: inherit; + font-size: 11px; + cursor: pointer; +} + +.guideReset:hover { + background: var(--dsw-alias-interactive-bg-hover); + color: var(--dsw-alias-label-primary); +} + +.guideReset:focus-visible { + outline: 2px solid var(--dsw-alias-border-l4); + outline-offset: 2px; +} + +.guideEmpty { + margin: 0; + padding: 12px 2px; + color: var(--dsw-alias-label-tertiary); + font-size: 12px; + line-height: 18px; +} + /* The inventory count: a soft-accent pill (the versionBadgeTag token recipe) so the count reads as metadata, not as part of the heading text. */ .count { @@ -347,64 +398,6 @@ color: var(--dsw-alias-label-tertiary); } -/* Custom switch: a real checkbox (native semantics + focus, visually - hidden) driving a styled 36x20 track with a sliding thumb. */ -.switch { - position: relative; - display: inline-flex; - flex: none; - cursor: pointer; -} - -.switchInput { - position: absolute; - width: 1px; - height: 1px; - margin: 0; - opacity: 0; -} - -.switchTrack { - display: inline-flex; - align-items: center; - width: 36px; - height: 20px; - padding: 2px; - box-sizing: border-box; - border-radius: 10px; - border: 1px solid var(--dsw-alias-border-l2); - background: var(--dsw-alias-bg-layer-2); - transition: background 0.15s ease, border-color 0.15s ease; -} - -.switchThumb { - display: block; - width: 14px; - height: 14px; - border-radius: 50%; - background: var(--dsw-alias-label-tertiary); - transition: transform 0.15s ease, background 0.15s ease; -} - -.switch:hover .switchTrack { - border-color: var(--dsw-alias-label-dimmed); -} - -.switchInput:checked + .switchTrack { - border-color: var(--dsw-alias-button-primary-fill); - background: var(--dsw-alias-button-primary-fill); -} - -.switchInput:checked + .switchTrack .switchThumb { - transform: translateX(16px); - background: var(--dsw-alias-bg-layer-3); -} - -.switchInput:focus-visible + .switchTrack { - outline: 2px solid var(--dsw-alias-state-business-primary); - outline-offset: 2px; -} - .control { flex: none; display: flex; @@ -843,9 +836,7 @@ .cardSettings, .cardSwitchTrack, .cardSwitchThumb, - .popupRow, - .switchTrack, - .switchThumb { + .popupRow { transition: none; } } diff --git a/src/client/SideCardSection.tsx b/src/client/SideCardSection.tsx index c25cd3c3..6e9eb3ec 100644 --- a/src/client/SideCardSection.tsx +++ b/src/client/SideCardSection.tsx @@ -44,7 +44,7 @@ * shows the wire error inline — a broken settings surface never crashes the * shell. */ -import { Fragment, useEffect, useRef, useState, type ReactNode } from 'react' +import { Fragment, useEffect, useRef, useState, useSyncExternalStore, type ReactNode } from 'react' import { IconChevronDownOutlineRegular, IconPlusOutlineRegular, @@ -58,11 +58,15 @@ import clsx from 'clsx' import type {} from '@deepseek-ai/dsh-client-ui-settings/client' import type { PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' import type { SidebarPrefs } from '../prefs-shared.ts' +import { Switch } from './Switch.tsx' import { api } from './api.ts' import { parsePrefs } from './prefs.ts' import { AddPluginModal, type PluginKind } from './add-plugin-modal.tsx' import { t } from './locales.ts' import type { SidebarStore } from './state.ts' +import type { NativeGuideCatalog, NativeGuideEntry } from './native/guide-catalog.ts' +import { orderGuideEntries } from './native/guide-layout.ts' +import { GuideOrderList } from './native/guide-order.tsx' import type { BetterSidebarService, FileViewerDescriptor, @@ -76,6 +80,8 @@ import css from './SideCardSection.module.css' export interface SideCardSectionInjected { store: SidebarStore service: BetterSidebarService + /** Live host guide cards; absent in harness renders that do not mount the start page. */ + guideCatalog?: NativeGuideCatalog } /** Full section props: the runtime share plus the injected face. */ @@ -114,6 +120,10 @@ function tabInventory(tabs: readonly TabDescriptor[]): TabDescriptor[] { return tabs.filter(tab => tab.hidden !== true).sort((a, b) => (a.order ?? 100) - (b.order ?? 100)) } +/** An empty, reference-stable guide inventory for harness renders without a catalog. */ +const EMPTY_GUIDE_ENTRIES: readonly NativeGuideEntry[] = [] +const NOOP_SUBSCRIBE = (): (() => void) => () => {} + /** Viewer inventory order: priority desc (the catch-all `code` comes last). */ function viewerOrder(a: FileViewerDescriptor, b: FileViewerDescriptor): number { return (b.priority ?? 0) - (a.priority ?? 0) @@ -174,33 +184,6 @@ function SettingsRender(props: { return <>{content} } -/** - * The custom switch: a real checkbox (hidden, native semantics and focus) - * driving a styled track/thumb. Used by the general toggle rows and the - * secondary settings popup rows. - */ -function Switch(props: { - checked: boolean - onChange: (next: boolean) => void - label: string -}) { - const { checked, onChange, label } = props - return ( - - ) -} - /** * The body of a feature's secondary settings popup: one row (title/desc + * control) per declared setting. Switches render the custom switch; text and @@ -656,7 +639,7 @@ export function SettingsBody(props: { * @param props - composed slot props (runtime share + injected store/service). * @returns the section element tree. */ -export function SideCardSection({ store, service }: SideCardSectionProps) { +export function SideCardSection({ store, service, guideCatalog }: SideCardSectionProps) { const [prefs, setPrefs] = useState(() => store.getPrefs()) const [error, setError] = useState(null) // Which feature's secondary settings popup is open (null = closed). @@ -684,6 +667,16 @@ export function SideCardSection({ store, service }: SideCardSectionProps) { setViewers([...service.getFileViewers()].sort(viewerOrder)) }), [service]) + // The host's registered guide cards: the start-page inventory. The catalog + // is optional so harness renders (and a host without the native surface) + // simply see no start-page rows. + const subscribeGuide = guideCatalog?.subscribe ?? NOOP_SUBSCRIBE + const snapshotGuide = guideCatalog === undefined + ? () => EMPTY_GUIDE_ENTRIES + : () => guideCatalog.getSnapshot() + const guideEntries = useSyncExternalStore(subscribeGuide, snapshotGuide, snapshotGuide) + const orderedGuide = orderGuideEntries(guideEntries, prefs.guideOrder) + // The settings document revision (guards concurrent writes). A ref: commits // read the freshest value at execution time, no re-render needed. const revisionRef = useRef(undefined) @@ -757,6 +750,35 @@ export function SideCardSection({ store, service }: SideCardSectionProps) { applyPref({ viewersEnabled: { ...optimisticRef.current.viewersEnabled, [id]: next } }) } + /** Hide/show one start-page card without touching its tab type. */ + const onToggleGuide = (key: string, shown: boolean): void => { + const next = { ...optimisticRef.current.guideHidden } + if (shown) delete next[key] + else next[key] = true + applyPref({ guideHidden: next }) + } + + /** Move one card within the current explicit order. */ + const onMoveGuide = (key: string, delta: -1 | 1): void => { + const keys = orderedGuide.map(entry => entry.key) + const at = keys.indexOf(key) + const to = at + delta + if (at < 0 || to < 0 || to >= keys.length) return + const next = [...keys] + const [moved] = next.splice(at, 1) + if (moved === undefined) return + next.splice(to, 0, moved) + applyPref({ guideOrder: next }) + } + + /** Commit the maximum row count; an invalid value restores the stored one. */ + const commitGuideRows = (raw: string, input: HTMLInputElement): void => { + const parsed = Number(raw) + const next = Number.isSafeInteger(parsed) && parsed >= 1 ? parsed : prefs.guideRows + if (next !== prefs.guideRows) applyPref({ guideRows: next }) + input.value = String(next) + } + /** Flip one declaratively-declared toggle (a SidebarPrefs boolean field). */ const onToggleSetting = (toggle: SidebarSettingToggle, next: boolean): void => { applyPref({ [toggle.key]: next }) @@ -1006,6 +1028,55 @@ export function SideCardSection({ store, service }: SideCardSectionProps) { + {/* 开始页: the host guide's inventory. These switches control the start + page only — the feature cards above still own availability. */} +
+
+ {t('settingsStartPageTitle')} + {orderedGuide.length} +
+

{t('settingsStartPageDesc')}

+
+ + {t('settingsGuideRowsTitle')} + {t('settingsGuideRowsDesc')} + + { commitGuideRows(event.currentTarget.value, event.currentTarget) }} + onKeyDown={(event) => { + if (event.key === 'Enter') event.currentTarget.blur() + }} + /> +
+
+ {t('guideOrder')} + +
+ {orderedGuide.length === 0 + ?

{t('guideEmpty')}

+ : ( +
+ {/* 文件预览: one small card per registered file viewer. */}
diff --git a/src/client/Switch.module.css b/src/client/Switch.module.css new file mode 100644 index 00000000..829cbc50 --- /dev/null +++ b/src/client/Switch.module.css @@ -0,0 +1,64 @@ +/* Custom switch: a real checkbox (native semantics + focus, visually hidden) + driving a styled 36x20 track with a sliding thumb. */ +.switch { + position: relative; + display: inline-flex; + flex: none; + cursor: pointer; +} + +.switchInput { + position: absolute; + width: 1px; + height: 1px; + margin: 0; + opacity: 0; +} + +.switchTrack { + display: inline-flex; + align-items: center; + width: 36px; + height: 20px; + padding: 2px; + box-sizing: border-box; + border-radius: 10px; + border: 1px solid var(--dsw-alias-border-l2); + background: var(--dsw-alias-bg-layer-2); + transition: background 0.15s ease, border-color 0.15s ease; +} + +.switchThumb { + display: block; + width: 14px; + height: 14px; + border-radius: 50%; + background: var(--dsw-alias-label-tertiary); + transition: transform 0.15s ease, background 0.15s ease; +} + +.switch:hover .switchTrack { + border-color: var(--dsw-alias-label-dimmed); +} + +.switchInput:checked + .switchTrack { + border-color: var(--dsw-alias-button-primary-fill); + background: var(--dsw-alias-button-primary-fill); +} + +.switchInput:checked + .switchTrack .switchThumb { + transform: translateX(16px); + background: var(--dsw-alias-bg-layer-3); +} + +.switchInput:focus-visible + .switchTrack { + outline: 2px solid var(--dsw-alias-state-business-primary); + outline-offset: 2px; +} + +@media (prefers-reduced-motion: reduce) { + .switchTrack, + .switchThumb { + transition: none; + } +} diff --git a/src/client/Switch.tsx b/src/client/Switch.tsx new file mode 100644 index 00000000..55a8a34d --- /dev/null +++ b/src/client/Switch.tsx @@ -0,0 +1,29 @@ +/** + * The shared on/off switch: a real checkbox (native semantics and focus) + * driving a styled track/thumb. Used by the settings rows and the start-page + * order list. + */ +import css from './Switch.module.css' + +/** One labelled switch. */ +export function Switch(props: { + checked: boolean + onChange: (next: boolean) => void + label: string +}) { + const { checked, onChange, label } = props + return ( + + ) +} diff --git a/src/client/index.tsx b/src/client/index.tsx index fca3bed1..7b06e92d 100644 --- a/src/client/index.tsx +++ b/src/client/index.tsx @@ -20,6 +20,7 @@ import { Sidebar } from './Sidebar.tsx' import { RenderBoundary } from './RenderBoundary.tsx' import { createNativeTabRecords } from './native/tab-adapter.tsx' import { registerNativeSurface } from './native/index.ts' +import { createNativeGuideCatalog } from './native/guide-catalog.ts' import { registerBottomToggle } from './sidebar/bottom-toggle.tsx' import { ContextDiagnosticsHost, createContextDiagnosticsHost, registerContextDiagnosticsUI } from './context-diagnostics-ui.tsx' import { createNativeSurface } from './native/surface.ts' @@ -179,6 +180,11 @@ export function apply(ctx: Context): void { // right column belongs to the host and only the bottom workbench stays // plugin-owned. Both halves live for this fiber's lifetime. const nativeRecords = createNativeTabRecords() + // One live catalog of host guide cards, shared by the start-page takeover + // and the settings inventory. It subscribes to the host tab registry and is + // released with this activation. + const nativeGuide = createNativeGuideCatalog(ctx) + ctx.effect(() => () => { nativeGuide.dispose() }, 'dsh-better-sidebar: native guide catalog') const nativeSurface = createNativeSurface(ctx, nativeRecords) service.setSurface(nativeSurface) // The optional dsh-context diagnostics: ONE controller per activation. It @@ -192,6 +198,7 @@ export function apply(ctx: Context): void { ctx.effect( () => registerNativeSurface({ ctx, store: sidebarStore, service, records: nativeRecords, diagnostics, + guideCatalog: nativeGuide.catalog, reportFailure: (phase, error) => { fail(`native ${phase}`, error) }, }), 'dsh-better-sidebar: native right-Sidebar registrations', @@ -487,7 +494,7 @@ export function apply(ctx: Context): void { id: 'better-sidebar', order: 100, label: () => t('settingsNav'), - inject: () => ({ store: sidebarStore, service }), + inject: () => ({ store: sidebarStore, service, guideCatalog: nativeGuide.catalog }), }, SideCardSection)) } catch (error) { fail('load', error) diff --git a/src/client/locales-ar.ts b/src/client/locales-ar.ts index 050bc38a..075bc7d8 100644 --- a/src/client/locales-ar.ts +++ b/src/client/locales-ar.ts @@ -380,6 +380,17 @@ export const ar: Record = { settingsShellArgsDesc: 'وسائط صدفة صريحة، مفصولة بمسافات؛ عند عدم الفراغ تستبدل الافتراضيات بالكامل (نفس عقد yaml shellArgs)', settingsShellArgsPlaceholder: 'مثل -l (فارغ = الافتراضيات)', settingsTabsTitle: 'محتوى الشريط الجانبي', + settingsStartPageTitle: 'صفحة البدء', + settingsStartPageDesc: 'اضبط صفوف البطاقات والرؤية والترتيب لصفحة البدء؛ هذه المفاتيح تؤثر على مدخلات صفحة البدء فقط', + settingsGuideRowsTitle: 'الحد الأقصى للصفوف', + settingsGuideRowsDesc: 'بطاقتان في الصف على اللوحة العريضة وبطاقة واحدة على الضيقة؛ البطاقات الزائدة تنتقل إلى «المزيد». الافتراضي 6 صفوف، والحد الأدنى 1', + settingsGuideShow: 'إظهار في صفحة البدء', + settingsGuideReset: 'إعادة الترتيب الافتراضي', + guideMore: 'المزيد', + guideOrder: 'تغيير الترتيب', + guideEmpty: 'لا توجد صفحات للعرض', + guideShellEmpty: 'لا توجد أوامر shell متاحة', + guideShellFailed: 'تعذر تحميل أوامر shell: {error}', settingsViewersTitle: 'عارضات الملفات', settingsMobileTitle: "الجوال", settingsMobileNoAutoOpenTitle: "عدم الفتح التلقائي على الشاشات الضيقة", diff --git a/src/client/locales-de.ts b/src/client/locales-de.ts index 908a8a62..f870f299 100644 --- a/src/client/locales-de.ts +++ b/src/client/locales-de.ts @@ -365,6 +365,17 @@ export const de: Record = { settingsShellArgsDesc: 'Explizite Shell-Startargumente, durch Leerzeichen getrennt; wenn nicht leer, ersetzen sie die Standardargumente vollständig (gleicher Vertrag wie shellArgs in der yaml)', settingsShellArgsPlaceholder: 'z. B. -l (leer = Standardargumente)', settingsTabsTitle: 'Seitenleisten-Inhalt', + settingsStartPageTitle: 'Startseite', + settingsStartPageDesc: 'Kartenzeilen, Sichtbarkeit und Reihenfolge der Startseite einstellen; diese Schalter betreffen nur die Einträge der Startseite', + settingsGuideRowsTitle: 'Maximale Zeilen', + settingsGuideRowsDesc: 'Zwei Karten pro Zeile auf breiten, eine auf schmalen Panels; Karten über dem Zeilenbudget landen unter „Mehr“. Standard 6 Zeilen, mindestens 1', + settingsGuideShow: 'Auf der Startseite anzeigen', + settingsGuideReset: 'Standardreihenfolge', + guideMore: 'Mehr', + guideOrder: 'Reihenfolge ändern', + guideEmpty: 'Keine Seiten zum Anzeigen', + guideShellEmpty: 'Keine Shells verfügbar', + guideShellFailed: 'Shells konnten nicht geladen werden: {error}', settingsViewersTitle: 'Datei-Viewer', settingsMobileTitle: "Mobil", settingsMobileNoAutoOpenTitle: "Auf schmalen Bildschirmen nicht automatisch öffnen", diff --git a/src/client/locales-fr.ts b/src/client/locales-fr.ts index f551ee7a..a14bbe3a 100644 --- a/src/client/locales-fr.ts +++ b/src/client/locales-fr.ts @@ -372,6 +372,17 @@ export const fr: Record = { settingsShellArgsDesc: 'Arguments explicites de lancement du shell, séparés par des espaces ; non vide = remplacement complet des arguments par défaut (contrat identique aux shellArgs du yaml)', settingsShellArgsPlaceholder: 'ex. -l (vide = arguments par défaut)', settingsTabsTitle: 'Contenu de la barre latérale', + settingsStartPageTitle: 'Page de démarrage', + settingsStartPageDesc: 'Réglez les lignes de cartes, la visibilité et l\'ordre de la page de démarrage ; ces interrupteurs ne concernent que ses entrées', + settingsGuideRowsTitle: 'Lignes maximales', + settingsGuideRowsDesc: 'Deux cartes par ligne sur un panneau large, une sur un panneau étroit ; les cartes au-delà du budget passent dans « Plus ». 6 lignes par défaut, au moins 1', + settingsGuideShow: 'Afficher sur la page de démarrage', + settingsGuideReset: 'Rétablir l\'ordre', + guideMore: 'Plus', + guideOrder: 'Réorganiser', + guideEmpty: 'Aucune page à afficher', + guideShellEmpty: 'Aucun shell disponible', + guideShellFailed: 'Échec du chargement des shells : {error}', settingsViewersTitle: 'Aperçus de fichiers', settingsMobileTitle: "Mobile", settingsMobileNoAutoOpenTitle: "Ne pas ouvrir automatiquement sur écran étroit", diff --git a/src/client/locales-hi.ts b/src/client/locales-hi.ts index f418f233..77fd35f1 100644 --- a/src/client/locales-hi.ts +++ b/src/client/locales-hi.ts @@ -379,6 +379,17 @@ export const hi: Record = { settingsShellArgsDesc: 'स्पष्ट shell तर्क, स्पेस से अलग; ग़ैर-खाली होने पर डिफ़ॉल्ट को पूरी तरह बदलें (yaml shellArgs के समान अनुबंध)', settingsShellArgsPlaceholder: 'जैसे -l (खाली = डिफ़ॉल्ट)', settingsTabsTitle: 'साइडबार सामग्री', + settingsStartPageTitle: 'प्रारंभ पृष्ठ', + settingsStartPageDesc: 'प्रारंभ पृष्ठ की कार्ड पंक्तियाँ, दृश्यता और क्रम सेट करें; ये स्विच केवल प्रारंभ पृष्ठ प्रविष्टियों पर लागू होते हैं', + settingsGuideRowsTitle: 'अधिकतम पंक्तियाँ', + settingsGuideRowsDesc: 'चौड़े पैनल में प्रति पंक्ति दो कार्ड, संकीर्ण में एक; सीमा से अधिक कार्ड "अधिक" में जाते हैं। डिफ़ॉल्ट 6 पंक्तियाँ, न्यूनतम 1', + settingsGuideShow: 'प्रारंभ पृष्ठ पर दिखाएँ', + settingsGuideReset: 'क्रम रीसेट करें', + guideMore: 'अधिक', + guideOrder: 'क्रम बदलें', + guideEmpty: 'दिखाने के लिए कोई पृष्ठ नहीं', + guideShellEmpty: 'कोई शेल उपलब्ध नहीं', + guideShellFailed: 'शेल लोड नहीं हो सके: {error}', settingsViewersTitle: 'फ़ाइल दर्शक', settingsMobileTitle: "मोबाइल", settingsMobileNoAutoOpenTitle: "छोटी स्क्रीन पर स्वतः न खोलें", diff --git a/src/client/locales-id.ts b/src/client/locales-id.ts index d1ed0d58..1b8f0067 100644 --- a/src/client/locales-id.ts +++ b/src/client/locales-id.ts @@ -377,6 +377,17 @@ export const id: Record = { settingsShellArgsDesc: 'Argumen shell eksplisit, dipisah spasi; jika tidak kosong, sepenuhnya menggantikan default (kontrak yang sama dengan shellArgs yaml)', settingsShellArgsPlaceholder: 'mis. -l (kosong = default)', settingsTabsTitle: 'Konten sidebar', + settingsStartPageTitle: 'Halaman mulai', + settingsStartPageDesc: 'Atur baris kartu, visibilitas, dan urutan halaman mulai; sakelar ini hanya memengaruhi entri halaman mulai', + settingsGuideRowsTitle: 'Baris maksimum', + settingsGuideRowsDesc: 'Dua kartu per baris pada panel lebar, satu pada panel sempit; kartu di luar batas masuk ke Lainnya. Standar 6 baris, minimal 1', + settingsGuideShow: 'Tampilkan di halaman mulai', + settingsGuideReset: 'Atur ulang urutan', + guideMore: 'Lainnya', + guideOrder: 'Ubah urutan', + guideEmpty: 'Tidak ada halaman untuk ditampilkan', + guideShellEmpty: 'Tidak ada shell tersedia', + guideShellFailed: 'Gagal memuat shell: {error}', settingsViewersTitle: 'Pratinjau berkas', settingsMobileTitle: "Seluler", settingsMobileNoAutoOpenTitle: "Jangan buka otomatis di layar sempit", diff --git a/src/client/locales-it.ts b/src/client/locales-it.ts index 8f3ac789..1e0ee223 100644 --- a/src/client/locales-it.ts +++ b/src/client/locales-it.ts @@ -370,6 +370,17 @@ export const it: Record = { settingsShellArgsDesc: 'Argomenti espliciti della shell, separati da spazi; quando non vuoti sostituiscono completamente i predefiniti (stesso contratto di shellArgs di yaml)', settingsShellArgsPlaceholder: 'es. -l (vuoto = predefiniti)', settingsTabsTitle: 'Contenuto della barra laterale', + settingsStartPageTitle: 'Pagina iniziale', + settingsStartPageDesc: 'Imposta righe, visibilità e ordine dei riquadri della pagina iniziale; questi interruttori riguardano solo le sue voci', + settingsGuideRowsTitle: 'Righe massime', + settingsGuideRowsDesc: 'Due riquadri per riga su pannelli larghi, uno su quelli stretti; i riquadri oltre il limite finiscono in «Altro». 6 righe predefinite, almeno 1', + settingsGuideShow: 'Mostra nella pagina iniziale', + settingsGuideReset: 'Ripristina ordine', + guideMore: 'Altro', + guideOrder: 'Riordina', + guideEmpty: 'Nessuna pagina da mostrare', + guideShellEmpty: 'Nessuna shell disponibile', + guideShellFailed: 'Caricamento delle shell non riuscito: {error}', settingsViewersTitle: 'Visualizzatori di file', settingsMobileTitle: "Mobile", settingsMobileNoAutoOpenTitle: "Non aprire automaticamente su schermi stretti", diff --git a/src/client/locales-ja.ts b/src/client/locales-ja.ts index e96ab0cf..3fe28253 100644 --- a/src/client/locales-ja.ts +++ b/src/client/locales-ja.ts @@ -379,6 +379,17 @@ export const ja: Record = { settingsShellArgsDesc: '明示的なシェル起動引数(スペース区切り)。非空の場合デフォルト引数を完全に置き換え(yaml の shellArgs 契約と同じ)', settingsShellArgsPlaceholder: '例: -l(空欄でデフォルト引数)', settingsTabsTitle: 'サイドバーの内容', + settingsStartPageTitle: 'スタートページ', + settingsStartPageDesc: 'スタートページのカード行数・表示内容・順序を設定します。ここのスイッチはスタートページの入口だけに作用します', + settingsGuideRowsTitle: '最大行数', + settingsGuideRowsDesc: '広い画面では 1 行 2 枚、狭い画面では 1 枚。行数を超えたカードは「その他」にまとめます。既定 6 行、最小 1 行', + settingsGuideShow: 'スタートページに表示', + settingsGuideReset: '既定の順序に戻す', + guideMore: 'その他', + guideOrder: '順序を調整', + guideEmpty: '表示できるページがありません', + guideShellEmpty: '利用できるシェルがありません', + guideShellFailed: 'シェルの読み込みに失敗しました: {error}', settingsViewersTitle: 'ファイルプレビュー', settingsMobileTitle: "モバイル", settingsMobileNoAutoOpenTitle: "狭い画面では自動で開かない", diff --git a/src/client/locales-ko.ts b/src/client/locales-ko.ts index c499e2c2..54e85e0b 100644 --- a/src/client/locales-ko.ts +++ b/src/client/locales-ko.ts @@ -371,6 +371,17 @@ export const ko: Record = { settingsShellArgsDesc: '명시적 shell 시작 인수, 공백으로 구분. 비어 있지 않으면 기본 인수를 완전히 대체합니다(yaml의 shellArgs 계약과 동일)', settingsShellArgsPlaceholder: '예: -l (비워두면 기본 인수 사용)', settingsTabsTitle: '사이드바 콘텐츠', + settingsStartPageTitle: '시작 페이지', + settingsStartPageDesc: '시작 페이지의 카드 행 수, 표시 여부, 순서를 설정합니다. 이 스위치는 시작 페이지 항목에만 적용됩니다', + settingsGuideRowsTitle: '최대 행 수', + settingsGuideRowsDesc: '넓은 패널에서는 한 줄에 두 장, 좁은 패널에서는 한 장; 행 한도를 넘는 카드는 더보기 아래로 들어갑니다. 기본 6행, 최소 1행', + settingsGuideShow: '시작 페이지에 표시', + settingsGuideReset: '순서 초기화', + guideMore: '더보기', + guideOrder: '순서 조정', + guideEmpty: '표시할 페이지가 없습니다', + guideShellEmpty: '사용 가능한 셸이 없습니다', + guideShellFailed: '셸을 불러오지 못했습니다: {error}', settingsViewersTitle: '파일 미리보기', settingsMobileTitle: "모바일", settingsMobileNoAutoOpenTitle: "좁은 화면에서는 자동으로 열지 않기", diff --git a/src/client/locales-nl.ts b/src/client/locales-nl.ts index fae633b3..42a8b677 100644 --- a/src/client/locales-nl.ts +++ b/src/client/locales-nl.ts @@ -377,6 +377,17 @@ export const nl: Record = { settingsShellArgsDesc: 'Expliciete shell-argumenten, spatiegescheiden; indien niet-leeg vervangen ze de standaardwaarden volledig (zelfde contract als de yaml shellArgs)', settingsShellArgsPlaceholder: 'bijv. -l (leeg = standaardwaarden)', settingsTabsTitle: 'Zijbalk-inhoud', + settingsStartPageTitle: 'Startpagina', + settingsStartPageDesc: 'Kies het aantal kaartrijen, de zichtbaarheid en de volgorde van de startpagina; deze schakelaars gelden alleen voor startpagina-items', + settingsGuideRowsTitle: 'Maximaal aantal rijen', + settingsGuideRowsDesc: 'Twee kaarten per rij op een breed paneel, één op een smal paneel; kaarten boven de limiet gaan onder Meer. Standaard 6 rijen, minimaal 1', + settingsGuideShow: 'Op de startpagina tonen', + settingsGuideReset: 'Volgorde herstellen', + guideMore: 'Meer', + guideOrder: 'Volgorde wijzigen', + guideEmpty: 'Geen pagina\'s om te tonen', + guideShellEmpty: 'Geen shells beschikbaar', + guideShellFailed: 'Shells laden mislukt: {error}', settingsViewersTitle: 'Bestandsviewers', settingsMobileTitle: "Mobiel", settingsMobileNoAutoOpenTitle: "Niet automatisch openen op smalle schermen", diff --git a/src/client/locales-pl.ts b/src/client/locales-pl.ts index a072ab7b..c774bbc8 100644 --- a/src/client/locales-pl.ts +++ b/src/client/locales-pl.ts @@ -381,6 +381,17 @@ export const pl: Record = { settingsShellArgsDesc: 'Jawne argumenty powłoki, oddzielone spacjami; niepuste w pełni zastępuje domyślne (zgodnie z kontraktem shellArgs w yaml)', settingsShellArgsPlaceholder: 'np. -l (puste = domyślne)', settingsTabsTitle: 'Treść panelu bocznego', + settingsStartPageTitle: 'Strona startowa', + settingsStartPageDesc: 'Ustaw liczbę wierszy kart, widoczność i kolejność strony startowej; te przełączniki dotyczą tylko jej pozycji', + settingsGuideRowsTitle: 'Maksymalna liczba wierszy', + settingsGuideRowsDesc: 'Dwie karty w wierszu na szerokim panelu, jedna na wąskim; karty ponad limit trafiają do „Więcej”. Domyślnie 6 wierszy, co najmniej 1', + settingsGuideShow: 'Pokaż na stronie startowej', + settingsGuideReset: 'Przywróć kolejność', + guideMore: 'Więcej', + guideOrder: 'Zmień kolejność', + guideEmpty: 'Brak stron do wyświetlenia', + guideShellEmpty: 'Brak dostępnych powłok', + guideShellFailed: 'Nie udało się wczytać powłok: {error}', settingsViewersTitle: 'Podglądy plików', settingsMobileTitle: "Mobile", settingsMobileNoAutoOpenTitle: "Nie otwieraj automatycznie na wąskim ekranie", diff --git a/src/client/locales-pt.ts b/src/client/locales-pt.ts index 9167acee..5011a5c8 100644 --- a/src/client/locales-pt.ts +++ b/src/client/locales-pt.ts @@ -362,6 +362,17 @@ export const pt: Record = { settingsShellArgsDesc: 'Argumentos explícitos do shell, separados por espaço; quando não vazios, substituem totalmente os padrões (mesmo contrato do shellArgs do yaml)', settingsShellArgsPlaceholder: 'ex.: -l (vazio = padrões)', settingsTabsTitle: 'Conteúdo da barra lateral', + settingsStartPageTitle: 'Página inicial', + settingsStartPageDesc: 'Defina linhas de cartões, visibilidade e ordem da página inicial; estes interruptores afetam apenas as entradas dela', + settingsGuideRowsTitle: 'Máximo de linhas', + settingsGuideRowsDesc: 'Dois cartões por linha em painéis largos, um em painéis estreitos; cartões além do limite vão para Mais. 6 linhas por padrão, no mínimo 1', + settingsGuideShow: 'Mostrar na página inicial', + settingsGuideReset: 'Restaurar ordem', + guideMore: 'Mais', + guideOrder: 'Reordenar', + guideEmpty: 'Nenhuma página para mostrar', + guideShellEmpty: 'Nenhum shell disponível', + guideShellFailed: 'Falha ao carregar shells: {error}', settingsViewersTitle: 'Visualizadores de arquivos', settingsMobileTitle: "Celular", settingsMobileNoAutoOpenTitle: "Não abrir automaticamente em telas estreitas", diff --git a/src/client/locales-ru.ts b/src/client/locales-ru.ts index 2b91714f..513002a1 100644 --- a/src/client/locales-ru.ts +++ b/src/client/locales-ru.ts @@ -376,6 +376,17 @@ export const ru: Record = { settingsShellArgsDesc: 'Явные аргументы запуска shell, разделённые пробелами; при непустом значении полностью заменяют аргументы по умолчанию (тот же контракт, что у shellArgs из yaml)', settingsShellArgsPlaceholder: 'напр. -l (пусто = по умолчанию)', settingsTabsTitle: 'Содержимое боковой панели', + settingsStartPageTitle: 'Начальная страница', + settingsStartPageDesc: 'Настройте число строк карточек, видимость и порядок начальной страницы; эти переключатели влияют только на её элементы', + settingsGuideRowsTitle: 'Максимум строк', + settingsGuideRowsDesc: 'Две карточки в строке на широкой панели, одна на узкой; карточки сверх лимита уходят в «Ещё». По умолчанию 6 строк, минимум 1', + settingsGuideShow: 'Показывать на начальной странице', + settingsGuideReset: 'Сбросить порядок', + guideMore: 'Ещё', + guideOrder: 'Изменить порядок', + guideEmpty: 'Нет страниц для показа', + guideShellEmpty: 'Нет доступных оболочек', + guideShellFailed: 'Не удалось загрузить оболочки: {error}', settingsViewersTitle: 'Просмотрщики файлов', settingsMobileTitle: "Мобильный", settingsMobileNoAutoOpenTitle: "Не открывать автоматически на узком экране", diff --git a/src/client/locales-sv.ts b/src/client/locales-sv.ts index 12626688..64de85d4 100644 --- a/src/client/locales-sv.ts +++ b/src/client/locales-sv.ts @@ -362,6 +362,17 @@ export const sv: Record = { settingsShellArgsDesc: 'Uttryckliga skalargument, mellanslagsseparerade; när icke-tomma ersätter de helt standardvärdena (samma kontrakt som yaml shellArgs)', settingsShellArgsPlaceholder: 't.ex. -l (tomt = standard)', settingsTabsTitle: 'Sidopanelens innehåll', + settingsStartPageTitle: 'Startsida', + settingsStartPageDesc: 'Ställ in startsidans kortrader, synlighet och ordning; dessa reglage påverkar bara startsideposter', + settingsGuideRowsTitle: 'Max antal rader', + settingsGuideRowsDesc: 'Två kort per rad i en bred panel, ett i en smal; kort utöver radbudgeten hamnar under Mer. Standard 6 rader, minst 1', + settingsGuideShow: 'Visa på startsidan', + settingsGuideReset: 'Återställ ordning', + guideMore: 'Mer', + guideOrder: 'Ändra ordning', + guideEmpty: 'Inga sidor att visa', + guideShellEmpty: 'Inga skal tillgängliga', + guideShellFailed: 'Det gick inte att läsa in skal: {error}', settingsViewersTitle: 'Filvisare', settingsMobileTitle: "Mobil", settingsMobileNoAutoOpenTitle: "Öppna inte automatiskt på smala skärmar", diff --git a/src/client/locales-th.ts b/src/client/locales-th.ts index eb8daad2..fbb9db18 100644 --- a/src/client/locales-th.ts +++ b/src/client/locales-th.ts @@ -379,6 +379,17 @@ export const th: Record = { settingsShellArgsDesc: 'อาร์กิวเมนต์ shell ที่ชัดเจน คั่นด้วยช่องว่าง; เมื่อไม่ว่างจะแทนที่ค่าเริ่มต้นทั้งหมด (สัญญาณเดียวกับ yaml shellArgs)', settingsShellArgsPlaceholder: 'เช่น -l (ว่าง = ค่าเริ่มต้น)', settingsTabsTitle: 'เนื้อหาแถบด้านข้าง', + settingsStartPageTitle: 'หน้าเริ่มต้น', + settingsStartPageDesc: 'ตั้งค่าจำนวนแถวการ์ด การแสดงผล และลำดับของหน้าเริ่มต้น สวิตช์เหล่านี้มีผลกับรายการในหน้าเริ่มต้นเท่านั้น', + settingsGuideRowsTitle: 'จำนวนแถวสูงสุด', + settingsGuideRowsDesc: 'แสดงการ์ดแถวละสองใบบนแผงกว้าง และแถวละใบบนแผงแคบ การ์ดที่เกินจำนวนแถวจะถูกเก็บไว้ใน "เพิ่มเติม" ค่าเริ่มต้น 6 แถว ขั้นต่ำ 1', + settingsGuideShow: 'แสดงในหน้าเริ่มต้น', + settingsGuideReset: 'รีเซ็ตลำดับ', + guideMore: 'เพิ่มเติม', + guideOrder: 'ปรับลำดับ', + guideEmpty: 'ไม่มีหน้าที่จะแสดง', + guideShellEmpty: 'ไม่มีเชลล์ที่ใช้ได้', + guideShellFailed: 'โหลดเชลล์ไม่สำเร็จ: {error}', settingsViewersTitle: 'ตัวพรีวิวไฟล์', settingsMobileTitle: "มือถือ", settingsMobileNoAutoOpenTitle: "ไม่เปิดอัตโนมัติบนจอแคบ", diff --git a/src/client/locales-tr.ts b/src/client/locales-tr.ts index a4c97e9c..ea66ce98 100644 --- a/src/client/locales-tr.ts +++ b/src/client/locales-tr.ts @@ -379,6 +379,17 @@ export const tr: Record = { settingsShellArgsDesc: 'Açık kabuk bağımsız değişkenleri, boşlukla ayrılmış; boş olmadıklarında varsayılanları tamamen değiştirir (yaml shellArgs ile aynı sözleşme)', settingsShellArgsPlaceholder: 'ör. -l (boş = varsayılanlar)', settingsTabsTitle: 'Kenar çubuğu içeriği', + settingsStartPageTitle: 'Başlangıç sayfası', + settingsStartPageDesc: 'Başlangıç sayfasının kart satırlarını, görünürlüğünü ve sırasını ayarlayın; bu anahtarlar yalnızca başlangıç sayfası girişlerini etkiler', + settingsGuideRowsTitle: 'En fazla satır', + settingsGuideRowsDesc: 'Geniş panelde satır başına iki kart, dar panelde bir kart; satır sınırını aşan kartlar Daha fazla altında toplanır. Varsayılan 6 satır, en az 1', + settingsGuideShow: 'Başlangıç sayfasında göster', + settingsGuideReset: 'Sırayı sıfırla', + guideMore: 'Daha fazla', + guideOrder: 'Sırala', + guideEmpty: 'Gösterilecek sayfa yok', + guideShellEmpty: 'Kullanılabilir kabuk yok', + guideShellFailed: 'Kabuklar yüklenemedi: {error}', settingsViewersTitle: 'Dosya önizleyicileri', settingsMobileTitle: "Mobil", settingsMobileNoAutoOpenTitle: "Dar ekranlarda otomatik açma", diff --git a/src/client/locales-vi.ts b/src/client/locales-vi.ts index df6d05d2..a8e52448 100644 --- a/src/client/locales-vi.ts +++ b/src/client/locales-vi.ts @@ -379,6 +379,17 @@ export const vi: Record = { settingsShellArgsDesc: 'Tham số shell tường minh, phân tách bằng dấu cách; khi không trống sẽ thay thế hoàn toàn mặc định (đồng bộ với contract shellArgs yaml)', settingsShellArgsPlaceholder: 'vd: -l (để trống = mặc định)', settingsTabsTitle: 'Nội dung thanh bên', + settingsStartPageTitle: 'Trang bắt đầu', + settingsStartPageDesc: 'Đặt số hàng thẻ, khả năng hiển thị và thứ tự của trang bắt đầu; các công tắc này chỉ ảnh hưởng đến mục trên trang bắt đầu', + settingsGuideRowsTitle: 'Số hàng tối đa', + settingsGuideRowsDesc: 'Hai thẻ mỗi hàng trên bảng rộng, một thẻ trên bảng hẹp; thẻ vượt hạn mức sẽ vào mục Khác. Mặc định 6 hàng, tối thiểu 1', + settingsGuideShow: 'Hiển thị trên trang bắt đầu', + settingsGuideReset: 'Đặt lại thứ tự', + guideMore: 'Khác', + guideOrder: 'Sắp xếp', + guideEmpty: 'Không có trang nào để hiển thị', + guideShellEmpty: 'Không có shell khả dụng', + guideShellFailed: 'Tải shell thất bại: {error}', settingsViewersTitle: 'Trình xem tệp', settingsMobileTitle: "Di động", settingsMobileNoAutoOpenTitle: "Không tự mở trên màn hình hẹp", diff --git a/src/client/locales-zh-HK.ts b/src/client/locales-zh-HK.ts index 3de05007..055c2201 100644 --- a/src/client/locales-zh-HK.ts +++ b/src/client/locales-zh-HK.ts @@ -394,6 +394,17 @@ export const zhHK: Record = { settingsShellArgsDesc: '顯式 shell 啟動參數,空格分隔;非空時完全替換預設參數(與 yaml 的 shellArgs 契約一致)', settingsShellArgsPlaceholder: '如 -l(留空用預設參數)', settingsTabsTitle: '側邊欄內容', + settingsStartPageTitle: '開始頁', + settingsStartPageDesc: '設定開始頁的卡片列數、顯示內容與順序;這裡的開關只影響開始頁入口', + settingsGuideRowsTitle: '最大列數', + settingsGuideRowsDesc: '寬螢幕每列兩張、窄螢幕一張;超過列數的卡片收進「更多」。預設 6 列,最少 1 列', + settingsGuideShow: '在開始頁顯示', + settingsGuideReset: '恢復預設順序', + guideMore: '更多', + guideOrder: '調整順序', + guideEmpty: '沒有可顯示的頁面', + guideShellEmpty: '沒有可用的 Shell', + guideShellFailed: 'Shell 載入失敗:{error}', settingsViewersTitle: '檔案預覽', settingsMobileTitle: "手機", settingsMobileNoAutoOpenTitle: "窄屏時不自動彈出", diff --git a/src/client/locales-zh-MO.ts b/src/client/locales-zh-MO.ts index 33da2c35..9aed0bd6 100644 --- a/src/client/locales-zh-MO.ts +++ b/src/client/locales-zh-MO.ts @@ -394,6 +394,17 @@ export const zhMO: Record = { settingsShellArgsDesc: '顯式 shell 啟動參數,空格分隔;非空時完全替換預設參數(與 yaml 的 shellArgs 契約一致)', settingsShellArgsPlaceholder: '如 -l(留空用預設參數)', settingsTabsTitle: '側邊欄內容', + settingsStartPageTitle: '開始頁', + settingsStartPageDesc: '設定開始頁的卡片列數、顯示內容與順序;這裡的開關只影響開始頁入口', + settingsGuideRowsTitle: '最大列數', + settingsGuideRowsDesc: '寬螢幕每列兩張、窄螢幕一張;超過列數的卡片收進「更多」。預設 6 列,最少 1 列', + settingsGuideShow: '在開始頁顯示', + settingsGuideReset: '恢復預設順序', + guideMore: '更多', + guideOrder: '調整順序', + guideEmpty: '沒有可顯示的頁面', + guideShellEmpty: '沒有可用的 Shell', + guideShellFailed: 'Shell 載入失敗:{error}', settingsViewersTitle: '檔案預覽', settingsMobileTitle: "手機", settingsMobileNoAutoOpenTitle: "窄屏時不自動彈出", diff --git a/src/client/locales-zh-TW.ts b/src/client/locales-zh-TW.ts index d3500ca9..4d18053f 100644 --- a/src/client/locales-zh-TW.ts +++ b/src/client/locales-zh-TW.ts @@ -394,6 +394,17 @@ export const zhTW: Record = { settingsShellArgsDesc: '顯式 shell 啟動參數,空格分隔;非空時完全替換預設參數(與 yaml 的 shellArgs 契約一致)', settingsShellArgsPlaceholder: '如 -l(留空用預設參數)', settingsTabsTitle: '側邊欄內容', + settingsStartPageTitle: '開始頁', + settingsStartPageDesc: '設定開始頁的卡片列數、顯示內容與順序;這裡的開關只影響開始頁入口', + settingsGuideRowsTitle: '最大列數', + settingsGuideRowsDesc: '寬螢幕每列兩張、窄螢幕一張;超過列數的卡片收進「更多」。預設 6 列,最少 1 列', + settingsGuideShow: '在開始頁顯示', + settingsGuideReset: '恢復預設順序', + guideMore: '更多', + guideOrder: '調整順序', + guideEmpty: '沒有可顯示的頁面', + guideShellEmpty: '沒有可用的 Shell', + guideShellFailed: 'Shell 載入失敗:{error}', settingsViewersTitle: '檔案預覽', settingsMobileTitle: "手機", settingsMobileNoAutoOpenTitle: "窄屏時不自動彈出", diff --git a/src/client/locales.ts b/src/client/locales.ts index 2c2feedf..86d5f8c9 100644 --- a/src/client/locales.ts +++ b/src/client/locales.ts @@ -391,6 +391,17 @@ export const zh = { settingsShellArgsDesc: '显式 shell 启动参数,空格分隔;非空时完全替换默认参数(与 yaml 的 shellArgs 契约一致)', settingsShellArgsPlaceholder: '如 -l(留空用默认参数)', settingsTabsTitle: '侧边栏内容', + settingsStartPageTitle: '开始页', + settingsStartPageDesc: '设置开始页的卡片行数、显示内容与顺序;这里的开关只影响开始页入口', + settingsGuideRowsTitle: '最大行数', + settingsGuideRowsDesc: '宽屏每行两张、窄屏一张;超出行数的卡片收进「更多」。默认 6 行,最小 1 行', + settingsGuideShow: '在开始页显示', + settingsGuideReset: '恢复默认顺序', + guideMore: '更多', + guideOrder: '调整顺序', + guideEmpty: '没有可显示的页面', + guideShellEmpty: '没有可用的 Shell', + guideShellFailed: 'Shell 加载失败:{error}', settingsViewersTitle: '文件预览', settingsMobileTitle: '手机', settingsMobileNoAutoOpenTitle: '窄屏时不自动弹出', @@ -1100,6 +1111,17 @@ export const en: Record = { settingsShellArgsPlaceholder: 'e.g. -l (empty = defaults)', settingsFontSizeDesc: 'Terminal font size in px (9–32, default 13)', settingsTabsTitle: 'Sidebar content', + settingsStartPageTitle: 'Start page', + settingsStartPageDesc: 'Choose the start page card rows, visibility, and order; these switches only affect start page entries', + settingsGuideRowsTitle: 'Maximum rows', + settingsGuideRowsDesc: 'Two cards per row on a wide pane, one on a narrow one; cards beyond the row budget go under More. 6 rows by default, at least 1', + settingsGuideShow: 'Show on the start page', + settingsGuideReset: 'Reset order', + guideMore: 'More', + guideOrder: 'Reorder', + guideEmpty: 'Nothing to show', + guideShellEmpty: 'No shells available', + guideShellFailed: 'Failed to load shells: {error}', settingsViewersTitle: 'File viewers', settingsMobileTitle: 'Mobile', settingsMobileNoAutoOpenTitle: "Don't auto-open on narrow screens", diff --git a/src/client/native/guide-catalog.ts b/src/client/native/guide-catalog.ts new file mode 100644 index 00000000..4985c2cc --- /dev/null +++ b/src/client/native/guide-catalog.ts @@ -0,0 +1,117 @@ +/** + * The live inventory of host guide cards (the native start page), as the + * plugin's own start page and settings section consume it. + * + * The host's tab registry is the single authority: a type disabled in the + * side-card settings unregisters its native type, so its card leaves this + * catalog too. Entries are kept as thunks/components rather than resolved + * strings so a language switch re-renders without a registry notification. + */ +import type { ComponentType } from 'react' +import type { Context } from '../../context-types.ts' +import { descriptorIdOfGuideEntry, guideKeyOf } from './guide-ids.ts' + +/** One host guide card, normalized for the plugin's own surfaces. */ +export interface NativeGuideEntry { + /** Stable identity: providerId::entryId. */ + readonly key: string + /** Implementation id of the type that contributed the card. */ + readonly providerId: string + /** Entry id inside that provider. */ + readonly entryId: string + /** The kind openTab accepts. */ + readonly kind: string + /** Card title in the active language. */ + readonly title: () => string + /** Optional one-line description in the active language. */ + readonly description?: () => string + /** Optional card glyph component. */ + readonly icon?: ComponentType<{ size?: number }> + /** The Better Sidebar descriptor that owns this card, when it is ours. */ + readonly descriptorId?: string +} + +/** The catalog face the guide body and the settings section share. */ +export interface NativeGuideCatalog { + /** Reference-stable snapshot of the registered guide cards. */ + getSnapshot(): readonly NativeGuideEntry[] + /** Observe registry changes. */ + subscribe(listener: () => void): () => void +} + +/** The slice of the host tab registry this module reads. */ +interface GuideRegistry { + guide(): readonly { + readonly id: string + readonly kind: string + readonly providerId: string + readonly title: () => string + readonly description?: () => string + readonly icon?: ComponentType<{ size?: number }> + }[] + subscribe(listener: () => void): () => void +} + +const EMPTY: readonly NativeGuideEntry[] = [] + +/** One registry snapshot, normalized. */ +function entriesOf(registry: GuideRegistry | undefined): readonly NativeGuideEntry[] { + if (registry === undefined) return EMPTY + return registry.guide().map((entry) => { + const descriptorId = descriptorIdOfGuideEntry(entry.providerId, entry.id) + return { + key: guideKeyOf(entry.providerId, entry.id), + providerId: entry.providerId, + entryId: entry.id, + kind: entry.kind, + title: entry.title, + ...(entry.description === undefined ? {} : { description: entry.description }), + ...(entry.icon === undefined ? {} : { icon: entry.icon }), + ...(descriptorId === undefined ? {} : { descriptorId }), + } + }) +} + +/** + * Create the catalog and wait for the host registry. + * @param ctx - the client context. + * @returns the catalog plus the disposer releasing its registry subscription. + */ +export function createNativeGuideCatalog(ctx: Context): { catalog: NativeGuideCatalog; dispose: () => void } { + const listeners = new Set<() => void>() + let snapshot: readonly NativeGuideEntry[] = EMPTY + let registry: GuideRegistry | undefined + let unsubscribe: (() => void) | undefined + + const publish = (): void => { + snapshot = entriesOf(registry) + for (const listener of listeners) listener() + } + + const seat = ctx.inject(['sidebarRightTabs'], (injected) => { + registry = injected.get('sidebarRightTabs') as unknown as GuideRegistry | undefined + if (registry === undefined) { + publish() + return + } + unsubscribe = registry.subscribe(publish) + publish() + return () => { + unsubscribe?.() + unsubscribe = undefined + registry = undefined + publish() + } + }) + + return { + catalog: { + getSnapshot: () => snapshot, + subscribe: (listener) => { + listeners.add(listener) + return () => { listeners.delete(listener) } + }, + }, + dispose: () => { void seat.dispose() }, + } +} diff --git a/src/client/native/guide-ids.ts b/src/client/native/guide-ids.ts new file mode 100644 index 00000000..01e33d29 --- /dev/null +++ b/src/client/native/guide-ids.ts @@ -0,0 +1,36 @@ +/** + * Identity vocabulary shared by the native tab registration and the start-page + * takeover. Kept dependency-free so the catalog and the slot registration can + * both use it without importing each other. + */ + +/** The kind the plugin's files window owns (page + file viewer). */ +export const EDITOR_KIND = 'editor' + +/** The built-in page kind this plugin takes over. */ +export const FILES_KIND = 'files' + +/** The prefix of every implementation id this plugin registers natively. */ +const NATIVE_ID_PREFIX = 'dsh-better-sidebar:' + +/** The plugin's implementation id for a descriptor (unique across kinds). */ +export function nativeId(descriptorId: string): string { + return NATIVE_ID_PREFIX + descriptorId +} + +/** Stable identity of one host guide card: provider implementation + entry id. */ +export function guideKeyOf(providerId: string, entryId: string): string { + return providerId + '::' + entryId +} + +/** + * The Better Sidebar descriptor that owns one native guide card, when it is + * one of ours. The files takeover is its own registration id but is the + * editor descriptor's page. + */ +export function descriptorIdOfGuideEntry(providerId: string, entryId: string): string | undefined { + if (providerId === nativeId(FILES_KIND) && entryId === FILES_KIND) return EDITOR_KIND + if (!providerId.startsWith(NATIVE_ID_PREFIX)) return undefined + const implementation = providerId.slice(NATIVE_ID_PREFIX.length) + return entryId === implementation ? implementation : undefined +} diff --git a/src/client/native/guide-layout.ts b/src/client/native/guide-layout.ts new file mode 100644 index 00000000..49d580e2 --- /dev/null +++ b/src/client/native/guide-layout.ts @@ -0,0 +1,102 @@ +/** + * Pure start-page layout math: ordering, visibility, the two-column threshold, + * and the overflow that collapses into the "More" card. + */ + +/** The wide layout starts at two columns from this pane width on. */ +export const GUIDE_TWO_COLUMN_MIN_WIDTH = 520 + +/** Rows a document without a stored value gets. */ +export const GUIDE_DEFAULT_ROWS = 6 + +/** One card the layout reasons about. */ +export interface GuideLayoutEntry { + readonly key: string +} + +/** Inputs of computeGuideLayout. */ +export interface GuideLayoutOptions { + /** Explicit start-page order, by card key. */ + readonly order: readonly string[] + /** Visibility overrides; an absent key is visible. */ + readonly hidden: Readonly> + /** Maximum rows; normalized to at least one. */ + readonly rows: number + /** Pane width in CSS pixels. */ + readonly width: number +} + +/** The settled layout one guide render uses. */ +export interface GuideLayout { + readonly columns: number + readonly rows: number + readonly capacity: number + readonly visible: readonly T[] + readonly overflow: readonly T[] + readonly showMore: boolean +} + +/** One or two columns for a pane width. */ +export function columnsForWidth(width: number): number { + return width >= GUIDE_TWO_COLUMN_MIN_WIDTH ? 2 : 1 +} + +/** Normalize a stored row count; anything below one falls back to the default. */ +export function normalizeGuideRows(rows: number): number { + return Number.isSafeInteger(rows) && rows >= 1 ? rows : GUIDE_DEFAULT_ROWS +} + +/** + * Sort entries by the stored order. Keys absent from the order follow in their + * registration order; keys in the order that no longer exist do not matter. + */ +export function orderGuideEntries( + entries: readonly T[], + order: readonly string[], +): T[] { + const rank = new Map() + for (const [index, key] of order.entries()) if (!rank.has(key)) rank.set(key, index) + return entries + .map((entry, index) => ({ entry, index, rank: rank.get(entry.key) })) + .sort((left, right) => { + if (left.rank !== undefined && right.rank !== undefined) { + return left.rank - right.rank || left.index - right.index + } + if (left.rank !== undefined) return -1 + if (right.rank !== undefined) return 1 + return left.index - right.index + }) + .map(item => item.entry) +} + +/** + * Resolve the cards one start page draws. + * + * Hidden cards are removed before the capacity check, so hiding a card never + * creates an artificial overflow. Once the remaining list exceeds the row + * budget, ONE slot goes to the "More" card: visible cards are + * "capacity - 1", and the rest live in its menu. At the minimum capacity of + * one, the page therefore shows the More card alone. + */ +export function computeGuideLayout( + entries: readonly T[], + options: GuideLayoutOptions, +): GuideLayout { + const rows = normalizeGuideRows(options.rows) + const columns = columnsForWidth(options.width) + const ordered = orderGuideEntries(entries, options.order) + const shown = ordered.filter(entry => options.hidden[entry.key] !== true) + const capacity = rows * columns + if (shown.length <= capacity) { + return { columns, rows, capacity, visible: shown, overflow: [], showMore: false } + } + const visibleCount = Math.max(0, capacity - 1) + return { + columns, + rows, + capacity, + visible: shown.slice(0, visibleCount), + overflow: shown.slice(visibleCount), + showMore: true, + } +} diff --git a/src/client/native/guide-order.tsx b/src/client/native/guide-order.tsx new file mode 100644 index 00000000..a7a1a539 --- /dev/null +++ b/src/client/native/guide-order.tsx @@ -0,0 +1,97 @@ +/** + * Shared start-page order editor: the settings section renders the list inline, + * the guide's "More" menu renders it inside a dialog. Both act on the same + * catalog/order/visibility vocabulary. + */ +import { createElement } from 'react' +import { + IconChevronDownOutlineRegular, + IconChevronUpOutlineRegular, + Modal, +} from '@deepseek-ai/dsh-client-ui-primitives' +import clsx from 'clsx' +import type { NativeGuideEntry } from './guide-catalog.ts' +import { t } from '../locales.ts' +import { Switch } from '../Switch.tsx' +import css from './guide.module.css' + +/** The list's actions; callers own persistence. */ +export interface GuideOrderListProps { + entries: readonly NativeGuideEntry[] + hidden: Readonly> + onMove: (key: string, delta: -1 | 1) => void + onToggle: (key: string, hidden: boolean) => void +} + +/** The inline order/visibility list. */ +export function GuideOrderList({ entries, hidden, onMove, onToggle }: GuideOrderListProps) { + return ( +
+ {entries.map((entry, index) => { + const shown = hidden[entry.key] !== true + const title = entry.title() + const description = entry.description?.() ?? entry.kind + return ( +
+ + + {title} + {description} + + + + + { onToggle(entry.key, !next) }} + /> + +
+ ) + })} +
+ ) +} + +/** The order editor opened from the guide's "More" menu. */ +export function GuideOrderDialog(props: GuideOrderListProps & { + open: boolean + onClose: () => void +}) { + const { open, onClose, entries, hidden, onMove, onToggle } = props + return ( + + {t('settingsDone')} + + )} + > + + ) +} diff --git a/src/client/native/guide-prefs.ts b/src/client/native/guide-prefs.ts new file mode 100644 index 00000000..a4d426f4 --- /dev/null +++ b/src/client/native/guide-prefs.ts @@ -0,0 +1,40 @@ +/** + * Serialized writes for the start page's own preferences from the guide card's + * "Reorder" dialog. The settings section has its own revision-guarded queue; + * this one uses the same revision-free settings route as the editor's + * plugin-owned settings, and adopts the returned document. + */ +import { api } from '../api.ts' +import { parsePrefs } from '../prefs.ts' +import type { SidebarStore } from '../state.ts' + +let queue: Promise = Promise.resolve() + +/** Persist one patch of start-page preferences. */ +export function writeGuidePrefs(store: SidebarStore, patch: Record): void { + queue = queue.then(async () => { + const view = await api.settingsUpdate(patch) + store.setPrefs(parsePrefs(view.value)) + }).catch((error: unknown) => { + console.error('start page settings write failed', error) + }) +} + +/** Persist the full explicit order. */ +export function saveGuideOrder(store: SidebarStore, order: readonly string[]): void { + writeGuidePrefs(store, { guideOrder: [...order] }) +} + +/** Persist one card's start-page visibility. */ +export function setGuideEntryHidden(store: SidebarStore, key: string, hidden: boolean): void { + const current = store.getPrefs().guideHidden + const next = { ...current } + if (hidden) next[key] = true + else delete next[key] + writeGuidePrefs(store, { guideHidden: next }) +} + +/** Persist the maximum row count. */ +export function saveGuideRows(store: SidebarStore, rows: number): void { + writeGuidePrefs(store, { guideRows: rows }) +} diff --git a/src/client/native/guide.module.css b/src/client/native/guide.module.css new file mode 100644 index 00000000..a49ac3c6 --- /dev/null +++ b/src/client/native/guide.module.css @@ -0,0 +1,288 @@ +/* The start page: a centered, scrollable two-column card grid over the host + guide body. Every visual value is a host token (no hardcoded colors). */ +.root { + width: 100%; + min-height: 100%; + box-sizing: border-box; + padding: 24px; + overflow-y: auto; +} + +.guide { + width: 100%; + max-width: 760px; + margin: 0 auto; + display: flex; + flex-direction: column; + gap: 12px; +} + +.grid { + display: grid; + gap: 12px; + align-items: stretch; +} + +.gridOne { + grid-template-columns: minmax(0, 1fr); +} + +.gridTwo { + grid-template-columns: repeat(2, minmax(0, 1fr)); +} + +.card { + position: relative; + display: flex; + align-items: center; + min-height: 56px; + box-sizing: border-box; + border: 1px solid var(--dsw-alias-border-l2); + border-radius: 12px; + background: var(--dsw-alias-bg-layer-1); + color: var(--dsw-alias-label-primary); + transition: background 0.12s ease, border-color 0.12s ease; +} + +.card:hover { + background: var(--dsw-alias-interactive-bg-hover); + border-color: var(--dsw-alias-label-dimmed); +} + +.cardMain { + display: flex; + flex: 1; + align-items: center; + gap: 12px; + min-width: 0; + padding: 12px 16px; + border: 0; + border-radius: inherit; + background: transparent; + color: inherit; + font: inherit; + text-align: left; + cursor: pointer; +} + +.card:has(.cardMenuButton) .cardMain { + padding-right: 44px; +} + +.cardMain:focus-visible, +.cardMenuButton:focus-visible, +.moreCard:focus-visible, +.orderButton:focus-visible, +.dialogDone:focus-visible { + outline: 2px solid var(--dsw-alias-border-l4); + outline-offset: 2px; +} + +.cardIcon { + display: inline-flex; + flex: none; + align-items: center; + justify-content: center; + width: 22px; + height: 22px; + color: var(--dsw-alias-label-secondary); +} + +.cardText { + display: flex; + flex: 1; + flex-direction: column; + gap: 2px; + min-width: 0; +} + +.cardTitle { + overflow: hidden; + font-size: 14px; + line-height: 20px; + text-overflow: ellipsis; + white-space: nowrap; +} + +.cardDesc { + display: -webkit-box; + overflow: hidden; + color: var(--dsw-alias-label-tertiary); + font-size: 12px; + line-height: 18px; + -webkit-box-orient: vertical; + -webkit-line-clamp: 2; +} + +.cardMenuButton { + position: absolute; + top: 50%; + right: 8px; + display: inline-flex; + align-items: center; + justify-content: center; + width: 28px; + height: 28px; + padding: 0; + transform: translateY(-50%); + border: 0; + border-radius: 6px; + background: transparent; + color: var(--dsw-alias-label-secondary); + cursor: pointer; +} + +.cardMenuButton:hover { + background: var(--dsw-alias-interactive-bg-hover); + color: var(--dsw-alias-label-primary); +} + +.moreSlot { + display: flex; + min-width: 0; +} + +.moreSlot > * { + flex: 1; + min-width: 0; +} + +.moreCard { + display: flex; + align-items: center; + gap: 12px; + width: 100%; + padding: 12px 16px; + border-style: dashed; + background: transparent; + font: inherit; + text-align: left; + cursor: pointer; +} + +.moreCard:hover { + background: var(--dsw-alias-interactive-bg-hover); + border-color: var(--dsw-alias-label-dimmed); +} + +.empty { + margin: 0; + padding: 48px 16px; + color: var(--dsw-alias-label-tertiary); + font-size: 13px; + line-height: 20px; + text-align: center; +} + +.orderList { + display: flex; + flex-direction: column; +} + +.orderRow { + display: flex; + align-items: center; + gap: 10px; + padding: 10px 2px; + border-bottom: 1px solid var(--dsw-alias-border-l2); +} + +.orderRow:last-child { + border-bottom: none; +} + +.orderRowHidden { + opacity: 0.55; +} + +.orderIcon { + display: inline-flex; + flex: none; + align-items: center; + justify-content: center; + width: 20px; + height: 20px; + color: var(--dsw-alias-label-secondary); +} + +.orderText { + display: flex; + flex: 1; + flex-direction: column; + gap: 2px; + min-width: 0; +} + +.orderTitle { + overflow: hidden; + font-size: 13px; + line-height: 18px; + text-overflow: ellipsis; + white-space: nowrap; +} + +.orderDesc { + overflow: hidden; + color: var(--dsw-alias-label-tertiary); + font-size: 11px; + line-height: 16px; + text-overflow: ellipsis; + white-space: nowrap; +} + +.orderActions { + display: inline-flex; + flex: none; + align-items: center; + gap: 4px; +} + +.orderButton { + display: inline-flex; + align-items: center; + justify-content: center; + width: 24px; + height: 24px; + padding: 0; + border: 1px solid var(--dsw-alias-border-l2); + border-radius: 6px; + background: transparent; + color: var(--dsw-alias-label-secondary); + cursor: pointer; +} + +.orderButton:hover:not(:disabled) { + background: var(--dsw-alias-interactive-bg-hover); + color: var(--dsw-alias-label-primary); +} + +.orderButton:disabled { + opacity: 0.35; + cursor: default; +} + +.dialogDone { + min-width: 72px; + 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; + font-size: 13px; + cursor: pointer; +} + +.dialogDone:hover { + background: var(--dsw-alias-interactive-bg-hover); +} + +@media (prefers-reduced-motion: reduce) { + .card, + .cardMenuButton, + .moreCard, + .orderButton, + .dialogDone { + transition: none; + } +} diff --git a/src/client/native/guide.tsx b/src/client/native/guide.tsx new file mode 100644 index 00000000..712c9ddf --- /dev/null +++ b/src/client/native/guide.tsx @@ -0,0 +1,336 @@ +/** + * The plugin's start page: the native guide slot's chain replacement. + * + * It draws the host's registered guide cards itself so the page can use a + * two-column grid, a configurable row budget, and a "More" card. A card is + * opened through the guide tab's own actions, exactly like the shipped guide + * does, so the guide tab is replaced rather than left behind. + */ +import { createElement, useEffect, useLayoutEffect, useRef, useState, useSyncExternalStore } from 'react' +import type { ComponentType, ReactNode } from 'react' +import { + IconEllipsisOutlineRegular, + Menu, +} from '@deepseek-ai/dsh-client-ui-primitives' +import clsx from 'clsx' +import type { SidebarPrefs } from '../../prefs-shared.ts' +import type { HostShellCatalog } from '../terminal-client.ts' +import type { SidebarStore } from '../state.ts' +import { t } from '../locales.ts' +import type { NativeGuideCatalog, NativeGuideEntry } from './guide-catalog.ts' +import { columnsForWidth, computeGuideLayout, orderGuideEntries } from './guide-layout.ts' +import { GuideOrderDialog } from './guide-order.tsx' +import { saveGuideOrder, setGuideEntryHidden } from './guide-prefs.ts' +import css from './guide.module.css' + +/** The terminal service slice the card's native menu needs. */ +export interface GuideShellMenu { + launchShells: (signal: AbortSignal) => Promise + selectShell: (path: string) => void +} + +/** The native tab actions a guide card opens through (structurally the host's). */ +interface GuideActions { + openTab: (kind: string, options: { replaceTab?: boolean; params?: Record }) => void + close: () => void +} + +/** What the chain component receives from the native registration. */ +export interface NativeGuideProps { + /** Host-injected hook for the guide tab's own record. */ + useTabInfo?: () => { tab: { actions: GuideActions } } | undefined + catalog: NativeGuideCatalog + store: SidebarStore + /** Present only when the host exposes both shell catalog and selection. */ + shellMenu?: GuideShellMenu | undefined +} + +/** The grid's inputs, extracted for direct rendering in tests. */ +export interface GuideGridProps { + entries: readonly NativeGuideEntry[] + prefs: Pick + /** Pane width in CSS pixels. */ + width: number + onOpen: (entry: NativeGuideEntry, params?: Record) => void + onSaveOrder?: (order: readonly string[]) => void + onToggleHidden?: (key: string, hidden: boolean) => void + shellMenu?: GuideShellMenu | undefined +} + +/** One card's glyph, when it has one. */ +function cardIcon(entry: NativeGuideEntry): ReactNode { + const Icon: ComponentType<{ size?: number }> | undefined = entry.icon + return Icon === undefined ? null : createElement(Icon, { size: 16 }) +} + +/** The terminal card's shell menu: the host's shell catalog, drawn natively here. */ +function TerminalMenu(props: { + entry: NativeGuideEntry + shellMenu: GuideShellMenu + onOpen: (entry: NativeGuideEntry, params?: Record) => void +}) { + const { entry, shellMenu, onOpen } = props + const [open, setOpen] = useState(false) + const [attempt, setAttempt] = useState(0) + const [state, setState] = useState< + | { phase: 'loading' } + | { phase: 'ready'; shells: HostShellCatalog['shells']; selected?: string } + | { phase: 'failed'; message: string } + >({ phase: 'loading' }) + + useEffect(() => { + if (!open) return + const lifetime = new AbortController() + let live = true + setState({ phase: 'loading' }) + Promise.resolve() + .then(() => shellMenu.launchShells(lifetime.signal)) + .then((catalog) => { + if (!live) return + setState({ + phase: 'ready', + shells: catalog.shells, + ...(catalog.selectedShell === undefined ? {} : { selected: catalog.selectedShell }), + }) + }, (error: unknown) => { + if (!live) return + setState({ phase: 'failed', message: error instanceof Error ? error.message : String(error) }) + }) + return () => { + live = false + lifetime.abort() + } + }, [open, attempt, shellMenu]) + + const items = state.phase === 'loading' + ? [{ id: 'loading', label: t('loading'), disabled: true }] + : state.phase === 'failed' + ? [ + { id: 'failed', label: t('guideShellFailed', { error: state.message }), disabled: true }, + { id: 'retry', label: t('terminalRetry') }, + ] + : state.shells.length === 0 + ? [{ id: 'empty', label: t('guideShellEmpty'), disabled: true }] + : state.shells.map(shell => ({ id: shell.path, label: shell.name })) + + return ( + { setOpen(false) }} + portal + autoFocus + align="end" + items={items} + selectedId={state.phase === 'ready' ? state.selected : undefined} + onSelect={(id) => { + if (state.phase === 'failed') { + if (id === 'retry') setAttempt(value => value + 1) + return + } + if (state.phase !== 'ready') return + shellMenu.selectShell(id) + setOpen(false) + onOpen(entry, { shellPath: id }) + }} + anchor={( + + )} + /> + ) +} + +/** One card in the start-page grid. */ +function GuideCard(props: { + entry: NativeGuideEntry + onOpen: (entry: NativeGuideEntry, params?: Record) => void + shellMenu?: GuideShellMenu | undefined +}) { + const { entry, onOpen, shellMenu } = props + const description = entry.description?.() + const terminal = entry.kind === 'terminal' && shellMenu !== undefined + return ( +
+ + {terminal ? : null} +
+ ) +} + +/** The whole start-page grid, including the More card and the order dialog. */ +export function GuideGrid(props: GuideGridProps) { + const { entries, prefs, width, onOpen, onSaveOrder, onToggleHidden, shellMenu } = props + const [orderOpen, setOrderOpen] = useState(false) + const [moreOpen, setMoreOpen] = useState(false) + const layout = computeGuideLayout(entries, { + order: prefs.guideOrder, + hidden: prefs.guideHidden, + rows: prefs.guideRows, + width, + }) + const orderedAll = orderGuideEntries(entries, prefs.guideOrder) + + const move = (key: string, delta: -1 | 1): void => { + const keys = orderedAll.map(entry => entry.key) + const at = keys.indexOf(key) + const to = at + delta + if (at < 0 || to < 0 || to >= keys.length) return + const next = [...keys] + const [moved] = next.splice(at, 1) + if (moved === undefined) return + next.splice(to, 0, moved) + onSaveOrder?.(next) + } + + const moreItems = [ + ...layout.overflow.map(entry => ({ id: 'open:' + entry.key, label: entry.title() })), + ...(layout.overflow.length === 0 ? [] : [{ type: 'separator' as const, id: 'order-separator' }]), + { id: 'order', label: t('guideOrder') }, + ] + + /** The grid body; the More anchor is a card-sized Menu trigger. */ + const moreCard = ( +
+ { setMoreOpen(false) }} + portal + autoFocus + align="end" + items={moreItems} + onSelect={(id) => { + setMoreOpen(false) + if (id === 'order') { + setOrderOpen(true) + return + } + if (!id.startsWith('open:')) return + const key = id.slice('open:'.length) + const entry = layout.overflow.find(candidate => candidate.key === key) + if (entry !== undefined) onOpen(entry) + }} + anchor={( + + )} + /> +
+ ) + + return ( +
+ {layout.visible.length === 0 && !layout.showMore ? ( +

{t('guideEmpty')}

+ ) : ( +
+ {layout.visible.map(entry => ( + + ))} + {layout.showMore ? moreCard : null} +
+ )} + { setOrderOpen(false) }} + entries={orderedAll} + hidden={prefs.guideHidden} + onMove={move} + onToggle={(key, hidden) => { onToggleHidden?.(key, hidden) }} + /> +
+ ) +} + +/** Measure the pane width so the grid can choose one or two columns. */ +function useGuideWidth(ref: { current: HTMLDivElement | null }): number { + const [width, setWidth] = useState(0) + useLayoutEffect(() => { + const node = ref.current + if (node === null) return + const measure = (): void => { setWidth(node.clientWidth) } + measure() + if (typeof ResizeObserver === 'undefined') return + const observer = new ResizeObserver(measure) + observer.observe(node) + return () => { observer.disconnect() } + }, [ref]) + return width +} + +/** The chain component registered into the host's guide slot. */ +export function NativeGuide(props: NativeGuideProps) { + const { catalog, store, shellMenu, useTabInfo } = props + const entries = useSyncExternalStore(catalog.subscribe, catalog.getSnapshot, catalog.getSnapshot) + // The store's members are methods (they read their receiver); bind them + // through arrows or useSyncExternalStore crashes on the first render. + const snapshot = useSyncExternalStore( + (listener) => store.subscribe(listener), + () => store.getSnapshot(), + () => store.getSnapshot(), + ) + const prefs = snapshot.prefs + const rootRef = useRef(null) + const width = useGuideWidth(rootRef) + const actions = useTabInfo?.()?.tab.actions + + const open = (entry: NativeGuideEntry, params?: Record): void => { + if (actions === undefined) return + actions.openTab(entry.kind, { replaceTab: true, ...(params === undefined ? {} : { params }) }) + actions.close() + } + + return ( +
+ { saveGuideOrder(store, order) }} + onToggleHidden={(key, hidden) => { setGuideEntryHidden(store, key, hidden) }} + shellMenu={shellMenu} + /> +
+ ) +} diff --git a/src/client/native/index.ts b/src/client/native/index.ts index b62cf626..213cebb5 100644 --- a/src/client/native/index.ts +++ b/src/client/native/index.ts @@ -32,6 +32,11 @@ import { parseFileAddress } from '../resource-address.ts' import type { ContextDiagnostics } from '../context-diagnostics.ts' import type { BetterSidebarService, TabDescriptor } from '../service.ts' import type { SidebarStore } from '../state.ts' +import { webTerminals } from '../terminal-client.ts' +import type { NativeGuideCatalog } from './guide-catalog.ts' +import { NativeGuide } from './guide.tsx' +import { EDITOR_KIND, FILES_KIND, nativeId } from './guide-ids.ts' +import { mountedSessionId } from './surface.ts' import { NativeTabBody, NativeTabTitle, @@ -111,17 +116,6 @@ interface NativeTabRegistry { }): () => void } -/** The kind the plugin's files window owns (page + file viewer). */ -const EDITOR_KIND = 'editor' - -/** The built-in page kind this plugin takes over. */ -const FILES_KIND = 'files' - -/** The plugin's implementation id for a descriptor (unique across kinds). */ -function nativeId(descriptorId: string): string { - return `dsh-better-sidebar:${descriptorId}` -} - /** The descriptor's title text, evaluated fresh for the current locale. */ function titleOf(descriptor: TabDescriptor): string { return typeof descriptor.title === 'function' ? descriptor.title() : descriptor.title @@ -246,6 +240,13 @@ export interface NativeSurfaceDeps { readonly service: BetterSidebarService /** The shared native tab record registry (the surface writes it too). */ readonly records: NativeTabRecords + /** + * The live catalog of host guide cards. When present, the plugin replaces + * the shipped guide page with its own start page; omitted keeps the host's + * guide untouched (the unit harnesses use this to exercise the original + * surface without mounting the start page). + */ + readonly guideCatalog?: NativeGuideCatalog /** * The activation's optional dsh-context diagnostics controller (see * ../context-diagnostics.ts). Forwarded into the tab bodies' injected bag, @@ -275,7 +276,7 @@ export interface NativeSurfaceDeps { * @returns a disposer unregistering everything. */ export function registerNativeSurface(deps: NativeSurfaceDeps): () => void { - const { ctx, store, service, records, reportFailure, diagnostics } = deps + const { ctx, store, service, records, reportFailure, diagnostics, guideCatalog } = deps // Bind the store BEFORE any body can render: the per-session state is the // authority for the explorer's expansion set, so the native surface and the // workbench share one set per session and a closed tab cannot drop it. @@ -318,6 +319,45 @@ export function registerNativeSurface(deps: NativeSurfaceDeps): () => void { } } + // The start page: replace the host guide body with the plugin's own grid. + // The chain slot is declared by the host's guide type, so injection waits + // for that declaration; a failure leaves the shipped guide in place. + let disposeGuide: (() => void) | undefined + if (guideCatalog !== undefined) { + const catalog = guideCatalog + try { + disposeGuide = ctx.slots.inject('sidebar.right.tab.guide', () => { + try { + return ctx.slots.register({ + name: 'sidebar.right.tab.guide', + // Always elect: the shipped guide is the fallback we replace. + select: () => ({}), + inject: (sessionId: string) => { + const scope = typeof sessionId === 'string' && sessionId !== '' + ? sessionId + : mountedSessionId(ctx) + const terminals = webTerminals(ctx) + const launchShells = terminals?.launchShells + const selectShell = terminals?.selectShell + const shellMenu = scope !== undefined && launchShells !== undefined && selectShell !== undefined + ? { + launchShells: (signal: AbortSignal) => launchShells(scope, signal), + selectShell: (path: string) => { selectShell(path) }, + } + : undefined + return { catalog, store, ...(shellMenu === undefined ? {} : { shellMenu }) } + }, + }, NativeGuide) + } catch (error) { + reportFailure?.('register start page', error) + return () => {} + } + }) + } catch (error) { + reportFailure?.('register start page', error) + } + } + const fileSessionIdOf = (info: NativeTabInfo): string | undefined => { const address = parseFileAddress(info.tab.contentId) return address !== undefined && address.scope === 'session' ? address.sessionId : undefined @@ -559,6 +599,7 @@ export function registerNativeSurface(deps: NativeSurfaceDeps): () => void { live.clear() for (const dispose of disposeSubscriptions.reverse()) disposeSafely(dispose, 'a native tab subscription') if (disposeClose !== undefined) disposeSafely(disposeClose, 'the editor close handler') + if (disposeGuide !== undefined) disposeSafely(disposeGuide, 'the start-page guide takeover') } }) return () => { diff --git a/src/client/prefs.ts b/src/client/prefs.ts index 137ea9c3..7e694f14 100644 --- a/src/client/prefs.ts +++ b/src/client/prefs.ts @@ -93,9 +93,32 @@ export function parsePrefs(value: unknown): SidebarPrefs { tabsEnabled: booleanMapOf(record.tabsEnabled), viewersEnabled: booleanMapOf(record.viewersEnabled), pluginSettings: pluginSettingsMapOf(record.pluginSettings), + guideRows: positiveIntegerOf(record.guideRows, SIDEBAR_PREFS_DEFAULTS.guideRows), + guideOrder: uniqueStringListOf(record.guideOrder), + guideHidden: booleanMapOf(record.guideHidden), } } +/** One positive safe integer, or the fallback (row counts are 1-based). */ +function positiveIntegerOf(value: unknown, fallback: number): number { + return typeof value === 'number' && Number.isSafeInteger(value) && value >= 1 ? value : fallback +} + +/** A trimmed, de-duplicated string list preserving first-seen order. */ +function uniqueStringListOf(value: unknown): string[] { + if (!Array.isArray(value)) return [] + const out: string[] = [] + const seen = new Set() + for (const item of value) { + if (typeof item !== 'string') continue + const trimmed = item.trim() + if (trimmed === '' || seen.has(trimmed)) continue + seen.add(trimmed) + out.push(trimmed) + } + return out +} + /** * Validate the plugin-owned settings map (v0.12.0+): `{ descriptorId: { key: * value } }`, nested open maps. Any non-object value (or a malformed whole) diff --git a/src/client/terminal-client.ts b/src/client/terminal-client.ts index 3615cf52..f2a8bbf1 100644 --- a/src/client/terminal-client.ts +++ b/src/client/terminal-client.ts @@ -121,8 +121,29 @@ export interface HostTerminalView { close(): Promise } +/** One shell the host offers for new terminals. */ +export interface HostShellChoice { + readonly name: string + readonly path: string +} + +/** The host's shell catalog and remembered selection. */ +export interface HostShellCatalog { + readonly shells: readonly HostShellChoice[] + /** The shell the host will use when none is named. */ + readonly selectedShell?: string +} + /** The service slice this plugin consumes. */ export interface WebTerminalsFace { + /** + * Shells the host can launch for a session (the guide card's native menu). + * Optional: a host that only exposes the terminal view leaves the plugin + * card as a plain tile. + */ + launchShells?(sessionId: string, signal: AbortSignal): Promise + /** Remember the shell choice for terminals opened afterwards. */ + selectShell?(path: string): void view( sessionId: string, key: string, diff --git a/src/config.ts b/src/config.ts index 013e06c8..ae00de77 100644 --- a/src/config.ts +++ b/src/config.ts @@ -124,6 +124,13 @@ export const PrefsSchema: z = z.object({ // "settings seam" opening — without it the seam would drop third-party // keys as unknown schema fields. pluginSettings: z.dict(z.dict(z.any())).default({}), + // The start page's own layout preferences. `guideRows` is a MAXIMUM row + // count with no upper bound (the layout only ever slices the entry list); + // `guideOrder` and `guideHidden` are open maps so a third-party entry can + // appear or disappear without a schema migration. + guideRows: z.number().step(1).min(1).default(6), + guideOrder: z.array(z.string()).default([]), + guideHidden: z.dict(z.boolean()).default({}), }) // ── The Loader row schema ─────────────────────────────────────────────────── diff --git a/src/prefs-shared.ts b/src/prefs-shared.ts index 5fdf5987..4ae8a525 100644 --- a/src/prefs-shared.ts +++ b/src/prefs-shared.ts @@ -142,6 +142,27 @@ export interface SidebarPrefs { * numbers / booleans; custom panels are responsible for their own). */ pluginSettings: Record> + /** + * Maximum number of rows the native start page draws before the overflow + * collapses into its "More" card. The wide layout puts two cards on a row + * and a narrow one puts one; the minimum is a single row and there is no + * upper bound (a huge value simply never overflows). + */ + guideRows: number + /** + * Explicit start-page order, as `providerId::entryId` keys (the host guide + * card identity). Keys absent from this list follow in registration order; + * keys that no longer exist are ignored. Empty means "registry order". + */ + guideOrder: string[] + /** + * Start-page visibility overrides keyed by `providerId::entryId`. An absent + * key means VISIBLE, so old documents need no migration and a newly + * registered entry shows by default. `false` hides the card from the start + * page only: the tab type stays registered, and shortcuts, resource opens + * and already-open tabs are untouched. + */ + guideHidden: Record } // ── Side-chat composer preferences ────────────────────────────────────────── @@ -207,4 +228,10 @@ export const SIDEBAR_PREFS_DEFAULTS: SidebarPrefs = { tabsEnabled: {}, viewersEnabled: {}, pluginSettings: {}, + // Six rows: on a wide pane that is twelve card slots (the current set of + // native entries fits without a "More" card), while a narrow pane still + // scrolls through six. The value is a maximum, not a fixed height. + guideRows: 6, + guideOrder: [], + guideHidden: {}, } diff --git a/tests/e2e/mount.e2e.ts b/tests/e2e/mount.e2e.ts index 07be4cde..aeeef2a4 100644 --- a/tests/e2e/mount.e2e.ts +++ b/tests/e2e/mount.e2e.ts @@ -308,6 +308,22 @@ test('plugin mounts into the DSH shell and survives a built-in tab sweep', async 'a freshly expanded surface shows the guide page', ).toBeVisible({ timeout: 30_000 }) + // The start page is the PLUGIN's chain takeover, not the host's shipped + // guide: the marker exists only on the plugin's grid, and its column count + // follows the measured pane width (two columns from 520px on). + const startPage = page.locator('[data-dsh-guide-grid]') + await expect(startPage, 'the plugin start-page takeover must own the guide body').toBeVisible({ timeout: 30_000 }) + const startPageGeometry = await startPage.evaluate((element) => ({ + width: element.clientWidth, + columns: element.getAttribute('data-guide-columns'), + })) + expect(startPageGeometry.columns).toBe(startPageGeometry.width >= 520 ? '2' : '1') + // The host's terminal card keeps its native shell menu under the takeover. + await expect( + page.locator('[data-sidebar-right-guide-entry="terminal"] [data-guide-shell-menu]'), + 'the terminal card must expose the host shell menu', + ).toHaveCount(1, { timeout: 30_000 }) + // Every built-in descriptor must be registered as a native tab type: the // guide lists one entry per type, so a missing entry is a real regression // (descriptor removed, registration failed, or the type got disabled). diff --git a/tests/guide-layout.spec.ts b/tests/guide-layout.spec.ts new file mode 100644 index 00000000..ff60b7d4 --- /dev/null +++ b/tests/guide-layout.spec.ts @@ -0,0 +1,91 @@ +/** + * Pure start-page layout: ordering, visibility, the two-column threshold, and + * the overflow that becomes the "More" card. + */ +import { describe, expect, it } from 'vitest' +import { + GUIDE_DEFAULT_ROWS, + GUIDE_TWO_COLUMN_MIN_WIDTH, + columnsForWidth, + computeGuideLayout, + normalizeGuideRows, + orderGuideEntries, +} from '../src/client/native/guide-layout.ts' + +const entries = ['a', 'b', 'c', 'd', 'e'].map(key => ({ key })) + +describe('start-page layout', () => { + it('switches to two columns exactly at the threshold', () => { + expect(columnsForWidth(GUIDE_TWO_COLUMN_MIN_WIDTH - 1)).toBe(1) + expect(columnsForWidth(GUIDE_TWO_COLUMN_MIN_WIDTH)).toBe(2) + expect(columnsForWidth(1200)).toBe(2) + }) + + it('normalizes the row count to at least one and defaults to six', () => { + expect(GUIDE_DEFAULT_ROWS).toBe(6) + expect(normalizeGuideRows(0)).toBe(6) + expect(normalizeGuideRows(-2)).toBe(6) + expect(normalizeGuideRows(2.5)).toBe(6) + expect(normalizeGuideRows(1)).toBe(1) + expect(normalizeGuideRows(40)).toBe(40) + }) + + it('orders by the explicit list and appends unknown entries in registry order', () => { + expect(orderGuideEntries(entries, ['d', 'b']).map(entry => entry.key)) + .toEqual(['d', 'b', 'a', 'c', 'e']) + expect(orderGuideEntries(entries, ['zzz']).map(entry => entry.key)) + .toEqual(['a', 'b', 'c', 'd', 'e']) + // Duplicate order keys keep the first occurrence. + expect(orderGuideEntries(entries, ['c', 'c', 'a']).map(entry => entry.key)) + .toEqual(['c', 'a', 'b', 'd', 'e']) + }) + + it('removes hidden cards before the capacity check', () => { + const layout = computeGuideLayout(entries, { + order: [], + hidden: { b: true, d: true }, + rows: 1, + width: 600, + }) + expect(layout.visible.map(entry => entry.key)).toEqual(['a']) + expect(layout.overflow.map(entry => entry.key)).toEqual(['c', 'e']) + expect(layout.showMore).toBe(true) + }) + + it('reserves one cell for More once the list exceeds the row budget', () => { + const two = computeGuideLayout(entries, { order: [], hidden: {}, rows: 1, width: 600 }) + expect(two.columns).toBe(2) + expect(two.capacity).toBe(2) + expect(two.visible.map(entry => entry.key)).toEqual(['a']) + expect(two.overflow.map(entry => entry.key)).toEqual(['b', 'c', 'd', 'e']) + expect(two.showMore).toBe(true) + + const one = computeGuideLayout(entries, { order: [], hidden: {}, rows: 1, width: 400 }) + expect(one.columns).toBe(1) + expect(one.capacity).toBe(1) + // At the minimum capacity the page shows the More card alone. + expect(one.visible).toEqual([]) + expect(one.overflow).toHaveLength(5) + expect(one.showMore).toBe(true) + }) + + it('shows everything when it fits, with no More card', () => { + const layout = computeGuideLayout(entries, { order: [], hidden: {}, rows: 6, width: 600 }) + expect(layout.capacity).toBe(12) + expect(layout.visible).toHaveLength(5) + expect(layout.overflow).toEqual([]) + expect(layout.showMore).toBe(false) + }) + + it('has no More card when every card is hidden', () => { + const layout = computeGuideLayout(entries, { + order: [], + hidden: { a: true, b: true, c: true, d: true, e: true }, + rows: 1, + width: 400, + }) + expect(layout.visible).toEqual([]) + expect(layout.overflow).toEqual([]) + expect(layout.showMore).toBe(false) + }) +}) diff --git a/tests/native-guide.spec.tsx b/tests/native-guide.spec.tsx new file mode 100644 index 00000000..95649524 --- /dev/null +++ b/tests/native-guide.spec.tsx @@ -0,0 +1,278 @@ +// @vitest-environment jsdom +/** + * Start-page component and catalog: the chain component's cards, the More + * card, hidden entries, the terminal shell menu, and the registry catalog. + */ +import { beforeAll, describe, expect, it, vi } from 'vitest' +import { createElement } from 'react' +import { renderToString } from 'react-dom/server' +import { act } from 'react-dom/test-utils' +import { GuideGrid, NativeGuide } from '../src/client/native/guide.tsx' +import { createNativeGuideCatalog } from '../src/client/native/guide-catalog.ts' +import { registerNativeSurface } from '../src/client/native/index.ts' +import { createNativeTabRecords } from '../src/client/native/tab-adapter.tsx' +import { createBetterSidebarService } from '../src/client/service.ts' +import { createSidebarStore } from '../src/client/state.ts' +import type { NativeGuideEntry } from '../src/client/native/guide-catalog.ts' +import { SIDEBAR_PREFS_DEFAULTS } from '../src/prefs-shared.ts' +import { renderRoot, setupReactAct } from './test-utils.ts' + +setupReactAct() + +beforeAll(() => { + Object.defineProperty(navigator, 'language', { value: 'en-US', configurable: true }) +}) + +/** One synthetic card. */ +function entry(key: string, kind = key): NativeGuideEntry { + return { + key, + providerId: 'p', + entryId: key, + kind, + title: () => key.toUpperCase(), + description: () => key + ' description', + } +} + +/** The five cards most layout tests use. */ +const entries = ['a', 'b', 'c', 'd', 'e'].map(key => entry(key)) + +/** Render one grid into HTML. */ +function htmlOf(props: { + entries?: readonly NativeGuideEntry[] + prefs?: Partial + width?: number + onOpen?: (entry: NativeGuideEntry, params?: Record) => void + shellMenu?: { launchShells: (signal: AbortSignal) => Promise<{ shells: { name: string; path: string }[]; selectedShell?: string }>; selectShell: (path: string) => void } +}): string { + return renderToString(createElement(GuideGrid, { + entries: props.entries ?? entries, + prefs: { ...SIDEBAR_PREFS_DEFAULTS, ...props.prefs }, + width: props.width ?? 600, + onOpen: props.onOpen ?? (() => {}), + ...(props.shellMenu === undefined ? {} : { shellMenu: props.shellMenu }), + })) +} + +describe('GuideGrid', () => { + it('draws two columns and one data entry per card when the list fits', () => { + const html = htmlOf({}) + expect(html).toContain('data-guide-columns="2"') + expect(html).toContain('data-guide-rows="6"') + for (const key of ['a', 'b', 'c', 'd', 'e']) { + expect(html, key).toContain('data-sidebar-right-guide-entry="' + key + '"') + } + expect(html).not.toContain('data-guide-more') + expect(html).toContain('a description') + }) + + it('switches to one column and turns the overflow into the More card', () => { + const wide = htmlOf({ prefs: { guideRows: 1 }, width: 600 }) + expect(wide).toContain('data-guide-columns="2"') + expect(wide).toContain('data-guide-rows="1"') + expect(wide).toContain('data-sidebar-right-guide-entry="a"') + expect(wide).not.toContain('data-sidebar-right-guide-entry="b"') + expect(wide).toContain('data-guide-more="true"') + + const narrow = htmlOf({ prefs: { guideRows: 1 }, width: 400 }) + expect(narrow).toContain('data-guide-columns="1"') + expect(narrow).toContain('data-guide-rows="1"') + // At capacity one the More card is the only cell. + expect(narrow).not.toContain('data-sidebar-right-guide-entry="a"') + expect(narrow).toContain('data-guide-more="true"') + }) + + it('omits hidden cards and keeps the explicit order', () => { + const html = htmlOf({ + prefs: { guideOrder: ['c', 'a'], guideHidden: { a: true } }, + width: 400, + }) + expect(html).not.toContain('data-sidebar-right-guide-entry="a"') + expect(html.indexOf('data-sidebar-right-guide-entry="c"')) + .toBeLessThan(html.indexOf('data-sidebar-right-guide-entry="b"')) + }) + + it('opens a card through the supplied action and closes the guide tab', () => { + const onOpen = vi.fn() + const mounted = renderRoot(createElement(GuideGrid, { + entries, + prefs: { ...SIDEBAR_PREFS_DEFAULTS }, + width: 600, + onOpen, + })) + const card = mounted.container.querySelector('[data-sidebar-right-guide-entry="a"] button') + expect(card).not.toBeNull() + act(() => { (card as HTMLButtonElement).click() }) + expect(onOpen).toHaveBeenCalledWith(expect.objectContaining({ key: 'a' })) + mounted.unmount() + }) + + it('draws the terminal shell trigger only when the host offers both shell faces', () => { + const terminal = entry('terminal') + const without = htmlOf({ entries: [terminal] }) + expect(without).not.toContain('aria-haspopup="menu"') + const shells = { + launchShells: async () => ({ shells: [{ name: 'zsh', path: '/bin/zsh' }], selectedShell: '/bin/zsh' }), + selectShell: () => {}, + } + const withMenu = htmlOf({ entries: [terminal], shellMenu: shells }) + expect(withMenu).toContain('aria-haspopup="menu"') + }) + + it('lists host shells and opens the chosen shell', async () => { + const terminal = entry('terminal') + const selectShell = vi.fn() + const launchShells = vi.fn(async () => ({ + shells: [{ name: 'zsh', path: '/bin/zsh' }, { name: 'bash', path: '/bin/bash' }], + selectedShell: '/bin/zsh', + })) + const onOpen = vi.fn() + const mounted = renderRoot(createElement(GuideGrid, { + entries: [terminal], + prefs: { ...SIDEBAR_PREFS_DEFAULTS }, + width: 600, + onOpen, + shellMenu: { launchShells, selectShell }, + })) + const trigger = mounted.container.querySelector('[data-sidebar-right-guide-entry="terminal"] button[aria-haspopup="menu"]') + expect(trigger).not.toBeNull() + await act(async () => { + ;(trigger as HTMLButtonElement).click() + await Promise.resolve() + }) + expect(launchShells).toHaveBeenCalled() + const bash = [...document.querySelectorAll('[role="menuitem"]')].find(node => node.textContent?.includes('bash')) + expect(bash).toBeDefined() + act(() => { (bash as HTMLElement).click() }) + expect(selectShell).toHaveBeenCalledWith('/bin/bash') + expect(onOpen).toHaveBeenCalledWith(expect.objectContaining({ kind: 'terminal' }), { shellPath: '/bin/bash' }) + mounted.unmount() + }) +}) + +describe('NativeGuide', () => { + it('renders from a real store and catalog without losing their method receivers', () => { + const store = createSidebarStore() + store.setSession('s1') + const catalog = { getSnapshot: () => entries, subscribe: () => () => {} } + const openTab = vi.fn() + const close = vi.fn() + const mounted = renderRoot(createElement(NativeGuide, { + catalog, + store, + useTabInfo: () => ({ tab: { actions: { openTab, close } } }), + })) + const card = mounted.container.querySelector('[data-sidebar-right-guide-entry="a"] button') + expect(card).not.toBeNull() + act(() => { (card as HTMLButtonElement).click() }) + expect(openTab).toHaveBeenCalledWith('a', { replaceTab: true }) + expect(close).toHaveBeenCalled() + mounted.unmount() + }) +}) + +describe('registerNativeSurface start-page takeover', () => { + it('registers one chain guide and releases it with the seat', () => { + const store = createSidebarStore() + store.setSession('s1') + const service = createBetterSidebarService(store) + service.registerTab({ id: 'git', title: 'Changes', component: () => null }) + const records = createNativeTabRecords() + const catalog = { getSnapshot: () => [], subscribe: () => () => {} } + const slotRegistrations: Array<{ name: string; options: Record }> = [] + const released: string[] = [] + const registry = { + register: (definition: { id: string; kind: string }) => () => { released.push(definition.id) }, + } + const ctx = { + inject: (_deps: readonly string[], callback: (injected: { get: (name: string) => unknown }) => unknown) => { + const cleanup = callback({ get: () => registry }) + return { dispose: () => { if (typeof cleanup === 'function') cleanup() } } + }, + get: () => undefined, + slots: { + inject: (_key: string, callback: () => () => void) => callback(), + register: (options: Record) => { + slotRegistrations.push({ name: String(options.name), options }) + return () => { released.push('slot:' + String(options.name)) } + }, + }, + } + const dispose = registerNativeSurface({ + ctx: ctx as never, + store, + service, + records, + guideCatalog: catalog, + }) + const guide = slotRegistrations.filter(item => item.name === 'sidebar.right.tab.guide') + expect(guide).toHaveLength(1) + const select = guide[0]?.options.select as (() => unknown) | undefined + expect(select?.()).toEqual({}) + const inject = guide[0]?.options.inject as ((sessionId: string) => Record) | undefined + const face = inject?.('s1') + expect(face?.catalog).toBe(catalog) + expect(face?.store).toBe(store) + expect(face?.shellMenu).toBeUndefined() + dispose() + expect(released).toContain('slot:sidebar.right.tab.guide') + }) +}) + +describe('createNativeGuideCatalog', () => { + it('maps guide cards to stable keys and the owning descriptor', () => { + const registry = { + guide: () => [ + { id: 'files', kind: 'files', providerId: 'dsh-better-sidebar:files', title: () => 'Files' }, + { id: 'git', kind: 'git', providerId: 'dsh-better-sidebar:git', title: () => 'Git', description: () => 'Changes' }, + { id: 'new', kind: 'terminal', providerId: 'dsh-client-ui-sidebar-terminal', title: () => 'Terminal' }, + ], + subscribe: () => () => {}, + } + const ctx = { + inject: (_deps: readonly string[], callback: (injected: { get: (name: string) => unknown }) => unknown) => { + const cleanup = callback({ get: () => registry }) + return { dispose: () => { if (typeof cleanup === 'function') cleanup() } } + }, + } + const created = createNativeGuideCatalog(ctx as never) + const snapshot = created.catalog.getSnapshot() + expect(snapshot.map(item => item.key)).toEqual([ + 'dsh-better-sidebar:files::files', + 'dsh-better-sidebar:git::git', + 'dsh-client-ui-sidebar-terminal::new', + ]) + expect(snapshot[0]?.descriptorId).toBe('editor') + expect(snapshot[1]?.descriptorId).toBe('git') + expect(snapshot[2]?.descriptorId).toBeUndefined() + expect(snapshot[1]?.description?.()).toBe('Changes') + created.dispose() + }) + + it('notifies subscribers when the registry changes', () => { + let cards: Array<{ id: string; kind: string; providerId: string; title: () => string }> = [] + const listeners = new Set<() => void>() + const registry = { + guide: () => cards, + subscribe: (listener: () => void) => { + listeners.add(listener) + return () => { listeners.delete(listener) } + }, + } + const ctx = { + inject: (_deps: readonly string[], callback: (injected: { get: (name: string) => unknown }) => unknown) => { + const cleanup = callback({ get: () => registry }) + return { dispose: () => { if (typeof cleanup === 'function') cleanup() } } + }, + } + const created = createNativeGuideCatalog(ctx as never) + const listener = vi.fn() + created.catalog.subscribe(listener) + cards = [{ id: 'x', kind: 'x', providerId: 'p', title: () => 'X' }] + for (const notify of listeners) notify() + expect(listener).toHaveBeenCalled() + expect(created.catalog.getSnapshot()).toHaveLength(1) + created.dispose() + }) +}) diff --git a/tests/prefs.spec.ts b/tests/prefs.spec.ts index 532eeb09..49659465 100644 --- a/tests/prefs.spec.ts +++ b/tests/prefs.spec.ts @@ -51,6 +51,9 @@ describe('side card preferences', () => { tabsEnabled: {}, viewersEnabled: {}, pluginSettings: {}, + guideRows: 6, + guideOrder: [], + guideHidden: {}, }) }) @@ -76,6 +79,9 @@ describe('side card preferences', () => { tabsEnabled: {}, viewersEnabled: {}, pluginSettings: {}, + guideRows: 6, + guideOrder: [], + guideHidden: {}, }) }) @@ -101,6 +107,9 @@ describe('side card preferences', () => { tabsEnabled: {}, viewersEnabled: {}, pluginSettings: {}, + guideRows: 6, + guideOrder: [], + guideHidden: {}, }) expect((await loadPrefs(wire({ autoOpenSubagent: 1 }))).autoOpenSubagent) .toBe(true) @@ -216,6 +225,26 @@ describe('side card preferences', () => { expect(parsed.viewersEnabled).toEqual({ image: false }) }) + it('validates the start-page preferences: rows >= 1, a clean order, boolean visibility', async () => { + // Rows are a maximum, 1-based, and malformed/zero values fall back to 6. + expect((await loadPrefs(wire({}))).guideRows).toBe(6) + for (const bad of [undefined, null, 0, -1, 2.5, '4', NaN]) { + expect((await loadPrefs(wire({ guideRows: bad }))).guideRows).toBe(6) + } + expect((await loadPrefs(wire({ guideRows: 1 }))).guideRows).toBe(1) + expect((await loadPrefs(wire({ guideRows: 42 }))).guideRows).toBe(42) + + // The order keeps first-seen order, trims, drops blanks/non-strings and dedupes. + expect((await loadPrefs(wire({ guideOrder: [' b ', 'a', 'b', '', 3] }))).guideOrder) + .toEqual(['b', 'a']) + expect((await loadPrefs(wire({ guideOrder: 'a' }))).guideOrder).toEqual([]) + + // Visibility is an open boolean map; absent means visible. + expect((await loadPrefs(wire({ guideHidden: { a: true, b: false, c: 'yes' } }))).guideHidden) + .toEqual({ a: true, b: false }) + expect((await loadPrefs(wire({ guideHidden: [] }))).guideHidden).toEqual({}) + }) + }) describe('external disable (aionui-panel provider choice)', () => { diff --git a/tests/side-card-section.spec.tsx b/tests/side-card-section.spec.tsx index 05761c98..22ce3dc7 100644 --- a/tests/side-card-section.spec.tsx +++ b/tests/side-card-section.spec.tsx @@ -31,6 +31,7 @@ import { createBetterSidebarService, type BetterSidebarService } from '../src/cl import type { TabDescriptor } from '../src/client/service.ts' import { FeatureSettingsRows, mergePluginSetting, SettingsBody, SideCardSection, type SideCardSectionProps } from '../src/client/SideCardSection.tsx' import { SIDEBAR_PREFS_DEFAULTS } from '../src/prefs-shared.ts' +import type { NativeGuideCatalog, NativeGuideEntry } from '../src/client/native/guide-catalog.ts' /** One tab + one viewer + the subagent-style nested toggle under a tab. */ function mount(): { store: SidebarStore; service: BetterSidebarService } { @@ -68,13 +69,25 @@ function mount(): { store: SidebarStore; service: BetterSidebarService } { return { store, service } } -function renderSection(store: SidebarStore, service: BetterSidebarService): string { +function renderSection( + store: SidebarStore, + service: BetterSidebarService, + guideCatalog?: NativeGuideCatalog, +): string { return renderToString(createElement( SideCardSection, - { store, service } as unknown as SideCardSectionProps, + { store, service, guideCatalog } as unknown as SideCardSectionProps, )) } +/** A catalog with one host terminal card and one third-party card. */ +function guideCatalogOf(entries: readonly NativeGuideEntry[]): NativeGuideCatalog { + return { + getSnapshot: () => entries, + subscribe: () => () => {}, + } +} + /** Count `aria-pressed` occurrences of one value in the rendered HTML. */ function pressedCount(html: string, value: string): number { return html.match(new RegExp(`aria-pressed="${value}"`, 'g'))?.length ?? 0 @@ -115,6 +128,45 @@ describe('SideCardSection declarative inventory', () => { expect(html).toContain('>1') }) + it('lists every native start-page card, ordered, default-on, and not filtered by feature state', () => { + const { store, service } = mount() + const entries: NativeGuideEntry[] = [ + { + key: 'host::terminal', + providerId: 'host', + entryId: 'terminal', + kind: 'terminal', + title: () => 'Terminal', + description: () => 'Shell', + }, + { + key: 'third::dash', + providerId: 'third', + entryId: 'dash', + kind: 'dash', + title: () => 'Dashboard', + }, + ] + const catalog = guideCatalogOf(entries) + let html = renderSection(store, service, catalog) + expect(html).toContain('Start page') + expect(html).toContain('Terminal') + expect(html).toContain('Dashboard') + expect(html).toContain('aria-label="Show on the start page: Terminal"') + expect(html).toContain('aria-label="Maximum rows"') + // Explicit order puts Dashboard before Terminal, independently of catalog order. + store.setPrefs({ ...store.getPrefs(), guideOrder: ['third::dash'] }) + html = renderSection(store, service, catalog) + expect(html.indexOf('>Dashboard<')).toBeLessThan(html.indexOf('>Terminal<')) + // A hidden card stays in the settings list (so it can be restored) and is + // marked off, not dropped. + store.setPrefs({ ...store.getPrefs(), guideHidden: { 'host::terminal': true } }) + html = renderSection(store, service, catalog) + expect(html).toContain('Terminal') + expect(html).toContain('aria-label="Show on the start page: Terminal"') + expect(html).toContain('Dashboard') + }) + it('renders the mobile group: heading + both narrow-viewport switches, on by default', () => { const { store, service } = mount() const html = renderSection(store, service)