2026-06-14 00:47:14 -04:00
|
|
|
import { useCallback, useEffect, useState } from 'react';
|
|
|
|
|
import { MatrixClient } from 'matrix-js-sdk';
|
|
|
|
|
import { useMatrixClient } from './useMatrixClient';
|
|
|
|
|
import { useAccountDataCallback } from './useAccountDataCallback';
|
|
|
|
|
|
|
|
|
|
const NOTES_KEY = 'io.lotus.user_notes';
|
|
|
|
|
export const USER_NOTE_MAX_LENGTH = 500;
|
|
|
|
|
|
|
|
|
|
type UserNotesContent = Record<string, string>;
|
|
|
|
|
|
|
|
|
|
function readNotes(mx: MatrixClient): UserNotesContent {
|
|
|
|
|
return (mx.getAccountData(NOTES_KEY as any)?.getContent() as UserNotesContent | undefined) ?? {};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function useUserNotes(): {
|
|
|
|
|
getNote: (userId: string) => string;
|
|
|
|
|
setNote: (userId: string, note: string) => Promise<void>;
|
|
|
|
|
} {
|
|
|
|
|
const mx = useMatrixClient();
|
|
|
|
|
const [notes, setNotes] = useState<UserNotesContent>(() => readNotes(mx));
|
|
|
|
|
|
|
|
|
|
useAccountDataCallback(
|
|
|
|
|
mx,
|
2026-06-15 20:50:00 -04:00
|
|
|
useCallback((evt) => {
|
|
|
|
|
if (evt.getType() === NOTES_KEY) {
|
|
|
|
|
setNotes(evt.getContent<UserNotesContent>() ?? {});
|
|
|
|
|
}
|
|
|
|
|
}, []),
|
2026-06-14 00:47:14 -04:00
|
|
|
);
|
|
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
setNotes(readNotes(mx));
|
|
|
|
|
}, [mx]);
|
|
|
|
|
|
|
|
|
|
const getNote = useCallback((userId: string) => notes[userId] ?? '', [notes]);
|
|
|
|
|
|
|
|
|
|
const setNote = useCallback(
|
|
|
|
|
async (userId: string, note: string) => {
|
|
|
|
|
const current = readNotes(mx);
|
|
|
|
|
const updated = { ...current };
|
|
|
|
|
const trimmed = note.trim().slice(0, USER_NOTE_MAX_LENGTH);
|
|
|
|
|
if (trimmed) {
|
|
|
|
|
updated[userId] = trimmed;
|
|
|
|
|
} else {
|
|
|
|
|
delete updated[userId];
|
|
|
|
|
}
|
|
|
|
|
await (mx as any).setAccountData(NOTES_KEY, updated);
|
|
|
|
|
},
|
|
|
|
|
[mx],
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
return { getNote, setNote };
|
|
|
|
|
}
|