从零开始-文件资源管理器-21-创建、编辑文本文件

添加一个新建文件、编辑文件的功能。实现一些轻文本的编辑任务。

开发

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

git-repo

yangWs29/share-explorer

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,607评论 6 507
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,239评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,960评论 0 355
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,750评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,764评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,604评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,347评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,253评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,702评论 1 315
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,893评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,015评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,734评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,352评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,934评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,052评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,216评论 3 371
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,969评论 2 355

推荐阅读更多精彩内容