diff --git a/.env.sample b/.env.sample index 30e1044124..e35f803405 100644 --- a/.env.sample +++ b/.env.sample @@ -120,6 +120,11 @@ AWS_S3_UPLOAD_BUCKET_NAME=bucket_name_here AWS_S3_FORCE_PATH_STYLE=true AWS_S3_ACL=private +# Optional CloudFront CDN for attachment downloads (uploads stay on S3). +# Requires a key pair for signed URLs; otherwise downloads fall back to S3. +AWS_CLOUDFRONT_URL= +AWS_CLOUDFRONT_KEY_PAIR_ID= +AWS_CLOUDFRONT_PRIVATE_KEY= # –––––––––––––––––––––––––––––––––––––– # –––––––––––––––– SSL ––––––––––––––– @@ -140,6 +145,11 @@ FORCE_HTTPS=true # and "X-Client-IP". # PROXY_IP_HEADER= +# Whether to trust the X-Forwarded-* headers (e.g. X-Forwarded-For, +# X-Forwarded-Proto) set by an upstream proxy. Set to false if not +# running behind a proxy in production. +# PROXY_HEADERS_TRUSTED=true + # –––––––––––––––––––––––––––––––––––––– # –––––––––– AUTHENTICATION –––––––––– diff --git a/.github/workflows/calibreapp-image-actions.yml b/.github/workflows/calibreapp-image-actions.yml index ab3d7c6689..d90251c498 100644 --- a/.github/workflows/calibreapp-image-actions.yml +++ b/.github/workflows/calibreapp-image-actions.yml @@ -43,7 +43,7 @@ jobs: uses: actions/checkout@v5 - name: Compress Images id: calibre - uses: calibreapp/image-actions@main + uses: calibreapp/image-actions@3d5873ac3e7bf1a38b24d9778d8dc639d5706d8b # main with: githubToken: ${{ secrets.GITHUB_TOKEN }} # For non-Pull Requests, run in compressOnly mode and we'll PR after. @@ -54,7 +54,7 @@ jobs: if: | github.event_name != 'pull_request' && steps.calibre.outputs.markdown != '' - uses: peter-evans/create-pull-request@v3 + uses: peter-evans/create-pull-request@18f7dc018cc2cd597073088f7c7591b9d1c02672 # v3 with: title: "chore: Auto Compress Images" branch-suffix: timestamp diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7d4d299439..208f43f7e1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -27,7 +27,7 @@ jobs: deps: ${{ steps.filter.outputs.deps }} steps: - uses: actions/checkout@v5 - - uses: dorny/paths-filter@v2 + - uses: dorny/paths-filter@4512585405083f25c027a35db413c2b3b9006d50 # v2 id: filter with: filters: | @@ -126,7 +126,7 @@ jobs: run: echo "NODE_ENV=production" >> $GITHUB_ENV - run: yarn vite:build - name: Send bundle stats to RelativeCI - uses: relative-ci/agent-action@v2 + uses: relative-ci/agent-action@38328454d6a23942175eba485fca4fbb807b1f03 # v2 with: key: ${{ secrets.RELATIVE_CI_KEY }} token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/docker-build-check.yml b/.github/workflows/docker-build-check.yml deleted file mode 100644 index 97b6709be5..0000000000 --- a/.github/workflows/docker-build-check.yml +++ /dev/null @@ -1,43 +0,0 @@ -name: Docker Build Check - -on: - push: - paths: - - "Dockerfile" - - "Dockerfile.base" - pull_request: - paths: - - "Dockerfile" - - "Dockerfile.base" - -env: - BASE_IMAGE_NAME: outline-base - -jobs: - build: - runs-on: ubicloud-standard-8 - steps: - - name: Checkout - uses: actions/checkout@v5 - - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v3 - with: - driver: docker - - - name: Build base image - uses: docker/build-push-action@v6 - with: - context: . - file: Dockerfile.base - tags: ${{ env.BASE_IMAGE_NAME }}:latest - push: false - - - name: Build main image - uses: docker/build-push-action@v6 - with: - context: . - file: Dockerfile - push: false - build-args: | - BASE_IMAGE=${{ env.BASE_IMAGE_NAME }}:latest diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index c8be149fd6..722402d1c3 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -4,6 +4,7 @@ on: push: tags: - "v*" + workflow_dispatch: env: IMAGE_NAME: outlinewiki/outline @@ -11,13 +12,13 @@ env: jobs: build-arm: - runs-on: ubicloud-standard-8-arm + runs-on: blacksmith-8vcpu-ubuntu-2404-arm steps: - name: Checkout uses: actions/checkout@v5 - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v4 + - name: Setup Blacksmith Builder + uses: useblacksmith/setup-docker-builder@ab5c1da94f53f5cd75c1038092aa276dddfccbba # v1 - name: Docker base meta id: base_meta @@ -37,7 +38,7 @@ jobs: - name: Build and push base image id: base_build - uses: docker/build-push-action@v7 + uses: useblacksmith/build-push-action@fb9e3e6a9299c78462bfadd0d93352c316adc9b8 # v2 with: context: . file: Dockerfile.base @@ -45,8 +46,6 @@ jobs: tags: ${{ env.BASE_IMAGE_NAME }} outputs: type=image,push-by-digest=true,name-canonical=true,push=true platforms: linux/arm64 - cache-from: type=gha - cache-to: type=gha,mode=max pull: false - name: Docker meta @@ -61,7 +60,7 @@ jobs: - name: Build and push id: build - uses: docker/build-push-action@v7 + uses: useblacksmith/build-push-action@fb9e3e6a9299c78462bfadd0d93352c316adc9b8 # v2 with: context: . file: Dockerfile @@ -69,8 +68,6 @@ jobs: tags: ${{ env.IMAGE_NAME }} outputs: type=image,push-by-digest=true,name-canonical=true,push=true platforms: linux/arm64 - cache-from: type=gha - cache-to: type=gha,mode=max pull: false build-args: | BASE_IMAGE=${{ env.BASE_IMAGE_NAME }}@${{ steps.base_build.outputs.digest }} @@ -90,13 +87,13 @@ jobs: retention-days: 1 build-amd: - runs-on: ubicloud-standard-8 + runs-on: blacksmith-8vcpu-ubuntu-2404 steps: - name: Checkout uses: actions/checkout@v5 - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v4 + - name: Setup Blacksmith Builder + uses: useblacksmith/setup-docker-builder@ab5c1da94f53f5cd75c1038092aa276dddfccbba # v1 - name: Docker base meta id: base_meta @@ -116,7 +113,7 @@ jobs: - name: Build and push base image id: base_build - uses: docker/build-push-action@v7 + uses: useblacksmith/build-push-action@fb9e3e6a9299c78462bfadd0d93352c316adc9b8 # v2 with: context: . file: Dockerfile.base @@ -124,8 +121,6 @@ jobs: tags: ${{ env.BASE_IMAGE_NAME }} outputs: type=image,push-by-digest=true,name-canonical=true,push=true platforms: linux/amd64 - cache-from: type=gha - cache-to: type=gha,mode=max pull: false - name: Docker meta @@ -140,7 +135,7 @@ jobs: - name: Build and push id: build - uses: docker/build-push-action@v7 + uses: useblacksmith/build-push-action@fb9e3e6a9299c78462bfadd0d93352c316adc9b8 # v2 with: context: . file: Dockerfile @@ -148,8 +143,6 @@ jobs: tags: ${{ env.IMAGE_NAME }} outputs: type=image,push-by-digest=true,name-canonical=true,push=true platforms: linux/amd64 - cache-from: type=gha - cache-to: type=gha,mode=max pull: false build-args: | BASE_IMAGE=${{ env.BASE_IMAGE_NAME }}@${{ steps.base_build.outputs.digest }} @@ -169,7 +162,7 @@ jobs: retention-days: 1 merge: - runs-on: ubicloud-standard-8 + runs-on: blacksmith-8vcpu-ubuntu-2404 needs: - build-amd - build-arm @@ -188,8 +181,8 @@ jobs: username: ${{ secrets.DOCKERHUB_USERNAME }} password: ${{ secrets.DOCKERHUB_TOKEN }} - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v4 + - name: Setup Blacksmith Builder + uses: useblacksmith/setup-docker-builder@ab5c1da94f53f5cd75c1038092aa276dddfccbba # v1 - name: Docker meta id: meta diff --git a/.github/workflows/update-node.yml b/.github/workflows/update-node.yml index beef80ed35..b87a089b64 100644 --- a/.github/workflows/update-node.yml +++ b/.github/workflows/update-node.yml @@ -78,7 +78,7 @@ jobs: - name: Create pull request if: steps.check.outputs.updated == 'true' - uses: peter-evans/create-pull-request@v7 + uses: peter-evans/create-pull-request@22a9089034f40e5a961c8808d113e2c98fb63676 # v7 with: commit-message: "fix: Update Node.js to ${{ steps.check.outputs.latest }}" title: "fix: Update Node.js to ${{ steps.check.outputs.latest }}" diff --git a/.gitignore b/.gitignore index ba5f1314d6..91db22af1e 100644 --- a/.gitignore +++ b/.gitignore @@ -14,6 +14,7 @@ data/* *.pem *.key *.cert +.history # Yarn Berry .yarn/* diff --git a/.oxlintrc.json b/.oxlintrc.json index 6be149f106..1fb98f54a6 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -73,6 +73,23 @@ "eqeqeq": "error", "curly": "error", "no-console": "error", + "no-restricted-imports": [ + "error", + { + "paths": [ + { + "name": "prosemirror-tables", + "importNames": [ + "addRowBefore", + "addRowAfter", + "addColumnBefore", + "addColumnAfter" + ], + "message": "Use the wrappers from shared/editor/commands/table instead, which respect the target index and place the cursor in the inserted cell." + } + ] + } + ], "no-unused-expressions": "error", "arrow-body-style": ["error", "as-needed"], "react/react-in-jsx-scope": "off", @@ -93,6 +110,7 @@ "typescript/consistent-type-imports": "error", "typescript/restrict-template-expressions": "error", "typescript/no-floating-promises": "error", + "typescript/no-useless-default-assignment": "error", "no-unused-vars": [ "error", { diff --git a/Dockerfile b/Dockerfile index 4abf0c7b97..210f3b8cf2 100644 --- a/Dockerfile +++ b/Dockerfile @@ -6,7 +6,7 @@ ARG APP_PATH WORKDIR $APP_PATH # --- -FROM node:24.15.0-slim AS runner +FROM node:24.16.0-slim AS runner LABEL org.opencontainers.image.source="https://github.com/outline/outline" diff --git a/Dockerfile.base b/Dockerfile.base index 4eea4c5fe0..21517f0dd3 100644 --- a/Dockerfile.base +++ b/Dockerfile.base @@ -1,5 +1,5 @@ ARG APP_PATH=/opt/outline -FROM node:24.15.0 AS deps +FROM node:24.16.0 AS deps ARG APP_PATH WORKDIR $APP_PATH diff --git a/LICENSE b/LICENSE index d7c1fe0e55..1de4bdfea8 100644 --- a/LICENSE +++ b/LICENSE @@ -3,7 +3,7 @@ Business Source License 1.1 Parameters Licensor: General Outline, Inc. -Licensed Work: Outline 1.7.1 +Licensed Work: Outline 1.8.1 The Licensed Work is (c) 2026 General Outline, Inc. Additional Use Grant: You may make use of the Licensed Work, provided that you may not use the Licensed Work for a Document @@ -15,7 +15,7 @@ Additional Use Grant: You may make use of the Licensed Work, provided that Licensed Work by creating teams and documents controlled by such third parties. -Change Date: 2030-05-04 +Change Date: 2030-06-06 Change License: Apache License, Version 2.0 diff --git a/app/actions/definitions/collections.tsx b/app/actions/definitions/collections.tsx index 0f560e155b..cf8c6d9357 100644 --- a/app/actions/definitions/collections.tsx +++ b/app/actions/definitions/collections.tsx @@ -20,6 +20,7 @@ import { UnsubscribeIcon, } from "outline-icons"; import { toast } from "sonner"; +import { errToString } from "@shared/utils/error"; import Collection from "~/models/Collection"; import { CollectionEdit } from "~/components/Collection/CollectionEdit"; import { CollectionNew } from "~/components/Collection/CollectionNew"; @@ -173,7 +174,7 @@ export const importDocument = createAction({ }); history.push(document.path); } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } finally { toast.dismiss(toastId); } diff --git a/app/actions/definitions/documents.tsx b/app/actions/definitions/documents.tsx index aa33e6202d..a0b178b908 100644 --- a/app/actions/definitions/documents.tsx +++ b/app/actions/definitions/documents.tsx @@ -36,6 +36,7 @@ import { OpenIcon, } from "outline-icons"; import { toast } from "sonner"; +import { errToString } from "@shared/utils/error"; import Icon from "@shared/components/Icon"; import type { NavigationNode } from "@shared/types"; import { ExportContentType, TeamPreference } from "@shared/types"; @@ -81,6 +82,7 @@ import { trashPath, documentEditPath, } from "~/utils/routeHelpers"; +import { documentBreadcrumbText } from "~/components/DocumentBreadcrumb"; import CollectionIcon from "~/components/Icons/CollectionIcon"; import type { Action, @@ -108,19 +110,21 @@ export const openDocument = createActionWithChildren({ shortcut: ["o", "d"], keywords: "go to", icon: , - children: ({ stores }) => { + children: ({ stores, t }) => { const nodes = stores.collections.navigationNodes.reduce( (acc, node) => [...acc, ...node.children], [] as NavigationNode[] ); const documents = stores.documents.orderedData; - return uniqBy([...documents, ...nodes], "id").map((item) => - createInternalLinkAction({ + return uniqBy([...documents, ...nodes], "id").map((item) => { + const document = stores.documents.get(item.id); + return createInternalLinkAction({ // Note: using url which includes the slug rather than id here to bust // cache if the document is renamed id: item.url, name: item.title, + description: document ? documentBreadcrumbText(document, t) : undefined, icon: item.icon ? ( node.id === document.id) ?? -1; } +/** + * Determines whether the user can create a sibling of the given document. + * A sibling shares the document's parent, so this mirrors the backend's + * create authorization: create permission on the parent document, or on the + * collection when the document is at the root. + * + * @param stores - the root stores. + * @param document - the document to create a sibling of. + * @returns true if the user can create a sibling. + */ +function canCreateSiblingDocument( + stores: ActionContext["stores"], + document: { collectionId?: string | null; parentDocumentId?: string } +): boolean { + return document.parentDocumentId + ? stores.policies.abilities(document.parentDocumentId).createChildDocument + : !!document.collectionId && + stores.policies.abilities(document.collectionId).createDocument; +} + export const createNestedDocument = createInternalLinkAction({ name: ({ t }) => t("Nested document"), analyticsName: "New document", @@ -269,10 +293,14 @@ const createDocumentBefore = createInternalLinkAction({ return false; } const document = stores.documents.get(activeDocumentId); - return ( - !!document?.collectionId && - stores.policies.abilities(currentTeamId).createDocument - ); + if (!document?.collectionId) { + return false; + } + const collection = stores.collections.get(document.collectionId); + if (collection?.sort.field === "title") { + return false; + } + return canCreateSiblingDocument(stores, document); }, to: ({ activeDocumentId, stores, sidebarContext }) => { const document = activeDocumentId @@ -307,10 +335,14 @@ const createDocumentAfter = createInternalLinkAction({ return false; } const document = stores.documents.get(activeDocumentId); - return ( - !!document?.collectionId && - stores.policies.abilities(currentTeamId).createDocument - ); + if (!document?.collectionId) { + return false; + } + const collection = stores.collections.get(document.collectionId); + if (collection?.sort.field === "title") { + return false; + } + return canCreateSiblingDocument(stores, document); }, to: ({ activeDocumentId, stores, sidebarContext }) => { const document = activeDocumentId @@ -335,6 +367,18 @@ const createDocumentAfter = createInternalLinkAction({ }, }); +function isAlphabeticallySorted( + stores: ActionContext["stores"], + activeDocumentId: string +): boolean { + const document = stores.documents.get(activeDocumentId); + if (!document?.collectionId) { + return false; + } + const collection = stores.collections.get(document.collectionId); + return collection?.sort.field === "title"; +} + export const createNewDocument = createActionWithChildren({ name: ({ t }) => t("New document"), analyticsName: "New document", @@ -342,17 +386,48 @@ export const createNewDocument = createActionWithChildren({ icon: , keywords: "create", visible: ({ currentTeamId, activeDocumentId, stores }) => { - if (!activeDocumentId) { + if (!activeDocumentId || !currentTeamId) { return false; } - - return ( - !!currentTeamId && stores.policies.abilities(currentTeamId).createDocument - ); + if (!stores.policies.abilities(currentTeamId).createDocument) { + return false; + } + return !isAlphabeticallySorted(stores, activeDocumentId); }, children: [createDocumentBefore, createDocumentAfter, createNestedDocument], }); +export const createNewDocumentInAlphabeticalCollection = + createInternalLinkAction({ + name: ({ t }) => t("New document"), + analyticsName: "New document", + section: ActiveDocumentSection, + icon: , + keywords: "create", + visible: ({ currentTeamId, activeDocumentId, stores }) => { + if (!activeDocumentId || !currentTeamId) { + return false; + } + if (!stores.policies.abilities(currentTeamId).createDocument) { + return false; + } + if (!stores.policies.abilities(activeDocumentId).createChildDocument) { + return false; + } + return isAlphabeticallySorted(stores, activeDocumentId); + }, + to: ({ activeDocumentId, sidebarContext }) => { + const [pathname, search] = + newNestedDocumentPath(activeDocumentId).split("?"); + + return { + pathname, + search, + state: { sidebarContext }, + }; + }, + }); + export const starDocument = createAction({ name: ({ t }) => t("Star"), analyticsName: "Star document", @@ -1049,7 +1124,7 @@ export const importDocument = createAction({ ); history.push(document.url); } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } finally { toast.dismiss(toastId); } @@ -1528,6 +1603,7 @@ export const rootDocumentActions = [ createDocument, createDraftDocument, createNewDocument, + createNewDocumentInAlphabeticalCollection, createNestedDocument, createTemplateFromDocument, deleteDocument, diff --git a/app/actions/definitions/revisions.tsx b/app/actions/definitions/revisions.tsx index be90ec8633..fee7d43e9e 100644 --- a/app/actions/definitions/revisions.tsx +++ b/app/actions/definitions/revisions.tsx @@ -3,6 +3,7 @@ import { LinkIcon, RestoreIcon, TrashIcon, DownloadIcon } from "outline-icons"; import { matchPath } from "react-router-dom"; import { toast } from "sonner"; import { ExportContentType } from "@shared/types"; +import Revision from "~/models/Revision"; import stores from "~/stores"; import { createAction, createActionWithChildren } from "~/actions"; import { RevisionSection } from "~/actions/sections"; @@ -21,7 +22,7 @@ export const restoreRevision = createAction({ section: RevisionSection, visible: ({ activeDocumentId }) => !!activeDocumentId && stores.policies.abilities(activeDocumentId).update, - perform: async ({ event, location, activeDocumentId }) => { + perform: async ({ event, location, activeDocumentId, getActiveModel }) => { event?.preventDefault(); if (!activeDocumentId) { return; @@ -30,7 +31,10 @@ export const restoreRevision = createAction({ const match = matchPath<{ revisionId: string }>(location.pathname, { path: matchDocumentHistory, }); - const revisionId = match?.params.revisionId; + const revisionId = getActiveModel(Revision)?.id ?? match?.params.revisionId; + if (!revisionId) { + return; + } const document = stores.documents.get(activeDocumentId); if (!document) { diff --git a/app/actions/definitions/shares.tsx b/app/actions/definitions/shares.tsx index 5ddde114e3..fb4ce8239a 100644 --- a/app/actions/definitions/shares.tsx +++ b/app/actions/definitions/shares.tsx @@ -1,4 +1,5 @@ import copy from "copy-to-clipboard"; +import { errToString } from "@shared/utils/error"; import type Share from "~/models/Share"; import { createAction, createInternalLinkAction } from ".."; import { ArrowIcon, CopyIcon, TrashIcon } from "outline-icons"; @@ -53,7 +54,7 @@ export const revokeShareFactory = ({ await stores.shares.revoke(share); toast.message(t("Share link revoked")); } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } }, }); diff --git a/app/actions/sections.ts b/app/actions/sections.ts index fa5190d736..a192f97f46 100644 --- a/app/actions/sections.ts +++ b/app/actions/sections.ts @@ -13,6 +13,10 @@ ActiveCollectionSection.priority = 0.8; export const DeveloperSection = ({ t }: ActionContext) => t("Debug"); +export const DateSection = ({ t }: ActionContext) => t("Date"); + +DateSection.priority = 1; + export const DocumentSection = ({ t }: ActionContext) => t("Document"); export const SearchResultsSection = ({ t }: ActionContext) => diff --git a/app/components/Authenticated.tsx b/app/components/Authenticated.tsx index 8b0ac6fcb6..9a50239400 100644 --- a/app/components/Authenticated.tsx +++ b/app/components/Authenticated.tsx @@ -1,5 +1,5 @@ import { observer } from "mobx-react"; -import { useEffect } from "react"; +import { useEffect, useRef } from "react"; import { useTranslation } from "react-i18next"; import { Redirect } from "react-router-dom"; import useCurrentUser from "~/hooks/useCurrentUser"; @@ -16,6 +16,7 @@ const Authenticated = ({ children }: Props) => { const { i18n } = useTranslation(); const user = useCurrentUser({ rejectOnEmpty: false }); const language = user?.language; + const hasLoggedOut = useRef(false); // Watching for language changes here as this is the earliest point we might have the user // available and means we can start loading translations faster @@ -23,23 +24,36 @@ const Authenticated = ({ children }: Props) => { void changeLanguage(language, i18n); }, [i18n, language]); + const shouldLogout = !auth.authenticated && !auth.isFetching; + + // Passive logout when we land here without an authenticated session – note we + // intentionally do not revoke the server-side token, as that would clobber + // the session in any other tab that may have already re-authenticated. + useEffect(() => { + if (shouldLogout && !hasLoggedOut.current) { + hasLoggedOut.current = true; + void auth.logout({ + savePath: true, + clearCache: false, + revokeToken: false, + }); + } + }, [shouldLogout, auth]); + + useEffect(() => { + if (auth.logoutRedirectUri) { + window.location.href = auth.logoutRedirectUri; + } + }, [auth.logoutRedirectUri]); + if (auth.authenticated) { return children; } - if (auth.isFetching) { + if (auth.isFetching || auth.logoutRedirectUri) { return ; } - void auth.logout({ - savePath: true, - clearCache: false, - }); - - if (auth.logoutRedirectUri) { - window.location.href = auth.logoutRedirectUri; - return null; - } return ; }; diff --git a/app/components/AuthenticatedLayout.tsx b/app/components/AuthenticatedLayout.tsx index 4aa0c01ba4..6499cb5b5a 100644 --- a/app/components/AuthenticatedLayout.tsx +++ b/app/components/AuthenticatedLayout.tsx @@ -1,6 +1,8 @@ import { observer } from "mobx-react"; import * as React from "react"; +import { DndProvider } from "react-dnd"; import { useLocation } from "react-router-dom"; +import { EditorAwareHTML5Backend } from "~/components/EditorAwareHTML5Backend"; import ErrorSuspended from "~/scenes/Errors/ErrorSuspended"; import Layout from "~/components/Layout"; import RegisterKeyDown from "~/components/RegisterKeyDown"; @@ -104,14 +106,16 @@ const AuthenticatedLayout: React.FC = ({ children }: Props) => { - - - - - {children} - - - + + + + + + {children} + + + + diff --git a/app/components/Collaborators.tsx b/app/components/Collaborators.tsx index 360e33ffd9..0f554e9b51 100644 --- a/app/components/Collaborators.tsx +++ b/app/components/Collaborators.tsx @@ -79,10 +79,10 @@ function Collaborators(props: Props) { // Memoize ids to avoid unnecessary effect executions const missingUserIds = useMemo( () => - uniq([...document.collaboratorIds, ...Array.from(presentIds)]) + uniq([...collaboratorIdsSet, ...presentIds]) .filter((userId) => !users.get(userId)) .sort(), - [document.collaboratorIds, presentIds, users] + [collaboratorIdsSet, presentIds, users] ); useEffect(() => { diff --git a/app/components/Collection/CollectionEdit.tsx b/app/components/Collection/CollectionEdit.tsx index cef1e0c80b..c85e94c9dc 100644 --- a/app/components/Collection/CollectionEdit.tsx +++ b/app/components/Collection/CollectionEdit.tsx @@ -1,6 +1,7 @@ import { observer } from "mobx-react"; import { useCallback } from "react"; import { toast } from "sonner"; +import { errToString } from "@shared/utils/error"; import useStores from "~/hooks/useStores"; import type { FormData } from "./CollectionForm"; import { CollectionForm } from "./CollectionForm"; @@ -23,7 +24,7 @@ export const CollectionEdit = observer(function CollectionEdit_({ await collection?.save(data); onSubmit?.(); } catch (error) { - toast.error(error.message); + toast.error(errToString(error)); } }, [collection, onSubmit] diff --git a/app/components/Collection/CollectionNew.tsx b/app/components/Collection/CollectionNew.tsx index 05877b2c03..1645f93f5f 100644 --- a/app/components/Collection/CollectionNew.tsx +++ b/app/components/Collection/CollectionNew.tsx @@ -2,6 +2,7 @@ import { runInAction } from "mobx"; import { observer } from "mobx-react"; import { useCallback } from "react"; import { toast } from "sonner"; +import { errToString } from "@shared/utils/error"; import useStores from "~/hooks/useStores"; import history from "~/utils/history"; import type { FormData } from "./CollectionForm"; @@ -26,7 +27,7 @@ export const CollectionNew = observer(function CollectionNew_({ onSubmit?.(); history.push(collection.path); } catch (error) { - toast.error(error.message); + toast.error(errToString(error)); } }, [collections, onSubmit] diff --git a/app/components/CommandBar/useRecentDocumentActions.tsx b/app/components/CommandBar/useRecentDocumentActions.tsx index a104350439..bb109fc0fd 100644 --- a/app/components/CommandBar/useRecentDocumentActions.tsx +++ b/app/components/CommandBar/useRecentDocumentActions.tsx @@ -1,13 +1,16 @@ import { DocumentIcon } from "outline-icons"; import { useMemo } from "react"; +import { useTranslation } from "react-i18next"; import Icon from "@shared/components/Icon"; import { createInternalLinkAction } from "~/actions"; import { RecentSection } from "~/actions/sections"; +import { documentBreadcrumbText } from "~/components/DocumentBreadcrumb"; import useStores from "~/hooks/useStores"; import { documentPath } from "~/utils/routeHelpers"; const useRecentDocumentActions = (count = 6) => { const { documents, ui } = useStores(); + const { t } = useTranslation(); return useMemo( () => @@ -19,6 +22,7 @@ const useRecentDocumentActions = (count = 6) => { name: item.titleWithDefault, analyticsName: "Recently viewed document", section: RecentSection, + description: documentBreadcrumbText(item, t), icon: item.icon ? ( { to: documentPath(item), }) ), - [count, ui.activeDocumentId, documents.recentlyViewed] + [count, ui.activeDocumentId, documents.recentlyViewed, t] ); }; diff --git a/app/components/CommentDeleteDialog.tsx b/app/components/CommentDeleteDialog.tsx index 7808c022b4..61c8faa899 100644 --- a/app/components/CommentDeleteDialog.tsx +++ b/app/components/CommentDeleteDialog.tsx @@ -1,6 +1,7 @@ import { observer } from "mobx-react"; import { useTranslation, Trans } from "react-i18next"; import { toast } from "sonner"; +import { errToString } from "@shared/utils/error"; import type Comment from "~/models/Comment"; import ConfirmationDialog from "~/components/ConfirmationDialog"; import Text from "~/components/Text"; @@ -21,7 +22,7 @@ function CommentDeleteDialog({ comment, onSubmit }: Props) { await comment.delete(); onSubmit?.(); } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } }; diff --git a/app/components/ConfirmMoveDialog.tsx b/app/components/ConfirmMoveDialog.tsx index 75d13f186a..55401670a8 100644 --- a/app/components/ConfirmMoveDialog.tsx +++ b/app/components/ConfirmMoveDialog.tsx @@ -1,6 +1,7 @@ import { observer } from "mobx-react"; import { Trans, useTranslation } from "react-i18next"; import { toast } from "sonner"; +import { errToString } from "@shared/utils/error"; import type { NavigationNode } from "@shared/types"; import { CollectionPermission } from "@shared/types"; import type Collection from "~/models/Collection"; @@ -50,7 +51,7 @@ function ConfirmMoveDialog({ collection, item, ...rest }: Props) { ) ); } else { - toast.error(err.message); + toast.error(errToString(err)); } } finally { dialogs.closeAllModals(); diff --git a/app/components/ConfirmationDialog.tsx b/app/components/ConfirmationDialog.tsx index 6dc927d312..75e702f9d9 100644 --- a/app/components/ConfirmationDialog.tsx +++ b/app/components/ConfirmationDialog.tsx @@ -2,6 +2,7 @@ import { observer } from "mobx-react"; import * as React from "react"; import { useTranslation } from "react-i18next"; import { toast } from "sonner"; +import { errToString } from "@shared/utils/error"; import Button from "~/components/Button"; import Flex from "~/components/Flex"; import Text from "~/components/Text"; @@ -44,7 +45,7 @@ const ConfirmationDialog: React.FC = ({ } dialogs.closeAllModals(); } catch (err) { - toast.error(err.message); + toast.error(errToString(err)); } finally { setIsSaving(false); } diff --git a/app/components/DefaultCollectionInputSelect.tsx b/app/components/DefaultCollectionInputSelect.tsx index e46edac00a..caac5675eb 100644 --- a/app/components/DefaultCollectionInputSelect.tsx +++ b/app/components/DefaultCollectionInputSelect.tsx @@ -8,6 +8,7 @@ import { getLuminance } from "polished"; import React, { useState } from "react"; import { useTranslation } from "react-i18next"; import { toast } from "sonner"; +import { toError } from "@shared/utils/error"; import Icon from "@shared/components/Icon"; import { colorPalette } from "@shared/utils/collections"; import type { Option } from "~/components/InputSelect"; @@ -27,7 +28,7 @@ const DefaultCollectionInputSelect = observer( const { t } = useTranslation(); const { collections, ui } = useStores(); const [fetching, setFetching] = useState(false); - const [fetchError, setFetchError] = useState(); + const [fetchError, setFetchError] = useState(); React.useEffect(() => { async function fetchData() { @@ -41,7 +42,7 @@ const DefaultCollectionInputSelect = observer( toast.error( t("Collections could not be loaded, please reload the app") ); - setFetchError(error); + setFetchError(toError(error)); } finally { setFetching(false); } diff --git a/app/components/DesktopEventHandler.tsx b/app/components/DesktopEventHandler.tsx index dbfac609b1..28ca23249c 100644 --- a/app/components/DesktopEventHandler.tsx +++ b/app/components/DesktopEventHandler.tsx @@ -15,7 +15,7 @@ export default function DesktopEventHandler() { const hasDisabledUpdateMessage = useRef(false); useEffect(() => { - Desktop.bridge?.redirect((path: string, replace = false) => { + Desktop.bridge?.redirect((path: string, replace: boolean) => { if (replace) { history.replace(path); } else { diff --git a/app/components/DocumentBreadcrumb.tsx b/app/components/DocumentBreadcrumb.tsx index c3da07a972..aa53d86efc 100644 --- a/app/components/DocumentBreadcrumb.tsx +++ b/app/components/DocumentBreadcrumb.tsx @@ -1,10 +1,10 @@ +import type { TFunction } from "i18next"; import { observer } from "mobx-react"; import { ArchiveIcon, GoToIcon, TrashIcon } from "outline-icons"; import * as React from "react"; import { useTranslation } from "react-i18next"; import styled from "styled-components"; import Icon from "@shared/components/Icon"; -import type { NavigationNode } from "@shared/types"; import type Collection from "~/models/Collection"; import type Document from "~/models/Document"; import Breadcrumb from "~/components/Breadcrumb"; @@ -20,6 +20,56 @@ import { archivePath, trashPath } from "~/utils/routeHelpers"; import { createInternalLinkAction } from "~/actions"; import { ActiveDocumentSection } from "~/actions/sections"; +/** + * Returns the breadcrumb parts leading up to a document, separating the + * (possibly deleted) collection label from ancestor document titles. The + * document itself is not included. + * + * @param document - the document to compute the breadcrumb for. + * @param t - translation function for fallback titles. + * @returns the collection label and ancestor titles. + */ +export function documentBreadcrumbParts( + document: Document, + t: TFunction +): { collection: string | undefined; ancestors: string[] } { + let collectionLabel: string | undefined; + if (document.isCollectionDeleted) { + collectionLabel = t("Deleted Collection"); + } else if (document.collection?.name) { + collectionLabel = document.collection.name; + } + + return { + collection: collectionLabel, + ancestors: document.pathTo + .slice(0, -1) + .map((node) => node.title || t("Untitled")), + }; +} + +/** + * Returns the breadcrumb path leading up to a document as a plain text + * string. Includes the collection name (or "Deleted Collection" fallback) + * and any ancestor document titles, slash-separated. + * + * @param document - the document to compute the breadcrumb for. + * @param t - translation function for fallback titles. + * @returns the breadcrumb as a slash-separated string, or undefined if the + * document has no resolvable parent context. + */ +export function documentBreadcrumbText( + document: Document, + t: TFunction +): string | undefined { + const parts = documentBreadcrumbParts(document, t); + const segments = [ + ...(parts.collection ? [parts.collection] : []), + ...parts.ancestors, + ]; + return segments.length ? segments.join(" / ") : undefined; +} + type Props = { children?: React.ReactNode; document: Document; @@ -147,22 +197,25 @@ function DocumentBreadcrumb( return <>; } - const slicedPath = reverse - ? path.slice(depth && -depth) - : path.slice(0, depth); + const { collection: collectionLabel, ancestors: ancestorLabels } = + documentBreadcrumbParts(document, t); + + const slicedAncestors = reverse + ? ancestorLabels.slice(depth && -depth) + : ancestorLabels.slice(0, depth); const showCollection = - collection && - (!reverse || depth === undefined || slicedPath.length < depth); + !!collectionLabel && + (!reverse || depth === undefined || slicedAncestors.length < depth); return ( <> - {showCollection && collection.name} - {slicedPath.map((node: NavigationNode, index: number) => ( - + {showCollection && collectionLabel} + {slicedAncestors.map((label, index) => ( + {showCollection && } - {node.title || t("Untitled")} - {!showCollection && index !== slicedPath.length - 1 && ( + {label} + {!showCollection && index !== slicedAncestors.length - 1 && ( )} diff --git a/app/components/DocumentContext.tsx b/app/components/DocumentContext.tsx index e37ec76d6d..20a8d2ac82 100644 --- a/app/components/DocumentContext.tsx +++ b/app/components/DocumentContext.tsx @@ -31,6 +31,10 @@ class DocumentContext { @action setDocument = (document: Document) => { + // Reset the focused comment when navigating between documents + if (this.document && this.document.id !== document.id) { + this.focusedCommentId = null; + } this.document = document; this.updateState(); }; diff --git a/app/components/DocumentExplorer/DocumentCopy.tsx b/app/components/DocumentExplorer/DocumentCopy.tsx index 0210a6a078..fe36f738e3 100644 --- a/app/components/DocumentExplorer/DocumentCopy.tsx +++ b/app/components/DocumentExplorer/DocumentCopy.tsx @@ -40,8 +40,8 @@ function DocumentCopy({ document, onSubmit }: Props) { return nodes; }, [policies, collectionTrees]); - const copy = async () => { - if (!selectedPath) { + const copy = async (path = selectedPath) => { + if (!path) { toast.message(t("Select a location to copy")); return; } @@ -52,10 +52,8 @@ function DocumentCopy({ document, onSubmit }: Props) { publish, recursive, title: document.title, - collectionId: selectedPath.collectionId, - ...(selectedPath.type === "document" - ? { parentDocumentId: selectedPath.id } - : {}), + collectionId: path.collectionId, + ...(path.type === "document" ? { parentDocumentId: path.id } : {}), }); toast.success(t("Document copied")); @@ -111,7 +109,7 @@ function DocumentCopy({ document, onSubmit }: Props) { t("Select a location to copy") )} - diff --git a/app/components/DocumentExplorer/DocumentExplorer.tsx b/app/components/DocumentExplorer/DocumentExplorer.tsx index 7bb06360ed..daa6dccde1 100644 --- a/app/components/DocumentExplorer/DocumentExplorer.tsx +++ b/app/components/DocumentExplorer/DocumentExplorer.tsx @@ -31,7 +31,7 @@ import useStores from "~/hooks/useStores"; type Props = { /** Action taken upon submission of selected item, could be publish, move etc. */ - onSubmit: () => void; + onSubmit: (item: NavigationNode | null) => void; /** A side-effect of item selection */ onSelect: (item: NavigationNode | null) => void; /** Items to be shown in explorer */ @@ -255,6 +255,13 @@ function DocumentExplorer({ } }; + const submitNode = (node: number) => { + const selectedNode = nodes[node]; + + selectNode(selectedNode); + onSubmit(selectedNode); + }; + const ListItem = observer( ({ index, @@ -311,7 +318,8 @@ function DocumentExplorer({ width: `calc(${style.width} - ${HORIZONTAL_PADDING * 2}px)`, }} onPointerMove={() => setActiveNode(index)} - onClick={() => toggleSelect(index)} + onClick={() => selectNode(nodes[index])} + onDoubleClick={() => submitNode(index)} icon={renderedIcon} title={title} path={path} @@ -325,7 +333,8 @@ function DocumentExplorer({ width: `calc(${style.width} - ${HORIZONTAL_PADDING * 2}px)`, }} onPointerMove={() => setActiveNode(index)} - onClick={() => toggleSelect(index)} + onClick={() => selectNode(nodes[index])} + onDoubleClick={() => submitNode(index)} onDisclosureClick={(ev) => { ev.stopPropagation(); toggleCollapse(index); @@ -387,7 +396,7 @@ function DocumentExplorer({ } case "Enter": { if (isModKey(ev)) { - onSubmit(); + onSubmit(selectedNode); } else { toggleSelect(activeNode); } diff --git a/app/components/DocumentExplorer/DocumentExplorerNode.tsx b/app/components/DocumentExplorer/DocumentExplorerNode.tsx index b4556d0c97..a47984d48c 100644 --- a/app/components/DocumentExplorer/DocumentExplorerNode.tsx +++ b/app/components/DocumentExplorer/DocumentExplorerNode.tsx @@ -29,8 +29,10 @@ type Props = { onDisclosureClick: (ev: React.MouseEvent) => void; /** Fired on pointer movement over the node; used to update the active highlight. */ onPointerMove: (ev: React.MouseEvent) => void; - /** Fired when the node is clicked to toggle its selection. */ + /** Fired when the node is clicked to select it. */ onClick: (ev: React.MouseEvent) => void; + /** Fired when the node is double-clicked to submit the current selection. */ + onDoubleClick: (ev: React.MouseEvent) => void; }; function DocumentExplorerNode( @@ -46,6 +48,7 @@ function DocumentExplorerNode( onDisclosureClick, onPointerMove, onClick, + onDoubleClick, }: Props, ref: React.RefObject ) { @@ -59,6 +62,7 @@ function DocumentExplorerNode( selected={selected} active={active} onClick={onClick} + onDoubleClick={onDoubleClick} style={style} onPointerMove={onPointerMove} role="option" diff --git a/app/components/DocumentExplorer/DocumentExplorerSearchResult.tsx b/app/components/DocumentExplorer/DocumentExplorerSearchResult.tsx index 0b41ec9241..38d5449080 100644 --- a/app/components/DocumentExplorer/DocumentExplorerSearchResult.tsx +++ b/app/components/DocumentExplorer/DocumentExplorerSearchResult.tsx @@ -17,6 +17,7 @@ type Props = { onPointerMove: (ev: React.MouseEvent) => void; onClick: (ev: React.MouseEvent) => void; + onDoubleClick: (ev: React.MouseEvent) => void; }; function DocumentExplorerSearchResult({ @@ -28,6 +29,7 @@ function DocumentExplorerSearchResult({ path, onPointerMove, onClick, + onDoubleClick, }: Props) { const { t } = useTranslation(); @@ -36,6 +38,7 @@ function DocumentExplorerSearchResult({ selected={selected} active={active} onClick={onClick} + onDoubleClick={onDoubleClick} style={style} onPointerMove={onPointerMove} role="option" diff --git a/app/components/DocumentExplorer/DocumentMove.tsx b/app/components/DocumentExplorer/DocumentMove.tsx index 5a05f74474..80d9640a47 100644 --- a/app/components/DocumentExplorer/DocumentMove.tsx +++ b/app/components/DocumentExplorer/DocumentMove.tsx @@ -56,17 +56,17 @@ function DocumentMove({ document }: Props) { return nodes; }, [policies, collectionTrees, document.id]); - const move = async () => { - if (!selectedPath) { + const move = async (path = selectedPath) => { + if (!path) { toast.message(t("Select a location to move")); return; } try { setMoving(true); - const { type, id: parentDocumentId } = selectedPath; + const { type, id: parentDocumentId } = path; - const collectionId = selectedPath.collectionId as string; + const collectionId = path.collectionId as string; if (type === "document") { await document.move({ collectionId, parentDocumentId }); @@ -103,7 +103,7 @@ function DocumentMove({ document }: Props) { t("Select a location to move") )} - diff --git a/app/components/DocumentExplorer/TemplateMove.tsx b/app/components/DocumentExplorer/TemplateMove.tsx index b472f38107..d16ca6941b 100644 --- a/app/components/DocumentExplorer/TemplateMove.tsx +++ b/app/components/DocumentExplorer/TemplateMove.tsx @@ -33,15 +33,14 @@ function TemplateMove({ template }: Props) { [policies, collectionTrees] ); - const move = async () => { - if (!selectedPath) { + const move = async (path = selectedPath) => { + if (!path) { toast.message(t("Select a location to move")); return; } try { - const collectionId = (selectedPath.collectionId ?? - selectedPath.id) as string; + const collectionId = (path.collectionId ?? path.id) as string; await template.save({ collectionId }); toast.success(t("Template moved")); @@ -76,7 +75,7 @@ function TemplateMove({ template }: Props) { t("Select a location to move") )} - diff --git a/app/components/DocumentListItem.tsx b/app/components/DocumentListItem.tsx index 8df3789913..2453e68750 100644 --- a/app/components/DocumentListItem.tsx +++ b/app/components/DocumentListItem.tsx @@ -5,6 +5,7 @@ import { import { observer } from "mobx-react"; import * as React from "react"; import { useTranslation } from "react-i18next"; +import { mergeRefs } from "react-merge-refs"; import { Link } from "react-router-dom"; import { DocumentIcon } from "outline-icons"; import styled, { css, useTheme } from "styled-components"; @@ -27,6 +28,7 @@ import { useLocationSidebarContext } from "~/hooks/useLocationSidebarContext"; import DocumentMenu from "~/menus/DocumentMenu"; import { documentPath } from "~/utils/routeHelpers"; import { determineSidebarContext } from "./Sidebar/components/SidebarContext"; +import { useDragDocument } from "./Sidebar/hooks/useDragAndDrop"; import { ActionContextProvider } from "~/hooks/useActionContext"; import { useDocumentMenuAction } from "~/hooks/useDocumentMenuAction"; import { ContextMenu } from "./Menu/ContextMenu"; @@ -98,6 +100,23 @@ function DocumentListItem( const contextMenuAction = useDocumentMenuAction({ documentId: document.id }); + const [{ isDragging }, draggableRef] = useDragDocument( + document.asNavigationNode, + 0, + document, + false, + false + ); + + const mergedRef = React.useMemo( + () => + mergeRefs([ + itemRef, + draggableRef, + ] as React.Ref[]), + [itemRef, draggableRef] + ); + return ( ` display: flex; @@ -237,6 +258,8 @@ const DocumentLink = styled(Link)<{ max-height: 50vh; width: calc(100vw - 8px); cursor: var(--pointer); + transition: opacity 250ms ease; + opacity: ${(props) => (props.$isDragging ? 0.1 : 1)}; &:focus-visible { outline: none; diff --git a/app/components/EditableTitle.tsx b/app/components/EditableTitle.tsx index 38f0433e3b..cd9b065e0a 100644 --- a/app/components/EditableTitle.tsx +++ b/app/components/EditableTitle.tsx @@ -1,6 +1,7 @@ import * as React from "react"; import { toast } from "sonner"; import styled from "styled-components"; +import { errToString } from "@shared/utils/error"; import { s, ellipsis } from "@shared/styles"; import EventBoundary from "@shared/components/EventBoundary"; @@ -109,7 +110,7 @@ function EditableTitle( setValue(value); setIsEditing(true); - toast.error(error.message); + toast.error(errToString(error)); throw error; } finally { setIsSubmitting(false); diff --git a/app/components/EditorAwareHTML5Backend.ts b/app/components/EditorAwareHTML5Backend.ts new file mode 100644 index 0000000000..ff35a5a7b8 --- /dev/null +++ b/app/components/EditorAwareHTML5Backend.ts @@ -0,0 +1,68 @@ +import type { BackendFactory } from "dnd-core"; +import { HTML5Backend } from "react-dnd-html5-backend"; + +/** + * react-dnd's HTML5 backend installs global drag listeners on `window` in both + * the capture and bubble phases. The bubble-phase `dragover` handler runs after + * ProseMirror's and, when react-dnd isn't tracking a drag, forces + * `dataTransfer.dropEffect = "none"` – which tells the browser the drop is + * disallowed and silently rejects images dragged into the editor. + * + * These handlers live on `window`, so a propagation-based guard can't stop + * react-dnd without also starving the editor of the event. Instead we wrap the + * backend and make all of its top-level handlers no-op for events that occur + * within the editor surface, leaving ProseMirror to handle them itself. + */ +const topHandlerNames = [ + "handleTopDragStart", + "handleTopDragStartCapture", + "handleTopDragEnter", + "handleTopDragEnterCapture", + "handleTopDragLeaveCapture", + "handleTopDragOver", + "handleTopDragOverCapture", + "handleTopDrop", + "handleTopDropCapture", + "handleTopDragEndCapture", +] as const; + +const isWithinEditor = (target: EventTarget | null): boolean => + target instanceof Element && Boolean(target.closest(".ProseMirror")); + +/** + * An HTML5 drag-and-drop backend that ignores drag events originating within the + * rich text editor so that ProseMirror can handle them itself. + * + * @param manager The drag-and-drop manager. + * @param context The global context. + * @param options Backend options. + * @returns The wrapped HTML5 backend instance. + */ +export const EditorAwareHTML5Backend: BackendFactory = ( + manager, + context, + options +) => { + const backend = HTML5Backend(manager, context, options); + + // The top-level handlers are private instance fields on the backend, so reach + // for them through an index signature view of the instance. + const handlers = backend as unknown as Record< + string, + (event: DragEvent) => void + >; + + for (const name of topHandlerNames) { + const original = handlers[name]; + if (typeof original === "function") { + handlers[name] = (event: DragEvent) => { + if (isWithinEditor(event.target)) { + return; + } + original.call(backend, event); + }; + } + } + + return backend; +}; diff --git a/app/components/FilterOptions.tsx b/app/components/FilterOptions.tsx index 049902be2e..59338ec0b7 100644 --- a/app/components/FilterOptions.tsx +++ b/app/components/FilterOptions.tsx @@ -1,16 +1,26 @@ import { deburr } from "es-toolkit/compat"; +import { CheckmarkIcon } from "outline-icons"; import * as React from "react"; import { useTranslation } from "react-i18next"; import styled from "styled-components"; import { s } from "@shared/styles"; import type { FetchPageParams } from "~/stores/base/Store"; import Button, { Inner } from "~/components/Button"; +import Scrollable from "~/components/Scrollable"; import Text from "~/components/Text"; +import useMobile from "~/hooks/useMobile"; import Input, { NativeInput, Outline } from "./Input"; import type { PaginatedItem } from "./PaginatedList"; import PaginatedList from "./PaginatedList"; +import { + Drawer, + DrawerContent, + DrawerTitle, + DrawerTrigger, +} from "./primitives/Drawer"; import { MenuProvider } from "./primitives/Menu/MenuContext"; import { Menu, MenuContent, MenuTrigger, MenuButton } from "./primitives/Menu"; +import * as MenuComponents from "./primitives/components/Menu"; import { MenuIconWrapper } from "./primitives/components/Menu"; interface TFilterOption extends PaginatedItem { @@ -34,7 +44,7 @@ type Props = { const FilterOptions = ({ options, - selectedKeys = [], + selectedKeys, className, onSelect, showFilter, @@ -45,6 +55,7 @@ const FilterOptions = ({ ...rest }: Props) => { const { t } = useTranslation(); + const isMobile = useMobile(); const searchInputRef = React.useRef(null); const listRef = React.useRef(null); const [open, setOpen] = React.useState(false); @@ -58,23 +69,45 @@ const FilterOptions = ({ : ""; const renderItem = React.useCallback( - (option) => ( - {option.icon} - ) : undefined - } - label={option.label} - onClick={() => { - onSelect(option.key); - setOpen(false); - }} - selected={selectedKeys.includes(option.key)} - /> - ), - [onSelect, showIcons, selectedKeys] + (option) => { + const handleClick = () => { + onSelect(option.key); + setOpen(false); + }; + + const icon = + option.icon && showIcons ? ( + {option.icon} + ) : undefined; + + // On mobile the options render inside a Drawer (bottom sheet) rather than + // a Radix dropdown menu, so use the raw menu components directly instead + // of the dropdown-bound MenuButton which expects a menu root context. + if (isMobile) { + return ( + + {icon} + {option.label} + + {selectedKeys.includes(option.key) ? ( + + ) : null} + + + ); + } + + return ( + + ); + }, + [onSelect, showIcons, selectedKeys, isMobile] ); const handleFilter = React.useCallback( @@ -169,39 +202,73 @@ const FilterOptions = ({ React.useEffect(() => { if (open) { - searchInputRef.current?.focus(); + // Avoid auto-focusing on mobile as it immediately pops the on-screen + // keyboard over the drawer. + if (!isMobile) { + searchInputRef.current?.focus(); + } } else { setQuery(""); } - }, [open]); + }, [open, isMobile]); const showFilterInput = showFilter || options.length > 10; const defaultLabel = rest.defaultLabel || t("Filter options"); + const trigger = ( + + {selectedItems.length ? selectedLabel : defaultLabel} + + ); + + const list = ( + + listRef={listRef} + options={{ query, ...fetchQueryOptions }} + items={filteredOptions} + fetch={fetchQuery} + renderItem={renderItem} + onEscape={handleEscapeFromList} + heading={showFilterInput && !isMobile ? : undefined} + empty={} + /> + ); + + // On mobile render the options inside a Drawer (bottom sheet) to match the + // popover style used by context menus across the app. + if (isMobile) { + return ( + + {trigger} + + {defaultLabel} + {showFilterInput && ( + + )} + {list} + + + ); + } + return ( - - - {selectedItems.length ? selectedLabel : defaultLabel} - - + {trigger} - - listRef={listRef} - options={{ query, ...fetchQueryOptions }} - items={filteredOptions} - fetch={fetchQuery} - renderItem={renderItem} - onEscape={handleEscapeFromList} - heading={showFilterInput ? : undefined} - empty={} - /> + {list} {showFilterInput && ( { - setOpen(false); const icType = determineIconType(ic); const finalColor = icType === IconType.SVG ? chosenColor : null; onChange(ic, finalColor); diff --git a/app/components/InputSearchPage.tsx b/app/components/InputSearchPage.tsx index 6e898de5e9..d73601bb36 100644 --- a/app/components/InputSearchPage.tsx +++ b/app/components/InputSearchPage.tsx @@ -4,6 +4,7 @@ import * as React from "react"; import { useTranslation } from "react-i18next"; import { useHistory } from "react-router-dom"; import styled, { useTheme } from "styled-components"; +import breakpoint from "styled-components-breakpoint"; import { s } from "@shared/styles"; import { isModKey, @@ -117,6 +118,12 @@ function InputSearchPage({ const InputMaxWidth = styled(Input).attrs({ round: true })` max-width: min(calc(30vw + 20px), 100%); + + /* On mobile the input grows to fill the header, so add a gap before the + * adjacent action button (e.g. "New doc"). */ + ${breakpoint("mobile", "tablet")` + margin-inline-end: 8px; + `} `; const Shortcut = styled.span<{ $visible: boolean }>` diff --git a/app/components/Lightbox.tsx b/app/components/Lightbox.tsx index 448dd59a5f..9618f13e39 100644 --- a/app/components/Lightbox.tsx +++ b/app/components/Lightbox.tsx @@ -2,7 +2,12 @@ import { observer } from "mobx-react"; import * as Dialog from "@radix-ui/react-dialog"; import type { Keyframes } from "styled-components"; import styled, { css, keyframes } from "styled-components"; -import type { ComponentProps, HTMLAttributes, ReactNode } from "react"; +import type { + ComponentProps, + HTMLAttributes, + ReactNode, + SyntheticEvent, +} from "react"; import { createContext, forwardRef, @@ -18,6 +23,7 @@ import { Error as ImageError } from "@shared/editor/components/Image"; import { BackIcon, CloseIcon, + CommentIcon, CrossIcon, DownloadIcon, LinkIcon, @@ -55,6 +61,10 @@ import { NodeSelection } from "prosemirror-state"; import { ImageSource } from "@shared/editor/lib/FileHelper"; import Desktop from "~/utils/Desktop"; import { HStack } from "./primitives/HStack"; +import { useDocumentContext } from "./DocumentContext"; +import LightboxComments from "~/scenes/Document/components/Comments/LightboxComments"; +import { PortalContext } from "./Portal"; +import useHideElement from "~/hooks/useHideElement"; export enum LightboxStatus { READY_TO_OPEN, @@ -88,6 +98,15 @@ type Animation = { const ANIMATION_DURATION = 0.3 * Second.ms; +/** + * Stops a React synthetic event from propagating to ancestor handlers, including + * Radix Dialog's outside-interaction detection and the editor's own click + * handlers, so the comments sidebar can manage its own focus. + */ +const stopPropagation = (event: SyntheticEvent) => { + event.stopPropagation(); +}; + type Props = { /** List of allowed images */ images: LightboxImage[]; @@ -225,6 +244,11 @@ function Lightbox({ images, activeImage, onUpdate, onClose, readOnly }: Props) { const overlayRef = useRef(null); const contentRef = useRef(null); const [status, setStatus] = useState({ lightbox: null, image: null }); + const [commentsOpen, setCommentsOpen] = useState(false); + const [commentsRendered, setCommentsRendered] = useState(false); + const [commentsVisible, setCommentsVisible] = useState(false); + const [commentsPortalEl, setCommentsPortalEl] = + useState(null); const animation = useRef(null); const finalImage = useRef<{ center: { x: number; y: number }; @@ -233,6 +257,10 @@ function Lightbox({ images, activeImage, onUpdate, onClose, readOnly }: Props) { } | null>(null); const zoomPanPinchRef = useRef(null); const editor = useEditor(); + const { document: contextDocument } = useDocumentContext(); + const activeNode = editor?.view?.state?.doc?.nodeAt(activeImage.pos); + const canShowComments = + !!contextDocument && activeNode?.type.name === "image"; const currentImageIndex = findIndex( images, @@ -312,6 +340,19 @@ function Lightbox({ images, activeImage, onUpdate, onClose, readOnly }: Props) { } }, [status.lightbox]); + useEffect(() => { + if (commentsOpen) { + setCommentsRendered(true); + const frame = window.requestAnimationFrame(() => + setCommentsVisible(true) + ); + return () => window.cancelAnimationFrame(frame); + } + setCommentsVisible(false); + const timer = window.setTimeout(() => setCommentsRendered(false), 200); + return () => window.clearTimeout(timer); + }, [commentsOpen]); + useEffect(() => { if (status.image === ImageStatus.MIN_ZOOM) { // It was observed that focus went to `body` as the zoom out button was disabled @@ -321,6 +362,15 @@ function Lightbox({ images, activeImage, onUpdate, onClose, readOnly }: Props) { } }, [status.image]); + // Hide the inline image in the editor while the lightbox zoom transition is + // active, otherwise a duplicate is visible behind the fading overlay. + useHideElement( + activeImage.getElement(), + status.lightbox !== null && + status.lightbox !== LightboxStatus.READY_TO_OPEN && + status.lightbox !== LightboxStatus.CLOSED + ); + const rememberImagePosition = () => { if (imgRef.current) { const lightboxImgDOMRect = imgRef.current.getBoundingClientRect(); @@ -441,6 +491,10 @@ function Lightbox({ images, activeImage, onUpdate, onClose, readOnly }: Props) { status.image === ImageStatus.MAX_ZOOM ) ) { + // Refresh the cached natural image position to account for any layout + // changes (e.g., the comments sidebar opening) since the image loaded. + rememberImagePosition(); + // in lightbox const lightboxImgDOMRect = imgRef.current.getBoundingClientRect(); const { @@ -632,17 +686,30 @@ function Lightbox({ images, activeImage, onUpdate, onClose, readOnly }: Props) { }, [activeImage, status.lightbox]); const handleKeyDown = (ev: React.KeyboardEvent) => { - ev.preventDefault(); + // Don't intercept keys while typing into an input, textarea, or editor. + const target = ev.target as HTMLElement | null; + if ( + target && + target !== ev.currentTarget && + (target.tagName === "INPUT" || + target.tagName === "TEXTAREA" || + target.isContentEditable) + ) { + return; + } switch (ev.key) { case "ArrowLeft": { + ev.preventDefault(); prev(); break; } case "ArrowRight": { + ev.preventDefault(); next(); break; } case "Escape": { + ev.preventDefault(); close(); break; } @@ -698,14 +765,21 @@ function Lightbox({ images, activeImage, onUpdate, onClose, readOnly }: Props) { onAnimationStart={handleFadeStart} onAnimationEnd={handleFadeEnd} /> - + {t("Lightbox")} {t("View, navigate, or download images in the document")} - + )} - + {canShowComments && ( + + setCommentsOpen((open) => !open)} + aria-label={t("Comments")} + aria-pressed={commentsOpen} + size={32} + icon={} + borderOnHover + neutral + /> + + )} + + - + {currentImageIndex > 0 && !( status.image === ImageStatus.ZOOMED || @@ -878,12 +967,36 @@ function Lightbox({ images, activeImage, onUpdate, onClose, readOnly }: Props) { status.image === ImageStatus.ZOOMED || status.image === ImageStatus.MAX_ZOOM ) && ( -