Skip to content
tsx
import 'prosekit/basic/style.css'

import { createEditor } from 'prosekit/core'
import { ProseKit } from 'prosekit/react'
import { useMemo } from 'react'

import { defineExtension } from './extension'
import WordCounter from './word-counter'

export default function Editor() {
  const editor = useMemo(() => {
    const extension = defineExtension()
    return createEditor({
      extension,
      defaultContent: 'Start typing and observe the word count update below.',
    })
  }, [])

  return (
    <ProseKit editor={editor}>
      <div className='box-border h-full w-full min-h-36 overflow-y-hidden overflow-x-hidden rounded-md border border-solid border-gray-200 shadow dark:border-zinc-700 flex flex-col bg-white dark:bg-neutral-900'>
        <div className='relative w-full flex-1 box-border overflow-y-scroll'>
          <div ref={editor.mount} className='ProseMirror box-border min-h-full px-[max(4rem,_calc(50%-20rem))] py-8 outline-none outline-0 [&_span[data-mention="user"]]:text-blue-500 [&_span[data-mention="tag"]]:text-violet-500 [&_pre]:text-white [&_pre]:bg-zinc-800'></div>
          <WordCounter />
        </div>
      </div>
    </ProseKit>
  )
}
ts
import { defineBasicExtension } from 'prosekit/basic'
import { union } from 'prosekit/core'

export function defineExtension() {
  return union(defineBasicExtension())
}

export type EditorExtension = ReturnType<typeof defineExtension>
tsx
import { useEditor } from 'prosekit/react'

export default function WordCounter() {
  const editor = useEditor({ update: true })

  const doc = editor.state.doc
  const words = doc ? doc.textBetween(0, doc.content.size, ' ') : ''
  const wordCount = words.split(/\s+/).filter((s) => s).length
  const characterCount = doc ? doc.textContent.length : 0

  return (
    <div className="p-4 text-center italic tabular-nums">
      Word Count: {wordCount}
      <br />
      Character Count: {characterCount}
    </div>
  )
}