Files
jobboard/app/static/roles.js
T

2347 lines
104 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* 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, since the score is not what put the row there, and the CV
* match under What fits me, a dash for a role not judged yet), the title,
* company · place · badges · age · tags, the summary or the description's
* opening, and ▼ ● ▲ ★ from judge.js. A passed role is dimmed, never
* dropped, so a stray tap stays visible to be undone. A hidden company's roles
* are never in the feed.
*
* 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.
* The feed's first request carries the first two before the agents are in,
* and waits for them when there is neither, since the server gates nothing
* for a request that names no agent (`start`).
* 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 What I'm looking for (`order=score`, the agent's want feed score
* moved by its votes), Newest (`order=newest`) or What fits me (`order=cv`,
* the roles the agent's `judge` read against its CV first, by that total),
* the same three whichever agent is viewed, and all carry the agent's votes.
* What fits me needs a CV: an agent without one is shown What I'm looking
* for, as an agentless page is shown Newest. Every order keeps to the
* roles the agent's fetch gate passes, which a note under Viewing as says,
* and for a phone, whose rail is shut, the end of the list and the empty
* state; Show gated (`gated=true`) adds the ones it rejects, with the
* reason. The reader says when the gate rejects the role open.
*
* Saved filters belong to the viewing agent (`/api/agents/{id}/filters`):
* pills in the rail, newsdesk's `#active` row, each the query string
* `addressFor` writes without the agent. A click reads it into the filter
* as a company link is read (`readUrl`) and pushes; × deletes it; Save
* names the filters on screen in a field of its own. No editing: a change
* is saved under a new name.
*
* 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 bound or track, 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_keys=` and `?agent=`
* are how Settings › Sources and Search agents 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 older links and saved filters, still filter and show as a
* chip of their own to take off; nothing in the rail types a new one. Seniority
* (a From and a To rung and a Track, `level_from`, `level_to` and `track`)
* 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
* rungs and which level is on which come from the page (`ROLEDESK_LADDER`),
* an old `?seniority=` is ignored.
*
* The list is paged: 60 rows, then 60 more each time the end of the list comes
* within 600px of the screen. The server sorts afresh on every request and a
* vote or a read moves a role in its list or out of it, so the next page
* starts a row earlier for each and a row already on screen is dropped
* (`pageAsk`, `pageMerge`): none is skipped and none is shown twice. 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, overridesControl,
judgeButtons, loadTracked, chipInput, remoteHelpers } = 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");
// The seniority ladder from the page: `rungs` in order and, for each level
// word, its rung (an index into them) and track (`app.models.LADDER`).
const LADDER = window.ROLEDESK_LADDER;
// What each rung is called on each side of the ladder, [individual, people].
// The rungs below Staff have no side and are named as they are.
const RUNG_SIDES = {
staff: ["Staff", "Manager"], principal: ["Principal", "Senior Manager"],
distinguished: ["Distinguished", "Director"],
};
const TRACKS = { "": "Both", ic: "Individual", people: "People" };
// What the list is in the order of. What I'm looking for is the viewing
// agent's want feed score, moved by its votes; Newest is the posting date;
// What fits me is the agent's `judge` total, the roles not judged after by
// CV closeness.
const SORTS = { score: "What I\u2019m looking for", cv: "What fits me", time: "Newest" };
// The route's `order` for each.
const ORDERS = { score: "score", time: "newest", cv: "cv" };
// How many days ahead a deadline earns a badge: today to today + 4, the
// window of `closing=1` (Closing soon).
const CLOSING_DAYS = 4;
// 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, a `remote:` token remote roles (`remote:any` within the viewing
// agent's scope, `remote:country:DK` those a person there can take), its
// count the roles it would find (`places.suggest`).
const PLACE_KINDS = { country: "country", region: "region", place: "town", remote: "remote" };
// 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 older links and saved filters; `companyKeys` and `places`
// are the rail's chips. `levelFrom`, `levelTo` and `track` are the seniority
// range; `seniorityUnknown` and `payUnknown` are the "and roles with no
// level / no pay" boxes, asked only while a range, a track 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: "",
gated: false, companyKeys: [], places: [],
levelFrom: "", levelTo: "", track: "", seniorityUnknown: true, payUnknown: false,
closing: false,
};
}
/** How many filters are on, for the burger; `more` counts only the ones
under "More filters", for its summary. A chip, a bound or the track 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.closing, f.agent !== null && f.gated].filter(Boolean).length
+ f.companyKeys.length + f.places.length
+ [f.levelFrom, f.levelTo, f.track].filter(Boolean).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
offset: 0, // how far into the server's list the pages have read
more: false, // the server's list goes on past `offset`
moved: 0, // votes and reads no page has been asked after yet (`pageAsk`)
movedOnce: 0, // those one page has been asked after
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
saved: [], // the viewing agent's saved filters, [{id, name, query}] by name
};
// 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 viewing agent, once the agents are in. */
const viewed = () => state.agents.find((a) => a.id === state.filter.agent) || null;
/** Whether What fits me has a CV to go by: the viewed agent has one, or
the agents are not in yet, when the address is taken at its word. */
const hasCv = () => !state.agentsLoaded || Boolean(viewed()?.cv_text?.trim());
/** The order the list is in. What I'm looking for needs an agent to score
by: with none enabled the server answers newest first, and so does this.
What fits me needs that agent's CV too, and without one is What I'm
looking for. */
function sortShown() {
const { sort, agent } = state.filter;
if (sort === "time" || agent === null) return "time";
return sort === "cv" && hasCv() ? "cv" : "score";
}
/** Whether a bound or a track is set, which is what "no level" asks about. */
const seniorityOn = (f = state.filter) => Boolean(f.levelFrom || f.levelTo || f.track);
/** 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.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));
for (const [param, key] of [["level_from", "levelFrom"], ["level_to", "levelTo"], ["track", "track"]]) {
if (f[key]) p.set(param, f[key]);
}
// Each box is sent only off its default, and only while its filter is on.
if (seniorityOn(f) && !f.seniorityUnknown) p.set("seniority_unknown", "false");
if (f.pay && f.payUnknown) p.set("pay_unknown", "true");
if (f.closing) p.set("closing", "1");
if (f.agent !== null) {
p.set("agent", String(f.agent));
p.set("order", ORDERS[sortShown()]);
// Every order keeps to the fetch gate, so each can show what it rejects.
if (f.gated) 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.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))];
// A name the ladder does not know is dropped, rather than sent for a 422.
f.levelFrom = LADDER.rungs.includes(q.get("level_from")) ? q.get("level_from") : "";
f.levelTo = LADDER.rungs.includes(q.get("level_to")) ? q.get("level_to") : "";
f.track = q.get("track") in TRACKS ? q.get("track") : "";
f.seniorityUnknown = q.get("seniority_unknown") !== "false";
f.payUnknown = q.get("pay_unknown") === "true";
f.closing = q.get("closing") === "1" || q.get("closing") === "true";
if (!view) return;
if (q.get("sort") === "time" || q.get("sort") === "cv") f.sort = q.get("sort");
// 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, unless `write` is false, the address, rather than sent to
/api/roles for a 422. Nothing is asked when every token already has
its text. */
async function labelPlaces({ write = true } = {}) {
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;
if (write) 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 !== "score") p.set("sort", f.sort);
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));
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();
renderRail();
renderActive();
}
// -------------------------------------------------------------- loading
/** The most rows one request may ask for (`limit` on /api/roles). */
const MOST = 1000;
/* Where the next page starts and how many rows it asks for. The server
sorts afresh on every request, and a vote moves a role in its order
(`_VOTED_SCORE`) or out of the list (Judged), as a read does with Show
read off. Each row that leaves the part already read lets a row from
below up into it, which a page asked from `offset` would never show, so
the page starts one row earlier for each such change and is that much
longer; the rows it repeats are dropped (`pageMerge`). `moved` holds
each change for two pages, the one asked after it and the next
(`state.moved` and `state.movedOnce`), since a vote still in flight
when a page is asked may land after the server has read that page. */
function pageAsk(offset, moved, page = PAGE) {
const back = Math.min(offset, moved, MOST - page);
return { offset: offset - back, limit: page + back };
}
/* An answer onto the rows on screen: the rows not on screen yet after
them, in the server's order, so the role a pass sank is not shown a
second time; how far into the server's list the pages have now read;
and whether it goes on. A short page is its end whatever `total` says,
since the count and the page are two queries. */
function pageMerge(items, ask, answer) {
const shown = new Set(items.map((r) => r.uid));
const offset = ask.offset + answer.items.length;
return {
items: items.concat(answer.items.filter((r) => !shown.has(r.uid))),
offset,
more: answer.items.length >= ask.limit && offset < answer.total,
};
}
// For the tests, which page through a list sorted afresh without a DOM.
window.feedPaging = { pageAsk, pageMerge };
let feedRequest = 0;
/* The feed has nothing to show, so the empty state offers a retry rather
than leaving the feed blank for good. */
function feedFailed() {
state.feedError = true;
state.loaded = false;
renderFeed();
}
/* A reload starts the list again; an append asks for the rows after the
ones read (`pageAsk`). `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.
Nothing is asked while no agent is named and the agents have not said
whether there is one, since the server would list every open role,
ungated (`start`); the empty state offers the retry instead. */
async function loadFeed({ append = false, keep = 0 } = {}) {
if (state.filter.agent === null && !state.agentsLoaded) {
if (!append) feedFailed();
return;
}
if (append && (state.loading || !state.more)) return;
const ask = append ? pageAsk(state.offset, state.moved + state.movedOnce)
: { offset: 0, limit: Math.min(MOST, Math.max(PAGE, keep)) };
const params = feedParams();
params.set("offset", String(ask.offset));
params.set("limit", String(ask.limit));
const moved = state.moved;
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 (`feedFailed`).
if (!append && request === feedRequest) feedFailed();
return;
} finally {
if (request === feedRequest) state.loading = false;
}
if (request !== feedRequest) return;
state.feedError = false;
// The changes made before this page was asked are counted once more, for
// the next; those made while it was in flight wait for theirs.
state.movedOnce = moved;
state.moved -= moved;
const held = append ? state.items[state.selected]?.uid : state.readingUid;
const page = pageMerge(append ? state.items : [], ask, data);
state.total = data.total;
state.items = page.items;
state.offset = page.offset;
state.more = page.more;
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();
agentSaved();
await loadCompanies(id).catch(() => {});
reload();
loadFilters().catch(() => {});
if (state.readingUid) refreshReader(state.readingUid);
}
// The tag counts. Asked with the agent only, the 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.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 = {}, { 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();
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();
}
/* 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=`. */
function companyHref(key) {
const f = Object.assign({}, state.filter, { companyKeys: [key], company: "" });
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 `<b>${esc(role.company)}</b>`;
return `<a class="company" href="${esc(companyHref(role.company_key))}"
data-company="${esc(role.company_key)}" title="Only ${esc(role.company)}'s roles"
>${esc(role.company)}</a>`;
}
/* Who is viewing changed: its saved filters in, the last agent's field and
message gone. */
function agentSaved() {
closeSaveForm();
loadSaved().catch(() => {});
}
/* 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());
readUrl(new URL(link.href).search, { view: false });
$("#search").value = state.q;
setFilter();
}
/* 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 three whatever is viewed. What I'm looking for needs
// an agent to score by, and What fits me that agent's CV, so without one
// each is greyed and says why.
const none = state.agentsLoaded && !state.agents.length;
const why = {
score: none ? "No search agent is enabled, so nothing is scored." : "",
cv: none ? "No search agent is enabled, so nothing is judged."
: !hasCv() ? "This agent has no CV, so nothing is judged against one. Search agents sets it."
: "",
};
$("#sort").querySelectorAll("[data-sort]").forEach((b) => {
b.setAttribute("aria-pressed", String(sortShown() === b.dataset.sort));
const off = Boolean(why[b.dataset.sort]);
if (off) b.setAttribute("aria-disabled", "true");
else b.removeAttribute("aria-disabled");
b.title = why[b.dataset.sort] || "";
});
$("#show-gated").hidden = f.agent === 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) => `
<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.";
renderChips();
setValue("f-function", f.function);
setValue("f-remote", f.remote);
setValue("f-pay", f.pay);
setValue("f-judged", f.judged);
setValue("f-closing", f.closing);
setValue("f-gated", f.gated);
renderFacets();
renderSaved();
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 an older link or saved filter
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 = `<button type="button" class="tag" title="Take this filter off"
aria-label="Remove the filter ${esc(noun)} contains ${esc(text)}"
>${esc(noun)} contains “${esc(text)}”<span class="chip-x" aria-hidden="true">×</span></button>`;
el.querySelector("button").onclick = () => setFilter({ [key]: "" });
}
/* 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"],
};
/* A rung's name on the track chosen: with both, the two sides together. */
function rungLabel(rung, track) {
const sides = RUNG_SIDES[rung];
if (!sides) return rung.charAt(0).toUpperCase() + rung.slice(1);
return track === "ic" ? sides[0] : track === "people" ? sides[1] : sides.join(" / ");
}
/* How many roles a rung holds on the track chosen, the facet's per-level
counts added up: a level with no track counts on either. Undefined
until the facet answers. */
function rungCount(facets, rung, track) {
if (!facets) return undefined;
const at = LADDER.rungs.indexOf(rung);
return facets.seniority.reduce((sum, x) => {
const place = LADDER.levels[x.value];
return place && place[0] === at && (!track || !place[1] || place[1] === track)
? sum + x.count : sum;
}, 0);
}
/* Seniority and Pay with their counts. The rungs of both selects are the
ladder's, worded for the track; the option is set only when its text
changed, since the rail is drawn again on every filter and rewriting an
open select shuts it. */
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));
for (const [id, key] of [["f-level-from", "levelFrom"], ["f-level-to", "levelTo"]]) {
const select = document.getElementById(id);
LADDER.rungs.forEach((rung, i) => {
const n = rungCount(facets, rung, f.track);
const text = rungLabel(rung, f.track) + (n === undefined ? "" : ` · ${shown(n)}`);
const option = select.options[i + 1];
if (option.textContent !== text) option.textContent = text;
});
setValue(id, f[key]);
}
$("#f-track").querySelectorAll("[data-track]").forEach((b) => {
b.setAttribute("aria-pressed", String(f.track === b.dataset.track));
});
$("#f-seniority-unknown-row").hidden = !seniorityOn(f);
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 bound or the track set, pushed as a filter. The last one taken off
ticks "no level" again, which is how the box starts for the next. */
function setSeniority(patch) {
const next = { ...state.filter, ...patch };
setFilter({ ...patch, seniorityUnknown: seniorityOn(next) ? next.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;
// Every order keeps to the agent's fetch gate; Show gated says it widened.
const gate = $("#agent-gate");
gate.hidden = state.filter.agent === null;
gate.textContent = state.filter.gated
? "Filtered by this agent's fetch gate, and Show gated adds the roles it rejects."
: "Already filtered by this agent's fetch gate: world, location and role exclusion. Hidden companies are never shown.";
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.
<a href="/settings/agents">Search agents</a> sets one up.`;
}
}
// ------------------------------------------------------- saved filters
/** The filter on screen as a saved filter's query: the query string
`addressFor` writes, without the agent (`POST /api/agents/{id}/filters`). */
function savedQuery(f = state.filter, q = state.q) {
const p = new URLSearchParams(addressFor("", f, q).replace(/^\?/, ""));
p.delete("agent");
return p.toString();
}
/** Whether two queries say the same, whatever the order of their parts. */
function sameQuery(a, b) {
const sorted = (query) => {
const p = new URLSearchParams(query);
p.sort();
return p.toString();
};
return sorted(a) === sorted(b);
}
// The viewing agent's saved filters, the newest answer only; none without
// an agent, when the section is hidden.
let savedRequest = 0;
async function loadSaved() {
const agent = state.filter.agent;
const request = ++savedRequest;
let rows = [];
if (agent !== null) {
try {
rows = await api(`/api/agents/${agent}/filters`);
} catch (err) {
rows = []; // toasted; the section says none is saved
}
}
if (request !== savedRequest) return;
state.saved = rows;
renderSaved();
}
/* The pills, rebuilt only when the list changed, since the rail is drawn
on every filter and a rebuild drops the focus of the pill just pressed.
The pill whose query is the filter on screen is pressed. */
function renderSaved() {
const section = $("#saved");
section.hidden = state.filter.agent === null;
if (section.hidden) return;
const list = $("#saved-list");
const key = JSON.stringify([state.filter.agent, state.saved.map((x) => [x.id, x.name])]);
if (list.dataset.key !== key) {
list.dataset.key = key;
list.innerHTML = state.saved.length
? state.saved.map((x) => `<span class="saved">`
+ `<button type="button" class="pill" data-apply="${x.id}" title="Apply “${esc(x.name)}”"
>${esc(x.name)}</button>`
+ `<button type="button" class="pill-x" data-delete="${x.id}" title="Delete “${esc(x.name)}”"
aria-label="Delete the saved filter ${esc(x.name)}">×</button></span>`).join("")
: `<p class="rail-note">None saved for this agent yet.</p>`;
list.querySelectorAll("[data-apply]").forEach((b) => {
b.onclick = () => applySaved(Number(b.dataset.apply));
});
list.querySelectorAll("[data-delete]").forEach((b) => {
b.onclick = () => deleteSaved(Number(b.dataset.delete));
});
}
const current = savedQuery();
list.querySelectorAll("[data-apply]").forEach((b) => {
const x = state.saved.find((y) => y.id === Number(b.dataset.apply));
b.setAttribute("aria-pressed", String(Boolean(x) && sameQuery(x.query, current)));
});
}
/* A saved filter onto the page, the way a company link is followed
(`companyClick`): its query read into the filter and the search, the
agent kept, and the list pushed, so back is the filter it replaced. Its
order is read too, since `addressFor` wrote it. Place tokens are named
first, a token no longer known dropped rather than sent for a 422. On a
phone the rail is put away, since the list is what was asked for. */
async function applySaved(id) {
const saved = state.saved.find((x) => x.id === id);
if (!saved) return;
const query = new URLSearchParams(saved.query);
readUrl(`?${saved.query}`, { view: false });
const sort = query.get("sort");
state.filter.sort = sort === "time" || sort === "cv" ? sort : "score";
$("#search").value = state.q;
companyChips?.clear();
placeChips?.clear();
await labelPlaces({ write: false });
if (filtersOn(state.filter, { more: true })) $("#f-more").open = true;
if (overlayRail() && state.railOpen) toggleRail();
setFilter();
}
async function deleteSaved(id) {
const saved = state.saved.find((x) => x.id === id);
if (!saved) return;
try {
await api(`/api/filters/${id}`, { method: "DELETE" });
} catch (err) {
if (err.status !== 404) return; // toasted; a 404 is gone already
}
state.saved = state.saved.filter((x) => x.id !== id);
renderSaved();
savedSay(`Deleted “${saved.name}”.`);
}
/* The name field: opened by "save", shut by cancel, Escape, a save or
another agent. */
function openSaveForm() {
$("#save-form").hidden = false;
$("#save-open").setAttribute("aria-expanded", "true");
$("#save-name").value = "";
savedSay("");
$("#save-name").focus();
}
function closeSaveForm() {
$("#save-form").hidden = true;
$("#save-open").setAttribute("aria-expanded", "false");
}
let savedSaid = 0;
/** A short line under the pills, gone after a few seconds. */
function savedSay(text) {
const note = $("#saved-note");
note.textContent = text;
note.hidden = !text;
clearTimeout(savedSaid);
if (text) savedSaid = setTimeout(() => { note.hidden = true; }, 5000);
}
/* The filters on screen under the name typed. A name the agent already
has, whatever its case, is said under the field rather than sent; the
server's 409, for a name saved meanwhile elsewhere, is said there too. */
async function saveFilter(e) {
e.preventDefault();
const agent = state.filter.agent;
if (agent === null) return;
const name = $("#save-name").value.trim();
if (!name) {
savedSay("Give it a name.");
return;
}
const taken = (n) => `“${n}” is already saved. Pick another name.`;
if (state.saved.some((x) => x.name.toLowerCase() === name.toLowerCase())) {
savedSay(taken(name));
return;
}
try {
await api(`/api/agents/${agent}/filters`, {
method: "POST", body: { name, query: savedQuery() },
});
} catch (err) {
if (err.status === 409) savedSay(taken(name));
return;
}
if (agent !== state.filter.agent) return;
closeSaveForm();
await loadSaved();
savedSay(`Saved as “${name}”.`);
}
/* 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 heading and bullet marks of a description line, see `paragraphs`. */
const LINE_MARK = /^(## |\u2022 )/gm;
/* 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) {
/* The server's order (`_EXCERPT_SOURCE`): summary, description, teaser. */
const text = (role.summary || role.description || role.teaser || "")
.replace(LINE_MARK, "").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("");
}
/** 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 "";
}
/** Days from today (UTC, as `closing=1` counts) to a `YYYY-MM-DD`
deadline: 0 is today, negative is past; null with no date. */
function daysLeft(deadline) {
const at = Date.parse(`${deadline || ""}T00:00:00Z`);
if (!Number.isFinite(at)) return null;
const today = Date.parse(`${new Date().toISOString().slice(0, 10)}T00:00:00Z`);
return Math.round((at - today) / 86400000);
}
/** "closes today" or "closes in N d" within the Closing soon window, else "". */
function closesIn(deadline) {
const n = daysLeft(deadline);
if (n === null || n < 0 || n > CLOSING_DAYS) return "";
return n === 0 ? "closes today" : `closes in ${n} d`;
}
/* The posting's languages against the agent's (`lang_flag`): ⚠ when it
requires one the agent lacks or a level above the agent's, ★ when it
names one of the agent's as a plus. A glyph with the reason as its title,
newsdesk's mark; the reader spells the reason out for a phone. */
const LANG_MARKS = {
missing: ["⚠", "warn"], below: ["⚠", "warn"], plus: ["★", "plus"],
};
function langMark(role) {
const mark = LANG_MARKS[role.lang_flag];
if (!mark) return "";
const note = role.lang_note || "";
return `<span class="badge mark ${mark[1]}" title="${esc(note)}" role="img"
aria-label="${esc(note || "Languages")}">${mark[0]}</span>`;
}
/** Closed, closing soon, the language flag, pay, remote, function and
seniority, as the row and the reader both show them. */
function badges(role) {
const words = [remoteHelpers.remoteBadge(role), role.function, role.seniority].filter(Boolean);
const pay = payBadge(role);
const closing = role.closed_at ? "" : closesIn(role.deadline);
return (role.closed_at ? `<span class="badge closed">closed</span>` : "")
+ (closing ? `<span class="badge closing" title="Apply by ${esc(role.deadline)}">${closing}</span>` : "")
+ langMark(role)
+ (pay ? `<span class="badge">${esc(pay)}</span>` : "")
+ words.map((w) => `<span class="badge">${esc(w)}</span>`).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 ? `<span class="dupes" title="Posted ${n} times">×${n}</span>` : "";
}
/* Where a role's own posting is: the ad's own page once it is known
(`posting_url`, found for a Jobindex role when its text is fetched), else
the link the board listed. Either way only an http(s) link. */
function ownLink(x) {
return safeUrl(x?.posting_url) || safeUrl(x?.original_url);
}
/* Where the row and the reader open a role: the copy of the place it leads
with, the one nearest the agent (`lead_url`, `places.Nearness`), else
its own posting. */
function linkOf(x) {
return safeUrl(x?.lead_url) || ownLink(x);
}
/* 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) => linkOf(c));
if (!copies.length) return "";
return `<div class="also">
<h2 class="reader-label">Also posted</h2>
${copies.map((c) => {
const url = linkOf(c);
const when = c.posted_at ? ago(c.posted_at) : "";
return `<a href="${esc(url)}" target="_blank" rel="noopener">
<b>${esc(c.host || host(url))}</b>
${esc([c.place, when].filter(Boolean).join(" · ") || host(url))} ↗</a>`;
}).join("")}
</div>`;
}
/* The role's places as the server orders them, the nearest to the agent
first, one entry for each place text a link opens: the copies' own
links, and the role's link for its own. */
function placeEntries(r) {
const seen = new Set();
const own = ownLink(r);
const out = [];
for (const p of Array.isArray(r.places) ? r.places : []) {
const url = p.url ? safeUrl(p.url) : own;
const key = `${p.url || ""}\u0001${p.position}\u0001${p.text}`;
if (!p.text || seen.has(key)) continue;
seen.add(key);
out.push({ text: p.text, url });
}
return out;
}
/* The place line of the reader: the leading place and "+N" for the
others, as the feed's row shows it. */
function placeLine(r) {
const texts = [...new Set(placeEntries(r).map((e) => e.text))];
return texts.length > 1 ? `${texts[0]} +${texts.length - 1}` : r.place || texts[0] || "";
}
/* Every place of a role that has several, each a link to its own posting,
laid out as "Also posted". */
function placesList(r) {
const entries = placeEntries(r);
if (new Set(entries.map((e) => e.text)).size < 2) return "";
return `<div class="also places">
<h2 class="reader-label">Places</h2>
${entries.map((e) => e.url
? `<a href="${esc(e.url)}" target="_blank" rel="noopener">${esc(e.text)} ↗</a>`
: `<span>${esc(e.text)}</span>`).join("")}
</div>`;
}
/* The gutter's number, of 100, and what it says: the agent's score, or
under What fits me the CV match. A role `judge` has not read yet has an
empty bar and, faint, how close it is to the CV (`cv_fit`), which is
what orders it there, else a dash. */
function gutterOf(role) {
if (sortShown() === "cv") {
const judged = role.cv_score !== null && role.cv_score !== undefined;
if (judged) {
return {
pct: Math.round(Math.min(100, Math.max(0, role.cv_score))),
shown: String(Math.round(role.cv_score)),
title: "How well it matches the CV, of 100",
};
}
const near = role.cv_fit !== null && role.cv_fit !== undefined;
return {
pct: 0,
shown: near ? String(Math.round(Math.min(1, Math.max(0, role.cv_fit)) * 100)) : "–",
title: near ? "Not judged against the CV yet; how close it is to the CV, of 100"
: "Not judged against the CV yet",
near,
};
}
const scored = role.score !== null && role.score !== undefined;
const pct = scored ? Math.round(Math.min(1, Math.max(0, role.score)) * 100) : 0;
return { pct, shown: scored ? String(pct) : "", title: "How well it matches, of 100" };
}
function drawRow(el, role) {
const { pct, shown, title, near } = gutterOf(role);
const text = excerpt(role);
el.innerHTML = `
<div class="gutter"><i style="height:${pct}%"></i></div>
<div class="score${near ? " near" : ""}" title="${esc(title)}">${esc(shown)}</div>
<div class="body">
<a class="headline" href="${esc(pathFor(role.uid))}">${esc(role.title || "(untitled)")}</a>
<div class="meta">
${role.company ? companyName(role) : ""}
${dupes(role)}
${role.place ? `<span>${esc(role.place)}</span>` : ""}
${badges(role)}
<span title="Posted">${ago(role.posted_at)}</span>
${role.gated_reason
? `<span class="gated" title="Rejected by this agent's fetch gate">${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, and
// its company the fastest way to ask for the rest of that company's.
el.querySelectorAll(".tag").forEach((b) => { b.onclick = () => toggleTag(b.dataset.tag); });
el.querySelector(".company")?.addEventListener("click", companyClick);
}
/* A passed role is dimmed, never dropped: the pass has to stay visible to be
undone. */
function paintRow(el, role) {
el.dataset.read = String(Boolean(role.read_at));
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 }) {
// Drawn again for another order too, whose gutter is another number.
if (el.role !== role || el.drawnSort !== sortShown()) {
el.role = role;
el.drawnSort = sortShown();
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 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);
renderStrip();
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>`;
// Without the agents the feed may not know whose it is, so they are
// asked again with it.
const retry = empty.querySelector("[data-retry]");
if (retry) retry.onclick = () => (state.agentsLoaded ? loadFeed() : start());
} else {
// An agent's list is what its fetch gate passes, which a phone,
// whose rail is shut, learns here and at the end of the list.
const filtered = state.q || filtersOn();
const gate = gateKept() ? `${esc(gateOwner())} fetch gate` : "";
empty.innerHTML = filtered
? `<h2>Nothing matches</h2>
<p>No open role ${gate ? `that passes ${gate} ` : ""}fits these filters.
<button type="button" class="linky" data-clear>Clear them</button> and start again.</p>`
: gate
? `<h2>No roles yet</h2>
<p>No open role passes ${gate} yet. <a href="/settings/sources#runs">Runs</a>
starts a pull; <a href="/settings/sources#job-boards">Job boards</a> and
<a href="/settings/sources#company-boards">Company boards</a> decide what it
brings in, <a href="/settings/agents">Search agents</a> what the gate passes.</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. Whether it has run
// out is the server's to say (`pageMerge`), since the rows on screen
// keep the ones a vote or a read has since taken out of its list.
const end = $("#feed-end");
const n = state.items.length;
end.hidden = !state.loaded || !n;
end.textContent = state.more ? "Loading more…" : `${listSaid(n)} — that is all of them.`;
}
/** Whether the list keeps to the viewing agent's fetch gate: there is an
agent, and Show gated is off. */
const gateKept = () => state.filter.agent !== null && !state.filter.gated;
/** Whose fetch gate, for a sentence: the viewing agent's name, or "this
agent's" until the agents are in. */
function gateOwner() {
const agent = viewed();
return agent ? `${agent.name}'s` : "this agent's";
}
/** The rows on screen in words, for the end of the list: how many and,
with an agent viewing, that they are what its fetch gate passes (and
the filters keep), or with Show gated that they hold what it rejects. */
function listSaid(n) {
const roles = `${number.format(n)} ${n === 1 ? "role" : "roles"}`;
if (state.filter.agent === null) return roles;
const gate = `${gateOwner()} fetch gate`;
const filtered = Boolean(state.q) || filtersOn() > (state.filter.gated ? 1 : 0);
if (state.filter.gated) {
return `${roles}${filtered ? " in these filters" : ""}, the ones ${gate} rejects included`;
}
return `${roles} ${n === 1 ? "passes" : "pass"} ${gate}${filtered ? " and these filters" : ""}`;
}
/* 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, its ⊘ ▲ ★ for the viewing
agent, which is where a company is starred from, and its two overrides,
under them which parts of the fetch gate apply to it (`gateNote`). Built
again only for another company or agent, since the feed is drawn on
every page; the count, the affinity and the overrides 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 = `
<div class="strip-head">
<b class="strip-name">${esc(name)}</b>
<span class="strip-count"></span>
${careers ? `<a class="reader-careers" href="${esc(careers)}" target="_blank" rel="noopener"
title="The company's careers page">Careers ↗</a>` : ""}
<span class="affinity-slot"></span>
<button type="button" class="linky strip-drop"
title="Take the company filter off">All companies</button>
</div>
<p class="strip-note"></p>
<p class="strip-status" role="status"></p>`;
el.querySelector(".strip-drop").onclick = dropCompany;
}
const slot = el.querySelector(".affinity-slot");
const drawn = `${affinity}:${company ? `${company.all_countries}:${company.all_roles}` : ""}`;
if (slot.dataset.affinity !== drawn) {
slot.dataset.affinity = drawn;
slot.replaceChildren(affinityControl(key, affinity,
(updated) => affinityChanged(key, company, updated), state.filter.agent));
// The two overrides need a company row, which a first stance makes.
if (company) slot.append(" ", overridesControl(key, company, renderStrip));
const note = el.querySelector(".strip-note");
note.textContent = gateNote(company);
note.hidden = !note.textContent;
}
const n = state.total;
el.querySelector(".strip-count").textContent = state.loaded
? `${number.format(n)} ${n === 1 ? "role matches" : "roles match"}` : "";
}
/* Which parts of the viewing agent's fetch gate apply to a company's
roles: All locations lifts the location gate, All roles the role
exclusion and the fetch terms; the world gate always holds. A favourite
only ranks higher, so it is not named here. A hidden company has no
roles in the feed at all. Nothing with no agent, when no fetch gate
applies. */
function gateNote(company) {
if (state.filter.agent === null) return "";
if (company?.affinity === -1) return "Hidden for this agent: its roles are never shown.";
const locations = Boolean(company?.all_countries);
const roles = Boolean(company?.all_roles);
if (locations && roles) {
return "All locations and All roles: every role in the agent's world, "
+ "not filtered by location, role exclusion or fetch terms.";
}
if (locations) {
return "All locations: every role in the agent's world, not filtered by location. "
+ "The agent's role exclusion still applies.";
}
if (roles) {
return "All roles: no titles left out and no fetch terms. "
+ "The agent's locations still apply.";
}
return "The roles this agent's fetch gate passes: its world, locations and role exclusion. "
+ "All locations lifts the locations for this company, All roles the role exclusion.";
}
/* A company seen only through a search has no row until its first change
creates one, so the list is reloaded then. Hiding takes the company's
rows out at once, since a hidden company is never in the feed; where the
others rank waits on the `score` it queued, whose id the affinity route
answers with (`updated.score_job`), and the feed reloads when that has
finished. A list the company filter has come off meanwhile has its rows
asked again in the new order, as `renderAffinity` does. */
async function affinityChanged(key, company, updated) {
if (!company) await loadCompanies(state.filter.agent).catch(() => {});
if (updated?.affinity === -1) reload(); else renderFeed();
const status = () => $("#company-strip .strip-status");
if (status()) status().textContent = "Scoring again; the list reloads when that is done.";
await scored(updated?.score_job);
if (status()) status().textContent = "";
if (state.filter.companyKeys.includes(key)) reload();
else loadFeed({ keep: state.items.length });
}
/* Wait for the `score` job `job`, the way agents.js's `rescore` waits:
until the queue holds it neither running nor queued. None, when the
route could queue no job, is nothing to wait for. */
async function scored(job) {
if (job == null) return;
for (let i = 0; i < 300; i += 1) {
let snapshot;
try {
snapshot = await api("/api/jobs");
} catch (err) {
return;
}
if (![...snapshot.running, ...snapshot.queued].some((j) => j.id === job)) return;
await new Promise((resolve) => setTimeout(resolve, 1000));
}
}
// ----------------------------------------------------------- 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;
navigate(pathFor(uid), { replace: Boolean(state.readingUid) });
}
// 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 with no list of ours under it (arrived at by a link) has its entry
// replaced by the list instead, rather than leaving the app.
function closeReader() {
if (underIs(pathFor(null) + location.search)) 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.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;
// With Show read off the server's list loses it, see `pageAsk`.
if (!state.filter.showRead) state.moved += 1;
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 "";
}
/* What the reader shows below the title for pay, or null when the role
states none: 'normalised' shows the range from the normalised columns,
plus the board's own text underneath when it says more than the range
does — a period, several zones — spotted by " per " or ";" in it, which
every conforming `salary_text` carries and the plain range never does
(`plugins.ats`'s `_pay_line`); 'stated' shows the text itself, with a
note that it was not normalised. */
function payDisplay(r) {
if (r.salary_state === "normalised") {
const range = salary(r);
const text = r.salary_text || "";
return { range, detail: /(;| per )/.test(text) && text !== range ? text : "", note: "" };
}
if (r.salary_state === "stated") {
return { range: r.salary_text, detail: "", note: "as stated, not normalised" };
}
return null;
}
function host(url) {
try { return new URL(url).host.replace(/^www\./, ""); } catch (e) { return ""; }
}
/* A description is a line per paragraph (`plugins.readers._shared.html_text`):
"## " starts a heading and "• " a list item, which is how a board's HTML
keeps its sections and bullets (`LINE_MARK`). A fetched page keeps its
line breaks, and an older description is one long line, which stays one
paragraph. */
function paragraphs(text) {
let html = "";
let list = false;
for (const line of text.split(/\n+/).map((p) => p.trim()).filter(Boolean)) {
const item = line.startsWith("\u2022 ");
if (item !== list) { html += item ? "<ul>" : "</ul>"; list = item; }
html += item ? `<li>${esc(line.slice(2))}</li>`
: line.startsWith("## ") ? `<h3>${esc(line.slice(3))}</h3>`
: `<p>${esc(line)}</p>`;
}
return list ? `${html}</ul>` : html;
}
const deadlineFormat = new Intl.DateTimeFormat("en-GB", {
weekday: "short", day: "numeric", month: "short", year: "numeric", timeZone: "UTC",
});
const languageNames = (() => {
try { return new Intl.DisplayNames(["en"], { type: "language" }); } catch (err) { return null; }
})();
/** An ISO 639-1 code as its English name, the code itself when unknown. */
function languageName(code) {
try { return languageNames?.of(code) || code; } catch (err) { return code; }
}
const MUST_MARKS = { met: ["✓", "met"], broken: ["✗", "broken"], unclear: ["?", "unclear"] };
/* The agent's `judge` reading against its CV: the total and its three
numbers, each of 10, career as the server counted it (capped at 4 when a must-have
is broken, with what the model said), the must-haves with a verdict
each, then the strengths and gaps it named. A box as the summary is,
since it is the same kind of thing: a model's reading, not the posting. */
function cvMatch(r) {
const j = r.judgement;
if (!j) return "";
const list = (items, none) => (items?.length
? `<ul>${items.map((x) => `<li>${esc(x)}</li>`).join("")}</ul>`
: `<p class="muted small">${none}</p>`);
const counted = j.career_capped ?? j.career;
const career = counted < j.career
? `career ${counted}/10 (capped: breaks a must-have; model said ${j.career}/10)`
: `career ${j.career}/10`;
const musts = Array.isArray(j.musts) && j.musts.length
? `<ul class="cv-musts">${j.musts.map((m) => {
const [mark, word] = MUST_MARKS[m.verdict] || MUST_MARKS.unclear;
return `<li class="must-${word}"><span class="mark" role="img"
aria-label="${word}" title="${word}">${mark}</span><span>${esc(m.text)}</span></li>`;
}).join("")}</ul>` : "";
return `<section class="reader-summary reader-cv">
<h2 class="reader-label">CV match</h2>
<p class="cv-total"><b>${Math.round(j.cv_score)}</b> of 100
<span>skills ${j.skills}/10 · experience ${j.experience}/10 · ${career}</span></p>
${musts}
<div class="cv-lists">
<div><h3 class="reader-label">Strengths</h3>${list(j.strengths, "None named.")}</div>
<div><h3 class="reader-label">Gaps</h3>${list(j.gaps, "None named.")}</div>
</div>
</section>`;
}
/* The last day to apply and the languages the posting names, each with
its level and whether it is required or a plus, under them the flag's
reason, which a phone has no hover to read off the ⚠ or ★. newsdesk's
settings `dl`. Nothing when the posting says neither. */
function roleFacts(r) {
const rows = [];
if (r.deadline) {
const at = Date.parse(`${r.deadline}T00:00:00Z`);
const soon = r.closed_at ? "" : closesIn(r.deadline);
rows.push(["Apply by", esc(Number.isFinite(at) ? deadlineFormat.format(at) : r.deadline)
+ (soon ? ` · <span class="closing">${soon}</span>` : "")]);
}
const langs = Array.isArray(r.languages_required) ? r.languages_required : [];
if (langs.length || r.lang_note) {
const named = langs.map((l) => esc(`${languageName(l.language)} (${
[l.level, l.kind === "plus" ? "a plus" : "required"].filter(Boolean).join(", ")})`));
rows.push(["Languages", named.join(" · ")
+ (r.lang_note ? `<span class="fact-note">${langMark(r)} ${esc(r.lang_note)}</span>` : "")]);
}
if (!rows.length) return "";
return `<dl class="reader-facts">${rows.map(([k, v]) => `<dt>${k}</dt><dd>${v}</dd>`).join("")}</dl>`;
}
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 = linkOf(r);
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)
: (r.teaser || "").trim()
? `<p class="reader-note reader-teaser">A short description from the board's
list; the board gave no full text.</p>${paragraphs(r.teaser.trim())}`
: `<p class="reader-note">The board gave no description for this one.</p>`;
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;
// Under the title, in the copy note's style: that the viewing agent's
// fetch gate rejects the role and why (`gated_reason`), since a link
// from elsewhere, a saved role on Applications say, opens one the feed
// never lists.
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 ? companyName(r) : ""}
${careers ? `<a class="reader-careers" href="${esc(careers)}" target="_blank" rel="noopener"
title="The company's careers page">Careers ↗</a>` : ""}
<span class="affinity-slot"></span>
${placeLine(r) ? `<span>${esc(placeLine(r))}</span>` : ""}
${r.first_seen ? `<span title="First seen">${ago(r.first_seen)}</span>` : ""}
${badges(r)}
${tagChips(r.tags)}
</div>
<h1>${esc(r.title || "")}</h1>
${loaded && r.dup_of ? `<p class="reader-note reader-copy">A copy of
<a href="${esc(pathFor(r.dup_of))}">a posting</a> the feed lists once.</p>` : ""}
${loaded && state.filter.agent !== null && r.gated_reason
? `<p class="reader-note reader-copy">Rejected by ${esc(gateOwner())} fetch gate:
${esc(r.gated_reason)}. The feed lists it only with Show gated.</p>` : ""}
${pay ? `<p class="reader-salary">${esc(pay.range)}</p>
${pay.detail ? `<p class="muted small">${esc(pay.detail)}</p>` : ""}
${pay.note ? `<p class="muted small">${esc(pay.note)}</p>` : ""}` : ""}
${r.summary ? `<section class="reader-summary">
<h2 class="reader-label">Summary</h2><p>${esc(r.summary)}</p></section>` : ""}
${loaded ? cvMatch(r) : ""}
${loaded ? roleFacts(r) : ""}
<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>` : ""}
${loaded ? placesList(r) : ""}
${loaded ? alsoPosted(r) : ""}
</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(".reader-meta .company")?.addEventListener("click", companyClick);
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-copy a")?.addEventListener("click", (e) => {
if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || e.button !== 0) return;
e.preventDefault();
openReader(r.dup_of);
});
el.querySelector(".reader-body").scrollTop = scrolled;
}
/* The company's ⊘ ▲ ★, the one place a company is judged outside the
Companies page, and its two fetch overrides beside them. A company seen
only through a search has no row until its first change creates one, so
the list is reloaded then, and the overrides, which need a row, wait for it.
Hiding reloads the feed, which no longer holds the company's roles. Any
other stance moves every role of the company once the `score` it queued
has run, up into the rows already read as well as down out of them,
which no page asked from an offset makes up for (`pageAsk`); so the rows
on screen are asked again then, as many, in the new order. */
function renderAffinity(slot, r) {
const company = companies.get(r.company_key);
if (!r.company_key) { slot.replaceChildren(); return; }
slot.replaceChildren(affinityControl(r.company_key, company ? company.affinity : 0, async (updated) => {
if (!company) await loadCompanies(state.filter.agent).catch(() => {});
renderAffinity(slot, r);
if (updated?.affinity === -1) { reload(); return; }
renderFeed();
await scored(updated?.score_job);
loadFeed({ keep: state.items.length });
}, state.filter.agent));
if (company) {
slot.append(" ", overridesControl(r.company_key, company,
async () => renderAffinity(slot, r)));
}
}
/* 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(roleUrl(uid).replace(/(\?|$)/, "/text$1"), { 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 = linkOf(role);
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) {
if (replace) history.replaceState(history.state, "", path + location.search);
else history.pushState({ from: here() }, "", 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,
// and back and forward through the filters.
window.addEventListener("popstate", restore);
// ------------------------------------------------ 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;
setOrder(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({}); });
$("#save-open").addEventListener("click",
() => ($("#save-form").hidden ? openSaveForm() : closeSaveForm()));
$("#save-cancel").addEventListener("click", closeSaveForm);
$("#save-form").addEventListener("submit", saveFilter);
$("#save-name").addEventListener("keydown", (e) => {
if (e.key === "Escape") closeSaveForm();
});
// A pick or a removal is a filter set, pushed; the text typed to find
// it is the chip input's own and never reaches the address.
companyChips = chipInput($("#f-company"), {
suggest: (q) => {
const p = new URLSearchParams({ q });
if (state.filter.agent !== null) p.set("agent", String(state.filter.agent));
return api(`/api/suggest/companies?${p}`).then((rows) => rows.map((c) => ({
value: c.key, label: c.name,
hint: c.affinity === 2 ? `★ ${number.format(c.count)}` : c.count,
})));
},
onChange: (items) => {
items.forEach((i) => companyNames.set(i.value, i.label));
setFilter({ companyKeys: items.map((i) => i.value) });
},
placeholder: "Company", label: "Company",
});
placeChips = chipInput($("#f-place"), {
suggest: (q) => {
// The viewing agent, so "Remote" counts the remote roles within its
// scope; the server may ignore it.
const p = new URLSearchParams({ q });
if (state.filter.agent !== null) p.set("agent", String(state.filter.agent));
return api(`/api/suggest/places?${p}`).then((rows) => rows.map((s) => ({
value: s.token, label: s.label,
hint: `${PLACE_KINDS[s.kind] || s.kind} · ${number.format(s.count)}`,
})));
},
onChange: (items) => {
items.forEach((i) => placeLabels.set(i.value, i.label));
setFilter({ places: items.map((i) => i.value) });
},
placeholder: "Place", label: "Place",
});
for (const key of ["function", "remote", "judged"]) {
$(`#f-${key}`).addEventListener("change", (e) => setFilter({ [key]: e.target.value }));
}
// "No pay stated" starts unticked for each pay picked anew.
$("#f-pay").addEventListener("change", (e) => setFilter({
pay: e.target.value, payUnknown: e.target.value ? state.filter.payUnknown : false,
}));
$("#f-pay-unknown").addEventListener("change",
(e) => setFilter({ payUnknown: e.target.checked }));
// From and To hold "" and the rungs; the options are the ladder's.
for (const [id, key] of [["f-level-from", "levelFrom"], ["f-level-to", "levelTo"]]) {
$(`#${id}`).innerHTML = `<option value="">Any level</option>` + LADDER.rungs.map((rung) =>
`<option value="${esc(rung)}"></option>`).join("");
$(`#${id}`).addEventListener("change", (e) => setSeniority({ [key]: e.target.value }));
}
$("#f-track").innerHTML = Object.entries(TRACKS).map(([key, label]) =>
`<button type="button" data-track="${key}">${label}</button>`).join("");
$("#f-track").querySelectorAll("[data-track]").forEach((b) => {
b.onclick = () => { if (b.dataset.track !== state.filter.track) setSeniority({ track: b.dataset.track }); };
});
$("#f-seniority-unknown").addEventListener("change",
(e) => setFilter({ seniorityUnknown: e.target.checked }));
$("#f-gated").addEventListener("change", (e) => setFilter({ gated: e.target.checked }));
$("#f-closing").addEventListener("change", (e) => setFilter({ closing: 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"));
// ▼ ● ▲ and ★, which likes, on a row or in the reader move the role in
// the server's order, or out of its list under Judged or with Show read
// off, which the next page makes up for (`pageAsk`). The keys press the
// same buttons. Counted at the click, failed or undone ones too, since a
// page that starts a row too early only repeats one.
for (const pane of [$("#roles-list"), $("#reader")]) {
pane.addEventListener("click", (e) => {
if (e.target.closest(".judge button")) state.moved += 1;
});
}
// 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();
loadSaved().catch(() => {});
await Promise.all([loadTracked(), loadCompanies(state.filter.agent)]).catch(() => {});
await loadFeed({ keep: state.items.length });
if (state.readingUid) renderReader();
window.scrollTo(0, y);
});
}
/* Whose feed it is, then the feed. The server keeps to a fetch gate only
for an agent it is told of, and without one lists every open role, so
the first request carries the agent whenever one is known before the
agents are in: the address's, else the one this browser viewed last
(`storedAgent`). `chooseAgent` checks it against the enabled ones when
they land, and the feed reloads if it picks another. With neither, the
feed waits for the agents: with none enabled the list of every open
role is the right one, and when they cannot be had the feed's error
state offers to try again (`loadFeed`), rather than every open role
passing for the agent's list.
The rest fills in when it arrives and the feed does not wait on it: the
companies, the tag counts, the saved filters. Each one drawn before is
greyed or missing, 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. `keep` and `y` put the list back as it
was (`kept`). Run again by the error state's retry when the agents did
not come. */
async function start({ keep = 0, y = null } = {}) {
if (state.filter.agent === null) state.filter.agent = storedAgent();
const agentsIn = loadAgents().then(() => { chooseAgent(); return true; }, () => false);
const trackedIn = loadTracked().catch(() => {});
// What the reader's fetch and then the feed's first request go out with,
// so the agents landing later know whether either is to be asked again.
const routed = state.filter.agent;
route();
if (state.filter.agent === null) await agentsIn;
const asked = state.filter.agent;
const sortAsked = sortShown();
const enhance = (async () => {
const [ready] = await Promise.all([agentsIn, trackedIn]);
if (!ready) return;
await loadCompanies(state.filter.agent).catch(() => {});
renderRail();
renderActive();
loadFilters().catch(() => {});
loadSaved().catch(() => {});
// Reload for the score and votes when the agent chosen is not the one
// asked for (a remembered one disabled since), and either way bring
// the reader's affinity control and judge buttons up to date, since
// `companies` was still empty when it first painted. What fits me
// asked of an agent with no CV is What I'm looking for.
if (state.filter.agent !== asked || sortShown() !== sortAsked) reload();
else renderFeed();
if (state.readingUid) {
if (state.filter.agent !== routed) refreshReader(state.readingUid);
else renderReader();
}
})();
await loadFeed({ keep });
if (y !== null && !state.readingUid) window.scrollTo(0, y);
await enhance;
}
document.addEventListener("DOMContentLoaded", async () => {
readUrl();
const was = kept();
if (was && !narrow.matches) state.railOpen = was.rail;
wire();
renderRail();
renderActive();
// Named before the first request, which a token the server does not
// know would turn into a 422 rather than a list.
await labelPlaces();
await start(was ? { keep: was.count, y: was.y || 0 } : {});
});
})();