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 ea7b9f86eb..b289db622e 100644
--- a/app/components/PaginatedList.tsx
+++ b/app/components/PaginatedList.tsx
@@ -1,265 +1,309 @@
import isEqual from "lodash/isEqual";
-import { observable, action, computed } from "mobx";
-import { observer } from "mobx-react";
import * as React from "react";
-import { withTranslation, WithTranslation } from "react-i18next";
+import { useTranslation } from "react-i18next";
import { Waypoint } from "react-waypoint";
import { Pagination } from "@shared/constants";
-import RootStore from "~/stores/RootStore";
import ArrowKeyNavigation from "~/components/ArrowKeyNavigation";
import DelayedMount from "~/components/DelayedMount";
import PlaceholderList from "~/components/List/Placeholder";
-import withStores from "~/components/withStores";
+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 = WithTranslation &
- RootStore &
- React.HTMLAttributes & {
- 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;
- };
+/**
+ * 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;
-@observer
-class PaginatedList extends React.PureComponent<
- Props
-> {
- @observable
- error?: Error;
+ /** Additional options to pass to the fetch function */
+ options?: Record;
- @observable
- isFetchingMore = false;
+ /** Optional header content to display above the list */
+ heading?: React.ReactNode;
- @observable
- isFetching = false;
+ /** Content to display when the list is empty */
+ empty?: JSX.Element | null;
- @observable
- isFetchingInitial = !this.props.items?.length;
+ /** Optional loading state content */
+ loading?: JSX.Element | null;
- @observable
- fetchCounter = 0;
+ /** Array of items to display in the list */
+ items?: T[];
- @observable
- renderCount = Pagination.defaultLimit;
+ /** CSS class name to apply to the list container */
+ className?: string;
- @observable
- offset = 0;
+ /**
+ * 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;
- @observable
- allowLoadMore = true;
+ /**
+ * 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;
- componentDidMount() {
- void this.fetchResults();
- }
+ /**
+ * Function to render section headings (typically date-based)
+ * @param name The heading text or element to render
+ */
+ renderHeading?: (name: React.ReactElement | string) => React.ReactNode;
- componentDidUpdate(prevProps: Props) {
- if (
- prevProps.fetch !== this.props.fetch ||
- !isEqual(prevProps.options, this.props.options)
- ) {
- this.reset();
- void this.fetchResults();
- }
- }
+ /**
+ * Handler for escape key press
+ * @param ev Keyboard event object
+ */
+ onEscape?: (ev: React.KeyboardEvent) => void;
- reset = () => {
- this.offset = 0;
- this.allowLoadMore = true;
- this.renderCount = Pagination.defaultLimit;
- this.isFetching = false;
- this.isFetchingInitial = false;
- this.isFetchingMore = false;
- };
+ /** Reference to the list container element */
+ listRef?: React.RefObject;
+}
- @action
- fetchResults = async () => {
- if (!this.props.fetch) {
+/**
+ * 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 = null,
+ items = [],
+ className,
+ renderItem,
+ renderError,
+ renderHeading,
+ onEscape,
+ listRef,
+ ...rest
+}: 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 [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);
+ setRenderCount(Pagination.defaultLimit);
+ setIsFetching(false);
+ setIsFetchingInitial(false);
+ setIsFetchingMore(false);
+ }, []);
+
+ const fetchResults = React.useCallback(async () => {
+ if (!fetch) {
return;
}
- this.isFetching = true;
- const counter = ++this.fetchCounter;
- const limit = this.props.options?.limit ?? Pagination.defaultLimit;
- this.error = undefined;
+
+ setIsFetching(true);
+ const counter = fetchCounter + 1;
+ setFetchCounter(counter);
+ const limit = options?.limit ?? Pagination.defaultLimit;
+ setError(undefined);
try {
- const results = await this.props.fetch({
+ const results = await fetch({
limit,
- offset: this.offset,
- ...this.props.options,
+ offset,
+ ...options,
});
- if (this.offset !== 0) {
- this.renderCount += limit;
+ if (offset !== 0) {
+ setRenderCount((prevCount) => prevCount + limit);
}
if (results && (results.length === 0 || results.length < limit)) {
- this.allowLoadMore = false;
+ setAllowLoadMore(false);
} else {
- this.offset += limit;
+ setOffset((prevOffset) => prevOffset + limit);
}
- this.isFetchingInitial = false;
+ setIsFetchingInitial(false);
} catch (err) {
- this.error = err;
+ setError(err);
} finally {
// only the most recent fetch should end the loading state
- if (counter >= this.fetchCounter) {
- this.isFetching = false;
- this.isFetchingMore = false;
+ if (counter >= fetchCounter) {
+ setIsFetching(false);
+ setIsFetchingMore(false);
}
}
- };
+ }, [fetch, fetchCounter, offset, options]);
- @action
- loadMoreResults = async () => {
- // Don't paginate if there aren't more results or we’re currently fetching
- if (!this.allowLoadMore || this.isFetching) {
+ 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 = (this.props.items?.length ?? 0) - this.renderCount;
+ const leftToRender = (items?.length ?? 0) - renderCount;
if (leftToRender > 0) {
- this.renderCount += Pagination.defaultLimit;
+ 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) {
- this.isFetchingMore = true;
- await this.fetchResults();
+ setIsFetchingMore(true);
+ await fetchResults();
}
- };
+ }, [allowLoadMore, isFetching, items?.length, renderCount, fetchResults]);
- @computed
- get itemsToRender() {
- return this.props.items?.slice(0, this.renderCount) ?? [];
- }
+ React.useEffect(() => {
+ void fetchResults();
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
- render() {
- const {
- items = [],
- heading,
- auth,
- empty = null,
- renderHeading,
- renderError,
- onEscape,
- } = this.props;
+ const prevFetch = usePrevious(fetch);
+ const prevOptions = usePrevious(options);
- const showLoading =
- this.isFetching &&
- !this.isFetchingMore &&
- (!items?.length || (this.fetchCounter <= 1 && this.isFetchingInitial));
-
- if (showLoading) {
- return (
- this.props.loading || (
-
-
-
- )
- );
+ // Equivalent to componentDidUpdate
+ React.useEffect(() => {
+ if (prevFetch !== fetch || !isEqual(prevOptions, options)) {
+ reset();
+ void fetchResults();
}
+ }, [fetch, options, reset, prevFetch, prevOptions, fetchResults]);
- if (items?.length === 0) {
- if (this.error && renderError) {
- return renderError({ error: this.error, retry: this.fetchResults });
- }
+ // Computed property equivalent
+ const itemsToRender = React.useMemo(
+ () => items?.slice(0, renderCount) ?? [],
+ [items, renderCount]
+ );
- return empty;
- }
+ const showLoading =
+ isFetching &&
+ !isFetchingMore &&
+ (!items?.length || (fetchCounter <= 1 && isFetchingInitial));
+ if (showLoading) {
return (
- <>
- {heading}
-
- {() => {
- let previousHeading = "";
- return this.itemsToRender.map((item, index) => {
- const children = this.props.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 =
- "updatedAt" in item && item.updatedAt
- ? item.updatedAt
- : "createdAt" in item && item.createdAt
- ? item.createdAt
- : previousHeading;
- const currentHeading = dateToHeading(
- currentDate,
- this.props.t,
- auth.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
- if (
- children &&
- (!previousHeading || currentHeading !== previousHeading)
- ) {
- previousHeading = currentHeading;
- return (
-
- {renderHeading(currentHeading)}
- {children}
-
- );
- }
-
- return children;
- });
- }}
-
- {this.allowLoadMore && (
-
-
+ loading || (
+
+
- )}
- >
+
+ )
);
}
-}
-export const Component = PaginatedList;
+ if (items?.length === 0) {
+ if (error && renderError) {
+ return renderError({ error, retry: fetchResults });
+ }
-export default withTranslation()(withStores(PaginatedList));
+ 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 =
+ "updatedAt" in item && item.updatedAt
+ ? item.updatedAt
+ : "createdAt" in item && item.createdAt
+ ? item.createdAt
+ : previousHeading;
+ const currentHeading = dateToHeading(
+ currentDate,
+ t,
+ 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
+ if (
+ children &&
+ (!previousHeading || currentHeading !== previousHeading)
+ ) {
+ previousHeading = currentHeading;
+ return (
+
+ {renderHeading(currentHeading)}
+ {children}
+
+ );
+ }
+
+ return children;
+ });
+ }}
+
+ {allowLoadMore && (
+
+
+
+ )}
+
+ );
+};
+
+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) => (
)}
/>