添加一个新建文件、编辑文件的功能。实现一些轻文本的编辑任务。
开发
explorer-manage
新建、编辑都使用 node 的 fs.writeFileSync 方法。
新增三个方法
- 创建文件
- 获取文件内容
- 写入文件
import fs from 'fs'
export const createFileAction = (path) => {
return fs.writeFileSync(formatPath(path), '')
}
export const getFileContent = (path) => {
return fs.readFileSync(formatPath(path), 'utf-8')
}
export const writeFile = (path, content = '') => {
return fs.writeFileSync(formatPath(path), content)
}
explorer
客户端使用 @uiw/react-codemirror
这个代码编辑器,后续还可以添加配套的代码语言支持,方便在线编辑与代码着色。
当点击 txt|text|xml|html|htm|css|less|sass|json|js|ts|mjs|jsx|py|php|md
这些后缀名的文件时,使用弹窗的形式编辑文本内容。
安装依赖
pnpm install @uiw/react-codemirror
将之前的创建文件夹按钮变为浮动菜单的形式,并添加一个创建文件的按钮
Next.js server actions:创建文件
import { createFileAction } from '@/explorer-manager/src/main.mjs'
export const createFile: (file_path: string) => Promise<ActionResType> = (file_path) => {
try {
createFileAction(file_path)
return Promise.resolve({ status: 'ok', message: 'done' })
} catch (err: any) {
return Promise.resolve({ status: 'error', message: JSON.stringify(err?.message) })
}
}
...
const ReaddirExtraActionBtn: React.FC = () => {
const [open, changeOpen] = useState<'folder' | 'file' | undefined>(undefined)
const { update } = useUpdateReaddirList()
return (
<>
<Dropdown
placement="top"
arrow={true}
trigger={['hover', 'click']}
menu={{
items: [
{
key: 'create-folder',
icon: <FolderOutlined />,
label: '创建文件夹',
onClick: () => {
changeOpen('folder')
},
},
{
key: 'create-file',
icon: <FileOutlined />,
label: '创建文件',
onClick: () => {
changeOpen('file')
},
},
{
key: 'reload',
icon: <ReloadOutlined />,
label: '刷新',
onClick: update,
},
],
}}
>
<Button icon={<PlusOutlined />} />
</Dropdown>
<Modal
open={!!open}
onCancel={() => changeOpen(undefined)}
title={open === 'folder' ? '新建文件夹' : '新建文件'}
footer={false}
>
{open === 'folder' ? <CreateFolderForm /> : <CreateFileForm />}
</Modal>
</>
)
}
export default ReaddirExtraActionBtn
open 为 'folder' | 'file' | undefined 对应的创建文件夹、文件、关闭弹窗三个状态。
CreateFileForm 组件
'use client'
import React from 'react'
import { App, Flex, Form, Input } from 'antd'
import SubmitBtn from '@/components/submit-btn'
import { createFile } from '@/components/readdir-extra-action-btn/action'
import { useUpdateReaddirList } from '@/app/path/readdir-context'
import { useReplacePathname } from '@/components/use-replace-pathname'
const onFinishFailed = (errorInfo: any) => {
console.log('Failed:', errorInfo)
}
const CreateFileForm: React.FC = () => {
const { update } = useUpdateReaddirList()
const { message: appMessage } = App.useApp()
const { replace_pathname } = useReplacePathname()
return (
<Form
labelCol={{ span: 2 }}
initialValues={{ file_name: '新建文件.txt' }}
onFinish={(values) => {
const { file_name } = values
createFile([replace_pathname, file_name].join('/'))
.then(({ status, message }) => {
if (status === 'error') {
return Promise.reject({ status, message })
}
update()
appMessage.success('新建文件成功').then()
})
.catch(({ message }) => {
appMessage.error(`新建文件失败: ${message}`).then()
})
}}
onFinishFailed={onFinishFailed}
>
<Form.Item name="file_name" rules={[{ required: true, message: '请输入文名称' }]}>
<Input />
</Form.Item>
<Form.Item>
<Flex justify="flex-end">
<SubmitBtn>创建</SubmitBtn>
</Flex>
</Form.Item>
</Form>
)
}
export default CreateFileForm
简单的 form 表单。提交时调用 createFile server action 方法创建文件。
Next.js server actions:获取文件内容与写入文件内容
'use server'
import { getFileContent, writeFile } from '@/explorer-manager/src/main.mjs'
export const getEditFileContentAction: (path: string) => Promise<string> = (path) => {
return new Promise((res, rej) => {
try {
res(getFileContent(path))
} catch (e) {
rej(e)
}
})
}
export const writeFileAction: (path: string, content: string) => Promise<string> = (path, content) => {
return new Promise((res, rej) => {
try {
writeFile(path, content)
res('done')
} catch (e) {
rej(e)
}
})
}
创建上下文组件
'use client'
import createCtx from '@/lib/create-ctx'
import React from 'react'
import EditFileModal from '@/components/edit-file/modal'
export const EditFileContext = createCtx<string>('')
export const EditFileProvider: React.FC<React.PropsWithChildren> = ({ children }) => {
return (
<EditFileContext.ContextProvider value={''}>
{children}
<EditFileModal />
</EditFileContext.ContextProvider>
)
}
编辑弹窗组件
'use client'
import React, { useRef } from 'react'
import CodeMirror from '@uiw/react-codemirror'
import { EditFileContext } from '@/components/edit-file/edit-file-context'
import { Button, Card, Flex, Modal, Space } from 'antd'
import { useRequest } from 'ahooks'
import { getEditFileContentAction, writeFileAction } from '@/components/edit-file/action'
const EditContent: React.FC = () => {
const edit_file_path = EditFileContext.useStore()
const { data, loading } = useRequest(() => getEditFileContentAction(edit_file_path))
const file_content = useRef<string>('')
const editFileDispatch = EditFileContext.useDispatch()
return (
<Space direction="vertical" style={{ width: '100%' }}>
<Card loading={loading} bordered={false}>
<CodeMirror
value={data}
maxHeight={'60vh'}
minHeight={'15em'}
theme="dark"
onChange={(value) => {
file_content.current = value
}}
/>
</Card>
<Flex justify="end">
<Button
onClick={() => {
writeFileAction(edit_file_path, file_content.current).then(() => {
editFileDispatch('')
})
}}
>
保存
</Button>
</Flex>
</Space>
)
}
const EditFileModal = () => {
const edit_file_path = EditFileContext.useStore()
const editFileDispatch = EditFileContext.useDispatch()
return (
<Modal
title={decodeURIComponent(edit_file_path.split('/').pop() || '')}
width="75%"
footer={null}
destroyOnClose={true}
open={!!edit_file_path}
onCancel={() => {
editFileDispatch('')
}}
>
<EditContent />
</Modal>
)
}
export default EditFileModal
这里使用的 server action,减少了 http api 的编辑与对接的过程。开发人员不用太多关注 xhr/fetch 的动作。可以更专注的在代码逻辑上。
默认情况下,server action 的提交大小为 1MB 大小。参考链接 server actions:bodysizelimit 可通过编辑 bodysizelimit 参数实现增大缩小最大提交量。
效果
截屏2023-12-25 10.29.21.png
截屏2023-12-25 10.19.22.png
截屏2023-12-25 10.18.16.png