Last active
December 19, 2023 12:20
-
-
Save jlandahl/c897fdfc06692295dd51f54c33783ce0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import setupViewEdit from "@lib/view_edit.tsx"; | |
import H2 from "@components/H2.tsx"; | |
import type model from "@/model.ts"; | |
export default function Prompt(props: any) { | |
const [editMode, prompt, EditButton] = setupViewEdit<model.Prompt>(`/api/prompt/${props.id}`, data); | |
function data(): string { | |
const text: HTMLInputElement = document.getElementById("text"); | |
let editForm = { | |
prompt_id: prompt().prompt_id, | |
prompt: text.value | |
} as model.PromptEditForm; | |
return JSON.stringify(editForm); | |
} | |
return <> | |
<H2>Prompt</H2> | |
<form> | |
ID: {prompt()?.prompt_id} | |
<br/> | |
<label for="text">Text:</label> | |
<textarea id="text" | |
name="text" | |
value={prompt()?.prompt} | |
class="block p-2.5 border border-gray-300 focus:ring-blue-500 focus:border-blue-500 dark:border-gray-600 dark:focus:ring-blue-500 dark:focus:border-blue-500" | |
rows={6} | |
cols={100} | |
wrap="soft" | |
disabled={!editMode()}/> | |
<p/> | |
<EditButton/> | |
</form> | |
</>; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createResource, createSignal } from 'solid-js'; | |
export default function setupViewEdit<T>(url: string, data: () => string) { | |
const [editMode, setEditMode] = createSignal(false); | |
const [record, { refetch }] = createResource(fetchRecord); | |
async function fetchRecord(): Promise<T> { | |
const response = await fetch(url); | |
return await response.json() | |
} | |
async function submit() { | |
if (!editMode()) { | |
return; | |
} | |
const _response = await fetch(url, | |
{ | |
method: "POST", | |
headers: { "Content-Type": "application/json" }, | |
body: data() | |
} | |
); | |
refetch(); | |
} | |
function toggleMode(e: Event) { | |
e.preventDefault(); | |
if (editMode()) { | |
submit(); | |
} | |
setEditMode(!editMode()); | |
} | |
function cancel(e: Event) { | |
e.preventDefault(); | |
setEditMode(!editMode()); | |
refetch(); | |
} | |
function EditButton(props: any) { | |
return <> | |
<button class="btn btn-primary" onClick={toggleMode}> | |
{editMode() ? 'Save' : 'Edit'} | |
</button> | |
<button class="btn" onClick={cancel} disabled={!editMode()}> | |
Cancel | |
</button> | |
</>; | |
} | |
return [editMode, record, EditButton]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment