File size: 7,189 Bytes
4af09f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { useEffect, useState, useCallback, useRef } from 'react';
import { useFileStore } from '../../stores/fileStore';
import { LexicalComposer } from '@lexical/react/LexicalComposer';
import { RichTextPlugin } from '@lexical/react/LexicalRichTextPlugin';
import { ContentEditable } from '@lexical/react/LexicalContentEditable';
import { HistoryPlugin } from '@lexical/react/LexicalHistoryPlugin';
import { OnChangePlugin } from '@lexical/react/LexicalOnChangePlugin';
import LexicalErrorBoundary from '@lexical/react/LexicalErrorBoundary';

import LineNumbers from './LineNumberPlugin';
import HoverToolbar from './HoverToolbar';
import AutoHighlighterPlugin from '../../plugins/AutoHighlighterPlugin';
import { CloudSavingDone01Icon, Tick02Icon } from 'hugeicons-react';
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext';
import { INSERT_LINE_BREAK_COMMAND, COMMAND_PRIORITY_EDITOR, $createLineBreakNode, $getSelection, $isRangeSelection } from 'lexical';

// Premium Theme mapping for Lexical
const theme = {
  paragraph: 'editor-paragraph',
  text: {
    bold: 'editor-text-bold',
    italic: 'editor-text-italic',
    strikethrough: 'editor-text-strikethrough',
    underline: 'editor-text-underline',
  },
};

export default function EditorCore() {
  const { files, activeFileId, updateFileContent } = useFileStore();
  const [editorKey, setEditorKey] = useState(0);
  const [isSaving, setIsSaving] = useState(false);
  const debounceRef = useRef<any>(null);

  const ShiftEnterPlugin = () => {
    const [editor] = useLexicalComposerContext();
    useEffect(() => {
      return editor.registerCommand(
        INSERT_LINE_BREAK_COMMAND,
        () => {
          editor.update(() => {
            const selection = $getSelection();
            if ($isRangeSelection(selection)) {
              selection.insertNodes([$createLineBreakNode()]);
            }
          });
          return true;
        },
        COMMAND_PRIORITY_EDITOR
      );
    }, [editor]);
    return null;
  };

  const activeFile = files.find(f => f.id === activeFileId && f.type === 'file');

  // Ensure editor re-initializes exactly on file change
  useEffect(() => {
    setEditorKey(k => k + 1);
  }, [activeFileId]);

  // Clipboard Transformation (Emdash Prefix)
  useEffect(() => {
    const handleCopy = (e: ClipboardEvent) => {
      const selection = window.getSelection();
      if (!selection || selection.rangeCount === 0) return;
      
      let text = selection.toString();
      if (!text) return;

      // SPEC: Emdash as very beginning of number line with content
      // Logic: Prefix lines with content with "— " (emdash + space)
      const lines = text.split('\n');
      const transformed = lines.map(line => {
        if (line.trim().length > 0) {
          return `— ${line}`;
        }
        return line;
      }).join('\n');

      e.clipboardData?.setData('text/plain', transformed);
      e.preventDefault();
    };

    document.addEventListener('copy', handleCopy);
    return () => document.removeEventListener('copy', handleCopy);
  }, []);

  const handleOnChange = useCallback((editorState: any) => {
    setIsSaving(true);
    if (debounceRef.current) clearTimeout(debounceRef.current);
    
    debounceRef.current = setTimeout(() => {
      editorState.read(() => {
         const jsonString = JSON.stringify(editorState.toJSON());
         if (activeFileId) {
            updateFileContent(activeFileId, jsonString).then(() => {
               setIsSaving(false);
            });
         } else {
            setIsSaving(false);
         }
      });
    }, 300); // 300ms debounce for near-instant premium persistence
  }, [activeFileId, updateFileContent]);

  if (!activeFile) {
    return (
      <div className="editor-placeholder" style={{ 
        display: 'flex', flexDirection: 'column', gap: '8px', opacity: 0.4, 
        fontFamily: 'var(--font-ibm-plex)' 
      }}>
        <div style={{ fontSize: '14px', fontWeight: 500 }}>No active document</div>
        <div style={{ fontSize: '11px' }}>Select a file from the sidebar to begin editing.</div>
      </div>
    );
  }

  const initialConfig = {
    namespace: 'HybridDocEditor',
    theme,
    nodes: [],
    onError(error: Error) {
      console.error('Lexical Error:', error);
    },
    editorState: activeFile.content ? (
       activeFile.content.includes('"root":{') ? activeFile.content : undefined
    ) : undefined,
  };

  return (
    <div key={`editor-${editorKey}`} className="editor-shell" style={{ display: 'flex', flexDirection: 'column', height: '100%', flex: 1 }}>
       <LexicalComposer initialConfig={initialConfig}>
        <div className="editor-scroller" style={{ flex: 1, overflowY: 'auto', display: 'flex', position: 'relative' }}>
          <LineNumbers />
          <div className="editor-input-container" style={{ flex: 1, padding: '24px 32px', position: 'relative' }}>
              <RichTextPlugin
                contentEditable={
                  <ContentEditable 
                    className="ContentEditable" 
                    spellCheck={true}
                    data-gramm="true"
                    data-gramm_editor="true"
                    data-enable-grammarly="true"
                    style={{ 
                      minHeight: '100%', 
                      outline: 'none', 
                      lineHeight: '1.5',
                      fontSize: '15px'
                    }} 
                  />
                }
                placeholder={
                  <div className="editor-placeholder" style={{ 
                    position: 'absolute', top: 24, left: 32, pointerEvents: 'none', opacity: 0.3, fontSize: '15px' 
                  }}>
                    Start your thinking here...
                  </div>
                }
                ErrorBoundary={LexicalErrorBoundary}
              />
              <HistoryPlugin />
              <OnChangePlugin onChange={handleOnChange} ignoreSelectionChange />
              <ShiftEnterPlugin />
              <HoverToolbar />
              <AutoHighlighterPlugin />
              
              {/* Save Status Indicator */}
              <div style={{
                position: 'fixed',
                bottom: '24px',
                right: '24px',
                display: 'flex',
                alignItems: 'center',
                gap: '8px',
                padding: '6px 12px',
                background: 'var(--bg-panel)',
                border: '1px solid var(--border-color)',
                borderRadius: '20px',
                fontSize: '11px',
                fontWeight: 600,
                color: 'var(--text-secondary)',
                opacity: isSaving ? 1 : 0.4,
                transition: 'opacity 0.3s ease',
                pointerEvents: 'none',
                boxShadow: '0 4px 12px rgba(0,0,0,0.05)',
                zIndex: 10
              }}>
                {isSaving ? <CloudSavingDone01Icon size={14} className="spin" /> : <Tick02Icon size={14} />}
                {isSaving ? 'Syncing...' : 'Saved'}
              </div>
          </div>
        </div>
       </LexicalComposer>
    </div>
  );
}