Files
website/src/hooks/useLocalStorage.ts
mroxso e7cf9c4677 feat: local draft notes with a blank "new note" entry point (#28)
* feat: local draft notes with a blank "new note" entry point

Writing was tied to publishing: the Feed composer either sits empty
or fires a note straight to relays, with nowhere to keep something
you're not ready to publish yet.

The Note app now supports a draft mode when opened without an id: a
blank note kept in localStorage until you publish it or discard it,
reachable via a new "New note" button in the Feed toolbar, the Go
menu, or the command palette (all already open the Note app with no
params).

Closes #19

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BYiUtZMQeA5RHggQw73wto

* fix: guard against double-publish and dropped relay params

Per review:
- handlePublish now also checks publish.isPending itself, not just
  the button's disabled state — a second click landing before React
  re-renders could otherwise fire mutateAsync twice.
- Publishing a draft now merges into the existing params instead of
  replacing them outright, so relay hints (or anything else already
  in params) survive the id being added.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BYiUtZMQeA5RHggQw73wto

* docs: mark notes app's id param as optional

Per review — the draft mode added by this PR means id is no longer
required to open the Note app.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BYiUtZMQeA5RHggQw73wto

* fix: sync useLocalStorage across same-tab consumers of one key

Per review: the Notes app is explicitly non-singleton, so opening two
"New Note" windows meant two DraftNote instances writing the same
localStorage key independently — the native `storage` event only
fires in *other* tabs/documents, never the one that wrote, so the two
windows would silently diverge (discard/publish in one wouldn't
update the other).

useLocalStorage now also dispatches a same-document custom event on
every write, and every instance sharing that key listens for it —
verified live with two open draft windows staying in sync as one is
typed into.

Also dropped a redundant `{}` params argument on an openApp() call
that every other call site omits when opening with no parameters.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BYiUtZMQeA5RHggQw73wto

---------

Co-authored-by: highperfocused <highperfocused@pm.me>
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
2026-09-06 18:40:40 +02:00

96 lines
3.0 KiB
TypeScript

import { useCallback, useEffect, useState } from 'react';
/**
* Fired on `window` whenever `useLocalStorage` writes a key, so every
* component sharing that key *within this document* stays in sync — the
* native `storage` event only fires in *other* tabs/documents, never the
* one that made the write. Without this, e.g. two "New Note" draft windows
* open at once would silently diverge: each holds its own React state, both
* write to the same localStorage entry, and neither sees the other's edits.
*/
const LOCAL_STORAGE_EVENT = 'app:local-storage';
interface LocalStorageEventDetail {
key: string;
value: string;
}
/**
* Generic hook for managing localStorage state
*/
export function useLocalStorage<T>(
key: string,
defaultValue: T,
serializer?: {
serialize: (value: T) => string;
deserialize: (value: string) => T;
}
) {
const serialize = serializer?.serialize || JSON.stringify;
const deserialize = serializer?.deserialize || JSON.parse;
const [state, setState] = useState<T>(() => {
try {
const item = localStorage.getItem(key);
return item ? deserialize(item) : defaultValue;
} catch (error) {
console.warn(`Failed to load ${key} from localStorage:`, error);
return defaultValue;
}
});
const setValue = useCallback(
(value: T | ((prev: T) => T)) => {
setState((prev) => {
try {
const valueToStore = value instanceof Function ? value(prev) : value;
const serialized = serialize(valueToStore);
localStorage.setItem(key, serialized);
window.dispatchEvent(
new CustomEvent<LocalStorageEventDetail>(LOCAL_STORAGE_EVENT, {
detail: { key, value: serialized },
}),
);
return valueToStore;
} catch (error) {
console.warn(`Failed to save ${key} to localStorage:`, error);
return prev;
}
});
},
[key, serialize],
);
// Sync with localStorage changes from other tabs, and from other
// components sharing this key in this tab (see LOCAL_STORAGE_EVENT above).
useEffect(() => {
const handleStorageChange = (e: StorageEvent) => {
if (e.key === key && e.newValue !== null) {
try {
setState(deserialize(e.newValue));
} catch (error) {
console.warn(`Failed to sync ${key} from localStorage:`, error);
}
}
};
const handleLocalChange = (e: Event) => {
const detail = (e as CustomEvent<LocalStorageEventDetail>).detail;
if (detail?.key !== key) return;
try {
setState(deserialize(detail.value));
} catch (error) {
console.warn(`Failed to sync ${key} from localStorage:`, error);
}
};
window.addEventListener('storage', handleStorageChange);
window.addEventListener(LOCAL_STORAGE_EVENT, handleLocalChange);
return () => {
window.removeEventListener('storage', handleStorageChange);
window.removeEventListener(LOCAL_STORAGE_EVENT, handleLocalChange);
};
}, [key, deserialize]);
return [state, setValue] as const;
}