1
0
Fork 0
mirror of https://github.com/kou029w/quot.git synced 2025-01-19 16:38:06 +00:00
quot/app/views/pages/page.tsx

86 lines
2.2 KiB
TypeScript
Raw Normal View History

2022-08-23 09:01:47 +09:00
import { createResource } from "solid-js";
2022-09-01 23:54:20 +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 { 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 jwt = window.localStorage.getItem("jwt");
2022-08-29 01:02:47 +09:00
const res = await fetch(
`${import.meta.env.QUOT_API_ENDPOINT}/pages?id=eq.${id}`,
2022-08-29 01:02:47 +09:00
{
method: "PUT",
headers: {
2022-09-06 23:43:35 +09:00
...(jwt ? { authorization: `Bearer ${jwt}` } : {}),
"content-type": "application/json",
},
2022-08-29 01:02:47 +09:00
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> {
const jwt = window.localStorage.getItem("jwt");
2022-08-29 01:02:47 +09:00
const res = await fetch(
`${import.meta.env.QUOT_API_ENDPOINT}/pages?id=eq.${id}`,
{
method: "DELETE",
2022-09-06 23:43:35 +09:00
headers: jwt ? { authorization: `Bearer ${jwt}` } : {},
}
2022-08-29 01:02:47 +09:00
);
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> {
const jwt = window.localStorage.getItem("jwt");
2022-08-29 01:02:47 +09:00
const res = await fetch(
`${import.meta.env.QUOT_API_ENDPOINT}/pages?id=eq.${id}`,
{ headers: jwt ? { authorization: `Bearer ${jwt}` } : {} }
2022-08-29 01:02:47 +09:00
);
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-29 10:39:16 +09:00
window.history.replaceState(
{},
"",
`/${content.text ? id.toString(16) : "new"}`
);
2022-08-24 12:49:02 +09:00
}
2022-09-01 10:03:59 +09:00
}
2022-08-24 12:49:02 +09:00
);
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>
);
};