2026-07-07 23:24:08 -04:00
|
|
|
import { useCallback } from 'react';
|
2026-06-14 00:47:14 -04:00
|
|
|
import { useMatrixClient } from './useMatrixClient';
|
2026-07-07 23:24:08 -04:00
|
|
|
import { createAccountDataListStore } from './createAccountDataListStore';
|
2026-06-14 00:47:14 -04:00
|
|
|
|
|
|
|
|
const NOTES_KEY = 'io.lotus.user_notes';
|
|
|
|
|
export const USER_NOTE_MAX_LENGTH = 500;
|
|
|
|
|
|
|
|
|
|
type UserNotesContent = Record<string, string>;
|
|
|
|
|
|
2026-07-07 23:24:08 -04:00
|
|
|
// Shared, concurrency-safe store. See createAccountDataListStore for why the
|
|
|
|
|
// snapshot + write queue must be module-scoped (writes are serialized to avoid
|
|
|
|
|
// lost updates, since setAccountData replaces the whole content with no merge).
|
2026-07-02 20:56:27 -04:00
|
|
|
//
|
2026-07-07 23:24:08 -04:00
|
|
|
// Notes are a flat Record<userId, note> rather than a wrapped list, so `read`
|
|
|
|
|
// and `write` pass the content through unchanged.
|
|
|
|
|
const notesStore = createAccountDataListStore<UserNotesContent, UserNotesContent>({
|
|
|
|
|
eventType: NOTES_KEY,
|
|
|
|
|
read: (content) => content ?? {},
|
|
|
|
|
write: (notes) => notes,
|
|
|
|
|
});
|
2026-07-02 20:56:27 -04:00
|
|
|
|
2026-06-14 00:47:14 -04:00
|
|
|
export function useUserNotes(): {
|
|
|
|
|
getNote: (userId: string) => string;
|
|
|
|
|
setNote: (userId: string, note: string) => Promise<void>;
|
|
|
|
|
} {
|
|
|
|
|
const mx = useMatrixClient();
|
2026-07-07 23:24:08 -04:00
|
|
|
const notes = notesStore.useValue(mx);
|
2026-06-14 00:47:14 -04:00
|
|
|
|
|
|
|
|
const getNote = useCallback((userId: string) => notes[userId] ?? '', [notes]);
|
|
|
|
|
|
|
|
|
|
const setNote = useCallback(
|
2026-07-02 20:56:27 -04:00
|
|
|
(userId: string, note: string) => {
|
2026-06-14 00:47:14 -04:00
|
|
|
const trimmed = note.trim().slice(0, USER_NOTE_MAX_LENGTH);
|
2026-07-07 23:24:08 -04:00
|
|
|
return notesStore.enqueueWrite(mx, (current) => {
|
2026-07-02 20:56:27 -04:00
|
|
|
const updated = { ...current };
|
|
|
|
|
if (trimmed) {
|
|
|
|
|
updated[userId] = trimmed;
|
|
|
|
|
} else {
|
|
|
|
|
delete updated[userId];
|
|
|
|
|
}
|
|
|
|
|
return updated;
|
|
|
|
|
});
|
2026-06-14 00:47:14 -04:00
|
|
|
},
|
|
|
|
|
[mx],
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
return { getNote, setNote };
|
|
|
|
|
}
|