/* The Roles tab: newsdesk's feed and reader, on roledesk's API. * * Three panes, as newsdesk has them (news/newsdesk/web/templates/index.html, * whose functions keep their names here): the rail of filters (`renderRail`), * the feed (`renderFeed`, `loadFeed`), and the reader (`showReader`, * `renderReader`), a third column beside the feed that replaces it below * 60rem. The template renders an empty shell; everything on screen comes from * the JSON routes in app/web/api.py, and every request goes through `api()` * from app.js, so a failure is one toast carrying the server's own sentence. * * A row is newsdesk's `.row`: the score gutter and number (hidden under * Newest first, since the score is not what put the row there), the title, * company · place · badges · age · tags, the summary or the description's * opening, and ▲ ● ▼ ★ from judge.js. A passed role and a hidden company's * are dimmed, never dropped, so a stray tap stays visible to be undone. * * Opening a role pushes `/roles/{uid}`; closing goes back. Stepping with j/k * while it is open replaces that entry rather than stacking one per role, so * back always means "out of the reader". The server answers `/roles/{uid}` * with this same page, and `route` is the only thing that reads the path. * * The filters are in the query string, replaced rather than pushed, so a * reload or a link keeps them and the back button is not buried under them. * `?company=` and `?agent=` are how the Companies and Ranking pages link in. * * The list is paged: 60 rows, then 60 more each time the end of the list comes * within 600px of the screen, with the offset the rows already shown. Back to * this page from another tab puts the same number of rows and the scroll * position back, from sessionStorage. */ (function () { "use strict"; const { api, esc, debounce, companies, loadCompanies, affinityControl, judgeButtons, loadTracked } = window; const $ = (sel, root = document) => root.querySelector(sel); // Below this the rail is over the feed rather than beside it, and the reader // replaces the feed. Asked of the stylesheet's own breakpoint rather than // measured in pixels, so a larger root font size cannot make the two // disagree (newsdesk's reasoning). const narrow = window.matchMedia("(max-width: 60rem)"); const overlayRail = () => narrow.matches; const PAGE = 60; /** Shorter than this and not fetched: the description is a teaser. */ const TEASER = 500; /** How many rows and how far down, for coming back to this page. */ const KEPT = "roledesk.roles"; const number = new Intl.NumberFormat("en"); // What the list is in the order of. Best first is the first enabled // ranking's score, moved by the role's vote; Newest first is first seen. const SORTS = { score: "Best first", time: "Newest first" }; // The named windows over `days`, which counts back from now. const PERIODS = { all: { label: "Any time", days: null }, today: { label: "Today", days: 1 }, week: { label: "This week", days: 7 }, month: { label: "This month", days: 30 }, }; // Everything `clearFilters` has to put back, in one place, so a new filter // added here cannot be forgotten there. function blankFilter() { return { sort: "score", agent: null, period: "all", tags: new Set(), showRead: true, company: "", place: "", function: "", remote: "", judged: "", showMuted: false, gated: false, }; } const state = { filter: blankFilter(), q: "", railOpen: !narrow.matches, railAutoShut: false, // the reader folded the rail, so closing unfolds it agents: [], // the enabled rankings, from /api/agents tags: [], // [{tag, count, unread}] from /api/filters items: [], // the rows on screen, in order total: 0, // how many roles the filters match in all loaded: false, // the first page has landed loading: false, // a page is in flight, so the pager holds off selected: 0, // which row the keyboard is on reading: null, // the fetched role, or null while it loads readingUid: null, // set before the fetch lands, so a late answer is dropped pushedReader: false, // we own a history entry, so closing is `history.back()` summarising: null, // the uid whose summary is being waited for listY: 0, // where the page was scrolled when the reader replaced the feed }; const safeUrl = (u) => (/^https?:\/\//i.test(u || "") ? u : ""); function ago(iso) { const mins = (Date.now() - new Date(iso)) / 60000; if (!Number.isFinite(mins)) return ""; if (mins < 60) return `${Math.max(0, Math.round(mins))}m`; if (mins < 1440) return `${Math.round(mins / 60)}h`; return `${Math.round(mins / 1440)}d`; } // ------------------------------------------------------------ the order /** The ranking the list is ordered by, or null for Newest first. Best first with no ranking enabled is Newest first; an `agent` from the URL that is not an enabled ranking falls back to the first one. */ function rankedBy() { if (state.filter.sort !== "score" || !state.agents.length) return null; const chosen = state.agents.find((a) => a.id === state.filter.agent); return (chosen || state.agents[0]).id; } const sortShown = () => (rankedBy() === null ? "time" : "score"); function feedParams() { const f = state.filter; const p = new URLSearchParams(); if (state.q) p.set("q", state.q); for (const key of ["company", "place"]) if (f[key].trim()) p.set(key, f[key].trim()); for (const key of ["function", "remote", "judged"]) if (f[key]) p.set(key, f[key]); const days = PERIODS[f.period].days; if (days) p.set("days", String(days)); if (f.showMuted) p.set("show_muted", "true"); if (!f.showRead) p.set("include_read", "false"); f.tags.forEach((t) => p.append("tags", t)); const agent = rankedBy(); if (agent !== null) { p.set("agent", String(agent)); if (f.gated) p.set("gated", "true"); } return p; } // ------------------------------------------------ filters in the address const PERIOD_OF_DAYS = { 1: "today", 7: "week", 30: "month" }; /** The query string into the filter, once, at load. */ function readUrl() { const q = new URLSearchParams(location.search); const f = state.filter; state.q = q.get("q") || ""; for (const key of ["company", "place", "function", "remote", "judged"]) { f[key] = q.get(key) || ""; } f.period = PERIOD_OF_DAYS[q.get("days")] || "all"; f.showMuted = q.get("show_muted") === "true"; f.showRead = q.get("include_read") !== "false"; f.gated = q.get("gated") === "true" || q.get("gated") === "1"; f.tags = new Set(q.getAll("tags")); if (q.get("sort") === "time") f.sort = "time"; if (q.get("agent")) { f.sort = "score"; f.agent = Number(q.get("agent")); } if (f.company || f.place || f.function || f.remote || f.judged || f.showMuted || f.gated) { $("#f-more").open = true; } } /** The filter into the query string, replacing the entry rather than adding one: a filter is a question, not a place. */ function writeUrl() { const p = feedParams(); p.delete("agent"); p.delete("gated"); const f = state.filter; if (f.sort === "time") p.set("sort", "time"); else if (f.agent !== null) p.set("agent", String(f.agent)); if (f.gated && f.sort === "score") p.set("gated", "true"); const query = p.toString(); const url = location.pathname + (query ? `?${query}` : ""); if (url !== location.pathname + location.search) history.replaceState(history.state, "", url); } // -------------------------------------------------------------- loading let feedRequest = 0; /* A reload starts the list again; an append asks for the rows after the ones shown. `keep` asks for that many in one go, which is how the list is put back as it was. The latch is let go only by the newest request: a reload overtaking an append must not let a second append start with an offset into the list being replaced. */ async function loadFeed({ append = false, keep = 0 } = {}) { if (append && (state.loading || state.items.length >= state.total)) return; const params = feedParams(); params.set("offset", String(append ? state.items.length : 0)); params.set("limit", String(Math.min(1000, Math.max(PAGE, keep)))); const request = ++feedRequest; state.loading = true; let data; try { data = await api(`/api/roles?${params}`); } catch (err) { return; } finally { if (request === feedRequest) state.loading = false; } if (request !== feedRequest) return; const held = append ? state.items[state.selected]?.uid : state.readingUid; state.total = data.total; state.items = append ? state.items.concat(data.items) : data.items; state.loaded = true; const at = held ? state.items.findIndex((r) => r.uid === held) : -1; state.selected = at >= 0 ? at : append ? state.selected : 0; renderFeed(); renderStats(); // Still within reach of the end after a short page: the observer only // fires on a change, and nothing changed, so ask again here. requestAnimationFrame(() => { const end = $("#feed-end").getBoundingClientRect(); if (end.height && end.top < window.innerHeight + 600) loadFeed({ append: true }); }); } /* A different list starts at the top. Without this the window stays where the last one was scrolled to, the end of a shorter list is immediately in view, and picking a filter silently fetches pages nobody asked for. */ function reload() { loadFeed().then(() => { window.scrollTo(0, 0); $("#list").scrollTop = 0; }); } async function loadAgents() { state.agents = (await api("/api/agents")).filter((a) => a.enabled); } // The tag counts. Asked with `show_muted` only, the one filter the route // takes, so picking a tag does not renumber the others. let filtersRequest = 0; async function loadFilters() { const params = new URLSearchParams(); if (state.filter.showMuted) params.set("show_muted", "true"); const request = ++filtersRequest; const data = await api(`/api/filters?${params}`); if (request !== filtersRequest) return; state.tags = data.tags || []; renderRail(); } // ------------------------------------------------------------ the rail function setFilter(patch = {}, { counts = false } = {}) { Object.assign(state.filter, patch); writeUrl(); // A filter is a question about the feed, and the role open over the old // answer is the wrong thing to leave on screen. Its entry is replaced // rather than popped, or back would land on the list the filter just left. if (state.readingUid) navigate(pathFor(null), { replace: true }); reload(); if (counts) loadFilters().catch(() => {}); renderRail(); renderActive(); } function clearFilters() { const kept = { agent: state.filter.agent }; state.filter = Object.assign(blankFilter(), kept); setFilter({}, { counts: true }); } // Text that has not changed is not a change: without this, Escape in an // empty box would shut the reader and call it a search. function setSearch(q) { if (q === state.q) return; state.q = q; setFilter({}); } function toggleTag(tag) { const tags = state.filter.tags; if (tags.has(tag)) tags.delete(tag); else tags.add(tag); setFilter({}); } // An explicit toggle sticks: closing the reader won't undo a choice you made. function toggleRail() { state.railOpen = !state.railOpen; state.railAutoShut = false; renderRail(); } /** A text field or select's value, written only when it differs, so the caret of the field being typed in is left where it is. */ function setValue(id, value) { const el = document.getElementById(id); if (el.type === "checkbox") el.checked = Boolean(value); else if (el.value !== value) el.value = value; } function renderRail() { const f = state.filter; $("#show-read").setAttribute("aria-pressed", String(f.showRead)); // The order. One ranking, or none, is the segmented control; more than one // is a select naming each, so none is lost. const ranked = rankedBy(); const many = state.agents.length > 1; $("#sort").hidden = many; $("#agent").hidden = !many; if (many) { const select = $("#agent"); select.replaceChildren(...state.agents.map((a) => new Option(a.name, String(a.id))), new Option(SORTS.time, "")); select.value = ranked === null ? "" : String(ranked); } else { const none = !state.agents.length; $("#sort").innerHTML = Object.entries(SORTS).map(([key, label]) => { const off = key === "score" && none; return ``; }).join(""); $("#sort").querySelectorAll("[data-sort]").forEach((b) => { b.onclick = () => { if (b.getAttribute("aria-disabled") === "true") return; setFilter({ sort: b.dataset.sort }); }; }); } $("#show-gated").hidden = ranked === null; $("#period").value = f.period; // Tags are chips, multi-select. One the filter holds stays on the list // even when nothing carries it any more, so it can still be taken off. const live = state.tags.filter((t) => t.count > 0); for (const tag of f.tags) { if (!live.some((t) => t.tag === tag)) live.push({ tag, count: 0, unread: 0 }); } $("#tags").innerHTML = live.map((t) => ` `).join(""); $("#tags").querySelectorAll("[data-tag]").forEach((b) => { b.onclick = () => toggleTag(b.dataset.tag); }); $("#clear-tags").hidden = f.tags.size === 0; const note = $("#tag-note"); note.hidden = live.length > 0; note.textContent = "No role is tagged yet."; setValue("f-company", f.company); setValue("f-place", f.place); setValue("f-function", f.function); setValue("f-remote", f.remote); setValue("f-judged", f.judged); setValue("f-show-muted", f.showMuted); setValue("f-gated", f.gated); const more = [f.company.trim(), f.place.trim(), f.function, f.remote, f.judged, f.showMuted, ranked !== null && f.gated].filter(Boolean).length; $("#f-active").textContent = more ? ` · ${more}` : ""; document.body.dataset.rail = state.railOpen ? "open" : "shut"; $("#rail-toggle").setAttribute("aria-expanded", String(state.railOpen)); } /* With the rail shut, which is every narrow screen, the burger is the only thing left that can say a filter is on, so it says how many, in words: a number in a circle reads as "new things" on the one control that means things are being left out (newsdesk's reasoning). */ function renderActive() { const f = state.filter; const on = [!f.showRead, f.period !== "all", f.company.trim(), f.place.trim(), f.function, f.remote, f.judged, f.showMuted, rankedBy() !== null && f.gated] .filter(Boolean).length + f.tags.size; const count = on === 1 ? "1 filter" : `${on} filters`; $(".rail-toggle-label").textContent = on ? count : "Menu"; $("#rail-toggle").setAttribute("aria-label", on ? `Menu — ${count} on` : "Menu"); } function renderStats() { const noun = state.total === 1 ? "role" : "roles"; $("#rail-stats").textContent = state.loaded ? `${number.format(state.total)} ${noun} match` : ""; } // ------------------------------------------------------------ the feed // Add, drop, patch, never rebuild (newsdesk's `sync`): a row that stays // keeps its element, and with it its buttons and its focus. `entries` are // [key, item] pairs in screen order, `make` builds an element for a new // one, and `fill` writes this render's values into one that stays. function sync(parent, entries, make, fill) { const had = new Map(); for (const el of parent.children) had.set(el.dataset.key, el); let last = null; for (const [key, item] of entries) { const k = String(key); let el = had.get(k); if (el) had.delete(k); else { el = make(item); el.dataset.key = k; } fill(el, item); // Where it belongs, and left alone when it is already there, since // moving a node is a remove and an insert. const at = last ? last.nextElementSibling : parent.firstElementChild; if (el !== at) parent.insertBefore(el, at); last = el; } for (const el of had.values()) el.remove(); } /* The summary when there is one, else the description's opening, cut at a word. */ function excerpt(role) { if (role.summary) return role.summary; const text = (role.description || "").replace(/\s+/g, " ").trim(); if (text.length <= 160) return text; const cut = text.slice(0, 160); const space = cut.lastIndexOf(" "); return `${(space > 100 ? cut.slice(0, space) : cut).replace(/[\s,.;:–-]+$/, "")}…`; } function tagChips(tags) { return (tags || []).map((tag) => ` `).join(""); } function badges(role, { seniority = false } = {}) { const words = [role.remote, role.function, seniority ? role.seniority : ""].filter(Boolean); return (role.closed_at ? `closed` : "") + words.map((w) => `${esc(w)}`).join(""); } function drawRow(el, role) { const scored = role.score !== null && role.score !== undefined; const pct = scored ? Math.round(Math.min(1, Math.max(0, role.score)) * 100) : 0; const text = excerpt(role); el.innerHTML = `
${esc(text)}
` : ""}No open role fits these filters. and start again.
` : `Nothing has been pulled yet. Pulls runs one; Searches and Companies decide what it brings in.
`; const clear = empty.querySelector("[data-clear]"); if (clear) clear.onclick = () => { state.q = ""; $("#search").value = ""; clearFilters(); }; } // The end of the list says which end it is: a list that has run out and // one that is still loading look the same otherwise. const end = $("#feed-end"); const n = state.items.length; end.hidden = !state.loaded || !n; end.textContent = n < state.total ? "Loading more…" : `${number.format(n)} ${n === 1 ? "role" : "roles"} — that is all of them.`; } // ----------------------------------------------------------- the reader // Reading happens in a third column rather than on a page of its own, so // voting stays one keystroke away from the text being judged. function openReader(uid) { if (!uid) return; const reading = Boolean(state.readingUid); navigate(pathFor(uid), { replace: reading }); if (!reading) state.pushedReader = true; } // Every way of closing goes through the back button rather than around it, // so the entry `openReader` pushed is popped by the close that matches it. A // role arrived at directly (a link, a reload) has no entry of ours under it, // so its list replaces it instead of leaving the app. function closeReader() { if (state.pushedReader) history.back(); else navigate(pathFor(null), { replace: true }); } // What `route` does when the path names a role: the pane, and the fetch. async function showReader(uid) { if (!state.readingUid) state.listY = window.scrollY; // Drop the last role first, or the loading render paints its text for as // long as the fetch takes. state.reading = null; state.readingUid = uid; const idx = state.items.findIndex((r) => r.uid === uid); if (idx >= 0) state.selected = idx; // Three columns need room. Below that the rail yields, since choosing // what to read is done the moment reading starts. if (state.railOpen && window.innerWidth < 1500) { state.railOpen = false; state.railAutoShut = true; renderRail(); } renderReader({ loading: true }); renderFeed(); rowAt(state.selected)?.scrollIntoView({ block: "nearest" }); markRead(uid); try { const role = await api(`/api/roles/${encodeURIComponent(uid)}`); if (state.readingUid !== uid) return; // moved on before this landed state.reading = role; renderReader(); } catch (err) { if (state.readingUid === uid) renderReader({ error: err.detail || String(err) }); } } // What `route` does when the path no longer names a role. function shutReader() { state.pushedReader = false; state.reading = null; state.readingUid = null; state.summarising = null; if (state.railAutoShut) { state.railOpen = true; state.railAutoShut = false; } renderReader(); renderFeed(); renderRail(); document.title = "Roles — roledesk"; // The feed was not on screen while the reader was (narrow), or was a // pane of its own that shortened the page (wide), and the page lost its // place with it. Back to where it was, then as far as the row the keys // moved to. window.scrollTo(0, state.listY); rowAt(state.selected)?.scrollIntoView({ block: "nearest" }); } async function markRead(uid) { const item = state.items.find((r) => r.uid === uid); if (item && item.read_at) return; if (item) { item.read_at = new Date().toISOString(); renderFeed(); } try { const role = await api(`/api/roles/${encodeURIComponent(uid)}/read`, { method: "POST" }); if (item && role) item.read_at = role.read_at; } catch (err) { /* toasted by api() */ } } function salary(r) { const n = (v) => number.format(v); const unit = r.currency ? `${r.currency} ` : ""; if (r.salary_min && r.salary_max && r.salary_min !== r.salary_max) { return `${unit}${n(r.salary_min)}–${n(r.salary_max)}`; } if (r.salary_min || r.salary_max) { const one = r.salary_min || r.salary_max; return r.salary_min ? `From ${unit}${n(one)}` : `Up to ${unit}${n(one)}`; } return ""; } function host(url) { try { return new URL(url).host.replace(/^www\./, ""); } catch (e) { return ""; } } /* Plain text in paragraphs: a fetched page keeps its line breaks, and a board's description is one long line, which stays one paragraph. */ function paragraphs(text) { return text.split(/\n+/).map((p) => p.trim()).filter(Boolean) .map((p) => `${esc(p)}
`).join(""); } function renderReader({ loading = false, error = "" } = {}) { const el = $("#reader"); const open = Boolean(state.readingUid); el.hidden = !open; const want = open ? "open" : "shut"; if (document.body.dataset.reader !== want) { document.body.dataset.reader = want; renderRail(); } if (!open) { el.replaceChildren(); return; } // The list row is already in memory, and a list row is the whole role, so // the pane paints from it at once and the fetch only brings it up to date. const stub = state.items.find((r) => r.uid === state.readingUid); const r = state.reading || stub || {}; const same = el.dataset.uid === state.readingUid; const scrolled = same ? el.querySelector(".reader-body")?.scrollTop || 0 : 0; el.dataset.uid = state.readingUid; if (r.title) document.title = `${r.title} — roledesk`; const out = safeUrl(r.original_url); const text = (r.article_text || r.description || "").trim(); const body = error ? `This role could not be loaded: ${esc(error)}
` : !r.uid ? `Loading…
` : text ? paragraphs(text) : `The board gave no description for this one.
`; const pay = salary(r); const waiting = state.summarising === state.readingUid; const teaser = r.uid && !r.article_text && out && (r.description || "").length < TEASER; el.innerHTML = `${esc(pay)}
` : ""} ${r.summary ? `${esc(r.summary)}