<script lang="ts">
import { untrack } from "svelte";
import { gists } from "../../stores/gists.svelte.js";
import { workbench } from "../../stores/workbench.svelte.js";
import type { CreateGistRequest, UpdateGistRequest } from "../../api/types.js";
import GistEditor from "./GistEditor.svelte";
interface Props {
mode: "create" | "edit";
gistId?: string;
}
let { mode, gistId }: Props = $props();
// What this effect is about is the two props above it: which gist, and
// whether we are editing or creating. Everything the calls below touch is a
// consequence of that, not a trigger for it — and left tracked, a store
// method that reads and writes the same field turns the effect into a loop
// that freezes the whole page (`effect_update_depth_exceeded`).
$effect(() => {
const currentMode = mode;
const currentId = gistId;
untrack(() => {
if (currentMode === "edit" && currentId) {
void gists.selectGist(currentId);
}
if (currentMode === "create") {
gists.clearSelection();
}
});
});
async function handleSave(payload: CreateGistRequest | UpdateGistRequest) {
if (mode === "create") {
const gist = await gists.create(payload as CreateGistRequest);
workbench.close("gist:new");
workbench.openGist(gist);
return;
}
if (!gistId) {
throw new Error("gist id is required for edit mode");
}
const gist = await gists.update(gistId, payload as UpdateGistRequest);
workbench.openGist(gist);
}
</script>
<GistEditor
gist={gists.selectedGist}
{mode}
loading={gists.detailLoading}
saving={gists.saving}
error={gists.detailError}
onsave={handleSave}
oncancelcreate={() => workbench.close("gist:new")}
/>