/* 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 from a role 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 rail opens on Viewing as: the search agent the feed is seen as. An * agent is a persona ("me as a candidate", "me as a hiring manager watching * the market") with its own scores, votes and hidden companies, so every * request that has an answer per agent names it: the feed, the tag counts, * the role in the reader, the company list, each vote (judge.js's `{agent}`) * and each company affinity. One is always picked while any is enabled: the * one in `?agent=`, else the one this browser viewed last (localStorage), * else the enabled one with the lowest id, which is the server's default too. * Picking another reloads the feed and the counts under the reader, which * stays open and is fetched again for that agent's vote. * * Order is Best first (`order=score`, the agent's score moved by its votes) * or Newest first (`order=newest`), the same two whichever agent is viewed, * and both carry the agent's votes and hidden companies. * * The filters are in the query string, so a reload or a link keeps them, and * each one set is a history entry, so back takes it off again: a tag, the * period, Show read, a select, a checkbox, a seniority level, a company or * place chip picked or removed, Clear, and a company's name. Text is the * exception: the search box replaces the entry, or back would step through a * search a letter at a time. Who is viewing and the * order are not filters and replace too; back and forward leave both as * they are and write them into the entry they land on. `popstate` reads the * address into the filter and reloads the feed, pushing nothing. * * Every entry this page pushes carries `{from}`, the address it was pushed * over, so a way out that means "the list as it was" (closing the reader, * taking the company off) is `history.back()` when the entry under it is * that list, and a new entry otherwise, e.g. on a link arrived at from * another page. That replaces a flag held in memory, and survives a reload * and a step back into the reader. * * A filter set while the reader is open pushes the new list over the role, * so the reader shuts and back reopens the role over the old list: back * undoes the one thing done last, and a click on the company in the reader * reads as the link it is. Nothing to change (Clear with nothing set) just * closes the reader, as Escape would. * * A company's name, in a row and in the reader, is a link to the list on * screen with that company as its one company chip (`?company_keys=`); a * plain click filters in place and pushes. With one company filtered a strip * over the feed names it, counts its roles, links its careers page and * carries its ★ ▲ ⊘ for the viewing agent. `?company=`, `?company_keys=` and * `?agent=` are how the Companies and Search agents pages link in. * * Company and Place in the rail are chip inputs (chips.js) on the suggest * routes: a chip is a company key or a place token (`country:DK`, * `region:skane`), several joined by OR. `?company=` and `?place=`, the * substrings of the links from other pages, still filter and show as a chip * of their own to take off; nothing in the rail types a new one. Seniority * and Pay carry the counts of `/api/roles/facets`, asked after each reload * with the feed's own parameters, so each says what a click would add. * * 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, safeUrl, companies, loadCompanies, affinityControl, allRolesControl, judgeButtons, loadTracked, chipInput } = 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"; /** The agent last viewed as, so the next visit opens on the same persona. */ const VIEWING = "roledesk.agent"; const number = new Intl.NumberFormat("en"); // What the list is in the order of. Best first is the viewing agent's // score, moved by its votes; 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 }, }; // The place suggestion's kind, as its hint says it: a `place:` token is a // town (`places.suggest`). const PLACE_KINDS = { country: "country", region: "region", place: "town" }; // Everything `clearFilters` has to put back, in one place, so a new filter // added here cannot be forgotten there. `company` and `place` are the // substrings of links from other pages; `companyKeys` and `places` are the // rail's chips. `seniorityUnknown` and `payUnknown` are the "and roles // with no level / no pay" boxes, asked only while a level or a pay option // is picked. function blankFilter() { return { sort: "score", agent: null, period: "all", tags: new Set(), showRead: true, company: "", place: "", function: "", remote: "", judged: "", pay: "", showMuted: false, gated: false, companyKeys: [], places: [], seniority: [], seniorityUnknown: true, payUnknown: false, }; } /** How many filters are on, for the burger; `more` counts only the ones under "More filters", for its summary. A chip or a level is one each, as a tag is; the "no level" and "no pay" boxes widen a filter already counted. */ function filtersOn(f = state.filter, { more = false } = {}) { const folded = [f.company.trim(), f.place.trim(), f.function, f.remote, f.pay, f.judged, f.showMuted, sortShown() === "score" && f.gated].filter(Boolean).length + f.companyKeys.length + f.places.length + f.seniority.length; if (more) return folded; return folded + [!f.showRead, f.period !== "all"].filter(Boolean).length + f.tags.size; } const state = { filter: blankFilter(), q: "", railOpen: !narrow.matches, railAutoShut: false, // the reader folded the rail, so closing unfolds it agents: [], // the enabled search agents, from /api/agents, by id agentsLoaded: false, // so "no agent" is not said before the answer 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 summarising: null, // the uid whose summary is being waited for listY: 0, // where the page was scrolled when the reader replaced the feed feedError: false, // the feed's own fetch failed; the empty state offers a retry facets: null, // {seniority, pay} counts from /api/roles/facets for this filter }; // The chips' text, by company key and by place token: what a pick said, // or what the server named a token read from the address. Kept for the // page's life, so back to an earlier filter finds its chips' names. const companyNames = new Map(); const placeLabels = new Map(); // The rail's two chip inputs, made in `wire`. let companyChips = null; let placeChips = null; 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 order the list is in. Best first needs an agent to score by: with none enabled the server answers newest first, and so does this. */ const sortShown = () => (state.filter.sort === "score" && state.filter.agent !== null ? "score" : "time"); /** The feed's query for a filter, the one on screen unless told. */ function feedParams(f = state.filter, q = state.q) { const p = new URLSearchParams(); if (q) p.set("q", q); for (const key of ["company", "place"]) if (f[key].trim()) p.set(key, f[key].trim()); for (const key of ["function", "remote", "judged", "pay"]) 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)); f.companyKeys.forEach((key) => p.append("company_keys", key)); f.places.forEach((token) => p.append("places", token)); f.seniority.forEach((level) => p.append("seniority", level)); // Each box is sent only off its default, and only while its filter is on. if (f.seniority.length && !f.seniorityUnknown) p.set("seniority_unknown", "false"); if (f.pay && f.payUnknown) p.set("pay_unknown", "true"); if (f.agent !== null) { p.set("agent", String(f.agent)); p.set("order", sortShown() === "score" ? "score" : "newest"); if (f.gated && sortShown() === "score") p.set("gated", "true"); } return p; } // ------------------------------------------------ filters in the address const PERIOD_OF_DAYS = { 1: "today", 7: "week", 30: "month" }; /** A query string into the filter and the search: the address at load, on back and forward, and a company link followed in place. Who is viewing and the order are read only when `view` is set, at load: on back and forward they stay as they are, since neither is a step in the history. */ function readUrl(search = location.search, { view = true } = {}) { const q = new URLSearchParams(search); const f = state.filter; state.q = q.get("q") || ""; for (const key of ["company", "place", "function", "remote", "judged", "pay"]) { 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")); f.companyKeys = [...new Set(q.getAll("company_keys").filter(Boolean))]; f.places = [...new Set(q.getAll("places").filter(Boolean))]; f.seniority = [...new Set(q.getAll("seniority").filter(Boolean))]; f.seniorityUnknown = q.get("seniority_unknown") !== "false"; f.payUnknown = q.get("pay_unknown") === "true"; if (!view) return; if (q.get("sort") === "time") f.sort = "time"; // Checked against the enabled agents once they are in (`chooseAgent`). if (q.get("agent")) f.agent = Number(q.get("agent")); // Open where the rail is a column of its own, which scrolls; shut where // it is an overlay, unless a filter in it is on, which it then shows. if (!narrow.matches || filtersOn(f, { more: true })) $("#f-more").open = true; } /* The chip text of place tokens read from the address, which carries only the token. A token the server does not know is dropped from the filter and the address, rather than sent to /api/roles for a 422. Nothing is asked when every token already has its text. */ async function labelPlaces() { const missing = state.filter.places.filter((t) => !placeLabels.has(t)); if (!missing.length) return; const p = new URLSearchParams(); missing.forEach((t) => p.append("tokens", t)); let found; try { found = await api(`/api/places/labels?${p}`); } catch (err) { return; // toasted; the chips show the tokens themselves } for (const { token, label } of found) placeLabels.set(token, label); const kept = state.filter.places.filter((t) => placeLabels.has(t) || !missing.includes(t)); if (kept.length !== state.filter.places.length) { state.filter.places = kept; writeUrl(); } renderRail(); } /** A company chip's text: what was picked, else the company list's name, else a row's, else the key, until one of those has come in. */ function companyLabel(key) { return companyNames.get(key) || companies.get(key)?.name || state.items.find((r) => r.company_key === key)?.company || key; } const here = () => location.pathname + location.search; /** `path` with a filter's query, the one on screen unless told. */ function addressFor(path, f = state.filter, q = state.q) { const p = feedParams(f, q); p.delete("order"); if (f.sort === "time") p.set("sort", "time"); const query = p.toString(); return path + (query ? `?${query}` : ""); } /** The filter into the address. `push` makes it an entry of its own, carrying the address it was pushed over (`from`); otherwise the entry is replaced and keeps its `from`. `list` takes the path to the list, for a filter, which shuts the reader; without it the path stays, for the agent and the order, which do not. False when nothing changed. */ function writeUrl({ push = false, list = false } = {}) { const url = addressFor(list ? pathFor(null) : location.pathname); const was = here(); if (url === was) return false; if (push) history.pushState({ from: was }, "", url); else history.replaceState(history.state, "", url); return true; } /** An address with the agent and the order taken out and the rest sorted: what two entries are compared on, since neither of those is a step. */ function filterPart(url) { const u = new URL(url, location.origin); u.searchParams.delete("agent"); u.searchParams.delete("sort"); u.searchParams.sort(); return u.pathname + u.search; } /** Whether the entry under this one is ours and shows `url`, so getting there is `history.back()` rather than one more entry on top. */ function underIs(url) { const from = history.state && history.state.from; return typeof from === "string" && filterPart(from) === filterPart(url); } /* Back or forward: the entry's filter into the rail and the feed, and its role into the reader. The agent and the order are the ones on screen, written into the entry landed on, so the entry says what is shown. */ function restore() { const before = addressFor(pathFor(null)); const muted = state.filter.showMuted; readUrl(location.search, { view: false }); $("#search").value = state.q; writeUrl(); route(); // An entry this page pushed holds only tokens it had names for, unless // the page was reloaded since; then the names are asked again. labelPlaces(); if (addressFor(pathFor(null)) === before) return; reload(); if (state.filter.showMuted !== muted) loadFilters().catch(() => {}); renderRail(); renderActive(); } // -------------------------------------------------------------- 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) { // An append failure leaves what is already on screen; a first load or // a reload has nothing to show, so the empty state offers a retry // rather than leaving the feed blank for good. if (!append && request === feedRequest) { state.feedError = true; state.loaded = false; renderFeed(); } return; } finally { if (request === feedRequest) state.loading = false; } if (request !== feedRequest) return; state.feedError = false; 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(); // A company chip read from the address may only now have a name, off // its rows; and a new list has new counts under the rail's filters. renderChips(); if (!append) loadFacets().catch(() => {}); // 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) .sort((a, b) => a.id - b.id); state.agentsLoaded = true; } function storedAgent() { try { return Number(localStorage.getItem(VIEWING)) || null; } catch (err) { return null; } } function rememberAgent(id) { try { if (id === null) localStorage.removeItem(VIEWING); else localStorage.setItem(VIEWING, String(id)); } catch (err) { /* private mode: the next visit opens on the default */ } } /** The agent to view as, among the enabled ones: the address's, else the one this browser viewed last, else the lowest id. An agent disabled or deleted since is passed over, not kept as a question nobody answers. */ function chooseAgent() { const ids = state.agents.map((a) => a.id); const wanted = [state.filter.agent, storedAgent()].find((id) => ids.includes(id)); state.filter.agent = wanted ?? (ids.length ? ids[0] : null); rememberAgent(state.filter.agent); writeUrl(); } /* Another persona over the same roles: its scores, votes and hidden companies, so the companies come first (they dim rows), then the feed and the tag counts. The reader stays, fetched again for this agent's vote; a filter closes it, an agent does not, since the role is still in question, only the eyes on it changed. */ async function setAgent(id) { if (id === state.filter.agent) return; state.filter.agent = id; rememberAgent(id); writeUrl(); renderRail(); renderActive(); await loadCompanies(id).catch(() => {}); reload(); loadFilters().catch(() => {}); if (state.readingUid) refreshReader(state.readingUid); } // The tag counts. Asked with `show_muted` and the agent only, the filters // 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"); if (state.filter.agent !== null) params.set("agent", String(state.filter.agent)); const request = ++filtersRequest; const data = await api(`/api/filters?${params}`); if (request !== filtersRequest) return; state.tags = data.tags || []; renderRail(); } // How many roles each seniority level and each pay state would bring, // under every other filter on screen (`Store.role_facets`). Asked after // each reload with the feed's parameters, the newest answer only. let facetsRequest = 0; async function loadFacets() { const request = ++facetsRequest; const data = await api(`/api/roles/facets?${feedParams()}`); if (request !== facetsRequest) return; state.facets = data; renderFacets(); } // ------------------------------------------------------------ the rail /* A filter is a question about the feed, and the role open over the old answer is the wrong thing to leave on screen, so the new list goes over it: pushed, so back takes the filter off and brings the role back, or replacing the entry for text being typed (`replace`). A filter that changes nothing only closes the reader. */ function setFilter(patch = {}, { counts = false, replace = false } = {}) { Object.assign(state.filter, patch); if (state.readingUid && addressFor(pathFor(null)) === pathFor(null) + location.search) { closeReader(); } else { writeUrl({ push: !replace, list: true }); route(); } reload(); if (counts) loadFilters().catch(() => {}); renderRail(); renderActive(); } // Who is viewing and in which order are not filters, so they stay. function clearFilters() { const kept = { agent: state.filter.agent, sort: state.filter.sort }; state.filter = Object.assign(blankFilter(), kept); // Text half typed into a chip field goes too, and with it its list. companyChips?.clear(); placeChips?.clear(); setFilter({}, { counts: true }); } /* The other order over the same filter: the entry is replaced, since an order is not a step back would undo, and an open role stays open, as it does for another agent, since the role in question has not changed. */ function setOrder(sort) { if (sort === state.filter.sort) return; state.filter.sort = sort; writeUrl(); renderRail(); renderActive(); reload(); } // 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({}, { replace: true }); } /** Where a company's name links: the list on screen, every filter and the search kept, with this company as its one company filter, in place of any company chips and of `?company=`. A company this agent hid turns on Show hidden companies, or its own name would lead to an empty list. */ function companyHref(key) { const f = Object.assign({}, state.filter, { companyKeys: [key], company: "" }); if (companies.get(key)?.affinity === -1) f.showMuted = true; return addressFor(pathFor(null), f); } /** A company's name, as a link to its roles when it has a key. */ function companyName(role) { if (!role.company_key) return `${esc(role.company)}`; return `${esc(role.company)}`; } /* A plain click lists the company's roles in place, the list its link leads to, and pushes, so back is the list it left; a modified or middle click is the browser's, and opens the link. The link is written again first: a row drawn before the last change of filter holds the address of the list it was drawn in. */ function companyClick(e) { if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || e.button !== 0) return; e.preventDefault(); const link = e.currentTarget; link.href = companyHref(link.dataset.company); companyNames.set(link.dataset.company, link.textContent.trim()); const counts = state.filter.showMuted; readUrl(new URL(link.href).search, { view: false }); $("#search").value = state.q; setFilter({}, { counts: counts !== state.filter.showMuted }); } /* The strip's way back to every company: back, when the entry under this one is the same list without the company, else that list pushed. */ function dropCompany() { const without = Object.assign({}, state.filter, { companyKeys: [] }); if (underIs(addressFor(pathFor(null), without))) history.back(); else setFilter({ companyKeys: [] }); } 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)); renderAgent(); // The order, the same two whatever is viewed. Best first needs an agent // to score by, so with none it is greyed and says why. const none = state.agentsLoaded && !state.agents.length; $("#sort").querySelectorAll("[data-sort]").forEach((b) => { b.setAttribute("aria-pressed", String(sortShown() === b.dataset.sort)); const off = b.dataset.sort === "score" && none; if (off) b.setAttribute("aria-disabled", "true"); else b.removeAttribute("aria-disabled"); b.title = off ? "No search agent is enabled, so nothing is scored." : ""; }); const ranked = sortShown() === "score"; $("#show-gated").hidden = !ranked; $("#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."; renderChips(); setValue("f-function", f.function); setValue("f-remote", f.remote); setValue("f-pay", f.pay); setValue("f-judged", f.judged); setValue("f-show-muted", f.showMuted); setValue("f-gated", f.gated); renderFacets(); const more = filtersOn(f, { more: true }); $("#f-active").textContent = more ? ` · ${more}` : ""; document.body.dataset.rail = state.railOpen ? "open" : "shut"; $("#rail-toggle").setAttribute("aria-expanded", String(state.railOpen)); } /* The chip inputs and the substring chips, from the filter: at load, on back and forward, and after Clear. A chip input is set only when its chips differ, since `set` draws them all again, and a pick has drawn its own already. */ function renderChips() { if (!companyChips) return; const f = state.filter; syncChips(companyChips, f.companyKeys.map((key) => ({ value: key, label: companyLabel(key) }))); syncChips(placeChips, f.places.map((t) => ({ value: t, label: placeLabels.get(t) || t }))); renderText("f-company-text", f.company.trim(), "Company", "company"); renderText("f-place-text", f.place.trim(), "Place", "place"); } function syncChips(input, want) { const have = input.values(); if (have.length === want.length && have.every((c, i) => c.value === want[i].value && c.label === want[i].label)) return; input.set(want); } /* `?company=` or `?place=`, the substring a link from another page brought: a plain chip saying what it matches, which takes it off and pushes, as a filter does. */ function renderText(id, text, noun, key) { const el = document.getElementById(id); el.hidden = !text; if (!text) { el.replaceChildren(); delete el.dataset.text; return; } if (el.dataset.text === text) return; el.dataset.text = text; el.innerHTML = ``; el.querySelector("button").onclick = () => setFilter({ [key]: "" }); } const levelLabel = (level) => level.charAt(0).toUpperCase() + level.slice(1); /* Which of the facet's pay states each Pay option keeps (`Store.PAY`), so the option's count is theirs added up: 'stated' in the facet is a line with no figure, the option "stated_only". */ const PAY_STATES = { "": ["normalised", "stated", ""], stated: ["normalised", "stated"], normalised: ["normalised"], stated_only: ["stated"], }; /* Seniority and Pay with their counts. The levels are the facet's, in the server's order; until it answers, the ones pressed, so a level read from the address can be taken off at once. Built again only when a level, a count or a press changed, so a pressed button keeps its focus. */ function renderFacets() { const f = state.filter; const facets = state.facets; const countOf = (list, value) => list?.find((x) => x.value === value)?.count; const shown = (n) => (n === undefined ? "" : number.format(n)); const levels = facets ? facets.seniority.map((x) => x.value).filter(Boolean) : []; for (const level of f.seniority) if (!levels.includes(level)) levels.push(level); const row = $("#f-seniority"); const counts = levels.map((level) => countOf(facets?.seniority, level)); const sig = JSON.stringify([levels, counts, f.seniority]); if (row.dataset.key !== sig) { row.dataset.key = sig; row.innerHTML = levels.map((level, i) => ` `).join(""); row.querySelectorAll("[data-level]").forEach((b) => { b.onclick = () => toggleLevel(b.dataset.level); }); } $("#f-seniority-unknown-row").hidden = !f.seniority.length; setValue("f-seniority-unknown", f.seniorityUnknown); $("#f-seniority-unknown-count").textContent = shown(countOf(facets?.seniority, "")); for (const option of $("#f-pay").options) { const states = PAY_STATES[option.value]; const n = facets && states ? states.reduce((sum, s) => sum + (countOf(facets.pay, s) || 0), 0) : undefined; const text = n === undefined ? option.dataset.label : `${option.dataset.label} (${shown(n)})`; if (option.textContent !== text) option.textContent = text; } $("#f-pay-unknown-row").hidden = !f.pay; setValue("f-pay-unknown", f.payUnknown); $("#f-pay-unknown-count").textContent = shown(countOf(facets?.pay, "")); } /* A level pressed or let go, pushed as a filter. The last one let go ticks "no level" again, which is how the box starts for the next. */ function toggleLevel(level) { const f = state.filter; const next = f.seniority.includes(level) ? f.seniority.filter((l) => l !== level) : [...f.seniority, level]; setFilter({ seniority: next, seniorityUnknown: next.length ? f.seniorityUnknown : true }); } /* Viewing as: a select of the enabled agents, also when there is one, and with none a sentence and the way to make one. Nothing until the agents are in, so a page with agents never says it has none. */ function renderAgent() { const agents = state.agents; const select = $("#agent"); select.hidden = !agents.length; $("#agent-none").hidden = !state.agentsLoaded || agents.length > 0; if (agents.length) { // Rebuilt only when the agents changed, since the rail is drawn again on // every filter and a rebuild shuts a select that is open. const key = agents.map((a) => `${a.id}:${a.name}`).join("\n"); if (select.dataset.key !== key) { select.dataset.key = key; select.replaceChildren(...agents.map((a) => new Option(a.name, String(a.id)))); } select.value = String(state.filter.agent); // A long name is cut at the rail's edge; the whole of it is a hover away. select.title = select.selectedOptions[0]?.text || ""; } else if (state.agentsLoaded) { $("#agent-none").innerHTML = `No search agent is enabled, so nothing is ranked. Search agents sets one up.`; } } /* 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 on = filtersOn(); 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(); } /* Built on the server (`app.models.excerpt`) and served as `role.excerpt`, so the list response never carries the full description a row would otherwise need to cut this from — see docs/decisions.md, "The pages". */ function excerpt(role) { return role.excerpt || ""; } /* The same cut, run here instead: for the one row `merge` refreshes after a fetch or a summarise, off the full role that call answers with, which is the only time this page ever sees a role's `summary` or `description` directly. */ function excerptOf(role) { const text = (role.summary || role.description || "").replace(/\s+/g, " ").trim(); if (text.length <= 200) return text; const cut = text.slice(0, 200); const space = cut.lastIndexOf(" "); return `${(space > 120 ? cut.slice(0, space) : cut).replace(/[\s,.;:–-]+$/, "")}…`; } function tagChips(tags) { return (tags || []).map((tag) => ` `).join(""); } /** The feed row's small pay badge: the range for 'normalised', "pay stated" for 'stated', nothing for '' — `role.salary_state`, computed by the API from `salary_min`/`salary_max`/`salary_text` (app/models.py). */ function payBadge(role) { if (role.salary_state === "normalised") return salary(role); if (role.salary_state === "stated") return "pay stated"; return ""; } /** Closed, pay, remote, function and seniority, as the row and the reader both show them. */ function badges(role) { const words = [role.remote, role.function, role.seniority].filter(Boolean); const pay = payBadge(role); return (role.closed_at ? `closed` : "") + (pay ? `${esc(pay)}` : "") + words.map((w) => `${esc(w)}`).join(""); } /* How many postings the row stands for, when a board or another host lists the same role more than once (`dupes`); the reader lists them. */ function dupes(role) { const n = (role.copies || 0) + 1; return n > 1 ? `×${n}` : ""; } /* The other postings of this role, each a link to where it is posted, labelled by host and place, as newsdesk's "Also covered by". */ function alsoPosted(r) { const copies = (Array.isArray(r.copies) ? r.copies : []) .filter((c) => safeUrl(c.original_url)); if (!copies.length) return ""; return `
${esc(text)}
` : ""}The server did not answer. .
`; const retry = empty.querySelector("[data-retry]"); if (retry) retry.onclick = () => loadFeed(); } else { const filtered = state.q || filtersOn(); empty.innerHTML = filtered ? `No open role fits these filters. and start again.
` : `Nothing has been pulled yet. Runs starts one; Job boards and Company boards 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.`; } /* With exactly one company filtered, which is where its name leads, a strip over the feed says whose roles these are and carries what is done with a company from here: its careers page, and its ★ ▲ ⊘ for the viewing agent, which is where a company is starred from. Built again only for another company or agent, since the feed is drawn on every page; the count and the affinity are patched. */ function renderStrip() { const el = $("#company-strip"); const key = state.filter.companyKeys.length === 1 ? state.filter.companyKeys[0] : null; el.hidden = key === null; if (key === null) { el.replaceChildren(); delete el.dataset.key; return; } const company = companies.get(key); const name = company?.name || state.items.find((r) => r.company_key === key)?.company || key; const careers = safeUrl(company?.careers_url); const affinity = company ? company.affinity : 0; const sig = JSON.stringify([key, name, careers, state.filter.agent]); if (el.dataset.key !== sig) { el.dataset.key = sig; el.innerHTML = `${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 carries what a row draws — // title, company, place, tags, pay — so the pane paints those at once; // the body, the summary state and the original link wait on the fetch // (`loaded`), since the list row no longer carries them (see // `Store.roles_page`). const stub = state.items.find((r) => r.uid === state.readingUid); const loaded = Boolean(state.reading) && state.reading.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)}
` : !loaded ? `Loading…
` : text ? paragraphs(text) : (r.teaser || "").trim() ? `${paragraphs(r.teaser.trim())}` : `The board gave no description for this one.
`; const pay = payDisplay(r); const careers = safeUrl(companies.get(r.company_key)?.careers_url); const waiting = state.summarising === state.readingUid; const teaser = loaded && !r.article_text && out && (r.description || "").length < TEASER; el.innerHTML = `A copy of a posting the feed lists once.
` : ""} ${pay ? `${esc(pay.range)}
${pay.detail ? `${esc(pay.detail)}
` : ""} ${pay.note ? `${esc(pay.note)}
` : ""}` : ""} ${r.summary ? `${esc(r.summary)}