1
0
Fork 0
mirror of https://github.com/kou029w/quot.git synced 2025-01-19 08:28:09 +00:00
quot/app/src/pages/page.tsx

74 lines
1.8 KiB
TypeScript
Raw Normal View History

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> {
const res = await fetch(
new URL(`/pages?id=eq.${id}`, import.meta.env.QUOT_API_URL),
{
method: "PUT",
headers: { "content-type": "application/json" },
body: JSON.stringify(content),
}
);
return res.ok;
}
2022-08-28 17:49:49 +09:00
async function deletePage(id: number): Promise<boolean> {
const res = await fetch(
new URL(`/pages?id=eq.${id}`, import.meta.env.QUOT_API_URL),
{ method: "DELETE" }
);
return res.ok;
}
2022-08-24 22:07:33 +09:00
async function fetchPage(id: number): Promise<Pages.ResponsePage> {
2022-08-23 09:01:47 +09:00
const res = await fetch(
new URL(`/pages?id=eq.${id}`, import.meta.env.QUOT_API_URL)
);
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>
);
};