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 (action?.visible && !action.visible(context) && hideOnActionDisabled) {
+ return null;
+ }
+
+ const label =
+ typeof action.name === "function" ? action.name(context) : action.name;
+
+ const button = (
+
+ );
+
+ 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 ;
}
diff --git a/app/components/CenteredContent.tsx b/app/components/CenteredContent.tsx
index 2582d4a686..7ddb942559 100644
--- a/app/components/CenteredContent.tsx
+++ b/app/components/CenteredContent.tsx
@@ -3,18 +3,17 @@ import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
type Props = {
- children?: React.ReactNode;
withStickyHeader?: boolean;
};
-const Container = styled.div<{ withStickyHeader?: boolean }>`
+const Container = styled.div`
width: 100%;
max-width: 100vw;
padding: ${(props) => (props.withStickyHeader ? "4px 12px" : "60px 12px")};
${breakpoint("tablet")`
padding: ${(props: any) =>
- props.withStickyHeader ? "4px 60px 60px" : "60px"};
+ props.withStickyHeader ? "4px 44px 60px" : "60px 44px"};
`};
`;
@@ -27,7 +26,7 @@ const Content = styled.div`
`};
`;
-const CenteredContent = ({ children, ...rest }: Props) => {
+const CenteredContent: React.FC = ({ children, ...rest }) => {
return (
{children}
diff --git a/app/components/Collaborators.tsx b/app/components/Collaborators.tsx
index a67ac265d8..a58c9340b6 100644
--- a/app/components/Collaborators.tsx
+++ b/app/components/Collaborators.tsx
@@ -52,18 +52,14 @@ function Collaborators(props: Props) {
// load any users we don't yet have in memory
React.useEffect(() => {
- const userIdsToFetch = uniq([
- ...document.collaboratorIds,
- ...presentIds,
- ]).filter((userId) => !users.get(userId));
+ const ids = uniq([...document.collaboratorIds, ...presentIds])
+ .filter((userId) => !users.get(userId))
+ .sort();
- if (!isEqual(requestedUserIds, userIdsToFetch)) {
- setRequestedUserIds(userIdsToFetch);
+ if (!isEqual(requestedUserIds, ids) && ids.length > 0) {
+ setRequestedUserIds(ids);
+ users.fetchPage({ ids, limit: 100 });
}
-
- userIdsToFetch
- .filter((userId) => requestedUserIds.includes(userId))
- .forEach((userId) => users.fetch(userId));
}, [document, users, presentIds, document.collaboratorIds, requestedUserIds]);
const popover = usePopoverState({
diff --git a/app/components/CollectionDescription.tsx b/app/components/CollectionDescription.tsx
index 68818c5d4d..81e34b02e2 100644
--- a/app/components/CollectionDescription.tsx
+++ b/app/components/CollectionDescription.tsx
@@ -1,3 +1,4 @@
+import debounce from "lodash/debounce";
import { observer } from "mobx-react";
import { transparentize } from "polished";
import * as React from "react";
@@ -9,7 +10,6 @@ import ButtonLink from "~/components/ButtonLink";
import Editor from "~/components/Editor";
import LoadingIndicator from "~/components/LoadingIndicator";
import NudeButton from "~/components/NudeButton";
-import useDebouncedCallback from "~/hooks/useDebouncedCallback";
import usePolicy from "~/hooks/usePolicy";
import useStores from "~/hooks/useStores";
import useToasts from "~/hooks/useToasts";
@@ -49,21 +49,25 @@ function CollectionDescription({ collection }: Props) {
[isExpanded]
);
- const handleSave = useDebouncedCallback(async (getValue) => {
- try {
- await collection.save({
- description: getValue(),
- });
- setDirty(false);
- } catch (err) {
- showToast(
- t("Sorry, an error occurred saving the collection", {
- type: "error",
- })
- );
- throw err;
- }
- }, 1000);
+ const handleSave = React.useMemo(
+ () =>
+ debounce(async (getValue) => {
+ try {
+ await collection.save({
+ description: getValue(),
+ });
+ setDirty(false);
+ } catch (err) {
+ showToast(
+ t("Sorry, an error occurred saving the collection", {
+ type: "error",
+ })
+ );
+ throw err;
+ }
+ }, 1000),
+ [collection, showToast, t]
+ );
const handleChange = React.useCallback(
(getValue) => {
@@ -107,7 +111,6 @@ function CollectionDescription({ collection }: Props) {
maxLength={1000}
embedsDisabled
readOnlyWriteCheckboxes
- grow
/>
) : (
diff --git a/app/components/CollectionIcon.tsx b/app/components/CollectionIcon.tsx
index 427e554913..f015515484 100644
--- a/app/components/CollectionIcon.tsx
+++ b/app/components/CollectionIcon.tsx
@@ -5,6 +5,7 @@ import * as React from "react";
import Collection from "~/models/Collection";
import { icons } from "~/components/IconPicker";
import useStores from "~/hooks/useStores";
+import Logger from "~/utils/logger";
type Props = {
collection: Collection;
@@ -36,7 +37,9 @@ function ResolvedCollectionIcon({
const Component = icons[collection.icon].component;
return ;
} catch (error) {
- console.warn("Failed to render custom icon " + collection.icon);
+ Logger.warn("Failed to render custom icon", {
+ icon: collection.icon,
+ });
}
}
diff --git a/app/components/CommandBar.tsx b/app/components/CommandBar.tsx
index cfb8fb8409..9f76a1e21a 100644
--- a/app/components/CommandBar.tsx
+++ b/app/components/CommandBar.tsx
@@ -6,10 +6,12 @@ import { useTranslation } from "react-i18next";
import { Portal } from "react-portal";
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
+import { depths } from "@shared/styles";
import CommandBarResults from "~/components/CommandBarResults";
import SearchActions from "~/components/SearchActions";
import rootActions from "~/actions/root";
import useCommandBarActions from "~/hooks/useCommandBarActions";
+import useSettingsActions from "~/hooks/useSettingsAction";
import useStores from "~/hooks/useStores";
import { CommandBarAction } from "~/types";
import { metaDisplay } from "~/utils/keyboard";
@@ -18,8 +20,13 @@ import Text from "./Text";
function CommandBar() {
const { t } = useTranslation();
const { ui } = useStores();
+ const settingsActions = useSettingsActions();
+ const commandBarActions = React.useMemo(
+ () => [...rootActions, settingsActions],
+ [settingsActions]
+ );
- useCommandBarActions(rootActions);
+ useCommandBarActions(commandBarActions);
const { rootAction } = useKBar((state) => ({
rootAction: state.currentRootActionId
@@ -42,9 +49,7 @@ function CommandBar() {
t("Type a command or search")
}…`}
/>
-
+
{ui.commandBarOpenedFromSidebar && (
@@ -63,7 +68,7 @@ function CommandBar() {
);
}
-function KBarPortal({ children }: { children: React.ReactNode }) {
+const KBarPortal: React.FC = ({ children }) => {
const { showing } = useKBar((state) => ({
showing: state.visualState !== "hidden",
}));
@@ -73,7 +78,7 @@ function KBarPortal({ children }: { children: React.ReactNode }) {
}
return {children};
-}
+};
const Hint = styled(Text)`
display: flex;
@@ -86,7 +91,7 @@ const Hint = styled(Text)`
`;
const Positioner = styled(KBarPositioner)`
- z-index: ${(props) => props.theme.depths.commandBar};
+ z-index: ${depths.commandBar};
`;
const SearchInput = styled(KBarSearch)`
diff --git a/app/components/CommandBarResults.tsx b/app/components/CommandBarResults.tsx
index 250269b678..7c2b59ee1a 100644
--- a/app/components/CommandBarResults.tsx
+++ b/app/components/CommandBarResults.tsx
@@ -1,27 +1,14 @@
import { useMatches, KBarResults } from "kbar";
-import { orderBy } from "lodash";
import * as React from "react";
import styled from "styled-components";
import CommandBarItem from "~/components/CommandBarItem";
-import { SearchSection } from "~/actions/sections";
-type Props = {
- prioritizeSearchResults: boolean;
-};
-
-export default function CommandBarResults(props: Props) {
+export default function CommandBarResults() {
const { results, rootActionId } = useMatches();
return (
- // this is an unfortunate hack until kbar supports priority internally
- typeof item !== "string" &&
- item.section === SearchSection &&
- props.prioritizeSearchResults
- ? -1
- : 1
- )}
+ items={results}
maxHeight={400}
onRender={({ item, active }) =>
typeof item === "string" ? (
diff --git a/app/components/ConfirmationDialog.tsx b/app/components/ConfirmationDialog.tsx
new file mode 100644
index 0000000000..ac5baffa15
--- /dev/null
+++ b/app/components/ConfirmationDialog.tsx
@@ -0,0 +1,58 @@
+import { observer } from "mobx-react";
+import * as React from "react";
+import Button from "~/components/Button";
+import Flex from "~/components/Flex";
+import Text from "~/components/Text";
+import useStores from "~/hooks/useStores";
+import useToasts from "~/hooks/useToasts";
+
+type Props = {
+ onSubmit: () => void;
+ children: JSX.Element;
+ submitText?: string;
+ savingText?: string;
+ danger?: boolean;
+};
+
+function ConfirmationDialog({
+ onSubmit,
+ children,
+ submitText,
+ savingText,
+ danger,
+}: Props) {
+ const [isSaving, setIsSaving] = React.useState(false);
+ const { dialogs } = useStores();
+ const { showToast } = useToasts();
+
+ const handleSubmit = React.useCallback(
+ async (ev: React.SyntheticEvent) => {
+ ev.preventDefault();
+ setIsSaving(true);
+ try {
+ await onSubmit();
+ dialogs.closeAllModals();
+ } catch (err) {
+ showToast(err.message, {
+ type: "error",
+ });
+ } finally {
+ setIsSaving(false);
+ }
+ },
+ [onSubmit, dialogs, showToast]
+ );
+
+ 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(
)}
+
>
diff --git a/app/components/ContextMenu/index.tsx b/app/components/ContextMenu/index.tsx
index 9d2612219e..04ccf1160f 100644
--- a/app/components/ContextMenu/index.tsx
+++ b/app/components/ContextMenu/index.tsx
@@ -1,10 +1,16 @@
import * as React from "react";
+import { useTranslation } from "react-i18next";
import { Portal } from "react-portal";
import { Menu } from "reakit/Menu";
-import styled from "styled-components";
+import styled, { DefaultTheme } from "styled-components";
import breakpoint from "styled-components-breakpoint";
+import { depths } from "@shared/styles";
+import Scrollable from "~/components/Scrollable";
+import useMenuContext from "~/hooks/useMenuContext";
import useMenuHeight from "~/hooks/useMenuHeight";
import usePrevious from "~/hooks/usePrevious";
+import useStores from "~/hooks/useStores";
+import useUnmount from "~/hooks/useUnmount";
import {
fadeIn,
fadeAndSlideUp,
@@ -34,36 +40,57 @@ type Props = {
visible?: boolean;
placement?: Placement;
animating?: boolean;
- children: React.ReactNode;
unstable_disclosureRef?: React.RefObject;
onOpen?: () => void;
onClose?: () => void;
hide?: () => void;
};
-export default function ContextMenu({
+const ContextMenu: React.FC = ({
children,
onOpen,
onClose,
...rest
-}: Props) {
+}) => {
const previousVisible = usePrevious(rest.visible);
const maxHeight = useMenuHeight(rest.visible, rest.unstable_disclosureRef);
const backgroundRef = React.useRef(null);
+ const { ui } = useStores();
+ const { t } = useTranslation();
+ const { setIsMenuOpen } = useMenuContext();
+
+ useUnmount(() => {
+ setIsMenuOpen(false);
+ });
React.useEffect(() => {
if (rest.visible && !previousVisible) {
if (onOpen) {
onOpen();
}
+ if (rest["aria-label"] !== t("Submenu")) {
+ setIsMenuOpen(true);
+ }
}
if (!rest.visible && previousVisible) {
if (onClose) {
onClose();
}
+ if (rest["aria-label"] !== t("Submenu")) {
+ setIsMenuOpen(false);
+ }
}
- }, [onOpen, onClose, previousVisible, rest.visible]);
+ }, [
+ onOpen,
+ onClose,
+ previousVisible,
+ rest.visible,
+ ui.sidebarCollapsed,
+ setIsMenuOpen,
+ rest,
+ t,
+ ]);
// Perf win – don't render anything until the menu has been opened
if (!rest.visible && !previousVisible) {
@@ -90,6 +117,7 @@ export default function ContextMenu({
topAnchor={topAnchor}
rightAnchor={rightAnchor}
ref={backgroundRef}
+ hiddenScrollbars
style={
maxHeight && topAnchor
? {
@@ -111,7 +139,9 @@ export default function ContextMenu({
)}
>
);
-}
+};
+
+export default ContextMenu;
export const Backdrop = styled.div`
animation: ${fadeIn} 200ms ease-in-out;
@@ -121,7 +151,7 @@ export const Backdrop = styled.div`
right: 0;
bottom: 0;
background: ${(props) => props.theme.backdrop};
- z-index: ${(props) => props.theme.depths.menu - 1};
+ z-index: ${depths.menu - 1};
${breakpoint("tablet")`
display: none;
@@ -130,10 +160,12 @@ export const Backdrop = styled.div`
export const Position = styled.div`
position: absolute;
- z-index: ${(props) => props.theme.depths.menu};
+ z-index: ${depths.menu};
- // overrides make mobile-first coding style challenging
- // so we explicitly define mobile breakpoint here
+ /*
+ * overrides make mobile-first coding style challenging
+ * so we explicitly define mobile breakpoint here
+ */
${breakpoint("mobile", "tablet")`
position: fixed !important;
transform: none !important;
@@ -144,10 +176,13 @@ export const Position = styled.div`
`};
`;
-export const Background = styled.div<{
+type BackgroundProps = {
topAnchor?: boolean;
rightAnchor?: boolean;
-}>`
+ theme: DefaultTheme;
+};
+
+export const Background = styled(Scrollable)`
animation: ${mobileContextMenu} 200ms ease;
transform-origin: 50% 100%;
max-width: 100%;
@@ -156,8 +191,6 @@ export const Background = styled.div<{
padding: 6px 0;
min-width: 180px;
min-height: 44px;
- overflow: hidden;
- overflow-y: auto;
max-height: 75vh;
pointer-events: all;
font-weight: normal;
@@ -167,11 +200,12 @@ export const Background = styled.div<{
}
${breakpoint("tablet")`
- animation: ${(props: any) =>
+ animation: ${(props: BackgroundProps) =>
props.topAnchor ? fadeAndSlideDown : fadeAndSlideUp} 200ms ease;
- transform-origin: ${(props: any) => (props.rightAnchor ? "75%" : "25%")} 0;
+ transform-origin: ${(props: BackgroundProps) =>
+ props.rightAnchor ? "75%" : "25%"} 0;
max-width: 276px;
- background: ${(props: any) => props.theme.menuBackground};
- box-shadow: ${(props: any) => props.theme.menuShadow};
+ background: ${(props: BackgroundProps) => props.theme.menuBackground};
+ box-shadow: ${(props: BackgroundProps) => props.theme.menuShadow};
`};
`;
diff --git a/app/components/CopyToClipboard.ts b/app/components/CopyToClipboard.ts
index 65279b29f6..e9982a1414 100644
--- a/app/components/CopyToClipboard.ts
+++ b/app/components/CopyToClipboard.ts
@@ -5,7 +5,7 @@ type Props = {
text: string;
children?: React.ReactElement;
onClick?: React.MouseEventHandler;
- onCopy: () => void;
+ onCopy?: () => void;
};
class CopyToClipboard extends React.PureComponent {
@@ -17,9 +17,8 @@ class CopyToClipboard extends React.PureComponent {
debug: process.env.NODE_ENV !== "production",
format: "text/plain",
});
- if (onCopy) {
- onCopy();
- }
+
+ onCopy?.();
if (elem && elem.props && typeof elem.props.onClick === "function") {
elem.props.onClick(ev);
diff --git a/app/components/DefaultCollectionInputSelect.tsx b/app/components/DefaultCollectionInputSelect.tsx
index 99f8222f22..c6e3633346 100644
--- a/app/components/DefaultCollectionInputSelect.tsx
+++ b/app/components/DefaultCollectionInputSelect.tsx
@@ -1,6 +1,7 @@
import { HomeIcon } from "outline-icons";
import React, { useState } from "react";
import { useTranslation } from "react-i18next";
+import { Optional } from "utility-types";
import CollectionIcon from "~/components/CollectionIcon";
import Flex from "~/components/Flex";
import InputSelect from "~/components/InputSelect";
@@ -8,7 +9,9 @@ import { IconWrapper } from "~/components/Sidebar/components/SidebarLink";
import useStores from "~/hooks/useStores";
import useToasts from "~/hooks/useToasts";
-type DefaultCollectionInputSelectProps = {
+type DefaultCollectionInputSelectProps = Optional<
+ React.ComponentProps
+> & {
onSelectCollection: (collection: string) => void;
defaultCollectionId: string | null;
};
@@ -16,6 +19,7 @@ type DefaultCollectionInputSelectProps = {
const DefaultCollectionInputSelect = ({
onSelectCollection,
defaultCollectionId,
+ ...rest
}: DefaultCollectionInputSelectProps) => {
const { t } = useTranslation();
const { collections } = useStores();
@@ -88,14 +92,11 @@ const DefaultCollectionInputSelect = ({
return (
);
};
diff --git a/app/components/Dialogs.tsx b/app/components/Dialogs.tsx
index 57e42ddce7..8cf15fe4ed 100644
--- a/app/components/Dialogs.tsx
+++ b/app/components/Dialogs.tsx
@@ -22,6 +22,7 @@ function Dialogs() {
dialogs.closeModal(id)}
title={modal.title}
>
diff --git a/app/components/DocumentBreadcrumb.tsx b/app/components/DocumentBreadcrumb.tsx
index 46ac078483..167c6e1e5b 100644
--- a/app/components/DocumentBreadcrumb.tsx
+++ b/app/components/DocumentBreadcrumb.tsx
@@ -12,7 +12,6 @@ import { collectionUrl } from "~/utils/routeHelpers";
type Props = {
document: Document;
- children?: React.ReactNode;
onlyText?: boolean;
};
@@ -49,7 +48,11 @@ function useCategory(document: Document): MenuInternalLink | null {
return null;
}
-const DocumentBreadcrumb = ({ document, children, onlyText }: Props) => {
+const DocumentBreadcrumb: React.FC = ({
+ document,
+ children,
+ onlyText,
+}) => {
const { collections } = useStores();
const { t } = useTranslation();
const category = useCategory(document);
diff --git a/app/components/DocumentCard.tsx b/app/components/DocumentCard.tsx
index 2c89b96ec9..7fce7b7bb1 100644
--- a/app/components/DocumentCard.tsx
+++ b/app/components/DocumentCard.tsx
@@ -108,7 +108,7 @@ function DocumentCard(props: Props) {
{!isDragging && pin && (
-
+
diff --git a/app/components/DocumentHistory.tsx b/app/components/DocumentHistory.tsx
index 2fac71298c..2323d2b77c 100644
--- a/app/components/DocumentHistory.tsx
+++ b/app/components/DocumentHistory.tsx
@@ -72,6 +72,7 @@ function DocumentHistory() {
- {items.map((document) => (
-
- ))}
-
- );
-}
diff --git a/app/components/DocumentListItem.tsx b/app/components/DocumentListItem.tsx
index e8426cebb6..c5a9e3960e 100644
--- a/app/components/DocumentListItem.tsx
+++ b/app/components/DocumentListItem.tsx
@@ -3,6 +3,7 @@ import { PlusIcon } from "outline-icons";
import * as React from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router-dom";
+import { CompositeStateReturn, CompositeItem } from "reakit/Composite";
import styled, { css } from "styled-components";
import breakpoint from "styled-components-breakpoint";
import Document from "~/models/Document";
@@ -33,7 +34,8 @@ type Props = {
showPin?: boolean;
showDraft?: boolean;
showTemplate?: boolean;
-};
+} & CompositeStateReturn;
+
const SEARCH_RESULT_REGEX = /]*>(.*?)<\/b>/gi;
function replaceResultMarks(tag: string) {
@@ -61,6 +63,7 @@ function DocumentListItem(
showTemplate,
highlight,
context,
+ ...rest
} = props;
const queryIsInTitle =
!!highlight &&
@@ -71,9 +74,11 @@ function DocumentListItem(
const canCollection = usePolicy(document.collectionId);
return (
-
@@ -155,7 +161,7 @@ function DocumentListItem(
modal={false}
/>
-
+
);
}
@@ -196,6 +202,10 @@ const DocumentLink = styled(Link)<{
max-height: 50vh;
width: calc(100vw - 8px);
+ &:focus-visible {
+ outline: none;
+ }
+
${breakpoint("tablet")`
width: auto;
`};
diff --git a/app/components/DocumentMeta.tsx b/app/components/DocumentMeta.tsx
index c975705554..716ce06576 100644
--- a/app/components/DocumentMeta.tsx
+++ b/app/components/DocumentMeta.tsx
@@ -35,11 +35,10 @@ type Props = {
showLastViewed?: boolean;
showParentDocuments?: boolean;
document: Document;
- children?: React.ReactNode;
to?: string;
};
-function DocumentMeta({
+const DocumentMeta: React.FC = ({
showPublished,
showCollection,
showLastViewed,
@@ -48,7 +47,7 @@ function DocumentMeta({
children,
to,
...rest
-}: Props) {
+}) => {
const { t } = useTranslation();
const { collections } = useStores();
const user = useCurrentUser();
@@ -74,42 +73,61 @@ function DocumentMeta({
const collection = collections.get(document.collectionId);
const lastUpdatedByCurrentUser = user.id === updatedBy.id;
+ const userName = updatedBy.name;
let content;
if (deletedAt) {
content = (
- {t("deleted")}
+ {lastUpdatedByCurrentUser
+ ? t("You deleted")
+ : t("{{ userName }} deleted", { userName })}{" "}
+
);
} else if (archivedAt) {
content = (
- {t("archived")}
+ {lastUpdatedByCurrentUser
+ ? t("You archived")
+ : t("{{ userName }} archived", { userName })}{" "}
+
);
} else if (createdAt === updatedAt) {
content = (
- {t("created")}
+ {lastUpdatedByCurrentUser
+ ? t("You created")
+ : t("{{ userName }} created", { userName })}{" "}
+
);
} else if (publishedAt && (publishedAt === updatedAt || showPublished)) {
content = (
- {t("published")}
+ {lastUpdatedByCurrentUser
+ ? t("You published")
+ : t("{{ userName }} published", { userName })}{" "}
+
);
} else if (isDraft) {
content = (
- {t("saved")}
+ {lastUpdatedByCurrentUser
+ ? t("You saved")
+ : t("{{ userName }} saved", { userName })}{" "}
+
);
} else {
content = (
- {t("updated")}
+ {lastUpdatedByCurrentUser
+ ? t("You updated")
+ : t("{{ userName }} updated", { userName })}{" "}
+
);
}
@@ -144,7 +162,6 @@ function DocumentMeta({
return (
- {lastUpdatedByCurrentUser ? t("You") : updatedBy.name}
{to ? {content} : content}
{showCollection && collection && (
@@ -172,6 +189,6 @@ function DocumentMeta({
{children}
);
-}
+};
export default observer(DocumentMeta);
diff --git a/app/components/DocumentTemplatizeDialog.tsx b/app/components/DocumentTemplatizeDialog.tsx
new file mode 100644
index 0000000000..ad643f9744
--- /dev/null
+++ b/app/components/DocumentTemplatizeDialog.tsx
@@ -0,0 +1,52 @@
+import invariant from "invariant";
+import { observer } from "mobx-react";
+import * as React from "react";
+import { useTranslation, Trans } from "react-i18next";
+import { useHistory } from "react-router-dom";
+import ConfirmationDialog from "~/components/ConfirmationDialog";
+import useStores from "~/hooks/useStores";
+import useToasts from "~/hooks/useToasts";
+import { documentUrl } from "~/utils/routeHelpers";
+
+type Props = {
+ documentId: string;
+};
+
+function DocumentTemplatizeDialog({ documentId }: Props) {
+ const history = useHistory();
+ const { showToast } = useToasts();
+ const { t } = useTranslation();
+ const { documents } = useStores();
+ const document = documents.get(documentId);
+ invariant(document, "Document must exist");
+
+ const handleSubmit = React.useCallback(async () => {
+ const template = await document?.templatize();
+ if (template) {
+ history.push(documentUrl(template));
+ showToast(t("Template created, go ahead and customize it"), {
+ type: "info",
+ });
+ }
+ }, [document, showToast, history, t]);
+
+ return (
+
+ ,
+ }}
+ />
+
+ );
+}
+
+export default observer(DocumentTemplatizeDialog);
diff --git a/app/components/DocumentViews.tsx b/app/components/DocumentViews.tsx
index e77c205e13..62ec57d909 100644
--- a/app/components/DocumentViews.tsx
+++ b/app/components/DocumentViews.tsx
@@ -4,6 +4,7 @@ import { observer } from "mobx-react";
import * as React from "react";
import { useTranslation } from "react-i18next";
import Document from "~/models/Document";
+import User from "~/models/User";
import Avatar from "~/components/Avatar";
import ListItem from "~/components/List/Item";
import PaginatedList from "~/components/PaginatedList";
@@ -40,8 +41,9 @@ function DocumentViews({ document, isOpen }: Props) {
<>
{isOpen && (
{
+ renderItem={(item: User) => {
const view = documentViews.find((v) => v.user.id === item.id);
const isPresent = presentIds.includes(item.id);
const isEditing = editingIds.includes(item.id);
diff --git a/app/components/Editor.tsx b/app/components/Editor.tsx
index 22406cf6b4..db53763c08 100644
--- a/app/components/Editor.tsx
+++ b/app/components/Editor.tsx
@@ -1,17 +1,30 @@
+import { formatDistanceToNow } from "date-fns";
+import { deburr, sortBy } from "lodash";
+import { TextSelection } from "prosemirror-state";
import * as React from "react";
import { Optional } from "utility-types";
+import insertFiles from "@shared/editor/commands/insertFiles";
import embeds from "@shared/editor/embeds";
+import { supportedImageMimeTypes } from "@shared/utils/files";
+import getDataTransferFiles from "@shared/utils/getDataTransferFiles";
+import parseDocumentSlug from "@shared/utils/parseDocumentSlug";
import { isInternalUrl } from "@shared/utils/urls";
+import Document from "~/models/Document";
+import ClickablePadding from "~/components/ClickablePadding";
import ErrorBoundary from "~/components/ErrorBoundary";
-import { Props as EditorProps } from "~/editor";
+import HoverPreview from "~/components/HoverPreview";
+import type { Props as EditorProps, Editor as SharedEditor } from "~/editor";
import useDictionary from "~/hooks/useDictionary";
+import useStores from "~/hooks/useStores";
import useToasts from "~/hooks/useToasts";
+import { NotFoundError } from "~/utils/errors";
+import { uploadFile } from "~/utils/files";
import history from "~/utils/history";
import { isModKey } from "~/utils/keyboard";
-import { uploadFile } from "~/utils/uploadFile";
import { isHash } from "~/utils/urls";
+import DocumentBreadcrumb from "./DocumentBreadcrumb";
-const SharedEditor = React.lazy(
+const LazyLoadedEditor = React.lazy(
() =>
import(
/* webpackChunkName: "shared-editor" */
@@ -21,7 +34,13 @@ const SharedEditor = React.lazy(
export type Props = Optional<
EditorProps,
- "placeholder" | "defaultValue" | "onClickLink" | "embeds" | "dictionary"
+ | "placeholder"
+ | "defaultValue"
+ | "onClickLink"
+ | "embeds"
+ | "dictionary"
+ | "onShowToast"
+ | "extensions"
> & {
shareId?: string | undefined;
embedsDisabled?: boolean;
@@ -30,12 +49,78 @@ export type Props = Optional<
onPublish?: (event: React.MouseEvent) => any;
};
-function Editor(props: Props, ref: React.Ref) {
+function Editor(props: Props, ref: React.RefObject) {
const { id, shareId } = props;
+ const { documents } = useStores();
const { showToast } = useToasts();
const dictionary = useDictionary();
+ const [
+ activeLinkEvent,
+ setActiveLinkEvent,
+ ] = React.useState(null);
- const onUploadImage = React.useCallback(
+ const handleLinkActive = React.useCallback((event: MouseEvent) => {
+ setActiveLinkEvent(event);
+ return false;
+ }, []);
+
+ const handleLinkInactive = React.useCallback(() => {
+ setActiveLinkEvent(null);
+ }, []);
+
+ const handleSearchLink = React.useCallback(
+ async (term: string) => {
+ if (isInternalUrl(term)) {
+ // search for exact internal document
+ const slug = parseDocumentSlug(term);
+ if (!slug) {
+ return [];
+ }
+
+ try {
+ const document = await documents.fetch(slug);
+ const time = formatDistanceToNow(Date.parse(document.updatedAt), {
+ addSuffix: true,
+ });
+
+ return [
+ {
+ title: document.title,
+ subtitle: `Updated ${time}`,
+ url: document.url,
+ },
+ ];
+ } catch (error) {
+ // NotFoundError could not find document for slug
+ if (!(error instanceof NotFoundError)) {
+ throw error;
+ }
+ }
+ }
+
+ // default search for anything that doesn't look like a URL
+ const results = await documents.searchTitles(term);
+
+ return sortBy(
+ results.map((document: Document) => {
+ return {
+ title: document.title,
+ subtitle: ,
+ url: document.url,
+ };
+ }),
+ (document) =>
+ deburr(document.title)
+ .toLowerCase()
+ .startsWith(deburr(term).toLowerCase())
+ ? -1
+ : 1
+ );
+ },
+ [documents]
+ );
+
+ const onUploadFile = React.useCallback(
async (file: File) => {
const result = await uploadFile(file, {
documentId: id,
@@ -79,26 +164,90 @@ function Editor(props: Props, ref: React.Ref) {
[shareId]
);
- const onShowToast = React.useCallback(
- (message: string) => {
- showToast(message);
+ const focusAtEnd = React.useCallback(() => {
+ ref.current?.focusAtEnd();
+ }, [ref]);
+
+ const handleDrop = React.useCallback(
+ (event: React.DragEvent) => {
+ event.preventDefault();
+ event.stopPropagation();
+ const files = getDataTransferFiles(event);
+ const view = ref.current?.view;
+ if (!view) {
+ return;
+ }
+
+ // Insert all files as attachments if any of the files are not images.
+ const isAttachment = files.some(
+ (file) => !supportedImageMimeTypes.includes(file.type)
+ );
+
+ // Find a valid position at the end of the document
+ const pos = TextSelection.near(
+ view.state.doc.resolve(view.state.doc.nodeSize - 2)
+ ).from;
+
+ insertFiles(view, event, pos, files, {
+ uploadFile: onUploadFile,
+ onFileUploadStart: props.onFileUploadStart,
+ onFileUploadStop: props.onFileUploadStop,
+ onShowToast: showToast,
+ dictionary,
+ isAttachment,
+ });
},
- [showToast]
+ [
+ ref,
+ props.onFileUploadStart,
+ props.onFileUploadStop,
+ dictionary,
+ onUploadFile,
+ showToast,
+ ]
+ );
+
+ // see: https://stackoverflow.com/a/50233827/192065
+ const handleDragOver = React.useCallback(
+ (event: React.DragEvent) => {
+ event.stopPropagation();
+ event.preventDefault();
+ },
+ []
);
return (
-
+ <>
+
+ {props.grow && !props.readOnly && (
+
+ )}
+ {activeLinkEvent && !shareId && (
+
+ )}
+ >
);
}
diff --git a/app/components/ErrorBoundary.tsx b/app/components/ErrorBoundary.tsx
index 286711bc2a..6445c4fa98 100644
--- a/app/components/ErrorBoundary.tsx
+++ b/app/components/ErrorBoundary.tsx
@@ -1,4 +1,3 @@
-import * as Sentry from "@sentry/react";
import { observable } from "mobx";
import { observer } from "mobx-react";
import * as React from "react";
@@ -10,9 +9,10 @@ import CenteredContent from "~/components/CenteredContent";
import PageTitle from "~/components/PageTitle";
import Text from "~/components/Text";
import env from "~/env";
+import isHosted from "~/utils/isHosted";
+import Logger from "~/utils/logger";
type Props = WithTranslation & {
- children: React.ReactNode;
reloadOnChunkMissing?: boolean;
};
@@ -26,7 +26,6 @@ class ErrorBoundary extends React.Component {
componentDidCatch(error: Error) {
this.error = error;
- console.error(error);
if (
this.props.reloadOnChunkMissing &&
@@ -40,9 +39,7 @@ class ErrorBoundary extends React.Component {
return;
}
- if (env.SENTRY_DSN) {
- Sentry.captureException(error);
- }
+ Logger.error("ErrorBoundary", error);
}
handleReload = () => {
@@ -62,7 +59,7 @@ class ErrorBoundary extends React.Component {
if (this.error) {
const error = this.error;
- const isReported = !!env.SENTRY_DSN && env.DEPLOYMENT === "hosted";
+ const isReported = !!env.SENTRY_DSN && isHosted;
const isChunkError = this.error.message.match(/chunk/);
if (isChunkError) {
diff --git a/app/components/EventBoundary.tsx b/app/components/EventBoundary.tsx
index 41ae1878c0..5eb0c67229 100644
--- a/app/components/EventBoundary.tsx
+++ b/app/components/EventBoundary.tsx
@@ -1,11 +1,10 @@
import * as React from "react";
type Props = {
- children: React.ReactNode;
className?: string;
};
-export default function EventBoundary({ children, className }: Props) {
+const EventBoundary: React.FC = ({ children, className }) => {
const handleClick = React.useCallback((event: React.SyntheticEvent) => {
event.preventDefault();
event.stopPropagation();
@@ -16,4 +15,6 @@ export default function EventBoundary({ children, className }: Props) {
{children}
);
-}
+};
+
+export default EventBoundary;
diff --git a/app/components/EventListItem.tsx b/app/components/EventListItem.tsx
index 99a6e84169..43c9b0d662 100644
--- a/app/components/EventListItem.tsx
+++ b/app/components/EventListItem.tsx
@@ -9,10 +9,14 @@ import {
import * as React from "react";
import { useTranslation } from "react-i18next";
import { useLocation } from "react-router-dom";
-import styled from "styled-components";
+import { CompositeStateReturn } from "reakit/Composite";
+import styled, { css } from "styled-components";
import Document from "~/models/Document";
import Event from "~/models/Event";
import Avatar from "~/components/Avatar";
+import CompositeItem, {
+ Props as ItemProps,
+} from "~/components/List/CompositeItem";
import Item, { Actions } from "~/components/List/Item";
import Time from "~/components/Time";
import usePolicy from "~/hooks/usePolicy";
@@ -23,9 +27,9 @@ type Props = {
document: Document;
event: Event;
latest?: boolean;
-};
+} & CompositeStateReturn;
-const EventListItem = ({ event, latest, document }: Props) => {
+const EventListItem = ({ event, latest, document, ...rest }: Props) => {
const { t } = useTranslation();
const location = useLocation();
const can = usePolicy(document.id);
@@ -35,6 +39,13 @@ const EventListItem = ({ event, latest, document }: Props) => {
const isRevision = event.name === "revisions.create";
let meta, icon, to;
+ const ref = React.useRef(null);
+ // the time component tends to steal focus when clicked
+ // ...so forward the focus back to the parent item
+ const handleTimeClick = React.useCallback(() => {
+ ref.current?.focus();
+ }, [ref]);
+
switch (event.name) {
case "revisions.create":
case "documents.latest_version": {
@@ -89,11 +100,15 @@ const EventListItem = ({ event, latest, document }: Props) => {
const isActive = location.pathname === to;
+ if (document.isDeleted) {
+ to = undefined;
+ }
+
return (
- {
format="MMM do, h:mm a"
relative={false}
addSuffix
+ onClick={handleTimeClick}
/>
}
image={}
@@ -115,10 +131,22 @@ const EventListItem = ({ event, latest, document }: Props) => {
) : undefined
}
+ ref={ref}
+ {...rest}
/>
);
};
+const BaseItem = React.forwardRef(
+ ({ to, ...rest }: ItemProps, ref?: React.Ref) => {
+ if (to) {
+ return ;
+ }
+
+ return ;
+ }
+);
+
const Subtitle = styled.span`
svg {
margin: -3px;
@@ -126,7 +154,7 @@ const Subtitle = styled.span`
}
`;
-const ListItem = styled(Item)`
+const ItemStyle = css`
border: 0;
position: relative;
margin: 8px;
@@ -172,4 +200,12 @@ const ListItem = styled(Item)`
}
`;
+const ListItem = styled(Item)`
+ ${ItemStyle}
+`;
+
+const CompositeListItem = styled(CompositeItem)`
+ ${ItemStyle}
+`;
+
export default EventListItem;
diff --git a/app/components/Flex.tsx b/app/components/Flex.tsx
index f61e01b52d..ba3afef955 100644
--- a/app/components/Flex.tsx
+++ b/app/components/Flex.tsx
@@ -1,18 +1,9 @@
+import { CSSProperties } from "react";
import styled from "styled-components";
-type JustifyValues =
- | "center"
- | "space-around"
- | "space-between"
- | "flex-start"
- | "flex-end";
+type JustifyValues = CSSProperties["justifyContent"];
-type AlignValues =
- | "stretch"
- | "center"
- | "baseline"
- | "flex-start"
- | "flex-end";
+type AlignValues = CSSProperties["alignItems"];
const Flex = styled.div<{
auto?: boolean;
diff --git a/app/components/Guide.tsx b/app/components/Guide.tsx
index 9d2727ab05..4f90ddd68c 100644
--- a/app/components/Guide.tsx
+++ b/app/components/Guide.tsx
@@ -1,24 +1,23 @@
-import { observer } from "mobx-react";
import * as React from "react";
import { Dialog, DialogBackdrop, useDialogState } from "reakit/Dialog";
import styled from "styled-components";
+import { depths } from "@shared/styles";
import Scrollable from "~/components/Scrollable";
import usePrevious from "~/hooks/usePrevious";
type Props = {
- children?: React.ReactNode;
isOpen: boolean;
title?: string;
onRequestClose: () => void;
};
-const Guide = ({
+const Guide: React.FC = ({
children,
isOpen,
title = "Untitled",
onRequestClose,
...rest
-}: Props) => {
+}) => {
const dialog = useDialogState({
animated: 250,
});
@@ -73,7 +72,7 @@ const Backdrop = styled.div`
right: 0;
bottom: 0;
background-color: ${(props) => props.theme.backdrop} !important;
- z-index: ${(props) => props.theme.depths.modalOverlay};
+ z-index: ${depths.modalOverlay};
transition: opacity 200ms ease-in-out;
opacity: 0;
@@ -88,7 +87,7 @@ const Scene = styled.div`
right: 0;
bottom: 0;
margin: 12px;
- z-index: ${(props) => props.theme.depths.modal};
+ z-index: ${depths.modal};
display: flex;
justify-content: center;
align-items: flex-start;
@@ -112,4 +111,4 @@ const Content = styled(Scrollable)`
padding: 16px;
`;
-export default observer(Guide);
+export default Guide;
diff --git a/app/components/Header.tsx b/app/components/Header.tsx
index 4e980c0e2b..775813e686 100644
--- a/app/components/Header.tsx
+++ b/app/components/Header.tsx
@@ -5,9 +5,11 @@ import { transparentize } from "polished";
import * as React from "react";
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
+import { depths } from "@shared/styles";
import Button from "~/components/Button";
import Fade from "~/components/Fade";
import Flex from "~/components/Flex";
+import useEventListener from "~/hooks/useEventListener";
import useMobile from "~/hooks/useMobile";
import useStores from "~/hooks/useStores";
import { supportsPassiveListener } from "~/utils/browser";
@@ -28,19 +30,17 @@ function Header({ breadcrumb, title, actions, hasSidebar }: Props) {
const passThrough = !actions && !breadcrumb && !title;
const [isScrolled, setScrolled] = React.useState(false);
- const handleScroll = React.useCallback(
- throttle(() => setScrolled(window.scrollY > 75), 50),
+ const handleScroll = React.useMemo(
+ () => throttle(() => setScrolled(window.scrollY > 75), 50),
[]
);
- React.useEffect(() => {
- window.addEventListener(
- "scroll",
- handleScroll,
- supportsPassiveListener ? { passive: true } : false
- );
- return () => window.removeEventListener("scroll", handleScroll);
- }, [handleScroll]);
+ useEventListener(
+ "scroll",
+ handleScroll,
+ window,
+ supportsPassiveListener ? { passive: true } : { capture: false }
+ );
const handleClickTitle = React.useCallback(() => {
window.scrollTo({
@@ -100,7 +100,7 @@ const Actions = styled(Flex)`
const Wrapper = styled(Flex)<{ $passThrough?: boolean }>`
top: 0;
- z-index: ${(props) => props.theme.depths.header};
+ z-index: ${depths.header};
position: sticky;
background: ${(props) => props.theme.background};
diff --git a/app/components/Highlight.tsx b/app/components/Highlight.tsx
index 40761b17b3..efb2437143 100644
--- a/app/components/Highlight.tsx
+++ b/app/components/Highlight.tsx
@@ -1,3 +1,4 @@
+import { escapeRegExp } from "lodash";
import * as React from "react";
import replace from "string-replace-to-array";
import styled from "styled-components";
@@ -23,7 +24,7 @@ function Highlight({
regex = highlight;
} else {
regex = new RegExp(
- (highlight || "").replace(/[-\\^$*+?.()|[\]{}]/g, "\\$&"),
+ escapeRegExp(highlight || ""),
caseSensitive ? "g" : "gi"
);
}
@@ -41,10 +42,10 @@ function Highlight({
);
}
-const Mark = styled.mark`
+export const Mark = styled.mark`
background: ${(props) => props.theme.searchHighlight};
border-radius: 2px;
- padding: 0 4px;
+ padding: 0 2px;
`;
export default Highlight;
diff --git a/app/components/HoverPreview.tsx b/app/components/HoverPreview.tsx
index ab49c19489..67e12ab4ad 100644
--- a/app/components/HoverPreview.tsx
+++ b/app/components/HoverPreview.tsx
@@ -2,9 +2,11 @@ import { transparentize } from "polished";
import * as React from "react";
import { Portal } from "react-portal";
import styled from "styled-components";
+import { depths } from "@shared/styles";
import parseDocumentSlug from "@shared/utils/parseDocumentSlug";
-import { isInternalUrl } from "@shared/utils/urls";
+import { isExternalUrl } from "@shared/utils/urls";
import HoverPreviewDocument from "~/components/HoverPreviewDocument";
+import useMobile from "~/hooks/useMobile";
import useStores from "~/hooks/useStores";
import { fadeAndSlideDown } from "~/styles/animations";
@@ -123,8 +125,13 @@ function HoverPreviewInternal({ node, onClose }: Props) {
}
function HoverPreview({ node, ...rest }: Props) {
+ const isMobile = useMobile();
+ if (isMobile) {
+ return null;
+ }
+
// previews only work for internal doc links for now
- if (!isInternalUrl(node.href)) {
+ if (isExternalUrl(node.href)) {
return null;
}
@@ -150,7 +157,7 @@ const Margin = styled.div`
const CardContent = styled.div`
overflow: hidden;
- max-height: 350px;
+ max-height: 20em;
user-select: none;
`;
@@ -195,7 +202,7 @@ const Card = styled.div`
const Position = styled.div<{ fixed?: boolean; top?: number; left?: number }>`
margin-top: 10px;
position: ${({ fixed }) => (fixed ? "fixed" : "absolute")};
- z-index: ${(props) => props.theme.depths.hoverPreview};
+ z-index: ${depths.hoverPreview};
display: flex;
max-height: 75%;
diff --git a/app/components/Input.tsx b/app/components/Input.tsx
index e8135f6cd3..c73c8b1333 100644
--- a/app/components/Input.tsx
+++ b/app/components/Input.tsx
@@ -97,7 +97,7 @@ export const LabelText = styled.div`
display: inline-block;
`;
-export type Props = {
+export type Props = React.HTMLAttributes & {
type?: "text" | "email" | "checkbox" | "search" | "textarea";
value?: string;
label?: string;
@@ -119,6 +119,7 @@ export type Props = {
onChange?: (
ev: React.ChangeEvent
) => unknown;
+ innerRef?: React.RefObject;
onKeyDown?: (ev: React.KeyboardEvent) => unknown;
onFocus?: (ev: React.SyntheticEvent) => unknown;
onBlur?: (ev: React.SyntheticEvent) => unknown;
@@ -126,7 +127,7 @@ export type Props = {
@observer
class Input extends React.Component {
- input = React.createRef();
+ input = this.props.innerRef;
@observable
focused = false;
@@ -147,10 +148,6 @@ class Input extends React.Component {
}
};
- focus() {
- this.input.current?.focus();
- }
-
render() {
const {
type = "text",
diff --git a/app/components/InputSearch.tsx b/app/components/InputSearch.tsx
index 1a1fbdca78..a49c7f6487 100644
--- a/app/components/InputSearch.tsx
+++ b/app/components/InputSearch.tsx
@@ -2,7 +2,7 @@ import { SearchIcon } from "outline-icons";
import * as React from "react";
import { useTranslation } from "react-i18next";
import { useTheme } from "styled-components";
-import Input, { Props as InputProps } from "./Input";
+import Input, { Props as InputProps } from "~/components/Input";
type Props = InputProps & {
placeholder?: string;
@@ -11,7 +11,10 @@ type Props = InputProps & {
onKeyDown?: (event: React.KeyboardEvent) => unknown;
};
-export default function InputSearch(props: Props) {
+function InputSearch(
+ props: Props,
+ ref: React.RefObject
+) {
const { t } = useTranslation();
const theme = useTheme();
const [isFocused, setIsFocused] = React.useState(false);
@@ -39,7 +42,10 @@ export default function InputSearch(props: Props) {
onBlur={handleBlur}
margin={0}
labelHidden
+ innerRef={ref}
{...rest}
/>
);
}
+
+export default React.forwardRef(InputSearch);
diff --git a/app/components/InputSearchPage.tsx b/app/components/InputSearchPage.tsx
index 6fec91daf1..347dec37f0 100644
--- a/app/components/InputSearchPage.tsx
+++ b/app/components/InputSearchPage.tsx
@@ -8,7 +8,7 @@ import useBoolean from "~/hooks/useBoolean";
import useKeyDown from "~/hooks/useKeyDown";
import { isModKey } from "~/utils/keyboard";
import { searchPath } from "~/utils/routeHelpers";
-import Input from "./Input";
+import Input, { Outline } from "./Input";
type Props = {
source: string;
@@ -30,7 +30,7 @@ function InputSearchPage({
collectionId,
source,
}: Props) {
- const inputRef = React.useRef(null);
+ const inputRef = React.useRef(null);
const theme = useTheme();
const history = useHistory();
const { t } = useTranslation();
@@ -67,7 +67,7 @@ function InputSearchPage({
return (
{
disabled,
note,
icon,
+ ...rest
} = props;
const select = useSelectState({
@@ -128,7 +131,7 @@ const InputSelect = (props: Props) => {
wrappedLabel
))}
-