✨ feat(frontend): 补齐本地文件免上传分享入口

This commit is contained in:
orion committed 2026-09-18 10:56:46 +08:00
1 parent 7f9aaf8a4d
commit 638a56d894
16 files changed
+402

No files matched your search

+8
View File
@@ -61,3 +61,11 @@ Primary submit actions must not add white/gradient hover overlays.
Playwright Page。Vite 固定运行于 `127.0.0.1:5180`;分别传入 `http` 和 `network`
验证服务端 500、断网时错误显示于弹窗内、原记录保留,以及重新打开时清空旧错误。
测试拦截全部管理 API,不会修改部署实例。
## 本地文件分享
- `localShare.test.mjs`:目录导航、路径原样保留、有效期白名单与输入边界。
- `localShare.integration.test.mjs`:真实 Vue 状态与服务边界,覆盖目录响应乱序、重复提交、失败重试。
- `localShare.browser.mjs`:导出 `runLocalShareChecks(page, dark)`;Vite 运行于
`127.0.0.1:5180`。管理 API 全部拦截为独立数据,覆盖目录/搜索/分页、生成失败重试、
取件码/链接复制、空目录/加载错误和移动端溢出检查。
+5
View File
@@ -0,0 +1,5 @@
<!doctype html><html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>本地文件分享 · 独立测试</title><div id="app"></div><script type="module">
import {createApp,ref} from 'vue';import {createRouter,createMemoryHistory} from 'vue-router';import {createI18n} from 'vue-i18n';import LocalFiles from '/src/views/manage/LocalFilesView.vue';import zh from '/src/i18n/locales/zh-CN.ts';import '/src/assets/style/main.css';
const dark=new URLSearchParams(location.search).has('dark');document.documentElement.classList.toggle('dark',dark);
const app=createApp(LocalFiles);app.provide('isDarkMode',ref(dark));app.use(createI18n({legacy:false,locale:'zh-CN',messages:{'zh-CN':zh}}));const router=createRouter({history:createMemoryHistory(),routes:[{path:'/',component:{template:'<div/>'}}]});app.use(router);router.isReady().then(()=>app.mount('#app'));
</script></html>
+62
View File
@@ -0,0 +1,62 @@
import assert from 'node:assert/strict'
// Independent API fixture. Never sends requests to a deployed instance.
export async function runLocalShareChecks(page, dark = false) {
const headers={'access-control-allow-origin':'*','access-control-allow-headers':'*','access-control-allow-methods':'*'}
let failShare=true, requests=0, failList=false
await page.context().grantPermissions(['clipboard-read','clipboard-write'],{origin:'http://127.0.0.1:5180'})
await page.route('**/*',route=>new URL(route.request().url()).hostname==='127.0.0.1'?route.continue():route.abort())
const entry=(name,type='file',path=name)=>({name,file:name,path,type,size:type==='dir'?null:1024,ctime:null})
await page.route('**/api/v1/config',route=>route.fulfill({headers,json:{code:200,detail:{config:{expireStyle:['day','count','forever'],max_save_seconds:604800}}}}))
await page.route('**/admin/**',async route=>{
const req=route.request(),url=new URL(req.url())
if(req.method()==='OPTIONS') return route.fulfill({status:204,headers})
if(url.pathname==='/admin/local/lists'){
if(failList){failList=false;return route.fulfill({status:500,headers,json:{detail:'目录暂时不可用'}})}
const path=url.searchParams.get('path'),size=Number(url.searchParams.get('size')||20),keyword=url.searchParams.get('keyword')||''
let items=path==='文档'?[entry(' final 报告.txt ','file','文档/ final 报告.txt ')]:path==='空目录'?[]:[entry('文档','dir'),entry('空目录','dir'),...Array.from({length:23},(_,n)=>entry(`file-${String(n).padStart(2,'0')}.txt`))]
items=items.filter(x=>x.name.includes(keyword));const total=items.length,p=Math.min(Number(url.searchParams.get('page')||1),Math.max(1,Math.ceil(total/size)))
return route.fulfill({headers,json:{code:200,detail:{path,parent:'',items:items.slice((p-1)*size,p*size),total,page:p,size,truncated:false}}})
}
if(url.pathname==='/admin/local/share'){
requests++; assert.deepEqual(req.postDataJSON(),{filename:'文档/ final 报告.txt ',expire_style:'count',expire_value:2})
await new Promise(r=>setTimeout(r,180))
if(failShare){failShare=false;return route.fulfill({status:500,headers,json:{detail:'文件暂时不可读'}})}
return route.fulfill({headers,json:{code:200,detail:{id:18,code:'ABCD2345',name:' final 报告.txt ',path:'文档/ final 报告.txt '}}})
}
throw new Error('Unexpected API '+url.pathname)
})
await page.goto('http://127.0.0.1:5180/theme-assets/tests/local-files.html'+(dark?'?dark':''))
await page.getByRole('button',{name:'打开 文档',exact:true}).waitFor()
await page.getByRole('button',{name:'下一页',exact:true}).click()
await page.getByText('file-22.txt',{exact:true}).waitFor()
await page.getByRole('searchbox',{name:'在当前目录搜索'}).fill('文档')
await page.getByRole('button',{name:'搜索',exact:true}).click()
await page.getByRole('button',{name:'打开 文档',exact:true}).click()
await page.getByRole('button',{name:/分享.*final 报告/}).click()
const dialog=page.getByRole('dialog')
await dialog.getByRole('combobox').selectOption('count')
await dialog.locator('input[type=number]').fill('2')
await dialog.getByRole('button',{name:'生成取件码',exact:true}).click()
await dialog.getByRole('alert').waitFor()
assert.ok((await dialog.getByRole('alert').textContent()).includes('文件暂时不可读'))
await dialog.getByRole('button',{name:'生成取件码',exact:true}).click()
await dialog.getByRole('textbox',{name:'取件码',exact:true}).waitFor()
assert.equal(await dialog.getByRole('textbox',{name:'取件码',exact:true}).inputValue(),'ABCD2345')
await dialog.getByRole('button',{name:'复制取件码',exact:true}).click()
assert.equal(await page.evaluate(()=>navigator.clipboard.readText()),'ABCD2345')
await dialog.getByRole('button',{name:'复制链接',exact:true}).click()
assert.equal(await page.evaluate(()=>navigator.clipboard.readText()),'http://127.0.0.1:5180/#/?code=ABCD2345')
assert.equal(requests,2)
await dialog.getByRole('button',{name:'完成',exact:true}).click()
await page.getByRole('button',{name:'返回上一级',exact:true}).click()
await page.getByRole('button',{name:'打开 空目录',exact:true}).click()
await page.getByText('当前目录还没有文件',{exact:true}).waitFor()
failList=true
await page.getByRole('button',{name:'刷新目录',exact:true}).click()
await page.getByText('目录暂时不可用',{exact:true}).waitFor()
await page.getByRole('button',{name:'重试目录',exact:true}).click()
await page.getByText('当前目录还没有文件',{exact:true}).waitFor()
assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth),false)
console.log(JSON.stringify({localShare:dark?'dark':'light',directorySearchPagination:true,shareRetryCopy:true,emptyErrorRetry:true,requests}))
}
+48
View File
@@ -0,0 +1,48 @@
import {test,before,after} from 'node:test'
import assert from 'node:assert/strict'
import {effectScope} from 'vue'
import {createServer} from 'vite'
let server, create, service, config
before(async()=>{
server=await createServer({server:{middlewareMode:true,watch:null},appType:'custom'})
create=(await server.ssrLoadModule('/src/composables/useLocalFiles.ts')).useLocalFiles
const exports=await server.ssrLoadModule('/src/services/index.ts');service=exports.LocalShareService;config=exports.ConfigService
})
after(async()=>await server?.close())
const listing=path=>({code:200,detail:{path,parent:'',items:[{name:path,type:'file',path,size:1}],page:1,size:20,total:1}})
test('slower previous directory response cannot replace current contents',async()=>{
const original=service.list,scope=effectScope(),flow=scope.run(create),pending={}
service.list=params=>new Promise(resolve=>{pending[params.path]=resolve})
try {
const old=flow.load('old'),current=flow.load('current')
pending.current(listing('current'));await current
pending.old(listing('old'));await old
assert.equal(flow.path.value,'current');assert.equal(flow.items.value[0].name,'current');assert.equal(flow.loading.value,false)
}finally{service.list=original;scope.stop()}
})
test('share failure keeps dialog retryable and success blocks duplicate generation',async()=>{
const originalShare=service.share,originalConfig=config.getUserConfig,scope=effectScope(),flow=scope.run(create)
let calls=0,resolveShare
config.getUserConfig=async()=>({code:200,detail:{config:{expireStyle:['count'],max_save_seconds:86400}}})
service.share=()=>{calls++;return new Promise(resolve=>{resolveShare=resolve})}
try {
await flow.loadConfig();flow.openShare({name:'a.txt',path:'docs/a.txt',type:'file',size:1})
flow.expireValue.value='2';const sending=flow.share();await flow.share();flow.closeShare()
assert.equal(calls,1);assert.equal(flow.selected.value.path,'docs/a.txt')
resolveShare({code:500,detail:null});await sending
assert.ok(flow.shareError.value);assert.equal(flow.sharing.value,false)
const retry=flow.share();resolveShare({code:200,detail:{code:'ABCD2345',id:1,name:'a.txt',path:'docs/a.txt'}});await retry
await flow.share();assert.equal(calls,2);assert.equal(flow.result.value.code,'ABCD2345')
flow.closeShare();assert.equal(flow.selected.value,null)
}finally{service.share=originalShare;config.getUserConfig=originalConfig;scope.stop()}
})
test('failed directory load clears old files and retry restores results',async()=>{
const original=service.list,scope=effectScope(),flow=scope.run(create)
try{
service.list=async()=>listing('old');await flow.load('old')
service.list=async()=>{throw new Error('unreadable')};await flow.load('new')
assert.deepEqual(flow.items.value,[]);assert.equal(flow.total.value,0);assert.equal(flow.error.value,'unreadable')
service.list=async()=>listing('new');await flow.load()
assert.equal(flow.error.value,'');assert.equal(flow.items.value[0].path,'new')
}finally{service.list=original;scope.stop()}
})
+19
View File
@@ -0,0 +1,19 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { localBreadcrumbs, buildLocalShareRequest, expirationChoices } from '../src/utils/local-share.ts'
test('breadcrumbs preserve literal paths including spaces and unicode', () => {
assert.deepEqual(localBreadcrumbs('报告/ final '), [{name:'本地文件',path:''},{name:'报告',path:'报告'},{name:' final ',path:'报告/ final '}])
assert.deepEqual(localBreadcrumbs(''), [{name:'本地文件',path:''}])
})
test('sharing preserves the selected filename and rejects invalid expiration values', () => {
assert.deepEqual(buildLocalShareRequest('报告/ final.txt ', 'count', '2',['day','count']), {filename:'报告/ final.txt ',expire_style:'count',expire_value:2})
assert.equal(buildLocalShareRequest('a','forever','',['forever']).expire_value,1)
for (const value of ['', '0', '-1', '1.5', 'abc', '1000001']) assert.throws(()=>buildLocalShareRequest('a','day',value,['day']))
assert.throws(()=>buildLocalShareRequest('a','forever','1',['day']))
assert.throws(()=>buildLocalShareRequest('','day','1',['day']))
})
test('expiration choices only expose server-enabled recognized policies', () => {
assert.deepEqual(expirationChoices(['day','count','bad','day']).map(x=>x.value),['day','count'])
assert.deepEqual(expirationChoices([]),[])
})