import { renderToString } from "https://esm.sh/react-dom@18.2.0/server";
import { useEffect, useState } from "https://esm.sh/react@18.2.0";
import { extractValInfo } from "https://esm.town/v/pomdtr/extractValInfo?v=25";
import { html } from "https://esm.town/v/stevekrouse/html";
export const Button = (props) => {
const [clientHydrated, setClientHydrated] = useState(false);
useEffect(() => setClientHydrated(true), []);
return <button disabled={!clientHydrated} {...props}></button>;
};
export const Form = ({ onSubmit, ...props }: any) => {
const [clientHydrated, setClientHydrated] = useState(false);
useEffect(() => setClientHydrated(true), []);
return (
<form
disabled={!clientHydrated}
onSubmit={async (e) => {
e.preventDefault();
const onData = onSubmit ? onSubmit(e) : () => 1;
const formData = new FormData(e.target as any);
const resp = await fetch("/", {
method: props.action ?? "POST",
body: formData,
});
await onData(resp);
}}
{...props}
>
</form>
);
};
export const hydrate = (importMetaURL: string) =>
async function(req: Request): Promise<Response> {
const { author, name } = extractValInfo(importMetaURL);
const valURL = `https://www.val.town/v/${author}/${name}`;
const moduleURL = `https://esm.town/v/${author}/${name}`;
const exports = await import(moduleURL);
const action = exports.action ?? (() => ({}));
const loader = exports.loader ?? (() => ({}));
const Component = exports.Component ?? (() => (
<div>
Error: Please ensure you <code>export Component</code>" in{" "}
<a target="_blank" href={valURL}>@{author}/{name}</a>.
</div>
));
if (req.method === "GET") {
const props = await loader(req);
const script = `
import { hydrateRoot } from "https://esm.sh/react-dom@18.2.0/client";
import { jsx as _jsx } from "https://esm.sh/react@18.2.0/jsx-runtime";
import { Component } from "https://esm.town/v/${author}/${name}";
let props = ${JSON.stringify(props)}
try {
hydrateRoot(document, _jsx(Component, props));
} catch (e) {
console.error(e)
}
`;
return html(renderToString(
<>
<Component {...props} />
<script type="module" dangerouslySetInnerHTML={{ __html: script }} />
</>,
));
} else {
return action(req);
}
};