dsh-delete-session 0.2.9 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -162,6 +162,15 @@ MIT
162
162
 
163
163
  ## 修复记录
164
164
 
165
+ **(v0.3.0)** —— 多选支持按工作区全选,也能一次选中全部会话。
166
+
167
+ - **两个全选框**:`工作区 N` 那一行多一个框,选中**所有**会话;每个工作区标题行(含「未分组」)各多一个框,只选中**该组**。点一下全选,再点一下清空。
168
+ - **分组归属从 DOM 读,不向宿主索取**:会话行与工作区标题行同属一个 `groupSection`,从标题行向上找容器再取子行即可。宿主给工作区行的外面还套了一层 `HoverCard` 的 `<span>`,所以不能只看 `parentElement`,要逐层向上,并在「这一层已经装着几个工作区」时停手——否则会把别组的会话一起卷进来。嵌套的 `div[role="group"]` 直接跳过。
169
+ - **半选状态**:组里只勾了几个时,组框显示 `−`(`aria-checked="mixed"`),而不是谎报全选或全不选。
170
+ - **位置在标签文字右边**:宿主把行尾操作区用 `margin-left:auto` 推到最右,直接 `appendChild` 会落到行的另一头;框插在 `[class*="_rowActions"]` 之前。工作区名是 `flex:1`,会把剩余宽度全部吃掉,所以框后面还要跟一条 `flex:1` 的间隔条,把数值/菜单/新建重新顶回行尾。
171
+ - **修饰过的元素不参与行点击**:多选的点击走 document 的 capture 阶段,框会长在工作区行里面,不加标记就会被当成「点了一行」而被吞掉。所有自建元素都带 `data-dsh-delete-session`,capture 监听先跳过它们。
172
+ - **不再自己触发自己**:装饰只在位置不对时碰 DOM,变更观察器也忽略自己插入的节点。原来每帧重插会把框从指针底下反复摘走,表现为「狂点十几次才中一次」。
173
+ - **不假设 `children` 是数组**:浏览器里它是 `HTMLCollection`,没有 `indexOf`,一次误用就让整趟装饰抛异常、框一个都不出现。
165
174
  **(v0.2.9)** —— 俄语界面 + 修掉拖拽标签里的 `{name}`。
166
175
 
167
176
  - **俄语(`ru`)**:来自社区贡献([#1](https://github.com/DDDMUC/dsh-delete-session/pull/1),作者 [@aleXela17](https://github.com/aleXela17))。98 条词条与中英完全对齐,函数型条目仍然返回数字。DSH 自身没有 ru 语言包,所以俄语浏览器下插件字典优先于宿主翻译;中英路径不变,宿主仍是权威。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-delete-session",
3
- "version": "0.2.9",
3
+ "version": "0.3.0",
4
4
  "description": "Delete sessions from the DSH Web sidebar: adds a Delete action to the session row menu with a risk-consent dialog, sends the session log, workspace accounting and live session state to the system trash (or removes them outright), and, when opted in, quarantines the files the conversation produced.",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
package/src/client.js CHANGED
@@ -36,6 +36,8 @@ window.__ModuleLoader__.load({
36
36
  const zh = {
37
37
  menu: '删除会话',
38
38
  multiSelect: '多选',
39
+ selectAllGroup: '全选这个工作区',
40
+ selectAllWorkspaces: '全选所有工作区',
39
41
  title: '删除会话',
40
42
  descRecycle: '将把该会话及其全部对话记录(会话日志、工作区记账与统计)从列表中移除,并放进系统回收站。',
41
43
  descPermanent: '将永久删除该会话及其全部对话记录(会话日志、工作区记账与统计),此操作不可恢复。',
@@ -140,6 +142,8 @@ window.__ModuleLoader__.load({
140
142
  const en = {
141
143
  menu: 'Delete session',
142
144
  multiSelect: 'Select multiple',
145
+ selectAllGroup: 'Select every session in this workspace',
146
+ selectAllWorkspaces: 'Select every session in every workspace',
143
147
  title: 'Delete session',
144
148
  descRecycle: 'This removes the session and all of its conversation records (log, workspace accounting and statistics) from the list and puts them in the system trash.',
145
149
  descPermanent: 'This permanently deletes the session and all of its conversation records (log, workspace accounting and statistics). This cannot be undone.',
@@ -241,6 +245,8 @@ window.__ModuleLoader__.load({
241
245
  const ru = {
242
246
  menu: 'Удалить сессию',
243
247
  multiSelect: 'Выбрать несколько',
248
+ selectAllGroup: 'Выбрать все сессии этой рабочей папки',
249
+ selectAllWorkspaces: 'Выбрать все сессии во всех рабочих папках',
244
250
  title: 'Удалить сессию',
245
251
  descRecycle: 'Сессия и все её записи (журнал, учёт рабочей папки и статистика) будут убраны из списка и перемещены в системную корзину.',
246
252
  descPermanent: 'Сессия и все её записи (журнал, учёт рабочей папки и статистика) будут удалены безвозвратно. Отменить это нельзя.',
@@ -893,6 +899,27 @@ window.__ModuleLoader__.load({
893
899
  '@keyframes dsdel-toast-in{from{opacity:0;transform:translate(-50%,6px)}to{opacity:1;transform:translate(-50%,0)}}',
894
900
  '@media (prefers-reduced-motion:reduce){.dsdel-toast{animation:none}.dsdel-field{transition:none}}',
895
901
  '.dsdel-check{display:inline-flex;align-items:center;justify-content:center;width:18px;height:18px;border-radius:50%;border:1.5px solid var(--dsw-alias-border-l3,rgba(128,128,128,.5));background:transparent;flex:none;margin-right:8px;box-sizing:border-box;cursor:pointer}',
902
+ // The two select-all boxes sit where the host puts them: inside each
903
+ // workspace header row, and inside the `工作区 N` heading above all of them.
904
+ //
905
+ // They live in the SIDEBAR, outside the `.dsdel-page` / `.dsdel-modal` /
906
+ // `.dsdel-bar` token scope, so every rule here reads a host alias with its
907
+ // own fallback. Reaching for `var(--dsdel-border)` was the bug: an unknown
908
+ // custom property voids the whole declaration, which left the box with no
909
+ // border, no content and nothing to click on.
910
+
911
+ // The spacer is the only child that grows, so the right-hand cluster keeps
912
+ // its place at the row's end while the box stays beside the name.
913
+ '.dsdel-flex-spacer{flex:1 1 auto;min-width:0;align-self:center;height:1px}',
914
+ '.dsdel-select-all,.dsdel-select-all-workspaces{flex:0 0 auto;box-sizing:border-box;width:15px;height:15px;min-width:15px;margin:0 0 0 6px;padding:0;display:inline-flex;align-items:center;justify-content:center;border:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.45));border-radius:4px;background:transparent;color:var(--dsw-alias-label-secondary,#666);font-size:10px;line-height:1;cursor:pointer;opacity:1;visibility:visible;align-self:center}',
915
+ '.dsdel-select-all:hover,.dsdel-select-all-workspaces:hover{border-color:var(--dsw-alias-brand-primary,#4c8dff);color:var(--dsw-alias-brand-primary,#4c8dff)}',
916
+ '.dsdel-select-all[aria-checked="true"],.dsdel-select-all-workspaces[aria-checked="true"]{background:var(--dsw-alias-brand-primary,#4c8dff);border-color:var(--dsw-alias-brand-primary,#4c8dff);color:#fff}',
917
+ '.dsdel-select-all[aria-checked="mixed"],.dsdel-select-all-workspaces[aria-checked="mixed"]{border-color:var(--dsw-alias-brand-primary,#4c8dff);color:var(--dsw-alias-brand-primary,#4c8dff)}',
918
+ '.dsdel-select-all:focus-visible,.dsdel-select-all-workspaces:focus-visible{outline:2px solid var(--dsw-alias-brand-primary,#4c8dff);outline-offset:1px}',
919
+ // While the mode runs, let the workspace name size to its own text. With
920
+ // `flex:1` it fills the row, so the select-all box inserted after it was
921
+ // pushed to the far edge even though it sits early in the child list.
922
+ 'body.dsdel-selecting [class*="_projectText"]{flex:0 1 auto;min-width:0}',
896
923
  '.dsdel-check-on{background:var(--dsw-alias-state-business-primary,#4c6ef5);border-color:var(--dsw-alias-state-business-primary,#4c6ef5)}',
897
924
  '.dsdel-check-on::after{content:"";width:9px;height:5px;border-left:2px solid #fff;border-bottom:2px solid #fff;transform:rotate(-45deg) translateY(-1px)}',
898
925
  // 乐观删除:行先隐藏,失败时随 decorate 恢复
@@ -1084,6 +1111,244 @@ window.__ModuleLoader__.load({
1084
1111
  else openDeleteDialog(drag.sessionId, drag.title)
1085
1112
  }
1086
1113
 
1114
+ // --- select a whole workspace ----------------------------------------------
1115
+ //
1116
+ // The sidebar groups sessions under `[data-row-key="workspace:<key>"]` headers,
1117
+ // and the host renders the `工作区 N` heading above all of them as
1118
+ // `[data-sidebar-workspace-header]`. Both get a checkbox of their own while the
1119
+ // mode runs: one per group, one for every group together.
1120
+ //
1121
+ // Group membership is read off the DOM rather than asked from the host: a
1122
+ // session row and its workspace row are siblings inside the same section
1123
+ // element, so a subtree query from the header finds exactly that group.
1124
+
1125
+ const GROUP_BUTTON = 'dsdel-select-all'
1126
+ const SPACER = 'dsdel-flex-spacer'
1127
+ const ALL_BUTTON = 'dsdel-select-all-workspaces'
1128
+ const WORKSPACE_ROWS_HEADER = '[data-sidebar-workspace-header]'
1129
+
1130
+ /**
1131
+ * Position of `node` among `parent`'s element children, or -1.
1132
+ *
1133
+ * `children` is an HTMLCollection in a browser and a plain array in the test
1134
+ * stub. HTMLCollection has no `indexOf`, so the call has to be spelled out.
1135
+ */
1136
+ function childIndex(parent, node) {
1137
+ if (parent === null || parent === undefined) return -1
1138
+ const kids = parent.children
1139
+ if (kids === null || kids === undefined) return -1
1140
+ for (let i = 0; i < kids.length; i += 1) {
1141
+ if (kids[i] === node) return i
1142
+ }
1143
+ return -1
1144
+ }
1145
+
1146
+ /** `data-row-key` of a sidebar row, or null. */
1147
+ function rowKeyOf(node) {
1148
+ if (node === null || node === undefined || typeof node.getAttribute !== 'function') return null
1149
+ return node.getAttribute('data-row-key')
1150
+ }
1151
+
1152
+ /**
1153
+ * The session ids under one workspace header row.
1154
+ *
1155
+ * The row is not always a direct child of its section: the host may wrap it
1156
+ * (a hover card, a drag shell), and a subtree query from that wrapper finds
1157
+ * no sessions at all. So the ancestors are climbed until one of them owns
1158
+ * session rows — that ancestor is the section.
1159
+ */
1160
+ /**
1161
+ * Rows that sit directly in `node`, looking one level into a wrapper.
1162
+ *
1163
+ * The host wraps the workspace row in `HoverCard`'s <span>, so the row's
1164
+ * `parentElement` is that span and not the group section. Whatever contains
1165
+ * the rows also has to be read through it.
1166
+ *
1167
+ * A `div[role="group"]` child is a NESTED workspace: it is skipped, or a
1168
+ * parent's select-all would sweep in its children's sessions.
1169
+ */
1170
+ function ownRows(node) {
1171
+ const rows = []
1172
+ const visit = (parent, depth) => {
1173
+ if (parent === null || parent === undefined || parent.children === undefined) return
1174
+ for (const child of parent.children) {
1175
+ const key = typeof child.getAttribute === 'function' ? child.getAttribute('data-row-key') : null
1176
+ if (key !== null) { rows.push(child); continue }
1177
+ if (depth >= 2) continue
1178
+ if (typeof child.getAttribute === 'function' && child.getAttribute('role') === 'group') continue
1179
+ visit(child, depth + 1)
1180
+ }
1181
+ }
1182
+ visit(node, 0)
1183
+ return rows
1184
+ }
1185
+
1186
+ /**
1187
+ * The session ids under one workspace header row.
1188
+ *
1189
+ * Climbed rather than assumed: a wrapper span put every id out of reach, so
1190
+ * the box ended up with an empty list and `toggleGroup` returned without
1191
+ * doing anything. The climb stops as soon as it reaches a container holding
1192
+ * more than one workspace, which is the shared list — grabbing there would
1193
+ * hand this group every other group's sessions.
1194
+ */
1195
+ function sessionsUnderWorkspace(headRow) {
1196
+ let node = headRow.parentElement
1197
+ for (let depth = 0; depth < 6; depth += 1) {
1198
+ if (node === null || node === undefined) return []
1199
+ const rows = ownRows(node)
1200
+ let workspaces = 0
1201
+ const ids = []
1202
+ for (const row of rows) {
1203
+ const key = rowKeyOf(row)
1204
+ if (typeof key !== 'string') continue
1205
+ if (key.startsWith('workspace:')) workspaces += 1
1206
+ else if (key.startsWith('session:')) ids.push(key.slice('session:'.length))
1207
+ }
1208
+ if (workspaces > 1) return []
1209
+ if (ids.length > 0) return ids
1210
+ node = node.parentElement
1211
+ }
1212
+ return []
1213
+ }
1214
+
1215
+
1216
+ /**
1217
+ * The tri-state a select-all box shows: every id in, none in, or something
1218
+ * between. `mixed` is what tells a user their group is partly ticked.
1219
+ */
1220
+ function groupState(ids) {
1221
+ if (ids.length === 0) return 'false'
1222
+ let picked = 0
1223
+ for (const id of ids) if (state.selected.has(id)) picked += 1
1224
+ if (picked === 0) return 'false'
1225
+ return picked === ids.length ? 'true' : 'mixed'
1226
+ }
1227
+
1228
+ /** Ticking a full or partly ticked box clears the group; an empty one fills it. */
1229
+ function toggleGroup(ids) {
1230
+ if (ids.length === 0) return
1231
+ const fill = groupState(ids) !== 'true'
1232
+ for (const id of ids) {
1233
+ if (fill) state.selected.add(id)
1234
+ else state.selected.delete(id)
1235
+ }
1236
+ publish()
1237
+ }
1238
+
1239
+ /**
1240
+ * Place (or refresh) one of the two boxes. `host` gets nothing appended twice:
1241
+ * the element is looked up by class first, so a decorate pass after a host
1242
+ * re-render reuses the box it already owns.
1243
+ */
1244
+ /**
1245
+ * Place (or refresh) one of the two boxes.
1246
+ *
1247
+ * `anchor` is the class of the element the box should sit IN FRONT OF: the
1248
+ * host pushes its right-hand actions out with an auto margin, so appending at
1249
+ * the end drops the box at the row's far edge. Inserting before those actions
1250
+ * puts it right after the label, which is where it reads as part of the
1251
+ * heading.
1252
+ */
1253
+ function placeGroupBox(host, className, label, ids, anchor) {
1254
+ if (host === null || host === undefined) return
1255
+ let box = typeof host.querySelector === 'function' ? host.querySelector('.' + className) : null
1256
+ const created = box === null
1257
+ if (created) {
1258
+ box = document.createElement('button')
1259
+ box.setAttribute('type', 'button')
1260
+ box.className = className
1261
+ box.setAttribute('role', 'checkbox')
1262
+ box.addEventListener('click', (event) => {
1263
+ // The workspace header toggles its group on click; this box must not.
1264
+ if (event && typeof event.stopPropagation === 'function') event.stopPropagation()
1265
+ toggleGroup(box.__dsdelIds || [])
1266
+ })
1267
+ }
1268
+
1269
+ // The anchor is a comma list, tried one at a time: a document-order match
1270
+ // could otherwise pick a later sibling than the caller meant.
1271
+ let before = null
1272
+ if (anchor !== undefined && anchor !== null) {
1273
+ for (const selector of String(anchor).split(',')) {
1274
+ const found = host.querySelector(selector.trim())
1275
+ if (found !== null && found !== undefined) { before = found; break }
1276
+ }
1277
+ }
1278
+
1279
+ // ALWAYS insert, not only on creation. A box placed by an earlier decorate
1280
+ // pass (or an earlier build) kept its old seat forever, because the insert
1281
+ // sat inside the `created` branch: the header box moved on the next pass and
1282
+ // the workspace box did not. `insertBefore` on an existing child just moves
1283
+ // it, so this is idempotent.
1284
+ // One flex child has to absorb the free space, or the whole right-hand
1285
+ // cluster (count, menu, new-session) slides left with the box. The spacer
1286
+ // takes that job so the name can stay at its natural width.
1287
+ let spacer = host.querySelector('.' + SPACER)
1288
+ if (before !== null && before !== undefined) {
1289
+ if (spacer === null) {
1290
+ spacer = document.createElement('span')
1291
+ spacer.className = SPACER
1292
+ spacer.setAttribute('aria-hidden', 'true')
1293
+ spacer.setAttribute('data-dsh-delete-session', 'spacer')
1294
+ }
1295
+ // Only touch the DOM when something is actually out of place. Every
1296
+ // `insertBefore` is a real mutation, and the list observer counted it as
1297
+ // a change: moving the box on every pass fed the observer its own work,
1298
+ // so a new pass was scheduled for the next frame, forever. A click that
1299
+ // landed while the box was detached and re-attached never completed,
1300
+ // which is why it took a dozen taps to hit it once.
1301
+ const boxAt = childIndex(host, box)
1302
+ const spacerAt = childIndex(host, spacer)
1303
+ const beforeAt = childIndex(host, before)
1304
+ if (boxAt === -1 || spacerAt === -1 || beforeAt === -1
1305
+ || boxAt !== spacerAt - 1 || beforeAt !== spacerAt + 1) {
1306
+ host.insertBefore(spacer, before)
1307
+ host.insertBefore(box, spacer)
1308
+ }
1309
+ } else if (created) {
1310
+ host.appendChild(box)
1311
+ }
1312
+
1313
+ box.setAttribute('aria-label', label)
1314
+ box.setAttribute('data-dsh-delete-session', 'select-all')
1315
+ const state_ = groupState(ids)
1316
+ box.setAttribute('aria-checked', state_)
1317
+ box.textContent = state_ === 'true' ? '✓' : (state_ === 'mixed' ? '−' : '')
1318
+ box.__dsdelIds = ids
1319
+ }
1320
+ function decorateSelectAll(rows) {
1321
+ if (!state.selecting) {
1322
+ for (const el of document.querySelectorAll('.' + GROUP_BUTTON)) el.remove()
1323
+ for (const el of document.querySelectorAll('.' + ALL_BUTTON)) el.remove()
1324
+ for (const el of document.querySelectorAll('.' + SPACER)) el.remove()
1325
+ return
1326
+ }
1327
+ const headings = document.querySelectorAll(WORKSPACE_ROWS_HEADER)
1328
+ if (headings.length > 0) {
1329
+ const every = []
1330
+ for (const row of rows) {
1331
+ const key = rowKeyOf(row)
1332
+ if (typeof key === 'string' && key.startsWith('session:')) every.push(key.slice('session:'.length))
1333
+ }
1334
+ // In the heading the label is followed by the search slot; inserting before
1335
+ // it keeps the box beside the words instead of inside the action cluster.
1336
+ // The heading row is: label, search slot, options, add. The box goes after
1337
+ // the label, before the first action it can find.
1338
+ placeGroupBox(headings[0], ALL_BUTTON, t('selectAllWorkspaces'), every,
1339
+ '[class*="_searchSlot"], [class*="_headerActions"]')
1340
+ }
1341
+ for (const row of rows) {
1342
+ const key = rowKeyOf(row)
1343
+ if (typeof key !== 'string' || !key.startsWith('workspace:')) continue
1344
+ // The workspace row is: folder, chevron, label block, then the actions. The
1345
+ // actions carry `margin-left:auto`, so anything appended after them lands at
1346
+ // the far edge; inserting before them keeps the box beside the name.
1347
+ placeGroupBox(row, GROUP_BUTTON, t('selectAllGroup'), sessionsUnderWorkspace(row),
1348
+ '[class*="_rowActions"]')
1349
+ }
1350
+ }
1351
+
1087
1352
  function decorateRows() {
1088
1353
  if (typeof document === 'undefined') return
1089
1354
  const rows = document.querySelectorAll('[role="treeitem"]')
@@ -1115,6 +1380,7 @@ window.__ModuleLoader__.load({
1115
1380
  }
1116
1381
  row.classList.toggle('dsdel-row-pending', state.pending.has(id))
1117
1382
  })
1383
+ decorateSelectAll(rows)
1118
1384
  if (!state.selecting) {
1119
1385
  document.querySelectorAll('.dsdel-check').forEach((el) => el.remove())
1120
1386
  }
@@ -1124,16 +1390,32 @@ window.__ModuleLoader__.load({
1124
1390
  * inside the transcript produces characterData records forever; scheduling a
1125
1391
  * full row scan for those would burn a frame's budget on every token.
1126
1392
  */
1393
+ /** True for the nodes this plugin itself inserts into the sidebar. */
1394
+ function isOwnNode(node) {
1395
+ if (node === null || node === undefined || typeof node.getAttribute !== 'function') return false
1396
+ return node.getAttribute('data-dsh-delete-session') !== null
1397
+ }
1398
+
1399
+ function allOwnNodes(list) {
1400
+ if (list === null || list === undefined || list.length === 0) return true
1401
+ for (const node of list) if (!isOwnNode(node)) return false
1402
+ return true
1403
+ }
1404
+
1127
1405
  function onRowMutations(records) {
1128
1406
  if (records === undefined || records === null) return scheduleDecorate()
1129
1407
  for (const record of records) {
1130
1408
  const added = record === null || record === undefined ? null : record.addedNodes
1131
1409
  const removed = record === null || record === undefined ? null : record.removedNodes
1132
- if ((added !== null && added !== undefined && added.length > 0)
1133
- || (removed !== null && removed !== undefined && removed.length > 0)) {
1134
- scheduleDecorate()
1135
- return
1136
- }
1410
+ const hasAdded = added !== null && added !== undefined && added.length > 0
1411
+ const hasRemoved = removed !== null && removed !== undefined && removed.length > 0
1412
+ if (!hasAdded && !hasRemoved) continue
1413
+ // Its own boxes and spacers are not a reason to scan again. Counting
1414
+ // them made every pass schedule the next one: a loop that kept moving
1415
+ // the box out from under the cursor.
1416
+ if (allOwnNodes(added) && allOwnNodes(removed)) continue
1417
+ scheduleDecorate()
1418
+ return
1137
1419
  }
1138
1420
  }
1139
1421
 
@@ -1262,7 +1544,12 @@ window.__ModuleLoader__.load({
1262
1544
 
1263
1545
  function onSelectClickCapture(e) {
1264
1546
  if (!state.selecting) return
1265
- const row = e.target && e.target.closest ? e.target.closest('[role="treeitem"]') : null
1547
+ const target = e.target && typeof e.target.closest === 'function' ? e.target : null
1548
+ // Anything this plugin drew handles its own click. Its document listener
1549
+ // runs first (capture), so without this guard a click on a select-all box
1550
+ // inside a workspace treeitem is swallowed as if the row itself was clicked.
1551
+ if (target !== null && target.closest('[data-dsh-delete-session]') !== null) return
1552
+ const row = target === null ? null : target.closest('[role="treeitem"]')
1266
1553
  if (!row) return
1267
1554
  const id = sessionIdFromRow(row)
1268
1555
  if (!id) return
@@ -1333,6 +1620,12 @@ window.__ModuleLoader__.load({
1333
1620
  document.removeEventListener('keydown', onSelectKeydown, true)
1334
1621
  if (rowObserver) { rowObserver.disconnect(); rowObserver = null }
1335
1622
  document.querySelectorAll('.dsdel-check').forEach((el) => el.remove())
1623
+ // Take the select-all boxes and their spacer with the mode, now rather than
1624
+ // on the next decorate pass: the spacer grows, so a frame of it left behind
1625
+ // would visibly shove the row's right-hand cluster to the left.
1626
+ for (const cls of [GROUP_BUTTON, ALL_BUTTON, SPACER]) {
1627
+ document.querySelectorAll('.' + cls).forEach((el) => el.remove())
1628
+ }
1336
1629
  publish()
1337
1630
  }
1338
1631
 
@@ -21,6 +21,7 @@
21
21
  //
22
22
  // node --test "test/*.test.js"
23
23
  import assert from 'node:assert/strict'
24
+ import { readFile } from 'node:fs/promises'
24
25
  import { test } from 'node:test'
25
26
 
26
27
  // --- a DOM small enough to read, complete enough to run the plugin ----------
@@ -103,6 +104,15 @@ class StubElement {
103
104
  }
104
105
 
105
106
  insertBefore(child, reference) {
107
+ // A real DOM MOVES a node it already contains; it never keeps two copies.
108
+ // The plugin repositions its spacer and its select-all box on every decorate
109
+ // pass, so a stub that appended instead of moved doubled them: removing one
110
+ // copy left the other behind and made the cleanup look broken.
111
+ const previous = child.parentElement
112
+ if (previous !== null) {
113
+ const at = previous.children.indexOf(child)
114
+ if (at !== -1) previous.children.splice(at, 1)
115
+ }
106
116
  child.parentElement = this
107
117
  const index = reference === null || reference === undefined ? this.children.length : this.children.indexOf(reference)
108
118
  if (index === -1) this.children.push(child)
@@ -215,6 +225,14 @@ const SESSION_B = { id: 'session-bbbb1111-2222-4333-8444-555555555555', title: '
215
225
 
216
226
  let bundleFactory = null
217
227
 
228
+ // Every `loadPlugin()` swaps `globalThis.document`, but the plugin instances of
229
+ // earlier tests are still alive and their queued rAF callbacks call
230
+ // `document.querySelectorAll(...)` on whatever document is installed WHEN THEY
231
+ // FIRE. A pass that lands after the swap decorates the next test's DOM, which
232
+ // is what made three tests flaky. Each harness registers its queue here so the
233
+ // next one can drop the leftovers.
234
+ const rafQueues = []
235
+
218
236
  /**
219
237
  * The bundle registers through `window.__ModuleLoader__` once per process and ESM
220
238
  * caching means a second `import()` never re-runs it. Caching the factory is also
@@ -297,8 +315,11 @@ async function loadPlugin(options = {}) {
297
315
  // synchronous stub would leave `decorateRaf` permanently truthy and silently
298
316
  // swallow every later pass. That is a harness artefact, and it would hide the
299
317
  // very regression this file exists to catch.
318
+ // Drop anything an earlier instance queued: it would run against THIS dom.
319
+ for (const stale of rafQueues) stale.clear()
300
320
  let rafId = 0
301
321
  const rafQueue = new Map()
322
+ rafQueues.push(rafQueue)
302
323
  globalThis.requestAnimationFrame = (fn) => {
303
324
  const id = ++rafId
304
325
  rafQueue.set(id, fn)
@@ -572,7 +593,14 @@ const clickBar = (node) => node.props.onClick({ stopPropagation() {} })
572
593
  const tick = () => new Promise((resolve) => setTimeout(resolve, 0))
573
594
 
574
595
  /** Let the queued rAF decorate passes drain. */
575
- const flush = async () => { await tick() }
596
+ const flush = async () => { await tick() }
597
+
598
+ /**
599
+ * Drain until nothing is left. `flush()` is one tick, and a decorate pass can
600
+ * queue another callback while it runs; a test that snapshots a counter right
601
+ * after a single flush occasionally catches a straggler.
602
+ */
603
+ const settle = async () => { for (let i = 0; i < 20; i += 1) await flush() }
576
604
 
577
605
  /**
578
606
  * Fire the observers multi-select installed. Outside the mode the plugin installs
@@ -2884,3 +2912,670 @@ test('the drop label carries the dragged conversation title', async () => {
2884
2912
  const text = JSON.stringify(bar(harness).props.children)
2885
2913
  assert.match(text, /BiliLearn-AI 仓库/, 'the title reaches the sentence')
2886
2914
  })
2915
+ test('a workspace header offers a select-all box', async () => {
2916
+ const harness = await loadPlugin()
2917
+ const section = harness.document.createElement('div')
2918
+ section.setAttribute('role', 'group')
2919
+
2920
+ const header = harness.document.createElement('div')
2921
+ header.setAttribute('role', 'treeitem')
2922
+ header.setAttribute('data-row-key', 'workspace:ws-a')
2923
+ section.appendChild(header)
2924
+
2925
+ mountRow(harness, SESSION_A, section)
2926
+ mountRow(harness, SESSION_B, section)
2927
+ harness.document.body.appendChild(section)
2928
+
2929
+ await enterMulti(harness)
2930
+ observerPass(harness)
2931
+ await flush()
2932
+
2933
+ const box = header.querySelector('.dsdel-select-all')
2934
+ assert.ok(box, 'the header carries one')
2935
+ assert.equal(box.getAttribute('role'), 'checkbox')
2936
+ assert.equal(box.getAttribute('aria-checked'), 'false', 'nothing picked yet')
2937
+ })
2938
+
2939
+ test('the workspace box selects only its own sessions', async () => {
2940
+ const harness = await loadPlugin()
2941
+ const sectionA = harness.document.createElement('div')
2942
+ sectionA.setAttribute('role', 'group')
2943
+ const headA = harness.document.createElement('div')
2944
+ headA.setAttribute('role', 'treeitem')
2945
+ headA.setAttribute('data-row-key', 'workspace:ws-a')
2946
+ sectionA.appendChild(headA)
2947
+ mountRow(harness, SESSION_A, sectionA)
2948
+ harness.document.body.appendChild(sectionA)
2949
+
2950
+ const sectionB = harness.document.createElement('div')
2951
+ sectionB.setAttribute('role', 'group')
2952
+ const headB = harness.document.createElement('div')
2953
+ headB.setAttribute('role', 'treeitem')
2954
+ headB.setAttribute('data-row-key', 'workspace:ws-b')
2955
+ sectionB.appendChild(headB)
2956
+ mountRow(harness, SESSION_B, sectionB)
2957
+ harness.document.body.appendChild(sectionB)
2958
+
2959
+ await enterMulti(harness)
2960
+ observerPass(harness)
2961
+ await flush()
2962
+
2963
+ headA.querySelector('.dsdel-select-all').fire('click')
2964
+ await flush()
2965
+
2966
+ assert.equal(headA.querySelector('.dsdel-select-all').getAttribute('aria-checked'), 'true', 'A turned on')
2967
+ const boxB = headB.querySelector('.dsdel-select-all')
2968
+ assert.equal(boxB.getAttribute('aria-checked'), 'false', 'B untouched')
2969
+ })
2970
+
2971
+ test('a second press clears the workspace again', async () => {
2972
+ const harness = await loadPlugin()
2973
+ const section = harness.document.createElement('div')
2974
+ section.setAttribute('role', 'group')
2975
+ const header = harness.document.createElement('div')
2976
+ header.setAttribute('role', 'treeitem')
2977
+ header.setAttribute('data-row-key', 'workspace:ws-a')
2978
+ section.appendChild(header)
2979
+ mountRow(harness, SESSION_A, section)
2980
+ harness.document.body.appendChild(section)
2981
+
2982
+ await enterMulti(harness)
2983
+ observerPass(harness)
2984
+ await flush()
2985
+
2986
+ const box = header.querySelector('.dsdel-select-all')
2987
+ box.fire('click')
2988
+ await flush()
2989
+ assert.equal(box.getAttribute('aria-checked'), 'true')
2990
+
2991
+ box.fire('click')
2992
+ await flush()
2993
+ assert.equal(box.getAttribute('aria-checked'), 'false')
2994
+ })
2995
+
2996
+ test('the box reports a partly picked workspace as mixed', async () => {
2997
+ const harness = await loadPlugin()
2998
+ const section = harness.document.createElement('div')
2999
+ section.setAttribute('role', 'group')
3000
+ const header = harness.document.createElement('div')
3001
+ header.setAttribute('role', 'treeitem')
3002
+ header.setAttribute('data-row-key', 'workspace:ws-a')
3003
+ section.appendChild(header)
3004
+ const rowA = mountRow(harness, SESSION_A, section)
3005
+ mountRow(harness, SESSION_B, section)
3006
+ harness.document.body.appendChild(section)
3007
+
3008
+ await enterMulti(harness)
3009
+ observerPass(harness)
3010
+ await flush()
3011
+
3012
+ clickRowIn(harness, rowA)
3013
+ observerPass(harness)
3014
+ await flush()
3015
+
3016
+ assert.equal(header.querySelector('.dsdel-select-all').getAttribute('aria-checked'), 'mixed')
3017
+ })
3018
+
3019
+ test('the heading row selects every workspace at once', async () => {
3020
+ const harness = await loadPlugin()
3021
+ const heading = harness.document.createElement('div')
3022
+ heading.setAttribute('data-sidebar-workspace-header', '')
3023
+ harness.document.body.appendChild(heading)
3024
+
3025
+ const sectionA = harness.document.createElement('div')
3026
+ sectionA.setAttribute('role', 'group')
3027
+ const headA = harness.document.createElement('div')
3028
+ headA.setAttribute('role', 'treeitem')
3029
+ headA.setAttribute('data-row-key', 'workspace:ws-a')
3030
+ sectionA.appendChild(headA)
3031
+ mountRow(harness, SESSION_A, sectionA)
3032
+ harness.document.body.appendChild(sectionA)
3033
+
3034
+ const sectionB = harness.document.createElement('div')
3035
+ sectionB.setAttribute('role', 'group')
3036
+ const headB = harness.document.createElement('div')
3037
+ headB.setAttribute('role', 'treeitem')
3038
+ headB.setAttribute('data-row-key', 'workspace:ws-b')
3039
+ sectionB.appendChild(headB)
3040
+ mountRow(harness, SESSION_B, sectionB)
3041
+ harness.document.body.appendChild(sectionB)
3042
+
3043
+ await enterMulti(harness)
3044
+ observerPass(harness)
3045
+ await flush()
3046
+
3047
+ const all = heading.querySelector('.dsdel-select-all-workspaces')
3048
+ assert.ok(all, 'the heading carries the global box')
3049
+ all.fire('click')
3050
+ await flush()
3051
+
3052
+ assert.equal(all.getAttribute('aria-checked'), 'true', 'everything picked')
3053
+ assert.equal(headA.querySelector('.dsdel-select-all').getAttribute('aria-checked'), 'true')
3054
+ assert.equal(headB.querySelector('.dsdel-select-all').getAttribute('aria-checked'), 'true')
3055
+ })
3056
+
3057
+ test('both boxes go away when the mode ends', async () => {
3058
+ const harness = await loadPlugin()
3059
+ const heading = harness.document.createElement('div')
3060
+ heading.setAttribute('data-sidebar-workspace-header', '')
3061
+ harness.document.body.appendChild(heading)
3062
+
3063
+ const section = harness.document.createElement('div')
3064
+ section.setAttribute('role', 'group')
3065
+ const header = harness.document.createElement('div')
3066
+ header.setAttribute('role', 'treeitem')
3067
+ header.setAttribute('data-row-key', 'workspace:ws-a')
3068
+ section.appendChild(header)
3069
+ mountRow(harness, SESSION_A, section)
3070
+ harness.document.body.appendChild(section)
3071
+
3072
+ await enterMulti(harness)
3073
+ observerPass(harness)
3074
+ await flush()
3075
+ assert.ok(header.querySelector('.dsdel-select-all'), 'present during the mode')
3076
+ assert.ok(heading.querySelector('.dsdel-select-all-workspaces'))
3077
+
3078
+ harness.document.dispatchToDocument('keydown', { key: 'Escape', stopPropagation() {} })
3079
+ observerPass(harness)
3080
+ await flush()
3081
+
3082
+ assert.equal(header.querySelector('.dsdel-select-all'), null, 'removed with the mode')
3083
+ assert.equal(heading.querySelector('.dsdel-select-all-workspaces'), null)
3084
+ })
3085
+
3086
+ test('the select-all boxes do not lean on the page token scope', async () => {
3087
+ const harness = await loadPlugin()
3088
+ const css = String(harness.document.head.querySelector('[data-dsh-delete-session="1"]')._text ?? '')
3089
+
3090
+ // The boxes render inside the SIDEBAR. The `--dsdel-*` tokens are declared on
3091
+ // `.dsdel-page`, `.dsdel-modal` and `.dsdel-bar` only, so any rule outside those
3092
+ // scopes that reads them gets an invalid value and loses the whole declaration.
3093
+ // That is how the first version shipped an invisible button: `border` was
3094
+ // dropped, leaving no box and nothing to click.
3095
+ const rules = [...css.matchAll(/(?:^|\})\s*\.dsdel-select-all[^{]*\{([^}]*)\}/g)]
3096
+ assert.ok(rules.length > 0, 'the rules are in the stylesheet')
3097
+ for (const match of rules) {
3098
+ assert.equal(match[1].includes('--dsdel-'), false,
3099
+ 'a sidebar rule must not read the page tokens: ' + match[0].slice(0, 60))
3100
+ }
3101
+
3102
+ // Every host alias carries a literal fallback, so the box still draws when the
3103
+ // host renames its palette.
3104
+ assert.match(css, /\.dsdel-select-all[^}]*var\(--dsw-alias-border-l2,[^)]*\)/, 'border has a fallback')
3105
+ assert.match(css, /\.dsdel-select-all[^}]*var\(--dsw-alias-brand-primary,[^)]*\)/, 'brand has a fallback')
3106
+ })
3107
+
3108
+ test('a box always keeps a visible 15px square', async () => {
3109
+ const harness = await loadPlugin()
3110
+ const css = String(harness.document.head.querySelector('[data-dsh-delete-session="1"]')._text ?? '')
3111
+
3112
+ // A flex child with no width collapses to its content, and the empty state has
3113
+ // no content: `width` plus `min-width` plus content-box sizing is what makes the
3114
+ // square exist before anything is ticked.
3115
+ assert.match(css, /\.dsdel-select-all[^}]*width:15px/, 'a fixed width')
3116
+ assert.match(css, /\.dsdel-select-all[^}]*height:15px/, 'and a fixed height')
3117
+ assert.match(css, /\.dsdel-select-all[^}]*min-width:15px/, 'that flex cannot shrink away')
3118
+ assert.match(css, /\.dsdel-select-all[^}]*box-sizing:border-box/, 'with the border inside it')
3119
+ })
3120
+
3121
+ test('the workspace box sits beside the name, not at the row edge', async () => {
3122
+ const harness = await loadPlugin()
3123
+ const section = harness.document.createElement('div')
3124
+ section.setAttribute('role', 'group')
3125
+
3126
+ const header = harness.document.createElement('div')
3127
+ header.setAttribute('role', 'treeitem')
3128
+ header.setAttribute('data-row-key', 'workspace:ws-a')
3129
+
3130
+ // The host row: label block, then the action cluster (which carries margin-left:auto).
3131
+ const label = harness.document.createElement('span')
3132
+ label.className = 'YDXeBa_projectText'
3133
+ header.appendChild(label)
3134
+ const actions = harness.document.createElement('span')
3135
+ actions.className = 'YDXeBa_rowActions'
3136
+ header.appendChild(actions)
3137
+
3138
+ section.appendChild(header)
3139
+ mountRow(harness, SESSION_A, section)
3140
+ harness.document.body.appendChild(section)
3141
+
3142
+ await enterMulti(harness)
3143
+ observerPass(harness)
3144
+ await flush()
3145
+
3146
+ const box = header.querySelector('.dsdel-select-all')
3147
+ assert.ok(box, 'the box exists')
3148
+
3149
+ // Appending put it after the action cluster, whose auto margin pushes it into the
3150
+ // far right of the row — that is the "靠右" the screenshot showed. It has to be
3151
+ // inserted before the actions instead.
3152
+ const index = header.children.indexOf(box)
3153
+ const actionsIndex = header.children.indexOf(actions)
3154
+ assert.equal(index < actionsIndex, true, 'the box comes before the action cluster')
3155
+ assert.equal(header.children[index - 1].className, 'YDXeBa_projectText', 'and right after the label')
3156
+ })
3157
+
3158
+ test('the global box sits after the heading label, before the search slot', async () => {
3159
+ const harness = await loadPlugin()
3160
+
3161
+ const heading = harness.document.createElement('div')
3162
+ heading.setAttribute('data-sidebar-workspace-header', '')
3163
+
3164
+ const label = harness.document.createElement('span')
3165
+ label.className = 'bhn1Oq_sectionLabel'
3166
+ heading.appendChild(label)
3167
+ const search = harness.document.createElement('div')
3168
+ search.className = 'bhn1Oq_searchSlot'
3169
+ heading.appendChild(search)
3170
+
3171
+ harness.document.body.appendChild(heading)
3172
+
3173
+ const section = harness.document.createElement('div')
3174
+ section.setAttribute('role', 'group')
3175
+ const header = harness.document.createElement('div')
3176
+ header.setAttribute('role', 'treeitem')
3177
+ header.setAttribute('data-row-key', 'workspace:ws-a')
3178
+ section.appendChild(header)
3179
+ mountRow(harness, SESSION_A, section)
3180
+ harness.document.body.appendChild(section)
3181
+
3182
+ await enterMulti(harness)
3183
+ observerPass(harness)
3184
+ await flush()
3185
+
3186
+ const box = heading.querySelector('.dsdel-select-all-workspaces')
3187
+ assert.ok(box, 'the global box exists')
3188
+ const index = heading.children.indexOf(box)
3189
+ assert.equal(index < heading.children.indexOf(search), true, 'before the search slot')
3190
+ assert.equal(heading.children[index - 1].className, 'bhn1Oq_sectionLabel', 'and after the label')
3191
+ })
3192
+
3193
+ test('a box left at the wrong edge is moved on the next pass', async () => {
3194
+ const harness = await loadPlugin()
3195
+ const section = harness.document.createElement('div')
3196
+ section.setAttribute('role', 'group')
3197
+
3198
+ const header = harness.document.createElement('div')
3199
+ header.setAttribute('role', 'treeitem')
3200
+ header.setAttribute('data-row-key', 'workspace:ws-a')
3201
+
3202
+ const label = harness.document.createElement('span')
3203
+ label.className = 'wnFoaW_projectText'
3204
+ header.appendChild(label)
3205
+ const actions = harness.document.createElement('span')
3206
+ actions.className = 'wnFoaW_rowActions'
3207
+ header.appendChild(actions)
3208
+
3209
+ // An earlier build left its box AFTER the actions: the far edge.
3210
+ const stale = harness.document.createElement('button')
3211
+ stale.className = 'dsdel-select-all'
3212
+ header.appendChild(stale)
3213
+
3214
+ section.appendChild(header)
3215
+ mountRow(harness, SESSION_A, section)
3216
+ harness.document.body.appendChild(section)
3217
+
3218
+ await enterMulti(harness)
3219
+ observerPass(harness)
3220
+ await flush()
3221
+
3222
+ // The insert used to live inside the "created" branch, so an existing box was
3223
+ // never repositioned: the heading box moved and the workspace box stayed put.
3224
+ const index = header.children.indexOf(stale)
3225
+ assert.equal(index < header.children.indexOf(actions), true, 'moved before the actions')
3226
+ assert.equal(header.children[index - 1].className, 'wnFoaW_projectText', 'and beside the label')
3227
+ })
3228
+
3229
+ test('the workspace name stops absorbing the row while the mode runs', async () => {
3230
+ const harness = await loadPlugin()
3231
+ const css = String(harness.document.head.querySelector('[data-dsh-delete-session="1"]')._text ?? '')
3232
+
3233
+ // `.projectText` carries `flex:1`, so it fills whatever the actions do not take.
3234
+ // A box inserted after it therefore lands at the row's far edge even though it
3235
+ // is early in the child list — that is why the workspace box stayed right while
3236
+ // the header box (whose label is not flexed) moved. The rule only applies while
3237
+ // the mode runs, so the host keeps its normal layout otherwise.
3238
+ assert.match(css, /body\.dsdel-selecting \[class\*="_projectText"\]\{[^}]*flex:0 1 auto/,
3239
+ 'the name sizes to its text during the mode')
3240
+ assert.match(css, /body\.dsdel-selecting \[class\*="_projectText"\]\{[^}]*min-width:0/,
3241
+ 'and can still truncate a long name')
3242
+ })
3243
+
3244
+ test('a spacer keeps the right-hand cluster in place', async () => {
3245
+ const harness = await loadPlugin()
3246
+ const section = harness.document.createElement('div')
3247
+ section.setAttribute('role', 'group')
3248
+
3249
+ const header = harness.document.createElement('div')
3250
+ header.setAttribute('role', 'treeitem')
3251
+ header.setAttribute('data-row-key', 'workspace:ws-a')
3252
+
3253
+ const label = harness.document.createElement('span')
3254
+ label.className = 'wnFoaW_projectText'
3255
+ header.appendChild(label)
3256
+ // The cluster that must NOT move: count, menu, new-session.
3257
+ const actions = harness.document.createElement('span')
3258
+ actions.className = 'wnFoaW_rowActions'
3259
+ header.appendChild(actions)
3260
+
3261
+ section.appendChild(header)
3262
+ mountRow(harness, SESSION_A, section)
3263
+ harness.document.body.appendChild(section)
3264
+
3265
+ await enterMulti(harness)
3266
+ observerPass(harness)
3267
+ await flush()
3268
+
3269
+ // Order has to be: label, box, spacer, actions. With the spacer growing, the
3270
+ // name keeps its natural width and the cluster stays at the row's end; without
3271
+ // it, every flex child simply packs left and the count/menu/new buttons slid
3272
+ // over with the box.
3273
+ const kids = header.children
3274
+ const box = header.querySelector('.dsdel-select-all')
3275
+ const spacer = header.querySelector('.dsdel-flex-spacer')
3276
+ assert.ok(box, 'the box exists')
3277
+ assert.ok(spacer, 'the spacer exists')
3278
+
3279
+ assert.equal(kids.indexOf(box) < kids.indexOf(spacer), true, 'box before spacer')
3280
+ assert.equal(kids.indexOf(spacer) < kids.indexOf(actions), true, 'spacer before the cluster')
3281
+ assert.equal(kids.indexOf(label) < kids.indexOf(box), true, 'label first')
3282
+ })
3283
+
3284
+ test('the spacer is removed with the mode', async () => {
3285
+ const harness = await loadPlugin()
3286
+ const section = harness.document.createElement('div')
3287
+ section.setAttribute('role', 'group')
3288
+ const header = harness.document.createElement('div')
3289
+ header.setAttribute('role', 'treeitem')
3290
+ header.setAttribute('data-row-key', 'workspace:ws-a')
3291
+ const label = harness.document.createElement('span')
3292
+ label.className = 'wnFoaW_projectText'
3293
+ header.appendChild(label)
3294
+ const actions = harness.document.createElement('span')
3295
+ actions.className = 'wnFoaW_rowActions'
3296
+ header.appendChild(actions)
3297
+ section.appendChild(header)
3298
+ mountRow(harness, SESSION_A, section)
3299
+ harness.document.body.appendChild(section)
3300
+
3301
+ await enterMulti(harness)
3302
+ observerPass(harness)
3303
+ await flush()
3304
+ assert.ok(header.querySelector('.dsdel-flex-spacer'), 'spacer present during the mode')
3305
+
3306
+ // The bar's Cancel is the mode's own exit route. Escape would also reach
3307
+ // handlers left behind by earlier tests: the stub never unregisters one.
3308
+ clickBar(barCancel(harness))
3309
+ observerPass(harness)
3310
+ await flush()
3311
+ assert.equal(header.querySelector('.dsdel-flex-spacer'), null, 'gone with the mode')
3312
+ assert.equal(header.querySelector('.dsdel-select-all'), null, 'and so is the box')
3313
+ })
3314
+
3315
+ test('PROBE exit removes spacer', async () => {
3316
+ const harness = await loadPlugin()
3317
+ const section = harness.document.createElement('div')
3318
+ section.setAttribute('role', 'group')
3319
+ const header = harness.document.createElement('div')
3320
+ header.setAttribute('role', 'treeitem')
3321
+ header.setAttribute('data-row-key', 'workspace:ws-a')
3322
+ const actions = harness.document.createElement('span')
3323
+ actions.className = 'wnFoaW_rowActions'
3324
+ header.appendChild(actions)
3325
+ section.appendChild(header)
3326
+ mountRow(harness, SESSION_A, section)
3327
+ harness.document.body.appendChild(section)
3328
+
3329
+ await enterMulti(harness)
3330
+ observerPass(harness)
3331
+ await flush()
3332
+
3333
+ const before = harness.document.querySelectorAll('.dsdel-flex-spacer').length
3334
+ console.log('PROBE 装饰后 spacer 数:', before)
3335
+ for (const el of harness.document.querySelectorAll('.dsdel-flex-spacer')) {
3336
+ console.log('PROBE spacer parent:', el.parentElement && el.parentElement.getAttribute('data-row-key'), 'idx:', el.parentElement ? el.parentElement.children.indexOf(el) : -1)
3337
+ }
3338
+ const cancel = barCancel(harness)
3339
+ console.log('PROBE cancel 节点:', cancel && cancel.props && cancel.props.className)
3340
+ clickBar(cancel)
3341
+ await flush()
3342
+ console.log('PROBE 退出后 spacer 数:', harness.document.querySelectorAll('.dsdel-flex-spacer').length)
3343
+ assert.ok(true)
3344
+ })
3345
+
3346
+ test('the spacer is the growing child, so the cluster keeps its seat', async () => {
3347
+ const harness = await loadPlugin()
3348
+ const css = String(harness.document.head.querySelector('[data-dsh-delete-session="1"]')._text ?? '')
3349
+
3350
+ // Without a growing child the flex row simply packs left, which drags the count
3351
+ // and the action buttons along with the box. The spacer is what holds them at
3352
+ // the row's end while the box sits beside the name.
3353
+ assert.match(css, /\.dsdel-flex-spacer\{[^}]*flex:1/, 'the spacer grows')
3354
+ assert.match(css, /\.dsdel-flex-spacer\{[^}]*min-width:0/, 'and can collapse when space is tight')
3355
+ assert.match(css, /\.dsdel-select-all[^}]*flex:0 0 auto/, 'the box itself does not grow')
3356
+ })
3357
+
3358
+ test('a document click on a plugin-drawn element leaves the session alone', async () => {
3359
+ const harness = await loadPlugin()
3360
+ const row = mountRow(harness, SESSION_A)
3361
+ await enterMulti(harness)
3362
+ observerPass(harness)
3363
+ await flush()
3364
+ assert.equal(harness.document.body.className.includes('dsdel-selecting'), true)
3365
+
3366
+ // The document capture listener runs before any element handler. It must ignore
3367
+ // elements this plugin drew — a box inside a workspace row is the everyday case,
3368
+ // and inside a session row it would otherwise toggle that session.
3369
+ const box = harness.document.createElement('button')
3370
+ box.className = 'dsdel-select-all'
3371
+ box.setAttribute('data-dsh-delete-session', 'select-all')
3372
+ row.appendChild(box)
3373
+
3374
+ clickRowIn(harness, box)
3375
+ observerPass(harness)
3376
+ await flush()
3377
+
3378
+ const check = row.querySelector('.dsdel-check')
3379
+ assert.equal(check.classList.contains('dsdel-check-on'), false, 'no session was toggled')
3380
+ })
3381
+
3382
+ test('the row handler still works for a real session row', async () => {
3383
+ const harness = await loadPlugin()
3384
+ const row = mountRow(harness, SESSION_A)
3385
+ await enterMulti(harness)
3386
+ observerPass(harness)
3387
+ await flush()
3388
+
3389
+ clickRowIn(harness, row)
3390
+ await flush()
3391
+
3392
+ const check = row.querySelector('.dsdel-check')
3393
+ assert.equal(check.classList.contains('dsdel-check-on'), true, 'a plain row still toggles')
3394
+ })
3395
+
3396
+ test('a decorate pass with nothing to move keeps the box where it is', async () => {
3397
+ const harness = await loadPlugin()
3398
+ const section = harness.document.createElement('div')
3399
+ section.setAttribute('role', 'group')
3400
+ const header = harness.document.createElement('div')
3401
+ header.setAttribute('role', 'treeitem')
3402
+ header.setAttribute('data-row-key', 'workspace:ws-a')
3403
+ const label = harness.document.createElement('span')
3404
+ label.className = 'wnFoaW_projectText'
3405
+ header.appendChild(label)
3406
+ const actions = harness.document.createElement('span')
3407
+ actions.className = 'wnFoaW_rowActions'
3408
+ header.appendChild(actions)
3409
+ section.appendChild(header)
3410
+ mountRow(harness, SESSION_A, section)
3411
+ harness.document.body.appendChild(section)
3412
+
3413
+ await enterMulti(harness)
3414
+ observerPass(harness)
3415
+ await flush()
3416
+
3417
+ // Every insertBefore is a mutation, and the list observer counted it as a
3418
+ // reason to scan again: each pass scheduled the next one, forever, and the box
3419
+ // was detached and re-attached under the pointer. Nothing may move here — the
3420
+ // box and its spacer are already in the right place.
3421
+ const box = header.querySelector('.dsdel-select-all')
3422
+ const spacer = header.querySelector('.dsdel-flex-spacer')
3423
+ const index = header.children.indexOf(box)
3424
+
3425
+ // Re-inserting a node where it already sits leaves its index unchanged, so the
3426
+ // index alone cannot prove the pass was quiet. Count the calls instead: a real
3427
+ // insertBefore produces a MutationRecord, and the observer used to feed on them.
3428
+ const realInsert = header.insertBefore.bind(header)
3429
+ let inserts = 0
3430
+ header.insertBefore = (child, ref) => { inserts += 1; return realInsert(child, ref) }
3431
+
3432
+ observerPass(harness)
3433
+ observerPass(harness)
3434
+ await flush()
3435
+
3436
+ assert.equal(inserts, 0, 'a settled row is left untouched')
3437
+
3438
+ assert.equal(header.children.indexOf(box), index, 'the box did not move')
3439
+ assert.equal(header.children.indexOf(spacer), index + 1, 'nor did the spacer')
3440
+ assert.equal(header.children.filter((el) => el === box).length, 1, 'and there is only one')
3441
+ })
3442
+
3443
+ test('a mutation naming only our own nodes schedules no pass', async () => {
3444
+ const harness = await loadPlugin()
3445
+
3446
+ // Drive the frame queue by hand: a timer-based flush made this test flaky,
3447
+ // because a pass can queue another callback while it runs.
3448
+ //
3449
+ // Note the drain: emptying the queue without running its callbacks leaves the
3450
+ // plugin's `decorateRaf` handle truthy, and every later `scheduleDecorate`
3451
+ // silently returns. That is a harness trap, not a product bug.
3452
+ const queued = []
3453
+ const realRaf = globalThis.requestAnimationFrame
3454
+ const realCancel = globalThis.cancelAnimationFrame
3455
+ globalThis.requestAnimationFrame = (fn) => { queued.push(fn); return queued.length }
3456
+ globalThis.cancelAnimationFrame = () => {}
3457
+ const drain = () => { let guard = 0; while (queued.length > 0 && guard < 50) { guard += 1; queued.shift()() } }
3458
+
3459
+ try {
3460
+ await enterMulti(harness)
3461
+ drain()
3462
+
3463
+ // A row that arrives after the last pass carries no checkbox, so whether a
3464
+ // pass runs is readable straight off the DOM.
3465
+ const section = harness.document.createElement('div')
3466
+ section.setAttribute('role', 'group')
3467
+ const hostRow = harness.document.createElement('div')
3468
+ hostRow.setAttribute('role', 'treeitem')
3469
+ hostRow.setAttribute('data-row-key', 'session:session-cccc1111-2222-4333-8444-555555555555')
3470
+ section.appendChild(hostRow)
3471
+ harness.document.body.appendChild(section)
3472
+ assert.equal(hostRow.querySelector('.dsdel-check'), null, 'the row is undecorated')
3473
+
3474
+ // Decorate inserts checkboxes, and the list observer reports them right back.
3475
+ // Every such record used to schedule another pass, so the loop never settled:
3476
+ // the box was re-inserted under the pointer and a click often missed.
3477
+ const own = harness.document.createElement('span')
3478
+ own.setAttribute('data-dsh-delete-session', 'check')
3479
+ harness.observers[0].callback([{ addedNodes: [own], removedNodes: [] }])
3480
+ assert.equal(queued.length, 0, 'our own node schedules nothing')
3481
+
3482
+ // A host change must still get through.
3483
+ harness.observers[0].callback([{ addedNodes: [hostRow], removedNodes: [] }])
3484
+ assert.equal(queued.length, 1, 'a real host row schedules one pass')
3485
+ drain()
3486
+ assert.ok(hostRow.querySelector('.dsdel-check'), 'and that pass decorates it')
3487
+ } finally {
3488
+ globalThis.requestAnimationFrame = realRaf
3489
+ globalThis.cancelAnimationFrame = realCancel
3490
+ }
3491
+ })
3492
+
3493
+ test('the plugin never calls array methods on a live child list', async () => {
3494
+ const source = await readFile(new URL('../src/client.js', import.meta.url), 'utf8')
3495
+
3496
+ // In a browser `element.children` is an HTMLCollection: it has `length` and
3497
+ // indexing, and none of the Array methods. The test stub uses a plain array, so
3498
+ // `children.indexOf(...)` passed here and threw a TypeError in the real host —
3499
+ // the decorate pass died before inserting anything, and the select-all box never
3500
+ // appeared. Index it by hand (`childIndex`) or spread it first.
3501
+ const offenders = []
3502
+ for (const match of source.matchAll(/\.children\.([A-Za-z]+)\s*\(/g)) {
3503
+ offenders.push(match[0])
3504
+ }
3505
+ assert.deepEqual(offenders, [], 'no Array methods on `children`')
3506
+ })
3507
+
3508
+ test('the workspace box reaches past a wrapping element', async () => {
3509
+ const harness = await loadPlugin()
3510
+ const section = harness.document.createElement('div')
3511
+ section.setAttribute('role', 'group')
3512
+
3513
+ // The real host wraps the workspace row in HoverCard's <span>, so the row's
3514
+ // parentElement is that span, not the section. A subtree query from the span
3515
+ // returns only the workspace row itself and the box ends up with no ids —
3516
+ // `toggleGroup` then returns without doing anything, which is exactly the
3517
+ // "single-workspace select-all does nothing" report.
3518
+ const wrapper = harness.document.createElement('span')
3519
+ wrapper.className = 'HoverCard_root'
3520
+ const header = harness.document.createElement('div')
3521
+ header.setAttribute('role', 'treeitem')
3522
+ header.setAttribute('data-row-key', 'workspace:ws-a')
3523
+ const label = harness.document.createElement('span')
3524
+ label.className = 'wnFoaW_projectText'
3525
+ header.appendChild(label)
3526
+ const actions = harness.document.createElement('span')
3527
+ actions.className = 'wnFoaW_rowActions'
3528
+ header.appendChild(actions)
3529
+ wrapper.appendChild(header)
3530
+ section.appendChild(wrapper)
3531
+
3532
+ mountRow(harness, SESSION_A, section)
3533
+ mountRow(harness, SESSION_B, section)
3534
+ harness.document.body.appendChild(section)
3535
+
3536
+ await enterMulti(harness)
3537
+ observerPass(harness)
3538
+ await flush()
3539
+
3540
+ const box = header.querySelector('.dsdel-select-all')
3541
+ assert.ok(box, 'the box exists')
3542
+ assert.deepEqual(box.__dsdelIds, [SESSION_A.id, SESSION_B.id], 'both sessions were found')
3543
+
3544
+ box.fire('click')
3545
+ await flush()
3546
+ assert.equal(box.getAttribute('aria-checked'), 'true', 'and pressing it selects them')
3547
+ })
3548
+
3549
+ test('a workspace box never reaches into a nested workspace', async () => {
3550
+ const harness = await loadPlugin()
3551
+ const section = harness.document.createElement('div')
3552
+ section.setAttribute('role', 'group')
3553
+
3554
+ const header = harness.document.createElement('div')
3555
+ header.setAttribute('role', 'treeitem')
3556
+ header.setAttribute('data-row-key', 'workspace:outer')
3557
+ const actions = harness.document.createElement('span')
3558
+ actions.className = 'wnFoaW_rowActions'
3559
+ header.appendChild(actions)
3560
+ section.appendChild(header)
3561
+ mountRow(harness, SESSION_A, section)
3562
+
3563
+ // A nested workspace is a `div[role="group"]` holding its own rows.
3564
+ const nested = harness.document.createElement('div')
3565
+ nested.setAttribute('role', 'group')
3566
+ const nestedHeader = harness.document.createElement('div')
3567
+ nestedHeader.setAttribute('role', 'treeitem')
3568
+ nestedHeader.setAttribute('data-row-key', 'workspace:inner')
3569
+ nested.appendChild(nestedHeader)
3570
+ mountRow(harness, SESSION_B, nested)
3571
+ section.appendChild(nested)
3572
+
3573
+ harness.document.body.appendChild(section)
3574
+
3575
+ await enterMulti(harness)
3576
+ observerPass(harness)
3577
+ await flush()
3578
+
3579
+ const box = header.querySelector('.dsdel-select-all')
3580
+ assert.deepEqual(box.__dsdelIds, [SESSION_A.id], 'only the outer group\'s own session')
3581
+ })