summaryrefslogtreecommitdiff
path: root/frontend/src/components/document/DocumentEditor.tsx
blob: 2ef37feb28a565428c8180a4c6ddf9463b42895e (plain) (blame)
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
import { useCallback, useRef, useState } from 'react';
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 { HeadingNode } from '@lexical/rich-text';
import { ListNode, ListItemNode } from '@lexical/list';
import { LinkNode } from '@lexical/link';
import {
  $getRoot,
  $createParagraphNode,
  $createTextNode,
  type EditorState,
  type LexicalEditor,
} from 'lexical';
import { $createHeadingNode } from '@lexical/rich-text';

import { StepsDiagramNode, $isStepsDiagramNode, $createStepsDiagramNode } from './nodes/StepsDiagramNode';
import { ContractBlockNode, $isContractBlockNode } from './nodes/ContractBlockNode';
import editorTheme from './EditorTheme';
import AutoSavePlugin from './AutoSavePlugin';
import ContextMenu, { type ContextMenuAction } from './ContextMenu';
import './DocumentEditor.css';
import './nodes/StepsDiagram.css';
import './nodes/ContractBlock.css';

interface DocumentEditorProps {
  directiveId: string;
  title: string;
  goal: string;
  status: string;
  prBranch?: string | null;
  onGoalChange?: (newGoal: string) => void;
  onTitleChange?: (newTitle: string) => void;
  onCleanup?: () => void;
  onCreatePr?: () => void;
  onPlanOrders?: () => void;
  onTogglePause?: () => void;
  readOnly?: boolean;
}

function buildInitialEditorState(directiveId: string, title: string, goal: string) {
  return () => {
    const root = $getRoot();

    // Title as H1
    const heading = $createHeadingNode('h1');
    heading.append($createTextNode(title));
    root.append(heading);

    // Goal as paragraph(s), split by newlines
    const lines = goal.split('\n');
    for (const line of lines) {
      const paragraph = $createParagraphNode();
      if (line.trim()) {
        paragraph.append($createTextNode(line));
      }
      root.append(paragraph);
    }

    // Insert steps diagram node after the goal content
    const stepsNode = $createStepsDiagramNode(directiveId);
    root.append(stepsNode);

    // Add a trailing paragraph so the user can type below the diagram
    const trailingParagraph = $createParagraphNode();
    root.append(trailingParagraph);
  };
}

function onError(error: Error) {
  console.error('[DocumentEditor] Lexical error:', error);
}

export default function DocumentEditor({
  directiveId,
  title,
  goal,
  status,
  prBranch,
  onGoalChange,
  onTitleChange,
  onCleanup,
  onCreatePr,
  onPlanOrders,
  onTogglePause,
  readOnly = false,
}: DocumentEditorProps) {
  const editorRef = useRef<LexicalEditor | null>(null);
  const latestGoalRef = useRef(goal);
  const latestTitleRef = useRef(title);

  // Context menu state
  const [ctxMenu, setCtxMenu] = useState<{ x: number; y: number } | null>(null);

  const initialConfig = {
    namespace: `DocumentEditor-${directiveId}`,
    theme: editorTheme,
    editorState: buildInitialEditorState(directiveId, title, goal),
    nodes: [HeadingNode, ListNode, ListItemNode, LinkNode, StepsDiagramNode, ContractBlockNode],
    onError,
    editable: !readOnly,
  };

  const handleChange = useCallback(
    (_editorState: EditorState, editor: LexicalEditor) => {
      editorRef.current = editor;

      editor.getEditorState().read(() => {
        const root = $getRoot();
        const children = root.getChildren();

        let newTitle = '';
        const goalLines: string[] = [];

        for (let i = 0; i < children.length; i++) {
          const child = children[i];
          // Skip decorator nodes (steps diagram, contract blocks) when extracting text
          if ($isStepsDiagramNode(child)) continue;
          if ($isContractBlockNode(child)) continue;

          const text = child.getTextContent();

          if (i === 0 && child.getType() === 'heading') {
            newTitle = text;
          } else {
            goalLines.push(text);
          }
        }

        const newGoal = goalLines.join('\n');

        if (newTitle !== latestTitleRef.current) {
          latestTitleRef.current = newTitle;
          onTitleChange?.(newTitle);
        }

        if (newGoal !== latestGoalRef.current) {
          latestGoalRef.current = newGoal;
          onGoalChange?.(newGoal);
        }
      });
    },
    [onGoalChange, onTitleChange]
  );

  const getContent = useCallback(() => {
    return latestGoalRef.current;
  }, []);

  const handleAutoSave = useCallback(
    (content: string) => {
      onGoalChange?.(content);
    },
    [onGoalChange]
  );

  // Context menu handler
  const handleContextMenu = useCallback(
    (e: React.MouseEvent) => {
      e.preventDefault();
      setCtxMenu({ x: e.clientX, y: e.clientY });
    },
    []
  );

  const closeCtxMenu = useCallback(() => setCtxMenu(null), []);

  const isPaused = status === 'paused';
  const isIdle = status === 'idle';

  const ctxActions: ContextMenuAction[] = [
    {
      label: 'Clean Up',
      icon: '\uD83E\uDDF9', // broom
      disabled: !isIdle,
      onClick: () => onCleanup?.(),
    },
    {
      label: 'Update PR',
      icon: '\uD83D\uDD00', // shuffle
      disabled: !prBranch,
      onClick: () => onCreatePr?.(),
    },
    {
      label: 'Plan Orders',
      icon: '\uD83D\uDCCB', // clipboard
      onClick: () => onPlanOrders?.(),
    },
    {
      label: isPaused ? 'Resume Directive' : 'Pause Directive',
      icon: isPaused ? '\u25B6' : '\u23F8',
      onClick: () => onTogglePause?.(),
    },
  ];

  return (
    <div className="document-editor-container" onContextMenu={handleContextMenu}>
      <LexicalComposer initialConfig={initialConfig}>
        <div className="doc-editor-input">
          <RichTextPlugin
            contentEditable={
              <ContentEditable className="doc-editor-content-editable doc-editor-root" />
            }
            placeholder={
              <div className="doc-editor-placeholder">Start writing...</div>
            }
            ErrorBoundary={LexicalErrorBoundary}
          />
        </div>
        <HistoryPlugin />
        <OnChangePlugin onChange={handleChange} />
        {!readOnly && (
          <AutoSavePlugin
            onAutoSave={handleAutoSave}
            getContent={getContent}
            enabled={!readOnly}
          />
        )}
      </LexicalComposer>

      {ctxMenu && (
        <ContextMenu
          x={ctxMenu.x}
          y={ctxMenu.y}
          actions={ctxActions}
          dividerAfter={[2]}
          onClose={closeCtxMenu}
        />
      )}
    </div>
  );
}