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

2023-01-09 10:42:52 +08:00
 Exuanbo

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
1115 次点击
所在节点    React
0 条回复

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/907516

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX