NotesEditor.tsx

8.3 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  function scheduleAutosave() {37    setDirty(true);38    if (saveTimer) clearTimeout(saveTimer);39    saveTimer = window.setTimeout(save, AUTOSAVE_MS);40  }4142  async function save() {43    const t = title();44    const b = body();45    // Don't save if genuinely empty (new note, nothing typed)46    if (!t.trim() && !b.trim()) return;47    const res = await sendMessage({48      type: "SAVE_NOTE",49      payload: { id: noteId(), title: t || "Untitled", body: b },50    }) as { ok: boolean; data?: VaultEntry };51    if (res?.ok && res.data) {52      setNoteId(res.data.id);53      setDirty(false);54      showSaved();55      props.onSaved(res.data);56    }57  }5859  function showSaved() {60    setSaved(true);61    if (savedFadeTimer) clearTimeout(savedFadeTimer);62    savedFadeTimer = window.setTimeout(() => setSaved(false), SAVED_DISPLAY_MS);63  }6465  function exec(cmd: string, val?: string) {66    document.execCommand(cmd, false, val);67    bodyRef?.focus();68    scheduleAutosave();69  }7071  async function handleBack() {72    // Await the final save before navigating away — fire-and-forget would let73    // the component unmount before the message round-trip completes.74    if (dirty() && (title().trim() || body().trim())) {75      if (saveTimer) { clearTimeout(saveTimer); saveTimer = null; }76      await save();77    }78    props.onBack();79  }8081  function handleKeyboardResize() {82    if (!isNativePlatform()) return;83    const vp = window.visualViewport;84    const viewportH = vp?.height ?? window.innerHeight;85    const kbH = window.innerHeight - viewportH;86    if (kbH > 50) {87      setKeyboardVisible(true);88      setContentHeight(viewportH - HEADER_HEIGHT);89      if (document.activeElement) {90        (document.activeElement as HTMLElement).scrollIntoView?.({ behavior: "smooth", block: "nearest" });91      }92    } else {93      setKeyboardVisible(false);94      setContentHeight(null);95    }96  }9798  onMount(() => {99    // Populate editor content100    if (titleRef) titleRef.textContent = props.note?.title ?? "";101    // M15/THREAT-006: sanitize stored note body before assigning to innerHTML.102    if (bodyRef) bodyRef.innerHTML = toHtml(props.note?.notes ?? "");103104    if (props.autoFocusTitle && titleRef) {105      setTimeout(() => {106        titleRef.focus();107        // Place cursor at end108        const range = document.createRange();109        const sel = window.getSelection();110        range.selectNodeContents(titleRef);111        range.collapse(false);112        sel?.removeAllRanges();113        sel?.addRange(range);114      }, 300);115    }116117    if (isNativePlatform()) {118      window.addEventListener("resize", handleKeyboardResize);119    }120121    onCleanup(() => {122      if (saveTimer) clearTimeout(saveTimer);123      if (savedFadeTimer) clearTimeout(savedFadeTimer);124      if (isNativePlatform()) window.removeEventListener("resize", handleKeyboardResize);125    });126  });127128  // Swipe right from left edge to go back (mobile)129  let swipeStartX = 0;130  let swipeStartY = 0;131  let swipeCaptured = false;132133  function handleSwipeStart(e: TouchEvent) {134    const t = e.touches[0];135    if (!t) return;136    swipeStartX = t.clientX;137    swipeStartY = t.clientY;138    swipeCaptured = false;139  }140141  function handleSwipeMove(e: TouchEvent) {142    const t = e.touches[0];143    if (!t) return;144    const dx = t.clientX - swipeStartX;145    const dy = Math.abs(t.clientY - swipeStartY);146    if (!swipeCaptured && swipeStartX < 30 && dx > 40 && dy < dx) {147      swipeCaptured = true;148    }149  }150151  function handleSwipeEnd() {152    if (swipeCaptured) {153      handleBack();154    }155    swipeCaptured = false;156  }157158  const execFn: ToolbarExec = exec;159160  return (161    <div162      class="peach-note-editor-surface"163      onTouchStart={handleSwipeStart}164      onTouchMove={handleSwipeMove}165      onTouchEnd={handleSwipeEnd}166    >167      {/* Header */}168      <div class="peach-notes-header">169        <button class="peach-notes-back" onClick={handleBack} aria-label="Back to notes list">‹</button>170        <span class="peach-notes-header-title is-breadcrumb" onClick={handleBack}>notes</span>171        <div class="peach-notes-header-actions">172          <Show when={noteId()}>173            <button174              class="peach-notes-header-btn"175              aria-label="Delete note"176              onClick={() => {177                const id = noteId();178                if (!id) return;179                // Find entry by id for callback180                props.onDelete({ id, title: title(), notes: body(), type: "note", createdAt: 0, modifiedAt: Date.now() } as VaultEntry);181              }}182              title="Delete note"183            >184              <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">185                <polyline points="1,3.5 13,3.5" />186                <path d="M5 3.5V2h4v1.5" />187                <rect x="2.5" y="3.5" width="9" height="9" rx="1.5" />188                <line x1="5.5" y1="6.5" x2="5.5" y2="10" />189                <line x1="8.5" y1="6.5" x2="8.5" y2="10" />190              </svg>191            </button>192          </Show>193        </div>194      </div>195196      {/* Scrollable content */}197      <div198        ref={contentScrollRef}199        class="peach-note-editor-scroll"200        style={contentHeight() !== null ? { height: `${contentHeight()}px` } : undefined}201      >202        {/* Desktop toolbar — above content */}203        <Show when={!isNativePlatform()}>204          <NoteToolbar exec={execFn} />205        </Show>206207        <div208          ref={titleRef}209          class="peach-note-title-field"210          contenteditable="true"211          data-placeholder="Title"212          onInput={() => {213            setTitle(titleRef.textContent ?? "");214            scheduleAutosave();215          }}216          onKeyDown={(e) => {217            if (e.key === "Enter") {218              e.preventDefault();219              bodyRef?.focus();220            }221          }}222          aria-label="Note title"223        />224225        <div class="peach-note-hairline" />226227        <div228          ref={bodyRef}229          class="peach-note-body-field"230          contenteditable="true"231          data-placeholder="Begin writing…"232          onInput={() => {233            setBody(bodyRef.innerHTML ?? "");234            scheduleAutosave();235          }}236          onKeyDown={(e) => {237            const mod = e.metaKey || e.ctrlKey;238            if (mod && e.key === "b") { e.preventDefault(); exec("bold"); }239            if (mod && e.key === "i") { e.preventDefault(); exec("italic"); }240            if (mod && e.key === "u") { e.preventDefault(); exec("underline"); }241          }}242          aria-label="Note body"243          aria-multiline="true"244        />245      </div>246247      {/* Saved indicator */}248      <div class="peach-note-saved-indicator" style={{ opacity: saved() ? "1" : "0" }}>249        saved.250      </div>251252      {/* Mobile keyboard toolbar */}253      <Show when={isNativePlatform()}>254        <NoteToolbar255          exec={execFn}256          keyboardVisible={keyboardVisible()}257          onDismissKeyboard={() => {258            titleRef?.blur();259            bodyRef?.blur();260          }}261        />262      </Show>263    </div>264  );265}