Spaces:
Running

File size: 2,500 Bytes
64378fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import { createContext, html, useContext, useMemo, useRef, useState } from "./runtime.js";
import { useCloud } from "./cloud.js";

// ---------------------------------------------------------------------------
// Editable copy.
//
// Wrap any wording on the page in <Copy id="...">. 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}<//>`;
}