Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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
181 changes: 97 additions & 84 deletions src/components/NoteManager/NoteManager.tsx
Original file line number Diff line number Diff line change
@@ -1,24 +1,23 @@
import { memo, useCallback, useContext, useEffect, useRef, useState } from "react";
import { memo, useCallback, useContext, useRef } from "react";
import "./NoteManager.css";
import type { ISynctexBlockId } from "@fluffylabs/links-metadata";
import { Button, Textarea } from "@fluffylabs/shared-ui";
import { twMerge } from "tailwind-merge";
import { validateMath } from "../../utils/validateMath";
import { useLatestCallback } from "../../hooks/useLatestCallback";
import { type ILocationContext, LocationContext } from "../LocationProvider/LocationProvider";
import { type INotesContext, NotesContext } from "../NotesProvider/NotesProvider";
import { LABEL_LOCAL } from "../NotesProvider/consts/labels";
import type { IDecoratedNote } from "../NotesProvider/types/DecoratedNote";
import type { IStorageNote } from "../NotesProvider/types/StorageNote";
import { Selection } from "../Selection/Selection";
import { areSelectionsEqual } from "../NotesProvider/utils/areSelectionsEqual";
import { type ISelectionContext, SelectionContext } from "../SelectionProvider/SelectionProvider";
import { InactiveNoteSkeleton } from "./components/InactiveNoteSkeleton";
import { NewNote } from "./components/NewNote";
import { NotesList } from "./components/NotesList";

const DEFAULT_AUTHOR = "";

export function NoteManager({ className }: { className?: string }) {
return (
<div className={twMerge("notes-wrapper gap-4", className)}>
<Selection />
<Notes />
</div>
);
Expand All @@ -27,62 +26,66 @@ export function NoteManager({ className }: { className?: string }) {
const MemoizedNotesList = memo(NotesList);

function Notes() {
const [noteContent, setNoteContent] = useState("");
const [noteContentError, setNoteContentError] = useState("");
const { locationParams, setLocationParams } = useContext(LocationContext) as ILocationContext;
const { notesReady, activeNotes, notes, handleAddNote, handleDeleteNote, handleUpdateNote } = useContext(
NotesContext,
) as INotesContext;
const { selectedBlocks, pageNumber, handleClearSelection } = useContext(SelectionContext) as ISelectionContext;
const keepShowingNewNote = useRef<{ selectionEnd: ISynctexBlockId; selectionStart: ISynctexBlockId }>(undefined);

const handleAddNoteRef = useRef(handleAddNote);
handleAddNoteRef.current = handleAddNote;
const handleDeleteNoteRef = useRef(handleDeleteNote);
handleDeleteNoteRef.current = handleDeleteNote;
const handleUpdateNoteRef = useRef(handleUpdateNote);
handleUpdateNoteRef.current = handleUpdateNote;

const memoizedHandleDeleteNote = useCallback((note: IDecoratedNote) => {
handleDeleteNoteRef.current(note);
}, []);

const memoizedHandleUpdateNote = useCallback((note: IDecoratedNote, newNote: IStorageNote) => {
handleUpdateNoteRef.current(note, newNote);
}, []);

const handleAddNoteClick = useCallback(() => {
if (
selectedBlocks.length === 0 ||
pageNumber === null ||
!locationParams.selectionStart ||
!locationParams.selectionEnd
) {
throw new Error("Attempted saving a note without selection.");
}

setNoteContentError("");

const mathValidationError = validateMath(noteContent);

if (mathValidationError) {
setNoteContentError(mathValidationError);
return;
}

const newNote: IStorageNote = {
noteVersion: 3,
content: noteContent,
date: Date.now(),
author: DEFAULT_AUTHOR,
selectionStart: locationParams.selectionStart,
selectionEnd: locationParams.selectionEnd,
version: locationParams.version,
labels: [LABEL_LOCAL],
};

handleAddNoteRef.current(newNote);
const latestHandleAddNote = useLatestCallback(handleAddNote);
const latestDeleteNote = useLatestCallback(handleDeleteNote);
const latestUpdateNote = useLatestCallback(handleUpdateNote);

const memoizedHandleDeleteNote = useCallback(
(note: IDecoratedNote) => {
latestDeleteNote.current(note);
handleClearSelection();
},
[handleClearSelection, latestDeleteNote],
);

const memoizedHandleUpdateNote = useCallback(
(note: IDecoratedNote, newNote: IStorageNote) => {
latestUpdateNote.current(note, newNote);
},
[latestUpdateNote],
);

const handleNewNoteCancel = useCallback(() => {
handleClearSelection();
}, [noteContent, pageNumber, selectedBlocks, handleClearSelection, locationParams]);
}, [handleClearSelection]);

const handleAddNoteClick = useCallback(
({ noteContent, labels }: { noteContent: string; labels: string[] }) => {
if (
selectedBlocks.length === 0 ||
pageNumber === null ||
!locationParams.selectionStart ||
!locationParams.selectionEnd
) {
throw new Error("Attempted saving a note without selection.");
}

const newNote: IStorageNote = {
noteVersion: 3,
content: noteContent,
date: Date.now(),
author: DEFAULT_AUTHOR,
selectionStart: locationParams.selectionStart,
selectionEnd: locationParams.selectionEnd,
version: locationParams.version,
labels,
};

latestHandleAddNote.current(newNote);
keepShowingNewNote.current = {
selectionStart: locationParams.selectionStart,
selectionEnd: locationParams.selectionEnd,
};
},
[pageNumber, selectedBlocks, locationParams, latestHandleAddNote],
);

const locationRef = useRef({ locationParams, setLocationParams });
locationRef.current = { locationParams, setLocationParams };
Expand Down Expand Up @@ -113,38 +116,48 @@ function Notes() {
[],
);

useEffect(() => {
if (selectedBlocks.length === 0) {
setNoteContent("");
setNoteContentError("");
}
}, [selectedBlocks]);
const isActiveNotes = notes.some((note) => activeNotes.includes(note));

return (
<div className="note-manager flex flex-col gap-2.5" style={{ opacity: notesReady ? 1.0 : 0.3 }}>
<div className="flex flex-col p-2 gap-2">
<Textarea
disabled={selectedBlocks.length === 0}
className={noteContentError ? "error" : ""}
autoFocus
value={noteContent}
onChange={(ev) => setNoteContent(ev.currentTarget.value)}
placeholder="Add a note to the selected fragment. Math typesetting is supported! Use standard delimiters such as $...$, \[...\] or \begin{equation}...\end{equation}."
<div
className="note-manager flex flex-col gap-2.5"
style={{ opacity: notesReady ? 1.0 : 0.3, pointerEvents: notesReady ? "auto" : "none" }}
>
{locationParams.selectionEnd &&
locationParams.selectionStart &&
pageNumber !== null &&
selectedBlocks.length > 0 &&
!isActiveNotes &&
(notesReady || areSelectionsEqual(locationParams, keepShowingNewNote.current)) && (
<NewNote
selectionStart={locationParams.selectionStart}
selectionEnd={locationParams.selectionEnd}
version={locationParams.version}
onCancel={handleNewNoteCancel}
onSave={handleAddNoteClick}
/>
)}

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

{notesReady && 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}
/>

{noteContentError ? <div className="validation-message">{noteContentError}</div> : null}
<Button disabled={noteContent.length < 1} onClick={handleAddNoteClick} variant="secondary">
Add
</Button>
</div>

<MemoizedNotesList
activeNotes={activeNotes}
notes={notes}
onEditNote={memoizedHandleUpdateNote}
onDeleteNote={memoizedHandleDeleteNote}
onSelectNote={memoizedHandleSelectNote}
/>
)}
</div>
);
}
26 changes: 26 additions & 0 deletions src/components/NoteManager/components/InactiveNoteSkeleton.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { cn } from "@fluffylabs/shared-ui";
import { NoteContainer } from "./SimpleComponents/NoteContainer";

const skeletonLine = "rounded-md bg-gray-300/100 dark:bg-white/10";

export const InactiveNoteSkeleton = ({ className }: { className?: string }) => (
<NoteContainer
active={false}
aria-hidden="true"
className={cn(
"note relative rounded-xl p-4 bg-[var(--inactive-note-bg)] border border-[var(--border)]/60 select-none animate-pulse",
className,
)}
>
<div className="flex flex-col gap-3">
<div className="flex items-center gap-2">
<div className={cn("h-4 w-9/12 rounded-md bg-brand-primary/50")} />
</div>
<div className="space-y-1">
<div className={cn("h-4 w-full", skeletonLine)} />
<div className={cn("h-4 w-11/12", skeletonLine)} />
<div className={cn("h-4 w-8/12", skeletonLine)} />
</div>
</div>
</NoteContainer>
);
136 changes: 136 additions & 0 deletions src/components/NoteManager/components/NewNote.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
import type { ISynctexBlockId } from "@fluffylabs/links-metadata";
import { Button } from "@fluffylabs/shared-ui";
import { type ChangeEvent, useCallback, useMemo, useRef, useState } from "react";
import { useLatestCallback } from "../../../hooks/useLatestCallback";
import { validateMath } from "../../../utils/validateMath";
import { type IDecoratedNote, NoteSource } from "../../NotesProvider/types/DecoratedNote";
import type { INoteV3 } from "../../NotesProvider/types/StorageNote";
import type { ISingleNoteContext } from "./NoteContext";
import { NoteLayout } from "./NoteLayout";
import { NoteContainer } from "./SimpleComponents/NoteContainer";

type NewNoteProps = {
selectionStart: ISynctexBlockId;
selectionEnd: ISynctexBlockId;
version: string;
onCancel: () => void;
onSave: ({ noteContent, labels }: { noteContent: string; labels: string[] }) => void;
};

export const NewNote = ({ selectionEnd, selectionStart, version, onCancel, onSave }: NewNoteProps) => {
const dateRef = useRef(new Date().getTime());

const [noteContent, setNoteContent] = useState("");
const [noteContentError, setNoteContentError] = useState<string | null>(null);
const [labels, setLabels] = useState<string[]>(["local"]);

const latestOnCancel = useLatestCallback(onCancel);
const latestOnSave = useLatestCallback(onSave);

const handleCancelClick = useCallback(() => {
latestOnCancel.current();
}, [latestOnCancel]);

const handleSaveClick = useCallback(() => {
const mathValidationError = validateMath(noteContent);
if (mathValidationError) {
setNoteContentError(mathValidationError);
return;
}

latestOnSave.current({ noteContent, labels });
}, [noteContent, latestOnSave, labels]);

const currentVersionLink = "";
const originalVersionLink = "";

const handleNoteContentChange = useCallback((event: ChangeEvent<HTMLTextAreaElement>) => {
setNoteContent(event.target.value);
setNoteContentError(null);
}, []);

const noteDirty = useMemo(
() =>
({
author: "",
content: noteContent,
labels,
date: dateRef.current,
noteVersion: 3,
selectionEnd,
selectionStart,
version,
}) satisfies INoteV3,
[noteContent, version, selectionStart, selectionEnd, labels],
);

const note = useMemo(
() =>
({
current: {
isMigrated: true,
isUpToDate: true,
selectionEnd,
selectionStart,
version,
},
key: "newNote",
original: {
author: "",
content: "",
date: dateRef.current,
labels: [],
noteVersion: 3,
selectionEnd,
selectionStart,
version,
},
source: NoteSource.Local,
}) satisfies IDecoratedNote,
[selectionEnd, selectionStart, version],
);

const noteLayoutContext = useMemo(
() =>
({
active: true,
isEditable: true,
handleEditClick: () => {},
handleSaveClick,
handleCancelClick,
onEditNote: () => {},
isEditing: true,
note,
noteDirty,
handleNoteContentChange,
handleNoteLabelsChange: setLabels,
handleSelectNote: () => {},
noteOriginalVersionShort: "",
currentVersionLink,
originalVersionLink,
}) satisfies ISingleNoteContext,
[noteDirty, handleNoteContentChange, note, handleCancelClick, handleSaveClick],
);

return (
<NoteLayout.Root value={noteLayoutContext}>
<NoteContainer active={true}>
<div className="flex flex-col gap-2">
<NoteLayout.SelectedText />
<NoteLayout.TextArea className={noteContentError ? "error" : ""} />
{noteContentError ? <div className="validation-message">{noteContentError}</div> : null}
<NoteLayout.Labels />
<div className="actions gap-2">
<div className="fill" />
<Button variant="tertiary" data-testid={"cancel-button"} onClick={handleCancelClick} size="sm">
Cancel
</Button>
<Button data-testid={"save-button"} onClick={handleSaveClick} size="sm">
Save
</Button>
</div>
</div>
</NoteContainer>
</NoteLayout.Root>
);
};
Loading
Loading