NotesEditor.tsx

8.7 KB · raw

1import { createSignal, onCleanup, onMount, Show } from "solid-js";2import type { VaultEntry } from "../../shared/types";3import { sendMessage } from "../../shared/bridge";4import { isNativePlatform } from "../../shared/native";5import { NoteToolbar, type ToolbarExec } from "../components/NoteToolbar";6import { toHtml } from "./NoteEditor";78const HEADER_HEIGHT = 52;9const AUTOSAVE_MS = 800;10const SAVED_DISPLAY_MS = 1500;1112interface NotesEditorProps {13  note: VaultEntry | null; // null = new note14  onBack: () => void;15  onSaved: (note: VaultEntry) => void;16  onDelete: (note: VaultEntry) => void;17  autoFocusTitle?: boolean;18}1920export function NotesEditor(props: NotesEditorProps) {21  let titleRef!: HTMLDivElement;22  let bodyRef!: HTMLDivElement;23  let contentScrollRef!: HTMLDivElement;2425  const [noteId, setNoteId] = createSignal<string | undefined>(props.note?.id);26  const [title, setTitle] = createSignal(props.note?.title ?? "");27  const [body, setBody] = createSignal(props.note?.notes ?? "");28  const [saved, setSaved] = createSignal(false);29  const [keyboardVisible, setKeyboardVisible] = createSignal(false);30  const [contentHeight, setContentHeight] = createSignal<number | null>(null);31  const [dirty, setDirty] = createSignal(false);3233  let saveTimer: number | null = null;34  let savedFadeTimer: number | null = null;3536  // An "empty" contenteditable body frequently serialises to "<br>", a37  // zero-width space, &nbsp;, or whitespace-only markup rather than "". Trim38  // alone can't catch those, so strip tags/entities/formatting and check for39  // any actual visible character before deciding a note has content.40  function bodyIsBlank(html: string): boolean {41    return !html42      .replace(/<[^>]*>|&nbsp;|&#160;|\u200b|\ufeff/g, "")43      .replace(/\s+/g, "");44  }4546  function scheduleAutosave() {47    setDirty(true);48    if (saveTimer) clearTimeout(saveTimer);49    saveTimer = window.setTimeout(save, AUTOSAVE_MS);50  }5152  async function save() {53    const t = title();54    const b = body();55    // Don't save if genuinely empty (new note, nothing typed)56    if (!t.trim() && bodyIsBlank(b)) return;57    const res = await sendMessage({58      type: "SAVE_NOTE",59      payload: { id: noteId(), title: t || "Untitled", body: b },60    }) as { ok: boolean; data?: VaultEntry };61    if (res?.ok && res.data) {62      setNoteId(res.data.id);63      setDirty(false);64      showSaved();65      props.onSaved(res.data);66    }67  }6869  function showSaved() {70    setSaved(true);71    if (savedFadeTimer) clearTimeout(savedFadeTimer);72    savedFadeTimer = window.setTimeout(() => setSaved(false), SAVED_DISPLAY_MS);73  }7475  function exec(cmd: string, val?: string) {76    document.execCommand(cmd, false, val);77    bodyRef?.focus();78    scheduleAutosave();79  }8081  async function handleBack() {82    // Await the final save before navigating away — fire-and-forget would let83    // the component unmount before the message round-trip completes.84    if (dirty() && (title().trim() || !bodyIsBlank(body()))) {85      if (saveTimer) { clearTimeout(saveTimer); saveTimer = null; }86      await save();87    }88    props.onBack();89  }9091  function handleKeyboardResize() {92    if (!isNativePlatform()) return;93    const vp = window.visualViewport;94    const viewportH = vp?.height ?? window.innerHeight;95    const kbH = window.innerHeight - viewportH;96    if (kbH > 50) {97      setKeyboardVisible(true);98      setContentHeight(viewportH - HEADER_HEIGHT);99      if (document.activeElement) {100        (document.activeElement as HTMLElement).scrollIntoView?.({ behavior: "smooth", block: "nearest" });101      }102    } else {103      setKeyboardVisible(false);104      setContentHeight(null);105    }106  }107108  onMount(() => {109    // Populate editor content110    if (titleRef) titleRef.textContent = props.note?.title ?? "";111    // M15/THREAT-006: sanitize stored note body before assigning to innerHTML.112    if (bodyRef) bodyRef.innerHTML = toHtml(props.note?.notes ?? "");113114    if (props.autoFocusTitle && titleRef) {115      setTimeout(() => {116        titleRef.focus();117        // Place cursor at end118        const range = document.createRange();119        const sel = window.getSelection();120        range.selectNodeContents(titleRef);121        range.collapse(false);122        sel?.removeAllRanges();123        sel?.addRange(range);124      }, 300);125    }126127    if (isNativePlatform()) {128      window.addEventListener("resize", handleKeyboardResize);129    }130131    onCleanup(() => {132      if (saveTimer) clearTimeout(saveTimer);133      if (savedFadeTimer) clearTimeout(savedFadeTimer);134      if (isNativePlatform()) window.removeEventListener("resize", handleKeyboardResize);135    });136  });137138  // Swipe right from left edge to go back (mobile)139  let swipeStartX = 0;140  let swipeStartY = 0;141  let swipeCaptured = false;142143  function handleSwipeStart(e: TouchEvent) {144    const t = e.touches[0];145    if (!t) return;146    swipeStartX = t.clientX;147    swipeStartY = t.clientY;148    swipeCaptured = false;149  }150151  function handleSwipeMove(e: TouchEvent) {152    const t = e.touches[0];153    if (!t) return;154    const dx = t.clientX - swipeStartX;155    const dy = Math.abs(t.clientY - swipeStartY);156    if (!swipeCaptured && swipeStartX < 30 && dx > 40 && dy < dx) {157      swipeCaptured = true;158    }159  }160161  function handleSwipeEnd() {162    if (swipeCaptured) {163      handleBack();164    }165    swipeCaptured = false;166  }167168  const execFn: ToolbarExec = exec;169170  return (171    <div172      class="peach-note-editor-surface"173      onTouchStart={handleSwipeStart}174      onTouchMove={handleSwipeMove}175      onTouchEnd={handleSwipeEnd}176    >177      {/* Header */}178      <div class="peach-notes-header">179        <button class="peach-notes-back" onClick={handleBack} aria-label="Back to notes list">‹</button>180        <span class="peach-notes-header-title is-breadcrumb" onClick={handleBack}>notes</span>181        <div class="peach-notes-header-actions">182          <Show when={noteId()}>183            <button184              class="peach-notes-header-btn"185              aria-label="Delete note"186              onClick={() => {187                const id = noteId();188                if (!id) return;189                // Find entry by id for callback190                props.onDelete({ id, title: title(), notes: body(), type: "note", createdAt: 0, modifiedAt: Date.now() } as VaultEntry);191              }}192              title="Delete note"193            >194              <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">195                <polyline points="1,3.5 13,3.5" />196                <path d="M5 3.5V2h4v1.5" />197                <rect x="2.5" y="3.5" width="9" height="9" rx="1.5" />198                <line x1="5.5" y1="6.5" x2="5.5" y2="10" />199                <line x1="8.5" y1="6.5" x2="8.5" y2="10" />200              </svg>201            </button>202          </Show>203        </div>204      </div>205206      {/* Scrollable content */}207      <div208        ref={contentScrollRef}209        class="peach-note-editor-scroll"210        style={contentHeight() !== null ? { height: `${contentHeight()}px` } : undefined}211      >212        {/* Desktop toolbar — above content */}213        <Show when={!isNativePlatform()}>214          <NoteToolbar exec={execFn} />215        </Show>216217        <div218          ref={titleRef}219          class="peach-note-title-field"220          contenteditable="true"221          data-placeholder="Title"222          onInput={() => {223            setTitle(titleRef.textContent ?? "");224            scheduleAutosave();225          }}226          onKeyDown={(e) => {227            if (e.key === "Enter") {228              e.preventDefault();229              bodyRef?.focus();230            }231          }}232          aria-label="Note title"233        />234235        <div class="peach-note-hairline" />236237        <div238          ref={bodyRef}239          class="peach-note-body-field"240          contenteditable="true"241          data-placeholder="Begin writing…"242          onInput={() => {243            setBody(bodyRef.innerHTML ?? "");244            scheduleAutosave();245          }}246          onKeyDown={(e) => {247            const mod = e.metaKey || e.ctrlKey;248            if (mod && e.key === "b") { e.preventDefault(); exec("bold"); }249            if (mod && e.key === "i") { e.preventDefault(); exec("italic"); }250            if (mod && e.key === "u") { e.preventDefault(); exec("underline"); }251          }}252          aria-label="Note body"253          aria-multiline="true"254        />255      </div>256257      {/* Saved indicator */}258      <div class="peach-note-saved-indicator" style={{ opacity: saved() ? "1" : "0" }}>259        saved.260      </div>261262      {/* Mobile keyboard toolbar */}263      <Show when={isNativePlatform()}>264        <NoteToolbar265          exec={execFn}266          keyboardVisible={keyboardVisible()}267          onDismissKeyboard={() => {268            titleRef?.blur();269            bodyRef?.blur();270          }}271        />272      </Show>273    </div>274  );275}