Download web/src/components/CodeEditor.tsx from SSSAssist/Thoth: direct link, hf CLI and curl.
- Browser
- Download file 13.2 kB
-
https://huggingface.co/spaces/SSSAssist/Thoth/resolve/main/web/src/components/CodeEditor.tsx
- Command line
-
hf download hf://spaces/SSSAssist/Thoth/web/src/components/CodeEditor.tsx
-
curl -L -o CodeEditor.tsx https://huggingface.co/spaces/SSSAssist/Thoth/resolve/main/web/src/components/CodeEditor.tsx
13.2 kB
| import { | |
| type Completion, type CompletionContext, autocompletion, closeBrackets, closeBracketsKeymap, completionKeymap, snippetCompletion, | |
| } from '@codemirror/autocomplete'; | |
| import { defaultKeymap, history, historyKeymap, indentWithTab } from '@codemirror/commands'; | |
| import { HighlightStyle, StreamLanguage, bracketMatching, syntaxHighlighting } from '@codemirror/language'; | |
| import { stex } from '@codemirror/legacy-modes/mode/stex'; | |
| import { highlightSelectionMatches, search, searchKeymap } from '@codemirror/search'; | |
| import { Compartment, EditorState } from '@codemirror/state'; | |
| import { EditorView, drawSelection, highlightActiveLine, highlightActiveLineGutter, keymap, lineNumbers } from '@codemirror/view'; | |
| import { tags as t } from '@lezer/highlight'; | |
| import { forwardRef, useEffect, useImperativeHandle, useRef } from 'react'; | |
| export interface EditorHandle { | |
| getSelection(): { text: string; line: number }; | |
| insertAtCursor(text: string): void; | |
| /** Seçimi `before` ve `after` ile sarar; seçim yoksa `placeholder` yazılır. */ | |
| wrapSelection(before: string, after: string, placeholder?: string): void; | |
| /** `oldText`'i belgede bulup `newText` ile değiştirir; bulunamazsa false döner. */ | |
| applyEdit(oldText: string, newText: string): boolean; | |
| goToLine(line: number): void; | |
| findText(text: string): boolean; | |
| /** Bir belgenin içeriğini dışarıdan değiştirir (ör. sürüm geri yükleme); geri alma geçmişi sıfırlanır. */ | |
| setDoc(key: string, content: string): void; | |
| /** Açık belgenin içeriğini değiştirir; yalnızca farklı kısım güncellenir ve işlem geri alınabilir. */ | |
| replaceDoc(content: string): void; | |
| focus(): void; | |
| } | |
| interface Props { | |
| docKey: string; | |
| /** docKey ilk kez açıldığında kullanılacak içerik. */ | |
| content: string; | |
| readOnly: boolean; | |
| spellcheck: boolean; | |
| onChange: (key: string, content: string) => void; | |
| onSave: () => void; | |
| onCompile: () => void; | |
| onFormat: () => void; | |
| getCiteKeys: () => string[]; | |
| } | |
| const env = (name: string, body = '\t#{}') => | |
| snippetCompletion(`\\begin{${name}}\n${body}\n\\end{${name}}`, { label: `\\begin{${name}}`, type: 'keyword' }); | |
| const cmd = (label: string, template = `${label}{#{}}`, detail?: string) => | |
| snippetCompletion(template, { label, detail, type: 'function' }); | |
| const COMMANDS: Completion[] = [ | |
| snippetCompletion('\\begin{#{ortam}}\n\t#{}\n\\end{#{ortam}}', { label: '\\begin', detail: 'ortam', type: 'keyword' }), | |
| env('itemize', '\t\\item #{}'), | |
| env('enumerate', '\t\\item #{}'), | |
| env('equation'), | |
| env('align'), | |
| env('figure', '\t\\centering\n\t\\includegraphics[width=0.8\\textwidth]{#{dosya}}\n\t\\caption{#{Açıklama}}\n\t\\label{fig:#{etiket}}'), | |
| env('table', '\t\\centering\n\t\\caption{#{Açıklama}}\n\t\\label{tab:#{etiket}}\n\t\\begin{tabular}{#{lcr}}\n\t\t#{}\n\t\\end{tabular}'), | |
| env('tabular'), | |
| env('abstract'), | |
| env('frame'), | |
| ...['chapter', 'section', 'subsection', 'subsubsection', 'paragraph', 'textbf', 'textit', 'emph', 'underline', 'texttt', | |
| 'cite', 'parencite', 'textcite', 'ref', 'eqref', 'label', 'footnote', 'caption', 'input', 'include', 'usepackage', 'title', 'author', 'date', | |
| 'sqrt', 'url', 'bibliography', 'bibliographystyle'].map((n) => cmd(`\\${n}`)), | |
| cmd('\\frac', '\\frac{#{pay}}{#{payda}}'), | |
| cmd('\\includegraphics', '\\includegraphics[width=#{0.8}\\textwidth]{#{dosya}}'), | |
| cmd('\\href', '\\href{#{adres}}{#{metin}}'), | |
| ...['item', 'maketitle', 'tableofcontents', 'newpage', 'centering', 'noindent', 'today', 'hline', 'toprule', 'midrule', | |
| 'bottomrule', 'sum', 'int', 'alpha', 'beta', 'gamma', 'delta', 'lambda', 'mu', 'pi', 'sigma', 'theta', 'infty', | |
| 'times', 'cdot', 'leq', 'geq', 'neq', 'approx', 'rightarrow', 'textwidth', 'linewidth'].map( | |
| (n): Completion => ({ label: `\\${n}`, type: 'function' }), | |
| ), | |
| ]; | |
| function completions(getCiteKeys: () => string[]) { | |
| return (ctx: CompletionContext) => { | |
| // \cite{...}, \parencite{...}, \textcite{anahtar1, anah| -> kaynakça anahtarları | |
| const cite = ctx.matchBefore(/\\[a-zA-Z]*cite[a-zA-Z]*\*?(\[[^\]]*\])*\{[^}]*/); | |
| if (cite) { | |
| const start = Math.max(cite.text.lastIndexOf('{'), cite.text.lastIndexOf(',')) + 1; | |
| const from = cite.from + start + (cite.text.slice(start).match(/^\s*/)?.[0].length ?? 0); | |
| return { from, options: getCiteKeys().map((k): Completion => ({ label: k, type: 'constant' })), validFor: /^[\w:.+-]*$/ }; | |
| } | |
| // \ref{ -> belgedeki \label'lar | |
| const ref = ctx.matchBefore(/\\(eq|page|auto)?ref\{[^}]*/); | |
| if (ref) { | |
| const labels = [...ctx.state.doc.toString().matchAll(/\\label\{([^}]+)\}/g)].map((m) => m[1]); | |
| return { | |
| from: ref.from + ref.text.indexOf('{') + 1, | |
| options: [...new Set(labels)].map((l): Completion => ({ label: l, type: 'constant' })), | |
| validFor: /^[\w:.+-]*$/, | |
| }; | |
| } | |
| const word = ctx.matchBefore(/\\[a-zA-Z]*/); | |
| if (!word) return null; | |
| return { from: word.from, options: COMMANDS, validFor: /^\\[a-zA-Z]*$/ }; | |
| }; | |
| } | |
| const highlightStyle = HighlightStyle.define([ | |
| { tag: t.tagName, color: 'var(--syn-command)' }, | |
| { tag: t.keyword, color: 'var(--syn-math)' }, | |
| { tag: t.atom, color: 'var(--syn-env)' }, | |
| { tag: [t.comment, t.lineComment], color: 'var(--syn-comment)', fontStyle: 'italic' }, | |
| { tag: t.bracket, color: 'var(--syn-bracket)' }, | |
| { tag: [t.string, t.number], color: 'var(--syn-math)' }, | |
| { tag: t.standard(t.variableName), color: 'var(--syn-env)' }, | |
| { tag: t.invalid, color: 'var(--danger)' }, | |
| ]); | |
| const theme = EditorView.theme({ | |
| '&': { height: '100%', fontSize: '14px', backgroundColor: 'var(--editor-bg)', color: 'var(--text)' }, | |
| '&.cm-focused': { outline: 'none' }, | |
| '.cm-scroller': { fontFamily: 'var(--mono)', lineHeight: '1.65' }, | |
| '.cm-content': { padding: '12px 0', caretColor: 'var(--text)' }, | |
| '.cm-line': { padding: '0 16px 0 8px' }, | |
| '.cm-gutters': { backgroundColor: 'var(--editor-bg)', color: 'var(--faint)', border: 'none' }, | |
| '.cm-activeLine, .cm-activeLineGutter': { backgroundColor: 'var(--active-line)' }, | |
| '.cm-cursor': { borderLeftColor: 'var(--text)' }, | |
| '.cm-selectionBackground, &.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground': { backgroundColor: 'var(--selection)' }, | |
| '.cm-selectionMatch': { backgroundColor: 'var(--selection-match)' }, | |
| '.cm-panels': { backgroundColor: 'var(--surface)', color: 'var(--text)', borderColor: 'var(--border)' }, | |
| '.cm-panels input, .cm-panels button': { fontSize: '13px' }, | |
| '.cm-tooltip': { backgroundColor: 'var(--surface)', color: 'var(--text)', border: '1px solid var(--border)', borderRadius: '6px' }, | |
| '.cm-tooltip-autocomplete ul li[aria-selected]': { backgroundColor: 'var(--accent)', color: '#fff' }, | |
| }); | |
| const PHRASES = { | |
| Find: 'Bul', Replace: 'Değiştir', next: 'sonraki', previous: 'önceki', all: 'tümü', 'match case': 'büyük/küçük harf', | |
| regexp: 'düzenli ifade', 'by word': 'tam sözcük', replace: 'değiştir', 'replace all': 'tümünü değiştir', close: 'kapat', | |
| 'Go to line': 'Satıra git', go: 'git', 'current match': 'geçerli eşleşme', 'on line': 'satır', | |
| }; | |
| export const CodeEditor = forwardRef<EditorHandle, Props>(function CodeEditor(props, ref) { | |
| const host = useRef<HTMLDivElement>(null); | |
| const view = useRef<EditorView | null>(null); | |
| const states = useRef(new Map<string, EditorState>()); | |
| const activeKey = useRef<string | null>(null); | |
| const latest = useRef(props); | |
| latest.current = props; | |
| const compartments = useRef({ readOnly: new Compartment(), spell: new Compartment() }); | |
| function createState(content: string) { | |
| const { readOnly, spell } = compartments.current; | |
| return EditorState.create({ | |
| doc: content, | |
| extensions: [ | |
| lineNumbers(), highlightActiveLine(), highlightActiveLineGutter(), drawSelection(), history(), bracketMatching(), | |
| closeBrackets(), highlightSelectionMatches(), search({ top: true }), EditorView.lineWrapping, | |
| StreamLanguage.define(stex), syntaxHighlighting(highlightStyle), theme, EditorState.phrases.of(PHRASES), | |
| autocompletion({ override: [completions(() => latest.current.getCiteKeys())] }), | |
| keymap.of([ | |
| { key: 'Mod-s', preventDefault: true, run: () => (latest.current.onSave(), true) }, | |
| { key: 'Mod-Enter', preventDefault: true, run: () => (latest.current.onCompile(), true) }, | |
| { key: 'Shift-Alt-f', preventDefault: true, run: () => (latest.current.onFormat(), true) }, | |
| ...closeBracketsKeymap, ...defaultKeymap, ...searchKeymap, ...historyKeymap, ...completionKeymap, indentWithTab, | |
| ]), | |
| readOnly.of(EditorState.readOnly.of(latest.current.readOnly)), | |
| spell.of(EditorView.contentAttributes.of({ spellcheck: String(latest.current.spellcheck), lang: 'tr' })), | |
| EditorView.updateListener.of((u) => { | |
| if (u.docChanged && activeKey.current) latest.current.onChange(activeKey.current, u.state.doc.toString()); | |
| }), | |
| ], | |
| }); | |
| } | |
| useEffect(() => { | |
| view.current = new EditorView({ parent: host.current! }); | |
| return () => { | |
| view.current?.destroy(); | |
| activeKey.current = null; // yeniden kurulumda eski görünümün durumu saklanmasın | |
| }; | |
| }, []); | |
| // Açık dosya değişince önceki belgenin durumu (geri alma geçmişiyle) saklanır, yenisi yüklenir. | |
| useEffect(() => { | |
| const v = view.current!; | |
| if (activeKey.current) states.current.set(activeKey.current, v.state); | |
| activeKey.current = props.docKey; | |
| v.setState(states.current.get(props.docKey) ?? createState(props.content)); | |
| }, [props.docKey]); | |
| useEffect(() => { | |
| const { readOnly, spell } = compartments.current; | |
| view.current!.dispatch({ | |
| effects: [ | |
| readOnly.reconfigure(EditorState.readOnly.of(props.readOnly)), | |
| spell.reconfigure(EditorView.contentAttributes.of({ spellcheck: String(props.spellcheck), lang: 'tr' })), | |
| ], | |
| }); | |
| }, [props.docKey, props.readOnly, props.spellcheck]); | |
| useImperativeHandle(ref, () => ({ | |
| getSelection() { | |
| const { state } = view.current!; | |
| const range = state.selection.main; | |
| return { text: state.sliceDoc(range.from, range.to), line: state.doc.lineAt(range.from).number }; | |
| }, | |
| insertAtCursor(text) { | |
| const v = view.current!; | |
| const range = v.state.selection.main; | |
| v.dispatch({ changes: { from: range.from, to: range.to, insert: text }, selection: { anchor: range.from + text.length }, scrollIntoView: true }); | |
| v.focus(); | |
| }, | |
| wrapSelection(before, after, placeholder = '') { | |
| const v = view.current!; | |
| const range = v.state.selection.main; | |
| const inner = v.state.sliceDoc(range.from, range.to) || placeholder; | |
| v.dispatch({ | |
| changes: { from: range.from, to: range.to, insert: before + inner + after }, | |
| selection: { anchor: range.from + before.length, head: range.from + before.length + inner.length }, | |
| scrollIntoView: true, | |
| }); | |
| v.focus(); | |
| }, | |
| applyEdit(oldText, newText) { | |
| const v = view.current!; | |
| const doc = v.state.doc.toString(); | |
| let from = doc.indexOf(oldText); | |
| let length = oldText.length; | |
| if (from < 0 && oldText.trim()) { | |
| // Baştaki/sondaki boşluk farklarına tolerans gösterilir. | |
| from = doc.indexOf(oldText.trim()); | |
| length = oldText.trim().length; | |
| newText = newText.trim(); | |
| } | |
| if (from < 0) return false; | |
| v.dispatch({ changes: { from, to: from + length, insert: newText }, selection: { anchor: from, head: from + newText.length }, scrollIntoView: true }); | |
| return true; | |
| }, | |
| goToLine(line) { | |
| const v = view.current!; | |
| const target = v.state.doc.line(Math.min(Math.max(line, 1), v.state.doc.lines)); | |
| v.dispatch({ selection: { anchor: target.from }, effects: EditorView.scrollIntoView(target.from, { y: 'center' }) }); | |
| v.focus(); | |
| }, | |
| findText(text) { | |
| const v = view.current!; | |
| const from = v.state.doc.toString().indexOf(text); | |
| if (from < 0) return false; | |
| v.dispatch({ selection: { anchor: from, head: from + text.length }, effects: EditorView.scrollIntoView(from, { y: 'center' }) }); | |
| v.focus(); | |
| return true; | |
| }, | |
| setDoc(key, content) { | |
| const state = createState(content); | |
| if (key === activeKey.current) view.current!.setState(state); | |
| else states.current.set(key, state); | |
| }, | |
| replaceDoc(content) { | |
| const v = view.current!; | |
| const current = v.state.doc.toString(); | |
| // Ortak baş ve son atlanır; böylece imleç ve kaydırma konumu korunur. | |
| let start = 0; | |
| while (start < current.length && start < content.length && current[start] === content[start]) start++; | |
| let end = 0; | |
| while ( | |
| end < current.length - start && end < content.length - start && | |
| current[current.length - 1 - end] === content[content.length - 1 - end] | |
| ) end++; | |
| v.dispatch({ changes: { from: start, to: current.length - end, insert: content.slice(start, content.length - end) } }); | |
| }, | |
| focus: () => view.current?.focus(), | |
| })); | |
| return <div ref={host} className="code-editor" />; | |
| }); | |