roles.js already checked a role's original_url is http(s) before putting it in an href, so a board that wrote something other than a URL could not make the reader navigate to it; sources.js (a search sample's row.url), companies.js (careers_url) and applications.js (application.url) put the same kind of outside data straight into a link unchecked. safeUrl moves to app.js, beside the app's other shared helpers, and is exported the same way; a link whose safeUrl comes back empty is now left out of the page (plain text) instead of getting an href of "". Co-Authored-By: Claude Sonnet <noreply@anthropic.com>
1149 lines
48 KiB
JavaScript
1149 lines
48 KiB
JavaScript
/* 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 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, 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 Search agents 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, safeUrl, 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";
|
||
/** 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 },
|
||
};
|
||
|
||
// 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 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
|
||
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
|
||
feedError: false, // the feed's own fetch failed; the empty state offers a retry
|
||
};
|
||
|
||
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");
|
||
|
||
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));
|
||
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" };
|
||
|
||
/** 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";
|
||
// Checked against the enabled agents once they are in (`chooseAgent`).
|
||
if (q.get("agent")) 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("order");
|
||
if (state.filter.sort === "time") p.set("sort", "time");
|
||
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) {
|
||
// 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();
|
||
// 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();
|
||
}
|
||
|
||
// ------------------------------------------------------------ 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();
|
||
}
|
||
|
||
// 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);
|
||
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));
|
||
|
||
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) => `
|
||
<button type="button" class="tag" data-tag="${esc(t.tag)}"
|
||
aria-pressed="${f.tags.has(t.tag)}"
|
||
title="${esc(`${number.format(t.count)} roles, ${number.format(t.unread ?? t.count)} unread`)}"
|
||
>${esc(t.tag)}<span class="count">${number.format(t.unread ?? t.count)}</span></button>`).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 && 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));
|
||
}
|
||
|
||
/* Viewing as: a select with two or more agents, the name with 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 < 2;
|
||
$("#agent-one").hidden = agents.length !== 1;
|
||
$("#agent-none").hidden = !state.agentsLoaded || agents.length > 0;
|
||
if (agents.length > 1) {
|
||
// 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 (agents.length === 1) {
|
||
$("#agent-one").textContent = agents[0].name;
|
||
} else if (state.agentsLoaded) {
|
||
$("#agent-none").innerHTML = `No search agent is enabled, so nothing is ranked.
|
||
<a href="/settings/agents">Search agents</a> 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 f = state.filter;
|
||
const on = [!f.showRead, f.period !== "all", f.company.trim(), f.place.trim(),
|
||
f.function, f.remote, f.judged, f.showMuted, sortShown() === "score" && 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();
|
||
}
|
||
|
||
/* 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) => `
|
||
<button type="button" class="tag mini" data-tag="${esc(tag)}"
|
||
aria-pressed="${state.filter.tags.has(tag)}">${esc(tag)}</button>`).join("");
|
||
}
|
||
|
||
function badges(role, { seniority = false } = {}) {
|
||
const words = [role.remote, role.function, seniority ? role.seniority : ""].filter(Boolean);
|
||
return (role.closed_at ? `<span class="badge closed">closed</span>` : "")
|
||
+ words.map((w) => `<span class="badge">${esc(w)}</span>`).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 = `
|
||
<div class="gutter"><i style="height:${pct}%"></i></div>
|
||
<div class="score" title="How well it matches, of 100">${scored ? pct : ""}</div>
|
||
<div class="body">
|
||
<a class="headline" href="${esc(pathFor(role.uid))}">${esc(role.title || "(untitled)")}</a>
|
||
<div class="meta">
|
||
${role.company ? `<b>${esc(role.company)}</b>` : ""}
|
||
${role.place ? `<span>${esc(role.place)}</span>` : ""}
|
||
${badges(role)}
|
||
<span title="Posted">${ago(role.posted_at)}</span>
|
||
${role.gated_reason
|
||
? `<span class="gated" title="Kept out of the ranking">${esc(role.gated_reason)}</span>`
|
||
: ""}
|
||
${tagChips(role.tags)}
|
||
</div>
|
||
${text ? `<p class="excerpt">${esc(text)}</p>` : ""}
|
||
</div>
|
||
<div class="actions judge"></div>`;
|
||
el.querySelector(".actions").appendChild(
|
||
judgeButtons(role, () => paintRow(el, role), { agent: state.filter.agent }));
|
||
// Plain click reads it here; a modified or middle click still gets the
|
||
// real link, which is this same page with the role open.
|
||
el.querySelector(".headline").onclick = (e) => {
|
||
if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || e.button !== 0) return;
|
||
e.preventDefault();
|
||
openReader(role.uid);
|
||
};
|
||
// A tag on a role is also the fastest way to ask for more like it.
|
||
el.querySelectorAll(".tag").forEach((b) => { b.onclick = () => toggleTag(b.dataset.tag); });
|
||
}
|
||
|
||
/* A passed role and a hidden company's are dimmed, never dropped: the pass
|
||
has to stay visible to be undone. */
|
||
function paintRow(el, role) {
|
||
const company = companies.get(role.company_key);
|
||
el.dataset.read = String(Boolean(role.read_at));
|
||
el.classList.toggle("muted", Boolean(company && company.affinity === -1));
|
||
el.classList.toggle("passed", role.vote === -1);
|
||
el.classList.toggle("gated", Boolean(role.gated_reason));
|
||
}
|
||
|
||
function makeRow() {
|
||
const el = document.createElement("article");
|
||
el.className = "row";
|
||
return el;
|
||
}
|
||
|
||
function fillRow(el, { role, i }) {
|
||
if (el.role !== role) {
|
||
el.role = role;
|
||
drawRow(el, role);
|
||
}
|
||
el.dataset.uid = role.uid;
|
||
el.dataset.idx = String(i);
|
||
el.dataset.current = String(i === state.selected);
|
||
el.dataset.open = String(role.uid === state.readingUid);
|
||
paintRow(el, role);
|
||
el.querySelectorAll(".tag").forEach((b) => {
|
||
b.setAttribute("aria-pressed", String(state.filter.tags.has(b.dataset.tag)));
|
||
});
|
||
}
|
||
|
||
const rowAt = (i) => $(`#roles-list .row[data-idx="${i}"]`);
|
||
|
||
function renderFeed() {
|
||
// Which order the list is in, for the stylesheet: under Newest first the
|
||
// score gutter goes, since the score is not what put the row where it is.
|
||
$("#list").dataset.sort = sortShown();
|
||
sync($("#roles-list"), state.items.map((role, i) => [role.uid, { role, i }]), makeRow, fillRow);
|
||
|
||
const empty = $("#feed-empty");
|
||
empty.hidden = !((state.loaded || state.feedError) && !state.items.length);
|
||
if (!empty.hidden) {
|
||
if (state.feedError) {
|
||
empty.innerHTML = `<h2>Could not load the feed</h2>
|
||
<p>The server did not answer. <button type="button" class="linky" data-retry
|
||
>Try again</button>.</p>`;
|
||
const retry = empty.querySelector("[data-retry]");
|
||
if (retry) retry.onclick = () => loadFeed();
|
||
} else {
|
||
const f = state.filter;
|
||
const filtered = state.q || f.tags.size || f.period !== "all" || !f.showRead
|
||
|| f.company.trim() || f.place.trim() || f.function || f.remote || f.judged;
|
||
empty.innerHTML = filtered
|
||
? `<h2>Nothing matches</h2>
|
||
<p>No open role fits these filters.
|
||
<button type="button" class="linky" data-clear>Clear them</button> and start again.</p>`
|
||
: `<h2>No roles yet</h2>
|
||
<p>Nothing has been pulled yet. <a href="/settings/sources#runs">Runs</a> starts one;
|
||
<a href="/settings/sources#job-boards">Job boards</a> and
|
||
<a href="/settings/sources#company-boards">Company boards</a> decide what it brings in.</p>`;
|
||
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);
|
||
await refreshReader(uid);
|
||
}
|
||
|
||
/** One role as the viewing agent sees it, which is what its vote is. */
|
||
function roleUrl(uid) {
|
||
const agent = state.filter.agent;
|
||
return `/api/roles/${encodeURIComponent(uid)}${agent === null ? "" : `?agent=${agent}`}`;
|
||
}
|
||
|
||
// The fetch behind the reader: on opening, and again when the agent changes.
|
||
async function refreshReader(uid) {
|
||
try {
|
||
const role = await api(roleUrl(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) => `<p>${esc(p)}</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
|
||
? `<p class="reader-note">This role could not be loaded: ${esc(error)}</p>`
|
||
: !loaded
|
||
? `<p class="reader-note">Loading…</p>`
|
||
: text ? paragraphs(text)
|
||
: `<p class="reader-note">The board gave no description for this one.</p>`;
|
||
const pay = salary(r);
|
||
const waiting = state.summarising === state.readingUid;
|
||
const teaser = loaded && !r.article_text && out && (r.description || "").length < TEASER;
|
||
|
||
el.innerHTML = `
|
||
<div class="reader-bar">
|
||
<span class="judge"></span>
|
||
${out
|
||
? `<a class="reader-external" href="${esc(out)}" target="_blank" rel="noopener"
|
||
title="Open the posting (o)" aria-label="Open the posting">↗</a>`
|
||
: ""}
|
||
<button type="button" class="close" title="Close (esc)" aria-label="Close">✕</button>
|
||
</div>
|
||
<div class="reader-body">
|
||
<div class="reader-meta">
|
||
${r.company ? `<b>${esc(r.company)}</b>` : ""}
|
||
<span class="affinity-slot"></span>
|
||
${r.place ? `<span>${esc(r.place)}</span>` : ""}
|
||
${r.first_seen ? `<span title="First seen">${ago(r.first_seen)}</span>` : ""}
|
||
${badges(r, { seniority: true })}
|
||
${tagChips(r.tags)}
|
||
</div>
|
||
<h1>${esc(r.title || "")}</h1>
|
||
${pay ? `<p class="reader-salary">${esc(pay)}</p>` : ""}
|
||
${r.summary ? `<section class="reader-summary">
|
||
<h2 class="reader-label">Summary</h2><p>${esc(r.summary)}</p></section>` : ""}
|
||
<div class="reader-tools">
|
||
${loaded && !r.summary && !waiting
|
||
? `<button type="button" class="secondary" data-tool="summarise">Summarise</button>` : ""}
|
||
${teaser ? `<button type="button" class="secondary" data-tool="fetch">Fetch the posting</button>` : ""}
|
||
<span class="muted small" role="status">${waiting
|
||
? "The summary appears here when it is ready." : ""}</span>
|
||
</div>
|
||
<div class="prose">${body}</div>
|
||
${out ? `<p class="reader-out"><a href="${esc(out)}" target="_blank" rel="noopener"
|
||
>Read it on ${esc(host(out) || "the board")} ↗</a></p>` : ""}
|
||
</div>
|
||
<div class="reader-foot">
|
||
<button type="button" class="step-prev" ${state.selected <= 0 ? "disabled" : ""}>← Previous</button>
|
||
<button type="button" class="step-next" ${
|
||
state.selected >= state.items.length - 1 ? "disabled" : ""}>Next →</button>
|
||
</div>`;
|
||
|
||
if (r.uid) {
|
||
el.querySelector(".judge").appendChild(judgeButtons(r, null, { agent: state.filter.agent }));
|
||
}
|
||
renderAffinity(el.querySelector(".affinity-slot"), r);
|
||
el.querySelector(".close").onclick = () => closeReader();
|
||
el.querySelector(".step-prev").onclick = () => move(-1);
|
||
el.querySelector(".step-next").onclick = () => move(1);
|
||
el.querySelectorAll(".tag").forEach((b) => { b.onclick = () => toggleTag(b.dataset.tag); });
|
||
el.querySelector('[data-tool="summarise"]')?.addEventListener("click",
|
||
(e) => summarise(e.currentTarget));
|
||
el.querySelector('[data-tool="fetch"]')?.addEventListener("click",
|
||
(e) => fetchText(e.currentTarget));
|
||
el.querySelector(".reader-out a")?.addEventListener("click", () => markRead(r.uid));
|
||
el.querySelector(".reader-body").scrollTop = scrolled;
|
||
}
|
||
|
||
/* The company's ★ ▲ ⊘, the one place a company is judged outside the
|
||
Companies page. A company seen only through a search has no row of its
|
||
own to judge. A change dims or undims its rows in the feed. */
|
||
function renderAffinity(slot, r) {
|
||
const company = companies.get(r.company_key);
|
||
if (!company) { slot.replaceChildren(); return; }
|
||
slot.replaceChildren(affinityControl(r.company_key, company.affinity, () => {
|
||
renderAffinity(slot, r);
|
||
renderFeed();
|
||
}, state.filter.agent));
|
||
}
|
||
|
||
/* The answer, into the role on screen and into its row, whose excerpt is
|
||
the summary once there is one. */
|
||
function merge(updated) {
|
||
if (!updated || updated.uid !== state.readingUid) return;
|
||
if (state.reading) Object.assign(state.reading, updated);
|
||
else state.reading = updated;
|
||
const item = state.items.find((x) => x.uid === updated.uid);
|
||
if (item) {
|
||
item.excerpt = excerptOf(updated);
|
||
const row = $(`#roles-list .row[data-uid="${CSS.escape(updated.uid)}"]`);
|
||
if (row) row.role = null; // drawn again from the new excerpt
|
||
renderFeed();
|
||
}
|
||
renderReader();
|
||
}
|
||
|
||
async function busy(button, label, work) {
|
||
const was = button.textContent;
|
||
button.disabled = true;
|
||
button.textContent = label;
|
||
try {
|
||
return await work();
|
||
} catch (err) {
|
||
return null; // toasted by api()
|
||
} finally {
|
||
button.disabled = false;
|
||
button.textContent = was;
|
||
}
|
||
}
|
||
|
||
/* A search role's description is a teaser of a couple of hundred
|
||
characters; this fetches the posting once and keeps it. */
|
||
async function fetchText(button) {
|
||
const uid = state.readingUid;
|
||
const role = await busy(button, "Fetching…",
|
||
() => api(`/api/roles/${encodeURIComponent(uid)}/text`, { method: "POST" }));
|
||
if (role) merge(role);
|
||
}
|
||
|
||
/* Queued rather than done at once: ask for the role again until the
|
||
summary is there, for two minutes, and stop as soon as the reader is on
|
||
another role. */
|
||
async function summarise(button) {
|
||
const uid = state.readingUid;
|
||
const job = await busy(button, "Summarising…",
|
||
() => api(`/api/roles/${encodeURIComponent(uid)}/summarise`, { method: "POST" }));
|
||
if (!job || state.readingUid !== uid) return;
|
||
state.summarising = uid;
|
||
renderReader();
|
||
for (let i = 0; i < 30 && state.summarising === uid; i++) {
|
||
await new Promise((resolve) => setTimeout(resolve, 4000));
|
||
if (state.summarising !== uid) return;
|
||
let fresh;
|
||
try { fresh = await api(roleUrl(uid)); } catch (err) { break; }
|
||
if (fresh.summary) { state.summarising = null; merge(fresh); return; }
|
||
}
|
||
if (state.summarising === uid) {
|
||
state.summarising = null;
|
||
renderReader();
|
||
}
|
||
}
|
||
|
||
// ------------------------------------------------------------ the keys
|
||
|
||
function move(delta) {
|
||
if (!state.items.length) return;
|
||
state.selected = Math.max(0, Math.min(state.items.length - 1, state.selected + delta));
|
||
renderFeed();
|
||
rowAt(state.selected)?.scrollIntoView({ block: "nearest" });
|
||
// With the reader open, j/k walks the list and the reader follows.
|
||
if (state.readingUid) openReader(state.items[state.selected].uid);
|
||
}
|
||
|
||
/** Press one of judge.js's buttons for the role in hand: the reader's when
|
||
it is open, else the selected row's. One control, whichever way in. */
|
||
function judge(cls) {
|
||
const box = state.readingUid
|
||
? $("#reader .reader-bar .judge")
|
||
: rowAt(state.selected)?.querySelector(".actions");
|
||
box?.querySelector(`.${cls}`)?.click();
|
||
}
|
||
|
||
function openOriginal() {
|
||
const uid = state.readingUid || state.items[state.selected]?.uid;
|
||
const role = state.reading?.uid === uid ? state.reading
|
||
: state.items.find((r) => r.uid === uid);
|
||
const url = safeUrl(role?.original_url);
|
||
if (!url) return;
|
||
window.open(url, "_blank", "noopener");
|
||
markRead(uid);
|
||
}
|
||
|
||
document.addEventListener("keydown", (e) => {
|
||
// Every shortcut is a bare keypress, so a chord belongs to the browser:
|
||
// ctrl+C must copy, not clear the filters. Shift is not in the list,
|
||
// since S arrives with it held.
|
||
if (e.ctrlKey || e.metaKey || e.altKey) return;
|
||
const tag = e.target.tagName;
|
||
if (tag === "INPUT" || tag === "TEXTAREA" || e.target.isContentEditable) {
|
||
if (e.key === "Escape") {
|
||
if (e.target.id === "search") { e.target.value = ""; setSearch(""); }
|
||
e.target.blur();
|
||
}
|
||
return;
|
||
}
|
||
// A focused select takes letters as type-ahead.
|
||
if (tag === "SELECT") return;
|
||
// Enter on a focused button or link is that control's.
|
||
if (e.key === "Enter" && e.target.closest("button, a, summary")) return;
|
||
const current = state.items[state.selected];
|
||
const map = {
|
||
j: () => move(1),
|
||
k: () => move(-1),
|
||
u: () => judge("up"),
|
||
n: () => judge("mid"),
|
||
d: () => judge("down"),
|
||
S: () => judge("star"),
|
||
Enter: () => (state.readingUid ? closeReader() : current && openReader(current.uid)),
|
||
Escape: () => {
|
||
if (overlayRail() && state.railOpen) toggleRail();
|
||
else if (state.readingUid) closeReader();
|
||
},
|
||
o: openOriginal,
|
||
"/": () => $("#search").focus(),
|
||
f: toggleRail,
|
||
c: clearFilters,
|
||
};
|
||
if (map[e.key]) { e.preventDefault(); map[e.key](); }
|
||
});
|
||
|
||
// ---------------------------------------------------------- the router
|
||
|
||
// / the feed
|
||
// /roles/<uid> a role, open over the feed
|
||
//
|
||
// The query string is the filter's and rides along unchanged.
|
||
function parseRoute(path) {
|
||
const role = path.match(/^\/roles\/([^/]+)$/);
|
||
return { uid: role ? decodeURIComponent(role[1]) : null };
|
||
}
|
||
|
||
function pathFor(uid) {
|
||
return uid ? `/roles/${encodeURIComponent(uid)}` : "/";
|
||
}
|
||
|
||
function navigate(path, { replace = false } = {}) {
|
||
if (path !== location.pathname) {
|
||
history[replace ? "replaceState" : "pushState"](null, "", path + location.search);
|
||
}
|
||
route();
|
||
}
|
||
|
||
// Make the screen match the path. Called on every navigation and on the
|
||
// back and forward buttons; stepping from one role to the next does not
|
||
// reload the list under it.
|
||
function route() {
|
||
const to = parseRoute(location.pathname);
|
||
if (to.uid) {
|
||
if (to.uid !== state.readingUid) showReader(to.uid);
|
||
} else if (state.readingUid) {
|
||
shutReader();
|
||
}
|
||
}
|
||
|
||
// The system back gesture, which on a phone is the reflex Escape is here.
|
||
window.addEventListener("popstate", route);
|
||
|
||
// ------------------------------------------------ back from another page
|
||
|
||
function keep() {
|
||
try {
|
||
sessionStorage.setItem(KEPT, JSON.stringify({
|
||
url: location.pathname + location.search, count: state.items.length,
|
||
y: window.scrollY, rail: state.railOpen,
|
||
}));
|
||
} catch (err) { /* private mode: back is a fresh list, which is fine */ }
|
||
}
|
||
|
||
function kept() {
|
||
const [entry] = performance.getEntriesByType("navigation");
|
||
if (!entry || !["back_forward", "reload"].includes(entry.type)) return null;
|
||
try {
|
||
const was = JSON.parse(sessionStorage.getItem(KEPT) || "null");
|
||
return was && was.url === location.pathname + location.search ? was : null;
|
||
} catch (err) {
|
||
return null;
|
||
}
|
||
}
|
||
|
||
// The header's height, for everything pinned under it: the rail, the
|
||
// reader, the scrim. It is not a constant (44px touch targets make the
|
||
// header taller), and everything pinned to a stale number slides under it.
|
||
function measureChrome() {
|
||
const header = $("header.top");
|
||
document.documentElement.style.setProperty("--chrome", `${header.offsetHeight}px`);
|
||
}
|
||
|
||
function wire() {
|
||
$("#rail-toggle").addEventListener("click", toggleRail);
|
||
$("#scrim").addEventListener("click", toggleRail);
|
||
$("#show-read").addEventListener("click", () => setFilter({ showRead: !state.filter.showRead }));
|
||
$("#agent").addEventListener("change", (e) => setAgent(Number(e.target.value)));
|
||
$("#sort").innerHTML = Object.entries(SORTS).map(([key, label]) =>
|
||
`<button type="button" data-sort="${key}">${label}</button>`).join("");
|
||
$("#sort").querySelectorAll("[data-sort]").forEach((b) => {
|
||
b.onclick = () => {
|
||
if (b.getAttribute("aria-disabled") === "true") return;
|
||
setFilter({ sort: b.dataset.sort });
|
||
};
|
||
});
|
||
$("#period").innerHTML = Object.entries(PERIODS).map(([key, p]) =>
|
||
`<option value="${key}">${esc(p.label)}</option>`).join("");
|
||
$("#period").addEventListener("change", (e) => setFilter({ period: e.target.value }));
|
||
$("#clear-tags").addEventListener("click", () => { state.filter.tags.clear(); setFilter({}); });
|
||
|
||
const typed = debounce(() => setFilter({}), 300);
|
||
for (const key of ["company", "place"]) {
|
||
$(`#f-${key}`).addEventListener("input", (e) => { state.filter[key] = e.target.value; typed(); });
|
||
}
|
||
for (const key of ["function", "remote", "judged"]) {
|
||
$(`#f-${key}`).addEventListener("change", (e) => setFilter({ [key]: e.target.value }));
|
||
}
|
||
$("#f-show-muted").addEventListener("change",
|
||
(e) => setFilter({ showMuted: e.target.checked }, { counts: true }));
|
||
$("#f-gated").addEventListener("change", (e) => setFilter({ gated: e.target.checked }));
|
||
|
||
const searched = debounce((value) => setSearch(value.trim()), 250);
|
||
$("#search").addEventListener("input", (e) => searched(e.target.value));
|
||
$("#search").value = state.q;
|
||
|
||
// The rail follows the layout: beside the feed when there is room, put
|
||
// away when it would be an overlay.
|
||
narrow.addEventListener("change", () => {
|
||
state.railOpen = !narrow.matches;
|
||
state.railAutoShut = false;
|
||
renderRail();
|
||
});
|
||
|
||
measureChrome();
|
||
new ResizeObserver(measureChrome).observe($("header.top"));
|
||
|
||
new IntersectionObserver((entries) => {
|
||
if (entries.some((e) => e.isIntersecting)) loadFeed({ append: true });
|
||
}, { rootMargin: "600px" }).observe($("#feed-end"));
|
||
|
||
// Kept on the way out, whichever way that is, so back finds it.
|
||
window.addEventListener("pagehide", keep);
|
||
// Back from another tab without a reload (the back/forward cache): the
|
||
// rows are the ones left, but a vote, a star or an agent may have changed
|
||
// there.
|
||
window.addEventListener("pageshow", async (e) => {
|
||
if (!e.persisted) return;
|
||
const y = window.scrollY;
|
||
await loadAgents().then(chooseAgent).catch(() => {});
|
||
renderRail();
|
||
await Promise.all([loadTracked(), loadCompanies(state.filter.agent)]).catch(() => {});
|
||
await loadFeed({ keep: state.items.length });
|
||
if (state.readingUid) renderReader();
|
||
window.scrollTo(0, y);
|
||
});
|
||
}
|
||
|
||
document.addEventListener("DOMContentLoaded", async () => {
|
||
readUrl();
|
||
const was = kept();
|
||
if (was && !narrow.matches) state.railOpen = was.rail;
|
||
wire();
|
||
renderRail();
|
||
renderActive();
|
||
|
||
// The feed is the page; agents and companies are enhancements that fill
|
||
// in when they arrive, not something it waits on — a slow or failed
|
||
// /api/agents or /api/companies must not leave it blank. Each one drawn
|
||
// here is greyed or missing until `enhance` lands, which is what "no
|
||
// agent" (renderAgent), an unjoined company (paintRow) and the tag row
|
||
// being empty already mean, so nothing here is a new state to handle.
|
||
const before = state.filter.agent;
|
||
const enhance = (async () => {
|
||
try {
|
||
await Promise.all([loadTracked(), loadAgents()]);
|
||
chooseAgent();
|
||
await loadCompanies(state.filter.agent);
|
||
} catch (err) {
|
||
return;
|
||
}
|
||
renderRail();
|
||
renderActive();
|
||
loadFilters().catch(() => {});
|
||
// The feed's first request went out with whatever agent `readUrl` had
|
||
// (often none): reload for the score and votes once the real one is
|
||
// known, and either way bring the reader's affinity control and judge
|
||
// buttons up to date, since `companies` was still empty when it first
|
||
// painted.
|
||
if (state.filter.agent !== before) reload();
|
||
else renderFeed();
|
||
if (state.readingUid) {
|
||
if (state.filter.agent !== before) refreshReader(state.readingUid);
|
||
else renderReader();
|
||
}
|
||
})();
|
||
|
||
route();
|
||
await loadFeed({ keep: was ? was.count : 0 });
|
||
if (was && !state.readingUid) window.scrollTo(0, was.y || 0);
|
||
await enhance;
|
||
});
|
||
})();
|