feat: 顶层项目行模型 + 按级别收起恢复 + 顶层整区落点与图标区分
- v0.5: 删除「未分类」桶,不归组项目渲染为顶层项目行;null 覆盖=强制顶层; 删除分组成员回顶层;拖拽/菜单移出分组(树中无未分类桶) - v0.6: 拖动只收起被拖级别(拖项目收项目行、分组行不收;拖分组收分组行、 项目行不收),dragend 恢复 dragstart 展开快照 - v0.6.1: 整个顶层区域为移出落点(拖拽中整区高亮 / 空顶层文字落点区, 行间空白可 drop);项目行改用项目符号图标与分组文件夹区分; 行 drop stopPropagation 防重复移出 - 验证脚本:按级别收起/恢复、图标区分、顶层区域空白 drop 断言(42/42); 排序/拖出测试改用手动分组,对用户环境成员数变化健壮 - README 中英双语同步 v0.6.1,替换截图
This commit is contained in:
parent
61717b2be9
commit
3e494b0cfa
75
README.md
75
README.md
|
|
@ -23,38 +23,42 @@
|
|||
|
||||
## Features
|
||||
|
||||
### Three-level tree browsing
|
||||
- **Category folder → project folder → session row**, both levels collapsible; expansion state
|
||||
### Grouped tree browsing
|
||||
- **Group folder → project folder → session row**, both levels collapsible; expansion state
|
||||
persists independently (`dsh.workspace.groups.view.v1`, survives refresh/restart)
|
||||
- **"未分类" fallback bucket**: projects matching no group or moved out of a group land here,
|
||||
**always at the very bottom of the list**
|
||||
- **Top-level project rows**: ungrouped projects (matching no rule, dragged out of a group,
|
||||
or returned by a group delete) render as plain rows right after the group folders, at the
|
||||
same level — **there is no "未分类" bucket**
|
||||
|
||||
### Group management (full lifecycle)
|
||||
- **Create groups manually**: the "新建分组" button in the section header shows the group
|
||||
immediately (empty groups render too)
|
||||
- **Rename / delete any group**: every group row (**rule categories included**) has a hover
|
||||
`⋯` menu; deleting a group sends all of its projects back to "未分类"; rule-category
|
||||
rename/delete rides the overlay (`renamed` / `hidden`), **the rule YAML stays untouched**
|
||||
`⋯` menu; deleting a group sends all of its projects back to the **top level**;
|
||||
rule-category rename/delete rides the overlay (`renamed` / `hidden`),
|
||||
**the rule YAML stays untouched**
|
||||
- **Rule-based auto-classification**: the sidecar YAML declares category rules (`pathPrefix` /
|
||||
`pathExact` / `nameContains` / `basenameContains`); edit the config to adjust grouping
|
||||
without touching code
|
||||
|
||||
### Drag-and-drop grouping + ordering
|
||||
- **Drag projects into groups**: drop on any group row or on a project row inside a group
|
||||
(cross-group move = overrides the rule classification); drop on "未分类" or use the menu
|
||||
"移到未分类" = **forced uncategorized** (rule matches are ignored)
|
||||
- **Drag projects OUT of a group**: even when every project is grouped (the uncategorized
|
||||
bucket is empty and hidden at rest), the bucket **appears while dragging** so you can
|
||||
always drag a project out; rule-classified projects also have the "移到未分类" menu item
|
||||
(cross-group move = overrides the rule classification)
|
||||
- **Drag projects OUT of a group**: the **entire top-level area** is the move-out drop
|
||||
target while dragging — an empty top level shows a dashed drop zone, a non-empty one
|
||||
lights up as a whole (the rows AND the gaps between them accept the drop); grouped
|
||||
projects also have a "移出分组" menu item (rule-classified ones included)
|
||||
- **Reorder projects inside a group**: top half of a project row = insert before it,
|
||||
bottom half = insert after it
|
||||
- **Reorder groups**: group rows are draggable — top half of another group row = move before it,
|
||||
bottom half = move after it
|
||||
- **Insertion position indicator**: a 2px line (above/below the row) shows the exact drop
|
||||
point while dragging — what you see is where it lands
|
||||
- **Smart collapsing**: dragging a project folds the other groups' projects (the source group
|
||||
stays open for ordering); dragging a group folds every group (group rows stay visible as
|
||||
reorder targets)
|
||||
- **Level-aware folding, auto-restored**: dragging a project folds every project row
|
||||
(grouped AND top-level; group rows stay expanded); dragging a group folds every group
|
||||
(project rows keep their expansion) — dragend restores the pre-drag expansion snapshot
|
||||
- **Distinct row icons**: group rows use a folder glyph, project rows a project glyph
|
||||
(same as the official workspace browser) — groups and projects are easy to tell apart
|
||||
|
||||
### Search & operations
|
||||
- **Tree-shaped search**: results keep the three-level structure (category → project → matched
|
||||
|
|
@ -85,8 +89,9 @@
|
|||
grouping overrides, group/project ordering, rule-category renames and hides), validates it
|
||||
and writes it atomically to `$DSH_HOME/workspace-groups.manual.json`.
|
||||
- **Classification priority**: manual override (written by drag/menu; `null` = forced
|
||||
uncategorized) → YAML rule classification (hidden rule categories are inert) → "未分类"
|
||||
bucket (always at the bottom). The YAML is never rewritten.
|
||||
top-level, rules ignored) → YAML rule classification (hidden rule categories are inert)
|
||||
→ **top level** (ungrouped projects render as top-level rows). The YAML is never
|
||||
rewritten.
|
||||
|
||||
## Install (GitHub distribution)
|
||||
|
||||
|
|
@ -161,7 +166,8 @@ first match wins):
|
|||
| `nameContains` | Project display title contains (case-insensitive) |
|
||||
| `basenameContains` | Project directory name contains (case-insensitive) |
|
||||
|
||||
Projects matching no category go into the "未分类" bucket — never hidden.
|
||||
Projects matching no category — or moved out of a group — render as **top-level project
|
||||
rows** (same level as the group folders), never hidden.
|
||||
|
||||
## Manual groups & drag-and-drop grouping (runtime overlay)
|
||||
|
||||
|
|
@ -182,15 +188,15 @@ UI operations**, at `$DSH_HOME/workspace-groups.manual.json` (e.g. `~/.dsh/works
|
|||
}
|
||||
```
|
||||
|
||||
- `categories` — manually created group names (no rules; empty groups render too); names
|
||||
must not collide with rule categories or "未分类".
|
||||
- `categories` — manually created group names (no rules; empty groups render too).
|
||||
- `assignments` — workspace → group classification overrides keyed by the stable workspace id
|
||||
(renames don't affect it). **Takes precedence over YAML rules**; a value of `null` means
|
||||
**forced uncategorized** (even when a rule would match).
|
||||
- `categoryOrder` — group display order ("未分类" is always at the bottom, not listed here).
|
||||
**forced top-level** (even when a rule would match).
|
||||
- `categoryOrder` — group display order (top-level rows are not listed here; they always
|
||||
render after the group folders).
|
||||
- `workspaceOrder` — per-group manual ordering of projects (written by drag ordering).
|
||||
- `renamed` / `hidden` — UI rename/delete of rule categories (a hidden category's rules become
|
||||
inert and its matches fall to "未分类"); the rule YAML stays untouched.
|
||||
inert and its matches go top-level); the rule YAML stays untouched.
|
||||
- The file is written in full by the browser UI (`PUT /workspace-groups/manual`, atomic
|
||||
replace); manual edits also take effect on next load. A malformed write returns 400 and
|
||||
keeps the previous file — the rule YAML is never at risk.
|
||||
|
|
@ -198,11 +204,11 @@ UI operations**, at `$DSH_HOME/workspace-groups.manual.json` (e.g. `~/.dsh/works
|
|||
| Action | How |
|
||||
|---|---|
|
||||
| Create group | "新建分组" button in the section header (folder icon), enter a name in the dialog |
|
||||
| Rename/delete group | hover `⋯` menu on **any** group (rule categories included); deleting sends its projects back to "未分类" |
|
||||
| Rename/delete group | hover `⋯` menu on **any** group (rule categories included); deleting sends its projects back to the top level |
|
||||
| Drag project into group | drag a project row onto a target group row / any project row inside a group, release to move |
|
||||
| Reorder projects | drag a project row onto another project row in the same group: **top half = insert before, bottom half = insert after** (indicator shows the spot); other groups' projects auto-fold while dragging |
|
||||
| Move out of a group | drop on "未分类", or the project row's "移到未分类" menu (forced uncategorized) |
|
||||
| Reorder groups | drag a group row onto another group row: **top half = move before, bottom half = move after** (indicator shows the spot; all groups fold while dragging); "未分类" stays at the bottom |
|
||||
| Reorder projects | drag a project row onto another project row in the same group: **top half = insert before, bottom half = insert after** (indicator shows the spot); all project rows fold while dragging and restore on dragend |
|
||||
| Move out of a group | drop anywhere on the **top-level area** (empty → dashed drop zone / non-empty → whole-area highlight; the gaps between rows count too), or the project row's "移出分组" menu (forced top-level) |
|
||||
| Reorder groups | drag a group row onto another group row: **top half = move before, bottom half = move after** (indicator shows the spot; all groups fold while dragging, restored on dragend) |
|
||||
|
||||
## Topics
|
||||
|
||||
|
|
@ -279,15 +285,24 @@ scripts/
|
|||
correct classification, expansion persistence, search keeps workspace membership;
|
||||
`workspace.json` / session on-disk / official store: zero intrusion.
|
||||
- v0.3 real-browser verification 24/24 (`scripts/verify-groups.mjs`: create group / drag /
|
||||
order / collapse / rule-category menu / rename / delete-back-to-uncategorized / bottom-pinned /
|
||||
order / collapse / rule-category menu / rename / delete-back-to-top-level /
|
||||
scene restore; zero-intrusion assertions).
|
||||
- v0.4 real-browser verification 30/30 (added: insertion indicator, project/group
|
||||
**downward drag** (bottom half → insert after the target), group upward drag (top half →
|
||||
move before the target); scene restored).
|
||||
- v0.4.1 real-browser verification 34/34 (added: dragging projects OUT of a group —
|
||||
the empty uncategorized bucket appears while dragging; drop on it = forced
|
||||
uncategorized; rule-classified projects get the "移到未分类" menu item).
|
||||
- 68 unit tests green (vitest: `core` / `manual` / `tree` / `store`).
|
||||
top-level drop zone / top-level rows = forced top-level; grouped projects get the
|
||||
"移出分组" menu item).
|
||||
- v0.5 real-browser verification 35/35 (model change: **no "未分类" bucket** — top-level
|
||||
project rows, group delete returns members to the top level, drag/menu move-out to the
|
||||
top level, no uncategorized bucket anywhere in the tree; scene restored).
|
||||
- v0.6 real-browser verification 40/40 (added: **level-aware folding** — dragging a project
|
||||
folds project rows only (group rows stay open), dragging a group folds group rows only;
|
||||
dragend restores the pre-drag expansion snapshot).
|
||||
- v0.6.1 real-browser verification 42/42 (added: the whole top-level area as the move-out
|
||||
drop target with a visible landing highlight; distinct folder-vs-project row icons;
|
||||
scene restored).
|
||||
- 66 unit tests green (vitest: `core` / `manual` / `tree` / `store`).
|
||||
- Reproducible automated verification: `node scripts/verify-groups.mjs` (host restarted).
|
||||
|
||||
## License
|
||||
|
|
|
|||
62
README_ZH.md
62
README_ZH.md
|
|
@ -16,7 +16,7 @@
|
|||
|
||||
典型场景:多个 DSH 插件项目(SkillsManagePlugins / Documentation-Driven AI Coding /
|
||||
DeepSeek峰谷小组件 等)归入一个「DSH 插件」分类文件夹,点开是各项目,再点开是各自会话;
|
||||
临时项目随手建个「临时」分组拖进去,用完删除分组即全部回到「未分类」。
|
||||
临时项目随手建个「临时」分组拖进去,用完删除分组,项目全部回归**顶层**。
|
||||
|
||||
## 截图
|
||||
|
||||
|
|
@ -24,29 +24,32 @@ DeepSeek峰谷小组件 等)归入一个「DSH 插件」分类文件夹,点
|
|||
|
||||
## 特性
|
||||
|
||||
### 三层树浏览
|
||||
- **分类文件夹 → 项目文件夹 → 会话行**,分类/项目均可折叠;展开状态独立持久化
|
||||
### 分组树浏览
|
||||
- **分组文件夹 → 项目文件夹 → 会话行**,分组/项目均可折叠;展开状态独立持久化
|
||||
(`dsh.workspace.groups.view.v1`,刷新/重启保留)
|
||||
- **「未分类」兜底桶**:不匹配任何分组、被移出分组的项目自动归入,**恒在列表最底部**
|
||||
- **顶层项目行**:不归组的项目(不匹配任何规则、被移出分组、删除分组后回归的)
|
||||
直接显示在分组列表之后,与分组平级——**没有「未分类」桶**
|
||||
|
||||
### 分组管理(完整生命周期)
|
||||
- **手动新建分组**:区头「新建分组」按钮即建即显,空分组也渲染
|
||||
- **重命名 / 删除任意分组**:每个分组行(**含规则分类**)悬停 `⋯` 菜单;
|
||||
删除分组后组内所有项目回到「未分类」;规则分类的改名/删除经 overlay 生效
|
||||
删除分组后组内所有项目回到**顶层**;规则分类的改名/删除经 overlay 生效
|
||||
(`renamed` / `hidden`),**规则 YAML 原样保留**
|
||||
- **规则自动归类**:sidecar YAML 声明分类规则(`pathPrefix` / `pathExact` /
|
||||
`nameContains` / `basenameContains`),改配置即可调整归类,无需改代码
|
||||
|
||||
### 拖拽归类 + 排序
|
||||
- **拖项目进分组**:拖到任意分组行 / 分组内项目行即移入(跨组移动 = 覆盖规则归类);
|
||||
拖到「未分类」或菜单「移到未分类」= **强制归入未分类**(规则匹配也无效)
|
||||
- **从分组拖出**:即使所有项目都在分组里(未分类桶为空),**拖拽中未分类桶也会
|
||||
临时显示**,随时可把项目拖出分组;规则分类里的项目行菜单同样有「移到未分类」
|
||||
- **拖项目进分组**:拖到任意分组行 / 分组内项目行即移入(跨组移动 = 覆盖规则归类)
|
||||
- **从分组拖出**:拖动时**整个顶层区域都是移出落点**——顶层为空显示虚线落点区、
|
||||
顶层有行时整区高亮(**行与行间空白都可 drop**)= 移出分组;分组内项目行的菜单
|
||||
「移出分组」(规则归类项目也有)
|
||||
- **项目组内排序**:拖到项目行上半 = 插到它前面、下半 = 插到它后面
|
||||
- **分组排序**:分组行可拖动,拖到另一分组行上半 = 移到它前面、下半 = 移到它后面
|
||||
- **插入位置指示线**:拖动中实时显示 2px 指示线(行上/下方),松手落点所见即所得
|
||||
- **智能收起**:拖项目时其他分组的项目自动收起(源分组保留便于排序);拖分组时所有
|
||||
分组收起(分组行仍可见作排序目标)
|
||||
- **按级别收起 + 结束后恢复**:拖项目只收起项目行(分组内 + 顶层,分组行不收);
|
||||
拖分组只收起分组行(项目行不收);dragend 自动恢复拖动前的展开状态
|
||||
- **行图标可区分**:分组行是文件夹图标、项目行是项目符号图标(官方同款),
|
||||
分组与项目一眼可分
|
||||
|
||||
### 搜索与操作
|
||||
- **树形搜索**:命中后仍保留三层树结构(分类 → 项目 → 命中会话),命中行高亮 +
|
||||
|
|
@ -74,8 +77,8 @@ DeepSeek峰谷小组件 等)归入一个「DSH 插件」分类文件夹,点
|
|||
`PUT /workspace-groups/manual` 接收整份 overlay(手动分组、每工作区归类覆盖、
|
||||
分组/项目排序、规则分类改名与隐藏),校验后原子写入
|
||||
`$DSH_HOME/workspace-groups.manual.json`。
|
||||
- **归类优先级**:手动覆盖(拖拽/菜单写入;`null` = 强制未分类)→ YAML 规则
|
||||
自动归类(被隐藏的规则分类失效)→ 「未分类」桶(恒在最底部)。
|
||||
- **归类优先级**:手动覆盖(拖拽/菜单写入;`null` = 强制顶层、规则匹配也无效)→
|
||||
YAML 规则自动归类(被隐藏的规则分类失效)→ **顶层**(不归组的项目显示为顶层行)。
|
||||
YAML 永不改写。
|
||||
|
||||
## 安装(GitHub 分发)
|
||||
|
|
@ -149,7 +152,7 @@ categories:
|
|||
| `nameContains` | 项目显示标题包含(忽略大小写) |
|
||||
| `basenameContains` | 项目目录名包含(忽略大小写) |
|
||||
|
||||
未命中任何分类的项目进入「未分类」桶,不会被隐藏。
|
||||
未命中任何分类、或被移出分组的项目显示为**顶层项目行**(与分组平级),不会被隐藏。
|
||||
|
||||
## 手动分组与拖拽归类(runtime overlay)
|
||||
|
||||
|
|
@ -170,25 +173,24 @@ categories:
|
|||
}
|
||||
```
|
||||
|
||||
- `categories` —— 手动新建的分组名(无规则,空分组也渲染);名称不可与规则分类
|
||||
或「未分类」重复。
|
||||
- `categories` —— 手动新建的分组名(无规则,空分组也渲染)。
|
||||
- `assignments` —— 工作区 → 分组的归类覆盖,键是稳定的工作区 id(重命名不影响)。
|
||||
**优先级高于 YAML 规则**;值为 `null` 表示**强制归入未分类**(即使规则能匹配)。
|
||||
- `categoryOrder` —— 分组显示顺序(「未分类」恒在最底部,不在此列)。
|
||||
**优先级高于 YAML 规则**;值为 `null` 表示**强制移到顶层**(即使规则能匹配)。
|
||||
- `categoryOrder` —— 分组显示顺序(顶层项目不在此列,恒显示在分组之后)。
|
||||
- `workspaceOrder` —— 每个分组内项目的手动排序(拖拽排序写入)。
|
||||
- `renamed` / `hidden` —— 规则分类的 UI 改名/删除(隐藏后其规则失效,匹配项目
|
||||
落入未分类);规则 YAML 原样保留。
|
||||
变顶层);规则 YAML 原样保留。
|
||||
- 文件由浏览器 UI 全量写入(`PUT /workspace-groups/manual`,原子替换),手工编辑
|
||||
同样生效(下次加载时读取);写坏会返回 400 并保留原文件,不会破坏规则 YAML。
|
||||
|
||||
| 操作 | 入口 |
|
||||
|---|---|
|
||||
| 新建分组 | 区头「新建分组」按钮(文件夹图标),弹窗输入名称 |
|
||||
| 重命名/删除分组 | **任意分组**(含规则分类)悬停 `⋯` 菜单;删除后组内项目回「未分类」 |
|
||||
| 重命名/删除分组 | **任意分组**(含规则分类)悬停 `⋯` 菜单;删除后组内项目回顶层 |
|
||||
| 拖项目进分组 | 拖动项目行到目标分组行 / 分组内任意项目行,松手即移入 |
|
||||
| 项目排序 | 拖动项目行到同组另一项目行:**上半 = 插到它前、下半 = 插到它后**(指示线显示落点);拖动时其他分组项目自动收起 |
|
||||
| 移出分组 | 拖到「未分类」,或项目行菜单「移到未分类」(强制归入未分类) |
|
||||
| 分组排序 | 拖动分组行到另一分组行:**上半 = 移到它前、下半 = 移到它后**(指示线显示落点;拖动时所有分组收起);未分类恒在底部 |
|
||||
| 项目排序 | 拖动项目行到同组另一项目行:**上半 = 插到它前、下半 = 插到它后**(指示线显示落点);拖动时所有项目行收起、dragend 恢复 |
|
||||
| 移出分组 | 拖到**顶层区域任意位置**(顶层为空显示虚线落点区 / 有行时整区高亮,行间空白也可 drop),或项目行菜单「移出分组」(强制移到顶层) |
|
||||
| 分组排序 | 拖动分组行到另一分组行:**上半 = 移到它前、下半 = 移到它后**(指示线显示落点;拖动时所有分组收起、dragend 恢复) |
|
||||
|
||||
## 收录标签(topics)
|
||||
|
||||
|
|
@ -262,12 +264,18 @@ scripts/
|
|||
- v0.1/v0.2 真实组合验证(headless Chrome + CDP 实操):三层树顶替生效、分类正确、
|
||||
展开持久化、搜索保留归属;`workspace.json` / 会话落盘 / 官方 store 零侵入。
|
||||
- v0.3 真机验证 24/24(`scripts/verify-groups.mjs`:建组/拖拽/排序/收起/规则分类
|
||||
菜单/重命名/删除回未分类/置底/现场恢复,零侵入断言)。
|
||||
菜单/重命名/删除回顶层/现场恢复,零侵入断言)。
|
||||
- v0.4 真机验证 30/30(新增:插入指示线、项目/分组**向下拖**(行下半 → 插到目标
|
||||
之后)、分组向上拖(行上半 → 移到目标之前);现场恢复通过)。
|
||||
- v0.4.1 真机验证 34/34(新增:**从分组拖出**——未分类桶为空时拖拽中也显示,
|
||||
拖到其上 = 强制未分类;规则分类项目行也有「移到未分类」菜单)。
|
||||
- 单测 68 用例全绿(vitest:`core` / `manual` / `tree` / `store`)。
|
||||
- v0.4.1 真机验证 34/34(新增:**从分组拖出**——顶层落点区/顶层行 drop =
|
||||
强制顶层;分组内项目行菜单「移出分组」)。
|
||||
- v0.5 真机验证 35/35(模型变更:**无「未分类」桶**——顶层项目行、删除分组成员
|
||||
回顶层、拖拽/菜单移出到顶层、树中不存在未分类桶;现场恢复)。
|
||||
- v0.6 真机验证 40/40(新增:**按级别收起**——拖项目只收起项目行(分组行不收)、
|
||||
拖分组只收起分组行(项目行不收);dragend 还原拖动前展开快照)。
|
||||
- v0.6.1 真机验证 42/42(新增:**整个顶层区域为移出落点**且拖拽中有可见高亮提示;
|
||||
分组/项目行图标区分;现场恢复)。
|
||||
- 单测 66 用例全绿(vitest:`core` / `manual` / `tree` / `store`)。
|
||||
- 可复跑的自动化真机验证:`node scripts/verify-groups.mjs`(需 host 已重启)。
|
||||
|
||||
## License
|
||||
|
|
|
|||
466
lib/client.js
466
lib/client.js
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
|
@ -2446,7 +2446,12 @@ function requireJsYaml() {
|
|||
const { Type, Schema, FAILSAFE_SCHEMA, JSON_SCHEMA, CORE_SCHEMA, DEFAULT_SCHEMA, load, loadAll, dump, YAMLException, types, safeLoad, safeLoadAll, safeDump } = /* @__PURE__ */ getDefaultExportFromCjs(requireJsYaml());
|
||||
//#endregion
|
||||
//#region src/core/types.ts
|
||||
/** The label of the fallback bucket for unmatched workspaces. */
|
||||
/**
|
||||
* Legacy label of the fallback bucket. The top-level (ungrouped) concept
|
||||
* replaced the rendered "未分类" bucket: workspaces in no group render as
|
||||
* top-level rows beside the group folders. The constant survives for data
|
||||
* compatibility (reserved name, assignment null marker).
|
||||
*/
|
||||
const UNCATEGORIZED_LABEL = "未分类";
|
||||
//#endregion
|
||||
//#region src/core/matcher.ts
|
||||
|
|
|
|||
|
|
@ -1,9 +1,15 @@
|
|||
import type { GroupsBrowserProps } from './contract.ts';
|
||||
/** Row reference used by drop targets: which kind of row, which key. */
|
||||
export type DropRowRef = {
|
||||
kind: 'category' | 'workspace';
|
||||
kind: 'category' | 'workspace' | 'topLevel';
|
||||
key: string;
|
||||
};
|
||||
/**
|
||||
* Which level's rows fold while a drag is in progress: dragging a project
|
||||
* folds every project row (grouped AND top-level), dragging a group folds
|
||||
* every group row. The other level keeps its expansion untouched.
|
||||
*/
|
||||
export type DragLevel = 'workspace' | 'category' | null;
|
||||
/**
|
||||
* Current drop indicator. A `line` renders a 2px insertion line above/below a
|
||||
* row (project reorder inside a group, or group reorder); an `into` renders
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@
|
|||
*/
|
||||
import type { LocaleDictOf } from '@deepseek-ai/dsh-client-ui-slots';
|
||||
/** Dictionary keys of the workspaceGroups namespace (single source of truth). */
|
||||
export type WorkspaceGroupsKey = 'section.workspaces' | 'section.sessions' | 'search' | 'search.placeholder' | 'search.clear' | 'search.noMatches' | 'search.unavailable' | 'search.pending' | 'search.hasMore' | 'search.results.aria' | 'workspace.add' | 'workspace.addBusy' | 'workspace.addError' | 'workspace.addErrorTitle' | 'workspace.rename' | 'workspace.delete' | 'workspace.deleteTitle' | 'workspace.deleteConfirm' | 'workspace.deleteCancel' | 'workspace.renaming' | 'workspace.deleting' | 'workspace.renameTitle' | 'workspace.renamePlaceholder' | 'workspace.renameConfirm' | 'workspace.renameCancel' | 'workspace.moveToUncategorized' | 'group.create' | 'group.createTitle' | 'group.createPlaceholder' | 'group.createConfirm' | 'group.createCancel' | 'group.rename' | 'group.renameTitle' | 'group.renameConfirm' | 'group.delete' | 'group.deleteTitle' | 'group.deleteConfirm' | 'group.deleteCancel' | 'group.nameDuplicate' | 'group.nameReserved' | 'manual.saveError' | 'session.new' | 'session.rename' | 'session.archive' | 'session.fork' | 'session.renameTitle' | 'session.renamePlaceholder' | 'session.renameConfirm' | 'session.renameCancel' | 'session.renaming' | 'uncategorized' | 'empty.none' | 'empty.noWorkspaces' | 'close' | 'cancel' | 'confirm' | 'retry' | 'configUnavailable' | 'collapse' | 'expandMore' | 'newSession';
|
||||
export type WorkspaceGroupsKey = 'section.workspaces' | 'section.sessions' | 'search' | 'search.placeholder' | 'search.clear' | 'search.noMatches' | 'search.unavailable' | 'search.pending' | 'search.hasMore' | 'search.results.aria' | 'workspace.add' | 'workspace.addBusy' | 'workspace.addError' | 'workspace.addErrorTitle' | 'workspace.rename' | 'workspace.delete' | 'workspace.deleteTitle' | 'workspace.deleteConfirm' | 'workspace.deleteCancel' | 'workspace.renaming' | 'workspace.deleting' | 'workspace.renameTitle' | 'workspace.renamePlaceholder' | 'workspace.renameConfirm' | 'workspace.renameCancel' | 'workspace.moveOutOfGroup' | 'group.create' | 'group.createTitle' | 'group.createPlaceholder' | 'group.createConfirm' | 'group.createCancel' | 'group.rename' | 'group.renameTitle' | 'group.renameConfirm' | 'group.delete' | 'group.deleteTitle' | 'group.deleteConfirm' | 'group.deleteCancel' | 'group.nameDuplicate' | 'group.nameReserved' | 'group.dropTopLevel' | 'section.topLevel' | 'manual.saveError' | 'session.new' | 'session.rename' | 'session.archive' | 'session.fork' | 'session.renameTitle' | 'session.renamePlaceholder' | 'session.renameConfirm' | 'session.renameCancel' | 'session.renaming' | 'uncategorized' | 'empty.none' | 'empty.noWorkspaces' | 'close' | 'cancel' | 'confirm' | 'retry' | 'configUnavailable' | 'collapse' | 'expandMore' | 'newSession';
|
||||
export type WorkspaceGroupsDict = LocaleDictOf<'workspaceGroups'>;
|
||||
/** Simplified Chinese dictionary. */
|
||||
export declare const zh: WorkspaceGroupsDict;
|
||||
|
|
|
|||
|
|
@ -52,16 +52,18 @@ export declare function CategoryRow({ node, t, onToggle, onRename, onDelete, dro
|
|||
onDragStartCategory?: (event: DragEvent) => void;
|
||||
} & RowDropProps): import("react").JSX.Element;
|
||||
/** One workspace folder row inside a category: draggable source + drop target. */
|
||||
export declare function WorkspaceRow({ node, t, onToggle, onNewSession, onRename, onDelete, canMoveOut, onMoveOut, dropActive, insertLine, onRowDragOver, onRowDragLeave, onRowDrop, onDragStartExtra }: {
|
||||
export declare function WorkspaceRow({ node, t, onToggle, onNewSession, onRename, onDelete, canMoveOut, onMoveOut, flat, dropActive, insertLine, onRowDragOver, onRowDragLeave, onRowDrop, onDragStartExtra }: {
|
||||
node: WorkspaceGroupNode;
|
||||
t: T;
|
||||
onToggle: () => void;
|
||||
onNewSession: () => void;
|
||||
onRename: () => void;
|
||||
onDelete: () => void;
|
||||
/** Project currently sits inside a group — offer "move to uncategorized". */
|
||||
/** Project currently sits inside a group — offer "move out of group". */
|
||||
canMoveOut?: boolean;
|
||||
onMoveOut?: () => void;
|
||||
/** Render as a top-level row (no folder indentation). */
|
||||
flat?: boolean;
|
||||
/** Extra dragstart hook (e.g. collapse all expanded projects while dragging). */
|
||||
onDragStartExtra?: () => void;
|
||||
} & RowDropProps): import("react").JSX.Element;
|
||||
|
|
|
|||
|
|
@ -78,13 +78,12 @@ export declare function workspaceLabel(cwd: string | undefined): string;
|
|||
*/
|
||||
export declare function deriveGroups(list: SessionListState, workspaces: readonly WorkspaceView[], archivedSessionIds: readonly SessionId[], config: GroupsConfig, view: GroupsTreeView, manual: ManualGroups): CategoryNode[];
|
||||
/**
|
||||
* While a drag is in progress, the empty uncategorized bucket must still
|
||||
* render as a drop target — otherwise a project can never be dragged OUT of a
|
||||
* group when every project is grouped (the bucket hides when empty). Appends
|
||||
* a collapsed empty uncategorized node when the bucket is absent; never
|
||||
* duplicates an existing one. Pure; the caller decides when a drag is active.
|
||||
* Top-level (ungrouped) workspace rows: workspaces resolving to no category
|
||||
* (no manual override and no matching rule, or a forced `null` override).
|
||||
* Rendered after the group folders as plain project rows (not inside any
|
||||
* folder), in host registration order.
|
||||
*/
|
||||
export declare function withDraggingUncategorized(groups: readonly CategoryNode[], dragging: boolean): readonly CategoryNode[];
|
||||
export declare function deriveTopLevel(list: SessionListState, workspaces: readonly WorkspaceView[], archivedSessionIds: readonly SessionId[], config: GroupsConfig, view: GroupsTreeView, manual: ManualGroups): WorkspaceGroupNode[];
|
||||
/** Bounded set of matched sessions plus content snippets (feeds the search tree). */
|
||||
export interface SearchMatchSet {
|
||||
/** Session ids that matched (local metadata hits + Host content hits). */
|
||||
|
|
@ -102,12 +101,20 @@ export declare function deriveSearchMatches(list: SessionListState, workspaces:
|
|||
items: readonly SessionSearchResultItem[];
|
||||
hasMore: boolean;
|
||||
}, limit: number): SearchMatchSet;
|
||||
/** Search tree: group folders plus top-level (ungrouped) matched workspaces. */
|
||||
export interface SearchTree {
|
||||
/** Group folders containing matched sessions, in display order. */
|
||||
categories: CategoryNode[];
|
||||
/** Top-level (ungrouped) workspaces holding matched sessions. */
|
||||
topLevel: WorkspaceGroupNode[];
|
||||
}
|
||||
/**
|
||||
* Build a three-level search tree containing ONLY the branches that hold a
|
||||
* matched session: 分类文件夹 → 项目文件夹 → 命中会话行. Every matched
|
||||
* session carries `matched: true` so rows render with the search-hit tint.
|
||||
* Classification uses the same precedence as the idle tree (manual override →
|
||||
* rules), so search shows the same grouping the user sees.
|
||||
* rules), so search shows the same grouping the user sees. Matched top-level
|
||||
* workspaces are returned separately (rendered as plain rows).
|
||||
*
|
||||
* @param list - sessions list snapshot.
|
||||
* @param workspaces - real workspaces in stable Host order.
|
||||
|
|
@ -116,6 +123,7 @@ export declare function deriveSearchMatches(list: SessionListState, workspaces:
|
|||
* @param archivedSessionIds - registry-global archive set.
|
||||
* @param manual - runtime overlay (manual groups + overrides).
|
||||
* @param snippetsBySession - optional content-match snippets keyed by session id.
|
||||
* @returns categories in render order, pruned to matched branches only.
|
||||
* @returns group folders in render order plus top-level matched workspaces,
|
||||
* pruned to matched branches only.
|
||||
*/
|
||||
export declare function deriveSearchGroups(list: SessionListState, workspaces: readonly WorkspaceView[], config: GroupsConfig, matchedIds: ReadonlySet<SessionId>, archivedSessionIds: readonly SessionId[], manual: ManualGroups, snippetsBySession?: ReadonlyMap<SessionId, string>): CategoryNode[];
|
||||
export declare function deriveSearchGroups(list: SessionListState, workspaces: readonly WorkspaceView[], config: GroupsConfig, matchedIds: ReadonlySet<SessionId>, archivedSessionIds: readonly SessionId[], manual: ManualGroups, snippetsBySession?: ReadonlyMap<SessionId, string>): SearchTree;
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@
|
|||
* name (or a manual-group name). Its DISPLAY key is what the tree renders and
|
||||
* what assignments reference — for rule categories that is the rename
|
||||
* override when present. Hidden rule categories are inert: workspaces that
|
||||
* would match them fall into the uncategorized bucket.
|
||||
* would match them become top-level (ungrouped).
|
||||
*/
|
||||
import { type GroupCategory, type GroupsConfig, type ManualGroups } from './types.ts';
|
||||
/** Classify a workspace by rules only; hidden categories are inert. */
|
||||
|
|
@ -25,7 +25,8 @@ export declare function originalRuleNameForDisplay(categories: readonly GroupCat
|
|||
* Effective category entries in display order: rule categories (YAML order,
|
||||
* hidden skipped, renamed applied) first, then manual-only groups in
|
||||
* creation order — unless `manual.categoryOrder` overrides the sequence.
|
||||
* The uncategorized bucket is never included (it always renders last).
|
||||
* Top-level (ungrouped) workspaces are never included; they render as
|
||||
* separate top-level rows after the group folders.
|
||||
*/
|
||||
export interface EffectiveCategory {
|
||||
/** Display key (what the tree renders and assignments reference). */
|
||||
|
|
@ -34,19 +35,19 @@ export interface EffectiveCategory {
|
|||
source: 'rule' | 'manual';
|
||||
}
|
||||
export declare function effectiveCategories(config: GroupsConfig, manual: ManualGroups | undefined): EffectiveCategory[];
|
||||
/** Display keys of all effective categories (uncategorized bucket excluded). */
|
||||
/** Display keys of all effective categories (top-level workspaces excluded). */
|
||||
export declare function displayCategoryKeys(config: GroupsConfig, manual: ManualGroups | undefined): string[];
|
||||
/**
|
||||
* Resolve the category key a workspace renders under. Precedence:
|
||||
* manual override (`null` = force uncategorized) → rule classification
|
||||
* (hidden rules inert) → uncategorized bucket (`undefined`).
|
||||
* Resolve the category key a workspace renders under, or `undefined` when it
|
||||
* is top-level (ungrouped). Precedence: manual override (`null` = forced
|
||||
* top-level) → rule classification (hidden rules inert) → top-level.
|
||||
*/
|
||||
export declare function resolveCategory(config: GroupsConfig, manual: ManualGroups | undefined, workspaceId: string, path: string, title: string): string | undefined;
|
||||
/** Whether a category key is a manual-only group (manageable via list). */
|
||||
export declare function isManualOnlyCategory(config: GroupsConfig, manual: ManualGroups | undefined, key: string): boolean;
|
||||
/**
|
||||
* Names that may not be used for a new/renamed group: the reserved
|
||||
* uncategorized label plus every current display key.
|
||||
* Names that may not be used for a new/renamed group: the legacy reserved
|
||||
* label plus every current display key.
|
||||
*/
|
||||
export declare function takenCategoryNames(config: GroupsConfig, manual: ManualGroups | undefined): Set<string>;
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -77,11 +77,16 @@ export interface ManualGroups {
|
|||
renamed?: Record<string, string>;
|
||||
/**
|
||||
* Rule category original names hidden by a UI delete. Hidden rules are
|
||||
* inert: workspaces matching them fall into the uncategorized bucket.
|
||||
* inert: workspaces matching them become top-level (ungrouped).
|
||||
*/
|
||||
hidden?: string[];
|
||||
}
|
||||
/** The label of the fallback bucket for unmatched workspaces. */
|
||||
/**
|
||||
* Legacy label of the fallback bucket. The top-level (ungrouped) concept
|
||||
* replaced the rendered "未分类" bucket: workspaces in no group render as
|
||||
* top-level rows beside the group folders. The constant survives for data
|
||||
* compatibility (reserved name, assignment null marker).
|
||||
*/
|
||||
export declare const UNCATEGORIZED_LABEL = "\u672A\u5206\u7C7B";
|
||||
/** Normalize a path for prefix matching: trailing slashes stripped. */
|
||||
export declare function normalizePath(path: string): string;
|
||||
|
|
|
|||
BIN
screenshot.png
BIN
screenshot.png
Binary file not shown.
|
Before Width: | Height: | Size: 173 KiB After Width: | Height: | Size: 72 KiB |
|
|
@ -9,11 +9,15 @@
|
|||
* - v0.2:新建分组弹窗 → 空分组渲染 → 拖拽项目进分组 → PUT 落盘 →
|
||||
* 刷新持久化 → 非法 PUT 400;
|
||||
* - v0.3:拖拽项目组内排序 + 拖动时其他分组项目收起、规则分类行出现
|
||||
* 「⋯」菜单 → 重命名(renamed 落盘)→ 删除(成员回未分类 + hidden 落盘)、
|
||||
* 未分类恒为最末段;
|
||||
* 「⋯」菜单 → 重命名(renamed 落盘)→ 删除(成员回顶层 + hidden 落盘)、
|
||||
* 树中不存在「未分类」桶;
|
||||
* - v0.4:拖拽插入位置指示线(上半=插到行前 / 下半=插到行后):项目
|
||||
* 拖到目标行下半 → 插到目标之后;分组向下拖 → 移到目标分组之后、
|
||||
* 向上拖 → 移到目标分组之前;
|
||||
* - v0.4.1:从分组拖出到顶层(拖拽中顶层落点区显示、拖出落盘 null、
|
||||
* 顶层行渲染、分组内项目菜单「移出分组」);
|
||||
* - v0.6:按级别收起 + 结束后恢复 —— 拖项目只折叠项目行(分组内+顶层)、
|
||||
* 分组行不收;拖分组只折叠分组行、项目行不收;dragend 还原拖动前快照;
|
||||
* - 现场恢复:还原原 overlay(原无文件则删除),不留测试数据;
|
||||
* - 依赖 host 已重启(PUT /workspace-groups/manual 可用);
|
||||
* - 以 0/1 退出码供质量门调用。
|
||||
|
|
@ -69,6 +73,10 @@ async function main() {
|
|||
const profileDir = await mkdtemp(join(tmpdir(), 'wg-cdp-'))
|
||||
let chrome
|
||||
let page
|
||||
// Hoisted for the finally-block scene restore (runs even when steps throw).
|
||||
let originalManual = null
|
||||
let overlayPath = ''
|
||||
let overlayExistedBefore = false
|
||||
try {
|
||||
chrome = spawn(CHROME, [
|
||||
`--remote-debugging-port=${CDP_PORT}`,
|
||||
|
|
@ -121,13 +129,20 @@ async function main() {
|
|||
report('host GET /workspace-groups/config 可访问', false, String(error))
|
||||
return 1
|
||||
}
|
||||
const originalManual = snapshot.manual ?? { categories: [], assignments: {} }
|
||||
const overlayPath = join(process.env.DSH_HOME ?? join(process.env.HOME ?? '.', '.dsh'), 'workspace-groups.manual.json')
|
||||
const overlayExistedBefore = await access(overlayPath).then(() => true, () => false)
|
||||
originalManual = snapshot.manual ?? { categories: [], assignments: {} }
|
||||
try {
|
||||
overlayPath = join(process.env.DSH_HOME ?? join(process.env.HOME ?? '.', '.dsh'), 'workspace-groups.manual.json')
|
||||
overlayExistedBefore = await access(overlayPath).then(() => true, () => false)
|
||||
} catch { /* non-fatal */ }
|
||||
|
||||
// ---- 1. GUI 树就绪 ----
|
||||
report('GUI 三层树渲染(.wgRoot + 项目行)', await waitFor(`document.querySelectorAll('.wgProjectRow').length > 0`))
|
||||
report('区头存在「新建分组」按钮', await evaluate(`!!document.querySelector('button[aria-label="新建分组"]')`))
|
||||
report('分组行与项目行图标可区分(文件夹 vs 项目符号)', await evaluate(`(() => {
|
||||
const g = document.querySelector('.wgCategoryRow [data-wg-row-icon="group"] svg')?.outerHTML ?? ''
|
||||
const p = document.querySelector('.wgProjectRow [data-wg-row-icon="project"] svg')?.outerHTML ?? ''
|
||||
return g !== '' && p !== '' && g !== p
|
||||
})()`))
|
||||
|
||||
// ---- 2. 新建分组 ----
|
||||
const groupName = '验证分组'
|
||||
|
|
@ -205,143 +220,74 @@ async function main() {
|
|||
if (cat1 === undefined) {
|
||||
report('v0.3 需至少一个可见规则分类(跳过排序/收起断言)', false, `categories=${JSON.stringify(ruleKeys)}`)
|
||||
} else {
|
||||
// Expand both rule categories so their project rows are visible.
|
||||
// Expand both rule categories so their project rows are visible, then
|
||||
// expand every project row (the v0.6 fold/restore assertions need them
|
||||
// expanded before the drag starts).
|
||||
const expandCat = (key) => evaluate(`(() => {
|
||||
const row = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(key)}]')
|
||||
if (!row) return false
|
||||
if (row.getAttribute('aria-expanded') === 'false') row.click()
|
||||
return true
|
||||
})()`)
|
||||
const expandProject = (key) => evaluate(`(() => {
|
||||
const section = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(key)}]')?.parentElement
|
||||
if (!section) return false
|
||||
for (const row of section.querySelectorAll('.wgProjectRow')) {
|
||||
if (row.getAttribute('aria-expanded') === 'false') row.click()
|
||||
}
|
||||
return true
|
||||
})()`)
|
||||
await expandCat(cat1)
|
||||
await expandCat(cat2)
|
||||
// NOTE: cat1 (first visible rule category) may have only 1 member left —
|
||||
// the v0.2 flow dragged one project out of it, and the user environment
|
||||
// may already have few members. Assertions must not require >= 2 rows in
|
||||
// cat1; reorder/drag-out tests run against cat2 (验证分组) instead.
|
||||
const rowsVisible = await waitFor(`(() => {
|
||||
const s1 = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat1)}]')?.parentElement
|
||||
const s2 = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat2)}]')?.parentElement
|
||||
return !!s1 && !!s2 && s1.querySelectorAll('.wgProjectRow').length >= 2 && s2.querySelectorAll('.wgProjectRow').length >= 1
|
||||
return !!s1 && !!s2 && s1.querySelectorAll('.wgProjectRow').length >= 1 && s2.querySelectorAll('.wgProjectRow').length >= 1
|
||||
})()`)
|
||||
report('两个规则分类展开且项目行可见', rowsVisible)
|
||||
|
||||
const reorder = await evaluate(`(() => {
|
||||
await expandProject(cat1)
|
||||
await expandProject(cat2)
|
||||
report('项目行展开(会话可见,供折叠断言用)', await waitFor(`(() => {
|
||||
const s1 = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat1)}]')?.parentElement
|
||||
if (!s1) return { error: 'no section' }
|
||||
const rows = s1.querySelectorAll('.wgProjectRow')
|
||||
const source = rows[1] // drag the second project
|
||||
const target = rows[0] // drop before the first
|
||||
if (!source || !target) return { error: 'rows missing' }
|
||||
const dt = new DataTransfer()
|
||||
source.dispatchEvent(new DragEvent('dragstart', { bubbles: true, cancelable: true, dataTransfer: dt }))
|
||||
window.__wgDt = dt // stash for the drop step (React re-renders may recreate rows)
|
||||
return { wsid: source.getAttribute('data-wsid'), targetWsid: target.getAttribute('data-wsid') }
|
||||
})()`)
|
||||
// React commits the collapse on the next render — wait for the other
|
||||
// category's project rows to disappear before dropping.
|
||||
report('拖动项目时其他分组项目收起', await waitFor(`(() => {
|
||||
const s2 = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat2)}]')?.parentElement
|
||||
return !!s2 && s2.querySelectorAll('.wgProjectRow').length === 0
|
||||
})()`, 5000))
|
||||
await evaluate(`(() => {
|
||||
const s1 = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat1)}]')?.parentElement
|
||||
if (!s1) return false
|
||||
const target = s1.querySelector('.wgProjectRow')
|
||||
if (!target || !window.__wgDt) return false
|
||||
target.dispatchEvent(new DragEvent('dragover', { bubbles: true, cancelable: true, dataTransfer: window.__wgDt }))
|
||||
target.dispatchEvent(new DragEvent('drop', { bubbles: true, cancelable: true, dataTransfer: window.__wgDt }))
|
||||
return true
|
||||
})()`)
|
||||
// The user-visible contract: the dragged project now renders first in the group.
|
||||
report('组内拖拽排序(第二个项目移到第一个之前)', await waitFor(`(() => {
|
||||
const s1 = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat1)}]')?.parentElement
|
||||
if (!s1) return false
|
||||
const first = s1.querySelector('.wgProjectRow')
|
||||
return !!first && first.getAttribute('data-wsid') === ${JSON.stringify(reorder.wsid)}
|
||||
const rows1 = s1 ? [...s1.querySelectorAll('.wgProjectRow')] : []
|
||||
const rows2 = s2 ? [...s2.querySelectorAll('.wgProjectRow')] : []
|
||||
return rows1.length >= 1 && rows1.every(r => r.getAttribute('aria-expanded') === 'true')
|
||||
&& rows2.length >= 1 && rows2.every(r => r.getAttribute('aria-expanded') === 'true')
|
||||
})()`))
|
||||
|
||||
// ---- v0.4:拖到目标行下半 → 插到目标之后(指示线可见) ----
|
||||
const reorderAfter = await evaluate(`(() => {
|
||||
const s1 = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat1)}]')?.parentElement
|
||||
if (!s1) return { error: 'no section' }
|
||||
const rows = s1.querySelectorAll('.wgProjectRow')
|
||||
const source = rows[0] // currently the first project
|
||||
const target = rows[1] // drop on the BOTTOM half of the second
|
||||
if (!source || !target) return { error: 'rows missing' }
|
||||
// ---- 排序前置:从顶层拖一个项目进 cat2(组内排序需要 2 个成员) ----
|
||||
// cat1 只剩 1 个成员,不能再消耗它;顶层项目(null 覆盖)是安全来源。
|
||||
const seedTop = await evaluate(`(() => {
|
||||
const source = document.querySelector('.wgProjectRow.wgProjectFlat')
|
||||
const target = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat2)}]')
|
||||
if (!source || !target) return { error: 'no top-level row or cat2' }
|
||||
const dt = new DataTransfer()
|
||||
source.dispatchEvent(new DragEvent('dragstart', { bubbles: true, cancelable: true, dataTransfer: dt }))
|
||||
const rect = target.getBoundingClientRect()
|
||||
target.dispatchEvent(new DragEvent('dragover', { bubbles: true, cancelable: true, clientY: rect.top + rect.height - 1, dataTransfer: dt }))
|
||||
window.__wgDt = dt // stash for the drop step
|
||||
return { sourceWsid: source.getAttribute('data-wsid'), targetWsid: target.getAttribute('data-wsid') }
|
||||
})()`)
|
||||
report('拖项目悬停行下半 → 下方插入指示线', await waitFor(`(() => {
|
||||
const s1 = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat1)}]')?.parentElement
|
||||
return !!s1 && !!s1.querySelector('.wgProjectRow.wgInsertAfter')
|
||||
})()`, 5000))
|
||||
await evaluate(`(() => {
|
||||
const s1 = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat1)}]')?.parentElement
|
||||
if (!s1) return false
|
||||
const target = s1.querySelector('.wgProjectRow[data-wsid="${reorderAfter.targetWsid}"]')
|
||||
if (!target || !window.__wgDt) return false
|
||||
target.dispatchEvent(new DragEvent('drop', { bubbles: true, cancelable: true, clientY: target.getBoundingClientRect().top + target.getBoundingClientRect().height - 1, dataTransfer: window.__wgDt }))
|
||||
return true
|
||||
})()`)
|
||||
report('项目拖到目标行下半 → 插入到目标之后', await waitFor(`(() => {
|
||||
const s1 = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat1)}]')?.parentElement
|
||||
if (!s1) return false
|
||||
const first = s1.querySelector('.wgProjectRow')
|
||||
return !!first && first.getAttribute('data-wsid') === ${JSON.stringify(reorderAfter.targetWsid)}
|
||||
})()`))
|
||||
|
||||
// ---- v0.4.1:从分组拖出 —— 未分类桶为空时拖拽中也显示为落点 ----
|
||||
const uncatBefore = await evaluate(`!!document.querySelector('.wgCategoryRow[data-wg-category="未分类"]')`)
|
||||
const dragOut = await evaluate(`(() => {
|
||||
const s1 = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat1)}]')?.parentElement
|
||||
if (!s1) return { error: 'no section' }
|
||||
const source = s1.querySelector('.wgProjectRow')
|
||||
if (!source) return { error: 'no project row' }
|
||||
const dt = new DataTransfer()
|
||||
source.dispatchEvent(new DragEvent('dragstart', { bubbles: true, cancelable: true, dataTransfer: dt }))
|
||||
window.__wgDt = dt // stash for the drop step
|
||||
target.dispatchEvent(new DragEvent('dragover', { bubbles: true, cancelable: true, dataTransfer: dt }))
|
||||
window.__wgDt = dt
|
||||
window.__wgSource = source
|
||||
return { wsid: source.getAttribute('data-wsid') }
|
||||
})()`)
|
||||
report('拖拽中未分类桶可见(原为空也显示)', !!dragOut.wsid && await waitFor(`!!document.querySelector('.wgCategoryRow[data-wg-category="未分类"]')`, 5000),
|
||||
`拖拽前未分类桶存在=${uncatBefore}`)
|
||||
const droppedOut = await evaluate(`(() => {
|
||||
const target = document.querySelector('.wgCategoryRow[data-wg-category="未分类"]')
|
||||
await evaluate(`(() => {
|
||||
const target = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat2)}]')
|
||||
if (!target || !window.__wgDt) return false
|
||||
target.dispatchEvent(new DragEvent('dragover', { bubbles: true, cancelable: true, dataTransfer: window.__wgDt }))
|
||||
target.dispatchEvent(new DragEvent('drop', { bubbles: true, cancelable: true, dataTransfer: window.__wgDt }))
|
||||
window.__wgSource?.dispatchEvent(new DragEvent('dragend', { bubbles: true }))
|
||||
return true
|
||||
})()`)
|
||||
report('拖到未分类 = 从分组拖出(assignments=null 落盘)', droppedOut && !!dragOut.wsid && await waitFor(`fetch(${JSON.stringify(BASE)} + '/workspace-groups/config', { cache: 'no-store' }).then(r => r.json()).then(d => d.manual?.assignments?.[${JSON.stringify(dragOut.wsid)}] === null)`))
|
||||
await evaluate(`(() => {
|
||||
const row = document.querySelector('.wgCategoryRow[data-wg-category="未分类"]')
|
||||
if (row && row.getAttribute('aria-expanded') === 'false') row.click()
|
||||
return true
|
||||
})()`)
|
||||
report('拖出的项目出现在未分类桶', !!dragOut.wsid && await waitFor(`(() => {
|
||||
const s = document.querySelector('.wgCategoryRow[data-wg-category="未分类"]')?.parentElement
|
||||
return !!s && !!s.querySelector('.wgProjectRow[data-wsid=${JSON.stringify(dragOut.wsid ?? '')}]')
|
||||
report('排序前置:顶层项目拖入验证分组(凑 2 个成员)', !!seedTop.wsid && await waitFor(`(() => {
|
||||
const s2 = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat2)}]')?.parentElement
|
||||
return !!s2 && s2.querySelectorAll('.wgProjectRow').length >= 2
|
||||
})()`))
|
||||
await expandProject(cat2)
|
||||
|
||||
// ---- v0.4.1b:规则分类项目行菜单也提供「移到未分类」 ----
|
||||
const menuMoveOut = await evaluate(`(() => {
|
||||
const s1 = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat1)}]')?.parentElement
|
||||
const row = s1?.querySelector('.wgProjectRow')
|
||||
if (!row) return false
|
||||
row.querySelector('button[aria-label^="重命名 "]')?.click()
|
||||
return true
|
||||
})()`)
|
||||
report('规则分类项目行菜单出现', menuMoveOut && await waitFor(`[...document.querySelectorAll('button')].some(b => b.textContent.trim() === '移到未分类')`, 4000))
|
||||
// Close the menu (performs the move-out PUT) and let the async write
|
||||
// settle — the following group-reorder drops are rejected by the
|
||||
// manualSaving re-entrancy guard while a save is in flight.
|
||||
await evaluate(`(() => {
|
||||
const item = [...document.querySelectorAll('button')].find(b => b.textContent.trim() === '移到未分类')
|
||||
if (item) { item.click(); return true }
|
||||
return false
|
||||
})()`)
|
||||
await sleep(1000)
|
||||
|
||||
// ---- v0.4:分组拖动 — 下半 = 移到目标分组之后 ----
|
||||
// ---- v0.4:分组拖动(在项目消耗测试之前,保证两分组行都在) ----
|
||||
// 下半 = 移到目标分组之后
|
||||
const groupDown = await evaluate(`(() => {
|
||||
const source = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat2)}]')
|
||||
const target = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat1)}]')
|
||||
|
|
@ -351,6 +297,7 @@ async function main() {
|
|||
const rect = target.getBoundingClientRect()
|
||||
target.dispatchEvent(new DragEvent('dragover', { bubbles: true, cancelable: true, clientY: rect.top + rect.height - 1, dataTransfer: dt }))
|
||||
window.__wgCatDt = dt
|
||||
window.__wgCatSource = source // dragend fires on the dragged source
|
||||
return true
|
||||
})()`)
|
||||
report('拖分组悬停目标行下半 → 下方插入指示线', groupDown && await waitFor(`!!document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat1)}].wgInsertAfter')`, 5000))
|
||||
|
|
@ -358,6 +305,7 @@ async function main() {
|
|||
const target = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat1)}]')
|
||||
if (!target || !window.__wgCatDt) return false
|
||||
target.dispatchEvent(new DragEvent('drop', { bubbles: true, cancelable: true, clientY: target.getBoundingClientRect().top + target.getBoundingClientRect().height - 1, dataTransfer: window.__wgCatDt }))
|
||||
window.__wgCatSource?.dispatchEvent(new DragEvent('dragend', { bubbles: true }))
|
||||
return true
|
||||
})()`)
|
||||
report('分组向下拖 → 移到目标分组之后', await waitFor(`fetch(${JSON.stringify(BASE)} + '/workspace-groups/config', { cache: 'no-store' }).then(r => r.json()).then(d => {
|
||||
|
|
@ -365,7 +313,7 @@ async function main() {
|
|||
return o.indexOf(${JSON.stringify(cat2)}) > o.indexOf(${JSON.stringify(cat1)})
|
||||
})`))
|
||||
|
||||
// ---- v0.4:分组拖动 — 上半 = 移到目标分组之前 ----
|
||||
// 上半 = 移到目标分组之前
|
||||
const groupUp = await evaluate(`(() => {
|
||||
const source = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat1)}]')
|
||||
const target = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat2)}]')
|
||||
|
|
@ -375,6 +323,7 @@ async function main() {
|
|||
const rect = target.getBoundingClientRect()
|
||||
target.dispatchEvent(new DragEvent('dragover', { bubbles: true, cancelable: true, clientY: rect.top + 1, dataTransfer: dt }))
|
||||
window.__wgCatDt = dt
|
||||
window.__wgCatSource = source // dragend fires on the dragged source
|
||||
return true
|
||||
})()`)
|
||||
report('拖分组悬停目标行上半 → 上方插入指示线', groupUp && await waitFor(`!!document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat2)}].wgInsertBefore')`, 5000))
|
||||
|
|
@ -382,14 +331,169 @@ async function main() {
|
|||
const target = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat2)}]')
|
||||
if (!target || !window.__wgCatDt) return false
|
||||
target.dispatchEvent(new DragEvent('drop', { bubbles: true, cancelable: true, clientY: target.getBoundingClientRect().top + 1, dataTransfer: window.__wgCatDt }))
|
||||
window.__wgCatSource?.dispatchEvent(new DragEvent('dragend', { bubbles: true }))
|
||||
return true
|
||||
})()`)
|
||||
report('分组向上拖 → 移到目标分组之前', await waitFor(`fetch(${JSON.stringify(BASE)} + '/workspace-groups/config', { cache: 'no-store' }).then(r => r.json()).then(d => {
|
||||
const o = d.manual?.categoryOrder ?? []
|
||||
return o.indexOf(${JSON.stringify(cat1)}) < o.indexOf(${JSON.stringify(cat2)})
|
||||
})`))
|
||||
// Let the group-reorder PUT settle before the next drag (manualSaving
|
||||
// rejects concurrent writes).
|
||||
await sleep(1000)
|
||||
|
||||
// ---- v0.3:规则分类行出现菜单 → 重命名 → 删除回未分类 ------------------
|
||||
// Group drags folded every group — dragend must restore the snapshot
|
||||
// automatically (no manual re-expand needed). cat1 has 1 member, cat2
|
||||
// has 2 (v0.2 drag-in + top-level seed).
|
||||
const autoRestored = await waitFor(`(() => {
|
||||
const s1 = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat1)}]')?.parentElement
|
||||
const s2 = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat2)}]')?.parentElement
|
||||
return !!s1 && !!s2 && s1.querySelectorAll('.wgProjectRow').length >= 1 && s2.querySelectorAll('.wgProjectRow').length >= 2
|
||||
})()`)
|
||||
report('分组拖动后自动恢复展开(dragend 还原快照)', autoRestored)
|
||||
|
||||
// ---- v0.3:组内排序(在 cat2 内;cat1 只剩 1 个成员不够排序) ----
|
||||
const reorder = await evaluate(`(() => {
|
||||
const s2 = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat2)}]')?.parentElement
|
||||
if (!s2) return { error: 'no section' }
|
||||
const rows = s2.querySelectorAll('.wgProjectRow')
|
||||
const source = rows[1] // drag the second project
|
||||
const target = rows[0] // drop before the first
|
||||
if (!source || !target) return { error: 'rows missing' }
|
||||
const dt = new DataTransfer()
|
||||
source.dispatchEvent(new DragEvent('dragstart', { bubbles: true, cancelable: true, dataTransfer: dt }))
|
||||
window.__wgDt = dt // stash for the drop step (React re-renders may recreate rows)
|
||||
window.__wgSource = source // dragend fires on the dragged source
|
||||
return { wsid: source.getAttribute('data-wsid'), targetWsid: target.getAttribute('data-wsid') }
|
||||
})()`)
|
||||
// v0.6: dragging a PROJECT folds every project row (grouped AND
|
||||
// top-level) but leaves group rows expanded.
|
||||
report('拖动项目时分组行不收起', await waitFor(`(() => {
|
||||
const r1 = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat1)}]')
|
||||
const r2 = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat2)}]')
|
||||
return !!r1 && !!r2 && r1.getAttribute('aria-expanded') === 'true' && r2.getAttribute('aria-expanded') === 'true'
|
||||
})()`, 5000))
|
||||
report('拖动项目时分组内项目行折叠', await waitFor(`(() => {
|
||||
const s2 = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat2)}]')?.parentElement
|
||||
if (!s2) return false
|
||||
const rows = [...s2.querySelectorAll('.wgProjectRow')]
|
||||
return rows.length >= 2 && rows.every(r => r.getAttribute('aria-expanded') === 'false')
|
||||
})()`, 5000))
|
||||
report('拖动项目时其他分组项目行也折叠', await waitFor(`(() => {
|
||||
const s1 = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat1)}]')?.parentElement
|
||||
if (!s1) return false
|
||||
const rows = [...s1.querySelectorAll('.wgProjectRow')]
|
||||
return rows.length >= 1 && rows.every(r => r.getAttribute('aria-expanded') === 'false')
|
||||
})()`, 5000))
|
||||
await evaluate(`(() => {
|
||||
const s2 = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat2)}]')?.parentElement
|
||||
if (!s2) return false
|
||||
const target = s2.querySelector('.wgProjectRow')
|
||||
if (!target || !window.__wgDt) return false
|
||||
target.dispatchEvent(new DragEvent('dragover', { bubbles: true, cancelable: true, dataTransfer: window.__wgDt }))
|
||||
target.dispatchEvent(new DragEvent('drop', { bubbles: true, cancelable: true, dataTransfer: window.__wgDt }))
|
||||
window.__wgSource?.dispatchEvent(new DragEvent('dragend', { bubbles: true }))
|
||||
return true
|
||||
})()`)
|
||||
report('拖项目 dragend 后恢复项目行展开(快照还原)', await waitFor(`(() => {
|
||||
const s2 = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat2)}]')?.parentElement
|
||||
if (!s2) return false
|
||||
const rows = [...s2.querySelectorAll('.wgProjectRow')]
|
||||
return rows.length >= 2 && rows.every(r => r.getAttribute('aria-expanded') === 'true')
|
||||
})()`, 5000))
|
||||
// The user-visible contract: the dragged project now renders first in the group.
|
||||
report('组内拖拽排序(第二个项目移到第一个之前)', await waitFor(`(() => {
|
||||
const s2 = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat2)}]')?.parentElement
|
||||
if (!s2) return false
|
||||
const first = s2.querySelector('.wgProjectRow')
|
||||
return !!first && first.getAttribute('data-wsid') === ${JSON.stringify(reorder.wsid)}
|
||||
})()`))
|
||||
|
||||
// ---- v0.4:拖到目标行下半 → 插到目标之后(指示线可见,cat2 内) ----
|
||||
const reorderAfter = await evaluate(`(() => {
|
||||
const s2 = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat2)}]')?.parentElement
|
||||
if (!s2) return { error: 'no section' }
|
||||
const rows = s2.querySelectorAll('.wgProjectRow')
|
||||
const source = rows[0] // currently the first project
|
||||
const target = rows[1] // drop on the BOTTOM half of the second
|
||||
if (!source || !target) return { error: 'rows missing' }
|
||||
const dt = new DataTransfer()
|
||||
source.dispatchEvent(new DragEvent('dragstart', { bubbles: true, cancelable: true, dataTransfer: dt }))
|
||||
const rect = target.getBoundingClientRect()
|
||||
target.dispatchEvent(new DragEvent('dragover', { bubbles: true, cancelable: true, clientY: rect.top + rect.height - 1, dataTransfer: dt }))
|
||||
window.__wgDt = dt // stash for the drop step
|
||||
window.__wgSource = source // dragend fires on the dragged source
|
||||
return { sourceWsid: source.getAttribute('data-wsid'), targetWsid: target.getAttribute('data-wsid') }
|
||||
})()`)
|
||||
report('拖项目悬停行下半 → 下方插入指示线', await waitFor(`(() => {
|
||||
const s2 = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat2)}]')?.parentElement
|
||||
return !!s2 && !!s2.querySelector('.wgProjectRow.wgInsertAfter')
|
||||
})()`, 5000))
|
||||
await evaluate(`(() => {
|
||||
const s2 = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat2)}]')?.parentElement
|
||||
if (!s2) return false
|
||||
const target = s2.querySelector('.wgProjectRow[data-wsid="${reorderAfter.targetWsid}"]')
|
||||
if (!target || !window.__wgDt) return false
|
||||
target.dispatchEvent(new DragEvent('drop', { bubbles: true, cancelable: true, clientY: target.getBoundingClientRect().top + target.getBoundingClientRect().height - 1, dataTransfer: window.__wgDt }))
|
||||
window.__wgSource?.dispatchEvent(new DragEvent('dragend', { bubbles: true }))
|
||||
return true
|
||||
})()`)
|
||||
report('项目拖到目标行下半 → 插入到目标之后', await waitFor(`(() => {
|
||||
const s2 = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat2)}]')?.parentElement
|
||||
if (!s2) return false
|
||||
const first = s2.querySelector('.wgProjectRow')
|
||||
return !!first && first.getAttribute('data-wsid') === ${JSON.stringify(reorderAfter.targetWsid)}
|
||||
})()`))
|
||||
|
||||
// ---- v0.4.1:从分组拖出(用 cat2 的项目;cat1 只剩 1 个成员留给删除流程) ----
|
||||
const dragOut = await evaluate(`(() => {
|
||||
const s2 = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat2)}]')?.parentElement
|
||||
if (!s2) return { error: 'no section' }
|
||||
const source = s2.querySelector('.wgProjectRow')
|
||||
if (!source) return { error: 'no project row' }
|
||||
const dt = new DataTransfer()
|
||||
source.dispatchEvent(new DragEvent('dragstart', { bubbles: true, cancelable: true, dataTransfer: dt }))
|
||||
window.__wgDt = dt // stash for the drop step
|
||||
window.__wgSource = source // dragend fires on the dragged source
|
||||
return { wsid: source.getAttribute('data-wsid') }
|
||||
})()`)
|
||||
report('拖拽中顶层移出目标可见(空落点区或顶层行)', !!dragOut.wsid && await waitFor(`!!(document.querySelector('.wgTopLevelDrop') || document.querySelector('.wgProjectRow.wgProjectFlat'))`, 5000))
|
||||
report('拖拽中顶层落点可见(整区高亮或空落点区)', !!dragOut.wsid && await waitFor(`!!(document.querySelector('.wgTopLevelArea.wgDropTarget') || document.querySelector('.wgTopLevelDrop'))`, 5000))
|
||||
// Drop on the top-level AREA container (the gaps between rows, not a row
|
||||
// itself) — the whole area must act as the move-out landing spot.
|
||||
const droppedOut = await evaluate(`(() => {
|
||||
const target = document.querySelector('.wgTopLevelArea')
|
||||
if (!target || !window.__wgDt) return false
|
||||
target.dispatchEvent(new DragEvent('dragover', { bubbles: true, cancelable: true, dataTransfer: window.__wgDt }))
|
||||
target.dispatchEvent(new DragEvent('drop', { bubbles: true, cancelable: true, dataTransfer: window.__wgDt }))
|
||||
window.__wgSource?.dispatchEvent(new DragEvent('dragend', { bubbles: true }))
|
||||
return true
|
||||
})()`)
|
||||
report('拖到顶层区域空白 = 从分组拖出(assignments=null 落盘)', droppedOut && !!dragOut.wsid && await waitFor(`fetch(${JSON.stringify(BASE)} + '/workspace-groups/config', { cache: 'no-store' }).then(r => r.json()).then(d => d.manual?.assignments?.[${JSON.stringify(dragOut.wsid)}] === null)`))
|
||||
report('拖出的项目出现在顶层(无分组行)', !!dragOut.wsid && await waitFor(`!!document.querySelector('.wgProjectRow.wgProjectFlat[data-wsid=${JSON.stringify(dragOut.wsid)}]')`))
|
||||
|
||||
// ---- v0.4.1b:分组内项目行菜单提供「移出分组」 ----
|
||||
// cat2 还剩 1 个项目(v0.2 拖入 + 排序前置种子 - 拖出 1);移出后
|
||||
// 手动分组变空(仍渲染),cat1 的成员留给删除流程。
|
||||
await expandCat(cat2)
|
||||
const menuMoveOut = await evaluate(`(() => {
|
||||
const s2 = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat2)}]')?.parentElement
|
||||
const row = s2?.querySelector('.wgProjectRow')
|
||||
if (!row) return false
|
||||
row.querySelector('button[aria-label^="重命名 "]')?.click()
|
||||
return true
|
||||
})()`)
|
||||
report('分组内项目行菜单出现「移出分组」', menuMoveOut && await waitFor(`[...document.querySelectorAll('button')].some(b => b.textContent.trim() === '移出分组')`, 4000))
|
||||
// Close the menu (performs the move-out PUT) and let the async write
|
||||
// settle before the delete flow (manualSaving guards concurrent writes).
|
||||
await evaluate(`(() => {
|
||||
const item = [...document.querySelectorAll('button')].find(b => b.textContent.trim() === '移出分组')
|
||||
if (item) { item.click(); return true }
|
||||
return false
|
||||
})()`)
|
||||
await sleep(1000)
|
||||
|
||||
// ---- v0.3:规则分类行出现菜单 → 重命名 → 删除回顶层 --------------------
|
||||
const hasMenu = await evaluate(`(() => {
|
||||
const row = document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(cat1)}]')
|
||||
if (!row) return false
|
||||
|
|
@ -419,7 +523,7 @@ async function main() {
|
|||
report('renamed 落盘(原规则名 → 新名)', await fetch(`${BASE}/workspace-groups/config`, { cache: 'no-store' })
|
||||
.then(r => r.json()).then(d => d.manual?.renamed?.[cat1] === renamed))
|
||||
|
||||
// Delete the renamed rule group: its projects must go to 未分类 (null).
|
||||
// Delete the renamed rule group: its projects must go top-level (null).
|
||||
// Capture the group's members first (expand the group if collapsed),
|
||||
// then drive the delete flow.
|
||||
await evaluate(`(() => {
|
||||
|
|
@ -454,18 +558,9 @@ async function main() {
|
|||
return true
|
||||
})()`)
|
||||
report('删除分组后分组消失', await waitFor(`!document.querySelector('.wgCategoryRow[data-wg-category=${JSON.stringify(renamed)}]')`))
|
||||
// The uncategorized bucket first appears COLLAPSED — expand it before
|
||||
// asserting its members (data is correct; rows render on expand).
|
||||
await evaluate(`(() => {
|
||||
const row = document.querySelector('.wgCategoryRow[data-wg-category="未分类"]')
|
||||
if (row && row.getAttribute('aria-expanded') === 'false') row.click()
|
||||
return true
|
||||
})()`)
|
||||
// Every former member must now render inside the 未分类 section (bottom).
|
||||
report('删除后成员回未分类(DOM)', await waitFor(`(() => {
|
||||
const s = document.querySelector('.wgCategoryRow[data-wg-category="未分类"]')?.parentElement
|
||||
if (!s) return false
|
||||
const ids = new Set([...s.querySelectorAll('.wgProjectRow')].map(r => r.getAttribute('data-wsid')))
|
||||
// Every former member must now render as a top-level (ungrouped) row.
|
||||
report('删除后成员回顶层(DOM)', await waitFor(`(() => {
|
||||
const ids = new Set([...document.querySelectorAll('.wgProjectRow.wgProjectFlat')].map(r => r.getAttribute('data-wsid')))
|
||||
return ${JSON.stringify(memberIds)}.every(id => ids.has(id))
|
||||
})()`), `members=${JSON.stringify(memberIds)}`)
|
||||
const deleted = await fetch(`${BASE}/workspace-groups/config`, { cache: 'no-store' }).then(r => r.json())
|
||||
|
|
@ -474,31 +569,44 @@ async function main() {
|
|||
&& !Object.values(assignments).includes(renamed)
|
||||
&& !Object.keys(deleted.manual?.workspaceOrder ?? {}).includes(renamed)
|
||||
&& !(deleted.manual?.categoryOrder ?? []).includes(renamed))
|
||||
report('未分类恒为最末段', await waitFor(`(() => {
|
||||
const rows = document.querySelectorAll('.wgCategoryRow')
|
||||
return rows.length > 0 && rows[rows.length - 1].getAttribute('data-wg-category') === ${JSON.stringify('未分类')}
|
||||
// No 未分类 bucket exists anywhere in the tree.
|
||||
report('树中不存在「未分类」桶', await waitFor(`(() => {
|
||||
const rows = [...document.querySelectorAll('.wgCategoryRow')]
|
||||
return rows.every(r => r.getAttribute('data-wg-category') !== ${JSON.stringify('未分类')})
|
||||
})()`))
|
||||
}
|
||||
|
||||
// ---- 6. 现场恢复 ----
|
||||
await fetch(`${BASE}/workspace-groups/manual`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(originalManual),
|
||||
})
|
||||
if (!overlayExistedBefore) {
|
||||
// The original environment had no overlay file — remove the one we created.
|
||||
await unlink(overlayPath).catch(() => {})
|
||||
}
|
||||
await page.send('Page.reload')
|
||||
await waitFor(`!!document.querySelector('.wgRoot')`, 8000)
|
||||
const cleaned = await fetch(`${BASE}/workspace-groups/config`, { cache: 'no-store' }).then(r => r.json())
|
||||
const backToOriginal = JSON.stringify(cleaned.manual ?? { categories: [], assignments: {} }) === JSON.stringify(originalManual)
|
||||
report('现场恢复:overlay 还原为原始内容', backToOriginal)
|
||||
} catch (error) {
|
||||
console.error('验证脚本异常:', error)
|
||||
} finally {
|
||||
if (page) page.close()
|
||||
// 现场恢复必须在 finally 执行:任何异常/中断都不能把测试数据留在
|
||||
// 用户 overlay 里(此前恢复代码在 try 内,异常时会污染真实环境)。
|
||||
let restored = false
|
||||
if (page) {
|
||||
try {
|
||||
if (originalManual !== null) {
|
||||
await fetch(`${BASE}/workspace-groups/manual`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(originalManual),
|
||||
})
|
||||
if (!overlayExistedBefore && overlayPath !== '') {
|
||||
// The original environment had no overlay file — remove the one we created.
|
||||
await unlink(overlayPath).catch(() => {})
|
||||
}
|
||||
restored = true
|
||||
}
|
||||
} catch { /* best-effort restore */ }
|
||||
if (restored) {
|
||||
try {
|
||||
const cleaned = await fetch(`${BASE}/workspace-groups/config`, { cache: 'no-store' }).then(r => r.json())
|
||||
const backToOriginal = JSON.stringify(cleaned.manual ?? { categories: [], assignments: {} }) === JSON.stringify(originalManual)
|
||||
report('现场恢复:overlay 还原为原始内容', backToOriginal)
|
||||
} catch { report('现场恢复:overlay 还原为原始内容', false, '恢复校验请求失败') }
|
||||
} else {
|
||||
report('现场恢复:overlay 还原为原始内容', false, '恢复请求失败')
|
||||
}
|
||||
page.close()
|
||||
}
|
||||
if (chrome) chrome.kill('SIGKILL')
|
||||
await rm(profileDir, { recursive: true, force: true })
|
||||
}
|
||||
|
|
|
|||
|
|
@ -35,7 +35,7 @@ import {
|
|||
} from '../core/matcher.ts'
|
||||
import { UNCATEGORIZED_LABEL, type GroupsConfig, type ManualGroups } from '../core/types.ts'
|
||||
import type { GroupsBrowserProps } from './contract.ts'
|
||||
import { deriveGroups, deriveSearchGroups, deriveSearchMatches, UNCATEGORIZED_KEY, withDraggingUncategorized, type CategoryNode } from './tree.ts'
|
||||
import { deriveGroups, deriveSearchGroups, deriveSearchMatches, deriveTopLevel, UNCATEGORIZED_KEY, type CategoryNode, type WorkspaceGroupNode } from './tree.ts'
|
||||
import { CategoryRow, DND_CATEGORY_TYPE, DND_WORKSPACE_TYPE, hasPluginDragType, SessionRow, WorkspaceRow } from './rows.tsx'
|
||||
import css from './styles.css?inline'
|
||||
|
||||
|
|
@ -116,7 +116,14 @@ async function saveManualOverlay(manual: ManualGroups): Promise<void> {
|
|||
type GroupDialogState = { mode: 'create' } | { mode: 'rename'; from: string } | null
|
||||
|
||||
/** Row reference used by drop targets: which kind of row, which key. */
|
||||
export type DropRowRef = { kind: 'category' | 'workspace'; key: string }
|
||||
export type DropRowRef = { kind: 'category' | 'workspace' | 'topLevel'; key: string }
|
||||
|
||||
/**
|
||||
* Which level's rows fold while a drag is in progress: dragging a project
|
||||
* folds every project row (grouped AND top-level), dragging a group folds
|
||||
* every group row. The other level keeps its expansion untouched.
|
||||
*/
|
||||
export type DragLevel = 'workspace' | 'category' | null
|
||||
|
||||
/**
|
||||
* Current drop indicator. A `line` renders a 2px insertion line above/below a
|
||||
|
|
@ -275,9 +282,9 @@ export function GroupsBrowser({
|
|||
() => Object.entries(workspaceExpansion).filter(([, v]) => v).map(([k]) => k),
|
||||
[workspaceExpansion],
|
||||
)
|
||||
// Whether a drag is in progress (drives the always-visible uncategorized
|
||||
// drop target while dragging).
|
||||
const [dragging, setDragging] = useState(false)
|
||||
// Which level is being dragged: drives the top-level drop target (project
|
||||
// drags only) and which level's rows fold.
|
||||
const [dragging, setDragging] = useState<DragLevel>(null)
|
||||
const groups = useMemo(
|
||||
() => deriveGroups(list, workspaces, archivedSessionIds, config, {
|
||||
expandedCategories,
|
||||
|
|
@ -285,13 +292,22 @@ export function GroupsBrowser({
|
|||
}, manual),
|
||||
[list, workspaces, archivedSessionIds, config, manual, expandedCategories, expandedWorkspaces],
|
||||
)
|
||||
// While a drag is active, keep the uncategorized bucket visible even when
|
||||
// empty — it is the only way to drag a project OUT of a group when every
|
||||
// project is currently grouped.
|
||||
const displayGroups = useMemo(
|
||||
() => withDraggingUncategorized(groups, dragging),
|
||||
[groups, dragging],
|
||||
// Top-level (ungrouped) workspace rows, rendered after the group folders.
|
||||
const topLevel = useMemo(
|
||||
() => deriveTopLevel(list, workspaces, archivedSessionIds, config, {
|
||||
expandedCategories,
|
||||
expandedWorkspaces,
|
||||
}, manual),
|
||||
[list, workspaces, archivedSessionIds, config, manual, expandedCategories, expandedWorkspaces],
|
||||
)
|
||||
// While dragging a project, an empty top-level area must still be a visible
|
||||
// drop target — otherwise a project can never be dragged OUT of a group when
|
||||
// every project is currently grouped.
|
||||
const topLevelDropActive = dragging === 'workspace' && topLevel.length === 0
|
||||
// With top-level rows present, the whole top-level area lights up as the
|
||||
// move-out drop target while dragging a project (rows AND the gaps between
|
||||
// them), so the user always sees a landing spot when dragging out.
|
||||
const topLevelAreaActive = dragging === 'workspace' && topLevel.length > 0
|
||||
|
||||
// Add workspace flow: self-contained (no directory-flow hole dependency).
|
||||
const [adding, setAdding] = useState(false)
|
||||
|
|
@ -500,9 +516,31 @@ export function GroupsBrowser({
|
|||
|
||||
const [dragIndicator, setDragIndicator] = useState<DragIndicator>(null)
|
||||
|
||||
// Cancel any stale indicator when a drag ends outside a row (or is aborted).
|
||||
// Expansion state taken at dragstart; dragend restores it so the folding
|
||||
// caused by a drag is always undone afterwards ("结束后恢复").
|
||||
const expansionSnapshot = useRef<{ categories: Record<string, boolean>; workspaces: Record<string, boolean> } | null>(null)
|
||||
// Live expansion state for the dragend restore (the document-level listener
|
||||
// is registered once, so it must read current values through a ref).
|
||||
const liveExpansionRef = useRef({ categoryExpansion, workspaceExpansion, actions })
|
||||
liveExpansionRef.current = { categoryExpansion, workspaceExpansion, actions }
|
||||
|
||||
// Cancel any stale indicator when a drag ends outside a row (or is aborted),
|
||||
// and restore the expansion snapshot taken at dragstart.
|
||||
useEffect(() => {
|
||||
const clear = () => { setDragIndicator(null); setDragging(false) }
|
||||
const clear = () => {
|
||||
setDragIndicator(null)
|
||||
setDragging(null)
|
||||
const snapshot = expansionSnapshot.current
|
||||
if (snapshot === null) return
|
||||
expansionSnapshot.current = null
|
||||
const { categoryExpansion: currentCategories, workspaceExpansion: currentWorkspaces, actions: currentActions } = liveExpansionRef.current
|
||||
for (const [key, value] of Object.entries(snapshot.categories)) {
|
||||
if (currentCategories[key] !== value) currentActions.setCategoryExpanded(key, value)
|
||||
}
|
||||
for (const [key, value] of Object.entries(snapshot.workspaces)) {
|
||||
if (currentWorkspaces[key] !== value) currentActions.setWorkspaceExpanded(key, value)
|
||||
}
|
||||
}
|
||||
document.addEventListener('dragend', clear)
|
||||
return () => { document.removeEventListener('dragend', clear) }
|
||||
}, [])
|
||||
|
|
@ -576,8 +614,12 @@ export function GroupsBrowser({
|
|||
*/
|
||||
const onDropRow = (categoryKey: string, row: DropRowRef) => (event: DragEvent): void => {
|
||||
event.preventDefault()
|
||||
// Keep the drop from bubbling to the enclosing top-level area (which is
|
||||
// also a move-out target): a row drop and the area-drop below it must not
|
||||
// both fire moveWorkspaceTo.
|
||||
event.stopPropagation()
|
||||
setDragIndicator(null)
|
||||
setDragging(false)
|
||||
setDragging(null)
|
||||
const draggedCategory = event.dataTransfer.getData(DND_CATEGORY_TYPE)
|
||||
if (draggedCategory !== '') {
|
||||
// Group reorder: only category rows are targets (project rows fold
|
||||
|
|
@ -591,6 +633,12 @@ export function GroupsBrowser({
|
|||
}
|
||||
const workspaceId = event.dataTransfer.getData(DND_WORKSPACE_TYPE) || event.dataTransfer.getData('text/plain')
|
||||
if (workspaceId === '') return
|
||||
if (row.kind === 'topLevel') {
|
||||
// Dropping on the top-level area / a top-level row = move OUT of any
|
||||
// group (forced top-level, rules ignored).
|
||||
void moveWorkspaceTo(workspaceId, UNCATEGORIZED_KEY)
|
||||
return
|
||||
}
|
||||
// Project move/reorder: a line on a project row = reorder before/after it;
|
||||
// dropping anywhere else in a category = move into the group (its end).
|
||||
const rect = (event.currentTarget as HTMLElement).getBoundingClientRect()
|
||||
|
|
@ -606,6 +654,13 @@ export function GroupsBrowser({
|
|||
if (draggingCategory && row.kind !== 'category') return // group drags target category rows only
|
||||
event.preventDefault()
|
||||
event.dataTransfer.dropEffect = 'move'
|
||||
if (row.kind === 'topLevel') {
|
||||
// Dropping a project on the top-level area: whole-area highlight, drop
|
||||
// moves the project out of its group.
|
||||
setDragIndicator(prev =>
|
||||
prev?.mode === 'into' && prev.categoryKey === UNCATEGORIZED_KEY ? prev : { mode: 'into', categoryKey: UNCATEGORIZED_KEY })
|
||||
return
|
||||
}
|
||||
const rect = (event.currentTarget as HTMLElement).getBoundingClientRect()
|
||||
const before = event.clientY < rect.top + rect.height / 2
|
||||
if (draggingCategory || row.kind === 'workspace') {
|
||||
|
|
@ -627,32 +682,32 @@ export function GroupsBrowser({
|
|||
setDragIndicator(null)
|
||||
}
|
||||
|
||||
// While dragging a project, everything else folds: other categories collapse
|
||||
// (project rows render only inside expanded categories), and every session
|
||||
// expansion collapses — the source category stays open so dropping on a
|
||||
// sibling row can reorder inside it.
|
||||
const onDragStartWorkspace = (workspaceId: string) => (): void => {
|
||||
setDragging(true)
|
||||
const workspace = workspaces.find(w => w.workspaceId === workspaceId)
|
||||
const sourceKey = workspace === undefined
|
||||
? undefined
|
||||
: resolveCategory(config, manual, workspace.workspaceId, workspace.path, workspace.title)
|
||||
for (const key of Object.keys(categoryExpansion)) {
|
||||
if (!categoryExpansion[key]) continue
|
||||
if (sourceKey !== undefined && key === sourceKey) continue
|
||||
actions.setCategoryExpanded(key, false)
|
||||
// While dragging a project, only PROJECT rows fold — every expanded
|
||||
// workspace collapses (inside groups AND top-level); group rows keep their
|
||||
// expansion so the user still sees where groups are. dragend restores the
|
||||
// snapshot taken here.
|
||||
const onDragStartWorkspace = (_workspaceId: string) => (): void => {
|
||||
setDragging('workspace')
|
||||
expansionSnapshot.current = {
|
||||
categories: { ...categoryExpansion },
|
||||
workspaces: { ...workspaceExpansion },
|
||||
}
|
||||
for (const key of Object.keys(workspaceExpansion)) {
|
||||
if (workspaceExpansion[key]) actions.setWorkspaceExpanded(key, false)
|
||||
}
|
||||
}
|
||||
|
||||
// While dragging a group, every group folds (their rows stay visible as
|
||||
// reorder targets).
|
||||
// While dragging a group, only GROUP rows fold (their rows stay visible as
|
||||
// reorder targets); project rows keep their expansion. dragend restores the
|
||||
// snapshot taken here.
|
||||
const onDragStartCategory = (categoryKey: string) => (event: DragEvent): void => {
|
||||
event.dataTransfer.setData(DND_CATEGORY_TYPE, categoryKey)
|
||||
event.dataTransfer.effectAllowed = 'move'
|
||||
setDragging(true)
|
||||
setDragging('category')
|
||||
expansionSnapshot.current = {
|
||||
categories: { ...categoryExpansion },
|
||||
workspaces: { ...workspaceExpansion },
|
||||
}
|
||||
for (const key of Object.keys(categoryExpansion)) {
|
||||
if (categoryExpansion[key]) actions.setCategoryExpanded(key, false)
|
||||
}
|
||||
|
|
@ -776,19 +831,18 @@ export function GroupsBrowser({
|
|||
{groups.length === 0 && (
|
||||
<div className="wgEmpty">{workspacePhase === 'ready' ? t('empty.noWorkspaces') : t('empty.none')}</div>
|
||||
)}
|
||||
{displayGroups.map((category) => (
|
||||
{groups.map((category) => (
|
||||
<CategorySection
|
||||
key={category.key}
|
||||
category={category}
|
||||
current={current}
|
||||
now={now}
|
||||
t={t}
|
||||
manageable={category.key !== UNCATEGORIZED_KEY}
|
||||
dragIndicator={dragIndicator}
|
||||
onDragOverRow={onDragOverRow}
|
||||
onDragLeaveRow={onDragLeaveRow}
|
||||
onDropRow={onDropRow}
|
||||
{...(category.key === UNCATEGORIZED_KEY ? {} : { onDragStartCategory: onDragStartCategory(category.key) })}
|
||||
onDragStartCategory={onDragStartCategory(category.key)}
|
||||
onDragStartWorkspace={onDragStartWorkspace}
|
||||
onToggleCategory={() => { actions.setCategoryExpanded(category.key, !category.expanded) }}
|
||||
onToggleWorkspace={(key) => { actions.setWorkspaceExpanded(key, !workspaceExpansion[key]) }}
|
||||
|
|
@ -817,17 +871,49 @@ export function GroupsBrowser({
|
|||
}}
|
||||
onMoveOut={(workspaceId) => { void moveWorkspaceTo(workspaceId, UNCATEGORIZED_KEY) }}
|
||||
canMoveOut={(workspaceId) => {
|
||||
// The menu "移到未分类" is offered for any project that
|
||||
// The menu "移出分组" is offered for any project that
|
||||
// currently sits inside a group (rule-classified or manual) —
|
||||
// not just overridden ones. Projects already in the
|
||||
// uncategorized bucket (resolveCategory === undefined) don't
|
||||
// need it.
|
||||
// not just overridden ones. Top-level projects
|
||||
// (resolveCategory === undefined) don't need it.
|
||||
const workspace = workspaces.find(w => w.workspaceId === workspaceId)
|
||||
return workspace !== undefined
|
||||
&& resolveCategory(config, manual, workspace.workspaceId, workspace.path, workspace.title) !== undefined
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
{/* Top-level (ungrouped) workspaces, rendered after the group
|
||||
folders. While dragging a project, an empty top-level area
|
||||
shows a drop target so projects can always be dragged OUT. */}
|
||||
{(topLevel.length > 0 || topLevelDropActive) && (
|
||||
<TopLevelSection
|
||||
topLevel={topLevel}
|
||||
current={current}
|
||||
now={now}
|
||||
t={t}
|
||||
showDropTarget={topLevelDropActive}
|
||||
areaActive={topLevelAreaActive}
|
||||
dropActive={dragIndicator?.mode === 'into' && dragIndicator.categoryKey === UNCATEGORIZED_KEY}
|
||||
onDragOverRow={onDragOverRow}
|
||||
onDragLeaveRow={onDragLeaveRow}
|
||||
onDropRow={onDropRow}
|
||||
onDragStartWorkspace={onDragStartWorkspace}
|
||||
onToggleWorkspace={(key) => { actions.setWorkspaceExpanded(key, !workspaceExpansion[key]) }}
|
||||
onNewSession={startSession}
|
||||
onOpen={open}
|
||||
onRenameRequest={(workspaceId, title) => {
|
||||
setRenameTarget({ workspaceId, currentTitle: title })
|
||||
setRenameDraft(title)
|
||||
setRenameError(null)
|
||||
}}
|
||||
onDeleteRequest={(workspaceId, title) => {
|
||||
setDeleteTarget({ workspaceId, title })
|
||||
setDeleteError(null)
|
||||
}}
|
||||
onSessionRename={onSessionRename}
|
||||
onSessionArchive={onSessionArchive}
|
||||
onFork={forkSession}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
|
@ -974,19 +1060,17 @@ function categoriesForCurrent(
|
|||
}
|
||||
|
||||
/** One category section: header row + expanded workspace folders. */
|
||||
function CategorySection({ category, current, now, t, manageable, dragIndicator, onDragOverRow, onDragLeaveRow, onDropRow, onDragStartCategory, onDragStartWorkspace, onToggleCategory, onToggleWorkspace, onNewSession, onOpen, onRenameRequest, onDeleteRequest, onSessionRename, onSessionArchive, onFork, onGroupRename, onGroupDelete, onMoveOut, canMoveOut }: {
|
||||
function CategorySection({ category, current, now, t, dragIndicator, onDragOverRow, onDragLeaveRow, onDropRow, onDragStartCategory, onDragStartWorkspace, onToggleCategory, onToggleWorkspace, onNewSession, onOpen, onRenameRequest, onDeleteRequest, onSessionRename, onSessionArchive, onFork, onGroupRename, onGroupDelete, onMoveOut, canMoveOut }: {
|
||||
category: CategoryNode
|
||||
current: SessionId | undefined
|
||||
now: number
|
||||
t: GroupsBrowserProps['t']
|
||||
/** Rename/delete menu + group reorder source (false for the uncategorized bucket). */
|
||||
manageable: boolean
|
||||
dragIndicator: DragIndicator
|
||||
onDragOverRow: (row: DropRowRef) => (event: DragEvent) => void
|
||||
onDragLeaveRow: (event: DragEvent) => void
|
||||
/** Drop factory: bind the target category and the row kind (before/after re-derived at drop time). */
|
||||
onDropRow: (categoryKey: string, row: DropRowRef) => (event: DragEvent) => void
|
||||
onDragStartCategory?: (event: DragEvent) => void
|
||||
onDragStartCategory: (event: DragEvent) => void
|
||||
onDragStartWorkspace: (workspaceId: WorkspaceId) => () => void
|
||||
onToggleCategory: () => void
|
||||
onToggleWorkspace: (key: string) => void
|
||||
|
|
@ -1012,7 +1096,9 @@ function CategorySection({ category, current, now, t, manageable, dragIndicator,
|
|||
node={category}
|
||||
t={t}
|
||||
onToggle={onToggleCategory}
|
||||
{...(manageable ? { onRename: onGroupRename, onDelete: onGroupDelete, onDragStartCategory } : {})}
|
||||
onRename={onGroupRename}
|
||||
onDelete={onGroupDelete}
|
||||
onDragStartCategory={onDragStartCategory}
|
||||
dropActive={categoryInto}
|
||||
{...(categoryLine !== undefined ? { insertLine: categoryLine } : {})}
|
||||
onRowDragOver={onDragOverRow({ kind: 'category', key: category.key })}
|
||||
|
|
@ -1062,6 +1148,92 @@ function CategorySection({ category, current, now, t, manageable, dragIndicator,
|
|||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Top-level (ungrouped) workspace rows rendered after the group folders. While
|
||||
* a project drag is in progress the ENTIRE top-level area is a move-out drop
|
||||
* target: empty → a labelled placeholder (.wgTopLevelDrop); non-empty → the
|
||||
* area container lights up (.wgDropTarget) and every row + the gaps between
|
||||
* them accept the drop (rows keep their own handlers; the area container
|
||||
* catches drops on the gaps).
|
||||
*/
|
||||
function TopLevelSection({ topLevel, current, now, t, showDropTarget, areaActive, dropActive, onDragOverRow, onDragLeaveRow, onDropRow, onDragStartWorkspace, onToggleWorkspace, onNewSession, onOpen, onRenameRequest, onDeleteRequest, onSessionRename, onSessionArchive, onFork }: {
|
||||
topLevel: readonly WorkspaceGroupNode[]
|
||||
current: SessionId | undefined
|
||||
now: number
|
||||
t: GroupsBrowserProps['t']
|
||||
showDropTarget: boolean
|
||||
/** Whole-area highlight while dragging a project (top-level rows present). */
|
||||
areaActive: boolean
|
||||
dropActive: boolean
|
||||
onDragOverRow: (row: DropRowRef) => (event: DragEvent) => void
|
||||
onDragLeaveRow: (event: DragEvent) => void
|
||||
onDropRow: (categoryKey: string, row: DropRowRef) => (event: DragEvent) => void
|
||||
onDragStartWorkspace: (workspaceId: WorkspaceId) => () => void
|
||||
onToggleWorkspace: (key: string) => void
|
||||
onNewSession: (workspaceId?: WorkspaceId) => void
|
||||
onOpen: (sessionId: SessionId) => void
|
||||
onRenameRequest: (workspaceId: WorkspaceId, currentTitle: string) => void
|
||||
onDeleteRequest: (workspaceId: WorkspaceId, title: string) => void
|
||||
onSessionRename: (sessionId: SessionId, currentTitle: string) => void
|
||||
onSessionArchive: (sessionId: SessionId) => void
|
||||
onFork: (sessionId: SessionId) => void
|
||||
}) {
|
||||
const topRef: DropRowRef = { kind: 'topLevel', key: UNCATEGORIZED_KEY }
|
||||
return (
|
||||
<div
|
||||
role="group"
|
||||
aria-label={t('section.topLevel')}
|
||||
className={areaActive ? 'wgTopLevelArea wgDropTarget' : 'wgTopLevelArea'}
|
||||
onDragOver={onDragOverRow(topRef)}
|
||||
onDragLeave={onDragLeaveRow}
|
||||
onDrop={onDropRow(UNCATEGORIZED_KEY, topRef)}
|
||||
>
|
||||
{showDropTarget && (
|
||||
<div
|
||||
className={`wgTopLevelDrop${dropActive ? ' wgDropTarget' : ''}`}
|
||||
role="treeitem"
|
||||
onDragOver={onDragOverRow(topRef)}
|
||||
onDragLeave={onDragLeaveRow}
|
||||
onDrop={onDropRow(UNCATEGORIZED_KEY, topRef)}
|
||||
>
|
||||
{t('group.dropTopLevel')}
|
||||
</div>
|
||||
)}
|
||||
{topLevel.map((workspace) => (
|
||||
<div key={workspace.workspaceId} role="group">
|
||||
<WorkspaceRow
|
||||
node={workspace}
|
||||
t={t}
|
||||
flat
|
||||
onToggle={() => { onToggleWorkspace(workspace.workspaceId as string) }}
|
||||
onNewSession={() => { onNewSession(workspace.workspaceId) }}
|
||||
onRename={() => { onRenameRequest(workspace.workspaceId, workspace.label) }}
|
||||
onDelete={() => { onDeleteRequest(workspace.workspaceId, workspace.label) }}
|
||||
dropActive={dropActive}
|
||||
onRowDragOver={onDragOverRow(topRef)}
|
||||
onRowDragLeave={onDragLeaveRow}
|
||||
onRowDrop={onDropRow(UNCATEGORIZED_KEY, topRef)}
|
||||
onDragStartExtra={onDragStartWorkspace(workspace.workspaceId)}
|
||||
/>
|
||||
{workspace.expanded && workspace.sessions.map((session) => (
|
||||
<SessionRow
|
||||
key={session.id}
|
||||
node={session}
|
||||
currentId={current}
|
||||
now={now}
|
||||
t={t}
|
||||
onOpen={onOpen}
|
||||
onRename={onSessionRename}
|
||||
onFork={onFork}
|
||||
onArchive={onSessionArchive}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Search body rendered as a three-level tree pruned to matched branches:
|
||||
* 分类文件夹 → 项目文件夹 → 命中会话行. Reuses the same row components as
|
||||
|
|
@ -1086,10 +1258,12 @@ function SearchBody({ list, workspaces, config, archivedSessionIds, query, remot
|
|||
() => deriveSearchMatches(list, workspaces, config, query, archivedSessionIds, currentRemote, resultLimit),
|
||||
[list, workspaces, config, query, archivedSessionIds, currentRemote, resultLimit],
|
||||
)
|
||||
const groups = useMemo(
|
||||
const searchTree = useMemo(
|
||||
() => deriveSearchGroups(list, workspaces, config, matches.matchedIds, archivedSessionIds, manual, matches.snippetsBySession),
|
||||
[list, workspaces, config, matches, archivedSessionIds, manual],
|
||||
)
|
||||
const groups = searchTree.categories
|
||||
const searchTopLevel = searchTree.topLevel
|
||||
const pending = currentRemote.status === 'loading'
|
||||
const failed = currentRemote.status === 'error'
|
||||
return (
|
||||
|
|
@ -1128,9 +1302,37 @@ function SearchBody({ list, workspaces, config, archivedSessionIds, query, remot
|
|||
</div>
|
||||
</div>
|
||||
))}
|
||||
{searchTopLevel.map((workspace) => (
|
||||
<div key={workspace.workspaceId} role="group">
|
||||
<WorkspaceRow
|
||||
node={workspace}
|
||||
t={t}
|
||||
flat
|
||||
onToggle={() => {}}
|
||||
onNewSession={() => {}}
|
||||
onRename={() => {}}
|
||||
onDelete={() => {}}
|
||||
/>
|
||||
<div role="group">
|
||||
{workspace.sessions.map((session) => (
|
||||
<SessionRow
|
||||
key={session.id}
|
||||
node={session}
|
||||
currentId={current}
|
||||
now={now}
|
||||
t={t}
|
||||
onOpen={open}
|
||||
onRename={() => {}}
|
||||
onFork={() => {}}
|
||||
onArchive={() => {}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{pending && <div className="wgSearchStatus" role="status">{t('search.pending')}</div>}
|
||||
{failed && <div className="wgSearchStatus" role="status">{t('search.unavailable')}</div>}
|
||||
{!pending && groups.length === 0 && (
|
||||
{!pending && groups.length === 0 && searchTopLevel.length === 0 && (
|
||||
<div className="wgEmpty">{t('search.noMatches')}</div>
|
||||
)}
|
||||
{matches.hasMore && (
|
||||
|
|
|
|||
|
|
@ -31,7 +31,7 @@ export type WorkspaceGroupsKey =
|
|||
| 'workspace.renamePlaceholder'
|
||||
| 'workspace.renameConfirm'
|
||||
| 'workspace.renameCancel'
|
||||
| 'workspace.moveToUncategorized'
|
||||
| 'workspace.moveOutOfGroup'
|
||||
| 'group.create'
|
||||
| 'group.createTitle'
|
||||
| 'group.createPlaceholder'
|
||||
|
|
@ -46,6 +46,8 @@ export type WorkspaceGroupsKey =
|
|||
| 'group.deleteCancel'
|
||||
| 'group.nameDuplicate'
|
||||
| 'group.nameReserved'
|
||||
| 'group.dropTopLevel'
|
||||
| 'section.topLevel'
|
||||
| 'manual.saveError'
|
||||
| 'session.new'
|
||||
| 'session.rename'
|
||||
|
|
@ -97,7 +99,7 @@ export const zh: WorkspaceGroupsDict = {
|
|||
'workspace.renamePlaceholder': '工作区名称',
|
||||
'workspace.renameConfirm': '重命名',
|
||||
'workspace.renameCancel': '取消',
|
||||
'workspace.moveToUncategorized': '移到未分类',
|
||||
'workspace.moveOutOfGroup': '移出分组',
|
||||
'group.create': '新建分组',
|
||||
'group.createTitle': '新建分组',
|
||||
'group.createPlaceholder': '分组名称',
|
||||
|
|
@ -108,10 +110,12 @@ export const zh: WorkspaceGroupsDict = {
|
|||
'group.renameConfirm': '重命名',
|
||||
'group.delete': '删除分组',
|
||||
'group.deleteTitle': '删除分组',
|
||||
'group.deleteConfirm': '删除后,该分组内的所有项目将回到「未分类」。确定删除?',
|
||||
'group.deleteConfirm': '删除后,该分组内的所有项目将移到顶层(不归组)。确定删除?',
|
||||
'group.deleteCancel': '取消删除',
|
||||
'group.nameDuplicate': '已存在同名分组',
|
||||
'group.nameReserved': '该名称不可用',
|
||||
'group.dropTopLevel': '松开以移出分组到顶层',
|
||||
'section.topLevel': '顶层项目',
|
||||
'manual.saveError': '分组变更保存失败',
|
||||
'session.new': '新建会话',
|
||||
'session.rename': '重命名会话',
|
||||
|
|
@ -162,7 +166,7 @@ export const en: WorkspaceGroupsDict = {
|
|||
'workspace.renamePlaceholder': 'Workspace name',
|
||||
'workspace.renameConfirm': 'Rename',
|
||||
'workspace.renameCancel': 'Cancel',
|
||||
'workspace.moveToUncategorized': 'Move to Uncategorized',
|
||||
'workspace.moveOutOfGroup': 'Move out of group',
|
||||
'group.create': 'New group',
|
||||
'group.createTitle': 'New group',
|
||||
'group.createPlaceholder': 'Group name',
|
||||
|
|
@ -173,10 +177,12 @@ export const en: WorkspaceGroupsDict = {
|
|||
'group.renameConfirm': 'Rename',
|
||||
'group.delete': 'Delete group',
|
||||
'group.deleteTitle': 'Delete group',
|
||||
'group.deleteConfirm': 'Deleting removes this group; every project inside it returns to Uncategorized. Delete?',
|
||||
'group.deleteConfirm': 'Deleting removes this group; every project inside it moves to the top level (ungrouped). Delete?',
|
||||
'group.deleteCancel': 'Cancel delete',
|
||||
'group.nameDuplicate': 'A group with this name already exists',
|
||||
'group.nameReserved': 'This name is not available',
|
||||
'group.dropTopLevel': 'Release to move out of the group',
|
||||
'section.topLevel': 'Top-level projects',
|
||||
'manual.saveError': 'Could not save group changes',
|
||||
'session.new': 'New Session',
|
||||
'session.rename': 'Rename session',
|
||||
|
|
|
|||
|
|
@ -18,6 +18,7 @@ import {
|
|||
IconFolderOpen16,
|
||||
IconFolderOpenOutline16,
|
||||
IconPlusOutline16,
|
||||
IconProjectAddOutline16,
|
||||
IconTriangleRightFill14,
|
||||
IconTrashOutline16,
|
||||
Menu,
|
||||
|
|
@ -123,7 +124,7 @@ export function CategoryRow({ node, t, onToggle, onRename, onDelete, dropActive
|
|||
<span className={`wgChevron${node.expanded ? ' wgChevronOpen' : ''}`}>
|
||||
<IconTriangleRightFill14 />
|
||||
</span>
|
||||
<span className="wgCategoryIcon">
|
||||
<span className="wgCategoryIcon" data-wg-row-icon="group">
|
||||
{node.expanded ? <IconFolderOpen16 /> : <IconFolderClose16 />}
|
||||
</span>
|
||||
<span className="wgCategoryLabel">{node.label}</span>
|
||||
|
|
@ -163,23 +164,25 @@ export function CategoryRow({ node, t, onToggle, onRename, onDelete, dropActive
|
|||
}
|
||||
|
||||
/** One workspace folder row inside a category: draggable source + drop target. */
|
||||
export function WorkspaceRow({ node, t, onToggle, onNewSession, onRename, onDelete, canMoveOut = false, onMoveOut, dropActive = false, insertLine, onRowDragOver, onRowDragLeave, onRowDrop, onDragStartExtra }: {
|
||||
export function WorkspaceRow({ node, t, onToggle, onNewSession, onRename, onDelete, canMoveOut = false, onMoveOut, flat = false, dropActive = false, insertLine, onRowDragOver, onRowDragLeave, onRowDrop, onDragStartExtra }: {
|
||||
node: WorkspaceGroupNode
|
||||
t: T
|
||||
onToggle: () => void
|
||||
onNewSession: () => void
|
||||
onRename: () => void
|
||||
onDelete: () => void
|
||||
/** Project currently sits inside a group — offer "move to uncategorized". */
|
||||
/** Project currently sits inside a group — offer "move out of group". */
|
||||
canMoveOut?: boolean
|
||||
onMoveOut?: () => void
|
||||
/** Render as a top-level row (no folder indentation). */
|
||||
flat?: boolean
|
||||
/** Extra dragstart hook (e.g. collapse all expanded projects while dragging). */
|
||||
onDragStartExtra?: () => void
|
||||
} & RowDropProps) {
|
||||
const [menuOpen, setMenuOpen] = useState(false)
|
||||
const menuItems = [
|
||||
...(canMoveOut && onMoveOut !== undefined
|
||||
? [{ id: 'moveOut', label: t('workspace.moveToUncategorized'), icon: <IconFolderOpenOutline16 size={16} /> }]
|
||||
? [{ id: 'moveOut', label: t('workspace.moveOutOfGroup'), icon: <IconFolderOpenOutline16 size={16} /> }]
|
||||
: []),
|
||||
{ id: 'rename', label: t('workspace.rename'), icon: <IconEditOutline16 /> },
|
||||
{ id: 'delete', label: t('workspace.delete'), icon: <IconTrashOutline16 />, danger: true },
|
||||
|
|
@ -191,7 +194,7 @@ export function WorkspaceRow({ node, t, onToggle, onNewSession, onRename, onDele
|
|||
}
|
||||
return (
|
||||
<div
|
||||
className={`wgProjectRow${node.containsCurrent ? ' wgProjectActive' : ''}${dropActive ? ' wgDropTarget' : ''}${insertLine === 'before' ? ' wgInsertBefore' : insertLine === 'after' ? ' wgInsertAfter' : ''}`}
|
||||
className={`wgProjectRow${node.containsCurrent ? ' wgProjectActive' : ''}${flat ? ' wgProjectFlat' : ''}${dropActive ? ' wgDropTarget' : ''}${insertLine === 'before' ? ' wgInsertBefore' : insertLine === 'after' ? ' wgInsertAfter' : ''}`}
|
||||
role="treeitem"
|
||||
aria-expanded={node.expanded}
|
||||
data-wsid={node.workspaceId}
|
||||
|
|
@ -205,8 +208,10 @@ export function WorkspaceRow({ node, t, onToggle, onNewSession, onRename, onDele
|
|||
<span className={`wgChevron${node.expanded ? ' wgChevronOpen' : ''}`}>
|
||||
<IconTriangleRightFill14 />
|
||||
</span>
|
||||
<span className="wgCategoryIcon">
|
||||
{node.expanded ? <IconFolderOpen16 /> : <IconFolderClose16 />}
|
||||
<span className="wgCategoryIcon" data-wg-row-icon="project">
|
||||
{/* Project rows use the project glyph (same as the official workspace
|
||||
browser) so groups (folder glyph) and projects stay distinguishable. */}
|
||||
<IconProjectAddOutline16 />
|
||||
</span>
|
||||
<span className="wgProjectLabel" title={node.path}>{node.label}</span>
|
||||
<span className="wgRowActions">
|
||||
|
|
|
|||
|
|
@ -208,6 +208,33 @@
|
|||
position: relative;
|
||||
}
|
||||
|
||||
/* Top-level (ungrouped) workspace row: no folder indentation. */
|
||||
.wgProjectFlat {
|
||||
padding-left: 4px;
|
||||
}
|
||||
|
||||
/* Drop target shown while dragging a project and the top-level area is
|
||||
empty — the only way to drag a project out of a group. */
|
||||
.wgTopLevelDrop {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 30px;
|
||||
margin-top: 4px;
|
||||
border-radius: 6px;
|
||||
font-size: 11px;
|
||||
color: var(--dsw-fg-3, rgba(127, 127, 127, 0.8));
|
||||
border: 1px dashed var(--dsw-border, rgba(127, 127, 127, 0.3));
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
/* Top-level area container (rows present). While dragging a project it gains
|
||||
.wgDropTarget so the whole area — rows and the gaps between them — reads as
|
||||
the move-out landing spot. */
|
||||
.wgTopLevelArea {
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
.wgProjectRow:hover {
|
||||
background: var(--dsw-bg-hover, rgba(127, 127, 127, 0.12));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -157,16 +157,15 @@ export function deriveGroups(
|
|||
const descendants = indexSubagentDescendants(list.byId)
|
||||
|
||||
// Bucket workspaces by display key. Seed with every effective category so
|
||||
// manual groups render while empty; the uncategorized bucket is appended
|
||||
// LAST (groups always sit above ungrouped projects).
|
||||
// manual groups render while empty. Top-level (ungrouped) workspaces are
|
||||
// handled by deriveTopLevel and never land here.
|
||||
const byCategory = new Map<string, WorkspaceView[]>()
|
||||
for (const { key } of effectiveCategories(config, manual)) {
|
||||
byCategory.set(key, [])
|
||||
}
|
||||
byCategory.set(UNCATEGORIZED_KEY, [])
|
||||
for (const workspace of workspaces) {
|
||||
const key = resolveCategory(config, manual, workspace.workspaceId, workspace.path, workspace.title)
|
||||
?? UNCATEGORIZED_KEY
|
||||
if (key === undefined) continue // top-level — rendered by deriveTopLevel
|
||||
if (!byCategory.has(key)) byCategory.set(key, [])
|
||||
byCategory.get(key)!.push(workspace)
|
||||
}
|
||||
|
|
@ -177,13 +176,8 @@ export function deriveGroups(
|
|||
: workspaces.find(w => w.sessionIds.includes(list.current as SessionId))?.workspaceId
|
||||
|
||||
const nodes: CategoryNode[] = []
|
||||
// Effective categories in display order (categoryOrder applied), then the
|
||||
// uncategorized bucket pinned to the very bottom.
|
||||
const orderedKeys = [
|
||||
...effectiveCategories(config, manual).map(e => e.key),
|
||||
UNCATEGORIZED_KEY,
|
||||
]
|
||||
for (const key of orderedKeys) {
|
||||
// Effective categories in display order (categoryOrder applied).
|
||||
for (const key of effectiveCategories(config, manual).map(e => e.key)) {
|
||||
const bucket = byCategory.get(key) ?? []
|
||||
// Manual groups stay visible while empty; everything else hides when empty.
|
||||
if (bucket.length === 0 && !manualCategories.has(key)) continue
|
||||
|
|
@ -211,7 +205,7 @@ export function deriveGroups(
|
|||
}
|
||||
nodes.push({
|
||||
key,
|
||||
label: key === UNCATEGORIZED_KEY ? UNCATEGORIZED_LABEL : key,
|
||||
label: key,
|
||||
expanded,
|
||||
containsCurrent,
|
||||
workspaces: workspaceNodes,
|
||||
|
|
@ -220,31 +214,53 @@ export function deriveGroups(
|
|||
return nodes
|
||||
}
|
||||
|
||||
/**
|
||||
* Top-level (ungrouped) workspace rows: workspaces resolving to no category
|
||||
* (no manual override and no matching rule, or a forced `null` override).
|
||||
* Rendered after the group folders as plain project rows (not inside any
|
||||
* folder), in host registration order.
|
||||
*/
|
||||
export function deriveTopLevel(
|
||||
list: SessionListState,
|
||||
workspaces: readonly WorkspaceView[],
|
||||
archivedSessionIds: readonly SessionId[],
|
||||
config: GroupsConfig,
|
||||
view: GroupsTreeView,
|
||||
manual: ManualGroups,
|
||||
): WorkspaceGroupNode[] {
|
||||
const archived = new Set(archivedSessionIds)
|
||||
const expandedWorkspaces = new Set(view.expandedWorkspaces)
|
||||
const descendants = indexSubagentDescendants(list.byId)
|
||||
const currentWorkspaceId = list.current === undefined
|
||||
? undefined
|
||||
: workspaces.find(w => w.sessionIds.includes(list.current as SessionId))?.workspaceId
|
||||
|
||||
const nodes: WorkspaceGroupNode[] = []
|
||||
for (const workspace of workspaces) {
|
||||
const key = resolveCategory(config, manual, workspace.workspaceId, workspace.path, workspace.title)
|
||||
if (key !== undefined) continue // grouped — rendered inside deriveGroups
|
||||
const sessions = workspaceSessions(list, workspace, archived, descendants)
|
||||
const wsExpanded = expandedWorkspaces.has(workspace.workspaceId as string)
|
||||
nodes.push({
|
||||
workspaceId: workspace.workspaceId,
|
||||
path: workspace.path,
|
||||
label: workspace.title,
|
||||
createdAt: Date.parse(workspace.createdAt),
|
||||
sessionCount: sessions.length,
|
||||
expanded: wsExpanded,
|
||||
containsCurrent: workspace.workspaceId === currentWorkspaceId,
|
||||
sessions: wsExpanded ? sessions : [],
|
||||
})
|
||||
}
|
||||
return nodes
|
||||
}
|
||||
|
||||
/** Recency comparator: newest first, id as the deterministic tiebreak. */
|
||||
function byRecency(a: SessionSummary, b: SessionSummary): number {
|
||||
if (b.updatedAt !== a.updatedAt) return b.updatedAt - a.updatedAt
|
||||
return a.id < b.id ? -1 : 1
|
||||
}
|
||||
|
||||
/**
|
||||
* While a drag is in progress, the empty uncategorized bucket must still
|
||||
* render as a drop target — otherwise a project can never be dragged OUT of a
|
||||
* group when every project is grouped (the bucket hides when empty). Appends
|
||||
* a collapsed empty uncategorized node when the bucket is absent; never
|
||||
* duplicates an existing one. Pure; the caller decides when a drag is active.
|
||||
*/
|
||||
export function withDraggingUncategorized(
|
||||
groups: readonly CategoryNode[],
|
||||
dragging: boolean,
|
||||
): readonly CategoryNode[] {
|
||||
if (!dragging) return groups
|
||||
if (groups.some(g => g.key === UNCATEGORIZED_KEY)) return groups
|
||||
return [
|
||||
...groups,
|
||||
{ key: UNCATEGORIZED_KEY, label: UNCATEGORIZED_LABEL, expanded: false, containsCurrent: false, workspaces: [] },
|
||||
]
|
||||
}
|
||||
|
||||
/** Bounded set of matched sessions plus content snippets (feeds the search tree). */
|
||||
export interface SearchMatchSet {
|
||||
/** Session ids that matched (local metadata hits + Host content hits). */
|
||||
|
|
@ -320,12 +336,21 @@ export function deriveSearchMatches(
|
|||
}
|
||||
}
|
||||
|
||||
/** Search tree: group folders plus top-level (ungrouped) matched workspaces. */
|
||||
export interface SearchTree {
|
||||
/** Group folders containing matched sessions, in display order. */
|
||||
categories: CategoryNode[]
|
||||
/** Top-level (ungrouped) workspaces holding matched sessions. */
|
||||
topLevel: WorkspaceGroupNode[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a three-level search tree containing ONLY the branches that hold a
|
||||
* matched session: 分类文件夹 → 项目文件夹 → 命中会话行. Every matched
|
||||
* session carries `matched: true` so rows render with the search-hit tint.
|
||||
* Classification uses the same precedence as the idle tree (manual override →
|
||||
* rules), so search shows the same grouping the user sees.
|
||||
* rules), so search shows the same grouping the user sees. Matched top-level
|
||||
* workspaces are returned separately (rendered as plain rows).
|
||||
*
|
||||
* @param list - sessions list snapshot.
|
||||
* @param workspaces - real workspaces in stable Host order.
|
||||
|
|
@ -334,7 +359,8 @@ export function deriveSearchMatches(
|
|||
* @param archivedSessionIds - registry-global archive set.
|
||||
* @param manual - runtime overlay (manual groups + overrides).
|
||||
* @param snippetsBySession - optional content-match snippets keyed by session id.
|
||||
* @returns categories in render order, pruned to matched branches only.
|
||||
* @returns group folders in render order plus top-level matched workspaces,
|
||||
* pruned to matched branches only.
|
||||
*/
|
||||
export function deriveSearchGroups(
|
||||
list: SessionListState,
|
||||
|
|
@ -344,14 +370,14 @@ export function deriveSearchGroups(
|
|||
archivedSessionIds: readonly SessionId[],
|
||||
manual: ManualGroups,
|
||||
snippetsBySession?: ReadonlyMap<SessionId, string>,
|
||||
): CategoryNode[] {
|
||||
): SearchTree {
|
||||
const archived = new Set(archivedSessionIds)
|
||||
const descendants = indexSubagentDescendants(list.byId)
|
||||
|
||||
const byCategory = new Map<string, WorkspaceGroupNode[]>()
|
||||
for (const key of effectiveCategories(config, manual).map(e => e.key)) byCategory.set(key, [])
|
||||
byCategory.set(UNCATEGORIZED_KEY, [])
|
||||
|
||||
const topLevel: WorkspaceGroupNode[] = []
|
||||
for (const workspace of workspaces) {
|
||||
// Only sessions that matched the query and are visible in this folder.
|
||||
const nodes: SessionNode[] = []
|
||||
|
|
@ -369,10 +395,7 @@ export function deriveSearchGroups(
|
|||
}
|
||||
if (nodes.length === 0) continue
|
||||
|
||||
const key = resolveCategory(config, manual, workspace.workspaceId, workspace.path, workspace.title)
|
||||
?? UNCATEGORIZED_KEY
|
||||
if (!byCategory.has(key)) byCategory.set(key, [])
|
||||
byCategory.get(key)!.push({
|
||||
const node: WorkspaceGroupNode = {
|
||||
workspaceId: workspace.workspaceId,
|
||||
path: workspace.path,
|
||||
label: workspace.title,
|
||||
|
|
@ -381,25 +404,28 @@ export function deriveSearchGroups(
|
|||
expanded: true,
|
||||
containsCurrent: false,
|
||||
sessions: nodes,
|
||||
})
|
||||
}
|
||||
const key = resolveCategory(config, manual, workspace.workspaceId, workspace.path, workspace.title)
|
||||
if (key === undefined) {
|
||||
topLevel.push(node)
|
||||
continue
|
||||
}
|
||||
if (!byCategory.has(key)) byCategory.set(key, [])
|
||||
byCategory.get(key)!.push(node)
|
||||
}
|
||||
|
||||
const categories: CategoryNode[] = []
|
||||
// Same display order as the idle tree; the uncategorized bucket stays last.
|
||||
const orderedKeys = [
|
||||
...effectiveCategories(config, manual).map(e => e.key),
|
||||
UNCATEGORIZED_KEY,
|
||||
]
|
||||
for (const key of orderedKeys) {
|
||||
// Same display order as the idle tree.
|
||||
for (const key of effectiveCategories(config, manual).map(e => e.key)) {
|
||||
const workspaceNodes = byCategory.get(key)
|
||||
if (workspaceNodes === undefined || workspaceNodes.length === 0) continue
|
||||
categories.push({
|
||||
key,
|
||||
label: key === UNCATEGORIZED_KEY ? UNCATEGORIZED_LABEL : key,
|
||||
label: key,
|
||||
expanded: true,
|
||||
containsCurrent: false,
|
||||
workspaces: workspaceNodes,
|
||||
})
|
||||
}
|
||||
return categories
|
||||
return { categories, topLevel }
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@
|
|||
* name (or a manual-group name). Its DISPLAY key is what the tree renders and
|
||||
* what assignments reference — for rule categories that is the rename
|
||||
* override when present. Hidden rule categories are inert: workspaces that
|
||||
* would match them fall into the uncategorized bucket.
|
||||
* would match them become top-level (ungrouped).
|
||||
*/
|
||||
import {
|
||||
normalizePath,
|
||||
|
|
@ -73,7 +73,8 @@ export function originalRuleNameForDisplay(
|
|||
* Effective category entries in display order: rule categories (YAML order,
|
||||
* hidden skipped, renamed applied) first, then manual-only groups in
|
||||
* creation order — unless `manual.categoryOrder` overrides the sequence.
|
||||
* The uncategorized bucket is never included (it always renders last).
|
||||
* Top-level (ungrouped) workspaces are never included; they render as
|
||||
* separate top-level rows after the group folders.
|
||||
*/
|
||||
export interface EffectiveCategory {
|
||||
/** Display key (what the tree renders and assignments reference). */
|
||||
|
|
@ -115,15 +116,15 @@ export function effectiveCategories(
|
|||
})
|
||||
}
|
||||
|
||||
/** Display keys of all effective categories (uncategorized bucket excluded). */
|
||||
/** Display keys of all effective categories (top-level workspaces excluded). */
|
||||
export function displayCategoryKeys(config: GroupsConfig, manual: ManualGroups | undefined): string[] {
|
||||
return effectiveCategories(config, manual).map(e => e.key)
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the category key a workspace renders under. Precedence:
|
||||
* manual override (`null` = force uncategorized) → rule classification
|
||||
* (hidden rules inert) → uncategorized bucket (`undefined`).
|
||||
* Resolve the category key a workspace renders under, or `undefined` when it
|
||||
* is top-level (ungrouped). Precedence: manual override (`null` = forced
|
||||
* top-level) → rule classification (hidden rules inert) → top-level.
|
||||
*/
|
||||
export function resolveCategory(
|
||||
config: GroupsConfig,
|
||||
|
|
@ -133,7 +134,7 @@ export function resolveCategory(
|
|||
title: string,
|
||||
): string | undefined {
|
||||
const override = manual?.assignments[workspaceId]
|
||||
if (override !== undefined) return override ?? undefined // null forces the uncategorized bucket
|
||||
if (override !== undefined) return override ?? undefined // null forces top-level
|
||||
const matched = classify(config.categories, path, title)
|
||||
if (matched === undefined) return undefined
|
||||
if (isHiddenRule(manual, matched.name)) return undefined
|
||||
|
|
@ -150,8 +151,8 @@ export function isManualOnlyCategory(
|
|||
}
|
||||
|
||||
/**
|
||||
* Names that may not be used for a new/renamed group: the reserved
|
||||
* uncategorized label plus every current display key.
|
||||
* Names that may not be used for a new/renamed group: the legacy reserved
|
||||
* label plus every current display key.
|
||||
*/
|
||||
export function takenCategoryNames(config: GroupsConfig, manual: ManualGroups | undefined): Set<string> {
|
||||
const taken = new Set<string>(displayCategoryKeys(config, manual))
|
||||
|
|
|
|||
|
|
@ -81,12 +81,17 @@ export interface ManualGroups {
|
|||
renamed?: Record<string, string>
|
||||
/**
|
||||
* Rule category original names hidden by a UI delete. Hidden rules are
|
||||
* inert: workspaces matching them fall into the uncategorized bucket.
|
||||
* inert: workspaces matching them become top-level (ungrouped).
|
||||
*/
|
||||
hidden?: string[]
|
||||
}
|
||||
|
||||
/** The label of the fallback bucket for unmatched workspaces. */
|
||||
/**
|
||||
* Legacy label of the fallback bucket. The top-level (ungrouped) concept
|
||||
* replaced the rendered "未分类" bucket: workspaces in no group render as
|
||||
* top-level rows beside the group folders. The constant survives for data
|
||||
* compatibility (reserved name, assignment null marker).
|
||||
*/
|
||||
export const UNCATEGORIZED_LABEL = '未分类'
|
||||
|
||||
/** Normalize a path for prefix matching: trailing slashes stripped. */
|
||||
|
|
|
|||
|
|
@ -1,7 +1,8 @@
|
|||
/**
|
||||
* Tree-derivation tests: the renderer's data-shaping contract — manual
|
||||
* overrides win over rules, manual groups render while empty, rule buckets
|
||||
* hide while empty, and the uncategorized bucket collects the rest.
|
||||
* hide while empty, and top-level (ungrouped) workspaces render as separate
|
||||
* rows after the group folders (no "未分类" bucket).
|
||||
* Pure derivation (no DOM), fixtures cast to the runtime contract types.
|
||||
*
|
||||
* The browser runtime bundle self-registers via window.__ModuleLoader__ and
|
||||
|
|
@ -15,8 +16,8 @@ vi.mock('@deepseek-ai/dsh-client-runtime/client', () => ({
|
|||
}))
|
||||
|
||||
import type { SessionListState, SessionSummary, WorkspaceView } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import { deriveGroups, withDraggingUncategorized } from '../src/client/tree.ts'
|
||||
import { UNCATEGORIZED_LABEL, type GroupsConfig, type ManualGroups } from '../src/core/types.ts'
|
||||
import { deriveGroups, deriveTopLevel } from '../src/client/tree.ts'
|
||||
import type { GroupsConfig, ManualGroups } from '../src/core/types.ts'
|
||||
|
||||
const CONFIG: GroupsConfig = {
|
||||
categories: [
|
||||
|
|
@ -65,13 +66,15 @@ describe('deriveGroups with the manual overlay', () => {
|
|||
workspace('ws-c', '/tmp/random', 'Random'),
|
||||
]
|
||||
|
||||
it('groups by rules without an overlay', () => {
|
||||
it('groups by rules without an overlay; unmatched workspaces are top-level', () => {
|
||||
const groups = deriveGroups(listState(workspaces), workspaces, [], CONFIG, VIEW, { categories: [], assignments: {} })
|
||||
const labels = groups.map(g => g.label)
|
||||
expect(labels).toEqual(['DSH 插件', '文档', UNCATEGORIZED_LABEL])
|
||||
expect(labels).toEqual(['DSH 插件', '文档'])
|
||||
expect(groups[0]?.workspaces.map(w => w.workspaceId)).toEqual(['ws-a'])
|
||||
expect(groups[1]?.workspaces.map(w => w.workspaceId)).toEqual(['ws-b'])
|
||||
expect(groups[2]?.workspaces.map(w => w.workspaceId)).toEqual(['ws-c'])
|
||||
// ws-c matches no rule → top-level, not in any bucket.
|
||||
const top = deriveTopLevel(listState(workspaces), workspaces, [], CONFIG, VIEW, { categories: [], assignments: {} })
|
||||
expect(top.map(w => w.workspaceId)).toEqual(['ws-c'])
|
||||
})
|
||||
|
||||
it('a manual override moves a workspace into a manual group', () => {
|
||||
|
|
@ -98,7 +101,7 @@ describe('deriveGroups with the manual overlay', () => {
|
|||
expect(groups).toEqual([])
|
||||
})
|
||||
|
||||
it('drops into the uncategorized bucket are represented by absent overrides', () => {
|
||||
it('removing an override reverts to rule classification', () => {
|
||||
// ws-a overridden to 临时; override removed → rule classification applies again.
|
||||
const withOverride: ManualGroups = { categories: ['临时'], assignments: { 'ws-a': '临时' } }
|
||||
const moved = deriveGroups(listState(workspaces), workspaces, [], CONFIG, VIEW, withOverride)
|
||||
|
|
@ -110,13 +113,13 @@ describe('deriveGroups with the manual overlay', () => {
|
|||
expect(back.find(g => g.label === 'DSH 插件')?.workspaces.map(w => w.workspaceId)).toEqual(['ws-a'])
|
||||
})
|
||||
|
||||
it('a null override forces the uncategorized bucket (rule match ignored)', () => {
|
||||
it('a null override forces top-level (rule match ignored)', () => {
|
||||
const manual: ManualGroups = { categories: [], assignments: { 'ws-a': null } }
|
||||
const groups = deriveGroups(listState(workspaces), workspaces, [], CONFIG, VIEW, manual)
|
||||
const byLabel = new Map(groups.map(g => [g.label, g]))
|
||||
// ws-a forced to uncategorized; ws-c matches no rule and sits there too.
|
||||
expect(byLabel.get(UNCATEGORIZED_LABEL)?.workspaces.map(w => w.workspaceId)).toEqual(['ws-a', 'ws-c'])
|
||||
expect(byLabel.has('DSH 插件')).toBe(false)
|
||||
expect(groups.find(g => g.label === 'DSH 插件')).toBeUndefined()
|
||||
const top = deriveTopLevel(listState(workspaces), workspaces, [], CONFIG, VIEW, manual)
|
||||
// ws-a forced top-level; ws-c matches no rule and is top-level too.
|
||||
expect(top.map(w => w.workspaceId)).toEqual(['ws-a', 'ws-c'])
|
||||
})
|
||||
|
||||
it('stored workspace order wins inside a bucket', () => {
|
||||
|
|
@ -133,18 +136,6 @@ describe('deriveGroups with the manual overlay', () => {
|
|||
expect(groups.find(g => g.label === 'DSH 插件')?.workspaces.map(w => w.workspaceId)).toEqual(['ws-a2', 'ws-a1'])
|
||||
})
|
||||
|
||||
it('the uncategorized bucket is always the last section', () => {
|
||||
const manual: ManualGroups = {
|
||||
categories: ['临时'],
|
||||
assignments: { 'ws-b': '临时', 'ws-c': null },
|
||||
categoryOrder: ['临时'],
|
||||
}
|
||||
const groups = deriveGroups(listState(workspaces), workspaces, [], CONFIG, VIEW, manual)
|
||||
expect(groups[groups.length - 1]?.label).toBe(UNCATEGORIZED_LABEL)
|
||||
// ws-c (forced uncategorized) and any rule-less workspaces sit at the bottom.
|
||||
expect(groups[groups.length - 1]?.workspaces.map(w => w.workspaceId)).toEqual(['ws-c'])
|
||||
})
|
||||
|
||||
it('a renamed rule category renders under the new name', () => {
|
||||
const manual: ManualGroups = { categories: [], assignments: {}, renamed: { 'DSH 插件': '插件集' } }
|
||||
const groups = deriveGroups(listState(workspaces), workspaces, [], CONFIG, VIEW, manual)
|
||||
|
|
@ -154,43 +145,39 @@ describe('deriveGroups with the manual overlay', () => {
|
|||
expect(byLabel.has('DSH 插件')).toBe(false)
|
||||
})
|
||||
|
||||
it('a hidden rule category is inert — its members fall to uncategorized', () => {
|
||||
it('a hidden rule category is inert — its members become top-level', () => {
|
||||
const manual: ManualGroups = { categories: [], assignments: {}, hidden: ['DSH 插件'] }
|
||||
const groups = deriveGroups(listState(workspaces), workspaces, [], CONFIG, VIEW, manual)
|
||||
const byLabel = new Map(groups.map(g => [g.label, g]))
|
||||
expect(byLabel.get(UNCATEGORIZED_LABEL)?.workspaces.map(w => w.workspaceId)).toEqual(['ws-a', 'ws-c'])
|
||||
expect(groups.find(g => g.label === 'DSH 插件')).toBeUndefined()
|
||||
const top = deriveTopLevel(listState(workspaces), workspaces, [], CONFIG, VIEW, manual)
|
||||
expect(top.map(w => w.workspaceId)).toEqual(['ws-a', 'ws-c'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('withDraggingUncategorized', () => {
|
||||
describe('deriveTopLevel', () => {
|
||||
const ws = [
|
||||
workspace('ws-a', '/Users/zcol/Project/SomePlugin', 'DSH插件Demo'),
|
||||
workspace('ws-b', '/Users/zcol/Project/MyDocs', 'MyDocs'),
|
||||
workspace('ws-c', '/tmp/random', 'Random'),
|
||||
]
|
||||
const groups = deriveGroups(listState(ws), ws, [], CONFIG, VIEW, { categories: [], assignments: {} })
|
||||
|
||||
it('leaves the tree untouched when no drag is active', () => {
|
||||
expect(withDraggingUncategorized(groups, false)).toBe(groups)
|
||||
it('keeps host order for ungrouped workspaces', () => {
|
||||
const manual: ManualGroups = { categories: [], assignments: { 'ws-a': null, 'ws-b': '文档' } }
|
||||
const top = deriveTopLevel(listState(ws), ws, [], CONFIG, VIEW, manual)
|
||||
// ws-a (forced) and ws-c (rule-less), in host order; ws-b grouped.
|
||||
expect(top.map(w => w.workspaceId)).toEqual(['ws-a', 'ws-c'])
|
||||
})
|
||||
|
||||
it('appends a collapsed empty uncategorized bucket while dragging when absent', () => {
|
||||
// All workspaces are grouped — the idle tree has no uncategorized section.
|
||||
expect(groups.some(g => g.key === UNCATEGORIZED_LABEL)).toBe(false)
|
||||
const during = withDraggingUncategorized(groups, true)
|
||||
expect(during.length).toBe(groups.length + 1)
|
||||
const bucket = during[during.length - 1]
|
||||
expect(bucket?.key).toBe(UNCATEGORIZED_LABEL)
|
||||
expect(bucket?.expanded).toBe(false)
|
||||
expect(bucket?.workspaces).toEqual([])
|
||||
})
|
||||
|
||||
it('never duplicates an existing uncategorized bucket', () => {
|
||||
const withBucket = deriveGroups(listState(ws), ws, [], CONFIG, VIEW, {
|
||||
categories: [], assignments: { 'ws-b': null },
|
||||
})
|
||||
expect(withBucket.some(g => g.key === UNCATEGORIZED_LABEL)).toBe(true)
|
||||
const during = withDraggingUncategorized(withBucket, true)
|
||||
expect(during).toBe(withBucket)
|
||||
expect(during.filter(g => g.key === UNCATEGORIZED_LABEL)).toHaveLength(1)
|
||||
it('top-level rows are expanded according to the view', () => {
|
||||
const wsC = workspace('ws-c', '/tmp/random', 'Random', ['s1'])
|
||||
const view = { expandedCategories: [], expandedWorkspaces: ['ws-c'] }
|
||||
const top = deriveTopLevel(listState([wsC]), [wsC], [], CONFIG, view, { categories: [], assignments: {} })
|
||||
expect(top[0]?.expanded).toBe(true)
|
||||
expect(top[0]?.sessions).toHaveLength(1)
|
||||
expect(top[0]?.sessions[0]?.id).toBe('s1')
|
||||
// Collapsed view → no sessions.
|
||||
const collapsed = deriveTopLevel(listState([wsC]), [wsC], [], CONFIG, VIEW, { categories: [], assignments: {} })
|
||||
expect(collapsed[0]?.expanded).toBe(false)
|
||||
expect(collapsed[0]?.sessions).toEqual([])
|
||||
})
|
||||
})
|
||||
|
|
|
|||
Loading…
Reference in New Issue