619 lines
33 KiB
JavaScript
619 lines
33 KiB
JavaScript
// Dezio dashboard: the pages. The controls live in controls.js.
|
|
"use strict";
|
|
|
|
const state = { me: null, page: "me", sections: [], spy: null, turn: 0 };
|
|
|
|
// ---------------------------------------------------------------------------- helpers
|
|
function toast(text, bad) {
|
|
const el = $("toast");
|
|
el.textContent = text;
|
|
el.classList.toggle("bad", Boolean(bad));
|
|
el.classList.add("show");
|
|
clearTimeout(toast.timer);
|
|
toast.timer = setTimeout(() => el.classList.remove("show"), 3500);
|
|
}
|
|
|
|
// The site may live under a path such as /dezio; the server puts it on <html data-base>.
|
|
const BASE = document.documentElement.dataset.base || "";
|
|
|
|
async function api(method, path, body) {
|
|
const options = { method, credentials: "same-origin", headers: {} };
|
|
if (body !== undefined) {
|
|
options.headers["Content-Type"] = "application/json";
|
|
options.headers["X-CSRF-Token"] = state.me ? state.me.csrf : "";
|
|
options.body = JSON.stringify(body);
|
|
}
|
|
const response = await fetch(BASE + path, options);
|
|
let data = {};
|
|
try { data = await response.json(); } catch (e) { /* empty answer */ }
|
|
if (!response.ok) throw new Error(data.error || `Something went wrong (${response.status})`);
|
|
return data;
|
|
}
|
|
|
|
const dirty = () => state.sections.filter((s) => s.collect && JSON.stringify(s.collect()) !== s.saved);
|
|
|
|
function refreshSaveBar() {
|
|
const count = dirty().length;
|
|
$("savebar").classList.toggle("show", count > 0);
|
|
if (count) $("save-text").textContent = count === 1 ? "1 section changed" : `${count} sections changed`;
|
|
}
|
|
|
|
async function saveAll() {
|
|
const go = $("save-go");
|
|
go.disabled = true;
|
|
go.textContent = "Saving";
|
|
let failed = 0;
|
|
for (const s of dirty()) {
|
|
const body = s.collect();
|
|
s.status.textContent = "";
|
|
s.el.classList.remove("failed");
|
|
try {
|
|
const result = await api("PATCH", s.path, body);
|
|
s.saved = JSON.stringify(body);
|
|
if (result.notes && result.notes[0]) toast(result.notes[0]);
|
|
if (s.done) s.done(result);
|
|
} catch (e) {
|
|
failed += 1;
|
|
s.status.textContent = e.message;
|
|
s.el.classList.add("failed");
|
|
s.el.scrollIntoView({ behavior: "smooth", block: "center" });
|
|
}
|
|
}
|
|
go.disabled = false;
|
|
go.textContent = "Save changes";
|
|
refreshSaveBar();
|
|
if (!failed) toast("Saved");
|
|
}
|
|
|
|
// One card on a page. With `collect` and `path` its changes go through the save bar.
|
|
function section({ id, title, icn, hint, meta, body, collect, path, done, extra }) {
|
|
const status = h("p", { class: "status err", role: "alert" });
|
|
const el = h("section", { class: "section", id: `s-${id}` },
|
|
h("header", { class: "section-head" }, h("span", { class: "section-ic" }, icon(icn)), h("div", {}, h("h2", {}, title), hint ? h("p", { class: "hint" }, hint) : null), meta || null),
|
|
body, status, extra || null);
|
|
const entry = { id, title, el, status, collect, path, done };
|
|
if (collect) entry.saved = JSON.stringify(collect());
|
|
state.sections.push(entry);
|
|
const watch = () => refreshSaveBar();
|
|
el.addEventListener("input", watch);
|
|
el.addEventListener("change", watch);
|
|
return el;
|
|
}
|
|
|
|
function field(label, input, note) {
|
|
// A wrapping <label> would forward clicks onto the first button inside a picker.
|
|
const tag = input.matches("input, textarea") || input.querySelector(":scope > input") ? "label" : "div";
|
|
return h(tag, { class: "field" }, h("span", {}, label), input, note ? h("small", {}, note) : null);
|
|
}
|
|
|
|
function counted(area, limit) {
|
|
const count = h("small", { class: "count" });
|
|
const show = () => { count.textContent = `${area.value.length} / ${limit}`; };
|
|
area.addEventListener("input", show);
|
|
show();
|
|
return h("div", { class: "counted" }, area, count);
|
|
}
|
|
|
|
// A text box with place suggestions underneath while you type (only you see them).
|
|
function placeSuggestions(input) {
|
|
const list = h("div", { class: "suggest" });
|
|
let timer, asked = "";
|
|
const close = () => list.classList.remove("open");
|
|
input.addEventListener("input", () => {
|
|
clearTimeout(timer);
|
|
const text = input.value.trim();
|
|
if (text.length < 2) return close();
|
|
timer = setTimeout(async () => {
|
|
asked = text;
|
|
let found = [];
|
|
try { found = await api("GET", "/api/places?q=" + encodeURIComponent(text)); } catch (e) { /* none this time */ }
|
|
if (asked !== input.value.trim()) return; // they kept typing
|
|
list.replaceChildren(...found.map((label) => h("button", { type: "button", class: "pop-item",
|
|
onmousedown: (event) => { event.preventDefault(); input.value = label; close(); input.dispatchEvent(new Event("change", { bubbles: true })); } }, h("span", { class: "pop-label" }, label))));
|
|
list.classList.toggle("open", found.length > 0);
|
|
}, 250);
|
|
});
|
|
input.addEventListener("blur", () => setTimeout(close, 150));
|
|
input.addEventListener("keydown", (event) => { if (event.key === "Escape") close(); });
|
|
return h("div", { class: "suggest-wrap" }, input, list);
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------- quote styles
|
|
// One editor for a person's own quote look (Your settings) and for a server's default (server page).
|
|
// The preview is drawn by the bot itself, so it is exactly what /quote will make.
|
|
function quoteSection(id, title, hint, q, path) {
|
|
const st = JSON.parse(JSON.stringify(q.style));
|
|
const controls = {};
|
|
const drawing = h("span", { class: "monitor-note" });
|
|
const screen = h("div", { class: "monitor-screen" });
|
|
let shown = null, timer, token = 0;
|
|
const refresh = () => {
|
|
clearTimeout(timer);
|
|
timer = setTimeout(async () => {
|
|
const mine = ++token;
|
|
drawing.textContent = "Drawing";
|
|
drawing.classList.remove("err");
|
|
try {
|
|
const response = await fetch(BASE + "/api/quote/preview", { method: "POST", credentials: "same-origin",
|
|
headers: { "Content-Type": "application/json", "X-CSRF-Token": state.me.csrf }, body: JSON.stringify({ style: st }) });
|
|
if (!response.ok) throw new Error((await response.json()).error || "Couldn't draw that");
|
|
const url = URL.createObjectURL(await response.blob());
|
|
if (mine !== token) { URL.revokeObjectURL(url); return; }
|
|
const next = h("img", { alt: "Preview of the quote card" });
|
|
next.addEventListener("load", () => {
|
|
const old = shown;
|
|
shown = next;
|
|
screen.classList.toggle("tall", st.layout === "portrait");
|
|
requestAnimationFrame(() => next.classList.add("in"));
|
|
if (old) setTimeout(() => { URL.revokeObjectURL(old.src); old.remove(); }, 400);
|
|
}, { once: true });
|
|
next.src = url;
|
|
screen.append(next);
|
|
drawing.textContent = "";
|
|
} catch (e) { drawing.classList.add("err"); drawing.textContent = e.message; }
|
|
}, 350);
|
|
};
|
|
const edit = (key, read) => (event) => { st[key] = read(event.currentTarget); refresh(); };
|
|
const seg = (key, options, aria) => {
|
|
const el = segmented(options, st[key], aria);
|
|
el.addEventListener("change", edit(key, (e) => e.value()));
|
|
controls[key] = { set: (v) => el.set(v) };
|
|
return field(aria, el);
|
|
};
|
|
const colour = (key, label) => {
|
|
const el = colourPick(st[key], label);
|
|
el.addEventListener("input", edit(key, (e) => e.value));
|
|
controls[key] = { set: (v) => { el.value = v; } };
|
|
return field(label, el);
|
|
};
|
|
const check = (key, label) => {
|
|
const t = switchCtl(label, st[key]);
|
|
t.input.addEventListener("input", () => { st[key] = t.input.checked; refresh(); });
|
|
controls[key] = { set: (v) => { t.input.checked = Boolean(v); } };
|
|
return t;
|
|
};
|
|
|
|
// the presets, each tile painted with its own colours
|
|
const tiles = h("div", { class: "tiles", role: "radiogroup", "aria-label": "Start from" });
|
|
const paintTiles = () => tiles.querySelectorAll("button").forEach((b) => b.setAttribute("aria-checked", String(b.dataset.key === st.preset)));
|
|
for (const p of q.presets) {
|
|
const tile = h("button", { type: "button", role: "radio", "data-key": p.key, class: "tile" }, h("span", {}, p.label));
|
|
tile.style.background = p.style.bg2 ? `linear-gradient(135deg, ${p.style.bg}, ${p.style.bg2})` : p.style.bg;
|
|
tile.style.color = p.style.text;
|
|
tile.addEventListener("click", () => {
|
|
const keep = { font: st.font, size: st.size, bold: st.bold };
|
|
Object.assign(st, p.style, keep);
|
|
sync();
|
|
paintTiles();
|
|
refresh();
|
|
tile.dispatchEvent(new Event("input", { bubbles: true }));
|
|
});
|
|
tiles.append(tile);
|
|
}
|
|
|
|
const gradient = switchCtl("Gradient background", Boolean(st.bg2));
|
|
const end = colourPick(st.bg2 || "#eb459e", "Gradient end");
|
|
const endField = field("Gradient end", end);
|
|
const paintGradient = () => endField.classList.toggle("off", !gradient.input.checked);
|
|
gradient.input.addEventListener("input", () => { st.bg2 = gradient.input.checked ? end.value : null; paintGradient(); refresh(); });
|
|
end.addEventListener("input", () => { if (gradient.input.checked) { st.bg2 = end.value; refresh(); } });
|
|
|
|
const font = pick({ options: q.fonts.map((f) => ({ value: f, label: f })), value: st.font, label: "Font", allowNew: true, newLabel: (t) => `Use ${t} from Google Fonts`, searchLabel: "Any Google Font" });
|
|
font.addEventListener("input", edit("font", (e) => e.value || "Noto Sans"));
|
|
const size = fader({ label: "Text size", max: 160, value: st.size, format: (v) => (v ? `${v} px` : "Fit"), ticks: [[0, "Fit"], [80, "80"], [160, "160"]] });
|
|
size.addEventListener("input", edit("size", (e) => e.value));
|
|
const mark = h("input", { type: "text", value: st.watermark, maxlength: 40, placeholder: "None" });
|
|
mark.addEventListener("input", edit("watermark", (e) => e.value));
|
|
|
|
const sync = () => {
|
|
for (const [key, c] of Object.entries(controls)) c.set(st[key]);
|
|
gradient.input.checked = Boolean(st.bg2);
|
|
if (st.bg2) end.value = st.bg2;
|
|
font.value = st.font;
|
|
size.value = st.size;
|
|
mark.value = st.watermark;
|
|
paintGradient();
|
|
};
|
|
paintGradient();
|
|
paintTiles();
|
|
|
|
const editor = h("div", { class: "quote-controls" },
|
|
field("Start from", tiles),
|
|
h("div", { class: "row" }, seg("layout", [["wide", "Wide"], ["portrait", "Portrait"]], "Layout"), seg("image", [["fade", "Fade"], ["circle", "Round"], ["none", "None"]], "Picture")),
|
|
h("div", { class: "row" }, seg("icon", [["none", "None"], ["avatar", "Avatar"], ["server", "Server"]], "Icon"), field("Font", font)),
|
|
size,
|
|
field("Watermark", mark),
|
|
h("div", { class: "switches" }, check("grayscale", "Black and white picture"), check("flip", "Flip sides"), check("marks", "Big quote marks"), check("name", "Show name"),
|
|
check("handle", "Show @handle"), check("line", "Divider line"), check("bold", "Bold text"), check("quote_chars", "Quote marks around the text")),
|
|
h("div", { class: "colours" }, colour("bg", "Background"), colour("text", "Text"), colour("author", "Name"), colour("muted", "Handle and watermark")),
|
|
h("div", { class: "row" }, gradient, endField));
|
|
const monitor = h("div", { class: "monitor" }, h("div", { class: "monitor-top" }, h("span", {}, "What Create Quote will make"), drawing), screen);
|
|
|
|
const collect = () => ({ quote: st });
|
|
const reset = h("button", { class: "btn ghost", type: "button" }, icon("reset"), q.saved ? "Remove saved style" : "Back to the default look");
|
|
reset.addEventListener("click", async () => {
|
|
try {
|
|
const result = await api("PATCH", path, { quote: null });
|
|
const fresh = (result.settings && result.settings.quote) || { style: q.presets[0].style };
|
|
for (const key of Object.keys(st)) delete st[key];
|
|
Object.assign(st, JSON.parse(JSON.stringify(fresh.style)));
|
|
sync();
|
|
paintTiles();
|
|
entry.saved = JSON.stringify(collect());
|
|
refreshSaveBar();
|
|
refresh();
|
|
toast("Back to the default look");
|
|
} catch (e) { toast(e.message, true); }
|
|
});
|
|
refresh();
|
|
const el = section({ id, title, icn: "message", hint, body: h("div", { class: "quote-desk" }, editor, monitor), collect, path, extra: h("div", { class: "actions" }, reset) });
|
|
const entry = state.sections[state.sections.length - 1];
|
|
return el;
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------- role menus
|
|
// The same menus the /cosmetics editor in Discord changes: presets can be edited, custom menus added.
|
|
function roleMenusSection(g, path) {
|
|
const wrap = h("div", { class: "menus" });
|
|
let open = null;
|
|
const act = async (payload) => {
|
|
try {
|
|
const result = await api("POST", `${path}/rolemenus`, payload);
|
|
toast((result.notes && result.notes[0]) || "Done");
|
|
draw(result.rolemenus.menus);
|
|
} catch (e) { toast(e.message, true); }
|
|
};
|
|
const roleOptions = (m) => [...new Set([...m.available, ...m.roles])].map((r) => ({ value: r, label: r }));
|
|
const button = (label, cls, fn, icn) => h("button", { class: "btn " + cls, type: "button", onclick: fn }, icn ? icon(icn) : null, label);
|
|
const draw = (menus) => {
|
|
const cards = menus.map((m) => {
|
|
const name = h("input", { type: "text", value: m.name, maxlength: 60 });
|
|
const emoji = h("input", { type: "text", value: m.emoji, maxlength: 8 });
|
|
const kind = segmented([["many", "Pick several"], ["one", "Pick one"]], m.one ? "one" : "many", "How many roles members can pick");
|
|
const roles = multiPick({ options: roleOptions(m), values: m.roles, label: "Roles in this menu", allowNew: true, newLabel: (t) => `Add ${t} as a new role` });
|
|
const channel = channelPick(g.channels, "", "Channel to post in", "Channel to post in");
|
|
const save = () => act({ action: "save", key: m.key, name: name.value, emoji: emoji.value, one: kind.value() === "one", roles: roles.values() });
|
|
const card = h("details", { class: "menu", open: open === m.key, ontoggle: (event) => { if (event.target.open) open = m.key; } },
|
|
h("summary", {}, h("span", { class: "menu-emoji" }, m.emoji), h("span", { class: "menu-name" }, m.name),
|
|
h("small", {}, `${m.roles.length} ${m.roles.length === 1 ? "role" : "roles"}${m.preset ? " · preset" : ""}`), icon("chevron")),
|
|
h("div", { class: "menu-body" },
|
|
h("div", { class: "row" }, field("Name", name), h("div", { class: "narrow" }, field("Emoji", emoji)), field("Members can", kind)),
|
|
field("Roles", roles),
|
|
h("div", { class: "actions" }, button("Save menu", "primary", save),
|
|
m.preset ? button("Reset to preset", "ghost", () => act({ action: "reset", key: m.key }), "reset")
|
|
: button("Delete", "danger", async () => {
|
|
if (await ask(`Delete ${m.name}?`, "Its roles and posted message are removed too.", "Delete")) act({ action: "delete", key: m.key });
|
|
}, "trash")),
|
|
h("div", { class: "publish" }, field("Publish to a channel", channel, "Dezio creates any missing roles"),
|
|
button("Publish", "", () => act({ action: "publish", key: m.key, channel: channel.value }), "send"))));
|
|
return card;
|
|
});
|
|
const name = h("input", { type: "text", maxlength: 60, placeholder: "Games, Colours, Ping roles" });
|
|
const emoji = h("input", { type: "text", maxlength: 8, placeholder: "🎮" });
|
|
const roles = multiPick({ options: [], values: [], label: "Roles in the new menu", addLabel: "Add role", allowNew: true, newLabel: (t) => `Add ${t}` });
|
|
const create = h("details", { class: "menu" }, h("summary", {}, h("span", { class: "menu-emoji" }, icon("plus")), h("span", { class: "menu-name" }, "New menu"), icon("chevron")),
|
|
h("div", { class: "menu-body" }, h("div", { class: "row" }, field("Name", name), h("div", { class: "narrow" }, field("Emoji", emoji))), field("Roles", roles),
|
|
h("div", { class: "actions" }, button("Create menu", "primary", () => act({ action: "create", name: name.value, emoji: emoji.value, roles: roles.values() })))));
|
|
wrap.replaceChildren(...cards, create);
|
|
};
|
|
draw(g.rolemenus.menus);
|
|
return section({ id: "menus", title: "Role menus", icn: "tag", hint: "Dropdowns members use to give themselves roles. Edit a preset or make your own, then publish it to a channel", body: wrap });
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------- welcome preview
|
|
const TOKENS = ["{mention}", "{name}", "{display_name}", "{server}", "{count}", "{id}", "{avatar}"];
|
|
|
|
function fill(text, g) {
|
|
const me = state.me.user;
|
|
const values = { mention: `@${me.name}`, name: me.name, display_name: me.name, server: g.name, count: g.member_count ?? "128", id: me.id, avatar: me.avatar };
|
|
return text.replace(/\{(\w+)\}/g, (all, key) => values[key] ?? all);
|
|
}
|
|
|
|
// Only Discord's own image host passes the site's security policy; anything else shows as an empty slot.
|
|
function previewImage(url, g, cls) {
|
|
const src = fill(url, g).trim();
|
|
if (!src) return null;
|
|
if (!src.startsWith("https://cdn.discordapp.com/")) return h("div", { class: cls + " slot" });
|
|
return h("img", { class: cls, src, alt: "" });
|
|
}
|
|
|
|
function messageEditor(kind, g, w) {
|
|
const e = w[`${kind}_embed`];
|
|
const on = switchCtl(`Send ${kind} messages`, w[`${kind}_enabled`]);
|
|
const chan = channelPick(g.channels, w[`${kind}_channel`], "No channel", "Channel");
|
|
const inputs = {
|
|
title: h("input", { type: "text", value: e.title, maxlength: 256 }),
|
|
description: h("textarea", { maxlength: 2000 }, e.description),
|
|
image: h("input", { type: "text", value: e.image, placeholder: "https://…", maxlength: 500 }),
|
|
thumbnail: h("input", { type: "text", value: e.thumbnail, placeholder: "{avatar} or https://…", maxlength: 500 }),
|
|
footer: h("input", { type: "text", value: e.footer, maxlength: 300 }),
|
|
};
|
|
const embed = h("div", { class: "embed" });
|
|
const draw = () => {
|
|
const thumb = previewImage(inputs.thumbnail.value, g, "embed-thumb");
|
|
const image = previewImage(inputs.image.value, g, "embed-image");
|
|
const text = h("div", { class: "embed-text" },
|
|
inputs.title.value ? h("strong", {}, fill(inputs.title.value, g)) : null,
|
|
inputs.description.value ? h("p", {}, fill(inputs.description.value, g)) : null);
|
|
embed.replaceChildren(...[h("div", { class: "embed-top" }, text, thumb), image,
|
|
inputs.footer.value ? h("small", {}, fill(inputs.footer.value, g)) : null].filter(Boolean));
|
|
pane.classList.toggle("muted-out", !on.input.checked);
|
|
};
|
|
let last = inputs.description;
|
|
for (const el of Object.values(inputs)) {
|
|
el.addEventListener("input", draw);
|
|
el.addEventListener("focus", () => { last = el; });
|
|
}
|
|
on.input.addEventListener("input", draw);
|
|
const chips = h("div", { class: "tokens" }, TOKENS.map((t) => h("button", { type: "button", class: "token", onmousedown: (event) => event.preventDefault(), onclick: () => {
|
|
const at = last.selectionStart ?? last.value.length;
|
|
last.setRangeText(t, at, last.selectionEnd ?? at, "end");
|
|
last.focus();
|
|
last.dispatchEvent(new Event("input", { bubbles: true }));
|
|
} }, t)));
|
|
const pane = h("div", { class: "pane" },
|
|
h("div", { class: "pane-form" }, on, field("Channel", chan), field("Title", inputs.title), field("Message", inputs.description), chips,
|
|
h("div", { class: "row" }, field("Image", inputs.image), field("Thumbnail", inputs.thumbnail)), field("Footer", inputs.footer)),
|
|
h("div", { class: "pane-preview" }, h("span", { class: "monitor-note" }, "Preview"), embed));
|
|
draw();
|
|
pane.collect = () => ({
|
|
[`${kind}_enabled`]: on.input.checked, [`${kind}_channel`]: chan.value || null,
|
|
[`${kind}_embed`]: Object.fromEntries(Object.entries(inputs).map(([k, el]) => [k, el.value])),
|
|
});
|
|
return pane;
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------- pages
|
|
function skeleton() {
|
|
return h("div", { class: "skeleton", "aria-label": "Loading" }, h("span", { class: "sk-title" }), h("span", { class: "sk-sub" }), h("span", { class: "sk-card" }), h("span", { class: "sk-card" }));
|
|
}
|
|
|
|
function mount(parts) {
|
|
parts.forEach((part, i) => {
|
|
part.classList.add("rise");
|
|
part.style.setProperty("--i", Math.min(i, 6));
|
|
});
|
|
$("main").replaceChildren(...parts);
|
|
renderSide();
|
|
watchScroll();
|
|
}
|
|
|
|
async function showMe(turn) {
|
|
const s = await api("GET", "/api/user");
|
|
if (turn !== state.turn) return; // they went elsewhere meanwhile; a newer load draws the page
|
|
const parts = [h("header", { class: "page-head" }, h("h1", {}, "Your settings"), h("p", { class: "sub" }, "These follow you to every server that has Dezio"))];
|
|
|
|
if (s.lastfm_available) {
|
|
const name = h("input", { type: "text", value: s.lastfm || "", placeholder: "ListenBrainz username", maxlength: 64 });
|
|
const hint = (who) => (who ? `Linked to ${who}` : "Link your account for /fm, charts and Who Knows");
|
|
parts.push(section({ id: "lastfm", title: "ListenBrainz", icn: "music", hint: hint(s.lastfm),
|
|
body: field("Username", name, "Leave empty to unlink"), collect: () => ({ lastfm: name.value.trim() }), path: "/api/user",
|
|
done: (r) => { document.querySelector("#s-lastfm .hint").textContent = hint(r.settings.lastfm); } }));
|
|
}
|
|
|
|
if (s.afk_available) {
|
|
const list = h("div", { class: "afk-list" });
|
|
const clear = h("button", { class: "btn ghost", type: "button" }, "Clear AFK");
|
|
const render = (items) => {
|
|
clear.disabled = !items.length;
|
|
list.replaceChildren(...(items.length ? items.map((a) =>
|
|
h("div", { class: "afk-item" }, h("span", {}, h("strong", {}, a.where), ` ${a.reason}`),
|
|
h("small", {}, a.since ? new Date(a.since * 1000).toLocaleString() : ""))) :
|
|
[h("p", { class: "quiet" }, "You're not AFK anywhere")]));
|
|
};
|
|
render(s.afk);
|
|
const reason = h("input", { type: "text", placeholder: "Why you're away", maxlength: 200 });
|
|
const set = h("button", { class: "btn", type: "button" }, "Go AFK everywhere");
|
|
const doAfk = async (value) => {
|
|
try {
|
|
const result = await api("PATCH", "/api/user", { afk: value });
|
|
render(result.settings.afk);
|
|
toast(value ? "You're AFK everywhere" : "AFK cleared");
|
|
} catch (e) { toast(e.message, true); }
|
|
};
|
|
set.addEventListener("click", () => doAfk({ reason: reason.value }));
|
|
clear.addEventListener("click", () => doAfk(null));
|
|
parts.push(section({ id: "afk", title: "AFK", icn: "moon", hint: "People who ping you are told you're away. Talking again in Discord also clears it",
|
|
body: h("div", {}, list, field("Reason", reason), h("div", { class: "actions" }, set, clear)) }));
|
|
}
|
|
|
|
const quality = segmented([["fast", "Fast, smaller files"], ["best", "Best quality"]], s.download_quality, "Download quality");
|
|
parts.push(section({ id: "downloads", title: "Downloads", icn: "download", hint: "The default for /download and D!download",
|
|
body: quality, collect: () => ({ download_quality: quality.value() }), path: "/api/user" }));
|
|
|
|
const home = h("input", { type: "text", value: s.weather_home || "", placeholder: "Denver Colorado, Paris or a ZIP code", maxlength: 100, autocomplete: "off" });
|
|
const places = placeSuggestions(home);
|
|
const unit = segmented([["c", "°C"], ["f", "°F"]], s.temp_unit, "Units");
|
|
parts.push(section({ id: "weather", title: "Weather", icn: "cloud", hint: "Used when you run /weather without a place",
|
|
body: h("div", { class: "row" }, h("div", { class: "field grow" }, h("span", {}, "Home"), places), h("div", { class: "field" }, h("span", {}, "Units"), unit)),
|
|
collect: () => ({ weather_home: home.value, temp_unit: unit.value() }), path: "/api/user" }));
|
|
|
|
const snipe = switchCtl("Don't let others snipe my messages", s.snipe_optout, "Your deleted and edited messages won't show in snipe");
|
|
const dms = switchCtl("Block DMs sent through Dezio", s.dm_block, "Nobody can use /dm_echo to message you");
|
|
parts.push(section({ id: "privacy", title: "Privacy", icn: "shield", body: h("div", { class: "stack" }, snipe, dms),
|
|
collect: () => ({ snipe_optout: snipe.input.checked, dm_block: dms.input.checked }), path: "/api/user" }));
|
|
|
|
parts.push(quoteSection("quote", "Quote style", "How the pictures made with Create Quote look when you make them. Your own style wins over the server's", s.quote, "/api/user"));
|
|
mount(parts);
|
|
}
|
|
|
|
async function showGuild(id, turn) {
|
|
const g = await api("GET", `/api/guilds/${id}`);
|
|
if (turn !== state.turn) return;
|
|
const path = `/api/guilds/${id}`;
|
|
const facts = [`${g.channels.length} channels`, `${g.roles.length} roles`];
|
|
if (g.member_count) facts.unshift(`${g.member_count} members`);
|
|
const icon_ = g.icon ? h("img", { src: g.icon, alt: "" }) : h("span", {}, initials(g.name));
|
|
const parts = [h("header", { class: "page-head guild" }, h("span", { class: "guild-icon" }, icon_),
|
|
h("div", {}, h("h1", {}, g.name), h("p", { class: "sub" }, facts.join(" · "))))];
|
|
|
|
// general
|
|
const prefix = h("input", { type: "text", value: g.prefix, maxlength: 10, spellcheck: "false" });
|
|
const sample = h("code", {});
|
|
const paintSample = () => { sample.textContent = `${prefix.value || "?"}help`; };
|
|
prefix.addEventListener("input", paintSample);
|
|
paintSample();
|
|
const volume = fader({ label: "Default music volume", value: g.music_volume, format: (v) => `${v}%`, meter: 40, ticks: [[0, "Mute"], [80, "Default"], [100, "100%"]] });
|
|
const snipe = switchCtl("Snipe is on in this server", g.snipe, "Lets members see the last deleted and edited messages");
|
|
parts.push(section({ id: "general", title: "General", icn: "sliders", body: h("div", { class: "stack wide" },
|
|
volume,
|
|
h("div", { class: "row" }, h("div", { class: "narrow" }, field("Prefix", prefix)), h("p", { class: "hint inline" }, "Try ", sample, ". Slash commands always work too")),
|
|
snipe),
|
|
collect: () => ({ prefix: prefix.value, music_volume: volume.value, snipe: snipe.input.checked }), path }));
|
|
|
|
// logging
|
|
if (g.logging) {
|
|
const picks = {};
|
|
const count = h("span", { class: "section-meta" });
|
|
const paintCount = () => { count.textContent = `${Object.values(picks).filter((p) => p.value).length} of ${g.logging.types.length} on`; };
|
|
const rows = g.logging.types.map((t) => {
|
|
picks[t.key] = channelPick(g.channels, g.logging.channels[t.key], "Off", t.label);
|
|
picks[t.key].addEventListener("input", paintCount);
|
|
return h("div", { class: "log-row" }, h("span", {}, t.label), picks[t.key]);
|
|
});
|
|
paintCount();
|
|
const all = channelPick(g.channels, "", "Off", "Send every log to one channel");
|
|
all.addEventListener("input", (event) => {
|
|
event.stopPropagation();
|
|
for (const p of Object.values(picks)) p.value = all.value;
|
|
paintCount();
|
|
refreshSaveBar();
|
|
});
|
|
parts.push(section({ id: "logging", title: "Logging", icn: "list", hint: "Pick a channel for each kind of event, or leave it off", meta: count,
|
|
body: h("div", {}, h("div", { class: "log-row all" }, h("span", {}, "Set all to"), all), h("div", { class: "log-grid" }, rows)),
|
|
collect: () => ({ logging: Object.fromEntries(Object.entries(picks).map(([k, p]) => [k, p.value || null])) }), path }));
|
|
}
|
|
|
|
// welcome
|
|
if (g.welcome) {
|
|
const w = g.welcome;
|
|
const welcome = messageEditor("welcome", g, w);
|
|
const goodbye = messageEditor("goodbye", g, w);
|
|
goodbye.classList.add("hidden");
|
|
const tabs = segmented([["welcome", "Welcome"], ["goodbye", "Goodbye"]], "welcome", "Which message");
|
|
tabs.addEventListener("change", (event) => {
|
|
event.stopPropagation();
|
|
welcome.classList.toggle("hidden", tabs.value() !== "welcome");
|
|
goodbye.classList.toggle("hidden", tabs.value() !== "goodbye");
|
|
});
|
|
const autoroles = multiPick({ label: "Autoroles", values: w.autoroles,
|
|
options: g.roles.map((r) => ({ value: r.id, label: r.name, colour: r.colour || null, disabled: !r.assignable, hint: r.assignable ? null : "Not allowed", title: r.assignable ? null : "Above Dezio's role, or it has moderator or admin permissions" })) });
|
|
const sticky = switchCtl("Sticky roles", w.sticky_roles, "People who leave and come back get their old roles back");
|
|
parts.push(section({ id: "welcome", title: "Welcome and goodbye", icn: "user", hint: "Greet people as they arrive and leave",
|
|
body: h("div", { class: "stack wide" }, tabs, welcome, goodbye, field("Autoroles", autoroles, "Given to everyone who joins"), sticky),
|
|
collect: () => ({ welcome: { ...welcome.collect(), ...goodbye.collect(), sticky_roles: sticky.input.checked, autoroles: autoroles.values() } }), path }));
|
|
}
|
|
|
|
// AI
|
|
if (g.ai) {
|
|
const persona = h("textarea", { maxlength: 4000, placeholder: g.ai.default_persona }, g.ai.persona);
|
|
persona.rows = 8;
|
|
const lock = channelPick(g.channels, g.ai.lock, "Any channel", "Only answer in");
|
|
parts.push(section({ id: "ai", title: "AI chat", icn: "bot", hint: "How Dezio talks when someone mentions it. Leave the personality empty for the default",
|
|
body: h("div", { class: "stack" }, field("Personality", counted(persona, 4000)), field("Only answer in", lock)),
|
|
collect: () => ({ ai: { persona: persona.value, lock: lock.value || null } }), path }));
|
|
}
|
|
|
|
if (g.quote) {
|
|
parts.push(quoteSection("quote", "Quote style", "The server default, used for Create Quote by people who haven't saved a style of their own", g.quote, path));
|
|
}
|
|
if (g.rolemenus) {
|
|
parts.push(roleMenusSection(g, path));
|
|
}
|
|
mount(parts);
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------- navigation
|
|
const initials = (name) => name.split(/\s+/).map((w) => [...w][0] || "").join("").slice(0, 3);
|
|
|
|
function renderSide() {
|
|
const side = $("side");
|
|
const me = state.me;
|
|
const here = (page) => state.page === page;
|
|
const subnav = () => h("div", { class: "subnav" }, state.sections.map((s) =>
|
|
h("a", { href: `#s-${s.id}`, "data-spy": s.id, onclick: (event) => { event.preventDefault(); $(`s-${s.id}`).scrollIntoView({ behavior: "smooth", block: "start" }); } }, s.title)));
|
|
const row = (page, iconEl, label, title, disabled) => [
|
|
h("button", { type: "button", class: "nav-row" + (here(page) ? " active" : ""), disabled, title, "aria-current": here(page) ? "page" : null, onclick: () => go(page) },
|
|
h("span", { class: "nav-icon" }, iconEl), h("span", { class: "nav-label" }, label)),
|
|
here(page) && state.sections.length > 1 ? subnav() : null,
|
|
];
|
|
const servers = me.guilds.map((g) => row(g.id, g.icon ? h("img", { src: g.icon, alt: "" }) : initials(g.name), g.name,
|
|
g.manage ? g.name : `${g.name}: you need Manage Server`, !g.manage));
|
|
side.replaceChildren(h("h4", {}, "You"), ...row("me", h("img", { src: me.user.avatar, alt: "" }), "Your settings").filter(Boolean),
|
|
h("h4", {}, "Servers"), ...(servers.length ? servers.flat().filter(Boolean) : [h("p", { class: "quiet" }, "No servers shared with Dezio")]));
|
|
}
|
|
|
|
// Light up the side link of whichever section is under the top of the window.
|
|
function watchScroll() {
|
|
if (state.spy) removeEventListener("scroll", state.spy);
|
|
let queued = false;
|
|
const update = () => {
|
|
queued = false;
|
|
let current = state.sections[0];
|
|
for (const s of state.sections) if (s.el.getBoundingClientRect().top < 160) current = s;
|
|
document.querySelectorAll("[data-spy]").forEach((a) => a.classList.toggle("on", current && a.dataset.spy === current.id));
|
|
};
|
|
state.spy = () => { if (!queued) { queued = true; requestAnimationFrame(update); } };
|
|
addEventListener("scroll", state.spy, { passive: true });
|
|
update();
|
|
}
|
|
|
|
async function go(page, keepScroll) {
|
|
if (page !== state.page && dirty().length && !(await ask("Leave without saving?", "Your changes on this page will be lost.", "Leave", "Stay"))) return;
|
|
const top = scrollY;
|
|
const turn = ++state.turn; // sections are added to one shared list, so only the newest load may build the page
|
|
state.page = page;
|
|
state.sections = [];
|
|
refreshSaveBar();
|
|
history.replaceState(null, "", page === "me" ? `${BASE}/dashboard` : `${BASE}/dashboard#${page}`);
|
|
renderSide();
|
|
const slow = setTimeout(() => { if (turn === state.turn) $("main").replaceChildren(skeleton()); }, 160);
|
|
try {
|
|
if (page === "me") await showMe(turn); else await showGuild(page, turn);
|
|
} catch (e) {
|
|
if (turn === state.turn) $("main").replaceChildren(h("p", { class: "error" }, e.message));
|
|
}
|
|
clearTimeout(slow);
|
|
if (turn === state.turn) scrollTo(0, keepScroll ? top : 0);
|
|
}
|
|
|
|
const ERRORS = {
|
|
setup: "Sign-in isn't set up yet. The bot owner needs to add the OAuth client secret",
|
|
state: "That sign-in link expired. Please try again",
|
|
discord: "Discord didn't accept the sign-in. Please try again",
|
|
busy: "Too many sign-ins right now. Please try again in a minute",
|
|
};
|
|
|
|
async function start() {
|
|
const error = new URLSearchParams(location.search).get("error");
|
|
let me;
|
|
try { me = await api("GET", "/api/me"); } catch (e) { me = { signed_in: false, sign_in: true }; }
|
|
if (!me.signed_in) {
|
|
$("gate").classList.remove("hidden");
|
|
if (!me.sign_in) {
|
|
$("gate-text").textContent = ERRORS.setup;
|
|
$("gate-login").classList.add("hidden");
|
|
}
|
|
if (error && ERRORS[error]) {
|
|
$("gate-error").textContent = ERRORS[error];
|
|
$("gate-error").classList.remove("hidden");
|
|
}
|
|
return;
|
|
}
|
|
state.me = me;
|
|
$("who-avatar").src = me.user.avatar;
|
|
$("who-name").textContent = me.user.name;
|
|
$("logout").append(icon("logout"));
|
|
$("app").classList.remove("hidden");
|
|
$("logout").addEventListener("click", async () => {
|
|
try { await api("POST", "/logout", {}); } catch (e) { /* signed out anyway */ }
|
|
location.href = `${BASE}/dashboard`;
|
|
});
|
|
$("save-go").addEventListener("click", saveAll);
|
|
$("save-undo").addEventListener("click", () => { state.sections = []; go(state.page, true); });
|
|
addEventListener("beforeunload", (event) => { if (dirty().length) event.preventDefault(); });
|
|
const wanted = location.hash.slice(1);
|
|
await go(me.guilds.some((g) => g.id === wanted && g.manage) ? wanted : "me");
|
|
}
|
|
|
|
start();
|