diff --git a/.eslintrc b/.eslintrc index fcc8e7b8f7..38207533d4 100644 --- a/.eslintrc +++ b/.eslintrc @@ -65,7 +65,7 @@ ], "padding-line-between-statements": ["error", { "blankLine": "always", "prev": "*", "next": "export" }], "lines-between-class-members": ["error", "always", { "exceptAfterSingleLine": true }], - "lodash/import-scope": ["warn", "method"], + "lodash/import-scope": ["error", "method"], "import/no-named-as-default": "off", "import/no-named-as-default-member": "off", "import/newline-after-import": 2, diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ff2eb0afcd..fad0be731a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -11,7 +11,7 @@ env: DATABASE_URL: postgres://postgres:password@localhost:5432/outline_test REDIS_URL: redis://127.0.0.1:6379 URL: http://localhost:3000 - NODE_OPTIONS: --max-old-space-size=8000 + NODE_OPTIONS: --max-old-space-size=8192 SECRET_KEY: F0E5AD933D7F6FD8F4DBB3E038C501C052DC0593C686D21ACB30AE205D2F634B UTILS_SECRET: 123456 SLACK_VERIFICATION_TOKEN: 123456 @@ -63,6 +63,7 @@ jobs: runs-on: ubuntu-latest outputs: server: ${{ steps.filter.outputs.server }} + app: ${{ steps.filter.outputs.app }} steps: - uses: actions/checkout@v4 - uses: dorny/paths-filter@v2 @@ -81,7 +82,7 @@ jobs: - 'yarn.lock' test: - needs: build + needs: [build, changes] if: ${{ needs.changes.outputs.app == 'true' }} runs-on: ubuntu-latest strategy: @@ -143,8 +144,8 @@ jobs: yarn test --maxWorkers=2 $TESTFILES bundle-size: - needs: [build, types] - if: ${{ needs.changes.outputs.app == 'true' }} + needs: [build, types, changes] + if: ${{ needs.changes.outputs.app == 'true' && github.repository == 'outline/outline' }} runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 @@ -161,3 +162,4 @@ jobs: with: key: ${{ secrets.RELATIVE_CI_KEY }} token: ${{ secrets.GITHUB_TOKEN }} + webpackStatsFile: ./build/app/webpack-stats.json diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 0d58a68228..478a0aaaf9 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -3,25 +3,32 @@ name: Docker on: push: tags: - - 'v*' + - "v*" env: IMAGE_NAME: outlinewiki/outline BASE_IMAGE_NAME: outlinewiki/outline-base jobs: - build-and-push: - runs-on: ubuntu-latest + build-arm: + runs-on: ubicloud-standard-8-arm steps: - name: Checkout uses: actions/checkout@v4 - - name: Set up QEMU - uses: docker/setup-qemu-action@v3 - - name: Set up Docker Buildx uses: docker/setup-buildx-action@v3 + - name: Docker base meta + id: base_meta + uses: docker/metadata-action@v5 + with: + images: | + ${{ env.BASE_IMAGE_NAME }} + tags: | + type=semver,pattern={{version}} + type=semver,pattern={{major}}.{{minor}} + - name: Login to Docker Hub uses: docker/login-action@v3 with: @@ -29,24 +36,177 @@ jobs: password: ${{ secrets.DOCKERHUB_TOKEN }} - name: Build and push base image - uses: docker/build-push-action@v5 + id: base_build + uses: docker/build-push-action@v6 with: context: . file: Dockerfile.base - push: true - tags: ${{ env.BASE_IMAGE_NAME }}:latest - platforms: linux/amd64,linux/arm/v7,linux/arm64/v8,linux/ppc64le,linux/s390x + labels: ${{ steps.base_meta.outputs.labels }} + 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: Extract version - id: version - run: echo "VERSION=${GITHUB_REF#refs/tags/v}" >> $GITHUB_OUTPUT + - name: Docker meta + id: meta + uses: docker/metadata-action@v5 + with: + images: | + ${{ env.IMAGE_NAME }} + tags: | + type=semver,pattern={{version}} + type=semver,pattern={{major}}.{{minor}} - - name: Build and push main image - uses: docker/build-push-action@v5 + - name: Build and push + id: build + uses: docker/build-push-action@v6 with: context: . - push: true - platforms: linux/amd64,linux/arm/v7,linux/arm64/v8,linux/ppc64le,linux/s390x + file: Dockerfile + labels: ${{ steps.meta.outputs.labels }} + 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 }} + + - name: Export digest + run: | + mkdir -p ${{ runner.temp }}/digests + digest="${{ steps.build.outputs.digest }}" + touch "${{ runner.temp }}/digests/${digest#sha256:}" + + - name: Upload digest + uses: actions/upload-artifact@v4 + with: + name: digests-linux-arm64 + path: ${{ runner.temp }}/digests/* + if-no-files-found: error + retention-days: 1 + + build-amd: + runs-on: ubicloud-standard-8 + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Docker base meta + id: base_meta + uses: docker/metadata-action@v5 + with: + images: | + ${{ env.BASE_IMAGE_NAME }} tags: | - ${{ env.IMAGE_NAME }}:latest - ${{ env.IMAGE_NAME }}:${{ steps.version.outputs.VERSION }} + type=semver,pattern={{version}} + type=semver,pattern={{major}}.{{minor}} + + - name: Login to Docker Hub + uses: docker/login-action@v3 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + + - name: Build and push base image + id: base_build + uses: docker/build-push-action@v6 + with: + context: . + file: Dockerfile.base + labels: ${{ steps.base_meta.outputs.labels }} + 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 + id: meta + uses: docker/metadata-action@v5 + with: + images: | + ${{ env.IMAGE_NAME }} + tags: | + type=semver,pattern={{version}} + type=semver,pattern={{major}}.{{minor}} + + - name: Build and push + id: build + uses: docker/build-push-action@v6 + with: + context: . + file: Dockerfile + labels: ${{ steps.meta.outputs.labels }} + 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 }} + + - name: Export digest + run: | + mkdir -p ${{ runner.temp }}/digests + digest="${{ steps.build.outputs.digest }}" + touch "${{ runner.temp }}/digests/${digest#sha256:}" + + - name: Upload digest + uses: actions/upload-artifact@v4 + with: + name: digests-linux-amd64 + path: ${{ runner.temp }}/digests/* + if-no-files-found: error + retention-days: 1 + + merge: + runs-on: ubicloud-standard-8 + needs: + - build-amd + - build-arm + steps: + - name: Download digests + uses: actions/download-artifact@v4 + with: + path: ${{ runner.temp }}/digests + pattern: digests-* + merge-multiple: true + + - name: Login to Docker Hub + uses: docker/login-action@v3 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Docker meta + id: meta + uses: docker/metadata-action@v5 + with: + images: ${{ env.IMAGE_NAME }} + tags: | + type=ref,event=branch + type=ref,event=pr + type=semver,pattern={{version}} + type=semver,pattern={{major}}.{{minor}} + + - name: Create manifest list and push + working-directory: ${{ runner.temp }}/digests + run: | + docker buildx imagetools create $(jq -cr '.tags | map("-t " + .) | join(" ")' <<< "$DOCKER_METADATA_OUTPUT_JSON") \ + $(printf '${{ env.IMAGE_NAME }}@sha256:%s ' *) + + - name: Inspect image + run: | + docker buildx imagetools inspect ${{ env.IMAGE_NAME }}:${{ steps.meta.outputs.version }} \ No newline at end of file diff --git a/Dockerfile b/Dockerfile index a0393b6b93..fcc6d08168 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,5 +1,6 @@ ARG APP_PATH=/opt/outline -FROM outlinewiki/outline-base AS base +ARG BASE_IMAGE=outlinewiki/outline-base +FROM ${BASE_IMAGE} AS base ARG APP_PATH WORKDIR $APP_PATH @@ -30,7 +31,7 @@ RUN addgroup --gid 1001 nodejs && \ adduser --uid 1001 --ingroup nodejs nodejs && \ chown -R nodejs:nodejs $APP_PATH/build && \ mkdir -p /var/lib/outline && \ - chown -R nodejs:nodejs /var/lib/outline + chown -R nodejs:nodejs /var/lib/outline ENV FILE_STORAGE_LOCAL_ROOT_DIR=/var/lib/outline/data RUN mkdir -p "$FILE_STORAGE_LOCAL_ROOT_DIR" && \ diff --git a/Dockerfile.base b/Dockerfile.base index 13378f1caa..91f90f3c2a 100644 --- a/Dockerfile.base +++ b/Dockerfile.base @@ -1,11 +1,14 @@ ARG APP_PATH=/opt/outline -FROM node:20-slim AS deps +FROM node:20 AS deps ARG APP_PATH WORKDIR $APP_PATH COPY ./package.json ./yarn.lock ./ COPY ./patches ./patches +RUN apt-get update && apt-get install -y cmake +ENV NODE_OPTIONS="--max-old-space-size=24000" + RUN yarn install --no-optional --frozen-lockfile --network-timeout 1000000 && \ yarn cache clean diff --git a/LICENSE b/LICENSE index 3eeb03aa9a..a53c10886f 100644 --- a/LICENSE +++ b/LICENSE @@ -3,7 +3,7 @@ Business Source License 1.1 Parameters Licensor: General Outline, Inc. -Licensed Work: Outline 0.82.0 +Licensed Work: Outline 0.83.0 The Licensed Work is (c) 2025 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: 2029-02-15 +Change Date: 2029-04-11 Change License: Apache License, Version 2.0 diff --git a/app/actions/definitions/documents.tsx b/app/actions/definitions/documents.tsx index 911a466ed5..867fdb2b7d 100644 --- a/app/actions/definitions/documents.tsx +++ b/app/actions/definitions/documents.tsx @@ -29,6 +29,7 @@ import { PadlockIcon, GlobeIcon, LogoutIcon, + CaseSensitiveIcon, } from "outline-icons"; import * as React from "react"; import { toast } from "sonner"; @@ -510,6 +511,25 @@ export const copyDocumentAsMarkdown = createAction({ }, }); +export const copyDocumentAsPlainText = createAction({ + name: ({ t }) => t("Copy as text"), + section: ActiveDocumentSection, + keywords: "clipboard", + icon: , + iconInContextMenu: false, + visible: ({ activeDocumentId, stores }) => + !!activeDocumentId && stores.policies.abilities(activeDocumentId).download, + perform: ({ stores, activeDocumentId, t }) => { + const document = activeDocumentId + ? stores.documents.get(activeDocumentId) + : undefined; + if (document) { + copy(document.toPlainText()); + toast.success(t("Text copied to clipboard")); + } + }, +}); + export const copyDocumentShareLink = createAction({ name: ({ t }) => t("Copy public link"), section: ActiveDocumentSection, @@ -555,7 +575,12 @@ export const copyDocument = createAction({ section: ActiveDocumentSection, icon: , keywords: "clipboard", - children: [copyDocumentLink, copyDocumentShareLink, copyDocumentAsMarkdown], + children: [ + copyDocumentLink, + copyDocumentShareLink, + copyDocumentAsMarkdown, + copyDocumentAsPlainText, + ], }); export const duplicateDocument = createAction({ @@ -1205,6 +1230,7 @@ export const rootDocumentActions = [ copyDocumentLink, copyDocumentShareLink, copyDocumentAsMarkdown, + copyDocumentAsPlainText, starDocument, unstarDocument, publishDocument, diff --git a/app/components/HoverPreview/HoverPreview.tsx b/app/components/HoverPreview/HoverPreview.tsx index c6a79d8f6e..f57527e483 100644 --- a/app/components/HoverPreview/HoverPreview.tsx +++ b/app/components/HoverPreview/HoverPreview.tsx @@ -1,4 +1,5 @@ import { m } from "framer-motion"; +import { observer } from "mobx-react"; import * as React from "react"; import { Portal } from "react-portal"; import styled from "styled-components"; @@ -8,6 +9,7 @@ import useEventListener from "~/hooks/useEventListener"; import useKeyDown from "~/hooks/useKeyDown"; import useMobile from "~/hooks/useMobile"; import useOnClickOutside from "~/hooks/useOnClickOutside"; +import useStores from "~/hooks/useStores"; import LoadingIndicator from "../LoadingIndicator"; import { CARD_MARGIN } from "./Components"; import HoverPreviewDocument from "./HoverPreviewDocument"; @@ -23,9 +25,9 @@ const POINTER_WIDTH = 22; type Props = { /** The HTML element that is being hovered over, or null if none. */ element: HTMLElement | null; - /** Data to be previewed */ - data: Record | null; - /** Whether the preview data is being loaded */ + /** ID of the unfurl that will be shown in the hover preview. */ + unfurlId: string | null; + /** Whether the preview data is being loaded. */ dataLoading: boolean; /** A callback on close of the hover preview. */ onClose: () => void; @@ -36,151 +38,155 @@ enum Direction { DOWN, } -function HoverPreviewDesktop({ element, data, dataLoading, onClose }: Props) { - const [isVisible, setVisible] = React.useState(false); - const timerClose = React.useRef>(); - const cardRef = React.useRef(null); - const { cardLeft, cardTop, pointerLeft, pointerTop, pointerDir } = - useHoverPosition({ - cardRef, - element, - isVisible, - }); +const HoverPreviewDesktop = observer( + ({ element, unfurlId, dataLoading, onClose }: Props) => { + const { unfurls } = useStores(); + const [isVisible, setVisible] = React.useState(false); + const timerClose = React.useRef>(); + const cardRef = React.useRef(null); + const { cardLeft, cardTop, pointerLeft, pointerTop, pointerDir } = + useHoverPosition({ + cardRef, + element, + isVisible, + }); + const data = unfurlId ? unfurls.get(unfurlId)?.data : undefined; - const closePreview = React.useCallback(() => { - setVisible(false); - onClose(); - }, [onClose]); + const closePreview = React.useCallback(() => { + setVisible(false); + onClose(); + }, [onClose]); - const stopCloseTimer = React.useCallback(() => { - if (timerClose.current) { - clearTimeout(timerClose.current); - timerClose.current = undefined; - } - }, []); - - const startCloseTimer = React.useCallback(() => { - timerClose.current = setTimeout(closePreview, DELAY_CLOSE); - }, [closePreview]); - - // Open and close the preview when the element changes. - React.useEffect(() => { - if (element && data && !dataLoading) { - setVisible(true); - } else { - startCloseTimer(); - } - }, [startCloseTimer, element, data, dataLoading]); - - // Close the preview on Escape, scroll, or click outside. - useOnClickOutside(cardRef, closePreview); - useKeyDown("Escape", closePreview); - useEventListener("scroll", closePreview, window, { capture: true }); - - // Ensure that the preview stays open while the user is hovering over the card. - React.useEffect(() => { - const card = cardRef.current; - - if (isVisible) { - if (card) { - card.addEventListener("mouseenter", stopCloseTimer); - card.addEventListener("mouseleave", startCloseTimer); + const stopCloseTimer = React.useCallback(() => { + if (timerClose.current) { + clearTimeout(timerClose.current); + timerClose.current = undefined; } - } + }, []); - return () => { - if (card) { - card.removeEventListener("mouseenter", stopCloseTimer); - card.removeEventListener("mouseleave", startCloseTimer); + const startCloseTimer = React.useCallback(() => { + timerClose.current = setTimeout(closePreview, DELAY_CLOSE); + }, [closePreview]); + + // Open and close the preview when the element changes. + React.useEffect(() => { + if (element && data && !dataLoading) { + setVisible(true); + } else { + startCloseTimer(); + } + }, [startCloseTimer, element, data, dataLoading]); + + // Close the preview on Escape, scroll, or click outside. + useOnClickOutside(cardRef, closePreview); + useKeyDown("Escape", closePreview); + useEventListener("scroll", closePreview, window, { capture: true }); + + // Ensure that the preview stays open while the user is hovering over the card. + React.useEffect(() => { + const card = cardRef.current; + + if (isVisible) { + if (card) { + card.addEventListener("mouseenter", stopCloseTimer); + card.addEventListener("mouseleave", startCloseTimer); + } } - stopCloseTimer(); - }; - }, [element, startCloseTimer, isVisible, stopCloseTimer]); + return () => { + if (card) { + card.removeEventListener("mouseenter", stopCloseTimer); + card.removeEventListener("mouseleave", startCloseTimer); + } - if (dataLoading) { - return ; + stopCloseTimer(); + }; + }, [element, startCloseTimer, isVisible, stopCloseTimer]); + + if (dataLoading) { + return ; + } + + if (!data) { + return null; + } + + return ( + + + {isVisible ? ( + + {data.type === UnfurlResourceType.Mention ? ( + + ) : data.type === UnfurlResourceType.Document ? ( + + ) : data.type === UnfurlResourceType.Issue ? ( + + ) : data.type === UnfurlResourceType.PR ? ( + + ) : ( + + )} + + + ) : null} + + + ); } +); - if (!data) { - return null; - } - - return ( - - - {isVisible ? ( - - {data.type === UnfurlResourceType.Mention ? ( - - ) : data.type === UnfurlResourceType.Document ? ( - - ) : data.type === UnfurlResourceType.Issue ? ( - - ) : data.type === UnfurlResourceType.PR ? ( - - ) : ( - - )} - - - ) : null} - - - ); -} - -function HoverPreview({ element, data, dataLoading, ...rest }: Props) { +function HoverPreview({ element, unfurlId, dataLoading, ...rest }: Props) { const isMobile = useMobile(); if (isMobile) { return null; @@ -190,7 +196,7 @@ function HoverPreview({ element, data, dataLoading, ...rest }: Props) { ); diff --git a/app/components/HoverPreview/HoverPreviewIssue.tsx b/app/components/HoverPreview/HoverPreviewIssue.tsx index 032328ffa0..bf71e62ac4 100644 --- a/app/components/HoverPreview/HoverPreviewIssue.tsx +++ b/app/components/HoverPreview/HoverPreviewIssue.tsx @@ -1,9 +1,9 @@ import * as React from "react"; import { Trans } from "react-i18next"; +import { IssueStatusIcon } from "@shared/components/IssueStatusIcon"; import { UnfurlResourceType, UnfurlResponse } from "@shared/types"; import { Avatar } from "~/components/Avatar"; import Flex from "~/components/Flex"; -import { IssueStatusIcon } from "../Icons/IssueStatusIcon"; import Text from "../Text"; import Time from "../Time"; import { diff --git a/app/components/HoverPreview/HoverPreviewPullRequest.tsx b/app/components/HoverPreview/HoverPreviewPullRequest.tsx index 6393695134..c4165e4bf9 100644 --- a/app/components/HoverPreview/HoverPreviewPullRequest.tsx +++ b/app/components/HoverPreview/HoverPreviewPullRequest.tsx @@ -1,9 +1,9 @@ import * as React from "react"; import { Trans } from "react-i18next"; +import { PullRequestIcon } from "@shared/components/PullRequestIcon"; import { UnfurlResourceType, UnfurlResponse } from "@shared/types"; import { Avatar } from "~/components/Avatar"; import Flex from "~/components/Flex"; -import { PullRequestIcon } from "../Icons/PullRequestIcon"; import Text from "../Text"; import Time from "../Time"; import { diff --git a/app/components/Modal.tsx b/app/components/Modal.tsx index 45e3105ee1..35cf5dc995 100644 --- a/app/components/Modal.tsx +++ b/app/components/Modal.tsx @@ -114,6 +114,8 @@ const Modal: React.FC = ({ ev.stopPropagation()} + // maxHeight needed for proper overflow behavior in Safari + style={{ maxHeight: "65vh" }} column reverse > @@ -259,6 +261,7 @@ const Small = styled.div` width: 75vw; min-width: 350px; max-width: 450px; + max-height: 65vh; z-index: ${depths.modal}; display: flex; justify-content: center; diff --git a/app/components/Sidebar/Sidebar.tsx b/app/components/Sidebar/Sidebar.tsx index 49f6b16bd2..b475e10de1 100644 --- a/app/components/Sidebar/Sidebar.tsx +++ b/app/components/Sidebar/Sidebar.tsx @@ -54,6 +54,8 @@ const Sidebar = React.forwardRef(function _Sidebar( const [hasPointerMoved, setPointerMoved] = React.useState(false); const isSmallerThanMinimum = width < minWidth; + const hoverTimeoutRef = React.useRef(null); + const handleDrag = React.useCallback( (event: MouseEvent) => { // suppresses text selection @@ -114,6 +116,10 @@ const Sidebar = React.forwardRef(function _Sidebar( const handlePointerActivity = React.useCallback(() => { if (ui.sidebarIsClosed) { + // clear the timeout when mouse exits + if (hoverTimeoutRef.current) { + clearTimeout(hoverTimeoutRef.current); + } setHovering(document.hasFocus()); setPointerMoved(true); } @@ -122,12 +128,20 @@ const Sidebar = React.forwardRef(function _Sidebar( const handlePointerLeave = React.useCallback( (ev) => { if (hasPointerMoved) { - setHovering( - document.hasFocus() && - ev.pageX < width && - ev.pageY < window.innerHeight && - ev.pageY > 0 - ); + // clear any previous timeout + if (hoverTimeoutRef.current) { + clearTimeout(hoverTimeoutRef.current); + } + + // add a short delay when mouse exits the sidebar before closing + hoverTimeoutRef.current = setTimeout(() => { + setHovering( + document.hasFocus() && + ev.pageX < width && + ev.pageY < window.innerHeight && + ev.pageY > 0 + ); + }, 500); } }, [width, hasPointerMoved] diff --git a/app/components/Sidebar/components/DocumentLink.tsx b/app/components/Sidebar/components/DocumentLink.tsx index 122c87ab53..d1050bd34c 100644 --- a/app/components/Sidebar/components/DocumentLink.tsx +++ b/app/components/Sidebar/components/DocumentLink.tsx @@ -148,7 +148,12 @@ function InnerDocumentLink( const color = document?.color || node.color; // Draggable - const [{ isDragging }, drag] = useDragDocument(node, depth, document); + const [{ isDragging }, drag] = useDragDocument( + node, + depth, + document, + isEditing + ); // Drop to re-parent const parentRef = React.useRef(null); @@ -270,6 +275,8 @@ function InnerDocumentLink(
{ location?: Location; strict?: boolean; to: LocationDescriptor; + component?: React.ComponentType; onBeforeClick?: () => void; } @@ -146,17 +147,22 @@ const NavLink = ({ setPreActive(undefined); }, [currentLocation]); + const handleKeyDown = React.useCallback( + (event: React.KeyboardEvent) => { + if (["Enter", " "].includes(event.key)) { + navigateTo(); + event.currentTarget?.blur(); + } + }, + [navigateTo] + ); + return ( { - if (["Enter", " "].includes(event.key)) { - navigateTo(); - event.currentTarget?.blur(); - } - }} + onKeyDown={handleKeyDown} aria-current={(isActive && ariaCurrent) || undefined} className={className} style={style} diff --git a/app/components/Sidebar/hooks/useDragAndDrop.tsx b/app/components/Sidebar/hooks/useDragAndDrop.tsx index 4d1867c7ca..58ade6c59c 100644 --- a/app/components/Sidebar/hooks/useDragAndDrop.tsx +++ b/app/components/Sidebar/hooks/useDragAndDrop.tsx @@ -166,11 +166,13 @@ export function useDropToReorderStar(getIndex?: () => string) { * @param node The NavigationNode model to drag. * @param depth The depth of the node in the sidebar. * @param document The related Document model. + * @param isEditing Whether the sidebar item is currently being edited. */ export function useDragDocument( node: NavigationNode, depth: number, - document?: Document + document?: Document, + isEditing?: boolean ) { const icon = document?.icon || node.icon || node.emoji; const color = document?.color || node.color; @@ -188,7 +190,7 @@ export function useDragDocument( icon: icon ? : undefined, collectionId: document?.collectionId || "", } as DragObject), - canDrag: () => !!document?.isActive, + canDrag: () => !!document?.isActive && !isEditing, collect: (monitor) => ({ isDragging: monitor.isDragging(), }), diff --git a/app/components/Table.tsx b/app/components/Table.tsx index d1b9c25e74..b92d3effa1 100644 --- a/app/components/Table.tsx +++ b/app/components/Table.tsx @@ -335,6 +335,7 @@ const TR = styled.div<{ $columns: string }>` grid-template-columns: ${({ $columns }) => `${$columns}`}; align-items: center; border-bottom: 1px solid ${s("divider")}; + overflow: hidden; &:last-child { border-bottom: 0; @@ -357,7 +358,8 @@ const TD = styled.span` padding: 10px 6px; font-size: 14px; text-wrap: wrap; - word-break: break-word; + overflow: hidden; + text-overflow: ellipsis; &:first-child { font-size: 15px; diff --git a/app/components/Text.ts b/app/components/Text.ts index 2598b71744..33e6f02816 100644 --- a/app/components/Text.ts +++ b/app/components/Text.ts @@ -1,73 +1,3 @@ -import styled, { css } from "styled-components"; -import { ellipsis } from "@shared/styles"; - -type Props = { - /** The type of text to render */ - type?: "secondary" | "tertiary" | "danger"; - /** The size of the text */ - size?: "xlarge" | "large" | "medium" | "small" | "xsmall"; - /** The direction of the text (defaults to ltr) */ - dir?: "ltr" | "rtl" | "auto"; - /** Whether the text should be selectable (defaults to false) */ - selectable?: boolean; - /** The font weight of the text */ - weight?: "xbold" | "bold" | "normal"; - /** Whether the text should be italic */ - italic?: boolean; - /** Whether the text should be truncated with an ellipsis */ - ellipsis?: boolean; - /** Whether the text should be monospaced */ - monospace?: boolean; -}; - -/** - * Use this component for all interface text that should not be selectable - * by the user, this is the majority of UI text explainers, notes, headings. - */ -const Text = styled.span` - margin-top: 0; - text-align: ${(props) => (props.dir ? props.dir : "inherit")}; - color: ${(props) => - props.type === "secondary" - ? props.theme.textSecondary - : props.type === "tertiary" - ? props.theme.textTertiary - : props.type === "danger" - ? props.theme.brand.red - : props.theme.text}; - font-size: ${(props) => - props.size === "xlarge" - ? "26px" - : props.size === "large" - ? "18px" - : props.size === "medium" - ? "16px" - : props.size === "small" - ? "14px" - : props.size === "xsmall" - ? "13px" - : "inherit"}; - - ${(props) => - props.weight && - css` - font-weight: ${props.weight === "xbold" - ? 600 - : props.weight === "bold" - ? 500 - : props.weight === "normal" - ? 400 - : "inherit"}; - `} - - font-style: ${(props) => (props.italic ? "italic" : "normal")}; - font-family: ${(props) => - props.monospace ? props.theme.fontFamilyMono : "inherit"}; - - white-space: normal; - user-select: ${(props) => (props.selectable ? "text" : "none")}; - - ${(props) => props.ellipsis && ellipsis()} -`; +import Text from "@shared/components/Text"; export default Text; diff --git a/app/editor/components/PasteMenu.tsx b/app/editor/components/PasteMenu.tsx index 883d06c3ca..9042f50a4f 100644 --- a/app/editor/components/PasteMenu.tsx +++ b/app/editor/components/PasteMenu.tsx @@ -1,7 +1,15 @@ -import { LinkIcon } from "outline-icons"; +import { observer } from "mobx-react"; +import { EmailIcon, LinkIcon } from "outline-icons"; import React from "react"; import { useTranslation } from "react-i18next"; +import { v4 } from "uuid"; import { EmbedDescriptor } from "@shared/editor/embeds"; +import { MenuItem } from "@shared/editor/types"; +import { MentionType } from "@shared/types"; +import Integration from "~/models/Integration"; +import useCurrentUser from "~/hooks/useCurrentUser"; +import useStores from "~/hooks/useStores"; +import { determineMentionType, isURLMentionable } from "~/utils/mention"; import SuggestionsMenu, { Props as SuggestionsMenuProps, } from "./SuggestionsMenu"; @@ -15,34 +23,65 @@ type Props = Omit< embeds: EmbedDescriptor[]; }; -const PasteMenu = ({ embeds, ...props }: Props) => { +export const PasteMenu = observer(({ pastedText, embeds, ...props }: Props) => { const { t } = useTranslation(); + const { integrations } = useStores(); + const user = useCurrentUser({ rejectOnEmpty: false }); + + let mentionType: MentionType | undefined; + const url = pastedText ? new URL(pastedText) : undefined; + + if (url) { + const integration = integrations.find((intg: Integration) => + isURLMentionable({ url, integration: intg }) + ); + + mentionType = integration + ? determineMentionType({ url, integration }) + : undefined; + } const embed = React.useMemo(() => { for (const e of embeds) { - const matches = e.matcher(props.pastedText); + const matches = e.matcher(pastedText); if (matches) { return e; } } return; - }, [embeds, props.pastedText]); + }, [embeds, pastedText]); const items = React.useMemo( - () => [ - { - name: "noop", - title: t("Keep as link"), - icon: , - }, - { - name: "embed", - title: t("Embed"), - icon: embed?.icon, - keywords: embed?.keywords, - }, - ], - [embed, t] + () => + [ + { + name: "noop", + title: t("Keep as link"), + icon: , + }, + { + name: "mention", + title: t("Mention"), + icon: , + visible: !!mentionType, + attrs: { + id: v4(), + type: mentionType, + label: pastedText, + href: pastedText, + modelId: v4(), + actorId: user?.id, + }, + appendSpace: true, + }, + { + name: "embed", + title: t("Embed"), + icon: embed?.icon, + keywords: embed?.keywords, + }, + ] satisfies MenuItem[], + [t, embed, mentionType, pastedText, user] ); return ( @@ -52,9 +91,7 @@ const PasteMenu = ({ embeds, ...props }: Props) => { filterable={false} renderMenuItem={(item, _index, options) => ( { - props.onSelect?.(item); - }} + onClick={options.onClick} selected={options.selected} title={item.title} icon={item.icon} @@ -63,6 +100,4 @@ const PasteMenu = ({ embeds, ...props }: Props) => { items={items} /> ); -}; - -export default PasteMenu; +}); diff --git a/app/editor/components/SelectionToolbar.tsx b/app/editor/components/SelectionToolbar.tsx index a263317ba5..bea7956d6b 100644 --- a/app/editor/components/SelectionToolbar.tsx +++ b/app/editor/components/SelectionToolbar.tsx @@ -174,12 +174,12 @@ export default function SelectionToolbar(props: Props) { const { isTemplate, rtl, canComment, canUpdate, ...rest } = props; const { state } = view; const { selection } = state; - const isDividerSelection = isNodeActive(state.schema.nodes.hr)(state); if ((readOnly && !canComment) || isDragging) { return null; } + const isDividerSelection = isNodeActive(state.schema.nodes.hr)(state); const colIndex = getColumnIndex(state); const rowIndex = getRowIndex(state); const isTableSelection = colIndex !== undefined && rowIndex !== undefined; diff --git a/app/editor/extensions/ClipboardTextSerializer.ts b/app/editor/extensions/ClipboardTextSerializer.ts index 5fb3a90550..44e0f983ce 100644 --- a/app/editor/extensions/ClipboardTextSerializer.ts +++ b/app/editor/extensions/ClipboardTextSerializer.ts @@ -1,5 +1,6 @@ import { Plugin, PluginKey } from "prosemirror-state"; import Extension from "@shared/editor/lib/Extension"; +import { isList } from "@shared/editor/queries/isList"; import { ProsemirrorHelper } from "@shared/utils/ProsemirrorHelper"; /** @@ -18,17 +19,25 @@ export default class ClipboardTextSerializer extends Extension { new Plugin({ key: new PluginKey("clipboardTextSerializer"), props: { - clipboardTextSerializer: (slice) => { + clipboardTextSerializer: (slice, view) => { const isMultiline = slice.content.childCount > 1; // This is a cheap way to determine if the content is "complex", // aka it has multiple marks or formatting. In which case we'll use // markdown formatting + const hasMultipleListItems = slice.content.content + .filter((node) => node.content.content.length > 1) + .some((node) => isList(node, view.state.schema)); + const hasMultipleBlockTypes = + [ + ...new Set( + slice.content.content + .filter((node) => node.content.content.length > 1) + .map((node) => node.type.name) + ), + ].length > 1; const copyAsMarkdown = - isMultiline || - slice.content.content.some( - (node) => node.content.content.length > 1 - ); + isMultiline || hasMultipleBlockTypes || hasMultipleListItems; return copyAsMarkdown ? mdSerializer.serialize(slice.content, { diff --git a/app/editor/extensions/HoverPreviews.tsx b/app/editor/extensions/HoverPreviews.tsx index fff2eeef88..3a23d92473 100644 --- a/app/editor/extensions/HoverPreviews.tsx +++ b/app/editor/extensions/HoverPreviews.tsx @@ -4,9 +4,9 @@ import { EditorView } from "prosemirror-view"; import * as React from "react"; import Extension from "@shared/editor/lib/Extension"; import parseDocumentSlug from "@shared/utils/parseDocumentSlug"; +import stores from "~/stores"; import HoverPreview from "~/components/HoverPreview"; import env from "~/env"; -import { client } from "~/utils/ApiClient"; interface HoverPreviewsOptions { /** Delay before the target is considered "hovered" and callback is triggered. */ @@ -16,11 +16,11 @@ interface HoverPreviewsOptions { export default class HoverPreviews extends Extension { state: { activeLinkElement: HTMLElement | null; - data: Record | null; + unfurlId: string | null; dataLoading: boolean; } = observable({ activeLinkElement: null, - data: null, + unfurlId: null, dataLoading: false, }); @@ -62,19 +62,25 @@ export default class HoverPreviews extends Extension { ); if (url) { + const transformedUrl = url.startsWith("/") + ? env.URL + url + : url; + this.state.dataLoading = true; - try { - const data = await client.post("/urls.unfurl", { - url: url.startsWith("/") ? env.URL + url : url, - documentId, - }); + + const unfurl = await stores.unfurls.fetchUnfurl({ + url: transformedUrl, + documentId, + }); + + if (unfurl) { this.state.activeLinkElement = element; - this.state.data = data; - } catch (err) { + this.state.unfurlId = transformedUrl; + } else { this.state.activeLinkElement = null; - } finally { - this.state.dataLoading = false; } + + this.state.dataLoading = false; } }), this.options.delay @@ -101,10 +107,11 @@ export default class HoverPreviews extends Extension { widget = () => ( { this.state.activeLinkElement = null; + this.state.unfurlId = null; })} /> ); diff --git a/app/editor/extensions/PasteHandler.tsx b/app/editor/extensions/PasteHandler.tsx index 7311749f8b..79504fc05c 100644 --- a/app/editor/extensions/PasteHandler.tsx +++ b/app/editor/extensions/PasteHandler.tsx @@ -24,7 +24,7 @@ import parseCollectionSlug from "@shared/utils/parseCollectionSlug"; import parseDocumentSlug from "@shared/utils/parseDocumentSlug"; import { isCollectionUrl, isDocumentUrl, isUrl } from "@shared/utils/urls"; import stores from "~/stores"; -import PasteMenu from "../components/PasteMenu"; +import { PasteMenu } from "../components/PasteMenu"; export default class PasteHandler extends Extension { state: { @@ -415,6 +415,21 @@ export default class PasteHandler extends Extension { }); }; + private insertMention = () => { + const { view } = this.editor; + const { state } = view; + const result = this.findPlaceholder(state, this.state.pastedText); + + // Remove just the placeholder here. + // Mention node will be created by SuggestionsMenu. + if (result) { + const tr = state.tr.deleteRange(result[0], result[1]); + view.dispatch( + tr.setSelection(TextSelection.near(tr.doc.resolve(result[0]))) + ); + } + }; + private removePlaceholder = () => { const { view } = this.editor; const { state } = view; @@ -450,6 +465,11 @@ export default class PasteHandler extends Extension { this.insertEmbed(); break; } + case "mention": { + this.hidePasteMenu(); + this.insertMention(); + break; + } default: break; } diff --git a/app/hooks/useIsMounted.ts b/app/hooks/useIsMounted.ts index c1b6f141b2..3770b66a58 100644 --- a/app/hooks/useIsMounted.ts +++ b/app/hooks/useIsMounted.ts @@ -1,19 +1,3 @@ -import * as React from "react"; +import useIsMounted from "@shared/hooks/useIsMounted"; -/** - * Hook to check if component is still mounted - * - * @returns {boolean} true if the component is mounted, false otherwise - */ -export default function useIsMounted() { - const isMounted = React.useRef(false); - - React.useEffect(() => { - isMounted.current = true; - return () => { - isMounted.current = false; - }; - }, []); - - return React.useCallback(() => isMounted.current, []); -} +export default useIsMounted; diff --git a/app/hooks/useSettingsConfig.ts b/app/hooks/useSettingsConfig.ts index 31ca673011..99ab0a4590 100644 --- a/app/hooks/useSettingsConfig.ts +++ b/app/hooks/useSettingsConfig.ts @@ -8,7 +8,6 @@ import { GlobeIcon, TeamIcon, BeakerIcon, - BuildingBlocksIcon, SettingsIcon, ExportIcon, ImportIcon, @@ -42,7 +41,6 @@ const Notifications = lazy(() => import("~/scenes/Settings/Notifications")); const Preferences = lazy(() => import("~/scenes/Settings/Preferences")); const Profile = lazy(() => import("~/scenes/Settings/Profile")); const Security = lazy(() => import("~/scenes/Settings/Security")); -const SelfHosted = lazy(() => import("~/scenes/Settings/SelfHosted")); const Shares = lazy(() => import("~/scenes/Settings/Shares")); const Templates = lazy(() => import("~/scenes/Settings/Templates")); const Zapier = lazy(() => import("~/scenes/Settings/Zapier")); @@ -187,14 +185,6 @@ const useSettingsConfig = () => { icon: ExportIcon, }, // Integrations - { - name: t("Self Hosted"), - path: integrationSettingsPath("self-hosted"), - component: SelfHosted, - enabled: can.update && !isCloudHosted, - group: t("Integrations"), - icon: BuildingBlocksIcon, - }, { name: "Zapier", path: integrationSettingsPath("zapier"), diff --git a/app/models/Document.ts b/app/models/Document.ts index 78be2fe01a..0e4a4d0a64 100644 --- a/app/models/Document.ts +++ b/app/models/Document.ts @@ -17,6 +17,7 @@ import { NavigationNodeType, NotificationEventType, } from "@shared/types"; +import { ProsemirrorHelper } from "@shared/utils/ProsemirrorHelper"; import Storage from "@shared/utils/Storage"; import { isRTL } from "@shared/utils/rtl"; import slugify from "@shared/utils/slugify"; @@ -663,6 +664,24 @@ export default class Document extends ArchivableModel implements Searchable { return markdown; }; + /** + * Returns the plain text representation of the document derived from the ProseMirror data. + * + * @returns The plain text representation of the document as a string. + */ + toPlainText = () => { + const extensionManager = new ExtensionManager(withComments(richExtensions)); + const schema = new Schema({ + nodes: extensionManager.nodes, + marks: extensionManager.marks, + }); + const text = ProsemirrorHelper.toPlainText( + Node.fromJSON(schema, this.data), + schema + ); + return text; + }; + download = (contentType: ExportContentType) => client.post( `/documents.export`, diff --git a/app/models/Integration.ts b/app/models/Integration.ts index 7338e36afa..2e8f05123d 100644 --- a/app/models/Integration.ts +++ b/app/models/Integration.ts @@ -1,8 +1,8 @@ import { observable } from "mobx"; -import type { +import { IntegrationService, - IntegrationSettings, - IntegrationType, + type IntegrationSettings, + type IntegrationType, } from "@shared/types"; import User from "~/models/User"; import Model from "~/models/base/Model"; diff --git a/app/models/Unfurl.ts b/app/models/Unfurl.ts new file mode 100644 index 0000000000..23f3b9fd0c --- /dev/null +++ b/app/models/Unfurl.ts @@ -0,0 +1,18 @@ +import { observable } from "mobx"; +import { UnfurlResourceType, UnfurlResponse } from "@shared/types"; +import Model from "./base/Model"; + +class Unfurl extends Model { + static modelName = "Unfurl"; + + @observable + type: UnfurlType; + + @observable + data: UnfurlResponse[UnfurlType]; + + @observable + fetchedAt: string; +} + +export default Unfurl; diff --git a/app/scenes/Invite.tsx b/app/scenes/Invite.tsx index 8cb13d9c1b..4c22b2824d 100644 --- a/app/scenes/Invite.tsx +++ b/app/scenes/Invite.tsx @@ -209,7 +209,9 @@ function Invite({ onSubmit }: Props) { placeholder={`name@${predictedDomain}`} value={invite.email} required={index === 0} + autoComplete="off" autoFocus + data-1p-ignore flex /> .getoutline.com diff --git a/app/scenes/Login/urls.ts b/app/scenes/Login/urls.ts index fe5612453e..81a3fd92e1 100644 --- a/app/scenes/Login/urls.ts +++ b/app/scenes/Login/urls.ts @@ -3,6 +3,15 @@ import { parseDomain } from "@shared/utils/domains"; import env from "~/env"; import Desktop from "~/utils/Desktop"; +function validateAndEncodeSubdomain(subdomain: string): string { + const encodedSubdomain = encodeURIComponent(subdomain); + const urlPattern = /^[a-z\d-]{1,63}$/; + if (!urlPattern.test(encodedSubdomain)) { + throw new Error("Invalid subdomain"); + } + return `https://${encodedSubdomain}.getoutline.com`; +} + /** * If we're on a custom domain or a subdomain then the auth must point to the * apex (env.URL) for authentication so that the state cookie can be set and read. @@ -36,7 +45,7 @@ export async function navigateToSubdomain(subdomain: string) { .toLowerCase() .trim() .replace(/^https?:\/\//, ""); - const host = `https://${normalizedSubdomain}.getoutline.com`; + const host = validateAndEncodeSubdomain(normalizedSubdomain); await Desktop.bridge?.addCustomHost(host); window.location.href = host; } diff --git a/app/scenes/Settings/SelfHosted.tsx b/app/scenes/Settings/SelfHosted.tsx deleted file mode 100644 index bc836d218d..0000000000 --- a/app/scenes/Settings/SelfHosted.tsx +++ /dev/null @@ -1,140 +0,0 @@ -import find from "lodash/find"; -import { observer } from "mobx-react"; -import { BuildingBlocksIcon } from "outline-icons"; -import * as React from "react"; -import { useForm } from "react-hook-form"; -import { useTranslation } from "react-i18next"; -import { toast } from "sonner"; -import { IntegrationService, IntegrationType } from "@shared/types"; -import Integration from "~/models/Integration"; -import Button from "~/components/Button"; -import Heading from "~/components/Heading"; -import Input from "~/components/Input"; -import Scene from "~/components/Scene"; -import useStores from "~/hooks/useStores"; -import SettingRow from "./components/SettingRow"; - -type FormData = { - drawIoUrl: string; - gristUrl: string; -}; - -function SelfHosted() { - const { integrations } = useStores(); - const { t } = useTranslation(); - - const integrationDiagrams = find(integrations.orderedData, { - type: IntegrationType.Embed, - service: IntegrationService.Diagrams, - }) as Integration | undefined; - - const integrationGrist = find(integrations.orderedData, { - type: IntegrationType.Embed, - service: IntegrationService.Grist, - }) as Integration | undefined; - - const { - register, - reset, - handleSubmit: formHandleSubmit, - formState, - } = useForm({ - mode: "all", - defaultValues: { - drawIoUrl: integrationDiagrams?.settings.url, - gristUrl: integrationGrist?.settings.url, - }, - }); - - React.useEffect(() => { - void integrations.fetchPage({ - type: IntegrationType.Embed, - }); - }, [integrations]); - - React.useEffect(() => { - reset({ - drawIoUrl: integrationDiagrams?.settings.url, - gristUrl: integrationGrist?.settings.url, - }); - }, [integrationDiagrams, integrationGrist, reset]); - - const handleSubmit = React.useCallback( - async (data: FormData) => { - try { - if (data.drawIoUrl) { - await integrations.save({ - id: integrationDiagrams?.id, - type: IntegrationType.Embed, - service: IntegrationService.Diagrams, - settings: { - url: data.drawIoUrl, - }, - }); - } else { - await integrationDiagrams?.delete(); - } - - if (data.gristUrl) { - await integrations.save({ - id: integrationGrist?.id, - type: IntegrationType.Embed, - service: IntegrationService.Grist, - settings: { - url: data.gristUrl, - }, - }); - } else { - await integrationGrist?.delete(); - } - - toast.success(t("Settings saved")); - } catch (err) { - toast.error(err.message); - } - }, - [integrations, integrationDiagrams, integrationGrist, t] - ); - - return ( - }> - {t("Self Hosted")} - -
- - - - - - - - - -
-
- ); -} - -export default observer(SelfHosted); diff --git a/app/scenes/Settings/components/FileOperationListItem.tsx b/app/scenes/Settings/components/FileOperationListItem.tsx index 8e5e932276..19f6101f60 100644 --- a/app/scenes/Settings/components/FileOperationListItem.tsx +++ b/app/scenes/Settings/components/FileOperationListItem.tsx @@ -4,6 +4,7 @@ import * as React from "react"; import { useTranslation } from "react-i18next"; import { toast } from "sonner"; import { useTheme } from "styled-components"; +import Spinner from "@shared/components/Spinner"; import { FileOperationFormat, FileOperationState, @@ -13,7 +14,6 @@ import FileOperation from "~/models/FileOperation"; import { Action } from "~/components/Actions"; import ConfirmationDialog from "~/components/ConfirmationDialog"; import ListItem from "~/components/List/Item"; -import Spinner from "~/components/Spinner"; import Time from "~/components/Time"; import useCurrentUser from "~/hooks/useCurrentUser"; import useStores from "~/hooks/useStores"; diff --git a/app/scenes/Settings/components/ImageUpload.tsx b/app/scenes/Settings/components/ImageUpload.tsx index 50c43f54ec..d5e1db53ea 100644 --- a/app/scenes/Settings/components/ImageUpload.tsx +++ b/app/scenes/Settings/components/ImageUpload.tsx @@ -1,19 +1,18 @@ import invariant from "invariant"; -import { observable } from "mobx"; import { observer } from "mobx-react"; import * as React from "react"; +import { useState, useRef } from "react"; import AvatarEditor from "react-avatar-editor"; -import Dropzone from "react-dropzone"; +import { useDropzone } from "react-dropzone"; +import { useTranslation } from "react-i18next"; import styled from "styled-components"; import { s } from "@shared/styles"; import { AttachmentPreset } from "@shared/types"; import { AttachmentValidation } from "@shared/validations"; -import RootStore from "~/stores/RootStore"; import ButtonLarge from "~/components/ButtonLarge"; import Flex from "~/components/Flex"; import LoadingIndicator from "~/components/LoadingIndicator"; -import Modal from "~/components/Modal"; -import withStores from "~/components/withStores"; +import useStores from "~/hooks/useStores"; import { compressImage } from "~/utils/compressImage"; import { uploadFile, dataUrlToBlob } from "~/utils/files"; @@ -24,143 +23,167 @@ export type Props = { borderRadius?: number; }; -@observer -class ImageUpload extends React.Component { - @observable - isUploading = false; +const ImageUpload: React.FC = ({ + onSuccess, + onError, + submitText, + borderRadius, + children, +}) => { + const { dialogs } = useStores(); + const { t } = useTranslation(); - @observable - isCropping = false; + const [isUploading, setIsUploading] = useState(false); + const [isCropping, setIsCropping] = useState(false); - @observable - zoom = 1; + const uploadImage = React.useCallback( + async (blob: Blob, file: File) => { + try { + const compressed = await compressImage(blob, { + maxHeight: 512, + maxWidth: 512, + }); + const attachment = await uploadFile(compressed, { + name: file.name, + preset: AttachmentPreset.Avatar, + }); + void onSuccess(attachment.url); + } catch (err) { + onError(err.message); + } finally { + setIsUploading(false); + setIsCropping(false); + dialogs.closeAllModals(); + } + }, + [dialogs, onSuccess, onError] + ); - @observable - file: File; + const handleUpload = React.useCallback( + (blob: Blob, file: File) => { + setIsUploading(true); + // allow the UI to update before converting the canvas to a Blob + // for large images this can cause the page rendering to hang. + setTimeout(() => uploadImage(blob, file), 0); + }, + [uploadImage] + ); - avatarEditorRef = React.createRef(); + const handleClose = React.useCallback(() => { + setIsUploading(false); + setIsCropping(false); + }, []); - static defaultProps = { - submitText: "Crop Image", - borderRadius: 150, - }; - - onDropAccepted = async (files: File[]) => { - this.isCropping = true; - this.file = files[0]; - }; - - handleCrop = () => { - this.isUploading = true; - // allow the UI to update before converting the canvas to a Blob - // for large images this can cause the page rendering to hang. - setTimeout(this.uploadImage, 0); - }; - - uploadImage = async () => { - const canvas = this.avatarEditorRef.current?.getImage(); - invariant(canvas, "canvas is not defined"); - const imageBlob = dataUrlToBlob(canvas.toDataURL()); - - try { - const compressed = await compressImage(imageBlob, { - maxHeight: 512, - maxWidth: 512, - }); - const attachment = await uploadFile(compressed, { - name: this.file.name, - preset: AttachmentPreset.Avatar, - }); - void this.props.onSuccess(attachment.url); - } catch (err) { - this.props.onError(err.message); - } finally { - this.isUploading = false; - this.isCropping = false; - } - }; - - handleClose = () => { - this.isUploading = false; - this.isCropping = false; - }; - - handleZoom = (event: React.ChangeEvent) => { - const target = event.target; - - if (target instanceof HTMLInputElement) { - this.zoom = parseFloat(target.value); - } - }; - - renderCropping() { - const { ui, submitText } = this.props; - - return ( -  } - isOpen - > - - {this.isUploading && } - - - - { + setIsCropping(true); + dialogs.openModal({ + title: "", + content: ( + -
- - {this.isUploading ? "Uploading…" : submitText} - -
-
- ); + ), + onClose: handleClose, + }); + }, + [ + t, + dialogs, + handleUpload, + handleClose, + isUploading, + borderRadius, + submitText, + ] + ); + + const { getRootProps, getInputProps } = useDropzone({ + accept: AttachmentValidation.avatarContentTypes.join(", "), + onDropAccepted, + }); + + if (isCropping) { + return null; // onDropAccepted would have opened a modal for cropping the image. } - render() { - if (this.isCropping) { - return this.renderCropping(); - } + return ( +
+ + {children} +
+ ); +}; + +type AvatarEditorDialogProps = { + file: File; + onUpload: (blob: Blob, file: File) => void; + isUploading: boolean; + borderRadius: number; + submitText: string; +}; + +const AvatarEditorDialog: React.FC = observer( + ({ file, onUpload, isUploading, borderRadius, submitText }) => { + const { ui } = useStores(); + const { t } = useTranslation(); + const [zoom, setZoom] = useState(1); + const avatarEditorRef = useRef(null); + + const handleUpload = React.useCallback(() => { + const canvas = avatarEditorRef.current?.getImage(); + invariant(canvas, "canvas is not defined"); + const blob = dataUrlToBlob(canvas.toDataURL()); + onUpload(blob, file); + }, [file, onUpload]); + + const handleZoom = React.useCallback( + (event: React.ChangeEvent) => { + const target = event.target; + + if (target instanceof HTMLInputElement) { + setZoom(parseFloat(target.value)); + } + }, + [] + ); return ( - - {({ getRootProps, getInputProps }) => ( -
- - {this.props.children} -
- )} -
+ + {isUploading && } + + + + +
+ + {isUploading ? `${t(`Uploading`)}…` : submitText} + +
); } -} +); const AvatarEditorContainer = styled(Flex)` margin-bottom: 30px; @@ -191,4 +214,4 @@ const RangeInput = styled.input` } `; -export default withStores(ImageUpload); +export default observer(ImageUpload); diff --git a/app/scenes/Settings/components/ImportListItem.tsx b/app/scenes/Settings/components/ImportListItem.tsx index 2cc8d8f2b0..ce88d822b9 100644 --- a/app/scenes/Settings/components/ImportListItem.tsx +++ b/app/scenes/Settings/components/ImportListItem.tsx @@ -5,12 +5,12 @@ import React from "react"; import { useTranslation } from "react-i18next"; import { toast } from "sonner"; import { useTheme } from "styled-components"; +import Spinner from "@shared/components/Spinner"; import { ImportState } from "@shared/types"; import Import from "~/models/Import"; import { Action } from "~/components/Actions"; import ConfirmationDialog from "~/components/ConfirmationDialog"; import ListItem from "~/components/List/Item"; -import Spinner from "~/components/Spinner"; import Time from "~/components/Time"; import useCurrentUser from "~/hooks/useCurrentUser"; import useStores from "~/hooks/useStores"; diff --git a/app/scenes/Settings/components/MembersTable.tsx b/app/scenes/Settings/components/MembersTable.tsx index 962eb8ca68..690360c430 100644 --- a/app/scenes/Settings/components/MembersTable.tsx +++ b/app/scenes/Settings/components/MembersTable.tsx @@ -2,6 +2,7 @@ import compact from "lodash/compact"; import * as React from "react"; import { useTranslation } from "react-i18next"; import styled from "styled-components"; +import Text from "@shared/components/Text"; import User from "~/models/User"; import { Avatar, AvatarSize } from "~/components/Avatar"; import Badge from "~/components/Badge"; @@ -14,6 +15,7 @@ import { import { type Column as TableColumn } from "~/components/Table"; import Time from "~/components/Time"; import useCurrentUser from "~/hooks/useCurrentUser"; +import useMobile from "~/hooks/useMobile"; import UserMenu from "~/menus/UserMenu"; import { FILTER_HEIGHT } from "./StickyFilters"; @@ -27,6 +29,7 @@ type Props = Omit, "columns" | "rowHeight"> & { export function MembersTable({ canManage, ...rest }: Props) { const { t } = useTranslation(); const currentUser = useCurrentUser(); + const isMobile = useMobile(); const columns = React.useMemo[]>( () => @@ -38,13 +41,20 @@ export function MembersTable({ canManage, ...rest }: Props) { accessor: (user) => user.name, component: (user) => ( - {user.name}{" "} - {currentUser.id === user.id && `(${t("You")})`} + {" "} + + + {user.name} {currentUser.id === user.id && `(${t("You")})`} + + {isMobile && canManage && ( + {user.email} + )} + ), width: "4fr", }, - canManage + canManage && !isMobile ? { type: "data", id: "email", @@ -54,17 +64,19 @@ export function MembersTable({ canManage, ...rest }: Props) { width: "4fr", } : undefined, - { - type: "data", - id: "lastActiveAt", - header: t("Last active"), - accessor: (user) => user.lastActiveAt, - component: (user) => - user.lastActiveAt ? ( -