Add tree multiselection, batch actions and Markdown export
This commit is contained in:
1 parent
f473ec64b6
commit
ffc95d6dbc
14 files changed
+532
-46
No files matched your search
@@ -1,27 +1,27 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { batchFiles } from './batch'
|
||||
import { minimalPaths } from './selection'
|
||||
import { fuzzyMatch, segments } from './fuzzy'
|
||||
import Icon from './Icon.vue'
|
||||
import { basename, dirname, inAssetDir, joinPath, noteTitle } from './paths'
|
||||
import { move, ws } from './workspace'
|
||||
|
||||
// 「移动到…」:选择目标文件夹(手机上没有拖放,电脑上也比拖放快)
|
||||
const props = defineProps<{ path: string }>()
|
||||
const props = defineProps<{ path: string | string[] }>()
|
||||
const emit = defineEmits<{ close: [] }>()
|
||||
|
||||
const input = ref<HTMLInputElement>()
|
||||
const list = ref<HTMLElement>()
|
||||
const query = ref('')
|
||||
const selected = ref(0)
|
||||
const isDir = computed(() => ws.entries.some((e) => e.path === props.path && e.dir))
|
||||
const title = computed(() => (isDir.value ? basename(props.path) : noteTitle(props.path)))
|
||||
const paths = computed(() => minimalPaths(typeof props.path === 'string' ? [props.path] : props.path))
|
||||
const title = computed(() => paths.value.length > 1 ? `${paths.value.length} 项` : noteTitle(paths.value[0]))
|
||||
|
||||
// 可选的目标:根目录与所有文件夹;排除当前所在的文件夹,移动文件夹时还要排除它自己及其子文件夹
|
||||
const targets = computed(() => {
|
||||
const here = dirname(props.path)
|
||||
const inside = (d: string) => isDir.value && (d === props.path || d.startsWith(props.path + '/'))
|
||||
const dirs = ws.entries.filter((e) => e.dir && !inAssetDir(e.path) && e.path !== here && !inside(e.path)).map((e) => e.path)
|
||||
return here === '' ? dirs : ['', ...dirs]
|
||||
const inside = (dir: string) => paths.value.some((path) => ws.entries.some((entry) => entry.path === path && entry.dir) && (dir === path || dir.startsWith(path + '/')))
|
||||
return ['', ...ws.entries.filter((entry) => entry.dir && !inAssetDir(entry.path)).map((entry) => entry.path)]
|
||||
.filter((dir) => !inside(dir) && !paths.value.every((path) => dirname(path) === dir))
|
||||
})
|
||||
|
||||
const items = computed(() => {
|
||||
@@ -42,7 +42,8 @@ function choose(i: number) {
|
||||
const target = items.value[i]
|
||||
if (!target) return
|
||||
emit('close')
|
||||
void move(props.path, joinPath(target.path, basename(props.path)))
|
||||
if (paths.value.length === 1) void move(paths.value[0], joinPath(target.path, basename(paths.value[0])))
|
||||
else void batchFiles('move', paths.value, target.path)
|
||||
}
|
||||
|
||||
function onKeydown(e: KeyboardEvent) {
|
||||
|
||||
+26
-13
@@ -2,8 +2,9 @@
|
||||
import { computed, nextTick, ref, watch } from 'vue'
|
||||
import Icon from './Icon.vue'
|
||||
import { basename, inAssetDir, isImage, joinPath } from './paths'
|
||||
import { expanded, type TreeNode } from './tree'
|
||||
import { createFolder, createNote, move, openNote, remove, renameTarget, ws } from './workspace'
|
||||
import { contextSelection, expanded, selectedPaths, selectPath, type TreeNode } from './tree'
|
||||
import { batchFiles, exportFiles } from './batch'
|
||||
import { createFolder, createNote, move, openNote, renameTarget, ws } from './workspace'
|
||||
|
||||
const props = defineProps<{ node: TreeNode; depth: number }>()
|
||||
|
||||
@@ -28,6 +29,7 @@ function onTouchStart(e: TouchEvent) {
|
||||
pressStart = { x: e.touches[0].clientX, y: e.touches[0].clientY }
|
||||
pressTimer = setTimeout(() => {
|
||||
longPressed = true
|
||||
contextSelection(props.node.path)
|
||||
menuOpen.value = true
|
||||
}, LONG_PRESS_MS)
|
||||
}
|
||||
@@ -41,12 +43,14 @@ function cancelPress() {
|
||||
pressStart = null
|
||||
}
|
||||
|
||||
function activate() {
|
||||
function activate(event: MouseEvent) {
|
||||
// 长按后松手产生的点击不打开笔记
|
||||
if (longPressed) {
|
||||
longPressed = false
|
||||
return
|
||||
}
|
||||
selectPath(props.node.path, event)
|
||||
if (event.ctrlKey || event.metaKey || event.shiftKey) return
|
||||
if (props.node.dir) {
|
||||
if (isOpen.value) expanded.delete(props.node.path)
|
||||
else expanded.add(props.node.path)
|
||||
@@ -73,7 +77,7 @@ function commitRename() {
|
||||
if (target && target !== props.node.path) void move(props.node.path, target)
|
||||
}
|
||||
|
||||
function runMenu(action: 'note' | 'folder' | 'import' | 'images' | 'rename' | 'move' | 'share' | 'delete') {
|
||||
function runMenu(action: 'note' | 'folder' | 'import' | 'images' | 'rename' | 'move' | 'share' | 'delete' | 'export') {
|
||||
menuOpen.value = false
|
||||
const path = props.node.path
|
||||
if (action === 'note' || action === 'folder') {
|
||||
@@ -83,8 +87,14 @@ function runMenu(action: 'note' | 'folder' | 'import' | 'images' | 'rename' | 'm
|
||||
else if (action === 'images') ws.images = path
|
||||
else if (action === 'rename') ws.renaming = path
|
||||
else if (action === 'share') ws.sharing = path
|
||||
else if (action === 'move') ws.moving = path
|
||||
else void remove(path)
|
||||
else if (action === 'move') ws.moving = [...selectedPaths]
|
||||
else if (action === 'export') void exportFiles([...selectedPaths])
|
||||
else void batchFiles('delete', [...selectedPaths])
|
||||
}
|
||||
|
||||
function showMenu() {
|
||||
contextSelection(props.node.path)
|
||||
menuOpen.value = true
|
||||
}
|
||||
|
||||
function cancelRename() {
|
||||
@@ -119,11 +129,13 @@ function onDrop(e: DragEvent) {
|
||||
<li class="rm-tree-item">
|
||||
<div
|
||||
class="rm-tree-row"
|
||||
:class="{ active: isActive, drop: dropTarget, 'menu-open': menuOpen }"
|
||||
:class="{ active: isActive, selected: selectedPaths.has(node.path), drop: dropTarget, 'menu-open': menuOpen }"
|
||||
:style="{ paddingLeft: depth * 14 + 8 + 'px' }"
|
||||
:draggable="!isRenaming && !assetDir"
|
||||
role="treeitem"
|
||||
:aria-selected="selectedPaths.has(node.path)"
|
||||
@click="activate"
|
||||
@contextmenu.prevent="menuOpen = true"
|
||||
@contextmenu.prevent.stop="showMenu"
|
||||
@touchstart.passive="onTouchStart"
|
||||
@touchmove.passive="onTouchMove"
|
||||
@touchend="cancelPress"
|
||||
@@ -146,20 +158,21 @@ function onDrop(e: DragEvent) {
|
||||
/>
|
||||
<Icon v-if="image" name="image" :size="14" />
|
||||
<span v-if="!isRenaming" class="rm-tree-name">{{ node.dir ? node.name : node.name.replace(/\.md$/, '') }}</span>
|
||||
<button class="rm-icon-btn rm-tree-more" title="更多操作" @click.stop="menuOpen = !menuOpen">
|
||||
<button class="rm-icon-btn rm-tree-more" title="更多操作" @click.stop="menuOpen ? (menuOpen = false) : showMenu()">
|
||||
<Icon name="more" />
|
||||
</button>
|
||||
<div v-if="menuOpen" class="rm-menu" @click.stop>
|
||||
<template v-if="node.dir && !assetDir">
|
||||
<template v-if="node.dir && !assetDir && selectedPaths.size === 1">
|
||||
<button @click="runMenu('note')"><Icon name="noteAdd" />新建笔记</button>
|
||||
<button @click="runMenu('folder')"><Icon name="folderAdd" />新建文件夹</button>
|
||||
<button @click="runMenu('images')"><Icon name="image" />图片管理</button>
|
||||
<button @click="runMenu('import')"><Icon name="import" />导入</button>
|
||||
</template>
|
||||
<button v-if="image" @click="menuOpen = false; ws.image = node.path"><Icon name="image" />预览 / 替换图片</button>
|
||||
<button v-if="!assetDir" @click="runMenu('rename')"><Icon name="edit" />重命名</button>
|
||||
<button v-if="image && selectedPaths.size === 1" @click="menuOpen = false; ws.image = node.path"><Icon name="image" />预览 / 替换图片</button>
|
||||
<button v-if="!assetDir && selectedPaths.size === 1" @click="runMenu('rename')"><Icon name="edit" />重命名</button>
|
||||
<button v-if="!assetDir" @click="runMenu('move')"><Icon name="folder" />移动到…</button>
|
||||
<button v-if="!image" @click="runMenu('share')"><Icon name="link" />分享</button>
|
||||
<button v-if="!image && selectedPaths.size === 1" @click="runMenu('share')"><Icon name="link" />分享</button>
|
||||
<button @click="runMenu('export')"><Icon name="note" />导出 Markdown</button>
|
||||
<button v-if="!assetDir" class="danger" @click="runMenu('delete')"><Icon name="trash" />删除</button>
|
||||
</div>
|
||||
<div v-if="menuOpen" class="rm-menu-backdrop" @click.stop="menuOpen = false" @contextmenu.prevent.stop="menuOpen = false" />
|
||||
|
||||
@@ -142,6 +142,8 @@ export const api = {
|
||||
return json<ImportResult>(request('POST', '/api/v1/import', { body }))
|
||||
},
|
||||
|
||||
exportFiles: (paths: string[]) => request('POST', '/api/v1/export', { json: { paths } }),
|
||||
|
||||
tree: async () => (await json<{ entries: Entry[] }>(request('GET', '/api/v1/tree'))).entries,
|
||||
search: async (q: string) => (await json<{ results: SearchResult[] }>(request('GET', '/api/v1/search?q=' + encodeURIComponent(q)))).results,
|
||||
|
||||
|
||||
@@ -546,3 +546,5 @@ button {
|
||||
.rm-shortcut-bindings input { width: 130px; padding: 8px; color: var(--rm-text); background: var(--rm-bg); border: 1px solid var(--rm-accent); }
|
||||
|
||||
.rm-context-menu { position: fixed; right: auto; width: max-content; }
|
||||
|
||||
.rm-tree-row.selected { background: var(--rm-active); box-shadow: inset 2px 0 var(--rm-accent); }
|
||||
@@ -0,0 +1,41 @@
|
||||
import { api } from './api'
|
||||
import { basename, joinPath } from './paths'
|
||||
import { minimalPaths } from './selection'
|
||||
import { flush, move, refreshTree, remove, toast, ws } from './workspace'
|
||||
|
||||
export async function batchFiles(action: 'move' | 'delete', paths: string[], destination = '') {
|
||||
const subjects = minimalPaths(paths)
|
||||
if (action === 'delete' && !confirm(`将选中的 ${subjects.length} 项移入回收站?文件夹内的内容也会一起删除。`)) return
|
||||
const failures: string[] = []
|
||||
let succeeded = 0
|
||||
for (const path of subjects) {
|
||||
try {
|
||||
const result = action === 'move' ? await move(path, joinPath(destination, basename(path))) : await remove(path)
|
||||
if (result.ok) succeeded++
|
||||
else failures.push(`${path}:${result.error}`)
|
||||
} catch (cause) { failures.push(`${path}:${cause instanceof Error ? cause.message : String(cause)}`) }
|
||||
}
|
||||
await refreshTree().catch((cause) => toast('刷新目录失败:' + String(cause)))
|
||||
toast(`${action === 'move' ? '移动' : '删除'}完成:成功 ${succeeded} 项,失败 ${failures.length} 项${failures.length ? ';' + failures.join(';') : ''}`)
|
||||
}
|
||||
|
||||
export async function exportFiles(paths: string[]) {
|
||||
const subjects = minimalPaths(paths)
|
||||
const tabs = ws.tabs.filter((tab) => subjects.some((path) => tab.path === path || tab.path.startsWith(path + '/')))
|
||||
try {
|
||||
await Promise.all(tabs.map((tab) => flush(tab.path)))
|
||||
if (tabs.some((tab) => tab.dirty || tab.status !== 'ready')) throw new Error('请先保存笔记并解决冲突,再导出')
|
||||
const response = await api.exportFiles(subjects)
|
||||
const blob = await response.blob()
|
||||
const disposition = response.headers.get('Content-Disposition') ?? ''
|
||||
const encoded = /filename\*=utf-8''([^;]+)/i.exec(disposition)?.[1]
|
||||
const plain = /filename="([^"]+)"|filename=([^;]+)/i.exec(disposition)
|
||||
const filename = encoded ? decodeURIComponent(encoded) : plain?.[1] ?? plain?.[2] ?? '导出.zip'
|
||||
const url = URL.createObjectURL(blob)
|
||||
const link = Object.assign(document.createElement('a'), { href: url, download: filename })
|
||||
document.body.append(link)
|
||||
link.click()
|
||||
link.remove()
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000)
|
||||
} catch (cause) { toast('导出失败:' + (cause instanceof Error ? cause.message : String(cause))) }
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { expect, it } from 'vitest'
|
||||
import { minimalPaths, rangePaths } from './selection'
|
||||
|
||||
it('消除重叠主体,不受相似目录排序干扰', () => {
|
||||
expect(minimalPaths(['a/b.md', 'a-b.md', 'a', 'a', 'z.md'])).toEqual(['a', 'a-b.md', 'z.md'])
|
||||
})
|
||||
it('Shift 范围只使用可见项,允许向上选择和丢失锚点', () => {
|
||||
expect(rangePaths(['a', 'a/x.md', 'b'], 'b', 'a')).toEqual(['a', 'a/x.md', 'b'])
|
||||
expect(rangePaths(['a', 'b'], 'removed', 'b')).toEqual(['b'])
|
||||
})
|
||||
@@ -0,0 +1,21 @@
|
||||
// 父目录已经选中时不重复操作其内部项。
|
||||
export function minimalPaths(paths: Iterable<string>): string[] {
|
||||
const out: string[] = []
|
||||
const roots = new Set<string>()
|
||||
for (const path of [...new Set(paths)].sort()) {
|
||||
let parent = path
|
||||
let covered = false
|
||||
while (parent.includes('/')) {
|
||||
parent = parent.slice(0, parent.lastIndexOf('/'))
|
||||
if (roots.has(parent)) { covered = true; break }
|
||||
}
|
||||
if (!covered) { out.push(path); roots.add(path) }
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
export function rangePaths(visible: string[], anchor: string | null, target: string): string[] {
|
||||
const from = anchor === null ? -1 : visible.indexOf(anchor)
|
||||
const to = visible.indexOf(target)
|
||||
return from < 0 || to < 0 ? [target] : visible.slice(Math.min(from, to), Math.max(from, to) + 1)
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { computed, reactive, watch } from 'vue'
|
||||
import type { Entry } from './api'
|
||||
import { basename, dirname, hiddenAssetPath } from './paths'
|
||||
import { rangePaths } from './selection'
|
||||
import { ws } from './workspace'
|
||||
|
||||
export interface TreeNode {
|
||||
@@ -44,3 +45,35 @@ watch(
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
export const selectedPaths = reactive(new Set<string>())
|
||||
let anchor: string | null = null
|
||||
export const visiblePaths = computed(() => {
|
||||
const paths: string[] = []
|
||||
const visit = (nodes: TreeNode[]) => { for (const node of nodes) { paths.push(node.path); if (expanded.has(node.path)) visit(node.children) } }
|
||||
visit(tree.value)
|
||||
return paths
|
||||
})
|
||||
watch(visiblePaths, (paths) => {
|
||||
const visible = new Set(paths)
|
||||
for (const path of selectedPaths) if (!visible.has(path)) selectedPaths.delete(path)
|
||||
if (anchor && !visible.has(anchor)) anchor = null
|
||||
})
|
||||
|
||||
export function selectPath(path: string, event?: Pick<MouseEvent, 'ctrlKey' | 'metaKey' | 'shiftKey'>) {
|
||||
const additive = event?.ctrlKey || event?.metaKey
|
||||
if (event?.shiftKey) {
|
||||
const range = rangePaths(visiblePaths.value, anchor, path)
|
||||
if (!additive) selectedPaths.clear()
|
||||
range.forEach((item) => selectedPaths.add(item))
|
||||
return
|
||||
}
|
||||
if (!additive) selectedPaths.clear()
|
||||
if (additive && selectedPaths.has(path)) selectedPaths.delete(path)
|
||||
else selectedPaths.add(path)
|
||||
anchor = path
|
||||
}
|
||||
|
||||
export function contextSelection(path: string) {
|
||||
if (!selectedPaths.has(path)) selectPath(path)
|
||||
}
|
||||
+27
-22
@@ -63,7 +63,7 @@ export const ws = reactive({
|
||||
// 分享当前笔记的对话框(笔记路径)
|
||||
sharing: null as string | null,
|
||||
// 「移动到…」对话框(笔记或文件夹路径)
|
||||
moving: null as string | null,
|
||||
moving: null as string | string[] | null,
|
||||
// 导入目标目录,空字符串为根目录
|
||||
importing: null as string | null,
|
||||
// 图片预览与管理,独立于笔记标签和草稿
|
||||
@@ -715,32 +715,34 @@ export function renameTarget(path: string, name: string): string | null {
|
||||
return joinPath(dirname(path), name)
|
||||
}
|
||||
|
||||
export async function move(from: string, to: string) {
|
||||
if (from === to) return
|
||||
if (creating.has(from) && !(await creating.get(from))) return
|
||||
export type FileResult = { ok: true } | { ok: false; error: string }
|
||||
function operationFailed(error: string): FileResult {
|
||||
toast(error)
|
||||
return { ok: false, error }
|
||||
}
|
||||
|
||||
export async function move(from: string, to: string): Promise<FileResult> {
|
||||
if (from === to) return { ok: true }
|
||||
if (creating.has(from) && !(await creating.get(from))) return operationFailed('笔记尚未创建成功')
|
||||
if (ws.entries.some((e) => e.path === to)) {
|
||||
toast(`“${basename(to)}”已存在`)
|
||||
return
|
||||
return operationFailed(`“${basename(to)}”已存在`)
|
||||
}
|
||||
await withOp(async () => {
|
||||
const result = await withOp<FileResult>(async () => {
|
||||
// 图片改名会更新仓库中的引用,先保存已打开笔记,沿用版本冲突保护。
|
||||
const imageMove = isImage(from) && ws.entries.some((e) => e.path === from && !e.dir)
|
||||
const impacted = () => imageMove ? ws.tabs.map((t) => t.path) : affected(from)
|
||||
const busy = () => impacted().some((p) => slots.get(p)?.uploads || slots.get(p)?.paused)
|
||||
if (busy()) {
|
||||
toast('笔记正在处理粘贴、上传或移动,请完成后再移动')
|
||||
return
|
||||
return operationFailed('笔记正在处理粘贴、上传或移动,请完成后再移动')
|
||||
}
|
||||
// 先保存待保存的修改,确保移动的是最新内容;移动期间暂停保存,避免写到旧路径
|
||||
await Promise.all(impacted().map((p) => flush(p)))
|
||||
// 等待保存时仍可能开始粘贴,须在取得移动占用前再次检查。
|
||||
if (busy()) {
|
||||
toast('笔记正在处理粘贴、上传或移动,请完成后再移动')
|
||||
return
|
||||
return operationFailed('笔记正在处理粘贴、上传或移动,请完成后再移动')
|
||||
}
|
||||
if (imageMove && ws.tabs.some((t) => t.dirty || t.status !== 'ready')) {
|
||||
toast('请先保存笔记并解决冲突,再修改图片名称或位置')
|
||||
return
|
||||
if (impacted().some((p) => { const tab = tabOf(p); return tab && (tab.dirty || tab.status !== 'ready') })) {
|
||||
return operationFailed('请先保存笔记并解决冲突,再移动文件')
|
||||
}
|
||||
const paused = impacted().map(slot)
|
||||
paused.forEach((s) => s.paused++)
|
||||
@@ -770,8 +772,7 @@ export async function move(from: string, to: string) {
|
||||
try { await drafts.move(to, from) }
|
||||
catch (cause) { toast('恢复原路径草稿失败:' + (cause instanceof Error ? cause.message : errorText(cause))) }
|
||||
}
|
||||
toast('移动失败:' + (err instanceof Error ? err.message : errorText(err)))
|
||||
return
|
||||
return operationFailed('移动失败:' + (err instanceof Error ? err.message : errorText(err)))
|
||||
} finally {
|
||||
paused.forEach((s) => s.paused--)
|
||||
}
|
||||
@@ -784,21 +785,24 @@ export async function move(from: string, to: string) {
|
||||
const { rev } = await api.readFile(p)
|
||||
if (rev !== tab.rev) Object.assign(tab, { status: 'conflict', conflictRev: rev })
|
||||
} else await syncOpenTab(tab)
|
||||
}))
|
||||
})).catch((err) => toast('文件已移动,但同步笔记失败:' + errorText(err)))
|
||||
return { ok: true }
|
||||
})
|
||||
void refreshTree().catch((err) => toast('刷新目录失败:' + errorText(err)))
|
||||
return result
|
||||
}
|
||||
|
||||
export async function remove(path: string) {
|
||||
export async function remove(path: string): Promise<FileResult> {
|
||||
const entry = ws.entries.find((e) => e.path === path)
|
||||
if (!entry) return
|
||||
await withOp(async () => {
|
||||
if (!entry) return operationFailed('文件已不存在')
|
||||
return withOp<FileResult>(async () => {
|
||||
const paths = affected(path)
|
||||
await Promise.all(paths.map((p) => flush(p)))
|
||||
if (paths.some((p) => { const tab = tabOf(p); return tab && (tab.dirty || tab.status !== 'ready') })) return operationFailed('请先保存笔记并解决冲突,再删除文件')
|
||||
const snapshot = ws.entries
|
||||
ws.entries = ws.entries.filter((e) => remapPath(e.path, path, path) === null) // 去掉自身及其下所有条目
|
||||
for (const p of paths) {
|
||||
if (!(await closeTab(p))) { ws.entries = snapshot; return }
|
||||
if (!(await closeTab(p))) { ws.entries = snapshot; return operationFailed('关闭笔记失败,未删除文件') }
|
||||
}
|
||||
try {
|
||||
const item = await api.deleteFile(path)
|
||||
@@ -807,9 +811,10 @@ export async function remove(path: string) {
|
||||
label: '撤销',
|
||||
run: () => void restore(item.id),
|
||||
})
|
||||
return { ok: true }
|
||||
} catch (err) {
|
||||
ws.entries = snapshot
|
||||
toast('删除失败:' + errorText(err))
|
||||
return operationFailed('删除失败:' + errorText(err))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user