Roles as a feed, a read page, votes that move the rank, unstar

The Roles tab is news's feed row: the title opens /roles/{uid}, company,
place and age under it, the badges, a one-line excerpt (summary, else the
description's opening), and ▲ ● ▼ ★ on the right, under the text at 640px.
The company affinity control leaves the row. A passed role and a hidden
company's are dimmed and stay. The filter bar is one row: order, search and
a Filters <details> holding the rest, with a judged select and "Show hidden
companies". The list loads 60 and appends on an IntersectionObserver
sentinel; back from a read page restores the filters, rows and scroll.

GET /api/roles takes offset, defaults to 60 and answers {items, total}.
judged= is a WHERE on roles.vote. Under a ranking the served score and the
order are the stored score moved by the vote (x0.5 pass, x1.2 like, capped
at 1), so a vote shows at once without a rescore. POST and DELETE
/api/roles/{uid}/vote set and clear it; pressing the pressed stance clears.

★ saves; pressed again it calls DELETE /api/applications/{id}, which drops
the application while it is still saved and answers 409 after. save_role no
longer writes the placeholder next step.

The read page (role.html, role.js) is news's reader: a bar with back,
▲ ● ▼ ★ and ↗, the company with its affinity control, place, badges, salary,
summary, the text (fetched posting, else description) and the link out.
It offers Fetch the posting for a teaser and Summarise without a summary,
against the /text and /summarise routes B4 adds. The vote and star buttons
are judge.js, shared by the feed and the reader.

Applications: titles open the read page, the Next column is gone, a Saved
column instead, and the lede says what the page is for.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
WolfandClaude Fable 5.1 committed 2026-09-25 21:51:48 +02:00
1 parent 7d31cca394
commit 09c5dde113
13 files changed
+1216 -192

No files matched your search

+185 -28
View File
@@ -311,38 +311,204 @@ textarea:focus-visible {
.count { color: var(--dim); font-size: .85rem; margin: .75rem 0 .5rem; }
/* roles */
/* == roles, the read page, applications ================================== */
/* The feed row and the reader are news's (`newsdesk/web/static/app.css`):
* the row a grid with a bottom rule and no card, the actions on the right
* dropping under the text at 640px, a cast vote filled rather than tinted.
* Drawn by static/roles.js, static/role.js and static/judge.js; the phone
* and touch rules for all of it are at the end of this section rather than
* in the phone section below, so the section is one piece. */
.roles { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: .5rem; }
/* The filter bar: the order, the search box, and Filters on one row at any
width. Filters is a `<details>` whose summary is lifted into that row, so
the panel it opens sits in the flow under the row and pushes the list
down instead of covering it. */
.roles-filters { display: block; position: relative; }
.filter-line { display: flex; gap: .5rem; align-items: center; margin-right: 6.75rem; }
.filter-line select { flex: 0 1 auto; max-width: 45%; }
.filter-line input[type="search"] { flex: 1 1 8rem; }
.filter-more > summary {
position: absolute; top: .75rem; right: .75rem;
display: flex; align-items: center; justify-content: center; min-width: 6rem;
padding: .4rem .6rem; line-height: 1.2;
border: 1px solid var(--line); border-radius: .3rem;
color: var(--fg); background: var(--bg); cursor: pointer;
list-style: none; white-space: nowrap;
}
.filter-more > summary::-webkit-details-marker { display: none; }
.filter-more[open] > summary { border-color: var(--accent); color: var(--accent); }
.filter-active { margin-left: .3rem; color: var(--accent); font-weight: 600; }
.filter-panel {
display: flex; flex-wrap: wrap; gap: .5rem; align-items: center;
margin-top: .75rem; padding-top: .75rem; border-top: 1px solid var(--line);
}
.filter-panel select { flex: 1 1 9rem; }
/* The feed. */
.roles {
list-style: none; margin: 0; padding: 0;
background: var(--panel);
border: 1px solid var(--line); border-radius: var(--radius);
}
.roles:empty { display: none; }
.roles-end { height: 1px; }
.role {
background: var(--panel); border: 1px solid var(--line); border-radius: .5rem;
padding: .6rem .8rem;
display: flex; flex-direction: column; gap: .35rem;
display: grid; grid-template-columns: minmax(0, 1fr) auto;
align-items: start; gap: .85rem;
padding: .8rem 1rem .85rem;
border-bottom: 1px solid var(--line);
}
.role:last-child { border-bottom: 0; }
.role-body { min-width: 0; }
.role-title {
display: block; max-width: 60ch;
color: var(--fg); text-decoration: none;
font-size: 1.05rem; font-weight: 600; line-height: 1.35;
overflow-wrap: anywhere;
}
.role-main { display: flex; flex-wrap: wrap; align-items: baseline; gap: .5rem; }
.role-title { font-weight: 600; text-decoration: none; }
@media (hover: hover) {
.role-title:hover { text-decoration: underline; }
.role-title:hover { text-decoration: underline; text-underline-offset: 2px; }
}
.role-company { color: var(--dim); }
.role-meta {
display: flex; flex-wrap: wrap; align-items: center; gap: .5rem;
color: var(--dim); font-size: .85rem;
.role-meta, .reader-meta {
display: flex; flex-wrap: wrap; gap: .1rem .55rem; align-items: baseline;
margin-top: .25rem; font-size: .85rem; color: var(--dim);
}
.role-meta .badge {
/* The company is how you decide whether to read on: weight and full ink. */
.role-meta b, .reader-meta b { font-weight: 600; color: var(--fg); }
.role-meta > :empty, .reader-meta > :empty { display: none; }
.role-meta > * + *::before { content: "· "; }
.role-badges { display: flex; flex-wrap: wrap; gap: .35rem; margin-top: .35rem; }
.role-badges > :empty { display: none; }
.role-badges:not(:has(> :not(:empty))) { display: none; }
.role-badges .badge {
background: transparent; color: var(--dim);
border: 1px solid var(--line); border-radius: 1rem;
padding: .05rem .55rem; font-size: .78rem;
}
.role-meta .badge:empty { display: none; }
.role-meta .role-score {
.role-badges .role-score {
color: var(--accent); border-color: color-mix(in srgb, var(--accent) 45%, var(--line));
font-variant-numeric: tabular-nums;
}
.role-gated { color: var(--error); font-size: .85rem; }
.role-age { margin-left: auto; }
.role.muted, tr.muted { opacity: .55; }
.role.gated { opacity: .7; }
.role-gated { color: var(--error); font-size: .8rem; }
.role-excerpt {
margin: .35rem 0 0; max-width: 68ch;
font-size: .9rem; color: var(--dim);
white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
}
.role-excerpt:empty { display: none; }
/* A pass and a hidden company are dimmed and stay: a stray tap has to be
visible to be undone. The buttons keep full contrast, so the undo does. */
.role.muted .role-body, .role.passed .role-body { opacity: .55; }
.role.gated .role-body { opacity: .7; }
/* The Companies table dims a hidden company's row the same way. */
tr.muted { opacity: .55; }
/* ▲ ● ▼ ★, on a row and in the reader's bar (static/judge.js). */
.judge { display: flex; gap: .15rem; align-items: center; }
.judge button {
padding: .2rem .45rem; font-size: 1rem; line-height: 1;
color: var(--dim); background: none;
border: 1px solid transparent; border-radius: .3rem;
}
@media (hover: hover) {
.judge button:hover { color: var(--fg); border-color: var(--line); }
}
/* Filled when cast: a reversed glyph on solid ground reads at arm's length
where a tint does not. `--panel` for the glyph because it is the opposite
end of the scale from every fill in both schemes. */
.judge .up[aria-pressed="true"] {
color: var(--panel); background: var(--accent); border-color: var(--accent);
}
.judge .down[aria-pressed="true"] {
color: var(--panel); background: var(--error); border-color: var(--error);
}
/* Neither way is an answer and must be as loud as the other two, or it
cannot be told from unjudged; grey, since it is no direction. */
.judge .mid[aria-pressed="true"] {
color: var(--panel); background: var(--dim); border-color: var(--dim);
}
/* Saved is a different question from judging: amber, and set apart. */
.judge .star[aria-pressed="true"] {
color: var(--panel); background: var(--warn); border-color: var(--warn);
}
.judge .star { margin-left: .35rem; }
/* The read page. */
.reader {
background: var(--panel);
border: 1px solid var(--line); border-radius: var(--radius);
}
.reader-bar {
position: sticky; top: var(--header-h, 0px); z-index: 4;
display: flex; align-items: center; gap: .2rem;
padding: .35rem .6rem;
background: var(--panel);
border-bottom: 1px solid var(--line);
border-radius: var(--radius) var(--radius) 0 0;
}
.reader-bar .spacer { flex: 1; }
.reader-back, .reader-external {
display: inline-flex; align-items: center; justify-content: center;
padding: .2rem .55rem; font-size: 1rem; line-height: 1;
color: var(--dim); text-decoration: none;
border: 1px solid var(--line); border-radius: .3rem;
}
.reader-back { margin-right: .4rem; }
@media (hover: hover) {
.reader-back:hover, .reader-external:hover { color: var(--fg); border-color: var(--dim); }
}
.reader-body { padding: 1.4rem 2rem 2.5rem; overflow-wrap: anywhere; }
/* About 70 characters a line at the reading size. */
.reader-body > * { max-width: 40rem; margin-inline: auto; }
.reader-meta { align-items: center; margin-top: 0; }
.reader-meta .affinity { font-size: .85rem; }
.reader h1 { font-size: 1.6rem; line-height: 1.25; margin: .6rem auto .5rem; }
.reader .role-badges { margin-top: 0; }
.reader-salary { margin: .6rem auto 0; font-weight: 600; }
.reader-summary {
margin-top: 1.1rem; padding: .7rem .9rem;
background: color-mix(in srgb, var(--accent) 7%, var(--panel));
border-left: 3px solid var(--accent); border-radius: .3rem;
}
.reader-summary p { margin: 0; }
/* A label over a block rather than the posting's own heading. */
.reader-label {
margin: 0 0 .3rem; font-size: .72rem; font-weight: 600;
letter-spacing: .08em; text-transform: uppercase; color: var(--dim);
}
.reader-tools { display: flex; flex-wrap: wrap; gap: .5rem; align-items: center; margin-top: 1rem; }
.reader-tools:not(:has(> :not([hidden], :empty))) { display: none; }
.prose { margin-top: 1.2rem; font-size: 1.02rem; line-height: 1.7; }
.prose p { margin: 0 0 1rem; }
.reader-out { margin-top: 1.5rem; padding-top: 1rem; border-top: 1px solid var(--line); }
/* Applications: the table is the shared `table.list`. */
table.applications td[data-label="Saved"] { white-space: nowrap; color: var(--dim); }
@media (max-width: 640px) {
.filter-line { margin-right: 6.25rem; }
.filter-more > summary { right: 10px; min-width: 5.5rem; }
/* Edge to edge, like every panel on a phone. */
.roles, .reader { margin-inline: -10px; border-radius: 0; border-inline: 0; }
.reader { margin-top: -10px; border-top: 0; }
.reader-bar { border-radius: 0; }
.role { grid-template-columns: minmax(0, 1fr); gap: .45rem; padding: .75rem 10px; }
/* Under the text and to the right, where a thumb is. Two filled blocks
side by side need a gap or they read as one control. */
.role-actions { justify-content: flex-end; gap: .4rem; }
.role-actions button { padding: .25rem .75rem; min-height: 32px; font-size: 1.2rem; }
.reader-body { padding: .9rem .75rem 1.5rem; }
.reader h1 { font-size: 1.3rem; }
}
@media (pointer: coarse) {
.filter-more > summary { min-height: 2.75rem; }
.judge button { padding: .5rem .7rem; font-size: 1.15rem; }
.reader-bar { padding: .3rem .5rem; }
.reader-back, .reader-external { min-height: 2.75rem; min-width: 2.75rem; }
}
/* == end of roles, the read page, applications ============================ */
.affinity { display: inline-flex; gap: .15rem; }
.role-main .affinity { margin-left: auto; }
@@ -357,11 +523,6 @@ textarea:focus-visible {
background: var(--error); border-color: var(--error);
}
.save { align-self: flex-start; padding: .3rem .8rem; font-weight: 600; }
.save[disabled] {
background: var(--bg); color: var(--dim); border-color: var(--line); cursor: default;
}
/* agents */
.agents { list-style: none; margin: 0 0 1rem; padding: 0; display: flex; flex-direction: column; gap: .4rem; }
@@ -437,10 +598,6 @@ table.list select { padding: .25rem .4rem; }
}
}
@media (max-width: 480px) {
.role-age, .role-main .affinity { margin-left: 0; }
}
/* -- the phone ------------------------------------------------------------ */
/* Two axes, and deliberately not the same one, as in newsdesk: width decides
the layout, pointer decides the sizes. A tablet is wide and touched, a
+22 -7
View File
@@ -2,7 +2,9 @@
*
* The template renders an empty table; the rows come from /api/applications
* and a status change is a fetch through `api()` from app.js, which toasts a
* refusal. The company names come from app.js's shared company list.
* refusal. A role's title opens its read page, where ★ unsaves it; one that
* was never a posting links out to where it was found, if anywhere. The
* company names come from app.js's shared company list.
*/
(function () {
"use strict";
@@ -25,17 +27,30 @@
return select;
}
/** "25 Sep", or "25 Sep 2025" when it is not this year. */
function savedOn(iso) {
const at = new Date(iso);
if (Number.isNaN(at.getTime())) return "";
const options = { day: "numeric", month: "short" };
if (at.getFullYear() !== new Date().getFullYear()) options.year = "numeric";
return at.toLocaleDateString("en-GB", options);
}
function render(applications) {
const body = $("#applications-list");
body.replaceChildren();
for (const application of applications) {
const tr = document.createElement("tr");
if (application.url) {
if (application.role_uid || application.url) {
const link = document.createElement("a");
link.href = application.url;
link.target = "_blank";
link.rel = "noopener";
link.textContent = application.role_title || "(untitled)";
if (application.role_uid) {
link.href = `/roles/${encodeURIComponent(application.role_uid)}`;
} else {
link.href = application.url;
link.target = "_blank";
link.rel = "noopener";
}
cell(tr, "Role", link);
} else {
cell(tr, "Role", application.role_title || "(untitled)");
@@ -45,8 +60,8 @@
const select = statusSelect(application.status);
select.addEventListener("change", () => setStatus(application.id, select));
cell(tr, "Status", select);
cell(tr, "Next", [application.next_action, application.next_date]
.filter(Boolean).join(" · "));
const saved = cell(tr, "Saved", savedOn(application.created_at));
saved.title = application.created_at;
body.appendChild(tr);
}
$("#applications-count").textContent =
+132
View File
@@ -0,0 +1,132 @@
/* ▲ ● ▼ ★ for one role: the feed row and the read page share them.
*
* news's `voteButtons`, `starButton` and `vote()`, adapted. Three stances and
* no stance is four states from three buttons; pressing the stance a role
* already has clears it, which is the only way back to unjudged, since ● is
* an answer ("neither way") and not the absence of one. A vote never hides a
* role: a stray tap stays on screen, pressed, and one more tap undoes it.
*
* ★ is Save. It files the role under Applications (`POST /api/applications`)
* and, pressed again, takes it back out (`DELETE /api/applications/{id}`),
* which the server allows only while the application is still at `saved`; a
* 409 is toasted by `api()` and the star stays lit.
*
* Both are optimistic: the button changes before the request and changes back
* if it fails. `api()` has already toasted the failure by then.
*
* await loadTracked();
* container.append(judgeButtons(role, (role) => row.classList.toggle(...)));
*/
(function () {
"use strict";
const { api } = window;
/** @type {Map<string, object>} role_uid -> application, for roles saved */
const tracked = new Map();
async function loadTracked() {
const applications = await api("/api/applications");
tracked.clear();
for (const a of applications) if (a.role_uid) tracked.set(a.role_uid, a);
return tracked;
}
const STANCES = [
{ value: 1, cls: "up", glyph: "▲", said: "Like" },
{ value: 0, cls: "mid", glyph: "●", said: "Neither way" },
{ value: -1, cls: "down", glyph: "▼", said: "Pass" },
];
function button(cls, glyph) {
const b = document.createElement("button");
b.type = "button";
b.className = cls;
b.textContent = glyph;
return b;
}
/* The four buttons as a fragment, bound to `role`, which they read and
write in place (`role.vote`), so the caller's copy is always current.
`onChange(role)` runs after every change, optimistic or reverted: the
feed dims a passed row with it. */
function judgeButtons(role, onChange) {
const fragment = document.createDocumentFragment();
const votes = STANCES.map((s) => {
const b = button(s.cls, s.glyph);
b.addEventListener("click", () => vote(s.value));
fragment.appendChild(b);
return b;
});
const star = button("star", "★");
star.addEventListener("click", () => toggleSave());
fragment.appendChild(star);
function paint() {
STANCES.forEach((s, i) => {
const on = role.vote === s.value;
const said = on ? `${s.said} — tap again to undo` : s.said;
votes[i].setAttribute("aria-pressed", String(on));
votes[i].title = said;
votes[i].setAttribute("aria-label", said);
});
const saved = tracked.has(role.uid);
const said = saved ? "Saved to Applications — tap to unsave" : "Save to Applications";
star.setAttribute("aria-pressed", String(saved));
star.title = said;
star.setAttribute("aria-label", said);
if (onChange) onChange(role);
}
async function vote(value) {
const before = role.vote ?? null;
const clearing = before === value;
role.vote = clearing ? null : value;
paint();
const path = `/api/roles/${encodeURIComponent(role.uid)}/vote`;
try {
const updated = clearing
? await api(path, { method: "DELETE" })
: await api(path, { method: "POST", body: { value } });
role.vote = updated.vote;
role.voted_at = updated.voted_at;
} catch (err) {
role.vote = before;
}
paint();
}
// One request at a time: a second tap while the first is in flight would
// unsave an application whose id has not come back yet.
async function toggleSave() {
if (star.disabled) return;
star.disabled = true;
const before = tracked.get(role.uid);
try {
if (before) {
tracked.delete(role.uid);
paint();
await api(`/api/applications/${encodeURIComponent(before.id)}`,
{ method: "DELETE" });
} else {
tracked.set(role.uid, { role_uid: role.uid });
paint();
tracked.set(role.uid, await api("/api/applications", {
method: "POST", body: { role_uid: role.uid, status: "saved" },
}));
}
} catch (err) {
if (before) tracked.set(role.uid, before);
else tracked.delete(role.uid);
} finally {
star.disabled = false;
}
paint();
}
paint();
return fragment;
}
Object.assign(window, { judgeButtons, loadTracked });
})();
+200
View File
@@ -0,0 +1,200 @@
/* The read page of one role, news's reader.
*
* The bar: back, ▲ ● ▼ ★ (judge.js, the same buttons as the feed row) and ↗
* to the posting. Then the company with its ★ ▲ ⊘ control, the one place a
* company is judged outside the Companies page; place, badges, salary when
* stated; the summary when there is one; the text, which is the fetched
* posting when there is one and the board's description otherwise; and the
* way out once more at the end.
*
* A search role's description is a teaser of a couple of hundred characters,
* so under 500 of them, with nothing fetched yet, the page offers "Fetch the
* posting" (`POST /api/roles/{uid}/text`). "Summarise" is offered while there
* is no summary (`POST /api/roles/{uid}/summarise`). Both answer with the
* role, and the page is drawn again from it. A summary made by the queue
* rather than at once is waited for by asking for the role again.
*/
(function () {
"use strict";
const { api, companies, loadCompanies, affinityControl, judgeButtons, loadTracked } = window;
const $ = (sel, root = document) => root.querySelector(sel);
const uid = $("#role").dataset.uid;
const path = `/api/roles/${encodeURIComponent(uid)}`;
/** Shorter than this and not fetched: the description is a teaser. */
const TEASER = 500;
/** @type {object|null} the role on screen, updated in place */
let role = null;
function relativeAge(iso) {
const minutes = Math.max(0, Math.floor((Date.now() - new Date(iso).getTime()) / 60000));
if (minutes < 60) return `${minutes} min ago`;
const hours = Math.floor(minutes / 60);
if (hours < 24) return `${hours} h ago`;
return `${Math.floor(hours / 24)} d ago`;
}
function salary(r) {
const n = (v) => new Intl.NumberFormat("en").format(v);
const unit = r.currency ? `${r.currency} ` : "";
if (r.salary_min && r.salary_max && r.salary_min !== r.salary_max) {
return `${unit}${n(r.salary_min)}–${n(r.salary_max)}`;
}
if (r.salary_min || r.salary_max) {
const one = r.salary_min || r.salary_max;
return r.salary_min ? `From ${unit}${n(one)}` : `Up to ${unit}${n(one)}`;
}
return "";
}
function host(url) {
try { return new URL(url).host.replace(/^www\./, ""); } catch (e) { return ""; }
}
/* Plain text in paragraphs: a fetched page keeps its line breaks, and a
board's description is one long line, which stays one paragraph. */
function paragraphs(text) {
const box = document.createDocumentFragment();
for (const part of text.split(/\n\s*\n|\n/).map((p) => p.trim()).filter(Boolean)) {
const p = document.createElement("p");
p.textContent = part;
box.appendChild(p);
}
return box;
}
function badge(text) {
const span = document.createElement("span");
span.className = "badge";
span.textContent = text;
return span;
}
function renderAffinity() {
const slot = $("#role-affinity");
const company = companies.get(role.company_key);
// A company seen only through a search has no row of its own to judge.
if (!company) { slot.replaceChildren(); return; }
slot.replaceChildren(affinityControl(role.company_key, company.affinity, renderAffinity));
}
function render() {
document.title = `${role.title || "Role"} — roledesk`;
$("#role").removeAttribute("aria-busy");
const out = role.original_url || "";
$("#role-out").hidden = !out;
if (out) $("#role-out").href = out;
const end = $("#role-out-end");
end.hidden = !out;
if (out) {
const a = end.querySelector("a");
a.href = out;
a.textContent = `Read it on ${host(out) || "the board"} ↗`;
}
$("#role-company").textContent = role.company || "";
renderAffinity();
$("#role-place").textContent = role.place || "";
$("#role-age").textContent = role.first_seen ? relativeAge(role.first_seen) : "";
$("#role-title").textContent = role.title || "(untitled)";
const badges = [role.remote, role.function, role.seniority].filter(Boolean).map(badge);
if (role.closed_at) badges.unshift(badge("closed"));
$("#role-badges").replaceChildren(...badges);
$("#role-badges").hidden = !badges.length;
const pay = salary(role);
$("#role-salary").hidden = !pay;
$("#role-salary").textContent = pay;
const summary = $("#role-summary");
summary.hidden = !role.summary;
summary.querySelector("p").textContent = role.summary || "";
const text = (role.article_text || role.description || "").trim();
$("#role-text").replaceChildren(text ? paragraphs(text)
: Object.assign(document.createElement("p"), {
className: "muted", textContent: "The board gave no description for this one.",
}));
$("#role-summarise").hidden = Boolean(role.summary);
$("#role-fetch").hidden = Boolean(role.article_text)
|| (role.description || "").length >= TEASER;
}
function merge(updated) {
if (updated && updated.uid === role.uid) Object.assign(role, updated);
render();
}
/* Press, wait, draw again from the answer. A failure is toasted by `api()`
(a 404 included, while the route is not there yet) and the button comes
back as it was. */
async function ask(button, busy, route) {
const label = button.textContent;
button.disabled = true;
button.textContent = busy;
try {
merge(await api(`${path}/${route}`, { method: "POST" }));
return true;
} catch (err) {
return false;
} finally {
button.disabled = false;
button.textContent = label;
}
}
async function summarise() {
if (!(await ask($("#role-summarise"), "Summarising…", "summarise"))) return;
if (role.summary) return;
// Queued rather than done: ask again until it is there, for two minutes.
const note = $("#role-note");
note.textContent = "The summary appears here when it is ready.";
$("#role-summarise").hidden = true;
for (let i = 0; i < 30 && !role.summary; i++) {
await new Promise((resolve) => setTimeout(resolve, 4000));
try { merge(await api(path)); } catch (err) { break; }
}
note.textContent = "";
render();
}
/* Back is back when this page was opened from one of this app's lists, so
the list keeps its place; a link from anywhere else goes to the roles. */
function back(e) {
let from = null;
try { from = document.referrer ? new URL(document.referrer) : null; } catch (err) { /* */ }
if (from && from.origin === location.origin && history.length > 1) {
e.preventDefault();
history.back();
}
}
/* The bar sticks under the top bar, whose height is the phone's or the
desktop's, and the notch's on a standalone phone. */
function measureHeader() {
const top = document.querySelector("header.top");
if (top) document.documentElement.style.setProperty("--header-h", `${top.offsetHeight}px`);
}
document.addEventListener("DOMContentLoaded", async () => {
measureHeader();
window.addEventListener("resize", measureHeader);
$("#role-back").addEventListener("click", back);
try {
[role] = await Promise.all([api(path), loadCompanies(), loadTracked()]);
} catch (err) {
$("#role-title").textContent = "This role could not be loaded.";
return;
}
$("#role-judge").appendChild(judgeButtons(role));
render();
$("#role-summarise").addEventListener("click", summarise);
$("#role-fetch").addEventListener("click",
() => ask($("#role-fetch"), "Fetching…", "text"));
});
})();
+190 -65
View File
@@ -1,32 +1,56 @@
/* The Roles tab: the filter bar and the list of open roles.
/* The Roles tab: the filter bar and the feed of open roles.
*
* The template renders an empty shell; everything on screen comes from the
* JSON routes in app/web/api.py, and every action (Save, an affinity click)
* is a fetch from here, not a form post. The company list and its affinity
* control are app.js's, shared with the Companies page.
* JSON routes in app/web/api.py. A row is news's feed row: the title (a link
* to the read page), company · place · age, the badges, a one-line excerpt,
* and ▲ ● ▼ ★ from judge.js. The company is not judged here; that is the
* Companies page and the read page.
*
* The list is paged: 60 rows, then 60 more each time a sentinel under the
* list comes within 600px of the screen (news's `loadFeed`), with the offset
* the rows already shown. Going back from a read page puts the same rows and
* the same scroll position back, from sessionStorage.
*
* Every request goes through `api()` from app.js, so a failure is one toast
* carrying the server's own sentence. The catch blocks here only put the
* control back the way it was.
* carrying the server's own sentence.
*/
(function () {
"use strict";
const { api, count, debounce, companies, loadCompanies, affinityControl } = window;
const { api, debounce, companies, loadCompanies, judgeButtons, loadTracked } = window;
/** @type {Map<string, object>} role_uid -> application, for roles already tracked */
let trackedByRole = new Map();
/** @type {object[]} the last /api/roles response, already muted-filtered by the server */
let roles = [];
const PAGE = 60;
/** What the list was when a read page was opened from it. */
const KEPT = "roledesk.roles";
/** @type {object[]} the rows on screen, in order */
let items = [];
/** How many roles the filters match in all. */
let total = 0;
/** @type {object[]} the enabled rankings, from /api/agents */
let agents = [];
let loading = false;
let request = 0;
const $ = (sel, root = document) => root.querySelector(sel);
const number = new Intl.NumberFormat("en");
async function loadApplications() {
const applications = await api("/api/applications");
trackedByRole = new Map(applications.filter((a) => a.role_uid).map((a) => [a.role_uid, a]));
}
/* Every field of the filter bar, by id, and what it holds when unset. */
const FIELDS = ["f-agent", "f-q", "f-company", "f-place", "f-function", "f-remote",
"f-days", "f-judged", "f-show-muted", "f-gated"];
/* The ones inside Filters, which the summary counts. */
const PANEL = ["f-company", "f-place", "f-function", "f-remote", "f-days", "f-judged",
"f-show-muted", "f-gated"];
const read = (id) => {
const el = document.getElementById(id);
return el.type === "checkbox" ? el.checked : el.value;
};
const write = (id, value) => {
const el = document.getElementById(id);
if (el.type === "checkbox") el.checked = Boolean(value);
else el.value = value;
};
async function loadAgents() {
agents = (await api("/api/agents")).filter((a) => a.enabled);
@@ -38,7 +62,7 @@
const value = $(`#f-${key}`).value.trim();
if (value) params.set(key, value);
}
for (const key of ["function", "remote", "days"]) {
for (const key of ["function", "remote", "days", "judged"]) {
const value = $(`#f-${key}`).value;
if (value) params.set(key, value);
}
@@ -51,13 +75,48 @@
return params;
}
async function loadRoles() {
/* A reload starts the list again; an append asks for the rows after the
ones shown. `keep` asks for that many in one go, which is how the list is
put back as it was. The latch is let go only by the newest request: a
reload overtaking an append must not let a second append start with an
offset into the list being replaced. */
async function load({ append = false, keep = 0 } = {}) {
if (append && (loading || items.length >= total)) return;
const params = filterParams();
params.set("offset", String(append ? items.length : 0));
params.set("limit", String(Math.min(1000, Math.max(PAGE, keep))));
const mine = ++request;
loading = true;
let data;
try {
roles = await api(`/api/roles?${filterParams().toString()}`);
data = await api(`/api/roles?${params}`);
} catch (err) {
return;
} finally {
if (mine === request) loading = false;
}
renderRoles();
if (mine !== request) return;
total = data.total;
if (append) {
items = items.concat(data.items);
renderRows(data.items);
} else {
items = data.items;
$("#roles-list").replaceChildren();
renderRows(items);
}
renderCount();
// Still within reach of the sentinel after a short page: the observer
// only fires on a change, and nothing changed, so ask again here.
requestAnimationFrame(() => {
const end = $("#roles-end").getBoundingClientRect();
if (end.top < window.innerHeight + 600) load({ append: true });
});
}
function reload() {
load().then(() => window.scrollTo(0, 0));
renderActive();
}
function relativeAge(iso) {
@@ -69,67 +128,72 @@
return `${Math.floor(hours / 24)} d ago`;
}
function renderRoles() {
/* The summary when there is one, else the description's opening, cut at a
word. One line on screen; the stylesheet clips it. */
function excerpt(role) {
if (role.summary) return role.summary;
const text = (role.description || "").trim();
if (text.length <= 160) return text;
const cut = text.slice(0, 160);
const space = cut.lastIndexOf(" ");
return `${(space > 100 ? cut.slice(0, space) : cut).replace(/[\s,.;:–-]+$/, "")}…`;
}
/* A passed role and a hidden company's are dimmed, never dropped: the pass
has to stay visible to be undone. */
function dim(li, role) {
const company = companies.get(role.company_key);
li.classList.toggle("muted", Boolean(company && company.affinity === -1));
li.classList.toggle("passed", role.vote === -1);
}
function renderRows(rows) {
const list = $("#roles-list");
const template = $("#role-row");
list.replaceChildren();
for (const role of roles) {
for (const role of rows) {
const node = template.content.cloneNode(true);
const li = node.querySelector(".role");
const company = companies.get(role.company_key);
li.dataset.uid = role.uid;
if (company && company.affinity === -1) li.classList.add("muted");
const titleLink = node.querySelector(".role-title");
titleLink.textContent = role.title || "(untitled)";
titleLink.href = role.original_url || "#";
const title = node.querySelector(".role-title");
title.textContent = role.title || "(untitled)";
title.href = `/roles/${encodeURIComponent(role.uid)}`;
node.querySelector(".role-company").textContent = role.company || "";
node.querySelector(".role-place").textContent = role.place || "";
node.querySelector(".role-age").textContent = relativeAge(role.first_seen);
node.querySelector(".role-remote").textContent = role.remote || "";
node.querySelector(".role-function").textContent = role.function || "";
node.querySelector(".role-age").textContent = relativeAge(role.first_seen);
if (role.score !== null && role.score !== undefined) {
const badge = node.querySelector(".role-score");
badge.textContent = role.gated_reason ? "gated" : role.score.toFixed(2);
badge.title = "Match";
badge.textContent = role.gated_reason ? "gated" : `match ${Math.round(role.score * 100)}`;
badge.title = role.gated_reason ? "Kept out of the ranking" : "How well it matches, of 100";
node.querySelector(".role-gated").textContent = role.gated_reason || "";
if (role.gated_reason) li.classList.add("gated");
}
node.querySelector(".role-excerpt").textContent = excerpt(role);
node.querySelector(".affinity").replaceWith(
affinityControl(role.company_key, company ? company.affinity : 0, loadRoles));
const saveButton = node.querySelector(".save");
setSaveButton(saveButton, role.uid);
saveButton.addEventListener("click", () => saveRole(role.uid, saveButton));
node.querySelector(".role-actions").appendChild(judgeButtons(role, () => dim(li, role)));
list.appendChild(node);
}
$("#roles-count").textContent = count(roles.length, "role");
}
function setSaveButton(button, uid) {
const saved = trackedByRole.has(uid);
button.textContent = saved ? "Saved" : "Save";
button.disabled = saved;
function renderCount() {
const noun = total === 1 ? "role" : "roles";
$("#roles-count").textContent = items.length < total
? `${number.format(items.length)} of ${number.format(total)} ${noun}`
: `${number.format(total)} ${noun}`;
}
async function saveRole(uid, button) {
button.disabled = true;
button.textContent = "Saving…";
try {
const application = await api("/api/applications", {
method: "POST", body: { role_uid: uid, status: "saved" },
});
trackedByRole.set(uid, application);
setSaveButton(button, uid);
} catch (err) {
button.disabled = false;
button.textContent = "Save";
}
/* How many filters inside the panel are set, on its summary, so a closed
panel still says the list is narrowed. */
function renderActive() {
const set = PANEL.filter((id) => {
if (id === "f-gated" && $("#show-gated").hidden) return false;
const value = read(id);
return typeof value === "boolean" ? value : value.trim() !== "";
}).length;
$("#f-active").textContent = set ? `· ${set}` : "";
}
/* The filter bar's order: Newest, or a ranking's score. One ranking is the
@@ -155,6 +219,7 @@
for (const key of ["q", "company", "place"]) {
if (query.get(key)) $(`#f-${key}`).value = query.get(key);
}
if (query.get("company") || query.get("place")) $("#f-more").open = true;
const agent = query.get("agent");
if (agent && agents.some((a) => String(a.id) === agent)) {
$("#f-agent").value = agent;
@@ -162,27 +227,87 @@
}
}
// ------------------------------------------------ back from a read page
function keep() {
const filters = {};
for (const id of FIELDS) filters[id] = read(id);
try {
sessionStorage.setItem(KEPT, JSON.stringify({
filters, count: items.length, y: window.scrollY, open: $("#f-more").open,
}));
} catch (err) { /* private mode: back is a fresh list, which is fine */ }
}
function kept() {
try {
return JSON.parse(sessionStorage.getItem(KEPT) || "null");
} catch (err) {
return null;
}
}
function cameBack() {
const [entry] = performance.getEntriesByType("navigation");
return Boolean(entry && entry.type === "back_forward");
}
async function restore(state) {
for (const [id, value] of Object.entries(state.filters || {})) {
if (document.getElementById(id)) write(id, value);
}
if (!agents.some((a) => String(a.id) === $("#f-agent").value)) write("f-agent", "");
$("#show-gated").hidden = !$("#f-agent").value;
$("#f-more").open = Boolean(state.open);
renderActive();
await load({ keep: state.count || PAGE });
window.scrollTo(0, state.y || 0);
}
document.addEventListener("DOMContentLoaded", async () => {
try {
await Promise.all([loadCompanies(), loadApplications(), loadAgents()]);
await Promise.all([loadCompanies(), loadTracked(), loadAgents()]);
} catch (err) {
return;
}
renderAgentSelect();
prefill();
await loadRoles();
const state = cameBack() ? kept() : null;
if (state) {
await restore(state);
} else {
prefill();
renderActive();
await load();
}
const refetch = debounce(loadRoles, 300);
new IntersectionObserver((entries) => {
if (entries.some((e) => e.isIntersecting)) load({ append: true });
}, { rootMargin: "600px" }).observe($("#roles-end"));
const refetch = debounce(reload, 300);
for (const key of ["q", "company", "place"]) {
$(`#f-${key}`).addEventListener("input", refetch);
}
for (const sel of ["#f-function", "#f-remote", "#f-days", "#f-show-muted", "#f-gated"]) {
$(sel).addEventListener("change", loadRoles);
for (const sel of ["#f-function", "#f-remote", "#f-days", "#f-judged", "#f-show-muted",
"#f-gated"]) {
$(sel).addEventListener("change", reload);
}
$("#f-agent").addEventListener("change", () => {
$("#show-gated").hidden = !$("#f-agent").value;
loadRoles();
reload();
});
$("#filters").addEventListener("submit", (e) => e.preventDefault());
// Kept on the way out, whichever way that is, so back finds it.
window.addEventListener("pagehide", keep);
// Back from the read page without a reload (the back/forward cache): the
// rows are the ones left, but a vote or a star may have changed there.
window.addEventListener("pageshow", async (e) => {
if (!e.persisted) return;
const y = window.scrollY;
await Promise.all([loadTracked(), loadCompanies()]).catch(() => {});
await load({ keep: items.length });
window.scrollTo(0, y);
});
});
})();
+88 -11
View File
@@ -48,6 +48,23 @@ GIVE_UP_AFTER = 3
_EXTRACT_WAITING = (f"extracted_at IS NULL AND closed_at IS NULL "
f"AND extract_tries < {GIVE_UP_AFTER}")
#: What a vote may be: 1 like, 0 neither way, -1 pass, None unjudged.
VOTES = (-1, 0, 1, None)
#: The `judged` filter of `Store.roles`, as a `WHERE` on `roles.vote`. A
#: neutral vote is judged, and is neither liked nor passed.
JUDGED: dict[str, str] = {
"liked": "roles.vote = 1",
"unjudged": "roles.vote IS NULL",
"passed": "roles.vote = -1",
}
#: A ranking's score as `Store.roles` serves and orders it: halved by a pass,
#: lifted a fifth by a like, capped at 1. Applied at read time, so a vote
#: moves the role at once and the stored score stays what `score` computed.
_VOTED_SCORE = ("MIN(1.0, s.score * CASE roles.vote WHEN -1 THEN 0.5 "
"WHEN 1 THEN 1.2 ELSE 1 END)")
_COMPANY_FIELDS = ("name", "domain", "affinity", "status", "careers_url", "notes")
_SUBSCRIPTION_FIELDS = ("label", "company", "board", "params", "subscribed", "fetch",
"show", "target_id")
@@ -267,18 +284,35 @@ class Store:
row = self._row("SELECT * FROM roles WHERE uid=?", (uid,))
return Role.from_row(row) if row else None
def set_vote(self, uid: str, value: int | None) -> Role:
"""Judge one role: 1 like, 0 neither way, -1 pass, None unjudged again.
Stamps `voted_at`, or clears it with the vote. A vote never hides a
role; it moves it in a ranking (see `roles`). Raises ValueError for
another value and KeyError for an unknown uid."""
if isinstance(value, bool) or value not in VOTES:
raise ValueError(f"a vote is -1, 0 or 1, not {value!r}")
stamp = None if value is None else self.now()
if not self._write("UPDATE roles SET vote=?, voted_at=? WHERE uid=?",
(value, stamp, uid)):
raise KeyError(uid)
role = self.role(uid)
assert role is not None
return role
def roles(self, limit: int = 100, company: str | None = None,
place: str | None = None, open_only: bool = True,
q: str | None = None, function: str | None = None,
remote: str | None = None, days: int | None = None,
hide_muted: bool = False, agent: int | None = None,
gated: bool = False) -> list[ScoredRole]:
gated: bool = False, judged: str | None = None,
offset: int = 0) -> list[ScoredRole]:
"""Newest first by `first_seen`. `company` and `place` are
case-insensitive substrings of the columns a board wrote — not the
key, so a search does not have to know the exact slug a company folds
to. `q` is matched word by word against `title`; a role must match
every word. `function` and `remote` match a gate column exactly.
`days` keeps only roles first seen within that many days of now.
`judged` is a key of `JUDGED`: liked, unjudged or passed.
`hide_muted` excludes a muted company's roles before `limit` is
applied, in SQL rather than after the fact: a company that has
@@ -290,8 +324,47 @@ class Store:
`agent` orders by that agent's score instead, highest first, and
carries `score` and `gated_reason` on each row. Only roles it has
scored are listed, and a gated one only when `gated` is set."""
where, params = [], []
scored are listed, and a gated one only when `gated` is set. The score
is the stored one moved by the role's vote (`_VOTED_SCORE`), so a vote
shows in the order at once and needs no rescore.
`offset` skips that many rows of the same order, for the page that
loads the next 60 as it is scrolled; `count_roles` is the total."""
sql, params = self._roles_from(
company=company, place=place, open_only=open_only, q=q, function=function,
remote=remote, days=days, hide_muted=hide_muted, agent=agent, gated=gated,
judged=judged)
if agent is None:
select = "SELECT roles.* "
order = "roles.first_seen DESC, roles.uid"
else:
select = f"SELECT roles.*, {_VOTED_SCORE} AS score, s.gated_reason "
order = "score DESC, roles.first_seen DESC, roles.uid"
return [ScoredRole.from_row(r) for r in self._rows(
f"{select}{sql} ORDER BY {order} LIMIT ? OFFSET ?", [*params, limit, offset])]
def count_roles(self, company: str | None = None, place: str | None = None,
open_only: bool = True, q: str | None = None,
function: str | None = None, remote: str | None = None,
days: int | None = None, hide_muted: bool = False,
agent: int | None = None, gated: bool = False,
judged: str | None = None) -> int:
"""How many roles `roles` would list with the same filters and no limit."""
sql, params = self._roles_from(
company=company, place=place, open_only=open_only, q=q, function=function,
remote=remote, days=days, hide_muted=hide_muted, agent=agent, gated=gated,
judged=judged)
row = self._row(f"SELECT COUNT(*) AS n {sql}", params)
return int(row["n"]) if row else 0
def _roles_from(self, *, company: str | None, place: str | None, open_only: bool,
q: str | None, function: str | None, remote: str | None,
days: int | None, hide_muted: bool, agent: int | None,
gated: bool, judged: str | None) -> tuple[str, list[Any]]:
"""The `FROM ... WHERE ...` that `roles` and `count_roles` share, with
its parameters in order."""
where: list[str] = []
params: list[Any] = []
if company:
where.append("company LIKE ? ESCAPE '\\'")
params.append(_like(company))
@@ -310,6 +383,10 @@ class Store:
for word in (q or "").split():
where.append("title LIKE ? ESCAPE '\\'")
params.append(_like(word))
if judged:
if judged not in JUDGED:
raise ValueError(f"judged is {', '.join(JUDGED)}, not {judged!r}")
where.append(JUDGED[judged])
if open_only:
where.append("closed_at IS NULL")
if hide_muted:
@@ -317,20 +394,15 @@ class Store:
"(SELECT key FROM companies WHERE affinity = -1)")
joins: list[Any] = []
if agent is None:
sql = "SELECT roles.* FROM roles"
order = "roles.first_seen DESC, roles.uid"
sql = "FROM roles"
else:
sql = ("SELECT roles.*, s.score, s.gated_reason FROM roles "
"JOIN scores s ON s.uid = roles.uid AND s.agent_id = ?")
sql = "FROM roles JOIN scores s ON s.uid = roles.uid AND s.agent_id = ?"
joins.append(agent)
if not gated:
where.append("s.gated_reason = ''")
order = "s.score DESC, roles.first_seen DESC, roles.uid"
if where:
sql += " WHERE " + " AND ".join(where)
sql += f" ORDER BY {order} LIMIT ?"
return [ScoredRole.from_row(r)
for r in self._rows(sql, [*joins, *params, limit])]
return sql, [*joins, *params]
def mark_closed(self, source: str, seen_ids: Sequence[str],
subscription_id: int) -> int:
@@ -781,6 +853,11 @@ class Store:
row = self._row("SELECT * FROM applications WHERE id=?", (app_id,))
return Application.from_row(row) if row else None
def delete_application(self, app_id: str) -> bool:
"""Drop one application and its events. Whether that is allowed (only
while it is still `saved`) is the caller's rule, not the store's."""
return self._write("DELETE FROM applications WHERE id=?", (app_id,)) > 0
def applications(self, status: str | None = None) -> list[Application]:
sql, params = "SELECT * FROM applications", []
if status:
+3 -3
View File
@@ -3,12 +3,12 @@
{% block content %}
<h1>Applications</h1>
<p class="lede">Every role you saved on the Roles tab, and where it stands. Change the status as it moves.</p>
<p class="lede">The roles you starred, and where each one stands. Change the status as it moves; while it is still Saved, unstarring the role drops it from here.</p>
<p id="applications-count" class="count" role="status"></p>
<table class="list">
<table class="list applications">
<thead>
<tr><th>Role</th><th>Company</th><th>Status</th><th>Next</th></tr>
<tr><th>Role</th><th>Company</th><th>Status</th><th>Saved</th></tr>
</thead>
<tbody id="applications-list"></tbody>
</table>
+47
View File
@@ -0,0 +1,47 @@
{% extends "base.html" %}
{% block title %}Role — roledesk{% endblock %}
{# The read page of one role, news's reader: a bar with the back arrow,
▲ ● ▼ ★ and ↗, then the posting. An empty shell like every page;
`static/role.js` fetches `/api/roles/{uid}` and fills it. #}
{% block content %}
<article id="role" class="reader" data-uid="{{ uid }}" aria-busy="true">
<div class="reader-bar">
<a class="reader-back" id="role-back" href="/" title="Back to the roles"
aria-label="Back to the roles">←</a>
<span class="judge" id="role-judge"></span>
<span class="spacer"></span>
<a class="reader-external" id="role-out" target="_blank" rel="noopener"
title="Open the posting" aria-label="Open the posting" hidden>↗</a>
</div>
<div class="reader-body">
<div class="reader-meta">
<b id="role-company"></b>
<span id="role-affinity"></span>
<span id="role-place"></span>
<span id="role-age"></span>
</div>
<h1 id="role-title">Loading…</h1>
<div class="role-badges" id="role-badges"></div>
<p class="reader-salary" id="role-salary" hidden></p>
<section class="reader-summary" id="role-summary" hidden>
<h2 class="reader-label">Summary</h2>
<p></p>
</section>
<div class="reader-tools">
<button type="button" class="secondary" id="role-summarise" hidden>Summarise</button>
<button type="button" class="secondary" id="role-fetch" hidden>Fetch the posting</button>
<span class="muted small" id="role-note" role="status"></span>
</div>
<div class="prose" id="role-text"></div>
<p class="reader-out" id="role-out-end" hidden>
<a target="_blank" rel="noopener"></a>
</p>
</div>
</article>
{% endblock %}
{% block scripts %}
<script src="{{ asset('judge.js') }}"></script>
<script src="{{ asset('role.js') }}"></script>
{% endblock %}
+68 -46
View File
@@ -3,65 +3,87 @@
{# An empty shell: `static/roles.js` fills it and drives every action. The
server renders only the select options, from `app.models` and
`plugins.ats.FUNCTIONS`, so they cannot drift from what the store accepts. #}
`plugins.ats.FUNCTIONS`, so they cannot drift from what the store accepts.
The bar is one row at any width: the order, the search box, and a Filters
toggle. The toggle is a `<details>` whose summary is lifted into that row
by the stylesheet, so the panel it opens is in the flow under the row and
pushes the list down rather than covering it. #}
{% block content %}
<form id="filters" class="filters" autocomplete="off">
<select id="f-agent" aria-label="Order">
<option value="">Newest</option>
</select>
<input type="search" id="f-q" placeholder="Search titles" aria-label="Search titles">
<input type="text" id="f-company" placeholder="Company" aria-label="Company">
<input type="text" id="f-place" placeholder="Place" aria-label="Place">
<select id="f-function" aria-label="Function">
<option value="">Any function</option>
{% for value, label in functions %}
<option value="{{ value }}">{{ label }}</option>
{% endfor %}
</select>
<select id="f-remote" aria-label="Remote">
<option value="">Any remote</option>
{% for value, label in remote_options %}
<option value="{{ value }}">{{ label }}</option>
{% endfor %}
</select>
<select id="f-days" aria-label="New in">
<option value="">Any time</option>
<option value="1">New in 1 day</option>
<option value="3">New in 3 days</option>
<option value="7">New in 7 days</option>
<option value="30">New in 30 days</option>
</select>
<label class="check">
<input type="checkbox" id="f-show-muted"> Show muted
</label>
<label class="check" id="show-gated" hidden>
<input type="checkbox" id="f-gated"> Show gated
</label>
<form id="filters" class="filters roles-filters" autocomplete="off">
<div class="filter-line">
<select id="f-agent" aria-label="Order">
<option value="">Newest</option>
</select>
<input type="search" id="f-q" placeholder="Search titles" aria-label="Search titles">
</div>
<details id="f-more" class="filter-more">
<summary>Filters<span id="f-active" class="filter-active"></span></summary>
<div class="filter-panel">
<input type="text" id="f-company" placeholder="Company" aria-label="Company">
<input type="text" id="f-place" placeholder="Place" aria-label="Place">
<select id="f-function" aria-label="Function">
<option value="">Any function</option>
{% for value, label in functions %}
<option value="{{ value }}">{{ label }}</option>
{% endfor %}
</select>
<select id="f-remote" aria-label="Remote">
<option value="">Any remote</option>
{% for value, label in remote_options %}
<option value="{{ value }}">{{ label }}</option>
{% endfor %}
</select>
<select id="f-days" aria-label="New in">
<option value="">Any time</option>
<option value="1">New in 1 day</option>
<option value="3">New in 3 days</option>
<option value="7">New in 7 days</option>
<option value="30">New in 30 days</option>
</select>
<select id="f-judged" aria-label="Judged">
<option value="">Any vote</option>
<option value="liked">Liked</option>
<option value="unjudged">Unjudged</option>
<option value="passed">Passed</option>
</select>
<label class="check">
<input type="checkbox" id="f-show-muted"> Show hidden companies
</label>
<label class="check" id="show-gated" hidden>
<input type="checkbox" id="f-gated"> Show gated
</label>
</div>
</details>
</form>
<p id="roles-count" class="count" role="status"></p>
<ul id="roles-list" class="roles"></ul>
<div id="roles-end" class="roles-end" aria-hidden="true"></div>
<template id="role-row">
<li class="role">
<div class="role-main">
<a class="role-title" target="_blank" rel="noopener"></a>
<span class="role-company"></span>
<span class="affinity" role="group"></span>
<div class="role-body">
<a class="role-title"></a>
<div class="role-meta">
<b class="role-company"></b>
<span class="role-place"></span>
<span class="role-age"></span>
</div>
<div class="role-badges">
<span class="role-remote badge"></span>
<span class="role-function badge"></span>
<span class="role-score badge"></span>
<span class="role-gated"></span>
</div>
<p class="role-excerpt"></p>
</div>
<div class="role-meta">
<span class="role-place"></span>
<span class="role-remote badge"></span>
<span class="role-function badge"></span>
<span class="role-score badge"></span>
<span class="role-gated"></span>
<span class="role-age"></span>
</div>
<button type="button" class="save"></button>
<div class="role-actions judge"></div>
</li>
</template>
{% endblock %}
{% block scripts %}
<script src="{{ asset('judge.js') }}"></script>
<script src="{{ asset('roles.js') }}"></script>
{% endblock %}
+76 -18
View File
@@ -9,15 +9,15 @@ This is roledesk's own API, over the same store. Every refusal is
from __future__ import annotations
from datetime import timedelta
from typing import Annotated, Any
from typing import Annotated, Any, Literal
from fastapi import APIRouter, HTTPException, Query, Response
from pydantic import BaseModel, Field
from app import jobs
from app.models import (
AFFINITY, Agent, Application, Company, Gate, ScoredRole, Status, Subscription, Weights,
AFFINITY, Agent, Application, Company, Gate, Role, ScoredRole, Status, Subscription,
Weights,
)
from app.storage import Store
from app.web.deps import ConfigDep, StoreDep
@@ -27,6 +27,45 @@ router = APIRouter(prefix="/api", tags=["roledesk"])
# ------------------------------------------------------------------- roles
class VoteBody(BaseModel):
value: Literal[-1, 0, 1]
@router.get("/roles/{uid}")
def get_role(uid: str, store: StoreDep) -> Role:
"""One role, open or closed, for the read page."""
role = store.role(uid)
if role is None:
raise HTTPException(404, f"no such role: {uid}")
return role
@router.post("/roles/{uid}/vote")
def vote_role(uid: str, body: VoteBody, store: StoreDep) -> Role:
"""1 like, 0 neither way, -1 pass. The role stays listed either way; the
vote moves it in a ranking, see `Store.roles`."""
try:
return store.set_vote(uid, body.value)
except KeyError:
raise HTTPException(404, f"no such role: {uid}") from None
@router.delete("/roles/{uid}/vote")
def unvote_role(uid: str, store: StoreDep) -> Role:
"""Unjudged again: what pressing the stance a role already has does."""
try:
return store.set_vote(uid, None)
except KeyError:
raise HTTPException(404, f"no such role: {uid}") from None
class RolesPage(BaseModel):
"""One page of roles, and how many the same filters match in all."""
items: list[ScoredRole]
total: int
@router.get("/roles")
def list_roles(
store: StoreDep,
@@ -39,19 +78,26 @@ def list_roles(
show_muted: bool = False,
agent: int | None = None,
gated: bool = False,
limit: Annotated[int, Query(ge=1, le=1000)] = 200,
) -> list[ScoredRole]:
"""Open roles, newest first. See `Store.roles` for what each filter does.
judged: Literal["", "liked", "unjudged", "passed"] = "",
offset: Annotated[int, Query(ge=0)] = 0,
limit: Annotated[int, Query(ge=1, le=1000)] = 60,
) -> RolesPage:
"""Open roles, newest first, `limit` of them from `offset`, with the
total. See `Store.roles` for what each filter does.
A muted company's roles are left out unless `show_muted` is set. With
`agent`, ordered by that agent's score and carrying `score` and
`gated_reason`; a gated role only with `gated=1`."""
`agent`, ordered by that agent's score moved by the role's vote, and
carrying `score` and `gated_reason`; a gated role only with `gated=1`.
`judged` keeps the liked, the unjudged or the passed."""
if agent is not None and store.agent(agent) is None:
raise HTTPException(404, f"no such agent: {agent}")
return store.roles(limit=limit, q=q or None, company=company or None,
place=place or None, function=function or None,
remote=remote or None, days=days, hide_muted=not show_muted,
agent=agent, gated=gated)
filters: dict[str, Any] = {
"q": q or None, "company": company or None, "place": place or None,
"function": function or None, "remote": remote or None, "days": days,
"hide_muted": not show_muted, "agent": agent, "gated": gated,
"judged": judged or None}
return RolesPage(items=store.roles(limit=limit, offset=offset, **filters),
total=store.count_roles(**filters))
# --------------------------------------------------------------- companies
@@ -258,23 +304,35 @@ class SaveBody(BaseModel):
@router.post("/applications", status_code=201)
def save_role(body: SaveBody, store: StoreDep) -> Application:
"""Track one role. Pressing Save twice does not double-track it: the
existing row comes back rather than a second one starting at `saved`
over whatever status it has since moved to."""
"""Track one role: the ★ on a role. Pressing it twice does not
double-track it: the existing row comes back rather than a second one
starting at `saved` over whatever status it has since moved to."""
existing = next((a for a in store.applications() if a.role_uid == body.role_uid), None)
if existing is not None:
return existing
role = store.role(body.role_uid)
if role is None:
raise HTTPException(404, f"no such role: {body.role_uid}")
next_date = (store.clock() + timedelta(days=2)).date().isoformat()
application = Application(
role_uid=role.uid, company_key=role.company_key, role_title=role.title,
url=role.original_url, status=body.status, source=role.source,
next_action="Read the posting and decide", next_date=next_date)
url=role.original_url, status=body.status, source=role.source)
return store.save_application(application)
@router.delete("/applications/{app_id}", status_code=204)
def unsave_role(app_id: str, store: StoreDep) -> Response:
"""The ★ pressed again. Only while the application is still `saved`: once
it has moved on, it is history, and withdrawn is the status for that."""
application = store.application(app_id)
if application is None:
raise HTTPException(404, f"no such application: {app_id}")
if application.status != "saved":
raise HTTPException(409, f"This application is at {application.status} already, "
"so it stays. Set it to withdrawn instead.")
store.delete_application(app_id)
return Response(status_code=204)
@router.get("/applications")
def list_applications(store: StoreDep) -> list[Application]:
"""Every tracked application, with the role title and company key it was
+12 -1
View File
@@ -31,11 +31,12 @@ from collections.abc import Callable
from dataclasses import dataclass
from pathlib import Path
from fastapi import APIRouter, Request
from fastapi import APIRouter, HTTPException, Request
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.templating import Jinja2Templates
from app.models import REMOTE, STATUSES
from app.web.deps import StoreDep
_ROOT = Path(__file__).resolve().parents[2]
if str(_ROOT) not in sys.path:
@@ -121,6 +122,16 @@ def roles(request: Request) -> HTMLResponse:
remote_options=REMOTE_OPTIONS)
@router.get("/roles/{uid}", response_class=HTMLResponse)
def role(request: Request, uid: str, store: StoreDep) -> HTMLResponse:
"""The read page of one role. A shell like the others, filled by
`role.js`; the lookup here only makes an unknown uid a 404 page rather
than an empty one."""
if store.role(uid) is None:
raise HTTPException(404, f"no such role: {uid}")
return page(request, "role.html", uid=uid)
@router.get("/applications", response_class=HTMLResponse)
def applications(request: Request) -> HTMLResponse:
return page(request, "applications.html", status_options=STATUS_OPTIONS)