File size: 13,186 Bytes
f41aded
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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" />;
});