Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 42 additions & 5 deletions web/src/directoryOrder.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,31 @@
import type { Asset, LedgerState } from './types.ts';
import type { Asset, BackupRecord, LedgerState } from './types.ts';
import { latestBackupForAsset } from './selectors.ts';
export type DirectorySort = 'manual' | 'name-asc' | 'name-desc' | 'newest' | 'oldest';
import { buildHierarchy } from './hierarchy.ts';
import type { Hierarchy } from './hierarchy.ts';
export type DirectorySort = 'manual' | 'name-asc' | 'name-desc' | 'newest' | 'oldest' | 'notes-asc' | 'notes-desc';
export type DirectorySortColumn = 'name' | 'backup' | 'notes';
const columnSorts = {
name: ['name-asc', 'name-desc'],
backup: ['oldest', 'newest'],
notes: ['notes-asc', 'notes-desc'],
} as const;
export function directoryColumnSort(mode: DirectorySort, column: DirectorySortColumn) {
const [ascending, descending] = columnSorts[column];
const direction = mode === ascending ? 'ascending' : mode === descending ? 'descending' : 'none';
return {direction, next: mode === ascending ? descending : ascending} as const;
}
export function latestDirectoryBackup(state: LedgerState, assetId: string, tree: Hierarchy = buildHierarchy(state.assets)): BackupRecord | undefined {
if (tree.isLeaf(assetId)) return latestBackupForAsset(state, assetId);
let latest: BackupRecord | undefined;
for (const child of tree.leafDescendants(assetId)) {
if (child.backup_target !== true) continue;
const record = latestBackupForAsset(state, child.id);
if (record && (!latest || Date.parse(record.backed_up_at) > Date.parse(latest.backed_up_at))) latest = record;
}
return latest;
}
const byName = (a: Asset, b: Asset) => a.name.localeCompare(b.name, 'zh-CN') || a.id.localeCompare(b.id);
const compareNotes = new Intl.Collator('zh-CN', {numeric: true}).compare;
function portableTextOrder(left:string,right:string):number {
const a=Array.from(left),b=Array.from(right);
for(let index=0;index<Math.min(a.length,b.length);index++){
Expand All @@ -12,9 +36,17 @@ function portableTextOrder(left:string,right:string):number {
}
export function sortDirectoryAssets(state: LedgerState, assets: Asset[], mode: DirectorySort): Asset[] {
const times = new Map<string, number>();
if (mode === 'newest' || mode === 'oldest') for (const asset of assets) {
const latest = latestBackupForAsset(state, asset.id);
times.set(asset.id, latest ? Date.parse(latest.backed_up_at) : -Infinity);
const notes = new Map<string, string>();
if (mode === 'newest' || mode === 'oldest' || mode === 'notes-asc' || mode === 'notes-desc') {
const tree = buildHierarchy(state.assets);
for (const asset of assets) {
if (mode === 'notes-asc' || mode === 'notes-desc') {
notes.set(asset.id, asset.backup_target === true && tree.isLeaf(asset.id) ? latestBackupForAsset(state, asset.id)?.notes?.trim() ?? '' : '');
} else {
const latest = latestDirectoryBackup(state, asset.id, tree);
times.set(asset.id, latest ? Date.parse(latest.backed_up_at) : -Infinity);
}
}
}
return [...assets].sort((a, b) => {
if (mode === 'manual') {
Expand All @@ -25,6 +57,11 @@ export function sortDirectoryAssets(state: LedgerState, assets: Asset[], mode: D
}
if (mode === 'name-desc') return byName(b,a);
if (mode === 'name-asc') return byName(a,b);
if (mode === 'notes-asc' || mode === 'notes-desc') {
const left = notes.get(a.id)!, right = notes.get(b.id)!;
if (!left || !right) return Number(!left) - Number(!right) || byName(a,b);
return (mode === 'notes-asc' ? compareNotes(left,right) : compareNotes(right,left)) || byName(a,b);
}
const difference = mode === 'newest' ? times.get(b.id)! - times.get(a.id)! : times.get(a.id)! - times.get(b.id)!;
return difference || byName(a,b);
});
Expand Down
33 changes: 23 additions & 10 deletions web/src/features/Overview.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,26 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { ArrowUp, ChevronRight, File, FilePlus2, Folder, FolderPlus, GripVertical, ListPlus, Search } from 'lucide-react';
import type { ReactNode } from 'react';
import { ArrowDown, ArrowUp, ArrowUpDown, ChevronRight, File, FilePlus2, Folder, FolderPlus, GripVertical, ListPlus, Search } from 'lucide-react';
import { buildHierarchy } from '../hierarchy';
import { formatTime, latestBackupForAsset } from '../selectors';
import { formatTime } from '../selectors';
import type { Asset, LedgerState } from '../types';
import { EmptyState, PageHeading } from '../components/ui';
import { AssetDetail } from './AssetDetail';
import { ActionMenu } from '../components/ActionMenu';
import { advanceDirectoryDrag, finishDirectoryDrag, moveDirectoryAsset, sortDirectoryAssets, startDirectoryDrag } from '../directoryOrder';
import type { DirectoryDrag, DirectorySort } from '../directoryOrder';
import { advanceDirectoryDrag, directoryColumnSort, finishDirectoryDrag, latestDirectoryBackup, moveDirectoryAsset, sortDirectoryAssets, startDirectoryDrag } from '../directoryOrder';
import type { DirectoryDrag, DirectorySort, DirectorySortColumn } from '../directoryOrder';
import { directoryNavigation, searchDirectoryAssets } from '../directoryTools';
import type { DirectorySearchScope } from '../directoryTools';

function SortHeading({column, label, sort, disabled, onSort, children}: {
column: DirectorySortColumn; label: string; sort: DirectorySort; disabled: boolean;
onSort: (sort: DirectorySort) => void; children?: ReactNode;
}) {
const {direction, next} = directoryColumnSort(sort, column);
const Icon = direction === 'ascending' ? ArrowUp : direction === 'descending' ? ArrowDown : ArrowUpDown;
return <th aria-sort={direction}><div className="directory-sort-heading">{children}<button type="button" className="directory-sort-button" disabled={disabled} aria-label={`按${label}${direction === 'ascending' ? '降序' : '升序'}排序`} onClick={() => onSort(next)}>{label}<Icon size={14} aria-hidden="true" /></button></div></th>;
}

interface OverviewActions {
state: LedgerState; folderId: string | null;
onFolder: (id: string | null) => void;
Expand Down Expand Up @@ -66,13 +76,11 @@ export function Overview(actions: OverviewActions) {
const showBackupNotes = visibleAssets.some(asset => asset.backup_target === true && tree.isLeaf(asset.id));
const rows = visibleAssets.map(asset => {
const leaf = tree.isLeaf(asset.id);
const latest = leaf ? latestBackupForAsset(state, asset.id) : tree.leafDescendants(asset.id)
.filter(entry => entry.backup_target === true)
.flatMap(entry => { const record = latestBackupForAsset(state, entry.id); return record ? [record] : []; })
.sort((a, b) => Date.parse(b.backed_up_at) - Date.parse(a.backed_up_at))[0];
const latest = latestDirectoryBackup(state, asset.id, tree);
return {asset, leaf, latest};
});
const canReorder = sort === 'manual' && !keyword.trim() && !pending && !bulkSelecting;
const changeSort = (mode: DirectorySort) => { cancelDrag(); setSort(mode); };
const selectableIds=rows.filter(({asset,leaf})=>leaf?asset.backup_target===true:tree.leafDescendants(asset.id).some(child=>child.backup_target===true)).map(({asset})=>asset.id);
const selectedVisible=selectableIds.filter(id=>selected.includes(id));
const allSelected=selectableIds.length>0&&selectedVisible.length===selectableIds.length;
Expand Down Expand Up @@ -107,7 +115,7 @@ export function Overview(actions: OverviewActions) {
};
return <><PageHeading title="资料目录" action={folder?.kind !== 'file' ? <div className="heading-actions">{actions.onBulk&&!showingRecords?bulkSelecting?<><button className="button primary" disabled={!selectedVisible.length||pending} onClick={registerSelected}><ListPlus size={18}/>{selectedVisible.length?`登记所选(${selectedVisible.length})`:'登记所选'}</button>{actions.onPaste?<button className="button secondary" onClick={()=>{cancelSelection();actions.onPaste!();}}>粘贴表格</button>:null}<button className="button secondary" aria-label="取消批量登记" onClick={cancelSelection}>取消</button></>:<button className="button secondary" onClick={()=>{cancelDrag();setSelected([]);setBulkSelecting(true);}}><ListPlus size={18}/>批量登记</button>:null}{!bulkSelecting?<><button className="button secondary" onClick={() => actions.onCreate('file', folderId)}><FilePlus2 size={19} />添加文件</button><button className="button primary" onClick={() => actions.onCreate('folder', folderId)}><FolderPlus size={20} />新建文件夹</button></>:null}</div> : undefined} />
<div className="directory-toolbar"><nav className="breadcrumbs" aria-label="资料目录路径">{folder ? <button className="up-button" aria-label="返回上级目录" onClick={() => actions.onFolder(folder.parent_id ?? null)}><ArrowUp size={18} /></button> : null}<button onClick={() => actions.onFolder(null)}>全部资料</button>{[...ancestors, ...(folder ? [folder] : [])].map((entry, index, all) => <span key={entry.id}><ChevronRight size={16} />{index === all.length - 1 ? <strong aria-current="location">{entry.name}</strong> : <button onClick={() => actions.onFolder(entry.id)}>{entry.name}</button>}</span>)}</nav>
{showingRecords ? null : <div className="toolbar explorer-toolbar"><div className="directory-search"><select aria-label="搜索范围" value={searchScope} onChange={event => { setSearchScope(event.target.value as DirectorySearchScope); setSelected([]); }}><option value="current">当前目录</option><option value="all">全部资料</option></select><label className="search-field"><Search size={19} /><input aria-label={searchScope === 'all' ? '搜索全部资料' : '搜索当前目录'} placeholder={searchScope === 'all' ? '搜索全部资料' : '搜索当前目录'} value={keyword} onChange={event => { setKeyword(event.target.value); setSelected([]); }} /></label></div><select aria-label="目录排序" value={sort} onChange={e => { cancelDrag(); setSort(e.target.value as DirectorySort); }}><option value="manual">手动排序</option><option value="name-asc">名称升序</option><option value="name-desc">名称降序</option><option value="newest">最新备份优先</option><option value="oldest">最久未备份优先</option></select></div>}</div>
{showingRecords ? null : <div className="toolbar explorer-toolbar"><div className="directory-search"><select aria-label="搜索范围" value={searchScope} onChange={event => { setSearchScope(event.target.value as DirectorySearchScope); setSelected([]); }}><option value="current">当前目录</option><option value="all">全部资料</option></select><label className="search-field"><Search size={19} /><input aria-label={searchScope === 'all' ? '搜索全部资料' : '搜索当前目录'} placeholder={searchScope === 'all' ? '搜索全部资料' : '搜索当前目录'} value={keyword} onChange={event => { setKeyword(event.target.value); setSelected([]); }} /></label></div><select aria-label="目录排序" value={sort} onChange={e => changeSort(e.target.value as DirectorySort)}><option value="manual">手动排序</option><option value="name-asc">名称升序</option><option value="name-desc">名称降序</option><option value="newest">最新备份优先</option><option value="oldest">最久未备份优先</option><option value="notes-asc">备份说明升序</option><option value="notes-desc">备份说明降序</option></select></div>}</div>
{orderError ? <div className="connection-error" role="alert"><span>{orderError}</span><button className="button secondary compact" disabled={pending} onClick={()=>void actions.onRefresh().then(()=>setOrderError(''))}>刷新目录</button></div> : null}
{showingRecords ? <AssetDetail asset={folder} state={state} onEditRecords={() => actions.onEditRecords(folder.id)} onAddRecord={() => actions.onAddRecord(folder.id)} /> : <div className="surface explorer-surface" aria-busy={pending}>{!rows.length ? keyword ? <EmptyState title={searchingAll ? '没有匹配的资料' : '当前目录没有匹配的资料'} action={<button className="text-button" onClick={() => { setKeyword(''); setSelected([]); }}>清除搜索</button>} /> : <EmptyState title={folder ? '暂无下级资料' : '暂无资料'} action={folder ? <div className="empty-actions"><button className="button secondary" onClick={() => actions.onDetail(folder.id)}>备份信息</button><button className="button primary" disabled={actions.marking} onClick={() => actions.onMark(folder)}>设为备份对象</button></div> : undefined} /> : <table className={`explorer-table${showBackupNotes ? ' with-backup-notes' : ''}`}>
<colgroup>
Expand All @@ -116,7 +124,12 @@ export function Overview(actions: OverviewActions) {
{showBackupNotes ? <col className="directory-notes-column" /> : null}
<col className="directory-actions-column" />
</colgroup>
<thead><tr><th>{actions.onBulk&&bulkSelecting?<label className="directory-select-all"><input type="checkbox" aria-label={searchingAll ? '全选搜索结果备份资料' : '全选当前目录备份资料'} checked={allSelected} disabled={!selectableIds.length||pending} ref={node=>{if(node)node.indeterminate=selectedVisible.length>0&&!allSelected;}} onChange={()=>setSelected(current=>allSelected?current.filter(id=>!selectableIds.includes(id)):[...new Set([...current,...selectableIds])])}/><span>名称</span></label>:'名称'}</th><th>最新备份</th>{showBackupNotes ? <th>备份说明</th> : null}<th>操作</th></tr></thead><tbody>{rows.map(({asset, leaf, latest}) => {
<thead><tr>
<SortHeading column="name" label="名称" sort={sort} disabled={pending} onSort={changeSort}>{actions.onBulk&&bulkSelecting?<input type="checkbox" className="directory-selection" aria-label={searchingAll ? '全选搜索结果备份资料' : '全选当前目录备份资料'} checked={allSelected} disabled={!selectableIds.length||pending} ref={node=>{if(node)node.indeterminate=selectedVisible.length>0&&!allSelected;}} onChange={()=>setSelected(current=>allSelected?current.filter(id=>!selectableIds.includes(id)):[...new Set([...current,...selectableIds])])}/>:null}</SortHeading>
<SortHeading column="backup" label="最新备份" sort={sort} disabled={pending} onSort={changeSort} />
{showBackupNotes ? <SortHeading column="notes" label="备份说明" sort={sort} disabled={pending} onSort={changeSort} /> : null}
<th>操作</th>
</tr></thead><tbody>{rows.map(({asset, leaf, latest}) => {
const Icon = asset.kind === 'folder' ? Folder : File;
const marked = leaf && asset.backup_target === true;
const index=siblings.findIndex(entry=>entry.id===asset.id);
Expand Down
8 changes: 8 additions & 0 deletions web/src/styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,14 @@ td { padding: 16px; border-bottom: 1px solid var(--border); line-height: 1.5; ve
tbody tr:last-child td { border-bottom: 0; }
tbody tr:hover { background: #fcfdff; }
.explorer-table { table-layout: fixed; }
.directory-sort-heading { display: flex; align-items: center; justify-content: center; gap: 8px; }
.explorer-table th:first-child .directory-sort-heading { justify-content: flex-start; }
.directory-sort-button { display: inline-flex; align-items: center; gap: 6px; padding: 4px 0; border: 0; background: transparent; color: inherit; font: inherit; cursor: pointer; white-space: nowrap; }
.directory-sort-button svg { color: var(--muted); flex-shrink: 0; }
.directory-sort-button:hover, .explorer-table th[aria-sort="ascending"] .directory-sort-button, .explorer-table th[aria-sort="descending"] .directory-sort-button { color: var(--accent); }
.explorer-table th[aria-sort="ascending"] .directory-sort-button svg, .explorer-table th[aria-sort="descending"] .directory-sort-button svg { color: currentColor; }
.directory-sort-button:focus-visible { outline: 2px solid var(--accent); outline-offset: 4px; border-radius: 3px; }
.directory-sort-button:disabled { opacity: .5; cursor: wait; }
.explorer-table th:first-child { border-radius: 12px 0 0 0; }
.explorer-table th:last-child { border-radius: 0 12px 0 0; }
.explorer-table td { padding: 16px; height: 66px; }
Expand Down
32 changes: 32 additions & 0 deletions web/tests/directory-order.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,38 @@ test('manual legacy fallback uses portable Unicode order for privacy slot preser
assert.deepEqual(order.sortDirectoryAssets({...state,assets:items},items.slice(0,3),'name-asc').map(x=>x.id),['a','c','b']);
});
test('name modes and actual backup time modes include all versions and never-backed-up first for oldest',()=>{assert.equal(typeof order.sortDirectoryAssets,'function');for(const [mode, ids] of [['name-asc',['a','b','c']],['name-desc',['c','b','a']],['newest',['a','b','c']],['oldest',['c','b','a']]])assert.deepEqual(order.sortDirectoryAssets(state,state.assets,mode).map(x=>x.id),ids);});

test('column clicks start ascending and toggle only the active column',()=>{
assert.equal(typeof order.directoryColumnSort,'function');
for(const [column,ascending,descending] of [['name','name-asc','name-desc'],['backup','oldest','newest'],['notes','notes-asc','notes-desc']]){
assert.deepEqual(order.directoryColumnSort('manual',column),{direction:'none',next:ascending});
assert.deepEqual(order.directoryColumnSort(ascending,column),{direction:'ascending',next:descending});
assert.deepEqual(order.directoryColumnSort(descending,column),{direction:'descending',next:ascending});
}
assert.deepEqual(order.directoryColumnSort('notes-desc','name'),{direction:'none',next:'name-asc'});
});

test('backup notes sort naturally using only the latest visible description and keep blanks last',()=>{
const items=[asset('a','A','folder',{backup_target:true}),asset('b','B','folder',{backup_target:true}),asset('c','C','folder',{backup_target:true}),asset('d','D'),asset('p','Parent','folder',{backup_target:true}),asset('child','Child','file',{parent_id:'p',backup_target:true})];
const versions=items.map(item=>({id:'v-'+item.id,asset_id:item.id}));
const records=items.map((item,index)=>({id:'r-'+item.id,version_id:'v-'+item.id,location_id:'disk',backed_up_at:'2026-10-24T00:00:00Z',notes:['2','10',' ','1','0','0'][index]}));
records.push({id:'older',version_id:'v-a',location_id:'disk',backed_up_at:'2026-10-23T00:00:00Z',notes:'999'});
const noteState={assets:items,versions,records,locations:[]};
const roots=items.filter(item=>!item.parent_id);
assert.deepEqual(order.sortDirectoryAssets(noteState,roots,'notes-asc').map(x=>x.id),['a','b','c','d','p']);
assert.deepEqual(order.sortDirectoryAssets(noteState,roots,'notes-desc').map(x=>x.id),['b','a','c','d','p']);
assert.deepEqual(roots.map(x=>x.id),['a','b','c','d','p']);
});

test('backup time sorting matches parent rows that display the latest marked descendant backup',()=>{
const items=[asset('pa','A','folder'),asset('pb','B','folder'),asset('single','C'),asset('ca','CA','file',{parent_id:'pa',backup_target:true}),asset('cb','CB','file',{parent_id:'pb',backup_target:true}),asset('ignored','Ignored','file',{parent_id:'pa'})];
const versions=items.map(item=>({id:'v-'+item.id,asset_id:item.id}));
const records=[['pa','2026-12-01'],['ca','2026-10-01'],['cb','2026-10-20'],['single','2026-10-10'],['ignored','2026-11-01']].map(([id,date])=>({id:'r-'+id,version_id:'v-'+id,location_id:'disk',backed_up_at:date+'T00:00:00Z'}));
const grouped={assets:items,versions,records,locations:[]};
const roots=items.filter(item=>!item.parent_id);
assert.deepEqual(order.sortDirectoryAssets(grouped,roots,'newest').map(x=>x.id),['pb','single','pa']);
assert.deepEqual(order.sortDirectoryAssets(grouped,roots,'oldest').map(x=>x.id),['pa','single','pb']);
});
test('move produces complete sibling order without mutating input and rejects foreign ids',()=>{assert.equal(typeof order.moveDirectoryAsset,'function');const ids=['a','b','c'];assert.deepEqual(order.moveDirectoryAsset(ids,'c','a'),['c','a','b']);assert.deepEqual(ids,['a','b','c']);assert.equal(order.moveDirectoryAsset(ids,'foreign','a'),null);assert.equal(order.moveDirectoryAsset(ids,'a','a'),null);});

const {parseImportPreview}=await import('../src/importData.ts');
Expand Down
Loading