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`
${kicker}

${title}

${subtitle && html`

${subtitle}

`}
${right}
`; } function WordCounter({ text }) { return html`${wordCount(text)} words`; } function QuestionField({ value, onChange, placeholder }) { return html`
onChange(e.target.value)} placeholder=${placeholder} /> ${SUGGESTED_QUESTIONS.map((q) => html``)}
`; } function TextPicker({ value, onChange }) { return html`
`; } 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 Settings 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`
${date.toUpperCase()}

${greeting}

${app.settings.name ? app.settings.name + ", a" : "A"} quiet place to practise the paragraph, then see exactly what to improve.

<${Copy} id="dashboard.hero.title">Your writing, marked offline.

<${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.

<${Mark} size=${64} />
Credits ✦
${app.credits}
Earned by marking
Streak
${app.streak} days
Consecutive marked days
Level
${app.level}
${levelTitle(app.level)}
Average
${app.average}%
Last ${Math.min(20, app.drafts.length)} marked pieces
${engine.canGenerate ? "Model connected" : "Rule-based review"}
${engine.hasEndpoint ? "Your endpoint" : engine.hostedReady ? "Hosted model" : "Marks in this browser"}
${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."}

<${Copy} id="dashboard.practice.title">Other ways to practise

${practice.map( (p) => html`` )}

Recent

${recent.length > 0 && html``}
${recent.length === 0 ? html`
<${Mark} size=${34} />
Your first marked piece will appear here.
` : html`
${recent.map( (d) => html`
${d.title || "Untitled"}${d.question ? " · " + d.question : ""}
${new Date(d.at).toLocaleDateString("en-GB", { day: "numeric", month: "short" })} · ${d.mode} · ${wordCount(d.text)} words
${d.score}/${d.max}
` )}
`}
`; } // --------------------------------------------------------------------------- // 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`
${!engine.canGenerate && html`<${EngineHint} />`} ${error && html`<${Notice} kind="error">${error}`} ${app.chat.length === 0 && html`
<${Mark} size=${38} />
Paragraph, in conversation
Ask me anything.

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.

${[ "What does a semantic field actually mean?", "How should I revise Macbeth's ambition?", "Why did I lose effect marks?" ].map( (q) => html`` )}
`} ${app.chat.map( (m) => html`
${m.role !== "student" && html`<${Mark} size=${24} />`}
${m.role === "student" ? "You" : m.role === "draft" ? "AI-written study draft" : "Explication"}
${m.text}
${m.role === "draft" && html`
Study material only — do not submit this as your own work.
`}
` )} ${streaming && html`
<${Mark} size=${24} />
Explication
${streaming}
`} ${busy && !streaming && html`
<${Mark} size=${24} />
`}
${showExtract && html`
`} ${pending && html`
Spend ${CREDIT_COSTS.paragraphWriting} credits on a labelled AI paragraph?
`}
${app.credits} credits
${app.chat.length > 0 && html``} ↵ send
`; } // --------------------------------------------------------------------------- // 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`
<${PageHead} kicker=${kicker} title=${title} subtitle=${subtitle} right=${html`
<${Pill} tone="green">${marksLabel || "Marked /10"}
`} />
<${TextPicker} value=${textId} onChange=${setTextId} /> <${QuestionField} value=${question} onChange=${setQuestion} placeholder="How does the writer present…" /> ${poemMode && html`
`} ${!poemMode && supportsExtract && html`
${showExtract ? html`` : html``}
`}
<${WordCounter} text=${draft} />
${error && html`
<${Notice} kind="error">${error}
`}
Marking is free and earns credits. Nothing leaves this browser.
<${FeedbackPanel} feedback=${feedback} /> ${!feedback && html`
How it is marked
${PARAGRAPH_RUBRIC.map( (c) => html`
${c.max}
${c.title}
${c.guidance.split(".")[0]}.
` )}
`}
`; } 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`
<${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`
${totals.total}/${totals.max || 30}
`} />
<${TextPicker} value=${textId} onChange=${setTextId} /> <${QuestionField} value=${question} onChange=${setQuestion} placeholder="How does the writer present…" />
${ESSAY_PART_META.map( (m) => html`` )}
<${WordCounter} text=${currentText} />
${error && html`
<${Notice} kind="error">${error}
`}
<${FeedbackPanel} feedback=${currentFeedback} /> ${totals.max > 0 && html`
Whole essay${totals.total}/${totals.max}
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."}
`}
`; } // --------------------------------------------------------------------------- // 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`
<${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`Free review`} />
${error && html`
<${Notice} kind="error">${error}
`}
${feedback && html`
What the sentence is doing
${techniques.length > 0 ? techniques.map((t, i) => html`${t}`) : html`No technique named`}
${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."}
Sentences${sentenceList(sentence).length}
Words${wordCount(sentence)}
A stronger version
<${Pill} tone=${engine.canGenerate ? "green" : "neutral"}>${engine.canGenerate ? "AI suggestion" : "Needs a model"}
${suggestion ? html`
${suggestion}
Study suggestion only — rewrite it in your own voice.
` : html`

Ask for one rewritten sentence. It is a suggestion, not your own work, and it never replaces your attempt.

`}
`}
`; return tree; }