dsh-sidebar-fold 0.1.15 → 0.1.17

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/lib/client.js CHANGED
@@ -39,6 +39,11 @@ window.__ModuleLoader__.load({
39
39
  menuRow: 'dshsf-menu-row',
40
40
  menuText: 'dshsf-menu-text',
41
41
  menuIcon: 'dshsf-menu-icon',
42
+ /** Transient highlight on the row being dragged / targeted. */
43
+ rowDrag: 'dshsf-row-drag',
44
+ rowDragOver: 'dshsf-row-drag-over',
45
+ /** The settings-card handle a reorder drag is started from. */
46
+ rowHandle: 'dshsf-row-handle',
42
47
  });
43
48
  /**
44
49
  * Alignment of a panel row's content (icon + label) inside the row.
@@ -64,6 +69,10 @@ window.__ModuleLoader__.load({
64
69
  align: 'data-dshsf-align',
65
70
  /** On the toggle: the folded group holds the panel the user is looking at. */
66
71
  activeInside: 'data-dshsf-active-inside',
72
+ /** On a panel row we have wired for HTML5 drag-and-drop reordering. */
73
+ dnd: 'data-dshsf-dnd',
74
+ /** On a row wrapper carrying the flex `order` we wrote for a persisted rank. */
75
+ order: 'data-dshsf-order',
67
76
  });
68
77
  /** Selector fragments (hash-tolerant). */
69
78
  const SEL = Object.freeze({
@@ -304,6 +313,13 @@ window.__ModuleLoader__.load({
304
313
  'outline-offset:-2px',
305
314
  ]),
306
315
  rule(`.${CLS.menuText}`, ['overflow:hidden', 'text-overflow:ellipsis', 'white-space:nowrap']),
316
+ // Row drag feedback — opacity on the source, a token-tinted outline on the target.
317
+ rule(`.${CLS.rowDrag}`, ['opacity:.45']),
318
+ rule(`.${CLS.rowDragOver}`, ['outline:2px solid var(--dsw-alias-state-business-primary,#4d6bfe)', 'outline-offset:-2px']),
319
+ // The settings card's drag handle: a grab cursor is the only honest affordance
320
+ // (dimming the whole row, as the first cut did, reads as “disabled”).
321
+ rule(`.${CLS.rowHandle}`, ['cursor:grab', '-webkit-user-select:none', 'user-select:none']),
322
+ rule(`.${CLS.rowHandle}:active`, ['cursor:grabbing']),
307
323
  rule(`.${CLS.menuIcon}`, ['flex:none', 'display:block']),
308
324
  ].join('');
309
325
  /**
@@ -324,6 +340,8 @@ window.__ModuleLoader__.load({
324
340
  'settings.defaultFoldedHint': '新窗口在没有本地记录时采用的初始状态',
325
341
  'settings.rows': '入口行',
326
342
  'settings.rowsHint': '每行三档:显示=一直显示;折叠=允许折叠;隐藏到更多=移进「更多」菜单。',
343
+ 'settings.rowDrag': '拖动入口行可排序(「更多」固定末尾)',
344
+ 'settings.rowDragHint': '按住入口行拖到目标位置,顺序会保存到设置。',
327
345
  'settings.rowAlways': '显示',
328
346
  'settings.rowFold': '折叠',
329
347
  'settings.rowMore': '隐藏到更多',
@@ -351,6 +369,8 @@ window.__ModuleLoader__.load({
351
369
  'settings.defaultFoldedHint': 'Initial state for a window with no local record yet',
352
370
  'settings.rows': 'Entries',
353
371
  'settings.rowsHint': 'Three states per row: Show keeps it visible, Fold lets the fold hide it, Hide in More moves it into the “More” menu.',
372
+ 'settings.rowDrag': 'Drag entry rows to reorder (“More” stays last)',
373
+ 'settings.rowDragHint': 'Drag a row onto another to reorder; the order is saved to settings.',
354
374
  'settings.rowAlways': 'Show',
355
375
  'settings.rowFold': 'Fold',
356
376
  'settings.rowMore': 'Hide in More',
@@ -378,6 +398,8 @@ window.__ModuleLoader__.load({
378
398
  'settings.defaultFoldedHint': 'ローカル記録がないウィンドウの初期状態',
379
399
  'settings.rows': '項目',
380
400
  'settings.rowsHint': '行ごとに3段階:表示=常に表示、折りたたみ=折りたたみ可、「その他」へ隠す=「その他」メニューへ移動。',
401
+ 'settings.rowDrag': '項目行をドラッグして並べ替え(「その他」は末尾固定)',
402
+ 'settings.rowDragHint': '行を別の行へドラッグすると並びが変わり、設定に保存されます。',
381
403
  'settings.rowAlways': '表示',
382
404
  'settings.rowFold': '折りたたみ',
383
405
  'settings.rowMore': '「その他」へ隠す',
@@ -405,6 +427,8 @@ window.__ModuleLoader__.load({
405
427
  'settings.defaultFoldedHint': '로컬 기록이 없는 창의 초기 상태',
406
428
  'settings.rows': '항목',
407
429
  'settings.rowsHint': '행마다 3단계: 표시=항상 표시, 접기=접기 허용, 더 보기에 숨기기=“더 보기” 메뉴로 이동.',
430
+ 'settings.rowDrag': '항목 행을 끌어 순서 변경 (“더 보기”는 항상 마지막)',
431
+ 'settings.rowDragHint': '행을 다른 행으로 끌어 순서를 바꾸면 설정에 저장됩니다.',
408
432
  'settings.rowAlways': '표시',
409
433
  'settings.rowFold': '접기',
410
434
  'settings.rowMore': '더 보기에 숨기기',
@@ -432,6 +456,8 @@ window.__ModuleLoader__.load({
432
456
  'settings.defaultFoldedHint': 'État initial d’une fenêtre sans enregistrement local',
433
457
  'settings.rows': 'Entrées',
434
458
  'settings.rowsHint': 'Trois états par ligne : Afficher la garde visible, Replier laisse le repli la masquer, Masquer dans « Plus » la déplace dans le menu « Plus ».',
459
+ 'settings.rowDrag': 'Faites glisser les lignes pour réordonner (« Plus » reste en fin)',
460
+ 'settings.rowDragHint': 'Glissez une ligne sur une autre pour changer l’ordre ; il est enregistré dans les réglages.',
435
461
  'settings.rowAlways': 'Afficher',
436
462
  'settings.rowFold': 'Replier',
437
463
  'settings.rowMore': 'Masquer dans « Plus »',
@@ -459,6 +485,8 @@ window.__ModuleLoader__.load({
459
485
  'settings.defaultFoldedHint': 'Anfangszustand eines Fensters ohne lokalen Eintrag',
460
486
  'settings.rows': 'Einträge',
461
487
  'settings.rowsHint': 'Drei Zustände pro Zeile: Anzeigen bleibt sichtbar, Einklappen lässt die Zeile verschwinden, In „Mehr“ ausblenden verschiebt sie in das Menü „Mehr“.',
488
+ 'settings.rowDrag': 'Zeilen zum Neuanordnen ziehen („Mehr“ bleibt am Ende)',
489
+ 'settings.rowDragHint': 'Ziehen Sie eine Zeile auf eine andere; die Reihenfolge wird in den Einstellungen gespeichert.',
462
490
  'settings.rowAlways': 'Anzeigen',
463
491
  'settings.rowFold': 'Einklappen',
464
492
  'settings.rowMore': 'In „Mehr“ ausblenden',
@@ -486,6 +514,8 @@ window.__ModuleLoader__.load({
486
514
  'settings.defaultFoldedHint': 'Stato iniziale di una finestra senza record locale',
487
515
  'settings.rows': 'Voci',
488
516
  'settings.rowsHint': 'Tre stati per riga: Mostra resta visibile, Comprimi lascia che la compressione la nasconda, Nascondi in «Altro» la sposta nel menu «Altro».',
517
+ 'settings.rowDrag': 'Trascina le righe per riordinarle («Altro» resta in fondo)',
518
+ 'settings.rowDragHint': 'Trascina una riga su un’altra per cambiare l’ordine, salvato nelle impostazioni.',
489
519
  'settings.rowAlways': 'Mostra',
490
520
  'settings.rowFold': 'Comprimi',
491
521
  'settings.rowMore': 'Nascondi in «Altro»',
@@ -513,6 +543,8 @@ window.__ModuleLoader__.load({
513
543
  'settings.defaultFoldedHint': 'Начальное состояние окна без локальной записи',
514
544
  'settings.rows': 'Пункты',
515
545
  'settings.rowsHint': 'Три состояния на строку: Показывать оставляет её видимой, Сворачивать позволяет её скрыть, Скрыть в «Ещё» переносит её в меню «Ещё».',
546
+ 'settings.rowDrag': 'Перетаскивайте строки для изменения порядка («Ещё» всегда последняя)',
547
+ 'settings.rowDragHint': 'Перетащите строку на другую — порядок сохранится в настройках.',
516
548
  'settings.rowAlways': 'Показывать',
517
549
  'settings.rowFold': 'Сворачивать',
518
550
  'settings.rowMore': 'Скрыть в «Ещё»',
@@ -540,6 +572,8 @@ window.__ModuleLoader__.load({
540
572
  'settings.defaultFoldedHint': 'Estado inicial de una ventana sin registro local',
541
573
  'settings.rows': 'Entradas',
542
574
  'settings.rowsHint': 'Tres estados por fila: Mostrar la mantiene visible, Plegar deja que el pliegue la oculte, Ocultar en «Más» la mueve al menú «Más».',
575
+ 'settings.rowDrag': 'Arrastre las filas para reordenar («Más» siempre al final)',
576
+ 'settings.rowDragHint': 'Arrastre una fila sobre otra para cambiar el orden; se guarda en los ajustes.',
543
577
  'settings.rowAlways': 'Mostrar',
544
578
  'settings.rowFold': 'Plegar',
545
579
  'settings.rowMore': 'Ocultar en «Más»',
@@ -568,6 +602,8 @@ window.__ModuleLoader__.load({
568
602
  'settings.defaultFoldedHint': 'Estado inicial de uma janela sem registro local',
569
603
  'settings.rows': 'Entradas',
570
604
  'settings.rowsHint': 'Três estados por linha: Mostrar mantém a linha sempre visível; Recolher permite o recolhimento; Ocultar em «Mais» move a linha para o menu «Mais».',
605
+ 'settings.rowDrag': 'Arraste as linhas para reordenar («Mais» fica no fim)',
606
+ 'settings.rowDragHint': 'Arraste uma linha para outra para mudar a ordem; ela é salva nas configurações.',
571
607
  'settings.rowAlways': 'Mostrar',
572
608
  'settings.rowFold': 'Recolher',
573
609
  'settings.rowMore': 'Ocultar em «Mais»',
@@ -653,7 +689,7 @@ window.__ModuleLoader__.load({
653
689
  /** Whether the group is folded; `null` = never decided in this window yet. */
654
690
  let folded = null;
655
691
  /** Last config the fold was applied with (also read by the settings card). */
656
- let config = { defaultFolded: false, keepLabels: [], hideLabels: [], align: 'start' };
692
+ let config = { defaultFolded: false, keepLabels: [], hideLabels: [], align: 'start', orderLabels: [] };
657
693
  /** Registered so `index.ts` can notify the fold after a settings write. */
658
694
  const configListeners = new Set();
659
695
  /**
@@ -786,6 +822,48 @@ window.__ModuleLoader__.load({
786
822
  * `_panelRow` button. Returns `null` when nothing matches — the caller then
787
823
  * leaves the sidebar exactly as shipped.
788
824
  */
825
+ /**
826
+ * Move one label to another label's position in an ordered label list.
827
+ *
828
+ * Pure and case-sensitive by label identity: unknown labels leave the list
829
+ * untouched. Used both by the sidebar DnD and by the settings card so both
830
+ * surfaces compute the next order through one function.
831
+ */
832
+ function reorderLabels(labels, fromLabel, toLabel) {
833
+ const from = labels.indexOf(fromLabel);
834
+ const to = labels.indexOf(toLabel);
835
+ if (from < 0 || to < 0 || from === to)
836
+ return [...labels];
837
+ const next = [...labels];
838
+ const [moved] = next.splice(from, 1);
839
+ next.splice(to, 0, moved);
840
+ return next;
841
+ }
842
+ /**
843
+ * Arrange live panel rows into the persisted label order.
844
+ *
845
+ * Rows whose label is absent from `orderLabels` are appended in their current
846
+ * DOM order, so a config written before a row existed never loses that row.
847
+ * The "More" header (aria-haspopup="menu", or the last row as fallback) is
848
+ * always forced to the end — it is the fold toggle and must stay put.
849
+ */
850
+ function orderedRows(rows, orderLabels) {
851
+ if (rows.length < 2)
852
+ return [...rows];
853
+ const header = rows.find((row) => row.getAttribute('aria-haspopup') === 'menu') ?? rows[rows.length - 1];
854
+ const body = rows.filter((row) => row !== header);
855
+ const rank = (row) => {
856
+ const label = labelOf(row);
857
+ const idx = orderLabels.indexOf(label);
858
+ return idx < 0 ? Number.MAX_SAFE_INTEGER : idx;
859
+ };
860
+ // Stable sort: unknown labels keep their relative DOM order.
861
+ const sorted = body
862
+ .map((row, index) => ({ row, index, r: rank(row) }))
863
+ .sort((a, b) => (a.r - b.r) || (a.index - b.index))
864
+ .map((entry) => entry.row);
865
+ return [...sorted, header];
866
+ }
789
867
  function findPanelNav(root) {
790
868
  for (const label of PANELS_LABELS) {
791
869
  const byLabel = root.querySelector(`nav[aria-label="${label}"]`);
@@ -854,7 +932,9 @@ window.__ModuleLoader__.load({
854
932
  */
855
933
  function roster() {
856
934
  const nav = findPanelNav(document);
857
- const rows = nav === null ? [] : rosterFrom(rowsOf(nav), config.keepLabels, config.hideLabels);
935
+ const rows = nav === null
936
+ ? []
937
+ : rosterFrom(orderedRows(rowsOf(nav), config.orderLabels), config.keepLabels, config.hideLabels);
858
938
  const seen = new Set(rows.map((row) => row.label.toLowerCase()));
859
939
  for (const entry of moreMenuRows()) {
860
940
  if (seen.has(entry.label.toLowerCase()))
@@ -1195,6 +1275,159 @@ window.__ModuleLoader__.load({
1195
1275
  return;
1196
1276
  anchor.click();
1197
1277
  }
1278
+ // --- Row reorder (HTML5 DnD on the live sidebar rows) -----------------------
1279
+ /** Registered by index.ts / the settings card to learn when a sidebar drag commits a new order. */
1280
+ const orderListeners = new Set();
1281
+ let dragSourceLabel = null;
1282
+ /** Subscribe to order changes originating from the sidebar DOM. */
1283
+ function subscribeOrder(listener) {
1284
+ orderListeners.add(listener);
1285
+ return () => { orderListeners.delete(listener); };
1286
+ }
1287
+ /** Publish a new order from a sidebar drag and persist it in our config. */
1288
+ function notifyOrderChange(order) {
1289
+ config = { ...config, orderLabels: [...order] };
1290
+ for (const listener of Array.from(orderListeners))
1291
+ listener([...order]);
1292
+ }
1293
+ /**
1294
+ * Wire one panel row's **wrapper** for HTML5 drag-and-drop.
1295
+ *
1296
+ * Idempotent: an `ATTR.dnd` mark prevents duplicate listeners across the many
1297
+ * rescan passes. The wrapper (not the button) is the drag surface because it is
1298
+ * the visible row *and* the flex item `applyOrder` ranks — otherwise dropping on
1299
+ * the row's pin gutter would miss the target. The "More" header is never wired:
1300
+ * it stays the fold toggle and stays last.
1301
+ */
1302
+ function bindRowDrag(row, isHeader) {
1303
+ if (isHeader)
1304
+ return;
1305
+ const label = labelOf(row);
1306
+ if (label === '')
1307
+ return;
1308
+ const el = foldTarget(row);
1309
+ if (el.getAttribute(ATTR.dnd) !== null)
1310
+ return;
1311
+ el.setAttribute(ATTR.dnd, '');
1312
+ el.setAttribute('draggable', 'true');
1313
+ el.addEventListener('dragstart', (e) => {
1314
+ dragSourceLabel = label;
1315
+ el.classList.add(CLS.rowDrag);
1316
+ if (e?.dataTransfer)
1317
+ e.dataTransfer.effectAllowed = 'move';
1318
+ });
1319
+ el.addEventListener('dragover', (e) => {
1320
+ if (dragSourceLabel === null || dragSourceLabel === label)
1321
+ return;
1322
+ e?.preventDefault?.();
1323
+ if (e?.dataTransfer)
1324
+ e.dataTransfer.dropEffect = 'move';
1325
+ el.classList.add(CLS.rowDragOver);
1326
+ });
1327
+ el.addEventListener('dragleave', () => {
1328
+ el.classList.remove(CLS.rowDragOver);
1329
+ });
1330
+ el.addEventListener('drop', (e) => {
1331
+ e?.preventDefault?.();
1332
+ el.classList.remove(CLS.rowDragOver);
1333
+ const source = dragSourceLabel;
1334
+ dragSourceLabel = null;
1335
+ if (source === null || source === label)
1336
+ return;
1337
+ const all = rowsOf(mount?.nav ?? el.closest?.(SEL.panelList));
1338
+ if (all.length === 0)
1339
+ return;
1340
+ // Order the reorderable rows only: the "More" header is not a rank, it is
1341
+ // pinned last by orderedRows, and persisting its label would just be noise.
1342
+ const header = all.find((row) => row.getAttribute('aria-haspopup') === 'menu') ?? all[all.length - 1];
1343
+ const next = reorderLabels(all.filter((row) => row !== header).map(labelOf), source, label);
1344
+ applyOrder(all, next);
1345
+ notifyOrderChange(next);
1346
+ });
1347
+ el.addEventListener('dragend', () => {
1348
+ dragSourceLabel = null;
1349
+ el.classList.remove(CLS.rowDrag);
1350
+ el.classList.remove(CLS.rowDragOver);
1351
+ });
1352
+ }
1353
+ /** Wire every live row for reordering (called on each apply pass, idempotent). */
1354
+ function bindRowDrags(rows) {
1355
+ if (rows.length < 2)
1356
+ return;
1357
+ const header = rows.find((row) => row.getAttribute('aria-haspopup') === 'menu') ?? rows[rows.length - 1];
1358
+ for (const row of rows)
1359
+ bindRowDrag(row, row === header);
1360
+ }
1361
+ /**
1362
+ * Reorder the nav's rows to match the persisted label order.
1363
+ *
1364
+ * Written as the flex `order` property on each row's **wrapper**, never by moving
1365
+ * nodes. Two measured facts force that choice:
1366
+ *
1367
+ * - from the 0.2.2 line on every row button sits in its own `div._panelEntry`
1368
+ * (`SidebarRoot.tsx:78`), so the buttons are *not* siblings. The first cut
1369
+ * moved them with `parent.insertBefore(row, next)`, where `next` belonged to
1370
+ * another parent — the DOM throws `NotFoundError`, our `try` swallowed it, and
1371
+ * a drop therefore highlighted the target and changed nothing (the bug this
1372
+ * replaces);
1373
+ * - the nodes are React's, so re-parenting them is a fight we lose on the next
1374
+ * render. `order` is ours alone to write, it survives re-renders (the host sets
1375
+ * no `style` on these wrappers), and removing the declarations undoes it.
1376
+ *
1377
+ * `.panelList` is `display:flex; flex-direction:column` (`SidebarRoot.module.css`),
1378
+ * so `order` reorders the column without touching document order — which is also
1379
+ * why the observer (attributes filtered to `class`) cannot see these writes.
1380
+ *
1381
+ * The "More" header is ordered last by {@link orderedRows}, so it stays the fold
1382
+ * toggle no matter what the user drags.
1383
+ * @param rows - the nav's panel rows, in document order.
1384
+ * @param orderLabels - persisted label order; an empty list clears every rank.
1385
+ */
1386
+ function applyOrder(rows, orderLabels) {
1387
+ if (rows.length < 2)
1388
+ return;
1389
+ const entries = [];
1390
+ for (const row of rows) {
1391
+ const entry = foldTarget(row);
1392
+ if (!entries.includes(entry))
1393
+ entries.push(entry);
1394
+ }
1395
+ const wanted = new Map();
1396
+ if (orderLabels.length > 0) {
1397
+ orderedRows(rows, orderLabels).forEach((row, index) => {
1398
+ wanted.set(foldTarget(row), index + 1);
1399
+ });
1400
+ }
1401
+ for (const entry of entries) {
1402
+ const value = wanted.get(entry);
1403
+ if (value === undefined) {
1404
+ if (entry.getAttribute(ATTR.order) === null)
1405
+ continue;
1406
+ entry.removeAttribute(ATTR.order);
1407
+ const el = entry;
1408
+ if (el.style != null)
1409
+ el.style.order = '';
1410
+ continue;
1411
+ }
1412
+ const text = String(value);
1413
+ // Write only on change: a no-op write is a mutation nobody asked for.
1414
+ if (entry.getAttribute(ATTR.order) === text)
1415
+ continue;
1416
+ entry.setAttribute(ATTR.order, text);
1417
+ const el = entry;
1418
+ if (el.style != null)
1419
+ el.style.order = text;
1420
+ }
1421
+ }
1422
+ /** Undo every inline rank this plugin wrote (dispose / HMR sweep). */
1423
+ function clearOrder() {
1424
+ for (const node of Array.from(document.querySelectorAll(`[${ATTR.order}]`))) {
1425
+ node.removeAttribute(ATTR.order);
1426
+ const el = node;
1427
+ if (el.style != null)
1428
+ el.style.order = '';
1429
+ }
1430
+ }
1198
1431
  /**
1199
1432
  * Write the fold marks. Only attributes we own are touched: no host class,
1200
1433
  * no host attribute, and never the anchor's `aria-expanded` (that one is the
@@ -1208,6 +1441,11 @@ window.__ModuleLoader__.load({
1208
1441
  if (plan === null)
1209
1442
  return;
1210
1443
  const { header } = plan;
1444
+ // Reorder the live rows to the persisted order before any fold marks are
1445
+ // written. Ranks are inline `order` values written only when they change, and
1446
+ // the observer watches `class` alone, so a scan cannot trigger itself.
1447
+ applyOrder(rows, config.orderLabels);
1448
+ bindRowDrags(rows);
1211
1449
  if (header.getAttribute(ATTR.header) === null)
1212
1450
  header.setAttribute(ATTR.header, '');
1213
1451
  // Alignment is one nav-level mark with three rule sets behind it. Written on
@@ -1216,8 +1454,9 @@ window.__ModuleLoader__.load({
1216
1454
  const align = normalizeAlign(config.align);
1217
1455
  if (mount.nav.getAttribute(ATTR.align) !== align)
1218
1456
  mount.nav.setAttribute(ATTR.align, align);
1219
- // The settings card renders whatever is on screen right now; keep it in sync.
1220
- notifyRoster(rosterFrom(rows, config.keepLabels, config.hideLabels));
1457
+ // The settings card renders whatever is on screen right now; keep it in sync —
1458
+ // and in the order the column shows, so a drag reads the same on both surfaces.
1459
+ notifyRoster(rosterFrom(orderedRows(rows, config.orderLabels), config.keepLabels, config.hideLabels));
1221
1460
  mount.toggle.classList.toggle(CLS.toggleIdle, plan.idle);
1222
1461
  mount.toggle.setAttribute('aria-disabled', plan.idle ? 'true' : 'false');
1223
1462
  for (const row of rows) {
@@ -1331,6 +1570,12 @@ window.__ModuleLoader__.load({
1331
1570
  for (const row of Array.from(nav.querySelectorAll?.(`[${ATTR.folded}]`) ?? [])) {
1332
1571
  row.removeAttribute(ATTR.folded);
1333
1572
  }
1573
+ for (const row of Array.from(nav.querySelectorAll?.(`[${ATTR.dnd}]`) ?? [])) {
1574
+ row.removeAttribute(ATTR.dnd);
1575
+ row.removeAttribute('draggable');
1576
+ row.classList?.remove(CLS.rowDrag, CLS.rowDragOver);
1577
+ }
1578
+ clearOrder();
1334
1579
  mount = null;
1335
1580
  }
1336
1581
  /**
@@ -1390,6 +1635,12 @@ window.__ModuleLoader__.load({
1390
1635
  for (const row of Array.from(document.querySelectorAll(`[${ATTR.folded}]`))) {
1391
1636
  row.removeAttribute(ATTR.folded);
1392
1637
  }
1638
+ for (const row of Array.from(document.querySelectorAll(`[${ATTR.dnd}]`))) {
1639
+ row.removeAttribute(ATTR.dnd);
1640
+ row.removeAttribute('draggable');
1641
+ row.classList?.remove(CLS.rowDrag, CLS.rowDragOver);
1642
+ }
1643
+ clearOrder();
1393
1644
  mount = null;
1394
1645
  // The pin bookkeeping belongs to one window's DOM; a remount starts from what
1395
1646
  // the host shows now, never from a count that may no longer refer to it.
@@ -1517,6 +1768,7 @@ window.__ModuleLoader__.load({
1517
1768
  // dropped on the way in instead of being retried on every scan.
1518
1769
  hideLabels: pruneHidden(cfg.hideLabels),
1519
1770
  align: normalizeAlign(cfg.align),
1771
+ orderLabels: [...(cfg.orderLabels ?? [])],
1520
1772
  };
1521
1773
  }
1522
1774
  /** The configuration the fold is currently running with (settings card reads it). */
@@ -1529,6 +1781,7 @@ window.__ModuleLoader__.load({
1529
1781
  keepLabels: ['插件', 'Plugins'],
1530
1782
  hideLabels: [],
1531
1783
  align: 'start',
1784
+ orderLabels: [],
1532
1785
  };
1533
1786
  /**
1534
1787
  * The configuration card on this bundle's Plugin-Manager page.
@@ -1559,6 +1812,7 @@ window.__ModuleLoader__.load({
1559
1812
  keepLabels: ['插件', 'Plugins'],
1560
1813
  hideLabels: [],
1561
1814
  align: 'start',
1815
+ orderLabels: [],
1562
1816
  };
1563
1817
  /** The card body node, created once and re-used by every mount. */
1564
1818
  let cardRoot = null;
@@ -1581,6 +1835,7 @@ window.__ModuleLoader__.load({
1581
1835
  keepLabels: snap.value?.keepLabels ?? fallback.keepLabels,
1582
1836
  hideLabels: snap.value?.hideLabels ?? fallback.hideLabels,
1583
1837
  align: normalizeAlign(snap.value?.align ?? fallback.align),
1838
+ orderLabels: Array.isArray(snap.value?.orderLabels) ? snap.value.orderLabels : fallback.orderLabels,
1584
1839
  writable: snap.writable && snap.status === 'ready',
1585
1840
  status: snap.status,
1586
1841
  };
@@ -1590,6 +1845,7 @@ window.__ModuleLoader__.load({
1590
1845
  keepLabels: fallback.keepLabels,
1591
1846
  hideLabels: fallback.hideLabels,
1592
1847
  align: normalizeAlign(fallback.align),
1848
+ orderLabels: fallback.orderLabels,
1593
1849
  writable: false,
1594
1850
  status: 'unavailable',
1595
1851
  };
@@ -1741,6 +1997,75 @@ window.__ModuleLoader__.load({
1741
1997
  paint();
1742
1998
  commit({ keepLabels: lists.keepLabels, hideLabels: lists.hideLabels });
1743
1999
  }
2000
+ /**
2001
+ * Attach a drag handle to a settings row so the visible list can be reordered.
2002
+ *
2003
+ * The row itself is the drag source and drop target; both surfaces (sidebar and
2004
+ * card) compute the next order via reorderLabels and commit through commit().
2005
+ *
2006
+ * The drop commits in one direction only — the sidebar is the ordering
2007
+ * authority: `applyConfig` ranks the live rows, `paint()` re-reads the roster
2008
+ * (which now reports the new order), and only then does the write go out. The
2009
+ * first cut rebuilt the list by appending fresh rows to the card root, which
2010
+ * left the originals in place (a duplicated list that read as "nothing changed").
2011
+ */
2012
+ function makeDraggableRow(row, label, rows) {
2013
+ row.setAttribute('draggable', 'true');
2014
+ // A grab cursor, not the drag *feedback* class: dimming the row permanently
2015
+ // made every settings row look disabled.
2016
+ row.classList.add(CLS.rowHandle);
2017
+ let source = '';
2018
+ row.addEventListener('dragstart', (e) => {
2019
+ source = label;
2020
+ row.classList.add(CLS.rowDrag);
2021
+ if (e?.dataTransfer)
2022
+ e.dataTransfer.effectAllowed = 'move';
2023
+ });
2024
+ row.addEventListener('dragover', (e) => {
2025
+ if (source === '' || source === label)
2026
+ return;
2027
+ e?.preventDefault?.();
2028
+ if (e?.dataTransfer)
2029
+ e.dataTransfer.dropEffect = 'move';
2030
+ row.classList.add(CLS.rowDragOver);
2031
+ });
2032
+ row.addEventListener('dragleave', () => row.classList.remove(CLS.rowDragOver));
2033
+ row.addEventListener('drop', (e) => {
2034
+ e?.preventDefault?.();
2035
+ row.classList.remove(CLS.rowDragOver);
2036
+ const from = source;
2037
+ source = '';
2038
+ if (from === '' || from === label)
2039
+ return;
2040
+ const next = reorderLabels(rows.map((entry) => entry.label), from, label);
2041
+ applyConfig({ ...effectiveConfig(), orderLabels: next });
2042
+ paint();
2043
+ commit({ orderLabels: next });
2044
+ });
2045
+ row.addEventListener('dragend', () => {
2046
+ source = '';
2047
+ row.classList.remove(CLS.rowDrag);
2048
+ row.classList.remove(CLS.rowDragOver);
2049
+ });
2050
+ return row;
2051
+ }
2052
+ /** Build one three-state entry row (shared by paint and the DnD repaint). */
2053
+ function buildEntry(entry, rows) {
2054
+ const canHide = hostHasPin();
2055
+ const movable = canMoveToMore(entry.label, canHide);
2056
+ const hintText = movable
2057
+ ? pickDictionary(document.documentElement.lang ?? '')['settings.rowHint']
2058
+ : isFixedLabel(entry.label)
2059
+ ? pickDictionary(document.documentElement.lang ?? '')['settings.moreFixed']
2060
+ : pickDictionary(document.documentElement.lang ?? '')['settings.moreUnavailable'];
2061
+ const dict = pickDictionary(document.documentElement.lang ?? '');
2062
+ const built = buildRow(entry.label, hintText, segmentedControl(`row:${entry.label}`, entry.state, [
2063
+ { value: 'always', label: dict['settings.rowAlways'] },
2064
+ { value: 'foldable', label: dict['settings.rowFold'] },
2065
+ { value: 'more', label: dict['settings.rowMore'], unavailable: !movable },
2066
+ ], !currentValues().writable, (next) => writeRowState(rows, entry.label, next)));
2067
+ return makeDraggableRow(built, entry.label, rows);
2068
+ }
1744
2069
  /** Paint (or repaint) the card body from the current values and the live roster. */
1745
2070
  function paint() {
1746
2071
  if (cardRoot === null)
@@ -1767,6 +2092,11 @@ window.__ModuleLoader__.load({
1767
2092
  scopeTitle.setAttribute(ATTR.own, '');
1768
2093
  scopeTitle.textContent = dict['settings.rows'];
1769
2094
  cardRoot.appendChild(scopeTitle);
2095
+ const dragHint = document.createElement('span');
2096
+ dragHint.className = CLS.hint;
2097
+ dragHint.setAttribute(ATTR.own, '');
2098
+ dragHint.textContent = dict['settings.rowDrag'] + ' — ' + dict['settings.rowDragHint'];
2099
+ cardRoot.appendChild(dragHint);
1770
2100
  const hint = document.createElement('span');
1771
2101
  hint.className = CLS.hint;
1772
2102
  hint.setAttribute(ATTR.own, '');
@@ -1782,19 +2112,8 @@ window.__ModuleLoader__.load({
1782
2112
  // Two gates on the third state, per row: this host must ship the pin mechanism
1783
2113
  // at all (0.2.2 on), and the row must not be the host's fixed panel — the host
1784
2114
  // never unpins that one, so offering it would be a promise it silently refuses.
1785
- const canHide = hostHasPin();
1786
2115
  for (const entry of rows) {
1787
- const movable = canMoveToMore(entry.label, canHide);
1788
- const hintText = movable
1789
- ? dict['settings.rowHint']
1790
- : isFixedLabel(entry.label) ? dict['settings.moreFixed'] : dict['settings.moreUnavailable'];
1791
- cardRoot.appendChild(buildRow(entry.label, hintText, segmentedControl(`row:${entry.label}`, entry.state, [
1792
- { value: 'always', label: dict['settings.rowAlways'] },
1793
- { value: 'foldable', label: dict['settings.rowFold'] },
1794
- { value: 'more', label: dict['settings.rowMore'], unavailable: !movable },
1795
- ], !values.writable, (next) => {
1796
- writeRowState(rows, entry.label, next);
1797
- })));
2116
+ cardRoot.appendChild(buildEntry(entry, rows));
1798
2117
  }
1799
2118
  // ④ write outcome. The host owns persistence; a refused write leaves the card
1800
2119
  // and the sidebar agreeing with each other and disagreeing with the store, so
@@ -1851,6 +2170,7 @@ window.__ModuleLoader__.load({
1851
2170
  keepLabels: [...next.keepLabels],
1852
2171
  hideLabels: [...next.hideLabels],
1853
2172
  align: normalizeAlign(next.align),
2173
+ orderLabels: [...(next.orderLabels ?? [])],
1854
2174
  };
1855
2175
  paint();
1856
2176
  }
@@ -1883,7 +2203,7 @@ window.__ModuleLoader__.load({
1883
2203
  };
1884
2204
  }
1885
2205
  /** Exported for the guard test: the card writes no free-text label list. */
1886
- const CARD_WRITES = ['defaultFolded', 'align', 'keepLabels', 'hideLabels'];
2206
+ const CARD_WRITES = ['defaultFolded', 'align', 'keepLabels', 'hideLabels', 'orderLabels'];
1887
2207
  /**
1888
2208
  * The "More" menu's shortcut row into this plugin's own settings.
1889
2209
  *
@@ -2041,6 +2361,12 @@ window.__ModuleLoader__.load({
2041
2361
  /** Adopt a served snapshot, falling back to the built-ins when it says nothing. */
2042
2362
  function adopt(scope) {
2043
2363
  onScope(scope);
2364
+ // A sidebar drag publishes the new order here; commit it through the same
2365
+ // scoped form so the card and the sidebar share one persisted source.
2366
+ subscribeOrder((order) => {
2367
+ applyConfig({ ...effectiveConfig(), orderLabels: order });
2368
+ void scope.set('orderLabels', order);
2369
+ });
2044
2370
  const push = () => {
2045
2371
  const snap = scope.getSnapshot();
2046
2372
  const value = snap.value;
@@ -2053,6 +2379,8 @@ window.__ModuleLoader__.load({
2053
2379
  // Alignment is validated by `normalizeAlign` here so everything downstream
2054
2380
  // (fold marks, card radios) only ever sees one of the three known modes.
2055
2381
  align: normalizeAlign(typeof value?.align === 'string' ? value.align : BUILTIN_CONFIG.align),
2382
+ // Row order: absent on older hosts means keep the shipped DOM order.
2383
+ orderLabels: Array.isArray(value?.orderLabels) ? value.orderLabels : BUILTIN_CONFIG.orderLabels,
2056
2384
  };
2057
2385
  onFallback(next);
2058
2386
  applyConfig(next);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-sidebar-fold",
3
- "version": "0.1.15",
3
+ "version": "0.1.17",
4
4
  "description": "Folds the sidebar's add-on panel rows under the shipped \"More\" row, and from host 0.2.2 on gives every row three states — show, fold, or hide in the host's own \"More\" list. The fold state persists per window, rows are read from the live sidebar, and the managed rows' icon + label can be aligned left, centre or right.",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
@@ -37,13 +37,13 @@
37
37
  "scripts": {
38
38
  "lint": "node scripts/lint.mjs",
39
39
  "typecheck": "tsc -p tsconfig.json",
40
- "test": "node --experimental-strip-types --no-warnings --test tests/fold.test.ts tests/fold-plan.test.ts",
40
+ "test": "node --experimental-strip-types --no-warnings --test tests/fold.test.ts tests/fold-plan.test.ts tests/order.test.ts tests/order-apply.test.ts",
41
41
  "test:coverage": "node --experimental-strip-types --no-warnings --experimental-test-coverage --test tests/fold.test.ts tests/fold-plan.test.ts",
42
42
  "build": "node scripts/build-client.mjs",
43
43
  "verify": "node scripts/verify.mjs",
44
44
  "gen:locale": "node scripts/gen-locale-meta.mjs",
45
45
  "ci": "npm run lint && npm run typecheck && npm test && npm run build && npm run verify",
46
- "prepack": "npm run lint && npm run build && npm run verify",
46
+ "prepack": "npm run lint && npm run build && node scripts/check-surface-classes.mjs --prefix dshsf && npm run verify",
47
47
  "prepublishOnly": "npm run lint && npm run build && npm run verify",
48
48
  "hosts:check": "node scripts/sync-hosts.mjs",
49
49
  "hosts:write": "node scripts/sync-hosts.mjs --write"
@@ -81,4 +81,4 @@
81
81
  "@types/node": "^22.20.5",
82
82
  "typescript": "^5.6.0"
83
83
  }
84
- }
84
+ }
package/screenshots.json CHANGED
@@ -1,6 +1,6 @@
1
- {
2
- "screenshots": [
3
- "assets/middle.png",
4
- "assets/fold.png"
5
- ]
6
- }
1
+ {
2
+ "screenshots": [
3
+ "assets/middle.png",
4
+ "assets/fold.png"
5
+ ]
6
+ }
@@ -35,6 +35,11 @@ export const CLS = Object.freeze({
35
35
  menuRow: 'dshsf-menu-row',
36
36
  menuText: 'dshsf-menu-text',
37
37
  menuIcon: 'dshsf-menu-icon',
38
+ /** Transient highlight on the row being dragged / targeted. */
39
+ rowDrag: 'dshsf-row-drag',
40
+ rowDragOver: 'dshsf-row-drag-over',
41
+ /** The settings-card handle a reorder drag is started from. */
42
+ rowHandle: 'dshsf-row-handle',
38
43
  })
39
44
 
40
45
  /**
@@ -65,6 +70,10 @@ export const ATTR = Object.freeze({
65
70
  align: 'data-dshsf-align',
66
71
  /** On the toggle: the folded group holds the panel the user is looking at. */
67
72
  activeInside: 'data-dshsf-active-inside',
73
+ /** On a panel row we have wired for HTML5 drag-and-drop reordering. */
74
+ dnd: 'data-dshsf-dnd',
75
+ /** On a row wrapper carrying the flex `order` we wrote for a persisted rank. */
76
+ order: 'data-dshsf-order',
68
77
  })
69
78
 
70
79
  /** Selector fragments (hash-tolerant). */
@@ -315,5 +324,12 @@ export const SHEET = [
315
324
  'outline-offset:-2px',
316
325
  ]),
317
326
  rule(`.${CLS.menuText}`, ['overflow:hidden', 'text-overflow:ellipsis', 'white-space:nowrap']),
327
+ // Row drag feedback — opacity on the source, a token-tinted outline on the target.
328
+ rule(`.${CLS.rowDrag}`, ['opacity:.45']),
329
+ rule(`.${CLS.rowDragOver}`, ['outline:2px solid var(--dsw-alias-state-business-primary,#4d6bfe)', 'outline-offset:-2px']),
330
+ // The settings card's drag handle: a grab cursor is the only honest affordance
331
+ // (dimming the whole row, as the first cut did, reads as “disabled”).
332
+ rule(`.${CLS.rowHandle}`, ['cursor:grab', '-webkit-user-select:none', 'user-select:none']),
333
+ rule(`.${CLS.rowHandle}:active`, ['cursor:grabbing']),
318
334
  rule(`.${CLS.menuIcon}`, ['flex:none', 'display:block']),
319
- ].join('')
335
+ ].join('')