File size: 6,064 Bytes
b9ce80a
 
 
 
 
 
3e9eff3
b9ce80a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e9eff3
b9ce80a
3e9eff3
b9ce80a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { useEffect, useMemo, useRef, useState } from "react";
import { Link, useParams } from "react-router";

import { logout } from "wasp/client/auth";
import { getSpec, resetSection, updateSection, useQuery } from "wasp/client/operations";

import { SECTION_TEMPLATES, isSectionDone } from "./sections.js";
import "./styles.css";

export const SpecPage = ({ user }) => {
  const { id } = useParams();
  const specId = Number(id);
  const { data: spec, isLoading, error } = useQuery(getSpec, { id: specId });

  const [drafts, setDrafts] = useState({});
  const [current, setCurrent] = useState(0);
  const [mode, setMode] = useState("edit");
  const [saveState, setSaveState] = useState("idle");
  const timerRef = useRef(null);

  // Seed drafts from the server exactly once per loaded section.
  useEffect(() => {
    if (spec?.sections) {
      setDrafts((prev) => {
        const next = { ...prev };
        spec.sections.forEach((s) => {
          if (next[s.key] === undefined) next[s.key] = s.content;
        });
        return next;
      });
    }
  }, [spec]);

  const sections = spec?.sections ?? [];
  const sec = sections[current];

  const doneCount = useMemo(
    () => sections.filter((s) => isSectionDone(drafts[s.key])).length,
    [sections, drafts]
  );

  const handleChange = (value) => {
    if (!sec) return;
    setDrafts((d) => ({ ...d, [sec.key]: value }));
    setSaveState("saving");
    clearTimeout(timerRef.current);
    timerRef.current = setTimeout(async () => {
      try {
        await updateSection({ specId, key: sec.key, content: value });
        setSaveState("saved");
      } catch (err) {
        setSaveState("error");
      }
    }, 700);
  };

  const markdown = useMemo(() => {
    if (!spec) return "";
    return (
      `# Tech Spec — ${spec.title}\n\n` +
      sections
        .map((s, i) => `## ${i + 1}. ${s.title}\n\n${(drafts[s.key] ?? s.content).trim()}`)
        .join("\n\n---\n\n")
    );
  }, [spec, sections, drafts]);

  if (isLoading) {
    return <div className="wrap lede">Loading…</div>;
  }
  if (error) {
    return <div className="wrap"><p className="lede">Error: {error.message}</p><Link to="/">← Back</Link></div>;
  }
  if (!spec) return null;

  return (
    <div className="app">
      <header className="topbar">
        <Link to="/" className="logo row" style={{ textDecoration: "none", color: "inherit" }}>
          <div className="logo-mark" />SpecForge
        </Link>
        <span className={"chip" + (doneCount === sections.length ? " ready" : "")}>
          {doneCount}/{sections.length}{doneCount === sections.length ? " · ready for harness" : ""}
        </span>
        <div className="sp" />
        <button className="btn" onClick={() => setMode(mode === "edit" ? "preview" : "edit")}>
          {mode === "edit" ? "Preview" : "Edit"}
        </button>
        <button className="btn primary" onClick={() => copyToClipboard(markdown)}>Copy Markdown</button>
        <button className="btn" onClick={logout}>Logout</button>
      </header>
      <div className="wrap">
        <div className="editor">
          <nav className="sidenav">
            {sections.map((s, i) => (
              <button key={s.key} className={"secbtn" + (i === current ? " on" : "")} onClick={() => setCurrent(i)}>
                <span className={"dot" + (isSectionDone(drafts[s.key]) ? " done" : "")} />
                {s.title}
              </button>
            ))}
          </nav>
          <div className="pane">
            <div className="kick">Section {String(current + 1).padStart(2, "0")} of {sections.length}</div>
            <div className="h1" style={{ fontSize: 18 }}>{sec?.title}</div>
            <div className="hint">{sec?.hint}</div>
            {mode === "edit" ? (
              <textarea value={drafts[sec?.key] ?? ""} onChange={(e) => handleChange(e.target.value)} spellCheck="false" />
            ) : (
              <div className="preview">{drafts[sec?.key] ?? ""}</div>
            )}
            <div className="statusline">
              <span>{wordCount(drafts[sec?.key])} words</span>
              {saveState === "saving" && <span>saving…</span>}
              {saveState === "saved" && <span className="saved">✓ saved</span>}
              {saveState === "error" && <span style={{ color: "var(--warn)" }}>save failed</span>}
              <div className="sp" />
              <button
                className="btn"
                onClick={async () => {
                  if (!sec) return;
                  const template = SECTION_TEMPLATES.find((t) => t.key === sec.key);
                  await resetSection({ specId, key: sec.key }).catch((e) => window.alert(e.message));
                  setDrafts((d) => ({ ...d, [sec.key]: template?.starter ?? d[sec.key] }));
                }}
              >
                Reset section
              </button>
              <button className="btn" onClick={() => setCurrent((current + sections.length - 1) % sections.length)}>← Prev</button>
              <button className="btn" onClick={() => setCurrent((current + 1) % sections.length)}>Next →</button>
            </div>
          </div>
        </div>
        <p className="lede" style={{ marginTop: 14, fontSize: 12 }}>
          Signed in as {user?.identities?.username?.id} · spec #{spec.id} · every edit autosaves to the database.
        </p>
      </div>
    </div>
  );
};

function wordCount(text) {
  const t = (text ?? "").trim();
  return t ? t.split(/\s+/).length : 0;
}

async function copyToClipboard(text) {
  try {
    await navigator.clipboard.writeText(text);
    toast("Copied full spec as Markdown — paste into a .md file");
  } catch {
    toast("Clipboard blocked — select the preview text manually");
  }
}

function toast(msg) {
  let el = document.querySelector(".toast");
  if (!el) {
    el = document.createElement("div");
    el.className = "toast";
    document.body.appendChild(el);
  }
  el.textContent = msg;
  el.classList.add("show");
  setTimeout(() => el.classList.remove("show"), 2000);
}