diff --git a/.circleci/config.yml b/.circleci/config.yml index e847cf3b11..ca6ffe4b47 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -1,51 +1,93 @@ version: 2.1 +defaults: &defaults + working_directory: ~/outline + docker: + - image: cimg/node:14.19 + - image: cimg/redis:5.0 + - image: cimg/postgres:14.2 + environment: + POSTGRES_USER: postgres + POSTGRES_PASSWORD: password + POSTGRES_DB: circle_test + resource_class: large + environment: + NODE_ENV: test + SECRET_KEY: F0E5AD933D7F6FD8F4DBB3E038C501C052DC0593C686D21ACB30AE205D2F634B + DATABASE_URL_TEST: postgres://postgres:password@localhost:5432/circle_test + DATABASE_URL: postgres://postgres:password@localhost:5432/circle_test + URL: http://localhost:3000 + SMTP_FROM_EMAIL: hello@example.com + AWS_S3_UPLOAD_BUCKET_URL: https://s3.amazonaws.com + AWS_S3_UPLOAD_BUCKET_NAME: outline-circle + executors: docker-publisher: environment: IMAGE_NAME: outlinewiki/outline + BASE_IMAGE_NAME: outlinewiki/outline-base docker: - image: circleci/buildpack-deps:stretch jobs: build: - working_directory: ~/outline - docker: - - image: circleci/node:14 - - image: circleci/redis:latest - - image: circleci/postgres:9.6.5-alpine-ram - environment: - NODE_ENV: test - SECRET_KEY: F0E5AD933D7F6FD8F4DBB3E038C501C052DC0593C686D21ACB30AE205D2F634B - DATABASE_URL_TEST: postgres://root@localhost:5432/circle_test - DATABASE_URL: postgres://root@localhost:5432/circle_test - URL: http://localhost:3000 - SMTP_FROM_EMAIL: hello@example.com - AWS_S3_UPLOAD_BUCKET_URL: https://s3.amazonaws.com - AWS_S3_UPLOAD_BUCKET_NAME: outline-circle + <<: *defaults steps: - checkout - restore_cache: key: dependency-cache-{{ checksum "package.json" }} - run: name: install-deps - command: yarn install --pure-lockfile + command: yarn install --frozen-lockfile - save_cache: key: dependency-cache-{{ checksum "package.json" }} paths: - ./node_modules + lint: + <<: *defaults + steps: + - checkout + - restore_cache: + key: dependency-cache-{{ checksum "package.json" }} + - run: + name: lint + command: yarn lint + types: + <<: *defaults + steps: + - checkout + - restore_cache: + key: dependency-cache-{{ checksum "package.json" }} + - run: + name: typescript + command: yarn tsc + test-app: + <<: *defaults + steps: + - checkout + - restore_cache: + key: dependency-cache-{{ checksum "package.json" }} + - run: + name: test + command: yarn test:app + test-server: + <<: *defaults + steps: + - checkout + - restore_cache: + key: dependency-cache-{{ checksum "package.json" }} - run: name: migrate command: ./node_modules/.bin/sequelize db:migrate --url $DATABASE_URL_TEST - - run: - name: lint - command: yarn lint - - run: - name: typescript - command: yarn tsc - run: name: test - command: yarn test + command: yarn test:server + bundle-size: + <<: *defaults + steps: + - checkout + - restore_cache: + key: dependency-cache-{{ checksum "package.json" }} - run: name: build-webpack command: yarn build:webpack @@ -56,59 +98,59 @@ jobs: - setup_remote_docker: version: 20.10.6 - run: - name: Build Docker image - command: docker build -t $IMAGE_NAME:latest . - - run: - name: Archive Docker image - command: docker save -o image.tar $IMAGE_NAME - - persist_to_workspace: - root: . - paths: - - ./image.tar - publish-latest: - executor: docker-publisher - steps: - - attach_workspace: - at: /tmp/workspace - - setup_remote_docker: - version: 20.10.6 - - run: - name: Load archived Docker image - command: docker load -i /tmp/workspace/image.tar - - run: - name: Publish Docker Image to Docker Hub + name: Install Docker buildx command: | - echo "$DOCKERHUB_PASS" | docker login -u "$DOCKERHUB_USERNAME" --password-stdin - IMAGE_TAG=${CIRCLE_TAG/v/''} - docker tag $IMAGE_NAME:latest $IMAGE_NAME:$IMAGE_TAG - docker push $IMAGE_NAME:latest - docker push $IMAGE_NAME:$IMAGE_TAG - publish-tag: - executor: docker-publisher - steps: - - attach_workspace: - at: /tmp/workspace - - setup_remote_docker: - version: 20.10.6 + mkdir -p ~/.docker/cli-plugins + url="https://github.com/docker/buildx/releases/download/v0.8.0/buildx-v0.8.0.linux-amd64" + curl -sSL -o ~/.docker/cli-plugins/docker-buildx $url + chmod a+x ~/.docker/cli-plugins/docker-buildx - run: - name: Load archived Docker image - command: docker load -i /tmp/workspace/image.tar + name: Enable Docker buildx + command: export DOCKER_CLI_EXPERIMENTAL=enabled - run: - name: Publish Docker Image to Docker Hub + name: Initialize Docker buildx command: | - echo "$DOCKERHUB_PASS" | docker login -u "$DOCKERHUB_USERNAME" --password-stdin - IMAGE_TAG=${CIRCLE_TAG/v/''} - docker tag $IMAGE_NAME:latest $IMAGE_NAME:$IMAGE_TAG - docker push $IMAGE_NAME:$IMAGE_TAG + docker buildx install + docker context create docker-multiarch + docker run --rm --privileged multiarch/qemu-user-static --reset -p yes + docker buildx create --name docker-multiarch --platform linux/amd64,linux/arm/v6,linux/arm/v7,linux/arm64/v8,linux/ppc64le,linux/s390x docker-multiarch + docker buildx inspect --builder docker-multiarch --bootstrap + docker buildx use docker-multiarch + - run: + name: Build base image + command: docker build -f Dockerfile.base -t $BASE_IMAGE_NAME:latest --load . + - run: + name: Login to Docker Hub + command: echo "$DOCKERHUB_PASS" | docker login -u "$DOCKERHUB_USERNAME" --password-stdin + - run: + name: Publish base Docker Image to Docker Hub + command: docker push $BASE_IMAGE_NAME:latest + - run: + name: Build and push Docker image + command: docker buildx build -t $IMAGE_NAME:latest -t $IMAGE_NAME:${CIRCLE_TAG/v/''} --platform linux/amd64,linux/arm/v6,linux/arm/v7,linux/arm64/v8,linux/ppc64le,linux/s390x --push . workflows: version: 2 - build-and-test: + all: jobs: - - build: - filters: - tags: - ignore: /^v.*/ + - build + - lint: + requires: + - build + - test-server: + requires: + - build + - test-app: + requires: + - build + - types: + requires: + - build + - bundle-size: + requires: + - test-app + - test-server + build-docker: jobs: - build-image: @@ -117,19 +159,3 @@ workflows: only: /^v.*/ branches: ignore: /.*/ - - publish-latest: - requires: - - build-image - filters: - tags: - only: /^v\d+\.\d+\.\d+$/ - branches: - ignore: /.*/ - - publish-tag: - requires: - - build-image - filters: - tags: - only: /^v\d+\.\d+\.\d+-.*$/ - branches: - ignore: /.*/ diff --git a/.env.sample b/.env.sample index dfd6688df5..439c66d9f9 100644 --- a/.env.sample +++ b/.env.sample @@ -12,6 +12,8 @@ UTILS_SECRET=generate_a_new_key # should work out of the box. DATABASE_URL=postgres://user:pass@localhost:5432/outline DATABASE_URL_TEST=postgres://user:pass@localhost:5432/outline-test +DATABASE_CONNECTION_POOL_MIN= +DATABASE_CONNECTION_POOL_MAX= # Uncomment this to disable SSL for connecting to Postgres # PGSSLMODE=disable REDIS_URL=redis://localhost:6379 @@ -90,7 +92,7 @@ OIDC_USERNAME_CLAIM=preferred_username OIDC_DISPLAY_NAME=OpenID # Space separated auth scopes. -OIDC_SCOPES="openid profile email" +OIDC_SCOPES=openid profile email # –––––––––––––––– OPTIONAL –––––––––––––––– diff --git a/.eslintrc b/.eslintrc index 7fdd615848..46b29e1334 100644 --- a/.eslintrc +++ b/.eslintrc @@ -16,6 +16,7 @@ "plugin:prettier/recommended" ], "plugins": [ + "es", "@typescript-eslint", "eslint-plugin-import", "eslint-plugin-node", @@ -28,6 +29,7 @@ "curly": 2, "no-mixed-operators": "off", "no-useless-escape": "off", + "es/no-regexp-lookbehind-assertions": "error", "@typescript-eslint/no-unused-vars": [ "error", { diff --git a/.github/workflows/calibreapp-image-actions.yml b/.github/workflows/calibreapp-image-actions.yml new file mode 100644 index 0000000000..4294cc0bdc --- /dev/null +++ b/.github/workflows/calibreapp-image-actions.yml @@ -0,0 +1,56 @@ +# Image Actions will run in the following scenarios: +# - on Pull Requests containing images (not including forks) +# - on pushing of images to `main` (for forks) +# - on demand (https://github.blog/changelog/2020-07-06-github-actions-manual-triggers-with-workflow_dispatch/) +# - at 11 PM every Sunday in anything gets missed with any of the above scenarios +# For Pull Requests, the images are added to the PR. +# For other scenarios, a new PR will be opened if any images are compressed. +name: Compress images +on: + pull_request: + paths: + - "**.jpg" + - "**.jpeg" + - "**.png" + - "**.webp" + push: + branches: + - main + paths: + - "**.jpg" + - "**.jpeg" + - "**.png" + - "**.webp" + workflow_dispatch: + schedule: + - cron: "00 20 * * 0" +jobs: + build: + name: calibreapp/image-actions + runs-on: ubuntu-latest + # Only run on main repo on and PRs that match the main repo. + if: | + github.repository == 'outline/outline' && + (github.event_name != 'pull_request' || + github.event.pull_request.head.repo.full_name == github.repository) + steps: + - name: Checkout Branch + uses: actions/checkout@v2 + - name: Compress Images + id: calibre + uses: calibreapp/image-actions@main + with: + githubToken: ${{ secrets.GITHUB_TOKEN }} + # For non-Pull Requests, run in compressOnly mode and we'll PR after. + compressOnly: ${{ github.event_name != 'pull_request' }} + - name: Create Pull Request + # If it's not a Pull Request then commit any changes as a new PR. + if: | + github.event_name != 'pull_request' && + steps.calibre.outputs.markdown != '' + uses: peter-evans/create-pull-request@v3 + with: + title: "chore: Auto Compress Images" + branch-suffix: timestamp + commit-message: "chore: Compressed inefficient images automatically" + body: ${{ steps.calibre.outputs.markdown }} diff --git a/.husky/pre-commit b/.husky/pre-commit new file mode 100755 index 0000000000..25d2235737 --- /dev/null +++ b/.husky/pre-commit @@ -0,0 +1,4 @@ +#!/usr/bin/env sh +. "$(dirname "$0")/_/husky.sh" + +npx lint-staged \ No newline at end of file diff --git a/Dockerfile b/Dockerfile index 7ff9e86391..966086c5c2 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,45 +1,22 @@ -# syntax=docker/dockerfile:1.2 ARG APP_PATH=/opt/outline -FROM node:16-alpine AS deps-common - -ARG APP_PATH -WORKDIR $APP_PATH -COPY ./package.json ./yarn.lock ./ - -# --- -FROM deps-common AS deps-dev -RUN yarn install --no-optional --frozen-lockfile && \ - yarn cache clean - -# --- -FROM deps-common AS deps-prod -RUN yarn install --production=true --frozen-lockfile && \ - yarn cache clean - -# --- -FROM node:16-alpine AS builder +FROM outlinewiki/outline-base as base ARG APP_PATH WORKDIR $APP_PATH -COPY . . -COPY --from=deps-dev $APP_PATH/node_modules ./node_modules -ARG CDN_URL -RUN yarn build - # --- -FROM node:16-alpine AS runner +FROM node:16.14.2-alpine3.15 AS runner ARG APP_PATH WORKDIR $APP_PATH ENV NODE_ENV production -COPY --from=builder $APP_PATH/build ./build -COPY --from=builder $APP_PATH/server ./server -COPY --from=builder $APP_PATH/public ./public -COPY --from=builder $APP_PATH/.sequelizerc ./.sequelizerc -COPY --from=deps-prod $APP_PATH/node_modules ./node_modules -COPY --from=builder $APP_PATH/package.json ./package.json +COPY --from=base $APP_PATH/build ./build +COPY --from=base $APP_PATH/server ./server +COPY --from=base $APP_PATH/public ./public +COPY --from=base $APP_PATH/.sequelizerc ./.sequelizerc +COPY --from=base $APP_PATH/node_modules ./node_modules +COPY --from=base $APP_PATH/package.json ./package.json RUN addgroup -g 1001 -S nodejs && \ adduser -S nodejs -u 1001 && \ diff --git a/Dockerfile.base b/Dockerfile.base new file mode 100644 index 0000000000..eafc7ade93 --- /dev/null +++ b/Dockerfile.base @@ -0,0 +1,18 @@ +ARG APP_PATH=/opt/outline +FROM node:16.14.2-alpine3.15 AS deps + +ARG APP_PATH +WORKDIR $APP_PATH +COPY ./package.json ./yarn.lock ./ + +RUN yarn install --no-optional --frozen-lockfile --network-timeout 1000000 && \ + yarn cache clean + +COPY . . +ARG CDN_URL +RUN yarn build + +RUN rm -rf node_modules + +RUN yarn install --production=true --frozen-lockfile --network-timeout 1000000 && \ + yarn cache clean diff --git a/LICENSE b/LICENSE index 7ec4ebe7f9..4a5d10a7c7 100644 --- a/LICENSE +++ b/LICENSE @@ -3,7 +3,7 @@ Business Source License 1.1 Parameters Licensor: General Outline, Inc. -Licensed Work: Outline 0.60.1 +Licensed Work: Outline 0.63.0 The Licensed Work is (c) 2020 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: 2025-11-11 +Change Date: 2026-04-15 Change License: Apache License, Version 2.0 diff --git a/__mocks__/window.js b/__mocks__/window.js index 3b827de32b..3c3a486fb0 100644 --- a/__mocks__/window.js +++ b/__mocks__/window.js @@ -1 +1,2 @@ -window.matchMedia = data => data; +window.matchMedia = (data) => data; +window.env = {}; diff --git a/app/actions/definitions/collections.tsx b/app/actions/definitions/collections.tsx index 2d3288894d..a151d2c795 100644 --- a/app/actions/definitions/collections.tsx +++ b/app/actions/definitions/collections.tsx @@ -1,4 +1,10 @@ -import { CollectionIcon, EditIcon, PlusIcon } from "outline-icons"; +import { + CollectionIcon, + EditIcon, + PlusIcon, + StarredIcon, + UnstarredIcon, +} from "outline-icons"; import * as React from "react"; import stores from "~/stores"; import Collection from "~/models/Collection"; @@ -73,4 +79,59 @@ export const editCollection = createAction({ }, }); -export const rootCollectionActions = [openCollection, createCollection]; +export const starCollection = createAction({ + name: ({ t }) => t("Star"), + section: CollectionSection, + icon: , + keywords: "favorite bookmark", + visible: ({ activeCollectionId, stores }) => { + if (!activeCollectionId) { + return false; + } + const collection = stores.collections.get(activeCollectionId); + return ( + !collection?.isStarred && + stores.policies.abilities(activeCollectionId).star + ); + }, + perform: ({ activeCollectionId, stores }) => { + if (!activeCollectionId) { + return; + } + + const collection = stores.collections.get(activeCollectionId); + collection?.star(); + }, +}); + +export const unstarCollection = createAction({ + name: ({ t }) => t("Unstar"), + section: CollectionSection, + icon: , + keywords: "unfavorite unbookmark", + visible: ({ activeCollectionId, stores }) => { + if (!activeCollectionId) { + return false; + } + const collection = stores.collections.get(activeCollectionId); + return ( + !!collection?.isStarred && + stores.policies.abilities(activeCollectionId).unstar + ); + }, + perform: ({ activeCollectionId, stores }) => { + if (!activeCollectionId) { + return; + } + + const collection = stores.collections.get(activeCollectionId); + collection?.unstar(); + }, +}); + +export const rootCollectionActions = [ + openCollection, + createCollection, + starCollection, + unstarCollection, +]; diff --git a/app/actions/definitions/documents.tsx b/app/actions/definitions/documents.tsx index 9bd3565bc2..636a78f2ad 100644 --- a/app/actions/definitions/documents.tsx +++ b/app/actions/definitions/documents.tsx @@ -10,14 +10,15 @@ import { ShapesIcon, ImportIcon, PinIcon, + SearchIcon, } from "outline-icons"; import * as React from "react"; import getDataTransferFiles from "@shared/utils/getDataTransferFiles"; -import DocumentTemplatize from "~/scenes/DocumentTemplatize"; +import DocumentTemplatizeDialog from "~/components/DocumentTemplatizeDialog"; import { createAction } from "~/actions"; import { DocumentSection } from "~/actions/sections"; import history from "~/utils/history"; -import { homePath, newDocumentPath } from "~/utils/routeHelpers"; +import { homePath, newDocumentPath, searchPath } from "~/utils/routeHelpers"; export const openDocument = createAction({ name: ({ t }) => t("Open document"), @@ -51,8 +52,11 @@ export const createDocument = createAction({ visible: ({ activeCollectionId, stores }) => !!activeCollectionId && stores.policies.abilities(activeCollectionId).update, - perform: ({ activeCollectionId }) => - activeCollectionId && history.push(newDocumentPath(activeCollectionId)), + perform: ({ activeCollectionId, inStarredSection }) => + activeCollectionId && + history.push(newDocumentPath(activeCollectionId), { + starred: inStarredSection, + }), }); export const starDocument = createAction({ @@ -302,22 +306,28 @@ export const createTemplate = createAction({ if (!activeDocumentId) { return; } - event?.preventDefault(); event?.stopPropagation(); stores.dialogs.openModal({ title: t("Create template"), - content: ( - - ), + isCentered: true, + content: , }); }, }); +export const searchDocumentsForQuery = (searchQuery: string) => + createAction({ + id: "search", + section: DocumentSection, + name: ({ t }) => + t(`Search documents for "{{searchQuery}}"`, { searchQuery }), + icon: , + perform: () => history.push(searchPath(searchQuery)), + visible: ({ location }) => location.pathname !== searchPath(), + }); + export const rootDocumentActions = [ openDocument, createDocument, diff --git a/app/actions/definitions/navigation.tsx b/app/actions/definitions/navigation.tsx index 0334862dbb..a5c188c277 100644 --- a/app/actions/definitions/navigation.tsx +++ b/app/actions/definitions/navigation.tsx @@ -16,18 +16,14 @@ import * as React from "react"; import { developersUrl, changelogUrl, - mailToUrl, + feedbackUrl, githubIssuesUrl, } from "@shared/utils/urlHelpers"; import stores from "~/stores"; import SearchQuery from "~/models/SearchQuery"; import KeyboardShortcuts from "~/scenes/KeyboardShortcuts"; import { createAction } from "~/actions"; -import { - NavigationSection, - SearchSection, - RecentSearchesSection, -} from "~/actions/sections"; +import { NavigationSection, RecentSearchesSection } from "~/actions/sections"; import history from "~/utils/history"; import { organizationSettingsPath, @@ -57,17 +53,6 @@ export const navigateToRecentSearchQuery = (searchQuery: SearchQuery) => perform: () => history.push(searchPath(searchQuery.query)), }); -export const navigateToSearchQuery = (searchQuery: string) => - createAction({ - id: "search", - section: SearchSection, - name: ({ t }) => - t(`Search documents for "{{searchQuery}}"`, { searchQuery }), - icon: , - perform: () => history.push(searchPath(searchQuery)), - visible: ({ location }) => location.pathname !== searchPath(), - }); - export const navigateToDrafts = createAction({ name: ({ t }) => t("Drafts"), section: NavigationSection, @@ -106,6 +91,8 @@ export const navigateToSettings = createAction({ section: NavigationSection, shortcut: ["g", "s"], icon: , + visible: ({ stores }) => + stores.policies.abilities(stores.auth.team?.id || "").update, perform: () => history.push(organizationSettingsPath()), }); @@ -130,7 +117,7 @@ export const openFeedbackUrl = createAction({ section: NavigationSection, iconInContextMenu: false, icon: , - perform: () => window.open(mailToUrl()), + perform: () => window.open(feedbackUrl()), }); export const openBugReportUrl = createAction({ @@ -174,7 +161,6 @@ export const rootNavigationActions = [ navigateToTemplates, navigateToArchive, navigateToTrash, - navigateToSettings, openAPIDocumentation, openFeedbackUrl, openBugReportUrl, diff --git a/app/actions/index.ts b/app/actions/index.ts index b1b25bd04f..b13eaa99b5 100644 --- a/app/actions/index.ts +++ b/app/actions/index.ts @@ -10,6 +10,10 @@ import { MenuItemWithChildren, } from "~/types"; +function resolve(value: any, context: ActionContext): T { + return typeof value === "function" ? value(context) : value; +} + export function createAction(definition: Optional): Action { return { ...definition, @@ -21,18 +25,10 @@ export function actionToMenuItem( action: Action, context: ActionContext ): MenuItemButton | MenuItemWithChildren { - function resolve(value: any): T { - if (typeof value === "function") { - return value(context); - } - - return value; - } - - const resolvedIcon = resolve>(action.icon); - const resolvedChildren = resolve(action.children); + const resolvedIcon = resolve>(action.icon, context); + const resolvedChildren = resolve(action.children, context); const visible = action.visible ? action.visible(context) : true; - const title = resolve(action.name); + const title = resolve(action.name, context); const icon = resolvedIcon && action.iconInContextMenu !== false ? React.cloneElement(resolvedIcon, { @@ -69,23 +65,15 @@ export function actionToKBar( action: Action, context: ActionContext ): CommandBarAction[] { - function resolve(value: any): T { - if (typeof value === "function") { - return value(context); - } - - return value; - } - if (typeof action.visible === "function" && !action.visible(context)) { return []; } - const resolvedIcon = resolve>(action.icon); - const resolvedChildren = resolve(action.children); - const resolvedSection = resolve(action.section); - const resolvedName = resolve(action.name); - const resolvedPlaceholder = resolve(action.placeholder); + const resolvedIcon = resolve>(action.icon, context); + const resolvedChildren = resolve(action.children, context); + const resolvedSection = resolve(action.section, context); + const resolvedName = resolve(action.name, context); + const resolvedPlaceholder = resolve(action.placeholder, context); const children = resolvedChildren ? flattenDeep(resolvedChildren.map((a) => actionToKBar(a, context))).filter( (a) => !!a @@ -101,9 +89,7 @@ export function actionToKBar( keywords: action.keywords ?? "", shortcut: action.shortcut || [], icon: resolvedIcon, - perform: action.perform - ? () => action.perform && action.perform(context) - : undefined, + perform: action.perform ? () => action?.perform?.(context) : undefined, }, // @ts-expect-error ts-migrate(2769) FIXME: No overload matches this call. ].concat(children.map((child) => ({ ...child, parent: action.id }))); diff --git a/app/actions/sections.ts b/app/actions/sections.ts index 39549c6f19..2963e980fa 100644 --- a/app/actions/sections.ts +++ b/app/actions/sections.ts @@ -14,5 +14,3 @@ export const UserSection = ({ t }: ActionContext) => t("People"); export const RecentSearchesSection = ({ t }: ActionContext) => t("Recent searches"); - -export const SearchSection = ""; diff --git a/app/components/ActionButton.tsx b/app/components/ActionButton.tsx new file mode 100644 index 0000000000..4472a0e6d7 --- /dev/null +++ b/app/components/ActionButton.tsx @@ -0,0 +1,73 @@ +import * as React from "react"; +import Tooltip, { Props as TooltipProps } from "~/components/Tooltip"; +import { Action, ActionContext } from "~/types"; + +export type Props = { + /** Show the button in a disabled state */ + disabled?: boolean; + /** Hide the button entirely if action is not applicable */ + hideOnActionDisabled?: boolean; + /** Action to use on button */ + action?: Action; + /** Context of action, must be provided with action */ + context?: ActionContext; + /** If tooltip props are provided the button will be wrapped in a tooltip */ + tooltip?: Omit; +}; + +/** + * Button that can be used to trigger an action definition. + */ +const ActionButton = React.forwardRef( + ( + { + action, + context, + tooltip, + hideOnActionDisabled, + ...rest + }: Props & React.HTMLAttributes, + ref: React.Ref + ) => { + const disabled = rest.disabled; + + if (!context || !action) { + return + ); + + if (tooltip) { + return {button}; + } + + return button; + } +); + +export default ActionButton; diff --git a/app/components/Analytics.ts b/app/components/Analytics.ts index 1bf1e5d94c..044c6718f5 100644 --- a/app/components/Analytics.ts +++ b/app/components/Analytics.ts @@ -2,11 +2,7 @@ import * as React from "react"; import env from "~/env"; -type Props = { - children?: React.ReactNode; -}; - -export default class Analytics extends React.Component { +export default class Analytics extends React.Component { componentDidMount() { if (!env.GOOGLE_ANALYTICS_ID) { return; diff --git a/app/components/ArrowKeyNavigation.tsx b/app/components/ArrowKeyNavigation.tsx new file mode 100644 index 0000000000..7033e58ada --- /dev/null +++ b/app/components/ArrowKeyNavigation.tsx @@ -0,0 +1,51 @@ +import { observer } from "mobx-react"; +import * as React from "react"; +import { + useCompositeState, + Composite, + CompositeStateReturn, +} from "reakit/Composite"; + +type Props = { + children: (composite: CompositeStateReturn) => React.ReactNode; + onEscape?: (ev: React.KeyboardEvent) => void; +}; + +function ArrowKeyNavigation( + { children, onEscape, ...rest }: Props, + ref: React.RefObject +) { + const composite = useCompositeState(); + + const handleKeyDown = React.useCallback( + (ev) => { + if (onEscape) { + if (ev.key === "Escape") { + onEscape(ev); + } + + if ( + ev.key === "ArrowUp" && + composite.currentId === composite.items[0].id + ) { + onEscape(ev); + } + } + }, + [composite.currentId, composite.items, onEscape] + ); + + return ( + + {children(composite)} + + ); +} + +export default observer(React.forwardRef(ArrowKeyNavigation)); diff --git a/app/components/Authenticated.tsx b/app/components/Authenticated.tsx index 225791c663..976063b50e 100644 --- a/app/components/Authenticated.tsx +++ b/app/components/Authenticated.tsx @@ -15,7 +15,7 @@ type Props = { const Authenticated = ({ children }: Props) => { const { auth } = useStores(); const { i18n } = useTranslation(); - const language = auth.user && auth.user.language; + const language = auth.user?.language; // Watching for language changes here as this is the earliest point we have // the user available and means we can start loading translations faster diff --git a/app/components/AuthenticatedLayout.tsx b/app/components/AuthenticatedLayout.tsx index 11ad15b113..a591804bfa 100644 --- a/app/components/AuthenticatedLayout.tsx +++ b/app/components/AuthenticatedLayout.tsx @@ -34,10 +34,7 @@ const CommandBar = React.lazy( ) ); -type Props = WithTranslation & - RootStore & { - children?: React.ReactNode; - }; +type Props = WithTranslation & RootStore; @observer class AuthenticatedLayout extends React.Component { @@ -54,7 +51,11 @@ class AuthenticatedLayout extends React.Component { } }; - goToNewDocument = () => { + goToNewDocument = (event: KeyboardEvent) => { + if (event.metaKey || event.altKey) { + return; + } + const { activeCollectionId } = this.props.ui; if (!activeCollectionId) { return; diff --git a/app/components/Avatar/placeholder.png b/app/components/Avatar/placeholder.png index 573c74b4e2..315a63760c 100644 Binary files a/app/components/Avatar/placeholder.png and b/app/components/Avatar/placeholder.png differ diff --git a/app/components/Branding.tsx b/app/components/Branding.tsx index 9087de1473..4f96356632 100644 --- a/app/components/Branding.tsx +++ b/app/components/Branding.tsx @@ -1,6 +1,7 @@ import * as React from "react"; import styled from "styled-components"; import breakpoint from "styled-components-breakpoint"; +import { depths } from "@shared/styles"; import env from "~/env"; import OutlineLogo from "./OutlineLogo"; @@ -38,7 +39,7 @@ const Link = styled.a` } ${breakpoint("tablet")` - z-index: ${(props: any) => props.theme.depths.sidebar + 1}; + z-index: ${depths.sidebar + 1}; position: fixed; bottom: 0; left: 0; diff --git a/app/components/Breadcrumb.tsx b/app/components/Breadcrumb.tsx index 7ad14c4824..b0c3d205e2 100644 --- a/app/components/Breadcrumb.tsx +++ b/app/components/Breadcrumb.tsx @@ -9,11 +9,15 @@ import { MenuInternalLink } from "~/types"; type Props = { items: MenuInternalLink[]; max?: number; - children?: React.ReactNode; highlightFirstItem?: boolean; }; -function Breadcrumb({ items, highlightFirstItem, children, max = 2 }: Props) { +function Breadcrumb({ + items, + highlightFirstItem, + children, + max = 2, +}: React.PropsWithChildren) { const totalItems = items.length; const topLevelItems: MenuInternalLink[] = [...items]; let overflowItems; diff --git a/app/components/Button.tsx b/app/components/Button.tsx index e8171c2f59..21c570f9c9 100644 --- a/app/components/Button.tsx +++ b/app/components/Button.tsx @@ -111,7 +111,11 @@ const RealButton = styled.button<{ } &:disabled { - background: none; + background: ${lighten(0.05, props.theme.danger)}; + } + + &.focus-visible { + outline-color: ${darken(0.2, props.theme.danger)} !important; } `}; `; diff --git a/app/components/ButtonLink.tsx b/app/components/ButtonLink.tsx index 4c14c1664e..4d3463928f 100644 --- a/app/components/ButtonLink.tsx +++ b/app/components/ButtonLink.tsx @@ -3,10 +3,9 @@ import styled from "styled-components"; type Props = { onClick?: React.MouseEventHandler; - children: React.ReactNode; }; -const ButtonLink = React.forwardRef( +const ButtonLink: React.FC = React.forwardRef( (props: Props, ref: React.Ref) => { return + + + ); +} + +export default observer(ConfirmationDialog); diff --git a/app/components/ContentEditable.tsx b/app/components/ContentEditable.tsx index 984446ea0e..5d156365b0 100644 --- a/app/components/ContentEditable.tsx +++ b/app/components/ContentEditable.tsx @@ -1,6 +1,7 @@ import isPrintableKeyEvent from "is-printable-key-event"; import * as React from "react"; import styled from "styled-components"; +import useOnScreen from "~/hooks/useOnScreen"; type Props = Omit, "ref" | "onChange"> & { disabled?: boolean; @@ -17,6 +18,13 @@ type Props = Omit, "ref" | "onChange"> & { value: string; }; +export type RefHandle = { + focus: () => void; + focusAtStart: () => void; + focusAtEnd: () => void; + getComputedDirection: () => string; +}; + /** * Defines a content editable component with the same interface as a native * HTMLInputElement (or, as close as we can get). @@ -40,13 +48,36 @@ const ContentEditable = React.forwardRef( onClick, ...rest }: Props, - forwardedRef: React.RefObject + ref: React.RefObject ) => { - const innerRef = React.useRef(null); - const ref = forwardedRef || innerRef; + const contentRef = React.useRef(null); const [innerValue, setInnerValue] = React.useState(value); const lastValue = React.useRef(""); + React.useImperativeHandle(ref, () => ({ + focus: () => { + contentRef.current?.focus(); + }, + focusAtStart: () => { + if (contentRef.current) { + contentRef.current.focus(); + placeCaret(contentRef.current, true); + } + }, + focusAtEnd: () => { + if (contentRef.current) { + contentRef.current.focus(); + placeCaret(contentRef.current, false); + } + }, + getComputedDirection: () => { + if (contentRef.current) { + return window.getComputedStyle(contentRef.current).direction; + } + return "ltr"; + }, + })); + const wrappedEvent = ( callback: | React.FocusEventHandler @@ -54,7 +85,7 @@ const ContentEditable = React.forwardRef( | React.KeyboardEventHandler | undefined ) => (event: any) => { - const text = ref.current?.innerText || ""; + const text = contentRef.current?.innerText || ""; if (maxLength && isPrintableKeyEvent(event) && text.length >= maxLength) { event?.preventDefault(); @@ -69,17 +100,23 @@ const ContentEditable = React.forwardRef( callback?.(event); }; - React.useLayoutEffect(() => { - if (autoFocus) { - ref.current?.focus(); - } - }, [autoFocus, ref]); + // This is to account for being within a React.Suspense boundary, in this + // case the component may be rendered with display: none. React 18 may solve + // this in the future by delaying useEffect hooks: + // https://github.com/facebook/react/issues/14536#issuecomment-861980492 + const isVisible = useOnScreen(contentRef); React.useEffect(() => { - if (value !== ref.current?.innerText) { + if (autoFocus && isVisible && !disabled && !readOnly) { + contentRef.current?.focus(); + } + }, [autoFocus, disabled, isVisible, readOnly, contentRef]); + + React.useEffect(() => { + if (value !== contentRef.current?.innerText) { setInnerValue(value); } - }, [value, ref]); + }, [value, contentRef]); // Ensure only plain text can be pasted into title when pasting from another // rich text editor @@ -95,7 +132,7 @@ const ContentEditable = React.forwardRef( return (
props.theme.background}; transition: ${(props) => props.theme.backgroundTransition}; diff --git a/app/components/ContextMenu/MenuItem.tsx b/app/components/ContextMenu/MenuItem.tsx index c1354f7986..1b6ef6ba76 100644 --- a/app/components/ContextMenu/MenuItem.tsx +++ b/app/components/ContextMenu/MenuItem.tsx @@ -7,8 +7,7 @@ import { hover } from "~/styles"; import MenuIconWrapper from "../MenuIconWrapper"; type Props = { - onClick?: (arg0: React.SyntheticEvent) => void | Promise; - children?: React.ReactNode; + onClick?: (event: React.SyntheticEvent) => void | Promise; selected?: boolean; disabled?: boolean; dangerous?: boolean; @@ -21,7 +20,7 @@ type Props = { icon?: React.ReactElement; }; -const MenuItem = ({ +const MenuItem: React.FC = ({ onClick, children, selected, @@ -30,7 +29,7 @@ const MenuItem = ({ hide, icon, ...rest -}: Props) => { +}) => { const handleClick = React.useCallback( (ev) => { if (onClick) { diff --git a/app/components/ContextMenu/MouseSafeArea.tsx b/app/components/ContextMenu/MouseSafeArea.tsx new file mode 100644 index 0000000000..a1cd354bcb --- /dev/null +++ b/app/components/ContextMenu/MouseSafeArea.tsx @@ -0,0 +1,66 @@ +import * as React from "react"; +import { useMousePosition } from "~/hooks/useMousePosition"; + +type Positions = { + /* Sub-menu x */ + x: number; + /* Sub-menu y */ + y: number; + /* Sub-menu height */ + h: number; + /* Sub-menu width */ + w: number; + /* Mouse x */ + mouseX: number; + /* Mouse y */ + mouseY: number; +}; + +/** + * Component to cover the area between the mouse cursor and the sub-menu, to + * allow moving cursor to lower parts of sub-menu without the sub-menu + * disappearing. + */ +export default function MouseSafeArea(props: { + parentRef: React.RefObject; +}) { + const { x = 0, y = 0, height: h = 0, width: w = 0 } = + props.parentRef.current?.getBoundingClientRect() || {}; + const [mouseX, mouseY] = useMousePosition(); + const positions = { x, y, h, w, mouseX, mouseY }; + + return ( +
+ ); +} + +const getLeft = ({ x, mouseX }: Positions) => + mouseX > x ? undefined : -Math.max(x - mouseX, 10) + "px"; + +const getRight = ({ x, w, mouseX }: Positions) => + mouseX > x ? -Math.max(mouseX - (x + w), 10) + "px" : undefined; + +const getWidth = ({ x, w, mouseX }: Positions) => + mouseX > x + ? Math.max(mouseX - (x + w), 10) + "px" + : Math.max(x - mouseX, 10) + "px"; + +const getClipPath = ({ x, y, h, mouseX, mouseY }: Positions) => + mouseX > x + ? `polygon(0% 0%, 0% 100%, 100% ${(100 * (mouseY - y)) / h - 10}%, 100% ${ + (100 * (mouseY - y)) / h + 5 + }%)` + : `polygon(100% 0%, 0% ${(100 * (mouseY - y)) / h - 10}%, 0% ${ + (100 * (mouseY - y)) / h + 5 + }%, 100% 100%)`; diff --git a/app/components/ContextMenu/Template.tsx b/app/components/ContextMenu/Template.tsx index 541a181766..cd92a12bfc 100644 --- a/app/components/ContextMenu/Template.tsx +++ b/app/components/ContextMenu/Template.tsx @@ -21,6 +21,7 @@ import { } from "~/types"; import Header from "./Header"; import MenuItem, { MenuAnchor } from "./MenuItem"; +import MouseSafeArea from "./MouseSafeArea"; import Separator from "./Separator"; import ContextMenu from "."; @@ -59,6 +60,7 @@ const Submenu = React.forwardRef( )} +