Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
118 changes: 76 additions & 42 deletions src/components/NoteManager/NoteManager.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { memo, useCallback, useContext, useEffect, useRef } from "react";
import "./NoteManager.css";
import type { ISynctexBlockId } from "@fluffylabs/links-metadata";
import { cn } from "@fluffylabs/shared-ui";
import { Alert, Button, cn } from "@fluffylabs/shared-ui";
import { twMerge } from "tailwind-merge";
import { useLatestCallback } from "../../hooks/useLatestCallback";
import { type ILocationContext, LocationContext } from "../LocationProvider/LocationProvider";
Expand All @@ -12,6 +12,7 @@ import { type ISelectionContext, SelectionContext } from "../SelectionProvider/S
import { InactiveNoteSkeleton } from "./components/InactiveNoteSkeleton";
import { NewNote } from "./components/NewNote";
import { NotesList } from "./components/NotesList";
import { useFilteredNoteAlert } from "./hooks/useFilteredNoteAlert";
import { useNoteManagerNotes } from "./useNoteManagerNotes";

const DEFAULT_AUTHOR = "";
Expand All @@ -31,7 +32,7 @@ function Notes() {
const {
notesManagerNotes: notes,
activeNotes,
latestHandleAddNote,
addNote,
sectionTitlesLoaded,
notesReady,
deleteNote,
Expand All @@ -40,6 +41,7 @@ function Notes() {
const { selectedBlocks, pageNumber, handleClearSelection } = useContext(SelectionContext) as ISelectionContext;
const keepShowingNewNote = useRef<{ selectionEnd: ISynctexBlockId; selectionStart: ISynctexBlockId }>(undefined);
const latestHandleClearSelection = useLatestCallback(handleClearSelection);
const { noteAlertVisibilityState, triggerFilteredNoteAlert, closeNoteAlert } = useFilteredNoteAlert();

const memoizedHandleDeleteNote = useCallback(
(note: IDecoratedNote) => {
Expand All @@ -53,9 +55,14 @@ function Notes() {
(note: IDecoratedNote, newNote: IStorageNote) => {
// NOTE(optimistic): intentional mutation for immediate UI feedback; be aware this bypasses immutability
note.original.content = newNote.content;
updateNote(note, newNote);
note.original.labels = newNote.labels;
const { isVisible } = updateNote(note, newNote);
if (!isVisible) {
handleClearSelection();
triggerFilteredNoteAlert("visibleForUpdated");
}
},
[updateNote],
[updateNote, handleClearSelection, triggerFilteredNoteAlert],
);

const handleNewNoteCancel = useCallback(() => {
Expand Down Expand Up @@ -84,13 +91,19 @@ function Notes() {
labels,
};

latestHandleAddNote.current(newNote);
const { isVisible } = addNote(newNote);

if (!isVisible) {
triggerFilteredNoteAlert("visibleForCreated");
handleClearSelection();
}

keepShowingNewNote.current = {
selectionStart: locationParams.selectionStart,
selectionEnd: locationParams.selectionEnd,
};
},
[pageNumber, selectedBlocks, locationParams, latestHandleAddNote],
[pageNumber, selectedBlocks, locationParams, addNote, handleClearSelection, triggerFilteredNoteAlert],
);

const locationRef = useRef({ locationParams, setLocationParams });
Expand Down Expand Up @@ -133,44 +146,65 @@ function Notes() {
}, [readyAndLoaded]);

return (
<div className={cn("note-manager flex flex-col gap-2.5", !readyAndLoaded && "opacity-30 pointer-events-none")}>
{locationParams.selectionEnd &&
locationParams.selectionStart &&
pageNumber !== null &&
selectedBlocks.length > 0 &&
!isActiveNotes &&
(readyAndLoaded || areSelectionsEqual(locationParams, keepShowingNewNote.current)) && (
<NewNote
selectionStart={locationParams.selectionStart}
selectionEnd={locationParams.selectionEnd}
version={locationParams.version}
onCancel={handleNewNoteCancel}
onSave={handleAddNoteClick}
/>
)}

{!readyAndLoaded && notes.length === 0 && (
<>
<InactiveNoteSkeleton />
<InactiveNoteSkeleton />
<InactiveNoteSkeleton />
<InactiveNoteSkeleton />
</>
<>
{noteAlertVisibilityState !== "hidden" && (
<Alert intent="warning">
<Alert.Title>
{noteAlertVisibilityState === "visibleForUpdated"
? "Note hidden after update"
: "Note hidden by label filter"}
</Alert.Title>
<div className="flex gap-4">
<Alert.Text>
{noteAlertVisibilityState === "visibleForUpdated"
? "Updated note doesn't match active labels."
: "Created note doesn't match active labels."}
</Alert.Text>
<Button variant="secondary" intent="warning" size="sm" className="self-end" onClick={closeNoteAlert}>
Close
</Button>
</div>
</Alert>
)}
<div className={cn("note-manager flex flex-col gap-2.5", !readyAndLoaded && "opacity-30 pointer-events-none")}>
{locationParams.selectionEnd &&
locationParams.selectionStart &&
pageNumber !== null &&
selectedBlocks.length > 0 &&
!isActiveNotes &&
(readyAndLoaded || areSelectionsEqual(locationParams, keepShowingNewNote.current)) && (
<NewNote
selectionStart={locationParams.selectionStart}
selectionEnd={locationParams.selectionEnd}
version={locationParams.version}
onCancel={handleNewNoteCancel}
onSave={handleAddNoteClick}
/>
)}

{!readyAndLoaded && notes.length === 0 && (
<>
<InactiveNoteSkeleton />
<InactiveNoteSkeleton />
<InactiveNoteSkeleton />
<InactiveNoteSkeleton />
</>
)}

{readyAndLoaded && notes.length === 0 && (
<div className="no-notes text-sidebar-foreground">No notes available</div>
)}
{readyAndLoaded && notes.length === 0 && (
<div className="no-notes text-sidebar-foreground">No notes available</div>
)}

{notes.length > 0 && (
<MemoizedNotesList
activeNotes={activeNotes}
notes={notes}
onEditNote={memoizedHandleUpdateNote}
onDeleteNote={memoizedHandleDeleteNote}
onSelectNote={memoizedHandleSelectNote}
/>
)}
</div>
{notes.length > 0 && (
<MemoizedNotesList
activeNotes={activeNotes}
notes={notes}
onEditNote={memoizedHandleUpdateNote}
onDeleteNote={memoizedHandleDeleteNote}
onSelectNote={memoizedHandleSelectNote}
/>
)}
</div>
</>
);
}
2 changes: 1 addition & 1 deletion src/components/NoteManager/components/Note.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ type NoteProps = {
note: IDecoratedNote;
sectionTitles: { sectionTitle: string; subSectionTitle: string };
active: boolean;
onEditNote: INotesContext["handleUpdateNote"];
onEditNote(noteToReplace: IDecoratedNote, newNote: IStorageNote): void;
onDeleteNote: INotesContext["handleDeleteNote"];
onSelectNote: (note: IDecoratedNote, opts: { type: "currentVersion" | "originalVersion" | "close" }) => void;
};
Expand Down
3 changes: 1 addition & 2 deletions src/components/NoteManager/components/NoteContext.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { createContext, useContext } from "react";
import type { INotesContext } from "../../NotesProvider/NotesProvider";
import type { IDecoratedNote } from "../../NotesProvider/types/DecoratedNote";
import type { IStorageNote } from "../../NotesProvider/types/StorageNote";

Expand All @@ -13,7 +12,7 @@ export type ISingleNoteContext = {
handleCancelClick: () => void;
handleNoteLabelsChange: (labels: string[]) => void;
noteDirty: IStorageNote;
onEditNote: INotesContext["handleUpdateNote"];
onEditNote: (noteToReplace: IDecoratedNote, newNote: IStorageNote) => void;
isEditing: boolean;
noteOriginalVersionShort: string | undefined;
originalVersionLink: string | undefined;
Expand Down
37 changes: 37 additions & 0 deletions src/components/NoteManager/hooks/useFilteredNoteAlert.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { useCallback, useEffect, useRef, useState } from "react";

const FILTERED_NOTE_ALERT_MS = 6_000;

export const useFilteredNoteAlert = () => {
const [noteAlertVisibilityState, setNoteAlertVisibilityState] = useState<
"hidden" | "visibleForCreated" | "visibleForUpdated"
>("hidden");
const alertTimeoutRef = useRef<number | null>(null);

const triggerFilteredNoteAlert = useCallback((type: "visibleForCreated" | "visibleForUpdated") => {
setNoteAlertVisibilityState(type);
if (alertTimeoutRef.current) {
window.clearTimeout(alertTimeoutRef.current);
}
alertTimeoutRef.current = window.setTimeout(() => {
setNoteAlertVisibilityState("hidden");
}, FILTERED_NOTE_ALERT_MS);
}, []);

useEffect(() => {
return () => {
if (alertTimeoutRef.current) {
window.clearTimeout(alertTimeoutRef.current);
}
};
}, []);

const closeNoteAlert = useCallback(() => {
setNoteAlertVisibilityState("hidden");
if (alertTimeoutRef.current) {
window.clearTimeout(alertTimeoutRef.current);
}
}, []);

return { noteAlertVisibilityState, triggerFilteredNoteAlert, closeNoteAlert };
};
13 changes: 11 additions & 2 deletions src/components/NoteManager/useNoteManagerNotes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,19 @@ export const useNoteManagerNotes = () => {
const latestDeleteNote = useLatestCallback(handleDeleteNote);
const latestUpdateNote = useLatestCallback(handleUpdateNote);

const addNote = useCallback<INotesContext["handleAddNote"]>(
(noteToAdd) => {
const { isVisible } = latestHandleAddNote.current(noteToAdd);

return { isVisible };
},
[latestHandleAddNote],
);

const updateNote = useCallback<INotesContext["handleUpdateNote"]>(
(noteToReplace, newNote) => {
metadataCacheByKey.current.delete(noteToReplace.key);
latestUpdateNote.current(noteToReplace, newNote);
return latestUpdateNote.current(noteToReplace, newNote);
},
[latestUpdateNote],
);
Expand Down Expand Up @@ -106,7 +115,7 @@ export const useNoteManagerNotes = () => {
sectionTitlesLoaded,
notes,
notesManagerNotes,
latestHandleAddNote,
addNote,
deleteNote,
updateNote,
};
Expand Down
26 changes: 18 additions & 8 deletions src/components/NotesProvider/NotesProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ export interface INotesContext {
canRedo: boolean;
remoteSources: IRemoteSource[];
handleSetRemoteSources(r: IRemoteSource, remove?: true): void;
handleAddNote(note: IStorageNote): void;
handleUpdateNote(noteToReplace: IDecoratedNote, newNote: IStorageNote): void;
handleAddNote(note: IStorageNote): { isVisible: boolean };
handleUpdateNote(noteToReplace: IDecoratedNote, newNote: IStorageNote): { isVisible: boolean };
handleDeleteNote(note: IDecoratedNote): void;
handleUndo(): void;
handleRedo(): void;
Expand Down Expand Up @@ -105,7 +105,7 @@ export function NotesProvider({ children }: INotesProviderProps) {

const allNotesReady = useMemo(() => localNotesReady && remoteNotesReady, [localNotesReady, remoteNotesReady]);

const { filteredNotes, labels, toggleLabel: handleToggleLabel } = useLabels(allNotes);
const { filteredNotes, labels, toggleLabel: handleToggleLabel, isVisibleByActiveLabelsLatest } = useLabels(allNotes);

const handleSetRemoteSources = useCallback((newSource: IRemoteSource, remove?: true) => {
setRemoteSources((prevRemoteSources) => {
Expand Down Expand Up @@ -148,27 +148,37 @@ export function NotesProvider({ children }: INotesProviderProps) {
handleSetRemoteSources,
handleToggleLabel,
handleAddNote: useCallback(
(note) =>
(note) => {
const isVisible = isVisibleByActiveLabelsLatest.current(note);

updateLocalNotes(localNotes, {
...localNotes,
notes: [note, ...localNotes.notes],
}),
[localNotes, updateLocalNotes],
});

return { isVisible };
},
[localNotes, updateLocalNotes, isVisibleByActiveLabelsLatest],
),
handleUpdateNote: useCallback(
(noteToReplace, newNote) => {
if (noteToReplace.source === NoteSource.Remote) {
console.warn("Refusing to edit remote note.", noteToReplace);
return;
return { isVisible: true };
}

const isVisible = isVisibleByActiveLabelsLatest.current(newNote);

const updateIdx = localNotesDecorated.indexOf(noteToReplace);
const newNotes = localNotes.notes.map((note, idx) => (updateIdx === idx ? newNote : note));
updateLocalNotes(localNotes, {
...localNotes,
notes: newNotes,
});

return { isVisible };
},
[localNotes, localNotesDecorated, updateLocalNotes],
[localNotes, localNotesDecorated, updateLocalNotes, isVisibleByActiveLabelsLatest],
),
handleDeleteNote: useCallback(
(noteToDelete) => {
Expand Down
18 changes: 14 additions & 4 deletions src/components/NotesProvider/hooks/useLabels.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { UnPrefixedLabel } from "@fluffylabs/links-metadata";
import { useCallback, useEffect, useMemo, useState } from "react";
import { type RefObject, useCallback, useEffect, useMemo, useState } from "react";
import { useLatestCallback } from "../../../hooks/useLatestCallback";
import { LABEL_LOCAL, LABEL_REMOTE } from "../consts/labels";
import { type IDecoratedNote, NoteSource, isDecoratedNote } from "../types/DecoratedNote";
import type { IStorageNote } from "../types/StorageNote";
Expand Down Expand Up @@ -119,6 +120,7 @@ export function useLabels(allNotes: IDecoratedNote[]): {
filteredNotes: IDecoratedNote[];
labels: ILabelTreeNode[];
toggleLabel: (label: ILabelTreeNode) => void;
isVisibleByActiveLabelsLatest: RefObject<(note: IDecoratedNote | IStorageNote) => boolean>;
} {
const [storageLabels, setStorageLabels] = useState<IStorageLabel[]>([]);
const [labels, setLabels] = useState<ILabelTreeNode[]>(initialEmptyArray as ILabelTreeNode[]);
Expand Down Expand Up @@ -226,12 +228,20 @@ export function useLabels(allNotes: IDecoratedNote[]): {
});
}, [allNotes, storageActivity]);

const activeLabels = useMemo(() => {
return labels.filter((label) => label.isActive).map((label) => label.prefixedLabel);
}, [labels]);

// filter notes when labels are changing
const filteredNotes = useMemo(() => {
const activeLabels = labels.filter((label) => label.isActive).map((label) => label.prefixedLabel);
// filter out notes
return getFilteredNotes(allNotes, activeLabels);
}, [allNotes, labels]);
}, [allNotes, activeLabels]);

const isVisibleByActiveLabelsLatest = useLatestCallback((note: IStorageNote | IDecoratedNote) => {
const filteringResult = getFilteredNotes([note], activeLabels);
return filteringResult.length > 0;
});

return { filteredNotes, labels, toggleLabel };
return { filteredNotes, labels, toggleLabel, isVisibleByActiveLabelsLatest };
}