File size: 9,609 Bytes
87495f8
85ef79d
3c3f089
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85ef79d
3c3f089
5de7de7
bffbaad
 
953203e
 
 
bffbaad
 
5b465ac
3c3f089
 
 
 
 
 
 
 
 
2c2081c
 
a21e1b7
b32fabf
15ae933
a8f0877
 
5b465ac
a8f0877
3c3f089
 
 
 
fe82d96
 
 
b32fabf
 
 
 
fe82d96
3c3f089
 
 
 
 
 
 
 
 
 
 
 
 
 
85ef79d
87495f8
a21e1b7
b32fabf
 
87495f8
3c3f089
87495f8
3c3f089
85ef79d
a8f0877
3c3f089
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a8f0877
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15ae933
 
 
 
 
 
 
a8f0877
 
 
 
 
 
 
 
 
 
 
 
 
 
a21e1b7
 
 
 
00a6446
fc46386
b32fabf
 
 
 
a8f0877
b32fabf
 
 
 
 
 
 
 
a8f0877
 
 
15ae933
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3c3f089
15ae933
 
3c3f089
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15ae933
 
3c3f089
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import React, { useRef, useEffect, useState, ChangeEvent, FormEvent } from "react";
import { Message, useChat } from "ai/react";
import { useAppDispatch, useAppSelector } from "../../store/hook";
import {
  compiler_state,
  initEsbuild,
} from "../../store/features/compilerSlice";
import { editor_state, set_monaco_input_value, update_editor_code } from "../../store/features/editorSlice";
import { theme_state } from "../../store/features/themeSlice";
import { ModalEnum, open_modal } from "../../store/features/modalSlice";

import ConsoleLog from "./ConsoleLog";
import Iframe from "./Iframe";
import InputCodeTab from "./InputCodeTab";
import Footer from "./Footer";
import Pane from "./Pane";
import { SendIcon } from "../../constants/icon";
import ReactMarkdown from "react-markdown";
import { ChatRequestOptions } from "ai";

const DEFAULT_PROMPT = `You are assisting in a WASM-powered live editor, Codetree, where React code is instantly reflected in the browser. Generate React code with the following constraints:
1. Always import both React and ReactDOM.
2. All logic should be encapsulated within a single app component file.
3. Always use inline styles for styling.
4. Code snippets should conclude with rendering to the DOM's root element: ReactDOM.render(<App />, document.getElementById('root'));
5. Ensure the code is optimized for a live browser environment and adheres strictly to React best practices.

Write the code with the above guidelines in mind.`;

const Playground = () => {
  const dispatch = useAppDispatch();
  const formRef = useRef<HTMLFormElement>(null);
  const inputRef = useRef<HTMLTextAreaElement>(null);
  const { theme } = useAppSelector(theme_state);
  const { esbuildStatus, isCompiling, output } = useAppSelector(compiler_state);
  const { logs, editorValue, isLogTabOpen } = useAppSelector(editor_state);
  const [markdownCode, setMarkdownCode] = useState('');
  const [prevMarkdownCode, setPrevMarkdownCode] = useState(markdownCode);
  const [isSystemInputVisible, setSystemInputVisible] = useState(false);
  const [isModelInputVisible, setModelInputVisible] = useState(false);
  const [aiProvider, setAIProvider] = useState<string>("openai");
  const [urlOption, setUrlOption] = useState<string | any>(null);
  const [isChatVisible, setIsChatVisible] = useState(true);

  const [systemMessage, setSystemMessage] = useState(
    DEFAULT_PROMPT
  );

  const isValidCodeBlock = (markdownCode: string) => {
    return markdownCode && markdownCode.length > 10 && markdownCode.includes('\n');
  }

  const modifiedHandleSubmit = async (e: FormEvent<HTMLFormElement>, chatRequestOptions?: ChatRequestOptions) => {
    e.preventDefault();
    await handleSubmit(e, { 
      ...chatRequestOptions, 
      aiProvider, 
    } as any);
  };

  useEffect(() => {
    const timer = setInterval(() => {
      if (isValidCodeBlock(markdownCode) && markdownCode !== prevMarkdownCode) {
        dispatch(update_editor_code({ type: 'javascript', content: markdownCode }));
        setPrevMarkdownCode(markdownCode);
      }
    }, 2000);

    return () => {
      clearInterval(timer);
    };
  }, [markdownCode, prevMarkdownCode, dispatch]);

  const { append, messages, input, setInput, handleSubmit, ...rest } = useChat({
    body: {
      systemMessage: systemMessage,
      aiProvider: aiProvider,
      url: urlOption
    },
    onError: (error) => {
      console.error(error);
    },
  });

  useEffect(() => {
    if (!esbuildStatus.isReady) {
      dispatch(initEsbuild());
    }
  }, [dispatch, esbuildStatus]);

  useEffect(() => {
    dispatch(open_modal(ModalEnum.TEMPLATE));
  }, [dispatch]);

  useEffect(() => {
    if(isValidCodeBlock(markdownCode)) {
      const newEditorValue = {
        name: "React",
        description: "By codetree",
        public: true,
        iconSrc: "/icons/reactjs.svg",
        tabs: {
          javascript: {
            title: "JS/JSX",
            entryPoints: "index.js",
            monacoLanguage: "javascript",
            data: markdownCode
          },
          html: {
            title: "index.html",
            entryPoints: "index.html",
            monacoLanguage: "html",
            data: ""
          },
          css: {
            title: "main.css",
            entryPoints: "main.css",
            monacoLanguage: "css",
            data: ""
          }
        }
      };
      
      dispatch(set_monaco_input_value(newEditorValue as any));
    }
  }, [markdownCode, dispatch]);

  return (
    <div style={{ background: theme.background }}>
      <div className="flex flex-col">
          <div className="px-4 pb-2 pt-3 shadow-lg sm:pb-3 sm:pt-4">
            <span className="text-lg font-semibold">System Prompt</span>
            <button
              onClick={() => setSystemInputVisible(!isSystemInputVisible)}
              className="p-2 rounded-full hover:bg-gray-200 transition duration-300"
            >
              {isSystemInputVisible ? '−' : '+'}
            </button>
            <span className="text-lg font-semibold">Model</span>
              <button
                onClick={() => setModelInputVisible(!isModelInputVisible)}
                className="p-2 rounded-full hover:bg-gray-200 transition duration-300"
              >
                {isModelInputVisible ? '−' : '+'}
            </button>
            <span className="text-lg font-semibold">Chat</span>
              <button
                onClick={() => setIsChatVisible(!isChatVisible)}
                className="p-2 rounded-full hover:bg-gray-200 transition duration-300"
              >
                {isChatVisible ? '−' : '+'}
            </button>
            
            {isSystemInputVisible && (
              <textarea 
                className="textarea my-4 border p-2 rounded-md shadow-sm w-full resize-none" 
                value={systemMessage || ''} 
                onChange={e => setSystemMessage(e.target.value)} 
                placeholder="Enter custom system prompt here"
                rows={2} // initial number of rows, can be adjusted
                style={{ overflowWrap: 'break-word', whiteSpace: 'pre-wrap' }}
              />
            )}
            {isModelInputVisible && (
              <div className="my-4">
                <select 
                  value={aiProvider}
                  onChange={(e) => setAIProvider(e.target.value)}
                  className="border p-2 rounded-md shadow-sm w-full bg-transparent text-gray-700 mt-2"
                >
                  <option value="openai">gpt-4</option>
                  <option value="meta-llama/Meta-Llama-3-8B">meta-llama/Meta-Llama-3-8B</option>
                  <label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="url-option">
                    Model URL Option:
                  </label>
                  
                </select>
                <input 
                  id="url-option"
                  type="url"
                  placeholder="Enter URL"
                  value={urlOption}
                  onChange={(e) => setUrlOption(e.target.value)}
                  className="border p-2 rounded-md shadow-sm w-full bg-transparent text-gray-700 mt-2"
                />
              </div>
            )}

            {isChatVisible &&
                <form ref={formRef} onSubmit={modifiedHandleSubmit} className="relative w-full">
                <textarea ref={inputRef} onChange={(e) => setInput(e.target.value)}
                placeholder="Enter your message"
                onKeyDown={(e) => {
                  if (e.key === "Enter" && !e.shiftKey) {
                    formRef.current?.requestSubmit();
                    e.preventDefault();
                  }
                }}
                  spellCheck={false} className="textarea" value={input} />
                <button 
                    type="submit"
                    className="absolute inset-y-0 right-3 my-auto flex h-8 w-8 items-center justify-center rounded-md transition-all"
                >
                  <SendIcon
                      className={"h-4 w-4"}
                  />
                </button>
              </form>
            }
            
        </div>
        {isChatVisible && (
          <div className="flex flex-col items-start space-y-4 overflow-y-auto max-h-[20vh]">
          {messages?.map((message, index) => (
            <p key={index} className="messages-text">
              <ReactMarkdown
                className="prose mt-1 w-full break-words prose-p:leading-relaxed" 
                components={{
                  a: (props) => (
                    <a {...props} target="_blank" rel="noopener noreferrer" />
                  ),
                  // @ts-ignore
                  code: ({node, ...props}) => {
                    const codeValue = props.children[0] || '';
                    setMarkdownCode(codeValue as any);
                    
                    return null;
                  }                    
                }}
              >
                {message.content}
              </ReactMarkdown>
            </p>
          ))}
          </div>
        )}
      </div>
      <Pane
        panelA={<InputCodeTab editorValue={editorValue} />}
        panelB={
          <Iframe
            tabs={editorValue.tabs}
            output={output}
            isCompiling={isCompiling}
            esbuildStatus={esbuildStatus}
          />
        }
        panelC={<ConsoleLog logs={logs} />}
        lastPanelVisibility={isLogTabOpen}
      />

      <Footer />
    </div>

  );
};

export default Playground;