import { createContext, html, useContext, useMemo, useRef, useState } from "./runtime.js";
import { useCloud } from "./cloud.js";
// ---------------------------------------------------------------------------
// Editable copy.
//
// Wrap any wording on the page in . When the developer turns
// edit mode on, each wrapped phrase becomes editable in place; saving writes
// the new wording to Supabase, so every visitor sees it. A key that has never
// been edited falls back to the wording written in the code.
// ---------------------------------------------------------------------------
const EditContext = createContext({ editing: false, setEditing: () => {} });
export function EditModeProvider({ children }) {
const [editing, setEditing] = useState(false);
const value = useMemo(() => ({ editing, setEditing }), [editing]);
return html`<${EditContext.Provider} value=${value}>${children}/>`;
}
export function useEditMode() {
return useContext(EditContext);
}
function toText(children) {
if (typeof children === "string") return children;
if (Array.isArray(children)) return children.map(toText).join("");
if (children == null || children === false) return "";
return String(children);
}
export function useCopyValue(id, fallback) {
const cloud = useCloud();
const saved = cloud.content[id];
return saved != null && saved !== "" ? saved : fallback;
}
export function Copy({ id, as = "span", className = "", children }) {
const cloud = useCloud();
const { editing } = useEditMode();
const fallback = toText(children);
const saved = cloud.content[id];
const value = saved != null && saved !== "" ? saved : fallback;
const ref = useRef(null);
const onBlur = async (event) => {
if (!editing) return;
const text = (event.currentTarget.innerText || "").replace(/\s+/g, " ").trim();
if (!text || text === value) return;
try {
await cloud.setContent(id, text);
cloud.flash("Saved — everyone will see this.");
} catch (err) {
cloud.flash(err && err.message ? err.message : "Could not save that change.");
}
};
const Tag = as;
return html`<${Tag}
ref=${ref}
className=${className + (editing ? " edit-target" : "")}
contentEditable=${editing ? "true" : undefined}
suppressContentEditableWarning=${true}
onBlur=${onBlur}
spellCheck=${false}
data-copy=${id}
title=${editing ? "Type to change this wording. It saves for everyone." : undefined}
>${value}/>`;
}