aboutsummaryrefslogtreecommitdiff
path: root/src/components/Editor/YaceEditor.tsx
blob: f3152e1697f579c3a0615324af18935e1e6d8e88 (plain)
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
import { useCallback, useEffect, useRef, useMemo } from 'react'
import {
  EditorView, keymap,
  highlightActiveLine, highlightActiveLineGutter,
  lineNumbers,
} from '@codemirror/view'
import { EditorState, type Extension } from '@codemirror/state'
import { defaultKeymap, indentWithTab, undo, redo } from '@codemirror/commands'
import { syntaxHighlighting, indentUnit, HighlightStyle } from '@codemirror/language'
import { tags } from '@lezer/highlight'
import { json } from '@codemirror/lang-json'
import { javascript } from '@codemirror/lang-javascript'
import { markdown } from '@codemirror/lang-markdown'
import { html } from '@codemirror/lang-html'
import { css } from '@codemirror/lang-css'
import { rust } from '@codemirror/lang-rust'
import { python } from '@codemirror/lang-python'
import { useTabsStore } from '@/stores/useTabsStore'
import { useContextMenuStore } from '@/stores/useContextMenuStore'
import { useSettingsStore } from '@/stores/useSettingsStore'

function buildLanguageExtensions(language: string) {
  switch (language) {
    case 'typescript':
      return javascript({ typescript: true })
    case 'javascript':
      return javascript()
    case 'json':
      return json()
    case 'markdown':
      return markdown()
    case 'html':
      return html()
    case 'css':
      return css()
    case 'rust':
      return rust()
    case 'python':
      return python()
    default:
      return []
  }
}

const tokyoNightSyntax = HighlightStyle.define([
  { tag: tags.keyword, color: '#7aa2f7' },
  { tag: [tags.controlKeyword, tags.operatorKeyword], color: '#7aa2f7' },
  { tag: tags.modifier, color: '#7aa2f7' },
  { tag: tags.definitionKeyword, color: '#7aa2f7' },
  { tag: tags.moduleKeyword, color: '#7aa2f7' },
  { tag: tags.self, color: '#ff5370' },
  { tag: tags.atom, color: '#ff9e64' },
  { tag: tags.bool, color: '#ff9e64' },
  { tag: tags.null, color: '#ff9e64' },
  { tag: tags.number, color: '#ff9e64' },
  { tag: tags.string, color: '#9ece6a' },
  { tag: tags.character, color: '#9ece6a' },
  { tag: tags.regexp, color: '#89ddff' },
  { tag: tags.escape, color: '#bb9af7' },
  { tag: tags.typeName, color: '#e0af68' },
  { tag: tags.className, color: '#e0af68' },
  { tag: tags.namespace, color: '#89ddff' },
  { tag: tags.macroName, color: '#ff5370' },
  { tag: tags.propertyName, color: '#73daca' },
  { tag: tags.attributeName, color: '#73daca' },
  { tag: tags.variableName, color: '#c0caf5' },
  { tag: tags.labelName, color: '#c0caf5' },
  { tag: tags.operator, color: '#89ddff' },
  { tag: tags.bracket, color: '#a9b1d6' },
  { tag: tags.angleBracket, color: '#89ddff' },
  { tag: tags.paren, color: '#a9b1d6' },
  { tag: tags.brace, color: '#a9b1d6' },
  { tag: tags.squareBracket, color: '#a9b1d6' },
  { tag: tags.separator, color: '#a9b1d6' },
  { tag: tags.punctuation, color: '#a9b1d6' },
  { tag: tags.comment, color: '#565f89', fontStyle: 'italic' },
  { tag: tags.lineComment, color: '#565f89', fontStyle: 'italic' },
  { tag: tags.blockComment, color: '#565f89', fontStyle: 'italic' },
  { tag: tags.docComment, color: '#565f89', fontStyle: 'italic' },
  { tag: tags.docString, color: '#565f89' },
  { tag: tags.meta, color: '#565f89' },
  { tag: tags.content, color: '#c0caf5' },
  { tag: tags.heading, color: '#7aa2f7', fontWeight: '600' },
  { tag: tags.strong, color: '#c0caf5', fontWeight: '700' },
  { tag: tags.emphasis, color: '#c0caf5', fontStyle: 'italic' },
  { tag: tags.strikethrough, color: '#565f89', textDecoration: 'line-through' },
  { tag: tags.link, color: '#73daca', textDecoration: 'underline' },
  { tag: tags.url, color: '#73daca', textDecoration: 'underline' },
  { tag: tags.list, color: '#7dcfff' },
  { tag: tags.quote, color: '#9ece6a' },
  { tag: tags.inserted, color: '#9ece6a' },
  { tag: tags.deleted, color: '#ff5370' },
  { tag: tags.changed, color: '#e0af68' },
  { tag: tags.invalid, color: '#ff5370' },
  { tag: tags.definition(tags.variableName), color: '#c0caf5' },
  { tag: tags.definition(tags.propertyName), color: '#73daca' },
  { tag: tags.function(tags.variableName), color: '#7dcfff' },
  { tag: tags.definition(tags.function(tags.variableName)), color: '#7dcfff' },
  { tag: tags.local(tags.variableName), color: '#c0caf5' },
  { tag: tags.special(tags.variableName), color: '#ff5370' },
  { tag: tags.special(tags.string), color: '#bb9af7' },
])

function buildEditorTheme(settings: {
  fontSize: number
  fontFamily: string
  ruler: boolean
  rulerColumn: number
}) {
  const rulerCSS = settings.ruler
    ? `linear-gradient(90deg, transparent calc(${settings.rulerColumn}ch + 0.5px), var(--color-ruler) calc(${settings.rulerColumn}ch + 0.5px), var(--color-ruler) calc(${settings.rulerColumn + 0.5}ch + 0.5px), transparent calc(${settings.rulerColumn + 0.5}ch + 0.5px))`
    : 'none'

  return EditorView.theme({
    '&': {
      fontSize: `${settings.fontSize}px`,
      fontFamily: `'${settings.fontFamily}', 'Cascadia Code', 'Fira Code', Consolas, monospace`,
      height: '100%',
      backgroundColor: 'var(--color-editor-bg)',
    },
    '.cm-scroller': {
      fontFamily: `'${settings.fontFamily}', 'Cascadia Code', 'Fira Code', Consolas, monospace`,
    },
    '.cm-content': {
      padding: '16px 0',
      caretColor: 'var(--color-accent)',
      backgroundImage: rulerCSS,
      backgroundPosition: '0 0',
      backgroundRepeat: 'no-repeat',
    },
    '.cm-line': {
      padding: '0 20px',
    },
    '.cm-gutters': {
      backgroundColor: 'var(--color-editor-surface)',
      borderRight: '1px solid var(--color-panel-border)',
      color: 'var(--color-text-muted)',
    },
    '.cm-lineNumbers .cm-gutterElement': {
      padding: '0 12px 0 16px',
      fontSize: '12px',
      fontFamily: `'${settings.fontFamily}', 'Cascadia Code', 'Fira Code', Consolas, monospace`,
      lineHeight: '1.6',
    },
    '.cm-activeLineGutter': {
      backgroundColor: 'var(--color-editor-line)',
      color: 'var(--color-text-primary)',
      fontWeight: '600',
    },
    '.cm-activeLine': {
      backgroundColor: 'rgba(12,12,14,0.5)',
    },
    '.cm-cursor': {
      borderLeftWidth: '2px',
      borderLeftColor: 'var(--color-accent)',
    },
    '&.cm-focused .cm-cursor': {
      borderLeftColor: 'var(--color-accent)',
    },
    '.cm-selectionBackground': {
      backgroundColor: 'rgba(240,160,48,0.2) !important',
    },
    '&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground': {
      backgroundColor: 'rgba(240,160,48,0.25) !important',
    },
    '.cm-selectionMatch': {
      backgroundColor: 'rgba(240,160,48,0.1) !important',
    },
  })
}

export default function YaceEditor() {
  const editorRef = useRef<HTMLDivElement>(null)
  const viewRef = useRef<EditorView | null>(null)
  const containerRef = useRef<HTMLDivElement>(null)
  const updateTimeoutRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)

  const activeTab = useTabsStore((s) =>
    s.activeTabId ? s.tabs.find((t) => t.id === s.activeTabId) ?? null : null
  )
  const updateContent = useTabsStore((s) => s.updateContent)
  const setCursorPosition = useTabsStore((s) => s.setCursorPosition)
  const openContextMenu = useContextMenuStore((s) => s.open)

  const fontSize = useSettingsStore((s) => s.fontSize)
  const tabSize = useSettingsStore((s) => s.tabSize)
  const fontFamily = useSettingsStore((s) => s.fontFamily)
  const wordWrap = useSettingsStore((s) => s.wordWrap)
  const lineNumbersEnabled = useSettingsStore((s) => s.lineNumbers)
  const ruler = useSettingsStore((s) => s.ruler)
  const rulerColumn = useSettingsStore((s) => s.rulerColumn)

  const settings = { fontSize, tabSize, fontFamily, wordWrap, lineNumbers: lineNumbersEnabled, ruler, rulerColumn }

  const editorItems = useMemo(() => [
    { id: 'undo', label: 'Undo', shortcut: 'Ctrl+Z', icon: 'undo' as const, action: () => viewRef.current && undo(viewRef.current) },
    { id: 'redo', label: 'Redo', shortcut: 'Ctrl+Shift+Z', icon: 'redo' as const, action: () => viewRef.current && redo(viewRef.current) },
    { id: 'sep1', label: '', separator: true, action: () => {} },
    { id: 'cut', label: 'Cut', shortcut: 'Ctrl+X', icon: 'cut' as const, action: () => { document.execCommand('cut') } },
    { id: 'copy', label: 'Copy', shortcut: 'Ctrl+C', icon: 'copy' as const, action: () => { document.execCommand('copy') } },
    { id: 'paste', label: 'Paste', shortcut: 'Ctrl+V', icon: 'paste' as const, action: () => { navigator.clipboard.readText().then((t) => viewRef.current?.dispatch({ changes: { from: viewRef.current.state.selection.main.head, insert: t } })) } },
    { id: 'sep2', label: '', separator: true, action: () => {} },
    { id: 'selectAll', label: 'Select All', shortcut: 'Ctrl+A', icon: 'selectAll' as const, action: () => { viewRef.current?.dispatch({ selection: { anchor: 0, head: viewRef.current.state.doc.length } }) } },
  ], [])

  const handleContextMenu = useCallback((e: MouseEvent) => {
    e.preventDefault()
    openContextMenu(e.clientX, e.clientY, editorItems)
  }, [openContextMenu, editorItems])

  const handleChange = useCallback(
    (content: string) => {
      if (updateTimeoutRef.current) clearTimeout(updateTimeoutRef.current)
      updateTimeoutRef.current = setTimeout(() => {
        const id = useTabsStore.getState().activeTabId
        if (id) updateContent(id, content)
      }, 300)
    },
    [updateContent]
  )

  useEffect(() => {
    if (!editorRef.current) return

    if (viewRef.current) viewRef.current.destroy()

    const languageExtensions = activeTab
      ? buildLanguageExtensions(activeTab.language)
      : []

    const updateListener = EditorView.updateListener.of((update) => {
      if (update.docChanged) {
        handleChange(update.state.doc.toString())
      }
      if (update.selectionSet) {
        const pos = update.state.selection.main.head
        const line = update.state.doc.lineAt(pos)
        setCursorPosition(line.number, pos - line.from + 1)
      }
    })

    const extensions: Extension[] = [
      ...(lineNumbersEnabled ? [lineNumbers(), highlightActiveLineGutter()] : [highlightActiveLineGutter()]),
      highlightActiveLine(),
      updateListener,
      keymap.of([...defaultKeymap, indentWithTab]),
      syntaxHighlighting(tokyoNightSyntax),
      buildEditorTheme(settings),
      EditorState.tabSize.of(tabSize),
      indentUnit.of(' '.repeat(tabSize)),
      languageExtensions,
    ]

    if (wordWrap) {
      extensions.push(EditorView.lineWrapping)
    }

    const state = EditorState.create({
      doc: activeTab?.content ?? '',
      extensions: extensions.flat(),
    })

    viewRef.current = new EditorView({
      state,
      parent: editorRef.current,
    })

    return () => {
      if (updateTimeoutRef.current) clearTimeout(updateTimeoutRef.current)
      viewRef.current?.destroy()
      viewRef.current = null
    }
  }, [activeTab?.id, activeTab?.language, fontSize, tabSize, fontFamily, wordWrap, lineNumbersEnabled, ruler, rulerColumn])

  useEffect(() => {
    const el = containerRef.current
    if (!el) return
    el.addEventListener('contextmenu', handleContextMenu)
    return () => el.removeEventListener('contextmenu', handleContextMenu)
  }, [handleContextMenu])

  if (!activeTab) {
    return null
  }

  return (
    <div ref={containerRef} className="flex-1 overflow-hidden bg-editor-bg">
      <div ref={editorRef} className="h-full" />
    </div>
  )
}