diff --git a/.github/actions/install/action.yml b/.github/actions/install/action.yml index 3cd311d501..cc2d710782 100644 --- a/.github/actions/install/action.yml +++ b/.github/actions/install/action.yml @@ -1,8 +1,15 @@ name: Install description: Set up Node.js, Corepack, and install dependencies with yarn cache +# The Blacksmith condition must match the runner selection in workflows/ci.yml. runs: using: composite steps: + - name: Mount Node.js toolcache + if: ${{ github.repository_owner == 'outline' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) }} + uses: useblacksmith/stickydisk@94697d49e77d0dd78b77deb85ad3de63a28b4b8a # v1.7.1 + with: + key: ${{ github.repository }}-node-toolcache + path: /opt/hostedtoolcache/node - name: Enable Corepack shell: bash run: corepack enable @@ -10,7 +17,20 @@ runs: uses: actions/setup-node@v5 with: node-version: 26.x - cache: "yarn" + # Blacksmith jobs persist the yarn cache on a sticky disk instead. + package-manager-cache: ${{ !(github.repository_owner == 'outline' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository)) }} + - name: Mount yarn cache + if: ${{ github.repository_owner == 'outline' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) }} + uses: useblacksmith/stickydisk@94697d49e77d0dd78b77deb85ad3de63a28b4b8a # v1.7.1 + with: + key: ${{ github.repository }}-yarn-cache + path: ~/.yarn/berry/cache + - name: Mount node_modules + if: ${{ github.repository_owner == 'outline' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) }} + uses: useblacksmith/stickydisk@94697d49e77d0dd78b77deb85ad3de63a28b4b8a # v1.7.1 + with: + key: ${{ github.repository }}-node-modules + path: ./node_modules - name: Install dependencies shell: bash run: yarn install --immutable diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ba95754024..d763a546ac 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -18,8 +18,12 @@ env: jobs: changes: - runs-on: ubuntu-latest + # Blacksmith runners are only available to the outline organization, and are + # not used for pull requests from forks so that fork-controlled code cannot + # write to the shared sticky disks. Keep in sync with actions/install. + runs-on: ${{ (github.repository_owner == 'outline' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository)) && 'blacksmith-8vcpu-ubuntu-2404' || 'ubuntu-latest' }} outputs: + runner: ${{ (github.repository_owner == 'outline' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository)) && 'blacksmith-8vcpu-ubuntu-2404' || 'ubuntu-latest' }} code: ${{ steps.filter.outputs.code }} config: ${{ steps.filter.outputs.config }} server: ${{ steps.filter.outputs.server }} @@ -60,7 +64,7 @@ jobs: lint: needs: changes if: ${{ needs.changes.outputs.code == 'true' }} - runs-on: ubuntu-latest + runs-on: ${{ needs.changes.outputs.runner }} steps: - uses: actions/checkout@v5 - uses: ./.github/actions/install @@ -79,7 +83,7 @@ jobs: types: needs: changes if: ${{ needs.changes.outputs.code == 'true' }} - runs-on: ubuntu-latest + runs-on: ${{ needs.changes.outputs.runner }} steps: - uses: actions/checkout@v5 - uses: ./.github/actions/install @@ -88,7 +92,7 @@ jobs: audit: needs: changes if: ${{ needs.changes.outputs.deps == 'true' }} - runs-on: ubuntu-latest + runs-on: ${{ needs.changes.outputs.runner }} steps: - uses: actions/checkout@v5 - uses: ./.github/actions/install @@ -97,7 +101,7 @@ jobs: test: needs: changes if: ${{ needs.changes.outputs.app == 'true' || needs.changes.outputs.config == 'true' }} - runs-on: ubuntu-latest + runs-on: ${{ needs.changes.outputs.runner }} strategy: matrix: test-group: [app, shared] @@ -109,37 +113,30 @@ jobs: test-server: needs: changes if: ${{ needs.changes.outputs.server == 'true' || needs.changes.outputs.config == 'true' }} - runs-on: ubuntu-latest - services: - postgres: - image: postgres:14.2 - env: - POSTGRES_USER: postgres - POSTGRES_PASSWORD: password - POSTGRES_DB: outline_test - ports: - - 5432:5432 - options: >- - --health-cmd pg_isready - --health-interval 10s - --health-timeout 5s - --health-retries 5 - + runs-on: ${{ needs.changes.outputs.runner }} strategy: matrix: - shard: [1, 2, 3, 4] + shard: [1, 2, 3, 4, 5, 6] steps: - uses: actions/checkout@v5 + # The runner image ships with PostgreSQL preinstalled, starting it is much + # faster than pulling and initializing a service container. + - name: Start PostgreSQL + run: | + sudo systemctl start postgresql.service + until pg_isready -h localhost; do sleep 1; done + sudo -u postgres psql -c "ALTER USER postgres PASSWORD 'password';" + sudo -u postgres createdb outline_test - uses: ./.github/actions/install - run: yarn sequelize db:migrate - name: Run server tests - run: yarn test:server --maxWorkers=2 --shard=${{ matrix.shard }}/4 + run: yarn test:server --maxWorkers=4 --shard=${{ matrix.shard }}/6 bundle-size: needs: changes if: ${{ (needs.changes.outputs.app == 'true' || needs.changes.outputs.config == 'true') && github.repository == 'outline/outline' }} - runs-on: ubuntu-latest + runs-on: ${{ needs.changes.outputs.runner }} steps: - uses: actions/checkout@v5 - uses: ./.github/actions/install diff --git a/.oxlintrc.json b/.oxlintrc.json index 5cc0cbd062..203bd0254f 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -70,6 +70,12 @@ "valid-typeof": "error" }, "overrides": [ + { + "files": ["**/*.{ts,tsx}"], + "rules": { + "no-redeclare": "off" + } + }, { "files": ["**/*.{js,jsx,ts,tsx}"], "rules": { diff --git a/AGENTS.md b/AGENTS.md index 7618999693..0fe213fa37 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -168,6 +168,7 @@ yarn test:shared # All shared code tests ``` - Write unit tests for utilities and business logic in a collocated .test.ts file. +- Server tests share a module registry between files. A server test that uses `vi.mock` or `vi.resetModules` must start with `// @vitest-isolate true` so it runs isolated. - Do not create new test directories - Mock external dependencies appropriately in **mocks** folder. - Aim for high code coverage but focus on critical paths. diff --git a/LICENSE b/LICENSE index 3ba5896f6a..494e025dfb 100644 --- a/LICENSE +++ b/LICENSE @@ -3,7 +3,7 @@ Business Source License 1.1 Parameters Licensor: General Outline, Inc. -Licensed Work: Outline 1.10.0 +Licensed Work: Outline 1.10.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-09-01 +Change Date: 2030-09-09 Change License: Apache License, Version 2.0 diff --git a/app/actions/definitions/documents.tsx b/app/actions/definitions/documents.tsx index 0e4c901c3a..5c10094009 100644 --- a/app/actions/definitions/documents.tsx +++ b/app/actions/definitions/documents.tsx @@ -63,6 +63,7 @@ import DocumentPublish from "~/scenes/DocumentPublish"; import DeleteDocumentsInTrash from "~/scenes/Trash/components/DeleteDocumentsInTrash"; import ConfirmationDialog from "~/components/ConfirmationDialog"; import { DialogTitle } from "~/components/DialogTitle"; +import { DocumentArchiveDialog } from "~/components/DocumentArchiveDialog"; import DocumentCopy from "~/components/DocumentExplorer/DocumentCopy"; import MarkdownIcon from "~/components/Icons/MarkdownIcon"; import { ImportDocumentDialog } from "~/components/ImportDocumentDialog"; @@ -742,10 +743,20 @@ export const shareDocument = createAction({ }, }); +/** + * Shows a file extension in the shortcut slot of menu items only, the command + * bar would otherwise register it as a key sequence. + */ +const fileExtensionHint = + (extension: string) => + ({ isMenu }: ActionContext) => + isMenu ? [extension] : undefined; + export const downloadDocumentAsMarkdown = createAction({ name: ({ t, isMenu }) => (isMenu ? t("Markdown") : t("Download as Markdown")), analyticsName: "Download document as Markdown", section: ActiveDocumentSection, + shortcut: fileExtensionHint(".md"), keywords: "md markdown export download", icon: , iconInContextMenu: false, @@ -767,6 +778,7 @@ export const downloadDocumentAsHTML = createAction({ name: ({ t, isMenu }) => (isMenu ? t("HTML") : t("Download as HTML")), analyticsName: "Download document as HTML", section: ActiveDocumentSection, + shortcut: fileExtensionHint(".html"), keywords: "xml html export download", icon: , iconInContextMenu: false, @@ -789,6 +801,7 @@ export const downloadDocumentAsTextBundle = createAction({ isMenu ? t("TextBundle") : t("Download as TextBundle"), analyticsName: "Download document as TextBundle", section: ActiveDocumentSection, + shortcut: fileExtensionHint(".textpack"), keywords: "textbundle textpack bear ulysses export download", icon: , iconInContextMenu: false, @@ -810,6 +823,7 @@ export const downloadDocumentAsPDF = createAction({ name: ({ t, isMenu }) => (isMenu ? t("PDF") : t("Download as PDF")), analyticsName: "Download document as PDF", section: ActiveDocumentSection, + shortcut: fileExtensionHint(".pdf"), keywords: "pdf export download", icon: , iconInContextMenu: false, @@ -1173,6 +1187,7 @@ export const printDocument = createAction({ name: ({ t, isMenu }) => (isMenu ? t("Print") : t("Print document")), analyticsName: "Print document", section: ActiveDocumentSection, + shortcut: ["Meta+P"], icon: , iconInContextMenu: false, visible: ({ activeDocumentId }) => !!(activeDocumentId && window.print), @@ -1473,10 +1488,11 @@ export const archiveDocument = createAction({ }) ), content: ( - { + { const succeeded = await performBatch(documents, (document) => - document.archive() + document.archive({ reason }) ); if (succeeded) { toast.success( @@ -1486,16 +1502,7 @@ export const archiveDocument = createAction({ ); } }} - savingText={`${t("Archiving")}…`} - > - {documents.length === 1 - ? t( - "Archiving this document will remove it from the collection and search results." - ) - : t( - "Archiving these documents will remove them from their collections and search results." - )} - + /> ), }); }, diff --git a/app/actions/index.ts b/app/actions/index.ts index 46decda4fb..37cbcca3e7 100644 --- a/app/actions/index.ts +++ b/app/actions/index.ts @@ -46,24 +46,7 @@ export function createAction( ...definition, type: "action", variant: "action", - perform: definition.perform - ? (context) => { - // We must use the specific analytics name here as the action name is - // translated and potentially contains user strings. - if (definition.analyticsName) { - Analytics.track("perform_action", definition.analyticsName, { - context: context.isButton - ? "button" - : context.isCommandBar - ? "commandbar" - : context.isMCP - ? "webmcp" - : "contextmenu", - }); - } - return definition.perform(context); - } - : () => {}, + perform: definition.perform ?? (() => {}), id: definition.id ?? uuidv4(), }; } @@ -182,7 +165,7 @@ export function actionToMenuItem( icon, visible, disabled, - tooltip: resolve(action.tooltip, context), + tooltip: resolve(action.tooltip, context), selected: resolve(action.selected, context), dangerous: action.dangerous, shortcut, @@ -353,6 +336,20 @@ export async function performAction( ? () => history.push(resolve(action.to, context)) : () => window.open(action.url, action.target); + // We must use the specific analytics name here as the action name is + // translated and potentially contains user strings. + if (action.analyticsName) { + Analytics.track("perform_action", action.analyticsName, { + context: context.isButton + ? "button" + : context.isCommandBar + ? "commandbar" + : context.isMCP + ? "webmcp" + : "contextmenu", + }); + } + const result = perform(); if (result instanceof Promise) { diff --git a/app/components/ActionButton.tsx b/app/components/ActionButton.tsx index e42f45bfba..f1650bbc1d 100644 --- a/app/components/ActionButton.tsx +++ b/app/components/ActionButton.tsx @@ -22,68 +22,67 @@ export type Props = React.HTMLAttributes & { /** * Button that can be used to trigger an action definition. */ -const ActionButton = React.forwardRef( - function ActionButton_( - { action, tooltip, hideOnActionDisabled, ...rest }: Props, - ref: React.Ref - ) { - const actionContext = useActionContext({ - isButton: true, - }); - const isMounted = useIsMounted(); - const [executing, setExecuting] = React.useState(false); +function ActionButton({ + action, + tooltip, + hideOnActionDisabled, + ref, + ...rest +}: Props & { ref?: React.Ref }) { + const actionContext = useActionContext({ + isButton: true, + }); + const isMounted = useIsMounted(); + const [executing, setExecuting] = React.useState(false); - if (!actionContext || !action) { - return - ); - - if (tooltip) { - return {button}; - } - - return button; + if (!actionContext || !action) { + return + ); + + if (tooltip) { + return {button}; + } + + return button; +} export default observer(ActionButton); diff --git a/app/components/ArrowKeyNavigation.tsx b/app/components/ArrowKeyNavigation.tsx index 7834efd5aa..7e520998b3 100644 --- a/app/components/ArrowKeyNavigation.tsx +++ b/app/components/ArrowKeyNavigation.tsx @@ -6,12 +6,16 @@ type Props = Omit, "children"> & { children: () => React.ReactNode; onEscape?: (ev: React.KeyboardEvent) => void; items: unknown[]; + ref?: React.Ref; }; -function ArrowKeyNavigation( - { children, onEscape, items, ...rest }: Props, - ref: React.RefObject -) { +function ArrowKeyNavigation({ + children, + onEscape, + items, + ref, + ...rest +}: Props) { const handleKeyDown = React.useCallback( (ev: React.KeyboardEvent) => { if (onEscape) { @@ -48,4 +52,4 @@ function ArrowKeyNavigation( ); } -export default observer(React.forwardRef(ArrowKeyNavigation)); +export default observer(ArrowKeyNavigation); diff --git a/app/components/Authenticated.tsx b/app/components/Authenticated.tsx index 9a50239400..734904f6ee 100644 --- a/app/components/Authenticated.tsx +++ b/app/components/Authenticated.tsx @@ -8,7 +8,7 @@ import { changeLanguage } from "~/utils/language"; import LoadingIndicator from "./LoadingIndicator"; type Props = { - children: JSX.Element; + children: React.JSX.Element; }; const Authenticated = ({ children }: Props) => { diff --git a/app/components/Avatar/Avatar.tsx b/app/components/Avatar/Avatar.tsx index 18abcd4b9f..34edf124cd 100644 --- a/app/components/Avatar/Avatar.tsx +++ b/app/components/Avatar/Avatar.tsx @@ -49,16 +49,16 @@ export type AvatarProps = { showTooltip?: boolean; /** Whether to show a profile card on hover for users, defaults to true */ showHoverCard?: boolean; + /** Ref to the outer element */ + ref?: React.Ref; } & Omit< React.ComponentPropsWithoutRef<"div">, "onClick" | "className" | "style" >; -const Avatar = React.forwardRef(function Avatar_( - props: AvatarProps, - ref: React.Ref -) { +function Avatar(props: AvatarProps) { const { + ref, model, style, variant = AvatarVariant.Round, @@ -111,7 +111,7 @@ const Avatar = React.forwardRef(function Avatar_( ) : ( content ); -}); +} const Relative = styled.div<{ $variant: AvatarVariant; $size: AvatarSize }>` position: relative; diff --git a/app/components/Avatar/AvatarWithHoverCard.tsx b/app/components/Avatar/AvatarWithHoverCard.tsx index 64f8000bfc..8ffb3c3a70 100644 --- a/app/components/Avatar/AvatarWithHoverCard.tsx +++ b/app/components/Avatar/AvatarWithHoverCard.tsx @@ -1,5 +1,4 @@ import { observer } from "mobx-react"; -import * as React from "react"; import { UserHoverCard } from "~/components/UserHoverCard"; import User from "~/models/User"; import type { AvatarProps } from "./Avatar"; @@ -9,10 +8,12 @@ import Avatar from "./Avatar"; * An avatar that additionally displays a profile card on hover when the model * it represents is a user. */ -const AvatarWithHoverCard = React.forwardRef(function AvatarWithHoverCard_( - { showTooltip, showHoverCard = true, ...props }: AvatarProps, - ref: React.Ref -) { +function AvatarWithHoverCard({ + showTooltip, + showHoverCard = true, + ref, + ...props +}: AvatarProps) { const { model } = props; if (!showHoverCard || !(model instanceof User)) { @@ -24,6 +25,6 @@ const AvatarWithHoverCard = React.forwardRef(function AvatarWithHoverCard_( ); -}); +} export default observer(AvatarWithHoverCard); diff --git a/app/components/Breadcrumb.tsx b/app/components/Breadcrumb.tsx index 7a9296ddd3..4a4b98aeb7 100644 --- a/app/components/Breadcrumb.tsx +++ b/app/components/Breadcrumb.tsx @@ -20,12 +20,16 @@ type Props = React.PropsWithChildren<{ actions: InternalLinkAction[]; max?: number; highlightFirstItem?: boolean; + ref?: React.Ref; }>; -function Breadcrumb( - { actions, highlightFirstItem, children, max = 2 }: Props, - ref: React.RefObject | null -) { +function Breadcrumb({ + actions, + highlightFirstItem, + children, + max = 2, + ref, +}: Props) { const actionContext = useActionContext({ isMenu: true }); const visibleActions = useComputed( @@ -141,4 +145,4 @@ const Title = styled.span` min-width: 0; `; -export default observer(React.forwardRef(Breadcrumb)); +export default observer(Breadcrumb); diff --git a/app/components/Button.tsx b/app/components/Button.tsx index 75a2b0b622..6bb3d8c9ad 100644 --- a/app/components/Button.tsx +++ b/app/components/Button.tsx @@ -158,13 +158,14 @@ export type Props = ActionButtonProps & { "data-on"?: string; "data-event-category"?: string; "data-event-action"?: string; + ref?: React.Ref; }; -const Button = ( - props: Props & React.ComponentPropsWithoutRef, - ref: React.Ref -) => { +function Button( + props: Props & React.ComponentPropsWithoutRef +) { const { + ref, type, children, value, @@ -200,10 +201,10 @@ const Button = ( ); -}; +} const StyledDisclosureIcon = styled(DisclosureIcon)` opacity: 0.8; `; -export default React.forwardRef(Button); +export default Button; diff --git a/app/components/ColorButton.tsx b/app/components/ColorButton.tsx index 1c3b359a87..67b4f76d06 100644 --- a/app/components/ColorButton.tsx +++ b/app/components/ColorButton.tsx @@ -10,13 +10,17 @@ type Props = React.HTMLAttributes & { active?: boolean; /** The size of the button in pixels */ size?: number; + ref?: React.Ref; }; -export const ColorButton = React.forwardRef( - ( - { color, active = false, size = 24, ...rest }: Props, - ref: React.Ref - ) => ( +export function ColorButton({ + color, + active = false, + size = 24, + ref, + ...rest +}: Props) { + return ( - ) -); + ); +} /** Highlight for the hovered or selected swatch, falls back for the gradient. */ const ring = css`2px solid var(--color, ${s("textTertiary")})`; diff --git a/app/components/CommandBar/CommandBarItem.tsx b/app/components/CommandBar/CommandBarItem.tsx index edb163fb2c..5af103303e 100644 --- a/app/components/CommandBar/CommandBarItem.tsx +++ b/app/components/CommandBar/CommandBarItem.tsx @@ -14,6 +14,7 @@ type Props = { action: CommandBarActionImpl; active: boolean; currentRootActionId: string | null | undefined; + ref?: React.Ref; }; const SEARCH_RESULT_REGEX = /]*>(.*?)<\/b>/gi; @@ -24,10 +25,7 @@ function replaceResultMarks(tag: string) { return tag.replace(/]*>(.*?)<\/b>/gi, "$1"); } -function CommandBarItem( - { action, active, currentRootActionId }: Props, - ref: React.RefObject -) { +function CommandBarItem({ action, active, currentRootActionId, ref }: Props) { const theme = useTheme(); const ancestors = React.useMemo(() => { if (!currentRootActionId || !action.ancestors) { @@ -168,4 +166,4 @@ const ForwardIcon = styled(BackIcon)` flex-shrink: 0; `; -export default React.forwardRef(CommandBarItem); +export default CommandBarItem; diff --git a/app/components/CommandBar/useSearchIndex.ts b/app/components/CommandBar/useSearchIndex.ts index 7ca8ec263e..d81900984c 100644 --- a/app/components/CommandBar/useSearchIndex.ts +++ b/app/components/CommandBar/useSearchIndex.ts @@ -90,7 +90,7 @@ export interface UseSearchIndex { * @returns the current results and functions to feed or reset the index. */ export function useSearchIndex(query: string): UseSearchIndex { - const indexRef = useRef(); + const indexRef = useRef(undefined); if (!indexRef.current) { indexRef.current = new SearchIndex(); } diff --git a/app/components/ContentEditable.tsx b/app/components/ContentEditable.tsx index 20b3948e81..c3ad930c27 100644 --- a/app/components/ContentEditable.tsx +++ b/app/components/ContentEditable.tsx @@ -2,6 +2,7 @@ import isPrintableKeyEvent from "is-printable-key-event"; import * as React from "react"; import styled from "styled-components"; import { s } from "@shared/styles"; +import { TextHelper } from "@shared/utils/TextHelper"; import useOnScreen from "~/hooks/useOnScreen"; type Props = Omit, "ref" | "onChange"> & { @@ -13,11 +14,13 @@ type Props = Omit, "ref" | "onChange"> & { onBlur?: React.FocusEventHandler | undefined; onInput?: React.FormEventHandler | undefined; onKeyDown?: React.KeyboardEventHandler | undefined; + onCompositionEnd?: React.CompositionEventHandler | undefined; placeholder?: string; maxLength?: number; autoFocus?: boolean; children?: React.ReactNode; value: string; + ref?: React.Ref; }; export type RefHandle = { @@ -31,29 +34,29 @@ export type RefHandle = { * Defines a content editable component with the same interface as a native * HTMLInputElement (or, as close as we can get). */ -const ContentEditable = React.forwardRef(function ContentEditable_( - { - disabled, - onChange, - onInput, - onFocus, - onBlur, - onKeyDown, - value, - children, - className, - maxLength, - autoFocus, - placeholder, - readOnly, - dir, - onClick, - ...rest - }: Props, - ref: React.RefObject -) { +function ContentEditable({ + disabled, + onChange, + onInput, + onFocus, + onBlur, + onKeyDown, + onCompositionEnd, + value, + children, + className, + maxLength, + autoFocus, + placeholder, + readOnly, + dir, + onClick, + ref, + ...rest +}: Props) { const contentRef = React.useRef(null); const [innerValue, setInnerValue] = React.useState(value); + const [isEmpty, setIsEmpty] = React.useState(value.length === 0); const lastValue = React.useRef(value); React.useImperativeHandle(ref, () => ({ @@ -95,18 +98,33 @@ const ContentEditable = React.forwardRef(function ContentEditable_( return; } - const text = event.currentTarget.textContent || ""; + let text = event.currentTarget.textContent || ""; + setIsEmpty(text.length === 0); + const overLimit = + !!maxLength && TextHelper.codePointLength(text) > maxLength; if ( maxLength && event.nativeEvent instanceof KeyboardEvent && isPrintableKeyEvent(event.nativeEvent) && - text.length >= maxLength + TextHelper.codePointLength(text) >= maxLength ) { event.preventDefault(); return; } + // Paste, drop, IME and other non-keyboard input paths bypass the check + // above, so clamp whatever landed in the DOM. Editing the DOM would + // break an active IME session, so wait for composition end and do not + // publish the over-limit buffer in the meantime. + if (overLimit && maxLength) { + if (isComposing(event)) { + callback?.(event); + return; + } + text = truncateContent(event.currentTarget, maxLength); + } + if (text !== lastValue.current) { lastValue.current = text; onChange?.(text); @@ -128,8 +146,17 @@ const ContentEditable = React.forwardRef(function ContentEditable_( }, [autoFocus, disabled, isVisible, readOnly, contentRef]); React.useEffect(() => { - if (contentRef.current && value !== contentRef.current.textContent) { - if (document.activeElement === contentRef.current) { + if (!contentRef.current) { + return; + } + + const isFocused = document.activeElement === contentRef.current; + setIsEmpty( + isFocused ? !contentRef.current.textContent : value.length === 0 + ); + + if (value !== contentRef.current.textContent) { + if (isFocused) { // Don't reset content while the user is actively editing. Update // lastValue so that the next input or blur event will push the // current DOM text back to the model via onChange. @@ -146,10 +173,21 @@ const ContentEditable = React.forwardRef(function ContentEditable_( const handlePaste = React.useCallback( (event: React.ClipboardEvent) => { event.preventDefault(); - const text = event.clipboardData.getData("text/plain"); + let text = event.clipboardData.getData("text/plain"); + + if (maxLength) { + const current = event.currentTarget.textContent || ""; + const selected = window.getSelection()?.toString() || ""; + const remaining = + maxLength - + (TextHelper.codePointLength(current) - + TextHelper.codePointLength(selected)); + text = TextHelper.truncate(text, remaining); + } + window.document.execCommand("insertText", false, text); }, - [] + [maxLength] ); const contentEditable = !disabled && !readOnly; @@ -163,8 +201,10 @@ const ContentEditable = React.forwardRef(function ContentEditable_( onFocus={wrappedEvent(onFocus)} onBlur={wrappedEvent(onBlur)} onKeyDown={wrappedEvent(onKeyDown)} + onCompositionEnd={wrappedEvent(onCompositionEnd)} onPaste={handlePaste} data-placeholder={placeholder} + data-empty={isEmpty} suppressContentEditableWarning role={contentEditable ? "textbox" : undefined} {...rest} @@ -173,7 +213,46 @@ const ContentEditable = React.forwardRef(function ContentEditable_( ); -}); +} + +function isComposing(event: React.SyntheticEvent) { + const native = event.nativeEvent; + return ( + (native instanceof InputEvent || native instanceof KeyboardEvent) && + native.isComposing + ); +} + +/** + * Truncates the text content of an element to the given number of code points + * while keeping the caret at its current position where possible. + */ +function truncateContent(element: HTMLElement, maxLength: number): string { + const selection = window.getSelection(); + const range = selection?.rangeCount ? selection.getRangeAt(0) : undefined; + let offset = Number.MAX_SAFE_INTEGER; + + if (range && element.contains(range.startContainer)) { + const before = range.cloneRange(); + before.selectNodeContents(element); + before.setEnd(range.startContainer, range.startOffset); + offset = before.toString().length; + } + + const text = TextHelper.truncate(element.textContent || "", maxLength); + element.textContent = text; + + const textNode = element.firstChild; + if (textNode && selection) { + const caret = document.createRange(); + caret.setStart(textNode, Math.min(offset, text.length)); + caret.collapse(true); + selection.removeAllRanges(); + selection.addRange(caret); + } + + return text; +} function placeCaret(element: HTMLElement, atStart: boolean) { if ( @@ -198,12 +277,14 @@ const Content = styled.span` cursor: text; word-break: anywhere; - &:empty { + /* Browsers can leave line breaks behind after all text is deleted. */ + &[data-empty="true"] { display: inline-block; } - &:empty::before { + &[data-empty="true"]::before { display: inline-block; + float: inline-start; color: ${s("placeholder")}; -webkit-text-fill-color: ${s("placeholder")}; content: attr(data-placeholder); diff --git a/app/components/CopyToClipboard.ts b/app/components/CopyToClipboard.ts index 5dc70b7cd4..92068f1cf1 100644 --- a/app/components/CopyToClipboard.ts +++ b/app/components/CopyToClipboard.ts @@ -3,15 +3,21 @@ import * as React from "react"; import { mergeRefs } from "react-merge-refs"; import env from "~/env"; -type Props = { - text: string; - children?: React.ReactElement; - onClick?: React.MouseEventHandler; - onCopy?: () => void; +type ChildProps = { + onClick?: React.MouseEventHandler; + ref?: React.Ref; }; -function CopyToClipboard(props: Props, ref: React.Ref) { - const { text, onCopy, children, ...rest } = props; +type Props = { + text: string; + children?: React.ReactElement; + onClick?: React.MouseEventHandler; + onCopy?: () => void; + ref?: React.Ref; +}; + +function CopyToClipboard(props: Props) { + const { text, onCopy, children, ref, ...rest } = props; const onClick = React.useCallback( (ev: React.MouseEvent) => { @@ -45,12 +51,9 @@ function CopyToClipboard(props: Props, ref: React.Ref) { return React.cloneElement(elem, { ...rest, - ref: - "ref" in elem - ? mergeRefs([elem.ref as React.MutableRefObject, ref]) - : ref, + ref: elem.props.ref ? mergeRefs([elem.props.ref, ref]) : ref, onClick, }); } -export default React.forwardRef(CopyToClipboard); +export default CopyToClipboard; diff --git a/app/components/DelayedMount.ts b/app/components/DelayedMount.ts index 40a806a165..0fc403d6ba 100644 --- a/app/components/DelayedMount.ts +++ b/app/components/DelayedMount.ts @@ -2,7 +2,7 @@ import { useState, useEffect } from "react"; type Props = { delay?: number; - children: JSX.Element; + children: React.JSX.Element; }; export default function DelayedMount({ delay = 250, children }: Props) { diff --git a/app/components/DeprecatedReason.tsx b/app/components/DeprecatedReason.tsx new file mode 100644 index 0000000000..f90a96cfab --- /dev/null +++ b/app/components/DeprecatedReason.tsx @@ -0,0 +1,93 @@ +import { observer } from "mobx-react"; +import { useState } from "react"; +import { useTranslation } from "react-i18next"; +import { toast } from "sonner"; +import styled from "styled-components"; +import { DeprecationValidation } from "@shared/validations"; +import type Collection from "~/models/Collection"; +import type Document from "~/models/Document"; +import ContentEditable from "~/components/ContentEditable"; +import usePolicy from "~/hooks/usePolicy"; + +interface Props { + model: Document | Collection; +} + +/** + * Displays an editable reason for archiving or deleting a document or collection. + * + * @param props the model to describe. + * @returns the reason field, in read-only mode for readers. + */ +export const DeprecatedReason = observer(function DeprecatedReason({ + model, +}: Props) { + const { t } = useTranslation(); + const can = usePolicy(model); + const readOnly = !can.updateDeprecatedReason; + const [draft, setDraft] = useState(); + const value = draft ?? model.deprecatedReason ?? ""; + + const handleSave = async () => { + if (readOnly || model.isSaving || draft === undefined) { + return; + } + + const deprecatedReason = draft.trim() || null; + if (deprecatedReason === model.deprecatedReason) { + setDraft(undefined); + return; + } + + try { + await model.save({ deprecatedReason }); + setDraft(undefined); + toast.success(t("Reason saved")); + } catch { + toast.error(t("The reason could not be saved. Please try again.")); + } + }; + + if (readOnly && !model.deprecatedReason) { + return null; + } + + return ( + { + if ( + event.key === "Enter" && + !event.shiftKey && + !event.nativeEvent.isComposing + ) { + event.preventDefault(); + event.currentTarget.blur(); + } + }} + /> + ); +}); + +const Input = styled(ContentEditable)` + margin-top: 4px; + + > span { + display: block; + background: transparent; + color: inherit; + -webkit-text-fill-color: currentColor; + white-space: pre-wrap; + + &[data-empty="true"] { + display: block; + } + } +`; diff --git a/app/components/DeprecationNotice.tsx b/app/components/DeprecationNotice.tsx new file mode 100644 index 0000000000..16cec7baad --- /dev/null +++ b/app/components/DeprecationNotice.tsx @@ -0,0 +1,15 @@ +import styled from "styled-components"; +import { s } from "@shared/styles"; +import Notice from "./Notice"; + +/** A deprecation notice with a focus border around its editable reason. */ +export const DeprecationNotice = styled(Notice)` + &:has([contenteditable="true"]:focus) { + outline: 1px solid ${s("inputBorderFocused")}; + } + + > span > span { + flex: 1; + min-width: 0; + } +`; diff --git a/app/components/DesktopEventHandler.tsx b/app/components/DesktopEventHandler.tsx index 28ca23249c..0243f014b5 100644 --- a/app/components/DesktopEventHandler.tsx +++ b/app/components/DesktopEventHandler.tsx @@ -3,6 +3,7 @@ import { useTranslation } from "react-i18next"; import { useHistory } from "react-router-dom"; import { toast } from "sonner"; import KeyboardShortcuts from "~/scenes/KeyboardShortcuts"; +import { showDownloadToast } from "~/components/DownloadToast"; import { useDesktopTitlebar } from "~/hooks/useDesktopTitlebar"; import useStores from "~/hooks/useStores"; import Desktop from "~/utils/Desktop"; @@ -41,6 +42,8 @@ export default function DesktopEventHandler() { }); }); + Desktop.bridge?.onDownloadComplete?.(showDownloadToast); + Desktop.bridge?.focus(() => { window.document.body.classList.remove("backgrounded"); }); diff --git a/app/components/DocumentArchiveDialog.tsx b/app/components/DocumentArchiveDialog.tsx new file mode 100644 index 0000000000..a6d95d7b2f --- /dev/null +++ b/app/components/DocumentArchiveDialog.tsx @@ -0,0 +1,53 @@ +import { useState } from "react"; +import { useTranslation } from "react-i18next"; +import { DeprecationValidation } from "@shared/validations"; +import ConfirmationDialog from "~/components/ConfirmationDialog"; +import Flex from "~/components/Flex"; +import Input from "~/components/Input"; + +interface Props { + count: number; + onSubmit: (reason?: string) => Promise; +} + +/** + * Confirms document archival with an optional reason. + * + * @param props the document count and archive callback. + * @returns the archive confirmation form. + */ +export function DocumentArchiveDialog({ count, onSubmit }: Props) { + const { t } = useTranslation(); + const [reason, setReason] = useState(""); + + const handleSubmit = () => onSubmit(reason.trim() || undefined); + + return ( + + +
+ {count === 1 + ? t( + "Archiving this document will remove it from the collection and search results." + ) + : t( + "Archiving these documents will remove them from their collections and search results." + )} +
+ setReason(event.currentTarget.value)} + maxLength={DeprecationValidation.maxReasonLength} + margin={0} + /> +
+
+ ); +} diff --git a/app/components/DocumentBreadcrumb.tsx b/app/components/DocumentBreadcrumb.tsx index 0692870c04..1f9b05722a 100644 --- a/app/components/DocumentBreadcrumb.tsx +++ b/app/components/DocumentBreadcrumb.tsx @@ -91,12 +91,16 @@ type Props = { * ancestors are shown. If less than or equal to 0, no items are shown. */ maxDepth?: number; + ref?: React.Ref; }; -function DocumentBreadcrumb( - { document, children, onlyText, maxDepth }: Props, - ref: React.RefObject | null -) { +function DocumentBreadcrumb({ + document, + children, + onlyText, + maxDepth, + ref, +}: Props) { const { collections } = useStores(); const { t } = useTranslation(); const sidebarContext = useLocationSidebarContext(); @@ -362,4 +366,4 @@ const SmallSlash = styled(GoToIcon)` opacity: 0.5; `; -export default observer(React.forwardRef(DocumentBreadcrumb)); +export default observer(DocumentBreadcrumb); diff --git a/app/components/DocumentContext.tsx b/app/components/DocumentContext.tsx index a5bd9ca81b..a69333b7a8 100644 --- a/app/components/DocumentContext.tsx +++ b/app/components/DocumentContext.tsx @@ -8,13 +8,19 @@ import type { TextStats } from "~/hooks/useTextStats"; import { getTextStats } from "~/hooks/useTextStats"; import type Document from "~/models/Document"; import type { Editor } from "~/editor"; +import type { ConnectionStatus } from "~/utils/multiplayer/CollaborationProvider"; class DocumentContext { /** The current document */ document?: Document; /** The editor instance for this document */ - editor?: Editor; + @observable.ref + editor: Editor | undefined = undefined; + + /** The total number of changes in the currently viewed revision diff */ + @observable + totalChanges: number = 0; /** The ID of the currently focused comment, or null if no comment is focused */ @observable @@ -28,6 +34,22 @@ class DocumentContext { @observable headings: Heading[] = []; + /** The connection status of the collaboration provider */ + @observable + multiplayerStatus: ConnectionStatus | undefined = undefined; + + /** The close code of the collaboration connection, when it was closed with an error */ + @observable + multiplayerErrorCode?: number = undefined; + + /** Whether there are local edits the collaboration server has not confirmed */ + @observable + hasUnsyncedChanges = false; + + /** Whether edits are also stored in the browser, so they survive a reload */ + @observable + hasLocalPersistence = true; + constructor() { makeObservable(this); } @@ -67,11 +89,31 @@ class DocumentContext { this.isEditorInitialized = initialized; }; + @action + setTotalChanges = (totalChanges: number) => { + this.totalChanges = totalChanges; + }; + @action setFocusedCommentId = (commentId: string | null) => { this.focusedCommentId = commentId; }; + @action + setMultiplayerStatus = (status: ConnectionStatus, errorCode?: number) => { + this.multiplayerStatus = status; + this.multiplayerErrorCode = errorCode; + }; + + @action + setMultiplayerSyncState = ( + hasUnsyncedChanges: boolean, + hasLocalPersistence: boolean + ) => { + this.hasUnsyncedChanges = hasUnsyncedChanges; + this.hasLocalPersistence = hasLocalPersistence; + }; + @action updateState = () => { this.editorDoc = this.editor?.view.state.doc; diff --git a/app/components/DocumentExplorer/DocumentExplorer.tsx b/app/components/DocumentExplorer/DocumentExplorer.tsx index daa6dccde1..9fe7304bd5 100644 --- a/app/components/DocumentExplorer/DocumentExplorer.tsx +++ b/app/components/DocumentExplorer/DocumentExplorer.tsx @@ -45,13 +45,13 @@ type Props = { const VERTICAL_PADDING = 6; const HORIZONTAL_PADDING = 24; -const innerElementType = React.forwardRef< - HTMLDivElement, - React.HTMLAttributes ->(function innerElementType( - { style, ...rest }: React.HTMLAttributes, - ref -) { +function innerElementType({ + style, + ref, + ...rest +}: React.HTMLAttributes & { + ref?: React.Ref; +}) { return (
); -}); +} function DocumentExplorer({ onSubmit, diff --git a/app/components/DocumentExplorer/DocumentExplorerNode.tsx b/app/components/DocumentExplorer/DocumentExplorerNode.tsx index a47984d48c..9dfc313e8d 100644 --- a/app/components/DocumentExplorer/DocumentExplorerNode.tsx +++ b/app/components/DocumentExplorer/DocumentExplorerNode.tsx @@ -33,25 +33,25 @@ type Props = { onClick: (ev: React.MouseEvent) => void; /** Fired when the node is double-clicked to submit the current selection. */ onDoubleClick: (ev: React.MouseEvent) => void; + /** Ref to the node element. */ + ref?: React.Ref; }; -function DocumentExplorerNode( - { - selected, - active, - style, - expanded, - icon, - title, - depth, - hasChildren, - onDisclosureClick, - onPointerMove, - onClick, - onDoubleClick, - }: Props, - ref: React.RefObject -) { +function DocumentExplorerNode({ + selected, + active, + style, + expanded, + icon, + title, + depth, + hasChildren, + onDisclosureClick, + onPointerMove, + onClick, + onDoubleClick, + ref, +}: Props) { const { t } = useTranslation(); const DISCLOSURE = 24; const width = (depth + 2) * DISCLOSURE; @@ -148,4 +148,4 @@ export const Node = styled.span<{ `} `; -export default observer(React.forwardRef(DocumentExplorerNode)); +export default observer(DocumentExplorerNode); diff --git a/app/components/DocumentListItem.tsx b/app/components/DocumentListItem.tsx index eeb3f79f0e..fa473f7c05 100644 --- a/app/components/DocumentListItem.tsx +++ b/app/components/DocumentListItem.tsx @@ -1,7 +1,3 @@ -import { - useFocusEffect, - useRovingTabIndex, -} from "@getoutline/react-roving-tabindex"; import { observer } from "mobx-react"; import * as React from "react"; import { useTranslation } from "react-i18next"; @@ -35,6 +31,7 @@ import { ActionContextProvider } from "~/hooks/useActionContext"; import { useDocumentMenuAction } from "~/hooks/useDocumentMenuAction"; import { ContextMenu } from "./Menu/ContextMenu"; import { useDocumentActiveModels } from "~/hooks/useDocumentActiveModels"; +import { useRovingTabIndex } from "~/hooks/useRovingTabIndex"; type Props = { document: Document; @@ -44,6 +41,7 @@ type Props = { showCollection?: boolean; showPublished?: boolean; showDraft?: boolean; + ref?: React.RefObject; }; const SEARCH_RESULT_REGEX = /]*>(.*?)<\/b>/gi; @@ -53,10 +51,7 @@ function replaceResultMarks(tag: string) { return tag.replace(new RegExp(SEARCH_RESULT_REGEX.source), "$1"); } -function DocumentListItem( - props: Props, - ref: React.RefObject -) { +function DocumentListItem(props: Props) { const { t } = useTranslation(); const user = useCurrentUser(); const theme = useTheme(); @@ -66,14 +61,13 @@ function DocumentListItem( const selection = useModelSelection(); const iconRef = React.useRef(null); - let itemRef: React.Ref = + let itemRef: React.RefObject = React.useRef(null); - if (ref) { - itemRef = ref; + if (props.ref) { + itemRef = props.ref; } const { focused, ...rovingTabIndex } = useRovingTabIndex(itemRef, false); - useFocusEffect(focused, itemRef); const { document, @@ -83,6 +77,7 @@ function DocumentListItem( showDraft = true, highlight, context, + ref: _ref, ...rest } = props; const queryIsInTitle = @@ -445,4 +440,4 @@ const ResultContext = styled(Highlight)` overflow: hidden; `; -export default observer(React.forwardRef(DocumentListItem)); +export default observer(DocumentListItem); diff --git a/app/components/DownloadToast.tsx b/app/components/DownloadToast.tsx new file mode 100644 index 0000000000..d13cf9b5d3 --- /dev/null +++ b/app/components/DownloadToast.tsx @@ -0,0 +1,71 @@ +import { t } from "i18next"; +import { useCallback } from "react"; +import { useTranslation } from "react-i18next"; +import { toast } from "sonner"; +import Button from "~/components/Button"; +import Flex from "~/components/Flex"; +import Desktop from "~/utils/Desktop"; + +type DownloadedFile = { + /** The user facing name of the downloaded file. */ + fileName: string; + /** The absolute path the file was saved to. */ + filePath: string; +}; + +/** + * Displays a toast notifying that a file finished downloading, with the file + * name and actions to open the file or reveal it in the file manager. Desktop + * app only. + * + * @param file the name and path of the downloaded file. + */ +export function showDownloadToast(file: DownloadedFile) { + const toastId = `download-${file.filePath}`; + + toast.message(t("Download complete"), { + id: toastId, + description: , + }); +} + +function DownloadToastDescription({ + file, + toastId, +}: { + file: DownloadedFile; + toastId: string; +}) { + const { t } = useTranslation(); + + const handleOpen = useCallback(() => { + toast.dismiss(toastId); + void Desktop.bridge?.openDownload?.(file.filePath); + }, [file.filePath, toastId]); + + const handleShowInFolder = useCallback(() => { + toast.dismiss(toastId); + void Desktop.bridge?.showDownloadInFolder?.(file.filePath); + }, [file.filePath, toastId]); + + // The name given to the file manager differs by operating system. + const showInFolderLabel = Desktop.isMacApp() + ? t("Show in Finder") + : Desktop.isWindowsApp() + ? t("Show in Explorer") + : t("Show in folder"); + + return ( + + {file.fileName} + + + + + + ); +} diff --git a/app/components/EditableTitle.tsx b/app/components/EditableTitle.tsx index 2a9bcfdce6..9709f3eead 100644 --- a/app/components/EditableTitle.tsx +++ b/app/components/EditableTitle.tsx @@ -20,6 +20,7 @@ type Props = Omit, "onSubmit"> & { maxLength?: number; /** The default editing state. */ isEditing?: boolean; + ref?: React.Ref; }; export type RefHandle = { @@ -27,10 +28,15 @@ export type RefHandle = { setIsEditing: (isEditing: boolean) => void; }; -function EditableTitle( - { title, onSubmit, canUpdate, onEditing, onCancel, ...rest }: Props, - ref: React.RefObject -) { +function EditableTitle({ + title, + onSubmit, + canUpdate, + onEditing, + onCancel, + ref, + ...rest +}: Props) { const [isEditing, setIsEditing] = React.useState(rest.isEditing || false); const [originalValue, setOriginalValue] = React.useState(title); const [value, setValue] = React.useState(title); @@ -190,4 +196,4 @@ const Input = styled.input` } `; -export default React.forwardRef(EditableTitle); +export default EditableTitle; diff --git a/app/components/Editor.tsx b/app/components/Editor.tsx index fd127de3c3..e0b0dcd73c 100644 --- a/app/components/Editor.tsx +++ b/app/components/Editor.tsx @@ -32,7 +32,7 @@ export type Props = Optional< editorStyle?: React.CSSProperties; }; -function Editor(props: Props, ref: React.RefObject | null) { +function Editor({ ref, ...props }: Props & { ref?: React.Ref }) { const { id, onChange, @@ -45,9 +45,9 @@ function Editor(props: Props, ref: React.RefObject | null) { const { shareId } = useShare(); const { t } = useTranslation(); const embeds = useEmbeds(!shareId); - const localRef = React.useRef(); + const localRef = React.useRef(undefined); const preferences = useCurrentUser({ rejectOnEmpty: false })?.preferences; - const previousCommentIds = React.useRef(); + const previousCommentIds = React.useRef(undefined); // Upload progress tracking for delayed toast const progressMap = React.useMemo(() => new Map(), []); @@ -265,4 +265,4 @@ function Editor(props: Props, ref: React.RefObject | null) { ); } -export default observer(React.forwardRef(Editor)); +export default observer(Editor); diff --git a/app/components/Fade.tsx b/app/components/Fade.tsx index a3de3c4eb4..8e0aeccfd2 100644 --- a/app/components/Fade.tsx +++ b/app/components/Fade.tsx @@ -12,7 +12,7 @@ const Fade = styled.span<{ timing?: number | string }>` `; type Props = { - children?: JSX.Element | null; + children?: React.JSX.Element | null; /** If true, children will be animated. */ animate: boolean; }; diff --git a/app/components/Header.tsx b/app/components/Header.tsx index 1d7ad66ce8..bbf3e640ef 100644 --- a/app/components/Header.tsx +++ b/app/components/Header.tsx @@ -35,12 +35,10 @@ type Props = { | React.ReactNode; hasSidebar?: boolean; className?: string; + ref?: React.Ref; }; -function Header( - { left, title, actions, hasSidebar, className }: Props, - ref: React.RefObject | null -) { +function Header({ left, title, actions, hasSidebar, className, ref }: Props) { const { ui } = useStores(); const { t } = useTranslation(); const { pane, isSplitView } = useSplitView(); @@ -251,4 +249,4 @@ const CloseSplitPaneButton = styled(Button)` pointer-events: auto; `; -export default observer(React.forwardRef(Header)); +export default observer(Header); diff --git a/app/components/HoverPreview/HoverPreview.tsx b/app/components/HoverPreview/HoverPreview.tsx index 00965d055c..e0c8419338 100644 --- a/app/components/HoverPreview/HoverPreview.tsx +++ b/app/components/HoverPreview/HoverPreview.tsx @@ -44,7 +44,9 @@ const HoverPreviewDesktop = observer( ({ element, unfurlId, dataLoading, onClose }: Props) => { const { unfurls } = useStores(); const [isVisible, setVisible] = React.useState(false); - const timerClose = React.useRef>(); + const timerClose = React.useRef | undefined>( + undefined + ); const cardRef = React.useRef(null); const { cardLeft, cardTop, pointerLeft, pointerTop, pointerDir } = useHoverPosition({ @@ -248,7 +250,7 @@ function useHoverPosition({ element, isVisible, }: { - cardRef: React.RefObject; + cardRef: React.RefObject; element: HTMLElement | null; isVisible: boolean; }) { diff --git a/app/components/HoverPreview/HoverPreviewDocument.tsx b/app/components/HoverPreview/HoverPreviewDocument.tsx index 4f5d1de441..2979d3187d 100644 --- a/app/components/HoverPreview/HoverPreviewDocument.tsx +++ b/app/components/HoverPreview/HoverPreviewDocument.tsx @@ -13,37 +13,56 @@ import { Description, } from "./Components"; -type Props = Omit; +type Props = Omit & { + ref?: React.Ref; +}; + +function HoverPreviewDocument({ + url, + id, + title, + summary, + lastActivityByViewer, + ref, +}: Props) { + const parsedUrl = new URL(url, window.location.href); + const content = ( + + + + + {title} + {lastActivityByViewer && {lastActivityByViewer}} + + }> + + + + + + + + ); + + if (parsedUrl.origin !== window.location.origin) { + return ( + + {content} + + ); + } -const HoverPreviewDocument = React.forwardRef(function HoverPreviewDocument_( - { url, id, title, summary, lastActivityByViewer }: Props, - ref: React.Ref -) { return ( - - - - - - {title} - {lastActivityByViewer && {lastActivityByViewer}} - - }> - - - - - - - + + {content} ); -}); +} export default HoverPreviewDocument; diff --git a/app/components/HoverPreview/HoverPreviewGroup.tsx b/app/components/HoverPreview/HoverPreviewGroup.tsx index 55177186e7..e056d34f7a 100644 --- a/app/components/HoverPreview/HoverPreviewGroup.tsx +++ b/app/components/HoverPreview/HoverPreviewGroup.tsx @@ -15,12 +15,17 @@ import { } from "./Components"; import ErrorBoundary from "../ErrorBoundary"; -type Props = Omit; +type Props = Omit & { + ref?: React.Ref; +}; -const HoverPreviewGroup = React.forwardRef(function HoverPreviewGroup_( - { name, description, memberCount, users }: Props, - ref: React.Ref -) { +function HoverPreviewGroup({ + name, + description, + memberCount, + users, + ref, +}: Props) { const { t } = useTranslation(); return ( @@ -65,6 +70,6 @@ const HoverPreviewGroup = React.forwardRef(function HoverPreviewGroup_( ); -}); +} export default HoverPreviewGroup; diff --git a/app/components/HoverPreview/HoverPreviewIssue.tsx b/app/components/HoverPreview/HoverPreviewIssue.tsx index bc7baef6d0..2fd4ba3c9b 100644 --- a/app/components/HoverPreview/HoverPreviewIssue.tsx +++ b/app/components/HoverPreview/HoverPreviewIssue.tsx @@ -21,12 +21,21 @@ import { Info, } from "./Components"; -type Props = Omit; +type Props = Omit & { + ref?: React.Ref; +}; -const HoverPreviewIssue = React.forwardRef(function HoverPreviewIssue_( - { url, id, title, description, author, labels, state, createdAt }: Props, - ref: React.Ref -) { +function HoverPreviewIssue({ + url, + id, + title, + description, + author, + labels, + state, + createdAt, + ref, +}: Props) { const authorName = author.name; const urlObj = new URL(url); const service = @@ -88,7 +97,7 @@ const HoverPreviewIssue = React.forwardRef(function HoverPreviewIssue_( ); -}); +} const StyledIssueStatusIcon = styled(IssueStatusIcon)` margin-top: 2px; diff --git a/app/components/HoverPreview/HoverPreviewLink.tsx b/app/components/HoverPreview/HoverPreviewLink.tsx index b5ef796948..868c4605a7 100644 --- a/app/components/HoverPreview/HoverPreviewLink.tsx +++ b/app/components/HoverPreview/HoverPreviewLink.tsx @@ -18,12 +18,16 @@ type Props = { thumbnailUrl: string; /** Some description about the link provider */ description: string; + ref?: React.Ref; }; -const HoverPreviewLink = React.forwardRef(function HoverPreviewLink_( - { url, thumbnailUrl, title, description }: Props, - ref: React.Ref -) { +function HoverPreviewLink({ + url, + thumbnailUrl, + title, + description, + ref, +}: Props) { return ( @@ -39,6 +43,6 @@ const HoverPreviewLink = React.forwardRef(function HoverPreviewLink_( ); -}); +} export default HoverPreviewLink; diff --git a/app/components/HoverPreview/HoverPreviewMention.tsx b/app/components/HoverPreview/HoverPreviewMention.tsx index e05ccbcbcc..2db4b88079 100644 --- a/app/components/HoverPreview/HoverPreviewMention.tsx +++ b/app/components/HoverPreview/HoverPreviewMention.tsx @@ -4,12 +4,17 @@ import { Avatar, AvatarSize } from "~/components/Avatar"; import Flex from "~/components/Flex"; import { Preview, Title, Info, Card, CardContent } from "./Components"; -type Props = Omit; +type Props = Omit & { + ref?: React.Ref; +}; -const HoverPreviewMention = React.forwardRef(function HoverPreviewMention_( - { avatarUrl, name, lastActive, color }: Props, - ref: React.Ref -) { +function HoverPreviewMention({ + avatarUrl, + name, + lastActive, + color, + ref, +}: Props) { return ( @@ -32,6 +37,6 @@ const HoverPreviewMention = React.forwardRef(function HoverPreviewMention_( ); -}); +} export default HoverPreviewMention; diff --git a/app/components/HoverPreview/HoverPreviewProject.tsx b/app/components/HoverPreview/HoverPreviewProject.tsx index 9cfb43a83a..f45b6a6b97 100644 --- a/app/components/HoverPreview/HoverPreviewProject.tsx +++ b/app/components/HoverPreview/HoverPreviewProject.tsx @@ -30,12 +30,21 @@ type Props = Pick< | "state" | "targetDate" | "description" ->; +> & { + ref?: React.Ref; +}; -const HoverPreviewProject = React.forwardRef(function HoverPreviewProject_( - { url, name, color, lead, labels, state, description, targetDate }: Props, - ref: React.Ref -) { +function HoverPreviewProject({ + url, + name, + color, + lead, + labels, + state, + description, + targetDate, + ref, +}: Props) { const { t } = useTranslation(); return ( @@ -116,7 +125,7 @@ const HoverPreviewProject = React.forwardRef(function HoverPreviewProject_( ); -}); +} const StyledSquircle = styled(Squircle)` flex-shrink: 0; diff --git a/app/components/HoverPreview/HoverPreviewPullRequest.tsx b/app/components/HoverPreview/HoverPreviewPullRequest.tsx index e9a4f41eca..d0b11c5343 100644 --- a/app/components/HoverPreview/HoverPreviewPullRequest.tsx +++ b/app/components/HoverPreview/HoverPreviewPullRequest.tsx @@ -19,57 +19,63 @@ import { Info, } from "./Components"; -type Props = Omit; +type Props = Omit & { + ref?: React.Ref; +}; -const HoverPreviewPullRequest = React.forwardRef( - function HoverPreviewPullRequest_( - { url, title, id, description, author, state, createdAt }: Props, - ref: React.Ref - ) { - const authorName = author.name; +function HoverPreviewPullRequest({ + url, + title, + id, + description, + author, + state, + createdAt, + ref, +}: Props) { + const authorName = author.name; - return ( - - - - - - - <StyledPullRequestIcon size={18} state={state} /> - <span> - <Backticks content={title} /> -  <Text type="tertiary">{id}</Text> - </span> - - - - - - {{ authorName }} opened{" "} - - - - {description && ( - - }> - - - - )} + return ( + + + + + + + <StyledPullRequestIcon size={18} state={state} /> + <span> + <Backticks content={title} /> +  <Text type="tertiary">{id}</Text> + </span> + + + + + + {{ authorName }} opened{" "} + + - - - - - ); - } -); + {description && ( + + }> + + + + )} + + + + + + ); +} const StyledPullRequestIcon = styled(PullRequestIcon)` margin-top: 2px; diff --git a/app/components/IconPicker/components/Grid.tsx b/app/components/IconPicker/components/Grid.tsx index 9be2b95de9..b82ac48bfc 100644 --- a/app/components/IconPicker/components/Grid.tsx +++ b/app/components/IconPicker/components/Grid.tsx @@ -10,12 +10,18 @@ type Props = { columns: number; itemWidth: number; onOverflowChange?: (hasMoreBelow: boolean) => void; + ref?: React.Ref; }; -const Grid = ( - { width, height, data, columns, itemWidth, onOverflowChange }: Props, - ref: React.Ref -) => { +function Grid({ + width, + height, + data, + columns, + itemWidth, + onOverflowChange, + ref, +}: Props) { const offsetRef = React.useRef(0); const maxOffset = Math.max(0, data.length * itemWidth - height); @@ -47,7 +53,7 @@ const Grid = ( {Row} ); -}; +} type RowProps = { data: React.ReactNode[][]; @@ -82,4 +88,4 @@ const RowContainer = styled.div<{ columns: number }>` align-content: center; `; -export default React.forwardRef(Grid); +export default Grid; diff --git a/app/components/IconPicker/components/GridTemplate.tsx b/app/components/IconPicker/components/GridTemplate.tsx index 27f1df6ae0..2d0238a9b2 100644 --- a/app/components/IconPicker/components/GridTemplate.tsx +++ b/app/components/IconPicker/components/GridTemplate.tsx @@ -58,20 +58,20 @@ type Props = { onIconActive?: (icon: IconNode) => void; /** Callback when whether the grid has content below the fold changes */ onOverflowChange?: (hasMoreBelow: boolean) => void; + /** Ref to the scrolling container */ + ref?: React.Ref; }; -const GridTemplate = ( - { - width, - height, - data, - empty, - onIconSelect, - onIconActive, - onOverflowChange, - }: Props, - ref: React.Ref -) => { +function GridTemplate({ + width, + height, + data, + empty, + onIconSelect, + onIconActive, + onOverflowChange, + ref, +}: Props) { const isMobile = useMobile(); const buttonSize = isMobile ? BUTTON_SIZE_MOBILE : BUTTON_SIZE_DESKTOP; const iconSize = isMobile ? ICON_SIZE_MOBILE : ICON_SIZE_DESKTOP; @@ -159,7 +159,7 @@ const GridTemplate = ( onOverflowChange={onOverflowChange} /> ); -}; +} const CategoryName = styled(Text)` grid-column: 1 / -1; @@ -173,4 +173,4 @@ const Icon = styled.svg` transition-delay: var(--delay); `; -export default React.forwardRef(GridTemplate); +export default GridTemplate; diff --git a/app/components/Icons/GmailIcon.tsx b/app/components/Icons/GmailIcon.tsx new file mode 100644 index 0000000000..f362c20b95 --- /dev/null +++ b/app/components/Icons/GmailIcon.tsx @@ -0,0 +1,30 @@ +interface GmailIconProps { + size?: number; + color?: string; +} + +/** + * Renders the Gmail logo as a decorative icon. + * + * @param props the icon size and color. + * @returns the Gmail logo. + * @see https://github.com/simple-icons/simple-icons/blob/12.4.0/icons/gmail.svg + */ +export function GmailIcon({ + size = 24, + color = "currentColor", +}: GmailIconProps) { + return ( + + ); +} diff --git a/app/components/Icons/OutlookIcon.tsx b/app/components/Icons/OutlookIcon.tsx new file mode 100644 index 0000000000..bf2c83ae9a --- /dev/null +++ b/app/components/Icons/OutlookIcon.tsx @@ -0,0 +1,30 @@ +interface OutlookIconProps { + size?: number; + color?: string; +} + +/** + * Renders the Outlook logo as a decorative icon. + * + * @param props the icon size and color. + * @returns the Outlook logo. + * @see https://github.com/simple-icons/simple-icons/blob/12.4.0/icons/microsoftoutlook.svg + */ +export function OutlookIcon({ + size = 24, + color = "currentColor", +}: OutlookIconProps) { + return ( + + ); +} diff --git a/app/components/Input.tsx b/app/components/Input.tsx index 99c5cf8c42..1a75fa77ba 100644 --- a/app/components/Input.tsx +++ b/app/components/Input.tsx @@ -192,10 +192,11 @@ export interface Props extends Omit< } function Input( - props: Props, - ref: React.RefObject + props: Props & { ref?: React.Ref } ) { - const internalRef = React.useRef(); + const internalRef = React.useRef< + HTMLInputElement | HTMLTextAreaElement | undefined + >(undefined); const [focused, setFocused] = React.useState(false); const [charCount, setCharCount] = React.useState(() => { if (typeof props.value === "string") { @@ -282,6 +283,7 @@ function Input( onChange, onRequestSubmit, children, + ref, ...rest } = props; @@ -322,7 +324,7 @@ function Input( , + ref as React.Ref, ])} onBlur={handleBlur} onFocus={handleFocus} @@ -340,10 +342,7 @@ function Input( /> ) : ( , - ])} + ref={mergeRefs([internalRef, ref as React.Ref])} onBlur={handleBlur} onFocus={handleFocus} hasIcon={!!icon} @@ -384,4 +383,4 @@ export const TextWrapper = styled.span` margin-top: -16px; `; -export default React.forwardRef(Input); +export default Input; diff --git a/app/components/InputSearch.tsx b/app/components/InputSearch.tsx index 5cba7ab023..0b185c5958 100644 --- a/app/components/InputSearch.tsx +++ b/app/components/InputSearch.tsx @@ -12,12 +12,10 @@ type Props = InputProps & { onFocus?: (event: React.FocusEvent) => unknown; onChange?: (event: React.ChangeEvent) => unknown; onKeyDown?: (event: React.KeyboardEvent) => unknown; + ref?: React.Ref; }; -function InputSearch( - props: Props, - ref: React.RefObject -) { +function InputSearch(props: Props) { const { t } = useTranslation(); const theme = useTheme(); const [isFocused, setIsFocused] = React.useState(false); @@ -26,6 +24,7 @@ function InputSearch( onKeyDown, onBlur, onFocus, + ref, ...rest } = props; @@ -65,4 +64,4 @@ function InputSearch( ); } -export default React.forwardRef(InputSearch); +export default InputSearch; diff --git a/app/components/InputSelect.tsx b/app/components/InputSelect.tsx index 7111993fcb..aace4093af 100644 --- a/app/components/InputSelect.tsx +++ b/app/components/InputSelect.tsx @@ -77,139 +77,138 @@ type Props = Omit, "onChange"> & { help?: string; /** Render function to override the selected value shown in the trigger. Receives the currently selected option, or undefined when none is selected. */ displayValue?: (selectedOption: Item | undefined) => React.ReactNode; + ref?: React.Ref; } & TriggerButtonProps; -export const InputSelect = React.forwardRef( - (props, ref) => { - const { - options, - value, - onChange, - label, - labelHidden, - short, - help, - displayValue, - ...triggerProps - } = props; +export function InputSelect(props: Props) { + const { + ref, + options, + value, + onChange, + label, + labelHidden, + short, + help, + displayValue, + ...triggerProps + } = props; - const [localValue, setLocalValue] = React.useState(value); - const [open, setOpen] = React.useState(false); + const [localValue, setLocalValue] = React.useState(value); + const [open, setOpen] = React.useState(false); - const contentRef = - React.useRef>(null); + const contentRef = + React.useRef>(null); - const isMobile = useMobile(); + const isMobile = useMobile(); - const placeholder = `Select a ${label.toLowerCase()}`; - const optionsHaveIcon = options.some( - (opt) => opt.type === "item" && !!opt.icon - ); + const placeholder = `Select a ${label.toLowerCase()}`; + const optionsHaveIcon = options.some( + (opt) => opt.type === "item" && !!opt.icon + ); - const selectedOption = React.useMemo( - () => - localValue - ? (options.find( - (opt) => opt.type === "item" && opt.value === localValue - ) as Item | undefined) - : undefined, - [localValue, options] - ); + const selectedOption = React.useMemo( + () => + localValue + ? (options.find( + (opt) => opt.type === "item" && opt.value === localValue + ) as Item | undefined) + : undefined, + [localValue, options] + ); - const resolvedDisplayValue = displayValue - ? displayValue(selectedOption) - : undefined; + const resolvedDisplayValue = displayValue + ? displayValue(selectedOption) + : undefined; - const renderOption = React.useCallback( - (option: Option, idx: number) => { - if (option.type === "separator") { - return ; - } - - if (option.type === "heading") { - return ( - - {option.label} - - ); - } + const renderOption = React.useCallback( + (option: Option, idx: number) => { + if (option.type === "separator") { + return ; + } + if (option.type === "heading") { return ( - - + + {option.label} + ); - }, - [optionsHaveIcon] - ); - - const onValueChange = React.useCallback( - async (val: string) => { - setLocalValue(val); - onChange(val); - }, - [onChange, setLocalValue] - ); - - const enablePointerEvents = React.useCallback(() => { - if (contentRef.current) { - contentRef.current.style.pointerEvents = "auto"; } - }, []); - const disablePointerEvents = React.useCallback(() => { - if (contentRef.current) { - contentRef.current.style.pointerEvents = "none"; - } - }, []); - - React.useEffect(() => { - setLocalValue(value); - }, [value]); - - if (isMobile) { return ( - + + ); - } + }, + [optionsHaveIcon] + ); + const onValueChange = React.useCallback( + async (val: string) => { + setLocalValue(val); + onChange(val); + }, + [onChange, setLocalValue] + ); + + const enablePointerEvents = React.useCallback(() => { + if (contentRef.current) { + contentRef.current.style.pointerEvents = "auto"; + } + }, []); + + const disablePointerEvents = React.useCallback(() => { + if (contentRef.current) { + contentRef.current.style.pointerEvents = "none"; + } + }, []); + + React.useEffect(() => { + setLocalValue(value); + }, [value]); + + if (isMobile) { return ( - - + ); } -); -InputSelect.displayName = "InputSelect"; + + return ( + + + ); +} type MobileSelectProps = Props & { placeholder: string; @@ -217,125 +216,124 @@ type MobileSelectProps = Props & { resolvedDisplayValue?: React.ReactNode; }; -const MobileSelect = React.forwardRef( - (props, ref) => { - const { - options, - value, - onChange, - label, - labelHidden, - disabled, - short, - placeholder, - optionsHaveIcon, - displayValue: _displayValue, - resolvedDisplayValue, - ...triggerProps - } = props; +function MobileSelect(props: MobileSelectProps) { + const { + ref, + options, + value, + onChange, + label, + labelHidden, + disabled, + short, + placeholder, + optionsHaveIcon, + displayValue: _displayValue, + resolvedDisplayValue, + ...triggerProps + } = props; - const [open, setOpen] = React.useState(false); - const contentRef = - React.useRef>(null); + const [open, setOpen] = React.useState(false); + const contentRef = + React.useRef>(null); - const selectedOption = React.useMemo( - () => - value - ? options.find((opt) => opt.type === "item" && opt.value === value) - : undefined, - [value, options] - ); + const selectedOption = React.useMemo( + () => + value + ? options.find((opt) => opt.type === "item" && opt.value === value) + : undefined, + [value, options] + ); - const handleSelect = React.useCallback( - async (val: string) => { - setOpen(false); - onChange(val); - }, - [onChange] - ); + const handleSelect = React.useCallback( + async (val: string) => { + setOpen(false); + onChange(val); + }, + [onChange] + ); - const renderOption = React.useCallback( - (option: Option, idx: number) => { - if (option.type === "separator") { - return ; - } - - if (option.type === "heading") { - return ( - - {option.label} - - ); - } - - const isSelected = option === selectedOption; + const renderOption = React.useCallback( + (option: Option, idx: number) => { + if (option.type === "separator") { + return ; + } + if (option.type === "heading") { return ( - handleSelect(option.value)} - data-state={isSelected ? "checked" : "unchecked"} - > - + + {option.label} + ); - }, - [handleSelect, selectedOption, optionsHaveIcon] - ); - - const enablePointerEvents = React.useCallback(() => { - if (contentRef.current) { - contentRef.current.style.pointerEvents = "auto"; } - }, []); - const disablePointerEvents = React.useCallback(() => { - if (contentRef.current) { - contentRef.current.style.pointerEvents = "none"; - } - }, []); + const isSelected = option === selectedOption; - return ( - - - ); - } -); + {resolvedDisplayValue !== undefined ? ( + resolvedDisplayValue + ) : selectedOption ? ( +