import React, { useEffect, useState } from "https://esm.sh/react";
import { createRoot } from "https://esm.sh/react-dom/client";
function App() {
const [note, setNote] = useState("");
const [loading, setLoading] = useState(true);
useEffect(() => {
fetchTodayNote();
}, []);
const fetchTodayNote = async () => {
setLoading(true);
const response = await fetch("/get-note");
const data = await response.json();
setNote(data.note);
setLoading(false);
};
const generateNewNote = async () => {
setLoading(true);
await fetch("/generate-note", { method: "POST" });
await fetchTodayNote();
};
return (
<div className="container">
<h1>Daily Note for My Daughter đź’–</h1>
{loading ? <p>Loading...</p> : (
<div className="note-container">
<p className="note">{note}</p>
</div>
)}
<button onClick={generateNewNote} disabled={loading}>
Generate New Note
</button>
<p className="footer">
<a href={import.meta.url.replace("esm.town", "val.town")}>View Source</a>
</p>
</div>
);
}
function client() {
createRoot(document.getElementById("root")).render(<App />);
}
if (typeof document !== "undefined") { client(); }
async function server(request: Request): Promise<Response> {
const { OpenAI } = await import("https://esm.town/v/std/openai");
const { sqlite } = await import("https://esm.town/v/stevekrouse/sqlite");
const KEY = new URL(import.meta.url).pathname.split("/").at(-1);
await sqlite.execute(`
CREATE TABLE IF NOT EXISTS ${KEY}_daughter_notes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
note TEXT NOT NULL,
date TEXT NOT NULL UNIQUE
)
`);
const path = new URL(request.url).pathname;
if (path === "/get-note") {
const today = new Date().toISOString().split("T")[0];
const result = await sqlite.execute(`SELECT note FROM ${KEY}_daughter_notes WHERE date = ?`, [today]);
if (result.rows.length > 0) {
return new Response(JSON.stringify({ note: result.rows[0].note }), {
headers: { "Content-Type": "application/json" },
});
} else {
return new Response(JSON.stringify({ note: "No note generated for today yet. Click 'Generate New Note'!" }), {
headers: { "Content-Type": "application/json" },
});
}
} else if (path === "/generate-note" && request.method === "POST") {
const openai = new OpenAI();
const completion = await openai.chat.completions.create({
messages: [
{
role: "system",
content: "You are a loving mother writing a short, cute note to your daughter. Keep it under 50 words.",
},
{ role: "user", content: "Write a cute, encouraging note for my daughter." },
],
model: "gpt-4o-mini",
max_tokens: 100,
});
const newNote = completion.choices[0].message.content.trim();