diff --git a/.babelrc b/.babelrc
index de6335c5e9..7fb6d8caf2 100644
--- a/.babelrc
+++ b/.babelrc
@@ -1,6 +1,11 @@
{
"presets": [
- "@babel/preset-react",
+ [
+ "@babel/preset-react",
+ {
+ "runtime": "automatic"
+ }
+ ],
"@babel/preset-env",
"@babel/preset-typescript"
],
@@ -60,4 +65,4 @@
]
}
}
-}
+}
\ No newline at end of file
diff --git a/.env.sample b/.env.sample
index 51046501da..49456ae74b 100644
--- a/.env.sample
+++ b/.env.sample
@@ -1,48 +1,80 @@
-# –––––––––––––––– REQUIRED ––––––––––––––––
-
NODE_ENV=production
-# Generate a hex-encoded 32-byte random key. You should use `openssl rand -hex 32`
-# in your terminal to generate a random value.
-SECRET_KEY=generate_a_new_key
-
-# Generate a unique random key. The format is not important but you could still use
-# `openssl rand -hex 32` in your terminal to produce this.
-UTILS_SECRET=generate_a_new_key
-
-# For production point these at your databases, in development the default
-# should work out of the box.
-DATABASE_URL=postgres://user:pass@postgres:5432/outline
-DATABASE_CONNECTION_POOL_MIN=
-DATABASE_CONNECTION_POOL_MAX=
-# Uncomment this to disable SSL for connecting to Postgres
-# PGSSLMODE=disable
-
-# For redis you can either specify an ioredis compatible url like this
-REDIS_URL=redis://redis:6379
-# or alternatively, if you would like to provide additional connection options,
-# use a base64 encoded JSON connection option object. Refer to the ioredis documentation
-# for a list of available options.
-# Example: Use Redis Sentinel for high availability
-# {"sentinels":[{"host":"sentinel-0","port":26379},{"host":"sentinel-1","port":26379}],"name":"mymaster"}
-# REDIS_URL=ioredis://eyJzZW50aW5lbHMiOlt7Imhvc3QiOiJzZW50aW5lbC0wIiwicG9ydCI6MjYzNzl9LHsiaG9zdCI6InNlbnRpbmVsLTEiLCJwb3J0IjoyNjM3OX1dLCJuYW1lIjoibXltYXN0ZXIifQ==
-
-# URL should point to the fully qualified, publicly accessible URL. If using a
-# proxy the port in URL and PORT may be different.
+# This URL should point to the fully qualified, publicly accessible, URL. If using a
+# proxy this will be the proxy's URL.
URL=
+
+# The port to expose the Outline server on, this should match what is configured
+# in your docker-compose.yml
PORT=3000
# See [documentation](docs/SERVICES.md) on running a separate collaboration
# server, for normal operation this does not need to be set.
COLLABORATION_URL=
+# If using a Cloudfront/Cloudflare distribution or similar it can be set below.
+# This will cause paths to javascript, stylesheets, and images to be updated to
+# the hostname defined in CDN_URL. In your CDN configuration the origin server
+# should be set to the same as URL.
+CDN_URL=
+
+# How many processes should be spawned. As a reasonable rule divide your servers
+# available memory by 512 for a rough estimate
+WEB_CONCURRENCY=1
+
+# Generate a hex-encoded 32-byte random key. Use `openssl rand -hex 32` in your
+# terminal to generate a random value.
+SECRET_KEY=generate_a_new_key
+
+# Generate a unique random key. The format is not important but you could still use
+# `openssl rand -hex 32` in your terminal to generate a random value.
+UTILS_SECRET=generate_a_new_key
+
+# The default interface language. See translate.getoutline.com for a list of
+# available language codes and their rough percentage translated.
+DEFAULT_LANGUAGE=en_US
+
+
+# ––––––––––––––––––––––––––––––––––––––
+# ––––––––––––– DATABASE –––––––––––––
+# ––––––––––––––––––––––––––––––––––––––
+
+# The database URL for your production database, including username, password, and database name.
+DATABASE_URL=postgres://user:pass@postgres:5432/outline
+
+# The in-memory database pool per-process settings. Ensure that the pool size that will not exceed
+# the maximum number of connections allowed by your database. Defaults to 0 and 5.
+DATABASE_CONNECTION_POOL_MIN=
+DATABASE_CONNECTION_POOL_MAX=
+
+# Uncomment this line if you will not use SSL for connecting to Postgres. This is acceptable
+# if the database and the application are on the same machine.
+# PGSSLMODE=disable
+
+
+# ––––––––––––––––––––––––––––––––––––––
+# –––––––––––––– REDIS –––––––––––––––
+# ––––––––––––––––––––––––––––––––––––––
+
+# The Redis URL for your environment you can either specify an ioredis compatible url or a Base64
+# encoded configuration object.
+# DOCS: https://docs.getoutline.com/s/hosting/doc/redis-LGM4BFXYp4
+REDIS_URL=redis://redis:6379
+
+
+# ––––––––––––––––––––––––––––––––––––––
+# ––––––––––– FILE STORAGE –––––––––––
+# ––––––––––––––––––––––––––––––––––––––
+
# Specify what storage system to use. Possible value is one of "s3" or "local".
-# For "local", the avatar images and document attachments will be saved on local disk.
+# For "local" images and document attachments will be saved on local disk, for "s3" they
+# will be stored in an S3-compatible network store.
+# DOCS: https://docs.getoutline.com/s/hosting/doc/file-storage-N4M0T6Ypu7
FILE_STORAGE=local
# If "local" is configured for FILE_STORAGE above, then this sets the parent directory under
-# which all attachments/images go. Make sure that the process has permissions to create
-# this path and also to write files to it.
+# which all attachments/images are stored. Make sure that the process has permissions to
+# create this path and also to write files to it.
FILE_STORAGE_LOCAL_ROOT_DIR=/var/lib/outline/data
# Maximum allowed size for the uploaded attachment.
@@ -56,8 +88,8 @@ FILE_STORAGE_IMPORT_MAX_SIZE=
# and the files are temporary being automatically deleted after a period of time.
FILE_STORAGE_WORKSPACE_IMPORT_MAX_SIZE=
-# To support uploading of images for avatars and document attachments in a distributed
-# architecture an s3-compatible storage can be configured if FILE_STORAGE=s3 above.
+# To support uploading of images for avatars and document attachments in a distributed
+# architecture, an s3-compatible storage can be configured if FILE_STORAGE=s3 above.
AWS_ACCESS_KEY_ID=get_a_key_from_aws
AWS_SECRET_ACCESS_KEY=get_the_secret_of_above_key
AWS_REGION=xx-xxxx-x
@@ -67,38 +99,55 @@ AWS_S3_UPLOAD_BUCKET_NAME=bucket_name_here
AWS_S3_FORCE_PATH_STYLE=true
AWS_S3_ACL=private
-# –––––––––––––– AUTHENTICATION ––––––––––––––
+
+# ––––––––––––––––––––––––––––––––––––––
+# –––––––––––––––– SSL –––––––––––––––
+# ––––––––––––––––––––––––––––––––––––––
+
+# Base64 encoded private key and certificate for HTTPS termination. This is one
+# of three ways to configure SSL and can be left empty.
+# DOCS: https://docs.getoutline.com/s/hosting/doc/ssl-pzk7WO8d1n
+SSL_KEY=
+SSL_CERT=
+
+# Auto-redirect to https in production. The default is true but you may set to
+# false if you can be sure that SSL is terminated at an external loadbalancer.
+FORCE_HTTPS=true
+
+
+# ––––––––––––––––––––––––––––––––––––––
+# –––––––––– AUTHENTICATION ––––––––––
+# ––––––––––––––––––––––––––––––––––––––
# Third party signin credentials, at least ONE OF EITHER Google, Slack,
-# or Microsoft is required for a working installation or you'll have no sign-in
-# options.
+# Discord, or Microsoft is required for a working installation or you'll
+# have no sign-in options.
-# To configure Slack auth, you'll need to create an Application at
-# => https://api.slack.com/apps
-#
-# When configuring the Client ID, add a redirect URL under "OAuth & Permissions":
-# https:///auth/slack.callback
+# Slack sign-in provider
+# DOCS: https://docs.getoutline.com/s/hosting/doc/slack-sgMujR8J9J
SLACK_CLIENT_ID=get_a_key_from_slack
SLACK_CLIENT_SECRET=get_the_secret_of_above_key
-# To configure Google auth, you'll need to create an OAuth Client ID at
-# => https://console.cloud.google.com/apis/credentials
-#
-# When configuring the Client ID, add an Authorized redirect URI:
-# https:///auth/google.callback
+# Google sign-in provider
+# DOCS: https://docs.getoutline.com/s/hosting/doc/google-hOuvtCmTqQ
GOOGLE_CLIENT_ID=
GOOGLE_CLIENT_SECRET=
-# To configure Microsoft/Azure auth, you'll need to create an OAuth Client. See
-# the guide for details on setting up your Azure App:
-# => https://wiki.generaloutline.com/share/dfa77e56-d4d2-4b51-8ff8-84ea6608faa4
+# Microsoft Entra / Azure AD sign-in provider
+# DOCS: https://docs.getoutline.com/s/hosting/doc/microsoft-entra-UVz6jsIOcv
AZURE_CLIENT_ID=
AZURE_CLIENT_SECRET=
AZURE_RESOURCE_APP_ID=
-# To configure generic OIDC auth, you'll need some kind of identity provider.
-# See documentation for whichever IdP you use to acquire the following info:
-# Redirect URI is https:///auth/oidc.callback
+# Discord sign-in provider
+# DOCS: https://docs.getoutline.com/s/hosting/doc/discord-g4JdWFFub6
+DISCORD_CLIENT_ID=
+DISCORD_CLIENT_SECRET=
+DISCORD_SERVER_ID=
+DISCORD_SERVER_ROLES=
+
+# Generic OIDC provider
+# DOCS: https://docs.getoutline.com/s/hosting/doc/oidc-8CPBm6uC0I
OIDC_CLIENT_ID=
OIDC_CLIENT_SECRET=
OIDC_AUTH_URI=
@@ -116,75 +165,54 @@ OIDC_DISPLAY_NAME=OpenID Connect
# Space separated auth scopes.
OIDC_SCOPES=openid profile email
-# To configure the GitHub integration, you'll need to create a GitHub App at
-# => https://github.com/settings/apps
-#
-# When configuring the Client ID, add a redirect URL under "Permissions & events":
-# https:///api/github.callback
+
+# ––––––––––––––––––––––––––––––––––––––
+# –––––––––––––– EMAIL –––––––––––––––
+# ––––––––––––––––––––––––––––––––––––––
+
+# To support sending outgoing transactional emails such as "document updated" or
+# email sign-in you'll need to connect an SMTP server. Service can be configured
+# with any service from this list: https://community.nodemailer.com/2-0-0-beta/setup-smtp/well-known-services/
+# DOCS: https://docs.getoutline.com/s/hosting/doc/smtp-cqCJyZGMIB
+SMTP_SERVICE=
+SMTP_USERNAME=
+SMTP_PASSWORD=
+SMTP_FROM_EMAIL=
+
+
+# ––––––––––––––––––––––––––––––––––––––
+# –––––––––– RATE LIMITER ––––––––––––
+# ––––––––––––––––––––––––––––––––––––––
+
+# Whether the rate limiter is enabled or not
+RATE_LIMITER_ENABLED=true
+
+# Individual endpoints have hardcoded rate limits that are enabled
+# with the above setting, however this is a global rate limiter
+# across all requests
+RATE_LIMITER_REQUESTS=1000
+RATE_LIMITER_DURATION_WINDOW=60
+
+
+# ––––––––––––––––––––––––––––––––––––––
+# ––––––––––– INTEGRATIONS –––––––––––
+# ––––––––––––––––––––––––––––––––––––––
+
+# The GitHub integration allows previewing issue and pull request links
+# DOCS: https://docs.getoutline.com/s/hosting/doc/github-GchT3NNxI9
GITHUB_CLIENT_ID=
GITHUB_CLIENT_SECRET=
GITHUB_APP_NAME=
GITHUB_APP_ID=
GITHUB_APP_PRIVATE_KEY=
-# To configure Discord auth, you'll need to create a Discord Application at
-# => https://discord.com/developers/applications/
-#
-# When configuring the Client ID, add a redirect URL under "OAuth2":
-# https:///auth/discord.callback
-DISCORD_CLIENT_ID=
-DISCORD_CLIENT_SECRET=
-
-# DISCORD_SERVER_ID should be the ID of the Discord server that Outline is
-# integrated with.
-# Used to verify that the user is a member of the server as well as server
-# metadata such as nicknames, server icon and name.
-DISCORD_SERVER_ID=
-
-# DISCORD_SERVER_ROLES should be a comma separated list of role IDs that are
-# allowed to access Outline. If this is not set, all members of the server
-# will be allowed to access Outline.
-# DISCORD_SERVER_ID and DISCORD_SERVER_ROLES must be set together.
-DISCORD_SERVER_ROLES=
-
-# –––––––––––––––– OPTIONAL ––––––––––––––––
-
-# Base64 encoded private key and certificate for HTTPS termination. This is only
-# required if you do not use an external reverse proxy. See documentation:
-# https://wiki.generaloutline.com/share/1c922644-40d8-41fe-98f9-df2b67239d45
-SSL_KEY=
-SSL_CERT=
-
-# If using a Cloudfront/Cloudflare distribution or similar it can be set below.
-# This will cause paths to javascript, stylesheets, and images to be updated to
-# the hostname defined in CDN_URL. In your CDN configuration the origin server
-# should be set to the same as URL.
-CDN_URL=
-
-# Auto-redirect to https in production. The default is true but you may set to
-# false if you can be sure that SSL is terminated at an external loadbalancer.
-FORCE_HTTPS=true
-
-# Have the installation check for updates by sending anonymized statistics to
-# the maintainers
-ENABLE_UPDATES=true
-
-# How many processes should be spawned. As a reasonable rule divide your servers
-# available memory by 512 for a rough estimate
-WEB_CONCURRENCY=1
-
-# You can remove this line if your reverse proxy already logs incoming http
-# requests and this ends up being duplicative
-DEBUG=http
-
-# Configure lowest severity level for server logs. Should be one of
-# error, warn, info, http, verbose, debug and silly
-LOG_LEVEL=info
+# The Linear integration allows previewing issue links as rich mentions
+LINEAR_CLIENT_ID=
+LINEAR_CLIENT_SECRET=
# For a complete Slack integration with search and posting to channels the
-# following configs are also needed, some more details
-# => https://wiki.generaloutline.com/share/be25efd1-b3ef-4450-b8e5-c4a4fc11e02a
-#
+# following configs are also needed in addition to Slack authentication:
+# DOCS: https://docs.getoutline.com/s/hosting/doc/slack-G2mc8DOJHk
SLACK_VERIFICATION_TOKEN=your_token
SLACK_APP_ID=A0XXXXXXX
SLACK_MESSAGE_ACTIONS=true
@@ -194,33 +222,34 @@ SLACK_MESSAGE_ACTIONS=true
DROPBOX_APP_KEY=
# Optionally enable Sentry (sentry.io) to track errors and performance,
-# and optionally add a Sentry proxy tunnel for bypassing ad blockers in the UI:
-# https://docs.sentry.io/platforms/javascript/troubleshooting/#using-the-tunnel-option)
+# DOCS: https://docs.getoutline.com/s/hosting/doc/sentry-jxcFttcDl5
SENTRY_DSN=
SENTRY_TUNNEL=
-# To support sending outgoing transactional emails such as "document updated" or
-# "you've been invited" you'll need to provide authentication for an SMTP server
-SMTP_HOST=
-SMTP_PORT=
-SMTP_USERNAME=
-SMTP_PASSWORD=
-SMTP_FROM_EMAIL=
-SMTP_REPLY_EMAIL=
-SMTP_TLS_CIPHERS=
-SMTP_SECURE=true
+# Enable importing pages from a Notion workspace
+# DOCS: https://docs.getoutline.com/s/hosting/doc/notion-2v6g7WY3l3
+NOTION_CLIENT_ID=
+NOTION_CLIENT_SECRET=
-# The default interface language. See translate.getoutline.com for a list of
-# available language codes and their rough percentage translated.
-DEFAULT_LANGUAGE=en_US
-
-# Optionally enable rate limiter at application web server
-RATE_LIMITER_ENABLED=true
-
-# Configure default throttling parameters for rate limiter
-RATE_LIMITER_REQUESTS=1000
-RATE_LIMITER_DURATION_WINDOW=60
-
-# Iframely API config
+# The Iframely integration allows previews of third-party content within Outline.
+# For example, hovering over an external link will show a preview.
+# DOCS: https://docs.getoutline.com/s/hosting/doc/iframely-HwLF1EZ9mo
IFRAMELY_URL=
IFRAMELY_API_KEY=
+
+
+# ––––––––––––––––––––––––––––––––––––––
+# ––––––––––––– DEBUGGING ––––––––––––
+# ––––––––––––––––––––––––––––––––––––––
+
+# Have the installation check for updates by sending anonymized statistics to
+# the maintainers
+ENABLE_UPDATES=true
+
+# Debugging categories to enable – you can remove the default "http" value if
+# your proxy already logs incoming http requests and this ends up being duplicative
+DEBUG=http
+
+# Configure lowest severity level for server logs. Should be one of
+# error, warn, info, http, verbose, debug, or silly
+LOG_LEVEL=info
diff --git a/.eslintrc b/.eslintrc
index fcc8e7b8f7..458b0314d8 100644
--- a/.eslintrc
+++ b/.eslintrc
@@ -2,7 +2,9 @@
"parser": "@typescript-eslint/parser",
"parserOptions": {
"sourceType": "module",
- "extraFileExtensions": [".json"],
+ "extraFileExtensions": [
+ ".json"
+ ],
"project": "./tsconfig.json",
"ecmaFeatures": {
"jsx": true
@@ -17,6 +19,7 @@
],
"plugins": [
"es",
+ "react",
"@typescript-eslint",
"eslint-plugin-import",
"eslint-plugin-node",
@@ -24,24 +27,47 @@
"eslint-plugin-lodash"
],
"rules": {
+ "no-restricted-imports": [
+ "error",
+ {
+ "paths": [
+ {
+ "name": "reakit/Menu",
+ "importNames": [
+ "useMenuState"
+ ],
+ "message": "Do not use useMenuState from reakit/Menu. Use useMenuState instead."
+ }
+ ]
+ }
+ ],
"eqeqeq": 2,
"curly": 2,
"no-console": "error",
- "arrow-body-style": ["error", "as-needed"],
+ "arrow-body-style": [
+ "error",
+ "as-needed"
+ ],
"spaced-comment": "error",
"object-shorthand": "error",
"no-mixed-operators": "off",
"no-useless-escape": "off",
"no-shadow": "off",
"es/no-regexp-lookbehind-assertions": "error",
- "react/self-closing-comp": ["error", {
- "component": true,
- "html": true
- }],
+ "react/react-in-jsx-scope": "off",
+ "react/self-closing-comp": [
+ "error",
+ {
+ "component": true,
+ "html": true
+ }
+ ],
"@typescript-eslint/no-shadow": [
"warn",
{
- "allow": ["transaction"],
+ "allow": [
+ "transaction"
+ ],
"hoist": "all",
"ignoreTypeValueShadow": true
}
@@ -63,9 +89,25 @@
"ignoreRestSiblings": true
}
],
- "padding-line-between-statements": ["error", { "blankLine": "always", "prev": "*", "next": "export" }],
- "lines-between-class-members": ["error", "always", { "exceptAfterSingleLine": true }],
- "lodash/import-scope": ["warn", "method"],
+ "padding-line-between-statements": [
+ "error",
+ {
+ "blankLine": "always",
+ "prev": "*",
+ "next": "export"
+ }
+ ],
+ "lines-between-class-members": [
+ "error",
+ "always",
+ {
+ "exceptAfterSingleLine": true
+ }
+ ],
+ "lodash/import-scope": [
+ "error",
+ "method"
+ ],
"import/no-named-as-default": "off",
"import/no-named-as-default-member": "off",
"import/newline-after-import": 2,
@@ -134,10 +176,13 @@
"version": "detect"
},
"import/parsers": {
- "@typescript-eslint/parser": [".ts", ".tsx"]
+ "@typescript-eslint/parser": [
+ ".ts",
+ ".tsx"
+ ]
},
"import/resolver": {
"typescript": {}
}
}
-}
+}
\ No newline at end of file
diff --git a/.github/config.yml b/.github/config.yml
index 1e9936e096..f60d1faf0e 100644
--- a/.github/config.yml
+++ b/.github/config.yml
@@ -15,6 +15,8 @@ requestInfoDefaultTitles:
requestInfoLabelToAdd: more information needed
+requestInfoUserstoExclude:
+ - tommoor
# Configuration for new-pr-welcome - https://github.com/behaviorbot/new-pr-welcome
diff --git a/.github/workflows/auto_close_prs.yml b/.github/workflows/auto_close_prs.yml
new file mode 100644
index 0000000000..4266f5e711
--- /dev/null
+++ b/.github/workflows/auto_close_prs.yml
@@ -0,0 +1,59 @@
+name: Auto Close Unsigned PRs
+
+on:
+ schedule:
+ - cron: '0 0 * * *' # Run daily at midnight UTC
+
+jobs:
+ close-unsigned-prs:
+ runs-on: ubuntu-latest
+ permissions:
+ pull-requests: write
+ issues: write
+
+ steps:
+ - name: Close unsigned PRs
+ uses: actions/github-script@v6
+ with:
+ script: |
+ const now = new Date();
+ const TWO_WEEKS = 14 * 24 * 60 * 60 * 1000; // 14 days in milliseconds
+
+ const prs = await github.rest.pulls.list({
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ state: 'open'
+ });
+
+ for (const pr of prs.data) {
+ const prCreatedAt = new Date(pr.created_at);
+ const prAge = now - prCreatedAt;
+
+ if (prAge < TWO_WEEKS) continue;
+
+ const comments = await github.rest.issues.listComments({
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ issue_number: pr.number
+ });
+
+ const hasNotSignedComment = comments.data.some(comment =>
+ comment.body.toLowerCase().includes('https://cla-assistant.io/pull/badge/not_signed')
+ );
+
+ if (hasNotSignedComment) {
+ await github.rest.pulls.update({
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ pull_number: pr.number,
+ state: 'closed'
+ });
+
+ await github.rest.issues.createComment({
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ issue_number: pr.number,
+ body: 'This PR has been automatically closed because it has been open for more than 14 days and has not accepted the CLA.'
+ });
+ }
+ }
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index ff2eb0afcd..fad0be731a 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -11,7 +11,7 @@ env:
DATABASE_URL: postgres://postgres:password@localhost:5432/outline_test
REDIS_URL: redis://127.0.0.1:6379
URL: http://localhost:3000
- NODE_OPTIONS: --max-old-space-size=8000
+ NODE_OPTIONS: --max-old-space-size=8192
SECRET_KEY: F0E5AD933D7F6FD8F4DBB3E038C501C052DC0593C686D21ACB30AE205D2F634B
UTILS_SECRET: 123456
SLACK_VERIFICATION_TOKEN: 123456
@@ -63,6 +63,7 @@ jobs:
runs-on: ubuntu-latest
outputs:
server: ${{ steps.filter.outputs.server }}
+ app: ${{ steps.filter.outputs.app }}
steps:
- uses: actions/checkout@v4
- uses: dorny/paths-filter@v2
@@ -81,7 +82,7 @@ jobs:
- 'yarn.lock'
test:
- needs: build
+ needs: [build, changes]
if: ${{ needs.changes.outputs.app == 'true' }}
runs-on: ubuntu-latest
strategy:
@@ -143,8 +144,8 @@ jobs:
yarn test --maxWorkers=2 $TESTFILES
bundle-size:
- needs: [build, types]
- if: ${{ needs.changes.outputs.app == 'true' }}
+ needs: [build, types, changes]
+ if: ${{ needs.changes.outputs.app == 'true' && github.repository == 'outline/outline' }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@@ -161,3 +162,4 @@ jobs:
with:
key: ${{ secrets.RELATIVE_CI_KEY }}
token: ${{ secrets.GITHUB_TOKEN }}
+ webpackStatsFile: ./build/app/webpack-stats.json
diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml
index 0d58a68228..478a0aaaf9 100644
--- a/.github/workflows/docker.yml
+++ b/.github/workflows/docker.yml
@@ -3,25 +3,32 @@ name: Docker
on:
push:
tags:
- - 'v*'
+ - "v*"
env:
IMAGE_NAME: outlinewiki/outline
BASE_IMAGE_NAME: outlinewiki/outline-base
jobs:
- build-and-push:
- runs-on: ubuntu-latest
+ build-arm:
+ runs-on: ubicloud-standard-8-arm
steps:
- name: Checkout
uses: actions/checkout@v4
- - name: Set up QEMU
- uses: docker/setup-qemu-action@v3
-
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
+ - name: Docker base meta
+ id: base_meta
+ uses: docker/metadata-action@v5
+ with:
+ images: |
+ ${{ env.BASE_IMAGE_NAME }}
+ tags: |
+ type=semver,pattern={{version}}
+ type=semver,pattern={{major}}.{{minor}}
+
- name: Login to Docker Hub
uses: docker/login-action@v3
with:
@@ -29,24 +36,177 @@ jobs:
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Build and push base image
- uses: docker/build-push-action@v5
+ id: base_build
+ uses: docker/build-push-action@v6
with:
context: .
file: Dockerfile.base
- push: true
- tags: ${{ env.BASE_IMAGE_NAME }}:latest
- platforms: linux/amd64,linux/arm/v7,linux/arm64/v8,linux/ppc64le,linux/s390x
+ labels: ${{ steps.base_meta.outputs.labels }}
+ tags: ${{ env.BASE_IMAGE_NAME }}
+ outputs: type=image,push-by-digest=true,name-canonical=true,push=true
+ platforms: linux/arm64
+ cache-from: type=gha
+ cache-to: type=gha,mode=max
+ pull: false
- - name: Extract version
- id: version
- run: echo "VERSION=${GITHUB_REF#refs/tags/v}" >> $GITHUB_OUTPUT
+ - name: Docker meta
+ id: meta
+ uses: docker/metadata-action@v5
+ with:
+ images: |
+ ${{ env.IMAGE_NAME }}
+ tags: |
+ type=semver,pattern={{version}}
+ type=semver,pattern={{major}}.{{minor}}
- - name: Build and push main image
- uses: docker/build-push-action@v5
+ - name: Build and push
+ id: build
+ uses: docker/build-push-action@v6
with:
context: .
- push: true
- platforms: linux/amd64,linux/arm/v7,linux/arm64/v8,linux/ppc64le,linux/s390x
+ file: Dockerfile
+ labels: ${{ steps.meta.outputs.labels }}
+ tags: ${{ env.IMAGE_NAME }}
+ outputs: type=image,push-by-digest=true,name-canonical=true,push=true
+ platforms: linux/arm64
+ cache-from: type=gha
+ cache-to: type=gha,mode=max
+ pull: false
+ build-args: |
+ BASE_IMAGE=${{ env.BASE_IMAGE_NAME }}@${{ steps.base_build.outputs.digest }}
+
+ - name: Export digest
+ run: |
+ mkdir -p ${{ runner.temp }}/digests
+ digest="${{ steps.build.outputs.digest }}"
+ touch "${{ runner.temp }}/digests/${digest#sha256:}"
+
+ - name: Upload digest
+ uses: actions/upload-artifact@v4
+ with:
+ name: digests-linux-arm64
+ path: ${{ runner.temp }}/digests/*
+ if-no-files-found: error
+ retention-days: 1
+
+ build-amd:
+ runs-on: ubicloud-standard-8
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+
+ - name: Set up Docker Buildx
+ uses: docker/setup-buildx-action@v3
+
+ - name: Docker base meta
+ id: base_meta
+ uses: docker/metadata-action@v5
+ with:
+ images: |
+ ${{ env.BASE_IMAGE_NAME }}
tags: |
- ${{ env.IMAGE_NAME }}:latest
- ${{ env.IMAGE_NAME }}:${{ steps.version.outputs.VERSION }}
+ type=semver,pattern={{version}}
+ type=semver,pattern={{major}}.{{minor}}
+
+ - name: Login to Docker Hub
+ uses: docker/login-action@v3
+ with:
+ username: ${{ secrets.DOCKERHUB_USERNAME }}
+ password: ${{ secrets.DOCKERHUB_TOKEN }}
+
+ - name: Build and push base image
+ id: base_build
+ uses: docker/build-push-action@v6
+ with:
+ context: .
+ file: Dockerfile.base
+ labels: ${{ steps.base_meta.outputs.labels }}
+ tags: ${{ env.BASE_IMAGE_NAME }}
+ outputs: type=image,push-by-digest=true,name-canonical=true,push=true
+ platforms: linux/amd64
+ cache-from: type=gha
+ cache-to: type=gha,mode=max
+ pull: false
+
+ - name: Docker meta
+ id: meta
+ uses: docker/metadata-action@v5
+ with:
+ images: |
+ ${{ env.IMAGE_NAME }}
+ tags: |
+ type=semver,pattern={{version}}
+ type=semver,pattern={{major}}.{{minor}}
+
+ - name: Build and push
+ id: build
+ uses: docker/build-push-action@v6
+ with:
+ context: .
+ file: Dockerfile
+ labels: ${{ steps.meta.outputs.labels }}
+ tags: ${{ env.IMAGE_NAME }}
+ outputs: type=image,push-by-digest=true,name-canonical=true,push=true
+ platforms: linux/amd64
+ cache-from: type=gha
+ cache-to: type=gha,mode=max
+ pull: false
+ build-args: |
+ BASE_IMAGE=${{ env.BASE_IMAGE_NAME }}@${{ steps.base_build.outputs.digest }}
+
+ - name: Export digest
+ run: |
+ mkdir -p ${{ runner.temp }}/digests
+ digest="${{ steps.build.outputs.digest }}"
+ touch "${{ runner.temp }}/digests/${digest#sha256:}"
+
+ - name: Upload digest
+ uses: actions/upload-artifact@v4
+ with:
+ name: digests-linux-amd64
+ path: ${{ runner.temp }}/digests/*
+ if-no-files-found: error
+ retention-days: 1
+
+ merge:
+ runs-on: ubicloud-standard-8
+ needs:
+ - build-amd
+ - build-arm
+ steps:
+ - name: Download digests
+ uses: actions/download-artifact@v4
+ with:
+ path: ${{ runner.temp }}/digests
+ pattern: digests-*
+ merge-multiple: true
+
+ - name: Login to Docker Hub
+ uses: docker/login-action@v3
+ with:
+ username: ${{ secrets.DOCKERHUB_USERNAME }}
+ password: ${{ secrets.DOCKERHUB_TOKEN }}
+
+ - name: Set up Docker Buildx
+ uses: docker/setup-buildx-action@v3
+
+ - name: Docker meta
+ id: meta
+ uses: docker/metadata-action@v5
+ with:
+ images: ${{ env.IMAGE_NAME }}
+ tags: |
+ type=ref,event=branch
+ type=ref,event=pr
+ type=semver,pattern={{version}}
+ type=semver,pattern={{major}}.{{minor}}
+
+ - name: Create manifest list and push
+ working-directory: ${{ runner.temp }}/digests
+ run: |
+ docker buildx imagetools create $(jq -cr '.tags | map("-t " + .) | join(" ")' <<< "$DOCKER_METADATA_OUTPUT_JSON") \
+ $(printf '${{ env.IMAGE_NAME }}@sha256:%s ' *)
+
+ - name: Inspect image
+ run: |
+ docker buildx imagetools inspect ${{ env.IMAGE_NAME }}:${{ steps.meta.outputs.version }}
\ No newline at end of file
diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml
new file mode 100644
index 0000000000..b4f59218ee
--- /dev/null
+++ b/.github/workflows/lint.yml
@@ -0,0 +1,30 @@
+name: Lint
+
+on:
+ pull_request:
+ branches: [ main ]
+
+jobs:
+ run-linters:
+ if: startsWith(github.actor, 'codegen-sh')
+ name: Run linters
+ runs-on: ubuntu-latest
+
+ permissions:
+ # Give the default GITHUB_TOKEN write permission to commit and push the
+ # added or changed files to the repository.
+ contents: write
+
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 20.x
+ cache: 'yarn'
+ - run: yarn install --frozen-lockfile
+ - run: yarn lint --fix
+
+ - name: Commit changes
+ uses: stefanzweifel/git-auto-commit-action@v5
+ with:
+ commit_message: 'Applied automatic fixes'
diff --git a/.jestconfig.json b/.jestconfig.json
index c63342864f..c45e43e75e 100644
--- a/.jestconfig.json
+++ b/.jestconfig.json
@@ -14,8 +14,7 @@
"setupFilesAfterEnv": ["/server/test/setup.ts"],
"globalSetup": "/server/test/globalSetup.js",
"globalTeardown": "/server/test/globalTeardown.js",
- "testEnvironment": "node",
- "testTimeout": 10000
+ "testEnvironment": "node"
},
{
"displayName": "app",
diff --git a/Dockerfile b/Dockerfile
index a0393b6b93..fcc6d08168 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -1,5 +1,6 @@
ARG APP_PATH=/opt/outline
-FROM outlinewiki/outline-base AS base
+ARG BASE_IMAGE=outlinewiki/outline-base
+FROM ${BASE_IMAGE} AS base
ARG APP_PATH
WORKDIR $APP_PATH
@@ -30,7 +31,7 @@ RUN addgroup --gid 1001 nodejs && \
adduser --uid 1001 --ingroup nodejs nodejs && \
chown -R nodejs:nodejs $APP_PATH/build && \
mkdir -p /var/lib/outline && \
- chown -R nodejs:nodejs /var/lib/outline
+ chown -R nodejs:nodejs /var/lib/outline
ENV FILE_STORAGE_LOCAL_ROOT_DIR=/var/lib/outline/data
RUN mkdir -p "$FILE_STORAGE_LOCAL_ROOT_DIR" && \
diff --git a/Dockerfile.base b/Dockerfile.base
index 13378f1caa..91f90f3c2a 100644
--- a/Dockerfile.base
+++ b/Dockerfile.base
@@ -1,11 +1,14 @@
ARG APP_PATH=/opt/outline
-FROM node:20-slim AS deps
+FROM node:20 AS deps
ARG APP_PATH
WORKDIR $APP_PATH
COPY ./package.json ./yarn.lock ./
COPY ./patches ./patches
+RUN apt-get update && apt-get install -y cmake
+ENV NODE_OPTIONS="--max-old-space-size=24000"
+
RUN yarn install --no-optional --frozen-lockfile --network-timeout 1000000 && \
yarn cache clean
diff --git a/LICENSE b/LICENSE
index 3eeb03aa9a..1a15000105 100644
--- a/LICENSE
+++ b/LICENSE
@@ -3,7 +3,7 @@ Business Source License 1.1
Parameters
Licensor: General Outline, Inc.
-Licensed Work: Outline 0.82.0
+Licensed Work: Outline 0.84.0
The Licensed Work is (c) 2025 General Outline, Inc.
Additional Use Grant: You may make use of the Licensed Work, provided that
you may not use the Licensed Work for a Document
@@ -15,7 +15,7 @@ Additional Use Grant: You may make use of the Licensed Work, provided that
Licensed Work by creating teams and documents
controlled by such third parties.
-Change Date: 2029-02-15
+Change Date: 2029-05-11
Change License: Apache License, Version 2.0
diff --git a/app.json b/app.json
index 32783bae09..447a183d29 100644
--- a/app.json
+++ b/app.json
@@ -171,6 +171,10 @@
"description": "smtp.example.com (optional)",
"required": false
},
+ "SMTP_SERVICE": {
+ "description": "Well-known SMTP service name for nodemailer (optional, e.g. 'gmail', 'SES')",
+ "required": false
+ },
"SMTP_PORT": {
"description": "1234 (optional)",
"required": false
diff --git a/app/.eslintrc b/app/.eslintrc
index fe6ddd8ce3..18bd1b9732 100644
--- a/app/.eslintrc
+++ b/app/.eslintrc
@@ -7,6 +7,9 @@
"plugins": [
"eslint-plugin-react-hooks"
],
+ "rules": {
+ "react/react-in-jsx-scope": "off"
+ },
"env": {
"jest": true,
"browser": true
diff --git a/app/actions/definitions/apiKeys.tsx b/app/actions/definitions/apiKeys.tsx
index 0bb9092e32..668d0debac 100644
--- a/app/actions/definitions/apiKeys.tsx
+++ b/app/actions/definitions/apiKeys.tsx
@@ -1,5 +1,4 @@
import { PlusIcon } from "outline-icons";
-import * as React from "react";
import stores from "~/stores";
import ApiKeyNew from "~/scenes/ApiKeyNew";
import { createAction } from "..";
diff --git a/app/actions/definitions/collections.tsx b/app/actions/definitions/collections.tsx
index b692ca1868..4a2da735ed 100644
--- a/app/actions/definitions/collections.tsx
+++ b/app/actions/definitions/collections.tsx
@@ -13,7 +13,6 @@ import {
UnstarredIcon,
UnsubscribeIcon,
} from "outline-icons";
-import * as React from "react";
import { toast } from "sonner";
import Collection from "~/models/Collection";
import { CollectionEdit } from "~/components/Collection/CollectionEdit";
diff --git a/app/actions/definitions/comments.tsx b/app/actions/definitions/comments.tsx
index f377374517..796934ba24 100644
--- a/app/actions/definitions/comments.tsx
+++ b/app/actions/definitions/comments.tsx
@@ -1,5 +1,4 @@
import { DoneIcon, SmileyIcon, TrashIcon } from "outline-icons";
-import * as React from "react";
import { toast } from "sonner";
import stores from "~/stores";
import Comment from "~/models/Comment";
diff --git a/app/actions/definitions/developer.tsx b/app/actions/definitions/developer.tsx
index af4f2dca2a..476b26cd03 100644
--- a/app/actions/definitions/developer.tsx
+++ b/app/actions/definitions/developer.tsx
@@ -7,7 +7,6 @@ import {
TrashIcon,
UserIcon,
} from "outline-icons";
-import * as React from "react";
import { toast } from "sonner";
import { createAction } from "~/actions";
import { DeveloperSection } from "~/actions/sections";
diff --git a/app/actions/definitions/documents.tsx b/app/actions/definitions/documents.tsx
index de48eff01d..c5fcf1ed1f 100644
--- a/app/actions/definitions/documents.tsx
+++ b/app/actions/definitions/documents.tsx
@@ -29,8 +29,8 @@ import {
PadlockIcon,
GlobeIcon,
LogoutIcon,
+ CaseSensitiveIcon,
} from "outline-icons";
-import * as React from "react";
import { toast } from "sonner";
import Icon from "@shared/components/Icon";
import {
@@ -505,6 +505,25 @@ export const copyDocumentAsMarkdown = createAction({
},
});
+export const copyDocumentAsPlainText = createAction({
+ name: ({ t }) => t("Copy as text"),
+ section: ActiveDocumentSection,
+ keywords: "clipboard",
+ icon: ,
+ iconInContextMenu: false,
+ visible: ({ activeDocumentId, stores }) =>
+ !!activeDocumentId && stores.policies.abilities(activeDocumentId).download,
+ perform: ({ stores, activeDocumentId, t }) => {
+ const document = activeDocumentId
+ ? stores.documents.get(activeDocumentId)
+ : undefined;
+ if (document) {
+ copy(document.toPlainText());
+ toast.success(t("Text copied to clipboard"));
+ }
+ },
+});
+
export const copyDocumentShareLink = createAction({
name: ({ t }) => t("Copy public link"),
section: ActiveDocumentSection,
@@ -550,7 +569,12 @@ export const copyDocument = createAction({
section: ActiveDocumentSection,
icon: ,
keywords: "clipboard",
- children: [copyDocumentLink, copyDocumentShareLink, copyDocumentAsMarkdown],
+ children: [
+ copyDocumentLink,
+ copyDocumentShareLink,
+ copyDocumentAsMarkdown,
+ copyDocumentAsPlainText,
+ ],
});
export const duplicateDocument = createAction({
@@ -721,7 +745,7 @@ export const importDocument = createAction({
return false;
},
- perform: ({ activeCollectionId, activeDocumentId, stores }) => {
+ perform: ({ activeDocumentId, activeCollectionId, stores }) => {
const { documents } = stores;
const input = document.createElement("input");
input.type = "file";
@@ -1042,12 +1066,17 @@ export const openDocumentComments = createAction({
analyticsName: "Open comments",
section: ActiveDocumentSection,
icon: ,
- visible: ({ activeDocumentId, stores }) => {
+ visible: ({ activeCollectionId, activeDocumentId, stores }) => {
const can = stores.policies.abilities(activeDocumentId ?? "");
+ const collection = activeCollectionId
+ ? stores.collections.get(activeCollectionId)
+ : undefined;
+
return (
!!activeDocumentId &&
can.comment &&
- !!stores.auth.team?.getPreference(TeamPreference.Commenting)
+ (collection?.canCreateComment ??
+ !!stores.auth.team?.getPreference(TeamPreference.Commenting))
);
},
perform: ({ activeDocumentId, stores }) => {
@@ -1185,6 +1214,7 @@ export const rootDocumentActions = [
copyDocumentLink,
copyDocumentShareLink,
copyDocumentAsMarkdown,
+ copyDocumentAsPlainText,
starDocument,
unstarDocument,
publishDocument,
diff --git a/app/actions/definitions/navigation.tsx b/app/actions/definitions/navigation.tsx
index a25801f0a7..165c5c18b9 100644
--- a/app/actions/definitions/navigation.tsx
+++ b/app/actions/definitions/navigation.tsx
@@ -13,7 +13,6 @@ import {
ShapesIcon,
DraftsIcon,
} from "outline-icons";
-import * as React from "react";
import { UrlHelper } from "@shared/utils/UrlHelper";
import { isMac } from "@shared/utils/browser";
import stores from "~/stores";
diff --git a/app/actions/definitions/notifications.tsx b/app/actions/definitions/notifications.tsx
index fa674d5f5b..d0de1d0750 100644
--- a/app/actions/definitions/notifications.tsx
+++ b/app/actions/definitions/notifications.tsx
@@ -1,5 +1,4 @@
import { ArchiveIcon, MarkAsReadIcon } from "outline-icons";
-import * as React from "react";
import { createAction } from "..";
import { NotificationSection } from "../sections";
diff --git a/app/actions/definitions/oauthClients.tsx b/app/actions/definitions/oauthClients.tsx
new file mode 100644
index 0000000000..aa2b7a1a44
--- /dev/null
+++ b/app/actions/definitions/oauthClients.tsx
@@ -0,0 +1,24 @@
+import { PlusIcon } from "outline-icons";
+import stores from "~/stores";
+import { OAuthClientNew } from "~/components/OAuthClient/OAuthClientNew";
+import { createAction } from "..";
+import { SettingsSection } from "../sections";
+
+export const createOAuthClient = createAction({
+ name: ({ t }) => t("New App"),
+ analyticsName: "New App",
+ section: SettingsSection,
+ icon: ,
+ keywords: "create",
+ visible: () =>
+ stores.policies.abilities(stores.auth.team?.id || "").createOAuthClient,
+ perform: ({ t, event }) => {
+ event?.preventDefault();
+ event?.stopPropagation();
+
+ stores.dialogs.openModal({
+ title: t("New Application"),
+ content: ,
+ });
+ },
+});
diff --git a/app/actions/definitions/revisions.tsx b/app/actions/definitions/revisions.tsx
index 9b91c007d8..c79497b33c 100644
--- a/app/actions/definitions/revisions.tsx
+++ b/app/actions/definitions/revisions.tsx
@@ -1,6 +1,5 @@
import copy from "copy-to-clipboard";
-import { LinkIcon, RestoreIcon } from "outline-icons";
-import * as React from "react";
+import { LinkIcon, RestoreIcon, TrashIcon } from "outline-icons";
import { matchPath } from "react-router-dom";
import { toast } from "sonner";
import stores from "~/stores";
@@ -13,7 +12,7 @@ import {
} from "~/utils/routeHelpers";
export const restoreRevision = createAction({
- name: ({ t }) => t("Restore revision"),
+ name: ({ t }) => t("Restore"),
analyticsName: "Restore revision",
icon: ,
section: RevisionSection,
@@ -42,6 +41,38 @@ export const restoreRevision = createAction({
},
});
+export const deleteRevision = createAction({
+ name: ({ t }) => t("Delete"),
+ analyticsName: "Delete revision",
+ icon: ,
+ section: RevisionSection,
+ dangerous: true,
+ visible: ({ activeDocumentId }) =>
+ !!activeDocumentId && stores.policies.abilities(activeDocumentId).update,
+ perform: async ({ t, event, location, activeDocumentId }) => {
+ event?.preventDefault();
+ if (!activeDocumentId) {
+ return;
+ }
+
+ const document = stores.documents.get(activeDocumentId);
+ if (!document) {
+ return;
+ }
+
+ const match = matchPath<{ revisionId: string }>(location.pathname, {
+ path: matchDocumentHistory,
+ });
+ const revisionId = match?.params.revisionId;
+ if (revisionId) {
+ const revision = stores.revisions.get(revisionId);
+ await revision?.delete();
+ toast.success(t("This version of the document was deleted"));
+ history.push(documentHistoryPath(document));
+ }
+ },
+});
+
export const copyLinkToRevision = createAction({
name: ({ t }) => t("Copy link"),
analyticsName: "Copy link to revision",
diff --git a/app/actions/definitions/settings.tsx b/app/actions/definitions/settings.tsx
index fa2b7cf753..6db3c67ccc 100644
--- a/app/actions/definitions/settings.tsx
+++ b/app/actions/definitions/settings.tsx
@@ -1,5 +1,4 @@
import { SunIcon, MoonIcon, BrowserIcon } from "outline-icons";
-import * as React from "react";
import stores from "~/stores";
import { Theme } from "~/stores/UiStore";
import { createAction } from "~/actions";
diff --git a/app/actions/definitions/teams.tsx b/app/actions/definitions/teams.tsx
index a9847551d7..0c827777bd 100644
--- a/app/actions/definitions/teams.tsx
+++ b/app/actions/definitions/teams.tsx
@@ -1,5 +1,4 @@
import { ArrowIcon, PlusIcon } from "outline-icons";
-import * as React from "react";
import styled from "styled-components";
import { stringToColor } from "@shared/utils/color";
import RootStore from "~/stores/RootStore";
@@ -11,7 +10,7 @@ import { ActionContext } from "~/types";
import Desktop from "~/utils/Desktop";
import { TeamSection } from "../sections";
-export const createTeamsList = ({ stores }: { stores: RootStore }) =>
+export const switchTeamsList = ({ stores }: { stores: RootStore }) =>
stores.auth.availableTeams?.map((session) => ({
id: `switch-${session.id}`,
name: session.name,
@@ -44,7 +43,7 @@ export const switchTeam = createAction({
section: TeamSection,
visible: ({ stores }) =>
!!stores.auth.availableTeams && stores.auth.availableTeams?.length > 1,
- children: createTeamsList,
+ children: switchTeamsList,
});
export const createTeam = createAction({
diff --git a/app/actions/definitions/users.tsx b/app/actions/definitions/users.tsx
index abd83b89c0..2d78562ef4 100644
--- a/app/actions/definitions/users.tsx
+++ b/app/actions/definitions/users.tsx
@@ -1,5 +1,4 @@
import { PlusIcon } from "outline-icons";
-import * as React from "react";
import { UserRole } from "@shared/types";
import { UserRoleHelper } from "@shared/utils/UserRoleHelper";
import stores from "~/stores";
diff --git a/app/actions/index.ts b/app/actions/index.ts
index 2a97701c0a..a7076bb410 100644
--- a/app/actions/index.ts
+++ b/app/actions/index.ts
@@ -1,5 +1,4 @@
import flattenDeep from "lodash/flattenDeep";
-import * as React from "react";
import { toast } from "sonner";
import { Optional } from "utility-types";
import { v4 as uuidv4 } from "uuid";
diff --git a/app/components/Arrow.tsx b/app/components/Arrow.tsx
index 149feb4578..7ae98fe854 100644
--- a/app/components/Arrow.tsx
+++ b/app/components/Arrow.tsx
@@ -1,5 +1,3 @@
-import * as React from "react";
-
export default function Arrow() {
return (
{
// Watching for language changes here as this is the earliest point we might have the user
// available and means we can start loading translations faster
- React.useEffect(() => {
+ useEffect(() => {
void changeLanguage(language, i18n);
}, [i18n, language]);
@@ -33,7 +32,7 @@ const Authenticated = ({ children }: Props) => {
}
void auth.logout(true);
- return ;
+ return ;
};
export default observer(Authenticated);
diff --git a/app/components/AuthenticatedLayout.tsx b/app/components/AuthenticatedLayout.tsx
index c51a16b545..405400bbfa 100644
--- a/app/components/AuthenticatedLayout.tsx
+++ b/app/components/AuthenticatedLayout.tsx
@@ -1,7 +1,13 @@
import { AnimatePresence } from "framer-motion";
import { observer } from "mobx-react";
import * as React from "react";
-import { Switch, Route, useLocation, matchPath } from "react-router-dom";
+import {
+ Switch,
+ Route,
+ useLocation,
+ matchPath,
+ Redirect,
+} from "react-router-dom";
import { TeamPreference } from "@shared/types";
import ErrorSuspended from "~/scenes/Errors/ErrorSuspended";
import Layout from "~/components/Layout";
@@ -10,6 +16,7 @@ import Sidebar from "~/components/Sidebar";
import SidebarRight from "~/components/Sidebar/Right";
import SettingsSidebar from "~/components/Sidebar/Settings";
import useCurrentTeam from "~/hooks/useCurrentTeam";
+import { usePostLoginPath } from "~/hooks/useLastVisitedPath";
import usePolicy from "~/hooks/usePolicy";
import useStores from "~/hooks/useStores";
import history from "~/utils/history";
@@ -42,12 +49,13 @@ type Props = {
};
const AuthenticatedLayout: React.FC = ({ children }: Props) => {
- const { ui, auth } = useStores();
+ const { ui, auth, collections } = useStores();
const location = useLocation();
const layoutRef = React.useRef(null);
const can = usePolicy(ui.activeDocumentId);
const canCollection = usePolicy(ui.activeCollectionId);
const team = useCurrentTeam();
+ const [spendPostLoginPath] = usePostLoginPath();
const goToSearch = (ev: KeyboardEvent) => {
if (!ev.metaKey && !ev.ctrlKey) {
@@ -72,6 +80,11 @@ const AuthenticatedLayout: React.FC = ({ children }: Props) => {
return ;
}
+ const postLoginPath = spendPostLoginPath();
+ if (postLoginPath) {
+ return ;
+ }
+
const sidebar = (
@@ -95,7 +108,9 @@ const AuthenticatedLayout: React.FC = ({ children }: Props) => {
can.comment &&
ui.activeDocumentId &&
ui.commentsExpanded &&
- team.getPreference(TeamPreference.Commenting);
+ (ui.activeCollectionId
+ ? collections.get(ui.activeCollectionId)?.canCreateComment
+ : !!team.getPreference(TeamPreference.Commenting));
const sidebarRight = (
+
{src && !error ? (
-
+
) : model ? (
{model.initial}
@@ -61,19 +79,21 @@ Avatar.defaultProps = {
size: AvatarSize.Medium,
};
-const Relative = styled.div`
+const Relative = styled.div<{ $variant: AvatarVariant; $size: AvatarSize }>`
position: relative;
user-select: none;
flex-shrink: 0;
+ border-radius: ${(props) =>
+ props.$variant === AvatarVariant.Round ? "50%" : `${props.$size / 8}px`};
+ overflow: hidden;
+ width: ${(props) => props.$size}px;
+ height: ${(props) => props.$size}px;
`;
-const CircleImg = styled.img<{ size: number }>`
+const Image = styled.img<{ size: number }>`
display: block;
width: ${(props) => props.size}px;
height: ${(props) => props.size}px;
- border-radius: 50%;
- flex-shrink: 0;
- overflow: hidden;
`;
export default Avatar;
diff --git a/app/components/Avatar/AvatarWithPresence.tsx b/app/components/Avatar/AvatarWithPresence.tsx
index c6855afe8b..8151dc0fe3 100644
--- a/app/components/Avatar/AvatarWithPresence.tsx
+++ b/app/components/Avatar/AvatarWithPresence.tsx
@@ -7,17 +7,43 @@ import User from "~/models/User";
import Tooltip from "~/components/Tooltip";
import Avatar, { AvatarSize } from "./Avatar";
+/**
+ * Props for the AvatarWithPresence component
+ */
type Props = {
+ /** The user to display the avatar for */
user: User;
+ /** Whether the user is currently present in the document */
isPresent: boolean;
+ /** Whether the user is currently editing the document */
isEditing: boolean;
+ /** Whether the user is currently observing the document */
isObserving: boolean;
+ /** Whether this avatar represents the current user */
isCurrentUser: boolean;
+ /** Optional click handler for the avatar */
onClick?: React.MouseEventHandler;
+ /** Size of the avatar, defaults to AvatarSize.Large */
size?: AvatarSize;
+ /** Optional inline styles to apply to the avatar wrapper */
style?: React.CSSProperties;
};
+/**
+ * AvatarWithPresence component displays a user's avatar with visual indicators
+ * for their current status (present, editing, observing).
+ *
+ * The component shows different visual states:
+ * - Present users have full opacity
+ * - Non-present users have reduced opacity
+ * - Observing users have a colored border matching their user color
+ * - Hovering shows a colored border
+ *
+ * A tooltip displays the user's name and current status.
+ *
+ * @param props - Component properties
+ * @returns React component
+ */
function AvatarWithPresence({
onClick,
user,
@@ -64,16 +90,33 @@ function AvatarWithPresence({
);
}
+/**
+ * Centered container for tooltip content
+ */
const Centered = styled.div`
text-align: center;
`;
+/**
+ * Props for the AvatarPresence styled component
+ */
type AvatarWrapperProps = {
+ /** Whether the user is currently present */
$isPresent: boolean;
+ /** Whether the user is currently observing */
$isObserving: boolean;
+ /** The user's color for border highlighting */
$color: string;
};
+/**
+ * Styled component that wraps the Avatar and provides visual indicators
+ * for the user's presence status.
+ *
+ * - Adjusts opacity based on presence
+ * - Adds colored borders for observing users
+ * - Handles hover effects
+ */
const AvatarPresence = styled.div`
opacity: ${(props) => (props.$isPresent ? 1 : 0.5)};
transition: opacity 250ms ease-in-out;
diff --git a/app/components/Avatar/GroupAvatar.tsx b/app/components/Avatar/GroupAvatar.tsx
index 38aad5ada5..e6c403bbd4 100644
--- a/app/components/Avatar/GroupAvatar.tsx
+++ b/app/components/Avatar/GroupAvatar.tsx
@@ -1,5 +1,4 @@
import { GroupIcon } from "outline-icons";
-import * as React from "react";
import { useTheme } from "styled-components";
import Squircle from "@shared/components/Squircle";
import Group from "~/models/Group";
diff --git a/app/components/Avatar/Initials.tsx b/app/components/Avatar/Initials.tsx
index 775e380e0c..e6d51b9be6 100644
--- a/app/components/Avatar/Initials.tsx
+++ b/app/components/Avatar/Initials.tsx
@@ -13,7 +13,6 @@ const Initials = styled(Flex)<{
}>`
align-items: center;
justify-content: center;
- border-radius: 50%;
width: 100%;
height: 100%;
color: ${(props) =>
@@ -23,7 +22,6 @@ const Initials = styled(Flex)<{
background-color: ${(props) => props.color ?? props.theme.textTertiary};
width: ${(props) => props.size}px;
height: ${(props) => props.size}px;
- border-radius: 50%;
flex-shrink: 0;
// adjust font size down for each additional character
diff --git a/app/components/Avatar/index.ts b/app/components/Avatar/index.ts
index be77236300..41f2a72501 100644
--- a/app/components/Avatar/index.ts
+++ b/app/components/Avatar/index.ts
@@ -1,7 +1,7 @@
-import Avatar, { IAvatar, AvatarSize } from "./Avatar";
+import Avatar, { IAvatar, AvatarSize, AvatarVariant } from "./Avatar";
import AvatarWithPresence from "./AvatarWithPresence";
import { GroupAvatar } from "./GroupAvatar";
-export { Avatar, GroupAvatar, AvatarSize, AvatarWithPresence };
+export { Avatar, GroupAvatar, AvatarSize, AvatarVariant, AvatarWithPresence };
export type { IAvatar };
diff --git a/app/components/Branding.tsx b/app/components/Branding.tsx
index 554086e8b9..0199039e19 100644
--- a/app/components/Branding.tsx
+++ b/app/components/Branding.tsx
@@ -1,4 +1,3 @@
-import * as React from "react";
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { depths, s } from "@shared/styles";
diff --git a/app/components/ChangeLanguage.tsx b/app/components/ChangeLanguage.tsx
index c5f9650719..0a8395f1fd 100644
--- a/app/components/ChangeLanguage.tsx
+++ b/app/components/ChangeLanguage.tsx
@@ -1,4 +1,4 @@
-import * as React from "react";
+import { useEffect } from "react";
import { useTranslation } from "react-i18next";
import { changeLanguage } from "~/utils/language";
@@ -9,7 +9,7 @@ type Props = {
export default function ChangeLanguage({ locale }: Props) {
const { i18n } = useTranslation();
- React.useEffect(() => {
+ useEffect(() => {
void changeLanguage(locale, i18n);
}, [locale, i18n]);
diff --git a/app/components/CircularProgressBar.tsx b/app/components/CircularProgressBar.tsx
index 8c38a3f570..78d28f42af 100644
--- a/app/components/CircularProgressBar.tsx
+++ b/app/components/CircularProgressBar.tsx
@@ -1,4 +1,3 @@
-import React from "react";
import styled, { useTheme } from "styled-components";
const cleanPercentage = (percentage: number) => {
diff --git a/app/components/Collaborators.tsx b/app/components/Collaborators.tsx
index c420d37349..c87d1f4fbe 100644
--- a/app/components/Collaborators.tsx
+++ b/app/components/Collaborators.tsx
@@ -3,7 +3,7 @@ import isEqual from "lodash/isEqual";
import orderBy from "lodash/orderBy";
import uniq from "lodash/uniq";
import { observer } from "mobx-react";
-import * as React from "react";
+import { useState, useMemo, useEffect, useCallback } from "react";
import { useTranslation } from "react-i18next";
import { usePopoverState, PopoverDisclosure } from "reakit/Popover";
import Document from "~/models/Document";
@@ -31,58 +31,97 @@ function Collaborators(props: Props) {
const { t } = useTranslation();
const user = useCurrentUser();
const currentUserId = user?.id;
- const [requestedUserIds, setRequestedUserIds] = React.useState([]);
+ const [requestedUserIds, setRequestedUserIds] = useState([]);
const { users, presence, ui } = useStores();
const { document } = props;
+ const { observingUserId } = ui;
const documentPresence = presence.get(document.id);
const documentPresenceArray = documentPresence
? Array.from(documentPresence.values())
: [];
- const presentIds = documentPresenceArray.map((p) => p.userId);
- const editingIds = documentPresenceArray
- .filter((p) => p.isEditing)
- .map((p) => p.userId);
+ // Use Set for O(1) lookups and stable references
+ const presentIds = useMemo(
+ () => new Set(documentPresenceArray.map((p) => p.userId)),
+ [documentPresenceArray]
+ );
+ const editingIds = useMemo(
+ () =>
+ new Set(
+ documentPresenceArray.filter((p) => p.isEditing).map((p) => p.userId)
+ ),
+ [documentPresenceArray]
+ );
// ensure currently present via websocket are always ordered first
- const collaborators = React.useMemo(
+ // Memoize collaboratorIds as a Set for efficient lookup
+ const collaboratorIdsSet = useMemo(
+ () => new Set(document.collaboratorIds),
+ [document.collaboratorIds]
+ );
+ const collaborators = useMemo(
() =>
orderBy(
filter(
- users.orderedData,
+ users.all,
(u) =>
- (presentIds.includes(u.id) ||
- document.collaboratorIds.includes(u.id)) &&
+ (presentIds.has(u.id) || collaboratorIdsSet.has(u.id)) &&
!u.isSuspended
),
- [(u) => presentIds.includes(u.id), "id"],
+ [(u) => presentIds.has(u.id), "id"],
["asc", "asc"]
),
- [document.collaboratorIds, users.orderedData, presentIds]
+ [collaboratorIdsSet, users.all, presentIds]
);
// load any users we don't yet have in memory
- React.useEffect(() => {
- const ids = uniq([...document.collaboratorIds, ...presentIds])
- .filter((userId) => !users.get(userId))
- .sort();
+ // Memoize ids to avoid unnecessary effect executions
+ const missingUserIds = useMemo(
+ () =>
+ uniq([...document.collaboratorIds, ...Array.from(presentIds)])
+ .filter((userId) => !users.get(userId))
+ .sort(),
+ [document.collaboratorIds, presentIds, users]
+ );
- if (!isEqual(requestedUserIds, ids) && ids.length > 0) {
- setRequestedUserIds(ids);
- void users.fetchPage({ ids, limit: 100 });
+ useEffect(() => {
+ if (
+ !isEqual(requestedUserIds, missingUserIds) &&
+ missingUserIds.length > 0
+ ) {
+ setRequestedUserIds(missingUserIds);
+ void users.fetchPage({ ids: missingUserIds, limit: 100 });
}
- }, [document, users, presentIds, document.collaboratorIds, requestedUserIds]);
+ }, [missingUserIds, requestedUserIds, users]);
const popover = usePopoverState({
gutter: 0,
placement: "bottom-end",
});
- const renderAvatar = React.useCallback(
+ // Memoize onClick handler to avoid inline function creation
+ const handleAvatarClick = useCallback(
+ (
+ collaboratorId: string,
+ isPresent: boolean,
+ isObserving: boolean,
+ isObservable: boolean
+ ) =>
+ (ev: React.MouseEvent) => {
+ if (isObservable && isPresent) {
+ ev.preventDefault();
+ ev.stopPropagation();
+ ui.setObservingUser(isObserving ? undefined : collaboratorId);
+ }
+ },
+ [ui]
+ );
+
+ const renderAvatar = useCallback(
({ model: collaborator, ...rest }) => {
- const isPresent = presentIds.includes(collaborator.id);
- const isEditing = editingIds.includes(collaborator.id);
- const isObserving = ui.observingUserId === collaborator.id;
+ const isPresent = presentIds.has(collaborator.id);
+ const isEditing = editingIds.has(collaborator.id);
+ const isObserving = observingUserId === collaborator.id;
const isObservable = collaborator.id !== currentUserId;
return (
@@ -96,21 +135,18 @@ function Collaborators(props: Props) {
isCurrentUser={currentUserId === collaborator.id}
onClick={
isObservable
- ? (ev) => {
- if (isPresent) {
- ev.preventDefault();
- ev.stopPropagation();
- ui.setObservingUser(
- isObserving ? undefined : collaborator.id
- );
- }
- }
+ ? handleAvatarClick(
+ collaborator.id,
+ isPresent,
+ isObserving,
+ isObservable
+ )
: undefined
}
/>
);
},
- [presentIds, ui, currentUserId, editingIds]
+ [presentIds, editingIds, observingUserId, currentUserId, handleAvatarClick]
);
return (
@@ -133,7 +169,7 @@ function Collaborators(props: Props) {
)}
-
+ {popover.visible && }
>
);
diff --git a/app/components/Collection/CollectionEdit.tsx b/app/components/Collection/CollectionEdit.tsx
index 31dee8d7b4..10e840d588 100644
--- a/app/components/Collection/CollectionEdit.tsx
+++ b/app/components/Collection/CollectionEdit.tsx
@@ -1,5 +1,5 @@
import { observer } from "mobx-react";
-import * as React from "react";
+import { useCallback } from "react";
import { toast } from "sonner";
import useStores from "~/hooks/useStores";
import { CollectionForm, FormData } from "./CollectionForm";
@@ -16,7 +16,7 @@ export const CollectionEdit = observer(function CollectionEdit_({
const { collections } = useStores();
const collection = collections.get(collectionId);
- const handleSubmit = React.useCallback(
+ const handleSubmit = useCallback(
async (data: FormData) => {
try {
await collection?.save(data);
diff --git a/app/components/Collection/CollectionForm.tsx b/app/components/Collection/CollectionForm.tsx
index 8e308d0927..bcd36bb82e 100644
--- a/app/components/Collection/CollectionForm.tsx
+++ b/app/components/Collection/CollectionForm.tsx
@@ -1,11 +1,12 @@
+import uniq from "lodash/uniq";
import { observer } from "mobx-react";
-import * as React from "react";
+import { useMemo, useEffect, useCallback, Suspense } from "react";
import { Controller, useForm } from "react-hook-form";
import { Trans, useTranslation } from "react-i18next";
import styled from "styled-components";
import Icon from "@shared/components/Icon";
import { randomElement } from "@shared/random";
-import { CollectionPermission } from "@shared/types";
+import { CollectionPermission, TeamPreference } from "@shared/types";
import { IconLibrary } from "@shared/utils/IconLibrary";
import { colorPalette } from "@shared/utils/collections";
import { CollectionValidation } from "@shared/validations";
@@ -14,13 +15,15 @@ import Button from "~/components/Button";
import Flex from "~/components/Flex";
import Input from "~/components/Input";
import InputSelectPermission from "~/components/InputSelectPermission";
+import { createLazyComponent } from "~/components/LazyLoad";
import Switch from "~/components/Switch";
import Text from "~/components/Text";
import useBoolean from "~/hooks/useBoolean";
import useCurrentTeam from "~/hooks/useCurrentTeam";
+import useStores from "~/hooks/useStores";
import { EmptySelectValue } from "~/types";
-const IconPicker = React.lazy(() => import("~/components/IconPicker"));
+const IconPicker = createLazyComponent(() => import("~/components/IconPicker"));
export interface FormData {
name: string;
@@ -28,8 +31,29 @@ export interface FormData {
color: string | null;
sharing: boolean;
permission: CollectionPermission | undefined;
+ commenting?: boolean | null;
}
+const useIconColor = (collection?: Collection) => {
+ const { collections } = useStores();
+ const hasMultipleCollections = collections.orderedData.length > 1;
+ const collectionColors = uniq(
+ collections.orderedData.map((c) => c.color).filter(Boolean)
+ ) as string[];
+
+ const iconColor = useMemo(
+ () =>
+ collection?.color ??
+ // If all the existing collections have the same color, use that color,
+ // otherwise pick a random color from the palette
+ (hasMultipleCollections && collectionColors.length === 1
+ ? collectionColors[0]
+ : randomElement(colorPalette)),
+ [collection?.color]
+ );
+ return iconColor;
+};
+
export const CollectionForm = observer(function CollectionForm_({
handleSubmit,
collection,
@@ -42,11 +66,7 @@ export const CollectionForm = observer(function CollectionForm_({
const [hasOpenedIconPicker, setHasOpenedIconPicker] = useBoolean(false);
- const iconColor = React.useMemo(
- () => collection?.color ?? randomElement(colorPalette),
- [collection?.color]
- );
-
+ const iconColor = useIconColor(collection);
const fallbackIcon = ;
const {
@@ -64,13 +84,19 @@ export const CollectionForm = observer(function CollectionForm_({
icon: collection?.icon,
sharing: collection?.sharing ?? true,
permission: collection?.permission,
+ commenting: collection?.commenting ?? true,
color: iconColor,
},
});
const values = watch();
- React.useEffect(() => {
+ // Preload the IconPicker component on mount
+ useEffect(() => {
+ void IconPicker.preload();
+ }, []);
+
+ useEffect(() => {
// If the user hasn't picked an icon yet, go ahead and suggest one based on
// the name of the collection. It's the little things sometimes.
if (!hasOpenedIconPicker && !collection) {
@@ -83,11 +109,11 @@ export const CollectionForm = observer(function CollectionForm_({
}
}, [collection, hasOpenedIconPicker, setValue, values.name, values.icon]);
- React.useEffect(() => {
+ useEffect(() => {
setTimeout(() => setFocus("name", { shouldSelect: true }), 100);
}, [setFocus]);
- const handleIconChange = React.useCallback(
+ const handleIconChange = useCallback(
(icon: string, color: string | null) => {
if (icon !== values.icon) {
setFocus("name");
@@ -116,7 +142,7 @@ export const CollectionForm = observer(function CollectionForm_({
maxLength: CollectionValidation.maxNameLength,
})}
prefix={
-
+
-
+
}
autoComplete="off"
autoFocus
@@ -166,6 +192,15 @@ export const CollectionForm = observer(function CollectionForm_({
/>
)}
+ {team.getPreference(TeamPreference.Commenting) && (
+
+ )}
+
{
try {
const collection = await collections.save(data);
diff --git a/app/components/CollectionDeleteDialog.tsx b/app/components/CollectionDeleteDialog.tsx
index 7cab8ab978..d3b2d4df88 100644
--- a/app/components/CollectionDeleteDialog.tsx
+++ b/app/components/CollectionDeleteDialog.tsx
@@ -1,5 +1,4 @@
import { observer } from "mobx-react";
-import * as React from "react";
import { useTranslation, Trans } from "react-i18next";
import { useHistory } from "react-router-dom";
import { toast } from "sonner";
diff --git a/app/components/CommandBar/CommandBarResults.tsx b/app/components/CommandBar/CommandBarResults.tsx
index bf64e26af0..59de8841b7 100644
--- a/app/components/CommandBar/CommandBarResults.tsx
+++ b/app/components/CommandBar/CommandBarResults.tsx
@@ -1,5 +1,4 @@
import { useMatches, KBarResults } from "kbar";
-import * as React from "react";
import styled from "styled-components";
import Text from "~/components/Text";
import CommandBarItem from "./CommandBarItem";
diff --git a/app/components/CommandBar/useRecentDocumentActions.tsx b/app/components/CommandBar/useRecentDocumentActions.tsx
index 92d18a5137..c19dcc5159 100644
--- a/app/components/CommandBar/useRecentDocumentActions.tsx
+++ b/app/components/CommandBar/useRecentDocumentActions.tsx
@@ -1,5 +1,5 @@
import { DocumentIcon } from "outline-icons";
-import * as React from "react";
+import { useMemo } from "react";
import Icon from "@shared/components/Icon";
import { createAction } from "~/actions";
import { RecentSection } from "~/actions/sections";
@@ -10,7 +10,7 @@ import { documentPath } from "~/utils/routeHelpers";
const useRecentDocumentActions = (count = 6) => {
const { documents, ui } = useStores();
- return React.useMemo(
+ return useMemo(
() =>
documents.recentlyViewed
.filter((document) => document.id !== ui.activeDocumentId)
diff --git a/app/components/CommandBar/useSettingsAction.tsx b/app/components/CommandBar/useSettingsAction.tsx
index 1902daf44b..d46234b825 100644
--- a/app/components/CommandBar/useSettingsAction.tsx
+++ b/app/components/CommandBar/useSettingsAction.tsx
@@ -1,5 +1,5 @@
import { SettingsIcon } from "outline-icons";
-import * as React from "react";
+import { useMemo } from "react";
import { createAction } from "~/actions";
import { NavigationSection } from "~/actions/sections";
import useSettingsConfig from "~/hooks/useSettingsConfig";
@@ -7,7 +7,7 @@ import history from "~/utils/history";
const useSettingsAction = () => {
const config = useSettingsConfig();
- const actions = React.useMemo(
+ const actions = useMemo(
() =>
config.map((item) => {
const Icon = item.icon;
@@ -22,7 +22,7 @@ const useSettingsAction = () => {
[config]
);
- const navigateToSettings = React.useMemo(
+ const navigateToSettings = useMemo(
() =>
createAction({
id: "settings",
diff --git a/app/components/CommandBar/useTemplatesAction.tsx b/app/components/CommandBar/useTemplatesAction.tsx
index 293bcdaf6c..ba82c3b5ca 100644
--- a/app/components/CommandBar/useTemplatesAction.tsx
+++ b/app/components/CommandBar/useTemplatesAction.tsx
@@ -1,5 +1,5 @@
import { NewDocumentIcon, ShapesIcon } from "outline-icons";
-import * as React from "react";
+import { useEffect, useMemo } from "react";
import Icon from "@shared/components/Icon";
import { createAction } from "~/actions";
import {
@@ -14,11 +14,11 @@ import { newDocumentPath } from "~/utils/routeHelpers";
const useTemplatesAction = () => {
const { templates } = useStores();
- React.useEffect(() => {
+ useEffect(() => {
void templates.fetchAll();
}, [templates]);
- const actions = React.useMemo(
+ const actions = useMemo(
() =>
templates.orderedData.map((template) =>
createAction({
@@ -61,7 +61,7 @@ const useTemplatesAction = () => {
[templates.orderedData]
);
- const newFromTemplate = React.useMemo(
+ const newFromTemplate = useMemo(
() =>
createAction({
id: "templates",
diff --git a/app/components/CommentDeleteDialog.tsx b/app/components/CommentDeleteDialog.tsx
index eae67f3172..c5cbcd8215 100644
--- a/app/components/CommentDeleteDialog.tsx
+++ b/app/components/CommentDeleteDialog.tsx
@@ -1,5 +1,4 @@
import { observer } from "mobx-react";
-import * as React from "react";
import { useTranslation, Trans } from "react-i18next";
import { toast } from "sonner";
import Comment from "~/models/Comment";
diff --git a/app/components/ConfirmMoveDialog.tsx b/app/components/ConfirmMoveDialog.tsx
index 61058db644..2177596a2b 100644
--- a/app/components/ConfirmMoveDialog.tsx
+++ b/app/components/ConfirmMoveDialog.tsx
@@ -1,5 +1,4 @@
import { observer } from "mobx-react";
-import * as React from "react";
import { Trans, useTranslation } from "react-i18next";
import { toast } from "sonner";
import { CollectionPermission, NavigationNode } from "@shared/types";
diff --git a/app/components/ContextMenu/Template.tsx b/app/components/ContextMenu/Template.tsx
index 9dafb79759..1f2b974384 100644
--- a/app/components/ContextMenu/Template.tsx
+++ b/app/components/ContextMenu/Template.tsx
@@ -3,7 +3,6 @@ import * as React from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router-dom";
import {
- useMenuState,
MenuButton,
MenuItem as BaseMenuItem,
MenuStateReturn,
@@ -13,6 +12,7 @@ import MenuIconWrapper from "~/components/ContextMenu/MenuIconWrapper";
import Flex from "~/components/Flex";
import { actionToMenuItem } from "~/actions";
import useActionContext from "~/hooks/useActionContext";
+import { useMenuState } from "~/hooks/useMenuState";
import {
Action,
ActionContext,
@@ -138,7 +138,7 @@ function Template({ items, actions, context, showIcons, ...menu }: Props) {
as={Link}
id={`${item.title}-${index}`}
to={item.to}
- key={index}
+ key={`${item.type}-${item.title}-${index}`}
disabled={item.disabled}
selected={item.selected}
icon={showIcons !== false ? item.icon : undefined}
@@ -154,7 +154,7 @@ function Template({ items, actions, context, showIcons, ...menu }: Props) {
@@ -185,18 +185,25 @@ function Template({ items, actions, context, showIcons, ...menu }: Props) {
);
return item.tooltip ? (
-
+
{menuItem}
) : (
- <>{menuItem}>
+
+ {menuItem}
+
);
}
if (item.type === "submenu") {
- return (
+ // Skip rendering empty submenus
+ return item.items.length > 0 ? (
- );
+ ) : null;
}
if (item.type === "separator") {
- return ;
+ return ;
}
if (item.type === "heading") {
- return ;
+ return (
+
+ );
}
const _exhaustiveCheck: never = item;
diff --git a/app/components/DelayedMount.ts b/app/components/DelayedMount.ts
index 4d55f2093a..40a806a165 100644
--- a/app/components/DelayedMount.ts
+++ b/app/components/DelayedMount.ts
@@ -1,4 +1,4 @@
-import * as React from "react";
+import { useState, useEffect } from "react";
type Props = {
delay?: number;
@@ -6,9 +6,9 @@ type Props = {
};
export default function DelayedMount({ delay = 250, children }: Props) {
- const [isShowing, setShowing] = React.useState(false);
+ const [isShowing, setShowing] = useState(false);
- React.useEffect(() => {
+ useEffect(() => {
const timeout = setTimeout(() => setShowing(true), delay);
return () => {
clearTimeout(timeout);
diff --git a/app/components/DesktopEventHandler.tsx b/app/components/DesktopEventHandler.tsx
index e4a513abbd..dbfac609b1 100644
--- a/app/components/DesktopEventHandler.tsx
+++ b/app/components/DesktopEventHandler.tsx
@@ -1,4 +1,4 @@
-import * as React from "react";
+import { useRef, useEffect } from "react";
import { useTranslation } from "react-i18next";
import { useHistory } from "react-router-dom";
import { toast } from "sonner";
@@ -12,9 +12,9 @@ export default function DesktopEventHandler() {
const { t } = useTranslation();
const history = useHistory();
const { dialogs } = useStores();
- const hasDisabledUpdateMessage = React.useRef(false);
+ const hasDisabledUpdateMessage = useRef(false);
- React.useEffect(() => {
+ useEffect(() => {
Desktop.bridge?.redirect((path: string, replace = false) => {
if (replace) {
history.replace(path);
diff --git a/app/components/Dialogs.tsx b/app/components/Dialogs.tsx
index e7f4d05589..f9cf9eda3b 100644
--- a/app/components/Dialogs.tsx
+++ b/app/components/Dialogs.tsx
@@ -1,5 +1,4 @@
import { observer } from "mobx-react";
-import * as React from "react";
import Guide from "~/components/Guide";
import Modal from "~/components/Modal";
import useStores from "~/hooks/useStores";
@@ -23,7 +22,10 @@ function Dialogs() {
key={id}
isOpen={modal.isOpen}
fullscreen={modal.fullscreen ?? false}
- onRequestClose={() => dialogs.closeModal(id)}
+ onRequestClose={() => {
+ modal.onClose?.();
+ dialogs.closeModal(id);
+ }}
title={modal.title}
style={modal.style}
>
diff --git a/app/components/DocumentBreadcrumb.tsx b/app/components/DocumentBreadcrumb.tsx
index d859cce6a9..ac461da381 100644
--- a/app/components/DocumentBreadcrumb.tsx
+++ b/app/components/DocumentBreadcrumb.tsx
@@ -18,6 +18,13 @@ type Props = {
children?: React.ReactNode;
document: Document;
onlyText?: boolean;
+ reverse?: boolean;
+ /**
+ * Maximum number of items to show in the breadcrumb.
+ * If value is less than or equals to 0, no items will be shown.
+ * If value is undefined, all items will be shown.
+ */
+ maxDepth?: number;
};
function useCategory(document: Document): MenuInternalLink | null {
@@ -45,7 +52,7 @@ function useCategory(document: Document): MenuInternalLink | null {
}
function DocumentBreadcrumb(
- { document, children, onlyText }: Props,
+ { document, children, onlyText, reverse = false, maxDepth }: Props,
ref: React.RefObject | null
) {
const { collections } = useStores();
@@ -56,6 +63,7 @@ function DocumentBreadcrumb(
? collections.get(document.collectionId)
: undefined;
const can = usePolicy(collection);
+ const depth = maxDepth === undefined ? undefined : Math.max(0, maxDepth);
React.useEffect(() => {
void document.loadRelations({ withoutPolicies: true });
@@ -82,20 +90,23 @@ function DocumentBreadcrumb(
};
}
- const path = document.pathTo;
+ const path = document.pathTo.slice(0, -1);
const items = React.useMemo(() => {
- const output = [];
+ const output: MenuInternalLink[] = [];
+
+ if (depth === 0) {
+ return output;
+ }
if (category) {
output.push(category);
}
-
if (collectionNode) {
output.push(collectionNode);
}
- path.slice(0, -1).forEach((node: NavigationNode) => {
+ path.forEach((node: NavigationNode) => {
const title = node.title || t("Untitled");
output.push({
type: "route",
@@ -112,21 +123,43 @@ function DocumentBreadcrumb(
},
});
});
- return output;
- }, [t, path, category, sidebarContext, collectionNode]);
+
+ return reverse
+ ? depth !== undefined
+ ? output.slice(-depth)
+ : output
+ : depth !== undefined
+ ? output.slice(0, depth)
+ : output;
+ }, [t, path, category, sidebarContext, collectionNode, reverse, depth]);
if (!collections.isLoaded) {
return null;
}
- if (onlyText === true) {
+ if (onlyText) {
+ if (depth === 0) {
+ return <>>;
+ }
+
+ const slicedPath = reverse
+ ? path.slice(depth && -depth)
+ : path.slice(0, depth);
+
+ const showCollection =
+ collection &&
+ (!reverse || depth === undefined || slicedPath.length < depth);
+
return (
<>
- {collection?.name}
- {path.slice(0, -1).map((node: NavigationNode) => (
+ {showCollection && collection.name}
+ {slicedPath.map((node: NavigationNode, index: number) => (
-
+ {showCollection && }
{node.title || t("Untitled")}
+ {!showCollection && index !== slicedPath.length - 1 && (
+
+ )}
))}
>
diff --git a/app/components/DocumentCard.tsx b/app/components/DocumentCard.tsx
index b485f5628a..db2d938d58 100644
--- a/app/components/DocumentCard.tsx
+++ b/app/components/DocumentCard.tsx
@@ -4,7 +4,7 @@ import { subDays } from "date-fns";
import { m } from "framer-motion";
import { observer } from "mobx-react";
import { CloseIcon, DocumentIcon, ClockIcon, EyeIcon } from "outline-icons";
-import * as React from "react";
+import { useRef, useCallback, useMemo } from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router-dom";
import styled, { useTheme } from "styled-components";
@@ -40,7 +40,7 @@ function DocumentCard(props: Props) {
const { collections } = useStores();
const theme = useTheme();
const { document, pin, canUpdatePin, isDraggable } = props;
- const pinnedToHome = React.useRef(!pin?.collectionId).current;
+ const pinnedToHome = useRef(!pin?.collectionId).current;
const collection = document.collectionId
? collections.get(document.collectionId)
: undefined;
@@ -63,7 +63,7 @@ function DocumentCard(props: Props) {
transition,
};
- const handleUnpin = React.useCallback(
+ const handleUnpin = useCallback(
async (ev) => {
ev.preventDefault();
ev.stopPropagation();
@@ -178,7 +178,7 @@ function DocumentCard(props: Props) {
const ReadingTime = ({ document }: { document: Document }) => {
const { t } = useTranslation();
- const markdown = React.useMemo(() => document.toMarkdown(), [document]);
+ const markdown = useMemo(() => document.toMarkdown(), [document]);
const stats = useTextStats(markdown);
return (
diff --git a/app/components/DocumentContext.tsx b/app/components/DocumentContext.tsx
index 92c34b4e03..d589111ec4 100644
--- a/app/components/DocumentContext.tsx
+++ b/app/components/DocumentContext.tsx
@@ -1,5 +1,5 @@
import { action, computed, observable } from "mobx";
-import React, { PropsWithChildren } from "react";
+import { createContext, useContext, useMemo, PropsWithChildren } from "react";
import { Heading } from "@shared/utils/ProsemirrorHelper";
import Document from "~/models/Document";
import Template from "~/models/Template";
@@ -68,10 +68,10 @@ class DocumentContext {
}
}
-const Context = React.createContext(null);
+const Context = createContext(null);
export const useDocumentContext = () => {
- const ctx = React.useContext(Context);
+ const ctx = useContext(Context);
if (!ctx) {
throw new Error(
"useDocumentContext must be used within DocumentContextProvider"
@@ -83,6 +83,6 @@ export const useDocumentContext = () => {
export const DocumentContextProvider = ({
children,
}: PropsWithChildren) => {
- const context = React.useMemo(() => new DocumentContext(), []);
+ const context = useMemo(() => new DocumentContext(), []);
return {children} ;
};
diff --git a/app/components/DocumentTasks.tsx b/app/components/DocumentTasks.tsx
index 7d0258711b..a9463c2fc1 100644
--- a/app/components/DocumentTasks.tsx
+++ b/app/components/DocumentTasks.tsx
@@ -1,7 +1,6 @@
import { TFunction } from "i18next";
import { observer } from "mobx-react";
import { DoneIcon } from "outline-icons";
-import * as React from "react";
import { useTranslation } from "react-i18next";
import styled, { useTheme } from "styled-components";
import Document from "~/models/Document";
diff --git a/app/components/DocumentViews.tsx b/app/components/DocumentViews.tsx
index 6c6eb29bd8..da077be23c 100644
--- a/app/components/DocumentViews.tsx
+++ b/app/components/DocumentViews.tsx
@@ -1,7 +1,7 @@
import compact from "lodash/compact";
import sortBy from "lodash/sortBy";
import { observer } from "mobx-react";
-import * as React from "react";
+import { useMemo, useCallback } from "react";
import { useTranslation } from "react-i18next";
import { dateLocale, dateToRelative } from "@shared/utils/date";
import Document from "~/models/Document";
@@ -14,78 +14,86 @@ import useStores from "~/hooks/useStores";
type Props = {
document: Document;
- isOpen?: boolean;
};
-function DocumentViews({ document, isOpen }: Props) {
+function DocumentViews({ document }: Props) {
const { t } = useTranslation();
const { views, presence } = useStores();
const user = useCurrentUser();
const locale = dateLocale(user.language);
-
const documentPresence = presence.get(document.id);
const documentPresenceArray = documentPresence
? Array.from(documentPresence.values())
: [];
- const presentIds = documentPresenceArray.map((p) => p.userId);
- const editingIds = documentPresenceArray
- .filter((p) => p.isEditing)
- .map((p) => p.userId);
+
+ // Use Set for O(1) lookups and stable references
+ const presentIds = useMemo(
+ () => new Set(documentPresenceArray.map((p) => p.userId)),
+ [documentPresenceArray]
+ );
+ const editingIds = useMemo(
+ () =>
+ new Set(
+ documentPresenceArray.filter((p) => p.isEditing).map((p) => p.userId)
+ ),
+ [documentPresenceArray]
+ );
// ensure currently present via websocket are always ordered first
- const documentViews = views.inDocument(document.id);
- const sortedViews = sortBy(
- documentViews,
- (view) => !presentIds.includes(view.userId)
+ const documentViews = useMemo(
+ () => views.inDocument(document.id),
+ [views, document.id]
);
- const users = React.useMemo(
+ const sortedViews = useMemo(
+ () => sortBy(documentViews, (view) => !presentIds.has(view.userId)),
+ [documentViews, presentIds]
+ );
+ const users = useMemo(
() => compact(sortedViews.map((v) => v.user)),
[sortedViews]
);
- return (
- <>
- {isOpen && (
- {
- const view = documentViews.find((v) => v.userId === model.id);
- const isPresent = presentIds.includes(model.id);
- const isEditing = editingIds.includes(model.id);
- const subtitle = isPresent
- ? isEditing
- ? t("Currently editing")
- : t("Currently viewing")
- : t("Viewed {{ timeAgo }}", {
- timeAgo: dateToRelative(
- view ? Date.parse(view.lastViewedAt) : new Date(),
- {
- addSuffix: true,
- locale,
- }
- ),
- });
- return (
-
- }
- border={false}
- small
- />
- );
- }}
+ // Memoize renderItem for PaginatedList
+ const renderItem = useCallback(
+ (model: User) => {
+ const view = documentViews.find((v) => v.userId === model.id);
+ const isPresent = presentIds.has(model.id);
+ const isEditing = editingIds.has(model.id);
+ const subtitle = isPresent
+ ? isEditing
+ ? t("Currently editing")
+ : t("Currently viewing")
+ : t("Viewed {{ timeAgo }}", {
+ timeAgo: dateToRelative(
+ view ? Date.parse(view.lastViewedAt) : new Date(),
+ {
+ addSuffix: true,
+ locale,
+ }
+ ),
+ });
+ return (
+
+ }
+ border={false}
+ small
/>
- )}
- >
+ );
+ },
+ [documentViews, presentIds, editingIds, t, locale]
+ );
+
+ return (
+
+ aria-label={t("Viewers")}
+ items={users}
+ renderItem={renderItem}
+ />
);
}
diff --git a/app/components/EditableTitle.tsx b/app/components/EditableTitle.tsx
index 0d691c1b17..aa487c728f 100644
--- a/app/components/EditableTitle.tsx
+++ b/app/components/EditableTitle.tsx
@@ -64,11 +64,12 @@ function EditableTitle(
async (ev) => {
ev.preventDefault();
ev.stopPropagation();
- setIsEditing(false);
+
const trimmedValue = value.trim();
if (trimmedValue === originalValue || trimmedValue.length === 0) {
setValue(originalValue);
+ setIsEditing(false);
onCancel?.();
return;
}
@@ -80,6 +81,8 @@ function EditableTitle(
setValue(originalValue);
toast.error(error.message);
throw error;
+ } finally {
+ setIsEditing(false);
}
},
[originalValue, value, onCancel, onSubmit]
diff --git a/app/components/Editor.tsx b/app/components/Editor.tsx
index 19f6a7c4f0..e41ef39a51 100644
--- a/app/components/Editor.tsx
+++ b/app/components/Editor.tsx
@@ -205,7 +205,7 @@ function Editor(props: Props, ref: React.RefObject | null) {
{paragraphs.map((paragraph, index) => (
- {paragraph.content.map((content) => content.text)}
+ {paragraph.content?.map((content) => content.text)}
))}
diff --git a/app/components/EventListItem.tsx b/app/components/EventListItem.tsx
index daa8f710cb..01dab0496b 100644
--- a/app/components/EventListItem.tsx
+++ b/app/components/EventListItem.tsx
@@ -11,7 +11,7 @@ import {
UserIcon,
CrossIcon,
} from "outline-icons";
-import * as React from "react";
+import { useRef } from "react";
import { useTranslation } from "react-i18next";
import { useLocation } from "react-router-dom";
import styled, { css } from "styled-components";
@@ -48,10 +48,12 @@ export type DocumentEvent = {
userId: string;
};
-export type Event = { id: string; actorId: string; createdAt: string } & (
- | RevisionEvent
- | DocumentEvent
-);
+export type Event = {
+ id: string;
+ actorId: string;
+ createdAt: string;
+ deletedAt?: string;
+} & (RevisionEvent | DocumentEvent);
type Props = {
document: Document;
@@ -65,7 +67,7 @@ const EventListItem = ({ event, document, ...rest }: Props) => {
const user = "userId" in event ? users.get(event.userId) : undefined;
const location = useLocation();
const sidebarContext = useLocationSidebarContext();
- const revisionLoadedRef = React.useRef(false);
+ const revisionLoadedRef = useRef(false);
const opts = {
userName: actor?.name,
};
@@ -74,7 +76,7 @@ const EventListItem = ({ event, document, ...rest }: Props) => {
event.id === RevisionHelper.latestId(document.id);
let meta, icon, to: LocationDescriptor | undefined;
- const ref = React.useRef(null);
+ const ref = useRef(null);
// the time component tends to steal focus when clicked
// ...so forward the focus back to the parent item
const handleTimeClick = () => {
@@ -85,6 +87,7 @@ const EventListItem = ({ event, document, ...rest }: Props) => {
if (
!document.isDeleted &&
event.name === "revisions.create" &&
+ !event.deletedAt &&
!isDerivedFromDocument &&
!revisionLoadedRef.current
) {
@@ -95,24 +98,31 @@ const EventListItem = ({ event, document, ...rest }: Props) => {
switch (event.name) {
case "revisions.create":
- icon = ;
- meta = event.latest ? (
- <>
- {t("Current version")} · {actor?.name}
- >
- ) : (
- t("{{userName}} edited", opts)
- );
- to = {
- pathname: documentHistoryPath(
- document,
- isDerivedFromDocument ? "latest" : event.id
- ),
- state: {
- sidebarContext,
- retainScrollPosition: true,
- },
- };
+ {
+ if (event.deletedAt) {
+ icon = ;
+ meta = t("Revision deleted");
+ } else {
+ icon = ;
+ meta = event.latest ? (
+ <>
+ {t("Current version")} · {actor?.name}
+ >
+ ) : (
+ t("{{userName}} edited", opts)
+ );
+ to = {
+ pathname: documentHistoryPath(
+ document,
+ isDerivedFromDocument ? "latest" : event.id
+ ),
+ state: {
+ sidebarContext,
+ retainScrollPosition: true,
+ },
+ };
+ }
+ }
break;
case "documents.archive":
@@ -181,7 +191,7 @@ const EventListItem = ({ event, document, ...rest }: Props) => {
to = undefined;
}
- return event.name === "revisions.create" ? (
+ return event.name === "revisions.create" && !event.deletedAt ? (
{
{meta} ·{" "}
-
+
);
diff --git a/app/components/Fade.tsx b/app/components/Fade.tsx
index 2f61695457..7b1e805d6c 100644
--- a/app/components/Fade.tsx
+++ b/app/components/Fade.tsx
@@ -1,7 +1,12 @@
-import React from "react";
+import { useState } from "react";
import styled from "styled-components";
import { fadeIn } from "~/styles/animations";
+/**
+ * Fade in animation for a component.
+ *
+ * @param timing - The duration of the fade in animation, default is 250ms.
+ */
const Fade = styled.span<{ timing?: number | string }>`
animation: ${fadeIn} ${(props) => props.timing || "250ms"} ease-in-out;
`;
@@ -16,8 +21,7 @@ type Props = {
* Wraps children in a if loading is true on mount.
*/
export const ConditionalFade = ({ animate, children }: Props) => {
- const [isAnimated] = React.useState(animate);
-
+ const [isAnimated] = useState(animate);
return isAnimated ? {children} : <>{children}>;
};
diff --git a/app/components/FilterOptions.tsx b/app/components/FilterOptions.tsx
index 34a4da1517..d621c0710f 100644
--- a/app/components/FilterOptions.tsx
+++ b/app/components/FilterOptions.tsx
@@ -1,7 +1,7 @@
import deburr from "lodash/deburr";
import * as React from "react";
import { useTranslation } from "react-i18next";
-import { useMenuState, MenuButton } from "reakit/Menu";
+import { MenuButton } from "reakit/Menu";
import styled from "styled-components";
import { s } from "@shared/styles";
import type { FetchPageParams } from "~/stores/base/Store";
@@ -9,6 +9,7 @@ import Button, { Inner } from "~/components/Button";
import ContextMenu from "~/components/ContextMenu";
import MenuItem from "~/components/ContextMenu/MenuItem";
import Text from "~/components/Text";
+import { useMenuState } from "~/hooks/useMenuState";
import Input, { NativeInput, Outline } from "./Input";
import PaginatedList, { PaginatedItem } from "./PaginatedList";
@@ -56,7 +57,7 @@ const FilterOptions = ({
: "";
const renderItem = React.useCallback(
- (option: TFilterOption) => (
+ (option) => (
{
@@ -174,7 +175,7 @@ const FilterOptions = ({
)}
-
listRef={listRef}
options={{ query, ...fetchQueryOptions }}
items={filteredOptions}
diff --git a/app/components/FullscreenLoading.tsx b/app/components/FullscreenLoading.tsx
index a7c5ec9f98..416a6d111a 100644
--- a/app/components/FullscreenLoading.tsx
+++ b/app/components/FullscreenLoading.tsx
@@ -1,4 +1,3 @@
-import * as React from "react";
import styled from "styled-components";
import Empty from "~/components/Empty";
import Fade from "~/components/Fade";
diff --git a/app/components/HoverPreview/Components.tsx b/app/components/HoverPreview/Components.tsx
index f56cf13625..de57687381 100644
--- a/app/components/HoverPreview/Components.tsx
+++ b/app/components/HoverPreview/Components.tsx
@@ -2,7 +2,6 @@ import { transparentize } from "polished";
import { Link } from "react-router-dom";
import styled, { css } from "styled-components";
import { s } from "@shared/styles";
-import { getTextColor } from "@shared/utils/color";
import Text from "~/components/Text";
export const CARD_MARGIN = 10;
@@ -33,7 +32,7 @@ export const Title = styled(Text).attrs({ as: "h2", size: "large" })`
display: flex;
align-items: flex-start;
justify-content: flex-start;
- gap: 4px;
+ gap: 6px;
`;
export const Info = styled(StyledText).attrs(() => ({
@@ -60,15 +59,27 @@ export const Thumbnail = styled.img`
export const Label = styled(Text).attrs({ size: "xsmall", weight: "bold" })<{
color?: string;
}>`
- background-color: ${(props) =>
- props.color ?? props.theme.backgroundSecondary};
- color: ${(props) =>
- props.color ? getTextColor(props.color) : props.theme.text};
+ border: 1px solid ${(props) => props.theme.divider};
width: fit-content;
border-radius: 2em;
- padding: 0 8px;
+ padding: 1px 8px 1px 20px;
margin-right: 0.5em;
margin-top: 0.5em;
+ position: relative;
+ flex-shrink: 0;
+
+ &::after {
+ content: "";
+ position: absolute;
+ left: 8px;
+ top: 50%;
+ transform: translateY(-50%);
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ background-color: ${(props) =>
+ props.color || props.theme.backgroundSecondary};
+ }
`;
export const CardContent = styled.div`
diff --git a/app/components/HoverPreview/HoverPreview.tsx b/app/components/HoverPreview/HoverPreview.tsx
index c6a79d8f6e..f57527e483 100644
--- a/app/components/HoverPreview/HoverPreview.tsx
+++ b/app/components/HoverPreview/HoverPreview.tsx
@@ -1,4 +1,5 @@
import { m } from "framer-motion";
+import { observer } from "mobx-react";
import * as React from "react";
import { Portal } from "react-portal";
import styled from "styled-components";
@@ -8,6 +9,7 @@ import useEventListener from "~/hooks/useEventListener";
import useKeyDown from "~/hooks/useKeyDown";
import useMobile from "~/hooks/useMobile";
import useOnClickOutside from "~/hooks/useOnClickOutside";
+import useStores from "~/hooks/useStores";
import LoadingIndicator from "../LoadingIndicator";
import { CARD_MARGIN } from "./Components";
import HoverPreviewDocument from "./HoverPreviewDocument";
@@ -23,9 +25,9 @@ const POINTER_WIDTH = 22;
type Props = {
/** The HTML element that is being hovered over, or null if none. */
element: HTMLElement | null;
- /** Data to be previewed */
- data: Record | null;
- /** Whether the preview data is being loaded */
+ /** ID of the unfurl that will be shown in the hover preview. */
+ unfurlId: string | null;
+ /** Whether the preview data is being loaded. */
dataLoading: boolean;
/** A callback on close of the hover preview. */
onClose: () => void;
@@ -36,151 +38,155 @@ enum Direction {
DOWN,
}
-function HoverPreviewDesktop({ element, data, dataLoading, onClose }: Props) {
- const [isVisible, setVisible] = React.useState(false);
- const timerClose = React.useRef>();
- const cardRef = React.useRef(null);
- const { cardLeft, cardTop, pointerLeft, pointerTop, pointerDir } =
- useHoverPosition({
- cardRef,
- element,
- isVisible,
- });
+const HoverPreviewDesktop = observer(
+ ({ element, unfurlId, dataLoading, onClose }: Props) => {
+ const { unfurls } = useStores();
+ const [isVisible, setVisible] = React.useState(false);
+ const timerClose = React.useRef>();
+ const cardRef = React.useRef(null);
+ const { cardLeft, cardTop, pointerLeft, pointerTop, pointerDir } =
+ useHoverPosition({
+ cardRef,
+ element,
+ isVisible,
+ });
+ const data = unfurlId ? unfurls.get(unfurlId)?.data : undefined;
- const closePreview = React.useCallback(() => {
- setVisible(false);
- onClose();
- }, [onClose]);
+ const closePreview = React.useCallback(() => {
+ setVisible(false);
+ onClose();
+ }, [onClose]);
- const stopCloseTimer = React.useCallback(() => {
- if (timerClose.current) {
- clearTimeout(timerClose.current);
- timerClose.current = undefined;
- }
- }, []);
-
- const startCloseTimer = React.useCallback(() => {
- timerClose.current = setTimeout(closePreview, DELAY_CLOSE);
- }, [closePreview]);
-
- // Open and close the preview when the element changes.
- React.useEffect(() => {
- if (element && data && !dataLoading) {
- setVisible(true);
- } else {
- startCloseTimer();
- }
- }, [startCloseTimer, element, data, dataLoading]);
-
- // Close the preview on Escape, scroll, or click outside.
- useOnClickOutside(cardRef, closePreview);
- useKeyDown("Escape", closePreview);
- useEventListener("scroll", closePreview, window, { capture: true });
-
- // Ensure that the preview stays open while the user is hovering over the card.
- React.useEffect(() => {
- const card = cardRef.current;
-
- if (isVisible) {
- if (card) {
- card.addEventListener("mouseenter", stopCloseTimer);
- card.addEventListener("mouseleave", startCloseTimer);
+ const stopCloseTimer = React.useCallback(() => {
+ if (timerClose.current) {
+ clearTimeout(timerClose.current);
+ timerClose.current = undefined;
}
- }
+ }, []);
- return () => {
- if (card) {
- card.removeEventListener("mouseenter", stopCloseTimer);
- card.removeEventListener("mouseleave", startCloseTimer);
+ const startCloseTimer = React.useCallback(() => {
+ timerClose.current = setTimeout(closePreview, DELAY_CLOSE);
+ }, [closePreview]);
+
+ // Open and close the preview when the element changes.
+ React.useEffect(() => {
+ if (element && data && !dataLoading) {
+ setVisible(true);
+ } else {
+ startCloseTimer();
+ }
+ }, [startCloseTimer, element, data, dataLoading]);
+
+ // Close the preview on Escape, scroll, or click outside.
+ useOnClickOutside(cardRef, closePreview);
+ useKeyDown("Escape", closePreview);
+ useEventListener("scroll", closePreview, window, { capture: true });
+
+ // Ensure that the preview stays open while the user is hovering over the card.
+ React.useEffect(() => {
+ const card = cardRef.current;
+
+ if (isVisible) {
+ if (card) {
+ card.addEventListener("mouseenter", stopCloseTimer);
+ card.addEventListener("mouseleave", startCloseTimer);
+ }
}
- stopCloseTimer();
- };
- }, [element, startCloseTimer, isVisible, stopCloseTimer]);
+ return () => {
+ if (card) {
+ card.removeEventListener("mouseenter", stopCloseTimer);
+ card.removeEventListener("mouseleave", startCloseTimer);
+ }
- if (dataLoading) {
- return ;
+ stopCloseTimer();
+ };
+ }, [element, startCloseTimer, isVisible, stopCloseTimer]);
+
+ if (dataLoading) {
+ return ;
+ }
+
+ if (!data) {
+ return null;
+ }
+
+ return (
+
+
+ {isVisible ? (
+
+ {data.type === UnfurlResourceType.Mention ? (
+
+ ) : data.type === UnfurlResourceType.Document ? (
+
+ ) : data.type === UnfurlResourceType.Issue ? (
+
+ ) : data.type === UnfurlResourceType.PR ? (
+
+ ) : (
+
+ )}
+
+
+ ) : null}
+
+
+ );
}
+);
- if (!data) {
- return null;
- }
-
- return (
-
-
- {isVisible ? (
-
- {data.type === UnfurlResourceType.Mention ? (
-
- ) : data.type === UnfurlResourceType.Document ? (
-
- ) : data.type === UnfurlResourceType.Issue ? (
-
- ) : data.type === UnfurlResourceType.PR ? (
-
- ) : (
-
- )}
-
-
- ) : null}
-
-
- );
-}
-
-function HoverPreview({ element, data, dataLoading, ...rest }: Props) {
+function HoverPreview({ element, unfurlId, dataLoading, ...rest }: Props) {
const isMobile = useMobile();
if (isMobile) {
return null;
@@ -190,7 +196,7 @@ function HoverPreview({ element, data, dataLoading, ...rest }: Props) {
);
diff --git a/app/components/HoverPreview/HoverPreviewIssue.tsx b/app/components/HoverPreview/HoverPreviewIssue.tsx
index 032328ffa0..4ee1dbf904 100644
--- a/app/components/HoverPreview/HoverPreviewIssue.tsx
+++ b/app/components/HoverPreview/HoverPreviewIssue.tsx
@@ -1,9 +1,15 @@
import * as React from "react";
import { Trans } from "react-i18next";
-import { UnfurlResourceType, UnfurlResponse } from "@shared/types";
+import styled from "styled-components";
+import { Backticks } from "@shared/components/Backticks";
+import { IssueStatusIcon } from "@shared/components/IssueStatusIcon";
+import {
+ IntegrationService,
+ UnfurlResourceType,
+ UnfurlResponse,
+} from "@shared/types";
import { Avatar } from "~/components/Avatar";
import Flex from "~/components/Flex";
-import { IssueStatusIcon } from "../Icons/IssueStatusIcon";
import Text from "../Text";
import Time from "../Time";
import {
@@ -23,6 +29,11 @@ const HoverPreviewIssue = React.forwardRef(function _HoverPreviewIssue(
ref: React.Ref
) {
const authorName = author.name;
+ const urlObj = new URL(url);
+ const service =
+ urlObj.hostname === "github.com"
+ ? IntegrationService.GitHub
+ : IntegrationService.Linear;
return (
@@ -31,13 +42,18 @@ const HoverPreviewIssue = React.forwardRef(function _HoverPreviewIssue(
-
+
- {title} {id}
+
+ {id}
-
-
+
+
{{ authorName }} created{" "}
@@ -62,4 +78,8 @@ const HoverPreviewIssue = React.forwardRef(function _HoverPreviewIssue(
);
});
+const StyledIssueStatusIcon = styled(IssueStatusIcon)`
+ margin-top: 2px;
+`;
+
export default HoverPreviewIssue;
diff --git a/app/components/HoverPreview/HoverPreviewPullRequest.tsx b/app/components/HoverPreview/HoverPreviewPullRequest.tsx
index 6393695134..ff830953ea 100644
--- a/app/components/HoverPreview/HoverPreviewPullRequest.tsx
+++ b/app/components/HoverPreview/HoverPreviewPullRequest.tsx
@@ -1,9 +1,11 @@
import * as React from "react";
import { Trans } from "react-i18next";
+import styled from "styled-components";
+import { Backticks } from "@shared/components/Backticks";
+import { PullRequestIcon } from "@shared/components/PullRequestIcon";
import { UnfurlResourceType, UnfurlResponse } from "@shared/types";
import { Avatar } from "~/components/Avatar";
import Flex from "~/components/Flex";
-import { PullRequestIcon } from "../Icons/PullRequestIcon";
import Text from "../Text";
import Time from "../Time";
import {
@@ -31,13 +33,14 @@ const HoverPreviewPullRequest = React.forwardRef(
-
+
- {title} {id}
+
+ {id}
-
-
+
+
{{ authorName }} opened{" "}
@@ -55,4 +58,8 @@ const HoverPreviewPullRequest = React.forwardRef(
}
);
+const StyledPullRequestIcon = styled(PullRequestIcon)`
+ margin-top: 2px;
+`;
+
export default HoverPreviewPullRequest;
diff --git a/app/components/IconPicker/components/ColorPicker.tsx b/app/components/IconPicker/components/ColorPicker.tsx
index 4658241896..c4a35b3da8 100644
--- a/app/components/IconPicker/components/ColorPicker.tsx
+++ b/app/components/IconPicker/components/ColorPicker.tsx
@@ -1,5 +1,5 @@
import { BackIcon } from "outline-icons";
-import React from "react";
+import * as React from "react";
import styled from "styled-components";
import { breakpoints, s, hover } from "@shared/styles";
import { colorPalette } from "@shared/utils/collections";
diff --git a/app/components/IconPicker/components/EmojiPanel.tsx b/app/components/IconPicker/components/EmojiPanel.tsx
index 2297d029e4..e57e2f7643 100644
--- a/app/components/IconPicker/components/EmojiPanel.tsx
+++ b/app/components/IconPicker/components/EmojiPanel.tsx
@@ -1,5 +1,5 @@
import concat from "lodash/concat";
-import React from "react";
+import * as React from "react";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
import { EmojiCategory, EmojiSkinTone, IconType } from "@shared/types";
diff --git a/app/components/IconPicker/components/GridTemplate.tsx b/app/components/IconPicker/components/GridTemplate.tsx
index 832a5e1c70..e571c5eba1 100644
--- a/app/components/IconPicker/components/GridTemplate.tsx
+++ b/app/components/IconPicker/components/GridTemplate.tsx
@@ -1,6 +1,6 @@
import chunk from "lodash/chunk";
import compact from "lodash/compact";
-import React from "react";
+import * as React from "react";
import styled from "styled-components";
import { IconType } from "@shared/types";
import { IconLibrary } from "@shared/utils/IconLibrary";
diff --git a/app/components/IconPicker/components/IconPanel.tsx b/app/components/IconPicker/components/IconPanel.tsx
index 22c8eccb82..c67bd3df40 100644
--- a/app/components/IconPicker/components/IconPanel.tsx
+++ b/app/components/IconPicker/components/IconPanel.tsx
@@ -1,4 +1,4 @@
-import React from "react";
+import * as React from "react";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
import { IconType } from "@shared/types";
diff --git a/app/components/IconPicker/components/SkinTonePicker.tsx b/app/components/IconPicker/components/SkinTonePicker.tsx
index fe0b216867..4a4b8e7098 100644
--- a/app/components/IconPicker/components/SkinTonePicker.tsx
+++ b/app/components/IconPicker/components/SkinTonePicker.tsx
@@ -1,6 +1,6 @@
-import React from "react";
+import { useMemo, useCallback } from "react";
import { useTranslation } from "react-i18next";
-import { Menu, MenuButton, MenuItem, useMenuState } from "reakit";
+import { Menu, MenuButton, MenuItem } from "reakit";
import styled from "styled-components";
import { depths, s, hover } from "@shared/styles";
import { EmojiSkinTone } from "@shared/types";
@@ -8,6 +8,7 @@ import { getEmojiVariants } from "@shared/utils/emoji";
import { Emoji } from "~/components/Emoji";
import Flex from "~/components/Flex";
import NudeButton from "~/components/NudeButton";
+import { useMenuState } from "~/hooks/useMenuState";
import { IconButton } from "./IconButton";
const SkinTonePicker = ({
@@ -19,16 +20,13 @@ const SkinTonePicker = ({
}) => {
const { t } = useTranslation();
- const handEmojiVariants = React.useMemo(
- () => getEmojiVariants({ id: "hand" }),
- []
- );
+ const handEmojiVariants = useMemo(() => getEmojiVariants({ id: "hand" }), []);
const menu = useMenuState({
placement: "bottom-end",
});
- const handleSkinClick = React.useCallback(
+ const handleSkinClick = useCallback(
(emojiSkin) => {
menu.hide();
onChange(emojiSkin);
@@ -36,7 +34,7 @@ const SkinTonePicker = ({
[menu, onChange]
);
- const menuItems = React.useMemo(
+ const menuItems = useMemo(
() =>
Object.entries(handEmojiVariants).map(([eskin, emoji]) => (
diff --git a/app/components/IconPicker/index.tsx b/app/components/IconPicker/index.tsx
index b094c40188..eb72cb5bb3 100644
--- a/app/components/IconPicker/index.tsx
+++ b/app/components/IconPicker/index.tsx
@@ -45,6 +45,7 @@ type Props = {
onChange: (icon: string | null, color: string | null) => void;
onOpen?: () => void;
onClose?: () => void;
+ children?: React.ReactNode;
};
const IconPicker = ({
@@ -59,6 +60,7 @@ const IconPicker = ({
onOpen,
onClose,
borderOnHover,
+ children,
}: Props) => {
const { t } = useTranslation();
@@ -174,7 +176,9 @@ const IconPicker = ({
onClick={handlePopoverButtonClick}
$borderOnHover={borderOnHover}
>
- {iconType && icon ? (
+ {children ? (
+ children
+ ) : iconType && icon ? (
) : (
diff --git a/app/components/Icons/CircleIcon.tsx b/app/components/Icons/CircleIcon.tsx
index 9da634ce56..c935fcd664 100644
--- a/app/components/Icons/CircleIcon.tsx
+++ b/app/components/Icons/CircleIcon.tsx
@@ -1,5 +1,3 @@
-import * as React from "react";
-
type Props = {
/** The size of the icon, 24px is default to match standard icons */
size?: number;
diff --git a/app/components/Icons/CollectionIcon.tsx b/app/components/Icons/CollectionIcon.tsx
index c3982f0223..838b0ccd3a 100644
--- a/app/components/Icons/CollectionIcon.tsx
+++ b/app/components/Icons/CollectionIcon.tsx
@@ -1,7 +1,6 @@
import { observer } from "mobx-react";
import { CollectionIcon, PrivateCollectionIcon } from "outline-icons";
import { getLuminance } from "polished";
-import * as React from "react";
import Icon from "@shared/components/Icon";
import { colorPalette } from "@shared/utils/collections";
import Collection from "~/models/Collection";
diff --git a/app/components/Icons/GoogleIcon.tsx b/app/components/Icons/GoogleIcon.tsx
index 66a5309d5d..00884a7ebf 100644
--- a/app/components/Icons/GoogleIcon.tsx
+++ b/app/components/Icons/GoogleIcon.tsx
@@ -1,5 +1,3 @@
-import * as React from "react";
-
type Props = {
/** The size of the icon, 24px is default to match standard icons */
size?: number;
diff --git a/app/components/Icons/IssueStatusIcon.tsx b/app/components/Icons/IssueStatusIcon.tsx
deleted file mode 100644
index 0b3e77c3c3..0000000000
--- a/app/components/Icons/IssueStatusIcon.tsx
+++ /dev/null
@@ -1,74 +0,0 @@
-import * as React from "react";
-import styled from "styled-components";
-
-type Props = {
- status: string;
- color: string;
- size?: number;
- className?: string;
-};
-
-/**
- * Issue status icon based on GitHub issue status, but can be used for any git-style integration.
- */
-export function IssueStatusIcon({ size, ...rest }: Props) {
- return (
-
-
-
- );
-}
-
-const Icon = styled.span<{ size?: number }>`
- display: inline-flex;
- flex-shrink: 0;
- width: ${(props) => props.size ?? 24}px;
- height: ${(props) => props.size ?? 24}px;
- align-items: center;
- justify-content: center;
-`;
-
-function BaseIcon(props: Props) {
- switch (props.status) {
- case "open":
- return (
-
-
-
-
- );
- case "closed":
- return (
-
-
-
-
- );
- case "canceled":
- return (
-
-
-
- );
- default:
- return null;
- }
-}
diff --git a/app/components/Icons/LanguageIcon.tsx b/app/components/Icons/LanguageIcon.tsx
index 286b945940..31a3871c46 100644
--- a/app/components/Icons/LanguageIcon.tsx
+++ b/app/components/Icons/LanguageIcon.tsx
@@ -1,5 +1,3 @@
-import * as React from "react";
-
export function LanguageIcon({ className }: { className?: string }) {
return (
-
-
- );
-}
-
-const Icon = styled.span<{ size?: number }>`
- display: inline-flex;
- flex-shrink: 0;
- width: ${(props) => props.size ?? 24}px;
- height: ${(props) => props.size ?? 24}px;
- align-items: center;
- justify-content: center;
-`;
-
-function BaseIcon(props: Props) {
- switch (props.status) {
- case "open":
- return (
-
-
-
- );
- case "merged":
- return (
-
-
-
- );
- case "closed":
- return (
-
-
-
- );
- default:
- return null;
- }
-}
diff --git a/app/components/Input.tsx b/app/components/Input.tsx
index 947efdd766..92a3136efe 100644
--- a/app/components/Input.tsx
+++ b/app/components/Input.tsx
@@ -45,6 +45,10 @@ export const NativeInput = styled.input<{
${ellipsis()}
${undraggableOnDesktop()}
+ &[readOnly] {
+ color: ${s("textSecondary")};
+ }
+
&:disabled,
&::placeholder {
color: ${s("placeholder")};
@@ -126,13 +130,14 @@ export interface Props
React.InputHTMLAttributes,
"prefix"
> {
- type?: "text" | "email" | "checkbox" | "search" | "textarea";
+ type?: "text" | "email" | "checkbox" | "search" | "textarea" | "password";
labelHidden?: boolean;
label?: string;
flex?: boolean;
short?: boolean;
margin?: string | number;
error?: string;
+ rows?: number;
/** Optional component that appears inside the input before the textarea and any icon */
prefix?: React.ReactNode;
/** Optional icon that appears inside the input before the textarea */
diff --git a/app/components/InputColor.tsx b/app/components/InputColor.tsx
index 37fcab3980..a53cd7406c 100644
--- a/app/components/InputColor.tsx
+++ b/app/components/InputColor.tsx
@@ -1,8 +1,9 @@
import * as React from "react";
import { useTranslation } from "react-i18next";
-import { MenuButton, useMenuState } from "reakit/Menu";
+import { MenuButton } from "reakit/Menu";
import styled from "styled-components";
import { s } from "@shared/styles";
+import { useMenuState } from "~/hooks/useMenuState";
import lazyWithRetry from "~/utils/lazyWithRetry";
import ContextMenu from "./ContextMenu";
import DelayedMount from "./DelayedMount";
diff --git a/app/components/InputSelectNew.tsx b/app/components/InputSelectNew.tsx
index 7a78080307..e0ba401d35 100644
--- a/app/components/InputSelectNew.tsx
+++ b/app/components/InputSelectNew.tsx
@@ -1,6 +1,6 @@
import * as VisuallyHidden from "@radix-ui/react-visually-hidden";
import { transparentize } from "polished";
-import React from "react";
+import * as React from "react";
import styled from "styled-components";
import Text from "~/components/Text";
import useMobile from "~/hooks/useMobile";
diff --git a/app/components/Labeled.tsx b/app/components/Labeled.tsx
deleted file mode 100644
index 30c858266d..0000000000
--- a/app/components/Labeled.tsx
+++ /dev/null
@@ -1,26 +0,0 @@
-import { observer } from "mobx-react";
-import * as React from "react";
-import styled from "styled-components";
-import { s } from "@shared/styles";
-import Flex from "~/components/Flex";
-
-type Props = {
- children?: React.ReactNode;
- label: React.ReactNode | string;
-};
-
-const Labeled: React.FC = ({ label, children, ...props }: Props) => (
-
- {label}
- {children}
-
-);
-
-export const Label = styled(Flex)`
- font-weight: 500;
- padding-bottom: 4px;
- display: inline-block;
- color: ${s("text")};
-`;
-
-export default observer(Labeled);
diff --git a/app/components/LanguagePrompt.tsx b/app/components/LanguagePrompt.tsx
index 8bf72554f5..48095648d7 100644
--- a/app/components/LanguagePrompt.tsx
+++ b/app/components/LanguagePrompt.tsx
@@ -1,6 +1,5 @@
import { m } from "framer-motion";
import find from "lodash/find";
-import * as React from "react";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
import { languages, languageOptions } from "@shared/i18n";
diff --git a/app/components/Layout.tsx b/app/components/Layout.tsx
index 6a3f744fcb..2d737085ab 100644
--- a/app/components/Layout.tsx
+++ b/app/components/Layout.tsx
@@ -38,39 +38,41 @@ const Layout = React.forwardRef(function Layout_(
});
return (
-
-
- {title ? title : env.APP_NAME}
-
+
+
+
+ {title ? title : env.APP_NAME}
+
-
+
- {ui.progressBarVisible && }
+ {ui.progressBarVisible && }
-
- {sidebar}
+
+ {sidebar}
-
-
- {children}
-
+
+
+ {children}
+
- {sidebarRight}
+ {sidebarRight}
+
-
+
);
});
diff --git a/app/components/LazyLoad.ts b/app/components/LazyLoad.ts
new file mode 100644
index 0000000000..7634887530
--- /dev/null
+++ b/app/components/LazyLoad.ts
@@ -0,0 +1,47 @@
+import * as React from "react";
+import lazyWithRetry from "~/utils/lazyWithRetry";
+
+export interface LazyComponent> {
+ Component: React.LazyExoticComponent;
+ preload: () => Promise<{ default: T }>;
+}
+
+interface LazyLoadOptions {
+ retries?: number;
+ interval?: number;
+}
+
+/**
+ * Creates a lazy-loaded component with preloading capability and automatic retries on failure.
+ *
+ * @param factory A function that returns a promise of a component (eg: () => import('./MyComponent'))
+ * @param options Optional configuration for retry behavior
+ * @returns An object containing the lazy Component and a preload function
+ *
+ * @example
+ * ```typescript
+ * const MyComponent = createLazyComponent(() => import('./MyComponent'));
+ *
+ * function App() {
+ * return (
+ * Loading...}>
+ *
+ *
+ * );
+ * }
+ *
+ * // Preload when needed:
+ * MyComponent.preload();
+ * ```
+ */
+export function createLazyComponent>(
+ factory: () => Promise<{ default: T }>,
+ options: LazyLoadOptions = {}
+): LazyComponent {
+ const { retries, interval } = options;
+
+ return {
+ Component: lazyWithRetry(factory, retries, interval),
+ preload: factory,
+ };
+}
diff --git a/app/components/List/Error.tsx b/app/components/List/Error.tsx
index 7cb0f7ec5a..7fc8ba336d 100644
--- a/app/components/List/Error.tsx
+++ b/app/components/List/Error.tsx
@@ -1,5 +1,4 @@
import { DisconnectedIcon, WarningIcon } from "outline-icons";
-import * as React from "react";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
import { s } from "@shared/styles";
diff --git a/app/components/List/Placeholder.tsx b/app/components/List/Placeholder.tsx
index 780dc50431..81463c2cca 100644
--- a/app/components/List/Placeholder.tsx
+++ b/app/components/List/Placeholder.tsx
@@ -1,5 +1,4 @@
import times from "lodash/times";
-import * as React from "react";
import styled from "styled-components";
import Fade from "~/components/Fade";
import Flex from "~/components/Flex";
diff --git a/app/components/LoadingIndicator/LoadingIndicator.ts b/app/components/LoadingIndicator/LoadingIndicator.ts
index b3fa21ead8..178e89478c 100644
--- a/app/components/LoadingIndicator/LoadingIndicator.ts
+++ b/app/components/LoadingIndicator/LoadingIndicator.ts
@@ -1,11 +1,11 @@
import { observer } from "mobx-react";
-import * as React from "react";
+import { useEffect } from "react";
import useStores from "~/hooks/useStores";
function LoadingIndicator() {
const { ui } = useStores();
- React.useEffect(() => {
+ useEffect(() => {
ui.enableProgressBar();
return () => ui.disableProgressBar();
}, [ui]);
diff --git a/app/components/LoadingIndicator/LoadingIndicatorBar.tsx b/app/components/LoadingIndicator/LoadingIndicatorBar.tsx
index 95d0a1e426..2985bcc13d 100644
--- a/app/components/LoadingIndicator/LoadingIndicatorBar.tsx
+++ b/app/components/LoadingIndicator/LoadingIndicatorBar.tsx
@@ -1,4 +1,3 @@
-import * as React from "react";
import styled, { keyframes } from "styled-components";
import { depths, s } from "@shared/styles";
diff --git a/app/components/Modal.tsx b/app/components/Modal.tsx
index 45e3105ee1..35cf5dc995 100644
--- a/app/components/Modal.tsx
+++ b/app/components/Modal.tsx
@@ -114,6 +114,8 @@ const Modal: React.FC = ({
ev.stopPropagation()}
+ // maxHeight needed for proper overflow behavior in Safari
+ style={{ maxHeight: "65vh" }}
column
reverse
>
@@ -259,6 +261,7 @@ const Small = styled.div`
width: 75vw;
min-width: 350px;
max-width: 450px;
+ max-height: 65vh;
z-index: ${depths.modal};
display: flex;
justify-content: center;
diff --git a/app/components/Notice.tsx b/app/components/Notice.tsx
index d1ead2519f..abaf94bfea 100644
--- a/app/components/Notice.tsx
+++ b/app/components/Notice.tsx
@@ -1,4 +1,4 @@
-import React from "react";
+import * as React from "react";
import styled from "styled-components";
import { s } from "@shared/styles";
import Flex from "./Flex";
diff --git a/app/components/Notifications/NotificationIcon.tsx b/app/components/Notifications/NotificationIcon.tsx
index 6a674668df..9ee1b77b48 100644
--- a/app/components/Notifications/NotificationIcon.tsx
+++ b/app/components/Notifications/NotificationIcon.tsx
@@ -1,6 +1,5 @@
import { observer } from "mobx-react";
import { SubscribeIcon } from "outline-icons";
-import * as React from "react";
import styled from "styled-components";
import { s } from "@shared/styles";
import useStores from "~/hooks/useStores";
diff --git a/app/components/Notifications/NotificationListItem.tsx b/app/components/Notifications/NotificationListItem.tsx
index 854d3b8ee7..53724b1e08 100644
--- a/app/components/Notifications/NotificationListItem.tsx
+++ b/app/components/Notifications/NotificationListItem.tsx
@@ -8,7 +8,7 @@ import { s, hover, truncateMultiline } from "@shared/styles";
import Notification from "~/models/Notification";
import CommentEditor from "~/scenes/Document/components/CommentEditor";
import useStores from "~/hooks/useStores";
-import { Avatar, AvatarSize } from "../Avatar";
+import { Avatar, AvatarSize, AvatarVariant } from "../Avatar";
import Flex from "../Flex";
import Text from "../Text";
import Time from "../Time";
@@ -41,7 +41,7 @@ function NotificationListItem({ notification, onNavigate }: Props) {
return (
-
+
@@ -79,7 +79,10 @@ const StyledCommentEditor = styled(CommentEditor)`
${truncateMultiline(3)}
`;
-const StyledAvatar = styled(Avatar)`
+const StyledAvatar = styled(Avatar).attrs({
+ variant: AvatarVariant.Round,
+ size: AvatarSize.Medium,
+})`
margin-top: 4px;
`;
diff --git a/app/components/Notifications/Notifications.tsx b/app/components/Notifications/Notifications.tsx
index e297041cca..481255133a 100644
--- a/app/components/Notifications/Notifications.tsx
+++ b/app/components/Notifications/Notifications.tsx
@@ -79,11 +79,11 @@ function Notifications(
-
fetch={notifications.fetchPage}
options={{ archived: false }}
items={isOpen ? notifications.orderedData : undefined}
- renderItem={(item: Notification) => (
+ renderItem={(item) => (
void;
+ oauthClient?: OAuthClient;
+}) {
+ const { t } = useTranslation();
+
+ const {
+ register,
+ handleSubmit: formHandleSubmit,
+ formState,
+ getValues,
+ setFocus,
+ setError,
+ control,
+ } = useForm({
+ mode: "all",
+ defaultValues: {
+ name: oauthClient?.name ?? "",
+ description: oauthClient?.description ?? "",
+ avatarUrl: oauthClient?.avatarUrl ?? "",
+ redirectUris: oauthClient?.redirectUris ?? [],
+ published: oauthClient?.published ?? false,
+ },
+ });
+
+ useEffect(() => {
+ setTimeout(() => setFocus("name", { shouldSelect: true }), 100);
+ }, [setFocus]);
+
+ return (
+
+ );
+});
diff --git a/app/components/OAuthClient/OAuthClientNew.tsx b/app/components/OAuthClient/OAuthClientNew.tsx
new file mode 100644
index 0000000000..9b31fca533
--- /dev/null
+++ b/app/components/OAuthClient/OAuthClientNew.tsx
@@ -0,0 +1,33 @@
+import { observer } from "mobx-react";
+import { useCallback } from "react";
+import { useHistory } from "react-router-dom";
+import { toast } from "sonner";
+import useStores from "~/hooks/useStores";
+import { settingsPath } from "~/utils/routeHelpers";
+import { OAuthClientForm, FormData } from "./OAuthClientForm";
+
+type Props = {
+ onSubmit: () => void;
+};
+
+export const OAuthClientNew = observer(function OAuthClientNew_({
+ onSubmit,
+}: Props) {
+ const { oauthClients } = useStores();
+ const history = useHistory();
+
+ const handleSubmit = useCallback(
+ async (data: FormData) => {
+ try {
+ const oauthClient = await oauthClients.save(data);
+ onSubmit?.();
+ history.push(settingsPath("applications", oauthClient.id));
+ } catch (error) {
+ toast.error(error.message);
+ }
+ },
+ [oauthClients, history, onSubmit]
+ );
+
+ return ;
+});
diff --git a/app/components/PageTheme.ts b/app/components/PageTheme.ts
index a6d2235604..c0256d1696 100644
--- a/app/components/PageTheme.ts
+++ b/app/components/PageTheme.ts
@@ -1,4 +1,4 @@
-import * as React from "react";
+import { useEffect } from "react";
import { useTheme } from "styled-components";
import useStores from "~/hooks/useStores";
@@ -6,7 +6,7 @@ export default function PageTheme() {
const { ui } = useStores();
const theme = useTheme();
- React.useEffect(() => {
+ useEffect(() => {
// wider page background beyond the React root
if (document.body) {
document.body.style.background = theme.background;
diff --git a/app/components/PaginatedDocumentList.tsx b/app/components/PaginatedDocumentList.tsx
index 744751533c..24c729b9fc 100644
--- a/app/components/PaginatedDocumentList.tsx
+++ b/app/components/PaginatedDocumentList.tsx
@@ -10,7 +10,7 @@ type Props = {
fetch: (options: any) => Promise;
options?: Record;
heading?: React.ReactNode;
- empty?: React.ReactNode;
+ empty?: JSX.Element;
showParentDocuments?: boolean;
showCollection?: boolean;
showPublished?: boolean;
@@ -32,7 +32,7 @@ const PaginatedDocumentList = React.memo(function PaginatedDocumentList({
const { t } = useTranslation();
return (
-
aria-label={t("Documents")}
items={documents}
empty={empty}
@@ -40,7 +40,7 @@ const PaginatedDocumentList = React.memo(function PaginatedDocumentList({
fetch={fetch}
options={options}
renderError={(props) => }
- renderItem={(item: Document, _index) => (
+ renderItem={(item, _index) => (
| undefined) => Promise;
options?: Record;
heading?: React.ReactNode;
- empty?: React.ReactNode;
+ empty?: JSX.Element;
};
const PaginatedEventList = React.memo(function PaginatedEventList({
diff --git a/app/components/PaginatedList.test.tsx b/app/components/PaginatedList.test.tsx
index 2a04ca2c96..1d89716ef7 100644
--- a/app/components/PaginatedList.test.tsx
+++ b/app/components/PaginatedList.test.tsx
@@ -1,13 +1,14 @@
import "../stores";
import { render } from "@testing-library/react";
import { TFunction } from "i18next";
-import * as React from "react";
+import { Provider } from "mobx-react";
import { getI18n } from "react-i18next";
import { Pagination } from "@shared/constants";
-import { Component as PaginatedList } from "./PaginatedList";
+import PaginatedList from "./PaginatedList";
describe("PaginatedList", () => {
const i18n = getI18n();
+ const authStore = {};
const props = {
i18n,
@@ -17,19 +18,23 @@ describe("PaginatedList", () => {
it("with no items renders nothing", () => {
const result = render(
-
+
+
+
);
expect(result.container.innerHTML).toEqual("");
});
it("with no items renders empty prop", async () => {
const result = render(
- Sorry, no results
}
- renderItem={render}
- {...props}
- />
+
+ Sorry, no results}
+ renderItem={render}
+ {...props}
+ />{" "}
+
);
await expect(
result.findAllByText("Sorry, no results")
@@ -42,13 +47,15 @@ describe("PaginatedList", () => {
id: "one",
};
render(
-
+
+ {" "}
+
);
expect(fetch).toHaveBeenCalledWith({
...options,
diff --git a/app/components/PaginatedList.tsx b/app/components/PaginatedList.tsx
index ea7b9f86eb..00e73a5e32 100644
--- a/app/components/PaginatedList.tsx
+++ b/app/components/PaginatedList.tsx
@@ -1,265 +1,315 @@
import isEqual from "lodash/isEqual";
-import { observable, action, computed } from "mobx";
-import { observer } from "mobx-react";
import * as React from "react";
-import { withTranslation, WithTranslation } from "react-i18next";
+import { useTranslation } from "react-i18next";
import { Waypoint } from "react-waypoint";
import { Pagination } from "@shared/constants";
-import RootStore from "~/stores/RootStore";
import ArrowKeyNavigation from "~/components/ArrowKeyNavigation";
import DelayedMount from "~/components/DelayedMount";
import PlaceholderList from "~/components/List/Placeholder";
-import withStores from "~/components/withStores";
+import useCurrentUser from "~/hooks/useCurrentUser";
+import usePrevious from "~/hooks/usePrevious";
import { dateToHeading } from "~/utils/date";
+/**
+ * Base interface for items that can be paginated
+ * @interface PaginatedItem
+ */
export interface PaginatedItem {
+ /** Unique identifier for the item */
id?: string;
+ /** Last update timestamp of the item */
updatedAt?: string;
+ /** Creation timestamp of the item */
createdAt?: string;
}
-type Props = WithTranslation &
- RootStore &
- React.HTMLAttributes & {
- fetch?: (
- options: Record | undefined
- ) => Promise | undefined;
- options?: Record;
- heading?: React.ReactNode;
- empty?: React.ReactNode;
- loading?: React.ReactElement;
- items?: T[];
- className?: string;
- renderItem: (item: T, index: number) => React.ReactNode;
- renderError?: (options: {
- error: Error;
- retry: () => void;
- }) => React.ReactNode;
- renderHeading?: (name: React.ReactElement | string) => React.ReactNode;
- onEscape?: (ev: React.KeyboardEvent) => void;
- listRef?: React.RefObject;
- };
+/**
+ * Props for the PaginatedList component
+ * @template T Type of items in the list, must extend PaginatedItem
+ */
+interface Props
+ extends React.HTMLAttributes {
+ /**
+ * Function to fetch paginated data. Should return a promise resolving to an array of items
+ * @param options Pagination and other query options
+ */
+ fetch?: (
+ options: Record | undefined
+ ) => Promise | undefined;
-@observer
-class PaginatedList extends React.PureComponent<
- Props
-> {
- @observable
- error?: Error;
+ /** Additional options to pass to the fetch function */
+ options?: Record;
- @observable
- isFetchingMore = false;
+ /** Optional header content to display above the list */
+ heading?: React.ReactNode;
- @observable
- isFetching = false;
+ /** Content to display when the list is empty */
+ empty?: JSX.Element | null;
- @observable
- isFetchingInitial = !this.props.items?.length;
+ /** Optional loading state content */
+ loading?: JSX.Element | null;
- @observable
- fetchCounter = 0;
+ /** Array of items to display in the list */
+ items?: T[];
- @observable
- renderCount = Pagination.defaultLimit;
+ /** CSS class name to apply to the list container */
+ className?: string;
- @observable
- offset = 0;
+ /**
+ * Function to render each individual item in the list
+ * @param item The item to render
+ * @param index The index of the item in the list
+ */
+ renderItem: (item: T, index: number) => React.ReactNode;
- @observable
- allowLoadMore = true;
+ /**
+ * Function to render error state
+ * @param options Object containing error details and retry function
+ */
+ renderError?: (options: {
+ /** Details of the error */
+ error: Error;
+ /** Function to retry the fetch operation */
+ retry: () => void;
+ }) => JSX.Element;
- componentDidMount() {
- void this.fetchResults();
- }
+ /**
+ * Function to render section headings (typically date-based)
+ * @param name The heading text or element to render
+ */
+ renderHeading?: (name: React.ReactElement | string) => React.ReactNode;
- componentDidUpdate(prevProps: Props) {
- if (
- prevProps.fetch !== this.props.fetch ||
- !isEqual(prevProps.options, this.props.options)
- ) {
- this.reset();
- void this.fetchResults();
- }
- }
+ /**
+ * Handler for escape key press
+ * @param ev Keyboard event object
+ */
+ onEscape?: (ev: React.KeyboardEvent) => void;
- reset = () => {
- this.offset = 0;
- this.allowLoadMore = true;
- this.renderCount = Pagination.defaultLimit;
- this.isFetching = false;
- this.isFetchingInitial = false;
- this.isFetchingMore = false;
- };
+ /** Reference to the list container element */
+ listRef?: React.RefObject;
+}
- @action
- fetchResults = async () => {
- if (!this.props.fetch) {
+/**
+ * A reusable component that renders a paginated list with infinite scrolling
+ * and optional date-based section headings.
+ *
+ * @template T Type of the list items, must extend PaginatedItem
+ */
+const PaginatedList = ({
+ fetch,
+ options,
+ heading,
+ empty = null,
+ loading = null,
+ items = [],
+ className,
+ renderItem,
+ renderError,
+ renderHeading,
+ onEscape,
+ listRef,
+ ...rest
+}: Props): JSX.Element | null => {
+ const user = useCurrentUser({ rejectOnEmpty: false });
+ const { t } = useTranslation();
+
+ const [error, setError] = React.useState();
+ const [isFetchingMore, setIsFetchingMore] = React.useState(false);
+ const [isFetching, setIsFetching] = React.useState(false);
+ const [isFetchingInitial, setIsFetchingInitial] = React.useState(
+ !items?.length
+ );
+ const [fetchCounter, setFetchCounter] = React.useState(0);
+ const [renderCount, setRenderCount] = React.useState(Pagination.defaultLimit);
+ const [offset, setOffset] = React.useState(0);
+ const [allowLoadMore, setAllowLoadMore] = React.useState(true);
+
+ const reset = React.useCallback(() => {
+ setOffset(0);
+ setAllowLoadMore(true);
+ setRenderCount(Pagination.defaultLimit);
+ setIsFetching(false);
+ setIsFetchingInitial(false);
+ setIsFetchingMore(false);
+ }, []);
+
+ const fetchResults = React.useCallback(async () => {
+ if (!fetch) {
return;
}
- this.isFetching = true;
- const counter = ++this.fetchCounter;
- const limit = this.props.options?.limit ?? Pagination.defaultLimit;
- this.error = undefined;
+
+ setIsFetching(true);
+ const counter = fetchCounter + 1;
+ setFetchCounter(counter);
+ const limit = options?.limit ?? Pagination.defaultLimit;
+ setError(undefined);
try {
- const results = await this.props.fetch({
+ const results = await fetch({
limit,
- offset: this.offset,
- ...this.props.options,
+ offset,
+ ...options,
});
- if (this.offset !== 0) {
- this.renderCount += limit;
+ if (offset !== 0) {
+ setRenderCount((prevCount) => prevCount + limit);
}
if (results && (results.length === 0 || results.length < limit)) {
- this.allowLoadMore = false;
+ setAllowLoadMore(false);
} else {
- this.offset += limit;
+ setOffset((prevOffset) => prevOffset + limit);
}
- this.isFetchingInitial = false;
+ setIsFetchingInitial(false);
} catch (err) {
- this.error = err;
+ setError(err);
} finally {
// only the most recent fetch should end the loading state
- if (counter >= this.fetchCounter) {
- this.isFetching = false;
- this.isFetchingMore = false;
+ if (counter >= fetchCounter) {
+ setIsFetching(false);
+ setIsFetchingMore(false);
}
}
- };
+ }, [fetch, fetchCounter, offset, options]);
- @action
- loadMoreResults = async () => {
- // Don't paginate if there aren't more results or we’re currently fetching
- if (!this.allowLoadMore || this.isFetching) {
+ const loadMoreResults = React.useCallback(async () => {
+ // Don't paginate if there aren't more results or we're currently fetching
+ if (!allowLoadMore || isFetching) {
return;
}
+
// If there are already cached results that we haven't yet rendered because
// of lazy rendering then show another page.
- const leftToRender = (this.props.items?.length ?? 0) - this.renderCount;
+ const leftToRender = (items?.length ?? 0) - renderCount;
if (leftToRender > 0) {
- this.renderCount += Pagination.defaultLimit;
+ setRenderCount((prevCount) => prevCount + Pagination.defaultLimit);
}
// If there are less than a pages results in the cache go ahead and fetch
// another page from the server
if (leftToRender <= Pagination.defaultLimit) {
- this.isFetchingMore = true;
- await this.fetchResults();
+ setIsFetchingMore(true);
+ await fetchResults();
}
- };
+ }, [allowLoadMore, isFetching, items?.length, renderCount, fetchResults]);
- @computed
- get itemsToRender() {
- return this.props.items?.slice(0, this.renderCount) ?? [];
- }
+ const prevFetch = usePrevious(fetch);
+ const prevOptions = usePrevious(options);
- render() {
- const {
- items = [],
- heading,
- auth,
- empty = null,
- renderHeading,
- renderError,
- onEscape,
- } = this.props;
+ // Initial fetch on mount
+ React.useEffect(() => {
+ if (fetch) {
+ void fetchResults();
+ }
+ }, [fetch]);
- const showLoading =
- this.isFetching &&
- !this.isFetchingMore &&
- (!items?.length || (this.fetchCounter <= 1 && this.isFetchingInitial));
-
- if (showLoading) {
- return (
- this.props.loading || (
-
-
-
- )
- );
+ // Handle updates to fetch or options
+ React.useEffect(() => {
+ if (!prevFetch || !prevOptions) {
+ return; // Skip on initial mount since it's handled by the above effect
}
- if (items?.length === 0) {
- if (this.error && renderError) {
- return renderError({ error: this.error, retry: this.fetchResults });
- }
-
- return empty;
+ if (prevFetch !== fetch || !isEqual(prevOptions, options)) {
+ reset();
+ void fetchResults();
}
+ }, [fetch, options, reset, fetchResults, prevFetch, prevOptions]);
+ // Computed property equivalent
+ const itemsToRender = React.useMemo(
+ () => items?.slice(0, renderCount) ?? [],
+ [items, renderCount]
+ );
+
+ const showLoading =
+ isFetching &&
+ !isFetchingMore &&
+ (!items?.length || (fetchCounter <= 1 && isFetchingInitial));
+
+ if (showLoading) {
return (
- <>
- {heading}
-
- {() => {
- let previousHeading = "";
- return this.itemsToRender.map((item, index) => {
- const children = this.props.renderItem(item, index);
-
- // If there is no renderHeading method passed then no date
- // headings are rendered
- if (!renderHeading) {
- return children;
- }
-
- // Our models have standard date fields, updatedAt > createdAt.
- // Get what a heading would look like for this item
- const currentDate =
- "updatedAt" in item && item.updatedAt
- ? item.updatedAt
- : "createdAt" in item && item.createdAt
- ? item.createdAt
- : previousHeading;
- const currentHeading = dateToHeading(
- currentDate,
- this.props.t,
- auth.user?.language
- );
-
- // If the heading is different to any previous heading then we
- // should render it, otherwise the item can go under the previous
- // heading
- if (
- children &&
- (!previousHeading || currentHeading !== previousHeading)
- ) {
- previousHeading = currentHeading;
- return (
-
- {renderHeading(currentHeading)}
- {children}
-
- );
- }
-
- return children;
- });
- }}
-
- {this.allowLoadMore && (
-
-
+ loading || (
+
+
- )}
- >
+
+ )
);
}
-}
-export const Component = PaginatedList;
+ if (items?.length === 0) {
+ if (error && renderError) {
+ return renderError({ error, retry: fetchResults });
+ }
-export default withTranslation()(withStores(PaginatedList));
+ return empty;
+ }
+
+ return (
+
+ {heading}
+
+ {() => {
+ let previousHeading = "";
+ return itemsToRender.map((item, index) => {
+ const children = renderItem(item, index);
+
+ // If there is no renderHeading method passed then no date
+ // headings are rendered
+ if (!renderHeading) {
+ return children;
+ }
+
+ // Our models have standard date fields, updatedAt > createdAt.
+ // Get what a heading would look like for this item
+ const currentDate =
+ "updatedAt" in item && item.updatedAt
+ ? item.updatedAt
+ : "createdAt" in item && item.createdAt
+ ? item.createdAt
+ : previousHeading;
+ const currentHeading = dateToHeading(
+ currentDate,
+ t,
+ user?.language
+ );
+
+ // If the heading is different to any previous heading then we
+ // should render it, otherwise the item can go under the previous
+ // heading
+ if (
+ children &&
+ (!previousHeading || currentHeading !== previousHeading)
+ ) {
+ previousHeading = currentHeading;
+ return (
+
+ {renderHeading(currentHeading)}
+ {children}
+
+ );
+ }
+
+ return children;
+ });
+ }}
+
+ {allowLoadMore && (
+
+
+
+ )}
+
+ );
+};
+
+export default PaginatedList;
diff --git a/app/components/PinnedDocuments.tsx b/app/components/PinnedDocuments.tsx
index 305f089d28..93294c3bb6 100644
--- a/app/components/PinnedDocuments.tsx
+++ b/app/components/PinnedDocuments.tsx
@@ -17,7 +17,7 @@ import {
import fractionalIndex from "fractional-index";
import { AnimatePresence } from "framer-motion";
import { observer } from "mobx-react";
-import * as React from "react";
+import { useState, useRef, useEffect, useCallback } from "react";
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
import Pin from "~/models/Pin";
@@ -44,12 +44,12 @@ function PinnedDocuments({
...rest
}: Props) {
const { documents } = useStores();
- const [items, setItems] = React.useState(pins.map((pin) => pin.documentId));
- const showPlaceholderRef = React.useRef(true);
+ const [items, setItems] = useState(pins.map((pin) => pin.documentId));
+ const showPlaceholderRef = useRef(true);
const showPlaceholder =
placeholderCount && !items.length && showPlaceholderRef.current;
- React.useEffect(() => {
+ useEffect(() => {
setItems(pins.map((pin) => pin.documentId));
}, [pins]);
@@ -65,7 +65,7 @@ function PinnedDocuments({
})
);
- const handleDragEnd = React.useCallback(
+ const handleDragEnd = useCallback(
(event: DragEndEvent) => {
const { active, over } = event;
diff --git a/app/components/PlaceholderDocument.tsx b/app/components/PlaceholderDocument.tsx
index 9d1cb61661..cdc16d90b3 100644
--- a/app/components/PlaceholderDocument.tsx
+++ b/app/components/PlaceholderDocument.tsx
@@ -1,4 +1,3 @@
-import * as React from "react";
import styled from "styled-components";
import DelayedMount from "~/components/DelayedMount";
import Fade from "~/components/Fade";
diff --git a/app/components/PluginIcon.tsx b/app/components/PluginIcon.tsx
index bfffb2b031..b8027f63e5 100644
--- a/app/components/PluginIcon.tsx
+++ b/app/components/PluginIcon.tsx
@@ -1,5 +1,4 @@
import { observer } from "mobx-react";
-import * as React from "react";
import styled from "styled-components";
import Logger from "~/utils/Logger";
import { Hook, usePluginValue } from "~/utils/PluginManager";
diff --git a/app/components/Reactions/Reaction.tsx b/app/components/Reactions/Reaction.tsx
index a67b7e9f1d..8ea941d461 100644
--- a/app/components/Reactions/Reaction.tsx
+++ b/app/components/Reactions/Reaction.tsx
@@ -1,6 +1,6 @@
import { observer } from "mobx-react";
import { transparentize } from "polished";
-import React from "react";
+import * as React from "react";
import { useTranslation } from "react-i18next";
import styled, { css } from "styled-components";
import { s, hover } from "@shared/styles";
diff --git a/app/components/Reactions/ReactionList.tsx b/app/components/Reactions/ReactionList.tsx
index fbe5b94697..d627e69b5e 100644
--- a/app/components/Reactions/ReactionList.tsx
+++ b/app/components/Reactions/ReactionList.tsx
@@ -1,6 +1,6 @@
import compact from "lodash/compact";
import { observer } from "mobx-react";
-import React from "react";
+import * as React from "react";
import Comment from "~/models/Comment";
import useHover from "~/hooks/useHover";
import useStores from "~/hooks/useStores";
diff --git a/app/components/Reactions/ReactionPicker.tsx b/app/components/Reactions/ReactionPicker.tsx
index 6aae9b446c..d2b97859f6 100644
--- a/app/components/Reactions/ReactionPicker.tsx
+++ b/app/components/Reactions/ReactionPicker.tsx
@@ -1,9 +1,10 @@
import { ReactionIcon } from "outline-icons";
-import React from "react";
+import * as React from "react";
import { useTranslation } from "react-i18next";
import { PopoverDisclosure, usePopoverState } from "reakit";
import EventBoundary from "@shared/components/EventBoundary";
import Flex from "~/components/Flex";
+import { createLazyComponent } from "~/components/LazyLoad";
import NudeButton from "~/components/NudeButton";
import PlaceholderText from "~/components/PlaceholderText";
import Popover from "~/components/Popover";
@@ -12,7 +13,7 @@ import useOnClickOutside from "~/hooks/useOnClickOutside";
import useWindowSize from "~/hooks/useWindowSize";
import Tooltip from "../Tooltip";
-const EmojiPanel = React.lazy(
+const EmojiPanel = createLazyComponent(
() => import("~/components/IconPicker/components/EmojiPanel")
);
@@ -104,6 +105,7 @@ const ReactionPicker: React.FC
= ({
aria-label={t("Reaction picker")}
className={className}
onClick={handlePopoverButtonClick}
+ onMouseEnter={() => EmojiPanel.preload()}
size={size}
>
@@ -123,7 +125,7 @@ const ReactionPicker: React.FC = ({
{popover.visible && (
}>
- | undefined
>(undefined);
/**
* Hook to get the scrollable container reference
*/
-export const useScrollContext = () => React.useContext(ScrollContext);
+export const useScrollContext = () => useContext(ScrollContext);
export default ScrollContext;
diff --git a/app/components/ScrollToTop.ts b/app/components/ScrollToTop.ts
index 4d76d406c6..e8b6b4734b 100644
--- a/app/components/ScrollToTop.ts
+++ b/app/components/ScrollToTop.ts
@@ -1,5 +1,5 @@
// based on: https://reacttraining.com/react-router/web/guides/scroll-restoration
-import * as React from "react";
+import { useEffect } from "react";
import { useLocation } from "react-router-dom";
import usePrevious from "~/hooks/usePrevious";
import { useScrollContext } from "./ScrollContext";
@@ -13,7 +13,7 @@ export default function ScrollToTop({ children }: Props) {
const previousLocationPathname = usePrevious(location.pathname);
const scrollContainerRef = useScrollContext();
- React.useEffect(() => {
+ useEffect(() => {
if (
location.pathname === previousLocationPathname ||
location.state?.retainScrollPosition
diff --git a/app/components/SearchActions.ts b/app/components/SearchActions.ts
index 9501e7b30f..a15f88d402 100644
--- a/app/components/SearchActions.ts
+++ b/app/components/SearchActions.ts
@@ -1,5 +1,5 @@
import { useKBar } from "kbar";
-import * as React from "react";
+import { useEffect } from "react";
import { searchDocumentsForQuery } from "~/actions/definitions/documents";
import { navigateToRecentSearchQuery } from "~/actions/definitions/navigation";
@@ -9,7 +9,7 @@ import useStores from "~/hooks/useStores";
export default function SearchActions() {
const { searches } = useStores();
- React.useEffect(() => {
+ useEffect(() => {
if (!searches.isLoaded && !searches.isFetching) {
void searches.fetchPage({
source: "app",
diff --git a/app/components/SearchPopover.tsx b/app/components/SearchPopover.tsx
index 4ac2bcc523..2390a7604a 100644
--- a/app/components/SearchPopover.tsx
+++ b/app/components/SearchPopover.tsx
@@ -200,7 +200,7 @@ function SearchPopover({ shareId, className }: Props) {
style={{ zIndex: depths.sidebar + 1 }}
shrink
>
-
options={{ query, snippetMinWords: 10, snippetMaxWords: 11 }}
items={cachedSearchResults}
fetch={performSearch}
@@ -209,7 +209,7 @@ function SearchPopover({ shareId, className }: Props) {
{t("No results for {{query}}", { query })}
}
loading={ }
- renderItem={(item: SearchResult, index) => (
+ renderItem={(item, index) => (
{
const { t } = useTranslation();
- const handleChange = React.useCallback(
+ const handleChange = useCallback(
(permission: DocumentPermission | typeof EmptySelectValue) => {
if (permission === EmptySelectValue) {
onRemove?.();
@@ -68,7 +68,7 @@ const DocumentMemberListItem = ({
if (!currentPermission) {
return null;
}
- const MaybeLink = membership?.source ? StyledLink : React.Fragment;
+ const MaybeLink = membership?.source ? StyledLink : Fragment;
return (
void;
}) {
const { t } = useTranslation();
- const timeout = React.useRef>();
+ const timeout = useRef>();
- const handleCopied = React.useCallback(() => {
+ const handleCopied = useCallback(() => {
onCopy();
timeout.current = setTimeout(() => {
diff --git a/app/components/Sharing/components/PermissionAction.tsx b/app/components/Sharing/components/PermissionAction.tsx
index c5fa426128..ca0812c6a3 100644
--- a/app/components/Sharing/components/PermissionAction.tsx
+++ b/app/components/Sharing/components/PermissionAction.tsx
@@ -1,4 +1,3 @@
-import * as React from "react";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
import Flex from "@shared/components/Flex";
diff --git a/app/components/Sharing/components/Placeholder.tsx b/app/components/Sharing/components/Placeholder.tsx
index 13f6685162..9bc0763219 100644
--- a/app/components/Sharing/components/Placeholder.tsx
+++ b/app/components/Sharing/components/Placeholder.tsx
@@ -1,5 +1,4 @@
import times from "lodash/times";
-import * as React from "react";
import { AvatarSize } from "~/components/Avatar";
import Fade from "~/components/Fade";
import PlaceholderText from "~/components/PlaceholderText";
diff --git a/app/components/Sharing/components/Suggestions.tsx b/app/components/Sharing/components/Suggestions.tsx
index ac2cf6d0b6..e9b67c6d9c 100644
--- a/app/components/Sharing/components/Suggestions.tsx
+++ b/app/components/Sharing/components/Suggestions.tsx
@@ -93,11 +93,13 @@ export const Suggestions = observer(
const suggestions = React.useMemo(() => {
const filtered: Suggestion[] = (
document
- ? users.notInDocument(document.id, query)
+ ? users
+ .notInDocument(document.id, query)
+ .filter((u) => u.id !== user.id)
: collection
? users.notInCollection(collection.id, query)
- : users.orderedData
- ).filter((u) => !u.isSuspended && u.id !== user.id);
+ : users.activeOrInvited
+ ).filter((u) => !u.isSuspended);
if (isEmail(query)) {
filtered.push(getSuggestionForEmail(query));
@@ -114,7 +116,7 @@ export const Suggestions = observer(
}, [
getSuggestionForEmail,
users,
- users.orderedData,
+ users.activeOrInvited,
groups,
groups.orderedData,
document?.id,
diff --git a/app/components/Sidebar/App.tsx b/app/components/Sidebar/App.tsx
index 1f89d2210c..c7d356e5d4 100644
--- a/app/components/Sidebar/App.tsx
+++ b/app/components/Sidebar/App.tsx
@@ -1,6 +1,6 @@
import { observer } from "mobx-react";
import { SearchIcon, HomeIcon, SidebarIcon } from "outline-icons";
-import * as React from "react";
+import { useEffect, useState, useCallback, useMemo } from "react";
import { DndProvider } from "react-dnd";
import { HTML5Backend } from "react-dnd-html5-backend";
import { useTranslation } from "react-i18next";
@@ -12,7 +12,7 @@ import useCurrentTeam from "~/hooks/useCurrentTeam";
import useCurrentUser from "~/hooks/useCurrentUser";
import usePolicy from "~/hooks/usePolicy";
import useStores from "~/hooks/useStores";
-import OrganizationMenu from "~/menus/OrganizationMenu";
+import TeamMenu from "~/menus/TeamMenu";
import { homePath, searchPath } from "~/utils/routeHelpers";
import TeamLogo from "../TeamLogo";
import Tooltip from "../Tooltip";
@@ -38,7 +38,7 @@ function AppSidebar() {
const user = useCurrentUser();
const can = usePolicy(team);
- React.useEffect(() => {
+ useEffect(() => {
void collections.fetchAll();
if (!user.isViewer) {
@@ -46,9 +46,9 @@ function AppSidebar() {
}
}, [documents, collections, user.isViewer]);
- const [dndArea, setDndArea] = React.useState();
- const handleSidebarRef = React.useCallback((node) => setDndArea(node), []);
- const html5Options = React.useMemo(
+ const [dndArea, setDndArea] = useState();
+ const handleSidebarRef = useCallback((node) => setDndArea(node), []);
+ const html5Options = useMemo(
() => ({
rootElement: dndArea,
}),
@@ -62,7 +62,7 @@ function AppSidebar() {
-
+
{(props: SidebarButtonProps) => (
)}
-
+
{
+ const groupedConfig = groupBy(
+ configs.filter((item) =>
+ item.group === "Integrations" && item.pluginId
+ ? integrations.findByService(item.pluginId)
+ : true
+ ),
+ "group"
+ );
+
+ const returnToApp = useCallback(() => {
history.push("/home");
}, [history]);
@@ -63,8 +71,9 @@ function SettingsSidebar() {
(function _Sidebar(
const [hasPointerMoved, setPointerMoved] = React.useState(false);
const isSmallerThanMinimum = width < minWidth;
+ const hoverTimeoutRef = React.useRef(null);
+
const handleDrag = React.useCallback(
(event: MouseEvent) => {
// suppresses text selection
@@ -114,6 +116,10 @@ const Sidebar = React.forwardRef(function _Sidebar(
const handlePointerActivity = React.useCallback(() => {
if (ui.sidebarIsClosed) {
+ // clear the timeout when mouse exits
+ if (hoverTimeoutRef.current) {
+ clearTimeout(hoverTimeoutRef.current);
+ }
setHovering(document.hasFocus());
setPointerMoved(true);
}
@@ -122,12 +128,20 @@ const Sidebar = React.forwardRef(function _Sidebar(
const handlePointerLeave = React.useCallback(
(ev) => {
if (hasPointerMoved) {
- setHovering(
- document.hasFocus() &&
- ev.pageX < width &&
- ev.pageY < window.innerHeight &&
- ev.pageY > 0
- );
+ // clear any previous timeout
+ if (hoverTimeoutRef.current) {
+ clearTimeout(hoverTimeoutRef.current);
+ }
+
+ // add a short delay when mouse exits the sidebar before closing
+ hoverTimeoutRef.current = setTimeout(() => {
+ setHovering(
+ document.hasFocus() &&
+ ev.pageX < width &&
+ ev.pageY < window.innerHeight &&
+ ev.pageY > 0
+ );
+ }, 500);
}
},
[width, hasPointerMoved]
@@ -307,6 +321,7 @@ const Container = styled(Flex)`
z-index: ${depths.mobileSidebar};
max-width: 80%;
min-width: 280px;
+ padding-left: var(--sal);
${fadeOnDesktopBackgrounded()}
@media print {
diff --git a/app/components/Sidebar/components/ArchiveLink.tsx b/app/components/Sidebar/components/ArchiveLink.tsx
index 9f04d19b03..f48feef8e7 100644
--- a/app/components/Sidebar/components/ArchiveLink.tsx
+++ b/app/components/Sidebar/components/ArchiveLink.tsx
@@ -1,7 +1,7 @@
import isUndefined from "lodash/isUndefined";
import { observer } from "mobx-react";
import { ArchiveIcon } from "outline-icons";
-import * as React from "react";
+import { useState, useEffect, useCallback } from "react";
import { useTranslation } from "react-i18next";
import Flex from "@shared/components/Flex";
import Collection from "~/models/Collection";
@@ -21,43 +21,43 @@ function ArchiveLink() {
const { collections } = useStores();
const { t } = useTranslation();
- const [disclosure, setDisclosure] = React.useState(false);
- const [expanded, setExpanded] = React.useState();
+ const [disclosure, setDisclosure] = useState(false);
+ const [expanded, setExpanded] = useState();
const { request, data, loading, error } = useRequest(
collections.fetchArchived,
true
);
- React.useEffect(() => {
+ useEffect(() => {
if (!isUndefined(data) && !loading && isUndefined(error)) {
setDisclosure(data.length > 0);
}
}, [data, loading, error]);
- React.useEffect(() => {
+ useEffect(() => {
setDisclosure(collections.archived.length > 0);
}, [collections.archived]);
- React.useEffect(() => {
+ useEffect(() => {
if (disclosure && isUndefined(expanded)) {
setExpanded(false);
}
}, [disclosure]);
- React.useEffect(() => {
+ useEffect(() => {
if (expanded) {
void request();
}
}, [expanded, request]);
- const handleDisclosureClick = React.useCallback((ev) => {
+ const handleDisclosureClick = useCallback((ev) => {
ev.preventDefault();
ev.stopPropagation();
setExpanded((e) => !e);
}, []);
- const handleClick = React.useCallback(() => {
+ const handleClick = useCallback(() => {
setExpanded(true);
}, []);
@@ -82,12 +82,12 @@ function ArchiveLink() {
{expanded === true ? (
-
aria-label={t("Archived collections")}
items={collections.archived}
loading={ }
renderError={(props) => }
- renderItem={(item: Collection) => (
+ renderItem={(item) => (
{
+ const handleDisclosureClick = useCallback((ev) => {
ev.preventDefault();
ev.stopPropagation();
setExpanded((e) => !e);
}, []);
- const handleClick = React.useCallback(() => {
+ const handleClick = useCallback(() => {
setExpanded(true);
}, []);
diff --git a/app/components/Sidebar/components/CollectionLinkChildren.tsx b/app/components/Sidebar/components/CollectionLinkChildren.tsx
index c08d658f10..931c5dc1f3 100644
--- a/app/components/Sidebar/components/CollectionLinkChildren.tsx
+++ b/app/components/Sidebar/components/CollectionLinkChildren.tsx
@@ -1,6 +1,6 @@
import noop from "lodash/noop";
import { observer } from "mobx-react";
-import * as React from "react";
+import { useState, useRef, useEffect, useCallback } from "react";
import { useTranslation } from "react-i18next";
import { Waypoint } from "react-waypoint";
import styled from "styled-components";
@@ -37,8 +37,8 @@ function CollectionLinkChildren({
const { documents } = useStores();
const { t } = useTranslation();
const childDocuments = useCollectionDocuments(collection, documents.active);
- const [showing, setShowing] = React.useState(pageSize);
- const dummyRef = React.useRef(null);
+ const [showing, setShowing] = useState(pageSize);
+ const dummyRef = useRef(null);
const [{ isOver, canDrop }, dropRef] = useDropToChangeCollection(
collection,
@@ -46,13 +46,13 @@ function CollectionLinkChildren({
dummyRef
);
- React.useEffect(() => {
+ useEffect(() => {
if (!expanded) {
setShowing(pageSize);
}
}, [expanded]);
- const showMore = React.useCallback(() => {
+ const showMore = useCallback(() => {
if (childDocuments && childDocuments.length > showing) {
setShowing((value) => value + pageSize);
}
diff --git a/app/components/Sidebar/components/Collections.tsx b/app/components/Sidebar/components/Collections.tsx
index f50efc9b92..833e62d940 100644
--- a/app/components/Sidebar/components/Collections.tsx
+++ b/app/components/Sidebar/components/Collections.tsx
@@ -1,6 +1,6 @@
import fractionalIndex from "fractional-index";
import { observer } from "mobx-react";
-import * as React from "react";
+import { useMemo } from "react";
import { useDrop } from "react-dnd";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
@@ -22,9 +22,9 @@ import SidebarContext from "./SidebarContext";
function Collections() {
const { documents, collections } = useStores();
const { t } = useTranslation();
- const orderedCollections = collections.orderedData;
+ const orderedCollections = collections.allActive;
- const params = React.useMemo(
+ const params = useMemo(
() => ({
limit: 100,
}),
@@ -54,7 +54,7 @@ function Collections() {
-
options={params}
aria-label={t("Collections")}
items={collections.allActive}
@@ -69,7 +69,7 @@ function Collections() {
) : undefined
}
renderError={(props) => }
- renderItem={(item: Collection, index) => (
+ renderItem={(item, index) => (
(null);
@@ -270,6 +275,8 @@ function InnerDocumentLink(
{
+ useEffect(() => {
preview(getEmptyImage(), { captureDraggingState: false });
}, [preview]);
// If the current collection is active and relevant to the sidebar section we
// are in then expand it automatically
- React.useEffect(() => {
+ useEffect(() => {
if (
collection.id === ui.activeCollectionId &&
sidebarContext === locationSidebarContext
@@ -93,7 +93,7 @@ function DraggableCollectionLink({
locationSidebarContext,
]);
- const handleDisclosureClick = React.useCallback((ev) => {
+ const handleDisclosureClick = useCallback((ev) => {
ev?.preventDefault();
setExpanded((e) => !e);
}, []);
diff --git a/app/components/Sidebar/components/DropToImport.tsx b/app/components/Sidebar/components/DropToImport.tsx
index fe6f16d167..5e2e9893b4 100644
--- a/app/components/Sidebar/components/DropToImport.tsx
+++ b/app/components/Sidebar/components/DropToImport.tsx
@@ -1,6 +1,6 @@
import invariant from "invariant";
import { observer } from "mobx-react";
-import * as React from "react";
+import { useCallback } from "react";
import Dropzone from "react-dropzone";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
@@ -33,7 +33,7 @@ function DropToImport({ disabled, children, collectionId, documentId }: Props) {
const canCollection = usePolicy(collectionId);
const canDocument = usePolicy(documentId);
- const handleRejection = React.useCallback(() => {
+ const handleRejection = useCallback(() => {
toast.error(
t("Document not supported – try Markdown, Plain text, HTML, or Word")
);
diff --git a/app/components/Sidebar/components/NavLink.tsx b/app/components/Sidebar/components/NavLink.tsx
index 8a1d4456ed..33a23373e8 100644
--- a/app/components/Sidebar/components/NavLink.tsx
+++ b/app/components/Sidebar/components/NavLink.tsx
@@ -39,6 +39,7 @@ export interface Props extends React.AnchorHTMLAttributes {
location?: Location;
strict?: boolean;
to: LocationDescriptor;
+ component?: React.ComponentType;
onBeforeClick?: () => void;
}
@@ -146,17 +147,22 @@ const NavLink = ({
setPreActive(undefined);
}, [currentLocation]);
+ const handleKeyDown = React.useCallback(
+ (event: React.KeyboardEvent) => {
+ if (["Enter", " "].includes(event.key)) {
+ navigateTo();
+ event.currentTarget?.blur();
+ }
+ },
+ [navigateTo]
+ );
+
return (
{
- if (["Enter", " "].includes(event.key)) {
- navigateTo();
- event.currentTarget?.blur();
- }
- }}
+ onKeyDown={handleKeyDown}
aria-current={(isActive && ariaCurrent) || undefined}
className={className}
style={style}
diff --git a/app/components/Sidebar/components/SharedWithMe.tsx b/app/components/Sidebar/components/SharedWithMe.tsx
index afaa0c310a..bd62c72e25 100644
--- a/app/components/Sidebar/components/SharedWithMe.tsx
+++ b/app/components/Sidebar/components/SharedWithMe.tsx
@@ -1,6 +1,6 @@
import fractionalIndex from "fractional-index";
import { observer } from "mobx-react";
-import * as React from "react";
+import { useEffect } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { Pagination } from "@shared/constants";
@@ -38,7 +38,7 @@ function SharedWithMe() {
fractionalIndex(null, user.documentMemberships[0].index)
);
- React.useEffect(() => {
+ useEffect(() => {
if (error) {
toast.error(t("Could not load shared documents"));
}
diff --git a/app/components/Sidebar/components/SidebarAction.tsx b/app/components/Sidebar/components/SidebarAction.tsx
index 334d42e445..d955b74155 100644
--- a/app/components/Sidebar/components/SidebarAction.tsx
+++ b/app/components/Sidebar/components/SidebarAction.tsx
@@ -1,6 +1,5 @@
import invariant from "invariant";
import { observer } from "mobx-react";
-import * as React from "react";
import { actionToMenuItem } from "~/actions";
import useActionContext from "~/hooks/useActionContext";
import { Action } from "~/types";
diff --git a/app/components/Sidebar/components/SidebarContext.ts b/app/components/Sidebar/components/SidebarContext.ts
index 9970336349..294ea7ecca 100644
--- a/app/components/Sidebar/components/SidebarContext.ts
+++ b/app/components/Sidebar/components/SidebarContext.ts
@@ -1,4 +1,4 @@
-import * as React from "react";
+import { createContext, useContext } from "react";
import Document from "~/models/Document";
import User from "~/models/User";
@@ -10,9 +10,9 @@ export type SidebarContextType =
| `starred-${string}`
| undefined;
-const SidebarContext = React.createContext(undefined);
+const SidebarContext = createContext(undefined);
-export const useSidebarContext = () => React.useContext(SidebarContext);
+export const useSidebarContext = () => useContext(SidebarContext);
export const groupSidebarContext = (groupId: string): SidebarContextType =>
`group-${groupId}`;
diff --git a/app/components/Sidebar/components/Starred.tsx b/app/components/Sidebar/components/Starred.tsx
index 5da0b999c1..9659c6db32 100644
--- a/app/components/Sidebar/components/Starred.tsx
+++ b/app/components/Sidebar/components/Starred.tsx
@@ -1,5 +1,5 @@
import { observer } from "mobx-react";
-import * as React from "react";
+import { useEffect } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import Star from "~/models/Star";
@@ -30,7 +30,7 @@ function Starred() {
const [reorderStarProps, dropToReorder] = useDropToReorderStar();
const [createStarProps, dropToStarRef] = useDropToCreateStar();
- React.useEffect(() => {
+ useEffect(() => {
if (error) {
toast.error(t("Could not load starred documents"));
}
diff --git a/app/components/Sidebar/components/StarredLink.tsx b/app/components/Sidebar/components/StarredLink.tsx
index 335170206d..f89706b9f0 100644
--- a/app/components/Sidebar/components/StarredLink.tsx
+++ b/app/components/Sidebar/components/StarredLink.tsx
@@ -38,10 +38,10 @@ function StarredLink({ star }: Props) {
const { ui, collections, documents } = useStores();
const [menuOpen, handleMenuOpen, handleMenuClose] = useBoolean();
const { documentId, collectionId } = star;
- const collection = collections.get(collectionId);
+ const collection = collectionId ? collections.get(collectionId) : undefined;
const locationSidebarContext = useLocationSidebarContext();
const sidebarContext = starredSidebarContext(
- star.documentId ?? star.collectionId
+ star.documentId ?? star.collectionId ?? ""
);
const [expanded, setExpanded] = useState(
(star.documentId
@@ -78,9 +78,9 @@ function StarredLink({ star }: Props) {
}, [documentId, documents]);
const handleDisclosureClick = React.useCallback(
- (ev: React.MouseEvent) => {
- ev.preventDefault();
- ev.stopPropagation();
+ (ev?: React.MouseEvent) => {
+ ev?.preventDefault();
+ ev?.stopPropagation();
setExpanded((prevExpanded) => !prevExpanded);
},
[]
diff --git a/app/components/Sidebar/components/TrashLink.tsx b/app/components/Sidebar/components/TrashLink.tsx
index 6e592ef925..6cd7aedd2c 100644
--- a/app/components/Sidebar/components/TrashLink.tsx
+++ b/app/components/Sidebar/components/TrashLink.tsx
@@ -1,6 +1,5 @@
import { observer } from "mobx-react";
import { TrashIcon } from "outline-icons";
-import * as React from "react";
import { useDrop } from "react-dnd";
import { useTranslation } from "react-i18next";
import DocumentDelete from "~/scenes/DocumentDelete";
diff --git a/app/components/Sidebar/components/Version.tsx b/app/components/Sidebar/components/Version.tsx
index f2e8810b2a..0d77a98dd4 100644
--- a/app/components/Sidebar/components/Version.tsx
+++ b/app/components/Sidebar/components/Version.tsx
@@ -1,4 +1,4 @@
-import * as React from "react";
+import { useState, useEffect } from "react";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
import Badge from "~/components/Badge";
@@ -8,10 +8,10 @@ import { version as currentVersion } from "../../../../package.json";
import SidebarLink from "./SidebarLink";
export default function Version() {
- const [versionsBehind, setVersionsBehind] = React.useState(-1);
+ const [versionsBehind, setVersionsBehind] = useState(-1);
const { t } = useTranslation();
- React.useEffect(() => {
+ useEffect(() => {
async function loadVersionInfo() {
try {
// Fetch version info from the server-side proxy
diff --git a/app/components/Sidebar/hooks/useCollectionDocuments.ts b/app/components/Sidebar/hooks/useCollectionDocuments.ts
index 62734ce11d..b3414c1a8b 100644
--- a/app/components/Sidebar/hooks/useCollectionDocuments.ts
+++ b/app/components/Sidebar/hooks/useCollectionDocuments.ts
@@ -1,4 +1,4 @@
-import * as React from "react";
+import { useMemo } from "react";
import { sortNavigationNodes } from "@shared/utils/collections";
import Collection from "~/models/Collection";
import Document from "~/models/Document";
@@ -7,7 +7,7 @@ export default function useCollectionDocuments(
collection: Collection | undefined,
activeDocument: Document | undefined
) {
- return React.useMemo(() => {
+ return useMemo(() => {
if (!collection?.sortedDocuments) {
return undefined;
}
diff --git a/app/components/Sidebar/hooks/useDragAndDrop.tsx b/app/components/Sidebar/hooks/useDragAndDrop.tsx
index 4d1867c7ca..58ade6c59c 100644
--- a/app/components/Sidebar/hooks/useDragAndDrop.tsx
+++ b/app/components/Sidebar/hooks/useDragAndDrop.tsx
@@ -166,11 +166,13 @@ export function useDropToReorderStar(getIndex?: () => string) {
* @param node The NavigationNode model to drag.
* @param depth The depth of the node in the sidebar.
* @param document The related Document model.
+ * @param isEditing Whether the sidebar item is currently being edited.
*/
export function useDragDocument(
node: NavigationNode,
depth: number,
- document?: Document
+ document?: Document,
+ isEditing?: boolean
) {
const icon = document?.icon || node.icon || node.emoji;
const color = document?.color || node.color;
@@ -188,7 +190,7 @@ export function useDragDocument(
icon: icon ? : undefined,
collectionId: document?.collectionId || "",
} as DragObject),
- canDrag: () => !!document?.isActive,
+ canDrag: () => !!document?.isActive && !isEditing,
collect: (monitor) => ({
isDragging: monitor.isDragging(),
}),
diff --git a/app/components/SkipNavContent.tsx b/app/components/SkipNavContent.tsx
index 9ca268ab69..73fc0d82e4 100644
--- a/app/components/SkipNavContent.tsx
+++ b/app/components/SkipNavContent.tsx
@@ -1,5 +1,3 @@
-import * as React from "react";
-
export const id = "skip-nav";
export default function SkipNavContent() {
diff --git a/app/components/SkipNavLink.tsx b/app/components/SkipNavLink.tsx
index 4099a4ae80..33d07363d2 100644
--- a/app/components/SkipNavLink.tsx
+++ b/app/components/SkipNavLink.tsx
@@ -1,4 +1,3 @@
-import * as React from "react";
import styled from "styled-components";
import { depths, s } from "@shared/styles";
import { id } from "~/components/SkipNavContent";
diff --git a/app/components/SortableTable.tsx b/app/components/SortableTable.tsx
index 306cef7bd7..7adbd8407e 100644
--- a/app/components/SortableTable.tsx
+++ b/app/components/SortableTable.tsx
@@ -1,5 +1,5 @@
import { ColumnSort } from "@tanstack/react-table";
-import * as React from "react";
+import { useCallback } from "react";
import { useHistory, useLocation } from "react-router-dom";
import useQuery from "~/hooks/useQuery";
import lazyWithRetry from "~/utils/lazyWithRetry";
@@ -14,7 +14,7 @@ export function SortableTable(props: Props) {
const history = useHistory();
const params = useQuery();
- const handleChangeSort = React.useCallback(
+ const handleChangeSort = useCallback(
(sort: ColumnSort) => {
params.set("sort", sort.id);
params.set("direction", sort.desc ? "desc" : "asc");
diff --git a/app/components/Star.tsx b/app/components/Star.tsx
index 1ad99e8111..1601ac49a8 100644
--- a/app/components/Star.tsx
+++ b/app/components/Star.tsx
@@ -1,6 +1,5 @@
import { observer } from "mobx-react";
import { StarredIcon, UnstarredIcon } from "outline-icons";
-import * as React from "react";
import { useTranslation } from "react-i18next";
import styled, { useTheme } from "styled-components";
import { hover } from "@shared/styles";
diff --git a/app/components/Table.tsx b/app/components/Table.tsx
index d1b9c25e74..b92d3effa1 100644
--- a/app/components/Table.tsx
+++ b/app/components/Table.tsx
@@ -335,6 +335,7 @@ const TR = styled.div<{ $columns: string }>`
grid-template-columns: ${({ $columns }) => `${$columns}`};
align-items: center;
border-bottom: 1px solid ${s("divider")};
+ overflow: hidden;
&:last-child {
border-bottom: 0;
@@ -357,7 +358,8 @@ const TD = styled.span`
padding: 10px 6px;
font-size: 14px;
text-wrap: wrap;
- word-break: break-word;
+ overflow: hidden;
+ text-overflow: ellipsis;
&:first-child {
font-size: 15px;
diff --git a/app/components/TeamContext.ts b/app/components/TeamContext.ts
index 9133503265..fc1af990f7 100644
--- a/app/components/TeamContext.ts
+++ b/app/components/TeamContext.ts
@@ -1,11 +1,11 @@
-import * as React from "react";
+import { createContext, useContext } from "react";
import { PublicTeam } from "@shared/types";
import Team from "~/models/Team";
-export const TeamContext = React.createContext(
+export const TeamContext = createContext(
undefined
);
export function useTeamContext() {
- return React.useContext(TeamContext);
+ return useContext(TeamContext);
}
diff --git a/app/components/TeamLogo.ts b/app/components/TeamLogo.ts
index 7e943f1f6c..d69586a9ab 100644
--- a/app/components/TeamLogo.ts
+++ b/app/components/TeamLogo.ts
@@ -1,8 +1,11 @@
import styled from "styled-components";
import { s } from "@shared/styles";
import { Avatar } from "./Avatar";
+import { AvatarVariant } from "./Avatar/Avatar";
-const TeamLogo = styled(Avatar)`
+const TeamLogo = styled(Avatar).attrs({
+ variant: AvatarVariant.Square,
+})`
border-radius: 4px;
border: 0;
position: relative;
diff --git a/app/components/TemplatizeDialog/Label.tsx b/app/components/TemplatizeDialog/Label.tsx
index c211b87d3e..0d52ccbd16 100644
--- a/app/components/TemplatizeDialog/Label.tsx
+++ b/app/components/TemplatizeDialog/Label.tsx
@@ -1,4 +1,4 @@
-import React from "react";
+import * as React from "react";
import styled from "styled-components";
import Flex from "~/components/Flex";
diff --git a/app/components/TemplatizeDialog/SelectLocation.tsx b/app/components/TemplatizeDialog/SelectLocation.tsx
index 25666aa751..4188422a9a 100644
--- a/app/components/TemplatizeDialog/SelectLocation.tsx
+++ b/app/components/TemplatizeDialog/SelectLocation.tsx
@@ -1,5 +1,5 @@
import { observer } from "mobx-react";
-import React from "react";
+import { useCallback, useMemo } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { AvatarSize } from "~/components/Avatar";
@@ -26,7 +26,7 @@ const SelectLocation = ({ defaultCollectionId, onSelect }: Props) => {
const can = usePolicy(team);
const { loading, error } = useRequest(
- React.useCallback(async () => {
+ useCallback(async () => {
if (!collections.isLoaded) {
await collections.fetchAll({
limit: 100,
@@ -47,7 +47,7 @@ const SelectLocation = ({ defaultCollectionId, onSelect }: Props) => {
}
: null;
- const collectionOptions: Option[] = React.useMemo(
+ const collectionOptions: Option[] = useMemo(
() =>
collections.orderedData.reduce((memo, collection) => {
const canCollection = policies.abilities(collection.id);
@@ -84,7 +84,7 @@ const SelectLocation = ({ defaultCollectionId, onSelect }: Props) => {
: [workspaceOption]
: collectionOptions;
- const handleSelection = React.useCallback(
+ const handleSelection = useCallback(
(value: string | null) => {
onSelect(value === "workspace" ? null : value);
},
diff --git a/app/components/Text.ts b/app/components/Text.ts
index 2598b71744..33e6f02816 100644
--- a/app/components/Text.ts
+++ b/app/components/Text.ts
@@ -1,73 +1,3 @@
-import styled, { css } from "styled-components";
-import { ellipsis } from "@shared/styles";
-
-type Props = {
- /** The type of text to render */
- type?: "secondary" | "tertiary" | "danger";
- /** The size of the text */
- size?: "xlarge" | "large" | "medium" | "small" | "xsmall";
- /** The direction of the text (defaults to ltr) */
- dir?: "ltr" | "rtl" | "auto";
- /** Whether the text should be selectable (defaults to false) */
- selectable?: boolean;
- /** The font weight of the text */
- weight?: "xbold" | "bold" | "normal";
- /** Whether the text should be italic */
- italic?: boolean;
- /** Whether the text should be truncated with an ellipsis */
- ellipsis?: boolean;
- /** Whether the text should be monospaced */
- monospace?: boolean;
-};
-
-/**
- * Use this component for all interface text that should not be selectable
- * by the user, this is the majority of UI text explainers, notes, headings.
- */
-const Text = styled.span`
- margin-top: 0;
- text-align: ${(props) => (props.dir ? props.dir : "inherit")};
- color: ${(props) =>
- props.type === "secondary"
- ? props.theme.textSecondary
- : props.type === "tertiary"
- ? props.theme.textTertiary
- : props.type === "danger"
- ? props.theme.brand.red
- : props.theme.text};
- font-size: ${(props) =>
- props.size === "xlarge"
- ? "26px"
- : props.size === "large"
- ? "18px"
- : props.size === "medium"
- ? "16px"
- : props.size === "small"
- ? "14px"
- : props.size === "xsmall"
- ? "13px"
- : "inherit"};
-
- ${(props) =>
- props.weight &&
- css`
- font-weight: ${props.weight === "xbold"
- ? 600
- : props.weight === "bold"
- ? 500
- : props.weight === "normal"
- ? 400
- : "inherit"};
- `}
-
- font-style: ${(props) => (props.italic ? "italic" : "normal")};
- font-family: ${(props) =>
- props.monospace ? props.theme.fontFamilyMono : "inherit"};
-
- white-space: normal;
- user-select: ${(props) => (props.selectable ? "text" : "none")};
-
- ${(props) => props.ellipsis && ellipsis()}
-`;
+import Text from "@shared/components/Text";
export default Text;
diff --git a/app/components/Time.tsx b/app/components/Time.tsx
index b811d392a1..3bd82f5b45 100644
--- a/app/components/Time.tsx
+++ b/app/components/Time.tsx
@@ -1,4 +1,4 @@
-import * as React from "react";
+import { Suspense } from "react";
import { dateToRelative } from "@shared/utils/date";
import type { Props as LocaleTimeProps } from "~/components/LocaleTime";
import lazyWithRetry from "~/utils/lazyWithRetry";
@@ -17,13 +17,13 @@ function Time({ onClick, ...props }: Props) {
return (
- {props.children || content}
}
>
-
+
);
}
diff --git a/app/components/Toasts.tsx b/app/components/Toasts.tsx
index 9f02c8ae7b..6d47614611 100644
--- a/app/components/Toasts.tsx
+++ b/app/components/Toasts.tsx
@@ -1,5 +1,4 @@
import { observer } from "mobx-react";
-import * as React from "react";
import { Toaster } from "sonner";
import styled, { useTheme } from "styled-components";
import useStores from "~/hooks/useStores";
diff --git a/app/components/WebsocketProvider.tsx b/app/components/WebsocketProvider.tsx
index 70543b40b2..bf16887394 100644
--- a/app/components/WebsocketProvider.tsx
+++ b/app/components/WebsocketProvider.tsx
@@ -1,15 +1,17 @@
+import * as Sentry from "@sentry/react";
import invariant from "invariant";
import find from "lodash/find";
-import isObject from "lodash/isObject";
import { action, observable } from "mobx";
import { observer } from "mobx-react";
-import * as React from "react";
+import { createContext, Component } from "react";
import { withTranslation, WithTranslation } from "react-i18next";
-import semver from "semver";
import { io, Socket } from "socket.io-client";
import { toast } from "sonner";
-import EDITOR_VERSION from "@shared/editor/version";
-import { FileOperationState, FileOperationType } from "@shared/types";
+import {
+ FileOperationState,
+ FileOperationType,
+ ImportState,
+} from "@shared/types";
import RootStore from "~/stores/RootStore";
import Collection from "~/models/Collection";
import Comment from "~/models/Comment";
@@ -18,6 +20,7 @@ import FileOperation from "~/models/FileOperation";
import Group from "~/models/Group";
import GroupMembership from "~/models/GroupMembership";
import GroupUser from "~/models/GroupUser";
+import Import from "~/models/Import";
import Membership from "~/models/Membership";
import Notification from "~/models/Notification";
import Pin from "~/models/Pin";
@@ -41,13 +44,14 @@ type SocketWithAuthentication = Socket & {
authenticated?: boolean;
};
-export const WebsocketContext =
- React.createContext(null);
+export const WebsocketContext = createContext(
+ null
+);
type Props = WithTranslation & RootStore;
@observer
-class WebsocketProvider extends React.Component {
+class WebsocketProvider extends Component {
@observable
socket: SocketWithAuthentication | null;
@@ -103,6 +107,7 @@ class WebsocketProvider extends React.Component {
subscriptions,
fileOperations,
notifications,
+ imports,
} = this.props;
const currentUserId = auth?.user?.id;
@@ -117,23 +122,10 @@ class WebsocketProvider extends React.Component {
}
});
- this.socket.on("authenticated", (data) => {
+ this.socket.on("authenticated", () => {
if (this.socket) {
this.socket.authenticated = true;
}
- if (isObject(data) && "editorVersion" in data) {
- const parsedClientVersion = semver.parse(EDITOR_VERSION);
- const parsedCurrentVersion = semver.parse(String(data.editorVersion));
-
- if (
- parsedClientVersion &&
- parsedCurrentVersion &&
- (parsedClientVersion.major < parsedCurrentVersion.major ||
- parsedClientVersion.minor < parsedCurrentVersion.minor)
- ) {
- window.location.reload();
- }
- }
});
this.socket.on("unauthorized", (err: Error) => {
@@ -144,6 +136,15 @@ class WebsocketProvider extends React.Component {
throw err;
});
+ // add a listener for all events that logs a sentry breadcrumb
+ this.socket.onAny((event: string, data: Record) => {
+ Sentry.addBreadcrumb({
+ category: "websocket",
+ message: `Received event: ${event}`,
+ data,
+ });
+ });
+
this.socket.on(
"entities",
action(async (event: WebsocketEntitiesEvent) => {
@@ -261,8 +262,10 @@ class WebsocketProvider extends React.Component {
}
policies.remove(document.id);
- const collection = collections.get(event.collectionId);
- collection?.removeDocument(document.id);
+ if (event.collectionId) {
+ const collection = collections.get(event.collectionId);
+ collection?.removeDocument(document.id);
+ }
}
)
);
@@ -636,6 +639,23 @@ class WebsocketProvider extends React.Component {
}
);
+ this.socket.on("imports.create", (event: PartialExcept) => {
+ imports.add(event);
+ });
+
+ this.socket.on("imports.update", (event: PartialExcept) => {
+ imports.add(event);
+
+ if (
+ event.state === ImportState.Completed &&
+ event.createdBy?.id === auth.user?.id
+ ) {
+ toast.success(event.name, {
+ description: this.props.t("Your import completed"),
+ });
+ }
+ });
+
this.socket.on(
"subscriptions.create",
(event: PartialExcept) => {
@@ -661,6 +681,10 @@ class WebsocketProvider extends React.Component {
}
});
+ this.socket.on("users.delete", (event: WebsocketEntityDeletedEvent) => {
+ users.remove(event.modelId);
+ });
+
this.socket.on(
"userMemberships.update",
async (event: PartialExcept) => {
diff --git a/app/components/primitives/Drawer.tsx b/app/components/primitives/Drawer.tsx
index 5aebc17481..c3381d9bbe 100644
--- a/app/components/primitives/Drawer.tsx
+++ b/app/components/primitives/Drawer.tsx
@@ -1,5 +1,5 @@
import * as VisuallyHidden from "@radix-ui/react-visually-hidden";
-import React from "react";
+import * as React from "react";
import styled from "styled-components";
import { Drawer as DrawerPrimitive } from "vaul";
import { depths, s } from "@shared/styles";
diff --git a/app/components/primitives/InputSelect.tsx b/app/components/primitives/InputSelect.tsx
index dbdd94fd6d..7400d4a9b3 100644
--- a/app/components/primitives/InputSelect.tsx
+++ b/app/components/primitives/InputSelect.tsx
@@ -1,5 +1,5 @@
import * as InputSelectPrimitive from "@radix-ui/react-select";
-import React from "react";
+import * as React from "react";
import styled from "styled-components";
import { depths, s } from "@shared/styles";
import { Props as ButtonProps } from "~/components/Button";
diff --git a/app/components/primitives/components/InputSelect.tsx b/app/components/primitives/components/InputSelect.tsx
index e0eb7178b6..0d9adec45f 100644
--- a/app/components/primitives/components/InputSelect.tsx
+++ b/app/components/primitives/components/InputSelect.tsx
@@ -3,14 +3,14 @@
*/
import { CheckmarkIcon } from "outline-icons";
-import React from "react";
+import { forwardRef } from "react";
import styled, { css } from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { s } from "@shared/styles";
import Button, { Inner } from "~/components/Button";
import Flex from "~/components/Flex";
-export const SelectItem = React.forwardRef<
+export const SelectItem = forwardRef<
HTMLDivElement,
React.ComponentPropsWithoutRef<"div">
>((props, ref) => {
@@ -31,7 +31,7 @@ export const SelectItem = React.forwardRef<
});
SelectItem.displayName = "SelectItem";
-export const SelectItemIndicator = React.forwardRef<
+export const SelectItemIndicator = forwardRef<
HTMLSpanElement,
React.ComponentPropsWithoutRef<"span">
>((props, ref) => (
diff --git a/app/editor/components/BlockMenu.tsx b/app/editor/components/BlockMenu.tsx
index 58ed827908..98531513c3 100644
--- a/app/editor/components/BlockMenu.tsx
+++ b/app/editor/components/BlockMenu.tsx
@@ -1,4 +1,3 @@
-import React from "react";
import useDictionary from "~/hooks/useDictionary";
import getMenuItems from "../menus/block";
import { useEditor } from "./EditorContext";
diff --git a/app/editor/components/EditorContext.tsx b/app/editor/components/EditorContext.tsx
index 2a7b9a58ce..bb110ece65 100644
--- a/app/editor/components/EditorContext.tsx
+++ b/app/editor/components/EditorContext.tsx
@@ -1,8 +1,8 @@
-import * as React from "react";
+import { createContext, useContext } from "react";
import { Editor } from "../";
-const EditorContext = React.createContext({} as Editor);
+const EditorContext = createContext({} as Editor);
-export const useEditor = () => React.useContext(EditorContext);
+export const useEditor = () => useContext(EditorContext);
export default EditorContext;
diff --git a/app/editor/components/EmojiMenu.tsx b/app/editor/components/EmojiMenu.tsx
index 0aa7d1acbf..a5d97d0452 100644
--- a/app/editor/components/EmojiMenu.tsx
+++ b/app/editor/components/EmojiMenu.tsx
@@ -1,5 +1,5 @@
import capitalize from "lodash/capitalize";
-import React from "react";
+import { useMemo } from "react";
import { emojiMartToGemoji, snakeCase } from "@shared/editor/lib/emoji";
import { search as emojiSearch } from "@shared/utils/emoji";
import EmojiMenuItem from "./EmojiMenuItem";
@@ -23,7 +23,7 @@ type Props = Omit<
const EmojiMenu = (props: Props) => {
const { search = "" } = props;
- const items = React.useMemo(
+ const items = useMemo(
() =>
emojiSearch({ query: search })
.map((item) => {
diff --git a/app/editor/components/EmojiMenuItem.tsx b/app/editor/components/EmojiMenuItem.tsx
index 89089b6c3d..9b771c7083 100644
--- a/app/editor/components/EmojiMenuItem.tsx
+++ b/app/editor/components/EmojiMenuItem.tsx
@@ -1,4 +1,3 @@
-import * as React from "react";
import styled from "styled-components";
import SuggestionsMenuItem, {
Props as SuggestionsMenuItemProps,
diff --git a/app/editor/components/FindAndReplace.tsx b/app/editor/components/FindAndReplace.tsx
index 09af0969d9..653fc8ca1e 100644
--- a/app/editor/components/FindAndReplace.tsx
+++ b/app/editor/components/FindAndReplace.tsx
@@ -41,6 +41,7 @@ function useKeyboardShortcuts({
useKeyDown(
(ev) =>
isModKey(ev) &&
+ !popover.visible &&
ev.code === "KeyF" &&
// Keyboard handler is through the AppMenu on Desktop v1.2.0+
!(Desktop.bridge && "onFindInPage" in Desktop.bridge),
diff --git a/app/editor/components/FloatingToolbar.tsx b/app/editor/components/FloatingToolbar.tsx
index 5aaa082cf1..be304adc86 100644
--- a/app/editor/components/FloatingToolbar.tsx
+++ b/app/editor/components/FloatingToolbar.tsx
@@ -7,6 +7,7 @@ import { isCode } from "@shared/editor/lib/isCode";
import { findParentNode } from "@shared/editor/queries/findParentNode";
import { EditorStyleHelper } from "@shared/editor/styles/EditorStyleHelper";
import { depths, s } from "@shared/styles";
+import { getSafeAreaInsets } from "@shared/utils/browser";
import { HEADER_HEIGHT } from "~/components/Header";
import { Portal } from "~/components/Portal";
import useEventListener from "~/hooks/useEventListener";
@@ -241,12 +242,16 @@ const FloatingToolbar = React.forwardRef(function FloatingToolbar_(
if (props.active) {
const rect = document.body.getBoundingClientRect();
+ const safeAreaInsets = getSafeAreaInsets();
+
return (
{props.children}
diff --git a/app/editor/components/LinkEditor.tsx b/app/editor/components/LinkEditor.tsx
index baed135a00..6bb0fa1fae 100644
--- a/app/editor/components/LinkEditor.tsx
+++ b/app/editor/components/LinkEditor.tsx
@@ -10,6 +10,7 @@ import styled from "styled-components";
import Icon from "@shared/components/Icon";
import { hideScrollbars, s } from "@shared/styles";
import { isInternalUrl, sanitizeUrl } from "@shared/utils/urls";
+import DocumentBreadcrumb from "~/components/DocumentBreadcrumb";
import Flex from "~/components/Flex";
import { ResizingHeightContainer } from "~/components/ResizingHeightContainer";
import Scrollable from "~/components/Scrollable";
@@ -253,7 +254,14 @@ const LinkEditor: React.FC = ({
onPointerMove={() => setSelectedIndex(index)}
selected={index === selectedIndex}
key={doc.id}
- subtitle={doc.collection?.name}
+ subtitle={
+
+ }
title={doc.title}
icon={
doc.icon ? (
diff --git a/app/editor/components/MentionMenu.tsx b/app/editor/components/MentionMenu.tsx
index 192668bbe4..481db5b4a8 100644
--- a/app/editor/components/MentionMenu.tsx
+++ b/app/editor/components/MentionMenu.tsx
@@ -1,7 +1,7 @@
import { isEmail } from "class-validator";
import { observer } from "mobx-react";
import { DocumentIcon, PlusIcon, CollectionIcon } from "outline-icons";
-import * as React from "react";
+import { useState, useCallback, useEffect } from "react";
import { useTranslation } from "react-i18next";
import { useLocation } from "react-router-dom";
import { toast } from "sonner";
@@ -11,6 +11,7 @@ import { MenuItem } from "@shared/editor/types";
import { MentionType } from "@shared/types";
import parseDocumentSlug from "@shared/utils/parseDocumentSlug";
import { Avatar, AvatarSize } from "~/components/Avatar";
+import DocumentBreadcrumb from "~/components/DocumentBreadcrumb";
import Flex from "~/components/Flex";
import {
DocumentsSection,
@@ -41,8 +42,8 @@ type Props = Omit<
>;
function MentionMenu({ search, isActive, ...rest }: Props) {
- const [loaded, setLoaded] = React.useState(false);
- const [items, setItems] = React.useState([]);
+ const [loaded, setLoaded] = useState(false);
+ const [items, setItems] = useState([]);
const { t } = useTranslation();
const { auth, documents, users, collections } = useStores();
const actorId = auth.currentUserId;
@@ -51,24 +52,24 @@ function MentionMenu({ search, isActive, ...rest }: Props) {
const maxResultsInSection = search ? 25 : 5;
const { loading, request } = useRequest(
- React.useCallback(async () => {
+ useCallback(async () => {
const res = await client.post("/suggestions.mention", { query: search });
res.data.documents.map(documents.add);
res.data.users.map(users.add);
res.data.collections.map(collections.add);
- }, [search, documents, users])
+ }, [search, documents, users, collections])
);
- React.useEffect(() => {
+ useEffect(() => {
if (isActive) {
void request();
}
}, [request, isActive]);
- React.useEffect(() => {
+ useEffect(() => {
if (actorId && !loading) {
- const items = users
+ const items: MentionItem[] = users
.findByQuery(search, { maxResults: maxResultsInSection })
.map(
(user) =>
@@ -112,7 +113,14 @@ function MentionMenu({ search, isActive, ...rest }: Props) {
),
title: doc.title,
- subtitle: doc.collection?.name,
+ subtitle: (
+
+ ),
section: DocumentsSection,
appendSpace: true,
attrs: {
@@ -178,7 +186,7 @@ function MentionMenu({ search, isActive, ...rest }: Props) {
}
}, [t, actorId, loading, search, users, documents, maxResultsInSection]);
- const handleSelect = React.useCallback(
+ const handleSelect = useCallback(
async (item: MentionItem) => {
if (
item.attrs.type === MentionType.Document ||
diff --git a/app/editor/components/NodeViewRenderer.tsx b/app/editor/components/NodeViewRenderer.tsx
index ca09ac2b33..c1db44c2f8 100644
--- a/app/editor/components/NodeViewRenderer.tsx
+++ b/app/editor/components/NodeViewRenderer.tsx
@@ -1,6 +1,6 @@
import isEqual from "lodash/isEqual";
import { action, computed, observable } from "mobx";
-import React, { FunctionComponent } from "react";
+import { FunctionComponent } from "react";
import { createPortal } from "react-dom";
export class NodeViewRenderer {
diff --git a/app/editor/components/PasteMenu.tsx b/app/editor/components/PasteMenu.tsx
index 883d06c3ca..8f6f74c69b 100644
--- a/app/editor/components/PasteMenu.tsx
+++ b/app/editor/components/PasteMenu.tsx
@@ -1,7 +1,16 @@
-import { LinkIcon } from "outline-icons";
+import { observer } from "mobx-react";
+import { EmailIcon, LinkIcon } from "outline-icons";
import React from "react";
import { useTranslation } from "react-i18next";
+import { v4 } from "uuid";
import { EmbedDescriptor } from "@shared/editor/embeds";
+import { MenuItem } from "@shared/editor/types";
+import { MentionType } from "@shared/types";
+import { isUrl } from "@shared/utils/urls";
+import Integration from "~/models/Integration";
+import useCurrentUser from "~/hooks/useCurrentUser";
+import useStores from "~/hooks/useStores";
+import { determineMentionType, isURLMentionable } from "~/utils/mention";
import SuggestionsMenu, {
Props as SuggestionsMenuProps,
} from "./SuggestionsMenu";
@@ -15,34 +24,65 @@ type Props = Omit<
embeds: EmbedDescriptor[];
};
-const PasteMenu = ({ embeds, ...props }: Props) => {
+export const PasteMenu = observer(({ pastedText, embeds, ...props }: Props) => {
const { t } = useTranslation();
+ const { integrations } = useStores();
+ const user = useCurrentUser({ rejectOnEmpty: false });
+
+ let mentionType: MentionType | undefined;
+
+ if (pastedText && isUrl(pastedText)) {
+ const url = new URL(pastedText);
+ const integration = integrations.find((intg: Integration) =>
+ isURLMentionable({ url, integration: intg })
+ );
+
+ mentionType = integration
+ ? determineMentionType({ url, integration })
+ : undefined;
+ }
const embed = React.useMemo(() => {
for (const e of embeds) {
- const matches = e.matcher(props.pastedText);
+ const matches = e.matcher(pastedText);
if (matches) {
return e;
}
}
return;
- }, [embeds, props.pastedText]);
+ }, [embeds, pastedText]);
const items = React.useMemo(
- () => [
- {
- name: "noop",
- title: t("Keep as link"),
- icon: ,
- },
- {
- name: "embed",
- title: t("Embed"),
- icon: embed?.icon,
- keywords: embed?.keywords,
- },
- ],
- [embed, t]
+ () =>
+ [
+ {
+ name: "noop",
+ title: t("Keep as link"),
+ icon: ,
+ },
+ {
+ name: "mention",
+ title: t("Mention"),
+ icon: ,
+ visible: !!mentionType,
+ attrs: {
+ id: v4(),
+ type: mentionType,
+ label: pastedText,
+ href: pastedText,
+ modelId: v4(),
+ actorId: user?.id,
+ },
+ appendSpace: true,
+ },
+ {
+ name: "embed",
+ title: t("Embed"),
+ icon: embed?.icon,
+ keywords: embed?.keywords,
+ },
+ ] satisfies MenuItem[],
+ [t, embed, mentionType, pastedText, user]
);
return (
@@ -52,9 +92,7 @@ const PasteMenu = ({ embeds, ...props }: Props) => {
filterable={false}
renderMenuItem={(item, _index, options) => (
{
- props.onSelect?.(item);
- }}
+ onClick={options.onClick}
selected={options.selected}
title={item.title}
icon={item.icon}
@@ -63,6 +101,4 @@ const PasteMenu = ({ embeds, ...props }: Props) => {
items={items}
/>
);
-};
-
-export default PasteMenu;
+});
diff --git a/app/editor/components/SelectionToolbar.tsx b/app/editor/components/SelectionToolbar.tsx
index a263317ba5..bea7956d6b 100644
--- a/app/editor/components/SelectionToolbar.tsx
+++ b/app/editor/components/SelectionToolbar.tsx
@@ -174,12 +174,12 @@ export default function SelectionToolbar(props: Props) {
const { isTemplate, rtl, canComment, canUpdate, ...rest } = props;
const { state } = view;
const { selection } = state;
- const isDividerSelection = isNodeActive(state.schema.nodes.hr)(state);
if ((readOnly && !canComment) || isDragging) {
return null;
}
+ const isDividerSelection = isNodeActive(state.schema.nodes.hr)(state);
const colIndex = getColumnIndex(state);
const rowIndex = getRowIndex(state);
const isTableSelection = colIndex !== undefined && rowIndex !== undefined;
diff --git a/app/editor/components/SuggestionsMenu.tsx b/app/editor/components/SuggestionsMenu.tsx
index 897fc12b48..7ce101c1aa 100644
--- a/app/editor/components/SuggestionsMenu.tsx
+++ b/app/editor/components/SuggestionsMenu.tsx
@@ -645,12 +645,11 @@ function SuggestionsMenu(props: Props) {
"section" in item ? item.section?.({ t }) : undefined;
const response = (
- <>
+
{currentHeading !== previousHeading && (
)}
@@ -659,7 +658,7 @@ function SuggestionsMenu(props: Props) {
onClick: () => handleClickItem(item),
})}
- >
+
);
previousHeading = currentHeading;
diff --git a/app/editor/components/SuggestionsMenuItem.tsx b/app/editor/components/SuggestionsMenuItem.tsx
index 0660485f54..199548ca3a 100644
--- a/app/editor/components/SuggestionsMenuItem.tsx
+++ b/app/editor/components/SuggestionsMenuItem.tsx
@@ -1,3 +1,4 @@
+import { transparentize } from "polished";
import * as React from "react";
import scrollIntoView from "scroll-into-view-if-needed";
import styled from "styled-components";
@@ -68,12 +69,16 @@ function SuggestionsMenuItem({
const Subtitle = styled.span<{ $active?: boolean }>`
color: ${(props) =>
- props.$active ? props.theme.white50 : props.theme.textTertiary};
+ props.$active
+ ? transparentize(0.35, props.theme.accentText)
+ : props.theme.textTertiary};
`;
const Shortcut = styled.span<{ $active?: boolean }>`
color: ${(props) =>
- props.$active ? props.theme.white50 : props.theme.textTertiary};
+ props.$active
+ ? transparentize(0.35, props.theme.accentText)
+ : props.theme.textTertiary};
flex-grow: 1;
text-align: right;
`;
diff --git a/app/editor/components/ToolbarMenu.tsx b/app/editor/components/ToolbarMenu.tsx
index 3d89eb4577..1576b13d32 100644
--- a/app/editor/components/ToolbarMenu.tsx
+++ b/app/editor/components/ToolbarMenu.tsx
@@ -1,5 +1,5 @@
import { TippyProps } from "@tippyjs/react";
-import * as React from "react";
+import { useMemo } from "react";
import { useMenuState } from "reakit";
import { MenuButton } from "reakit/Menu";
import styled from "styled-components";
@@ -28,7 +28,7 @@ function ToolbarDropdown(props: { active: boolean; item: MenuItem }) {
const { item } = props;
const { state } = view;
- const items: TMenuItem[] = React.useMemo(() => {
+ const items: TMenuItem[] = useMemo(() => {
const handleClick = (menuItem: MenuItem) => () => {
if (!menuItem.name) {
return;
diff --git a/app/editor/extensions/BlockMenu.tsx b/app/editor/extensions/BlockMenu.tsx
index c1807f1b54..ead19219f2 100644
--- a/app/editor/extensions/BlockMenu.tsx
+++ b/app/editor/extensions/BlockMenu.tsx
@@ -2,9 +2,9 @@ import { action } from "mobx";
import { PlusIcon } from "outline-icons";
import { Plugin } from "prosemirror-state";
import { Decoration, DecorationSet } from "prosemirror-view";
-import * as React from "react";
import ReactDOM from "react-dom";
import { WidgetProps } from "@shared/editor/lib/Extension";
+import { PlaceholderPlugin } from "@shared/editor/plugins/PlaceholderPlugin";
import { findParentNode } from "@shared/editor/queries/findParentNode";
import Suggestion from "~/editor/extensions/Suggestion";
import BlockMenu from "../components/BlockMenu";
@@ -49,7 +49,6 @@ export default class BlockMenuExtension extends Suggestion {
const decorations: Decoration[] = [];
const isEmptyNode = parent && parent.node.content.size === 0;
- const isSlash = parent && parent.node.textContent === "/";
if (isEmptyNode) {
decorations.push(
@@ -69,33 +68,29 @@ export default class BlockMenuExtension extends Suggestion {
}
)
);
-
- const isEmptyDoc = state.doc.textContent === "";
- if (!isEmptyDoc) {
- decorations.push(
- Decoration.node(
- parent.pos,
- parent.pos + parent.node.nodeSize,
- {
- class: "placeholder",
- "data-empty-text": this.options.dictionary.newLineEmpty,
- }
- )
- );
- }
- } else if (isSlash) {
- decorations.push(
- Decoration.node(parent.pos, parent.pos + parent.node.nodeSize, {
- class: "placeholder",
- "data-empty-text": ` ${this.options.dictionary.newLineWithSlash}`,
- })
- );
}
return DecorationSet.create(state.doc, decorations);
},
},
}),
+ new PlaceholderPlugin([
+ {
+ condition: ({ node, $start, textContent, state }) =>
+ $start.depth === 1 &&
+ state.selection.$from.pos === $start.pos + node.content.size &&
+ !!textContent &&
+ node.textContent === "",
+ text: this.options.dictionary.newLineEmpty,
+ },
+ {
+ condition: ({ node, $start, state }) =>
+ $start.depth === 1 &&
+ state.selection.$from.pos === $start.pos + node.content.size &&
+ node.textContent === "/",
+ text: ` ${this.options.dictionary.newLineWithSlash}`,
+ },
+ ]),
];
}
diff --git a/app/editor/extensions/ClipboardTextSerializer.ts b/app/editor/extensions/ClipboardTextSerializer.ts
index 5fb3a90550..44e0f983ce 100644
--- a/app/editor/extensions/ClipboardTextSerializer.ts
+++ b/app/editor/extensions/ClipboardTextSerializer.ts
@@ -1,5 +1,6 @@
import { Plugin, PluginKey } from "prosemirror-state";
import Extension from "@shared/editor/lib/Extension";
+import { isList } from "@shared/editor/queries/isList";
import { ProsemirrorHelper } from "@shared/utils/ProsemirrorHelper";
/**
@@ -18,17 +19,25 @@ export default class ClipboardTextSerializer extends Extension {
new Plugin({
key: new PluginKey("clipboardTextSerializer"),
props: {
- clipboardTextSerializer: (slice) => {
+ clipboardTextSerializer: (slice, view) => {
const isMultiline = slice.content.childCount > 1;
// This is a cheap way to determine if the content is "complex",
// aka it has multiple marks or formatting. In which case we'll use
// markdown formatting
+ const hasMultipleListItems = slice.content.content
+ .filter((node) => node.content.content.length > 1)
+ .some((node) => isList(node, view.state.schema));
+ const hasMultipleBlockTypes =
+ [
+ ...new Set(
+ slice.content.content
+ .filter((node) => node.content.content.length > 1)
+ .map((node) => node.type.name)
+ ),
+ ].length > 1;
const copyAsMarkdown =
- isMultiline ||
- slice.content.content.some(
- (node) => node.content.content.length > 1
- );
+ isMultiline || hasMultipleBlockTypes || hasMultipleListItems;
return copyAsMarkdown
? mdSerializer.serialize(slice.content, {
diff --git a/app/editor/extensions/EmojiMenu.tsx b/app/editor/extensions/EmojiMenu.tsx
index 3743990b1f..50e842d025 100644
--- a/app/editor/extensions/EmojiMenu.tsx
+++ b/app/editor/extensions/EmojiMenu.tsx
@@ -1,5 +1,4 @@
import { action } from "mobx";
-import * as React from "react";
import { WidgetProps } from "@shared/editor/lib/Extension";
import { isBrowser } from "@shared/utils/browser";
import Suggestion from "~/editor/extensions/Suggestion";
diff --git a/app/editor/extensions/FindAndReplace.tsx b/app/editor/extensions/FindAndReplace.tsx
index a2d9a12586..924a11a2b5 100644
--- a/app/editor/extensions/FindAndReplace.tsx
+++ b/app/editor/extensions/FindAndReplace.tsx
@@ -4,7 +4,6 @@ import { observable } from "mobx";
import { Node } from "prosemirror-model";
import { Command, Plugin, PluginKey } from "prosemirror-state";
import { Decoration, DecorationSet } from "prosemirror-view";
-import * as React from "react";
import scrollIntoView from "scroll-into-view-if-needed";
import Extension, { WidgetProps } from "@shared/editor/lib/Extension";
import FindAndReplace from "../components/FindAndReplace";
diff --git a/app/editor/extensions/HoverPreviews.tsx b/app/editor/extensions/HoverPreviews.tsx
index fff2eeef88..6df12402bd 100644
--- a/app/editor/extensions/HoverPreviews.tsx
+++ b/app/editor/extensions/HoverPreviews.tsx
@@ -1,12 +1,11 @@
import { action, observable } from "mobx";
import { Plugin } from "prosemirror-state";
import { EditorView } from "prosemirror-view";
-import * as React from "react";
import Extension from "@shared/editor/lib/Extension";
import parseDocumentSlug from "@shared/utils/parseDocumentSlug";
+import stores from "~/stores";
import HoverPreview from "~/components/HoverPreview";
import env from "~/env";
-import { client } from "~/utils/ApiClient";
interface HoverPreviewsOptions {
/** Delay before the target is considered "hovered" and callback is triggered. */
@@ -16,11 +15,11 @@ interface HoverPreviewsOptions {
export default class HoverPreviews extends Extension {
state: {
activeLinkElement: HTMLElement | null;
- data: Record | null;
+ unfurlId: string | null;
dataLoading: boolean;
} = observable({
activeLinkElement: null,
- data: null,
+ unfurlId: null,
dataLoading: false,
});
@@ -62,19 +61,25 @@ export default class HoverPreviews extends Extension {
);
if (url) {
+ const transformedUrl = url.startsWith("/")
+ ? env.URL + url
+ : url;
+
this.state.dataLoading = true;
- try {
- const data = await client.post("/urls.unfurl", {
- url: url.startsWith("/") ? env.URL + url : url,
- documentId,
- });
+
+ const unfurl = await stores.unfurls.fetchUnfurl({
+ url: transformedUrl,
+ documentId,
+ });
+
+ if (unfurl) {
this.state.activeLinkElement = element;
- this.state.data = data;
- } catch (err) {
+ this.state.unfurlId = transformedUrl;
+ } else {
this.state.activeLinkElement = null;
- } finally {
- this.state.dataLoading = false;
}
+
+ this.state.dataLoading = false;
}
}),
this.options.delay
@@ -101,10 +106,11 @@ export default class HoverPreviews extends Extension {
widget = () => (
{
this.state.activeLinkElement = null;
+ this.state.unfurlId = null;
})}
/>
);
diff --git a/app/editor/extensions/MentionMenu.tsx b/app/editor/extensions/MentionMenu.tsx
index b8815bf08b..5a4c1cdbf3 100644
--- a/app/editor/extensions/MentionMenu.tsx
+++ b/app/editor/extensions/MentionMenu.tsx
@@ -1,5 +1,4 @@
import { action } from "mobx";
-import * as React from "react";
import { WidgetProps } from "@shared/editor/lib/Extension";
import Suggestion from "~/editor/extensions/Suggestion";
import MentionMenu from "../components/MentionMenu";
diff --git a/app/editor/extensions/PasteHandler.tsx b/app/editor/extensions/PasteHandler.tsx
index 6982f74c93..dfd8f5611a 100644
--- a/app/editor/extensions/PasteHandler.tsx
+++ b/app/editor/extensions/PasteHandler.tsx
@@ -8,10 +8,9 @@ import {
TextSelection,
} from "prosemirror-state";
import { Decoration, DecorationSet } from "prosemirror-view";
-import * as React from "react";
import { v4 } from "uuid";
-import { LANGUAGES } from "@shared/editor/extensions/Prism";
import Extension, { WidgetProps } from "@shared/editor/lib/Extension";
+import { codeLanguages } from "@shared/editor/lib/code";
import isMarkdown from "@shared/editor/lib/isMarkdown";
import normalizePastedMarkdown from "@shared/editor/lib/markdown/normalize";
import { isRemoteTransaction } from "@shared/editor/lib/multiplayer";
@@ -24,7 +23,7 @@ import parseCollectionSlug from "@shared/utils/parseCollectionSlug";
import parseDocumentSlug from "@shared/utils/parseDocumentSlug";
import { isCollectionUrl, isDocumentUrl, isUrl } from "@shared/utils/urls";
import stores from "~/stores";
-import PasteMenu from "../components/PasteMenu";
+import { PasteMenu } from "../components/PasteMenu";
export default class PasteHandler extends Extension {
state: {
@@ -88,7 +87,7 @@ export default class PasteHandler extends Extension {
// If the users selection is currently in a code block then paste
// as plain text, ignore all formatting and HTML content.
- if (isInCode(state)) {
+ if (isInCode(state, { inclusive: true })) {
event.preventDefault();
view.dispatch(state.tr.insertText(text));
return true;
@@ -122,6 +121,8 @@ export default class PasteHandler extends Extension {
}
// Is the link a link to a document? If so, we can grab the title and insert it.
+ const containsHash = text.includes("#");
+
if (isDocumentUrl(text)) {
const slug = parseDocumentSlug(text);
@@ -133,7 +134,7 @@ export default class PasteHandler extends Extension {
return;
}
if (document) {
- if (state.schema.nodes.mention) {
+ if (state.schema.nodes.mention && !containsHash) {
view.dispatch(
view.state.tr.replaceWith(
state.selection.from,
@@ -178,7 +179,7 @@ export default class PasteHandler extends Extension {
return;
}
if (collection) {
- if (state.schema.nodes.mention) {
+ if (state.schema.nodes.mention && !containsHash) {
view.dispatch(
view.state.tr.replaceWith(
state.selection.from,
@@ -226,7 +227,7 @@ export default class PasteHandler extends Extension {
state.tr
.replaceSelectionWith(
state.schema.nodes.code_block.create({
- language: Object.keys(LANGUAGES).includes(
+ language: Object.keys(codeLanguages).includes(
vscodeMeta.mode
)
? vscodeMeta.mode
@@ -413,6 +414,21 @@ export default class PasteHandler extends Extension {
});
};
+ private insertMention = () => {
+ const { view } = this.editor;
+ const { state } = view;
+ const result = this.findPlaceholder(state, this.state.pastedText);
+
+ // Remove just the placeholder here.
+ // Mention node will be created by SuggestionsMenu.
+ if (result) {
+ const tr = state.tr.deleteRange(result[0], result[1]);
+ view.dispatch(
+ tr.setSelection(TextSelection.near(tr.doc.resolve(result[0])))
+ );
+ }
+ };
+
private removePlaceholder = () => {
const { view } = this.editor;
const { state } = view;
@@ -448,6 +464,11 @@ export default class PasteHandler extends Extension {
this.insertEmbed();
break;
}
+ case "mention": {
+ this.hidePasteMenu();
+ this.insertMention();
+ break;
+ }
default:
break;
}
diff --git a/app/editor/extensions/SmartText.ts b/app/editor/extensions/SmartText.ts
index 4ed503ad8e..4090cb8c9a 100644
--- a/app/editor/extensions/SmartText.ts
+++ b/app/editor/extensions/SmartText.ts
@@ -2,7 +2,8 @@ import Extension from "@shared/editor/lib/Extension";
import { InputRule } from "@shared/editor/lib/InputRule";
const rightArrow = new InputRule(/->$/, "→");
-const emdash = new InputRule(/--$/, "—");
+// Note that the suppression of pipe here prevents conflict with table creation rule.
+const emdash = new InputRule(/(?:^|[^\|])(--)$/, "—");
const oneHalf = new InputRule(/(?:^|\s)(1\/2)$/, "½");
const threeQuarters = new InputRule(/(?:^|\s)(3\/4)$/, "¾");
const copyright = new InputRule(/\(c\)$/, "©️");
diff --git a/app/editor/extensions/Suggestion.ts b/app/editor/extensions/Suggestion.ts
index 33dee58d3c..b77f31ab18 100644
--- a/app/editor/extensions/Suggestion.ts
+++ b/app/editor/extensions/Suggestion.ts
@@ -23,7 +23,7 @@ export default class Suggestion extends Extension {
this.options.trigger
)}(${`[\\p{L}\/\\p{M}\\d${
this.options.allowSpaces ? "\\s{1}" : ""
- }\\.]+`})${this.options.requireSearchTerm ? "" : "?"}$`,
+ }\\.\\-–_]+`})${this.options.requireSearchTerm ? "" : "?"}$`,
"u"
);
}
diff --git a/app/editor/index.tsx b/app/editor/index.tsx
index 0e8fe99a4c..328730bea1 100644
--- a/app/editor/index.tsx
+++ b/app/editor/index.tsx
@@ -843,7 +843,7 @@ const EditorContainer = styled(Styles)<{
${(props) =>
props.userId &&
css`
- .mention[data-id=${props.userId}] {
+ .mention[data-id="${props.userId}"] {
color: ${props.theme.textHighlightForeground};
background: ${props.theme.textHighlight};
diff --git a/app/editor/menus/attachment.tsx b/app/editor/menus/attachment.tsx
index 12fa3c4211..ec948bc255 100644
--- a/app/editor/menus/attachment.tsx
+++ b/app/editor/menus/attachment.tsx
@@ -1,6 +1,5 @@
import { TrashIcon, DownloadIcon, ReplaceIcon } from "outline-icons";
import { EditorState } from "prosemirror-state";
-import * as React from "react";
import { MenuItem } from "@shared/editor/types";
import { Dictionary } from "~/hooks/useDictionary";
diff --git a/app/editor/menus/code.tsx b/app/editor/menus/code.tsx
index 07fa0b7da3..cd69050cff 100644
--- a/app/editor/menus/code.tsx
+++ b/app/editor/menus/code.tsx
@@ -1,9 +1,11 @@
import { CopyIcon, ExpandedIcon } from "outline-icons";
import { Node as ProseMirrorNode } from "prosemirror-model";
import { EditorState } from "prosemirror-state";
-import * as React from "react";
-import { LANGUAGES } from "@shared/editor/extensions/Prism";
-import { getFrequentCodeLanguages } from "@shared/editor/lib/code";
+import {
+ getFrequentCodeLanguages,
+ codeLanguages,
+ getLabelForLanguage,
+} from "@shared/editor/lib/code";
import { MenuItem } from "@shared/editor/types";
import { Dictionary } from "~/hooks/useDictionary";
@@ -14,20 +16,19 @@ export default function codeMenuItems(
): MenuItem[] {
const node = state.selection.$from.node();
- const allLanguages = Object.entries(LANGUAGES) as [
- keyof typeof LANGUAGES,
- string
- ][];
const frequentLanguages = getFrequentCodeLanguages();
const frequentLangMenuItems = frequentLanguages.map((value) => {
- const label = LANGUAGES[value];
+ const label = codeLanguages[value]?.label;
return langToMenuItem({ node, value, label });
});
- const remainingLangMenuItems = allLanguages
- .filter(([value]) => !frequentLanguages.includes(value))
- .map(([value, label]) => langToMenuItem({ node, value, label }));
+ const remainingLangMenuItems = Object.entries(codeLanguages)
+ .filter(
+ ([value]) =>
+ !frequentLanguages.includes(value as keyof typeof codeLanguages)
+ )
+ .map(([value, item]) => langToMenuItem({ node, value, label: item.label }));
const languageMenuItems = frequentLangMenuItems.length
? [
@@ -52,8 +53,7 @@ export default function codeMenuItems(
visible: !readOnly,
name: "code_block",
icon: ,
- // @ts-expect-error We have a fallback for incorrect mapping
- label: LANGUAGES[node.attrs.language ?? "none"],
+ label: getLabelForLanguage(node.attrs.language ?? "none"),
children: languageMenuItems,
},
];
diff --git a/app/editor/menus/divider.tsx b/app/editor/menus/divider.tsx
index 384989ace5..6c889b3997 100644
--- a/app/editor/menus/divider.tsx
+++ b/app/editor/menus/divider.tsx
@@ -1,6 +1,5 @@
import { PageBreakIcon, HorizontalRuleIcon } from "outline-icons";
import { EditorState } from "prosemirror-state";
-import * as React from "react";
import { isNodeActive } from "@shared/editor/queries/isNodeActive";
import { MenuItem } from "@shared/editor/types";
import { Dictionary } from "~/hooks/useDictionary";
diff --git a/app/editor/menus/formatting.tsx b/app/editor/menus/formatting.tsx
index 3baf9e0044..6d8f4a81ec 100644
--- a/app/editor/menus/formatting.tsx
+++ b/app/editor/menus/formatting.tsx
@@ -19,7 +19,6 @@ import {
Heading3Icon,
} from "outline-icons";
import { EditorState } from "prosemirror-state";
-import * as React from "react";
import styled from "styled-components";
import Highlight from "@shared/editor/marks/Highlight";
import { getMarksBetween } from "@shared/editor/queries/getMarksBetween";
@@ -67,7 +66,7 @@ export default function formattingMenuItems(
shortcut: `${metaDisplay}+B`,
icon: ,
active: isMarkActive(schema.marks.strong),
- visible: !isCode && (!isMobile || !isEmpty),
+ visible: !isCodeBlock && (!isMobile || !isEmpty),
},
{
name: "em",
@@ -75,7 +74,7 @@ export default function formattingMenuItems(
shortcut: `${metaDisplay}+I`,
icon: ,
active: isMarkActive(schema.marks.em),
- visible: !isCode && (!isMobile || !isEmpty),
+ visible: !isCodeBlock && (!isMobile || !isEmpty),
},
{
name: "strikethrough",
@@ -83,7 +82,7 @@ export default function formattingMenuItems(
shortcut: `${metaDisplay}+D`,
icon: ,
active: isMarkActive(schema.marks.strikethrough),
- visible: !isCode && (!isMobile || !isEmpty),
+ visible: !isCodeBlock && (!isMobile || !isEmpty),
},
{
tooltip: dictionary.mark,
diff --git a/app/editor/menus/image.tsx b/app/editor/menus/image.tsx
index f67796a06c..5370f1f168 100644
--- a/app/editor/menus/image.tsx
+++ b/app/editor/menus/image.tsx
@@ -8,7 +8,6 @@ import {
AlignFullWidthIcon,
} from "outline-icons";
import { EditorState } from "prosemirror-state";
-import * as React from "react";
import { isNodeActive } from "@shared/editor/queries/isNodeActive";
import { MenuItem } from "@shared/editor/types";
import { Dictionary } from "~/hooks/useDictionary";
diff --git a/app/editor/menus/notice.tsx b/app/editor/menus/notice.tsx
index a1125c6b80..7909eb0e72 100644
--- a/app/editor/menus/notice.tsx
+++ b/app/editor/menus/notice.tsx
@@ -6,7 +6,6 @@ import {
WarningIcon,
} from "outline-icons";
import { EditorState } from "prosemirror-state";
-import * as React from "react";
import { NoticeTypes } from "@shared/editor/nodes/Notice";
import { MenuItem } from "@shared/editor/types";
import { Dictionary } from "~/hooks/useDictionary";
diff --git a/app/editor/menus/readOnly.tsx b/app/editor/menus/readOnly.tsx
index 0ee5c76647..e80b0e4a55 100644
--- a/app/editor/menus/readOnly.tsx
+++ b/app/editor/menus/readOnly.tsx
@@ -1,6 +1,5 @@
import { CommentIcon } from "outline-icons";
import { EditorState } from "prosemirror-state";
-import * as React from "react";
import { isMarkActive } from "@shared/editor/queries/isMarkActive";
import { MenuItem } from "@shared/editor/types";
import { Dictionary } from "~/hooks/useDictionary";
diff --git a/app/editor/menus/table.tsx b/app/editor/menus/table.tsx
index d0d7d23405..873f8b5a9c 100644
--- a/app/editor/menus/table.tsx
+++ b/app/editor/menus/table.tsx
@@ -1,6 +1,5 @@
import { AlignFullWidthIcon, DownloadIcon, TrashIcon } from "outline-icons";
import { EditorState } from "prosemirror-state";
-import * as React from "react";
import { isNodeActive } from "@shared/editor/queries/isNodeActive";
import { MenuItem, TableLayout } from "@shared/editor/types";
import { Dictionary } from "~/hooks/useDictionary";
diff --git a/app/editor/menus/tableCol.tsx b/app/editor/menus/tableCol.tsx
index 0f84506224..25a31aefc5 100644
--- a/app/editor/menus/tableCol.tsx
+++ b/app/editor/menus/tableCol.tsx
@@ -10,7 +10,6 @@ import {
TableHeaderColumnIcon,
} from "outline-icons";
import { EditorState } from "prosemirror-state";
-import * as React from "react";
import styled from "styled-components";
import { isNodeActive } from "@shared/editor/queries/isNodeActive";
import { MenuItem } from "@shared/editor/types";
diff --git a/app/editor/menus/tableRow.tsx b/app/editor/menus/tableRow.tsx
index 9c7ef62b31..6c48a9c2db 100644
--- a/app/editor/menus/tableRow.tsx
+++ b/app/editor/menus/tableRow.tsx
@@ -6,7 +6,6 @@ import {
TableHeaderRowIcon,
} from "outline-icons";
import { EditorState } from "prosemirror-state";
-import * as React from "react";
import { MenuItem } from "@shared/editor/types";
import { Dictionary } from "~/hooks/useDictionary";
diff --git a/app/hooks/useAutoRefresh.ts b/app/hooks/useAutoRefresh.ts
index 609af54722..c353e366f0 100644
--- a/app/hooks/useAutoRefresh.ts
+++ b/app/hooks/useAutoRefresh.ts
@@ -1,4 +1,4 @@
-import * as React from "react";
+import { useState } from "react";
import { Minute } from "@shared/utils/time";
import Logger from "~/utils/Logger";
import useIdle from "./useIdle";
@@ -14,7 +14,7 @@ let isReloaded = false;
* Hook to reload the app around once a day to stop old code from running.
*/
export default function useAutoRefresh() {
- const [minutes, setMinutes] = React.useState(0);
+ const [minutes, setMinutes] = useState(0);
const isVisible = usePageVisibility();
const isIdle = useIdle(15 * Minute.ms);
diff --git a/app/hooks/useBoolean.ts b/app/hooks/useBoolean.ts
index d65b476518..8318750cc1 100644
--- a/app/hooks/useBoolean.ts
+++ b/app/hooks/useBoolean.ts
@@ -1,4 +1,4 @@
-import * as React from "react";
+import { useState, useCallback } from "react";
type InitialState = boolean | (() => boolean);
@@ -10,12 +10,12 @@ type InitialState = boolean | (() => boolean);
export default function useBoolean(
initialState: InitialState = false
): [boolean, () => void, () => void] {
- const [value, setValue] = React.useState(initialState);
- const setTrue = React.useCallback(() => {
+ const [value, setValue] = useState(initialState);
+ const setTrue = useCallback(() => {
setValue(true);
}, []);
- const setFalse = React.useCallback(() => {
+ const setFalse = useCallback(() => {
setValue(false);
}, []);
diff --git a/app/hooks/useBuildTheme.ts b/app/hooks/useBuildTheme.ts
index a2f827b81a..0e35f151f4 100644
--- a/app/hooks/useBuildTheme.ts
+++ b/app/hooks/useBuildTheme.ts
@@ -1,4 +1,4 @@
-import * as React from "react";
+import { useMemo } from "react";
import { breakpoints } from "@shared/styles";
import {
buildDarkTheme,
@@ -27,7 +27,7 @@ export default function useBuildTheme(
const isPrinting = useMediaQuery("print");
const resolvedTheme = overrideTheme ?? ui.resolvedTheme;
- const theme = React.useMemo(
+ const theme = useMemo(
() =>
isPrinting
? buildLightTheme(customTheme)
diff --git a/app/hooks/useCollectionTrees.ts b/app/hooks/useCollectionTrees.ts
index c53cba0b02..de4338038f 100644
--- a/app/hooks/useCollectionTrees.ts
+++ b/app/hooks/useCollectionTrees.ts
@@ -1,4 +1,4 @@
-import * as React from "react";
+import { useMemo } from "react";
import { NavigationNode, NavigationNodeType } from "@shared/types";
import { sortNavigationNodes } from "@shared/utils/collections";
import Collection from "~/models/Collection";
@@ -77,7 +77,7 @@ export default function useCollectionTrees(): NavigationNode[] {
};
const key = collections.orderedData.map((o) => o.documents?.length).join("-");
- const collectionTrees = React.useMemo(
+ const collectionTrees = useMemo(
() => collections.orderedData.map(getCollectionTree),
// eslint-disable-next-line react-hooks/exhaustive-deps
[collections.orderedData, key]
diff --git a/app/hooks/useDesktopTitlebar.ts b/app/hooks/useDesktopTitlebar.ts
index 937c514c31..e004a325bf 100644
--- a/app/hooks/useDesktopTitlebar.ts
+++ b/app/hooks/useDesktopTitlebar.ts
@@ -1,8 +1,8 @@
-import * as React from "react";
+import { useEffect } from "react";
import Desktop from "~/utils/Desktop";
export const useDesktopTitlebar = () => {
- React.useEffect(() => {
+ useEffect(() => {
if (!Desktop.bridge) {
return;
}
diff --git a/app/hooks/useDictionary.ts b/app/hooks/useDictionary.ts
index 5b16343526..03dc05e8a2 100644
--- a/app/hooks/useDictionary.ts
+++ b/app/hooks/useDictionary.ts
@@ -1,10 +1,15 @@
-import * as React from "react";
+import { useMemo } from "react";
import { useTranslation } from "react-i18next";
+/**
+ * Hook that provides a dictionary of translated UI strings.
+ *
+ * @returns An object containing all translated UI strings used throughout the application
+ */
export default function useDictionary() {
const { t } = useTranslation();
- return React.useMemo(
+ return useMemo(
() => ({
addColumnAfter: t("Add column after"),
addColumnBefore: t("Add column before"),
diff --git a/app/hooks/useEditorClickHandlers.ts b/app/hooks/useEditorClickHandlers.ts
index d37767d51a..a5e5ad7e0e 100644
--- a/app/hooks/useEditorClickHandlers.ts
+++ b/app/hooks/useEditorClickHandlers.ts
@@ -1,4 +1,4 @@
-import * as React from "react";
+import { useCallback } from "react";
import { useHistory } from "react-router-dom";
import { isModKey } from "@shared/utils/keyboard";
import { isDocumentUrl, isInternalUrl } from "@shared/utils/urls";
@@ -14,7 +14,7 @@ type Params = {
export default function useEditorClickHandlers({ shareId }: Params) {
const history = useHistory();
const { documents } = useStores();
- const handleClickLink = React.useCallback(
+ const handleClickLink = useCallback(
(href: string, event?: MouseEvent) => {
// on page hash
if (isHash(href)) {
diff --git a/app/hooks/useEmbeds.ts b/app/hooks/useEmbeds.ts
index 56482a999b..ef62f19532 100644
--- a/app/hooks/useEmbeds.ts
+++ b/app/hooks/useEmbeds.ts
@@ -1,5 +1,5 @@
import find from "lodash/find";
-import * as React from "react";
+import { useEffect, useMemo } from "react";
import embeds from "@shared/editor/embeds";
import { IntegrationType } from "@shared/types";
import Integration from "~/models/Integration";
@@ -15,11 +15,10 @@ import useStores from "./useStores";
export default function useEmbeds(loadIfMissing = false) {
const { integrations } = useStores();
- React.useEffect(() => {
+ useEffect(() => {
async function fetchEmbedIntegrations() {
try {
- await integrations.fetchPage({
- limit: 100,
+ await integrations.fetchAll({
type: IntegrationType.Embed,
});
} catch (err) {
@@ -32,7 +31,7 @@ export default function useEmbeds(loadIfMissing = false) {
}
}, [integrations, loadIfMissing]);
- return React.useMemo(
+ return useMemo(
() =>
embeds.map((e) => {
// Find any integrations that match this embed and inject the settings
diff --git a/app/hooks/useEventListener.ts b/app/hooks/useEventListener.ts
index 66ff46a404..139f2cc283 100644
--- a/app/hooks/useEventListener.ts
+++ b/app/hooks/useEventListener.ts
@@ -1,4 +1,4 @@
-import * as React from "react";
+import { useRef, useEffect } from "react";
/**
* Helper to remove plumbing involved with adding and removing an event listener
@@ -15,14 +15,14 @@ export default function useEventListener(
element: Window | VisualViewport | Node | null = window,
options: AddEventListenerOptions = {}
) {
- const savedHandler = React.useRef();
+ const savedHandler = useRef();
const { capture, passive, once } = options;
- React.useEffect(() => {
+ useEffect(() => {
savedHandler.current = handler;
}, [handler]);
- React.useEffect(() => {
+ useEffect(() => {
const isSupported = element && element.addEventListener;
if (!isSupported) {
return;
diff --git a/app/hooks/useHover.ts b/app/hooks/useHover.ts
index 434c7120c6..eb52d30781 100644
--- a/app/hooks/useHover.ts
+++ b/app/hooks/useHover.ts
@@ -1,4 +1,4 @@
-import React from "react";
+import * as React from "react";
import useUnmount from "./useUnmount";
type Props = {
diff --git a/app/hooks/useIdle.ts b/app/hooks/useIdle.ts
index 23e0e5c185..811040742f 100644
--- a/app/hooks/useIdle.ts
+++ b/app/hooks/useIdle.ts
@@ -1,5 +1,5 @@
import throttle from "lodash/throttle";
-import * as React from "react";
+import { useState, useRef, useCallback, useEffect } from "react";
import { Minute } from "@shared/utils/time";
import useIsMounted from "./useIsMounted";
@@ -27,10 +27,10 @@ export default function useIdle(
events = activityEvents
) {
const isMounted = useIsMounted();
- const [isIdle, setIsIdle] = React.useState(false);
- const timeout = React.useRef>();
+ const [isIdle, setIsIdle] = useState(false);
+ const timeout = useRef>();
- const onActivity = React.useCallback(() => {
+ const onActivity = useCallback(() => {
if (timeout.current) {
clearTimeout(timeout.current);
}
@@ -42,7 +42,7 @@ export default function useIdle(
}, timeToIdle);
}, [isMounted, timeToIdle]);
- React.useEffect(() => {
+ useEffect(() => {
const handleUserActivityEvent = throttle(() => {
if (isMounted()) {
setIsIdle(false);
diff --git a/app/hooks/useImportDocument.ts b/app/hooks/useImportDocument.ts
index 09fbab6dc2..5f1da008b8 100644
--- a/app/hooks/useImportDocument.ts
+++ b/app/hooks/useImportDocument.ts
@@ -1,5 +1,5 @@
import invariant from "invariant";
-import * as React from "react";
+import { useState, useCallback } from "react";
import { useTranslation } from "react-i18next";
import { useHistory } from "react-router-dom";
import { toast } from "sonner";
@@ -16,10 +16,10 @@ export default function useImportDocument(
isImporting: boolean;
} {
const { documents } = useStores();
- const [isImporting, setImporting] = React.useState(false);
+ const [isImporting, setImporting] = useState(false);
const { t } = useTranslation();
const history = useHistory();
- const handleFiles = React.useCallback(
+ const handleFiles = useCallback(
async (files = []) => {
if (importingLock) {
return;
diff --git a/app/hooks/useInterval.ts b/app/hooks/useInterval.ts
index 29c5e30fbc..9d73e4ad57 100644
--- a/app/hooks/useInterval.ts
+++ b/app/hooks/useInterval.ts
@@ -1,4 +1,4 @@
-import * as React from "react";
+import { useRef, useEffect } from "react";
type Callback = () => void;
@@ -9,15 +9,15 @@ type Callback = () => void;
* @param delay The delay in milliseconds.
*/
export default function useInterval(callback: Callback, delay: number) {
- const savedCallback = React.useRef();
+ const savedCallback = useRef();
// Remember the latest callback.
- React.useEffect(() => {
+ useEffect(() => {
savedCallback.current = callback;
}, [callback]);
// Set up the interval.
- React.useEffect(() => {
+ useEffect(() => {
function tick() {
savedCallback.current?.();
}
diff --git a/app/hooks/useIsMounted.ts b/app/hooks/useIsMounted.ts
index c1b6f141b2..3770b66a58 100644
--- a/app/hooks/useIsMounted.ts
+++ b/app/hooks/useIsMounted.ts
@@ -1,19 +1,3 @@
-import * as React from "react";
+import useIsMounted from "@shared/hooks/useIsMounted";
-/**
- * Hook to check if component is still mounted
- *
- * @returns {boolean} true if the component is mounted, false otherwise
- */
-export default function useIsMounted() {
- const isMounted = React.useRef(false);
-
- React.useEffect(() => {
- isMounted.current = true;
- return () => {
- isMounted.current = false;
- };
- }, []);
-
- return React.useCallback(() => isMounted.current, []);
-}
+export default useIsMounted;
diff --git a/app/hooks/useKeyDown.ts b/app/hooks/useKeyDown.ts
index e11270d5c5..2f885fe93f 100644
--- a/app/hooks/useKeyDown.ts
+++ b/app/hooks/useKeyDown.ts
@@ -1,4 +1,4 @@
-import * as React from "react";
+import { useEffect } from "react";
import { isModKey } from "@shared/utils/keyboard";
import isTextInput from "~/utils/isTextInput";
@@ -40,7 +40,7 @@ export default function useKeyDown(
): void {
const predicate = createKeyPredicate(key);
- React.useEffect(() => {
+ useEffect(() => {
const handler = (event: KeyboardEvent) => {
if (predicate(event)) {
fn(event);
diff --git a/app/hooks/useLastVisitedPath.tsx b/app/hooks/useLastVisitedPath.tsx
index e2580c681a..05b2deb95d 100644
--- a/app/hooks/useLastVisitedPath.tsx
+++ b/app/hooks/useLastVisitedPath.tsx
@@ -1,4 +1,4 @@
-import * as React from "react";
+import { useCallback } from "react";
import { getCookie, removeCookie, setCookie } from "tiny-cookie";
import usePersistedState from "~/hooks/usePersistedState";
import Logger from "~/utils/Logger";
@@ -18,7 +18,7 @@ export function useLastVisitedPath(): [string, (path: string) => void] {
{ listen: false }
);
- const setPathAsLastVisitedPath = React.useCallback(
+ const setPathAsLastVisitedPath = useCallback(
(path: string) => {
if (isAllowedLoginRedirect(path) && path !== lastVisitedPath) {
setLastVisitedPath(path);
@@ -58,7 +58,7 @@ export function setPostLoginPath(path: string) {
export function usePostLoginPath() {
const key = "postLoginRedirectPath";
- const getter = React.useCallback(() => {
+ const getter = useCallback(() => {
let path;
try {
path = sessionStorage.getItem(key) || getCookie(key);
diff --git a/app/hooks/useLocaleTime.ts b/app/hooks/useLocaleTime.ts
index 0e6c832bd8..c666d0ae5e 100644
--- a/app/hooks/useLocaleTime.ts
+++ b/app/hooks/useLocaleTime.ts
@@ -1,5 +1,5 @@
import { format as formatDate } from "date-fns";
-import * as React from "react";
+import { useState, useRef, useEffect } from "react";
import { dateLocale, dateToRelative, locales } from "@shared/utils/date";
import useUserLocale from "~/hooks/useUserLocale";
@@ -44,10 +44,10 @@ export const useLocaleTime = ({
"MMMM do, yyyy h:mm a";
// @ts-expect-error fallback to formatLocaleLong
const formatLocale = format?.[userLocale] ?? formatLocaleLong;
- const [_, setMinutesMounted] = React.useState(0); // eslint-disable-line @typescript-eslint/no-unused-vars
- const callback = React.useRef<() => void>();
+ const [_, setMinutesMounted] = useState(0); // eslint-disable-line @typescript-eslint/no-unused-vars
+ const callback = useRef<() => void>();
- React.useEffect(() => {
+ useEffect(() => {
callback.current = eachMinute(() => {
setMinutesMounted((state) => ++state);
});
diff --git a/app/hooks/useLoggedInSessions.ts b/app/hooks/useLoggedInSessions.ts
new file mode 100644
index 0000000000..dbdbbcf719
--- /dev/null
+++ b/app/hooks/useLoggedInSessions.ts
@@ -0,0 +1,14 @@
+import { getCookie } from "tiny-cookie";
+
+export type Sessions = Record<
+ string,
+ {
+ name: string;
+ logoUrl: string;
+ url: string;
+ }
+>;
+
+export function useLoggedInSessions(): Sessions {
+ return JSON.parse(getCookie("sessions") || "{}");
+}
diff --git a/app/hooks/useMaxHeight.ts b/app/hooks/useMaxHeight.ts
index c3f5e0a922..6e8300f4b7 100644
--- a/app/hooks/useMaxHeight.ts
+++ b/app/hooks/useMaxHeight.ts
@@ -1,6 +1,15 @@
import * as React from "react";
import useWindowSize from "./useWindowSize";
+/**
+ * Hook to calculate the maximum height for an element based on its position and viewport size.
+ *
+ * @param options Configuration options
+ * @param options.elementRef A ref pointing to the element to calculate max height for
+ * @param options.maxViewportPercentage The maximum height of the element as a percentage of the viewport
+ * @param options.margin The margin to apply to the positioning
+ * @returns Object containing the calculated maxHeight and a function to recalculate it
+ */
const useMaxHeight = ({
elementRef,
maxViewportPercentage = 90,
diff --git a/app/hooks/useMediaQuery.ts b/app/hooks/useMediaQuery.ts
index ccf8d90590..79234ad0bb 100644
--- a/app/hooks/useMediaQuery.ts
+++ b/app/hooks/useMediaQuery.ts
@@ -1,5 +1,11 @@
import { useState, useEffect } from "react";
+/**
+ * Hook to check if a media query matches the current viewport.
+ *
+ * @param query The CSS media query to check against
+ * @returns boolean indicating whether the media query matches
+ */
export default function useMediaQuery(query: string): boolean {
const [matches, setMatches] = useState(false);
diff --git a/app/hooks/useMenuContext.tsx b/app/hooks/useMenuContext.tsx
index eb408f7a5d..8bdca2a51b 100644
--- a/app/hooks/useMenuContext.tsx
+++ b/app/hooks/useMenuContext.tsx
@@ -1,25 +1,54 @@
import noop from "lodash/noop";
-import React from "react";
+import * as React from "react";
type MenuContextType = {
isMenuOpen: boolean;
setIsMenuOpen: React.Dispatch>;
+ registerMenu: (menuId: string, hideFunction: () => void) => void;
+ unregisterMenu: (menuId: string) => void;
+ closeOtherMenus: (excludeMenuId: string) => void;
};
const MenuContext = React.createContext(null);
+// Registry to track all active menu instances
+const menuRegistry = new Map();
+
type Props = {
children?: React.ReactNode;
};
export const MenuProvider: React.FC = ({ children }: Props) => {
const [isMenuOpen, setIsMenuOpen] = React.useState(false);
+
+ const registerMenu = React.useCallback(
+ (menuId: string, hideFunction: () => void) => {
+ menuRegistry.set(menuId, hideFunction);
+ },
+ []
+ );
+
+ const unregisterMenu = React.useCallback((menuId: string) => {
+ menuRegistry.delete(menuId);
+ }, []);
+
+ const closeOtherMenus = React.useCallback((excludeMenuId: string) => {
+ menuRegistry.forEach((hideFunction, menuId) => {
+ if (menuId !== excludeMenuId) {
+ hideFunction();
+ }
+ });
+ }, []);
+
const memoized = React.useMemo(
() => ({
isMenuOpen,
setIsMenuOpen,
+ registerMenu,
+ unregisterMenu,
+ closeOtherMenus,
}),
- [isMenuOpen, setIsMenuOpen]
+ [isMenuOpen, setIsMenuOpen, registerMenu, unregisterMenu, closeOtherMenus]
);
return (
@@ -29,7 +58,15 @@ export const MenuProvider: React.FC = ({ children }: Props) => {
const useMenuContext: () => MenuContextType = () => {
const value = React.useContext(MenuContext);
- return value ? value : { isMenuOpen: false, setIsMenuOpen: noop };
+ return value
+ ? value
+ : {
+ isMenuOpen: false,
+ setIsMenuOpen: noop,
+ registerMenu: noop,
+ unregisterMenu: noop,
+ closeOtherMenus: noop,
+ };
};
export default useMenuContext;
diff --git a/app/hooks/useMenuState.tsx b/app/hooks/useMenuState.tsx
new file mode 100644
index 0000000000..fef3b4b095
--- /dev/null
+++ b/app/hooks/useMenuState.tsx
@@ -0,0 +1,43 @@
+import * as React from "react";
+import {
+ // eslint-disable-next-line no-restricted-imports
+ useMenuState as reakitUseMenuState,
+ MenuStateReturn,
+} from "reakit/Menu";
+import { v4 } from "uuid";
+import useMenuContext from "./useMenuContext";
+
+/**
+ * A hook that wraps Reakit's useMenuState with coordination logic to ensure
+ * only one context menu can be open at a time across the application.
+ */
+export function useMenuState(
+ options?: Parameters[0]
+): MenuStateReturn {
+ const menuState = reakitUseMenuState(options);
+ const { registerMenu, unregisterMenu, closeOtherMenus } = useMenuContext();
+ const menuId = React.useRef(`menu-${v4()}`).current;
+
+ // Register this menu instance on mount and unregister on unmount
+ React.useEffect(() => {
+ registerMenu(menuId, menuState.hide);
+ return () => unregisterMenu(menuId);
+ }, [menuId, menuState.hide, registerMenu, unregisterMenu]);
+
+ const coordinatedShow = React.useCallback(() => {
+ closeOtherMenus(menuId);
+ menuState.show();
+ }, [closeOtherMenus, menuId, menuState]);
+
+ const coordinatedToggle = React.useCallback(() => {
+ closeOtherMenus(menuId);
+ menuState.toggle();
+ }, [menuId, menuState, closeOtherMenus]);
+
+ // Return the menu state with the coordinated show method
+ return {
+ ...menuState,
+ toggle: coordinatedToggle,
+ show: coordinatedShow,
+ };
+}
diff --git a/app/hooks/useMobile.ts b/app/hooks/useMobile.ts
index d703dcdde7..abed58e124 100644
--- a/app/hooks/useMobile.ts
+++ b/app/hooks/useMobile.ts
@@ -1,6 +1,11 @@
import { breakpoints } from "@shared/styles";
import useMediaQuery from "~/hooks/useMediaQuery";
+/**
+ * Hook to detect if the current viewport is mobile-sized.
+ *
+ * @returns boolean indicating whether the current viewport is mobile-sized
+ */
export default function useMobile(): boolean {
return useMediaQuery(`(max-width: ${breakpoints.tablet - 1}px)`);
}
diff --git a/app/hooks/useMousePosition.ts b/app/hooks/useMousePosition.ts
index 46effdfc7f..a844e16e34 100644
--- a/app/hooks/useMousePosition.ts
+++ b/app/hooks/useMousePosition.ts
@@ -1,5 +1,5 @@
import throttle from "lodash/throttle";
-import * as React from "react";
+import { useState, useMemo } from "react";
import useEventListener from "./useEventListener";
import useIsMounted from "./useIsMounted";
@@ -15,11 +15,9 @@ type MousePosition = [number, number];
*/
export const useMousePosition = () => {
const isMounted = useIsMounted();
- const [mousePosition, setMousePosition] = React.useState([
- 0, 0,
- ]);
+ const [mousePosition, setMousePosition] = useState([0, 0]);
- const updateMousePosition = React.useMemo(
+ const updateMousePosition = useMemo(
() =>
throttle((ev: MouseEvent) => {
if (isMounted()) {
diff --git a/app/hooks/usePageVisibility.ts b/app/hooks/usePageVisibility.ts
index 48d5fe3965..7da5c87379 100644
--- a/app/hooks/usePageVisibility.ts
+++ b/app/hooks/usePageVisibility.ts
@@ -1,4 +1,4 @@
-import * as React from "react";
+import { useState } from "react";
import useEventListener from "./useEventListener";
/**
@@ -7,7 +7,7 @@ import useEventListener from "./useEventListener";
* @returns boolean if the page is visible
*/
export default function usePageVisibility(): boolean {
- const [visible, setVisible] = React.useState(true);
+ const [visible, setVisible] = useState(true);
useEventListener(
"visibilitychange",
diff --git a/app/hooks/usePaginatedRequest.ts b/app/hooks/usePaginatedRequest.ts
index caabc9e209..bc86f67fa7 100644
--- a/app/hooks/usePaginatedRequest.ts
+++ b/app/hooks/usePaginatedRequest.ts
@@ -1,5 +1,5 @@
import uniqBy from "lodash/uniqBy";
-import * as React from "react";
+import { useState, useEffect, useCallback } from "react";
import { PaginationParams } from "~/types";
import useRequest from "./useRequest";
@@ -34,13 +34,13 @@ export default function usePaginatedRequest(
requestFn: (params?: PaginationParams | undefined) => Promise,
params: PaginationParams = {}
): RequestResponse {
- const [data, setData] = React.useState();
- const [offset, setOffset] = React.useState(INITIAL_OFFSET);
- const [page, setPage] = React.useState(0);
- const [end, setEnd] = React.useState(false);
+ const [data, setData] = useState();
+ const [offset, setOffset] = useState(INITIAL_OFFSET);
+ const [page, setPage] = useState(0);
+ const [end, setEnd] = useState(false);
const displayLimit = params.limit || DEFAULT_LIMIT;
const fetchLimit = displayLimit + 1;
- const [paginatedReq, setPaginatedReq] = React.useState(
+ const [paginatedReq, setPaginatedReq] = useState(
() => () =>
requestFn({
...params,
@@ -56,11 +56,11 @@ export default function usePaginatedRequest(
request,
} = useRequest(paginatedReq);
- React.useEffect(() => {
+ useEffect(() => {
void request();
}, [request]);
- React.useEffect(() => {
+ useEffect(() => {
if (response && !loading) {
setData((prev) =>
uniqBy((prev ?? []).concat(response.slice(0, displayLimit)), "id")
@@ -70,7 +70,7 @@ export default function usePaginatedRequest(
}
}, [response, displayLimit, loading]);
- React.useEffect(() => {
+ useEffect(() => {
if (offset) {
setPaginatedReq(
() => () =>
@@ -83,11 +83,11 @@ export default function usePaginatedRequest(
}
}, [offset, fetchLimit, requestFn]);
- const next = React.useCallback(() => {
+ const next = useCallback(() => {
setOffset((prev) => prev + displayLimit);
}, [displayLimit]);
- React.useEffect(() => {
+ useEffect(() => {
setEnd(false);
setData(undefined);
setPage(0);
diff --git a/app/hooks/usePersistedState.ts b/app/hooks/usePersistedState.ts
index d75a79d43b..7d92f483b9 100644
--- a/app/hooks/usePersistedState.ts
+++ b/app/hooks/usePersistedState.ts
@@ -1,4 +1,4 @@
-import * as React from "react";
+import { useState, useCallback } from "react";
import { Primitive } from "utility-types";
import Storage from "@shared/utils/Storage";
import { isBrowser } from "@shared/utils/browser";
@@ -41,14 +41,14 @@ export default function usePersistedState(
defaultValue: T,
options?: Options
): [T, (value: T) => void] {
- const [storedValue, setStoredValue] = React.useState(() => {
+ const [storedValue, setStoredValue] = useState(() => {
if (!isBrowser) {
return defaultValue;
}
return Storage.get(key) ?? defaultValue;
});
- const setValue = React.useCallback(
+ const setValue = useCallback(
(value: T | ((value: T) => void)) => {
try {
// Allow value to be a function so we have same API as useState
diff --git a/app/hooks/usePinnedDocuments.ts b/app/hooks/usePinnedDocuments.ts
index a88ed2c120..3e129d5397 100644
--- a/app/hooks/usePinnedDocuments.ts
+++ b/app/hooks/usePinnedDocuments.ts
@@ -1,4 +1,4 @@
-import * as React from "react";
+import { useEffect } from "react";
import usePersistedState from "~/hooks/usePersistedState";
import useStores from "./useStores";
@@ -21,7 +21,7 @@ export function usePinnedDocuments(urlId: UrlId, collectionId?: string) {
: [];
}
- React.useEffect(() => {
+ useEffect(() => {
void pins
.fetchPage(urlId === "home" ? undefined : { collectionId })
.then(() => {
diff --git a/app/hooks/usePolicy.ts b/app/hooks/usePolicy.ts
index 86052f7c3d..74bb2ac9b5 100644
--- a/app/hooks/usePolicy.ts
+++ b/app/hooks/usePolicy.ts
@@ -1,4 +1,4 @@
-import * as React from "react";
+import { useEffect } from "react";
import Model from "~/models/base/Model";
import useCurrentUser from "./useCurrentUser";
import useStores from "./useStores";
@@ -18,8 +18,9 @@ export default function usePolicy(entity?: string | Model | null) {
? entity
: entity.id
: "";
+ const policy = policies.get(entityId);
- React.useEffect(() => {
+ useEffect(() => {
if (
entity &&
typeof entity !== "string" &&
@@ -28,11 +29,11 @@ export default function usePolicy(entity?: string | Model | null) {
) {
// The policy for this model is missing and we have an authenticated session, attempt to
// reload relationships for this model.
- if (!policies.get(entity.id) && user) {
+ if (!policy && user) {
void entity.loadRelations();
}
}
- }, [policies, user, entity]);
+ }, [policies, policy, user, entity]);
return policies.abilities(entityId);
}
diff --git a/app/hooks/usePrevious.ts b/app/hooks/usePrevious.ts
index 6e395ab3c3..4aebbf9e8f 100644
--- a/app/hooks/usePrevious.ts
+++ b/app/hooks/usePrevious.ts
@@ -1,4 +1,4 @@
-import * as React from "react";
+import { useRef, useEffect } from "react";
/**
* A hook to get the previous value of a variable.
@@ -8,9 +8,9 @@ import * as React from "react";
* @returns The previous value of the variable.
*/
export default function usePrevious(value: T, onlyTruthy = false): T | void {
- const ref = React.useRef();
+ const ref = useRef();
- React.useEffect(() => {
+ useEffect(() => {
if (onlyTruthy && !value) {
return;
}
diff --git a/app/hooks/useQuery.ts b/app/hooks/useQuery.ts
index 02405e1afc..42ae9349da 100644
--- a/app/hooks/useQuery.ts
+++ b/app/hooks/useQuery.ts
@@ -1,10 +1,15 @@
-import React from "react";
+import { useMemo } from "react";
import { useLocation } from "react-router-dom";
+/**
+ * Hook to access URL query parameters from the current location.
+ *
+ * @returns URLSearchParams object containing the current URL query parameters
+ */
export default function useQuery() {
const location = useLocation();
- const query = React.useMemo(
+ const query = useMemo(
() => new URLSearchParams(location.search),
[location.search]
);
diff --git a/app/hooks/useQueryNotices.ts b/app/hooks/useQueryNotices.ts
index 145fc00ffe..380cf6de03 100644
--- a/app/hooks/useQueryNotices.ts
+++ b/app/hooks/useQueryNotices.ts
@@ -1,4 +1,4 @@
-import * as React from "react";
+import { useEffect } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { QueryNotices } from "@shared/types";
@@ -14,7 +14,7 @@ export default function useQueryNotices() {
const { t } = useTranslation();
const notice = query.get("notice") as QueryNotices;
- React.useEffect(() => {
+ useEffect(() => {
switch (notice) {
case QueryNotices.UnsubscribeDocument: {
toast.success(
@@ -24,6 +24,14 @@ export default function useQueryNotices() {
);
break;
}
+ case QueryNotices.UnsubscribeCollection: {
+ toast.success(
+ t("Unsubscribed from collection", {
+ type: "success",
+ })
+ );
+ break;
+ }
default:
}
}, [t, notice]);
diff --git a/app/hooks/useRequest.ts b/app/hooks/useRequest.ts
index e5b6eed59a..7bfaae3244 100644
--- a/app/hooks/useRequest.ts
+++ b/app/hooks/useRequest.ts
@@ -1,4 +1,4 @@
-import * as React from "react";
+import { useState, useCallback, useEffect } from "react";
import useIsMounted from "./useIsMounted";
type RequestResponse = {
@@ -26,12 +26,12 @@ export default function useRequest(
makeRequestOnMount = false
): RequestResponse {
const isMounted = useIsMounted();
- const [data, setData] = React.useState();
- const [loading, setLoading] = React.useState(false);
- const [loaded, setLoaded] = React.useState(false);
- const [error, setError] = React.useState();
+ const [data, setData] = useState();
+ const [loading, setLoading] = useState(false);
+ const [loaded, setLoaded] = useState(false);
+ const [error, setError] = useState();
- const request = React.useCallback(async () => {
+ const request = useCallback(async () => {
setLoading(true);
try {
const response = await requestFn();
@@ -55,11 +55,11 @@ export default function useRequest(
return undefined;
}, [requestFn, isMounted]);
- React.useEffect(() => {
+ useEffect(() => {
if (makeRequestOnMount) {
void request();
}
- }, [request, makeRequestOnMount]);
+ }, []);
return { data, loading, loaded, error, request };
}
diff --git a/app/hooks/useSettingsConfig.ts b/app/hooks/useSettingsConfig.ts
index faa4c99bea..635e883c63 100644
--- a/app/hooks/useSettingsConfig.ts
+++ b/app/hooks/useSettingsConfig.ts
@@ -8,28 +8,31 @@ import {
GlobeIcon,
TeamIcon,
BeakerIcon,
- BuildingBlocksIcon,
SettingsIcon,
ExportIcon,
ImportIcon,
ShapesIcon,
Icon,
+ PlusIcon,
+ InternetIcon,
} from "outline-icons";
-import React, { ComponentProps } from "react";
+import { ComponentProps } from "react";
+import * as React from "react";
import { useTranslation } from "react-i18next";
import { integrationSettingsPath } from "@shared/utils/routeHelpers";
-import ZapierIcon from "~/components/Icons/ZapierIcon";
+import { Integrations } from "~/scenes/Settings/Integrations";
+import { createLazyComponent as lazy } from "~/components/LazyLoad";
import { Hook, PluginManager } from "~/utils/PluginManager";
-import isCloudHosted from "~/utils/isCloudHosted";
-import lazy from "~/utils/lazyWithRetry";
import { settingsPath } from "~/utils/routeHelpers";
import { useComputed } from "./useComputed";
import useCurrentTeam from "./useCurrentTeam";
import useCurrentUser from "./useCurrentUser";
import usePolicy from "./usePolicy";
+import useStores from "./useStores";
const ApiKeys = lazy(() => import("~/scenes/Settings/ApiKeys"));
-const PersonalApiKeys = lazy(() => import("~/scenes/Settings/PersonalApiKeys"));
+const Applications = lazy(() => import("~/scenes/Settings/Applications"));
+const APIAndApps = lazy(() => import("~/scenes/Settings/APIAndApps"));
const Details = lazy(() => import("~/scenes/Settings/Details"));
const Export = lazy(() => import("~/scenes/Settings/Export"));
const Features = lazy(() => import("~/scenes/Settings/Features"));
@@ -40,33 +43,40 @@ const Notifications = lazy(() => import("~/scenes/Settings/Notifications"));
const Preferences = lazy(() => import("~/scenes/Settings/Preferences"));
const Profile = lazy(() => import("~/scenes/Settings/Profile"));
const Security = lazy(() => import("~/scenes/Settings/Security"));
-const SelfHosted = lazy(() => import("~/scenes/Settings/SelfHosted"));
const Shares = lazy(() => import("~/scenes/Settings/Shares"));
const Templates = lazy(() => import("~/scenes/Settings/Templates"));
-const Zapier = lazy(() => import("~/scenes/Settings/Zapier"));
export type ConfigItem = {
name: string;
path: string;
icon: React.FC>;
component: React.ComponentType;
+ description?: string;
+ preload?: () => void;
enabled: boolean;
group: string;
+ pluginId?: string;
};
const useSettingsConfig = () => {
+ const { integrations } = useStores();
const user = useCurrentUser();
const team = useCurrentTeam();
const can = usePolicy(team);
const { t } = useTranslation();
+ React.useEffect(() => {
+ void integrations.fetchAll();
+ }, [integrations]);
+
const config = useComputed(() => {
const items: ConfigItem[] = [
// Account
{
name: t("Profile"),
path: settingsPath(),
- component: Profile,
+ component: Profile.Component,
+ preload: Profile.preload,
enabled: true,
group: t("Account"),
icon: ProfileIcon,
@@ -74,7 +84,8 @@ const useSettingsConfig = () => {
{
name: t("Preferences"),
path: settingsPath("preferences"),
- component: Preferences,
+ component: Preferences.Component,
+ preload: Preferences.preload,
enabled: true,
group: t("Account"),
icon: SettingsIcon,
@@ -82,24 +93,27 @@ const useSettingsConfig = () => {
{
name: t("Notifications"),
path: settingsPath("notifications"),
- component: Notifications,
+ component: Notifications.Component,
+ preload: Notifications.preload,
enabled: true,
group: t("Account"),
icon: EmailIcon,
},
{
- name: t("API Keys"),
- path: settingsPath("personal-api-keys"),
- component: PersonalApiKeys,
- enabled: can.createApiKey && !can.listApiKeys,
+ name: t("API & Apps"),
+ path: settingsPath("api-and-apps"),
+ component: APIAndApps.Component,
+ preload: APIAndApps.preload,
+ enabled: true,
group: t("Account"),
- icon: CodeIcon,
+ icon: PadlockIcon,
},
// Workspace
{
name: t("Details"),
path: settingsPath("details"),
- component: Details,
+ component: Details.Component,
+ preload: Details.preload,
enabled: can.update,
group: t("Workspace"),
icon: TeamIcon,
@@ -107,7 +121,8 @@ const useSettingsConfig = () => {
{
name: t("Security"),
path: settingsPath("security"),
- component: Security,
+ component: Security.Component,
+ preload: Security.preload,
enabled: can.update,
group: t("Workspace"),
icon: PadlockIcon,
@@ -115,7 +130,8 @@ const useSettingsConfig = () => {
{
name: t("Features"),
path: settingsPath("features"),
- component: Features,
+ component: Features.Component,
+ preload: Features.preload,
enabled: can.update,
group: t("Workspace"),
icon: BeakerIcon,
@@ -123,7 +139,8 @@ const useSettingsConfig = () => {
{
name: t("Members"),
path: settingsPath("members"),
- component: Members,
+ component: Members.Component,
+ preload: Members.preload,
enabled: can.listUsers,
group: t("Workspace"),
icon: UserIcon,
@@ -131,7 +148,8 @@ const useSettingsConfig = () => {
{
name: t("Groups"),
path: settingsPath("groups"),
- component: Groups,
+ component: Groups.Component,
+ preload: Groups.preload,
enabled: can.listGroups,
group: t("Workspace"),
icon: GroupIcon,
@@ -139,23 +157,35 @@ const useSettingsConfig = () => {
{
name: t("Templates"),
path: settingsPath("templates"),
- component: Templates,
- enabled: can.createDocument,
+ component: Templates.Component,
+ preload: Templates.preload,
+ enabled: can.readTemplate,
group: t("Workspace"),
icon: ShapesIcon,
},
{
name: t("API Keys"),
path: settingsPath("api-keys"),
- component: ApiKeys,
+ component: ApiKeys.Component,
+ preload: ApiKeys.preload,
enabled: can.listApiKeys,
group: t("Workspace"),
icon: CodeIcon,
},
+ {
+ name: t("Applications"),
+ path: settingsPath("applications"),
+ component: Applications.Component,
+ preload: Applications.preload,
+ enabled: can.listOAuthClients,
+ group: t("Workspace"),
+ icon: InternetIcon,
+ },
{
name: t("Shared Links"),
path: settingsPath("shares"),
- component: Shares,
+ component: Shares.Component,
+ preload: Shares.preload,
enabled: can.listShares,
group: t("Workspace"),
icon: GlobeIcon,
@@ -163,7 +193,8 @@ const useSettingsConfig = () => {
{
name: t("Import"),
path: settingsPath("import"),
- component: Import,
+ component: Import.Component,
+ preload: Import.preload,
enabled: can.createImport,
group: t("Workspace"),
icon: ImportIcon,
@@ -171,27 +202,20 @@ const useSettingsConfig = () => {
{
name: t("Export"),
path: settingsPath("export"),
- component: Export,
+ component: Export.Component,
+ preload: Export.preload,
enabled: can.createExport,
group: t("Workspace"),
icon: ExportIcon,
},
// Integrations
{
- name: t("Self Hosted"),
- path: integrationSettingsPath("self-hosted"),
- component: SelfHosted,
- enabled: can.update && !isCloudHosted,
+ name: `${t("Install")}…`,
+ path: settingsPath("integrations"),
+ component: Integrations,
+ enabled: true,
group: t("Integrations"),
- icon: BuildingBlocksIcon,
- },
- {
- name: "Zapier",
- path: integrationSettingsPath("zapier"),
- component: Zapier,
- enabled: can.update && isCloudHosted,
- group: t("Integrations"),
- icon: ZapierIcon,
+ icon: PlusIcon,
},
];
@@ -208,7 +232,10 @@ const useSettingsConfig = () => {
? integrationSettingsPath(plugin.id)
: settingsPath(plugin.id),
group: t(group),
- component: plugin.value.component,
+ pluginId: plugin.id,
+ description: plugin.value.description,
+ component: plugin.value.component.Component,
+ preload: plugin.value.component.preload,
enabled: plugin.value.enabled
? plugin.value.enabled(team, user)
: can.update,
diff --git a/app/hooks/useStores.ts b/app/hooks/useStores.ts
index e77130ebf9..a4a0edf6a3 100644
--- a/app/hooks/useStores.ts
+++ b/app/hooks/useStores.ts
@@ -1,7 +1,12 @@
import { MobXProviderContext } from "mobx-react";
-import * as React from "react";
+import { useContext } from "react";
import RootStore from "~/stores";
+/**
+ * Hook to access the MobX stores from the React context.
+ *
+ * @returns The root store containing all application stores
+ */
export default function useStores() {
- return React.useContext(MobXProviderContext) as typeof RootStore;
+ return useContext(MobXProviderContext) as typeof RootStore;
}
diff --git a/app/hooks/useTableRequest.ts b/app/hooks/useTableRequest.ts
index 206230f14e..3ee2454c25 100644
--- a/app/hooks/useTableRequest.ts
+++ b/app/hooks/useTableRequest.ts
@@ -1,6 +1,6 @@
import { ColumnSort } from "@tanstack/react-table";
import orderBy from "lodash/orderBy";
-import React from "react";
+import { useState, useRef, useCallback, useEffect } from "react";
import {
FetchPageParams,
PaginatedResponse,
@@ -31,19 +31,19 @@ export function useTableRequest({
reqFn,
reqParams,
}: Props): Response {
- const [total, setTotal] = React.useState();
- const [offset, setOffset] = React.useState({ value: INITIAL_OFFSET });
- const prevParamsRef = React.useRef(reqParams);
- const sortRef = React.useRef(sort);
+ const [total, setTotal] = useState();
+ const [offset, setOffset] = useState({ value: INITIAL_OFFSET });
+ const prevParamsRef = useRef(reqParams);
+ const sortRef = useRef(sort);
- const fetchPage = React.useCallback(
+ const fetchPage = useCallback(
() => reqFn({ ...reqParams, offset: offset.value, limit: PAGE_SIZE }),
[reqFn, reqParams, offset]
);
const { request, loading, error } = useRequest(fetchPage);
- const nextPage = React.useCallback(
+ const nextPage = useCallback(
() =>
setOffset((prev) => ({
value: prev.value + PAGE_SIZE,
@@ -60,7 +60,7 @@ export function useTableRequest({
? nextPage
: undefined;
- React.useEffect(() => {
+ useEffect(() => {
if (prevParamsRef.current !== reqParams) {
prevParamsRef.current = reqParams;
setOffset({ value: INITIAL_OFFSET });
diff --git a/app/hooks/useTemplateMenuItems.tsx b/app/hooks/useTemplateMenuItems.tsx
new file mode 100644
index 0000000000..a73bf6cf7d
--- /dev/null
+++ b/app/hooks/useTemplateMenuItems.tsx
@@ -0,0 +1,85 @@
+import { DocumentIcon } from "outline-icons";
+import { useCallback, useMemo } from "react";
+import { useTranslation } from "react-i18next";
+import Icon from "@shared/components/Icon";
+import { TextHelper } from "@shared/utils/TextHelper";
+import Document from "~/models/Document";
+import Template from "~/models/Template";
+import useCurrentUser from "~/hooks/useCurrentUser";
+import useStores from "~/hooks/useStores";
+import { MenuItem } from "~/types";
+
+type Props = {
+ /** The document to which the templates will be applied */
+ document: Document;
+ /** Callback to handle when a template is selected */
+ onSelectTemplate?: (template: Template) => void;
+};
+
+/**
+ * This hook provides a memoized list of menu items for both collection-specific
+ * templates and workspace-wide templates. It filters templates based on whether
+ * they are published and organizes them into appropriate sections.
+ *
+ * Collection-specific templates are displayed first, followed by workspace templates
+ * with a separator in between (if both types exist).
+ *
+ * @returns An array of MenuItem objects representing templates that can be applied
+ * to the current document. Returns an empty array if no callback is provided.
+ */
+export function useTemplateMenuItems({ document, onSelectTemplate }: Props) {
+ const user = useCurrentUser();
+ const { templates } = useStores();
+ const { t } = useTranslation();
+
+ const templateToMenuItem = useCallback(
+ (template: Template): MenuItem => ({
+ type: "button",
+ title: TextHelper.replaceTemplateVariables(
+ template.titleWithDefault,
+ user
+ ),
+ icon: template.icon ? (
+
+ ) : (
+
+ ),
+ onClick: () => onSelectTemplate?.(template),
+ }),
+ [user, onSelectTemplate]
+ );
+
+ const collectionItems = templates.orderedData
+ .filter(
+ (template) =>
+ !template.isWorkspaceTemplate &&
+ template.collectionId === document.collectionId
+ )
+ .map(templateToMenuItem);
+
+ const workspaceTemplates = templates.orderedData
+ .filter((tmpl) => tmpl.isWorkspaceTemplate)
+ .map(templateToMenuItem);
+
+ const workspaceItems: MenuItem[] = useMemo(
+ () =>
+ workspaceTemplates.length
+ ? [{ type: "heading", title: t("Workspace") }, ...workspaceTemplates]
+ : [],
+ [t, workspaceTemplates]
+ );
+
+ if (!onSelectTemplate) {
+ return [];
+ }
+
+ return collectionItems
+ ? workspaceItems.length
+ ? [
+ ...collectionItems,
+ { type: "separator" } as MenuItem,
+ ...workspaceItems,
+ ]
+ : collectionItems
+ : workspaceItems;
+}
diff --git a/app/hooks/useTextSelection.ts b/app/hooks/useTextSelection.ts
index df2d6686ca..6894fd8a07 100644
--- a/app/hooks/useTextSelection.ts
+++ b/app/hooks/useTextSelection.ts
@@ -1,4 +1,4 @@
-import * as React from "react";
+import { useState } from "react";
import useEventListener from "./useEventListener";
/**
@@ -7,7 +7,7 @@ import useEventListener from "./useEventListener";
* @returns The selected text
*/
export default function useTextSelection() {
- const [selection, setSelection] = React.useState("");
+ const [selection, setSelection] = useState("");
useEventListener(
"selectionchange",
diff --git a/app/hooks/useUnmount.ts b/app/hooks/useUnmount.ts
index 5be355e00c..8cf1f5cc4e 100644
--- a/app/hooks/useUnmount.ts
+++ b/app/hooks/useUnmount.ts
@@ -1,10 +1,15 @@
-import * as React from "react";
+import { useRef, useEffect } from "react";
+/**
+ * Hook that executes a callback when the component unmounts.
+ *
+ * @param callback Function to be called on component unmount
+ */
const useUnmount = (callback: (...args: Array) => any) => {
- const ref = React.useRef(callback);
+ const ref = useRef(callback);
ref.current = callback;
- React.useEffect(
+ useEffect(
() => () => {
ref.current();
},
diff --git a/app/hooks/useViewportHeight.ts b/app/hooks/useViewportHeight.ts
index 6175f314c3..3915de50a6 100644
--- a/app/hooks/useViewportHeight.ts
+++ b/app/hooks/useViewportHeight.ts
@@ -1,5 +1,11 @@
import { useLayoutEffect, useState } from "react";
+/**
+ * Hook to get the current viewport height, accounting for mobile virtual keyboards.
+ * Uses the VisualViewport API when available, falling back to window.innerHeight.
+ *
+ * @returns The current viewport height in pixels
+ */
export default function useViewportHeight(): number | void {
// https://developer.mozilla.org/en-US/docs/Web/API/VisualViewport#browser_compatibility
// Note: No support in Firefox at time of writing, however this mainly exists
diff --git a/app/hooks/useWindowScrollPosition.ts b/app/hooks/useWindowScrollPosition.ts
index 4f3cf2b333..10713d58f1 100644
--- a/app/hooks/useWindowScrollPosition.ts
+++ b/app/hooks/useWindowScrollPosition.ts
@@ -13,6 +13,13 @@ const defaultOptions = {
throttle: 100,
};
+/**
+ * Hook to track the window's scroll position.
+ *
+ * @param options Configuration options
+ * @param options.throttle Time in milliseconds to throttle the scroll event
+ * @returns Object containing the current scroll position (x, y coordinates)
+ */
export default function useWindowScrollPosition(options: {
throttle: number;
}): {
diff --git a/app/hooks/useWindowSize.ts b/app/hooks/useWindowSize.ts
index a607a97ee8..7be569c813 100644
--- a/app/hooks/useWindowSize.ts
+++ b/app/hooks/useWindowSize.ts
@@ -1,4 +1,4 @@
-import * as React from "react";
+import { useState, useEffect } from "react";
import useEventListener from "./useEventListener";
import useThrottledCallback from "./useThrottledCallback";
@@ -9,7 +9,7 @@ import useThrottledCallback from "./useThrottledCallback";
* @returns An object containing width and height of the current window
*/
export default function useWindowSize() {
- const [windowSize, setWindowSize] = React.useState({
+ const [windowSize, setWindowSize] = useState({
width: window.visualViewport?.width || window.innerWidth,
height: window.visualViewport?.height || window.innerHeight,
});
@@ -31,7 +31,7 @@ export default function useWindowSize() {
useEventListener("resize", handleResize, window.visualViewport);
// Call handler right away so state gets updated with initial window size
- React.useEffect(() => {
+ useEffect(() => {
handleResize();
}, [handleResize]);
diff --git a/app/index.tsx b/app/index.tsx
index c6d581110d..ede59695e2 100644
--- a/app/index.tsx
+++ b/app/index.tsx
@@ -3,7 +3,7 @@ import "vite/modulepreload-polyfill";
import { LazyMotion } from "framer-motion";
import { KBarProvider } from "kbar";
import { Provider } from "mobx-react";
-import * as React from "react";
+import { StrictMode } from "react";
import { render } from "react-dom";
import { HelmetProvider } from "react-helmet-async";
import { Router } from "react-router-dom";
@@ -48,7 +48,7 @@ const commandBarOptions = {
if (element) {
const App = () => (
-
+
@@ -76,7 +76,7 @@ if (element) {
-
+
);
render( , element);
diff --git a/app/menus/AccountMenu.tsx b/app/menus/AccountMenu.tsx
index 8ee8b2d1f7..5c70e0e28f 100644
--- a/app/menus/AccountMenu.tsx
+++ b/app/menus/AccountMenu.tsx
@@ -1,7 +1,7 @@
import { observer } from "mobx-react";
import * as React from "react";
import { useTranslation } from "react-i18next";
-import { MenuButton, useMenuState } from "reakit/Menu";
+import { MenuButton } from "reakit/Menu";
import ContextMenu from "~/components/ContextMenu";
import Template from "~/components/ContextMenu/Template";
import {
@@ -16,6 +16,7 @@ import {
logout,
} from "~/actions/definitions/navigation";
import { changeTheme } from "~/actions/definitions/settings";
+import { useMenuState } from "~/hooks/useMenuState";
import usePrevious from "~/hooks/usePrevious";
import useStores from "~/hooks/useStores";
import separator from "~/menus/separator";
diff --git a/app/menus/ApiKeyMenu.tsx b/app/menus/ApiKeyMenu.tsx
index 5f4045e487..cb00e7e33b 100644
--- a/app/menus/ApiKeyMenu.tsx
+++ b/app/menus/ApiKeyMenu.tsx
@@ -1,12 +1,12 @@
import { observer } from "mobx-react";
-import * as React from "react";
+import { useCallback } from "react";
import { useTranslation } from "react-i18next";
-import { useMenuState } from "reakit/Menu";
import ApiKey from "~/models/ApiKey";
import ApiKeyRevokeDialog from "~/scenes/Settings/components/ApiKeyRevokeDialog";
import ContextMenu from "~/components/ContextMenu";
import MenuItem from "~/components/ContextMenu/MenuItem";
import OverflowMenuButton from "~/components/ContextMenu/OverflowMenuButton";
+import { useMenuState } from "~/hooks/useMenuState";
import useStores from "~/hooks/useStores";
type Props = {
@@ -21,7 +21,7 @@ function ApiKeyMenu({ apiKey }: Props) {
const { dialogs } = useStores();
const { t } = useTranslation();
- const handleRevoke = React.useCallback(() => {
+ const handleRevoke = useCallback(() => {
dialogs.openModal({
title: t("Revoke token"),
content: (
diff --git a/app/menus/BreadcrumbMenu.tsx b/app/menus/BreadcrumbMenu.tsx
index 258d73e785..65b4fed231 100644
--- a/app/menus/BreadcrumbMenu.tsx
+++ b/app/menus/BreadcrumbMenu.tsx
@@ -1,9 +1,8 @@
-import * as React from "react";
import { useTranslation } from "react-i18next";
-import { useMenuState } from "reakit/Menu";
import ContextMenu from "~/components/ContextMenu";
import OverflowMenuButton from "~/components/ContextMenu/OverflowMenuButton";
import Template from "~/components/ContextMenu/Template";
+import { useMenuState } from "~/hooks/useMenuState";
import { MenuInternalLink } from "~/types";
type Props = {
diff --git a/app/menus/CollectionGroupMemberMenu.tsx b/app/menus/CollectionGroupMemberMenu.tsx
index 97c8078eb7..731c4b993b 100644
--- a/app/menus/CollectionGroupMemberMenu.tsx
+++ b/app/menus/CollectionGroupMemberMenu.tsx
@@ -1,10 +1,9 @@
import { observer } from "mobx-react";
-import * as React from "react";
import { useTranslation } from "react-i18next";
-import { useMenuState } from "reakit/Menu";
import ContextMenu from "~/components/ContextMenu";
import OverflowMenuButton from "~/components/ContextMenu/OverflowMenuButton";
import Template from "~/components/ContextMenu/Template";
+import { useMenuState } from "~/hooks/useMenuState";
type Props = {
onMembers: () => void;
diff --git a/app/menus/CollectionMenu.tsx b/app/menus/CollectionMenu.tsx
index 800b638d72..9b15431b94 100644
--- a/app/menus/CollectionMenu.tsx
+++ b/app/menus/CollectionMenu.tsx
@@ -11,7 +11,7 @@ import {
import * as React from "react";
import { useTranslation } from "react-i18next";
import { useHistory } from "react-router-dom";
-import { useMenuState, MenuButton, MenuButtonHTMLProps } from "reakit/Menu";
+import { MenuButton, MenuButtonHTMLProps } from "reakit/Menu";
import { VisuallyHidden } from "reakit/VisuallyHidden";
import { toast } from "sonner";
import { SubscriptionType } from "@shared/types";
@@ -37,6 +37,7 @@ import {
} from "~/actions/definitions/collections";
import useActionContext from "~/hooks/useActionContext";
import useCurrentTeam from "~/hooks/useCurrentTeam";
+import { useMenuState } from "~/hooks/useMenuState";
import usePolicy from "~/hooks/usePolicy";
import useRequest from "~/hooks/useRequest";
import useStores from "~/hooks/useStores";
diff --git a/app/menus/CommentMenu.tsx b/app/menus/CommentMenu.tsx
index d2205445cf..462aeb895c 100644
--- a/app/menus/CommentMenu.tsx
+++ b/app/menus/CommentMenu.tsx
@@ -1,9 +1,8 @@
import copy from "copy-to-clipboard";
import { observer } from "mobx-react";
import { CopyIcon, EditIcon } from "outline-icons";
-import * as React from "react";
+import { useCallback } from "react";
import { useTranslation } from "react-i18next";
-import { useMenuState } from "reakit/Menu";
import { toast } from "sonner";
import EventBoundary from "@shared/components/EventBoundary";
import Comment from "~/models/Comment";
@@ -18,6 +17,7 @@ import {
viewCommentReactionsFactory,
} from "~/actions/definitions/comments";
import useActionContext from "~/hooks/useActionContext";
+import { useMenuState } from "~/hooks/useMenuState";
import usePolicy from "~/hooks/usePolicy";
import useStores from "~/hooks/useStores";
import { commentPath, urlify } from "~/utils/routeHelpers";
@@ -51,7 +51,7 @@ function CommentMenu({
const context = useActionContext({ isContextMenu: true });
const document = documents.get(comment.documentId);
- const handleCopyLink = React.useCallback(() => {
+ const handleCopyLink = useCallback(() => {
if (document) {
copy(urlify(commentPath(document, comment)));
toast.message(t("Link copied"));
diff --git a/app/menus/DocumentMenu.tsx b/app/menus/DocumentMenu.tsx
index b4afa1e801..d1082ddb71 100644
--- a/app/menus/DocumentMenu.tsx
+++ b/app/menus/DocumentMenu.tsx
@@ -2,11 +2,17 @@ import capitalize from "lodash/capitalize";
import isEmpty from "lodash/isEmpty";
import noop from "lodash/noop";
import { observer } from "mobx-react";
-import { EditIcon, InputIcon, RestoreIcon, SearchIcon } from "outline-icons";
+import {
+ EditIcon,
+ InputIcon,
+ RestoreIcon,
+ SearchIcon,
+ ShapesIcon,
+} from "outline-icons";
import * as React from "react";
import { useTranslation } from "react-i18next";
import { useHistory } from "react-router-dom";
-import { useMenuState, MenuButton, MenuButtonHTMLProps } from "reakit/Menu";
+import { MenuButton, MenuButtonHTMLProps } from "reakit/Menu";
import { VisuallyHidden } from "reakit/VisuallyHidden";
import { toast } from "sonner";
import styled from "styled-components";
@@ -15,10 +21,11 @@ import { s } from "@shared/styles";
import { SubscriptionType, UserPreference } from "@shared/types";
import { getEventFiles } from "@shared/utils/files";
import Document from "~/models/Document";
+import Template from "~/models/Template";
import ContextMenu from "~/components/ContextMenu";
import OverflowMenuButton from "~/components/ContextMenu/OverflowMenuButton";
import Separator from "~/components/ContextMenu/Separator";
-import Template from "~/components/ContextMenu/Template";
+import MenuTemplate from "~/components/ContextMenu/Template";
import CollectionIcon from "~/components/Icons/CollectionIcon";
import Switch from "~/components/Switch";
import { actionToMenuItem } from "~/actions";
@@ -53,10 +60,12 @@ import {
import useActionContext from "~/hooks/useActionContext";
import useBoolean from "~/hooks/useBoolean";
import useCurrentUser from "~/hooks/useCurrentUser";
+import { useMenuState } from "~/hooks/useMenuState";
import useMobile from "~/hooks/useMobile";
import usePolicy from "~/hooks/usePolicy";
import useRequest from "~/hooks/useRequest";
import useStores from "~/hooks/useStores";
+import { useTemplateMenuItems } from "~/hooks/useTemplateMenuItems";
import { MenuItem, MenuItemButton } from "~/types";
import { documentEditPath } from "~/utils/routeHelpers";
import { MenuContext, useMenuContext } from "./MenuContext";
@@ -76,6 +85,8 @@ type Props = {
label?: (props: MenuButtonHTMLProps) => React.ReactNode;
/** Invoked when the "Find and replace" menu item is clicked */
onFindAndReplace?: () => void;
+ /** Invoked when the "Apply template" menu item is clicked */
+ onSelectTemplate?: (template: Template) => void;
/** Invoked when the "Rename" menu item is clicked */
onRename?: () => void;
/** Invoked when menu is opened */
@@ -147,6 +158,7 @@ type MenuContentProps = {
onOpen?: () => void;
onClose?: () => void;
onFindAndReplace?: () => void;
+ onSelectTemplate?: (template: Template) => void;
onRename?: () => void;
showDisplayOptions?: boolean;
showToggleEmbeds?: boolean;
@@ -156,6 +168,7 @@ const MenuContent: React.FC = observer(function MenuContent_({
onOpen,
onClose,
onFindAndReplace,
+ onSelectTemplate,
onRename,
showDisplayOptions,
showToggleEmbeds,
@@ -218,6 +231,11 @@ const MenuContent: React.FC = observer(function MenuContent_({
[collections.orderedData, handleRestore, policies]
);
+ const templateMenuItems = useTemplateMenuItems({
+ document,
+ onSelectTemplate,
+ });
+
return !isEmpty(can) ? (
= observer(function MenuContent_({
onOpen={onOpen}
onClose={onClose}
>
- = observer(function MenuContent_({
actionToMenuItem(archiveDocument, context),
actionToMenuItem(moveDocument, context),
actionToMenuItem(moveTemplate, context),
+ {
+ type: "submenu",
+ title: t("Apply template"),
+ icon: ,
+ items: templateMenuItems,
+ },
actionToMenuItem(pinDocument, context),
actionToMenuItem(createDocumentFromTemplate, context),
{
@@ -380,6 +404,7 @@ function DocumentMenu({
modal = true,
showToggleEmbeds,
showDisplayOptions,
+ onSelectTemplate,
label,
onRename,
onOpen,
@@ -463,6 +488,7 @@ function DocumentMenu({
onOpen={onOpen}
onClose={onClose}
onRename={onRename}
+ onSelectTemplate={onSelectTemplate}
showDisplayOptions={showDisplayOptions}
showToggleEmbeds={showToggleEmbeds}
/>
diff --git a/app/menus/FileOperationMenu.tsx b/app/menus/FileOperationMenu.tsx
index 1cc15bc59c..76f2324503 100644
--- a/app/menus/FileOperationMenu.tsx
+++ b/app/menus/FileOperationMenu.tsx
@@ -1,12 +1,12 @@
import { DownloadIcon, TrashIcon } from "outline-icons";
import * as React from "react";
import { useTranslation } from "react-i18next";
-import { useMenuState } from "reakit/Menu";
import { FileOperationState, FileOperationType } from "@shared/types";
import FileOperation from "~/models/FileOperation";
import ContextMenu from "~/components/ContextMenu";
import OverflowMenuButton from "~/components/ContextMenu/OverflowMenuButton";
import Template from "~/components/ContextMenu/Template";
+import { useMenuState } from "~/hooks/useMenuState";
import usePolicy from "~/hooks/usePolicy";
type Props = {
diff --git a/app/menus/GroupMemberMenu.tsx b/app/menus/GroupMemberMenu.tsx
index bda9c24eb9..3779f40c15 100644
--- a/app/menus/GroupMemberMenu.tsx
+++ b/app/menus/GroupMemberMenu.tsx
@@ -1,10 +1,9 @@
import { observer } from "mobx-react";
-import * as React from "react";
import { useTranslation } from "react-i18next";
-import { useMenuState } from "reakit/Menu";
import ContextMenu from "~/components/ContextMenu";
import OverflowMenuButton from "~/components/ContextMenu/OverflowMenuButton";
import Template from "~/components/ContextMenu/Template";
+import { useMenuState } from "~/hooks/useMenuState";
type Props = {
onRemove: () => void;
diff --git a/app/menus/GroupMenu.tsx b/app/menus/GroupMenu.tsx
index fd5ef0cbf6..58fe54457e 100644
--- a/app/menus/GroupMenu.tsx
+++ b/app/menus/GroupMenu.tsx
@@ -1,8 +1,7 @@
import { observer } from "mobx-react";
import { EditIcon, GroupIcon, TrashIcon } from "outline-icons";
-import * as React from "react";
+import { useCallback } from "react";
import { useTranslation } from "react-i18next";
-import { useMenuState } from "reakit/Menu";
import Group from "~/models/Group";
import {
DeleteGroupDialog,
@@ -12,6 +11,7 @@ import {
import ContextMenu from "~/components/ContextMenu";
import OverflowMenuButton from "~/components/ContextMenu/OverflowMenuButton";
import Template from "~/components/ContextMenu/Template";
+import { useMenuState } from "~/hooks/useMenuState";
import usePolicy from "~/hooks/usePolicy";
import useStores from "~/hooks/useStores";
@@ -27,7 +27,7 @@ function GroupMenu({ group }: Props) {
});
const can = usePolicy(group);
- const handleViewMembers = React.useCallback(() => {
+ const handleViewMembers = useCallback(() => {
dialogs.openModal({
title: t("Group members"),
content: ,
@@ -35,7 +35,7 @@ function GroupMenu({ group }: Props) {
});
}, [t, group, dialogs]);
- const handleEditGroup = React.useCallback(() => {
+ const handleEditGroup = useCallback(() => {
dialogs.openModal({
title: t("Edit group"),
content: (
@@ -44,7 +44,7 @@ function GroupMenu({ group }: Props) {
});
}, [t, group, dialogs]);
- const handleDeleteGroup = React.useCallback(() => {
+ const handleDeleteGroup = useCallback(() => {
dialogs.openModal({
title: t("Delete group"),
content: (
diff --git a/app/menus/ImportMenu.tsx b/app/menus/ImportMenu.tsx
new file mode 100644
index 0000000000..3642ea3c93
--- /dev/null
+++ b/app/menus/ImportMenu.tsx
@@ -0,0 +1,62 @@
+import { observer } from "mobx-react";
+import { CrossIcon, TrashIcon } from "outline-icons";
+import * as React from "react";
+import { useTranslation } from "react-i18next";
+import Import from "~/models/Import";
+import ContextMenu from "~/components/ContextMenu";
+import OverflowMenuButton from "~/components/ContextMenu/OverflowMenuButton";
+import Template from "~/components/ContextMenu/Template";
+import { useMenuState } from "~/hooks/useMenuState";
+import usePolicy from "~/hooks/usePolicy";
+import { MenuItem } from "~/types";
+
+type Props = {
+ /** Import to which actions will be applied. */
+ importModel: Import;
+ /** Callback to handle import cancellation. */
+ onCancel: () => Promise;
+ /** Callback to handle import deletion. */
+ onDelete: () => Promise;
+};
+
+export const ImportMenu = observer(
+ ({ importModel, onCancel, onDelete }: Props) => {
+ const { t } = useTranslation();
+ const can = usePolicy(importModel);
+ const menu = useMenuState({
+ modal: true,
+ });
+
+ const items = React.useMemo(
+ () =>
+ [
+ {
+ type: "button",
+ title: t("Cancel"),
+ visible: can.cancel,
+ icon: ,
+ dangerous: true,
+ onClick: onCancel,
+ },
+ {
+ type: "button",
+ title: t("Delete"),
+ visible: can.delete,
+ icon: ,
+ dangerous: true,
+ onClick: onDelete,
+ },
+ ] satisfies MenuItem[],
+ [t, can.delete, can.cancel, onCancel, onDelete]
+ );
+
+ return (
+ <>
+
+
+
+
+ >
+ );
+ }
+);
diff --git a/app/menus/InsightsMenu.tsx b/app/menus/InsightsMenu.tsx
index 0a295f554f..9032af3eba 100644
--- a/app/menus/InsightsMenu.tsx
+++ b/app/menus/InsightsMenu.tsx
@@ -1,7 +1,7 @@
import { t } from "i18next";
import { MoreIcon } from "outline-icons";
-import React from "react";
-import { MenuButton, useMenuState } from "reakit/Menu";
+import * as React from "react";
+import { MenuButton } from "reakit/Menu";
import styled from "styled-components";
import { s, hover } from "@shared/styles";
import ContextMenu from "~/components/ContextMenu";
@@ -10,6 +10,7 @@ import NudeButton from "~/components/NudeButton";
import { actionToMenuItem } from "~/actions";
import { toggleViewerInsights } from "~/actions/definitions/documents";
import useActionContext from "~/hooks/useActionContext";
+import { useMenuState } from "~/hooks/useMenuState";
import { MenuItem } from "~/types";
const InsightsMenu: React.FC = () => {
diff --git a/app/menus/MemberMenu.tsx b/app/menus/MemberMenu.tsx
index d95f7e4644..ffa53a3e97 100644
--- a/app/menus/MemberMenu.tsx
+++ b/app/menus/MemberMenu.tsx
@@ -1,11 +1,10 @@
-import * as React from "react";
import { useTranslation } from "react-i18next";
-import { useMenuState } from "reakit/Menu";
import User from "~/models/User";
import ContextMenu from "~/components/ContextMenu";
import OverflowMenuButton from "~/components/ContextMenu/OverflowMenuButton";
import Template from "~/components/ContextMenu/Template";
import useCurrentUser from "~/hooks/useCurrentUser";
+import { useMenuState } from "~/hooks/useMenuState";
type Props = {
user: User;
diff --git a/app/menus/NewChildDocumentMenu.tsx b/app/menus/NewChildDocumentMenu.tsx
index 74fc012bdb..8e888b8adc 100644
--- a/app/menus/NewChildDocumentMenu.tsx
+++ b/app/menus/NewChildDocumentMenu.tsx
@@ -1,10 +1,11 @@
import { observer } from "mobx-react";
import * as React from "react";
import { useTranslation, Trans } from "react-i18next";
-import { useMenuState, MenuButton, MenuButtonHTMLProps } from "reakit/Menu";
+import { MenuButton, MenuButtonHTMLProps } from "reakit/Menu";
import Document from "~/models/Document";
import ContextMenu from "~/components/ContextMenu";
import Template from "~/components/ContextMenu/Template";
+import { useMenuState } from "~/hooks/useMenuState";
import usePolicy from "~/hooks/usePolicy";
import useStores from "~/hooks/useStores";
import { MenuItem } from "~/types";
diff --git a/app/menus/NewDocumentMenu.tsx b/app/menus/NewDocumentMenu.tsx
index 84672a684c..7a532a8b24 100644
--- a/app/menus/NewDocumentMenu.tsx
+++ b/app/menus/NewDocumentMenu.tsx
@@ -1,6 +1,5 @@
import { observer } from "mobx-react";
import { PlusIcon } from "outline-icons";
-import * as React from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router-dom";
import Button from "~/components/Button";
diff --git a/app/menus/NewTemplateMenu.tsx b/app/menus/NewTemplateMenu.tsx
index d426a3ea99..92a79f6010 100644
--- a/app/menus/NewTemplateMenu.tsx
+++ b/app/menus/NewTemplateMenu.tsx
@@ -1,14 +1,15 @@
import { observer } from "mobx-react";
import { PlusIcon } from "outline-icons";
-import * as React from "react";
+import { useEffect, useMemo } from "react";
import { useTranslation } from "react-i18next";
-import { MenuButton, useMenuState } from "reakit/Menu";
+import { MenuButton } from "reakit/Menu";
import Button from "~/components/Button";
import ContextMenu from "~/components/ContextMenu";
import Template from "~/components/ContextMenu/Template";
import CollectionIcon from "~/components/Icons/CollectionIcon";
import TeamLogo from "~/components/TeamLogo";
import useCurrentTeam from "~/hooks/useCurrentTeam";
+import { useMenuState } from "~/hooks/useMenuState";
import usePolicy from "~/hooks/usePolicy";
import useStores from "~/hooks/useStores";
import { MenuItem } from "~/types";
@@ -22,7 +23,7 @@ function NewTemplateMenu() {
const team = useCurrentTeam();
const { collections, policies } = useStores();
const can = usePolicy(team);
- React.useEffect(() => {
+ useEffect(() => {
void collections.fetchPage({
limit: 100,
});
@@ -37,7 +38,7 @@ function NewTemplateMenu() {
}
: null;
- const collectionItems = React.useMemo(
+ const collectionItems = useMemo(
() =>
collections.orderedData.reduce((filtered, collection) => {
const can = policies.abilities(collection.id);
@@ -56,7 +57,7 @@ function NewTemplateMenu() {
[collections.orderedData, policies]
);
- const collectionItemsWithHeader: MenuItem[] = React.useMemo(
+ const collectionItemsWithHeader: MenuItem[] = useMemo(
() =>
collectionItems.length
? [
diff --git a/app/menus/NotificationMenu.tsx b/app/menus/NotificationMenu.tsx
index ec590bc4ae..62043543fa 100644
--- a/app/menus/NotificationMenu.tsx
+++ b/app/menus/NotificationMenu.tsx
@@ -1,7 +1,7 @@
import { t } from "i18next";
import { MoreIcon } from "outline-icons";
-import React from "react";
-import { MenuButton, useMenuState } from "reakit/Menu";
+import * as React from "react";
+import { MenuButton } from "reakit/Menu";
import styled from "styled-components";
import { s, hover } from "@shared/styles";
import ContextMenu from "~/components/ContextMenu";
@@ -11,6 +11,7 @@ import { actionToMenuItem, performAction } from "~/actions";
import { navigateToNotificationSettings } from "~/actions/definitions/navigation";
import { markNotificationsAsArchived } from "~/actions/definitions/notifications";
import useActionContext from "~/hooks/useActionContext";
+import { useMenuState } from "~/hooks/useMenuState";
import useOnClickOutside from "~/hooks/useOnClickOutside";
import { MenuItem } from "~/types";
diff --git a/app/menus/OAuthAuthenticationMenu.tsx b/app/menus/OAuthAuthenticationMenu.tsx
new file mode 100644
index 0000000000..ae7eb68d08
--- /dev/null
+++ b/app/menus/OAuthAuthenticationMenu.tsx
@@ -0,0 +1,57 @@
+import { observer } from "mobx-react";
+import { useCallback } from "react";
+import { useTranslation } from "react-i18next";
+import OAuthAuthentication from "~/models/oauth/OAuthAuthentication";
+import ConfirmationDialog from "~/components/ConfirmationDialog";
+import ContextMenu from "~/components/ContextMenu";
+import MenuItem from "~/components/ContextMenu/MenuItem";
+import OverflowMenuButton from "~/components/ContextMenu/OverflowMenuButton";
+import { useMenuState } from "~/hooks/useMenuState";
+import useStores from "~/hooks/useStores";
+
+type Props = {
+ /** The OAuthAuthentication to associate with the menu */
+ oauthAuthentication: OAuthAuthentication;
+};
+
+function OAuthAuthenticationMenu({ oauthAuthentication }: Props) {
+ const menu = useMenuState({
+ modal: true,
+ });
+ const { dialogs } = useStores();
+ const { t } = useTranslation();
+
+ const handleRevoke = useCallback(() => {
+ dialogs.openModal({
+ title: t("Revoke {{ appName }}", {
+ appName: oauthAuthentication.oauthClient.name,
+ }),
+ content: (
+ {
+ await oauthAuthentication.deleteAll();
+ dialogs.closeAllModals();
+ }}
+ submitText={t("Revoke")}
+ savingText={`${t("Revoking")}…`}
+ danger
+ >
+ {t("Are you sure you want to revoke access?")}
+
+ ),
+ });
+ }, [t, dialogs, oauthAuthentication]);
+
+ return (
+ <>
+
+
+
+ {t("Revoke")}
+
+
+ >
+ );
+}
+
+export default observer(OAuthAuthenticationMenu);
diff --git a/app/menus/OAuthClientMenu.tsx b/app/menus/OAuthClientMenu.tsx
new file mode 100644
index 0000000000..666f36dc66
--- /dev/null
+++ b/app/menus/OAuthClientMenu.tsx
@@ -0,0 +1,68 @@
+import { observer } from "mobx-react";
+import { useCallback } from "react";
+import { useTranslation } from "react-i18next";
+import OAuthClient from "~/models/oauth/OAuthClient";
+import OAuthClientDeleteDialog from "~/scenes/Settings/components/OAuthClientDeleteDialog";
+import ContextMenu from "~/components/ContextMenu";
+import OverflowMenuButton from "~/components/ContextMenu/OverflowMenuButton";
+import Template from "~/components/ContextMenu/Template";
+import { useMenuState } from "~/hooks/useMenuState";
+import useStores from "~/hooks/useStores";
+import { settingsPath } from "~/utils/routeHelpers";
+
+type Props = {
+ /** The oauthClient to associate with the menu */
+ oauthClient: OAuthClient;
+ /** Whether to show the edit button */
+ showEdit?: boolean;
+};
+
+function OAuthClientMenu({ oauthClient, showEdit }: Props) {
+ const menu = useMenuState({
+ modal: true,
+ });
+ const { dialogs } = useStores();
+ const { t } = useTranslation();
+
+ const handleDelete = useCallback(() => {
+ dialogs.openModal({
+ title: t("Delete app"),
+ content: (
+
+ ),
+ });
+ }, [t, dialogs, oauthClient]);
+
+ return (
+ <>
+
+
+
+
+ >
+ );
+}
+
+export default observer(OAuthClientMenu);
diff --git a/app/menus/RevisionMenu.tsx b/app/menus/RevisionMenu.tsx
index 89a949f228..7c94b9ed36 100644
--- a/app/menus/RevisionMenu.tsx
+++ b/app/menus/RevisionMenu.tsx
@@ -1,7 +1,5 @@
import { observer } from "mobx-react";
-import * as React from "react";
import { useTranslation } from "react-i18next";
-import { useMenuState } from "reakit/Menu";
import Document from "~/models/Document";
import ContextMenu from "~/components/ContextMenu";
import OverflowMenuButton from "~/components/ContextMenu/OverflowMenuButton";
@@ -12,6 +10,7 @@ import {
restoreRevision,
} from "~/actions/definitions/revisions";
import useActionContext from "~/hooks/useActionContext";
+import { useMenuState } from "~/hooks/useMenuState";
import separator from "./separator";
type Props = {
diff --git a/app/menus/ShareMenu.tsx b/app/menus/ShareMenu.tsx
index 2df6756e5f..a215db9792 100644
--- a/app/menus/ShareMenu.tsx
+++ b/app/menus/ShareMenu.tsx
@@ -3,13 +3,13 @@ import { ArrowIcon, CopyIcon, TrashIcon } from "outline-icons";
import * as React from "react";
import { useTranslation } from "react-i18next";
import { useHistory } from "react-router-dom";
-import { useMenuState } from "reakit/Menu";
import { toast } from "sonner";
import Share from "~/models/Share";
import ContextMenu from "~/components/ContextMenu";
import MenuItem from "~/components/ContextMenu/MenuItem";
import OverflowMenuButton from "~/components/ContextMenu/OverflowMenuButton";
import CopyToClipboard from "~/components/CopyToClipboard";
+import { useMenuState } from "~/hooks/useMenuState";
import usePolicy from "~/hooks/usePolicy";
import useStores from "~/hooks/useStores";
diff --git a/app/menus/TableOfContentsMenu.tsx b/app/menus/TableOfContentsMenu.tsx
index 108e2850cc..95a5a7b0ba 100644
--- a/app/menus/TableOfContentsMenu.tsx
+++ b/app/menus/TableOfContentsMenu.tsx
@@ -1,13 +1,14 @@
import { observer } from "mobx-react";
import { TableOfContentsIcon } from "outline-icons";
-import * as React from "react";
+import { useMemo } from "react";
import { useTranslation } from "react-i18next";
-import { MenuButton, useMenuState } from "reakit/Menu";
+import { MenuButton } from "reakit/Menu";
import styled from "styled-components";
import Button from "~/components/Button";
import ContextMenu from "~/components/ContextMenu";
import Template from "~/components/ContextMenu/Template";
import { useDocumentContext } from "~/components/DocumentContext";
+import { useMenuState } from "~/hooks/useMenuState";
import { MenuItem } from "~/types";
function TableOfContentsMenu() {
@@ -24,7 +25,7 @@ function TableOfContentsMenu() {
Infinity
);
- const items: MenuItem[] = React.useMemo(() => {
+ const items: MenuItem[] = useMemo(() => {
const i = [
{
type: "heading",
diff --git a/app/menus/OrganizationMenu.tsx b/app/menus/TeamMenu.tsx
similarity index 87%
rename from app/menus/OrganizationMenu.tsx
rename to app/menus/TeamMenu.tsx
index 1113476a71..c8d4134e47 100644
--- a/app/menus/OrganizationMenu.tsx
+++ b/app/menus/TeamMenu.tsx
@@ -1,7 +1,7 @@
import { observer } from "mobx-react";
import * as React from "react";
import { useTranslation } from "react-i18next";
-import { MenuButton, useMenuState } from "reakit/Menu";
+import { MenuButton } from "reakit/Menu";
import ContextMenu from "~/components/ContextMenu";
import Template from "~/components/ContextMenu/Template";
import {
@@ -10,10 +10,11 @@ import {
} from "~/actions/definitions/navigation";
import {
createTeam,
- createTeamsList,
+ switchTeamsList,
desktopLoginTeam,
} from "~/actions/definitions/teams";
import useActionContext from "~/hooks/useActionContext";
+import { useMenuState } from "~/hooks/useMenuState";
import usePrevious from "~/hooks/usePrevious";
import useStores from "~/hooks/useStores";
import separator from "~/menus/separator";
@@ -22,7 +23,7 @@ type Props = {
children?: React.ReactNode;
};
-const OrganizationMenu: React.FC = ({ children }: Props) => {
+const TeamMenu: React.FC = ({ children }: Props) => {
const menu = useMenuState({
unstable_offset: [4, -4],
placement: "bottom-start",
@@ -44,7 +45,7 @@ const OrganizationMenu: React.FC = ({ children }: Props) => {
// menu is not cached at all.
const actions = React.useMemo(
() => [
- ...createTeamsList(context),
+ ...switchTeamsList(context),
createTeam,
desktopLoginTeam,
separator(),
@@ -64,4 +65,4 @@ const OrganizationMenu: React.FC = ({ children }: Props) => {
);
};
-export default observer(OrganizationMenu);
+export default observer(TeamMenu);
diff --git a/app/menus/TemplateMenu.tsx b/app/menus/TemplateMenu.tsx
index 1d9ff5dd28..6d61c0978b 100644
--- a/app/menus/TemplateMenu.tsx
+++ b/app/menus/TemplateMenu.tsx
@@ -1,8 +1,6 @@
import { observer } from "mobx-react";
import { DuplicateIcon, EditIcon } from "outline-icons";
-import * as React from "react";
import { useTranslation } from "react-i18next";
-import { useMenuState } from "reakit/Menu";
import Template from "~/models/Template";
import ContextMenu from "~/components/ContextMenu";
import OverflowMenuButton from "~/components/ContextMenu/OverflowMenuButton";
@@ -10,6 +8,7 @@ import ContextMenuTemplate from "~/components/ContextMenu/Template";
import { actionToMenuItem } from "~/actions";
import { deleteTemplate } from "~/actions/definitions/templates";
import useActionContext from "~/hooks/useActionContext";
+import { useMenuState } from "~/hooks/useMenuState";
import usePolicy from "~/hooks/usePolicy";
import useStores from "~/hooks/useStores";
diff --git a/app/menus/TemplatesMenu.tsx b/app/menus/TemplatesMenu.tsx
index 48e4e48e7b..7237c749df 100644
--- a/app/menus/TemplatesMenu.tsx
+++ b/app/menus/TemplatesMenu.tsx
@@ -1,18 +1,14 @@
import { observer } from "mobx-react";
-import { DocumentIcon, ShapesIcon } from "outline-icons";
-import * as React from "react";
+import { ShapesIcon } from "outline-icons";
import { useTranslation } from "react-i18next";
-import { MenuButton, useMenuState } from "reakit/Menu";
-import Icon from "@shared/components/Icon";
-import { TextHelper } from "@shared/utils/TextHelper";
+import { MenuButton } from "reakit/Menu";
import Document from "~/models/Document";
import Template from "~/models/Template";
import Button from "~/components/Button";
import ContextMenu from "~/components/ContextMenu";
import ContextMenuTemplate from "~/components/ContextMenu/Template";
-import useCurrentUser from "~/hooks/useCurrentUser";
-import useStores from "~/hooks/useStores";
-import { MenuItem } from "~/types";
+import { useMenuState } from "~/hooks/useMenuState";
+import { useTemplateMenuItems } from "~/hooks/useTemplateMenuItems";
type Props = {
/** The document to which the templates will be applied */
@@ -24,59 +20,12 @@ type Props = {
};
function TemplatesMenu({ isCompact, onSelectTemplate, document }: Props) {
+ const { t } = useTranslation();
const menu = useMenuState({
modal: true,
});
- const user = useCurrentUser();
- const { templates } = useStores();
- const { t } = useTranslation();
- const templateToMenuItem = React.useCallback(
- (template: Template): MenuItem => ({
- type: "button",
- title: TextHelper.replaceTemplateVariables(
- template.titleWithDefault,
- user
- ),
- icon: template.icon ? (
-
- ) : (
-
- ),
- onClick: () => onSelectTemplate(template),
- }),
- [user, onSelectTemplate]
- );
-
- const collectionItems = templates.orderedData
- .filter(
- (template) =>
- !template.isWorkspaceTemplate &&
- template.collectionId === document.collectionId
- )
- .map(templateToMenuItem);
-
- const workspaceTemplates = templates.orderedData
- .filter((template) => template.isWorkspaceTemplate)
- .map(templateToMenuItem);
-
- const workspaceItems: MenuItem[] = React.useMemo(
- () =>
- workspaceTemplates.length
- ? [{ type: "heading", title: t("Workspace") }, ...workspaceTemplates]
- : [],
- [t, workspaceTemplates]
- );
-
- const items = collectionItems
- ? workspaceItems.length
- ? [
- ...collectionItems,
- { type: "separator" } as MenuItem,
- ...workspaceItems,
- ]
- : collectionItems
- : workspaceItems;
+ const items = useTemplateMenuItems({ onSelectTemplate, document });
if (!items.length) {
return null;
diff --git a/app/menus/UserMenu.tsx b/app/menus/UserMenu.tsx
index 5cc58638da..b9af7c6ac7 100644
--- a/app/menus/UserMenu.tsx
+++ b/app/menus/UserMenu.tsx
@@ -1,7 +1,6 @@
import { observer } from "mobx-react";
import * as React from "react";
import { useTranslation } from "react-i18next";
-import { useMenuState } from "reakit/Menu";
import { toast } from "sonner";
import { UserRole } from "@shared/types";
import User from "~/models/User";
@@ -19,6 +18,7 @@ import {
updateUserRoleActionFactory,
} from "~/actions/definitions/users";
import useActionContext from "~/hooks/useActionContext";
+import { useMenuState } from "~/hooks/useMenuState";
import usePolicy from "~/hooks/usePolicy";
import useStores from "~/hooks/useStores";
diff --git a/app/models/Collection.ts b/app/models/Collection.ts
index a0c36f8f62..842edb274a 100644
--- a/app/models/Collection.ts
+++ b/app/models/Collection.ts
@@ -6,6 +6,7 @@ import {
type NavigationNode,
NavigationNodeType,
type ProsemirrorData,
+ TeamPreference,
} from "@shared/types";
import { ProsemirrorHelper } from "@shared/utils/ProsemirrorHelper";
import { sortNavigationNodes } from "@shared/utils/collections";
@@ -68,6 +69,13 @@ export default class Collection extends ParanoidModel {
direction: "asc" | "desc";
};
+ /**
+ * Whether commenting is enabled for the collection.
+ */
+ @Field
+ @observable
+ commenting?: boolean | null;
+
/** The child documents of the collection. */
@observable
documents?: NavigationNode[];
@@ -121,6 +129,21 @@ export default class Collection extends ParanoidModel {
return !this.permission;
}
+ /**
+ * Returns whether comments should be enabled for this collection,
+ *
+ * @returns boolean
+ */
+ @computed
+ get canCreateComment(): boolean {
+ const teamCommentingEnabled =
+ !!this.store.rootStore.auth.team?.getPreference(
+ TeamPreference.Commenting
+ );
+
+ return teamCommentingEnabled && this.commenting !== false;
+ }
+
/** Returns whether the collection description is not empty. */
@computed
get hasDescription(): boolean {
diff --git a/app/models/Document.ts b/app/models/Document.ts
index a54c50cf80..bb6d6d49dd 100644
--- a/app/models/Document.ts
+++ b/app/models/Document.ts
@@ -17,6 +17,7 @@ import {
NavigationNodeType,
NotificationEventType,
} from "@shared/types";
+import { ProsemirrorHelper } from "@shared/utils/ProsemirrorHelper";
import Storage from "@shared/utils/Storage";
import { isRTL } from "@shared/utils/rtl";
import slugify from "@shared/utils/slugify";
@@ -320,6 +321,16 @@ export default class Document extends ArchivableModel implements Searchable {
);
}
+ /**
+ * Returns the documents that link to this document.
+ *
+ * @returns documents that link to this document
+ */
+ @computed
+ get backlinks(): Document[] {
+ return this.store.getBacklinkedDocuments(this.id);
+ }
+
/**
* Returns users that have been individually given access to the document.
*
@@ -580,7 +591,7 @@ export default class Document extends ArchivableModel implements Searchable {
*/
getSummary = (blocks = 4) => ({
...this.data,
- content: this.data.content.slice(0, blocks),
+ content: this.data.content?.slice(0, blocks),
});
@computed
@@ -643,6 +654,24 @@ export default class Document extends ArchivableModel implements Searchable {
return markdown;
};
+ /**
+ * Returns the plain text representation of the document derived from the ProseMirror data.
+ *
+ * @returns The plain text representation of the document as a string.
+ */
+ toPlainText = () => {
+ const extensionManager = new ExtensionManager(withComments(richExtensions));
+ const schema = new Schema({
+ nodes: extensionManager.nodes,
+ marks: extensionManager.marks,
+ });
+ const text = ProsemirrorHelper.toPlainText(
+ Node.fromJSON(schema, this.data),
+ schema
+ );
+ return text;
+ };
+
download = (contentType: ExportContentType) =>
client.post(
`/documents.export`,
diff --git a/app/models/Import.ts b/app/models/Import.ts
new file mode 100644
index 0000000000..687bb6b20d
--- /dev/null
+++ b/app/models/Import.ts
@@ -0,0 +1,57 @@
+import { observable } from "mobx";
+import { ImportableIntegrationService, ImportState } from "@shared/types";
+import ImportsStore from "~/stores/ImportsStore";
+import User from "./User";
+import Model from "./base/Model";
+import Field from "./decorators/Field";
+import { AfterChange } from "./decorators/Lifecycle";
+import Relation from "./decorators/Relation";
+
+class Import extends Model {
+ static modelName = "Import";
+
+ store: ImportsStore;
+
+ /** The name of the import. */
+ name: string;
+
+ /** Descriptive error message when the import errors out. */
+ error: string | null;
+
+ /** The current state of the import. */
+ @Field
+ @observable
+ state: ImportState;
+
+ /** The external service from which the import is created. */
+ service: ImportableIntegrationService;
+
+ /** The count of documents created in the import. */
+ @observable
+ documentCount: number;
+
+ /** The user who created the import. */
+ @Relation(() => User, {})
+ createdBy: User;
+
+ /** The ID of the user who created the import. */
+ createdById: string;
+
+ /**
+ * Cancel the import – this will stop the import process and mark it as
+ * cancelled at the first opportunity.
+ */
+ cancel = async () => this.store.cancel(this);
+
+ // hooks
+
+ @AfterChange
+ static removePolicies(model: Import, previousAttributes: Partial) {
+ if (previousAttributes.state && previousAttributes.state !== model.state) {
+ const { policies } = model.store.rootStore;
+ policies.remove(model.id);
+ }
+ }
+}
+
+export default Import;
diff --git a/app/models/Integration.ts b/app/models/Integration.ts
index 7338e36afa..2e8f05123d 100644
--- a/app/models/Integration.ts
+++ b/app/models/Integration.ts
@@ -1,8 +1,8 @@
import { observable } from "mobx";
-import type {
+import {
IntegrationService,
- IntegrationSettings,
- IntegrationType,
+ type IntegrationSettings,
+ type IntegrationType,
} from "@shared/types";
import User from "~/models/User";
import Model from "~/models/base/Model";
diff --git a/app/models/Revision.ts b/app/models/Revision.ts
index 818d11dc67..ce38ed0c32 100644
--- a/app/models/Revision.ts
+++ b/app/models/Revision.ts
@@ -3,11 +3,11 @@ import { ProsemirrorData } from "@shared/types";
import { isRTL } from "@shared/utils/rtl";
import Document from "./Document";
import User from "./User";
-import Model from "./base/Model";
+import ParanoidModel from "./base/ParanoidModel";
import Field from "./decorators/Field";
import Relation from "./decorators/Relation";
-class Revision extends Model {
+class Revision extends ParanoidModel {
static modelName = "Revision";
/** The document ID that the revision is related to */
diff --git a/app/models/Star.ts b/app/models/Star.ts
index 347f6385b0..4c6c76651d 100644
--- a/app/models/Star.ts
+++ b/app/models/Star.ts
@@ -22,7 +22,7 @@ class Star extends Model {
document?: Document;
/** The collection ID that is starred. */
- collectionId: string;
+ collectionId?: string;
/** The collection that is starred. */
@Relation(() => Collection, { onDelete: "cascade" })
diff --git a/app/models/Unfurl.ts b/app/models/Unfurl.ts
new file mode 100644
index 0000000000..23f3b9fd0c
--- /dev/null
+++ b/app/models/Unfurl.ts
@@ -0,0 +1,18 @@
+import { observable } from "mobx";
+import { UnfurlResourceType, UnfurlResponse } from "@shared/types";
+import Model from "./base/Model";
+
+class Unfurl extends Model {
+ static modelName = "Unfurl";
+
+ @observable
+ type: UnfurlType;
+
+ @observable
+ data: UnfurlResponse[UnfurlType];
+
+ @observable
+ fetchedAt: string;
+}
+
+export default Unfurl;
diff --git a/app/models/base/Model.ts b/app/models/base/Model.ts
index 747eb4e710..107b8a3ab4 100644
--- a/app/models/base/Model.ts
+++ b/app/models/base/Model.ts
@@ -43,12 +43,6 @@ export default abstract class Model {
this: Model,
options: { withoutPolicies?: boolean } = {}
): Promise {
- const relations = getRelationsForModelClass(
- this.constructor as typeof Model
- );
- if (!relations) {
- return;
- }
// this is to ensure that multiple loads don’t happen in parallel
if (this.loadingRelations) {
return this.loadingRelations;
@@ -56,14 +50,20 @@ export default abstract class Model {
const promises = [];
- for (const properties of relations.values()) {
- const store = this.store.rootStore.getStoreForModelName(
- properties.relationClassResolver().modelName
- );
- if ("fetch" in store) {
- const id = this[properties.idKey];
- if (id) {
- promises.push(store.fetch(id as string));
+ const relations = getRelationsForModelClass(
+ this.constructor as typeof Model
+ );
+
+ if (relations) {
+ for (const properties of relations.values()) {
+ const store = this.store.rootStore.getStoreForModelName(
+ properties.relationClassResolver().modelName
+ );
+ if ("fetch" in store) {
+ const id = this[properties.idKey];
+ if (id) {
+ promises.push(store.fetch(id as string));
+ }
}
}
}
diff --git a/app/models/base/ParanoidModel.ts b/app/models/base/ParanoidModel.ts
index ffca1a250c..6930e28aa3 100644
--- a/app/models/base/ParanoidModel.ts
+++ b/app/models/base/ParanoidModel.ts
@@ -1,7 +1,12 @@
-import { observable } from "mobx";
+import { computed, observable } from "mobx";
import Model from "./Model";
export default abstract class ParanoidModel extends Model {
@observable
deletedAt: string | undefined;
+
+ @computed
+ get isDeleted(): boolean {
+ return !!this.deletedAt;
+ }
}
diff --git a/app/models/oauth/OAuthAuthentication.ts b/app/models/oauth/OAuthAuthentication.ts
new file mode 100644
index 0000000000..c982befcfe
--- /dev/null
+++ b/app/models/oauth/OAuthAuthentication.ts
@@ -0,0 +1,39 @@
+import { action, observable } from "mobx";
+import { client } from "~/utils/ApiClient";
+import User from "../User";
+import ParanoidModel from "../base/ParanoidModel";
+import Field from "../decorators/Field";
+import Relation from "../decorators/Relation";
+import OAuthClient from "./OAuthClient";
+
+class OAuthAuthentication extends ParanoidModel {
+ static modelName = "OAuthAuthentication";
+
+ /** A list of scopes that this authentication has access to */
+ @Field
+ @observable
+ scope: string[];
+
+ @Relation(() => User)
+ user: User;
+
+ userId: string;
+
+ oauthClient: Pick;
+
+ oauthClientId: string;
+
+ lastActiveAt: string;
+
+ @action
+ public async deleteAll() {
+ await client.post(`/${this.store.apiEndpoint}.delete`, {
+ oauthClientId: this.oauthClientId,
+ scope: this.scope,
+ });
+
+ return this.store.remove(this.id);
+ }
+}
+
+export default OAuthAuthentication;
diff --git a/app/models/oauth/OAuthClient.ts b/app/models/oauth/OAuthClient.ts
new file mode 100644
index 0000000000..656824c4e1
--- /dev/null
+++ b/app/models/oauth/OAuthClient.ts
@@ -0,0 +1,92 @@
+import invariant from "invariant";
+import { observable, runInAction } from "mobx";
+import queryString from "query-string";
+import env from "~/env";
+import { client } from "~/utils/ApiClient";
+import User from "../User";
+import ParanoidModel from "../base/ParanoidModel";
+import Field from "../decorators/Field";
+import Relation from "../decorators/Relation";
+
+class OAuthClient extends ParanoidModel {
+ static modelName = "OAuthClient";
+
+ /** The human-readable name of this app */
+ @Field
+ @observable
+ name: string;
+
+ /** A short description of this app */
+ @Field
+ @observable
+ description: string | null;
+
+ /** The name of the developer of this app */
+ @Field
+ @observable
+ developerName: string | null;
+
+ /** The URL of the developer of this app */
+ @Field
+ @observable
+ developerUrl: string | null;
+
+ /** The URL of the avatar of the developer of this app */
+ @Field
+ @observable
+ avatarUrl: string | null;
+
+ /** The public identifier of this app */
+ @Field
+ clientId: string;
+
+ /** The secret key used to authenticate this app */
+ @Field
+ @observable
+ clientSecret: string;
+
+ /** Whether this app is published (available to other workspaces) */
+ @Field
+ @observable
+ published: boolean;
+
+ /** A list of valid redirect URIs for this app */
+ @Field
+ @observable
+ redirectUris: string[];
+
+ @Relation(() => User)
+ createdBy: User;
+
+ createdById: string;
+
+ // instance methods
+
+ public async rotateClientSecret() {
+ const res = await client.post("/oauthClients.rotate_secret", {
+ id: this.id,
+ });
+ invariant(res.data, "Failed to rotate client secret");
+
+ runInAction("OAuthClient#rotateSecret", () => {
+ this.clientSecret = res.data.clientSecret;
+ });
+ }
+
+ public get initial() {
+ return this.name[0];
+ }
+
+ public get authorizationUrl(): string {
+ const params = {
+ client_id: this.clientId,
+ redirect_uri: this.redirectUris[0],
+ response_type: "code",
+ scope: "read",
+ };
+
+ return `${env.URL}/oauth/authorize?${queryString.stringify(params)}`;
+ }
+}
+
+export default OAuthClient;
diff --git a/app/routes/authenticated.tsx b/app/routes/authenticated.tsx
index 30f407fe9e..28e7aba328 100644
--- a/app/routes/authenticated.tsx
+++ b/app/routes/authenticated.tsx
@@ -1,5 +1,5 @@
import { observer } from "mobx-react";
-import * as React from "react";
+import { Suspense } from "react";
import { Switch, Redirect, RouteComponentProps } from "react-router-dom";
import DocumentNew from "~/scenes/DocumentNew";
import Error404 from "~/scenes/Errors/Error404";
@@ -42,55 +42,77 @@ const RedirectDocument = ({
/>
);
+/**
+ * The authenticated routes are all the routes of the application that require
+ * the user to be logged in.
+ */
function AuthenticatedRoutes() {
const team = useCurrentTeam();
const can = usePolicy(team);
return (
-
-
-
-
-
- }
- >
-
- {can.createDocument && (
-
- )}
- {can.createDocument && (
-
- )}
- {can.createDocument && (
-
- )}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+ }
+ >
+
+ {can.createDocument && (
+
+ )}
+ {can.createDocument && (
+
+ )}
+ {can.createDocument && (
+
+ )}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
);
}
diff --git a/app/routes/index.tsx b/app/routes/index.tsx
index 3f90c125b8..c246ef62d0 100644
--- a/app/routes/index.tsx
+++ b/app/routes/index.tsx
@@ -1,4 +1,4 @@
-import * as React from "react";
+import { Suspense } from "react";
import { Switch, Redirect } from "react-router-dom";
import DesktopRedirect from "~/scenes/DesktopRedirect";
import DelayedMount from "~/components/DelayedMount";
@@ -6,20 +6,21 @@ import FullscreenLoading from "~/components/FullscreenLoading";
import Route from "~/components/ProfiledRoute";
import env from "~/env";
import useQueryNotices from "~/hooks/useQueryNotices";
-import lazyWithRetry from "~/utils/lazyWithRetry";
+import lazy from "~/utils/lazyWithRetry";
import { matchDocumentSlug as slug } from "~/utils/routeHelpers";
-const Authenticated = lazyWithRetry(() => import("~/components/Authenticated"));
-const AuthenticatedRoutes = lazyWithRetry(() => import("./authenticated"));
-const SharedDocument = lazyWithRetry(() => import("~/scenes/Document/Shared"));
-const Login = lazyWithRetry(() => import("~/scenes/Login"));
-const Logout = lazyWithRetry(() => import("~/scenes/Logout"));
+const Authenticated = lazy(() => import("~/components/Authenticated"));
+const AuthenticatedRoutes = lazy(() => import("./authenticated"));
+const SharedDocument = lazy(() => import("~/scenes/Document/Shared"));
+const Login = lazy(() => import("~/scenes/Login"));
+const Logout = lazy(() => import("~/scenes/Logout"));
+const OAuthAuthorize = lazy(() => import("~/scenes/Login/OAuthAuthorize"));
export default function Routes() {
useQueryNotices();
return (
-
@@ -43,6 +44,7 @@ export default function Routes() {
+
@@ -63,6 +65,6 @@ export default function Routes() {
)}
-
+
);
}
diff --git a/app/routes/settings.tsx b/app/routes/settings.tsx
index fbe6f6c2ef..5916cfd346 100644
--- a/app/routes/settings.tsx
+++ b/app/routes/settings.tsx
@@ -1,4 +1,3 @@
-import * as React from "react";
import { Switch } from "react-router-dom";
import Error404 from "~/scenes/Errors/Error404";
import Route from "~/components/ProfiledRoute";
@@ -7,6 +6,7 @@ import lazy from "~/utils/lazyWithRetry";
import { matchDocumentSlug, settingsPath } from "~/utils/routeHelpers";
const Template = lazy(() => import("~/scenes/Settings/components/Template"));
+const Application = lazy(() => import("~/scenes/Settings/Application"));
export default function SettingsRoutes() {
const configs = useSettingsConfig();
@@ -21,6 +21,12 @@ export default function SettingsRoutes() {
component={config.component}
/>
))}
+ {/* TODO: Refactor these exceptions into config? */}
+
{
- const [isLoading, setIsLoading] = React.useState(false);
- const [usersCount, setUsersCount] = React.useState(0);
- const [groupsCount, setGroupsCount] = React.useState(0);
+ const [isLoading, setIsLoading] = useState(false);
+ const [usersCount, setUsersCount] = useState(0);
+ const [groupsCount, setGroupsCount] = useState(0);
const { t } = useTranslation();
const { memberships, groupMemberships, users } = useStores();
const collectionUsers = users.inCollection(collection.id);
const context = useActionContext();
const isMobile = useMobile();
- React.useEffect(() => {
+ useEffect(() => {
const fetchData = async () => {
if (collection.permission || isMobile) {
return;
diff --git a/app/scenes/Collection/components/Notices.tsx b/app/scenes/Collection/components/Notices.tsx
index 345053e251..e919ea7d7a 100644
--- a/app/scenes/Collection/components/Notices.tsx
+++ b/app/scenes/Collection/components/Notices.tsx
@@ -1,5 +1,4 @@
import { ArchiveIcon } from "outline-icons";
-import * as React from "react";
import { useTranslation } from "react-i18next";
import Collection from "~/models/Collection";
import ErrorBoundary from "~/components/ErrorBoundary";
diff --git a/app/components/CollectionDescription.tsx b/app/scenes/Collection/components/Overview.tsx
similarity index 63%
rename from app/components/CollectionDescription.tsx
rename to app/scenes/Collection/components/Overview.tsx
index 2b76f4dd84..f5ef9d1a65 100644
--- a/app/components/CollectionDescription.tsx
+++ b/app/scenes/Collection/components/Overview.tsx
@@ -1,19 +1,23 @@
import debounce from "lodash/debounce";
import { observer } from "mobx-react";
-import * as React from "react";
+import { useMemo, useRef, useCallback, Suspense } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import styled from "styled-components";
import { richExtensions } from "@shared/editor/nodes";
import { s } from "@shared/styles";
+import { ProsemirrorHelper } from "@shared/utils/ProsemirrorHelper";
import { CollectionValidation } from "@shared/validations";
import Collection from "~/models/Collection";
+import Document from "~/models/Document";
import Editor from "~/components/Editor";
import LoadingIndicator from "~/components/LoadingIndicator";
+import Text from "~/components/Text";
import { withUIExtensions } from "~/editor/extensions";
+import useCurrentUser from "~/hooks/useCurrentUser";
import usePolicy from "~/hooks/usePolicy";
import useStores from "~/hooks/useStores";
-import Text from "./Text";
+import { Properties } from "~/types";
const extensions = withUIExtensions(richExtensions);
@@ -21,12 +25,13 @@ type Props = {
collection: Collection;
};
-function CollectionDescription({ collection }: Props) {
- const { collections } = useStores();
+function Overview({ collection }: Props) {
+ const { documents, collections } = useStores();
const { t } = useTranslation();
+ const user = useCurrentUser({ rejectOnEmpty: true });
const can = usePolicy(collection);
- const handleSave = React.useMemo(
+ const handleSave = useMemo(
() =>
debounce(async (getValue) => {
try {
@@ -41,9 +46,9 @@ function CollectionDescription({ collection }: Props) {
[collection, t]
);
- const childRef = React.useRef(null);
+ const childRef = useRef(null);
const childOffsetHeight = childRef.current?.offsetHeight || 0;
- const editorStyle = React.useMemo(
+ const editorStyle = useMemo(
() => ({
padding: "0 32px",
margin: "0 -32px",
@@ -52,24 +57,43 @@ function CollectionDescription({ collection }: Props) {
[childOffsetHeight]
);
+ const onCreateLink = useCallback(
+ async (params: Properties) => {
+ const newDocument = await documents.create(
+ {
+ collectionId: collection.id,
+ data: ProsemirrorHelper.getEmptyDocument(),
+ ...params,
+ },
+ {
+ publish: true,
+ }
+ );
+
+ return newDocument.url;
+ },
+ [collection, documents]
+ );
+
return (
<>
{collections.isSaving && }
{(collection.hasDescription || can.update) && (
- Loading…}>
+ Loading…}>
-
+
)}
>
);
@@ -81,4 +105,4 @@ const Placeholder = styled(Text)`
min-height: 27px;
`;
-export default observer(CollectionDescription);
+export default observer(Overview);
diff --git a/app/scenes/Collection/components/ShareButton.tsx b/app/scenes/Collection/components/ShareButton.tsx
index f505875c02..718ee22155 100644
--- a/app/scenes/Collection/components/ShareButton.tsx
+++ b/app/scenes/Collection/components/ShareButton.tsx
@@ -1,6 +1,5 @@
import { observer } from "mobx-react";
import { GlobeIcon, PadlockIcon } from "outline-icons";
-import * as React from "react";
import { useTranslation } from "react-i18next";
import { usePopoverState, PopoverDisclosure } from "reakit/Popover";
import Collection from "~/models/Collection";
diff --git a/app/scenes/Collection/index.tsx b/app/scenes/Collection/index.tsx
index 7568a8c174..01d2e200e7 100644
--- a/app/scenes/Collection/index.tsx
+++ b/app/scenes/Collection/index.tsx
@@ -1,5 +1,5 @@
import { observer } from "mobx-react";
-import * as React from "react";
+import { lazy, useState, useCallback, useEffect, Suspense } from "react";
import { useTranslation } from "react-i18next";
import {
useParams,
@@ -12,7 +12,7 @@ import {
} from "react-router-dom";
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
-import Icon, { IconTitleWrapper } from "@shared/components/Icon";
+import { IconTitleWrapper } from "@shared/components/Icon";
import { s } from "@shared/styles";
import { StatusFilter } from "@shared/types";
import { colorPalette } from "@shared/utils/collections";
@@ -20,7 +20,6 @@ import Collection from "~/models/Collection";
import { Action } from "~/components/Actions";
import CenteredContent from "~/components/CenteredContent";
import { CollectionBreadcrumb } from "~/components/CollectionBreadcrumb";
-import CollectionDescription from "~/components/CollectionDescription";
import Heading from "~/components/Heading";
import CollectionIcon from "~/components/Icons/CollectionIcon";
import InputSearchPage from "~/components/InputSearchPage";
@@ -46,9 +45,10 @@ import DropToImport from "./components/DropToImport";
import Empty from "./components/Empty";
import MembershipPreview from "./components/MembershipPreview";
import Notices from "./components/Notices";
+import Overview from "./components/Overview";
import ShareButton from "./components/ShareButton";
-const IconPicker = React.lazy(() => import("~/components/IconPicker"));
+const IconPicker = lazy(() => import("~/components/IconPicker"));
enum CollectionPath {
Overview = "overview",
@@ -66,8 +66,7 @@ const CollectionScene = observer(function _CollectionScene() {
const location = useLocation();
const { t } = useTranslation();
const { documents, collections, ui } = useStores();
- const [isFetching, setFetching] = React.useState(false);
- const [error, setError] = React.useState();
+ const [error, setError] = useState();
const currentPath = location.pathname;
const [, setLastVisitedPath] = useLastVisitedPath();
const sidebarContext = useLocationSidebarContext();
@@ -90,17 +89,17 @@ const CollectionScene = observer(function _CollectionScene() {
}
);
- const handleIconChange = React.useCallback(
+ const handleIconChange = useCallback(
(icon: string | null, color: string | null) =>
collection?.save({ icon, color }),
[collection]
);
- React.useEffect(() => {
+ useEffect(() => {
setLastVisitedPath(currentPath);
}, [currentPath, setLastVisitedPath]);
- React.useEffect(() => {
+ useEffect(() => {
if (collection?.name) {
const canonicalUrl = updateCollectionPath(match.url, collection);
@@ -110,7 +109,7 @@ const CollectionScene = observer(function _CollectionScene() {
}
}, [collection, collection?.name, history, id, match.url]);
- React.useEffect(() => {
+ useEffect(() => {
if (collection) {
ui.setActiveCollection(collection.id);
}
@@ -118,23 +117,18 @@ const CollectionScene = observer(function _CollectionScene() {
return () => ui.setActiveCollection(undefined);
}, [ui, collection]);
- React.useEffect(() => {
+ useEffect(() => {
async function fetchData() {
- if ((!can || !collection) && !error && !isFetching) {
- try {
- setError(undefined);
- setFetching(true);
- await collections.fetch(id);
- } catch (err) {
- setError(err);
- } finally {
- setFetching(false);
- }
+ try {
+ setError(undefined);
+ await collections.fetch(id);
+ } catch (err) {
+ setError(err);
}
}
void fetchData();
- }, [collections, isFetching, collection, error, id, can]);
+ }, []);
useCommandBarActions([editCollection], [ui.activeCollectionId ?? "none"]);
@@ -145,11 +139,7 @@ const CollectionScene = observer(function _CollectionScene() {
const hasOverview = can.update || collection?.hasDescription;
const fallbackIcon = collection ? (
-
+
) : null;
const tabProps = (path: CollectionPath) => ({
@@ -168,7 +158,7 @@ const CollectionScene = observer(function _CollectionScene() {
left={
collection.isArchived ? (
- ) : collection.isEmpty ? undefined : (
+ ) : (
{can.update ? (
-
+
-
+ >
+ {fallbackIcon}
+
+
) : (
fallbackIcon
)}
@@ -265,7 +257,7 @@ const CollectionScene = observer(function _CollectionScene() {
path={collectionPath(collection.path, CollectionPath.Overview)}
>
{hasOverview ? (
-
+
) : (
{
const token = params.get("token");
const { t } = useTranslation();
- React.useEffect(() => {
+ useEffect(() => {
if (token) {
window.open(
`outline://${window.location.host}/auth/redirect?token=${token}`,
diff --git a/app/scenes/Document/Shared.tsx b/app/scenes/Document/Shared.tsx
index 4f9b61aada..18bc8a831b 100644
--- a/app/scenes/Document/Shared.tsx
+++ b/app/scenes/Document/Shared.tsx
@@ -1,6 +1,6 @@
import { Location } from "history";
import { observer } from "mobx-react";
-import * as React from "react";
+import { useMemo, useState, useEffect } from "react";
import { Helmet } from "react-helmet-async";
import { useTranslation } from "react-i18next";
import { RouteComponentProps, useLocation } from "react-router-dom";
@@ -92,13 +92,13 @@ function SharedDocumentScene(props: Props) {
const { ui } = useStores();
const location = useLocation();
const user = useCurrentUser({ rejectOnEmpty: false });
- const searchParams = React.useMemo(
+ const searchParams = useMemo(
() => new URLSearchParams(location.search),
[location.search]
);
const { t, i18n } = useTranslation();
- const [response, setResponse] = React.useState();
- const [error, setError] = React.useState();
+ const [response, setResponse] = useState();
+ const [error, setError] = useState();
const { documents } = useStores();
const [, setPostLoginPath] = usePostLoginPath();
const { shareId = env.ROOT_SHARE_ID, documentSlug } = props.match.params;
@@ -110,7 +110,7 @@ function SharedDocumentScene(props: Props) {
: undefined;
const theme = useBuildTheme(response?.team?.customTheme, themeOverride);
- React.useEffect(() => {
+ useEffect(() => {
if (shareId) {
client.setShareId(shareId);
}
@@ -120,24 +120,24 @@ function SharedDocumentScene(props: Props) {
};
}, [shareId]);
- React.useEffect(() => {
+ useEffect(() => {
if (!user) {
void changeLanguage(detectLanguage(), i18n);
}
}, [user, i18n]);
// ensure the wider page color always matches the theme
- React.useEffect(() => {
+ useEffect(() => {
window.document.body.style.background = theme.background;
}, [theme]);
- React.useEffect(() => {
+ useEffect(() => {
if (documentId) {
ui.setActiveDocument(documentId);
}
}, [ui, documentId]);
- React.useEffect(() => {
+ useEffect(() => {
async function fetchData() {
try {
setResponse((state) => ({
diff --git a/app/scenes/Document/components/CommentThread.tsx b/app/scenes/Document/components/CommentThread.tsx
index 39daa0c1ae..0c14ecf94e 100644
--- a/app/scenes/Document/components/CommentThread.tsx
+++ b/app/scenes/Document/components/CommentThread.tsx
@@ -16,6 +16,7 @@ import { useDocumentContext } from "~/components/DocumentContext";
import Facepile from "~/components/Facepile";
import Fade from "~/components/Fade";
import { ResizingHeightContainer } from "~/components/ResizingHeightContainer";
+import useBoolean from "~/hooks/useBoolean";
import { useLocationSidebarContext } from "~/hooks/useLocationSidebarContext";
import useOnClickOutside from "~/hooks/useOnClickOutside";
import usePersistedState from "~/hooks/usePersistedState";
@@ -63,7 +64,7 @@ function CommentThread({
const history = useHistory();
const location = useLocation();
const sidebarContext = useLocationSidebarContext();
- const [autoFocus, setAutoFocus] = React.useState(thread.isNew);
+ const [autoFocus, setAutoFocusOn, setAutoFocusOff] = useBoolean(thread.isNew);
const can = usePolicy(document);
@@ -156,9 +157,9 @@ function CommentThread({
React.useEffect(() => {
if (!focused && autoFocus) {
- setAutoFocus(false);
+ setAutoFocusOff();
}
- }, [focused, autoFocus]);
+ }, [focused, autoFocus, setAutoFocusOff]);
React.useEffect(() => {
if (focused) {
@@ -273,7 +274,7 @@ function CommentThread({
)}
{!focused && !recessed && !draft && canReply && (
- setAutoFocus(true)}>{t("Reply")}…
+ {t("Reply")}…
)}
);
diff --git a/app/scenes/Document/components/Comments.tsx b/app/scenes/Document/components/Comments.tsx
index 63034508db..f17dfa66c5 100644
--- a/app/scenes/Document/components/Comments.tsx
+++ b/app/scenes/Document/components/Comments.tsx
@@ -1,7 +1,7 @@
import { AnimatePresence } from "framer-motion";
import { observer } from "mobx-react";
import { ArrowIcon } from "outline-icons";
-import * as React from "react";
+import { useRef, useState, useEffect } from "react";
import { useTranslation } from "react-i18next";
import { useRouteMatch } from "react-router-dom";
import styled from "styled-components";
@@ -39,10 +39,10 @@ function Comments() {
const focusedComment = useFocusedComment();
const can = usePolicy(document);
- const scrollableRef = React.useRef(null);
- const prevThreadCount = React.useRef(0);
- const isAtBottom = React.useRef(true);
- const [showJumpToRecentBtn, setShowJumpToRecentBtn] = React.useState(false);
+ const scrollableRef = useRef(null);
+ const prevThreadCount = useRef(0);
+ const isAtBottom = useRef(true);
+ const [showJumpToRecentBtn, setShowJumpToRecentBtn] = useState(false);
useKeyDown("Escape", () => document && ui.set({ commentsExpanded: false }));
@@ -91,7 +91,7 @@ function Comments() {
}
};
- React.useEffect(() => {
+ useEffect(() => {
// Handles: 1. on refresh 2. when switching sort setting
const readyToDisplay = Boolean(document && isEditorInitialized);
if (
@@ -103,7 +103,7 @@ function Comments() {
}
}, [sortOption.type, document, isEditorInitialized, viewingResolved]);
- React.useEffect(() => {
+ useEffect(() => {
setShowJumpToRecentBtn(false);
if (sortOption.type === CommentSortType.MostRecent && !viewingResolved) {
const commentsAdded = threads.length > prevThreadCount.current;
diff --git a/app/components/ConnectionStatus.tsx b/app/scenes/Document/components/ConnectionStatus.tsx
similarity index 88%
rename from app/components/ConnectionStatus.tsx
rename to app/scenes/Document/components/ConnectionStatus.tsx
index 6d79959633..e54467d589 100644
--- a/app/components/ConnectionStatus.tsx
+++ b/app/scenes/Document/components/ConnectionStatus.tsx
@@ -1,9 +1,14 @@
import { observer } from "mobx-react";
import { DisconnectedIcon } from "outline-icons";
-import * as React from "react";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
+import {
+ AuthenticationFailed,
+ AuthorizationFailed,
+ DocumentTooLarge,
+ TooManyConnections,
+} from "@shared/collaboration/CloseEvents";
import Fade from "~/components/Fade";
import NudeButton from "~/components/NudeButton";
import Tooltip from "~/components/Tooltip";
@@ -14,21 +19,21 @@ function ConnectionStatus() {
const { t } = useTranslation();
const codeToMessage = {
- 1009: {
+ [DocumentTooLarge.code]: {
title: t("Document is too large"),
body: t(
"This document has reached the maximum size and can no longer be edited"
),
},
- 4401: {
+ [AuthenticationFailed.code]: {
title: t("Authentication failed"),
body: t("Please try logging out and back in again"),
},
- 4403: {
+ [AuthorizationFailed.code]: {
title: t("Authorization failed"),
body: t("You may have lost access to this document, try reloading"),
},
- 4503: {
+ [TooManyConnections.code]: {
title: t("Too many users connected to document"),
body: t("Your edits will sync once other users leave the document"),
},
@@ -69,10 +74,6 @@ function ConnectionStatus() {
const Button = styled(NudeButton)`
display: none;
- position: fixed;
- bottom: 0;
- margin: 20px;
- transform: translateX(-32px);
${breakpoint("tablet")`
display: block;
diff --git a/app/scenes/Document/components/Contents.tsx b/app/scenes/Document/components/Contents.tsx
index 17dc95d6a2..0a165e69f0 100644
--- a/app/scenes/Document/components/Contents.tsx
+++ b/app/scenes/Document/components/Contents.tsx
@@ -1,6 +1,6 @@
import { observer } from "mobx-react";
import { transparentize } from "polished";
-import * as React from "react";
+import { useState, useEffect } from "react";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
@@ -13,13 +13,13 @@ import { decodeURIComponentSafe } from "~/utils/urls";
const HEADING_OFFSET = 20;
function Contents() {
- const [activeSlug, setActiveSlug] = React.useState();
+ const [activeSlug, setActiveSlug] = useState();
const scrollPosition = useWindowScrollPosition({
throttle: 100,
});
const { headings } = useDocumentContext();
- React.useEffect(() => {
+ useEffect(() => {
let activeId = headings.length > 0 ? headings[0].id : undefined;
for (let key = 0; key < headings.length; key++) {
diff --git a/app/scenes/Document/components/Document.tsx b/app/scenes/Document/components/Document.tsx
index 1bceeeb266..a7e864804a 100644
--- a/app/scenes/Document/components/Document.tsx
+++ b/app/scenes/Document/components/Document.tsx
@@ -4,7 +4,7 @@ import isEqual from "lodash/isEqual";
import { action, observable } from "mobx";
import { observer } from "mobx-react";
import { Node } from "prosemirror-model";
-import { AllSelection } from "prosemirror-state";
+import { AllSelection, TextSelection } from "prosemirror-state";
import * as React from "react";
import { WithTranslation, withTranslation } from "react-i18next";
import {
@@ -34,10 +34,10 @@ import RootStore from "~/stores/RootStore";
import Document from "~/models/Document";
import Revision from "~/models/Revision";
import Template from "~/models/Template";
+import ConnectionStatus from "~/scenes/Document/components/ConnectionStatus";
import DocumentMove from "~/scenes/DocumentMove";
import DocumentPublish from "~/scenes/DocumentPublish";
import Branding from "~/components/Branding";
-import ConnectionStatus from "~/components/ConnectionStatus";
import ErrorBoundary from "~/components/ErrorBoundary";
import LoadingIndicator from "~/components/LoadingIndicator";
import PageTitle from "~/components/PageTitle";
@@ -49,7 +49,6 @@ import type { Editor as TEditor } from "~/editor";
import { Properties } from "~/types";
import { client } from "~/utils/ApiClient";
import { emojiToUrl } from "~/utils/emoji";
-
import {
documentHistoryPath,
documentEditPath,
@@ -65,6 +64,7 @@ import Notices from "./Notices";
import PublicReferences from "./PublicReferences";
import References from "./References";
import RevisionViewer from "./RevisionViewer";
+import { SizeWarning } from "./SizeWarning";
const AUTOSAVE_DELAY = 3000;
@@ -147,7 +147,17 @@ class DocumentScene extends React.Component {
}
}
- replaceDocument = (template: Template | Revision) => {
+ /**
+ * Replaces the given selection with a template, if no selection is provided
+ * then the template is inserted at the beginning of the document.
+ *
+ * @param template The template to use
+ * @param selection The selection to replace, if any
+ */
+ replaceSelection = (
+ template: Template | Revision,
+ selection?: TextSelection | AllSelection
+ ) => {
const editorRef = this.editor.current;
if (!editorRef) {
@@ -155,6 +165,7 @@ class DocumentScene extends React.Component {
}
const { view, schema } = editorRef;
+ const sel = selection ?? TextSelection.near(view.state.doc.resolve(0));
const doc = Node.fromJSON(
schema,
ProsemirrorHelper.replaceTemplateVariables(
@@ -164,11 +175,7 @@ class DocumentScene extends React.Component {
);
if (doc) {
- view.dispatch(
- view.state.tr
- .setSelection(new AllSelection(view.state.doc))
- .replaceSelectionWith(doc)
- );
+ view.dispatch(view.state.tr.setSelection(sel).replaceSelectionWith(doc));
}
this.isEditorDirty = true;
@@ -218,7 +225,10 @@ class DocumentScene extends React.Component {
});
if (response) {
- await this.replaceDocument(response.data);
+ await this.replaceSelection(
+ response.data,
+ new AllSelection(editorRef.view.state.doc)
+ );
toast.success(t("Document restored"));
history.replace(this.props.document.url, history.location.state);
}
@@ -519,7 +529,7 @@ class DocumentScene extends React.Component {
}
savingIsDisabled={document.isSaving || this.isEmpty}
sharedTree={this.props.sharedTree}
- onSelectTemplate={this.replaceDocument}
+ onSelectTemplate={this.replaceSelection}
onSave={this.onSave}
/>
@@ -621,6 +631,7 @@ class DocumentScene extends React.Component {
)}
@@ -732,11 +743,14 @@ const RevisionContainer = styled.div`
`;
const Footer = styled.div`
- position: absolute;
+ position: fixed;
width: 100%;
+ bottom: 12px;
+ right: 20px;
text-align: right;
display: flex;
justify-content: flex-end;
+ gap: 20px;
`;
const Background = styled(Container)`
diff --git a/app/scenes/Document/components/DocumentMeta.tsx b/app/scenes/Document/components/DocumentMeta.tsx
index 1648994b8d..c2f10f24f6 100644
--- a/app/scenes/Document/components/DocumentMeta.tsx
+++ b/app/scenes/Document/components/DocumentMeta.tsx
@@ -1,7 +1,7 @@
import { LocationDescriptor } from "history";
import { observer, useObserver } from "mobx-react";
import { CommentIcon } from "outline-icons";
-import * as React from "react";
+import { useRef, Fragment } from "react";
import { useTranslation } from "react-i18next";
import { Link, useRouteMatch } from "react-router-dom";
import styled from "styled-components";
@@ -25,7 +25,7 @@ type Props = {
};
function TitleDocumentMeta({ to, document, revision, ...rest }: Props) {
- const { views, comments, ui } = useStores();
+ const { collections, views, comments, ui } = useStores();
const { t } = useTranslation();
const match = useRouteMatch();
const sidebarContext = useLocationSidebarContext();
@@ -33,17 +33,24 @@ function TitleDocumentMeta({ to, document, revision, ...rest }: Props) {
const documentViews = useObserver(() => views.inDocument(document.id));
const totalViewers = documentViews.length;
const onlyYou = totalViewers === 1 && documentViews[0].userId;
- const viewsLoadedOnMount = React.useRef(totalViewers > 0);
+ const viewsLoadedOnMount = useRef(totalViewers > 0);
const can = usePolicy(document);
- const Wrapper = viewsLoadedOnMount.current ? React.Fragment : Fade;
+ const Wrapper = viewsLoadedOnMount.current ? Fragment : Fade;
const insightsPath = documentInsightsPath(document);
const commentsCount = comments.unresolvedCommentsInDocumentCount(document.id);
+ const collection = document.collectionId
+ ? collections.get(document.collectionId)
+ : undefined;
+ const collectionCommentingEnabled =
+ collection?.canCreateComment ??
+ !!team.getPreference(TeamPreference.Commenting);
+
return (
- {team.getPreference(TeamPreference.Commenting) && can.comment && (
+ {collectionCommentingEnabled && can.comment && (
<>
•
) {
const { t } = useTranslation();
const match = useRouteMatch();
const focusedComment = useFocusedComment();
- const { ui, comments } = useStores();
+ const { ui, comments, collections } = useStores();
const user = useCurrentUser({ rejectOnEmpty: false });
const team = useCurrentTeam({ rejectOnEmpty: false });
const history = useHistory();
@@ -76,6 +76,15 @@ function DocumentEditor(props: Props, ref: React.RefObject) {
...rest
} = props;
const can = usePolicy(document);
+
+ // Check collection-level commenting setting
+ const collection = document.collectionId
+ ? collections.get(document.collectionId)
+ : undefined;
+ const collectionCommentingEnabled =
+ collection?.canCreateComment ??
+ !!team?.getPreference(TeamPreference.Commenting);
+
const iconColor = document.color ?? (last(colorPalette) as string);
const childRef = React.useRef(null);
const focusAtStart = React.useCallback(() => {
@@ -245,12 +254,12 @@ function DocumentEditor(props: Props, ref: React.RefObject) {
focusedCommentId={focusedComment?.id}
onClickCommentMark={handleClickComment}
onCreateCommentMark={
- team?.getPreference(TeamPreference.Commenting) && can.comment
+ collectionCommentingEnabled && can.comment
? handleDraftComment
: undefined
}
onDeleteCommentMark={
- team?.getPreference(TeamPreference.Commenting) && can.comment
+ collectionCommentingEnabled && can.comment
? handleRemoveComment
: undefined
}
diff --git a/app/scenes/Document/components/Header.tsx b/app/scenes/Document/components/Header.tsx
index b9ac404321..0775290170 100644
--- a/app/scenes/Document/components/Header.tsx
+++ b/app/scenes/Document/components/Header.tsx
@@ -7,7 +7,7 @@ import {
MoreIcon,
SunIcon,
} from "outline-icons";
-import * as React from "react";
+import { useRef, useState, useCallback } from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router-dom";
import styled, { useTheme } from "styled-components";
@@ -93,7 +93,7 @@ function DocumentHeader({
const isEditingFocus = useEditingFocus();
const { hasHeadings, editor } = useDocumentContext();
const sidebarContext = useLocationSidebarContext();
- const ref = React.useRef(null);
+ const ref = useRef(null);
const size = useComponentSize(ref);
const isMobile = isMobileMedia || size.width < 700;
const isShare = !!shareId;
@@ -101,15 +101,15 @@ function DocumentHeader({
// We cache this value for as long as the component is mounted so that if you
// apply a template there is still the option to replace it until the user
// navigates away from the doc
- const [isNew] = React.useState(document.isPersistedOnce);
+ const [isNew] = useState(document.isPersistedOnce);
- const handleSave = React.useCallback(() => {
+ const handleSave = useCallback(() => {
onSave({
done: true,
});
}, [onSave]);
- const handleToggle = React.useCallback(() => {
+ const handleToggle = useCallback(() => {
// Public shares, by default, show ToC on load.
if (isShare && ui.tocVisible === undefined) {
ui.set({ tocVisible: false });
@@ -375,6 +375,7 @@ function DocumentHeader({
neutral
/>
)}
+ onSelectTemplate={onSelectTemplate}
onFindAndReplace={editor?.commands.openFindAndReplace}
showToggleEmbeds={canToggleEmbeds}
showDisplayOptions
diff --git a/app/scenes/Document/components/History.tsx b/app/scenes/Document/components/History.tsx
index 815a625555..9957483b15 100644
--- a/app/scenes/Document/components/History.tsx
+++ b/app/scenes/Document/components/History.tsx
@@ -50,6 +50,7 @@ function History() {
name: "revisions.create",
actorId: data.createdBy.id,
createdAt: data.createdAt,
+ deletedAt: data.deletedAt,
latest: false,
} satisfies Event;
}
@@ -70,7 +71,7 @@ function History() {
return [];
}
- const [revisionsArr, eventsArr] = await Promise.all([
+ const [revisionsPage, eventsPage] = await Promise.all([
revisions.fetchPage({
documentId: document.id,
offset: offset.revisions,
@@ -85,7 +86,7 @@ function History() {
]);
const pageEvents = orderBy(
- [...revisionsArr, ...eventsArr].map(toEvent),
+ [...revisionsPage, ...eventsPage].map(toEvent),
"createdAt",
"desc"
).slice(0, Pagination.defaultLimit);
@@ -110,11 +111,8 @@ function History() {
const latestRevisionId = RevisionHelper.latestId(document.id);
return revisions
- .filter(
- (revision: Revision) =>
- revision.id !== latestRevisionId &&
- revision.documentId === document.id
- )
+ .getByDocumentId(document.id)
+ .filter((revision: Revision) => revision.id !== latestRevisionId)
.slice(0, offset.revisions)
.map(toEvent);
}, [document, revisions, offset.revisions, toEvent]);
@@ -123,7 +121,7 @@ function History() {
() =>
document
? events
- .filter({ documentId: document.id })
+ .getByDocumentId(document.id)
.slice(0, offset.events)
.map(toEvent)
: [],
diff --git a/app/scenes/Document/components/Insights.tsx b/app/scenes/Document/components/Insights.tsx
index f9ead39b3f..f60a4a8fe1 100644
--- a/app/scenes/Document/components/Insights.tsx
+++ b/app/scenes/Document/components/Insights.tsx
@@ -1,5 +1,4 @@
import { observer } from "mobx-react";
-import * as React from "react";
import { useTranslation } from "react-i18next";
import { useHistory, useRouteMatch } from "react-router-dom";
import styled from "styled-components";
@@ -144,10 +143,10 @@ function Insights() {
small
/>
)}
-
aria-label={t("Contributors")}
items={document.collaborators}
- renderItem={(model: User) => (
+ renderItem={(model) => (
{documentViews.length > 1 && (
-
+
)}
>
diff --git a/app/scenes/Document/components/KeyboardShortcutsButton.tsx b/app/scenes/Document/components/KeyboardShortcutsButton.tsx
index 40402c2868..49c9b54a9a 100644
--- a/app/scenes/Document/components/KeyboardShortcutsButton.tsx
+++ b/app/scenes/Document/components/KeyboardShortcutsButton.tsx
@@ -1,6 +1,5 @@
import { observer } from "mobx-react";
import { KeyboardIcon } from "outline-icons";
-import * as React from "react";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
@@ -33,9 +32,6 @@ function KeyboardShortcutsButton() {
const Button = styled(NudeButton)<{ $hidden: boolean }>`
display: none;
- position: fixed;
- bottom: 0;
- margin: 20px;
transition: opacity 500ms ease-in-out;
${(props) => props.$hidden && "opacity: 0;"}
diff --git a/app/scenes/Document/components/Loading.tsx b/app/scenes/Document/components/Loading.tsx
index fb998bb02b..84c4f3e194 100644
--- a/app/scenes/Document/components/Loading.tsx
+++ b/app/scenes/Document/components/Loading.tsx
@@ -1,5 +1,4 @@
import { Location } from "history";
-import * as React from "react";
import CenteredContent from "~/components/CenteredContent";
import PageTitle from "~/components/PageTitle";
import PlaceholderDocument from "~/components/PlaceholderDocument";
diff --git a/app/scenes/Document/components/MarkAsViewed.ts b/app/scenes/Document/components/MarkAsViewed.ts
index 8f887b2880..78d08c83e4 100644
--- a/app/scenes/Document/components/MarkAsViewed.ts
+++ b/app/scenes/Document/components/MarkAsViewed.ts
@@ -1,4 +1,4 @@
-import * as React from "react";
+import { useRef, useEffect } from "react";
import Document from "~/models/Document";
const MARK_AS_VIEWED_AFTER = 3 * 1000;
@@ -9,9 +9,9 @@ type Props = {
function MarkAsViewed(props: Props) {
const { document, children } = props;
- const viewTimeout = React.useRef | null>(null);
+ const viewTimeout = useRef | null>(null);
- React.useEffect(() => {
+ useEffect(() => {
viewTimeout.current = setTimeout(async () => {
const view = await document.view();
diff --git a/app/scenes/Document/components/MultiplayerEditor.tsx b/app/scenes/Document/components/MultiplayerEditor.tsx
index 805ad055a2..bb27f4e209 100644
--- a/app/scenes/Document/components/MultiplayerEditor.tsx
+++ b/app/scenes/Document/components/MultiplayerEditor.tsx
@@ -1,11 +1,23 @@
import { HocuspocusProvider, WebSocketStatus } from "@hocuspocus/provider";
import throttle from "lodash/throttle";
-import * as React from "react";
+import {
+ useState,
+ useLayoutEffect,
+ useMemo,
+ useEffect,
+ forwardRef,
+} from "react";
import { useTranslation } from "react-i18next";
import { useHistory } from "react-router-dom";
import { toast } from "sonner";
import { IndexeddbPersistence } from "y-indexeddb";
import * as Y from "yjs";
+import {
+ AuthenticationFailed,
+ DocumentTooLarge,
+ EditorUpdateError,
+} from "@shared/collaboration/CloseEvents";
+import EDITOR_VERSION from "@shared/editor/version";
import { supportsPassiveListener } from "@shared/utils/browser";
import Editor, { Props as EditorProps } from "~/components/Editor";
import MultiplayerExtension from "~/editor/extensions/Multiplayer";
@@ -45,12 +57,12 @@ function MultiplayerEditor({ onSynced, ...props }: Props, ref: any) {
const { t } = useTranslation();
const currentUser = useCurrentUser();
const { presence, auth, ui } = useStores();
- const [showCursorNames, setShowCursorNames] = React.useState(false);
+ const [showCursorNames, setShowCursorNames] = useState(false);
const [remoteProvider, setRemoteProvider] =
- React.useState(null);
- const [isLocalSynced, setLocalSynced] = React.useState(false);
- const [isRemoteSynced, setRemoteSynced] = React.useState(false);
- const [ydoc] = React.useState(() => new Y.Doc());
+ useState(null);
+ const [isLocalSynced, setLocalSynced] = useState(false);
+ const [isRemoteSynced, setRemoteSynced] = useState(false);
+ const [ydoc] = useState(() => new Y.Doc());
const token = auth.collaborationToken;
const isIdle = useIdle();
const isVisible = usePageVisibility();
@@ -60,11 +72,14 @@ function MultiplayerEditor({ onSynced, ...props }: Props, ref: any) {
// or useMemo as both of these are ran twice in React StrictMode resulting in
// an orphaned websocket connection.
// see: https://github.com/facebook/react/issues/20090#issuecomment-715926549
- React.useLayoutEffect(() => {
+ useLayoutEffect(() => {
const debug = env.ENVIRONMENT === "development";
const name = `document.${documentId}`;
const localProvider = new IndexeddbPersistence(name, ydoc);
const provider = new HocuspocusProvider({
+ parameters: {
+ editorVersion: EDITOR_VERSION,
+ },
url: `${env.COLLABORATION_URL}/collaboration`,
name,
document: ydoc,
@@ -140,8 +155,14 @@ function MultiplayerEditor({ onSynced, ...props }: Props, ref: any) {
provider.on("close", (ev: MessageEvent) => {
if ("code" in ev.event) {
provider.shouldConnect =
- ev.event.code !== 1009 && ev.event.code !== 4401;
+ ev.event.code !== DocumentTooLarge.code &&
+ ev.event.code !== AuthenticationFailed.code &&
+ ev.event.code !== EditorUpdateError.code;
ui.setMultiplayerStatus("disconnected", ev.event.code);
+
+ if (ev.event.code === EditorUpdateError.code) {
+ window.location.reload();
+ }
}
});
@@ -194,7 +215,7 @@ function MultiplayerEditor({ onSynced, ...props }: Props, ref: any) {
auth,
]);
- const user = React.useMemo(
+ const user = useMemo(
() => ({
id: currentUser.id,
name: currentUser.name,
@@ -203,7 +224,7 @@ function MultiplayerEditor({ onSynced, ...props }: Props, ref: any) {
[currentUser.id, currentUser.color, currentUser.name]
);
- const extensions = React.useMemo(() => {
+ const extensions = useMemo(() => {
if (!remoteProvider) {
return props.extensions;
}
@@ -218,7 +239,7 @@ function MultiplayerEditor({ onSynced, ...props }: Props, ref: any) {
];
}, [remoteProvider, user, ydoc, props.extensions]);
- React.useEffect(() => {
+ useEffect(() => {
if (isLocalSynced && isRemoteSynced) {
void onSynced?.();
}
@@ -226,7 +247,7 @@ function MultiplayerEditor({ onSynced, ...props }: Props, ref: any) {
// Disconnect the realtime connection while idle. `isIdle` also checks for
// page visibility and will immediately disconnect when a tab is hidden.
- React.useEffect(() => {
+ useEffect(() => {
if (!remoteProvider) {
return;
}
@@ -250,7 +271,7 @@ function MultiplayerEditor({ onSynced, ...props }: Props, ref: any) {
// Certain emoji combinations trigger this error in YJS, while waiting for a fix
// we must prevent the user from continuing to edit as their changes will not
// be persisted. See: https://github.com/yjs/yjs/issues/303
- React.useEffect(() => {
+ useEffect(() => {
function onUnhandledError(event: ErrorEvent) {
if (event.message.includes("URIError: URI malformed")) {
toast.error(
@@ -306,6 +327,4 @@ function MultiplayerEditor({ onSynced, ...props }: Props, ref: any) {
);
}
-export default React.forwardRef(
- MultiplayerEditor
-);
+export default forwardRef(MultiplayerEditor);
diff --git a/app/scenes/Document/components/Notices.tsx b/app/scenes/Document/components/Notices.tsx
index 5e23507fc9..e14e30f96f 100644
--- a/app/scenes/Document/components/Notices.tsx
+++ b/app/scenes/Document/components/Notices.tsx
@@ -1,6 +1,5 @@
import { differenceInDays } from "date-fns";
import { TrashIcon, ArchiveIcon } from "outline-icons";
-import * as React from "react";
import { Trans, useTranslation } from "react-i18next";
import Document from "~/models/Document";
import ErrorBoundary from "~/components/ErrorBoundary";
diff --git a/app/scenes/Document/components/ObservingBanner.tsx b/app/scenes/Document/components/ObservingBanner.tsx
index 538906aa9c..ff3e5d85c3 100644
--- a/app/scenes/Document/components/ObservingBanner.tsx
+++ b/app/scenes/Document/components/ObservingBanner.tsx
@@ -1,6 +1,5 @@
import { m, AnimatePresence } from "framer-motion";
import { observer } from "mobx-react";
-import * as React from "react";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
import { depths } from "@shared/styles";
diff --git a/app/scenes/Document/components/PublicReferences.tsx b/app/scenes/Document/components/PublicReferences.tsx
index cecb82c04f..3a9cd5fe11 100644
--- a/app/scenes/Document/components/PublicReferences.tsx
+++ b/app/scenes/Document/components/PublicReferences.tsx
@@ -1,5 +1,5 @@
import { observer } from "mobx-react";
-import * as React from "react";
+import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import { NavigationNode } from "@shared/types";
import Subheading from "~/components/Subheading";
@@ -18,7 +18,7 @@ function PublicReferences(props: Props) {
// The sharedTree is the entire document tree starting at the shared document
// we must filter down the tree to only the part with the document we're
// currently viewing
- const children = React.useMemo(() => {
+ const children = useMemo(() => {
let result: NavigationNode[];
function findChildren(node?: NavigationNode) {
diff --git a/app/scenes/Document/components/ReferenceListItem.tsx b/app/scenes/Document/components/ReferenceListItem.tsx
index 5bf08964d5..e723d9cce5 100644
--- a/app/scenes/Document/components/ReferenceListItem.tsx
+++ b/app/scenes/Document/components/ReferenceListItem.tsx
@@ -1,6 +1,5 @@
import { observer } from "mobx-react";
import { DocumentIcon } from "outline-icons";
-import * as React from "react";
import { Link } from "react-router-dom";
import styled from "styled-components";
import Icon from "@shared/components/Icon";
diff --git a/app/scenes/Document/components/References.tsx b/app/scenes/Document/components/References.tsx
index 8ed91d1df1..a9c6d723a2 100644
--- a/app/scenes/Document/components/References.tsx
+++ b/app/scenes/Document/components/References.tsx
@@ -1,5 +1,5 @@
import { observer } from "mobx-react";
-import * as React from "react";
+import { useEffect, useRef, Fragment } from "react";
import { Trans } from "react-i18next";
import { useLocation } from "react-router-dom";
import styled from "styled-components";
@@ -18,28 +18,26 @@ type Props = {
};
function References({ document }: Props) {
- const { collections, documents } = useStores();
+ const { documents } = useStores();
const user = useCurrentUser();
const location = useLocation();
const locationSidebarContext = useLocationSidebarContext();
- React.useEffect(() => {
+ useEffect(() => {
void documents.fetchBacklinks(document.id);
}, [documents, document.id]);
- const backlinks = documents.getBacklinkedDocuments(document.id);
- const collection = document.collectionId
- ? collections.get(document.collectionId)
- : undefined;
+ const backlinks = document.backlinks;
+ const collection = document.collection;
const children = collection
? collection.getChildrenForDocument(document.id)
: [];
const showBacklinks = !!backlinks.length;
const showChildDocuments = !!children.length;
- const shouldFade = React.useRef(!showBacklinks && !showChildDocuments);
+ const shouldFade = useRef(!showBacklinks && !showChildDocuments);
const isBacklinksTab = location.hash === "#backlinks" || !showChildDocuments;
const height = Math.max(backlinks.length, children.length) * 40;
- const Component = shouldFade.current ? Fade : React.Fragment;
+ const Component = shouldFade.current ? Fade : Fragment;
return showBacklinks || showChildDocuments ? (
diff --git a/app/scenes/Document/components/ShareButton.tsx b/app/scenes/Document/components/ShareButton.tsx
index 290a9c2cb4..ec24ec3e98 100644
--- a/app/scenes/Document/components/ShareButton.tsx
+++ b/app/scenes/Document/components/ShareButton.tsx
@@ -1,6 +1,5 @@
import { observer } from "mobx-react";
import { GlobeIcon } from "outline-icons";
-import * as React from "react";
import { useTranslation } from "react-i18next";
import { usePopoverState, PopoverDisclosure } from "reakit/Popover";
import Document from "~/models/Document";
diff --git a/app/scenes/Document/components/SizeWarning.tsx b/app/scenes/Document/components/SizeWarning.tsx
new file mode 100644
index 0000000000..99224904d1
--- /dev/null
+++ b/app/scenes/Document/components/SizeWarning.tsx
@@ -0,0 +1,56 @@
+import { WarningIcon } from "outline-icons";
+import { useTranslation } from "react-i18next";
+import styled from "styled-components";
+import breakpoint from "styled-components-breakpoint";
+import { DocumentValidation } from "@shared/validations";
+import type Document from "~/models/Document";
+import Fade from "~/components/Fade";
+import NudeButton from "~/components/NudeButton";
+import Tooltip from "~/components/Tooltip";
+
+type Props = {
+ document: Document;
+};
+
+export const SizeWarning = ({ document }: Props) => {
+ const { t } = useTranslation();
+ const length = document.toPlainText().length;
+
+ if (length < DocumentValidation.maxRecommendedLength) {
+ return null;
+ }
+
+ return (
+
+ {t("Warning")}
+
+ {t("This document is large which may affect performance")}
+
+ }
+ >
+
+
+
+
+
+
+ );
+};
+
+const Button = styled(NudeButton)`
+ display: none;
+
+ ${breakpoint("tablet")`
+ display: block;
+ `};
+
+ @media print {
+ display: none;
+ }
+`;
+
+const Centered = styled.div`
+ text-align: center;
+`;
diff --git a/app/scenes/Document/index.tsx b/app/scenes/Document/index.tsx
index ac390aaae2..d27b6fdc12 100644
--- a/app/scenes/Document/index.tsx
+++ b/app/scenes/Document/index.tsx
@@ -1,4 +1,4 @@
-import * as React from "react";
+import { useEffect } from "react";
import { StaticContext, useHistory } from "react-router";
import { RouteComponentProps } from "react-router-dom";
import { SidebarContextType } from "~/components/Sidebar/components/SidebarContext";
@@ -29,13 +29,13 @@ export default function DocumentScene(props: Props) {
const currentPath = props.location.pathname;
const [, setLastVisitedPath] = useLastVisitedPath();
- React.useEffect(() => {
+ useEffect(() => {
setLastVisitedPath(currentPath);
}, [currentPath, setLastVisitedPath]);
- React.useEffect(() => () => ui.clearActiveDocument(), [ui]);
+ useEffect(() => () => ui.clearActiveDocument(), [ui]);
- React.useEffect(() => {
+ useEffect(() => {
// When opening a document directly on app load, sidebarContext will not be set.
if (!props.location.state?.sidebarContext) {
history.replace({
diff --git a/app/scenes/DocumentMove.tsx b/app/scenes/DocumentMove.tsx
index 3271acb0ea..f836d57534 100644
--- a/app/scenes/DocumentMove.tsx
+++ b/app/scenes/DocumentMove.tsx
@@ -1,6 +1,6 @@
import flatten from "lodash/flatten";
import { observer } from "mobx-react";
-import * as React from "react";
+import { useState, useMemo } from "react";
import { useTranslation, Trans } from "react-i18next";
import { toast } from "sonner";
import styled from "styled-components";
@@ -23,11 +23,9 @@ function DocumentMove({ document }: Props) {
const { dialogs, policies } = useStores();
const { t } = useTranslation();
const collectionTrees = useCollectionTrees();
- const [selectedPath, selectPath] = React.useState(
- null
- );
+ const [selectedPath, selectPath] = useState(null);
- const items = React.useMemo(() => {
+ const items = useMemo(() => {
// Recursively filter out the document itself and its existing parent doc, if any.
const filterSourceDocument = (node: NavigationNode): NavigationNode => ({
...node,
diff --git a/app/scenes/DocumentNew.tsx b/app/scenes/DocumentNew.tsx
index f92efe8692..ba3b295092 100644
--- a/app/scenes/DocumentNew.tsx
+++ b/app/scenes/DocumentNew.tsx
@@ -1,5 +1,4 @@
import { observer } from "mobx-react";
-import * as React from "react";
import { useEffect } from "react";
import { useTranslation } from "react-i18next";
import { useHistory, useLocation, useRouteMatch } from "react-router-dom";
diff --git a/app/scenes/DocumentPermanentDelete.tsx b/app/scenes/DocumentPermanentDelete.tsx
index 6ae4ed20d1..e485408227 100644
--- a/app/scenes/DocumentPermanentDelete.tsx
+++ b/app/scenes/DocumentPermanentDelete.tsx
@@ -1,5 +1,4 @@
import { observer } from "mobx-react";
-import * as React from "react";
import { useTranslation, Trans } from "react-i18next";
import { useHistory } from "react-router-dom";
import { toast } from "sonner";
diff --git a/app/scenes/DocumentPublish.tsx b/app/scenes/DocumentPublish.tsx
index 14d6b6b10a..79d8f5ceca 100644
--- a/app/scenes/DocumentPublish.tsx
+++ b/app/scenes/DocumentPublish.tsx
@@ -1,6 +1,6 @@
import flatten from "lodash/flatten";
import { observer } from "mobx-react";
-import * as React from "react";
+import { useState, useMemo } from "react";
import { useTranslation, Trans } from "react-i18next";
import { toast } from "sonner";
import styled from "styled-components";
@@ -24,10 +24,8 @@ function DocumentPublish({ document }: Props) {
const { dialogs, policies } = useStores();
const { t } = useTranslation();
const collectionTrees = useCollectionTrees();
- const [selectedPath, selectPath] = React.useState(
- null
- );
- const publishOptions = React.useMemo(
+ const [selectedPath, selectPath] = useState(null);
+ const publishOptions = useMemo(
() =>
flatten(collectionTrees.map(flattenTree)).filter((node) =>
node.collectionId
diff --git a/app/scenes/Drafts.tsx b/app/scenes/Drafts.tsx
index d80fe7840f..92da166bd6 100644
--- a/app/scenes/Drafts.tsx
+++ b/app/scenes/Drafts.tsx
@@ -1,7 +1,6 @@
import { observer } from "mobx-react";
import { DraftsIcon } from "outline-icons";
import queryString from "query-string";
-import * as React from "react";
import { useTranslation } from "react-i18next";
import { useHistory, useLocation } from "react-router-dom";
import styled from "styled-components";
diff --git a/app/scenes/Errors/Error402.tsx b/app/scenes/Errors/Error402.tsx
index 5d0ec44dab..e207d7bc56 100644
--- a/app/scenes/Errors/Error402.tsx
+++ b/app/scenes/Errors/Error402.tsx
@@ -1,4 +1,3 @@
-import * as React from "react";
import { useTranslation } from "react-i18next";
import { useLocation } from "react-router-dom";
import Flex from "@shared/components/Flex";
diff --git a/app/scenes/Errors/Error403.tsx b/app/scenes/Errors/Error403.tsx
index cbfe5b9d81..c14fb86446 100644
--- a/app/scenes/Errors/Error403.tsx
+++ b/app/scenes/Errors/Error403.tsx
@@ -1,4 +1,3 @@
-import * as React from "react";
import { useTranslation } from "react-i18next";
import { useHistory } from "react-router-dom";
import Flex from "@shared/components/Flex";
diff --git a/app/scenes/Errors/Error404.tsx b/app/scenes/Errors/Error404.tsx
index 71ac974940..ea49bf24f8 100644
--- a/app/scenes/Errors/Error404.tsx
+++ b/app/scenes/Errors/Error404.tsx
@@ -1,4 +1,3 @@
-import * as React from "react";
import { useTranslation, Trans } from "react-i18next";
import Flex from "@shared/components/Flex";
import Button from "~/components/Button";
diff --git a/app/scenes/Errors/ErrorOffline.tsx b/app/scenes/Errors/ErrorOffline.tsx
index 5abcabe605..b44d0baa48 100644
--- a/app/scenes/Errors/ErrorOffline.tsx
+++ b/app/scenes/Errors/ErrorOffline.tsx
@@ -1,4 +1,3 @@
-import * as React from "react";
import { useTranslation } from "react-i18next";
import CenteredContent from "~/components/CenteredContent";
import Empty from "~/components/Empty";
diff --git a/app/scenes/Errors/ErrorSuspended.tsx b/app/scenes/Errors/ErrorSuspended.tsx
index b5981360af..e50e4e6656 100644
--- a/app/scenes/Errors/ErrorSuspended.tsx
+++ b/app/scenes/Errors/ErrorSuspended.tsx
@@ -1,5 +1,4 @@
import { observer } from "mobx-react";
-import * as React from "react";
import { useTranslation, Trans } from "react-i18next";
import CenteredContent from "~/components/CenteredContent";
import Heading from "~/components/Heading";
diff --git a/app/scenes/Home.tsx b/app/scenes/Home.tsx
index b2c5d27cdc..f933fdca4d 100644
--- a/app/scenes/Home.tsx
+++ b/app/scenes/Home.tsx
@@ -1,8 +1,7 @@
import { observer } from "mobx-react";
import { HomeIcon } from "outline-icons";
-import * as React from "react";
import { useTranslation } from "react-i18next";
-import { Switch, Route, Redirect } from "react-router-dom";
+import { Switch, Route } from "react-router-dom";
import styled from "styled-components";
import { s } from "@shared/styles";
import { Action } from "~/components/Actions";
@@ -18,7 +17,6 @@ import Tab from "~/components/Tab";
import Tabs from "~/components/Tabs";
import useCurrentTeam from "~/hooks/useCurrentTeam";
import useCurrentUser from "~/hooks/useCurrentUser";
-import { usePostLoginPath } from "~/hooks/useLastVisitedPath";
import { usePinnedDocuments } from "~/hooks/usePinnedDocuments";
import usePolicy from "~/hooks/usePolicy";
import useStores from "~/hooks/useStores";
@@ -29,16 +27,10 @@ function Home() {
const team = useCurrentTeam();
const user = useCurrentUser();
const { t } = useTranslation();
- const [spendPostLoginPath] = usePostLoginPath();
const userId = user?.id;
const { pins, count } = usePinnedDocuments("home");
const can = usePolicy(team);
- const postLoginPath = spendPostLoginPath();
- if (postLoginPath) {
- return ;
- }
-
return (
}
diff --git a/app/scenes/Invite.tsx b/app/scenes/Invite.tsx
index 8cb13d9c1b..4c22b2824d 100644
--- a/app/scenes/Invite.tsx
+++ b/app/scenes/Invite.tsx
@@ -209,7 +209,9 @@ function Invite({ onSubmit }: Props) {
placeholder={`name@${predictedDomain}`}
value={invite.email}
required={index === 0}
+ autoComplete="off"
autoFocus
+ data-1p-ignore
flex
/>
[
{
title: t("Navigation"),
@@ -415,6 +415,10 @@ function KeyboardShortcuts() {
shortcut: --- ,
label: t("Horizontal divider"),
},
+ {
+ shortcut: {"|--"} ,
+ label: t("Table"),
+ },
{
shortcut: {"```"} ,
label: t("Code block"),
@@ -477,13 +481,13 @@ function KeyboardShortcuts() {
],
[t]
);
- const [searchTerm, setSearchTerm] = React.useState("");
+ const [searchTerm, setSearchTerm] = useState("");
const normalizedSearchTerm = searchTerm.toLocaleLowerCase();
- const handleChange = React.useCallback((event) => {
+ const handleChange = useCallback((event) => {
setSearchTerm(event.target.value);
}, []);
- const handleKeyDown = React.useCallback((event) => {
+ const handleKeyDown = useCallback((event) => {
if (event.currentTarget.value && event.key === "Escape") {
event.preventDefault();
event.stopPropagation();
@@ -512,19 +516,19 @@ function KeyboardShortcuts() {
}
return (
-
+
{filtered.map((item) => (
-
+
{item.shortcut}
{item.label}
-
+
))}
-
+
);
})}
@@ -578,4 +582,4 @@ const Label = styled.dd`
color: ${s("textSecondary")};
`;
-export default React.memo(KeyboardShortcuts);
+export default memo(KeyboardShortcuts);
diff --git a/app/scenes/Login/index.tsx b/app/scenes/Login/Login.tsx
similarity index 90%
rename from app/scenes/Login/index.tsx
rename to app/scenes/Login/Login.tsx
index 96a356abe2..f41ac04f4a 100644
--- a/app/scenes/Login/index.tsx
+++ b/app/scenes/Login/Login.tsx
@@ -13,7 +13,6 @@ import { Config } from "~/stores/AuthStore";
import { AvatarSize } from "~/components/Avatar";
import ButtonLarge from "~/components/ButtonLarge";
import ChangeLanguage from "~/components/ChangeLanguage";
-import Fade from "~/components/Fade";
import Flex from "~/components/Flex";
import Heading from "~/components/Heading";
import OutlineIcon from "~/components/Icons/OutlineIcon";
@@ -30,21 +29,23 @@ import {
} from "~/hooks/useLastVisitedPath";
import useQuery from "~/hooks/useQuery";
import useStores from "~/hooks/useStores";
-import { draggableOnDesktop } from "~/styles";
import Desktop from "~/utils/Desktop";
import isCloudHosted from "~/utils/isCloudHosted";
import { detectLanguage } from "~/utils/language";
import { homePath } from "~/utils/routeHelpers";
import AuthenticationProvider from "./components/AuthenticationProvider";
-import BackButton from "./components/BackButton";
-import Notices from "./components/Notices";
+import { BackButton } from "./components/BackButton";
+import { Background } from "./components/Background";
+import { Centered } from "./components/Centered";
+import { Notices } from "./components/Notices";
import { getRedirectUrl, navigateToSubdomain } from "./urls";
type Props = {
children?: (config?: Config) => React.ReactNode;
+ onBack?: () => void;
};
-function Login({ children }: Props) {
+function Login({ children, onBack }: Props) {
const location = useLocation();
const query = useQuery();
const notice = query.get("notice");
@@ -110,9 +111,9 @@ function Login({ children }: Props) {
if (error) {
return (
-
+
-
+
{t("Error")}
@@ -142,9 +143,9 @@ function Login({ children }: Props) {
if (isCloudHosted && isCustomDomain && !config.name) {
return (
-
+
-
+
{t("Almost there")}…
@@ -160,17 +161,10 @@ function Login({ children }: Props) {
if (Desktop.isElectron() && notice === "domain-required") {
return (
-
+
-
+
{t("Choose workspace")}
{t(
@@ -206,8 +200,8 @@ function Login({ children }: Props) {
if (emailLinkSentTo) {
return (
-
-
+
+
{t("Check your email")}
@@ -241,10 +235,10 @@ function Login({ children }: Props) {
return (
-
+
-
+
@@ -336,14 +330,6 @@ const CheckEmailIcon = styled(EmailIcon)`
margin-bottom: -1.5em;
`;
-const Background = styled(Fade)`
- width: 100vw;
- height: 100%;
- background: ${s("background")};
- display: flex;
- ${draggableOnDesktop()}
-`;
-
const Logo = styled.div`
margin-bottom: -4px;
`;
@@ -389,12 +375,4 @@ const Or = styled.hr`
}
`;
-const Centered = styled(Flex)`
- user-select: none;
- width: 90vw;
- height: 100%;
- max-width: 320px;
- margin: 0 auto;
-`;
-
export default observer(Login);
diff --git a/app/scenes/Login/OAuthAuthorize.tsx b/app/scenes/Login/OAuthAuthorize.tsx
new file mode 100644
index 0000000000..22099676e9
--- /dev/null
+++ b/app/scenes/Login/OAuthAuthorize.tsx
@@ -0,0 +1,260 @@
+import { useState, useRef, useEffect } from "react";
+import { Trans, useTranslation } from "react-i18next";
+import styled from "styled-components";
+import Flex from "@shared/components/Flex";
+import { s } from "@shared/styles";
+import { parseDomain } from "@shared/utils/domains";
+import type OAuthClient from "~/models/oauth/OAuthClient";
+import ButtonLarge from "~/components/ButtonLarge";
+import ChangeLanguage from "~/components/ChangeLanguage";
+import Heading from "~/components/Heading";
+import LoadingIndicator from "~/components/LoadingIndicator";
+import PageTitle from "~/components/PageTitle";
+import Text from "~/components/Text";
+import env from "~/env";
+import useCurrentTeam from "~/hooks/useCurrentTeam";
+import { useLoggedInSessions } from "~/hooks/useLoggedInSessions";
+import useQuery from "~/hooks/useQuery";
+import useRequest from "~/hooks/useRequest";
+import { client } from "~/utils/ApiClient";
+import { BadRequestError, NotFoundError } from "~/utils/errors";
+import isCloudHosted from "~/utils/isCloudHosted";
+import { detectLanguage } from "~/utils/language";
+import Login from "./Login";
+import { OAuthScopeHelper } from "./OAuthScopeHelper";
+import { Background } from "./components/Background";
+import { Centered } from "./components/Centered";
+import { ConnectHeader } from "./components/ConnectHeader";
+import { TeamSwitcher } from "./components/TeamSwitcher";
+
+export default function OAuthAuthorize() {
+ const team = useCurrentTeam({ rejectOnEmpty: false });
+ const sessions = useLoggedInSessions();
+
+ // We're self-hosted or on a team subdomain already, just show the authorize screen.
+ if (team) {
+ return ;
+ }
+
+ // Cloud hosted and on root domain – show the workspace switcher.
+ const isAppRoot =
+ parseDomain(window.location.hostname).host === parseDomain(env.URL).host;
+ const hasLoggedInSessions = Object.keys(sessions).length > 0;
+ if (isCloudHosted && hasLoggedInSessions && isAppRoot) {
+ return ;
+ }
+
+ return ;
+}
+
+/**
+ * Authorize component is responsible for handling the OAuth authorization process.
+ * It retrieves the OAuth client information, displays the authorization request,
+ * and allows the user to either authorize or cancel the request.
+ */
+function Authorize() {
+ const team = useCurrentTeam();
+ const params = useQuery();
+ const { t } = useTranslation();
+ const [isSubmitting, setIsSubmitting] = useState(false);
+ const timeoutRef = useRef();
+ const {
+ client_id: clientId,
+ redirect_uri: redirectUri,
+ response_type: responseType,
+ code_challenge: codeChallenge,
+ code_challenge_method: codeChallengeMethod,
+ state,
+ scope,
+ } = Object.fromEntries(params);
+ const [scopes] = useState(() => scope?.split(" ") ?? []);
+ const { error: clientError, data: response } = useRequest<{
+ data: OAuthClient;
+ }>(() => client.post("/oauthClients.info", { clientId, redirectUri }), true);
+
+ const handleCancel = () => {
+ if (redirectUri && !clientError) {
+ const url = new URL(redirectUri);
+ url.searchParams.set("error", "access_denied");
+ window.location.href = url.toString();
+ return;
+ }
+ if (window.history.length) {
+ window.history.back();
+ } else {
+ window.location.href = "/";
+ }
+ };
+
+ const handleSubmit = () => {
+ setIsSubmitting(true);
+ timeoutRef.current = window.setTimeout(() => setIsSubmitting(false), 5000);
+ };
+
+ useEffect(
+ () => () => {
+ timeoutRef.current && window.clearTimeout(timeoutRef.current);
+ },
+ []
+ );
+
+ const missingParams = [
+ !clientId && "client_id",
+ !redirectUri && "redirect_uri",
+ !responseType && "response_type",
+ !scope && "scope",
+ !state && "state",
+ ].filter(Boolean);
+
+ if (missingParams.length || clientError) {
+ return (
+
+
+ {t("An error occurred")}
+ {clientError instanceof NotFoundError ? (
+
+ {t(
+ "The OAuth client could not be found, please check the provided client ID"
+ )}
+ {clientId}
+
+ ) : clientError instanceof BadRequestError ? (
+
+ {t(
+ "The OAuth client could not be loaded, please check the redirect URI is valid"
+ )}
+ {redirectUri}
+
+ ) : (
+
+ {t("Required OAuth parameters are missing")}
+
+ {missingParams.map((param) => (
+ <>
+ {param}
+
+ >
+ ))}
+
+
+ )}
+
+
+ );
+ }
+
+ if (!response) {
+ return ;
+ }
+
+ const { name, developerName, developerUrl } = response.data;
+
+ return (
+
+
+
+
+
+
+ {t(`{{ appName }} wants to access {{ teamName }}`, {
+ appName: name,
+ teamName: team.name,
+ })}
+
+ {developerName && (
+
+
+ ) : (
+
+ ),
+ }}
+ />
+
+ )}
+
+ {t(
+ "{{ appName }} will be able to access your account and perform the following actions",
+ {
+ appName: name,
+ }
+ )}
+ :
+
+
+ {OAuthScopeHelper.normalizeScopes(scopes, t).map((item) => (
+
+ {item}
+
+ ))}
+
+
+
+
+ );
+}
+
+const Button = styled(ButtonLarge)`
+ width: calc(50% - 4px);
+`;
+
+const StyledHeading = styled(Heading).attrs({
+ as: "h2",
+ centered: true,
+})`
+ margin-top: 0;
+`;
+
+const Pre = styled.pre`
+ background: ${s("backgroundSecondary")};
+ padding: 16px;
+ border-radius: 4px;
+ font-size: 12px;
+ white-space: pre-wrap;
+`;
diff --git a/app/scenes/Login/OAuthScopeHelper.ts b/app/scenes/Login/OAuthScopeHelper.ts
new file mode 100644
index 0000000000..598d4ef004
--- /dev/null
+++ b/app/scenes/Login/OAuthScopeHelper.ts
@@ -0,0 +1,56 @@
+import type { TFunction } from "i18next";
+import capitalize from "lodash/capitalize";
+import uniq from "lodash/uniq";
+import { Scope } from "@shared/types";
+
+export class OAuthScopeHelper {
+ public static normalizeScopes(scopes: string[], t: TFunction): string[] {
+ const methodToReadable = {
+ list: t("read"),
+ info: t("read"),
+ read: t("read"),
+ write: t("write"),
+ create: t("write"),
+ update: t("write"),
+ delete: t("write"),
+ "*": t("read and write"),
+ };
+
+ const translatedNamespaces = {
+ apiKeys: t("API keys"),
+ attachments: t("attachments"),
+ collections: t("collections"),
+ comments: t("comments"),
+ documents: t("documents"),
+ events: t("events"),
+ groups: t("groups"),
+ integrations: t("integrations"),
+ notifications: t("notifications"),
+ reactions: t("reactions"),
+ pins: t("pins"),
+ shares: t("shares"),
+ users: t("users"),
+ teams: t("teams"),
+ "*": t("workspace"),
+ };
+
+ const normalizedScopes = scopes.map((scope) => {
+ if (scope === Scope.Read) {
+ return t("Read all data");
+ }
+ if (scope === Scope.Write) {
+ return t("Write all data");
+ }
+
+ const [namespace, method] = scope.replace("/api/", "").split(/[:\.]/g);
+ const readableMethod =
+ methodToReadable[method as keyof typeof methodToReadable] ?? method;
+ const translatedNamespace =
+ translatedNamespaces[namespace as keyof typeof translatedNamespaces] ??
+ namespace;
+ return capitalize(`${readableMethod} ${translatedNamespace}`);
+ });
+
+ return uniq(normalizedScopes);
+ }
+}
diff --git a/app/scenes/Login/components/BackButton.tsx b/app/scenes/Login/components/BackButton.tsx
index 28ce8aa6b2..692d9fab64 100644
--- a/app/scenes/Login/components/BackButton.tsx
+++ b/app/scenes/Login/components/BackButton.tsx
@@ -1,5 +1,4 @@
import { BackIcon } from "outline-icons";
-import * as React from "react";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
import { parseDomain } from "@shared/utils/domains";
@@ -10,12 +9,21 @@ import isCloudHosted from "~/utils/isCloudHosted";
type Props = {
config?: Config;
+ onBack?: () => void;
};
-export default function BackButton({ config }: Props) {
+export function BackButton({ onBack, config }: Props) {
const { t } = useTranslation();
const isSubdomain = !!config?.hostname;
+ if (onBack) {
+ return (
+
+ {t("Back")}
+
+ );
+ }
+
if (!isCloudHosted || parseDomain(window.location.origin).custom) {
return null;
}
diff --git a/app/scenes/Login/components/Background.tsx b/app/scenes/Login/components/Background.tsx
new file mode 100644
index 0000000000..532d6e9841
--- /dev/null
+++ b/app/scenes/Login/components/Background.tsx
@@ -0,0 +1,12 @@
+import styled from "styled-components";
+import { s } from "@shared/styles";
+import Fade from "~/components/Fade";
+import { draggableOnDesktop } from "~/styles";
+
+export const Background = styled(Fade)`
+ width: 100vw;
+ height: 100%;
+ background: ${s("background")};
+ display: flex;
+ ${draggableOnDesktop()}
+`;
diff --git a/app/scenes/Login/components/Centered.tsx b/app/scenes/Login/components/Centered.tsx
new file mode 100644
index 0000000000..4c84301af1
--- /dev/null
+++ b/app/scenes/Login/components/Centered.tsx
@@ -0,0 +1,15 @@
+import styled from "styled-components";
+import Flex from "@shared/components/Flex";
+
+export const Centered = styled(Flex).attrs({
+ align: "center",
+ justify: "center",
+ column: true,
+ auto: true,
+})`
+ user-select: none;
+ width: 90vw;
+ height: 100%;
+ max-width: 320px;
+ margin: 0 auto;
+`;
diff --git a/app/scenes/Login/components/ConnectHeader.tsx b/app/scenes/Login/components/ConnectHeader.tsx
new file mode 100644
index 0000000000..68c7846584
--- /dev/null
+++ b/app/scenes/Login/components/ConnectHeader.tsx
@@ -0,0 +1,39 @@
+import { MoreIcon } from "outline-icons";
+import Flex from "@shared/components/Flex";
+import Text from "@shared/components/Text";
+import type Team from "~/models/Team";
+import type OAuthClient from "~/models/oauth/OAuthClient";
+import { Avatar } from "~/components/Avatar";
+import { AvatarSize, AvatarVariant } from "~/components/Avatar/Avatar";
+
+type Props = {
+ team: Team;
+ oauthClient: OAuthClient;
+};
+
+export function ConnectHeader({ team, oauthClient }: Props) {
+ return (
+
+
+
+
+
+
+
+
+
+ );
+}
diff --git a/app/scenes/Login/components/LoginDialog.tsx b/app/scenes/Login/components/LoginDialog.tsx
index c8a5b0a7f9..f6eeba0fdb 100644
--- a/app/scenes/Login/components/LoginDialog.tsx
+++ b/app/scenes/Login/components/LoginDialog.tsx
@@ -1,4 +1,3 @@
-import * as React from "react";
import { useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
@@ -39,7 +38,10 @@ export function LoginDialog() {
maxLength={255}
autoComplete="off"
placeholder={t("subdomain")}
- {...register("subdomain", { required: true, pattern: /^[a-z\d-]+$/ })}
+ {...register("subdomain", {
+ required: true,
+ pattern: /^[a-z\d-]{1,63}$/,
+ })}
>
.getoutline.com
diff --git a/app/scenes/Login/components/Notices.tsx b/app/scenes/Login/components/Notices.tsx
index 0a752b3f37..1ca9a5a1b9 100644
--- a/app/scenes/Login/components/Notices.tsx
+++ b/app/scenes/Login/components/Notices.tsx
@@ -1,6 +1,5 @@
/* eslint-disable react/no-unescaped-entities */
import { WarningIcon } from "outline-icons";
-import * as React from "react";
import { Trans } from "react-i18next";
import Notice from "~/components/Notice";
import useQuery from "~/hooks/useQuery";
@@ -123,7 +122,7 @@ function Message({ notice }: { notice: string }) {
}
}
-export default function Notices() {
+export function Notices() {
const query = useQuery();
const notice = query.get("notice");
diff --git a/app/scenes/Login/components/TeamSwitcher.tsx b/app/scenes/Login/components/TeamSwitcher.tsx
new file mode 100644
index 0000000000..842621bb86
--- /dev/null
+++ b/app/scenes/Login/components/TeamSwitcher.tsx
@@ -0,0 +1,109 @@
+import { ArrowIcon } from "outline-icons";
+import { useState } from "react";
+import { useTranslation } from "react-i18next";
+import styled from "styled-components";
+import Text from "@shared/components/Text";
+import { s } from "@shared/styles";
+import { AvatarSize } from "~/components/Avatar";
+import Avatar, { AvatarVariant } from "~/components/Avatar/Avatar";
+import ChangeLanguage from "~/components/ChangeLanguage";
+import Heading from "~/components/Heading";
+import OutlineIcon from "~/components/Icons/OutlineIcon";
+import env from "~/env";
+import type { Sessions } from "~/hooks/useLoggedInSessions";
+import { detectLanguage } from "~/utils/language";
+import Login from "../Login";
+import { Background } from "./Background";
+import { Centered } from "./Centered";
+
+type Props = { sessions: Sessions };
+
+export function TeamSwitcher({ sessions }: Props) {
+ const { t } = useTranslation();
+ const [showLogin, setShowLogin] = useState(false);
+ const url = new URL(window.location.href);
+ const appName = env.APP_NAME;
+
+ if (showLogin) {
+ return setShowLogin(false)} />;
+ }
+
+ return (
+
+
+
+
+
+ {t("Choose a workspace")}
+
+ {t(
+ "Choose an {{ appName }} workspace or login to continue connecting this app",
+ { appName }
+ )}
+ .
+
+ {Object.keys(sessions)?.map((teamId) => {
+ const session = sessions[teamId];
+ const location = session.url + url.pathname + url.search;
+ return (
+
+
+ {session.name}
+
+
+ );
+ })}
+ setShowLogin(true)}>
+
+ {t("Login to workspace")}
+
+
+
+ );
+}
+
+const StyledArrowIcon = styled(ArrowIcon)`
+ position: absolute;
+ transition: all 0.2s ease-in-out;
+ opacity: 0;
+ right: 12px;
+`;
+
+const TeamLink = styled.a`
+ position: relative;
+ left: -8px;
+ right: -8px;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 8px;
+ margin: 4px;
+ border-radius: 8px;
+ width: 100%;
+ color: ${s("text")};
+ font-weight: ${s("fontWeightMedium")};
+
+ &:hover {
+ background: ${s("listItemHoverBackground")};
+
+ ${StyledArrowIcon} {
+ opacity: 1;
+ right: 8px;
+ }
+ }
+`;
+
+const StyledHeading = styled(Heading).attrs({
+ as: "h2",
+ centered: true,
+})`
+ margin-top: 0;
+`;
diff --git a/app/scenes/Login/index.ts b/app/scenes/Login/index.ts
new file mode 100644
index 0000000000..04230a1bd9
--- /dev/null
+++ b/app/scenes/Login/index.ts
@@ -0,0 +1,3 @@
+import Login from "./Login";
+
+export default Login;
diff --git a/app/scenes/Login/urls.ts b/app/scenes/Login/urls.ts
index fe5612453e..81a3fd92e1 100644
--- a/app/scenes/Login/urls.ts
+++ b/app/scenes/Login/urls.ts
@@ -3,6 +3,15 @@ import { parseDomain } from "@shared/utils/domains";
import env from "~/env";
import Desktop from "~/utils/Desktop";
+function validateAndEncodeSubdomain(subdomain: string): string {
+ const encodedSubdomain = encodeURIComponent(subdomain);
+ const urlPattern = /^[a-z\d-]{1,63}$/;
+ if (!urlPattern.test(encodedSubdomain)) {
+ throw new Error("Invalid subdomain");
+ }
+ return `https://${encodedSubdomain}.getoutline.com`;
+}
+
/**
* If we're on a custom domain or a subdomain then the auth must point to the
* apex (env.URL) for authentication so that the state cookie can be set and read.
@@ -36,7 +45,7 @@ export async function navigateToSubdomain(subdomain: string) {
.toLowerCase()
.trim()
.replace(/^https?:\/\//, "");
- const host = `https://${normalizedSubdomain}.getoutline.com`;
+ const host = validateAndEncodeSubdomain(normalizedSubdomain);
await Desktop.bridge?.addCustomHost(host);
window.location.href = host;
}
diff --git a/app/scenes/Logout.tsx b/app/scenes/Logout.tsx
index 343af572aa..957d589e09 100644
--- a/app/scenes/Logout.tsx
+++ b/app/scenes/Logout.tsx
@@ -1,4 +1,3 @@
-import * as React from "react";
import { Redirect } from "react-router-dom";
import env from "~/env";
import useStores from "~/hooks/useStores";
diff --git a/app/scenes/Search/components/CollectionFilter.tsx b/app/scenes/Search/components/CollectionFilter.tsx
index 683cb3ee16..18768b7bfc 100644
--- a/app/scenes/Search/components/CollectionFilter.tsx
+++ b/app/scenes/Search/components/CollectionFilter.tsx
@@ -1,6 +1,6 @@
import { observer } from "mobx-react";
import { CollectionIcon as SVGCollectionIcon } from "outline-icons";
-import * as React from "react";
+import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import FilterOptions from "~/components/FilterOptions";
import CollectionIcon from "~/components/Icons/CollectionIcon";
@@ -17,7 +17,7 @@ function CollectionFilter(props: Props) {
const { t } = useTranslation();
const { collections } = useStores();
const { onSelect, collectionId } = props;
- const options = React.useMemo(() => {
+ const options = useMemo(() => {
const collectionOptions = collections.orderedData.map((collection) => ({
key: collection.id,
label: collection.name,
diff --git a/app/scenes/Search/components/DateFilter.tsx b/app/scenes/Search/components/DateFilter.tsx
index 160d0c2a89..ab8eb56251 100644
--- a/app/scenes/Search/components/DateFilter.tsx
+++ b/app/scenes/Search/components/DateFilter.tsx
@@ -1,4 +1,4 @@
-import * as React from "react";
+import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import { DateFilter as TDateFilter } from "@shared/types";
import FilterOptions from "~/components/FilterOptions";
@@ -12,7 +12,7 @@ type Props = {
const DateFilter = ({ dateFilter, onSelect }: Props) => {
const { t } = useTranslation();
- const options = React.useMemo(
+ const options = useMemo(
() => [
{
key: "",
diff --git a/app/scenes/Search/components/DocumentTypeFilter.tsx b/app/scenes/Search/components/DocumentTypeFilter.tsx
index 318d9051f3..5ec6155a7f 100644
--- a/app/scenes/Search/components/DocumentTypeFilter.tsx
+++ b/app/scenes/Search/components/DocumentTypeFilter.tsx
@@ -1,4 +1,4 @@
-import * as React from "react";
+import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import { StatusFilter as TStatusFilter } from "@shared/types";
import FilterOptions from "~/components/FilterOptions";
@@ -12,7 +12,7 @@ type Props = {
const DocumentTypeFilter = ({ statusFilter, onSelect }: Props) => {
const { t } = useTranslation();
- const options = React.useMemo(
+ const options = useMemo(
() => [
{
key: TStatusFilter.Published,
diff --git a/app/scenes/Search/components/RecentSearchListItem.tsx b/app/scenes/Search/components/RecentSearchListItem.tsx
index 24526f6227..1698db0faf 100644
--- a/app/scenes/Search/components/RecentSearchListItem.tsx
+++ b/app/scenes/Search/components/RecentSearchListItem.tsx
@@ -3,7 +3,7 @@ import {
useRovingTabIndex,
} from "@getoutline/react-roving-tabindex";
import { CloseIcon } from "outline-icons";
-import * as React from "react";
+import { useRef } from "react";
import { useTranslation } from "react-i18next";
import { Link } from "react-router-dom";
import styled from "styled-components";
@@ -20,7 +20,7 @@ type Props = {
function RecentSearchListItem({ searchQuery }: Props) {
const { t } = useTranslation();
- const ref = React.useRef(null);
+ const ref = useRef(null);
const { focused, ...rovingTabIndex } = useRovingTabIndex(ref, false);
useFocusEffect(focused, ref);
diff --git a/app/scenes/Search/components/UserFilter.tsx b/app/scenes/Search/components/UserFilter.tsx
index 8bec0eef0c..e0df2d910a 100644
--- a/app/scenes/Search/components/UserFilter.tsx
+++ b/app/scenes/Search/components/UserFilter.tsx
@@ -1,6 +1,6 @@
import { observer } from "mobx-react";
import { UserIcon } from "outline-icons";
-import * as React from "react";
+import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
import { Avatar, AvatarSize } from "~/components/Avatar";
@@ -21,7 +21,7 @@ function UserFilter(props: Props) {
const { t } = useTranslation();
const { users } = useStores();
- const options = React.useMemo(() => {
+ const options = useMemo(() => {
const userOptions = users.all.map((user) => ({
key: user.id,
label: user.name,
diff --git a/app/scenes/Settings/APIAndApps.tsx b/app/scenes/Settings/APIAndApps.tsx
new file mode 100644
index 0000000000..556d5eb219
--- /dev/null
+++ b/app/scenes/Settings/APIAndApps.tsx
@@ -0,0 +1,104 @@
+import { observer } from "mobx-react";
+import { PadlockIcon } from "outline-icons";
+import { useTranslation, Trans } from "react-i18next";
+import ApiKey from "~/models/ApiKey";
+import OAuthAuthentication from "~/models/oauth/OAuthAuthentication";
+import { Action } from "~/components/Actions";
+import Button from "~/components/Button";
+import Heading from "~/components/Heading";
+import PaginatedList from "~/components/PaginatedList";
+import Scene from "~/components/Scene";
+import Text from "~/components/Text";
+import { createApiKey } from "~/actions/definitions/apiKeys";
+import env from "~/env";
+import useActionContext from "~/hooks/useActionContext";
+import useCurrentTeam from "~/hooks/useCurrentTeam";
+import useCurrentUser from "~/hooks/useCurrentUser";
+import usePolicy from "~/hooks/usePolicy";
+import useStores from "~/hooks/useStores";
+import ApiKeyListItem from "./components/ApiKeyListItem";
+import OAuthAuthenticationListItem from "./components/OAuthAuthenticationListItem";
+
+function APIAndApps() {
+ const team = useCurrentTeam();
+ const user = useCurrentUser();
+ const { t } = useTranslation();
+ const { apiKeys, oauthAuthentications } = useStores();
+ const can = usePolicy(team);
+ const context = useActionContext();
+ const appName = env.APP_NAME;
+
+ return (
+ }
+ actions={
+ <>
+ {can.createApiKey && (
+
+
+
+ )}
+ >
+ }
+ >
+ {t("API & Apps")}
+ {t("API keys")}
+ {can.createApiKey ? (
+
+
+ ),
+ }}
+ />
+
+ ) : (
+ API keys have been disabled by an admin for your account
+ )}
+
+ fetch={apiKeys.fetchPage}
+ items={apiKeys.personalApiKeys}
+ options={{ userId: user.id }}
+ renderItem={(apiKey) => (
+
+ )}
+ />
+
+ {t("Application access")}
+
+ {t(
+ "Manage which third-party and internal applications have been granted access to your {{ appName }} account.",
+ { appName }
+ )}
+
+ >
+ }
+ renderItem={(oauthAuthentication: OAuthAuthentication) => (
+
+ )}
+ />
+
+ );
+}
+
+export default observer(APIAndApps);
diff --git a/app/scenes/Settings/ApiKeys.tsx b/app/scenes/Settings/ApiKeys.tsx
index ca411e3935..145a2246c6 100644
--- a/app/scenes/Settings/ApiKeys.tsx
+++ b/app/scenes/Settings/ApiKeys.tsx
@@ -1,6 +1,5 @@
import { observer } from "mobx-react";
import { CodeIcon } from "outline-icons";
-import * as React from "react";
import { useTranslation, Trans } from "react-i18next";
import ApiKey from "~/models/ApiKey";
import { Action } from "~/components/Actions";
@@ -58,11 +57,10 @@ function ApiKeys() {
}}
/>
-
fetch={apiKeys.fetchPage}
items={apiKeys.orderedData}
- heading={{t("All")} }
- renderItem={(apiKey: ApiKey) => (
+ renderItem={(apiKey) => (
)}
/>
diff --git a/app/scenes/Settings/Application.tsx b/app/scenes/Settings/Application.tsx
new file mode 100644
index 0000000000..b358af75b1
--- /dev/null
+++ b/app/scenes/Settings/Application.tsx
@@ -0,0 +1,325 @@
+import { observer } from "mobx-react";
+import { CopyIcon, InternetIcon, ReplaceIcon } from "outline-icons";
+import { useEffect, useCallback } from "react";
+import { Controller, useForm } from "react-hook-form";
+import { useTranslation } from "react-i18next";
+import { useParams } from "react-router-dom";
+import { toast } from "sonner";
+import { OAuthClientValidation } from "@shared/validations";
+import OAuthClient from "~/models/oauth/OAuthClient";
+import Breadcrumb from "~/components/Breadcrumb";
+import Button from "~/components/Button";
+import ConfirmationDialog from "~/components/ConfirmationDialog";
+import ContentEditable from "~/components/ContentEditable";
+import Heading from "~/components/Heading";
+import Input from "~/components/Input";
+import LoadingIndicator from "~/components/LoadingIndicator";
+import NudeButton from "~/components/NudeButton";
+import { FormData } from "~/components/OAuthClient/OAuthClientForm";
+import Scene from "~/components/Scene";
+import Switch from "~/components/Switch";
+import Tooltip from "~/components/Tooltip";
+import useRequest from "~/hooks/useRequest";
+import useStores from "~/hooks/useStores";
+import OAuthClientMenu from "~/menus/OAuthClientMenu";
+import isCloudHosted from "~/utils/isCloudHosted";
+import { settingsPath } from "~/utils/routeHelpers";
+import { ActionRow } from "./components/ActionRow";
+import { CopyButton } from "./components/CopyButton";
+import ImageInput from "./components/ImageInput";
+import SettingRow from "./components/SettingRow";
+
+type Props = {
+ oauthClient: OAuthClient;
+};
+
+const LoadingState = observer(function LoadingState() {
+ const { id } = useParams<{ id: string }>();
+ const { oauthClients } = useStores();
+ const oauthClient = oauthClients.get(id);
+ const { request } = useRequest(() => oauthClients.fetch(id));
+
+ useEffect(() => {
+ if (!oauthClient) {
+ void request();
+ }
+ }, [oauthClient]);
+
+ if (!oauthClient) {
+ return ;
+ }
+
+ return ;
+});
+
+const Application = observer(function Application({ oauthClient }: Props) {
+ const { t } = useTranslation();
+ const { dialogs } = useStores();
+
+ const {
+ register,
+ handleSubmit: formHandleSubmit,
+ formState,
+ getValues,
+ setError,
+ control,
+ } = useForm({
+ mode: "all",
+ defaultValues: {
+ name: oauthClient.name ?? "",
+ developerName: oauthClient.developerName ?? "",
+ developerUrl: oauthClient.developerUrl ?? "",
+ description: oauthClient.description ?? "",
+ avatarUrl: oauthClient.avatarUrl ?? "",
+ redirectUris: oauthClient.redirectUris ?? [],
+ published: oauthClient.published ?? false,
+ },
+ });
+
+ const handleSubmit = useCallback(
+ async (data: FormData) => {
+ try {
+ await oauthClient.save(data);
+ toast.success(
+ oauthClient.published
+ ? t("Application published")
+ : t("Application updated")
+ );
+ } catch (error) {
+ toast.error(error.message);
+ }
+ },
+ [oauthClient, t]
+ );
+
+ const handleRotateSecret = useCallback(async () => {
+ const onDelete = async () => {
+ try {
+ await oauthClient.rotateClientSecret();
+ toast.success(t("Client secret rotated"));
+ } catch (err) {
+ toast.error(err.message);
+ }
+ };
+
+ dialogs.openModal({
+ title: t("Rotate secret"),
+ content: (
+
+ {t(
+ "Rotating the client secret will invalidate the current secret. Make sure to update any applications using these credentials."
+ )}
+
+ ),
+ });
+ }, [t, dialogs, oauthClient]);
+
+ return (
+ ,
+ },
+ ]}
+ />
+ }
+ actions={ }
+ >
+
+
+ );
+});
+
+export default LoadingState;
diff --git a/app/scenes/Settings/PersonalApiKeys.tsx b/app/scenes/Settings/Applications.tsx
similarity index 52%
rename from app/scenes/Settings/PersonalApiKeys.tsx
rename to app/scenes/Settings/Applications.tsx
index b0bfaf6c62..2553464ad6 100644
--- a/app/scenes/Settings/PersonalApiKeys.tsx
+++ b/app/scenes/Settings/Applications.tsx
@@ -1,42 +1,39 @@
import { observer } from "mobx-react";
-import { CodeIcon } from "outline-icons";
-import * as React from "react";
+import { InternetIcon } from "outline-icons";
import { useTranslation, Trans } from "react-i18next";
-import ApiKey from "~/models/ApiKey";
+import OAuthClient from "~/models/oauth/OAuthClient";
import { Action } from "~/components/Actions";
import Button from "~/components/Button";
import Heading from "~/components/Heading";
import PaginatedList from "~/components/PaginatedList";
import Scene from "~/components/Scene";
import Text from "~/components/Text";
-import { createApiKey } from "~/actions/definitions/apiKeys";
+import { createOAuthClient } from "~/actions/definitions/oauthClients";
import useActionContext from "~/hooks/useActionContext";
import useCurrentTeam from "~/hooks/useCurrentTeam";
-import useCurrentUser from "~/hooks/useCurrentUser";
import usePolicy from "~/hooks/usePolicy";
import useStores from "~/hooks/useStores";
-import ApiKeyListItem from "./components/ApiKeyListItem";
+import OAuthClientListItem from "./components/OAuthClientListItem";
-function PersonalApiKeys() {
+function Applications() {
const team = useCurrentTeam();
- const user = useCurrentUser();
const { t } = useTranslation();
- const { apiKeys } = useStores();
+ const { oauthClients } = useStores();
const can = usePolicy(team);
const context = useActionContext();
return (
}
+ title={t("Applications")}
+ icon={ }
actions={
<>
- {can.createApiKey && (
+ {can.createOAuthClient && (
@@ -44,12 +41,10 @@ function PersonalApiKeys() {
>
}
>
- {t("API")}
+ {t("Applications")}
- {t("Personal keys")}}
- renderItem={(apiKey: ApiKey) => (
-
+
+ fetch={oauthClients.fetchPage}
+ items={oauthClients.orderedData}
+ renderItem={(oauthClient) => (
+
)}
/>
);
}
-export default observer(PersonalApiKeys);
+export default observer(Applications);
diff --git a/app/scenes/Settings/Details.tsx b/app/scenes/Settings/Details.tsx
index 1d9bb69f40..ba3b4449a0 100644
--- a/app/scenes/Settings/Details.tsx
+++ b/app/scenes/Settings/Details.tsx
@@ -108,7 +108,16 @@ function Details() {
toast.error(err.message);
}
},
- [team, name, subdomain, defaultCollectionId, publicBranding, customTheme, t]
+ [
+ tocPosition,
+ team,
+ name,
+ subdomain,
+ defaultCollectionId,
+ publicBranding,
+ customTheme,
+ t,
+ ]
);
const handleNameChange = React.useCallback(
diff --git a/app/scenes/Settings/Export.tsx b/app/scenes/Settings/Export.tsx
index ad1652f971..4cf83553f6 100644
--- a/app/scenes/Settings/Export.tsx
+++ b/app/scenes/Settings/Export.tsx
@@ -48,7 +48,7 @@ function Export() {
{t("Export data")}…
-
items={fileOperations.exports}
fetch={fileOperations.fetchPage}
options={{
@@ -59,7 +59,7 @@ function Export() {
Recent exports
}
- renderItem={(item: FileOperation) => (
+ renderItem={(item) => (
)}
/>
diff --git a/app/scenes/Settings/Groups.tsx b/app/scenes/Settings/Groups.tsx
index 2f1384ffe5..d48138e955 100644
--- a/app/scenes/Settings/Groups.tsx
+++ b/app/scenes/Settings/Groups.tsx
@@ -2,7 +2,7 @@ import { ColumnSort } from "@tanstack/react-table";
import deburr from "lodash/deburr";
import { observer } from "mobx-react";
import { PlusIcon, GroupIcon } from "outline-icons";
-import * as React from "react";
+import { useState, useMemo, useCallback, useEffect } from "react";
import { useTranslation, Trans } from "react-i18next";
import { useHistory, useLocation } from "react-router-dom";
import { toast } from "sonner";
@@ -43,9 +43,9 @@ function Groups() {
const history = useHistory();
const location = useLocation();
const params = useQuery();
- const [query, setQuery] = React.useState("");
+ const [query, setQuery] = useState("");
- const reqParams = React.useMemo(
+ const reqParams = useMemo(
() => ({
query: params.get("query") || undefined,
sort: params.get("sort") || "name",
@@ -56,7 +56,7 @@ function Groups() {
[params]
);
- const sort: ColumnSort = React.useMemo(
+ const sort: ColumnSort = useMemo(
() => ({
id: reqParams.sort,
desc: reqParams.direction === "DESC",
@@ -73,7 +73,7 @@ function Groups() {
const isEmpty = !loading && !groups.orderedData.length;
- const updateQuery = React.useCallback(
+ const updateQuery = useCallback(
(value: string) => {
if (value) {
params.set("query", value);
@@ -89,25 +89,25 @@ function Groups() {
[params, history, location.pathname]
);
- const handleSearch = React.useCallback((event) => {
+ const handleSearch = useCallback((event) => {
const { value } = event.target;
setQuery(value);
}, []);
- const handleNewGroup = React.useCallback(() => {
+ const handleNewGroup = useCallback(() => {
dialogs.openModal({
title: t("Create a group"),
content: ,
});
}, [t, dialogs]);
- React.useEffect(() => {
+ useEffect(() => {
if (error) {
toast.error(t("Could not load groups"));
}
}, [t, error]);
- React.useEffect(() => {
+ useEffect(() => {
const timeout = setTimeout(() => updateQuery(query), 250);
return () => clearTimeout(timeout);
}, [query, updateQuery]);
diff --git a/app/scenes/Settings/Import.tsx b/app/scenes/Settings/Import.tsx
index ae85e37279..838644b96f 100644
--- a/app/scenes/Settings/Import.tsx
+++ b/app/scenes/Settings/Import.tsx
@@ -1,10 +1,13 @@
+import orderBy from "lodash/orderBy";
import { observer } from "mobx-react";
import { NewDocumentIcon } from "outline-icons";
import * as React from "react";
import { useTranslation, Trans } from "react-i18next";
+import { Pagination } from "@shared/constants";
import { FileOperationType } from "@shared/types";
import { cdnPath } from "@shared/utils/urls";
import FileOperation from "~/models/FileOperation";
+import ImportModel from "~/models/Import";
import Button from "~/components/Button";
import Heading from "~/components/Heading";
import MarkdownIcon from "~/components/Icons/MarkdownIcon";
@@ -15,16 +18,146 @@ import Scene from "~/components/Scene";
import Text from "~/components/Text";
import env from "~/env";
import useStores from "~/hooks/useStores";
+import { Hook, PluginManager } from "~/utils/PluginManager";
import FileOperationListItem from "./components/FileOperationListItem";
import ImportJSONDialog from "./components/ImportJSONDialog";
+import { ImportListItem } from "./components/ImportListItem";
import ImportMarkdownDialog from "./components/ImportMarkdownDialog";
-import ImportNotionDialog from "./components/ImportNotionDialog";
+
+type Config = {
+ /** The title of the import. */
+ title: string;
+ /** The auxiliary descriptive text of the import. */
+ subtitle: string;
+ /** An icon to denote the kind of import. */
+ icon: React.ReactElement;
+ /** Trigger for the import. */
+ action: React.ReactElement;
+};
+
+function useImportsConfig() {
+ const { t } = useTranslation();
+ const { dialogs } = useStores();
+ const appName = env.APP_NAME;
+
+ return React.useMemo(() => {
+ const items: Config[] = [
+ {
+ title: t("Markdown"),
+ subtitle: t(
+ "Import a zip file of Markdown documents (exported from version 0.67.0 or earlier)"
+ ),
+ icon: ,
+ action: (
+ {
+ dialogs.openModal({
+ title: t("Import data"),
+ content: ,
+ });
+ }}
+ neutral
+ >
+ {t("Import")}…
+
+ ),
+ },
+ {
+ title: "JSON",
+ subtitle: t(
+ "Import a JSON data file exported from another {{ appName }} instance",
+ {
+ appName,
+ }
+ ),
+ icon: ,
+ action: (
+ {
+ dialogs.openModal({
+ title: t("Import data"),
+ content: ,
+ });
+ }}
+ neutral
+ >
+ {t("Import")}…
+
+ ),
+ },
+ ];
+
+ PluginManager.getHooks(Hook.Imports).forEach((plugin) => {
+ items.push({ ...plugin.value });
+ });
+
+ items.push({
+ title: "Confluence",
+ subtitle: t("Import pages from a Confluence instance"),
+ icon: ,
+ action: (
+
+ {t("Enterprise")}
+
+ ),
+ });
+
+ return items;
+ }, [t, dialogs, appName]);
+}
function Import() {
const { t } = useTranslation();
- const { dialogs, fileOperations } = useStores();
+ const { fileOperations, imports } = useStores();
+ const configs = useImportsConfig();
const appName = env.APP_NAME;
+ const [, setForceRender] = React.useState(0);
+ const offset = React.useMemo(() => ({ imports: 0, fileOperations: 0 }), []);
+
+ const fetchImports = React.useCallback(async () => {
+ const [importsArr, fileOpsArr] = await Promise.all([
+ imports.fetchPage({
+ offset: offset.imports,
+ limit: Pagination.defaultLimit,
+ }),
+ fileOperations.fetchPage({
+ type: FileOperationType.Import,
+ offset: offset.fileOperations,
+ limit: Pagination.defaultLimit,
+ }),
+ ]);
+
+ const pageImports = orderBy(
+ [...importsArr, ...fileOpsArr],
+ "createdAt",
+ "desc"
+ ).slice(0, Pagination.defaultLimit);
+
+ const apiImportsCount = pageImports.filter(
+ (item) => item instanceof ImportModel
+ ).length;
+
+ offset.imports += apiImportsCount;
+ offset.fileOperations += pageImports.length - apiImportsCount;
+
+ // needed to re-render after mobx store and offset is updated
+ setForceRender((s) => ++s);
+
+ return pageImports;
+ }, [imports, fileOperations, offset]);
+
+ const allImports = orderBy(
+ [
+ ...imports.orderedData,
+ ...fileOperations.filter({ type: FileOperationType.Import }),
+ ],
+ "createdAt",
+ "desc"
+ ).slice(0, offset.imports + offset.fileOperations);
+
return (
}>
{t("Import")}
@@ -38,100 +171,33 @@ function Import() {
- }
- title={t("Markdown")}
- subtitle={t(
- "Import a zip file of Markdown documents (exported from version 0.67.0 or earlier)"
- )}
- actions={
- {
- dialogs.openModal({
- title: t("Import data"),
- content: ,
- });
- }}
- neutral
- >
- {t("Import")}…
-
- }
- />
- }
- title="JSON"
- subtitle={t(
- "Import a JSON data file exported from another {{ appName }} instance",
- {
- appName,
- }
- )}
- actions={
- {
- dialogs.openModal({
- title: t("Import data"),
- content: ,
- });
- }}
- neutral
- >
- {t("Import")}…
-
- }
- />
- }
- title="Notion"
- subtitle={t("Import pages exported from Notion")}
- actions={
- {
- dialogs.openModal({
- title: t("Import data"),
- content: ,
- });
- }}
- neutral
- >
- {t("Import")}…
-
- }
- />
- }
- title="Confluence"
- subtitle={t("Import pages from a Confluence instance")}
- actions={
-
- {t("Enterprise")}
-
- }
- />
+ {configs.map((config) => (
+
+ ))}
-
+ items={allImports}
+ fetch={fetchImports}
heading={
Recent imports
}
- renderItem={(item: FileOperation) => (
-
- )}
+ renderItem={(item) =>
+ item instanceof ImportModel ? (
+
+ ) : (
+
+ )
+ }
/>
);
diff --git a/app/scenes/Settings/Integrations.tsx b/app/scenes/Settings/Integrations.tsx
new file mode 100644
index 0000000000..8c9fd508d7
--- /dev/null
+++ b/app/scenes/Settings/Integrations.tsx
@@ -0,0 +1,72 @@
+import groupBy from "lodash/groupBy";
+import * as React from "react";
+import { Trans, useTranslation } from "react-i18next";
+import styled from "styled-components";
+import Flex from "@shared/components/Flex";
+import Heading from "~/components/Heading";
+import InputSearch from "~/components/InputSearch";
+import Scene from "~/components/Scene";
+import Text from "~/components/Text";
+import useSettingsConfig from "~/hooks/useSettingsConfig";
+import useStores from "~/hooks/useStores";
+import { settingsPath } from "~/utils/routeHelpers";
+import IntegrationCard from "./components/IntegrationCard";
+import { StickyFilters } from "./components/StickyFilters";
+
+export function Integrations() {
+ const { t } = useTranslation();
+ const { integrations } = useStores();
+ const items = useSettingsConfig();
+ const [query, setQuery] = React.useState("");
+
+ const handleQuery = (event: React.ChangeEvent) => {
+ setQuery(event.target.value);
+ };
+
+ const groupedItems = groupBy(
+ items.filter(
+ (item) =>
+ item.group === "Integrations" &&
+ item.enabled &&
+ item.path !== settingsPath("integrations") &&
+ item.name.toLowerCase().includes(query.toLowerCase())
+ ),
+ (item) =>
+ item.pluginId && integrations.findByService(item.pluginId)
+ ? "connected"
+ : "available"
+ );
+
+ return (
+
+ {t("Integrations")}
+
+
+ Configure a variety of integrations with third-party services.
+
+
+
+
+
+
+
+ {groupedItems.connected?.map((item) => (
+
+ ))}
+ {groupedItems.available?.map((item) => (
+
+ ))}
+
+
+ );
+}
+
+const Cards = styled(Flex)`
+ margin-top: 20px;
+ width: "100%";
+`;
diff --git a/app/scenes/Settings/Members.tsx b/app/scenes/Settings/Members.tsx
index aebe49cb46..d2a947d2fe 100644
--- a/app/scenes/Settings/Members.tsx
+++ b/app/scenes/Settings/Members.tsx
@@ -1,7 +1,7 @@
import { ColumnSort } from "@tanstack/react-table";
import { observer } from "mobx-react";
import { PlusIcon, UserIcon } from "outline-icons";
-import * as React from "react";
+import { useState, useMemo, useCallback, useEffect } from "react";
import { Trans, useTranslation } from "react-i18next";
import { useHistory, useLocation } from "react-router-dom";
import { toast } from "sonner";
@@ -37,9 +37,9 @@ function Members() {
const { t } = useTranslation();
const params = useQuery();
const can = usePolicy(team);
- const [query, setQuery] = React.useState("");
+ const [query, setQuery] = useState("");
- const reqParams = React.useMemo(
+ const reqParams = useMemo(
() => ({
query: params.get("query") || undefined,
filter: params.get("filter") || "active",
@@ -52,7 +52,7 @@ function Members() {
[params]
);
- const sort: ColumnSort = React.useMemo(
+ const sort: ColumnSort = useMemo(
() => ({
id: reqParams.sort,
desc: reqParams.direction === "DESC",
@@ -72,7 +72,7 @@ function Members() {
reqParams,
});
- const updateParams = React.useCallback(
+ const updateParams = useCallback(
(name: string, value: string) => {
if (value) {
params.set(name, value);
@@ -88,28 +88,28 @@ function Members() {
[params, history, location.pathname]
);
- const handleStatusFilter = React.useCallback(
+ const handleStatusFilter = useCallback(
(status) => updateParams("filter", status),
[updateParams]
);
- const handleRoleFilter = React.useCallback(
+ const handleRoleFilter = useCallback(
(role) => updateParams("role", role),
[updateParams]
);
- const handleSearch = React.useCallback((event) => {
+ const handleSearch = useCallback((event) => {
const { value } = event.target;
setQuery(value);
}, []);
- React.useEffect(() => {
+ useEffect(() => {
if (error) {
toast.error(t("Could not load members"));
}
}, [t, error]);
- React.useEffect(() => {
+ useEffect(() => {
const timeout = setTimeout(() => updateParams("query", query), 250);
return () => clearTimeout(timeout);
}, [query, updateParams]);
@@ -194,7 +194,7 @@ function getFilteredUsers({
switch (filter) {
case "all":
- filteredUsers = users.orderedData;
+ filteredUsers = users.all;
break;
case "suspended":
filteredUsers = users.suspended;
diff --git a/app/scenes/Settings/Preferences.tsx b/app/scenes/Settings/Preferences.tsx
index 4acfb52c66..b6240c357c 100644
--- a/app/scenes/Settings/Preferences.tsx
+++ b/app/scenes/Settings/Preferences.tsx
@@ -3,12 +3,12 @@ import { SettingsIcon } from "outline-icons";
import * as React from "react";
import { Trans, useTranslation } from "react-i18next";
import { toast } from "sonner";
-import { languageOptions } from "@shared/i18n";
+import { languageOptions as availableLanguages } from "@shared/i18n";
import { TeamPreference, UserPreference } from "@shared/types";
import { Theme } from "~/stores/UiStore";
import Button from "~/components/Button";
import Heading from "~/components/Heading";
-import InputSelect from "~/components/InputSelect";
+import { InputSelectNew, Option } from "~/components/InputSelectNew";
import Scene from "~/components/Scene";
import Switch from "~/components/Switch";
import Text from "~/components/Text";
@@ -26,6 +26,29 @@ function Preferences() {
const team = useCurrentTeam();
const can = usePolicy(user.id);
+ const languageOptions: Option[] = React.useMemo(
+ () =>
+ availableLanguages.map(
+ (lang) =>
+ ({
+ type: "item",
+ label: lang.label,
+ value: lang.value,
+ } satisfies Option)
+ ),
+ []
+ );
+
+ const themeOptions: Option[] = React.useMemo(
+ () =>
+ [
+ { type: "item", label: t("Light"), value: Theme.Light },
+ { type: "item", label: t("Dark"), value: Theme.Dark },
+ { type: "item", label: t("System"), value: Theme.System },
+ ] satisfies Option[],
+ [t]
+ );
+
const handlePreferenceChange =
(inverted = false) =>
async (ev: React.ChangeEvent) => {
@@ -37,10 +60,21 @@ function Preferences() {
toast.success(t("Preferences saved"));
};
- const handleLanguageChange = async (language: string) => {
- await user.save({ language });
- toast.success(t("Preferences saved"));
- };
+ const handleLanguageChange = React.useCallback(
+ async (language: string) => {
+ await user.save({ language });
+ toast.success(t("Preferences saved"));
+ },
+ [t, user]
+ );
+
+ const handleThemeChange = React.useCallback(
+ (theme) => {
+ ui.setTheme(theme as Theme);
+ toast.success(t("Preferences saved"));
+ },
+ [t, ui]
+ );
const showDeleteAccount = () => {
dialogs.openModal({
@@ -77,12 +111,13 @@ function Preferences() {
>
}
>
-
- {
- ui.setTheme(theme as Theme);
- toast.success(t("Preferences saved"));
- }}
+ label={t("Appearance")}
+ hideLabel
/>
+ [
+ {
+ type: "item",
+ label: t("Editor"),
+ value: "member",
+ },
+ {
+ type: "item",
+ label: t("Viewer"),
+ value: "viewer",
+ },
+ ] satisfies Option[],
+ [t]
+ );
+
React.useEffect(() => {
if (!providers && !loading) {
void request();
@@ -229,21 +246,13 @@ function Security() {
)}
border={false}
>
-
diff --git a/app/scenes/Settings/SelfHosted.tsx b/app/scenes/Settings/SelfHosted.tsx
deleted file mode 100644
index bc836d218d..0000000000
--- a/app/scenes/Settings/SelfHosted.tsx
+++ /dev/null
@@ -1,140 +0,0 @@
-import find from "lodash/find";
-import { observer } from "mobx-react";
-import { BuildingBlocksIcon } from "outline-icons";
-import * as React from "react";
-import { useForm } from "react-hook-form";
-import { useTranslation } from "react-i18next";
-import { toast } from "sonner";
-import { IntegrationService, IntegrationType } from "@shared/types";
-import Integration from "~/models/Integration";
-import Button from "~/components/Button";
-import Heading from "~/components/Heading";
-import Input from "~/components/Input";
-import Scene from "~/components/Scene";
-import useStores from "~/hooks/useStores";
-import SettingRow from "./components/SettingRow";
-
-type FormData = {
- drawIoUrl: string;
- gristUrl: string;
-};
-
-function SelfHosted() {
- const { integrations } = useStores();
- const { t } = useTranslation();
-
- const integrationDiagrams = find(integrations.orderedData, {
- type: IntegrationType.Embed,
- service: IntegrationService.Diagrams,
- }) as Integration | undefined;
-
- const integrationGrist = find(integrations.orderedData, {
- type: IntegrationType.Embed,
- service: IntegrationService.Grist,
- }) as Integration | undefined;
-
- const {
- register,
- reset,
- handleSubmit: formHandleSubmit,
- formState,
- } = useForm({
- mode: "all",
- defaultValues: {
- drawIoUrl: integrationDiagrams?.settings.url,
- gristUrl: integrationGrist?.settings.url,
- },
- });
-
- React.useEffect(() => {
- void integrations.fetchPage({
- type: IntegrationType.Embed,
- });
- }, [integrations]);
-
- React.useEffect(() => {
- reset({
- drawIoUrl: integrationDiagrams?.settings.url,
- gristUrl: integrationGrist?.settings.url,
- });
- }, [integrationDiagrams, integrationGrist, reset]);
-
- const handleSubmit = React.useCallback(
- async (data: FormData) => {
- try {
- if (data.drawIoUrl) {
- await integrations.save({
- id: integrationDiagrams?.id,
- type: IntegrationType.Embed,
- service: IntegrationService.Diagrams,
- settings: {
- url: data.drawIoUrl,
- },
- });
- } else {
- await integrationDiagrams?.delete();
- }
-
- if (data.gristUrl) {
- await integrations.save({
- id: integrationGrist?.id,
- type: IntegrationType.Embed,
- service: IntegrationService.Grist,
- settings: {
- url: data.gristUrl,
- },
- });
- } else {
- await integrationGrist?.delete();
- }
-
- toast.success(t("Settings saved"));
- } catch (err) {
- toast.error(err.message);
- }
- },
- [integrations, integrationDiagrams, integrationGrist, t]
- );
-
- return (
- }>
- {t("Self Hosted")}
-
-
-
- );
-}
-
-export default observer(SelfHosted);
diff --git a/app/scenes/Settings/Shares.tsx b/app/scenes/Settings/Shares.tsx
index 1131c82633..481ff69e83 100644
--- a/app/scenes/Settings/Shares.tsx
+++ b/app/scenes/Settings/Shares.tsx
@@ -1,7 +1,7 @@
import { ColumnSort } from "@tanstack/react-table";
import { observer } from "mobx-react";
import { GlobeIcon, WarningIcon } from "outline-icons";
-import * as React from "react";
+import { useState, useMemo, useCallback, useEffect } from "react";
import { useTranslation, Trans } from "react-i18next";
import { Link, useHistory, useLocation } from "react-router-dom";
import { toast } from "sonner";
@@ -28,9 +28,9 @@ function Shares() {
const canShareDocuments = auth.team && auth.team.sharing;
const can = usePolicy(team);
const params = useQuery();
- const [query, setQuery] = React.useState("");
+ const [query, setQuery] = useState("");
- const reqParams = React.useMemo(
+ const reqParams = useMemo(
() => ({
query: params.get("query") || undefined,
sort: params.get("sort") || "createdAt",
@@ -41,7 +41,7 @@ function Shares() {
[params]
);
- const sort: ColumnSort = React.useMemo(
+ const sort: ColumnSort = useMemo(
() => ({
id: reqParams.sort,
desc: reqParams.direction === "DESC",
@@ -56,7 +56,7 @@ function Shares() {
reqParams,
});
- const updateParams = React.useCallback(
+ const updateParams = useCallback(
(name: string, value: string) => {
if (value) {
params.set(name, value);
@@ -72,18 +72,18 @@ function Shares() {
[params, history, location.pathname]
);
- const handleSearch = React.useCallback((event) => {
+ const handleSearch = useCallback((event) => {
const { value } = event.target;
setQuery(value);
}, []);
- React.useEffect(() => {
+ useEffect(() => {
if (error) {
toast.error(t("Could not load shares"));
}
}, [t, error]);
- React.useEffect(() => {
+ useEffect(() => {
const timeout = setTimeout(() => updateParams("query", query), 250);
return () => clearTimeout(timeout);
}, [query, updateParams]);
diff --git a/app/scenes/Settings/Templates.tsx b/app/scenes/Settings/Templates.tsx
index 5cdc7a661f..39e5944183 100644
--- a/app/scenes/Settings/Templates.tsx
+++ b/app/scenes/Settings/Templates.tsx
@@ -2,7 +2,7 @@ import { ColumnSort } from "@tanstack/react-table";
import deburr from "lodash/deburr";
import { observer } from "mobx-react";
import { PlusIcon, ShapesIcon } from "outline-icons";
-import * as React from "react";
+import { useEffect, useMemo, useCallback, useState } from "react";
import { useTranslation, Trans } from "react-i18next";
import { useHistory, useLocation } from "react-router-dom";
import { toast } from "sonner";
@@ -43,9 +43,9 @@ function Templates() {
const history = useHistory();
const location = useLocation();
const params = useQuery();
- const [query, setQuery] = React.useState("");
+ const [query, setQuery] = useState("");
- const reqParams = React.useMemo(
+ const reqParams = useMemo(
() => ({
query: params.get("query") || undefined,
sort: params.get("sort") || "title",
@@ -56,7 +56,7 @@ function Templates() {
[params]
);
- const sort: ColumnSort = React.useMemo(
+ const sort: ColumnSort = useMemo(
() => ({
id: reqParams.sort,
desc: reqParams.direction === "DESC",
@@ -73,7 +73,7 @@ function Templates() {
const isEmpty = !loading && !templates.orderedData.length;
- const updateQuery = React.useCallback(
+ const updateQuery = useCallback(
(value: string) => {
if (value) {
params.set("query", value);
@@ -89,12 +89,12 @@ function Templates() {
[params, history, location.pathname]
);
- const handleSearch = React.useCallback((event) => {
+ const handleSearch = useCallback((event) => {
const { value } = event.target;
setQuery(value);
}, []);
- const handleNewTemplate = React.useCallback(() => {
+ const handleNewTemplate = useCallback(() => {
dialogs.openModal({
title: t("Create a template"),
// content: ,
@@ -102,13 +102,13 @@ function Templates() {
});
}, [t, dialogs]);
- React.useEffect(() => {
+ useEffect(() => {
if (error) {
toast.error(t("Could not load templates"));
}
}, [t, error]);
- React.useEffect(() => {
+ useEffect(() => {
const timeout = setTimeout(() => updateQuery(query), 250);
return () => clearTimeout(timeout);
}, [query, updateQuery]);
diff --git a/app/scenes/Settings/components/ApiKeyListItem.tsx b/app/scenes/Settings/components/ApiKeyListItem.tsx
index 0eee5a9660..622748f043 100644
--- a/app/scenes/Settings/components/ApiKeyListItem.tsx
+++ b/app/scenes/Settings/components/ApiKeyListItem.tsx
@@ -1,6 +1,6 @@
import { observer } from "mobx-react";
import { CopyIcon } from "outline-icons";
-import * as React from "react";
+import { useState, useRef, useCallback } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import ApiKey from "~/models/ApiKey";
@@ -62,10 +62,10 @@ const ApiKeyListItem = ({ apiKey }: Props) => {
>
);
- const [copied, setCopied] = React.useState(false);
- const copyTimeoutIdRef = React.useRef>();
+ const [copied, setCopied] = useState(false);
+ const copyTimeoutIdRef = useRef>();
- const handleCopy = React.useCallback(() => {
+ const handleCopy = useCallback(() => {
if (copyTimeoutIdRef.current) {
clearTimeout(copyTimeoutIdRef.current);
}
diff --git a/app/scenes/Settings/components/ApiKeyRevokeDialog.tsx b/app/scenes/Settings/components/ApiKeyRevokeDialog.tsx
index b39f076618..c63a3a5a52 100644
--- a/app/scenes/Settings/components/ApiKeyRevokeDialog.tsx
+++ b/app/scenes/Settings/components/ApiKeyRevokeDialog.tsx
@@ -1,4 +1,3 @@
-import * as React from "react";
import { useTranslation } from "react-i18next";
import ApiKey from "~/models/ApiKey";
import ConfirmationDialog from "~/components/ConfirmationDialog";
diff --git a/app/scenes/Settings/components/CopyButton.tsx b/app/scenes/Settings/components/CopyButton.tsx
new file mode 100644
index 0000000000..7334d19471
--- /dev/null
+++ b/app/scenes/Settings/components/CopyButton.tsx
@@ -0,0 +1,50 @@
+import { LinkIcon } from "outline-icons";
+import * as React from "react";
+import { toast } from "sonner";
+import CopyToClipboard from "~/components/CopyToClipboard";
+import NudeButton from "~/components/NudeButton";
+import Tooltip from "~/components/Tooltip";
+
+type Props = {
+ /** The value to be copied */
+ value: string;
+ /** The message to show when the value is copied */
+ success: string;
+ /** The tooltip message */
+ tooltip: string;
+ /** An optional icon */
+ icon?: React.ReactNode;
+};
+
+/**
+ * A button that copies a value to the clipboard when clicked and shows a
+ * single icon.
+ */
+export function CopyButton({
+ value,
+ success,
+ tooltip,
+ icon = ,
+}: Props) {
+ const timeout = React.useRef>();
+
+ const handleCopied = React.useCallback(() => {
+ timeout.current = setTimeout(() => {
+ toast.message(success);
+ }, 100);
+
+ return () => {
+ if (timeout.current) {
+ clearTimeout(timeout.current);
+ }
+ };
+ }, [success]);
+
+ return (
+
+
+ {icon}
+
+
+ );
+}
diff --git a/app/scenes/Settings/components/DropToImport.tsx b/app/scenes/Settings/components/DropToImport.tsx
index 3219140ef0..a0a2f8e01c 100644
--- a/app/scenes/Settings/components/DropToImport.tsx
+++ b/app/scenes/Settings/components/DropToImport.tsx
@@ -1,6 +1,6 @@
import { observer } from "mobx-react";
import { NewDocumentIcon } from "outline-icons";
-import * as React from "react";
+import { useState, useCallback } from "react";
import Dropzone from "react-dropzone";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
@@ -28,10 +28,11 @@ type Props = {
function DropToImport({ disabled, onSubmit, children, format }: Props) {
const { t } = useTranslation();
const { collections } = useStores();
- const [file, setFile] = React.useState(null);
- const [isImporting, setImporting] = React.useState(false);
- const [permission, setPermission] =
- React.useState(CollectionPermission.ReadWrite);
+ const [file, setFile] = useState(null);
+ const [isImporting, setImporting] = useState(false);
+ const [permission, setPermission] = useState(
+ CollectionPermission.ReadWrite
+ );
const handleFiles = (files: File[]) => {
if (files.length > 1) {
@@ -66,7 +67,7 @@ function DropToImport({ disabled, onSubmit, children, format }: Props) {
}
};
- const handleRejection = React.useCallback(() => {
+ const handleRejection = useCallback(() => {
toast.error(t("File not supported – please upload a valid ZIP file"));
}, [t]);
diff --git a/app/scenes/Settings/components/FileOperationListItem.tsx b/app/scenes/Settings/components/FileOperationListItem.tsx
index 8e5e932276..19f6101f60 100644
--- a/app/scenes/Settings/components/FileOperationListItem.tsx
+++ b/app/scenes/Settings/components/FileOperationListItem.tsx
@@ -4,6 +4,7 @@ import * as React from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { useTheme } from "styled-components";
+import Spinner from "@shared/components/Spinner";
import {
FileOperationFormat,
FileOperationState,
@@ -13,7 +14,6 @@ import FileOperation from "~/models/FileOperation";
import { Action } from "~/components/Actions";
import ConfirmationDialog from "~/components/ConfirmationDialog";
import ListItem from "~/components/List/Item";
-import Spinner from "~/components/Spinner";
import Time from "~/components/Time";
import useCurrentUser from "~/hooks/useCurrentUser";
import useStores from "~/hooks/useStores";
diff --git a/app/scenes/Settings/components/GroupDialogs.tsx b/app/scenes/Settings/components/GroupDialogs.tsx
index 6941cf78e8..642d99e5fc 100644
--- a/app/scenes/Settings/components/GroupDialogs.tsx
+++ b/app/scenes/Settings/components/GroupDialogs.tsx
@@ -1,7 +1,7 @@
import debounce from "lodash/debounce";
import { observer } from "mobx-react";
import { PlusIcon } from "outline-icons";
-import React from "react";
+import * as React from "react";
import { Trans, useTranslation } from "react-i18next";
import { toast } from "sonner";
import { v4 as uuidv4 } from "uuid";
@@ -268,14 +268,14 @@ export const ViewGroupMembersDialog = observer(function ({
Members
-
items={users.inGroup(group.id)}
fetch={groupUsers.fetchPage}
options={{
id: group.id,
}}
empty={{t("This group has no members.")} }
- renderItem={(user: User) => (
+ renderItem={(user) => (
) : (
-
empty={
query ? (
{t("No people matching your search")}
@@ -392,7 +392,7 @@ const AddPeopleToGroupDialog = observer(function ({
}
items={users.notInGroup(group.id, query)}
fetch={query ? undefined : users.fetchPage}
- renderItem={(item: User) => (
+ renderItem={(item) => (
{
dialogs.openModal({
title: t("Group members"),
@@ -41,7 +41,7 @@ export function GroupsTable(props: Props) {
[t, dialogs]
);
- const columns = React.useMemo[]>(
+ const columns = useMemo[]>(
() =>
compact>([
{
diff --git a/app/scenes/Settings/components/ImageInput.tsx b/app/scenes/Settings/components/ImageInput.tsx
index 267c4b1e6f..c001559d4c 100644
--- a/app/scenes/Settings/components/ImageInput.tsx
+++ b/app/scenes/Settings/components/ImageInput.tsx
@@ -1,8 +1,9 @@
-import * as React from "react";
+import { EditIcon } from "outline-icons";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
import { s } from "@shared/styles";
import { Avatar, AvatarSize, IAvatar } from "~/components/Avatar";
+import { AvatarVariant } from "~/components/Avatar/Avatar";
import Button from "~/components/Button";
import Flex from "~/components/Flex";
import ImageUpload, { Props as ImageUploadProps } from "./ImageUpload";
@@ -17,10 +18,18 @@ export default function ImageInput({ model, onSuccess, ...rest }: Props) {
return (
-
-
+
+
- {t("Upload")}
+
@@ -38,10 +47,6 @@ const avatarStyles = `
height: ${AvatarSize.Upload}px;
`;
-const StyledAvatar = styled(Avatar)`
- border-radius: 8px;
-`;
-
const ImageBox = styled(Flex)`
${avatarStyles};
position: relative;
diff --git a/app/scenes/Settings/components/ImageUpload.tsx b/app/scenes/Settings/components/ImageUpload.tsx
index 89447a1a70..d5e1db53ea 100644
--- a/app/scenes/Settings/components/ImageUpload.tsx
+++ b/app/scenes/Settings/components/ImageUpload.tsx
@@ -1,19 +1,18 @@
import invariant from "invariant";
-import { observable } from "mobx";
import { observer } from "mobx-react";
import * as React from "react";
+import { useState, useRef } from "react";
import AvatarEditor from "react-avatar-editor";
-import Dropzone from "react-dropzone";
+import { useDropzone } from "react-dropzone";
+import { useTranslation } from "react-i18next";
import styled from "styled-components";
import { s } from "@shared/styles";
import { AttachmentPreset } from "@shared/types";
import { AttachmentValidation } from "@shared/validations";
-import RootStore from "~/stores/RootStore";
-import Button from "~/components/Button";
+import ButtonLarge from "~/components/ButtonLarge";
import Flex from "~/components/Flex";
import LoadingIndicator from "~/components/LoadingIndicator";
-import Modal from "~/components/Modal";
-import withStores from "~/components/withStores";
+import useStores from "~/hooks/useStores";
import { compressImage } from "~/utils/compressImage";
import { uploadFile, dataUrlToBlob } from "~/utils/files";
@@ -24,132 +23,167 @@ export type Props = {
borderRadius?: number;
};
-@observer
-class ImageUpload extends React.Component {
- @observable
- isUploading = false;
+const ImageUpload: React.FC = ({
+ onSuccess,
+ onError,
+ submitText,
+ borderRadius,
+ children,
+}) => {
+ const { dialogs } = useStores();
+ const { t } = useTranslation();
- @observable
- isCropping = false;
+ const [isUploading, setIsUploading] = useState(false);
+ const [isCropping, setIsCropping] = useState(false);
- @observable
- zoom = 1;
+ const uploadImage = React.useCallback(
+ async (blob: Blob, file: File) => {
+ try {
+ const compressed = await compressImage(blob, {
+ maxHeight: 512,
+ maxWidth: 512,
+ });
+ const attachment = await uploadFile(compressed, {
+ name: file.name,
+ preset: AttachmentPreset.Avatar,
+ });
+ void onSuccess(attachment.url);
+ } catch (err) {
+ onError(err.message);
+ } finally {
+ setIsUploading(false);
+ setIsCropping(false);
+ dialogs.closeAllModals();
+ }
+ },
+ [dialogs, onSuccess, onError]
+ );
- @observable
- file: File;
+ const handleUpload = React.useCallback(
+ (blob: Blob, file: File) => {
+ setIsUploading(true);
+ // allow the UI to update before converting the canvas to a Blob
+ // for large images this can cause the page rendering to hang.
+ setTimeout(() => uploadImage(blob, file), 0);
+ },
+ [uploadImage]
+ );
- avatarEditorRef = React.createRef();
+ const handleClose = React.useCallback(() => {
+ setIsUploading(false);
+ setIsCropping(false);
+ }, []);
- static defaultProps = {
- submitText: "Crop Image",
- borderRadius: 150,
- };
-
- onDropAccepted = async (files: File[]) => {
- this.isCropping = true;
- this.file = files[0];
- };
-
- handleCrop = () => {
- this.isUploading = true;
- // allow the UI to update before converting the canvas to a Blob
- // for large images this can cause the page rendering to hang.
- setTimeout(this.uploadImage, 0);
- };
-
- uploadImage = async () => {
- const canvas = this.avatarEditorRef.current?.getImage();
- invariant(canvas, "canvas is not defined");
- const imageBlob = dataUrlToBlob(canvas.toDataURL());
-
- try {
- const compressed = await compressImage(imageBlob, {
- maxHeight: 512,
- maxWidth: 512,
- });
- const attachment = await uploadFile(compressed, {
- name: this.file.name,
- preset: AttachmentPreset.Avatar,
- });
- void this.props.onSuccess(attachment.url);
- } catch (err) {
- this.props.onError(err.message);
- } finally {
- this.isUploading = false;
- this.isCropping = false;
- }
- };
-
- handleClose = () => {
- this.isUploading = false;
- this.isCropping = false;
- };
-
- handleZoom = (event: React.ChangeEvent) => {
- const target = event.target;
-
- if (target instanceof HTMLInputElement) {
- this.zoom = parseFloat(target.value);
- }
- };
-
- renderCropping() {
- const { ui, submitText } = this.props;
- return (
-
-
- {this.isUploading && }
-
-
-
- {
+ setIsCropping(true);
+ dialogs.openModal({
+ title: "",
+ content: (
+
-
- {this.isUploading ? "Uploading…" : submitText}
-
-
-
- );
+ ),
+ onClose: handleClose,
+ });
+ },
+ [
+ t,
+ dialogs,
+ handleUpload,
+ handleClose,
+ isUploading,
+ borderRadius,
+ submitText,
+ ]
+ );
+
+ const { getRootProps, getInputProps } = useDropzone({
+ accept: AttachmentValidation.avatarContentTypes.join(", "),
+ onDropAccepted,
+ });
+
+ if (isCropping) {
+ return null; // onDropAccepted would have opened a modal for cropping the image.
}
- render() {
- if (this.isCropping) {
- return this.renderCropping();
- }
+ return (
+
+
+ {children}
+
+ );
+};
+
+type AvatarEditorDialogProps = {
+ file: File;
+ onUpload: (blob: Blob, file: File) => void;
+ isUploading: boolean;
+ borderRadius: number;
+ submitText: string;
+};
+
+const AvatarEditorDialog: React.FC = observer(
+ ({ file, onUpload, isUploading, borderRadius, submitText }) => {
+ const { ui } = useStores();
+ const { t } = useTranslation();
+ const [zoom, setZoom] = useState(1);
+ const avatarEditorRef = useRef(null);
+
+ const handleUpload = React.useCallback(() => {
+ const canvas = avatarEditorRef.current?.getImage();
+ invariant(canvas, "canvas is not defined");
+ const blob = dataUrlToBlob(canvas.toDataURL());
+ onUpload(blob, file);
+ }, [file, onUpload]);
+
+ const handleZoom = React.useCallback(
+ (event: React.ChangeEvent) => {
+ const target = event.target;
+
+ if (target instanceof HTMLInputElement) {
+ setZoom(parseFloat(target.value));
+ }
+ },
+ []
+ );
return (
-
- {({ getRootProps, getInputProps }) => (
-
-
- {this.props.children}
-
- )}
-
+
+ {isUploading && }
+
+
+
+
+
+
+ {isUploading ? `${t(`Uploading`)}…` : submitText}
+
+
);
}
-}
+);
const AvatarEditorContainer = styled(Flex)`
margin-bottom: 30px;
@@ -180,8 +214,4 @@ const RangeInput = styled.input`
}
`;
-const CropButton = styled(Button)`
- width: 300px;
-`;
-
-export default withStores(ImageUpload);
+export default observer(ImageUpload);
diff --git a/app/scenes/Settings/components/ImportJSONDialog.tsx b/app/scenes/Settings/components/ImportJSONDialog.tsx
index 9a13c39852..1ccc4e98e9 100644
--- a/app/scenes/Settings/components/ImportJSONDialog.tsx
+++ b/app/scenes/Settings/components/ImportJSONDialog.tsx
@@ -1,4 +1,3 @@
-import * as React from "react";
import { Trans } from "react-i18next";
import { FileOperationFormat } from "@shared/types";
import env from "~/env";
diff --git a/app/scenes/Settings/components/ImportListItem.tsx b/app/scenes/Settings/components/ImportListItem.tsx
new file mode 100644
index 0000000000..f0c1ee5675
--- /dev/null
+++ b/app/scenes/Settings/components/ImportListItem.tsx
@@ -0,0 +1,159 @@
+import capitalize from "lodash/capitalize";
+import { observer } from "mobx-react";
+import { CrossIcon, DoneIcon, WarningIcon } from "outline-icons";
+import { useMemo, useCallback } from "react";
+import { useTranslation } from "react-i18next";
+import { toast } from "sonner";
+import { useTheme } from "styled-components";
+import Spinner from "@shared/components/Spinner";
+import { ImportState } from "@shared/types";
+import Import from "~/models/Import";
+import { Action } from "~/components/Actions";
+import ConfirmationDialog from "~/components/ConfirmationDialog";
+import ListItem from "~/components/List/Item";
+import Time from "~/components/Time";
+import useCurrentUser from "~/hooks/useCurrentUser";
+import useStores from "~/hooks/useStores";
+import { ImportMenu } from "~/menus/ImportMenu";
+import isCloudHosted from "~/utils/isCloudHosted";
+
+type Props = {
+ /** Import that's displayed as list item. */
+ importModel: Import;
+};
+
+export const ImportListItem = observer(({ importModel }: Props) => {
+ const { t } = useTranslation();
+ const { dialogs } = useStores();
+ const user = useCurrentUser();
+ const theme = useTheme();
+ const showProgress =
+ importModel.state !== ImportState.Canceled &&
+ importModel.state !== ImportState.Errored;
+ const showErrorInfo =
+ !isCloudHosted &&
+ importModel.state === ImportState.Errored &&
+ !!importModel.error;
+
+ const stateMap = useMemo(
+ () => ({
+ [ImportState.Created]: t("Processing"),
+ [ImportState.InProgress]: t("Processing"),
+ [ImportState.Processed]: t("Processing"),
+ [ImportState.Completed]: t("Completed"),
+ [ImportState.Errored]: t("Failed"),
+ [ImportState.Canceled]: t("Canceled"),
+ }),
+ [t]
+ );
+
+ const iconMap = useMemo(
+ () => ({
+ [ImportState.Created]: ,
+ [ImportState.InProgress]: ,
+ [ImportState.Processed]: ,
+ [ImportState.Completed]: ,
+ [ImportState.Errored]: ,
+ [ImportState.Canceled]: ,
+ }),
+ [theme]
+ );
+
+ const handleCancel = useCallback(async () => {
+ const onCancel = async () => {
+ try {
+ await importModel.cancel();
+ toast.success(t("Import canceled"));
+ } catch (err) {
+ toast.error(err.message);
+ }
+ };
+
+ dialogs.openModal({
+ title: t("Are you sure you want to cancel this import?"),
+ content: (
+
+ {t(
+ "Canceling this import will discard any progress made. This cannot be undone."
+ )}
+
+ ),
+ });
+ }, [t, dialogs, importModel]);
+
+ const handleDelete = useCallback(async () => {
+ const onDelete = async () => {
+ try {
+ await importModel.delete();
+ toast.success(t("Import deleted"));
+ } catch (err) {
+ toast.error(err.message);
+ }
+ };
+
+ dialogs.openModal({
+ title: t("Are you sure you want to delete this import?"),
+ content: (
+
+ {t(
+ "Deleting this import will also delete all collections and documents that were created from it. This cannot be undone."
+ )}
+
+ ),
+ });
+ }, [t, dialogs, importModel]);
+
+ return (
+
+ {stateMap[importModel.state]} •
+ {showErrorInfo && (
+ <>
+ {importModel.error}
+ {`. ${t("Check server logs for more details.")}`} •
+ >
+ )}
+ {t(`{{userName}} requested`, {
+ userName:
+ user.id === importModel.createdBy.id
+ ? t("You")
+ : importModel.createdBy.name,
+ })}
+
+
+ •
+ {capitalize(importModel.service)}
+ {showProgress && (
+ <>
+ •
+ {t("{{ count }} document imported", {
+ count: importModel.documentCount,
+ })}
+ >
+ )}
+ >
+ }
+ actions={
+
+
+
+ }
+ />
+ );
+});
diff --git a/app/scenes/Settings/components/ImportMarkdownDialog.tsx b/app/scenes/Settings/components/ImportMarkdownDialog.tsx
index c23190a8ca..526bdb192f 100644
--- a/app/scenes/Settings/components/ImportMarkdownDialog.tsx
+++ b/app/scenes/Settings/components/ImportMarkdownDialog.tsx
@@ -1,4 +1,3 @@
-import * as React from "react";
import { Trans } from "react-i18next";
import { FileOperationFormat } from "@shared/types";
import env from "~/env";
diff --git a/app/scenes/Settings/components/ImportNotionDialog.tsx b/app/scenes/Settings/components/ImportNotionDialog.tsx
deleted file mode 100644
index b0bc119f6c..0000000000
--- a/app/scenes/Settings/components/ImportNotionDialog.tsx
+++ /dev/null
@@ -1,36 +0,0 @@
-import * as React from "react";
-import { Trans, useTranslation } from "react-i18next";
-import { FileOperationFormat } from "@shared/types";
-import useStores from "~/hooks/useStores";
-import DropToImport from "./DropToImport";
-import HelpDisclosure from "./HelpDisclosure";
-
-function ImportNotionDialog() {
- const { t } = useTranslation();
- const { dialogs } = useStores();
-
- return (
- <>
- Where do I find the file?}>
- ,
- }}
- />
-
-
- <>
- {t(
- `Drag and drop the zip file from Notion's HTML export option, or click to upload`
- )}
- >
-
- >
- );
-}
-
-export default ImportNotionDialog;
diff --git a/app/scenes/Settings/components/IntegrationCard.tsx b/app/scenes/Settings/components/IntegrationCard.tsx
new file mode 100644
index 0000000000..bdb5125ead
--- /dev/null
+++ b/app/scenes/Settings/components/IntegrationCard.tsx
@@ -0,0 +1,92 @@
+import { useTranslation } from "react-i18next";
+import { Link } from "react-router-dom";
+import styled from "styled-components";
+import { s, ellipsis } from "@shared/styles";
+import { ConfigItem } from "~/hooks/useSettingsConfig";
+import Button from "../../../components/Button";
+import Flex from "../../../components/Flex";
+import Text from "../../../components/Text";
+
+type Props = {
+ integration: ConfigItem;
+ isConnected?: boolean;
+};
+
+function IntegrationCard({ integration, isConnected }: Props) {
+ const { t } = useTranslation();
+
+ return (
+
+
+
+
+ {integration.name}
+ {isConnected && {t("Connected")} }
+
+
+ {isConnected ? t("Configure") : t("Connect")}
+
+
+
+ {integration.description}
+
+ );
+}
+
+export default IntegrationCard;
+
+const Card = styled.div`
+ display: flex;
+ flex-direction: column;
+ flex-grow: 1;
+ padding: 20px;
+ width: 300px;
+ background: ${s("background")};
+ border: 1px solid ${s("inputBorder")};
+ color: ${s("text")};
+ border-radius: 8px;
+ transition: box-shadow 200ms ease;
+ cursor: var(--pointer);
+
+ &:hover {
+ box-shadow: rgba(0, 0, 0, 0.08) 0px 2px 4px, rgba(0, 0, 0, 0.06) 0px 4px 8px;
+ }
+`;
+
+const Name = styled(Text)`
+ margin: 0;
+ font-size: 16px;
+ font-weight: 600;
+ color: ${s("text")};
+ ${ellipsis()}
+`;
+
+const Description = styled(Text)`
+ margin: 8px 0 0;
+ font-size: 15px;
+ max-width: 100%;
+ color: ${s("textTertiary")};
+`;
+
+const Status = styled(Text).attrs({
+ type: "secondary",
+ size: "small",
+ as: "span",
+})`
+ display: inline-flex;
+ align-items: center;
+
+ &::after {
+ content: "";
+ display: inline-block;
+ width: 17px;
+ height: 17px;
+
+ background: radial-gradient(
+ circle at center,
+ ${s("accent")} 0 33%,
+ transparent 33%
+ );
+ border-radius: 50%;
+ }
+`;
diff --git a/app/scenes/Settings/components/IntegrationScene.tsx b/app/scenes/Settings/components/IntegrationScene.tsx
new file mode 100644
index 0000000000..c534114d2c
--- /dev/null
+++ b/app/scenes/Settings/components/IntegrationScene.tsx
@@ -0,0 +1,33 @@
+import { SettingsIcon } from "outline-icons";
+import * as React from "react";
+import { useTranslation } from "react-i18next";
+import Breadcrumb from "~/components/Breadcrumb";
+import Scene from "~/components/Scene";
+import { settingsPath } from "~/utils/routeHelpers";
+
+export function IntegrationScene({
+ children,
+ ...rest
+}: React.ComponentProps) {
+ const { t } = useTranslation();
+
+ return (
+ ,
+ to: settingsPath("integrations"),
+ },
+ ]}
+ />
+ }
+ {...rest}
+ >
+ {children}
+
+ );
+}
diff --git a/app/scenes/Settings/components/MembersTable.tsx b/app/scenes/Settings/components/MembersTable.tsx
index 962eb8ca68..9a301d1c05 100644
--- a/app/scenes/Settings/components/MembersTable.tsx
+++ b/app/scenes/Settings/components/MembersTable.tsx
@@ -1,7 +1,8 @@
import compact from "lodash/compact";
-import * as React from "react";
+import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
+import Text from "@shared/components/Text";
import User from "~/models/User";
import { Avatar, AvatarSize } from "~/components/Avatar";
import Badge from "~/components/Badge";
@@ -14,6 +15,7 @@ import {
import { type Column as TableColumn } from "~/components/Table";
import Time from "~/components/Time";
import useCurrentUser from "~/hooks/useCurrentUser";
+import useMobile from "~/hooks/useMobile";
import UserMenu from "~/menus/UserMenu";
import { FILTER_HEIGHT } from "./StickyFilters";
@@ -27,8 +29,9 @@ type Props = Omit, "columns" | "rowHeight"> & {
export function MembersTable({ canManage, ...rest }: Props) {
const { t } = useTranslation();
const currentUser = useCurrentUser();
+ const isMobile = useMobile();
- const columns = React.useMemo[]>(
+ const columns = useMemo[]>(
() =>
compact>([
{
@@ -38,13 +41,20 @@ export function MembersTable({ canManage, ...rest }: Props) {
accessor: (user) => user.name,
component: (user) => (
- {user.name}{" "}
- {currentUser.id === user.id && `(${t("You")})`}
+ {" "}
+
+
+ {user.name} {currentUser.id === user.id && `(${t("You")})`}
+
+ {isMobile && canManage && (
+ {user.email}
+ )}
+
),
width: "4fr",
},
- canManage
+ canManage && !isMobile
? {
type: "data",
id: "email",
@@ -54,17 +64,19 @@ export function MembersTable({ canManage, ...rest }: Props) {
width: "4fr",
}
: undefined,
- {
- type: "data",
- id: "lastActiveAt",
- header: t("Last active"),
- accessor: (user) => user.lastActiveAt,
- component: (user) =>
- user.lastActiveAt ? (
-
- ) : null,
- width: "2fr",
- },
+ isMobile
+ ? undefined
+ : {
+ type: "data",
+ id: "lastActiveAt",
+ header: t("Last active"),
+ accessor: (user) => user.lastActiveAt,
+ component: (user) =>
+ user.lastActiveAt ? (
+
+ ) : null,
+ width: "2fr",
+ },
{
type: "data",
id: "role",
@@ -85,7 +97,7 @@ export function MembersTable({ canManage, ...rest }: Props) {
{user.isSuspended && {t("Suspended")} }
),
- width: "2fr",
+ width: "80px",
},
canManage
? {
@@ -97,7 +109,7 @@ export function MembersTable({ canManage, ...rest }: Props) {
}
: undefined,
]),
- [t, currentUser, canManage]
+ [t, currentUser, canManage, isMobile]
);
return (
diff --git a/app/scenes/Settings/components/OAuthAuthenticationListItem.tsx b/app/scenes/Settings/components/OAuthAuthenticationListItem.tsx
new file mode 100644
index 0000000000..416c494e50
--- /dev/null
+++ b/app/scenes/Settings/components/OAuthAuthenticationListItem.tsx
@@ -0,0 +1,60 @@
+import { observer } from "mobx-react";
+import { useTranslation } from "react-i18next";
+import OAuthAuthentication from "~/models/oauth/OAuthAuthentication";
+import { OAuthScopeHelper } from "~/scenes/Login/OAuthScopeHelper";
+import { Avatar, AvatarSize } from "~/components/Avatar";
+import { AvatarVariant } from "~/components/Avatar/Avatar";
+import ListItem from "~/components/List/Item";
+import Text from "~/components/Text";
+import Time from "~/components/Time";
+import OAuthAuthenticationMenu from "~/menus/OAuthAuthenticationMenu";
+
+type Props = {
+ /** The OAuthAuthentication to display */
+ oauthAuthentication: OAuthAuthentication;
+};
+
+const OAuthAuthenticationListItem = ({ oauthAuthentication }: Props) => {
+ const { t } = useTranslation();
+
+ const subtitle = (
+ <>
+
+ {oauthAuthentication.lastActiveAt ? (
+ <>
+ {t("Last active")}{" "}
+
+ >
+ ) : (
+ t("Never used")
+ )}{" "}
+ ·{" "}
+
+
+ {OAuthScopeHelper.normalizeScopes(oauthAuthentication.scope, t).join(
+ ", "
+ )}
+
+ >
+ );
+
+ return (
+
+ }
+ title={oauthAuthentication.oauthClient.name}
+ subtitle={subtitle}
+ actions={
+
+ }
+ />
+ );
+};
+
+export default observer(OAuthAuthenticationListItem);
diff --git a/app/scenes/Settings/components/OAuthClientDeleteDialog.tsx b/app/scenes/Settings/components/OAuthClientDeleteDialog.tsx
new file mode 100644
index 0000000000..db9a698ab1
--- /dev/null
+++ b/app/scenes/Settings/components/OAuthClientDeleteDialog.tsx
@@ -0,0 +1,36 @@
+import { useTranslation } from "react-i18next";
+import OAuthClient from "~/models/oauth/OAuthClient";
+import ConfirmationDialog from "~/components/ConfirmationDialog";
+
+type Props = {
+ oauthClient: OAuthClient;
+ onSubmit: () => void;
+};
+
+export default function OAuthClientDeleteDialog({
+ oauthClient,
+ onSubmit,
+}: Props) {
+ const { t } = useTranslation();
+
+ const handleSubmit = async () => {
+ await oauthClient.delete();
+ onSubmit();
+ };
+
+ return (
+
+ {t(
+ "Are you sure you want to delete the {{ appName }} application? This cannot be undone.",
+ {
+ appName: oauthClient.name,
+ }
+ )}
+
+ );
+}
diff --git a/app/scenes/Settings/components/OAuthClientListItem.tsx b/app/scenes/Settings/components/OAuthClientListItem.tsx
new file mode 100644
index 0000000000..f66af59af0
--- /dev/null
+++ b/app/scenes/Settings/components/OAuthClientListItem.tsx
@@ -0,0 +1,54 @@
+import { observer } from "mobx-react";
+import { useTranslation } from "react-i18next";
+import { Link } from "react-router-dom";
+import OAuthClient from "~/models/oauth/OAuthClient";
+import { Avatar, AvatarSize } from "~/components/Avatar";
+import { AvatarVariant } from "~/components/Avatar/Avatar";
+import ListItem from "~/components/List/Item";
+import Text from "~/components/Text";
+import Time from "~/components/Time";
+import useCurrentUser from "~/hooks/useCurrentUser";
+import OAuthClientMenu from "~/menus/OAuthClientMenu";
+import { settingsPath } from "~/utils/routeHelpers";
+
+type Props = {
+ oauthClient: OAuthClient;
+};
+
+const OAuthClientListItem = ({ oauthClient }: Props) => {
+ const { t } = useTranslation();
+ const user = useCurrentUser();
+
+ const subtitle = (
+ <>
+
+ {t(`Created`)} {" "}
+ {oauthClient.createdById === user.id
+ ? ""
+ : t(`by {{ name }}`, { name: user.name })}
+
+ >
+ );
+
+ return (
+
+ }
+ title={
+
+ {oauthClient.name}
+
+ }
+ subtitle={subtitle}
+ actions={ }
+ />
+ );
+};
+
+export default observer(OAuthClientListItem);
diff --git a/app/scenes/Settings/components/SettingRow.tsx b/app/scenes/Settings/components/SettingRow.tsx
index de67a5db49..0b661bb4ab 100644
--- a/app/scenes/Settings/components/SettingRow.tsx
+++ b/app/scenes/Settings/components/SettingRow.tsx
@@ -39,7 +39,7 @@ const Column = styled.div`
flex: 1;
&:first-child {
- min-width: 70%;
+ min-width: 65%;
}
&:last-child {
diff --git a/app/scenes/Settings/components/SharesTable.tsx b/app/scenes/Settings/components/SharesTable.tsx
index 48377c450c..0880fbe63b 100644
--- a/app/scenes/Settings/components/SharesTable.tsx
+++ b/app/scenes/Settings/components/SharesTable.tsx
@@ -1,5 +1,5 @@
import compact from "lodash/compact";
-import * as React from "react";
+import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import { unicodeCLDRtoBCP47 } from "@shared/utils/date";
import Share from "~/models/Share";
@@ -27,7 +27,7 @@ export function SharesTable({ data, canManage, ...rest }: Props) {
const language = useUserLocale();
const hasDomain = data.some((share) => share.domain);
- const columns = React.useMemo[]>(
+ const columns = useMemo[]>(
() =>
compact>([
{
diff --git a/app/scenes/Settings/components/UserRoleFilter.tsx b/app/scenes/Settings/components/UserRoleFilter.tsx
index a7be6e3430..84019f0c24 100644
--- a/app/scenes/Settings/components/UserRoleFilter.tsx
+++ b/app/scenes/Settings/components/UserRoleFilter.tsx
@@ -1,6 +1,6 @@
import compact from "lodash/compact";
import { observer } from "mobx-react";
-import * as React from "react";
+import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import { UserRole } from "@shared/types";
import FilterOptions from "~/components/FilterOptions";
@@ -13,7 +13,7 @@ type Props = {
const UserRoleFilter = ({ activeKey, onSelect, ...rest }: Props) => {
const { t } = useTranslation();
- const options = React.useMemo(
+ const options = useMemo(
() =>
compact([
{
diff --git a/app/scenes/Settings/components/UserStatusFilter.tsx b/app/scenes/Settings/components/UserStatusFilter.tsx
index eabdf3c778..98a691d6d6 100644
--- a/app/scenes/Settings/components/UserStatusFilter.tsx
+++ b/app/scenes/Settings/components/UserStatusFilter.tsx
@@ -1,6 +1,6 @@
import compact from "lodash/compact";
import { observer } from "mobx-react";
-import * as React from "react";
+import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import FilterOptions from "~/components/FilterOptions";
import useCurrentUser from "~/hooks/useCurrentUser";
@@ -14,7 +14,7 @@ const UserStatusFilter = ({ activeKey, onSelect, ...rest }: Props) => {
const { t } = useTranslation();
const user = useCurrentUser();
- const options = React.useMemo(
+ const options = useMemo(
() =>
compact([
{
diff --git a/app/scenes/Trash/components/DeleteDocumentsInTrash.tsx b/app/scenes/Trash/components/DeleteDocumentsInTrash.tsx
index 6189511a00..3d4c3550a7 100644
--- a/app/scenes/Trash/components/DeleteDocumentsInTrash.tsx
+++ b/app/scenes/Trash/components/DeleteDocumentsInTrash.tsx
@@ -1,5 +1,4 @@
import { observer } from "mobx-react";
-import * as React from "react";
import { useTranslation, Trans } from "react-i18next";
import { useHistory } from "react-router-dom";
import { toast } from "sonner";
diff --git a/app/scenes/Trash/index.tsx b/app/scenes/Trash/index.tsx
index 8b2d553d92..20f9d4a40f 100644
--- a/app/scenes/Trash/index.tsx
+++ b/app/scenes/Trash/index.tsx
@@ -1,6 +1,5 @@
import { observer } from "mobx-react";
import { TrashIcon } from "outline-icons";
-import * as React from "react";
import { useTranslation } from "react-i18next";
import Button from "~/components/Button";
import Empty from "~/components/Empty";
diff --git a/app/stores/AuthStore.ts b/app/stores/AuthStore.ts
index 3afdd1f8ba..a3d6acc6bd 100644
--- a/app/stores/AuthStore.ts
+++ b/app/stores/AuthStore.ts
@@ -306,7 +306,7 @@ export default class AuthStore extends Store {
// if this logout was forced from an authenticated route then
// save the current path so we can go back there once signed in
if (savePath) {
- setPostLoginPath(window.location.pathname);
+ setPostLoginPath(window.location.pathname + window.location.search);
}
if (tryRevokingToken) {
diff --git a/app/stores/CollectionsStore.ts b/app/stores/CollectionsStore.ts
index dbc8140419..e50e334063 100644
--- a/app/stores/CollectionsStore.ts
+++ b/app/stores/CollectionsStore.ts
@@ -186,6 +186,13 @@ export default class CollectionsStore extends Store {
statusFilter: [CollectionStatusFilter.Archived],
});
+ get(id: string): Collection | undefined {
+ return (
+ this.data.get(id) ??
+ this.orderedData.find((collection) => id.endsWith(collection.urlId))
+ );
+ }
+
@computed
get archived(): Collection[] {
return orderBy(this.orderedData, "archivedAt", "desc").filter(
diff --git a/app/stores/DialogsStore.ts b/app/stores/DialogsStore.ts
index d39be23ddb..d8956ddb12 100644
--- a/app/stores/DialogsStore.ts
+++ b/app/stores/DialogsStore.ts
@@ -8,6 +8,7 @@ type DialogDefinition = {
isOpen: boolean;
fullscreen?: boolean;
style?: React.CSSProperties;
+ onClose?: () => void;
};
export default class DialogsStore {
@@ -50,6 +51,7 @@ export default class DialogsStore {
fullscreen,
replace,
style,
+ onClose,
}: {
id?: string;
title: string;
@@ -57,6 +59,7 @@ export default class DialogsStore {
content: React.ReactNode;
style?: React.CSSProperties;
replace?: boolean;
+ onClose?: () => void;
}) => {
setTimeout(
action(() => {
@@ -70,6 +73,7 @@ export default class DialogsStore {
fullscreen,
style,
isOpen: true,
+ onClose,
});
}),
0
diff --git a/app/stores/DocumentsStore.ts b/app/stores/DocumentsStore.ts
index 55c58b8c36..08766ca0d6 100644
--- a/app/stores/DocumentsStore.ts
+++ b/app/stores/DocumentsStore.ts
@@ -245,19 +245,14 @@ export default class DocumentsStore extends Store {
@action
fetchBacklinks = async (documentId: string): Promise => {
- const res = await client.post(`/documents.list`, {
+ const documents = await this.fetchAll({
backlinkDocumentId: documentId,
});
- invariant(res?.data, "Document list not available");
- const { data } = res;
runInAction("DocumentsStore#fetchBacklinks", () => {
- data.forEach(this.add);
- this.addPolicies(res.policies);
-
this.backlinks.set(
documentId,
- data.map((doc: Partial) => doc.id)
+ documents.map((doc) => doc.id)
);
});
};
@@ -266,8 +261,8 @@ export default class DocumentsStore extends Store {
const documentIds = this.backlinks.get(documentId) || [];
return orderBy(
compact(documentIds.map((id) => this.data.get(id))),
- "updatedAt",
- "desc"
+ "title",
+ "asc"
);
}
diff --git a/app/stores/EventsStore.ts b/app/stores/EventsStore.ts
index 901dd1b198..7d668d8558 100644
--- a/app/stores/EventsStore.ts
+++ b/app/stores/EventsStore.ts
@@ -1,5 +1,3 @@
-import orderBy from "lodash/orderBy";
-import { computed } from "mobx";
import Event from "~/models/Event";
import RootStore from "./RootStore";
import Store, { RPCAction } from "./base/Store";
@@ -11,8 +9,12 @@ export default class EventsStore extends Store> {
super(rootStore, Event);
}
- @computed
- get orderedData(): Event