Spaces:
Running

stepwise / static /visuals /render_market.js
Ashish-K's picture
Economics: demand and supply diagrams with diagram quizzes; save chats on shutdown (part 2)
5ecf721 verified
Raw History Blame Contribute Delete
15 kB
// Drawing for the market class: demand and supply diagram, shifts, equilibria, fixed prices; and a step-through explorer.
import * as MK from "./market.js";
const NS = "http://www.w3.org/2000/svg";
function s(tag, attrs = {}, ...kids) { const n = document.createElementNS(NS, tag); for (const [k, v] of Object.entries(attrs || {})) { if (v == null) continue; if (k === "text") n.textContent = v; else n.setAttribute(k, v); } for (const k of kids.flat()) if (k != null) n.append(k.nodeType ? k : document.createTextNode(String(k))); return n; }
function el(tag, attrs = {}, ...kids) { const n = document.createElement(tag); for (const [k, v] of Object.entries(attrs || {})) { if (v == null || v === false) continue; if (k === "text") n.textContent = v; else if (k.startsWith("on")) n.addEventListener(k.slice(2), v); else n.setAttribute(k, v === true ? "" : v); } for (const k of kids.flat()) if (k != null) n.append(k.nodeType ? k : document.createTextNode(String(k))); return n; }
const W = 440, H = 356, L = 56, R = 26, T = 32, B = 46;
// curves: { a, b, c, d } ; opts: which extras to draw
export function marketDiagram(inst, { curves2 = null, eq = false, eq2 = false, pc = null, gap = false, move = null, label2 = null, axesFrom = null, ax: axIn = null } = {}) {
const ax = axIn ? axIn : axesFrom ? MK.axes(axesFrom) : curves2 ? MK.axesFor([inst, ...curves2.map(([k]) => k)]) : MK.axes(inst);
const X = (q) => L + (q / ax.qMax) * (W - L - R), Y = (p) => T + (1 - p / ax.pMax) * (H - T - B);
const svg = s("svg", { viewBox: `0 0 ${W} ${H}`, class: "vz-svg vz-mkt", role: "img", "aria-label": "Demand and supply diagram" });
// grid and axes
const pLab = ax.pMax / ax.pStep > 10 ? 2 * ax.pStep : ax.pStep; const qLab = ax.qMax / ax.qStep > 8 ? 2 * ax.qStep : ax.qStep;
for (let p = 0; p <= ax.pMax + 1e-9; p += ax.pStep) { svg.append(s("line", { x1: L, x2: W - R, y1: Y(p), y2: Y(p), class: "mk-grid" })); if (Math.abs(p % pLab) < 1e-9) svg.append(s("text", { x: L - 7, y: Y(p) + 4, class: "mk-tick", "text-anchor": "end", text: `${p}` })); }
for (let q = 0; q <= ax.qMax + 1e-9; q += ax.qStep) { svg.append(s("line", { x1: X(q), x2: X(q), y1: T, y2: H - B, class: "mk-grid" })); if (Math.abs(q % qLab) < 1e-9) svg.append(s("text", { x: X(q), y: H - B + 16, class: "mk-tick", "text-anchor": "middle", text: `${q}` })); }
svg.append(s("line", { x1: L, y1: T - 4, x2: L, y2: H - B, class: "mk-axis" }), s("line", { x1: L, y1: H - B, x2: W - R + 4, y2: H - B, class: "mk-axis" }));
svg.append(s("text", { x: 8, y: 16, class: "mk-axlab", text: "Price ($)" }), s("text", { x: W - R, y: H - 8, class: "mk-axlab", "text-anchor": "end", text: "Quantity" }));
const clipQ = (q) => Math.max(0, Math.min(ax.qMax, q));
const demandLine = (k, cls, lab) => { // Q = a − bP: from (Q at pMax or 0) to (Q at P = 0)
const p0 = Math.min(ax.pMax, k.a / k.b); const pts = [[clipQ(k.a - k.b * p0), p0], [clipQ(k.a), k.a > ax.qMax ? (k.a - ax.qMax) / k.b : 0]];
svg.append(s("line", { x1: X(pts[0][0]), y1: Y(pts[0][1]), x2: X(pts[1][0]), y2: Y(pts[1][1]), class: `mk-d ${cls}` }), s("text", { x: X(pts[1][0]) + 4, y: Y(pts[1][1]) - 6, class: `mk-lab ${cls}`, text: lab }));
};
const supplyLine = (k, cls, lab) => { // Q = c + dP: from P where Q = 0 (or P = 0) up to pMax
const pLo = Math.max(0, -k.c / k.d); let pHi = ax.pMax; if (k.c + k.d * pHi > ax.qMax) pHi = (ax.qMax - k.c) / k.d;
svg.append(s("line", { x1: X(k.c + k.d * pLo), y1: Y(pLo), x2: X(k.c + k.d * pHi), y2: Y(pHi), class: `mk-s ${cls}` }), s("text", { x: X(k.c + k.d * pHi) + 4, y: Y(pHi) + 4, class: `mk-lab ${cls}`, text: lab }));
};
demandLine(inst, "", "D"); supplyLine(inst, "", "S");
const mark = (P, Q, name, cls = "") => {
svg.append(s("line", { x1: L, y1: Y(P), x2: X(Q), y2: Y(P), class: "mk-guide" }), s("line", { x1: X(Q), y1: Y(P), x2: X(Q), y2: H - B, class: "mk-guide" }),
s("circle", { cx: X(Q), cy: Y(P), r: 5, class: `mk-pt ${cls}` }), s("text", { x: X(Q) + 7, y: Y(P) - 7, class: `mk-lab ${cls}`, text: name }),
s("text", { x: L + 4, y: Y(P) - 4, class: `mk-val ${cls}`, text: `$${P}` }), s("text", { x: X(Q) + 3, y: H - B - 5, class: `mk-val ${cls}`, text: `${Q}` }));
};
if (curves2) for (const [k, which] of curves2) (which === "D" ? demandLine : supplyLine)(k, "new", label2 && label2[which] || `${which}2`);
if (eq) { const e = MK.solve({ ...inst, scenario: "eq" }); mark(e.P, e.Q, curves2 ? "E1" : "E"); }
if (eq2) mark(eq2.P, eq2.Q, "E2", "new");
if (pc != null) {
svg.append(s("line", { x1: L, y1: Y(pc), x2: W - R, y2: Y(pc), class: "mk-pc" }), s("text", { x: W - R, y: Y(pc) - 6, "text-anchor": "end", class: "mk-lab pc", text: `${inst.scenario === "diseq" ? "Price" : inst.control ? `${inst.control[0].toUpperCase()}${inst.control.slice(1)} price` : "Fixed price"} $${pc}` }));
if (gap) { const qd = Math.max(0, inst.a - inst.b * pc), qs = Math.max(0, inst.c + inst.d * pc); const below = qd > qs; const y = below ? Y(pc) + 14 : Y(pc) - 12;
svg.append(s("line", { x1: X(Math.min(qd, qs)), y1: y, x2: X(Math.max(qd, qs)), y2: y, class: "mk-gap" }), s("line", { x1: X(qd), y1: Y(pc), x2: X(qd), y2: H - B, class: "mk-guide" }), s("line", { x1: X(qs), y1: Y(pc), x2: X(qs), y2: H - B, class: "mk-guide" }),
s("text", { x: (X(qd) + X(qs)) / 2, y: below ? y + 17 : y - 7, "text-anchor": "middle", class: "mk-lab pc", text: `${qd > qs ? "shortage" : "surplus"} ${Math.abs(qd - qs)}` }));
}
}
if (move) { // a movement along one curve: two points and an arrow between them
const q = (p) => (move.side === "D" ? inst.a - inst.b * p : inst.c + inst.d * p);
const [x1, y1, x2, y2] = [X(q(move.p1)), Y(move.p1), X(q(move.p2)), Y(move.p2)];
svg.append(s("circle", { cx: x1, cy: y1, r: 5, class: "mk-pt" }), s("circle", { cx: x2, cy: y2, r: 5, class: "mk-pt new" }),
s("line", { x1, y1, x2: x1 + 0.85 * (x2 - x1), y2: y1 + 0.85 * (y2 - y1), class: "mk-move", "marker-end": "url(#mkArrow)" }),
s("text", { x: L + 4, y: y1 - 4, class: "mk-val", text: `$${move.p1}` }), s("text", { x: L + 4, y: y2 - 4, class: "mk-val new", text: `$${move.p2}` }));
}
svg.prepend(s("defs", {}, s("marker", { id: "mkArrow", viewBox: "0 0 10 10", refX: 8, refY: 5, markerWidth: 6, markerHeight: 6, orient: "auto" }, s("path", { d: "M0,0 L10,5 L0,10 z", class: "mk-arrowhead" }))));
return svg;
}
// the shifted curve(s) for an instance, as [curves, "D"|"S"] pairs
function shifted(inst) {
const out = []; const after = MK.curvesAfter(inst);
for (const ev of [inst.event, inst.event2].filter(Boolean)) { const e = MK.EVENTS[ev]; out.push([e.curve === "D" ? { ...inst, a: after.a } : { ...inst, c: after.c }, e.curve]); }
return out;
}
// a student's drawing with one fault (or none)
function drawnShift(inst, wrong) {
const e = MK.EVENTS[inst.event]; const k = inst.k;
const mk = (curve, dir) => [curve === "D" ? { ...inst, a: inst.a + dir * k } : { ...inst, c: inst.c + dir * k }, curve];
const other = e.curve === "D" ? "S" : "D";
const list = wrong === "wrongCurve" ? [mk(other, e.dir)] : wrong === "wrongWay" ? [mk(e.curve, -e.dir)] : wrong === "both" ? [mk(e.curve, e.dir), mk(other, e.dir)] : [mk(e.curve, e.dir)];
return list;
}
export function marketFigure(fig, { reveal = false } = {}) {
const inst = fig.inst; const show = fig.show || []; const sol = MK.solve(inst);
const box = el("div", { class: "vz" }, el("div", { class: "vz-cap", text: MK.describe(inst) }));
const isShift = ["shiftD", "shiftS", "both"].includes(inst.scenario);
if (show.includes("drawn") && !reveal) {
const list = drawnShift(inst, fig.wrong); const ax = MK.axesFor([inst, ...list.map(([k]) => k)]); // both diagrams on the same scale
box.append(marketDiagram(inst, { ax }));
box.append(el("div", { class: "vz-cap", text: "The student's diagram:" }), marketDiagram(inst, { curves2: list, ax }));
} else if (reveal && isShift) {
box.append(marketDiagram(inst, { curves2: shifted(inst), eq: true, eq2: { P: sol.P2, Q: sol.Q2 } }));
} else if (reveal && inst.pc != null) {
box.append(marketDiagram(inst, { eq: true, pc: inst.pc, gap: true }));
} else if (reveal && inst.scenario === "own") {
box.append(marketDiagram(inst, { move: { side: inst.side, p1: inst.p1, p2: inst.p2 } }));
} else {
box.append(marketDiagram(inst, { eq: reveal, pc: show.includes("pc") ? inst.pc : null }));
}
if (reveal && fig.after) {
const a = fig.after; const s2 = MK.solve(a);
box.append(el("div", { class: "vz-cap vz-after", text: "After the change:" }));
box.append(a.scenario === "control" ? marketDiagram(a, { eq: true, pc: a.pc, gap: true }) : marketDiagram(a, { curves2: shifted(a), eq: true, eq2: { P: s2.P2, Q: s2.Q2 } }));
}
return box;
}
// ---------- explorer ----------
export function marketExplorer(inst0) {
const base = { ...inst0, scenario: "eq" }; delete base.event; delete base.event2; delete base.pc;
let inst = { ...base }; let step = 0; let ev = ""; let pc = null;
const p = MK.PRODUCTS.find((x) => x.name === inst.product);
const root = el("div", { class: "vz vz-explorer" });
const say = el("p", { class: "vz-say", "aria-live": "polite" }); const stage = el("div", { class: "vz-stage" }); const controls = el("div", { class: "vz-controls" });
const back = el("button", { class: "btn ghost", type: "button", text: "← Back", onclick: () => { if (step > 0) { step--; draw(); } } });
const next = el("button", { class: "btn", type: "button", text: "Next →", onclick: () => { if (step < STEPS.length - 1) { step++; draw(); } } });
const dots = el("ol", { class: "vz-dots" });
root.append(el("div", { class: "vz-steps" }, back, dots, next), say, stage, controls);
const e0 = MK.solve(base);
const STEPS = [
["Buyers: the demand curve", () => `Each point on D says how many ${p.name} buyers want at that price. Cheaper means more wanted, so D slopes down.`],
["Sellers: the supply curve", () => `Each point on S says how many ${p.name} sellers offer at that price. A higher price makes selling more worthwhile, so S slopes up.`],
["Where they agree", () => `Only at $${e0.P} do buyers want exactly what sellers offer: ${e0.Q} ${p.unit}. That crossing is the equilibrium.`],
["Change something", () => {
if (pc != null) { const qd = Math.max(0, base.a - base.b * pc), qs = Math.max(0, base.c + base.d * pc); return `At a fixed price of $${pc}, buyers want ${qd} but sellers offer ${qs}: ${qd > qs ? `a shortage of ${qd - qs}` : qd < qs ? `a surplus of ${qs - qd}` : "the market clears"}. Neither curve moves.`; }
if (!ev) return "Pick an event below and watch which curve moves, or fix the price away from equilibrium.";
const e = MK.EVENTS[ev]; const s2 = MK.solve(inst);
return `${MK.eventText(inst)} That changes ${e.curve === "D" ? "what buyers want" : "what sellers can offer"} at every price, so ${e.curve === "D" ? "demand" : "supply"} shifts ${e.dir > 0 ? "right" : "left"}. The new equilibrium is $${s2.P2} and ${s2.Q2} ${p.unit} (was $${e0.P} and ${e0.Q}).`;
}],
];
function draw() {
dots.replaceChildren(...STEPS.map(([t], i) => el("li", { class: i === step ? "on" : i < step ? "done" : "" }, el("button", { type: "button", "aria-label": t, title: t, onclick: () => { step = i; draw(); } }))));
back.disabled = step === 0; next.disabled = step === STEPS.length - 1; controls.hidden = step < 3;
say.replaceChildren(el("strong", { text: `${step + 1}. ${STEPS[step][0]}. ` }), STEPS[step][1]());
let svg;
if (step === 0) { svg = marketDiagram(base); svg.querySelectorAll(".mk-s").forEach((n) => n.classList.add("hide")); }
else if (step < 3) svg = marketDiagram(base, { eq: step === 2 });
else if (pc != null) svg = marketDiagram(base, { eq: true, pc, gap: pc !== e0.P });
else if (ev) { const s2 = MK.solve(inst); svg = marketDiagram(base, { curves2: shifted(inst), eq: true, eq2: { P: s2.P2, Q: s2.Q2 } }); }
else svg = marketDiagram(base, { eq: true });
stage.replaceChildren(svg);
}
// only events that keep the diagram readable for this market
const usable = Object.keys(MK.EVENTS).filter((k) => { const t = { ...base, scenario: MK.EVENTS[k].curve === "D" ? "shiftD" : "shiftS", event: k, k: base.b + base.d }; return (!MK.EVENTS[k].crop || p.crop) && MK.checkInstance(t).passed; });
const sel = el("select", { "aria-label": "Event" }, el("option", { value: "", text: "Nothing changes" }), ...usable.map((k) => el("option", { value: k, text: MK.EVENTS[k].text(p) })));
sel.addEventListener("change", () => { ev = sel.value; pc = null; slider.value = e0.P; out.textContent = "off"; inst = ev ? { ...base, scenario: MK.EVENTS[ev].curve === "D" ? "shiftD" : "shiftS", event: ev, k: base.b + base.d } : { ...base }; draw(); });
const out = el("span", { class: "vz-num", text: "off" });
const slider = el("input", { type: "range", min: 1, max: Math.floor(base.a / base.b) - 1, step: 1, value: e0.P, "aria-label": "Fixed price" });
slider.addEventListener("input", () => { pc = Number(slider.value); ev = ""; sel.value = ""; inst = { ...base }; out.textContent = `$${pc}`; draw(); });
controls.append(el("label", { class: "vz-ctl" }, el("span", { class: "vz-ctl-l", text: "Event" }), sel),
el("label", { class: "vz-ctl" }, el("span", { class: "vz-ctl-l", text: "Fixed price" }), slider, out),
el("button", { type: "button", class: "react", text: "Reset", onclick: () => { ev = ""; pc = null; sel.value = ""; slider.value = e0.P; out.textContent = "off"; inst = { ...base }; draw(); } }));
draw();
return root;
}
export const CSS = `
.vz-mkt .mk-grid{stroke:var(--rule);stroke-width:1}
.vz-mkt .mk-axis{stroke:var(--ink);stroke-width:2}
.vz-mkt .mk-tick{fill:var(--ink-soft);font:12px var(--font-data)}
.vz-mkt .mk-axlab{fill:var(--ink-soft);font:600 13px var(--font-body)}
.vz-mkt .mk-d{stroke:#2f6fb0;stroke-width:3}
.vz-mkt .mk-s{stroke:#d0892e;stroke-width:3}
.vz-mkt .mk-d.new,.vz-mkt .mk-s.new{stroke-dasharray:8 5}
.vz-mkt .hide{display:none}
.vz-mkt .mk-lab{fill:var(--ink);font:700 15px var(--font-body)}
.vz-mkt .mk-lab.new{fill:var(--accent)}
.vz-mkt .mk-lab.pc{fill:var(--bad);font-weight:600;font-size:13px}
.vz-mkt .mk-guide{stroke:var(--ink-soft);stroke-width:1.2;stroke-dasharray:4 4}
.vz-mkt .mk-pt{fill:var(--ink)}
.vz-mkt .mk-pt.new{fill:var(--accent)}
.vz-mkt .mk-val{fill:var(--ink);font:600 12px var(--font-data)}
.vz-mkt .mk-val.new{fill:var(--accent)}
.vz-mkt .mk-pc{stroke:var(--bad);stroke-width:2}
.vz-mkt .mk-gap{stroke:var(--bad);stroke-width:3}
.vz-mkt .mk-move{stroke:var(--accent);stroke-width:2.5}
.vz-mkt .mk-arrowhead{fill:var(--accent)}
@media (max-width:520px){.vz-mkt .mk-tick{font-size:15px}.vz-mkt .mk-lab{font-size:18px}.vz-mkt .mk-val{font-size:15px}.vz-mkt .mk-axlab{font-size:16px}}
`;