-
Notifications
You must be signed in to change notification settings - Fork 80
Expand file tree
/
Copy pathCodeEditor.tsx
More file actions
71 lines (60 loc) · 2.13 KB
/
Copy pathCodeEditor.tsx
File metadata and controls
71 lines (60 loc) · 2.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
'use client'
import { useAwareness, useText } from '@y-sweet/react'
import { useCallback, useRef } from 'react'
import type { CodemirrorBinding } from 'y-codemirror'
import type { EditorFromTextArea } from 'codemirror'
import Header from '@/components/Header'
import 'codemirror/lib/codemirror.css'
if (typeof navigator !== 'undefined') {
// This accesses the global navigator, which is not available in SSR,
// so we guard the import.
require('codemirror/mode/javascript/javascript')
}
import './caret.css'
export function CodeEditor() {
const yText = useText('text', { observe: 'none' })
const awareness = useAwareness()
const editorRef = useRef<EditorFromTextArea | null>(null)
const bindingRef = useRef<CodemirrorBinding | null>(null)
const codeMirrorRef = useCallback(
(ref: HTMLTextAreaElement | null) => {
if (ref == null) {
if (editorRef.current != null) {
editorRef.current.toTextArea()
editorRef.current = null
}
if (bindingRef.current != null) {
bindingRef.current.destroy()
bindingRef.current = null
}
return
}
if (bindingRef.current !== null) {
bindingRef.current.awareness = awareness
return
}
// These libraries are designed to work in the browser, and will cause warnings
// if imported on the server. Nextjs renders components on both the server and
// the client, so we import them lazily here when they are used on the client.
const CodeMirror = require('codemirror')
const CodemirrorBinding = require('y-codemirror').CodemirrorBinding
editorRef.current = CodeMirror.fromTextArea(ref, {
lineNumbers: true,
mode: 'javascript',
})
bindingRef.current = new CodemirrorBinding(yText!, editorRef.current, awareness)
},
[awareness, yText],
)
return (
<div className="p-4 lg:p-8 space-y-4">
<Header
title="CodeMirror Editor"
githubLink="https://github.com/jamsocket/y-sweet/blob/main/examples/nextjs/src/app/(demos)/code-editor"
/>
<div>
<textarea ref={codeMirrorRef} />
</div>
</div>
)
}