V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
Exuanbo
V2EX  ›  React

[项目自荐] @codemirror-toolkit/react

  •  
  •   Exuanbo ·
    exuanbo · 2023-01-09 10:42:52 +08:00 · 1286 次点击
    这是一个创建于 676 天前的主题,其中的信息可能已经有所发展或是发生改变。

    https://github.com/exuanbo/codemirror-toolkit/tree/main/packages/react

    一个小巧灵活的在 React 中使用 CodeMirror 6 的解决方案,打包体积只有 ~1.5kB minified + gizipped 。

    import { createCodeMirror } from '@codemirror-toolkit/react'
    
    const codeMirror = createCodeMirror<HTMLDivElement>((prevState) => ({
      doc: prevState?.doc ?? 'Hello World!',
      // ...otherConfig,
    }))
    
    // if you want to use them in other files
    export const { useViewEffect, useContainerRef, /* ... */ } = codeMirror
    
    function Editor() {
      useViewEffect((view) => {
        console.log('EditorView is created')
        return () => {
          console.log('EditorView will be destroyed')
        }
      }, [])
      const containerRef = useContainerRef()
      return <div ref={containerRef} />
    }
    
    function App() {
      const [showEditor, setShowEditor] = useState(true)
      return (
        <>
          <button onClick={() => setShowEditor(!showEditor)}>
            {showEditor ? 'Destroy' : 'Create'} Editor
          </button>
          {showEditor && <Editor />}
        </>
      )
    }
    

    可以看出 API 的设计借鉴了 zustand 很多,也可以搭配 Context Provider 来使用:

    const {
      Provider: CodeMirrorProvider,
      useView,
      useContainerRef,
      // ...
    } = createCodeMirrorWithContext<HTMLDivElement>('CodeMirrorContext')
    
    function MenuBar() {
      const view = useView()
      // ...
    }
    
    function Editor() {
      const containerRef = useContainerRef()
      return <div ref={containerRef} />
    }
    
    function App({ initialInput }: { initialInput: string }) {
      return (
        <CodeMirrorProvider
          config={{
            doc: initialInput,
            // ...otherConfig,
          }}>
          <MenuBar />
          <Editor />
        </CodeMirrorProvider>
      )
    }
    

    Examples

    Source Playground
    react-with-context Open in StackBlitz
    react-with-extension-manager Open in StackBlitz
    react-with-view-update-listener Open in StackBlitz
    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   5429 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 44ms · UTC 07:02 · PVG 15:02 · LAX 23:02 · JFK 02:02
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.