From 9906d240bd560e2c8c64d697ade7a807bb8a8c39 Mon Sep 17 00:00:00 2001
From: Tom Moor
Date: Tue, 22 Apr 2025 23:14:54 -0400
Subject: [PATCH] tsc
---
app/components/DocumentViews.tsx | 4 +-
app/components/FilterOptions.tsx | 4 +-
.../Notifications/Notifications.tsx | 4 +-
app/components/PaginatedDocumentList.tsx | 6 +-
app/components/PaginatedEventList.tsx | 2 +-
app/components/PaginatedList.test.tsx | 38 ++--
app/components/PaginatedList.tsx | 197 +++++++++++-------
app/components/SearchPopover.tsx | 4 +-
.../Sidebar/components/ArchiveLink.tsx | 4 +-
.../Sidebar/components/Collections.tsx | 4 +-
app/scenes/Document/components/Insights.tsx | 4 +-
app/scenes/Settings/ApiKeys.tsx | 4 +-
app/scenes/Settings/Export.tsx | 4 +-
app/scenes/Settings/Import.tsx | 4 +-
app/scenes/Settings/PersonalApiKeys.tsx | 4 +-
.../Settings/components/GroupDialogs.tsx | 8 +-
plugins/webhooks/client/Settings.tsx | 8 +-
17 files changed, 181 insertions(+), 122 deletions(-)
diff --git a/app/components/DocumentViews.tsx b/app/components/DocumentViews.tsx
index 6c6eb29bd8..b8aa85a43e 100644
--- a/app/components/DocumentViews.tsx
+++ b/app/components/DocumentViews.tsx
@@ -46,10 +46,10 @@ function DocumentViews({ document, isOpen }: Props) {
return (
<>
{isOpen && (
-
aria-label={t("Viewers")}
items={users}
- renderItem={(model: User) => {
+ renderItem={(model) => {
const view = documentViews.find((v) => v.userId === model.id);
const isPresent = presentIds.includes(model.id);
const isEditing = editingIds.includes(model.id);
diff --git a/app/components/FilterOptions.tsx b/app/components/FilterOptions.tsx
index 34a4da1517..b48912f9c9 100644
--- a/app/components/FilterOptions.tsx
+++ b/app/components/FilterOptions.tsx
@@ -56,7 +56,7 @@ const FilterOptions = ({
: "";
const renderItem = React.useCallback(
- (option: TFilterOption) => (
+ (option) => (
}
- renderItem={render}
- {...props}
- />
+
+ Sorry, no results}
+ renderItem={render}
+ {...props}
+ />{" "}
+
);
await expect(
result.findAllByText("Sorry, no results")
@@ -42,13 +48,15 @@ describe("PaginatedList", () => {
id: "one",
};
render(
-
+
+ {" "}
+
);
expect(fetch).toHaveBeenCalledWith({
...options,
diff --git a/app/components/PaginatedList.tsx b/app/components/PaginatedList.tsx
index b7644af5b3..b289db622e 100644
--- a/app/components/PaginatedList.tsx
+++ b/app/components/PaginatedList.tsx
@@ -1,47 +1,106 @@
import isEqual from "lodash/isEqual";
-import { observer } from "mobx-react";
import * as React from "react";
import { useTranslation } from "react-i18next";
import { Waypoint } from "react-waypoint";
import { Pagination } from "@shared/constants";
-import { useStores } from "~/hooks/useStores";
import ArrowKeyNavigation from "~/components/ArrowKeyNavigation";
import DelayedMount from "~/components/DelayedMount";
import PlaceholderList from "~/components/List/Placeholder";
+import useCurrentUser from "~/hooks/useCurrentUser";
+import usePrevious from "~/hooks/usePrevious";
import { dateToHeading } from "~/utils/date";
+/**
+ * Base interface for items that can be paginated
+ * @interface PaginatedItem
+ */
export interface PaginatedItem {
+ /** Unique identifier for the item */
id?: string;
+ /** Last update timestamp of the item */
updatedAt?: string;
+ /** Creation timestamp of the item */
createdAt?: string;
}
-type Props = React.HTMLAttributes & {
+/**
+ * Props for the PaginatedList component
+ * @template T Type of items in the list, must extend PaginatedItem
+ */
+interface Props
+ extends React.HTMLAttributes {
+ /**
+ * Function to fetch paginated data. Should return a promise resolving to an array of items
+ * @param options Pagination and other query options
+ */
fetch?: (
options: Record | undefined
- ) => Promise | undefined;
- options?: Record;
- heading?: React.ReactNode;
- empty?: React.ReactNode;
- loading?: React.ReactElement;
- items?: T[];
- className?: string;
- renderItem: (item: T, index: number) => React.ReactNode;
- renderError?: (options: {
- error: Error;
- retry: () => void;
- }) => React.ReactNode;
- renderHeading?: (name: React.ReactElement | string) => React.ReactNode;
- onEscape?: (ev: React.KeyboardEvent) => void;
- listRef?: React.RefObject;
-};
+ ) => Promise | undefined;
-function PaginatedList({
+ /** Additional options to pass to the fetch function */
+ options?: Record;
+
+ /** Optional header content to display above the list */
+ heading?: React.ReactNode;
+
+ /** Content to display when the list is empty */
+ empty?: JSX.Element | null;
+
+ /** Optional loading state content */
+ loading?: JSX.Element | null;
+
+ /** Array of items to display in the list */
+ items?: T[];
+
+ /** CSS class name to apply to the list container */
+ className?: string;
+
+ /**
+ * Function to render each individual item in the list
+ * @param item The item to render
+ * @param index The index of the item in the list
+ */
+ renderItem: (item: T, index: number) => React.ReactNode;
+
+ /**
+ * Function to render error state
+ * @param options Object containing error details and retry function
+ */
+ renderError?: (options: {
+ /** Details of the error */
+ error: Error;
+ /** Function to retry the fetch operation */
+ retry: () => void;
+ }) => JSX.Element;
+
+ /**
+ * Function to render section headings (typically date-based)
+ * @param name The heading text or element to render
+ */
+ renderHeading?: (name: React.ReactElement | string) => React.ReactNode;
+
+ /**
+ * Handler for escape key press
+ * @param ev Keyboard event object
+ */
+ onEscape?: (ev: React.KeyboardEvent) => void;
+
+ /** Reference to the list container element */
+ listRef?: React.RefObject;
+}
+
+/**
+ * A reusable component that renders a paginated list with infinite scrolling
+ * and optional date-based section headings.
+ *
+ * @template T Type of the list items, must extend PaginatedItem
+ */
+const PaginatedList = ({
fetch,
options,
heading,
empty = null,
- loading,
+ loading = null,
items = [],
className,
renderItem,
@@ -50,19 +109,21 @@ function PaginatedList({
onEscape,
listRef,
...rest
-}: Props) {
- const { auth } = useStores();
+}: Props): JSX.Element | null => {
+ const user = useCurrentUser({ rejectOnEmpty: false });
const { t } = useTranslation();
-
+
const [error, setError] = React.useState();
const [isFetchingMore, setIsFetchingMore] = React.useState(false);
const [isFetching, setIsFetching] = React.useState(false);
- const [isFetchingInitial, setIsFetchingInitial] = React.useState(!items?.length);
+ const [isFetchingInitial, setIsFetchingInitial] = React.useState(
+ !items?.length
+ );
const [fetchCounter, setFetchCounter] = React.useState(0);
const [renderCount, setRenderCount] = React.useState(Pagination.defaultLimit);
const [offset, setOffset] = React.useState(0);
const [allowLoadMore, setAllowLoadMore] = React.useState(true);
-
+
const reset = React.useCallback(() => {
setOffset(0);
setAllowLoadMore(true);
@@ -71,35 +132,35 @@ function PaginatedList({
setIsFetchingInitial(false);
setIsFetchingMore(false);
}, []);
-
+
const fetchResults = React.useCallback(async () => {
if (!fetch) {
return;
}
-
+
setIsFetching(true);
const counter = fetchCounter + 1;
setFetchCounter(counter);
const limit = options?.limit ?? Pagination.defaultLimit;
setError(undefined);
-
+
try {
const results = await fetch({
limit,
offset,
...options,
});
-
+
if (offset !== 0) {
setRenderCount((prevCount) => prevCount + limit);
}
-
+
if (results && (results.length === 0 || results.length < limit)) {
setAllowLoadMore(false);
} else {
setOffset((prevOffset) => prevOffset + limit);
}
-
+
setIsFetchingInitial(false);
} catch (err) {
setError(err);
@@ -111,21 +172,21 @@ function PaginatedList({
}
}
}, [fetch, fetchCounter, offset, options]);
-
+
const loadMoreResults = React.useCallback(async () => {
// Don't paginate if there aren't more results or we're currently fetching
if (!allowLoadMore || isFetching) {
return;
}
-
+
// If there are already cached results that we haven't yet rendered because
// of lazy rendering then show another page.
const leftToRender = (items?.length ?? 0) - renderCount;
-
+
if (leftToRender > 0) {
setRenderCount((prevCount) => prevCount + Pagination.defaultLimit);
}
-
+
// If there are less than a pages results in the cache go ahead and fetch
// another page from the server
if (leftToRender <= Pagination.defaultLimit) {
@@ -133,40 +194,34 @@ function PaginatedList({
await fetchResults();
}
}, [allowLoadMore, isFetching, items?.length, renderCount, fetchResults]);
-
- // Equivalent to componentDidMount
+
React.useEffect(() => {
void fetchResults();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
-
+
+ const prevFetch = usePrevious(fetch);
+ const prevOptions = usePrevious(options);
+
// Equivalent to componentDidUpdate
React.useEffect(() => {
- const prevFetch = React.useRef(fetch);
- const prevOptions = React.useRef(options);
-
- if (
- prevFetch.current !== fetch ||
- !isEqual(prevOptions.current, options)
- ) {
+ if (prevFetch !== fetch || !isEqual(prevOptions, options)) {
reset();
void fetchResults();
}
-
- prevFetch.current = fetch;
- prevOptions.current = options;
- }, [fetch, options, reset, fetchResults]);
-
+ }, [fetch, options, reset, prevFetch, prevOptions, fetchResults]);
+
// Computed property equivalent
- const itemsToRender = React.useMemo(() => {
- return items?.slice(0, renderCount) ?? [];
- }, [items, renderCount]);
-
+ const itemsToRender = React.useMemo(
+ () => items?.slice(0, renderCount) ?? [],
+ [items, renderCount]
+ );
+
const showLoading =
isFetching &&
!isFetchingMore &&
(!items?.length || (fetchCounter <= 1 && isFetchingInitial));
-
+
if (showLoading) {
return (
loading || (
@@ -178,17 +233,17 @@ function PaginatedList({
)
);
}
-
+
if (items?.length === 0) {
if (error && renderError) {
return renderError({ error, retry: fetchResults });
}
-
+
return empty;
}
-
+
return (
- <>
+
{heading}
({
let previousHeading = "";
return itemsToRender.map((item, index) => {
const children = renderItem(item, index);
-
+
// If there is no renderHeading method passed then no date
// headings are rendered
if (!renderHeading) {
return children;
}
-
+
// Our models have standard date fields, updatedAt > createdAt.
// Get what a heading would look like for this item
const currentDate =
@@ -219,9 +274,9 @@ function PaginatedList({
const currentHeading = dateToHeading(
currentDate,
t,
- auth.user?.language
+ user?.language
);
-
+
// If the heading is different to any previous heading then we
// should render it, otherwise the item can go under the previous
// heading
@@ -231,15 +286,13 @@ function PaginatedList({
) {
previousHeading = currentHeading;
return (
-
+
{renderHeading(currentHeading)}
{children}
);
}
-
+
return children;
});
}}
@@ -249,10 +302,8 @@ function PaginatedList({
)}
- >
+
);
-}
+};
-export const Component = observer(PaginatedList);
-
-export default observer(PaginatedList);
+export default PaginatedList;
diff --git a/app/components/SearchPopover.tsx b/app/components/SearchPopover.tsx
index 4ac2bcc523..2390a7604a 100644
--- a/app/components/SearchPopover.tsx
+++ b/app/components/SearchPopover.tsx
@@ -200,7 +200,7 @@ function SearchPopover({ shareId, className }: Props) {
style={{ zIndex: depths.sidebar + 1 }}
shrink
>
-
options={{ query, snippetMinWords: 10, snippetMaxWords: 11 }}
items={cachedSearchResults}
fetch={performSearch}
@@ -209,7 +209,7 @@ function SearchPopover({ shareId, className }: Props) {
{t("No results for {{query}}", { query })}
}
loading={}
- renderItem={(item: SearchResult, index) => (
+ renderItem={(item, index) => (
{expanded === true ? (
-
aria-label={t("Archived collections")}
items={collections.archived}
loading={}
renderError={(props) => }
- renderItem={(item: Collection) => (
+ renderItem={(item) => (
-
options={params}
aria-label={t("Collections")}
items={collections.allActive}
@@ -69,7 +69,7 @@ function Collections() {
) : undefined
}
renderError={(props) => }
- renderItem={(item: Collection, index) => (
+ renderItem={(item, index) => (
)}
-
aria-label={t("Contributors")}
items={document.collaborators}
- renderItem={(model: User) => (
+ renderItem={(model) => (
-
fetch={apiKeys.fetchPage}
items={apiKeys.orderedData}
heading={{t("All")}
}
- renderItem={(apiKey: ApiKey) => (
+ renderItem={(apiKey) => (
)}
/>
diff --git a/app/scenes/Settings/Export.tsx b/app/scenes/Settings/Export.tsx
index ad1652f971..4cf83553f6 100644
--- a/app/scenes/Settings/Export.tsx
+++ b/app/scenes/Settings/Export.tsx
@@ -48,7 +48,7 @@ function Export() {
{t("Export data")}…
-
items={fileOperations.exports}
fetch={fileOperations.fetchPage}
options={{
@@ -59,7 +59,7 @@ function Export() {
Recent exports
}
- renderItem={(item: FileOperation) => (
+ renderItem={(item) => (
)}
/>
diff --git a/app/scenes/Settings/Import.tsx b/app/scenes/Settings/Import.tsx
index 7de0063880..838644b96f 100644
--- a/app/scenes/Settings/Import.tsx
+++ b/app/scenes/Settings/Import.tsx
@@ -183,7 +183,7 @@ function Import() {
))}
-
items={allImports}
fetch={fetchImports}
heading={
@@ -191,7 +191,7 @@ function Import() {
Recent imports
}
- renderItem={(item: ImportModel | FileOperation) =>
+ renderItem={(item) =>
item instanceof ImportModel ? (
) : (
diff --git a/app/scenes/Settings/PersonalApiKeys.tsx b/app/scenes/Settings/PersonalApiKeys.tsx
index b0bfaf6c62..32bb83d0c6 100644
--- a/app/scenes/Settings/PersonalApiKeys.tsx
+++ b/app/scenes/Settings/PersonalApiKeys.tsx
@@ -61,12 +61,12 @@ function PersonalApiKeys() {
}}
/>
-
fetch={apiKeys.fetchPage}
items={apiKeys.personalApiKeys}
options={{ userId: user.id }}
heading={{t("Personal keys")}
}
- renderItem={(apiKey: ApiKey) => (
+ renderItem={(apiKey) => (
)}
/>
diff --git a/app/scenes/Settings/components/GroupDialogs.tsx b/app/scenes/Settings/components/GroupDialogs.tsx
index 6941cf78e8..7ca290e0b2 100644
--- a/app/scenes/Settings/components/GroupDialogs.tsx
+++ b/app/scenes/Settings/components/GroupDialogs.tsx
@@ -268,14 +268,14 @@ export const ViewGroupMembersDialog = observer(function ({
Members
-
items={users.inGroup(group.id)}
fetch={groupUsers.fetchPage}
options={{
id: group.id,
}}
empty={{t("This group has no members.")}}
- renderItem={(user: User) => (
+ renderItem={(user) => (
) : (
-
empty={
query ? (
{t("No people matching your search")}
@@ -392,7 +392,7 @@ const AddPeopleToGroupDialog = observer(function ({
}
items={users.notInGroup(group.id, query)}
fetch={query ? undefined : users.fetchPage}
- renderItem={(item: User) => (
+ renderItem={(item) => (
-
fetch={webhookSubscriptions.fetchPage}
items={webhookSubscriptions.enabled}
heading={{t("Active")}
}
- renderItem={(webhook: WebhookSubscription) => (
+ renderItem={(webhook) => (
)}
/>
-
items={webhookSubscriptions.disabled}
heading={{t("Inactive")}
}
- renderItem={(webhook: WebhookSubscription) => (
+ renderItem={(webhook) => (
)}
/>