From 0951f34a9d564f222c8525502281b4e26e25454d Mon Sep 17 00:00:00 2001 From: agent Date: Thu, 12 Nov 2026 20:55:35 +0000 Subject: [PATCH] Add mobile-first web UI Compare (duel with row-by-row comparison and thumb-reach pick bar), Ranking, Triage (keep/drop pass, problem schools first), school detail with sources and notes, Settings. Picks go to a localStorage outbox first and sync in the background, so nothing is lost on a flaky connection. Light/dark themes, installable to the home screen. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HA82gXkMmmRRKLSnY6vQN3 --- public/css/app.css | 288 ++++++++++++++++++++++ public/icons/apple-touch-icon.png | Bin 0 -> 1865 bytes public/icons/icon-192.png | Bin 0 -> 2416 bytes public/icons/icon-512.png | Bin 0 -> 7330 bytes public/icons/icon.svg | 6 + public/index.html | 33 +++ public/js/main.js | 391 ++++++++++++++++++++++++++++++ public/js/ui.js | 99 ++++++++ public/js/views/duel.js | 125 ++++++++++ public/js/views/rank.js | 116 +++++++++ public/js/views/school.js | 210 ++++++++++++++++ public/js/views/settings.js | 110 +++++++++ public/js/views/triage.js | 85 +++++++ public/manifest.webmanifest | 15 ++ scripts/make_icons.py | 53 ++++ 15 files changed, 1531 insertions(+) create mode 100644 public/css/app.css create mode 100644 public/icons/apple-touch-icon.png create mode 100644 public/icons/icon-192.png create mode 100644 public/icons/icon-512.png create mode 100644 public/icons/icon.svg create mode 100644 public/index.html create mode 100644 public/js/main.js create mode 100644 public/js/ui.js create mode 100644 public/js/views/duel.js create mode 100644 public/js/views/rank.js create mode 100644 public/js/views/school.js create mode 100644 public/js/views/settings.js create mode 100644 public/js/views/triage.js create mode 100644 public/manifest.webmanifest create mode 100644 scripts/make_icons.py diff --git a/public/css/app.css b/public/css/app.css new file mode 100644 index 0000000..4c4c122 --- /dev/null +++ b/public/css/app.css @@ -0,0 +1,288 @@ +/* Elorasmus: mobile-first. Light/dark via tokens; data-theme on overrides the system. */ + +:root { + --bg: #f6f4ef; --surface: #ffffff; --surface-2: #eeebe3; --text: #1b1f24; --muted: #5f6873; --line: #e1ddd3; + --accent: #2d5bd7; --accent-text: #ffffff; + --a: #0f7f75; --a-soft: #d8efeb; --b: #b4570f; --b-soft: #f9e4d1; + --good: #1d7a43; --warn: #9a6400; --bad: #c0352e; + --radius: 14px; --shadow: 0 1px 2px rgb(0 0 0 / .06), 0 6px 20px rgb(0 0 0 / .06); + --max: 760px; --gutter: 16px; + color-scheme: light; +} +@media (prefers-color-scheme: dark) { + :root:not([data-theme="light"]) { + --bg: #111418; --surface: #1a1e24; --surface-2: #252b33; --text: #e8eaed; --muted: #9aa4ae; --line: #2d343d; + --accent: #7ea2ff; --accent-text: #0c1222; + --a: #3fc4b4; --a-soft: #153532; --b: #f2a45f; --b-soft: #3b2715; + --good: #5fcf8c; --warn: #f0b94e; --bad: #ff7d74; + --shadow: 0 1px 2px rgb(0 0 0 / .4), 0 6px 20px rgb(0 0 0 / .3); + color-scheme: dark; + } +} +:root[data-theme="dark"] { + --bg: #111418; --surface: #1a1e24; --surface-2: #252b33; --text: #e8eaed; --muted: #9aa4ae; --line: #2d343d; + --accent: #7ea2ff; --accent-text: #0c1222; + --a: #3fc4b4; --a-soft: #153532; --b: #f2a45f; --b-soft: #3b2715; + --good: #5fcf8c; --warn: #f0b94e; --bad: #ff7d74; + --shadow: 0 1px 2px rgb(0 0 0 / .4), 0 6px 20px rgb(0 0 0 / .3); + color-scheme: dark; +} + +* { box-sizing: border-box; } +html { -webkit-text-size-adjust: 100%; } +body { + margin: 0; background: var(--bg); color: var(--text); + font: 16px/1.45 system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; + overflow-x: hidden; +} +a { color: var(--accent); } +button { font: inherit; color: inherit; } +h1, h2, h3 { line-height: 1.2; margin: 0 0 .4em; } +h1 { font-size: 1.35rem; } h2 { font-size: 1.05rem; } h3 { font-size: .95rem; } +p { margin: .4em 0; } +ul, ol { margin: .3em 0; padding-left: 1.2em; } +.muted { color: var(--muted); } +.small { font-size: .82rem; } +.loading { padding: 40px var(--gutter); text-align: center; color: var(--muted); } +:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; } + +/* ---------- top bar ---------- */ +.topbar { + position: sticky; top: 0; z-index: 20; display: flex; align-items: center; gap: 8px; + padding: 6px var(--gutter); padding-top: calc(6px + env(safe-area-inset-top)); + background: color-mix(in srgb, var(--bg) 88%, transparent); backdrop-filter: blur(10px); + border-bottom: 1px solid var(--line); +} +.brand { display: flex; align-items: center; gap: 8px; font-weight: 700; color: var(--text); text-decoration: none; } +.picks { color: var(--muted); font-size: .8rem; display: none; } +.tabs { margin-left: auto; display: flex; gap: 2px; } +.tabs a { + display: flex; flex-direction: column; align-items: center; gap: 1px; min-width: 52px; padding: 4px 6px; + border-radius: 10px; color: var(--muted); text-decoration: none; font-size: .68rem; +} +.tabs a svg { width: 22px; height: 22px; } +.tabs a.active { color: var(--accent); background: var(--surface); box-shadow: var(--shadow); } +body.logged-out .tabs { display: none; } + +.view { max-width: var(--max); margin: 0 auto; padding: 12px var(--gutter) 24px; } + +/* ---------- shared bits ---------- */ +.btn { + display: inline-flex; align-items: center; justify-content: center; gap: 6px; min-height: 44px; padding: 0 16px; + border: 0; border-radius: 12px; background: var(--accent); color: var(--accent-text); font-weight: 600; + text-decoration: none; cursor: pointer; +} +.btn.ghost { background: var(--surface); color: var(--text); border: 1px solid var(--line); } +.link { background: none; border: 0; padding: 6px 0; color: var(--accent); cursor: pointer; text-decoration: underline; } +.chip { + display: inline-block; padding: 1px 8px; border-radius: 999px; font-size: .74rem; background: var(--surface-2); + color: var(--muted); white-space: nowrap; +} +.chip.warn { background: color-mix(in srgb, var(--warn) 18%, transparent); color: var(--warn); } +.notice { padding: 10px 12px; border-radius: 12px; background: var(--surface-2); } +.empty { text-align: center; padding: 40px 0; } + +.bar { display: inline-block; width: 46px; height: 6px; border-radius: 3px; background: var(--surface-2); vertical-align: middle; overflow: hidden; } +.bar > i { display: block; height: 100%; background: var(--accent); border-radius: 3px; } +.num { margin-left: 6px; font-variant-numeric: tabular-nums; } +.w0 { width: 0; } .w1 { width: 10%; } .w2 { width: 20%; } .w3 { width: 30%; } .w4 { width: 40%; } .w5 { width: 50%; } +.w6 { width: 60%; } .w7 { width: 70%; } .w8 { width: 80%; } .w9 { width: 90%; } .w10 { width: 100%; } + +.tone-ok, .tone-best, .tone-good { color: var(--good); } +.tone-fail, .tone-none, .tone-poor { color: var(--bad); } +.tone-unknown, .tone-weak { color: var(--warn); } +b.tone-ok { color: var(--good); } + +/* ---------- duel ---------- */ +.duel { padding-bottom: 150px; } +.prompt { margin: 0 0 8px; color: var(--muted); font-size: .85rem; text-align: center; } +.duel-heads { display: grid; grid-template-columns: 1fr auto 1fr; gap: 6px; align-items: stretch; } +.vs { align-self: center; font-weight: 700; color: var(--muted); font-size: .8rem; } +.school-head { + position: relative; display: flex; flex-direction: column; align-items: flex-start; gap: 2px; text-align: left; + padding: 10px 10px 10px; border-radius: var(--radius); background: var(--surface); box-shadow: var(--shadow); + border: 2px solid transparent; cursor: pointer; min-width: 0; +} +.school-head.side-a { border-color: var(--a); } +.school-head.side-b { border-color: var(--b); } +.side-tag { + display: inline-grid; place-items: center; width: 20px; height: 20px; border-radius: 6px; font-size: .72rem; font-weight: 800; + color: #fff; +} +.side-a .side-tag { background: var(--a); } +.side-b .side-tag { background: var(--b); } +.school-head .side-tag { position: absolute; top: 8px; right: 8px; } +.school-head .flag { font-size: 1.5rem; line-height: 1; } +.sname { font-weight: 700; font-size: .98rem; line-height: 1.2; overflow-wrap: anywhere; padding-right: 18px; } +.splace { color: var(--muted); font-size: .78rem; line-height: 1.25; } +.srating { margin-top: 4px; font-weight: 700; font-variant-numeric: tabular-nums; } +.srating small { display: block; font-weight: 400; color: var(--muted); font-size: .72rem; } +.provisional { opacity: .75; } + +.cmp { margin-top: 10px; background: var(--surface); border-radius: var(--radius); box-shadow: var(--shadow); padding: 4px 10px 8px; } +.cmp-section { + grid-column: 1 / -1; margin-top: 10px; padding: 2px 0; font-size: .7rem; letter-spacing: .06em; text-transform: uppercase; + color: var(--muted); font-weight: 700; +} +.cmp-row { + display: grid; grid-template-columns: minmax(84px, .9fr) 1fr 1fr; gap: 6px; align-items: center; + padding: 3px 0; border-top: 1px solid var(--line); font-size: .86rem; +} +.cmp-section + .cmp-row { border-top: 0; } +.cmp-label { color: var(--muted); font-size: .8rem; line-height: 1.2; } +.cmp-val { padding: 4px 6px; border-radius: 8px; min-width: 0; overflow-wrap: anywhere; line-height: 1.25; } +.cmp-val .bar { width: 38px; } +.cmp-val .bar > i { background: var(--muted); opacity: .55; } +.cmp-val.win .bar > i { opacity: 1; } +.win-a { background: var(--a-soft); } +.win-b { background: var(--b-soft); } +.win-a .bar > i { background: var(--a); } +.win-b .bar > i { background: var(--b); } +.win { font-weight: 600; } + +.duel-flags { display: grid; gap: 10px; margin-top: 12px; } +.flags { background: var(--surface); border-radius: var(--radius); padding: 10px 12px; box-shadow: var(--shadow); border-left: 4px solid; } +.flags.side-a { border-left-color: var(--a); } +.flags.side-b { border-left-color: var(--b); } +.flags h3 { display: flex; align-items: center; gap: 6px; } +.flags .summary { font-size: .88rem; } +.flags ul { list-style: none; padding: 0; font-size: .86rem; } +.flags li, .hl-list li, .wo-list li { padding-left: 1.3em; position: relative; margin: .25em 0; } +.flags li::before, .hl-list li::before, .wo-list li::before { position: absolute; left: 0; font-weight: 700; } +.flags li.hl::before, .hl-list li::before { content: "+"; color: var(--good); } +.flags li.wo::before, .wo-list li::before { content: "!"; color: var(--bad); left: .25em; } +.hl-list, .wo-list { list-style: none; padding: 0; } +.duel-drop { display: flex; justify-content: space-between; margin-top: 10px; font-size: .82rem; } + +/* ---------- bottom action bar ---------- */ +.actionbar { + position: fixed; left: 0; right: 0; bottom: 0; z-index: 15; background: var(--surface); border-top: 1px solid var(--line); + box-shadow: 0 -6px 20px rgb(0 0 0 / .08); padding: 6px var(--gutter) calc(10px + env(safe-area-inset-bottom)); +} +.actionbar > div { max-width: var(--max); margin: 0 auto; } +.actionbar-sub { display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px !important; } +.ghost { background: none; border: 0; padding: 6px 4px; color: var(--accent); cursor: pointer; font-weight: 600; font-size: .9rem; } +.ghost:disabled { color: var(--muted); opacity: .5; cursor: default; } +.actionbar-main { display: grid; grid-template-columns: 1fr 56px 1fr; gap: 8px; } +.pick { + min-height: 54px; border: 0; border-radius: 14px; font-weight: 700; font-size: .95rem; cursor: pointer; padding: 0 10px; + white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: #fff; +} +.pick span { display: inline-grid; place-items: center; width: 22px; height: 22px; border-radius: 6px; background: rgb(255 255 255 / .22); font-size: .8rem; } +.pick-a { background: var(--a); text-align: left; } +.pick-b { background: var(--b); text-align: right; } +.pick-draw { background: var(--surface-2); color: var(--text); font-size: 1.3rem; } +.pick:active { transform: scale(.98); } +:root[data-theme="dark"] .pick-a, :root[data-theme="dark"] .pick-b { color: #0d1117; } +@media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) .pick-a, :root:not([data-theme="light"]) .pick-b { color: #0d1117; } } +.triage + .actionbar .actionbar-main, .actionbar-main:has(.pick-keep) { grid-template-columns: 1fr 1fr; } +.pick-drop { background: var(--surface-2); color: var(--bad) !important; } +.pick-keep { background: var(--accent); color: var(--accent-text) !important; } + +/* ---------- ranking ---------- */ +.rank-tools { display: grid; gap: 8px; margin-bottom: 8px; } +.rank-tools input[type=search], select, input[type=number], textarea, .login input { + width: 100%; min-height: 42px; padding: 8px 10px; border-radius: 10px; border: 1px solid var(--line); + background: var(--surface); color: var(--text); font: inherit; +} +.rank-filters { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 6px; } +.rank-filters select { font-size: .85rem; padding: 6px; } +.check { display: flex; gap: 8px; align-items: flex-start; font-size: .9rem; margin: 6px 0; } +.check input { margin-top: 3px; width: 18px; height: 18px; flex: none; } +.rank-list { list-style: none; padding: 0; margin: 0; display: grid; gap: 6px; } +.rank-list li { display: grid; } +.rank-row { + display: grid; grid-template-columns: 26px 26px 1fr auto; gap: 8px; align-items: center; width: 100%; text-align: left; + padding: 10px; border: 0; border-radius: 12px; background: var(--surface); box-shadow: var(--shadow); cursor: pointer; +} +.rank-row.dropped { opacity: .55; } +.pos { font-weight: 700; color: var(--muted); text-align: right; font-variant-numeric: tabular-nums; } +.rank-row .flag { font-size: 1.3rem; } +.rmain { display: grid; min-width: 0; } +.rname { font-weight: 650; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.rmeta { font-size: .78rem; color: var(--muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.rchips { display: flex; gap: 4px; flex-wrap: wrap; margin-top: 3px; } +.rscore { text-align: right; font-weight: 700; font-variant-numeric: tabular-nums; } +.rscore small { display: block; font-weight: 400; color: var(--muted); font-size: .72rem; } +.restore { justify-self: end; font-size: .85rem; } + +/* ---------- detail ---------- */ +.back { display: inline-flex; align-items: center; gap: 2px; background: none; border: 0; color: var(--accent); padding: 4px 0; cursor: pointer; font-weight: 600; } +.back svg { width: 20px; height: 20px; } +.dhead { background: var(--surface); border-radius: var(--radius); box-shadow: var(--shadow); padding: 14px; margin: 6px 0 12px; } +.dflag { font-size: 2rem; line-height: 1; margin-bottom: 4px; } +.dstats { font-variant-numeric: tabular-nums; } +.dactions { display: flex; flex-wrap: wrap; gap: 8px 14px; align-items: center; margin-top: 8px; } +.dsummary { font-size: 1rem; } +.hlwo { display: grid; gap: 4px; margin: 8px 0 12px; font-size: .92rem; } +.dsec { background: var(--surface); border-radius: var(--radius); box-shadow: var(--shadow); padding: 12px 14px; margin-bottom: 12px; } +.dsec h2 { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; flex-wrap: wrap; } +.dsec h3 { margin-top: .8em; } +.dsec p, .dsec li { font-size: .92rem; } +.conf { font-size: .7rem; font-weight: 600; padding: 1px 8px; border-radius: 999px; background: var(--surface-2); color: var(--muted); } +.conf-low { color: var(--warn); } +.scored { margin: 8px 0 12px; } +.scored-head { display: flex; justify-content: space-between; align-items: center; font-weight: 650; } +.scored-head .bar { width: 90px; } +.kv { display: grid; grid-template-columns: 1fr; gap: 2px 12px; margin: 0; } +.kv dt { font-weight: 650; font-size: .85rem; margin-top: 8px; } +.kv dd { margin: 0; font-size: .92rem; } +.agreements { list-style: none; padding: 0; display: grid; gap: 8px; } +.agreements li { padding: 8px 10px; border-radius: 10px; background: var(--surface-2); } +.lang { font-weight: 600; } +.sources { font-size: .85rem; overflow-wrap: anywhere; } +.history { list-style: none; padding: 0; font-size: .9rem; } +.history .up { color: var(--good); font-weight: 700; display: inline-block; width: 3em; } +.history .down { color: var(--bad); font-weight: 700; display: inline-block; width: 3em; } +.advisory { font-weight: 700; } +.adv-none { color: var(--good); } .adv-caution { color: var(--warn); } .adv-partial-avoid, .adv-avoid { color: var(--bad); } +textarea { min-height: 96px; resize: vertical; } + +/* ---------- triage ---------- */ +.triage { padding-bottom: 110px; } +.progress { position: relative; height: 28px; border-radius: 10px; background: var(--surface-2); overflow: hidden; margin-bottom: 6px; } +.progress > i { position: absolute; inset: 0 auto 0 0; background: color-mix(in srgb, var(--accent) 30%, transparent); } +.progress > span { position: relative; z-index: 1; display: block; text-align: center; line-height: 28px; font-size: .82rem; font-weight: 600; } +.tcard { background: var(--surface); border-radius: var(--radius); box-shadow: var(--shadow); padding: 14px; margin-top: 8px; } +.tcard header { display: flex; gap: 10px; align-items: center; } +.tcard .flag { font-size: 2rem; } +.concerns { background: color-mix(in srgb, var(--bad) 12%, transparent); border-radius: 10px; padding: 8px 8px 8px 26px; color: var(--bad); font-size: .9rem; } +.tgrid { display: grid; grid-template-columns: auto 1fr; gap: 4px 12px; font-size: .9rem; margin: 10px 0; } +.tgrid dt { color: var(--muted); } .tgrid dd { margin: 0; } + +/* ---------- settings & login ---------- */ +.settings h2 { margin-top: 1.4em; } +.field { display: grid; gap: 6px; margin: 10px 0; border: 0; padding: 0; font-weight: 600; font-size: .92rem; } +.field legend { padding: 0; margin-bottom: 6px; } +.seg { display: flex; gap: 6px; flex-wrap: wrap; font-weight: 400; } +.seg label { display: flex; align-items: center; gap: 6px; padding: 8px 12px; border-radius: 10px; background: var(--surface); border: 1px solid var(--line); } +.langs { list-style: none; padding: 0; display: grid; gap: 6px; font-weight: 400; } +.langs li { display: grid; grid-template-columns: 1fr 90px auto; gap: 8px; align-items: center; } +.addlang { display: grid; grid-template-columns: 1fr auto; gap: 8px; } +.row { display: flex; flex-wrap: wrap; gap: 8px; } +.file { position: relative; overflow: hidden; } +.file input { position: absolute; inset: 0; opacity: 0; cursor: pointer; } +.about li { margin: .3em 0; } +.login { max-width: 340px; margin: 40px auto; display: grid; gap: 10px; background: var(--surface); padding: 20px; border-radius: var(--radius); box-shadow: var(--shadow); } +.error { color: var(--bad); min-height: 1.2em; } + +/* ---------- toast ---------- */ +.toast { + position: fixed; left: 50%; bottom: calc(132px + env(safe-area-inset-bottom)); transform: translate(-50%, 20px); z-index: 30; + display: flex; gap: 12px; align-items: center; max-width: calc(100vw - 32px); padding: 10px 14px; border-radius: 12px; + background: #1f252d; color: #f1f3f5; font-size: .88rem; box-shadow: 0 8px 24px rgb(0 0 0 / .25); + opacity: 0; pointer-events: none; transition: opacity .2s, transform .2s; +} +.toast.show { opacity: 1; transform: translate(-50%, 0); pointer-events: auto; } +.toast button { background: none; border: 0; color: #8fb4ff; font-weight: 700; cursor: pointer; padding: 4px; } + +/* ---------- wider screens ---------- */ +@media (min-width: 640px) { + .picks { display: inline; } + .duel-flags { grid-template-columns: 1fr 1fr; } + .kv { grid-template-columns: 200px 1fr; } + .kv dt { margin-top: 0; } + .sname { font-size: 1.08rem; } + .cmp-row { grid-template-columns: 170px 1fr 1fr; } +} +@media (prefers-reduced-motion: reduce) { * { transition: none !important; } } diff --git a/public/icons/apple-touch-icon.png b/public/icons/apple-touch-icon.png new file mode 100644 index 0000000000000000000000000000000000000000..e083985bca4266b92d99dad23b6d863c79fff7a4 GIT binary patch literal 1865 zcmeAS@N?(olHy`uVBq!ia0y~yVAuk}9Bd2>47O+4j2IZ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U&LDutcI)U0EO*2le v@>r|$E_pe}>CO77=eNzY&DQ7nXLobMGrqIt0#6ti7#KWV{an^LB{Ts5!e%|V literal 0 HcmV?d00001 diff --git a/public/icons/icon-512.png b/public/icons/icon-512.png new file mode 100644 index 0000000000000000000000000000000000000000..00993ab489d737b936bc8168bcb444e2d56ef98f GIT binary patch literal 7330 zcmeAS@N?(olHy`uVBq!ia0y~yU}6Aa4mJh`hA$OYelak}WO}+dhE&{od-r~JX!tGm z51-X51gqydEo|L>>&NQFK^aAgLIQ!BO)p#p0y#Z`4>x$YH;L>*mN;zkj~@p>aUkvQwS&p6|Y1 zb#1eks=wO2Y1jT|u79QZTKl!W^t_ZUIWh{5-Imvse+}P%xk_!{^P0!iN@72+y^3%6 zGCgs@uj$EW#MuNcM0~X_SnzA^jD6D4ptEZe zqUleo8gAuje+l28%*y1i)>Ri>8lQb5KA@pZa$Vi`Z7W^oxrzUs;#Odc zJk;QRkzIhzX5P=YFUxP9XFrj9-(mVZ#`8J%zp?*$%Ba!9xSDC+ORoCqX?6{V%=yb! zR?Itj`p>s-j7eX)Zpd-O{P@lDoRP!6WQD&#zz;?N78};PkGEgpKd>d5Su3rOtA6(( z{sTJA4!gN#-9L1H)oS^M%6U>5p@E-6|NQ=QkadCEuaL0Qe;ICweMnied;fj;0ESm< z?q@RQ|7D2a{a~{4NA+v=1(~ZEwF)0|*YDbJT(_3NBzl#ro>bNY2l>f=7*1SLab#|J z74wJvk0Z0fVz!W1zj(fGe8TS_w~d8|f7Qdf{i^j0pSGwj&|kpz`|m#k#tH7fn0h|5 zDrh9PnEqy5V0pp#uE%}-zln?s5`uD#ohoKMT7Ox-L215#0Fy{PLkq*v_>b%k907kA zk%<%O3TQ`1zfA%gyiX41XDB z>i+v%7r_t^{5Mkn-`hG5h5+%mk^3ILpCvEAaK&}iMsA(I%nfT9y#F&KXfOE4c;J#f zgGq+=0nz;o0>SZ{yX#lWGclOBW*ajf*dWiqU~+WBF?)s!0xLf9GnlaKddbhww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Gc`E9oaxDs@!65lVd0jkX`iP2Z@*p> z!4SZ4-OIREhMlE>;rRa?W(J23PwQ_pFbEXv*O-`<=nY(x7m*K97T?;f|Ev z)mImJI2agb{r6#GX^7bsw(4uLC<8;&-oO4svo`oh&HjFIf2Nbee0~WAqm}DJ z)*shmU|^~Ky`77Jf${#oQ>mP%aGEoR}3hn=5X%z=c;W3=EbpzvPGR zG-YR6aPxfd;e8CzObjWRC-2wQGyi7F;bfT5s#^d1uP+DF-+vz%FR1+0DlB$(sJ>}h zFTj{FA*A?L=z}*s0^6h*9PZx#72We?s}w`S_PTzGD~<{Fi>Ljx-5MqO;<`4& zgr9r=*5&_}OJs1k_`Twl7+aMIKadLoi|CqO^rRkdI!UP8c29aN<${)IH%n#MH5j^Zz9qRv8 v-?{#){&AMuTn=&5UaQw5P35IO{%L>9CeU|}W#C-~1_lOCS3j3^P6 + + + + + diff --git a/public/index.html b/public/index.html new file mode 100644 index 0000000..4e07203 --- /dev/null +++ b/public/index.html @@ -0,0 +1,33 @@ + + + + + + +%APP_TITLE% + + + + + + + + + + + + + + + + +
+ %APP_TITLE% + + +
+

Loading…

+
+ + + diff --git a/public/js/main.js b/public/js/main.js new file mode 100644 index 0000000..9177f9b --- /dev/null +++ b/public/js/main.js @@ -0,0 +1,391 @@ +// App controller: loads data, keeps the event log in sync with the server, routes between views. +// +// Every user action becomes an event ({id, t, type, ...}). Events go to a local outbox first +// (localStorage), are applied immediately, and are flushed to the server in the background, +// so a pick made on a flaky phone connection is never lost. Ratings are always recomputed by +// replaying server events (in server order) followed by not-yet-acknowledged local ones. + +import { replay, ranking, pairKey } from './elo.js'; +import { nextPair } from './pairing.js'; +import { DEFAULT_SETTINGS, shortName } from './metrics.js'; +import { html, toast, newId, local, ICONS } from './ui.js'; +import * as duelView from './views/duel.js'; +import * as rankView from './views/rank.js'; +import * as schoolView from './views/school.js'; +import * as triageView from './views/triage.js'; +import * as settingsView from './views/settings.js'; + +class ApiError extends Error { + constructor(status, message) { + super(message); + this.status = status; + } +} + +async function api(path, { method = 'GET', body } = {}) { + let res; + try { + res = await fetch(path, { + method, + credentials: 'same-origin', + headers: body === undefined ? {} : { 'Content-Type': 'application/json' }, + body: body === undefined ? undefined : JSON.stringify(body), + }); + } catch { + throw new ApiError(0, 'offline'); + } + const data = await res.json().catch(() => null); + if (!res.ok) throw new ApiError(res.status, data?.error ?? res.statusText); + return data; +} + +const ROUTES = { + '': duelView, rank: rankView, triage: triageView, settings: settingsView, school: schoolView, +}; + +const app = { + config: null, + data: null, + byCode: new Map(), + bySlug: new Map(), + serverEvents: [], + seq: 0, + outbox: local.get('outbox', []), + notes: {}, + settings: { ...DEFAULT_SETTINGS }, + state: null, + ctx: null, + recent: local.get('recent', []), + pair: local.get('pair', null), + positions: new Map(), + flushing: false, + retryDelay: 2000, + lastRoute: null, + + /* ---------- derived state ---------- */ + + recompute() { + const known = new Set(this.serverEvents.map((e) => e.id)); + this.outbox = this.outbox.filter((e) => !known.has(e.id)); + const events = [...this.serverEvents, ...this.outbox]; + const elo = { initial: this.config.elo.initial, kMax: this.config.elo.kMax, kMin: this.config.elo.kMin }; + this.state = replay(events, this.data.schools.map((s) => s.code), elo); + this.positions = new Map(ranking(this.state.stats).map((s, i) => [s.code, i + 1])); + this.ctx = { settings: this.settings, data: this.data }; + }, + + rankOf(code) { + return this.positions.get(code) ?? null; + }, + + currentPair() { + const ok = (c) => this.state.stats.get(c) && !this.state.stats.get(c).dropped; + if (!(this.pair && this.pair.length === 2 && this.pair[0] !== this.pair[1] && this.pair.every(ok))) { + this.pair = nextPair(this.state.stats, { + mode: this.settings.pairing, recent: this.recent, pairCounts: this.state.pairCounts, + }); + local.set('pair', this.pair); + } + return this.pair; + }, + + /* ---------- actions ---------- */ + + record(fields) { + const ev = { id: newId(), t: new Date().toISOString(), ...fields }; + this.outbox.push(ev); + local.set('outbox', this.outbox); + this.recompute(); + this.flush(); + return ev; + }, + + rememberPair(a, b) { + this.recent = [...this.recent, pairKey(a, b)].slice(-40); + local.set('recent', this.recent); + }, + + pick(a, b, r) { + const before = { a: this.state.stats.get(a).rating, b: this.state.stats.get(b).rating }; + this.record({ type: 'match', a, b, r }); + this.rememberPair(a, b); + this.pair = null; + const da = Math.round(this.state.stats.get(a).rating - before.a); + const db = Math.round(this.state.stats.get(b).rating - before.b); + const fmt = (code, d) => `${shortName(this.byCode.get(code))} ${d >= 0 ? '+' : ''}${d}`; + toast(r === 'draw' ? `Tie · ${fmt(a, da)} · ${fmt(b, db)}` : `${fmt(a, da)} · ${fmt(b, db)}`, { label: 'Undo', run: () => this.undo() }); + this.render(); + }, + + skip() { + if (this.pair) this.rememberPair(...this.pair); + this.pair = null; + this.render(); + }, + + undo() { + const target = this.state.lastUndoable; + if (!target) return toast('Nothing to undo'); + this.record({ type: 'undo', target: target.id }); + if (target.type === 'match') { + this.pair = [target.a, target.b]; + local.set('pair', this.pair); + } + const what = target.type === 'match' ? 'pick' : target.type; + toast(`Undid the last ${what}`); + this.render(); + }, + + drop(code) { + this.record({ type: 'drop', code }); + if (this.pair?.includes(code)) this.pair = null; + toast(`Dropped ${shortName(this.byCode.get(code))}`, { label: 'Undo', run: () => this.undo() }); + this.render(); + }, + + restore(code) { + this.record({ type: 'restore', code }); + toast(`${shortName(this.byCode.get(code))} is back in the race`); + this.render(); + }, + + review(code) { + this.record({ type: 'review', code }); + this.render(); + }, + + duelWith(code) { + const me = this.state.stats.get(code); + const others = [...this.state.stats.values()] + .filter((s) => !s.dropped && s.code !== code) + .sort((x, y) => Math.abs(x.rating - me.rating) - Math.abs(y.rating - me.rating)) + .slice(0, 5); + if (!others.length) return toast('No opponent available'); + const opp = others[Math.floor(Math.random() * others.length)].code; + this.pair = Math.random() < 0.5 ? [code, opp] : [opp, code]; + local.set('pair', this.pair); + this.navigate('#/'); + }, + + async saveNote(code, text) { + const res = await api(`api/notes/${encodeURIComponent(code)}`, { method: 'PUT', body: { text } }); + if (res.note) this.notes[code] = res.note; + else delete this.notes[code]; + }, + + async updateSettings(patch) { + const previous = this.settings; + this.settings = { ...this.settings, ...patch }; + if ('pairing' in patch) this.pair = null; + this.recompute(); + this.render(); + try { + await api('api/settings', { method: 'PUT', body: patch }); + } catch (err) { + this.settings = previous; + this.recompute(); + this.render(); + toast(err.status === 0 ? 'Offline: setting not saved' : `Setting not saved: ${err.message}`); + } + }, + + async importBackup(file) { + let data; + try { + data = JSON.parse(await file.text()); + } catch { + return toast('That file is not valid JSON'); + } + const n = Array.isArray(data?.events) ? data.events.length : 0; + if (!confirm(`Replace ALL current picks, notes and settings with this backup (${n} events)?\nThe server keeps a copy of the current state in DATA_DIR/backups.`)) return; + try { + await api('api/import', { method: 'POST', body: data }); + this.outbox = []; + local.set('outbox', []); + await this.sync({ full: true }); + toast('Backup imported'); + } catch (err) { + toast(`Import failed: ${err.message}`); + } + }, + + async logout() { + await api('api/logout', { method: 'POST', body: {} }).catch(() => {}); + location.reload(); + }, + + /* ---------- server sync ---------- */ + + /** Pull server state. Returns how many new events came from elsewhere (not our outbox). */ + async sync({ full = false } = {}) { + const res = await api(`api/state${full ? '' : `?since=${this.seq}`}`); + const mine = new Set(this.outbox.map((e) => e.id)); + let incoming; + if (full || res.seq < this.seq) { + // First load, or the server state was replaced (import): take it wholesale. + this.serverEvents = full ? res.events : (await api('api/state')).events; + incoming = this.serverEvents; + } else { + incoming = res.events.filter((e) => e.seq > this.seq); + this.serverEvents.push(...incoming); + } + this.seq = res.seq; + this.notes = res.notes; + this.settings = { ...DEFAULT_SETTINGS, stayMonths: this.config.defaults.stayMonths, ...res.settings }; + this.recompute(); + local.set('outbox', this.outbox); + return incoming.filter((e) => !mine.has(e.id)).length; + }, + + async flush() { + if (this.flushing || !this.outbox.length) return; + this.flushing = true; + const batch = this.outbox.slice(); + let sent = false; + try { + await api('api/events', { method: 'POST', body: { events: batch } }); + sent = true; + } catch (err) { + if (err.status === 401) { + this.flushing = false; + return this.showLogin(); + } + // 400 = the server refused something in the batch; find and discard just that event. + if (err.status === 400) sent = await this.discardRejected(batch); + if (!sent) { + setTimeout(() => this.flush(), this.retryDelay); + this.retryDelay = Math.min(this.retryDelay * 2, 60000); + } + } + this.flushing = false; + if (!sent) return; + this.retryDelay = 2000; + const foreign = await this.sync().catch(() => 0); + if (foreign) this.render(); // another device changed something meanwhile + if (this.outbox.length) this.flush(); + }, + + /** Resend events one by one; drop those refused (e.g. undo of something already undone elsewhere). */ + async discardRejected(batch) { + const rejected = []; + for (const ev of batch) { + try { + await api('api/events', { method: 'POST', body: { events: [ev] } }); + } catch (err) { + if (err.status !== 400) return false; // connection trouble: retry everything later + rejected.push(ev); + } + } + this.outbox = this.outbox.filter((e) => !rejected.includes(e)); + local.set('outbox', this.outbox); + if (rejected.length) toast(`${rejected.length} change(s) refused by the server and discarded`); + return true; + }, + + /* ---------- routing & rendering ---------- */ + + navigate(hash) { + location.hash = hash; + }, + + back() { + if (history.length > 1) history.back(); + else this.navigate('#/rank'); + }, + + applyTheme() { + const theme = local.get('theme', 'system'); + if (theme === 'system') delete document.documentElement.dataset.theme; + else document.documentElement.dataset.theme = theme; + }, + + route() { + const [, name = '', param] = location.hash.match(/^#\/?([a-z]*)\/?(.*)$/) ?? []; + return { name: ROUTES[name] ? name : '', param: decodeURIComponent(param ?? '') }; + }, + + render() { + const { name, param } = this.route(); + const view = document.getElementById('view'); + const key = `${name}/${param}`; + // Don't yank the notes box away from someone typing in it during a background sync. + if (key === this.lastRoute && view.contains(document.activeElement) && document.activeElement.matches('textarea, input[type=search]')) return; + view.onclick = view.onchange = view.oninput = null; + ROUTES[name].render(view, this, param); + for (const a of document.querySelectorAll('.tabs a')) a.classList.toggle('active', a.dataset.route === (name === 'school' ? 'rank' : name)); + document.getElementById('picks').textContent = `${this.state.matches.length} picks`; + if (key !== this.lastRoute) { + window.scrollTo(0, 0); + this.lastRoute = key; + } + }, + + showLogin(message = '') { + const view = document.getElementById('view'); + document.body.classList.add('logged-out'); + view.innerHTML = String(html` + `); + view.querySelector('form').onsubmit = async (e) => { + e.preventDefault(); + try { + await api('api/login', { method: 'POST', body: { password: e.target.password.value } }); + location.reload(); + } catch (err) { + this.showLogin(err.status === 401 ? 'Wrong password' : err.message); + } + }; + }, + + async start() { + this.applyTheme(); + document.querySelector('.tabs').innerHTML = String(html` + ${ICONS.duel}Compare + ${ICONS.rank}Ranking + ${ICONS.triage}Triage + ${ICONS.settings}Settings`); + try { + this.config = await api('api/config'); + document.title = this.config.title; + if (this.config.authRequired && !this.config.authenticated) return this.showLogin(); + this.data = await api('data/schools.json'); + if (this.config.eurCzk) this.data.fx = { ...this.data.fx, EURCZK: this.config.eurCzk }; + } catch (err) { + if (err.status === 401) return this.showLogin(); + document.getElementById('view').innerHTML = String(html`

Can't load the app

${err.message}

`); + return; + } + for (const s of this.data.schools) { + this.byCode.set(s.code, s); + this.bySlug.set(s.slug, s); + } + try { + await this.sync({ full: true }); + } catch (err) { + if (err.status === 401) return this.showLogin(); + // Offline: run on the local outbox only; sync when back. + this.recompute(); + toast('Offline: your picks are kept on this device and sent later'); + } + this.render(); + this.flush(); + addEventListener('hashchange', () => this.render()); + addEventListener('online', () => this.flush()); + document.addEventListener('visibilitychange', () => { + if (document.visibilityState === 'visible') this.sync().then((n) => n && this.render()).catch(() => {}); + }); + setInterval(() => { + if (document.visibilityState === 'visible') this.sync().then((n) => n && this.render()).catch(() => {}); + }, 60000); + document.addEventListener('keydown', (e) => { + if (this.route().name === '' && duelView.onKey(e, this)) e.preventDefault(); + }); + }, +}; + +app.start(); diff --git a/public/js/ui.js b/public/js/ui.js new file mode 100644 index 0000000..2e2f4de --- /dev/null +++ b/public/js/ui.js @@ -0,0 +1,99 @@ +// Tiny UI helpers. `html` is a tagged template that escapes every interpolated value unless it +// was produced by `html` itself (or wrapped in `raw`). Research text comes from the web, so +// escaping by default is the line of defence against markup injection. + +const ESC = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }; + +class Safe { + constructor(s) { this.s = s; } + toString() { return this.s; } +} + +export const raw = (s) => new Safe(String(s)); +export const esc = (v) => String(v ?? '').replace(/[&<>"']/g, (c) => ESC[c]); + +function piece(v) { + if (v == null || v === false) return ''; + if (v instanceof Safe) return v.s; + if (Array.isArray(v)) return v.map(piece).join(''); + return esc(v); +} + +export function html(strings, ...values) { + let out = strings[0]; + for (let i = 0; i < values.length; i++) out += piece(values[i]) + strings[i + 1]; + return new Safe(out); +} + +/** Only http(s) links survive; anything else (javascript:, data:) becomes "#". */ +export function safeUrl(u) { + try { + const url = new URL(u); + return url.protocol === 'https:' || url.protocol === 'http:' ? url.href : '#'; + } catch { + return '#'; + } +} + +export const extLink = (url, label) => + html`${label}`; + +/** Score bar 0-10 (no inline styles: CSP forbids them, so widths are classes). */ +export function bar(v, tone = '') { + if (v == null) return html`–`; + const w = Math.max(0, Math.min(10, Math.round(v))); + return html`${Math.round(v * 10) / 10}`; +} + +let toastTimer; +/** Show a short message; `action` = { label, run } adds a button (e.g. Undo). */ +export function toast(message, action) { + const el = document.getElementById('toast'); + el.replaceChildren(); + const span = document.createElement('span'); + span.textContent = message; + el.append(span); + if (action) { + const btn = document.createElement('button'); + btn.type = 'button'; + btn.textContent = action.label; + btn.addEventListener('click', () => { el.classList.remove('show'); action.run(); }, { once: true }); + el.append(btn); + } + el.classList.add('show'); + clearTimeout(toastTimer); + toastTimer = setTimeout(() => el.classList.remove('show'), action ? 5000 : 2600); +} + +/** Random id that works without a secure context (crypto.randomUUID needs HTTPS). */ +export function newId() { + const bytes = crypto.getRandomValues(new Uint8Array(16)); + return btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); +} + +/** localStorage that never throws (private mode, blocked storage). */ +export const local = { + get(key, fallback) { + try { + const v = localStorage.getItem(`elorasmus.${key}`); + return v == null ? fallback : JSON.parse(v); + } catch { + return fallback; + } + }, + set(key, value) { + try { + localStorage.setItem(`elorasmus.${key}`, JSON.stringify(value)); + } catch { /* storage unavailable: state just won't survive a reload */ } + }, +}; + +export const ICONS = { + duel: raw(''), + rank: raw(''), + triage: raw(''), + settings: raw(''), + back: raw(''), + undo: raw(''), + skip: raw(''), +}; diff --git a/public/js/views/duel.js b/public/js/views/duel.js new file mode 100644 index 0000000..a35b36f --- /dev/null +++ b/public/js/views/duel.js @@ -0,0 +1,125 @@ +// The main screen: two schools side by side, a comparison table, and pick buttons in thumb reach. + +import { html, bar } from '../ui.js'; +import { COMPARE_ROWS, rowWinner, shortName, place } from '../metrics.js'; +import { PROVISIONAL_GAMES } from '../elo.js'; + +function head(app, s, side) { + const st = app.state.stats.get(s.code); + const rank = app.rankOf(s.code); + const provisional = st.games < PROVISIONAL_GAMES; + return html` + `; +} + +function table(app, a, b) { + let section = ''; + const rows = []; + for (const row of COMPARE_ROWS) { + if (row.section !== section) { + section = row.section; + rows.push(html`
${section}
`); + } + const va = row.get(a, app.ctx); + const vb = row.get(b, app.ctx); + if (!va && !vb) continue; + const win = rowWinner(row, va, vb); + const cell = (v, side) => { + if (!v) return html`
–
`; + const content = v.bar != null ? bar(v.bar) : html`${v.text}`; + return html`
${content}
`; + }; + rows.push(html` +
+
${row.label}
${cell(va, 'a')}${cell(vb, 'b')} +
`); + } + return html`
${rows}
`; +} + +function flagsBlock(s, side) { + const r = s.research; + if (!r) return ''; + const items = [ + ...r.highlights.slice(0, 3).map((t) => html`
  • ${t}
  • `), + ...r.watchouts.slice(0, 3).map((t) => html`
  • ${t}
  • `), + ]; + return html` +
    +

    ${side.toUpperCase()} ${shortName(s)}

    +

    ${r.summary}

    +
      ${items}
    +
    `; +} + +export function render(root, app) { + const pair = app.currentPair(); + if (!pair) { + root.innerHTML = String(html` +
    +

    Not enough schools left

    +

    You need at least two schools that aren't dropped. Restore some in the ranking.

    + Open the ranking +
    `); + return; + } + const [a, b] = pair.map((c) => app.byCode.get(c)); + const undoable = app.state.lastUndoable; + root.innerHTML = String(html` +
    +

    Which would you rather go to?

    +
    ${head(app, a, 'a')}${head(app, b, 'b')}
    + ${table(app, a, b)} +
    ${flagsBlock(a, 'a')}${flagsBlock(b, 'b')}
    +
    + + +
    +
    +
    +
    + + ${app.state.matches.length} picks + +
    +
    + + + +
    +
    `); + + root.onclick = (e) => { + const t = e.target.closest('[data-action]'); + if (!t || t.disabled) return; + const action = t.dataset.action; + if (action === 'pick') app.pick(a.code, b.code, t.dataset.r); + else if (action === 'skip') app.skip(); + else if (action === 'undo') app.undo(); + else if (action === 'drop') app.drop(t.dataset.code); + else if (action === 'open') app.navigate(`#/school/${t.dataset.slug}`); + }; +} + +/** Desktop shortcuts: ←/→ pick, ↓ or = draw, space skip, z/backspace undo. */ +export function onKey(e, app) { + if (e.target.closest('input, textarea, select')) return false; + const pair = app.currentPair(); + if (!pair) return false; + const map = { ArrowLeft: 'a', ArrowRight: 'b', ArrowDown: 'draw', '=': 'draw' }; + if (map[e.key]) { app.pick(pair[0], pair[1], map[e.key]); return true; } + if (e.key === ' ') { app.skip(); return true; } + if (e.key === 'z' || e.key === 'Backspace') { app.undo(); return true; } + return false; +} diff --git a/public/js/views/rank.js b/public/js/views/rank.js new file mode 100644 index 0000000..ccd6bf3 --- /dev/null +++ b/public/js/views/rank.js @@ -0,0 +1,116 @@ +// Leaderboard: everything ordered by your Elo, with filters and alternative sort orders. + +import { html, local } from '../ui.js'; +import { shortName, place, netCost, moneyRange, languageFit } from '../metrics.js'; +import { ranking, PROVISIONAL_GAMES } from '../elo.js'; + +const SORTS = { + rating: { label: 'My Elo', key: (s, st) => -st.rating }, + academic: { label: 'AI/robotics research', key: (s) => -(s.research?.aiRobotics?.academic?.score ?? -1) }, + access: { label: 'Course access', key: (s) => -(s.research?.aiRobotics?.access?.score ?? -1) }, + net: { label: 'Cheapest', key: (s, st, app) => { const n = netCost(s, app.settings, app.data); return n ? (n.lo + n.hi) / 2 : 1e9; } }, + nature: { label: 'Nature (avg)', key: (s) => { + const n = s.research?.nature; + return n ? -(n.climbing.score + n.hiking.score + n.ocean.score) / 3 : 1; + } }, + name: { label: 'Name', key: (s) => shortName(s).toLowerCase() }, +}; + +export function render(root, app) { + const prefs = local.get('rank', { q: '', region: '', scope: '', sort: 'rating', dropped: false }); + const all = ranking(app.state.stats, { includeDropped: true }); + const position = new Map(ranking(app.state.stats).map((s, i) => [s.code, i + 1])); + const q = prefs.q.trim().toLowerCase(); + const regions = [...new Set(app.data.schools.map((s) => s.region))].sort(); + + const rows = all + .map((st) => ({ st, s: app.byCode.get(st.code) })) + .filter(({ s, st }) => (prefs.dropped ? st.dropped : !st.dropped)) + .filter(({ s }) => !prefs.region || s.region === prefs.region) + .filter(({ s }) => !prefs.scope || s.agreements.some((a) => a.scope === prefs.scope)) + .filter(({ s }) => !q || `${shortName(s)} ${s.research?.name ?? ''} ${s.catalogName} ${s.research?.city ?? ''} ${s.countryShort} ${s.code}` + .toLowerCase().includes(q)); + const sort = SORTS[prefs.sort] ?? SORTS.rating; + rows.sort((x, y) => { + const kx = sort.key(x.s, x.st, app); + const ky = sort.key(y.s, y.st, app); + return kx < ky ? -1 : kx > ky ? 1 : y.st.rating - x.st.rating; + }); + const droppedCount = all.filter((s) => s.dropped).length; + + root.innerHTML = String(html` +
    +
    + +
    + + + +
    + +
    +

    ${rows.length} schools · ${app.state.matches.length} picks so far

    +
      + ${rows.map(({ s, st }) => { + const n = netCost(s, app.settings, app.data); + const lang = languageFit(s, app.settings.languages); + const ai = s.research?.aiRobotics?.academic?.score; + return html` +
    1. + + ${st.dropped ? html`` : ''} +
    2. `; + })} +
    +
    `); + + const save = (patch) => { local.set('rank', { ...prefs, ...patch }); render(root, app); }; + root.onclick = (e) => { + const t = e.target.closest('[data-action]'); + if (!t) return; + if (t.dataset.action === 'open') app.navigate(`#/school/${t.dataset.slug}`); + if (t.dataset.action === 'restore') app.restore(t.dataset.code); + }; + root.onchange = (e) => { + const el = e.target; + if (el.name === 'dropped') save({ dropped: el.checked }); + else if (['region', 'scope', 'sort'].includes(el.name)) save({ [el.name]: el.value }); + }; + let typing; + root.oninput = (e) => { + if (e.target.name !== 'q') return; + clearTimeout(typing); + const value = e.target.value; + typing = setTimeout(() => { + save({ q: value }); + const input = root.querySelector('input[name="q"]'); + input.focus(); + input.setSelectionRange(value.length, value.length); + }, 250); + }; +} + diff --git a/public/js/views/school.js b/public/js/views/school.js new file mode 100644 index 0000000..c953d57 --- /dev/null +++ b/public/js/views/school.js @@ -0,0 +1,210 @@ +// Everything known about one school: catalog agreements, all research sections with sources, +// money breakdown for your stay, your notes, and your pick history for it. + +import { html, bar, extLink, ICONS } from '../ui.js'; +import { + shortName, fullName, place, languageFit, subjectFit, monthlyGrant, netCost, money, moneyRange, LANG_NAMES, +} from '../metrics.js'; + +const CONF_LABEL = { high: 'high confidence', medium: 'medium confidence', low: 'low confidence' }; +const conf = (c) => (c ? html`${CONF_LABEL[c]}` : ''); +const para = (t) => (t ? html`

    ${t}

    ` : ''); +const list = (items, cls = '') => (items?.length ? html`
      ${items.map((i) => html`
    • ${i}
    • `)}
    ` : ''); + +function scored(label, node, tone = '') { + if (!node) return ''; + return html`
    ${label}${bar(node.score, tone)}
    ${para(node.text)}
    `; +} + +function section(title, body, confidence) { + return html`

    ${title} ${conf(confidence)}

    ${body}
    `; +} + +function agreementsBlock(s, app) { + return html` +
      + ${s.agreements.map((a) => html` +
    • +
      ${a.scope === 'FEL' ? 'FEL agreement' : 'CTU-wide'} + ${a.places == null ? '?' : a.places >= 99 ? 'open' : a.places} place${a.places === 1 ? '' : 's'} · + levels ${a.levels.join(' ')}
      +
      ${a.isced.length ? a.iscedLabels.map((l, i) => `${a.isced[i]} ${l}`).join(' · ') : 'Any subject area'}
      +
      ${a.languages.length + ? a.languages.map((l) => html`${LANG_NAMES[l.lang] ?? l.lang} ${l.level} `) + : html`No language listed`}
      + ${a.factsheet ? html`
      ${extLink(a.factsheet, 'CTU factsheet (CTU login)')}
      ` : ''} +
    • `)} +
    +

    Subject fit: ${subjectFit(s).text} · + Language: ${languageFit(s, app.settings.languages).text}

    `; +} + +function moneyBlock(s, app) { + const r = s.research; + const g = monthlyGrant(s, app.settings, app.data); + const n = netCost(s, app.settings, app.data); + const m = app.settings.stayMonths; + const country = app.data.countries?.[s.country]; + const range = (x) => moneyRange(x, app.settings, app.data); + const liv = r?.living; + return html` +
    +
    Money from CTU
    ${money(g.eur, app.settings, app.data)}/month · ${s.funding?.label} +
    ${s.funding?.note}
    + ${r?.fees?.hostFunding?.monthlyEUR ? html`
    Host scholarship
    ${money(r.fees.hostFunding.monthlyEUR, app.settings, app.data)}/month (not guaranteed) +
    ${r.fees.hostFunding.text}
    ` : ''} + ${liv ? html` +
    Living /month
    ${range(liv.totalEUR)} +
    rent ${range(liv.rentEUR)} · food ${range(liv.foodEUR)} · transport ${range(liv.transportEUR)} · other ${range(liv.otherEUR)}
    +
    Housing
    ${liv.housing}
    ` : ''} + ${r?.fees ? html`
    Mandatory fees
    ${r.fees.mandatoryEUR != null ? money(r.fees.mandatoryEUR, app.settings, app.data) : '?'} per semester +
    ${r.fees.text}
    ` : ''} + ${r?.travel ? html`
    Getting there
    ${r.travel.duration} · ${range(r.travel.roundTripEUR)} round trip +
    ${r.travel.text}
    ` : ''} + ${country?.visa ? html`
    Visa
    ${country.visa.required ? `${country.visa.type || 'Required'} · ${country.visa.costEUR != null ? money(country.visa.costEUR, app.settings, app.data) : 'cost unknown'}` : 'Not needed'} +
    ${country.visa.text}
    ` : ''} + ${n ? html`
    Out of pocket (${m} months)
    ${range([n.lo, n.hi])} +
    living ${range(n.parts.living)} + travel ${range(n.parts.travel)} + visa ${money(n.parts.visa, app.settings, app.data)} + + fees ${money(n.parts.fees, app.settings, app.data)} − money received ${money(n.parts.grant, app.settings, app.data)}
    ` : ''} +
    + ${liv ? para(liv.text) : ''}`; +} + +function safetyBlock(s, app) { + const r = s.research; + const c = app.data.countries?.[s.country]; + return html` + ${r ? scored('City safety', { score: r.safety.score, text: r.safety.text }) : ''} + ${r ? html`

    Hazards: ${r.safety.hazards}

    ` : ''} + ${c ? html` + ${scored('Country stability', { score: c.stabilityScore, text: c.text })} +

    World Bank political stability: ${c.wgiPoliticalStability?.percentile ?? '?'}th percentile (${c.wgiPoliticalStability?.year}) · + Global Peace Index #${c.gpi?.rank ?? '?'} (${c.gpi?.year})

    +

    Czech MFA: ${c.mfaAdvisory?.level} ${c.mfaAdvisory?.text}

    +

    Health insurance: ${c.health?.text}

    ` : ''}`; +} + +export function render(root, app, slug) { + const s = app.bySlug.get(slug); + if (!s) { + root.innerHTML = String(html`

    Unknown school

    Back to the ranking
    `); + return; + } + const r = s.research; + const st = app.state.stats.get(s.code); + const rank = app.rankOf(s.code); + const note = app.notes[s.code]?.text ?? ''; + const history = [...st.history].reverse().slice(0, 30); + + root.innerHTML = String(html` +
    + +
    + +

    ${fullName(s)}

    +

    ${shortName(s) !== fullName(s) ? `${shortName(s)} · ` : ''}${place(s)} · ${s.code}

    +

    + ${Math.round(st.rating)} Elo ${rank && st.games ? `· #${rank}` : ''} · ${st.games} games (${st.wins}W ${st.losses}L ${st.draws}D) + ${st.dropped ? html`dropped` : ''} +

    +
    + ${st.dropped + ? html`` + : html` + `} + ${s.web ? extLink(s.web, 'Website') : ''} ${s.qs ? extLink(s.qs, 'QS') : ''} + ${extLink(`https://www.openstreetmap.org/?mlat=${s.lat}&mlon=${s.lon}#map=12/${s.lat}/${s.lon}`, 'Map')} +
    +
    + + ${r ? html` +

    ${r.summary}

    +
    ${list(r.highlights, 'hl-list')}${list(r.watchouts, 'wo-list')}
    ` : html` +

    Research for this school is still pending. You can still compare it using the catalog data.

    `} + + ${section('Agreements', agreementsBlock(s, app))} + + ${r ? html` + ${section('AI & robotics', html` + ${scored('Research', r.aiRobotics.academic)} + ${scored('Hands-on', r.aiRobotics.practical)} + ${scored('Course access for you', r.aiRobotics.access)} +

    ${Object.entries(r.aiRobotics.rankings).filter(([, v]) => v).map(([k, v]) => html`${({ qsWorld: 'QS', qsCS: 'QS CS', csrankings: 'CSRankings', other: '' })[k]} ${v} `)}

    + ${r.aiRobotics.labs.length ? html`

    Labs & groups

    ${list(r.aiRobotics.labs)}` : ''} + ${r.aiRobotics.courses.length ? html`

    Relevant English courses

    ${list(r.aiRobotics.courses)}` : ''} + ${r.aiRobotics.teams.length ? html`

    Student teams

    ${list(r.aiRobotics.teams)}` : ''}`, r.confidence.aiRobotics)} + + ${section('Money', moneyBlock(s, app), r.confidence.living)} + + ${section('Language', html` +
    +
    Teaching
    ${r.language.teaching}
    +
    Proof needed
    ${r.language.proof}
    +
    Local language in daily life
    ${bar(r.language.localNeed)} (10 = essential)
    +
    ${para(r.language.text)}`, r.confidence.language)} + + ${section('Social life & solitude', html` + ${scored('Social', r.social)} +

    ${r.social.esn ? html`ESN/buddy: ${r.social.esn}` : ''}${r.social.internationals ? html` · Internationals: ${r.social.internationals}` : ''}

    + ${scored('Calm & solitude', r.solitude)}`, r.confidence.social)} + + ${section('Nature', html` + ${scored('Climbing', r.nature.climbing)} + ${scored('Hiking', r.nature.hiking)} + ${scored('Ocean', r.nature.ocean)} + ${scored('Skiing', r.nature.skiing)} +

    Climate (Sep–Feb): ${r.nature.climate}

    `, r.confidence.nature)} + ` : ''} + + ${section('Safety & stability', safetyBlock(s, app), r?.confidence?.safety)} + + ${r ? html` + ${section('Calendar & application', html` +
    +
    Term
    ${r.calendar.term}
    +
    Fit with CTU winter
    ${r.calendar.fit} · full year: ${r.calendar.fullYear}
    +
    Host deadline
    ${r.application.nominationDeadline ?? 'unknown'}
    +
    ${para(r.calendar.text)}${para(r.application.text)}`, r.confidence.calendar)} + + ${section('Sources', html` +
      ${r.sources.map((src) => html`
    1. ${extLink(src.url, src.label)}
    2. `)}
    +

    Researched ${r.researchedAt} · overall ${CONF_LABEL[r.confidence.overall]}. Check money and language rules officially before applying.

    `)} + ` : ''} + + ${section('My notes', html` + +

    ${note ? 'Saved' : 'Saved automatically'}

    `)} + + ${history.length ? section('My picks', html` +
      ${history.map((m) => { + const meA = m.a === s.code; + const other = app.byCode.get(meA ? m.b : m.a); + const delta = meA ? m.da : m.db; + const outcome = m.r === 'draw' ? 'tied with' : (m.r === 'a') === meA ? 'beat' : 'lost to'; + return html`
    • ${delta >= 0 ? '+' : ''}${Math.round(delta)} ${outcome} ${shortName(other)}
    • `; + })}
    `) : ''} +
    `); + + root.onclick = (e) => { + const t = e.target.closest('[data-action]'); + if (!t) return; + const action = t.dataset.action; + if (action === 'back') app.back(); + else if (action === 'drop') app.drop(s.code); + else if (action === 'restore') app.restore(s.code); + else if (action === 'duel') app.duelWith(s.code); + }; + const textarea = root.querySelector('textarea[name="note"]'); + const status = root.querySelector('[data-note-status]'); + let timer; + const save = () => { + clearTimeout(timer); + if (textarea.value === (app.notes[s.code]?.text ?? '')) return; + status.textContent = 'Saving…'; + app.saveNote(s.code, textarea.value) + .then(() => { status.textContent = 'Saved'; }) + .catch(() => { status.textContent = 'Not saved: offline? It will retry when you leave the field.'; }); + }; + textarea.addEventListener('input', () => { status.textContent = 'Editing…'; clearTimeout(timer); timer = setTimeout(save, 1200); }); + textarea.addEventListener('blur', save); +} diff --git a/public/js/views/settings.js b/public/js/views/settings.js new file mode 100644 index 0000000..6f4aa36 --- /dev/null +++ b/public/js/views/settings.js @@ -0,0 +1,110 @@ +// Preferences (synced to the server), per-device display options, data export/import, about. + +import { html, extLink, local } from '../ui.js'; +import { LANG_NAMES } from '../metrics.js'; + +const LEVELS = ['A1', 'A2', 'B1', 'B2', 'C1', 'C2']; + +export function render(root, app) { + const s = app.settings; + const theme = local.get('theme', 'system'); + const researched = app.data.schools.filter((x) => x.research).length; + const f = app.data.funding; + root.innerHTML = String(html` +
    +

    Your situation

    + +
    Currency +
    + ${['EUR', 'CZK'].map((c) => html``)} +
    +
    + + + +
    Your languages +
      ${s.languages.map((l, i) => html` +
    • ${LANG_NAMES[l.lang] ?? l.lang} + +
    • `)} +
    +
    + + +
    +
    + +
    Next pair +
    + + +
    +

    Smart shows rarely compared schools first, then close contests: fewer picks for the same ranking quality.

    +
    + +

    This device

    +
    Theme +
    + ${['system', 'light', 'dark'].map((t) => html``)} +
    +
    + +

    Your data

    +

    Picks, notes and settings live on your server (DATA_DIR). Export a backup now and then.

    +
    + Export backup + + ${app.config.authRequired ? html`` : ''} +
    + +

    About the data

    +
      +
    • Catalog: CTU Mobility, FEL, Master, ${app.data.catalog.academicYear}, saved ${app.data.catalog.savedAt?.slice(4, 15) ?? '?'}.
    • +
    • Research: ${researched} of ${app.data.schools.length} schools so far. Data built ${app.data.generatedAt.slice(0, 10)}.
    • +
    • Erasmus+ rates: ${f.erasmus.status}.
    • +
    • Selection round: ${f.selection.deadline}
    • +
    • Exchange rate: 1 € = ${app.data.fx.EURCZK} Kč (${app.data.fx.date}).
    • +
    • Everything here was gathered from public web sources and can be wrong or outdated. + Check money, language rules and deadlines with the FEL international office before you apply.
    • +
    • Selection info sources: ${f.selection.sources.slice(0, 3).map((x) => html`${extLink(x.url, x.label)}; `)}
    • +
    +

    Elorasmus ${app.config.version}

    +
    `); + + const update = (patch) => app.updateSettings(patch); + root.onchange = async (e) => { + const el = e.target; + if (el.name === 'stayMonths') { + const v = Number(el.value); + if (v >= 1 && v <= 12) update({ stayMonths: v }); + } else if (el.name === 'currency' || el.name === 'pairing') update({ [el.name]: el.value }); + else if (el.name === 'fewerOpportunities' || el.name === 'countHostFunding') update({ [el.name]: el.checked }); + else if (el.name === 'level') { + const langs = s.languages.map((l, i) => (i === Number(el.dataset.i) ? { ...l, level: el.value } : l)); + update({ languages: langs }); + } else if (el.name === 'theme') { + local.set('theme', el.value); + app.applyTheme(); + } else if (el.name === 'import' && el.files?.[0]) { + app.importBackup(el.files[0]); + el.value = ''; + } + }; + root.onclick = (e) => { + const t = e.target.closest('[data-action]'); + if (!t) return; + if (t.dataset.action === 'rmlang') update({ languages: s.languages.filter((_, i) => i !== Number(t.dataset.i)) }); + if (t.dataset.action === 'addlang') { + const lang = root.querySelector('select[name="newlang"]').value; + if (lang) update({ languages: [...s.languages, { lang, level: 'B1' }] }); + } + if (t.dataset.action === 'logout') app.logout(); + }; +} diff --git a/public/js/views/triage.js b/public/js/views/triage.js new file mode 100644 index 0000000..750c70b --- /dev/null +++ b/public/js/views/triage.js @@ -0,0 +1,85 @@ +// Quick first pass: one school at a time, Keep or Drop. Schools with hard problems (language you +// don't speak, unrelated subject, unsafe country) come first, with the reasons shown. + +import { html, bar } from '../ui.js'; +import { shortName, place, languageFit, subjectFit, netCost, moneyRange, monthlyGrant, money } from '../metrics.js'; + +/** Reasons a school is probably not worth comparing. Empty = nothing obviously wrong. */ +export function concerns(s, app) { + const out = []; + const lang = languageFit(s, app.settings.languages); + if (lang.status === 'fail') out.push(`Language: ${lang.text.replace('✗ ', '')}`); + const subj = subjectFit(s); + if (subj.rank <= 1) out.push(`Subject area: ${subj.text}`); + const c = app.data.countries?.[s.country]; + if (c && c.stabilityScore <= 3) out.push(`Country stability ${c.stabilityScore}/10 (MFA: ${c.mfaAdvisory?.level})`); + const r = s.research; + if (r && r.safety.score <= 3) out.push(`City safety ${r.safety.score}/10`); + if (r && r.aiRobotics.access.score <= 2) out.push(`Few relevant courses for you (access ${r.aiRobotics.access.score}/10)`); + return out; +} + +export function render(root, app) { + const all = app.data.schools.map((s) => ({ s, st: app.state.stats.get(s.code) })); + const queue = all + .filter(({ st }) => !st.reviewed && !st.dropped) + .map((x) => ({ ...x, why: concerns(x.s, app) })) + .sort((x, y) => y.why.length - x.why.length); + const done = all.length - queue.length; + + if (!queue.length) { + root.innerHTML = String(html` +
    +

    Triage done

    +

    You've been through all ${all.length} schools. Now the comparisons do the rest.

    + Start comparing +
    `); + return; + } + + const { s, why } = queue[0]; + const r = s.research; + const n = netCost(s, app.settings, app.data); + const g = monthlyGrant(s, app.settings, app.data); + root.innerHTML = String(html` +
    +
    + ${done} / ${all.length} reviewed +
    +

    Optional first pass. Drop the obvious no-gos so your picks go to real candidates. Problem schools come first.

    +
    +
    + +

    ${shortName(s)}

    ${place(s)}

    +
    + ${why.length ? html`
      ${why.map((w) => html`
    • ${w}
    • `)}
    ` : ''} + ${r ? html` +

    ${r.summary}

    +
    +
    AI research
    ${bar(r.aiRobotics.academic.score)}
    +
    Course access
    ${bar(r.aiRobotics.access.score)}
    +
    Social / calm
    ${r.social.score} / ${r.solitude.score}
    +
    Climb / hike / ocean
    ${r.nature.climbing.score} / ${r.nature.hiking.score} / ${r.nature.ocean.score}
    +
    CTU money
    ${money(g.eur, app.settings, app.data)}/mo
    +
    Out of pocket
    ${n ? moneyRange([n.lo, n.hi], app.settings, app.data, { compact: true }) : '–'}
    +
    + ${r.watchouts.length ? html`
      ${r.watchouts.slice(0, 3).map((w) => html`
    • ${w}
    • `)}
    ` : ''}` + : html`

    Research pending: judge from the catalog for now, or keep it and decide later.

    `} + +
    +
    +
    +
    + + +
    +
    `); + + root.onclick = (e) => { + const t = e.target.closest('[data-action]'); + if (!t) return; + if (t.dataset.action === 'drop') app.drop(s.code); + if (t.dataset.action === 'keep') app.review(s.code); + if (t.dataset.action === 'open') app.navigate(`#/school/${t.dataset.slug}`); + }; +} diff --git a/public/manifest.webmanifest b/public/manifest.webmanifest new file mode 100644 index 0000000..ef1dd1c --- /dev/null +++ b/public/manifest.webmanifest @@ -0,0 +1,15 @@ +{ + "name": "Elorasmus", + "short_name": "Elorasmus", + "description": "Pick one of two exchange schools, again and again, and let Elo build your ranking.", + "start_url": "./", + "scope": "./", + "display": "standalone", + "background_color": "#f6f4ef", + "theme_color": "#f6f4ef", + "icons": [ + { "src": "icons/icon-192.png", "sizes": "192x192", "type": "image/png" }, + { "src": "icons/icon-512.png", "sizes": "512x512", "type": "image/png" }, + { "src": "icons/icon.svg", "sizes": "any", "type": "image/svg+xml" } + ] +} diff --git a/scripts/make_icons.py b/scripts/make_icons.py new file mode 100644 index 0000000..1e41341 --- /dev/null +++ b/scripts/make_icons.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python3 +"""Rasterise the app icon (same geometry as public/icons/icon.svg) to PNGs, stdlib only. + +Usage: python3 -I scripts/make_icons.py +Writes public/icons/icon-192.png, icon-512.png (rounded, transparent corners) and +apple-touch-icon.png (180 px, full-bleed: iOS applies its own mask). +""" +import os +import struct +import zlib + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +BG, TEAL, ORANGE, LIGHT = (0x14, 0x20, 0x2B), (0x16, 0xA3, 0x94), (0xE8, 0x89, 0x3A), (0xF6, 0xF4, 0xEF) +C1, C2, R = (24.3, 32.0), (39.7, 32.0), 15.4 # in a 64x64 design grid + + +def colour_at(x, y, rounded): + if rounded: # rounded rect, radius 14 + cx, cy = min(max(x, 14), 50), min(max(y, 14), 50) + if (x - cx) ** 2 + (y - cy) ** 2 > 14 ** 2: + return None + in1 = (x - C1[0]) ** 2 + (y - C1[1]) ** 2 <= R * R + in2 = (x - C2[0]) ** 2 + (y - C2[1]) ** 2 <= R * R + return LIGHT if in1 and in2 else ORANGE if in2 else TEAL if in1 else BG + + +def render(size, rounded, ss=4): + rows = [] + for py in range(size): + row = bytearray([0]) # PNG filter type 0 + for px in range(size): + acc, alpha = [0, 0, 0], 0 + for sy in range(ss): + for sx in range(ss): + c = colour_at((px + (sx + .5) / ss) * 64 / size, (py + (sy + .5) / ss) * 64 / size, rounded) + if c: + alpha += 1 + for i in range(3): + acc[i] += c[i] + n = ss * ss + row += bytes([round(acc[i] / alpha) if alpha else 0 for i in range(3)] + [round(255 * alpha / n)]) + rows.append(bytes(row)) + def chunk(tag, data): + return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF) + ihdr = struct.pack(">IIBBBBB", size, size, 8, 6, 0, 0, 0) # 8-bit RGBA + return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + chunk(b"IDAT", zlib.compress(b"".join(rows), 9)) + chunk(b"IEND", b"") + + +for name, size, rounded in (("icon-192.png", 192, True), ("icon-512.png", 512, True), ("apple-touch-icon.png", 180, False)): + path = os.path.join(ROOT, "public", "icons", name) + with open(path, "wb") as f: + f.write(render(size, rounded)) + print(path, os.path.getsize(path), "bytes")