File size: 6,242 Bytes
f0743f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import React, { useMemo, useState, useEffect, useRef, memo } from 'react';
import debounce from 'lodash/debounce';
import { KeyBinding } from '@codemirror/view';
import { autocompletion, completionKeymap } from '@codemirror/autocomplete';
import {
  useSandpack,
  SandpackCodeEditor,
  SandpackProvider as StyledProvider,
} from '@codesandbox/sandpack-react';
import type { SandpackProviderProps } from '@codesandbox/sandpack-react/unstyled';
import type { SandpackBundlerFile } from '@codesandbox/sandpack-client';
import type { CodeEditorRef } from '@codesandbox/sandpack-react';
import type { ArtifactFiles, Artifact } from '~/common';
import { useEditArtifact, useGetStartupConfig } from '~/data-provider';
import { useMutationState, useCodeState } from '~/Providers/EditorContext';
import { useArtifactsContext } from '~/Providers';
import { sharedFiles, sharedOptions } from '~/utils/artifacts';

const CodeEditor = memo(
  ({
    fileKey,
    readOnly,
    artifact,
    editorRef,
  }: {
    fileKey: string;
    readOnly?: boolean;
    artifact: Artifact;
    editorRef: React.MutableRefObject<CodeEditorRef>;
  }) => {
    const { sandpack } = useSandpack();
    const [currentUpdate, setCurrentUpdate] = useState<string | null>(null);
    const { isMutating, setIsMutating } = useMutationState();
    const { setCurrentCode } = useCodeState();
    const editArtifact = useEditArtifact({
      onMutate: (vars) => {
        setIsMutating(true);
        setCurrentUpdate(vars.updated);
      },
      onSuccess: () => {
        setIsMutating(false);
        setCurrentUpdate(null);
      },
      onError: () => {
        setIsMutating(false);
      },
    });

    /**
     * Create stable debounced mutation that doesn't depend on changing callbacks
     * Use refs to always access the latest values without recreating the debounce
     */
    const artifactRef = useRef(artifact);
    const isMutatingRef = useRef(isMutating);
    const currentUpdateRef = useRef(currentUpdate);
    const editArtifactRef = useRef(editArtifact);
    const setCurrentCodeRef = useRef(setCurrentCode);

    useEffect(() => {
      artifactRef.current = artifact;
    }, [artifact]);

    useEffect(() => {
      isMutatingRef.current = isMutating;
    }, [isMutating]);

    useEffect(() => {
      currentUpdateRef.current = currentUpdate;
    }, [currentUpdate]);

    useEffect(() => {
      editArtifactRef.current = editArtifact;
    }, [editArtifact]);

    useEffect(() => {
      setCurrentCodeRef.current = setCurrentCode;
    }, [setCurrentCode]);

    /**
     * Create debounced mutation once - never recreate it
     * All values are accessed via refs so they're always current
     */
    const debouncedMutation = useMemo(
      () =>
        debounce((code: string) => {
          if (readOnly) {
            return;
          }
          if (isMutatingRef.current) {
            return;
          }
          if (artifactRef.current.index == null) {
            return;
          }

          const artifact = artifactRef.current;
          const artifactIndex = artifact.index;
          const isNotOriginal =
            code && artifact.content != null && code.trim() !== artifact.content.trim();
          const isNotRepeated =
            currentUpdateRef.current == null
              ? true
              : code != null && code.trim() !== currentUpdateRef.current.trim();

          if (artifact.content && isNotOriginal && isNotRepeated && artifactIndex != null) {
            setCurrentCodeRef.current(code);
            editArtifactRef.current.mutate({
              index: artifactIndex,
              messageId: artifact.messageId ?? '',
              original: artifact.content,
              updated: code,
            });
          }
        }, 500),
      [readOnly],
    );

    /**
     * Listen to Sandpack file changes and trigger debounced mutation
     */
    useEffect(() => {
      const currentCode = (sandpack.files['/' + fileKey] as SandpackBundlerFile | undefined)?.code;
      if (currentCode) {
        debouncedMutation(currentCode);
      }
    }, [sandpack.files, fileKey, debouncedMutation]);

    /**
     * Cleanup: cancel pending mutations when component unmounts or artifact changes
     */
    useEffect(() => {
      return () => {
        debouncedMutation.cancel();
      };
    }, [artifact.id, debouncedMutation]);

    return (
      <SandpackCodeEditor
        ref={editorRef}
        showTabs={false}
        showRunButton={false}
        showLineNumbers={true}
        showInlineErrors={true}
        readOnly={readOnly === true}
        extensions={[autocompletion()]}
        extensionsKeymap={Array.from<KeyBinding>(completionKeymap)}
        className="hljs language-javascript bg-black"
      />
    );
  },
);

export const ArtifactCodeEditor = function ({
  files,
  fileKey,
  template,
  artifact,
  editorRef,
  sharedProps,
  readOnly: externalReadOnly,
}: {
  fileKey: string;
  artifact: Artifact;
  files: ArtifactFiles;
  template: SandpackProviderProps['template'];
  sharedProps: Partial<SandpackProviderProps>;
  editorRef: React.MutableRefObject<CodeEditorRef>;
  readOnly?: boolean;
}) {
  const { data: config } = useGetStartupConfig();
  const { isSubmitting } = useArtifactsContext();
  const options: typeof sharedOptions = useMemo(() => {
    if (!config) {
      return sharedOptions;
    }
    return {
      ...sharedOptions,
      activeFile: '/' + fileKey,
      bundlerURL: template === 'static' ? config.staticBundlerURL : config.bundlerURL,
    };
  }, [config, template, fileKey]);
  const initialReadOnly = (externalReadOnly ?? false) || (isSubmitting ?? false);
  const [readOnly, setReadOnly] = useState(initialReadOnly);
  useEffect(() => {
    setReadOnly((externalReadOnly ?? false) || (isSubmitting ?? false));
  }, [isSubmitting, externalReadOnly]);

  if (Object.keys(files).length === 0) {
    return null;
  }

  return (
    <StyledProvider
      theme="dark"
      files={{
        ...files,
        ...sharedFiles,
      }}
      options={options}
      {...sharedProps}
      template={template}
    >
      <CodeEditor fileKey={fileKey} artifact={artifact} editorRef={editorRef} readOnly={readOnly} />
    </StyledProvider>
  );
};