2022-08-23 09:01:47 +09:00
|
|
|
import { createResource } from "solid-js";
|
2022-08-24 12:49:02 +09:00
|
|
|
import type Pages from "../protocol/pages";
|
2022-08-23 09:01:47 +09:00
|
|
|
import Editor from "../components/editor";
|
2022-08-24 12:49:02 +09:00
|
|
|
import beforeunload from "../helpers/beforeunload";
|
|
|
|
import throttle from "../helpers/throttle";
|
2022-08-23 09:01:47 +09:00
|
|
|
|
2022-08-24 12:49:02 +09:00
|
|
|
const intervalMs = 333;
|
|
|
|
const { block, unblock } = beforeunload();
|
2022-08-23 09:01:47 +09:00
|
|
|
|
2022-08-24 12:49:02 +09:00
|
|
|
async function updatePage(
|
|
|
|
id: number,
|
|
|
|
content: Pages.RequestContentPage
|
|
|
|
): Promise<boolean> {
|
2022-08-28 19:57:18 +09:00
|
|
|
const res = await fetch(`/api/pages?id=eq.${id}`, {
|
|
|
|
method: "PUT",
|
|
|
|
headers: { "content-type": "application/json" },
|
|
|
|
body: JSON.stringify(content),
|
|
|
|
});
|
2022-08-24 12:49:02 +09:00
|
|
|
return res.ok;
|
|
|
|
}
|
|
|
|
|
2022-08-28 17:49:49 +09:00
|
|
|
async function deletePage(id: number): Promise<boolean> {
|
2022-08-28 19:57:18 +09:00
|
|
|
const res = await fetch(`/api/pages?id=eq.${id}`, { method: "DELETE" });
|
2022-08-28 17:49:49 +09:00
|
|
|
return res.ok;
|
|
|
|
}
|
|
|
|
|
2022-08-24 22:07:33 +09:00
|
|
|
async function fetchPage(id: number): Promise<Pages.ResponsePage> {
|
2022-08-28 19:57:18 +09:00
|
|
|
const res = await fetch(`/api/pages?id=eq.${id}`);
|
2022-08-24 12:49:02 +09:00
|
|
|
const data = (await res.json()) as Pages.Response;
|
|
|
|
return data[0]!;
|
2022-08-23 09:01:47 +09:00
|
|
|
}
|
|
|
|
|
|
|
|
export default (props: { id: number }) => {
|
2022-08-28 17:49:49 +09:00
|
|
|
const [page] = createResource(props.id, fetchPage);
|
2022-08-24 12:49:02 +09:00
|
|
|
const throttledUpdate = throttle(
|
|
|
|
async (id: number, content: Pages.RequestContentPage) => {
|
2022-08-28 17:49:49 +09:00
|
|
|
if (await (content.text ? updatePage(id, content) : deletePage(id))) {
|
2022-08-24 12:49:02 +09:00
|
|
|
unblock();
|
2022-08-28 17:49:49 +09:00
|
|
|
window.history.replaceState({}, "", `/${content.text ? id : "new"}`);
|
2022-08-24 12:49:02 +09:00
|
|
|
}
|
|
|
|
},
|
|
|
|
intervalMs
|
|
|
|
);
|
|
|
|
|
|
|
|
function onUpdatePage(content: Pages.RequestContentPage) {
|
|
|
|
block();
|
|
|
|
throttledUpdate(props.id, content);
|
|
|
|
}
|
2022-08-23 09:01:47 +09:00
|
|
|
|
|
|
|
return (
|
|
|
|
<main>
|
2022-08-28 17:49:49 +09:00
|
|
|
{() =>
|
|
|
|
!page.loading && (
|
|
|
|
<Editor
|
|
|
|
id={props.id}
|
|
|
|
title=""
|
|
|
|
text=""
|
|
|
|
{...page()}
|
|
|
|
onUpdatePage={onUpdatePage}
|
|
|
|
/>
|
|
|
|
)
|
|
|
|
}
|
2022-08-23 09:01:47 +09:00
|
|
|
</main>
|
|
|
|
);
|
|
|
|
};
|