diff --git a/.env.sample b/.env.sample index 6478fe6fe6..10a99c497d 100644 --- a/.env.sample +++ b/.env.sample @@ -127,6 +127,10 @@ GITHUB_APP_NAME= GITHUB_APP_ID= GITHUB_APP_PRIVATE_KEY= +# Linear +LINEAR_CLIENT_ID= +LINEAR_CLIENT_SECRET= + # To configure Discord auth, you'll need to create a Discord Application at # => https://discord.com/developers/applications/ # diff --git a/app/actions/definitions/oauthClients.tsx b/app/actions/definitions/oauthClients.tsx new file mode 100644 index 0000000000..76eba98ff3 --- /dev/null +++ b/app/actions/definitions/oauthClients.tsx @@ -0,0 +1,25 @@ +import { PlusIcon } from "outline-icons"; +import * as React from "react"; +import stores from "~/stores"; +import { OAuthClientNew } from "~/components/OAuthClient/OAuthClientNew"; +import { createAction } from ".."; +import { SettingsSection } from "../sections"; + +export const createOAuthClient = createAction({ + name: ({ t }) => t("New App"), + analyticsName: "New App", + section: SettingsSection, + icon: , + keywords: "create", + visible: () => + stores.policies.abilities(stores.auth.team?.id || "").createOAuthClient, + perform: ({ t, event }) => { + event?.preventDefault(); + event?.stopPropagation(); + + stores.dialogs.openModal({ + title: t("New Application"), + content: , + }); + }, +}); diff --git a/app/actions/definitions/teams.tsx b/app/actions/definitions/teams.tsx index a9847551d7..02be788fd6 100644 --- a/app/actions/definitions/teams.tsx +++ b/app/actions/definitions/teams.tsx @@ -11,7 +11,7 @@ import { ActionContext } from "~/types"; import Desktop from "~/utils/Desktop"; import { TeamSection } from "../sections"; -export const createTeamsList = ({ stores }: { stores: RootStore }) => +export const switchTeamsList = ({ stores }: { stores: RootStore }) => stores.auth.availableTeams?.map((session) => ({ id: `switch-${session.id}`, name: session.name, @@ -44,7 +44,7 @@ export const switchTeam = createAction({ section: TeamSection, visible: ({ stores }) => !!stores.auth.availableTeams && stores.auth.availableTeams?.length > 1, - children: createTeamsList, + children: switchTeamsList, }); export const createTeam = createAction({ diff --git a/app/components/Avatar/Avatar.tsx b/app/components/Avatar/Avatar.tsx index 731e132e9c..e8b730a90e 100644 --- a/app/components/Avatar/Avatar.tsx +++ b/app/components/Avatar/Avatar.tsx @@ -13,6 +13,11 @@ export enum AvatarSize { Upload = 64, } +export enum AvatarVariant { + Round = "round", + Square = "square", +} + export interface IAvatar { avatarUrl: string | null; color?: string; @@ -23,6 +28,8 @@ export interface IAvatar { type Props = { /** The size of the avatar */ size: AvatarSize; + /** The variant of the avatar */ + variant?: AvatarVariant; /** The source of the avatar image, if not passing a model. */ src?: string; /** The avatar model, if not passing a source. */ @@ -38,14 +45,14 @@ type Props = { }; function Avatar(props: Props) { - const { model, style, ...rest } = props; + const { model, style, variant = AvatarVariant.Round, ...rest } = props; const src = props.src || model?.avatarUrl; const [error, handleError] = useBoolean(false); return ( - + {src && !error ? ( - + ) : model ? ( {model.initial} @@ -61,19 +68,19 @@ Avatar.defaultProps = { size: AvatarSize.Medium, }; -const Relative = styled.div` +const Relative = styled.div<{ $variant: AvatarVariant; $size: AvatarSize }>` position: relative; user-select: none; flex-shrink: 0; -`; - -const CircleImg = styled.img<{ size: number }>` - display: block; - width: ${(props) => props.size}px; - height: ${(props) => props.size}px; - border-radius: 50%; - flex-shrink: 0; + border-radius: ${(props) => + props.$variant === AvatarVariant.Round ? "50%" : `${props.$size / 8}px`}; overflow: hidden; `; +const Image = styled.img<{ size: number }>` + display: block; + width: ${(props) => props.size}px; + height: ${(props) => props.size}px; +`; + export default Avatar; diff --git a/app/components/Avatar/Initials.tsx b/app/components/Avatar/Initials.tsx index 775e380e0c..e6d51b9be6 100644 --- a/app/components/Avatar/Initials.tsx +++ b/app/components/Avatar/Initials.tsx @@ -13,7 +13,6 @@ const Initials = styled(Flex)<{ }>` align-items: center; justify-content: center; - border-radius: 50%; width: 100%; height: 100%; color: ${(props) => @@ -23,7 +22,6 @@ const Initials = styled(Flex)<{ background-color: ${(props) => props.color ?? props.theme.textTertiary}; width: ${(props) => props.size}px; height: ${(props) => props.size}px; - border-radius: 50%; flex-shrink: 0; // adjust font size down for each additional character diff --git a/app/components/Collection/CollectionForm.tsx b/app/components/Collection/CollectionForm.tsx index 8e308d0927..776de17f03 100644 --- a/app/components/Collection/CollectionForm.tsx +++ b/app/components/Collection/CollectionForm.tsx @@ -1,3 +1,4 @@ +import uniq from "lodash/uniq"; import { observer } from "mobx-react"; import * as React from "react"; import { Controller, useForm } from "react-hook-form"; @@ -14,13 +15,15 @@ import Button from "~/components/Button"; import Flex from "~/components/Flex"; import Input from "~/components/Input"; import InputSelectPermission from "~/components/InputSelectPermission"; +import { createLazyComponent } from "~/components/LazyLoad"; import Switch from "~/components/Switch"; import Text from "~/components/Text"; import useBoolean from "~/hooks/useBoolean"; import useCurrentTeam from "~/hooks/useCurrentTeam"; +import useStores from "~/hooks/useStores"; import { EmptySelectValue } from "~/types"; -const IconPicker = React.lazy(() => import("~/components/IconPicker")); +const IconPicker = createLazyComponent(() => import("~/components/IconPicker")); export interface FormData { name: string; @@ -30,6 +33,26 @@ export interface FormData { permission: CollectionPermission | undefined; } +const useIconColor = (collection?: Collection) => { + const { collections } = useStores(); + const hasMultipleCollections = collections.orderedData.length > 1; + const collectionColors = uniq( + collections.orderedData.map((c) => c.color).filter(Boolean) + ) as string[]; + + const iconColor = React.useMemo( + () => + collection?.color ?? + // If all the existing collections have the same color, use that color, + // otherwise pick a random color from the palette + (hasMultipleCollections && collectionColors.length === 1 + ? collectionColors[0] + : randomElement(colorPalette)), + [collection?.color] + ); + return iconColor; +}; + export const CollectionForm = observer(function CollectionForm_({ handleSubmit, collection, @@ -42,11 +65,7 @@ export const CollectionForm = observer(function CollectionForm_({ const [hasOpenedIconPicker, setHasOpenedIconPicker] = useBoolean(false); - const iconColor = React.useMemo( - () => collection?.color ?? randomElement(colorPalette), - [collection?.color] - ); - + const iconColor = useIconColor(collection); const fallbackIcon = ; const { @@ -70,6 +89,11 @@ export const CollectionForm = observer(function CollectionForm_({ const values = watch(); + // Preload the IconPicker component on mount + React.useEffect(() => { + void IconPicker.preload(); + }, []); + React.useEffect(() => { // If the user hasn't picked an icon yet, go ahead and suggest one based on // the name of the collection. It's the little things sometimes. @@ -184,7 +208,7 @@ export const CollectionForm = observer(function CollectionForm_({ ); }); -const StyledIconPicker = styled(IconPicker)` +const StyledIconPicker = styled(IconPicker.Component)` margin-left: 4px; margin-right: 4px; `; diff --git a/app/components/DocumentBreadcrumb.tsx b/app/components/DocumentBreadcrumb.tsx index b5b3e7ca1c..5b1da8b897 100644 --- a/app/components/DocumentBreadcrumb.tsx +++ b/app/components/DocumentBreadcrumb.tsx @@ -18,6 +18,13 @@ type Props = { children?: React.ReactNode; document: Document; onlyText?: boolean; + reverse?: boolean; + /** + * Maximum number of items to show in the breadcrumb. + * If value is less than or equals to 0, no items will be shown. + * If value is undefined, all items will be shown. + */ + maxDepth?: number; }; function useCategory(document: Document): MenuInternalLink | null { @@ -54,7 +61,7 @@ function useCategory(document: Document): MenuInternalLink | null { } function DocumentBreadcrumb( - { document, children, onlyText }: Props, + { document, children, onlyText, reverse = false, maxDepth }: Props, ref: React.RefObject | null ) { const { collections } = useStores(); @@ -65,6 +72,7 @@ function DocumentBreadcrumb( ? collections.get(document.collectionId) : undefined; const can = usePolicy(collection); + const depth = maxDepth === undefined ? undefined : Math.max(0, maxDepth); React.useEffect(() => { void document.loadRelations({ withoutPolicies: true }); @@ -91,20 +99,23 @@ function DocumentBreadcrumb( }; } - const path = document.pathTo; + const path = document.pathTo.slice(0, -1); const items = React.useMemo(() => { - const output = []; + const output: MenuInternalLink[] = []; + + if (depth === 0) { + return output; + } if (category) { output.push(category); } - if (collectionNode) { output.push(collectionNode); } - path.slice(0, -1).forEach((node: NavigationNode) => { + path.forEach((node: NavigationNode) => { const title = node.title || t("Untitled"); output.push({ type: "route", @@ -121,21 +132,43 @@ function DocumentBreadcrumb( }, }); }); - return output; - }, [t, path, category, sidebarContext, collectionNode]); + + return reverse + ? depth !== undefined + ? output.slice(-depth) + : output + : depth !== undefined + ? output.slice(0, depth) + : output; + }, [t, path, category, sidebarContext, collectionNode, reverse, depth]); if (!collections.isLoaded) { return null; } - if (onlyText === true) { + if (onlyText) { + if (depth === 0) { + return <>; + } + + const slicedPath = reverse + ? path.slice(depth && -depth) + : path.slice(0, depth); + + const showCollection = + collection && + (!reverse || depth === undefined || slicedPath.length < depth); + return ( <> - {collection?.name} - {path.slice(0, -1).map((node: NavigationNode) => ( + {showCollection && collection.name} + {slicedPath.map((node: NavigationNode, index: number) => ( - + {showCollection && } {node.title || t("Untitled")} + {!showCollection && index !== slicedPath.length - 1 && ( + + )} ))} 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) => ( { @@ -174,7 +174,7 @@ const FilterOptions = ({ )} - listRef={listRef} options={{ query, ...fetchQueryOptions }} items={filteredOptions} diff --git a/app/components/HoverPreview/Components.tsx b/app/components/HoverPreview/Components.tsx index f56cf13625..de57687381 100644 --- a/app/components/HoverPreview/Components.tsx +++ b/app/components/HoverPreview/Components.tsx @@ -2,7 +2,6 @@ import { transparentize } from "polished"; import { Link } from "react-router-dom"; import styled, { css } from "styled-components"; import { s } from "@shared/styles"; -import { getTextColor } from "@shared/utils/color"; import Text from "~/components/Text"; export const CARD_MARGIN = 10; @@ -33,7 +32,7 @@ export const Title = styled(Text).attrs({ as: "h2", size: "large" })` display: flex; align-items: flex-start; justify-content: flex-start; - gap: 4px; + gap: 6px; `; export const Info = styled(StyledText).attrs(() => ({ @@ -60,15 +59,27 @@ export const Thumbnail = styled.img` export const Label = styled(Text).attrs({ size: "xsmall", weight: "bold" })<{ color?: string; }>` - background-color: ${(props) => - props.color ?? props.theme.backgroundSecondary}; - color: ${(props) => - props.color ? getTextColor(props.color) : props.theme.text}; + border: 1px solid ${(props) => props.theme.divider}; width: fit-content; border-radius: 2em; - padding: 0 8px; + padding: 1px 8px 1px 20px; margin-right: 0.5em; margin-top: 0.5em; + position: relative; + flex-shrink: 0; + + &::after { + content: ""; + position: absolute; + left: 8px; + top: 50%; + transform: translateY(-50%); + width: 6px; + height: 6px; + border-radius: 50%; + background-color: ${(props) => + props.color || props.theme.backgroundSecondary}; + } `; export const CardContent = styled.div` diff --git a/app/components/HoverPreview/HoverPreviewIssue.tsx b/app/components/HoverPreview/HoverPreviewIssue.tsx index bf71e62ac4..4ee1dbf904 100644 --- a/app/components/HoverPreview/HoverPreviewIssue.tsx +++ b/app/components/HoverPreview/HoverPreviewIssue.tsx @@ -1,7 +1,13 @@ import * as React from "react"; import { Trans } from "react-i18next"; +import styled from "styled-components"; +import { Backticks } from "@shared/components/Backticks"; import { IssueStatusIcon } from "@shared/components/IssueStatusIcon"; -import { UnfurlResourceType, UnfurlResponse } from "@shared/types"; +import { + IntegrationService, + UnfurlResourceType, + UnfurlResponse, +} from "@shared/types"; import { Avatar } from "~/components/Avatar"; import Flex from "~/components/Flex"; import Text from "../Text"; @@ -23,6 +29,11 @@ const HoverPreviewIssue = React.forwardRef(function _HoverPreviewIssue( ref: React.Ref ) { const authorName = author.name; + const urlObj = new URL(url); + const service = + urlObj.hostname === "github.com" + ? IntegrationService.GitHub + : IntegrationService.Linear; return ( @@ -31,13 +42,18 @@ const HoverPreviewIssue = React.forwardRef(function _HoverPreviewIssue( - <IssueStatusIcon status={state.name} color={state.color} /> + <StyledIssueStatusIcon + service={service} + state={state} + size={18} + /> <span> - {title} <Text type="tertiary">{id}</Text> + <Backticks content={title} /> +  <Text type="tertiary">{id}</Text> </span> - - + + {{ authorName }} created{" "} @@ -62,4 +78,8 @@ const HoverPreviewIssue = React.forwardRef(function _HoverPreviewIssue( ); }); +const StyledIssueStatusIcon = styled(IssueStatusIcon)` + margin-top: 2px; +`; + export default HoverPreviewIssue; diff --git a/app/components/HoverPreview/HoverPreviewPullRequest.tsx b/app/components/HoverPreview/HoverPreviewPullRequest.tsx index c4165e4bf9..ff830953ea 100644 --- a/app/components/HoverPreview/HoverPreviewPullRequest.tsx +++ b/app/components/HoverPreview/HoverPreviewPullRequest.tsx @@ -1,5 +1,7 @@ import * as React from "react"; import { Trans } from "react-i18next"; +import styled from "styled-components"; +import { Backticks } from "@shared/components/Backticks"; import { PullRequestIcon } from "@shared/components/PullRequestIcon"; import { UnfurlResourceType, UnfurlResponse } from "@shared/types"; import { Avatar } from "~/components/Avatar"; @@ -31,13 +33,14 @@ const HoverPreviewPullRequest = React.forwardRef( - <PullRequestIcon status={state.name} color={state.color} /> + <StyledPullRequestIcon size={18} state={state} /> <span> - {title} <Text type="tertiary">{id}</Text> + <Backticks content={title} /> +  <Text type="tertiary">{id}</Text> </span> - - + + {{ authorName }} opened{" "} @@ -55,4 +58,8 @@ const HoverPreviewPullRequest = React.forwardRef( } ); +const StyledPullRequestIcon = styled(PullRequestIcon)` + margin-top: 2px; +`; + export default HoverPreviewPullRequest; diff --git a/app/components/LazyLoad.ts b/app/components/LazyLoad.ts new file mode 100644 index 0000000000..7634887530 --- /dev/null +++ b/app/components/LazyLoad.ts @@ -0,0 +1,47 @@ +import * as React from "react"; +import lazyWithRetry from "~/utils/lazyWithRetry"; + +export interface LazyComponent> { + Component: React.LazyExoticComponent; + preload: () => Promise<{ default: T }>; +} + +interface LazyLoadOptions { + retries?: number; + interval?: number; +} + +/** + * Creates a lazy-loaded component with preloading capability and automatic retries on failure. + * + * @param factory A function that returns a promise of a component (eg: () => import('./MyComponent')) + * @param options Optional configuration for retry behavior + * @returns An object containing the lazy Component and a preload function + * + * @example + * ```typescript + * const MyComponent = createLazyComponent(() => import('./MyComponent')); + * + * function App() { + * return ( + * Loading...}> + * + * + * ); + * } + * + * // Preload when needed: + * MyComponent.preload(); + * ``` + */ +export function createLazyComponent>( + factory: () => Promise<{ default: T }>, + options: LazyLoadOptions = {} +): LazyComponent { + const { retries, interval } = options; + + return { + Component: lazyWithRetry(factory, retries, interval), + preload: factory, + }; +} diff --git a/app/components/Notifications/Notifications.tsx b/app/components/Notifications/Notifications.tsx index e297041cca..481255133a 100644 --- a/app/components/Notifications/Notifications.tsx +++ b/app/components/Notifications/Notifications.tsx @@ -79,11 +79,11 @@ function Notifications( - fetch={notifications.fetchPage} options={{ archived: false }} items={isOpen ? notifications.orderedData : undefined} - renderItem={(item: Notification) => ( + renderItem={(item) => ( void; + oauthClient?: OAuthClient; +}) { + const { t } = useTranslation(); + + const { + register, + handleSubmit: formHandleSubmit, + formState, + getValues, + setFocus, + setError, + control, + } = useForm({ + mode: "all", + defaultValues: { + name: oauthClient?.name ?? "", + description: oauthClient?.description ?? "", + avatarUrl: oauthClient?.avatarUrl ?? "", + redirectUris: oauthClient?.redirectUris ?? [], + published: oauthClient?.published ?? false, + }, + }); + + React.useEffect(() => { + setTimeout(() => setFocus("name", { shouldSelect: true }), 100); + }, [setFocus]); + + return ( +
+ <> + + + + ( + { + field.onChange(event.target.value.split("\n")); + }} + required + /> + )} + /> + {isCloudHosted && ( + + )} + + + + + + + ); +}); diff --git a/app/components/OAuthClient/OAuthClientNew.tsx b/app/components/OAuthClient/OAuthClientNew.tsx new file mode 100644 index 0000000000..eeae134dac --- /dev/null +++ b/app/components/OAuthClient/OAuthClientNew.tsx @@ -0,0 +1,33 @@ +import { observer } from "mobx-react"; +import * as React from "react"; +import { useHistory } from "react-router-dom"; +import { toast } from "sonner"; +import useStores from "~/hooks/useStores"; +import { settingsPath } from "~/utils/routeHelpers"; +import { OAuthClientForm, FormData } from "./OAuthClientForm"; + +type Props = { + onSubmit: () => void; +}; + +export const OAuthClientNew = observer(function OAuthClientNew_({ + onSubmit, +}: Props) { + const { oauthClients } = useStores(); + const history = useHistory(); + + const handleSubmit = React.useCallback( + async (data: FormData) => { + try { + const oauthClient = await oauthClients.save(data); + onSubmit?.(); + history.push(settingsPath("applications", oauthClient.id)); + } catch (error) { + toast.error(error.message); + } + }, + [oauthClients, history, onSubmit] + ); + + return ; +}); diff --git a/app/components/PaginatedDocumentList.tsx b/app/components/PaginatedDocumentList.tsx index 3e40739820..915de45019 100644 --- a/app/components/PaginatedDocumentList.tsx +++ b/app/components/PaginatedDocumentList.tsx @@ -10,7 +10,7 @@ type Props = { fetch: (options: any) => Promise; options?: Record; heading?: React.ReactNode; - empty?: React.ReactNode; + empty?: JSX.Element; showParentDocuments?: boolean; showCollection?: boolean; showPublished?: boolean; @@ -34,7 +34,7 @@ const PaginatedDocumentList = React.memo(function PaginatedDocumentList({ const { t } = useTranslation(); return ( - aria-label={t("Documents")} items={documents} empty={empty} @@ -42,7 +42,7 @@ const PaginatedDocumentList = React.memo(function PaginatedDocumentList({ fetch={fetch} options={options} renderError={(props) => } - renderItem={(item: Document, _index) => ( + renderItem={(item, _index) => ( | undefined) => Promise; options?: Record; heading?: React.ReactNode; - empty?: React.ReactNode; + empty?: JSX.Element; }; const PaginatedEventList = React.memo(function PaginatedEventList({ diff --git a/app/components/PaginatedList.test.tsx b/app/components/PaginatedList.test.tsx index 2a04ca2c96..3adb9b5c9b 100644 --- a/app/components/PaginatedList.test.tsx +++ b/app/components/PaginatedList.test.tsx @@ -1,13 +1,15 @@ import "../stores"; import { render } from "@testing-library/react"; import { TFunction } from "i18next"; +import { Provider } from "mobx-react"; import * as React from "react"; import { getI18n } from "react-i18next"; import { Pagination } from "@shared/constants"; -import { Component as PaginatedList } from "./PaginatedList"; +import PaginatedList from "./PaginatedList"; describe("PaginatedList", () => { const i18n = getI18n(); + const authStore = {}; const props = { i18n, @@ -17,19 +19,23 @@ describe("PaginatedList", () => { it("with no items renders nothing", () => { const result = render( - + + + ); expect(result.container.innerHTML).toEqual(""); }); it("with no items renders empty prop", async () => { const result = render( - Sorry, no results

} - 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..00e73a5e32 100644 --- a/app/components/PaginatedList.tsx +++ b/app/components/PaginatedList.tsx @@ -1,265 +1,315 @@ 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) ?? []; - } + const prevFetch = usePrevious(fetch); + const prevOptions = usePrevious(options); - render() { - const { - items = [], - heading, - auth, - empty = null, - renderHeading, - renderError, - onEscape, - } = this.props; + // Initial fetch on mount + React.useEffect(() => { + if (fetch) { + void fetchResults(); + } + }, [fetch]); - const showLoading = - this.isFetching && - !this.isFetchingMore && - (!items?.length || (this.fetchCounter <= 1 && this.isFetchingInitial)); - - if (showLoading) { - return ( - this.props.loading || ( - -
- -
-
- ) - ); + // Handle updates to fetch or options + React.useEffect(() => { + if (!prevFetch || !prevOptions) { + return; // Skip on initial mount since it's handled by the above effect } - if (items?.length === 0) { - if (this.error && renderError) { - return renderError({ error: this.error, retry: this.fetchResults }); - } - - return empty; + if (prevFetch !== fetch || !isEqual(prevOptions, options)) { + reset(); + void fetchResults(); } + }, [fetch, options, reset, fetchResults, prevFetch, prevOptions]); + // Computed property equivalent + const itemsToRender = React.useMemo( + () => items?.slice(0, renderCount) ?? [], + [items, renderCount] + ); + + 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/Reactions/ReactionPicker.tsx b/app/components/Reactions/ReactionPicker.tsx index 6aae9b446c..d5b765bb61 100644 --- a/app/components/Reactions/ReactionPicker.tsx +++ b/app/components/Reactions/ReactionPicker.tsx @@ -4,6 +4,7 @@ import { useTranslation } from "react-i18next"; import { PopoverDisclosure, usePopoverState } from "reakit"; import EventBoundary from "@shared/components/EventBoundary"; import Flex from "~/components/Flex"; +import { createLazyComponent } from "~/components/LazyLoad"; import NudeButton from "~/components/NudeButton"; import PlaceholderText from "~/components/PlaceholderText"; import Popover from "~/components/Popover"; @@ -12,7 +13,7 @@ import useOnClickOutside from "~/hooks/useOnClickOutside"; import useWindowSize from "~/hooks/useWindowSize"; import Tooltip from "../Tooltip"; -const EmojiPanel = React.lazy( +const EmojiPanel = createLazyComponent( () => import("~/components/IconPicker/components/EmojiPanel") ); @@ -104,6 +105,7 @@ const ReactionPicker: React.FC = ({ aria-label={t("Reaction picker")} className={className} onClick={handlePopoverButtonClick} + onMouseEnter={() => EmojiPanel.preload()} size={size} > @@ -123,7 +125,7 @@ const ReactionPicker: React.FC = ({ {popover.visible && ( }> - - 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) => ( { const filtered: Suggestion[] = ( document - ? users.notInDocument(document.id, query) + ? users + .notInDocument(document.id, query) + .filter((u) => u.id !== user.id) : collection ? users.notInCollection(collection.id, query) : users.activeOrInvited - ).filter((u) => !u.isSuspended && u.id !== user.id); + ).filter((u) => !u.isSuspended); if (isEmail(query)) { filtered.push(getSuggestionForEmail(query)); diff --git a/app/components/Sidebar/App.tsx b/app/components/Sidebar/App.tsx index 1f89d2210c..633e3781fb 100644 --- a/app/components/Sidebar/App.tsx +++ b/app/components/Sidebar/App.tsx @@ -12,7 +12,7 @@ import useCurrentTeam from "~/hooks/useCurrentTeam"; import useCurrentUser from "~/hooks/useCurrentUser"; import usePolicy from "~/hooks/usePolicy"; import useStores from "~/hooks/useStores"; -import OrganizationMenu from "~/menus/OrganizationMenu"; +import TeamMenu from "~/menus/TeamMenu"; import { homePath, searchPath } from "~/utils/routeHelpers"; import TeamLogo from "../TeamLogo"; import Tooltip from "../Tooltip"; @@ -62,7 +62,7 @@ function AppSidebar() { - + {(props: SidebarButtonProps) => ( )} - +
` z-index: ${depths.mobileSidebar}; max-width: 80%; min-width: 280px; + padding-left: var(--sal); ${fadeOnDesktopBackgrounded()} @media print { diff --git a/app/components/Sidebar/components/ArchiveLink.tsx b/app/components/Sidebar/components/ArchiveLink.tsx index 9f04d19b03..945ef4b284 100644 --- a/app/components/Sidebar/components/ArchiveLink.tsx +++ b/app/components/Sidebar/components/ArchiveLink.tsx @@ -82,12 +82,12 @@ function ArchiveLink() {
{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) => ( isModKey(ev) && + !popover.visible && ev.code === "KeyF" && // Keyboard handler is through the AppMenu on Desktop v1.2.0+ !(Desktop.bridge && "onFindInPage" in Desktop.bridge), diff --git a/app/editor/components/FloatingToolbar.tsx b/app/editor/components/FloatingToolbar.tsx index 5aaa082cf1..be304adc86 100644 --- a/app/editor/components/FloatingToolbar.tsx +++ b/app/editor/components/FloatingToolbar.tsx @@ -7,6 +7,7 @@ import { isCode } from "@shared/editor/lib/isCode"; import { findParentNode } from "@shared/editor/queries/findParentNode"; import { EditorStyleHelper } from "@shared/editor/styles/EditorStyleHelper"; import { depths, s } from "@shared/styles"; +import { getSafeAreaInsets } from "@shared/utils/browser"; import { HEADER_HEIGHT } from "~/components/Header"; import { Portal } from "~/components/Portal"; import useEventListener from "~/hooks/useEventListener"; @@ -241,12 +242,16 @@ const FloatingToolbar = React.forwardRef(function FloatingToolbar_( if (props.active) { const rect = document.body.getBoundingClientRect(); + const safeAreaInsets = getSafeAreaInsets(); + return ( {props.children} diff --git a/app/editor/components/LinkEditor.tsx b/app/editor/components/LinkEditor.tsx index baed135a00..6bb0fa1fae 100644 --- a/app/editor/components/LinkEditor.tsx +++ b/app/editor/components/LinkEditor.tsx @@ -10,6 +10,7 @@ import styled from "styled-components"; import Icon from "@shared/components/Icon"; import { hideScrollbars, s } from "@shared/styles"; import { isInternalUrl, sanitizeUrl } from "@shared/utils/urls"; +import DocumentBreadcrumb from "~/components/DocumentBreadcrumb"; import Flex from "~/components/Flex"; import { ResizingHeightContainer } from "~/components/ResizingHeightContainer"; import Scrollable from "~/components/Scrollable"; @@ -253,7 +254,14 @@ const LinkEditor: React.FC = ({ onPointerMove={() => setSelectedIndex(index)} selected={index === selectedIndex} key={doc.id} - subtitle={doc.collection?.name} + subtitle={ + + } title={doc.title} icon={ doc.icon ? ( diff --git a/app/editor/components/MentionMenu.tsx b/app/editor/components/MentionMenu.tsx index 192668bbe4..ca1b81eb2d 100644 --- a/app/editor/components/MentionMenu.tsx +++ b/app/editor/components/MentionMenu.tsx @@ -11,6 +11,7 @@ import { MenuItem } from "@shared/editor/types"; import { MentionType } from "@shared/types"; import parseDocumentSlug from "@shared/utils/parseDocumentSlug"; import { Avatar, AvatarSize } from "~/components/Avatar"; +import DocumentBreadcrumb from "~/components/DocumentBreadcrumb"; import Flex from "~/components/Flex"; import { DocumentsSection, @@ -57,7 +58,7 @@ function MentionMenu({ search, isActive, ...rest }: Props) { res.data.documents.map(documents.add); res.data.users.map(users.add); res.data.collections.map(collections.add); - }, [search, documents, users]) + }, [search, documents, users, collections]) ); React.useEffect(() => { @@ -68,7 +69,7 @@ function MentionMenu({ search, isActive, ...rest }: Props) { React.useEffect(() => { if (actorId && !loading) { - const items = users + const items: MentionItem[] = users .findByQuery(search, { maxResults: maxResultsInSection }) .map( (user) => @@ -112,7 +113,14 @@ function MentionMenu({ search, isActive, ...rest }: Props) { ), title: doc.title, - subtitle: doc.collection?.name, + subtitle: ( + + ), section: DocumentsSection, appendSpace: true, attrs: { diff --git a/app/editor/components/PasteMenu.tsx b/app/editor/components/PasteMenu.tsx index 9042f50a4f..8f6f74c69b 100644 --- a/app/editor/components/PasteMenu.tsx +++ b/app/editor/components/PasteMenu.tsx @@ -6,6 +6,7 @@ import { v4 } from "uuid"; import { EmbedDescriptor } from "@shared/editor/embeds"; import { MenuItem } from "@shared/editor/types"; import { MentionType } from "@shared/types"; +import { isUrl } from "@shared/utils/urls"; import Integration from "~/models/Integration"; import useCurrentUser from "~/hooks/useCurrentUser"; import useStores from "~/hooks/useStores"; @@ -29,9 +30,9 @@ export const PasteMenu = observer(({ pastedText, embeds, ...props }: Props) => { const user = useCurrentUser({ rejectOnEmpty: false }); let mentionType: MentionType | undefined; - const url = pastedText ? new URL(pastedText) : undefined; - if (url) { + if (pastedText && isUrl(pastedText)) { + const url = new URL(pastedText); const integration = integrations.find((intg: Integration) => isURLMentionable({ url, integration: intg }) ); diff --git a/app/editor/extensions/SmartText.ts b/app/editor/extensions/SmartText.ts index 4ed503ad8e..4090cb8c9a 100644 --- a/app/editor/extensions/SmartText.ts +++ b/app/editor/extensions/SmartText.ts @@ -2,7 +2,8 @@ import Extension from "@shared/editor/lib/Extension"; import { InputRule } from "@shared/editor/lib/InputRule"; const rightArrow = new InputRule(/->$/, "→"); -const emdash = new InputRule(/--$/, "—"); +// Note that the suppression of pipe here prevents conflict with table creation rule. +const emdash = new InputRule(/(?:^|[^\|])(--)$/, "—"); const oneHalf = new InputRule(/(?:^|\s)(1\/2)$/, "½"); const threeQuarters = new InputRule(/(?:^|\s)(3\/4)$/, "¾"); const copyright = new InputRule(/\(c\)$/, "©️"); diff --git a/app/editor/menus/formatting.tsx b/app/editor/menus/formatting.tsx index 3baf9e0044..e453a01228 100644 --- a/app/editor/menus/formatting.tsx +++ b/app/editor/menus/formatting.tsx @@ -67,7 +67,7 @@ export default function formattingMenuItems( shortcut: `${metaDisplay}+B`, icon: , active: isMarkActive(schema.marks.strong), - visible: !isCode && (!isMobile || !isEmpty), + visible: !isCodeBlock && (!isMobile || !isEmpty), }, { name: "em", @@ -75,7 +75,7 @@ export default function formattingMenuItems( shortcut: `${metaDisplay}+I`, icon: , active: isMarkActive(schema.marks.em), - visible: !isCode && (!isMobile || !isEmpty), + visible: !isCodeBlock && (!isMobile || !isEmpty), }, { name: "strikethrough", @@ -83,7 +83,7 @@ export default function formattingMenuItems( shortcut: `${metaDisplay}+D`, icon: , active: isMarkActive(schema.marks.strikethrough), - visible: !isCode && (!isMobile || !isEmpty), + visible: !isCodeBlock && (!isMobile || !isEmpty), }, { tooltip: dictionary.mark, diff --git a/app/hooks/useLoggedInSessions.ts b/app/hooks/useLoggedInSessions.ts new file mode 100644 index 0000000000..dbdbbcf719 --- /dev/null +++ b/app/hooks/useLoggedInSessions.ts @@ -0,0 +1,14 @@ +import { getCookie } from "tiny-cookie"; + +export type Sessions = Record< + string, + { + name: string; + logoUrl: string; + url: string; + } +>; + +export function useLoggedInSessions(): Sessions { + return JSON.parse(getCookie("sessions") || "{}"); +} diff --git a/app/hooks/useRequest.ts b/app/hooks/useRequest.ts index e5b6eed59a..4c40b81c68 100644 --- a/app/hooks/useRequest.ts +++ b/app/hooks/useRequest.ts @@ -59,7 +59,7 @@ export default function useRequest( if (makeRequestOnMount) { void request(); } - }, [request, makeRequestOnMount]); + }, []); return { data, loading, loaded, error, request }; } diff --git a/app/hooks/useSettingsConfig.ts b/app/hooks/useSettingsConfig.ts index 9d2942e648..c1fe3ce989 100644 --- a/app/hooks/useSettingsConfig.ts +++ b/app/hooks/useSettingsConfig.ts @@ -14,15 +14,16 @@ import { ShapesIcon, Icon, PlusIcon, + InternetIcon, } from "outline-icons"; import React, { ComponentProps } from "react"; import { useTranslation } from "react-i18next"; import { integrationSettingsPath } from "@shared/utils/routeHelpers"; import { Integrations } from "~/scenes/Settings/Integrations"; import ZapierIcon from "~/components/Icons/ZapierIcon"; +import { createLazyComponent as lazy } from "~/components/LazyLoad"; import { Hook, PluginManager } from "~/utils/PluginManager"; import isCloudHosted from "~/utils/isCloudHosted"; -import lazy from "~/utils/lazyWithRetry"; import { settingsPath } from "~/utils/routeHelpers"; import { useComputed } from "./useComputed"; import useCurrentTeam from "./useCurrentTeam"; @@ -31,7 +32,8 @@ import usePolicy from "./usePolicy"; import useStores from "./useStores"; const ApiKeys = lazy(() => import("~/scenes/Settings/ApiKeys")); -const PersonalApiKeys = lazy(() => import("~/scenes/Settings/PersonalApiKeys")); +const Applications = lazy(() => import("~/scenes/Settings/Applications")); +const APIAndApps = lazy(() => import("~/scenes/Settings/APIAndApps")); const Details = lazy(() => import("~/scenes/Settings/Details")); const Export = lazy(() => import("~/scenes/Settings/Export")); const Features = lazy(() => import("~/scenes/Settings/Features")); @@ -52,6 +54,7 @@ export type ConfigItem = { icon: React.FC>; component: React.ComponentType; description?: string; + preload?: () => void; enabled: boolean; group: string; isActive?: boolean; @@ -74,7 +77,8 @@ const useSettingsConfig = () => { { name: t("Profile"), path: settingsPath(), - component: Profile, + component: Profile.Component, + preload: Profile.preload, enabled: true, group: t("Account"), icon: ProfileIcon, @@ -82,7 +86,8 @@ const useSettingsConfig = () => { { name: t("Preferences"), path: settingsPath("preferences"), - component: Preferences, + component: Preferences.Component, + preload: Preferences.preload, enabled: true, group: t("Account"), icon: SettingsIcon, @@ -90,24 +95,27 @@ const useSettingsConfig = () => { { name: t("Notifications"), path: settingsPath("notifications"), - component: Notifications, + component: Notifications.Component, + preload: Notifications.preload, enabled: true, group: t("Account"), icon: EmailIcon, }, { - name: t("API Keys"), - path: settingsPath("personal-api-keys"), - component: PersonalApiKeys, - enabled: can.createApiKey && !can.listApiKeys, + name: t("API & Apps"), + path: settingsPath("api-and-apps"), + component: APIAndApps.Component, + preload: APIAndApps.preload, + enabled: true, group: t("Account"), - icon: CodeIcon, + icon: PadlockIcon, }, // Workspace { name: t("Details"), path: settingsPath("details"), - component: Details, + component: Details.Component, + preload: Details.preload, enabled: can.update, group: t("Workspace"), icon: TeamIcon, @@ -115,7 +123,8 @@ const useSettingsConfig = () => { { name: t("Security"), path: settingsPath("security"), - component: Security, + component: Security.Component, + preload: Security.preload, enabled: can.update, group: t("Workspace"), icon: PadlockIcon, @@ -123,7 +132,8 @@ const useSettingsConfig = () => { { name: t("Features"), path: settingsPath("features"), - component: Features, + component: Features.Component, + preload: Features.preload, enabled: can.update, group: t("Workspace"), icon: BeakerIcon, @@ -131,7 +141,8 @@ const useSettingsConfig = () => { { name: t("Members"), path: settingsPath("members"), - component: Members, + component: Members.Component, + preload: Members.preload, enabled: can.listUsers, group: t("Workspace"), icon: UserIcon, @@ -139,7 +150,8 @@ const useSettingsConfig = () => { { name: t("Groups"), path: settingsPath("groups"), - component: Groups, + component: Groups.Component, + preload: Groups.preload, enabled: can.listGroups, group: t("Workspace"), icon: GroupIcon, @@ -147,7 +159,8 @@ const useSettingsConfig = () => { { name: t("Templates"), path: settingsPath("templates"), - component: Templates, + component: Templates.Component, + preload: Templates.preload, enabled: can.readTemplate, group: t("Workspace"), icon: ShapesIcon, @@ -155,15 +168,26 @@ const useSettingsConfig = () => { { name: t("API Keys"), path: settingsPath("api-keys"), - component: ApiKeys, + component: ApiKeys.Component, + preload: ApiKeys.preload, enabled: can.listApiKeys, group: t("Workspace"), icon: CodeIcon, }, + { + name: t("Applications"), + path: settingsPath("applications"), + component: Applications.Component, + preload: Applications.preload, + enabled: can.listOAuthClients, + group: t("Workspace"), + icon: InternetIcon, + }, { name: t("Shared Links"), path: settingsPath("shares"), - component: Shares, + component: Shares.Component, + preload: Shares.preload, enabled: can.listShares, group: t("Workspace"), icon: GlobeIcon, @@ -171,7 +195,8 @@ const useSettingsConfig = () => { { name: t("Import"), path: settingsPath("import"), - component: Import, + component: Import.Component, + preload: Import.preload, enabled: can.createImport, group: t("Workspace"), icon: ImportIcon, @@ -179,7 +204,8 @@ const useSettingsConfig = () => { { name: t("Export"), path: settingsPath("export"), - component: Export, + component: Export.Component, + preload: Export.preload, enabled: can.createExport, group: t("Workspace"), icon: ExportIcon, @@ -188,7 +214,8 @@ const useSettingsConfig = () => { { name: "Zapier", path: integrationSettingsPath("zapier"), - component: Zapier, + component: Zapier.Component, + preload: Zapier.preload, enabled: can.update && isCloudHosted, group: t("Integrations"), icon: ZapierIcon, @@ -216,8 +243,9 @@ const useSettingsConfig = () => { ? integrationSettingsPath(plugin.id) : settingsPath(plugin.id), group: t(group), - component: plugin.value.component, description: plugin.value.description, + component: plugin.value.component.Component, + preload: plugin.value.component.preload, enabled: plugin.value.enabled ? plugin.value.enabled(team, user) : can.update, diff --git a/app/menus/OAuthAuthenticationMenu.tsx b/app/menus/OAuthAuthenticationMenu.tsx new file mode 100644 index 0000000000..8b826655c7 --- /dev/null +++ b/app/menus/OAuthAuthenticationMenu.tsx @@ -0,0 +1,57 @@ +import { observer } from "mobx-react"; +import * as React from "react"; +import { useTranslation } from "react-i18next"; +import { useMenuState } from "reakit/Menu"; +import OAuthAuthentication from "~/models/oauth/OAuthAuthentication"; +import ConfirmationDialog from "~/components/ConfirmationDialog"; +import ContextMenu from "~/components/ContextMenu"; +import MenuItem from "~/components/ContextMenu/MenuItem"; +import OverflowMenuButton from "~/components/ContextMenu/OverflowMenuButton"; +import useStores from "~/hooks/useStores"; + +type Props = { + /** The OAuthAuthentication to associate with the menu */ + oauthAuthentication: OAuthAuthentication; +}; + +function OAuthAuthenticationMenu({ oauthAuthentication }: Props) { + const menu = useMenuState({ + modal: true, + }); + const { dialogs } = useStores(); + const { t } = useTranslation(); + + const handleRevoke = React.useCallback(() => { + dialogs.openModal({ + title: t("Revoke {{ appName }}", { + appName: oauthAuthentication.oauthClient.name, + }), + content: ( + { + await oauthAuthentication.deleteAll(); + dialogs.closeAllModals(); + }} + submitText={t("Revoke")} + savingText={`${t("Revoking")}…`} + danger + > + {t("Are you sure you want to revoke access?")} + + ), + }); + }, [t, dialogs, oauthAuthentication]); + + return ( + <> + + + + {t("Revoke")} + + + + ); +} + +export default observer(OAuthAuthenticationMenu); diff --git a/app/menus/OAuthClientMenu.tsx b/app/menus/OAuthClientMenu.tsx new file mode 100644 index 0000000000..e2177c3b8e --- /dev/null +++ b/app/menus/OAuthClientMenu.tsx @@ -0,0 +1,68 @@ +import { observer } from "mobx-react"; +import * as React from "react"; +import { useTranslation } from "react-i18next"; +import { useMenuState } from "reakit/Menu"; +import OAuthClient from "~/models/oauth/OAuthClient"; +import OAuthClientDeleteDialog from "~/scenes/Settings/components/OAuthClientDeleteDialog"; +import ContextMenu from "~/components/ContextMenu"; +import OverflowMenuButton from "~/components/ContextMenu/OverflowMenuButton"; +import Template from "~/components/ContextMenu/Template"; +import useStores from "~/hooks/useStores"; +import { settingsPath } from "~/utils/routeHelpers"; + +type Props = { + /** The oauthClient to associate with the menu */ + oauthClient: OAuthClient; + /** Whether to show the edit button */ + showEdit?: boolean; +}; + +function OAuthClientMenu({ oauthClient, showEdit }: Props) { + const menu = useMenuState({ + modal: true, + }); + const { dialogs } = useStores(); + const { t } = useTranslation(); + + const handleDelete = React.useCallback(() => { + dialogs.openModal({ + title: t("Delete app"), + content: ( + + ), + }); + }, [t, dialogs, oauthClient]); + + return ( + <> + + +