1
0
Fork 0
mirror of https://github.com/kou029w/quot.git synced 2025-01-31 06:18:01 +00:00

add page editor

This commit is contained in:
Nebel 2022-08-24 09:50:35 +09:00
parent cd01268305
commit a9064197be
4 changed files with 79 additions and 13 deletions

View file

@ -1,14 +1,41 @@
import "./editor.css";
import beforeunload from "../helpers/beforeunload";
import throttle from "../helpers/throttle";
export default () => (
const intervalMs = 333;
const { block, unblock } = beforeunload();
const updatePage = throttle(async function (params: {
id: number;
title: string;
text: string;
}) {
const res = await fetch(
new URL(`/pages?id=eq.${params.id}`, import.meta.env.QUOT_API_URL),
{
method: "PUT",
headers: { "content-type": "application/json" },
body: JSON.stringify(params),
}
);
if (res.ok) unblock();
},
intervalMs);
export default (props: { id: number }) => {
return (
<textarea
id={String(props.id)}
class="editor"
autofocus
onInput={(e) => {
e.currentTarget.setAttribute(
"rows",
String(Math.max(2, e.currentTarget.value.split("\n").length))
);
const text = e.currentTarget.value;
const lines = text.split("\n");
block();
updatePage({ id: props.id, title: lines[0] ?? "", text });
e.currentTarget.setAttribute("rows", String(Math.max(2, lines.length)));
}}
></textarea>
);
};

View file

@ -0,0 +1,18 @@
function beforeunload() {
function listener(e: BeforeUnloadEvent) {
e.preventDefault();
e.returnValue = "";
}
function block() {
window.addEventListener("beforeunload", listener);
}
function unblock() {
window.removeEventListener("beforeunload", listener);
}
return { block, unblock };
}
export default beforeunload;

View file

@ -0,0 +1,21 @@
function throttle<Fn extends (...args: any[]) => any>(
fn: Fn,
ms: number
): (...args: Parameters<Fn>) => void {
let throttledFn = () => undefined;
let throttled: boolean = false;
return (...args: Parameters<Fn>): void => {
throttledFn = () => fn(...args);
if (throttled) return;
setTimeout(() => {
throttledFn();
throttled = false;
}, ms);
throttled = true;
};
}
export default throttle;

View file

@ -22,7 +22,7 @@ export default (props: { id: number }) => {
return (
<main>
<Editor />
<Editor id={props.id} />
<pre>{() => JSON.stringify(page(), null, " ")}</pre>
</main>
);