Spaces:
Running

explication / js /screens.js
quantilimited's picture
Serve the paid Explication build with Paragraph model downloads
30247fe
Raw History Blame Contribute Delete
35.4 kB
import { React, html, useEffect, useMemo, useRef, useState } from "./runtime.js";
import { useApp } from "./store.js";
import { useEngine } from "./engine.js";
import { Copy } from "./copy.js";
import {
Mark,
FeedbackPanel,
Notice,
Pill,
ScoreRing,
CriterionList,
usePersistent,
download,
Icon,
SECTIONS
} from "./components.js";
import {
CREDIT_COSTS,
ESSAY_PART_META,
ESSAY_RUBRICS,
PARAGRAPH_RUBRIC,
SUGGESTED_QUESTIONS,
TEXTS,
awardCredits,
checkQuotes,
combineEssay,
creditsForEssay,
levelTitle,
reviewEssayPart,
reviewParagraph,
reviewText,
sentenceList,
wordCount,
buildMarkingMessages,
parseMarkingReply
} from "./marking.js";
// ---------------------------------------------------------------------------
// Shared pieces
// ---------------------------------------------------------------------------
function PageHead({ kicker, title, subtitle, right }) {
return html`<div class="row between" style=${{ alignItems: "flex-start", gap: "16px" }}>
<div>
<div class="eyebrow">${kicker}</div>
<h1 class="page-title">${title}</h1>
${subtitle && html`<p class="subtitle">${subtitle}</p>`}
</div>
${right}
</div>`;
}
function WordCounter({ text }) {
return html`<span class="count">${wordCount(text)} words</span>`;
}
function QuestionField({ value, onChange, placeholder }) {
return html`<div class="field">
<label>Question <span class="hint">optional</span></label>
<input class="input" list="question-ideas" value=${value} onInput=${(e) => onChange(e.target.value)} placeholder=${placeholder} />
<datalist id="question-ideas">
${SUGGESTED_QUESTIONS.map((q) => html`<option key=${q} value=${q}></option>`)}
</datalist>
</div>`;
}
function TextPicker({ value, onChange }) {
return html`<div class="field">
<label>Text</label>
<select class="select" value=${value} onChange=${(e) => onChange(e.target.value)}>
${TEXTS.map((t) => html`<option key=${t.id} value=${t.id}>${t.title}${t.author ? " · " + t.author : ""}</option>`)}
</select>
</div>`;
}
function EngineHint({ compact = false }) {
const engine = useEngine();
if (engine.canGenerate) {
return html`<${Notice} kind="info">Model connected — ${engine.hasEndpoint ? "using your endpoint." : "running in this browser."} Chat and model answers are available.<//>`;
}
return html`<${Notice} kind="warn">
AI chat and model answers need a model. Download a Paragraph model in
<a href="#/settings">Settings</a> to run it on your own machine, or connect an OpenAI-compatible endpoint. The marking tools below work without one.
<//>`;
}
// ---------------------------------------------------------------------------
// Dashboard
// ---------------------------------------------------------------------------
export function Dashboard({ onNavigate }) {
const app = useApp();
const engine = useEngine();
const hour = new Date().getHours();
const greeting = hour < 12 ? "Good morning." : hour < 18 ? "Good afternoon." : "Good evening.";
const date = new Date().toLocaleDateString("en-GB", { weekday: "long", day: "numeric", month: "long" });
const recent = app.drafts.slice(0, 5);
const practice = [
{ id: "essay", title: "Essay", text: "Five parts, thirty marks, one argument." },
{ id: "poetry", title: "Unseen poetry", text: "Paste the poem. Check every quotation." },
{ id: "improve", title: "Improve", text: "One sentence at a time." },
{ id: "mockExam", title: "Mock exam", text: "Sit a timed paper, then mark it." }
];
return html`<main class="page">
<div class="eyebrow">${date.toUpperCase()}</div>
<h1 class="display">${greeting}</h1>
<p class="subtitle">
${app.settings.name ? app.settings.name + ", a" : "A"} quiet place to practise the paragraph, then see exactly what to improve.
</p>
<div class="card hero" style=${{ marginTop: "18px" }}>
<div style=${{ maxWidth: "520px" }}>
<h2 class="card-title"><${Copy} id="dashboard.hero.title">Your writing, marked offline.</${Copy}></h2>
<p class="subtitle" style=${{ margin: "0 0 14px" }}>
<${Copy} id="dashboard.hero.body">Paste a paragraph, add the extract if you have one, and get a mark out of ten against the GCSE criteria — with the single next change that matters.</${Copy}>
</p>
<div class="row wrap">
<button class="btn primary" onClick=${() => onNavigate("coach")}><${Icon} name="pen" size=${14} /> New feedback</button>
<button class="btn" onClick=${() => onNavigate("chat")}><${Icon} name="chat" size=${14} /> Talk it through</button>
</div>
</div>
<${Mark} size=${64} />
</div>
<div class="grid four" style=${{ marginTop: "12px" }}>
<div class="stat"><div class="head">Credits <span>✦</span></div><div class="value">${app.credits}</div><div class="note">Earned by marking</div></div>
<div class="stat"><div class="head">Streak</div><div class="value">${app.streak} <span style=${{ fontSize: "13px", color: "var(--faint)" }}>days</span></div><div class="note">Consecutive marked days</div></div>
<div class="stat"><div class="head">Level</div><div class="value">${app.level}</div><div class="note">${levelTitle(app.level)}</div></div>
<div class="stat"><div class="head">Average</div><div class="value">${app.average}%</div><div class="note">Last ${Math.min(20, app.drafts.length)} marked pieces</div></div>
</div>
<div class="card" style=${{ marginTop: "12px" }}>
<div class="row between wrap" style=${{ alignItems: "flex-start" }}>
<div style=${{ maxWidth: "560px" }}>
<div class="row" style=${{ gap: "7px" }}><i style=${{ width: 6, height: 6, borderRadius: "50%", background: engine.canGenerate ? "var(--success)" : "var(--warning)" }}></i>
<span class="mini-label" style=${{ color: "var(--secondary)" }}>${engine.canGenerate ? "Model connected" : "Rule-based review"}</span>
</div>
<div style=${{ fontWeight: 600, marginTop: "6px" }}>${engine.hasEndpoint ? "Your endpoint" : engine.hostedReady ? "Hosted model" : "Marks in this browser"}</div>
<div class="tiny faint" style=${{ marginTop: "2px", lineHeight: 1.5 }}>
${engine.canGenerate
? "Chat, model answers and AI suggestions are available. Marking still checks the rubric point by point."
: "Every mark is computed here from your words, quotations and technique — no upload, no account. Connect a model for chat and model answers."}
</div>
</div>
<button class="btn small" onClick=${() => onNavigate("settings")}>Model settings</button>
</div>
</div>
<div class="section-head"><h2 class="section-title"><${Copy} id="dashboard.practice.title">Other ways to practise</${Copy}></h2></div>
<div class="grid four">
${practice.map(
(p) => html`<button key=${p.id} class="card flat" style=${{ textAlign: "left" }} onClick=${() => onNavigate(p.id)}>
<div style=${{ fontFamily: "var(--serif)", fontSize: "15px", fontWeight: 600 }}>${p.title}</div>
<div class="tiny faint" style=${{ marginTop: "4px", lineHeight: 1.5 }}>${p.text}</div>
<div class="tiny" style=${{ color: "var(--accent)", marginTop: "9px", fontWeight: 600 }}>Open →</div>
</button>`
)}
</div>
<div class="section-head">
<h2 class="section-title">Recent</h2>
${recent.length > 0 && html`<button class="btn link small" onClick=${() => onNavigate("process")}>Process log</button>`}
</div>
<div class="card">
${recent.length === 0
? html`<div class="empty"><${Mark} size=${34} /><div style=${{ fontSize: "12px" }}>Your first marked piece will appear here.</div></div>`
: html`<div class="list">
${recent.map(
(d) => html`<div class="list-row" key=${d.id}>
<div class="main">
<div class="t">${d.title || "Untitled"}${d.question ? " · " + d.question : ""}</div>
<div class="s">${new Date(d.at).toLocaleDateString("en-GB", { day: "numeric", month: "short" })} · ${d.mode} · ${wordCount(d.text)} words</div>
</div>
<span class="pill green">${d.score}/${d.max}</span>
</div>`
)}
</div>`}
</div>
</main>`;
}
// ---------------------------------------------------------------------------
// Chat
// ---------------------------------------------------------------------------
const CHAT_SYSTEM = [
"You are Explication, a GCSE English Literature writing coach for students in England.",
"You are in a normal conversation. Answer questions about texts, techniques, marks and revision in British English.",
"Address the student as 'you'. Be precise, warm and brief: at most 140 words unless asked for more.",
"Never write the student's paragraph or essay for them in chat. If they ask for finished work, explain that the paid 'Write paragraph' action produces a clearly labelled study draft instead."
].join(" ");
export function Chat() {
const app = useApp();
const engine = useEngine();
const [input, setInput] = useState("");
const [busy, setBusy] = useState(false);
const [streaming, setStreaming] = useState("");
const [error, setError] = useState("");
const [pending, setPending] = useState(false);
const [showExtract, setShowExtract] = useState(false);
const endRef = useRef(null);
useEffect(() => {
if (endRef.current) endRef.current.scrollIntoView({ behavior: "smooth", block: "end" });
}, [app.chat.length, streaming]);
const send = async () => {
const text = input.trim();
if (!text || busy) return;
if (!engine.canGenerate) {
setError("Chatting needs a model. Open Settings to load a browser model or connect an endpoint. The marking tools work without one.");
return;
}
setError("");
setInput("");
setBusy(true);
setStreaming("");
app.addChat({ role: "student", text });
try {
const history = app.chat.slice(-8).map((m) => ({
role: m.role === "student" ? "user" : "assistant",
content: m.text
}));
const messages = [
{ role: "system", content: CHAT_SYSTEM },
...(app.chatExtract.trim()
? [{ role: "system", content: "The student is working with this extract:\n" + app.chatExtract.slice(0, 4000) }]
: []),
...history,
{ role: "user", content: text }
];
const full = await engine.chat(messages, setStreaming);
app.addChat({ role: "assistant", text: full || "(No reply.)" });
} catch (err) {
setError(err && err.message ? err.message : "The model could not reply.");
}
setStreaming("");
setBusy(false);
};
const writeParagraph = async () => {
if (!engine.canGenerate || app.credits < CREDIT_COSTS.paragraphWriting) return;
const topic = input.trim() || "the extract and question we are discussing";
setPending(false);
setError("");
setBusy(true);
setStreaming("");
app.spend(CREDIT_COSTS.paragraphWriting);
app.addChat({ role: "student", text: "Write a study paragraph about: " + topic });
try {
const messages = [
{
role: "system",
content:
"You write a single model GCSE English Literature paragraph for study, clearly labelled as AI-written. 120-180 words, British English. Embed one or two short quotations only if an extract is supplied; never invent quotations. Return only the paragraph."
},
{
role: "user",
content: (app.chatExtract ? "Extract:\n" + app.chatExtract + "\n\n" : "") + "Topic: " + topic
}
];
const full = await engine.chat(messages, setStreaming);
app.addChat({ role: "draft", text: full || "(No draft.)" });
} catch (err) {
setError(err && err.message ? err.message : "The draft could not be written.");
app.addCredits(CREDIT_COSTS.paragraphWriting);
}
setStreaming("");
setBusy(false);
};
return html`<main class="chat-wrap">
<div class="transcript">
<div class="transcript-inner">
${!engine.canGenerate && html`<${EngineHint} />`}
${error && html`<${Notice} kind="error">${error}<//>`}
${app.chat.length === 0 &&
html`<div class="card" style=${{ marginTop: "6px" }}>
<div class="row" style=${{ gap: "10px", marginBottom: "10px" }}><${Mark} size=${38} />
<div><div class="eyebrow">Paragraph, in conversation</div>
<div style=${{ fontFamily: "var(--serif)", fontSize: "21px", fontWeight: 600 }}>Ask me anything.</div></div>
</div>
<p class="subtitle" style=${{ margin: 0 }}>
Ask about a character, a technique, your marks or how to revise. Chatting is free. Asking for a finished paragraph costs ${CREDIT_COSTS.paragraphWriting} credits and is always labelled AI-written.
</p>
<div class="row wrap" style=${{ marginTop: "12px" }}>
${[
"What does a semantic field actually mean?",
"How should I revise Macbeth's ambition?",
"Why did I lose effect marks?"
].map(
(q) => html`<button key=${q} class="btn small" onClick=${() => setInput(q)}>${q}</button>`
)}
</div>
</div>`}
${app.chat.map(
(m) => html`<div class=${"msg " + (m.role === "student" ? "student" : "")} key=${m.id}>
${m.role !== "student" && html`<${Mark} size=${24} />`}
<div>
<div class="who">${m.role === "student" ? "You" : m.role === "draft" ? "AI-written study draft" : "Explication"}</div>
<div class="bubble" style=${m.role === "draft" ? { background: "var(--warning-soft)", borderColor: "#f0dcc5" } : {}}>${m.text}</div>
${m.role === "draft" && html`<div class="tiny" style=${{ color: "var(--warning)", marginTop: "4px" }}>Study material only — do not submit this as your own work.</div>`}
</div>
</div>`
)}
${streaming &&
html`<div class="msg"><${Mark} size=${24} />
<div><div class="who">Explication</div><div class="bubble">${streaming}</div></div>
</div>`}
${busy && !streaming && html`<div class="msg"><${Mark} size=${24} /><div class="bubble"><span class="spin"></span></div></div>`}
<div ref=${endRef}></div>
</div>
</div>
<div class="composer-dock">
<div class="composer">
${showExtract &&
html`<div style=${{ padding: "4px 4px 8px" }}>
<div class="field">
<label>Extract <span class="hint">optional · quotations are checked against it</span></label>
<textarea class="textarea plain" style=${{ minHeight: "80px", fontFamily: "var(--serif)" }} value=${app.chatExtract} onInput=${(e) => app.setChatExtract(e.target.value)} placeholder="Paste the passage you are working on."></textarea>
</div>
</div>`}
${pending &&
html`<div class="callout amber" style=${{ margin: "4px 4px 8px", display: "flex", gap: "10px", alignItems: "center", justifyContent: "space-between" }}>
<span>Spend ${CREDIT_COSTS.paragraphWriting} credits on a labelled AI paragraph?</span>
<span class="row"><button class="btn small" onClick=${() => setPending(false)}>Cancel</button><button class="btn small primary" onClick=${writeParagraph}>Spend</button></span>
</div>`}
<div class="row">
<button class="icon-btn ${showExtract ? "active" : ""}" title="Extract" onClick=${() => setShowExtract((v) => !v)}><${Icon} name="file" size=${15} /></button>
<textarea
value=${input}
onInput=${(e) => setInput(e.target.value)}
onKeyDown=${(e) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
send();
}
}}
placeholder=${engine.canGenerate ? "Message Explication — ask about a text, a technique or your writing…" : "Connect a model in Settings to chat."}
rows="1"
disabled=${busy}
></textarea>
<button class="send" onClick=${send} disabled=${!input.trim() || busy || !engine.canGenerate} aria-label="Send"><${Icon} name="up" size=${15} /></button>
</div>
<div class="foot">
<div class="row" style=${{ gap: "8px" }}>
<button class="btn small ghost" onClick=${() => (app.credits >= CREDIT_COSTS.paragraphWriting ? setPending(true) : null)} disabled=${!engine.canGenerate || busy}>
<${Icon} name="sparkle" size=${11} /> Write paragraph · ${CREDIT_COSTS.paragraphWriting} cr
</button>
<span class="tiny faint">${app.credits} credits</span>
</div>
<div class="row" style=${{ gap: "8px" }}>
${app.chat.length > 0 && html`<button class="btn small ghost" onClick=${app.clearChat}>New chat</button>`}
<span class="tiny faint"><span class="kbd">↵</span> send</span>
</div>
</div>
</div>
</div>
</main>`;
}
// ---------------------------------------------------------------------------
// Paragraph coach + poetry workspace
// ---------------------------------------------------------------------------
function Workspace({ mode, kicker, title, subtitle, supportsExtract, poemMode = false, writingLabel, writingPlaceholder, marksLabel }) {
const app = useApp();
const [textId, setTextId] = usePersistent("explication." + mode + ".textId", poemMode ? "power-conflict" : "macbeth");
const [question, setQuestion] = usePersistent("explication." + mode + ".question", "");
const [extract, setExtract] = usePersistent("explication." + mode + ".extract", "");
const [draft, setDraft] = usePersistent("explication." + mode + ".draft", "");
const [feedback, setFeedback] = useState(null);
const [showExtract, setShowExtract] = useState(false);
const [error, setError] = useState("");
const text = TEXTS.find((t) => t.id === textId) || TEXTS[0];
const mark = () => {
setError("");
if (wordCount(draft) < 8) {
setError("Write at least a sentence before marking.");
return;
}
const result = reviewText({
text: draft,
question,
extract: poemMode ? extract : supportsExtract && showExtract ? extract : extract,
rubric: PARAGRAPH_RUBRIC,
title: text.title
});
setFeedback(result);
app.recordDraft({
mode: mode === "coach" ? "Paragraph coach" : "Unseen poetry",
title: text.title,
question,
extract,
text: draft,
score: result.total,
max: result.max,
feedback: result,
summary: result.nextStep
});
};
return html`<main class="page">
<${PageHead} kicker=${kicker} title=${title} subtitle=${subtitle}
right=${html`<div class="row"><${Pill} tone="green">${marksLabel || "Marked /10"}<//></div>`} />
<div class="grid split" style=${{ marginTop: "18px" }}>
<div class="stack" style=${{ gap: "12px" }}>
<div class="card">
<div class="stack">
<${TextPicker} value=${textId} onChange=${setTextId} />
<${QuestionField} value=${question} onChange=${setQuestion} placeholder="How does the writer present…" />
${poemMode &&
html`<div class="field">
<label>Poem <span class="hint">paste the whole text</span></label>
<textarea class="textarea" style=${{ minHeight: "150px" }} value=${extract} onInput=${(e) => setExtract(e.target.value)} placeholder="Paste every stanza. Quotations are checked against this text."></textarea>
</div>`}
${!poemMode && supportsExtract &&
html`<div class="field">
<label>Extract <span class="hint">optional</span></label>
${showExtract
? html`<textarea class="textarea" style=${{ minHeight: "110px" }} value=${extract} onInput=${(e) => setExtract(e.target.value)} placeholder="Paste the passage. Any quotation is checked against it."></textarea>`
: html`<button class="btn small" style=${{ alignSelf: "flex-start" }} onClick=${() => setShowExtract(true)}><${Icon} name="plus" size=${12} /> Add the extract</button>`}
</div>`}
</div>
</div>
<div class="card">
<div class="row between" style=${{ marginBottom: "7px" }}>
<label style=${{ fontSize: "11px", fontWeight: 600, color: "var(--secondary)" }}>${writingLabel}</label>
<${WordCounter} text=${draft} />
</div>
<textarea class="textarea" style=${{ minHeight: "210px" }} value=${draft} onInput=${(e) => setDraft(e.target.value)} placeholder=${writingPlaceholder}></textarea>
${error && html`<div style=${{ marginTop: "8px" }}><${Notice} kind="error">${error}<//></div>`}
<div class="row between" style=${{ marginTop: "10px" }}>
<button class="btn ghost small" onClick=${() => { setDraft(""); setFeedback(null); }}>Clear</button>
<button class="btn primary" onClick=${mark}><${Icon} name="check" size=${13} /> Mark my writing</button>
</div>
<div class="tiny faint" style=${{ marginTop: "6px" }}>Marking is free and earns credits. Nothing leaves this browser.</div>
</div>
</div>
<div>
<${FeedbackPanel} feedback=${feedback} />
${!feedback &&
html`<div class="card" style=${{ marginTop: "12px" }}>
<div class="eyebrow">How it is marked</div>
<div class="stack" style=${{ marginTop: "8px", gap: "8px" }}>
${PARAGRAPH_RUBRIC.map(
(c) => html`<div key=${c.id} class="row" style=${{ alignItems: "flex-start", gap: "8px" }}>
<span class="pill neutral" style=${{ minWidth: "26px", justifyContent: "center" }}>${c.max}</span>
<div><div style=${{ fontSize: "11.5px", fontWeight: 600 }}>${c.title}</div>
<div class="tiny faint" style=${{ lineHeight: 1.45 }}>${c.guidance.split(".")[0]}.</div></div>
</div>`
)}
</div>
</div>`}
</div>
</div>
</main>`;
}
export function Coach() {
return html`<${Workspace}
mode="coach"
kicker="Paragraph coach"
title="One paragraph, marked properly."
subtitle="Write one analytical paragraph about a text you are studying. You get a mark out of ten against the GCSE criteria, and the single change that would raise it most."
supportsExtract=${true}
writingLabel="Your paragraph"
writingPlaceholder="Write one paragraph here. Embed a short quotation if you can."
marksLabel="Marked /10"
/>`;
}
export function Poetry() {
return html`<${Workspace}
mode="poetry"
kicker="Unseen poetry"
title="Read the poem, then write."
subtitle="Paste the whole poem, then write one analytical paragraph. Because the app has the entire text, a quotation that is not in it is a real error."
poemMode=${true}
writingLabel="Your paragraph"
writingPlaceholder="Write one paragraph about the poem: a method, a quotation, and what it makes the reader feel."
marksLabel="Marked /10"
/>`;
}
// ---------------------------------------------------------------------------
// Essay
// ---------------------------------------------------------------------------
export function Essay() {
const app = useApp();
const [textId, setTextId] = usePersistent("explication.essay.textId", "macbeth");
const [question, setQuestion] = usePersistent("explication.essay.question", "");
const [extract, setExtract] = usePersistent("explication.essay.extract", "");
const [parts, setParts] = usePersistent("explication.essay.parts", {});
const [feedbacks, setFeedbacks] = usePersistent("explication.essay.feedbacks", {});
const [active, setActive] = useState("introduction");
const [error, setError] = useState("");
const text = TEXTS.find((t) => t.id === textId) || TEXTS[0];
const currentText = parts[active] || "";
const currentFeedback = feedbacks[active] || null;
const markPart = (id) => {
const body = parts[id] || "";
if (wordCount(body) < 8) {
setError("Write this part before marking it.");
return;
}
setError("");
const rubric = id === "cohesion" ? ESSAY_RUBRICS.cohesion : ESSAY_RUBRICS[id];
const source = id === "cohesion" ? ESSAY_PART_META.filter((p) => p.id !== "cohesion").map((p) => parts[p.id] || "").join("\n\n") : body;
const result = reviewText({ text: source, question, extract, rubric, title: text.title });
setFeedbacks((f) => ({ ...f, [id]: result }));
};
const markAll = () => {
const next = { ...feedbacks };
let marked = 0;
for (const meta of ESSAY_PART_META) {
const body = parts[meta.id] || "";
if (meta.id === "cohesion") {
const source = ESSAY_PART_META.filter((p) => p.id !== "cohesion").map((p) => parts[p.id] || "").join("\n\n");
if (wordCount(source) >= 20) {
next.cohesion = reviewText({ text: source, question, extract, rubric: ESSAY_RUBRICS.cohesion, title: text.title });
}
continue;
}
if (wordCount(body) >= 8) {
next[meta.id] = reviewText({ text: body, question, extract, rubric: ESSAY_RUBRICS[meta.id], title: text.title });
marked += 1;
}
}
setFeedbacks(next);
setError(marked === 0 ? "Write at least one part first." : "");
};
const totals = combineEssay(ESSAY_PART_META.map((m) => feedbacks[m.id]).filter(Boolean));
const saveEssay = () => {
if (totals.max < 30) {
setError("Mark every part, including cohesion, before saving the essay.");
return;
}
const fullText = ESSAY_PART_META.map((m) => (parts[m.id] || "").trim()).filter(Boolean).join("\n\n");
app.recordDraft({
mode: "Essay",
title: text.title,
question,
extract,
text: fullText,
score: totals.total,
max: totals.max,
feedback: { total: totals.total, max: totals.max, criteria: [], strengths: [], improvements: [], nextStep: "", quotes: [] },
summary: "Full essay"
});
setError("");
};
return html`<main class="page">
<${PageHead} kicker="Essay" title="Build the argument, part by part."
subtitle="Mark each part on its own criteria, then the whole essay for cohesion. The marks add up to thirty — the same shape as the exam."
right=${html`<div class="row"><span class="pill neutral">${totals.total}/${totals.max || 30}</span></div>`} />
<div class="card" style=${{ marginTop: "18px" }}>
<div class="grid two">
<${TextPicker} value=${textId} onChange=${setTextId} />
<${QuestionField} value=${question} onChange=${setQuestion} placeholder="How does the writer present…" />
</div>
<div class="field" style=${{ marginTop: "10px" }}>
<label>Extract <span class="hint">optional · quotations are checked against it</span></label>
<textarea class="textarea" style=${{ minHeight: "80px" }} value=${extract} onInput=${(e) => setExtract(e.target.value)} placeholder="Paste the passage if the question gives you one."></textarea>
</div>
</div>
<div class="row wrap" style=${{ marginTop: "14px", gap: "6px" }}>
${ESSAY_PART_META.map(
(m) => html`<button key=${m.id}
class=${"btn small" + (active === m.id ? " primary" : "")}
onClick=${() => setActive(m.id)}>
${m.short}
${feedbacks[m.id] && html`<span style=${{ opacity: .7 }}>${feedbacks[m.id].total}/${feedbacks[m.id].max}</span>`}
</button>`
)}
</div>
<div class="grid split" style=${{ marginTop: "14px" }}>
<div class="card">
<div class="row between" style=${{ marginBottom: "7px" }}>
<label style=${{ fontSize: "11px", fontWeight: 600, color: "var(--secondary)" }}>
${ESSAY_PART_META.find((m) => m.id === active).title}
</label>
<${WordCounter} text=${currentText} />
</div>
<textarea class="textarea" style=${{ minHeight: "240px" }}
value=${currentText}
onInput=${(e) => setParts((p) => ({ ...p, [active]: e.target.value }))}
placeholder=${active === "cohesion"
? "Cohesion is marked from the parts you have written — no separate text needed."
: active === "introduction"
? "Open with a shaped line of argument that answers the question."
: active === "conclusion"
? "Return to the question, then say why it matters beyond this text."
: "One topic sentence, evidence, then method and effect developed together."}></textarea>
${error && html`<div style=${{ marginTop: "8px" }}><${Notice} kind="error">${error}<//></div>`}
<div class="row between" style=${{ marginTop: "10px" }}>
<div class="row">
<button class="btn ghost small" onClick=${markAll}>Mark all parts</button>
<button class="btn ghost small" onClick=${saveEssay} disabled=${totals.max < 30}>Save essay</button>
</div>
<button class="btn primary" onClick=${() => markPart(active)}><${Icon} name="check" size=${13} /> Mark this part</button>
</div>
</div>
<div>
<${FeedbackPanel} feedback=${currentFeedback} />
${totals.max > 0 &&
html`<div class="card" style=${{ marginTop: "12px" }}>
<div class="row between"><span class="eyebrow">Whole essay</span><span class="pill green">${totals.total}/${totals.max}</span></div>
<div class="bar" style=${{ marginTop: "9px", height: "6px" }}><i style=${{ width: (totals.total / Math.max(totals.max, 30)) * 100 + "%" }}></i></div>
<div class="tiny faint" style=${{ marginTop: "6px" }}>
Parts marked: ${ESSAY_PART_META.filter((m) => feedbacks[m.id]).length} of 6.
${totals.max === 30 && " Save the essay to earn credits on the full mark."}
</div>
</div>`}
</div>
</div>
</main>`;
}
// ---------------------------------------------------------------------------
// Improve
// ---------------------------------------------------------------------------
export function Improve() {
const app = useApp();
const engine = useEngine();
const [sentence, setSentence] = usePersistent("explication.improve.sentence", "");
const [feedback, setFeedback] = useState(null);
const [suggestion, setSuggestion] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
const analyse = () => {
if (wordCount(sentence) < 4) {
setError("Paste one sentence first.");
return;
}
setError("");
setFeedback(reviewText({ text: sentence, rubric: PARAGRAPH_RUBRIC, title: "Improve" }));
};
const askForSuggestion = async () => {
if (!engine.canGenerate) {
setError("A stronger version needs a model. Open Settings to connect one.");
return;
}
setError("");
setBusy(true);
setSuggestion("");
try {
const result = await engine.chat(
[
{
role: "system",
content:
"You are a GCSE English Literature coach. Improve ONE sentence the student wrote. Return only the improved sentence, no explanation, no quotation marks."
},
{ role: "user", content: sentence }
],
setSuggestion
);
setSuggestion(result.trim());
} catch (err) {
setError(err && err.message ? err.message : "The model could not reply.");
}
setBusy(false);
};
const techniques = feedback ? feedback.techniques : [];
const tree = html`<main class="page narrow">
<${PageHead} kicker="Improve" title="One sentence at a time."
subtitle="Pick a sentence from your own draft. The review names what it is doing, then you rewrite it stronger. A finished suggestion is available when a model is connected."
right=${html`<span class="pill neutral">Free review</span>`} />
<div class="card" style=${{ marginTop: "18px" }}>
<div class="field">
<label>Your sentence <span class="hint">${wordCount(sentence)} words</span></label>
<textarea class="textarea" style=${{ minHeight: "90px" }} value=${sentence} onInput=${(e) => setSentence(e.target.value)} placeholder="He is very angry and shouts at her."></textarea>
</div>
<div class="row between" style=${{ marginTop: "10px" }}>
<button class="btn ghost small" onClick=${() => { setSentence(""); setFeedback(null); setSuggestion(""); }}>Clear</button>
<button class="btn primary" onClick=${analyse}><${Icon} name="sparkle" size=${13} /> Review the sentence</button>
</div>
${error && html`<div style=${{ marginTop: "8px" }}><${Notice} kind="error">${error}<//></div>`}
</div>
${feedback &&
html`<div class="grid two" style=${{ marginTop: "12px" }}>
<div class="card">
<div class="eyebrow">What the sentence is doing</div>
<div class="stack" style=${{ marginTop: "8px" }}>
<div class="row wrap" style=${{ gap: "5px" }}>
${techniques.length > 0
? techniques.map((t, i) => html`<span key=${t + i} class="pill green">${t}</span>`)
: html`<span class="pill neutral">No technique named</span>`}
</div>
<div class="tiny muted" style=${{ lineHeight: 1.6 }}>
${techniques.length > 0
? "You name a method. Now say what it makes the reader feel, and why."
: "This is telling, not showing. Name the method (verb choice, imagery, a short sentence) before you explain the effect."}
</div>
<div class="divider"></div>
<div class="row between"><span class="tiny faint">Sentences</span><span class="tiny">${sentenceList(sentence).length}</span></div>
<div class="row between"><span class="tiny faint">Words</span><span class="tiny">${wordCount(sentence)}</span></div>
</div>
</div>
<div class="card">
<div class="row between">
<div class="eyebrow">A stronger version</div>
<${Pill} tone=${engine.canGenerate ? "green" : "neutral"}>${engine.canGenerate ? "AI suggestion" : "Needs a model"}<//>
</div>
${suggestion
? html`<div class="callout green" style=${{ marginTop: "9px", fontFamily: "var(--serif)", fontSize: "14px" }}>${suggestion}</div>
<div class="tiny faint" style=${{ marginTop: "7px" }}>Study suggestion only — rewrite it in your own voice.</div>`
: html`<p class="tiny faint" style=${{ marginTop: "9px", lineHeight: 1.6 }}>Ask for one rewritten sentence. It is a suggestion, not your own work, and it never replaces your attempt.</p>`}
<button class="btn" style=${{ marginTop: "10px" }} onClick=${askForSuggestion} disabled=${busy || !engine.canGenerate}>
${busy ? html`<span class="spin"></span>` : html`<${Icon} name="sparkle" size=${13} />`} ${suggestion ? "Try another" : "Suggest a stronger sentence"}
</button>
</div>
</div>`}
</main>`;
return tree;
}