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

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

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

    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   ·   我们的愿景   ·   实用小工具   ·   2701 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 15:05 · PVG 23:05 · LAX 08:05 · JFK 11:05
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.