const BUILD_ID = "20261001-triangles-6"; const COREGX_PROXY_URL = window.TRIANGLE_STUDIO_CONFIG.coregxProxyUrl; const EXAMPLE_BANKS = { "sides": [ "Draw a 3, 4, 5 triangle.", "Triangle ABC with AB=5, BC=6, AC=7.", "Draw triangle PQR with PQ=8, QR=10 and PR=12.", "A scalene triangle with sides 7, 9 and 11.", "Draw triangle ABC with symbolic side lengths AB=x, BC=2*x, and AC=2.5*x." ], "angles": [ "Triangle ABC with AB=8, AC=6 and angle BAC=60 degrees.", "Draw triangle ABC with AB=10, angle BAC=40 degrees and angle ABC=65 degrees.", "Triangle PQR: PQ=7, PR=5, angle QPR=75 degrees.", "Triangle ABC with AB=6, angle BAC=30 degrees and angle ABC=90 degrees.", "Draw triangle ABC with AB=8, AC=6, and angle BAC=pi/3 radians." ], "special": [ "An equilateral triangle with side length 6.", "An isosceles triangle with equal sides AB=7 and AC=7, and base BC=8.", "A right triangle ABC with right angle at B, AB=3 and BC=4.", "Animate an isosceles triangle ABC with equal sides AB=AC=t and base BC=6, varying t from 5 to 8 over 3 seconds.", "An isosceles right triangle ABC with the right angle at A and legs AB=5 and AC=5." ], "constructions": [ "A 3, 4, 5 triangle with a median from A to BC.", "Triangle ABC with AB=5, BC=6 and AC=7. Draw all three medians.", "Triangle ABC with AB=6, AC=6 and BC=8. Draw the altitude from A to BC.", "Draw a triangle with sides AB=7, BC=8, AC=9 and the angle bisector at B.", "Triangle ABC has sides AB=5, BC=6, AC=7. Mark the midpoints of all sides and join them to form the medial triangle." ] }; const exampleIndices = Object.fromEntries(Object.keys(EXAMPLE_BANKS).map(name => [name, 0])); const ui = { description: document.querySelector("#description"), build: document.querySelector("#build"), status: document.querySelector("#status"), preview: document.querySelector("#preview"), program: document.querySelector("#program"), downloads: document.querySelector("#downloads"), downloadProgram: document.querySelector("#download-program"), downloadSvg: document.querySelector("#download-svg"), downloadCad: document.querySelector("#download-cad"), }; let programUrl; let svgUrl; let cadUrl; function setStatus(message, isError = false) { ui.status.textContent = message; ui.status.classList.toggle("error", isError); } function showSvg(svg) { ui.preview.innerHTML = svg; } function stripCodeFence(value) { const text = value.trim(); if (!text.startsWith("```")) return text; const lines = text.split(/\r?\n/); lines.shift(); if (lines.at(-1)?.trim() === "```") lines.pop(); return lines.join("\n").trim(); } function alignNamedRightAngle(description, program) { const stated = description.match(/right angle\s+(?:is\s+)?at\s+([a-z][a-z0-9_]*)/i); const triangle = program.match(/^triangle\s+(\w+)\s+(\w+)\s+(\w+)\s*$/im); if (!stated || !triangle || !/^anglemode\s+degree\s*$/im.test(program)) return program; const vertices = triangle.slice(1); const vertex = vertices.find(name => name.toLowerCase() === stated[1].toLowerCase()); if (!vertex) return program; const lines = program.split(/\r?\n/); const rightAngles = lines.map((line, index) => ({ parts: line.trim().split(/\s+/), index })) .filter(({ parts }) => parts.length === 5 && parts[0].toLowerCase() === "angle" && /^90(?:\.0+)?$/.test(parts[4])); if (rightAngles.length !== 1) return program; const { parts, index } = rightAngles[0]; if (parts.slice(1, 4).some(name => !vertices.includes(name))) return program; if (parts[2] === vertex) return program; const otherVertices = vertices.filter(name => name !== vertex); lines[index] = `angle ${otherVertices[0]} ${vertex} ${otherVertices[1]} ${parts[4]}`; return lines.join("\n"); } function proxyEndpoint(path) { if (!/^https:\/\/.+/.test(COREGX_PROXY_URL)) { throw new Error("Add the Cloudflare Worker URL in config.js."); } const base = COREGX_PROXY_URL.endsWith("/") ? COREGX_PROXY_URL : `${COREGX_PROXY_URL}/`; return new URL(path.replace(/^\//, ""), base).toString(); } async function proxyFetch(route, options) { const endpoint = proxyEndpoint(route); try { return await fetch(endpoint, options); } catch (error) { const detail = error instanceof Error ? error.message : String(error); throw new Error(`Could not reach the ${route} proxy from ${window.location.origin}: ${detail}`); } } async function generateProgram(description) { setStatus("Converting to CoreGX using " + window.TRIANGLE_STUDIO_CONFIG.modelName + "…"); const promptResponse = await fetch("system_prompt.txt?v=" + BUILD_ID, { cache: "reload" }); if (!promptResponse.ok) throw new Error("Could not load the triangle prompt."); const response = await proxyFetch("generate", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ messages: [ { role: "system", content: await promptResponse.text() }, { role: "user", content: description }, ] }), }); const result = await response.json().catch(() => ({})); if (!response.ok || !result.ok) throw new Error(String(result.error || "Model request failed with HTTP " + response.status)); if (typeof result.content !== "string" || !result.content.trim()) throw new Error("The model returned no program."); return "defaultproperties constraint visible=true\n\n" + alignNamedRightAngle(description, stripCodeFence(result.content)) + "\n"; } async function renderCoreGX(program) { const response = await proxyFetch("render", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ program }), }); const result = await response.json().catch(() => ({})); if (!response.ok) throw new Error(`CoreGX request failed with HTTP ${response.status}.`); if (!result.ok) throw new Error(String(result.error || "CoreGX rejected the program.")); if (typeof result?.value?.svg !== "string") throw new Error("CoreGX returned no SVG."); return result.value.svg; } async function requestCad(program) { const options = { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ program, }), }; const response = await proxyFetch("cad", options); const result = await response.json().catch(() => ({})); if (!response.ok || !result.ok) { throw new Error(String(result.error || `CAD export failed with HTTP ${response.status}.`)); } const dxf = result?.value?.dxf ?? result.dxf; if (typeof dxf !== "string" || !dxf.trim()) throw new Error("CoreGX returned no CAD file."); return dxf; } async function exportCad() { const program = ui.program.textContent.trim(); if (!program) return; ui.downloadCad.disabled = true; setStatus("Exporting CAD…"); try { const dxf = await requestCad(program); if (cadUrl) URL.revokeObjectURL(cadUrl); cadUrl = URL.createObjectURL(new Blob([dxf], { type: "application/dxf;charset=utf-8" })); const link = document.createElement("a"); link.href = cadUrl; link.download = "triangle.dxf"; link.click(); setStatus("✓ CAD exported"); } catch (error) { setStatus(`⚠ ${error instanceof Error ? error.message : String(error)}`, true); } finally { ui.downloadCad.disabled = false; } } function setDownloads(program, svg) { if (programUrl) URL.revokeObjectURL(programUrl); if (svgUrl) URL.revokeObjectURL(svgUrl); programUrl = URL.createObjectURL(new Blob([program], { type: "text/plain;charset=utf-8" })); svgUrl = URL.createObjectURL(new Blob([svg], { type: "image/svg+xml;charset=utf-8" })); ui.downloadProgram.href = programUrl; ui.downloadSvg.href = svgUrl; ui.downloadProgram.classList.remove("is-disabled"); ui.downloadSvg.classList.remove("is-disabled"); ui.downloadProgram.removeAttribute("aria-disabled"); ui.downloadSvg.removeAttribute("aria-disabled"); ui.downloadCad.disabled = false; } async function buildTriangle() { const description = ui.description.value.trim(); if (!description) return setStatus("Describe a triangle first.", true); ui.build.disabled = true; ui.build.textContent = "Building…"; try { const program = await generateProgram(description); setStatus("Drawing the triangle…"); const svg = await renderCoreGX(program); showSvg(svg); ui.program.textContent = program; setDownloads(program, svg); setStatus("✓ Triangle built"); } catch (error) { setStatus(error instanceof Error ? error.message : String(error), true); } finally { ui.build.disabled = false; ui.build.textContent = "Build triangle"; } } document.querySelectorAll("[data-example]").forEach((button) => { button.addEventListener("click", () => { const name = button.dataset.example; const bank = EXAMPLE_BANKS[name]; const index = exampleIndices[name]; ui.description.value = bank[index]; exampleIndices[name] = (index + 1) % bank.length; ui.description.focus(); }); }); ui.build.addEventListener("click", buildTriangle); ui.downloadCad.addEventListener("click", exportCad); ui.description.addEventListener("keydown", (event) => { if ((event.ctrlKey || event.metaKey) && event.key === "Enter") buildTriangle(); }); window.addEventListener("beforeunload", () => { if (programUrl) URL.revokeObjectURL(programUrl); if (svgUrl) URL.revokeObjectURL(svgUrl); if (cadUrl) URL.revokeObjectURL(cadUrl); }); const STARTING_EXAMPLE_SVG = "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nA\nB\nC\n\n\n\n\n\n\n\n\n\n\n\n"; const STARTING_EXAMPLE_PROGRAM = "triangle A B C\ndistance AB 3\ndistance AC 4\ndistance BC 5"; showSvg(STARTING_EXAMPLE_SVG); ui.program.textContent = STARTING_EXAMPLE_PROGRAM; setDownloads(STARTING_EXAMPLE_PROGRAM, STARTING_EXAMPLE_SVG);