File size: 8,293 Bytes
ea6c2a8
 
 
22916b8
ea6c2a8
 
 
 
 
 
 
 
bcb0fad
5dcafa7
 
7017720
ea6c2a8
 
bc2c276
a582fa0
ea6c2a8
 
 
a450a2d
ea6c2a8
 
 
18847f3
ea6c2a8
 
5dcafa7
ea6c2a8
 
 
 
 
 
 
 
 
 
 
bc2c276
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22916b8
 
bc2c276
 
 
 
 
 
 
ea6c2a8
 
22916b8
bc2c276
 
 
22916b8
ea6c2a8
22916b8
 
 
 
 
 
 
bc2c276
 
ea6c2a8
 
 
 
 
 
 
 
 
 
 
 
 
 
bc2c276
bcb0fad
 
 
 
 
 
 
bc2c276
ea6c2a8
bc2c276
ea6c2a8
22916b8
bc2c276
18847f3
 
 
 
a582fa0
bc2c276
 
ea6c2a8
bc2c276
ea6c2a8
 
bc2c276
ea6c2a8
 
bc2c276
ea6c2a8
 
 
 
 
 
bc2c276
ea6c2a8
 
 
 
356a639
 
 
 
 
 
 
 
 
 
 
 
a450a2d
356a639
 
 
5dcafa7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea6c2a8
a582fa0
ea6c2a8
 
a582fa0
ea6c2a8
 
 
 
 
 
 
 
bcb0fad
7017720
5dcafa7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea6c2a8
 
5dcafa7
ea6c2a8
 
 
a450a2d
ea6c2a8
 
 
 
 
a582fa0
ea6c2a8
bcb0fad
 
 
 
ea6c2a8
7017720
 
 
ea6c2a8
 
 
 
 
 
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
import { useRef, useState } from "react";
import Editor from "@monaco-editor/react";
import classNames from "classnames";
import { useMount, useUnmount, useEvent, useLocalStorage } from "react-use";
import { toast } from "react-toastify";

import Header from "./header/header";
import DeployButton from "./deploy-button/deploy-button";
import { defaultHTML } from "../utils/consts";
import Tabs from "./tabs/tabs";
import AskAI from "./ask-ai/ask-ai";
import { Auth } from "../utils/types";
import Preview from "./preview/preview";
import WysiwygEditor from "./wysiwyg/wysiwyg-editor";
import SavedPages from "./saved-pages/saved-pages";
import Loading from "./loading/loading";

function App() {
  const [htmlStorage, , removeHtmlStorage] = useLocalStorage("html_content");

  const preview = useRef<HTMLDivElement>(null);
  const editor = useRef<HTMLDivElement>(null);
  const resizer = useRef<HTMLDivElement>(null);
  // Removed editorRef

  const [isResizing, setIsResizing] = useState(false);
  const [error, setError] = useState(false);
  const [html, setHtml] = useState((htmlStorage as string) ?? defaultHTML);
  const [isAiWorking, setisAiWorking] = useState(false);
  const [auth, setAuth] = useState<Auth | undefined>(undefined);
  const [editMode, setEditMode] = useState<'code' | 'wysiwyg'>('code');

  const fetchMe = async () => {
    const res = await fetch("/api/@me");
    if (res.ok) {
      const data = await res.json();
      setAuth(data);
    } else {
      setAuth(undefined);
    }
  };

  /**
   * Resets the layout based on screen size
   * - For desktop: Sets editor to 1/3 width and preview to 2/3
   * - For mobile: Removes inline styles to let CSS handle it
   */
  const resetLayout = () => {
    if (!editor.current || !preview.current) return;

    // lg breakpoint is 1024px based on useBreakpoint definition and Tailwind defaults
    if (window.innerWidth >= 1024) {
      // Set initial 1/3 - 2/3 sizes for large screens, accounting for resizer width
      const resizerWidth = resizer.current?.offsetWidth ?? 8; // w-2 = 0.5rem = 8px
      const availableWidth = window.innerWidth - resizerWidth;
      const initialEditorWidth = availableWidth / 3; // Editor takes 1/3 of space
      const initialPreviewWidth = availableWidth - initialEditorWidth; // Preview takes 2/3
      editor.current.style.width = `${initialEditorWidth}px`;
      preview.current.style.width = `${initialPreviewWidth}px`;
    } else {
      // Remove inline styles for smaller screens, let CSS flex-col handle it
      editor.current.style.width = "";
      preview.current.style.width = "";
    }
  };

  /**
   * Handles resizing when the user drags the resizer
   * Ensures minimum widths are maintained for both panels
   */
  const handleResize = (e: MouseEvent) => {
    if (!editor.current || !preview.current || !resizer.current) return;

    const resizerWidth = resizer.current.offsetWidth;
    const minWidth = 100; // Minimum width for editor/preview
    const maxWidth = window.innerWidth - resizerWidth - minWidth;

    const editorWidth = e.clientX;
    const clampedEditorWidth = Math.max(
      minWidth,
      Math.min(editorWidth, maxWidth)
    );
    const calculatedPreviewWidth =
      window.innerWidth - clampedEditorWidth - resizerWidth;

    editor.current.style.width = `${clampedEditorWidth}px`;
    preview.current.style.width = `${calculatedPreviewWidth}px`;
  };

  const handleMouseDown = () => {
    setIsResizing(true);
    document.addEventListener("mousemove", handleResize);
    document.addEventListener("mouseup", handleMouseUp);
  };

  const handleMouseUp = () => {
    setIsResizing(false);
    document.removeEventListener("mousemove", handleResize);
    document.removeEventListener("mouseup", handleMouseUp);
  };

  // Prevent accidental navigation away when AI is working or content has changed
  useEvent("beforeunload", (e) => {
    if (isAiWorking || html !== defaultHTML) {
      e.preventDefault();
      return "";
    }
  });

  // Initialize component on mount
  useMount(() => {
    // Fetch user data
    fetchMe();

    // Restore content from storage if available
    if (htmlStorage) {
      removeHtmlStorage();
      toast.warn("Previous HTML content restored from local storage.");
    }

    // Set initial layout based on window size
    resetLayout();

    // Attach event listeners
    if (!resizer.current) return;
    resizer.current.addEventListener("mousedown", handleMouseDown);
    window.addEventListener("resize", resetLayout);
  });

  // Clean up event listeners on unmount
  useUnmount(() => {
    document.removeEventListener("mousemove", handleResize);
    document.removeEventListener("mouseup", handleMouseUp);
    if (resizer.current) {
      resizer.current.removeEventListener("mousedown", handleMouseDown);
    }
    window.removeEventListener("resize", resetLayout);
  });

  return (
    <div className="h-screen bg-gray-950 font-sans overflow-hidden">
      <Header
        onReset={() => {
          if (isAiWorking) {
            toast.warn("Please wait for the AI to finish working.");
            return;
          }
          if (
            window.confirm("You're about to reset the editor. Are you sure?")
          ) {
            setHtml(defaultHTML);
            setError(false);
            removeHtmlStorage();
            // Removed editorRef scroll logic
          }
        }}
      >
        <div className="flex space-x-2">
          <SavedPages 
            currentHtml={html} 
            onLoadPage={(savedHtml) => {
              setHtml(savedHtml);
              setError(false);
            }} 
          />
          <button
            className="px-3 py-1.5 bg-purple-600 hover:bg-purple-700 text-white rounded text-sm"
            onClick={() => setEditMode(editMode === 'code' ? 'wysiwyg' : 'code')}
          >
            {editMode === 'code' ? 'Visual Editor' : 'Code Editor'}
          </button>
          <DeployButton html={html} error={error} auth={auth} />
        </div>
      </Header>
      <main className="max-lg:flex-col flex w-full">
        <div
          ref={editor}
          className="w-full h-[30dvh] lg:h-full relative"
          onClick={(e) => {
            if (isAiWorking) {
              e.preventDefault();
              e.stopPropagation();
              toast.warn("Please wait for the AI to finish working.");
            }
          }}
        >
          <Tabs />
          {isAiWorking && <Loading progress={0} showDetails={false} />}
          {editMode === 'code' ? (
            <Editor
              language="html"
              theme="vs-dark"
              className={classNames(
                "h-[calc(30dvh-41px)] lg:h-[calc(100dvh-96px)]",
                {
                  "pointer-events-none": isAiWorking,
                }
              )}
              value={html}
              onValidate={(markers) => {
                if (markers?.length > 0) {
                  setError(true);
                }
              }}
              onChange={(value) => {
                const newValue = value ?? "";
                setHtml(newValue);
                setError(false);
              }}
            />
          ) : (
            <div className="h-[calc(30dvh-41px)] lg:h-[calc(100dvh-96px)] overflow-hidden bg-gray-950">
              <WysiwygEditor 
                html={html}
                onSave={(updatedHtml) => {
                  setHtml(updatedHtml);
                  setError(false);
                }}
              />
            </div>
          )}
          <AskAI
            html={html}
            setHtml={setHtml}
            isAiWorking={isAiWorking}
            setisAiWorking={setisAiWorking}
            onScrollToBottom={() => {
              // For now, removing the direct editor scroll.
            }}
          />
        </div>
        <div
          ref={resizer}
          className="bg-gray-700 hover:bg-blue-500 w-2 cursor-col-resize h-[calc(100dvh-54px)] max-lg:hidden"
        />
        <Preview
          html={html}
          isResizing={isResizing}
          isAiWorking={isAiWorking}
          ref={preview}
        >
          {isAiWorking && <Loading progress={0} showDetails={false} />}
        </Preview>
      </main>
    </div>
  );
}

export default App;