char.lt-old/static/js/shorten.js

95 lines
2.1 KiB
JavaScript

import { r, q, h } from "./brief-html.js";
const populateRedirects = async (redirKey) => {
const body = q("main table tbody");
body.innerHTML = "Loading...";
const redirects = await fetch("/redirects.json", {
headers: { authorization: `Bearer ${redirKey}` },
}).then((r) => r.json());
body.innerHTML = "";
for (const redirect of redirects) {
body.appendChild(
h("tr", {}, [
h(
"td",
{},
h("a", { href: "/" + redirect.path }, [h("pre", {}, [redirect.path])])
),
h(
"td",
{},
h("a", { href: redirect.target_location }, [redirect.target_location])
),
h("td", {}, [redirect.redirect_code]),
])
);
}
};
const setupForm = (redirKey) => {
const form = h("form", {}, [
h("h2", {}, "create or replace"),
h("label", { for: "path" }, ["local path (random if empty)"]),
h(
"input",
{
type: "text",
name: "path",
id: "path",
placeholder: "my-cool-link",
},
[]
),
h("label", { for: "url" }, ["target url"]),
h(
"input",
{
type: "url",
name: "url",
id: "url",
placeholder: "https://…",
required: true,
},
[]
),
h("button", {}, ["Create"]),
]);
form.addEventListener("submit", async (e) => {
e.preventDefault();
const data = new URLSearchParams();
const path = form.querySelector("#path").value;
if (path) data.append("path", path);
data.append("target", form.querySelector("#url").value);
const response = await fetch("/shorten", {
method: "POST",
headers: {
"content-type": "application/x-www-form-urlencoded",
authorization: `Bearer ${redirKey}`,
},
body: data,
}).then((r) => r.json());
if (response.error) alert(response.error);
window.location.reload();
});
q("main").appendChild(form);
};
r(async () => {
const redirKey = window.localStorage.getItem("redirect-key");
if (redirKey == null) return;
await Promise.all([populateRedirects(redirKey), setupForm(redirKey)]);
});