Files
jobboard/app/static/watchlist.js
T

438 lines
16 KiB
JavaScript

/* The Watchlist tab: the companies the app cannot read a board of, for
* going through their careers pages by hand.
*
* The list is app.js's shared company list (`/api/companies`), narrowed to
* the by-hand list (`by_hand`: no board shown, not known from a search only),
* plus every company whose board is failing. The rating (`watch`: null
* unrated, 1 yes, 0 no) is global, not a search agent's affinity, and is set
* with `POST .../watch`. Opening the careers page stamps `careers_opened_at`
* (`POST .../opened`), so the row can say when, and the On the list filter
* sorts what was opened longest ago first. The filter is remembered per
* browser, and opens on Unrated.
*
* New company and Edit are the Job boards form of Sources (sources.js): Edit
* turns a row into the form from the page's `<template>`, in place, New puts
* a blank one on top, one is open at a time, and Save and Cancel put it
* away. New is `POST /api/companies`, Edit a `PATCH` of the fields that
* changed, and Remove a `DELETE`; a refusal is `api()`'s toast with the
* server's sentence, and the catch blocks here only put a control back.
*/
(function () {
"use strict";
const { api, count, debounce, safeUrl, companies, loadCompanies } = window;
const $ = (sel, root = document) => root.querySelector(sel);
const FILTER = "roledesk.watchlist";
const FILTERS = [
["unrated", "Unrated"], ["yes", "On the list"], ["no", "Not on the list"], ["all", "All"],
];
const DAY = 24 * 60 * 60 * 1000;
const NEW = "new";
/** @type {string | "new" | null} the row in edit mode: a company's key,
* NEW for the blank form on top, null for none */
let editing = null;
/** @type {HTMLFormElement | null} that form, kept across renders so a
* rating set on another row does not wipe what is being typed */
let editor = null;
function savedFilter() {
try {
const value = localStorage.getItem(FILTER);
return FILTERS.some(([f]) => f === value) ? value : "unrated";
} catch (err) {
return "unrated";
}
}
function saveFilter(value) {
try { localStorage.setItem(FILTER, value); } catch (err) { /* not remembered */ }
}
/** On the by-hand list: the server says so, or, from a server without
`by_hand`, no board and not known from a search only. */
function byHand(company) {
return "by_hand" in company
? Boolean(company.by_hand)
: company.subscription_id == null && !company.from_search;
}
/** The companies the tab is about, before any filter. */
function watched() {
return [...companies.values()].filter((c) => byHand(c) || c.failing_since);
}
function matchesFilter(company, filter) {
switch (filter) {
case "unrated": return company.watch == null;
case "yes": return company.watch === 1;
case "no": return company.watch === 0;
default: return true;
}
}
/** A `hand_reason` in words, from the options the page rendered into the
form: "no reader yet". "" for none given. */
function reasonWords(value) {
if (!value) return "";
const option = [...$("#company-form-template").content.querySelector("#cf-reason").options]
.find((o) => o.value === value);
const label = option ? option.textContent : value;
return label.charAt(0).toLowerCase() + label.slice(1);
}
function matchesQuery(company, q) {
return !q || company.name.toLowerCase().includes(q)
|| (company.board || company.ats || "").includes(q)
|| (company.country || "").toLowerCase() === q
|| (company.notes || "").toLowerCase().includes(q)
|| reasonWords(company.hand_reason).includes(q);
}
function ago(iso) {
if (!iso) return "not opened yet";
const days = Math.floor((Date.now() - new Date(iso).getTime()) / DAY);
if (Number.isNaN(days)) return "not opened yet";
if (days < 1) return "opened today";
return `opened ${count(days, "day")} ago`;
}
/** Where the link goes: the careers page, else the company's own site. */
function target(company) {
const careers = safeUrl(company.careers_url);
if (careers) return { url: careers, label: "Careers page" };
const site = company.domain ? safeUrl(`https://${company.domain}`) : "";
return site ? { url: site, label: "Website" } : null;
}
async function rate(company, watch, rerender) {
try {
const updated = await api(`/api/companies/${encodeURIComponent(company.key)}/watch`, {
method: "POST", body: { watch },
});
company.watch = updated.watch;
} catch (err) {
return;
}
rerender();
}
/** Yes and No, in `.affinity`'s look; pressing the pressed one clears it. */
function ratingControl(company, rerender) {
const span = document.createElement("span");
span.className = "affinity";
span.setAttribute("role", "group");
span.setAttribute("aria-label", `Watch ${company.name}`);
for (const [value, label, watch] of [[1, "Yes", true], [-1, "No", false]]) {
const pressed = company.watch === (watch ? 1 : 0);
const button = document.createElement("button");
button.type = "button";
button.dataset.value = String(value);
button.textContent = label;
button.setAttribute("aria-pressed", String(pressed));
button.addEventListener("click", () => rate(company, pressed ? null : watch, rerender));
span.appendChild(button);
}
return span;
}
function badge(text) {
const span = document.createElement("span");
span.className = "badge";
span.textContent = text;
return span;
}
function linky(text, onClick) {
const button = document.createElement("button");
button.type = "button";
button.className = "linky";
button.textContent = text;
button.addEventListener("click", () => onClick(button));
return button;
}
function subLine(company, rerender) {
const sub = document.createElement("span");
sub.className = "sub";
// The host, then why the company is read by hand. Without a reason the
// row says what it did before there were reasons: "board not found".
const host = company.board || company.ats || (company.hand_reason ? "" : "board not found");
if (host) sub.appendChild(badge(host));
if (company.hand_reason) sub.appendChild(badge(reasonWords(company.hand_reason)));
const place = [company.city, (company.country || "").toUpperCase()].filter(Boolean).join(", ");
if (place) sub.append(` ${place}`);
if (company.failing_since) {
const failing = document.createElement("span");
failing.className = "failing";
failing.textContent = `board failing since ${company.failing_since.slice(0, 10)}`;
sub.append(" · ");
sub.appendChild(failing);
}
sub.append(" · ");
const where = target(company);
if (where) {
const link = document.createElement("a");
link.href = where.url;
link.target = "_blank";
link.rel = "noopener noreferrer";
link.textContent = where.label;
link.addEventListener("click", () => opened(company, rerender));
sub.appendChild(link);
sub.append(` · ${ago(company.careers_opened_at)} `);
}
// Edit is also how a link is set: the form opens on the careers page box.
sub.append(linky("Edit", () => openForm(company)), " ",
linky("Remove", (button) => removeCompany(company, button)));
return sub;
}
/** The link was followed: stamp it. The new tab is already open, so this
only updates the row, and only the stamp, so the row does not jump. */
async function opened(company, rerender) {
try {
const updated = await api(`/api/companies/${encodeURIComponent(company.key)}/opened`,
{ method: "POST" });
company.careers_opened_at = updated.careers_opened_at;
} catch (err) {
return;
}
rerender();
}
function row(company) {
const row = document.createElement("div");
row.className = "crow";
row.dataset.key = company.key;
const name = document.createElement("span");
name.className = "name";
name.textContent = company.name;
row.appendChild(name);
row.appendChild(ratingControl(company, render));
row.appendChild(subLine(company, render));
if (company.notes) {
const note = document.createElement("span");
note.className = "sub notes";
note.textContent = company.notes;
row.appendChild(note);
}
return row;
}
/** The filter's options with their counts, kept on the chosen one. */
function drawFilter(all) {
const select = $("#w-filter");
const chosen = select.value || savedFilter();
select.replaceChildren();
for (const [value, label] of FILTERS) {
const option = document.createElement("option");
option.value = value;
option.textContent = `${label} (${all.filter((c) => matchesFilter(c, value)).length})`;
select.appendChild(option);
}
select.value = chosen;
}
function render() {
const all = watched();
drawFilter(all);
const q = $("#w-q").value.trim().toLowerCase();
const filter = $("#w-filter").value;
// The row being edited stays, whatever the filter says, so its form does.
const rows = all.filter((c) => c.key === editing
|| (matchesQuery(c, q) && matchesFilter(c, filter)));
// Overdue first on the list, never opened on top (the empty stamp sorts
// before any date); every other filter is by name.
rows.sort((a, b) => (filter === "yes"
? a.careers_opened_at.localeCompare(b.careers_opened_at) : 0)
|| a.name.localeCompare(b.name));
const body = $("#watchlist-list");
body.replaceChildren();
if (editing === NEW) body.appendChild(editor);
for (const company of rows) {
body.appendChild(editing === company.key ? editor : row(company));
}
$("#watchlist-count").textContent = count(rows.length, "company", "companies");
}
// ---------------------------------------------------------------- the form
function form(company) {
const f = $("#company-form-template").content.querySelector("form").cloneNode(true);
$("#company-form-title", f).textContent = company ? `Edit ${company.name}` : "New company";
$("#cf-name", f).value = company ? company.name : "";
// A company with a board keeps its name: the board is found by it.
const kept = Boolean(company && company.subscription_id != null);
$("#cf-name", f).readOnly = kept;
$("#cf-name-hint", f).hidden = !kept;
$("#cf-url", f).value = company ? company.careers_url || "" : "";
$("#cf-reason", f).value = company ? company.hand_reason || "" : "added";
$("#cf-notes", f).value = company ? company.notes || "" : "";
f.addEventListener("input", () => { f.dataset.dirty = "true"; });
$("#cf-cancel", f).addEventListener("click", () => { if (close()) render(); });
f.addEventListener("submit", saveCompany);
return f;
}
// Put the open form away, asking first if it holds changes. False when the
// answer was to keep them.
function close() {
if (editor && editor.dataset.dirty
&& !window.confirm("Discard the changes to this company?")) {
return false;
}
editing = null;
editor = null;
return true;
}
// Edit `company` in place of its row, or a new one on top of the list.
function openForm(company) {
const want = company ? company.key : NEW;
if (editing !== want) {
if (!close()) return;
editing = want;
editor = form(company);
$("#watchlist-answer").replaceChildren();
render();
}
editor.scrollIntoView({ behavior: "smooth", block: "nearest" });
$(company ? "#cf-url" : "#cf-name", editor).focus({ preventScroll: true });
}
function formBody(f) {
return {
name: $("#cf-name", f).value.trim(),
careers_url: $("#cf-url", f).value.trim(),
hand_reason: $("#cf-reason", f).value,
notes: $("#cf-notes", f).value.trim(),
};
}
/** A new company is unrated: if the filter or the text would hide it, they
change to show it, since the owner just asked for it. */
function reveal(company) {
if (!matchesFilter(company, $("#w-filter").value)) {
$("#w-filter").value = "unrated";
saveFilter("unrated");
}
if (!matchesQuery(company, $("#w-q").value.trim().toLowerCase())) $("#w-q").value = "";
}
async function saveCompany(event) {
event.preventDefault();
const f = event.target;
const button = $("button[type=submit]", f);
const body = formBody(f);
const company = editing === NEW ? null : companies.get(editing);
// Only what changed, so a company with a board is not sent the name it
// may not change.
const patch = {};
if (company) {
for (const [field, value] of Object.entries(body)) {
if (value !== (company[field] || "")) patch[field] = value;
}
}
button.disabled = true;
let answer = company;
try {
if (!company) {
answer = await api("/api/companies", { method: "POST", body });
} else if (Object.keys(patch).length) {
answer = await api(`/api/companies/${encodeURIComponent(company.key)}`,
{ method: "PATCH", body: patch });
}
} catch (err) {
button.disabled = false;
if (!company && err.status === 409) await taken(body.name, err.detail);
return;
}
if (company) {
Object.assign(company, answer);
} else {
companies.set(answer.key, answer);
reveal(answer);
}
editing = null;
editor = null;
$("#watchlist-answer").textContent = `${company ? "Saved" : "Added"} ${answer.name}.`;
render();
const shown = $(`#watchlist-list [data-key="${CSS.escape(answer.key)}"]`);
if (shown) shown.scrollIntoView({ behavior: "smooth", block: "nearest" });
}
// New refused, since the key its name folds to is taken, which the toast
// said. If that company is on this list, offer to edit it instead; if not,
// say where it is. The server's sentence ends "as <key>.", which finds it
// when the name typed is not the one it has ("Acme GmbH" for "Acme").
async function taken(name, detail) {
try {
await loadCompanies();
} catch (err) {
return;
}
render();
const said = / as (\S+)\.$/.exec(detail || "");
const wanted = name.toLowerCase();
const existing = (said && companies.get(said[1]))
|| [...companies.values()].find((c) => c.name.toLowerCase() === wanted);
if (!existing) return;
if (byHand(existing) || existing.failing_since) {
if (window.confirm(`${existing.name} is on the Watchlist already. Edit it instead?`)) {
delete editor.dataset.dirty;
openForm(existing);
}
return;
}
const why = existing.board ? "the app reads its board" : "it is known from a job board search";
const link = document.createElement("a");
link.href = "/settings/sources#company-boards";
link.textContent = "Settings, Sources, Company boards";
$("#watchlist-answer").replaceChildren(
`${existing.name} is not on the Watchlist, since ${why}; it is under `, link, ".");
}
// ---------------------------------------------------------------- actions
async function removeCompany(company, button) {
if (!window.confirm(`Remove ${company.name}? Its rating, note and careers link go with it.`)) {
return;
}
button.disabled = true;
try {
// A company with a board or open roles is refused, and the toast says which.
await api(`/api/companies/${encodeURIComponent(company.key)}`, { method: "DELETE" });
} catch (err) {
button.disabled = false;
return;
}
companies.delete(company.key);
if (editing === company.key) {
editing = null;
editor = null;
}
$("#watchlist-answer").textContent = `Removed ${company.name}.`;
render();
}
// -------------------------------------------------------------------- init
document.addEventListener("DOMContentLoaded", async () => {
if (!$("#watchlist-list")) return;
try {
await loadCompanies();
} catch (err) {
return;
}
$("#w-filter").value = savedFilter();
render();
$("#w-q").addEventListener("input", debounce(render, 150));
$("#w-filter").addEventListener("change", () => {
saveFilter($("#w-filter").value);
render();
});
$("#w-add").addEventListener("click", () => openForm(null));
});
})();