dsh-sidebar-fold 0.1.14 → 0.1.16

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/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,9 @@ 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',
38
41
  })
39
42
 
40
43
  /**
@@ -65,6 +68,8 @@ export const ATTR = Object.freeze({
65
68
  align: 'data-dshsf-align',
66
69
  /** On the toggle: the folded group holds the panel the user is looking at. */
67
70
  activeInside: 'data-dshsf-active-inside',
71
+ /** On a panel row we have wired for HTML5 drag-and-drop reordering. */
72
+ dnd: 'data-dshsf-dnd',
68
73
  })
69
74
 
70
75
  /** Selector fragments (hash-tolerant). */
@@ -315,5 +320,8 @@ export const SHEET = [
315
320
  'outline-offset:-2px',
316
321
  ]),
317
322
  rule(`.${CLS.menuText}`, ['overflow:hidden', 'text-overflow:ellipsis', 'white-space:nowrap']),
323
+ // Row drag feedback — opacity on the source, a token-tinted outline on the target.
324
+ rule(`.${CLS.rowDrag}`, ['opacity:.45']),
325
+ rule(`.${CLS.rowDragOver}`, ['outline:2px solid var(--dsw-alias-state-business-primary,#4d6bfe)', 'outline-offset:-2px']),
318
326
  rule(`.${CLS.menuIcon}`, ['flex:none', 'display:block']),
319
- ].join('')
327
+ ].join('')
@@ -30,7 +30,7 @@ import {
30
30
  import { pickDictionary } from './locales.ts'
31
31
 
32
32
  /** Minimal DOM surface we touch — keeps the tests free of a DOM dependency. */
33
- type ConfigLike = { defaultFolded: boolean; keepLabels: string[]; hideLabels: string[]; align: AlignMode }
33
+ type ConfigLike = { defaultFolded: boolean; keepLabels: string[]; hideLabels: string[]; align: AlignMode; orderLabels: string[] }
34
34
 
35
35
  /**
36
36
  * Coerce a served alignment value into a mode the sheet has a rule for.
@@ -107,7 +107,7 @@ let mount: Mount | null = null
107
107
  /** Whether the group is folded; `null` = never decided in this window yet. */
108
108
  let folded: boolean | null = null
109
109
  /** Last config the fold was applied with (also read by the settings card). */
110
- let config: ConfigLike = { defaultFolded: false, keepLabels: [], hideLabels: [], align: 'start' }
110
+ let config: ConfigLike = { defaultFolded: false, keepLabels: [], hideLabels: [], align: 'start', orderLabels: [] }
111
111
  /** Registered so `index.ts` can notify the fold after a settings write. */
112
112
  const configListeners = new Set<() => void>()
113
113
 
@@ -248,6 +248,48 @@ export function splitRows(
248
248
  * `_panelRow` button. Returns `null` when nothing matches — the caller then
249
249
  * leaves the sidebar exactly as shipped.
250
250
  */
251
+ /**
252
+ * Move one label to another label's position in an ordered label list.
253
+ *
254
+ * Pure and case-sensitive by label identity: unknown labels leave the list
255
+ * untouched. Used both by the sidebar DnD and by the settings card so both
256
+ * surfaces compute the next order through one function.
257
+ */
258
+ export function reorderLabels(labels: readonly string[], fromLabel: string, toLabel: string): string[] {
259
+ const from = labels.indexOf(fromLabel)
260
+ const to = labels.indexOf(toLabel)
261
+ if (from < 0 || to < 0 || from === to) return [...labels]
262
+ const next = [...labels]
263
+ const [moved] = next.splice(from, 1)
264
+ next.splice(to, 0, moved)
265
+ return next
266
+ }
267
+
268
+ /**
269
+ * Arrange live panel rows into the persisted label order.
270
+ *
271
+ * Rows whose label is absent from `orderLabels` are appended in their current
272
+ * DOM order, so a config written before a row existed never loses that row.
273
+ * The "More" header (aria-haspopup="menu", or the last row as fallback) is
274
+ * always forced to the end — it is the fold toggle and must stay put.
275
+ */
276
+ export function orderedRows(rows: readonly ElementLike[], orderLabels: readonly string[]): ElementLike[] {
277
+ if (rows.length < 2) return [...rows]
278
+ const header = rows.find((row) => row.getAttribute('aria-haspopup') === 'menu') ?? rows[rows.length - 1]
279
+ const body = rows.filter((row) => row !== header)
280
+ const rank = (row: ElementLike): number => {
281
+ const label = labelOf(row)
282
+ const idx = orderLabels.indexOf(label)
283
+ return idx < 0 ? Number.MAX_SAFE_INTEGER : idx
284
+ }
285
+ // Stable sort: unknown labels keep their relative DOM order.
286
+ const sorted = body
287
+ .map((row, index) => ({ row, index, r: rank(row) }))
288
+ .sort((a, b) => (a.r - b.r) || (a.index - b.index))
289
+ .map((entry) => entry.row)
290
+ return [...sorted, header]
291
+ }
292
+
251
293
  export function findPanelNav(root: QueryRoot): ElementLike | null {
252
294
  for (const label of PANELS_LABELS) {
253
295
  const byLabel = root.querySelector(`nav[aria-label="${label}"]`)
@@ -698,6 +740,102 @@ function openMoreList(): void {
698
740
  ;(anchor as HTMLElement).click()
699
741
  }
700
742
 
743
+ // --- Row reorder (HTML5 DnD on the live sidebar rows) -----------------------
744
+
745
+ /** Registered by index.ts / the settings card to learn when a sidebar drag commits a new order. */
746
+ const orderListeners = new Set<(order: string[]) => void>()
747
+ let dragSourceLabel: string | null = null
748
+
749
+ /** Subscribe to order changes originating from the sidebar DOM. */
750
+ export function subscribeOrder(listener: (order: string[]) => void): () => void {
751
+ orderListeners.add(listener)
752
+ return () => { orderListeners.delete(listener) }
753
+ }
754
+
755
+ /** Publish a new order from a sidebar drag and persist it in our config. */
756
+ function notifyOrderChange(order: string[]): void {
757
+ config = { ...config, orderLabels: [...order] }
758
+ for (const listener of Array.from(orderListeners)) listener([...order])
759
+ }
760
+
761
+ /**
762
+ * Wire one panel row for HTML5 drag-and-drop. Idempotent: an `ATTR.dnd` mark
763
+ * prevents duplicate listeners across the many rescan passes. The "More" header
764
+ * is never wired (it stays the fold toggle). Drop commits the reordered label
765
+ * list; the settings card and index.ts both observe it via subscribeOrder.
766
+ */
767
+ function bindRowDrag(row: ElementLike, isHeader: boolean): void {
768
+ if (isHeader || row.getAttribute(ATTR.dnd) !== null) return
769
+ const el = row as unknown as HTMLElement
770
+ el.setAttribute(ATTR.dnd, '')
771
+ el.setAttribute('draggable', 'true')
772
+ const label = labelOf(row)
773
+ if (label === '') return
774
+ el.addEventListener('dragstart', (e: any) => {
775
+ dragSourceLabel = label
776
+ el.classList?.add(CLS.rowDrag)
777
+ if (e?.dataTransfer) e.dataTransfer.effectAllowed = 'move'
778
+ })
779
+ el.addEventListener('dragover', (e: any) => {
780
+ if (dragSourceLabel === null || dragSourceLabel === label) return
781
+ e?.preventDefault?.()
782
+ if (e?.dataTransfer) e.dataTransfer.dropEffect = 'move'
783
+ el.classList?.add(CLS.rowDragOver)
784
+ })
785
+ el.addEventListener('dragleave', () => {
786
+ el.classList?.remove(CLS.rowDragOver)
787
+ })
788
+ el.addEventListener('drop', (e: any) => {
789
+ e?.preventDefault?.()
790
+ el.classList?.remove(CLS.rowDragOver)
791
+ if (dragSourceLabel === null || dragSourceLabel === label) return
792
+ const all = rowsOf(mount?.nav ?? (el.closest?.(SEL.panelList) as ElementLike))
793
+ if (all.length === 0) return
794
+ const labels = all.map(labelOf)
795
+ const next = reorderLabels(labels, dragSourceLabel, label)
796
+ dragSourceLabel = null
797
+ if (next.some((value) => value === '')) return
798
+ applyOrder(all, next)
799
+ notifyOrderChange(next)
800
+ })
801
+ el.addEventListener('dragend', () => {
802
+ dragSourceLabel = null
803
+ el.classList?.remove(CLS.rowDrag)
804
+ el.classList?.remove(CLS.rowDragOver)
805
+ })
806
+ }
807
+
808
+ /** Wire every live row for reordering (called on each apply pass, idempotent). */
809
+ function bindRowDrags(rows: readonly ElementLike[]): void {
810
+ if (rows.length < 2) return
811
+ const header = rows.find((row) => row.getAttribute('aria-haspopup') === 'menu') ?? rows[rows.length - 1]
812
+ for (const row of rows) bindRowDrag(row, row === header)
813
+ }
814
+
815
+ /**
816
+ * Reorder the nav's rows in place to match the persisted label order.
817
+ *
818
+ * Mutation-safe: a row is moved only when its position actually differs from
819
+ * the target. The host owns these nodes (React), so we only re-parent them —
820
+ * never clone, never replace — and the "More" header stays at the end.
821
+ */
822
+ function applyOrder(rows: readonly ElementLike[], orderLabels: readonly string[]): void {
823
+ if (orderLabels.length === 0) return
824
+ const target = orderedRows(rows, orderLabels)
825
+ if (target.length !== rows.length) return
826
+ const parent = rows[0]?.parentElement
827
+ if (parent == null) return
828
+ // Walk the target order and insert each row before its successor; insertBefore
829
+ // of a node already in place is a no-op in the DOM, so no mutation is emitted.
830
+ for (let i = target.length - 2; i >= 0; i--) {
831
+ const row = target[i]
832
+ const next = target[i + 1]
833
+ if ((row as any).nextElementSibling !== next) {
834
+ try { (parent as any).insertBefore(row, next) } catch { /* host may re-render */ }
835
+ }
836
+ }
837
+ }
838
+
701
839
  /**
702
840
  * Write the fold marks. Only attributes we own are touched: no host class,
703
841
  * no host attribute, and never the anchor's `aria-expanded` (that one is the
@@ -709,6 +847,11 @@ function applyFold(): void {
709
847
  const plan = planFold(rows, config.keepLabels, config.hideLabels, currentFolded(), isRail(mount.nav))
710
848
  if (plan === null) return
711
849
  const { header } = plan
850
+ // Reorder the live rows to the persisted order before any fold marks are
851
+ // written. insertBefore is idempotent (only moves when the order differs) so
852
+ // the MutationObserver cannot self-trigger an endless rescan loop.
853
+ applyOrder(rows, config.orderLabels)
854
+ bindRowDrags(rows)
712
855
  if (header.getAttribute(ATTR.header) === null) header.setAttribute(ATTR.header, '')
713
856
  // Alignment is one nav-level mark with three rule sets behind it. Written on
714
857
  // every scan (and only when it differs) so a settings write repaints the row
@@ -828,6 +971,11 @@ function unmount(): void {
828
971
  for (const row of Array.from(nav.querySelectorAll?.(`[${ATTR.folded}]`) ?? []) as ElementLike[]) {
829
972
  row.removeAttribute(ATTR.folded)
830
973
  }
974
+ for (const row of Array.from(nav.querySelectorAll?.(`[${ATTR.dnd}]`) ?? []) as ElementLike[]) {
975
+ row.removeAttribute(ATTR.dnd)
976
+ row.removeAttribute('draggable')
977
+ ;(row as unknown as HTMLElement).classList?.remove(CLS.rowDrag, CLS.rowDragOver)
978
+ }
831
979
  mount = null
832
980
  }
833
981
 
@@ -893,6 +1041,11 @@ function sweep(): void {
893
1041
  for (const row of Array.from(document.querySelectorAll(`[${ATTR.folded}]`)) as ElementLike[]) {
894
1042
  row.removeAttribute(ATTR.folded)
895
1043
  }
1044
+ for (const row of Array.from(document.querySelectorAll(`[${ATTR.dnd}]`)) as ElementLike[]) {
1045
+ row.removeAttribute(ATTR.dnd)
1046
+ row.removeAttribute('draggable')
1047
+ ;(row as unknown as HTMLElement).classList?.remove(CLS.rowDrag, CLS.rowDragOver)
1048
+ }
896
1049
  mount = null
897
1050
  // The pin bookkeeping belongs to one window's DOM; a remount starts from what
898
1051
  // the host shows now, never from a count that may no longer refer to it.
@@ -1014,6 +1167,7 @@ function copyConfig(cfg: ConfigLike): ConfigLike {
1014
1167
  // dropped on the way in instead of being retried on every scan.
1015
1168
  hideLabels: pruneHidden(cfg.hideLabels),
1016
1169
  align: normalizeAlign(cfg.align),
1170
+ orderLabels: [...(cfg.orderLabels ?? [])],
1017
1171
  }
1018
1172
  }
1019
1173
 
@@ -1028,4 +1182,5 @@ export const BUILTIN_CONFIG: ConfigLike = {
1028
1182
  keepLabels: ['插件', 'Plugins'],
1029
1183
  hideLabels: [],
1030
1184
  align: 'start',
1031
- }
1185
+ orderLabels: [],
1186
+ }
@@ -12,7 +12,7 @@
12
12
  * pending and the plugin silently inert.
13
13
  */
14
14
  import { PKG_NAME } from './constants.ts'
15
- import { applyConfig, BUILTIN_CONFIG, installFold, normalizeAlign, rescan } from './fold.ts'
15
+ import { applyConfig, BUILTIN_CONFIG, effectiveConfig, installFold, normalizeAlign, rescan, subscribeOrder } from './fold.ts'
16
16
  import { createSettingsRow, adoptPluginNavigation } from './menu-entry.ts'
17
17
  import { createConfigCard, onFallback, onScope, type SettingsScopeLike } from './settings-card.ts'
18
18
 
@@ -47,6 +47,12 @@ function safe(tag: string, fn: () => void): void {
47
47
  /** Adopt a served snapshot, falling back to the built-ins when it says nothing. */
48
48
  function adopt(scope: SettingsScopeLike): void {
49
49
  onScope(scope)
50
+ // A sidebar drag publishes the new order here; commit it through the same
51
+ // scoped form so the card and the sidebar share one persisted source.
52
+ subscribeOrder((order) => {
53
+ applyConfig({ ...effectiveConfig(), orderLabels: order })
54
+ void scope.set('orderLabels', order)
55
+ })
50
56
  const push = (): void => {
51
57
  const snap = scope.getSnapshot()
52
58
  const value = snap.value
@@ -59,6 +65,8 @@ function adopt(scope: SettingsScopeLike): void {
59
65
  // Alignment is validated by `normalizeAlign` here so everything downstream
60
66
  // (fold marks, card radios) only ever sees one of the three known modes.
61
67
  align: normalizeAlign(typeof value?.align === 'string' ? value.align : BUILTIN_CONFIG.align),
68
+ // Row order: absent on older hosts means keep the shipped DOM order.
69
+ orderLabels: Array.isArray(value?.orderLabels) ? value.orderLabels : BUILTIN_CONFIG.orderLabels,
62
70
  }
63
71
  onFallback(next)
64
72
  applyConfig(next)
@@ -220,4 +228,4 @@ export function apply(ctx: ClientCtx): void {
220
228
  disposer = null
221
229
  console.info(`${PKG_NAME}: fold removed`)
222
230
  }, `${PKG_NAME}: sidebar fold`)
223
- }
231
+ }
@@ -17,6 +17,8 @@ export const zh = {
17
17
  'settings.defaultFoldedHint': '新窗口在没有本地记录时采用的初始状态',
18
18
  'settings.rows': '入口行',
19
19
  'settings.rowsHint': '每行三档:显示=一直显示;折叠=允许折叠;隐藏到更多=移进「更多」菜单。',
20
+ 'settings.rowDrag': '拖动入口行可排序(「更多」固定末尾)',
21
+ 'settings.rowDragHint': '按住入口行拖到目标位置,顺序会保存到设置。',
20
22
  'settings.rowAlways': '显示',
21
23
  'settings.rowFold': '折叠',
22
24
  'settings.rowMore': '隐藏到更多',
@@ -48,6 +50,8 @@ export const en: Record<LocaleKey, string> = {
48
50
  'settings.defaultFoldedHint': 'Initial state for a window with no local record yet',
49
51
  'settings.rows': 'Entries',
50
52
  '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.',
53
+ 'settings.rowDrag': 'Drag entry rows to reorder (“More” stays last)',
54
+ 'settings.rowDragHint': 'Drag a row onto another to reorder; the order is saved to settings.',
51
55
  'settings.rowAlways': 'Show',
52
56
  'settings.rowFold': 'Fold',
53
57
  'settings.rowMore': 'Hide in More',
@@ -76,6 +80,8 @@ export const ja: Record<LocaleKey, string> = {
76
80
  'settings.defaultFoldedHint': 'ローカル記録がないウィンドウの初期状態',
77
81
  'settings.rows': '項目',
78
82
  'settings.rowsHint': '行ごとに3段階:表示=常に表示、折りたたみ=折りたたみ可、「その他」へ隠す=「その他」メニューへ移動。',
83
+ 'settings.rowDrag': '項目行をドラッグして並べ替え(「その他」は末尾固定)',
84
+ 'settings.rowDragHint': '行を別の行へドラッグすると並びが変わり、設定に保存されます。',
79
85
  'settings.rowAlways': '表示',
80
86
  'settings.rowFold': '折りたたみ',
81
87
  'settings.rowMore': '「その他」へ隠す',
@@ -104,6 +110,8 @@ export const ko: Record<LocaleKey, string> = {
104
110
  'settings.defaultFoldedHint': '로컬 기록이 없는 창의 초기 상태',
105
111
  'settings.rows': '항목',
106
112
  'settings.rowsHint': '행마다 3단계: 표시=항상 표시, 접기=접기 허용, 더 보기에 숨기기=“더 보기” 메뉴로 이동.',
113
+ 'settings.rowDrag': '항목 행을 끌어 순서 변경 (“더 보기”는 항상 마지막)',
114
+ 'settings.rowDragHint': '행을 다른 행으로 끌어 순서를 바꾸면 설정에 저장됩니다.',
107
115
  'settings.rowAlways': '표시',
108
116
  'settings.rowFold': '접기',
109
117
  'settings.rowMore': '더 보기에 숨기기',
@@ -132,6 +140,8 @@ export const fr: Record<LocaleKey, string> = {
132
140
  'settings.defaultFoldedHint': 'État initial d’une fenêtre sans enregistrement local',
133
141
  'settings.rows': 'Entrées',
134
142
  '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 ».',
143
+ 'settings.rowDrag': 'Faites glisser les lignes pour réordonner (« Plus » reste en fin)',
144
+ 'settings.rowDragHint': 'Glissez une ligne sur une autre pour changer l’ordre ; il est enregistré dans les réglages.',
135
145
  'settings.rowAlways': 'Afficher',
136
146
  'settings.rowFold': 'Replier',
137
147
  'settings.rowMore': 'Masquer dans « Plus »',
@@ -160,6 +170,8 @@ export const de: Record<LocaleKey, string> = {
160
170
  'settings.defaultFoldedHint': 'Anfangszustand eines Fensters ohne lokalen Eintrag',
161
171
  'settings.rows': 'Einträge',
162
172
  '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“.',
173
+ 'settings.rowDrag': 'Zeilen zum Neuanordnen ziehen („Mehr“ bleibt am Ende)',
174
+ 'settings.rowDragHint': 'Ziehen Sie eine Zeile auf eine andere; die Reihenfolge wird in den Einstellungen gespeichert.',
163
175
  'settings.rowAlways': 'Anzeigen',
164
176
  'settings.rowFold': 'Einklappen',
165
177
  'settings.rowMore': 'In „Mehr“ ausblenden',
@@ -188,6 +200,8 @@ export const it: Record<LocaleKey, string> = {
188
200
  'settings.defaultFoldedHint': 'Stato iniziale di una finestra senza record locale',
189
201
  'settings.rows': 'Voci',
190
202
  'settings.rowsHint': 'Tre stati per riga: Mostra resta visibile, Comprimi lascia che la compressione la nasconda, Nascondi in «Altro» la sposta nel menu «Altro».',
203
+ 'settings.rowDrag': 'Trascina le righe per riordinarle («Altro» resta in fondo)',
204
+ 'settings.rowDragHint': 'Trascina una riga su un’altra per cambiare l’ordine, salvato nelle impostazioni.',
191
205
  'settings.rowAlways': 'Mostra',
192
206
  'settings.rowFold': 'Comprimi',
193
207
  'settings.rowMore': 'Nascondi in «Altro»',
@@ -216,6 +230,8 @@ export const ru: Record<LocaleKey, string> = {
216
230
  'settings.defaultFoldedHint': 'Начальное состояние окна без локальной записи',
217
231
  'settings.rows': 'Пункты',
218
232
  'settings.rowsHint': 'Три состояния на строку: Показывать оставляет её видимой, Сворачивать позволяет её скрыть, Скрыть в «Ещё» переносит её в меню «Ещё».',
233
+ 'settings.rowDrag': 'Перетаскивайте строки для изменения порядка («Ещё» всегда последняя)',
234
+ 'settings.rowDragHint': 'Перетащите строку на другую — порядок сохранится в настройках.',
219
235
  'settings.rowAlways': 'Показывать',
220
236
  'settings.rowFold': 'Сворачивать',
221
237
  'settings.rowMore': 'Скрыть в «Ещё»',
@@ -244,6 +260,8 @@ export const es: Record<LocaleKey, string> = {
244
260
  'settings.defaultFoldedHint': 'Estado inicial de una ventana sin registro local',
245
261
  'settings.rows': 'Entradas',
246
262
  '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».',
263
+ 'settings.rowDrag': 'Arrastre las filas para reordenar («Más» siempre al final)',
264
+ 'settings.rowDragHint': 'Arrastre una fila sobre otra para cambiar el orden; se guarda en los ajustes.',
247
265
  'settings.rowAlways': 'Mostrar',
248
266
  'settings.rowFold': 'Plegar',
249
267
  'settings.rowMore': 'Ocultar en «Más»',
@@ -273,6 +291,8 @@ export const pt: Record<LocaleKey, string> = {
273
291
  'settings.defaultFoldedHint': 'Estado inicial de uma janela sem registro local',
274
292
  'settings.rows': 'Entradas',
275
293
  '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».',
294
+ 'settings.rowDrag': 'Arraste as linhas para reordenar («Mais» fica no fim)',
295
+ 'settings.rowDragHint': 'Arraste uma linha para outra para mudar a ordem; ela é salva nas configurações.',
276
296
  'settings.rowAlways': 'Mostrar',
277
297
  'settings.rowFold': 'Recolher',
278
298
  'settings.rowMore': 'Ocultar em «Mais»',
@@ -327,4 +347,4 @@ export function pickDictionary(lang: string): Record<LocaleKey, string> {
327
347
  if (tag.startsWith(candidate)) return dictionaries[candidate]
328
348
  }
329
349
  return en
330
- }
350
+ }
@@ -20,6 +20,7 @@
20
20
  */
21
21
  import { ATTR, CLS, type AlignMode } from './constants.ts'
22
22
  import { pickDictionary } from './locales.ts'
23
+ import { mountStarRow } from './star-row-copy.ts'
23
24
  import {
24
25
  applyConfig,
25
26
  canMoveToMore,
@@ -28,6 +29,7 @@ import {
28
29
  hostHasPin,
29
30
  isFixedLabel,
30
31
  normalizeAlign,
32
+ reorderLabels,
31
33
  roster,
32
34
  subscribeRoster,
33
35
  type RowState,
@@ -40,7 +42,7 @@ const react: any = require('react')
40
42
  /** One settings snapshot as the host's scoped form reports it. */
41
43
  export interface ConfigSnapshot {
42
44
  status: 'loading' | 'ready' | 'unavailable'
43
- value: { defaultFolded?: boolean; keepLabels?: string[]; hideLabels?: string[]; align?: string } | undefined
45
+ value: { defaultFolded?: boolean; keepLabels?: string[]; hideLabels?: string[]; align?: string; orderLabels?: string[] } | undefined
44
46
  revision: number | undefined
45
47
  writable: boolean
46
48
  }
@@ -56,11 +58,12 @@ export interface SettingsScopeLike {
56
58
  const scopeRef: { scope: SettingsScopeLike | undefined } = { scope: undefined }
57
59
 
58
60
  /** Fallback shown when no host form is served (≤0.1.6, or an unserved namespace). */
59
- let fallback: { defaultFolded: boolean; keepLabels: string[]; hideLabels: string[]; align: AlignMode } = {
61
+ let fallback: { defaultFolded: boolean; keepLabels: string[]; hideLabels: string[]; align: AlignMode; orderLabels: string[] } = {
60
62
  defaultFolded: false,
61
63
  keepLabels: ['插件', 'Plugins'],
62
64
  hideLabels: [],
63
65
  align: 'start',
66
+ orderLabels: [],
64
67
  }
65
68
 
66
69
  /** The card body node, created once and re-used by every mount. */
@@ -82,6 +85,7 @@ function currentValues(): {
82
85
  keepLabels: string[]
83
86
  hideLabels: string[]
84
87
  align: AlignMode
88
+ orderLabels: string[]
85
89
  writable: boolean
86
90
  status: ConfigSnapshot['status']
87
91
  } {
@@ -93,6 +97,7 @@ function currentValues(): {
93
97
  keepLabels: snap.value?.keepLabels ?? fallback.keepLabels,
94
98
  hideLabels: snap.value?.hideLabels ?? fallback.hideLabels,
95
99
  align: normalizeAlign(snap.value?.align ?? fallback.align),
100
+ orderLabels: Array.isArray(snap.value?.orderLabels) ? snap.value.orderLabels : fallback.orderLabels,
96
101
  writable: snap.writable && snap.status === 'ready',
97
102
  status: snap.status,
98
103
  }
@@ -102,6 +107,7 @@ function currentValues(): {
102
107
  keepLabels: fallback.keepLabels,
103
108
  hideLabels: fallback.hideLabels,
104
109
  align: normalizeAlign(fallback.align),
110
+ orderLabels: fallback.orderLabels,
105
111
  writable: false,
106
112
  status: 'unavailable',
107
113
  }
@@ -271,6 +277,79 @@ function writeRowState(rows: ReturnType<typeof roster>, label: string, next: Row
271
277
  commit({ keepLabels: lists.keepLabels, hideLabels: lists.hideLabels })
272
278
  }
273
279
 
280
+ /**
281
+ * Attach a drag handle to a settings row so the visible list can be reordered.
282
+ *
283
+ * The row itself is the drag source and drop target; both surfaces (sidebar and
284
+ * card) compute the next order via reorderLabels and commit through write().
285
+ */
286
+ function makeDraggableRow(row: HTMLElement, label: string, rows: ReturnType<typeof roster>): HTMLElement {
287
+ row.setAttribute('draggable', 'true')
288
+ row.classList.add(CLS.rowDrag)
289
+ let source = ''
290
+ row.addEventListener('dragstart', (e: any) => {
291
+ source = label
292
+ if (e?.dataTransfer) e.dataTransfer.effectAllowed = 'move'
293
+ })
294
+ row.addEventListener('dragover', (e: any) => {
295
+ if (source === '' || source === label) return
296
+ e?.preventDefault?.()
297
+ if (e?.dataTransfer) e.dataTransfer.dropEffect = 'move'
298
+ row.classList.add(CLS.rowDragOver)
299
+ })
300
+ row.addEventListener('dragleave', () => row.classList.remove(CLS.rowDragOver))
301
+ row.addEventListener('drop', (e: any) => {
302
+ e?.preventDefault?.()
303
+ row.classList.remove(CLS.rowDragOver)
304
+ if (source === '' || source === label) return
305
+ const labels = rows.map((entry) => entry.label)
306
+ const next = reorderLabels(labels, source, label)
307
+ source = ''
308
+ // Local optimistic reorder: repaint the roster in the new order first, then
309
+ // persist it through the same commit() path as the three-state writes.
310
+ const rank = new Map(next.map((value, index) => [value, index]))
311
+ const reordered = [...rows].sort((a, b) => (rank.get(a.label) ?? 0) - (rank.get(b.label) ?? 0))
312
+ for (const entry of reordered) {
313
+ // Build a fresh row for each entry in the new order.
314
+ cardRoot?.appendChild(buildEntry(entry, reordered))
315
+ }
316
+ commit({ orderLabels: next })
317
+ })
318
+ row.addEventListener('dragend', () => {
319
+ source = ''
320
+ row.classList.remove(CLS.rowDragOver)
321
+ })
322
+ return row
323
+ }
324
+
325
+ /** Build one three-state entry row (shared by paint and the DnD repaint). */
326
+ function buildEntry(entry: ReturnType<typeof roster>[number], rows: ReturnType<typeof roster>): HTMLElement {
327
+ const canHide = hostHasPin()
328
+ const movable = canMoveToMore(entry.label, canHide)
329
+ const hintText = movable
330
+ ? pickDictionary(document.documentElement.lang ?? '')['settings.rowHint']
331
+ : isFixedLabel(entry.label)
332
+ ? pickDictionary(document.documentElement.lang ?? '')['settings.moreFixed']
333
+ : pickDictionary(document.documentElement.lang ?? '')['settings.moreUnavailable']
334
+ const dict = pickDictionary(document.documentElement.lang ?? '')
335
+ const built = buildRow(
336
+ entry.label,
337
+ hintText,
338
+ segmentedControl(
339
+ `row:${entry.label}`,
340
+ entry.state,
341
+ [
342
+ { value: 'always', label: dict['settings.rowAlways'] },
343
+ { value: 'foldable', label: dict['settings.rowFold'] },
344
+ { value: 'more', label: dict['settings.rowMore'], unavailable: !movable },
345
+ ],
346
+ !currentValues().writable,
347
+ (next) => writeRowState(rows, entry.label, next as RowState),
348
+ ),
349
+ )
350
+ return makeDraggableRow(built, entry.label, rows)
351
+ }
352
+
274
353
  /** Paint (or repaint) the card body from the current values and the live roster. */
275
354
  function paint(): void {
276
355
  if (cardRoot === null) return
@@ -318,6 +397,12 @@ function paint(): void {
318
397
  scopeTitle.textContent = dict['settings.rows']
319
398
  cardRoot.appendChild(scopeTitle)
320
399
 
400
+ const dragHint = document.createElement('span')
401
+ dragHint.className = CLS.hint
402
+ dragHint.setAttribute(ATTR.own, '')
403
+ dragHint.textContent = dict['settings.rowDrag'] + ' — ' + dict['settings.rowDragHint']
404
+ cardRoot.appendChild(dragHint)
405
+
321
406
  const hint = document.createElement('span')
322
407
  hint.className = CLS.hint
323
408
  hint.setAttribute(ATTR.own, '')
@@ -335,31 +420,8 @@ function paint(): void {
335
420
  // Two gates on the third state, per row: this host must ship the pin mechanism
336
421
  // at all (0.2.2 on), and the row must not be the host's fixed panel — the host
337
422
  // never unpins that one, so offering it would be a promise it silently refuses.
338
- const canHide = hostHasPin()
339
423
  for (const entry of rows) {
340
- const movable = canMoveToMore(entry.label, canHide)
341
- const hintText = movable
342
- ? dict['settings.rowHint']
343
- : isFixedLabel(entry.label) ? dict['settings.moreFixed'] : dict['settings.moreUnavailable']
344
- cardRoot.appendChild(
345
- buildRow(
346
- entry.label,
347
- hintText,
348
- segmentedControl(
349
- `row:${entry.label}`,
350
- entry.state,
351
- [
352
- { value: 'always', label: dict['settings.rowAlways'] },
353
- { value: 'foldable', label: dict['settings.rowFold'] },
354
- { value: 'more', label: dict['settings.rowMore'], unavailable: !movable },
355
- ],
356
- !values.writable,
357
- (next) => {
358
- writeRowState(rows, entry.label, next as RowState)
359
- },
360
- ),
361
- ),
362
- )
424
+ cardRoot.appendChild(buildEntry(entry, rows))
363
425
  }
364
426
 
365
427
  // ④ write outcome. The host owns persistence; a refused write leaves the card
@@ -395,6 +457,11 @@ function paint(): void {
395
457
  note.textContent = dict['settings.readonly']
396
458
  cardRoot.appendChild(note)
397
459
  }
460
+
461
+ // star 快车道行(单源 _tools/star-row,改副本无效;重渲染随 cardRoot 一起重建)
462
+ const starRow = mountStarRow()
463
+ starRow.setAttribute(ATTR.own, '')
464
+ cardRoot.appendChild(starRow)
398
465
  }
399
466
 
400
467
  /**
@@ -416,6 +483,7 @@ export function onFallback(next: typeof fallback): void {
416
483
  keepLabels: [...next.keepLabels],
417
484
  hideLabels: [...next.hideLabels],
418
485
  align: normalizeAlign(next.align),
486
+ orderLabels: [...(next.orderLabels ?? [])],
419
487
  }
420
488
  paint()
421
489
  }
@@ -448,4 +516,4 @@ export function createConfigCard(): () => unknown {
448
516
  }
449
517
 
450
518
  /** Exported for the guard test: the card writes no free-text label list. */
451
- export const CARD_WRITES: readonly string[] = ['defaultFolded', 'align', 'keepLabels', 'hideLabels']
519
+ export const CARD_WRITES: readonly string[] = ['defaultFolded', 'align', 'keepLabels', 'hideLabels', 'orderLabels']