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) && ( + + )} +
{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
{item.title}
; + return ( +
{item.title}
+ ); } 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( - <IssueStatusIcon status={state.name} color={state.color} /> + <StyledIssueStatusIcon + service={service} + state={state} + size={18} + /> <span> - {title} <Text type="tertiary">{id}</Text> + <Backticks content={title} /> +  <Text type="tertiary">{id}</Text> </span> - - + + {{ 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( - <PullRequestIcon status={state.name} color={state.color} /> + <StyledPullRequestIcon size={18} state={state} /> <span> - {title} <Text type="tertiary">{id}</Text> + <Backticks content={title} /> +  <Text type="tertiary">{id}</Text> </span> - - + + {{ 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) => ( - - - {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 ( +
+ <> + + + + ( + { + field.onChange(event.target.value.split("\n")); + }} + required + /> + )} + /> + {isCloudHosted && ( + + )} + + + + + + + ); +}); 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 && (
{currentHeading}
)} @@ -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} > -