Compare commits

..

231 Commits

Author SHA1 Message Date
Saumya Pandey f86f163b81 fix: lazy load tippy 2022-09-04 21:34:20 +05:30
Tom Moor 2fa5e5c796 fix: Incorrect validation 2022-09-02 20:56:13 +02:00
Tom Moor 0882a50cfd fix: Requests using GET that should be POST, related #4042 2022-09-02 10:45:20 +02:00
Tom Moor c85f3bd7b4 fix: Remove ability to use GET for RPC API requests by default (#4042)
* fix: Remove ability to use GET for RPC API requests by default

* tsc
2022-09-02 01:05:40 -07:00
Nicolas Caluori 2d29f0f042 Content is displayed wrongly when printing / Save as PDF (#4043) 2022-09-02 01:05:09 -07:00
dependabot[bot] 67d119f932 chore(deps): bump moment-timezone from 0.5.34 to 0.5.37 (#4037)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-08-31 11:48:30 +05:30
Tom Moor 32b76303e5 Add simple count of views to share links (#4036)
* Add simple count of views to share links

* Remove no longer applicable tests

* Avoid incrementing view count for known bots
2022-08-30 23:16:40 -07:00
Tom Moor 212985e18f feat: Allow viewers to be upgraded to editors on individual collections (#4023)
* Improve types

* More types, fix default permission for viewers added to collection

* fix change of default role for CollectionGroup

* Restore policy

* test

* tests
2022-08-30 23:12:27 -07:00
Tom Moor b8115ae3ce fix: Add url validation to team and user avatar fields 2022-08-30 23:05:57 +02:00
Tom Moor 264f19d255 fix: Suppress TooManyRequestsError to error tracker 2022-08-28 21:17:51 +02:00
Tom Moor 6fc1cbc0ce fix: Unneccessary requests made on share links 2022-08-27 20:45:07 +02:00
Tom Moor 3cc3cd8cf8 fix: Do not replace SSR title with 'Untitled', closes #3985 2022-08-27 20:20:59 +02:00
Tom Moor b9f1fde2e3 test 2022-08-27 13:39:11 +02:00
Tom Moor a1d4cca9d9 Add support for document subscriptions to websockets 2022-08-27 12:53:40 +02:00
Tom Moor 922bf53753 fix: Document subscriptions backfill not recursive 2022-08-27 11:58:21 +02:00
Tom Moor 1c8fadbe02 Merge branch 'tom/socket-refactor' 2022-08-27 11:51:38 +02:00
Apoorv Mishra 4dbad4e46c feat: Support embed configuration (#3980)
* wip

* stash

* fix: make authenticationId nullable fk

* fix: apply generics to resolve compile time type errors

* fix: loosen integration settings

* chore: refactor into functional component

* feat: pass integrations all the way to embeds

* perf: avoid re-fetching integrations

* fix: change attr name to avoid type overlap

* feat: use hostname from embed settings in matcher

* Revert "feat: use hostname from embed settings in matcher"

This reverts commit e7485d9cda.

* feat: refactor  into a class

* chore: refactor url regex formation as a util

* fix: escape regex special chars

* fix: remove in-house escapeRegExp in favor of lodash's

* fix: sanitize url

* perf: memoize embeds

* fix: rename hostname to url and allow spreading entire settings instead of just url

* fix: replace diagrams with drawio

* fix: rename

* fix: support self-hosted and saas both

* fix: assert on settings url

* fix: move embed integrations loading to hook

* fix: address review comments

* fix: use observer in favor of explicit state setters

* fix: refactor useEmbedIntegrations into useEmbeds

* fix: use translations for toasts

Co-authored-by: Tom Moor <tom.moor@gmail.com>
2022-08-26 12:21:46 +05:30
CuriousCorrelation 24c71c38a5 feat: Document subscriptions (#3834)
Co-authored-by: Tom Moor <tom.moor@gmail.com>
2022-08-25 23:47:13 -07:00
Tom Moor 354a68a8b7 Remove long-deprecated documents.star/documents.unstar 2022-08-25 21:51:34 +02:00
Tom Moor bb12f1fabb SocketProvider -> WebsocketProvider 2022-08-25 21:34:54 +02:00
Tom Moor debadcb711 fix: Wrap websocket handlers in action
Separate documents.archive
2022-08-25 21:34:54 +02:00
Tom Moor d2aea687f3 Remove collection fetch on document delete 2022-08-25 21:34:54 +02:00
Tom Moor 60309975e0 Allow usePolicy to fetch missing policies 2022-08-25 21:34:54 +02:00
Tom Moor 983010b5d8 fix: collections.create event not propagated when initialized with private permissions 2022-08-25 21:34:54 +02:00
Tom Moor de5524d366 Add tracing around websocket processor 2022-08-25 21:34:54 +02:00
Tom Moor c62bfc4a60 Separate documents.update event 2022-08-25 21:34:54 +02:00
Tom Moor 7804f33e0d Separate teams.update event 2022-08-25 21:34:54 +02:00
Tom Moor d17e6f3432 Separate documents.delete event 2022-08-25 21:34:54 +02:00
Tom Moor 4f1277f912 Separate groups.delete event 2022-08-25 21:34:54 +02:00
Tom Moor b172da6fdf Separate collections.delete event 2022-08-25 21:34:54 +02:00
Tom Moor 138bc367dd types 2022-08-25 21:34:54 +02:00
Tom Moor c657134b46 types 2022-08-25 21:34:54 +02:00
Tom Moor 864f585e5b chore: Remove long deprecated database columns (#3821)
* chore: Remove long deprecated database columns

* test

* Update 20220720221531-remove-deprecated-columns.js

* fix rollback

* Add guard for upgrading past v0.54.0
2022-08-25 11:52:01 -07:00
Tom Moor a869ab7609 fix: Improve error messaging when file cannot be fetched for import
related #4006
2022-08-24 21:25:19 +02:00
Tom Moor a3d8e6c8fc chore: Add db:create command 2022-08-24 00:04:37 -07:00
Tom Moor 68f24fce21 fix: Add support for new clickup sharing links 2022-08-23 23:04:21 +02:00
Tom Moor f0cbbee4b8 Merge branch 'main' of github.com:outline/outline 2022-08-23 22:58:45 +02:00
Tom Moor 7345d0c256 Remove links to valid files 2022-08-23 10:21:35 -07:00
Tom Moor ee05a8a0ca Merge branch 'main' of github.com:outline/outline 2022-08-23 09:58:03 +02:00
Translate-O-Tron fd7e0ef41f New Crowdin updates (#3958) 2022-08-22 11:41:16 -07:00
Tom Moor 1e5cf2d960 chore: Update dd-trace 2022-08-22 14:47:19 +02:00
Tom Moor 421312b845 Possible fix for #3986 2022-08-22 09:47:47 +02:00
Tom Moor f1bd4a5b31 Merge branch '3991-add-explicit-timeouts-to-requests' 2022-08-22 09:21:22 +02:00
Tom Moor 72b0e78788 fix: Validate uuid on attachments.create endpoint 2022-08-20 23:46:01 +02:00
Tom Moor 8302840ab5 feat: Add timeout to incoming requests 2022-08-19 08:14:11 +02:00
Tom Moor f32f07cdcc chore: Refactor user activation to command 2022-08-18 11:24:27 +02:00
Tom Moor f620a9d34c fix: Cannot start without --services argument, regressed in 41d7cc26b5
closes #3984
2022-08-18 09:48:28 +02:00
Tom Moor 7113b5f604 fix: Restore user deletion through API, increase rate limit 2022-08-17 22:40:00 +02:00
Tom Moor 41d7cc26b5 chore: Adds name to Redis connections for debugging (#3982)
* chore: Adds name to Redis connections for debugging, minor associated refactoring

* Upgrade bull, ioredis

* Add pid to redis connection name in development
2022-08-17 12:55:57 -07:00
Tom Moor e57941732a fix: emoji column no longer filled in db, simplified state length validation 2022-08-16 22:05:10 +02:00
Tom Moor a738b51d87 chore: Add additional logging for unknown request errors 2022-08-16 19:49:15 +02:00
Tom Moor 85dab03820 docs 2022-08-16 19:43:50 +02:00
Tom Moor ed8176ca7d fix: Limit ws payload size 2022-08-16 10:27:55 +02:00
Tom Moor cfa7ecd7f8 fix: Add missing validation to document state 2022-08-16 09:35:31 +02:00
github-actions[bot] 44a4aee5cf chore: Auto Compress Images (#3977)
Co-authored-by: apoorv-mishra <apoorv-mishra@users.noreply.github.com>
2022-08-16 00:10:52 -07:00
Jonathan Harrrington 7ead17a8e0 Add support for Grist embeds. (#3914)
* Add support for Grist embeds.

* Change Grist integration to only support SaaS

* Update Regex

* Update shared/editor/embeds/index.tsx

Co-authored-by: Apoorv Mishra <apoorvmishra101092@gmail.com>

* Change Grist embed to use function based API

* Convert standard URL into embed url

* Update shared/editor/embeds/Grist.tsx

Co-authored-by: Apoorv Mishra <apoorvmishra101092@gmail.com>

* Update shared/editor/embeds/Grist.tsx

Co-authored-by: Apoorv Mishra <apoorvmishra101092@gmail.com>

* Update shared/editor/embeds/Grist.tsx

Co-authored-by: Apoorv Mishra <apoorvmishra101092@gmail.com>

* Lint and test updates

Co-authored-by: Apoorv Mishra <apoorvmishra101092@gmail.com>
Co-authored-by: Tom Moor <tom.moor@gmail.com>
2022-08-16 09:17:20 +05:30
Apoorv Mishra 7a758f84a0 chore: refactor server test setup (#3976)
* chore: refactor server test setup

* Close dangling redis connections instead of mocking rate limiter
  specific modules
* Segregate pre and post env test setup

* fix: remove mock file
2022-08-16 09:16:57 +05:30
Tom Moor 93bb9d067d fix: H1 and title should be different sizes, closes #3975 2022-08-15 23:02:35 +02:00
Tom Moor 9f3266abaf Remove headings 4 and below from TOC, see:
https://github.com/outline/outline/discussions/3973
2022-08-15 22:46:49 +02:00
Tom Moor 4d0473c22c Reference email image by cid for self hosted instances (#3957) 2022-08-14 08:50:49 -07:00
Tom Moor d8b4814aa9 perf: Suppress Mermaid diagram rendering when hidden (#3963) 2022-08-14 08:50:37 -07:00
Tom Moor a326e0ee88 chore: Rate limiter audit (#3965)
* chore: Rate limiter audit api/users

* Make requests required

* api/collections

* Remove checkRateLimit on FileOperation (now done at route level through rate limiter)

* auth rate limit

* Add metric logging when rate limit exceeded

* Refactor to shared configs

* test
2022-08-14 08:04:04 -07:00
Tom Moor 9338328a82 fix: Add expiry to socket<->user mapping in Redis 2022-08-13 22:26:13 +02:00
Tom Moor 31931fc80c test: Remove --detectLeaks as this expiremental flag is good – but flakey, tests fail in CI that do not locally 2022-08-12 15:37:08 +02:00
Tom Moor 7deda03000 test: Fix test memory leakage by mocking RateLimiter 2022-08-12 15:14:58 +02:00
Nan Yu 990de127e3 feat: add session switching to the root action menu (#3925)
* feat: add session switching to the root action menu

* minor fixes

* stylistic consistency

* capitalize account section

* minor fix
2022-08-12 05:11:22 -07:00
Apoorv Mishra 0c51bfb899 perf: reduce memory usage upon running server tests (#3949)
* perf: reduce memory usage upon running server tests

* perf: plug leaks in server/routes

* perf: plug leaks in server/scripts

* perf: plug leaks in server/policies

* perf: plug leaks in server/models

* perf: plug leaks in server/middlewares

* perf: plug leaks in server/commands

* fix: missing await on db.flush

* perf: plug leaks in server/queues

* chore: remove unused legacy funcs

* fix: await on db.flush

* perf: await on GC to run in between tests

* fix: remove db refs

* fix: revert embeds

* perf: plug leaks in shared/i18n
2022-08-11 21:39:17 +05:30
akp 8e1f42a9cb Add optional export notifications (#3935)
* Add `emails.export_completed` notification to settings menu

Signed-off-by: AKP <tom@tdpain.net>

* Don't send email when export_completed notifications are disabled

Signed-off-by: AKP <tom@tdpain.net>

* Automatically subscribe new users to `export_completed` notifications

Signed-off-by: AKP <tom@tdpain.net>

* Alter secondary text on export page to mention optional notifications

Signed-off-by: AKP <tom@tdpain.net>

* Alter toast text on collection export for optional notifications

Signed-off-by: AKP <tom@tdpain.net>

* Only subscribe new admins to export notifs

Signed-off-by: AKP <tom@tdpain.net>

* Move `export_completed` notification decision into `beforeSend`

Signed-off-by: AKP <tom@tdpain.net>

* Update server/emails/templates/ExportFailureEmail.tsx

Co-authored-by: Tom Moor <tom.moor@gmail.com>

* Update server/emails/templates/ExportSuccessEmail.tsx

Co-authored-by: Tom Moor <tom.moor@gmail.com>

Signed-off-by: AKP <tom@tdpain.net>
Co-authored-by: Tom Moor <tom.moor@gmail.com>
2022-08-11 07:31:35 -07:00
Tom Moor 1adcce6b5d fix: Upgrade markdown-it to fix text collapse bug (#3953)
* fix: Upgrade markdown-it to fix text collapse bug

* tsc. Need to overwrite the types for now until all Prosemirror modules are updated, they have recently been converted to Typescript and the types conflict
2022-08-11 06:31:52 -07:00
Translate-O-Tron a5d611d544 New Crowdin updates (#3795) 2022-08-11 05:46:21 -07:00
Tom Moor 1d242d44b1 chore: Add eslint rule for object shorthand (#3955) 2022-08-11 05:18:14 -07:00
Apoorv Mishra 7eaa8eb961 feat: Put request rate limit at application server (#3857)
* feat: Put request rate limit at application server

This PR contains implementation for a blanket rate limiter at
application server level. Currently the allowed throughput is set high
only to be changed later as per the actual data gathered.

* Simplify implementation

1. Remove shutdown handler to purge rate limiter keys
2. Have separate keys for default and custom(route-based) rate limiters
3. Do not kill default rate limiter because it is not needed anymore due
   to (2) above

* Set 60s as default for rate limiting window

* Fix env types
2022-08-11 15:40:30 +05:30
Tom Moor 593cf73118 test: Update jest configuration (#3951)
* Split shared tests

* Centralize and parallelize jest config

* ci
2022-08-10 13:26:36 -07:00
Tom Moor e5c5e8907a fix: Disallow data: URI's for images 2022-08-09 16:31:09 +02:00
dependabot[bot] 5640ec30cc chore(deps): bump compressorjs from 1.0.7 to 1.1.1 (#3943)
Bumps [compressorjs](https://github.com/fengyuanchen/compressorjs) from 1.0.7 to 1.1.1.
- [Release notes](https://github.com/fengyuanchen/compressorjs/releases)
- [Changelog](https://github.com/fengyuanchen/compressorjs/blob/main/CHANGELOG.md)
- [Commits](https://github.com/fengyuanchen/compressorjs/compare/v1.0.7...v1.1.1)

---
updated-dependencies:
- dependency-name: compressorjs
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-08-08 09:13:03 -07:00
dependabot[bot] da67486f2f chore(deps): bump aws-sdk from 2.1044.0 to 2.1189.0 (#3942)
Bumps [aws-sdk](https://github.com/aws/aws-sdk-js) from 2.1044.0 to 2.1189.0.
- [Release notes](https://github.com/aws/aws-sdk-js/releases)
- [Changelog](https://github.com/aws/aws-sdk-js/blob/master/CHANGELOG.md)
- [Commits](https://github.com/aws/aws-sdk-js/compare/v2.1044.0...v2.1189.0)

---
updated-dependencies:
- dependency-name: aws-sdk
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-08-08 09:11:55 -07:00
Tom Moor 8c39487c80 Move various document menu actions to action definitions 2022-08-08 17:31:53 +02:00
dependabot[bot] 3ab9d7492e chore(deps): bump react-merge-refs from 1.1.0 to 2.0.1 (#3903)
* chore(deps): bump react-merge-refs from 1.1.0 to 2.0.1

Bumps [react-merge-refs](https://github.com/gregberge/react-merge-refs) from 1.1.0 to 2.0.1.
- [Release notes](https://github.com/gregberge/react-merge-refs/releases)
- [Changelog](https://github.com/gregberge/react-merge-refs/blob/main/CHANGELOG.md)
- [Commits](https://github.com/gregberge/react-merge-refs/compare/v1.1.0...v2.0.1)

---
updated-dependencies:
- dependency-name: react-merge-refs
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>

* tsc

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Tom Moor <tom.moor@gmail.com>
2022-08-08 15:04:18 +01:00
dependabot[bot] 6a5d6ee3db chore(deps): bump oy-vey from 0.10.0 to 0.11.2 (#3902)
* chore(deps): bump oy-vey from 0.10.0 to 0.11.2

Bumps [oy-vey](https://github.com/oysterbooks/oy) from 0.10.0 to 0.11.2.
- [Release notes](https://github.com/oysterbooks/oy/releases)
- [Changelog](https://github.com/revivek/oy/blob/master/CHANGELOG.md)
- [Commits](https://github.com/oysterbooks/oy/compare/0.10.0...0.11.2)

---
updated-dependencies:
- dependency-name: oy-vey
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

* tsc

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Tom Moor <tom.moor@gmail.com>
2022-08-08 07:02:41 -07:00
Tom Moor 57f9871c22 Add NODE_ENV=production to env sample 2022-08-08 05:52:03 -07:00
Tom Moor dca491fc28 test: Fix frontend test failures from upgrading Jest to v28 2022-08-08 13:31:34 +02:00
Tom Moor e97cc61e2f test: Mock bull, fix setInterval capturing memory in tests
Towards #3939
2022-08-08 13:15:06 +02:00
Tom Moor ba385e1507 chore: Bump jest 2022-08-08 12:40:17 +02:00
Tom Moor 71c9fcf59b test: Avoid creation of new server/app instance for each route test 2022-08-08 12:06:54 +02:00
Tom Moor b45e6c504f fix: Prevent webhook delivery for deleted teams 2022-08-08 11:15:04 +02:00
Tom Moor 1b00d51c74 fix: Check WebhookSubscription is not disabled before delivery attempt 2022-08-08 11:10:10 +02:00
Tom Moor 7923a7e071 Enforce user invites/request on server 2022-08-08 11:02:37 +02:00
Tom Moor b37a848914 Add limit of 10 webhooks/team 2022-08-08 10:58:47 +02:00
github-actions[bot] dca9bc1598 chore: Compressed inefficient images automatically (#3933)
Co-authored-by: apoorv-mishra <apoorv-mishra@users.noreply.github.com>
2022-08-07 13:10:08 -07:00
Apoorv Mishra 982ab2b48e feat(editor): support google form embeds (#3930)
Fixes #3129 and #3923
2022-08-07 12:41:30 +05:30
Nan Yu 74d9409cc3 fix: refactor auth flow to explicitly pass in a host (#3909)
* fix: refactor auth flow to explicitly pass in a host

* add new error handler to all SSO providers

* refactor passport error into middleware
2022-08-04 02:00:52 -07:00
Apoorv Mishra 0a6cfe5a6a feat: Choose random color on collection creation (#3912)
Choose a random color from a shared color palette between backend
and frontend during collection creation.
2022-08-04 01:48:19 -07:00
Apoorv Mishra 4a16124a94 fix: Remove templatize action for trashed document (#3922) 2022-08-04 01:44:15 -07:00
Apoorv Mishra 294521f162 fix: Escape regex for embeds (#3907)
Fixes #3899
2022-08-02 01:40:11 -07:00
Apoorv Mishra 00481d2bfc fix: Improve document delete confirmation message (#3876)
Modify document delete confirmation message to warn
about the number of expected nested documents to be deleted.
2022-08-01 15:51:30 -07:00
Tom Moor eace258a86 Revert "chore(deps-dev): bump react-refresh from 0.9.0 to 0.14.0 (#3901)" (#3908)
This reverts commit de4b515e64.
2022-08-01 15:43:47 -07:00
dependabot[bot] de4b515e64 chore(deps-dev): bump react-refresh from 0.9.0 to 0.14.0 (#3901)
Bumps [react-refresh](https://github.com/facebook/react/tree/HEAD/packages/react) from 0.9.0 to 0.14.0.
- [Release notes](https://github.com/facebook/react/releases)
- [Changelog](https://github.com/facebook/react/blob/main/CHANGELOG.md)
- [Commits](https://github.com/facebook/react/commits/v0.14.0/packages/react)

---
updated-dependencies:
- dependency-name: react-refresh
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-08-01 13:57:32 -07:00
dependabot[bot] c35c566fef chore(deps-dev): bump concurrently from 6.2.1 to 7.3.0 (#3905)
Bumps [concurrently](https://github.com/open-cli-tools/concurrently) from 6.2.1 to 7.3.0.
- [Release notes](https://github.com/open-cli-tools/concurrently/releases)
- [Commits](https://github.com/open-cli-tools/concurrently/compare/v6.2.1...v7.3.0)

---
updated-dependencies:
- dependency-name: concurrently
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-08-01 11:56:14 -07:00
Pavlos d9dc6aa2d7 Fix URL in huntr page link (#3906) 2022-08-01 18:51:38 +01:00
Spotlight 192802d360 feat: Expand highlighted languages (#3891)
Adds Elixir, Kotlin, and Swift to the list of available languages to be highlighted.
2022-07-31 11:23:59 -07:00
Tom Moor cb9773ad85 chore: Add emailed confirmation code to account deletion (#3873)
* wip

* tests
2022-07-31 10:59:40 -07:00
Tom Moor f9d9a82e47 fix: Cannot hit enter after sentance starting with forward slash
closes #3879
2022-07-29 09:15:48 +01:00
Tom Moor 383bac241e fix: Suppress ForbiddenError in error tracker 2022-07-26 23:18:26 +01:00
Tom Moor ea28dc46eb fix: Error in WebhookProcessor when team is permanatly destroyed 2022-07-26 22:33:48 +01:00
Tom Moor 2794057738 fix: Sequelize rejectOnEmpty should result in 404 status 2022-07-26 22:06:47 +01:00
Tom Moor b7b1f5e1fd fix: Cleanup attachments uploaded to S3 when import fails (#3868) 2022-07-26 12:10:13 -07:00
Tom Moor 8fdd5bf734 fix: substitution of content when sending an image to a profile (#3869)
* fix: Limit public uploads to basic image types

* test
2022-07-26 12:10:00 -07:00
Tom Moor 086c3ec2d8 fix: Allow more flexible SMTP connection when SSL is not required. Do not fail on self-signed certs 2022-07-25 23:44:20 +01:00
Tom Moor f370b0296b fix: File operation cleanup task should also remove import data 2022-07-25 21:10:37 +01:00
Tom Moor 9b837763e6 0.65.2 2022-07-25 19:25:23 +01:00
dependabot[bot] 3d9a8be867 chore(deps-dev): bump typescript from 4.4.4 to 4.7.4 (#3866)
* chore(deps-dev): bump typescript from 4.4.4 to 4.7.4

Bumps [typescript](https://github.com/Microsoft/TypeScript) from 4.4.4 to 4.7.4.
- [Release notes](https://github.com/Microsoft/TypeScript/releases)
- [Commits](https://github.com/Microsoft/TypeScript/compare/v4.4.4...v4.7.4)

---
updated-dependencies:
- dependency-name: typescript
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

* tsc

* tsc

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Tom Moor <tom.moor@gmail.com>
2022-07-25 11:21:04 -07:00
dependabot[bot] c8caeebdba chore(deps): bump react-window from 1.8.6 to 1.8.7 (#3865)
Bumps [react-window](https://github.com/bvaughn/react-window) from 1.8.6 to 1.8.7.
- [Release notes](https://github.com/bvaughn/react-window/releases)
- [Changelog](https://github.com/bvaughn/react-window/blob/master/CHANGELOG.md)
- [Commits](https://github.com/bvaughn/react-window/commits)

---
updated-dependencies:
- dependency-name: react-window
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-07-25 11:09:47 -07:00
dependabot[bot] 2c7d5ac3d8 chore(deps-dev): bump @types/jsonwebtoken from 8.5.5 to 8.5.8 (#3864)
Bumps [@types/jsonwebtoken](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/jsonwebtoken) from 8.5.5 to 8.5.8.
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/jsonwebtoken)

---
updated-dependencies:
- dependency-name: "@types/jsonwebtoken"
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-07-25 11:09:32 -07:00
Tom Moor 30190866f8 test: Flakey test 2022-07-25 08:59:30 +01:00
Tom Moor 53a08cf307 chore: Basic protection against zip bombs 2022-07-24 23:51:04 +01:00
dependabot[bot] 1c5864deee chore(deps-dev): bump eslint-config-prettier from 8.3.0 to 8.5.0 (#3807)
Bumps [eslint-config-prettier](https://github.com/prettier/eslint-config-prettier) from 8.3.0 to 8.5.0.
- [Release notes](https://github.com/prettier/eslint-config-prettier/releases)
- [Changelog](https://github.com/prettier/eslint-config-prettier/blob/main/CHANGELOG.md)
- [Commits](https://github.com/prettier/eslint-config-prettier/compare/v8.3.0...v8.5.0)

---
updated-dependencies:
- dependency-name: eslint-config-prettier
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-07-24 13:11:11 -07:00
Tom Moor 865e6d048e fix: 'Export' option missing in collection menu for admins 2022-07-24 20:29:59 +01:00
Tom Moor 5e852170f9 perf: Read attachment buffers only when neccessary, closes #3849 2022-07-24 19:15:34 +01:00
Tom Moor 71da57773e docs 2022-07-24 14:09:43 +01:00
Tom Moor ec35af4bc5 Refactor validations 2022-07-24 13:40:04 +01:00
Nan Yu 870d9ed41e feat: allow external SSO methods to log into teams as long as emails match (#3813)
* wip

* wip

* fix comments

* better separation of conerns

* fix up tests

* fix semantics

* fixup tsc

* fix some tests

* the old semantics were easier to use

* add db:reset to scripts

* explicitly throw for unauthorized external authorization

* fix minor bug

* add additional tests for user creator and team creator

* yank the email matching logic out of teamcreator

* renaming

* fix type and test errors

* adds test to ensure that accountProvisioner works with email matching

* remove only

* fix comments

* recreate changes to allow self hosted to make teams
2022-07-24 04:55:30 -07:00
Apoorv Mishra 24170e8684 chore: Remove updatedAt column from events table (#3841) 2022-07-24 01:57:21 -07:00
Tom Moor 7ae892fe06 fix: Long collection description prevents import (#3847)
* fix: Long collection description prevents import
fix: Parallelize attachment upload during import

* fix: Improve Notion image import matching

* chore: Bump JSZIP (perf)

* fix: Allow redirect from /doc/<id> to canonical url

* fix: Importing document with only title duplicates title in body
2022-07-24 01:37:20 -07:00
Tom Moor 4f537c7578 Remove retry on export task 2022-07-23 17:00:32 +01:00
Tom Moor 4bca081faa chore: Add rolling window limits to import and export operations 2022-07-23 16:29:28 +01:00
Tom Moor 87b4c9fdba fix: Cannot create collection if all existing collections are deleted (#3836) 2022-07-22 10:44:11 -07:00
Tom Moor 6fe4b1cba1 fix: Code block previous language memory (#3830) 2022-07-22 01:59:48 -07:00
Tom Moor ef2abf824e fix: Correctly sanitize href in link editor 'open url' flow 2022-07-22 00:23:53 +01:00
Tom Moor 4b4b0f7037 Revert "feat: Port scenes/Search to functional component style (#3800)" (#3827)
This reverts commit 5758ff3459.
2022-07-21 03:37:27 -07:00
Tom Moor 80d50e3d88 fix: Diagrams.net proxy path considered as embeddable 2022-07-21 10:51:34 +01:00
Tom Moor ba264974cf fix: Improvement to accuracy of collaboration server metrics 2022-07-21 09:44:13 +01:00
CuriousCorrelation 71dd4f267b feat: Port UserListItem to functional style (#3802)
* feat: Port `UserListItem` to functional style

* Add translation for pending invite

* Add missing translations

* Update `translations.json`

* Revert "Update `translations.json`"

This reverts commit d8000a7510.

* fix: Incorrect translation strings

Co-authored-by: Tom Moor <tom.moor@gmail.com>
2022-07-20 15:07:01 -07:00
CuriousCorrelation 5758ff3459 feat: Port scenes/Search to functional component style (#3800)
* feat: Refactor Search scene to functional style

* fix: Clicking on recent not updating search input

* Replace translations and root objs with stores

* Replace `props.location` with `useLocation`

* deconstruct `useLocation` for readability

* Replace match prop term with `useParams`

* [WIP] Replace props history with `useHistory`

* Replace `ReactComponentProps` with state style

* Remove `lastParam` check, use dependency array instead

* Add explict match on param change

This reverts commit bfcc4038ff.
2022-07-20 15:06:49 -07:00
dependabot[bot] 6568b16ef9 chore(deps): bump terser from 4.8.0 to 4.8.1 (#3817)
Bumps [terser](https://github.com/terser/terser) from 4.8.0 to 4.8.1.
- [Release notes](https://github.com/terser/terser/releases)
- [Changelog](https://github.com/terser/terser/blob/master/CHANGELOG.md)
- [Commits](https://github.com/terser/terser/commits)

---
updated-dependencies:
- dependency-name: terser
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-07-20 15:05:19 -07:00
Tom Moor ef0412c449 fix: Cannot create new team on self-hosted (#3819) 2022-07-20 13:18:21 -07:00
Tom Moor 031a7d396f Add message to login screen for shared links 2022-07-19 17:57:13 +01:00
Nan Yu c3f5563e7f feat: scope login attempts to specific subdomains if available - do not switch subdomains (#3741)
* make the user lookup in user creator sensitive to team
* add team specific logic to oidc strat
* factor out slugifyDomain
* change type of req during auth to Koa.Context
2022-07-19 06:50:55 -07:00
Tom Moor 4ee3929e9d 0.65.1 2022-07-19 09:59:02 +01:00
Tom Moor 9ab409a640 fix: Account for non-SSL database connection in pending migrations check (#3811)
* fix: Account for non-SSL database connection in pending migrations check

* Double exit
2022-07-19 01:58:48 -07:00
Tom Moor 9cafe75bf2 0.65.0 2022-07-18 23:30:51 +01:00
Tom Moor 630b4eff8a chore: Bump passport 2022-07-18 22:51:11 +01:00
Tom Moor bf8ca59442 chore: Bump moment 2022-07-18 22:40:34 +01:00
Tom Moor 9dd28def67 fix: Force download of public attachments 2022-07-18 21:49:48 +01:00
dependabot[bot] d785389fde chore(deps): bump prosemirror-gapcursor from 1.2.1 to 1.3.1 (#3808)
Bumps [prosemirror-gapcursor](https://github.com/prosemirror/prosemirror-gapcursor) from 1.2.1 to 1.3.1.
- [Release notes](https://github.com/prosemirror/prosemirror-gapcursor/releases)
- [Changelog](https://github.com/ProseMirror/prosemirror-gapcursor/blob/master/CHANGELOG.md)
- [Commits](https://github.com/prosemirror/prosemirror-gapcursor/compare/1.2.1...1.3.1)

---
updated-dependencies:
- dependency-name: prosemirror-gapcursor
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-07-18 13:01:26 -07:00
Tom Moor 1ccd770bce Merge branch 'main' of github.com:outline/outline 2022-07-18 19:25:50 +01:00
dependabot[bot] 7719d378b0 chore(deps): bump semver and @types/semver (#3805)
Bumps [semver](https://github.com/npm/node-semver) and [@types/semver](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/semver). These dependencies needed to be updated together.

Updates `semver` from 7.3.5 to 7.3.7
- [Release notes](https://github.com/npm/node-semver/releases)
- [Changelog](https://github.com/npm/node-semver/blob/main/CHANGELOG.md)
- [Commits](https://github.com/npm/node-semver/compare/v7.3.5...v7.3.7)

Updates `@types/semver` from 7.3.9 to 7.3.10
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/semver)

---
updated-dependencies:
- dependency-name: semver
  dependency-type: direct:production
  update-type: version-update:semver-patch
- dependency-name: "@types/semver"
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-07-18 11:25:09 -07:00
dependabot[bot] f26f8d4bb9 chore(deps-dev): bump @types/node from 15.12.2 to 18.0.6 (#3806)
Bumps [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) from 15.12.2 to 18.0.6.
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node)

---
updated-dependencies:
- dependency-name: "@types/node"
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-07-18 11:24:43 -07:00
dependabot[bot] 89d4aeac67 chore(deps): bump slug and @types/slug (#3804)
Bumps [slug](https://github.com/Trott/slug) and [@types/slug](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/slug). These dependencies needed to be updated together.

Updates `slug` from 4.0.4 to 5.3.0
- [Release notes](https://github.com/Trott/slug/releases)
- [Changelog](https://github.com/Trott/slug/blob/main/CHANGELOG.md)
- [Commits](https://github.com/Trott/slug/compare/v4.0.4...v5.3.0)

Updates `@types/slug` from 5.0.2 to 5.0.3
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/slug)

---
updated-dependencies:
- dependency-name: slug
  dependency-type: direct:production
  update-type: version-update:semver-major
- dependency-name: "@types/slug"
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-07-18 11:24:29 -07:00
Tom Moor dc94a683e7 chore: Reduce timeout on webhook deliveries 2022-07-17 18:48:45 +01:00
Jamie Slome 04f5b08ba1 Update SECURITY.md (#3711)
* Update SECURITY.md

* Update SECURITY.md

Co-authored-by: Tom Moor <tom.moor@gmail.com>
2022-07-17 07:29:10 -07:00
CuriousCorrelation 5924f4909f fix: Cursor disappearing behind emoji (#3786)
* fix: Cursor disappearing behind emoji

* Move emoji node styles to `Styles.ts`

* fix: grammar

* fix: Pasting emoji adds a new line

* fix: DOM element type
2022-07-17 06:49:39 -07:00
CuriousCorrelation c00bad38e2 feat(editor): Ability to select line in codeblocks (#3798)
* feat(editor): Ability to select line in codeblocks

* fix: Check to make sure sel is indeed in codeblock
2022-07-17 06:49:30 -07:00
Tom Moor 11e1ef455f chore: Improve UUID vaildation – prevent nonsense reaching db queries 2022-07-17 14:49:04 +01:00
Tom Moor 4af69b2758 fix: Moving an image to empty space results in endless upload (#3799)
* fix: Error dragging images below doc, types

* fix: Handle html/text content dropped into padding

* refactor, docs
2022-07-17 03:31:55 -07:00
Tom Moor dee87f15af fix: Members table does not correctly reset from filters 2022-07-16 18:47:36 +01:00
dependabot[bot] 67885e7339 chore(deps): bump react-dnd-html5-backend from 14.0.0 to 16.0.1 (#3769)
Bumps [react-dnd-html5-backend](https://github.com/react-dnd/react-dnd) from 14.0.0 to 16.0.1.
- [Release notes](https://github.com/react-dnd/react-dnd/releases)
- [Changelog](https://github.com/react-dnd/react-dnd/blob/main/CHANGELOG.md)
- [Commits](https://github.com/react-dnd/react-dnd/commits)

---
updated-dependencies:
- dependency-name: react-dnd-html5-backend
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-07-16 10:15:11 -07:00
Tom Moor 0b0a1b0169 fix: Heading action depth conflict, closes #3558 2022-07-16 17:58:02 +01:00
Tom Moor de18196fd8 chore: Upgrade socket.io (#3697)
* Upgrade wip

* tsc

* tsc

* fix: Missing authenticated message
2022-07-16 06:02:03 -07:00
dependabot[bot] 96d1c4997b chore(deps): bump yjs from 13.5.34 to 13.5.39 (#3770)
Bumps [yjs](https://github.com/yjs/yjs) from 13.5.34 to 13.5.39.
- [Release notes](https://github.com/yjs/yjs/releases)
- [Commits](https://github.com/yjs/yjs/compare/v13.5.34...v13.5.39)

---
updated-dependencies:
- dependency-name: yjs
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-07-16 02:40:34 -07:00
Tom Moor 95f4fb2424 chore: Remove deprecated socket.io-auth (#3780) 2022-07-16 02:27:09 -07:00
Tom Moor 1247bb411e Merge branch 'paullessing-issue-3655-allowed-domains-save-no-change' 2022-07-16 00:38:28 +01:00
Tom Moor 7ffb182034 Merge branch 'issue-3655-allowed-domains-save-no-change' of github.com:paullessing/outline into paullessing-issue-3655-allowed-domains-save-no-change 2022-07-16 00:37:49 +01:00
Translate-O-Tron fc414e2dd4 New Crowdin updates (#3723) 2022-07-15 16:19:13 -07:00
Nan Yu c3ec7b0877 Feat: clarify security language and hide default settings when invites are required (#3751)
* clarify default role and allowed domains

* language tweaks

* Update app/scenes/Settings/Security.tsx

Co-authored-by: Tom Moor <tom.moor@gmail.com>

Co-authored-by: Tom Moor <tom.moor@gmail.com>
2022-07-15 16:13:41 -07:00
Tom Moor e509719c77 Add ability to quickly create test users in development (#3764) 2022-07-15 16:11:30 -07:00
Tom Moor a16cf72b73 feat: Error state for paginated lists (#3766)
* Add error state for failed list loading

* Move sidebar collections to PaginatedList for improved error handling, loading, retrying etc
2022-07-15 16:11:04 -07:00
CuriousCorrelation acabc00643 fix: ToolbarMenu popup on inline code selection (#3775)
* fix: `ToolbarMenu` popup on inline code selection

* fix: Replace `isCode` checks with single `isInCode`

* feat: Only relevant options on `code_inline` selection

* Change special case with item visibility toggle

* fix: `formattingMenuItems` visibility in `code_inline`
2022-07-15 16:10:47 -07:00
Tom Moor e989999d6e fix: Upgrade prosemirror-view fixes duplicate lines, closes #3371
Note: That this bump of prosemirror-view also includes typescript types for the first time ever, these conflict with the @types packages and cause the need for extensive changes throughout the codebase. To prevent this becoming a massive PR with days of testing these new types are being removed for now. In the future we will bump all of the pm dependencies and restore the package types here
2022-07-15 10:34:03 +01:00
dependabot[bot] c3e149eb86 chore(deps): bump @babel/core from 7.17.10 to 7.18.6 (#3771)
Bumps [@babel/core](https://github.com/babel/babel/tree/HEAD/packages/babel-core) from 7.17.10 to 7.18.6.
- [Release notes](https://github.com/babel/babel/releases)
- [Changelog](https://github.com/babel/babel/blob/main/CHANGELOG.md)
- [Commits](https://github.com/babel/babel/commits/v7.18.6/packages/babel-core)

---
updated-dependencies:
- dependency-name: "@babel/core"
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-07-13 12:48:57 -07:00
dependabot[bot] 4c05fe422c chore(deps): bump http-errors from 1.4.0 to 2.0.0 (#3772)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-07-13 00:59:56 -07:00
Tom Moor 47e73cee4e feat: Cleanup api keys and webhooks for suspended users (#3756) 2022-07-13 00:59:31 -07:00
CuriousCorrelation d1b01d28e6 fix: svg+xml image type ext not assigned properly (#3774) 2022-07-13 00:59:17 -07:00
Tom Moor 973cfc3fa3 Do not show suspended users to non admins (#3776) 2022-07-13 00:59:06 -07:00
dependabot[bot] dd6084d044 chore(deps-dev): bump @types/formidable from 2.0.0 to 2.0.5 (#3773)
Bumps [@types/formidable](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/formidable) from 2.0.0 to 2.0.5.
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/formidable)

---
updated-dependencies:
- dependency-name: "@types/formidable"
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-07-12 11:07:17 -07:00
Tom Moor 206545f350 fix: Ensure signed attachment urls are always downloaded rather than loaded in browser 2022-07-12 17:14:22 +01:00
Tom Moor e92d68a0a3 Create dependabot.yml 2022-07-12 09:40:44 +02:00
CuriousCorrelation 66dbcde29b feat: Redirect on unpublished share access (#3760)
* feat(WIP): Redirect on unpublished shares

* feat[WIP]: add redirect with test notice

* Revert to `Login` display, no redirects
2022-07-10 23:59:45 -07:00
Tom Moor 465a8bd505 fix: Version tag should open new tab, related type improvements
closes #3737
2022-07-10 11:22:45 +02:00
Tom Moor aef62d1356 fix: Publish click from editing heading, closes #3759 2022-07-10 10:23:00 +02:00
Tom Moor 35e82beaf7 chore: Upgrade koa- dependencies (#3761) 2022-07-09 10:23:42 -07:00
Tom Moor 8bb88b8550 chore: Audit of all model column validations (#3757)
* chore: Updating all model validations before the white-hatters get to it ;)

* test

* Remove isUrl validation, thinking about it need to account for minio and other weird urls here
2022-07-09 08:04:40 -07:00
Tom Moor da4a10e877 chore: Remove shares.info apiVersion 1 (#3758)
* chore: Remove shares.info apiVersion 1

* fix: Sporadic test failure
2022-07-09 04:28:56 -07:00
Tom Moor caaf6dd76b fix: Enter at beginning of collapsed heading should create a new heading above (#3754) 2022-07-09 02:23:12 -07:00
Tom Moor 2893924e9a fix: Must check length before passing to timingSafeEqual 2022-07-09 11:19:40 +02:00
Tom Moor 32b7a7df00 fix: Handle sanitizeUrl can receive non-string value
closes #3746
2022-07-08 21:15:07 +02:00
Tom Moor 97f8c0813c fix: Use crypto.timingSafeEqual, closes #3740 2022-07-08 21:10:51 +02:00
CuriousCorrelation 746dc30aeb feat: Add pending migrations check during startup (#3744)
* feat: Add pending migrations check during startup

* fix: migration pending log message

Co-authored-by: Tom Moor <tom.moor@gmail.com>

Co-authored-by: Tom Moor <tom.moor@gmail.com>
2022-07-08 11:30:16 -07:00
Tom Moor 4a46d19846 fix: Improved model validation for Collection (#3749)
* fix: Added improved model validation for Collection attributes

* sp

* fix: Enforce title length in UI
2022-07-08 11:10:22 -07:00
Tom Moor 98106e7f6f Update 20220702132722-add-webhooks-deleted-at.js 2022-07-08 02:22:48 -07:00
Nan Yu 1e808fc52c Feat: add auth provider to users on sign in (#3739)
* feat: merge a new authentication method onto existing user records when emails match

* adds test for invite acceptance and auth provider creation

* addresses comments
- test existing user and invites in different test cases
- update lastActiveAt syncronously when an invite is accepted

* sort arrays in test to prevent nondeterministic test behaivior when doing array compare
2022-07-08 00:24:46 -07:00
Tom Moor ec8c0645ba fix: Correct annotation order 🙈 2022-07-07 12:23:27 +02:00
Tom Moor f90309e781 fix: Unneccessary restrictive avatarUrl length 2022-07-07 12:16:54 +02:00
Paul Lessing d8f125f413 Fix: Move logic inline 2022-07-07 11:01:32 +01:00
Tom Moor c36e7bfbb6 fix: Add 10 domain limit per team (#3733)
* fix: Validate team domains are FQDN's
Add 10 domain limit per team
fix: Deletion of domains not happening within request lifecycle

* tests

* docs
2022-07-05 12:27:02 -07:00
Tom Moor 831df67358 feat: Adds route-level role filtering. (#3734)
* feat: Adds route-level role filtering. Another layer in the onion of security and performance

* fix: Regression in authentication middleware
2022-07-05 12:26:49 -07:00
Tom Moor c6fdffba77 chore: Internal request filtering 2022-07-05 11:06:47 +02:00
Tom Moor 4e189b8970 Improved sanitization of href's in editor 2022-07-05 10:14:16 +02:00
Tom Moor 2f3dcb2520 fix: Do not show 'Full width' toggle to viewers
closes #3728
2022-07-04 15:20:01 +02:00
Nan Yu f36f5f13f4 Fix: clear localstore after logout (#3731)
* fix: remove user, team, and policies from auth store and localstorage on logout

* true up the reset everywhere
2022-07-04 01:47:44 -07:00
Tom Moor 5d498632c6 fix: Models are not all removed from local store upon access change (#3729)
* fix: Clean data from stores correctly on 401/403 response

* Convert DataLoader from class component, remove observables and caching

* types
2022-07-03 13:48:50 -07:00
Tom Moor 9cd26168e1 Separates policy for file operations 2022-07-03 18:19:56 +02:00
Tom Moor ee10e1407a fix: Typo of fileOperation -> fileOperations 2022-07-03 16:27:03 +02:00
Tom Moor c9af7ff889 fix: Suppress db validation errors in error reporting 2022-07-03 16:03:53 +02:00
Tom Moor 27978b8fc4 fix: Remove teams.create from audit events 2022-07-03 14:16:49 +02:00
Tom Moor 62d9bf7105 chore: Move initial avatar upload to background worker (#3727)
* chore: Async user avatar upload processor

* chore: Async team avatar upload

* Refactor to task for retries

* Docs
Include avatarUrl in task props to prevent race condition
Remove transaction around upload fetch request
2022-07-03 02:36:15 -07:00
Tom Moor 1f3a1d4b86 fix: Improved websockets error handling (#3726)
* fix: Add websocket client error capturing
fix: Incorrect parsing of documentName will never be empty

* fix: Non-present documentId in collaboration route should trigger an error response

* fix: Close unhandled websocket requests
2022-07-03 00:00:59 -07:00
Tom Moor 8ebe4b27b1 fix: Add additional model validation (#3725) 2022-07-02 14:29:01 -07:00
Tom Moor 0c30d2bb34 fix: share.document can be null when document is deleted
closes #3724
2022-07-02 19:56:15 +02:00
Tom Moor f744d488f6 chore: Soft delete webhooks (#3722) 2022-07-02 10:41:28 -07:00
Tom Moor 8ebf6e884f fix: Startup warning caused by unnecessary compilation of tests and mocks in non-test environments 2022-07-02 15:57:35 +02:00
Tom Moor 4438c80ea1 fix: users.promote + users.demote not available for individual subscription in webhook form 2022-07-02 14:55:07 +02:00
Tom Moor 863f22750f feat: Add optional notification email when invite is accepted (#3718)
* feat: Add optional notification email when invite is accepted

* Refactor to use beforeSend
2022-07-02 05:40:40 -07:00
Tom Moor ee22a127f6 feat: Add email when webhook is disabled (#3721)
fix: Webhook not disabled under some error conditions
2022-07-02 05:36:40 -07:00
Tom Moor c9cd424a8d chore: Remove over-usage of invariant (#3719) 2022-07-02 05:29:39 -07:00
Tom Moor 108b5b934a fix: users.promote & users.demote not handled by DeliverWebhookTask 2022-07-02 14:24:49 +02:00
Tom Moor 94824af6e7 fix: Allow soft-deleted records to be queried from RevisionProcessor
closes #3706
2022-07-02 11:58:22 +02:00
Tom Moor 1c6eef3509 Don't show share link when team sharing disabled (#3714)
fix: Docs appear to be publicly shared when sharing previously enabled
2022-07-02 01:37:10 -07:00
Translate-O-Tron 4e09356982 New Crowdin updates (#3681) 2022-07-01 13:22:01 -07:00
Nan Yu 4b166432e6 fix: show a distinct error message when a user tries to create an account using a personal gmail (#3710)
* fix: show a different error message when a user tries to create an account using a personal gmail

* throw only after attempting to find the team
2022-07-01 13:21:23 -07:00
CuriousCorrelation adb55fa965 feat: Custom Length decorator for UTF-8 chars len (#3709)
* feat: Custom Length decorator for UTF-8 chars len

* fix: Length decorator function return type
2022-07-01 13:21:09 -07:00
Tom Moor 7ce57c9c83 fix: attachments events not recognised by DeliverWebhookTask 2022-07-01 18:40:32 +02:00
Tom Moor b44dc726f3 test: fix fetch related tests 2022-06-30 10:37:06 +02:00
Paul Lessing 117421b4cb Feat: Only show save domains button if changes were made
The logic for this is that we show the button if either:
a) one or more new non-empty domains have been added, or
b) an existing domain was modified, even if the modification was then undone.

The reasoning for b) is as follows:
If a user adds a new domain row, makes changes, then removes the domain row, it is clear to the user that no changes have been made, and therefore the "save" button should not be visible.
However, as soon as the user makes any changes to an existing domain, they want to feel confident that they can hit save and ensure that whatever change they made is persisted; even if the change is identical to the current state, because they may not be able to recall accurately what the current state was. In those situations a user gets more confidence out of being able to hit save, than they would from being told by the system "you haven't made any changes".
2022-06-29 08:33:07 +01:00
Tom Moor 930bfd5391 fix: Must import fetch, log errors, use git short sha for version 2022-06-29 08:28:44 +02:00
Tom Moor 10f86ed218 feat: Webhooks (#3691)
* Webhooks (#3607)

* Get the migration and the model setup. Also make the sample env file a bit easier to use. Now just requires setting a SECRET_KEY and besides that will boot up from the sample

* WIP: Start getting a Webhook page created. Just the skeleton state right now

* WIP: Getting a form created to create webhooks, need to bring in react-hook-forms now

* WIP: Get library installed and make TS happy

* Get a few checkboxes ready to go

* Get creating and destroying working with a decent start to a frontend

* Didn't mean to enable this

* Remove eslint and fix other random typescript issue

* Rename some events to be more realistic

* Revert these changes

* PR review comments around policies. Also make sure this inherits from IdModel so it actually gets an id

* Allow any admin on the team to edit webhooks

* Start sending some webhooks for some User events

* Make sure the URL is valid

* Start recording webhook deliveries

* Make sure to verify if the subscription is for the type of event we are looking at

* Refactor sending Webhooks and follow better webhook schema

This creates a presenter to unify the format of webhooks. We also
extract the sending of webhooks and recording their deliveries to a
method than can be used by each of the different event type methods

We also add a status to WebhookDelivery since we need to save the record
before we make the HTTP request to get its id. Then once we make the
request and get a response we can update the delivery with the HTTP info

* Turn off a subscription that has failed for the last 25 deliveries

* Get a first spec passing. Found a bug in my returning of promises so good to patch that up now

* This looks nicer

* Get some tests added for the processor

* Add cron task to delete older webhooks

* Add Document Events to the Processor

* Revisions, FileOperations and Collections

* Get all the server side events added to the processor and make Typescript make sure they are all accounted for

* Get all the events added to the Frontend and work on styling them a bit, still needs some love though

* Get UI styled up a bit

* Get events wired up for webhook subscriptions

* Get delete events working and test at least one variant of them

* Get deletes working and actually make sure to send the model id in the webhook

* Remove webhook secrets from this slice

* Add disabled label for subscriptions that are disabled

* Make sure to cascade the delete

* Reorg this file a bit

* Fix association

* I removed secret for the moment

* Apply Copy changes from PR Review

Co-authored-by: Tom Moor <tom.moor@gmail.com>

* Actually apply the copy changes

TIL that if you Resolve a conversation it _also_ removes the 'staged suggestion' from your list on Github

Co-authored-by: Tom Moor <tom.moor@gmail.com>

* Update app/scenes/Settings/Webhooks.tsx

Missed this copy change before

Co-authored-by: Tom Moor <tom.moor@gmail.com>

* Add disabled as yellow badge

* Resolve frontend comments

* Fixup Schema a bit and remove the dependency on the subscription

* Add test to make sure we don't disable until there are enough failures, and fix code to actually do that. Also some test fixes from the json response shape changes

* Fix WebhookDeliveries to store the responses as Text instead of blobs

* Switch to text better for response bodies, this is using the helpers better and makes the code read better

* Move the logic to a task but run in through the processor cause the tests expect that right now, moving the tests over next

* Split up the tests and actually enqueue the events from the WebhookProcessor instead of doing them inline

* Allow any team admin to see any webhook subscription for the team

* Add the indexes based on our lookup patterns

* Run eslint --fix to fix auto correct issues from when I tried to use Github to merge copy changes

* Allow subscriptions to be edited after creation

* Types caught that I didn't add the new event to the webhook processor, also added it to the frontend here

* I think this will get these into the translations file

* Catch a few more translations, use styled components better and remove usage of webhook subscription in the copy

Co-authored-by: Tom Moor <tom.moor@gmail.com>

* fix: tsc
fix: Document model payload empty

* fix: Revision webhook payload
Add custom UA for hooks

* Add webhooks icon, move under Integrations settings
Some spacing fixes

* Add actorId to webhook payloads

* Add View and ApiKey event types

* Spacing tweaks, fix team payload

* fix: Webhook not disabled after 25 failures

* fix: Enable webhook when editing if previously disabled

* fix: Correctly store response headers

* fix: Error in json/parsing/presentation results in hanging 'pending' webhook delivery

* fix: Awkward payload for users.invite webhook

* Add BaseEvent, ShareEvent

* fix: Add share events to form

* fix: Move webhook delivery cleanup to single DB call
Remove some unused abstraction

* Add user, collection, group context to membership webhook events
Some associated refactoring

Co-authored-by: Corey Alexander <coreyja@gmail.com>
2022-06-28 22:44:50 -07:00
Tom Moor 9a6e09bafa feat: Add mermaidjs integration (#3679)
* feat: Add mermaidjs integration (#3523)

* Add mermaidjs to dependencies and CodeFenceNode

* Fix diagram id for mermaidjs diagrams

* Fix typescript compiler errors on mermaid integration

* Fix id generation for mermaid diagrams

* Refactor mermaidjs integration into prosemirror plugin

* Remove unnecessary class attribute in mermaidjs integration

* Change mermaidjs label to singular

* Change decorator.inline to decorator.node for mermaid diagram id

* Fix diagram toggle state

* Add border and background to mermaid diagrams

* Stop mermaidjs from overwriting fontFamily inside diagrams

* Add stable diagramId to mermaid diagrams

* Separate text for hide/show diagram
Use uuid as diagramId, avoid storing in state
Fix cursor on diagrams

* fix: Base diagram visibility off presence of source

* fix: More cases where our font-family is ignored

* Disable HTML labels

* fix: Button styling – not technically required but now we have a third button this felt all the more needed

closes #3116

* named chunks

* Upgrade mermaid 9.1.3

Co-authored-by: Jan Niklas Richter <5812215+ArcticXWolf@users.noreply.github.com>
2022-06-28 22:44:36 -07:00
Paul Lessing c65a88fc9f Fix: Changing security settings should not implicitly save allowedDomains 2022-06-28 19:40:25 +01:00
Tom Moor e24a5adbd5 deps: upgrade nodemon, jpeg-js 2022-06-27 16:45:54 +02:00
Tom Moor cddb6b2c32 deps: upgrade bull-board 2022-06-27 16:42:45 +02:00
Tom Moor ac467b2936 fix: Return direct url to public attachments, closes #3686 2022-06-24 11:24:11 +02:00
Tom Moor 68ce304b48 fix: Language in document notification email, missing collection name 2022-06-24 10:01:54 +02:00
530 changed files with 17887 additions and 8268 deletions
+8
View File
@@ -35,6 +35,14 @@
"displayName": false
}
]
],
"ignore": [
"**/*.test.ts"
]
},
"development": {
"ignore": [
"**/*.test.ts"
]
}
}
+14 -1
View File
@@ -70,6 +70,15 @@ jobs:
- run:
name: test
command: yarn test:app
test-shared:
<<: *defaults
steps:
- checkout
- restore_cache:
key: dependency-cache-{{ checksum "package.json" }}
- run:
name: test
command: yarn test:shared
test-server:
<<: *defaults
steps:
@@ -81,7 +90,7 @@ jobs:
command: ./node_modules/.bin/sequelize db:migrate --url $DATABASE_URL_TEST
- run:
name: test
command: yarn test:server
command: yarn test:server --forceExit
bundle-size:
<<: *defaults
steps:
@@ -140,6 +149,9 @@ workflows:
- test-server:
requires:
- build
- test-shared:
requires:
- build
- test-app:
requires:
- build
@@ -149,6 +161,7 @@ workflows:
- bundle-size:
requires:
- test-app
- test-shared
- test-server
build-docker:
+9
View File
@@ -1,5 +1,7 @@
# –––––––––––––––– 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
@@ -168,3 +170,10 @@ SMTP_SECURE=true
# 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
+1 -2
View File
@@ -12,7 +12,6 @@
"plugin:@typescript-eslint/recommended",
"plugin:import/recommended",
"plugin:import/typescript",
"plugin:react-hooks/recommended",
"plugin:prettier/recommended"
],
"plugins": [
@@ -21,12 +20,12 @@
"eslint-plugin-import",
"eslint-plugin-node",
"eslint-plugin-react",
"eslint-plugin-react-hooks",
"import"
],
"rules": {
"eqeqeq": 2,
"curly": 2,
"object-shorthand": "error",
"no-mixed-operators": "off",
"no-useless-escape": "off",
"es/no-regexp-lookbehind-assertions": "error",
+11
View File
@@ -0,0 +1,11 @@
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
version: 2
updates:
- package-ecosystem: "npm" # See documentation for possible values
directory: "/" # Location of package manifests
schedule:
interval: "weekly"
+1
View File
@@ -3,6 +3,7 @@ build
node_modules/*
.env
.log
.vscode/*
npm-debug.log
stats.json
.DS_Store
+88
View File
@@ -0,0 +1,88 @@
{
"projects": [
{
"displayName": "server",
"verbose": false,
"roots": [
"<rootDir>/server"
],
"moduleNameMapper": {
"^@server/(.*)$": "<rootDir>/server/$1",
"^@shared/(.*)$": "<rootDir>/shared/$1"
},
"setupFiles": [
"<rootDir>/__mocks__/console.js",
"<rootDir>/server/test/env.ts"
],
"setupFilesAfterEnv": [
"<rootDir>/server/test/setup.ts"
],
"testEnvironment": "node",
"runner": "@getoutline/jest-runner-serial"
},
{
"displayName": "app",
"verbose": false,
"roots": [
"<rootDir>/app"
],
"moduleNameMapper": {
"^~/(.*)$": "<rootDir>/app/$1",
"^@shared/(.*)$": "<rootDir>/shared/$1",
"^.*[.](gif|ttf|eot|svg)$": "<rootDir>/__test__/fileMock.js",
"^uuid$": "<rootDir>/node_modules/uuid/dist/index.js"
},
"modulePaths": [
"<rootDir>/app"
],
"setupFiles": [
"<rootDir>/__mocks__/window.js"
],
"setupFilesAfterEnv": [
"<rootDir>/app/test/setup.ts"
],
"testEnvironment": "jsdom",
"testEnvironmentOptions": {
"url": "http://localhost"
}
},
{
"displayName": "shared-node",
"verbose": false,
"roots": [
"<rootDir>/shared"
],
"moduleNameMapper": {
"^@server/(.*)$": "<rootDir>/server/$1",
"^@shared/(.*)$": "<rootDir>/shared/$1"
},
"setupFiles": [
"<rootDir>/__mocks__/console.js"
],
"setupFilesAfterEnv": [
"<rootDir>/shared/test/setup.ts"
],
"testEnvironment": "node"
},
{
"displayName": "shared-jsdom",
"verbose": false,
"roots": [
"<rootDir>/shared"
],
"moduleNameMapper": {
"^~/(.*)$": "<rootDir>/app/$1",
"^@shared/(.*)$": "<rootDir>/shared/$1",
"^.*[.](gif|ttf|eot|svg)$": "<rootDir>/__test__/fileMock.js",
"^uuid$": "<rootDir>/node_modules/uuid/dist/index.js"
},
"setupFiles": [
"<rootDir>/__mocks__/window.js"
],
"testEnvironment": "jsdom",
"testEnvironmentOptions": {
"url": "http://localhost"
}
}
]
}
-17
View File
@@ -1,17 +0,0 @@
export default class Queue {
name;
constructor(name) {
this.name = name;
}
process = (fn) => {
console.log(`Registered function ${this.name}`);
this.processFn = fn;
};
add = (data) => {
console.log(`Running ${this.name}`);
return this.processFn({ data });
};
}
-1
View File
@@ -1,2 +1 @@
// Mock for node-uuid
global.console.warn = () => {};
+5 -1
View File
@@ -1,6 +1,10 @@
{
"extends": [
"../.eslintrc"
"../.eslintrc",
"plugin:react-hooks/recommended",
],
"plugins": [
"eslint-plugin-react-hooks",
],
"env": {
"jest": true,
-27
View File
@@ -1,27 +0,0 @@
{
"testURL": "http://localhost",
"verbose": false,
"rootDir": "..",
"roots": [
"<rootDir>/app",
"<rootDir>/shared"
],
"moduleNameMapper": {
"^~/(.*)$": "<rootDir>/app/$1",
"^@shared/(.*)$": "<rootDir>/shared/$1",
"^.*[.](gif|ttf|eot|svg)$": "<rootDir>/__test__/fileMock.js"
},
"moduleDirectories": [
"node_modules"
],
"modulePaths": [
"<rootDir>/app"
],
"setupFiles": [
"<rootDir>/__mocks__/window.js"
],
"setupFilesAfterEnv": [
"./app/test/setup.ts"
],
"testEnvironment": "jsdom"
}
-32
View File
@@ -1,32 +0,0 @@
import { ToolsIcon, TrashIcon } from "outline-icons";
import * as React from "react";
import stores from "~/stores";
import { createAction } from "~/actions";
import { DebugSection } from "~/actions/sections";
import env from "~/env";
import { deleteAllDatabases } from "~/utils/developer";
export const clearIndexedDB = createAction({
name: ({ t }) => t("Delete IndexedDB cache"),
icon: <TrashIcon />,
keywords: "cache clear database",
section: DebugSection,
perform: async ({ t }) => {
await deleteAllDatabases();
stores.toasts.showToast(t("IndexedDB cache deleted"));
},
});
export const development = createAction({
name: ({ t }) => t("Development"),
keywords: "debug",
icon: <ToolsIcon />,
iconInContextMenu: false,
section: DebugSection,
visible: ({ event }) =>
env.ENVIRONMENT === "development" ||
(event instanceof KeyboardEvent && event.altKey),
children: [clearIndexedDB],
});
export const rootDebugActions = [development];
+50
View File
@@ -0,0 +1,50 @@
import { ToolsIcon, TrashIcon, UserIcon } from "outline-icons";
import * as React from "react";
import stores from "~/stores";
import { createAction } from "~/actions";
import { DeveloperSection } from "~/actions/sections";
import env from "~/env";
import { client } from "~/utils/ApiClient";
import { deleteAllDatabases } from "~/utils/developer";
export const clearIndexedDB = createAction({
name: ({ t }) => t("Delete IndexedDB cache"),
icon: <TrashIcon />,
keywords: "cache clear database",
section: DeveloperSection,
perform: async ({ t }) => {
await deleteAllDatabases();
stores.toasts.showToast(t("IndexedDB cache deleted"));
},
});
export const createTestUsers = createAction({
name: "Create test users",
icon: <UserIcon />,
section: DeveloperSection,
visible: () => env.ENVIRONMENT === "development",
perform: async () => {
const count = 10;
try {
await client.post("/developer.create_test_users", { count });
stores.toasts.showToast(`${count} test users created`);
} catch (err) {
stores.toasts.showToast(err.message, { type: "error" });
}
},
});
export const developer = createAction({
name: ({ t }) => t("Developer"),
keywords: "debug",
icon: <ToolsIcon />,
iconInContextMenu: false,
section: DeveloperSection,
visible: ({ event }) =>
env.ENVIRONMENT === "development" ||
(event instanceof KeyboardEvent && event.altKey),
children: [clearIndexedDB, createTestUsers],
});
export const rootDeveloperActions = [developer];
+208 -5
View File
@@ -11,9 +11,18 @@ import {
ImportIcon,
PinIcon,
SearchIcon,
UnsubscribeIcon,
SubscribeIcon,
MoveIcon,
TrashIcon,
CrossIcon,
ArchiveIcon,
} from "outline-icons";
import * as React from "react";
import getDataTransferFiles from "@shared/utils/getDataTransferFiles";
import { getEventFiles } from "@shared/utils/files";
import DocumentDelete from "~/scenes/DocumentDelete";
import DocumentMove from "~/scenes/DocumentMove";
import DocumentPermanentDelete from "~/scenes/DocumentPermanentDelete";
import DocumentTemplatizeDialog from "~/components/DocumentTemplatizeDialog";
import { createAction } from "~/actions";
import { DocumentSection } from "~/actions/sections";
@@ -108,6 +117,68 @@ export const unstarDocument = createAction({
},
});
export const subscribeDocument = createAction({
name: ({ t }) => t("Subscribe"),
section: DocumentSection,
icon: <SubscribeIcon />,
visible: ({ activeDocumentId, stores }) => {
if (!activeDocumentId) {
return false;
}
const document = stores.documents.get(activeDocumentId);
return (
!document?.isSubscribed &&
stores.policies.abilities(activeDocumentId).subscribe
);
},
perform: ({ activeDocumentId, stores, t }) => {
if (!activeDocumentId) {
return;
}
const document = stores.documents.get(activeDocumentId);
document?.subscribe();
stores.toasts.showToast(t("Subscribed to document notifications"), {
type: "success",
});
},
});
export const unsubscribeDocument = createAction({
name: ({ t }) => t("Unsubscribe"),
section: DocumentSection,
icon: <UnsubscribeIcon />,
visible: ({ activeDocumentId, stores }) => {
if (!activeDocumentId) {
return false;
}
const document = stores.documents.get(activeDocumentId);
return (
!!document?.isSubscribed &&
stores.policies.abilities(activeDocumentId).unsubscribe
);
},
perform: ({ activeDocumentId, stores, currentUserId, t }) => {
if (!activeDocumentId || !currentUserId) {
return;
}
const document = stores.documents.get(activeDocumentId);
document?.unsubscribe(currentUserId);
stores.toasts.showToast(t("Unsubscribed from document notifications"), {
type: "success",
});
},
});
export const downloadDocument = createAction({
name: ({ t, isContextMenu }) =>
isContextMenu ? t("Download") : t("Download document"),
@@ -260,8 +331,8 @@ export const importDocument = createAction({
input.type = "file";
input.accept = documents.importFileTypes.join(", ");
input.onchange = async (ev: Event) => {
const files = getDataTransferFiles(ev);
input.onchange = async (ev) => {
const files = getEventFiles(ev);
try {
const file = files[0];
@@ -296,10 +367,11 @@ export const createTemplate = createAction({
return false;
}
const document = stores.documents.get(activeDocumentId);
return (
return !!(
!!activeCollectionId &&
stores.policies.abilities(activeCollectionId).update &&
!document?.isTemplate
!document?.isTemplate &&
!document?.isDeleted
);
},
perform: ({ activeDocumentId, stores, t, event }) => {
@@ -328,15 +400,146 @@ export const searchDocumentsForQuery = (searchQuery: string) =>
visible: ({ location }) => location.pathname !== searchPath(),
});
export const moveDocument = createAction({
name: ({ t }) => t("Move"),
section: DocumentSection,
icon: <MoveIcon />,
visible: ({ activeDocumentId, stores }) => {
if (!activeDocumentId) {
return false;
}
return !!stores.policies.abilities(activeDocumentId).move;
},
perform: ({ activeDocumentId, stores, t }) => {
if (activeDocumentId) {
const document = stores.documents.get(activeDocumentId);
if (!document) {
return;
}
stores.dialogs.openModal({
title: t("Move {{ documentName }}", {
documentName: document.noun,
}),
content: (
<DocumentMove
document={document}
onRequestClose={stores.dialogs.closeAllModals}
/>
),
});
}
},
});
export const archiveDocument = createAction({
name: ({ t }) => t("Archive"),
section: DocumentSection,
icon: <ArchiveIcon />,
visible: ({ activeDocumentId, stores }) => {
if (!activeDocumentId) {
return false;
}
return !!stores.policies.abilities(activeDocumentId).archive;
},
perform: async ({ activeDocumentId, stores, t }) => {
if (activeDocumentId) {
const document = stores.documents.get(activeDocumentId);
if (!document) {
return;
}
await document.archive();
stores.toasts.showToast(t("Document archived"), {
type: "success",
});
}
},
});
export const deleteDocument = createAction({
name: ({ t }) => t("Delete"),
section: DocumentSection,
icon: <TrashIcon />,
dangerous: true,
visible: ({ activeDocumentId, stores }) => {
if (!activeDocumentId) {
return false;
}
return !!stores.policies.abilities(activeDocumentId).delete;
},
perform: ({ activeDocumentId, stores, t }) => {
if (activeDocumentId) {
const document = stores.documents.get(activeDocumentId);
if (!document) {
return;
}
stores.dialogs.openModal({
title: t("Delete {{ documentName }}", {
documentName: document.noun,
}),
isCentered: true,
content: (
<DocumentDelete
document={document}
onSubmit={stores.dialogs.closeAllModals}
/>
),
});
}
},
});
export const permanentlyDeleteDocument = createAction({
name: ({ t }) => t("Permanently delete"),
section: DocumentSection,
icon: <CrossIcon />,
dangerous: true,
visible: ({ activeDocumentId, stores }) => {
if (!activeDocumentId) {
return false;
}
return !!stores.policies.abilities(activeDocumentId).permanentDelete;
},
perform: ({ activeDocumentId, stores, t }) => {
if (activeDocumentId) {
const document = stores.documents.get(activeDocumentId);
if (!document) {
return;
}
stores.dialogs.openModal({
title: t("Permanently delete {{ documentName }}", {
documentName: document.noun,
}),
isCentered: true,
content: (
<DocumentPermanentDelete
document={document}
onSubmit={stores.dialogs.closeAllModals}
/>
),
});
}
},
});
export const rootDocumentActions = [
openDocument,
archiveDocument,
createDocument,
createTemplate,
deleteDocument,
importDocument,
downloadDocument,
starDocument,
unstarDocument,
subscribeDocument,
unsubscribeDocument,
duplicateDocument,
moveDocument,
permanentlyDeleteDocument,
printDocument,
pinDocumentToCollection,
pinDocumentToHome,
+40
View File
@@ -0,0 +1,40 @@
import * as React from "react";
import styled from "styled-components";
import { createAction } from "~/actions";
import { loadSessionsFromCookie } from "~/hooks/useSessions";
export const changeTeam = createAction({
name: ({ t }) => t("Switch team"),
placeholder: ({ t }) => t("Select a team"),
keywords: "change workspace organization",
section: "Account",
visible: ({ currentTeamId }) => {
const sessions = loadSessionsFromCookie();
const otherSessions = sessions.filter(
(session) => session.teamId !== currentTeamId
);
return otherSessions.length > 0;
},
children: ({ currentTeamId }) => {
const sessions = loadSessionsFromCookie();
const otherSessions = sessions.filter(
(session) => session.teamId !== currentTeamId
);
return otherSessions.map((session) => ({
id: session.url,
name: session.name,
section: "Account",
icon: <Logo alt={session.name} src={session.logoUrl} />,
perform: () => (window.location.href = session.url),
}));
},
});
const Logo = styled("img")`
border-radius: 2px;
width: 24px;
height: 24px;
`;
export const rootTeamActions = [changeTeam];
+1
View File
@@ -56,6 +56,7 @@ export function actionToMenuItem(
title,
icon,
visible,
dangerous: action.dangerous,
onClick: () => action.perform && action.perform(context),
selected: action.selected ? action.selected(context) : undefined,
};
+4 -2
View File
@@ -1,8 +1,9 @@
import { rootCollectionActions } from "./definitions/collections";
import { rootDebugActions } from "./definitions/debug";
import { rootDeveloperActions } from "./definitions/developer";
import { rootDocumentActions } from "./definitions/documents";
import { rootNavigationActions } from "./definitions/navigation";
import { rootSettingsActions } from "./definitions/settings";
import { rootTeamActions } from "./definitions/teams";
import { rootUserActions } from "./definitions/users";
export default [
@@ -11,5 +12,6 @@ export default [
...rootUserActions,
...rootNavigationActions,
...rootSettingsActions,
...rootDebugActions,
...rootDeveloperActions,
...rootTeamActions,
];
+1 -1
View File
@@ -2,7 +2,7 @@ import { ActionContext } from "~/types";
export const CollectionSection = ({ t }: ActionContext) => t("Collection");
export const DebugSection = ({ t }: ActionContext) => t("Debug");
export const DeveloperSection = ({ t }: ActionContext) => t("Debug");
export const DocumentSection = ({ t }: ActionContext) => t("Document");
+1 -1
View File
@@ -37,7 +37,7 @@ function Breadcrumb({
return (
<Flex justify="flex-start" align="center">
{topLevelItems.map((item, index) => (
<React.Fragment key={item.to || index}>
<React.Fragment key={String(item.to) || index}>
{item.icon}
{item.to ? (
<Item
+2 -1
View File
@@ -1,3 +1,4 @@
import { LocationDescriptor } from "history";
import { ExpandedIcon } from "outline-icons";
import { darken, lighten } from "polished";
import * as React from "react";
@@ -155,7 +156,7 @@ export type Props<T> = {
primary?: boolean;
fullwidth?: boolean;
as?: T;
to?: string;
to?: LocationDescriptor;
borderOnHover?: boolean;
href?: string;
"data-on"?: string;
+1 -12
View File
@@ -1,17 +1,6 @@
import * as React from "react";
import styled from "styled-components";
type Props = {
onClick?: React.MouseEventHandler<HTMLButtonElement>;
};
const ButtonLink: React.FC<Props> = React.forwardRef(
(props: Props, ref: React.Ref<HTMLButtonElement>) => {
return <Button {...props} ref={ref} />;
}
);
const Button = styled.button`
const ButtonLink = styled.button`
margin: 0;
padding: 0;
border: 0;
+1 -1
View File
@@ -25,7 +25,7 @@ function CollectionDescription({ collection }: Props) {
const [isExpanded, setExpanded] = React.useState(false);
const [isEditing, setEditing] = React.useState(false);
const [isDirty, setDirty] = React.useState(false);
const can = usePolicy(collection.id);
const can = usePolicy(collection);
const handleStartEditing = React.useCallback(() => {
setEditing(true);
+2 -1
View File
@@ -1,3 +1,4 @@
import { LocationDescriptor } from "history";
import { CheckmarkIcon } from "outline-icons";
import * as React from "react";
import { MenuItem as BaseMenuItem } from "reakit/Menu";
@@ -10,7 +11,7 @@ type Props = {
selected?: boolean;
disabled?: boolean;
dangerous?: boolean;
to?: string;
to?: LocationDescriptor;
href?: string;
target?: "_blank";
as?: string | React.ComponentType<any>;
+4 -4
View File
@@ -49,8 +49,8 @@ function DocumentListItem(
ref: React.RefObject<HTMLAnchorElement>
) {
const { t } = useTranslation();
const currentUser = useCurrentUser();
const currentTeam = useCurrentTeam();
const user = useCurrentUser();
const team = useCurrentTeam();
const [menuOpen, handleMenuOpen, handleMenuClose] = useBoolean();
const {
@@ -70,7 +70,7 @@ function DocumentListItem(
!!document.title.toLowerCase().includes(highlight.toLowerCase());
const canStar =
!document.isDraft && !document.isArchived && !document.isTemplate;
const can = usePolicy(currentTeam.id);
const can = usePolicy(team);
const canCollection = usePolicy(document.collectionId);
return (
@@ -96,7 +96,7 @@ function DocumentListItem(
highlight={highlight}
dir={document.dir}
/>
{document.isBadgedNew && document.createdBy.id !== currentUser.id && (
{document.isBadgedNew && document.createdBy.id !== user.id && (
<Badge yellow>{t("New")}</Badge>
)}
{canStar && (
+2 -1
View File
@@ -1,3 +1,4 @@
import { LocationDescriptor } from "history";
import { observer } from "mobx-react";
import * as React from "react";
import { useTranslation } from "react-i18next";
@@ -35,7 +36,7 @@ type Props = {
showLastViewed?: boolean;
showParentDocuments?: boolean;
document: Document;
to?: string;
to?: LocationDescriptor;
};
const DocumentMeta: React.FC<Props> = ({
+2 -1
View File
@@ -1,3 +1,4 @@
import { LocationDescriptor } from "history";
import { observer, useObserver } from "mobx-react";
import * as React from "react";
import { useTranslation } from "react-i18next";
@@ -12,7 +13,7 @@ import useStores from "~/hooks/useStores";
type Props = {
document: Document;
isDraft: boolean;
to?: string;
to?: LocationDescriptor;
rtl?: boolean;
};
+34 -11
View File
@@ -1,22 +1,24 @@
import { formatDistanceToNow } from "date-fns";
import { deburr, sortBy } from "lodash";
import { observer } from "mobx-react";
import { DOMParser as ProsemirrorDOMParser } from "prosemirror-model";
import { TextSelection } from "prosemirror-state";
import * as React from "react";
import mergeRefs from "react-merge-refs";
import { mergeRefs } from "react-merge-refs";
import { Optional } from "utility-types";
import insertFiles from "@shared/editor/commands/insertFiles";
import embeds from "@shared/editor/embeds";
import { Heading } from "@shared/editor/lib/getHeadings";
import { supportedImageMimeTypes } from "@shared/utils/files";
import getDataTransferFiles from "@shared/utils/getDataTransferFiles";
import { getDataTransferFiles } from "@shared/utils/files";
import parseDocumentSlug from "@shared/utils/parseDocumentSlug";
import { isInternalUrl } from "@shared/utils/urls";
import { AttachmentValidation } from "@shared/validations";
import Document from "~/models/Document";
import ClickablePadding from "~/components/ClickablePadding";
import ErrorBoundary from "~/components/ErrorBoundary";
import HoverPreview from "~/components/HoverPreview";
import type { Props as EditorProps, Editor as SharedEditor } from "~/editor";
import useDictionary from "~/hooks/useDictionary";
import useEmbeds from "~/hooks/useEmbeds";
import useStores from "~/hooks/useStores";
import useToasts from "~/hooks/useToasts";
import { NotFoundError } from "~/utils/errors";
@@ -57,6 +59,7 @@ function Editor(props: Props, ref: React.RefObject<SharedEditor> | null) {
const { documents } = useStores();
const { showToast } = useToasts();
const dictionary = useDictionary();
const embeds = useEmbeds(!shareId);
const [
activeLinkEvent,
setActiveLinkEvent,
@@ -177,21 +180,41 @@ function Editor(props: Props, ref: React.RefObject<SharedEditor> | null) {
event.preventDefault();
event.stopPropagation();
const files = getDataTransferFiles(event);
const view = ref?.current?.view;
if (!view) {
return;
}
// Insert all files as attachments if any of the files are not images.
const isAttachment = files.some(
(file) => !supportedImageMimeTypes.includes(file.type)
);
// Find a valid position at the end of the document
// Find a valid position at the end of the document to insert our content
const pos = TextSelection.near(
view.state.doc.resolve(view.state.doc.nodeSize - 2)
).from;
// If there are no files in the drop event attempt to parse the html
// as a fragment and insert it at the end of the document
if (files.length === 0) {
const text =
event.dataTransfer.getData("text/html") ||
event.dataTransfer.getData("text/plain");
const dom = new DOMParser().parseFromString(text, "text/html");
view.dispatch(
view.state.tr.insert(
pos,
ProsemirrorDOMParser.fromSchema(view.state.schema).parse(dom)
)
);
return;
}
// Insert all files as attachments if any of the files are not images.
const isAttachment = files.some(
(file) => !AttachmentValidation.imageContentTypes.includes(file.type)
);
insertFiles(view, event, pos, files, {
uploadFile: onUploadFile,
onFileUploadStart: props.onFileUploadStart,
@@ -289,4 +312,4 @@ function Editor(props: Props, ref: React.RefObject<SharedEditor> | null) {
);
}
export default React.forwardRef(Editor);
export default observer(React.forwardRef(Editor));
+1
View File
@@ -2,6 +2,7 @@ import styled from "styled-components";
const Empty = styled.p`
color: ${(props) => props.theme.textTertiary};
user-select: none;
`;
export default Empty;
+1 -1
View File
@@ -33,7 +33,7 @@ type Props = {
const EventListItem = ({ event, latest, document, ...rest }: Props) => {
const { t } = useTranslation();
const location = useLocation();
const can = usePolicy(document.id);
const can = usePolicy(document);
const opts = {
userName: event.actor.name,
};
+3 -13
View File
@@ -40,6 +40,7 @@ import { useTranslation } from "react-i18next";
import { useMenuState, MenuButton, MenuItem } from "reakit/Menu";
import styled, { useTheme } from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { colorPalette } from "@shared/utils/collections";
import ContextMenu from "~/components/ContextMenu";
import Flex from "~/components/Flex";
import { LabelText } from "~/components/Input";
@@ -200,18 +201,7 @@ export const icons = {
keywords: "warning alert error",
},
};
const colors = [
"#4E5C6E",
"#0366d6",
"#9E5CF7",
"#FF825C",
"#FF5C80",
"#FFBE0B",
"#42DED1",
"#00D084",
"#FF4DFA",
"#2F362F",
];
type Props = {
onOpen?: () => void;
onClose?: () => void;
@@ -272,7 +262,7 @@ function IconPicker({ onOpen, onClose, icon, color, onChange }: Props) {
<ColorPicker
color={color}
onChange={(color) => onChange(color.hex, icon)}
colors={colors}
colors={colorPalette}
triangle="hide"
styles={{
default: {
+29 -30
View File
@@ -104,31 +104,17 @@ export const LabelText = styled.div`
display: inline-block;
`;
export type Props = Omit<React.HTMLAttributes<HTMLInputElement>, "onChange"> & {
export type Props = React.InputHTMLAttributes<
HTMLInputElement | HTMLTextAreaElement
> & {
type?: "text" | "email" | "checkbox" | "search" | "textarea";
value?: string;
label?: string;
className?: string;
labelHidden?: boolean;
label?: string;
flex?: boolean;
short?: boolean;
margin?: string | number;
icon?: React.ReactNode;
name?: string;
pattern?: string;
minLength?: number;
maxLength?: number;
autoFocus?: boolean;
autoComplete?: boolean | string;
readOnly?: boolean;
required?: boolean;
disabled?: boolean;
placeholder?: string;
onChange?: (
ev: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
) => unknown;
innerRef?: React.RefObject<HTMLInputElement | HTMLTextAreaElement>;
onKeyDown?: (ev: React.KeyboardEvent<HTMLInputElement>) => unknown;
innerRef?: React.Ref<any>;
onFocus?: (ev: React.SyntheticEvent) => unknown;
onBlur?: (ev: React.SyntheticEvent) => unknown;
};
@@ -171,8 +157,6 @@ class Input extends React.Component<Props> {
...rest
} = this.props;
const InputComponent: React.ComponentType =
type === "textarea" ? RealTextarea : RealInput;
const wrappedLabel = <LabelText>{label}</LabelText>;
return (
@@ -186,15 +170,24 @@ class Input extends React.Component<Props> {
))}
<Outline focused={this.focused} margin={margin}>
{icon && <IconWrapper>{icon}</IconWrapper>}
<InputComponent
// @ts-expect-error no idea why this is not working
ref={this.input}
onBlur={this.handleBlur}
onFocus={this.handleFocus}
hasIcon={!!icon}
type={type === "textarea" ? undefined : type}
{...rest}
/>
{type === "textarea" ? (
<RealTextarea
ref={this.props.innerRef}
onBlur={this.props.onBlur}
onFocus={this.handleFocus}
hasIcon={!!icon}
{...rest}
/>
) : (
<RealInput
ref={this.props.innerRef}
onBlur={this.props.onBlur}
onFocus={this.handleFocus}
hasIcon={!!icon}
type={type}
{...rest}
/>
)}
</Outline>
</label>
</Wrapper>
@@ -202,4 +195,10 @@ class Input extends React.Component<Props> {
}
}
export const ReactHookWrappedInput = React.forwardRef(
(props: Omit<Props, "innerRef">, ref: React.Ref<any>) => {
return <Input {...{ ...props, innerRef: ref }} />;
}
);
export default Input;
+3 -2
View File
@@ -1,6 +1,7 @@
import * as React from "react";
import { useTranslation } from "react-i18next";
import { $Diff } from "utility-types";
import { CollectionPermission } from "@shared/types";
import InputSelect, { Props, Option } from "./InputSelect";
export default function InputSelectPermission(
@@ -31,11 +32,11 @@ export default function InputSelectPermission(
options={[
{
label: t("View and edit"),
value: "read_write",
value: CollectionPermission.ReadWrite,
},
{
label: t("View only"),
value: "read",
value: CollectionPermission.Read,
},
{
label: t("No access"),
+53
View File
@@ -0,0 +1,53 @@
import { DisconnectedIcon, WarningIcon } from "outline-icons";
import * as React from "react";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
import Empty from "~/components/Empty";
import useEventListener from "~/hooks/useEventListener";
import { OfflineError } from "~/utils/errors";
import ButtonLink from "../ButtonLink";
import Flex from "../Flex";
type Props = {
error: Error;
retry: () => void;
};
export default function LoadingError({ error, retry, ...rest }: Props) {
const { t } = useTranslation();
useEventListener("online", retry);
const message =
error instanceof OfflineError ? (
<>
<DisconnectedIcon color="currentColor" /> {t("Youre offline.")}
</>
) : (
<>
<WarningIcon color="currentColor" /> {t("Sorry, an error occurred.")}
</>
);
return (
<Content {...rest}>
<Flex align="center" gap={4}>
{message}{" "}
<ButtonLink onClick={() => retry()}>{t("Click to retry")}</ButtonLink>
</Flex>
</Content>
);
}
const Content = styled(Empty)`
padding: 8px 0;
white-space: nowrap;
${ButtonLink} {
color: ${(props) => props.theme.textTertiary};
&:hover {
color: ${(props) => props.theme.textSecondary};
text-decoration: underline;
}
}
`;
+5 -1
View File
@@ -69,7 +69,11 @@ const ListItem = (
);
};
const Wrapper = styled.a<{ $small?: boolean; $border?: boolean; to?: string }>`
const Wrapper = styled.a<{
$small?: boolean;
$border?: boolean;
to?: string;
}>`
display: flex;
padding: ${(props) => (props.$border === false ? 0 : "8px 0")};
margin: ${(props) =>
+2
View File
@@ -2,6 +2,7 @@ import * as React from "react";
import { useTranslation } from "react-i18next";
import Document from "~/models/Document";
import DocumentListItem from "~/components/DocumentListItem";
import Error from "~/components/List/Error";
import PaginatedList from "~/components/PaginatedList";
type Props = {
@@ -40,6 +41,7 @@ const PaginatedDocumentList = React.memo<Props>(function PaginatedDocumentList({
heading={heading}
fetch={fetch}
options={options}
renderError={(props) => <Error {...props} />}
renderItem={(item: Document, _index, compositeProps) => (
<DocumentListItem
key={item.id}
+34 -16
View File
@@ -34,12 +34,19 @@ type Props<T> = WithTranslation &
index: number,
compositeProps: CompositeStateReturn
) => React.ReactNode;
renderError?: (options: {
error: Error;
retry: () => void;
}) => React.ReactNode;
renderHeading?: (name: React.ReactElement<any> | string) => React.ReactNode;
onEscape?: (ev: React.KeyboardEvent<HTMLDivElement>) => void;
};
@observer
class PaginatedList<T extends PaginatedItem> extends React.Component<Props<T>> {
@observable
error?: Error;
@observable
isFetchingMore = false;
@@ -80,6 +87,7 @@ class PaginatedList<T extends PaginatedItem> extends React.Component<Props<T>> {
this.isFetchingMore = false;
};
@action
fetchResults = async () => {
if (!this.props.fetch) {
return;
@@ -87,25 +95,30 @@ class PaginatedList<T extends PaginatedItem> extends React.Component<Props<T>> {
this.isFetching = true;
const counter = ++this.fetchCounter;
const limit = DEFAULT_PAGINATION_LIMIT;
this.error = undefined;
const results = await this.props.fetch({
limit,
offset: this.offset,
...this.props.options,
});
try {
const results = await this.props.fetch({
limit,
offset: this.offset,
...this.props.options,
});
if (results && (results.length === 0 || results.length < limit)) {
this.allowLoadMore = false;
} else {
this.offset += limit;
}
if (results && (results.length === 0 || results.length < limit)) {
this.allowLoadMore = false;
} else {
this.offset += limit;
}
this.renderCount += limit;
// only the most recent fetch should end the loading state
if (counter >= this.fetchCounter) {
this.isFetching = false;
this.isFetchingMore = false;
this.renderCount += limit;
} catch (err) {
this.error = err;
} finally {
// only the most recent fetch should end the loading state
if (counter >= this.fetchCounter) {
this.isFetching = false;
this.isFetchingMore = false;
}
}
};
@@ -138,6 +151,7 @@ class PaginatedList<T extends PaginatedItem> extends React.Component<Props<T>> {
auth,
empty = null,
renderHeading,
renderError,
onEscape,
} = this.props;
@@ -157,6 +171,10 @@ class PaginatedList<T extends PaginatedItem> extends React.Component<Props<T>> {
}
if (items?.length === 0) {
if (this.error && renderError) {
return renderError({ error: this.error, retry: this.fetchResults });
}
return empty;
}
+8 -4
View File
@@ -10,6 +10,7 @@ import Scrollable from "~/components/Scrollable";
import Text from "~/components/Text";
import { inviteUser } from "~/actions/definitions/users";
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";
@@ -34,12 +35,15 @@ function AppSidebar() {
const { t } = useTranslation();
const { documents } = useStores();
const team = useCurrentTeam();
const can = usePolicy(team.id);
const user = useCurrentUser();
const can = usePolicy(team);
React.useEffect(() => {
documents.fetchDrafts();
documents.fetchTemplates();
}, [documents]);
if (!user.isViewer) {
documents.fetchDrafts();
documents.fetchTemplates();
}
}, [documents, user.isViewer]);
const [dndArea, setDndArea] = React.useState();
const handleSidebarRef = React.useCallback((node) => setDndArea(node), []);
@@ -44,7 +44,7 @@ const CollectionLink: React.FC<Props> = ({
const { dialogs, documents, collections } = useStores();
const [menuOpen, handleMenuOpen, handleMenuClose] = useBoolean();
const [isEditing, setIsEditing] = React.useState(false);
const canUpdate = usePolicy(collection.id).update;
const canUpdate = usePolicy(collection).update;
const { t } = useTranslation();
const history = useHistory();
const inStarredSection = useStarredContext();
@@ -25,7 +25,7 @@ function CollectionLinkChildren({
expanded,
prefetchDocument,
}: Props) {
const can = usePolicy(collection.id);
const can = usePolicy(collection);
const { showToast } = useToasts();
const manualSort = collection.sort.field === "index";
const { documents } = useStores();
@@ -3,12 +3,13 @@ import { observer } from "mobx-react";
import * as React from "react";
import { useDrop } from "react-dnd";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
import Collection from "~/models/Collection";
import Fade from "~/components/Fade";
import Flex from "~/components/Flex";
import Error from "~/components/List/Error";
import PaginatedList from "~/components/PaginatedList";
import { createCollection } from "~/actions/definitions/collections";
import useStores from "~/hooks/useStores";
import useToasts from "~/hooks/useToasts";
import DraggableCollectionLink from "./DraggableCollectionLink";
import DropCursor from "./DropCursor";
import Header from "./Header";
@@ -18,39 +19,10 @@ import SidebarAction from "./SidebarAction";
import { DragObject } from "./SidebarLink";
function Collections() {
const [isFetching, setFetching] = React.useState(false);
const [fetchError, setFetchError] = React.useState();
const { documents, collections } = useStores();
const { showToast } = useToasts();
const isPreloaded = !!collections.orderedData.length;
const { t } = useTranslation();
const orderedCollections = collections.orderedData;
React.useEffect(() => {
async function load() {
if (!collections.isLoaded && !isFetching && !fetchError) {
try {
setFetching(true);
await collections.fetchPage({
limit: 100,
});
} catch (error) {
showToast(
t("Collections could not be loaded, please reload the app"),
{
type: "error",
}
);
setFetchError(error);
} finally {
setFetching(false);
}
}
}
load();
}, [collections, isFetching, showToast, fetchError, t]);
const [
{ isCollectionDropping, isDraggingAnyCollection },
dropToReorderCollection,
@@ -71,45 +43,46 @@ function Collections() {
}),
});
const content = (
<>
{isDraggingAnyCollection && (
<DropCursor
isActiveDrop={isCollectionDropping}
innerRef={dropToReorderCollection}
position="top"
/>
)}
{orderedCollections.map((collection: Collection, index: number) => (
<DraggableCollectionLink
key={collection.id}
collection={collection}
activeDocument={documents.active}
prefetchDocument={documents.prefetchDocument}
belowCollection={orderedCollections[index + 1]}
/>
))}
<SidebarAction action={createCollection} depth={0} />
</>
);
if (!collections.isLoaded || fetchError) {
return (
<Flex column>
<Header id="collections" title={t("Collections")}>
<PlaceholderCollections />
</Header>
</Flex>
);
}
return (
<Flex column>
<Header id="collections" title={t("Collections")}>
<Relative>{isPreloaded ? content : <Fade>{content}</Fade>}</Relative>
<Relative>
<PaginatedList
aria-label={t("Collections")}
items={collections.orderedData}
fetch={collections.fetchPage}
options={{ limit: 100 }}
loading={<PlaceholderCollections />}
heading={
isDraggingAnyCollection ? (
<DropCursor
isActiveDrop={isCollectionDropping}
innerRef={dropToReorderCollection}
position="top"
/>
) : undefined
}
renderError={(props) => <StyledError {...props} />}
renderItem={(item: Collection, index) => (
<DraggableCollectionLink
key={item.id}
collection={item}
activeDocument={documents.active}
prefetchDocument={documents.prefetchDocument}
belowCollection={orderedCollections[index + 1]}
/>
)}
/>
<SidebarAction action={createCollection} depth={0} />
</Relative>
</Header>
</Flex>
);
}
const StyledError = styled(Error)`
font-size: 15px;
padding: 0 8px;
`;
export default observer(Collections);
@@ -6,8 +6,8 @@ import { useDrag, useDrop } from "react-dnd";
import { useTranslation } from "react-i18next";
import { Link } from "react-router-dom";
import styled from "styled-components";
import { MAX_TITLE_LENGTH } from "@shared/constants";
import { sortNavigationNodes } from "@shared/utils/collections";
import { DocumentValidation } from "@shared/validations";
import Collection from "~/models/Collection";
import Document from "~/models/Document";
import Fade from "~/components/Fade";
@@ -319,7 +319,7 @@ function InnerDocumentLink(
onSubmit={handleTitleChange}
onEditing={handleTitleEditing}
canUpdate={canUpdate}
maxLength={MAX_TITLE_LENGTH}
maxLength={DocumentValidation.maxTitleLength}
/>
}
isActive={(match, location: Location<{ starred?: boolean }>) =>
@@ -39,7 +39,7 @@ function DraggableCollectionLink({
const [expanded, setExpanded] = React.useState(
collection.id === ui.activeCollectionId && !locationStateStarred
);
const can = usePolicy(collection.id);
const can = usePolicy(collection);
const belowCollectionIndex = belowCollection ? belowCollection.index : null;
// Drop to reorder collection
@@ -2,7 +2,7 @@
// This file is pulled almost 100% from react-router with the addition of one
// thing, automatic scroll to the active link. It's worth the copy paste because
// it avoids recalculating the link match again.
import { Location, createLocation } from "history";
import { Location, createLocation, LocationDescriptor } from "history";
import * as React from "react";
import {
__RouterContext as RouterContext,
@@ -13,12 +13,12 @@ import { Link } from "react-router-dom";
import scrollIntoView from "smooth-scroll-into-view-if-needed";
const resolveToLocation = (
to: string | Record<string, any>,
to: LocationDescriptor | ((location: Location) => LocationDescriptor),
currentLocation: Location
) => (typeof to === "function" ? to(currentLocation) : to);
const normalizeToLocation = (
to: string | Record<string, any>,
to: LocationDescriptor,
currentLocation: Location
) => {
return typeof to === "string"
@@ -30,17 +30,15 @@ const joinClassnames = (...classnames: (string | undefined)[]) => {
return classnames.filter((i) => i).join(" ");
};
export type Props = React.HTMLAttributes<HTMLAnchorElement> & {
export type Props = React.AnchorHTMLAttributes<HTMLAnchorElement> & {
activeClassName?: string;
activeStyle?: React.CSSProperties;
className?: string;
scrollIntoViewIfNeeded?: boolean;
exact?: boolean;
isActive?: (match: match | null, location: Location) => boolean;
location?: Location;
strict?: boolean;
style?: React.CSSProperties;
to: string | Record<string, any>;
to: LocationDescriptor;
};
/**
@@ -1,3 +1,4 @@
import { LocationDescriptor } from "history";
import * as React from "react";
import styled, { useTheme, css } from "styled-components";
import breakpoint from "styled-components-breakpoint";
@@ -14,8 +15,7 @@ export type DragObject = NavigationNode & {
};
type Props = Omit<NavLinkProps, "to"> & {
to?: string | Record<string, any>;
href?: string | Record<string, any>;
to?: LocationDescriptor;
innerRef?: (ref: HTMLElement | null | undefined) => void;
onClick?: React.MouseEventHandler<HTMLAnchorElement>;
onMouseEnter?: React.MouseEventHandler<HTMLAnchorElement>;
@@ -32,6 +32,7 @@ export default function Version() {
return (
<SidebarLink
target="_blank"
href="https://github.com/outline/outline/releases"
label={
<>
-387
View File
@@ -1,387 +0,0 @@
import invariant from "invariant";
import { find } from "lodash";
import { observable } from "mobx";
import { observer } from "mobx-react";
import * as React from "react";
import io from "socket.io-client";
import RootStore from "~/stores/RootStore";
import withStores from "~/components/withStores";
import { getVisibilityListener, getPageVisible } from "~/utils/pageVisibility";
type SocketWithAuthentication = {
authenticated?: boolean;
disconnected: boolean;
disconnect: () => void;
close: () => void;
on: (event: string, callback: (data: any) => void) => void;
emit: (event: string, data: any) => void;
io: any;
};
export const SocketContext: any = React.createContext<SocketWithAuthentication | null>(
null
);
type Props = RootStore;
@observer
class SocketProvider extends React.Component<Props> {
@observable
socket: SocketWithAuthentication | null;
componentDidMount() {
this.createConnection();
document.addEventListener(getVisibilityListener(), this.checkConnection);
}
componentWillUnmount() {
if (this.socket) {
this.socket.authenticated = false;
this.socket.disconnect();
}
document.removeEventListener(getVisibilityListener(), this.checkConnection);
}
checkConnection = () => {
if (this.socket?.disconnected && getPageVisible()) {
// null-ifying this reference is important, do not remove. Without it
// references to old sockets are potentially held in context
this.socket.close();
this.socket = null;
this.createConnection();
}
};
createConnection = () => {
this.socket = io(window.location.origin, {
path: "/realtime",
transports: ["websocket"],
reconnectionDelay: 1000,
reconnectionDelayMax: 30000,
});
invariant(this.socket, "Socket should be defined");
this.socket.authenticated = false;
const {
auth,
toasts,
documents,
collections,
groups,
pins,
stars,
memberships,
policies,
presence,
views,
fileOperations,
} = this.props;
if (!auth.token) {
return;
}
this.socket.on("connect", () => {
// immediately send current users token to the websocket backend where it
// is verified, if all goes well an 'authenticated' message will be
// received in response
this.socket?.emit("authentication", {
token: auth.token,
});
});
this.socket.on("disconnect", () => {
// when the socket is disconnected we need to clear all presence state as
// it's no longer reliable.
presence.clear();
});
// on reconnection, reset the transports option, as the Websocket
// connection may have failed (caused by proxy, firewall, browser, ...)
this.socket.on("reconnect_attempt", () => {
if (this.socket) {
this.socket.io.opts.transports = auth?.team?.domain
? ["websocket"]
: ["websocket", "polling"];
}
});
this.socket.on("authenticated", () => {
if (this.socket) {
this.socket.authenticated = true;
}
});
this.socket.on("unauthorized", (err: Error) => {
if (this.socket) {
this.socket.authenticated = false;
}
toasts.showToast(err.message, {
type: "error",
});
throw err;
});
this.socket.on("entities", async (event: any) => {
if (event.documentIds) {
for (const documentDescriptor of event.documentIds) {
const documentId = documentDescriptor.id;
let document = documents.get(documentId) || {};
if (event.event === "documents.delete") {
const document = documents.get(documentId);
if (document) {
document.deletedAt = documentDescriptor.updatedAt;
}
policies.remove(documentId);
continue;
}
// if we already have the latest version (it was us that performed
// the change) then we don't need to update anything either.
// @ts-expect-error ts-migrate(2339) FIXME: Property 'title' does not exist on type '{}'.
const { title, updatedAt } = document;
if (updatedAt === documentDescriptor.updatedAt) {
continue;
}
// otherwise, grab the latest version of the document
try {
document = await documents.fetch(documentId, {
force: true,
});
} catch (err) {
if (err.statusCode === 404 || err.statusCode === 403) {
documents.remove(documentId);
return;
}
}
// if the title changed then we need to update the collection also
// @ts-expect-error ts-migrate(2339) FIXME: Property 'title' does not exist on type '{}'.
if (title !== document.title) {
if (!event.collectionIds) {
event.collectionIds = [];
}
const existing = find(event.collectionIds, {
// @ts-expect-error ts-migrate(2339) FIXME: Property 'collectionId' does not exist on type '{}... Remove this comment to see the full error message
id: document.collectionId,
});
if (!existing) {
event.collectionIds.push({
// @ts-expect-error ts-migrate(2339) FIXME: Property 'collectionId' does not exist on type '{}... Remove this comment to see the full error message
id: document.collectionId,
});
}
}
}
}
if (event.collectionIds) {
for (const collectionDescriptor of event.collectionIds) {
const collectionId = collectionDescriptor.id;
const collection = collections.get(collectionId);
if (event.event === "collections.delete") {
if (collection) {
collection.deletedAt = collectionDescriptor.updatedAt;
}
const deletedDocuments = documents.inCollection(collectionId);
deletedDocuments.forEach((doc) => {
doc.deletedAt = collectionDescriptor.updatedAt;
policies.remove(doc.id);
});
documents.removeCollectionDocuments(collectionId);
memberships.removeCollectionMemberships(collectionId);
collections.remove(collectionId);
policies.remove(collectionId);
continue;
}
// if we already have the latest version (it was us that performed
// the change) then we don't need to update anything either.
if (collection?.updatedAt === collectionDescriptor.updatedAt) {
continue;
}
try {
await collections.fetch(collectionId, {
force: true,
});
} catch (err) {
if (err.statusCode === 404 || err.statusCode === 403) {
documents.removeCollectionDocuments(collectionId);
memberships.removeCollectionMemberships(collectionId);
collections.remove(collectionId);
policies.remove(collectionId);
return;
}
}
}
}
if (event.groupIds) {
for (const groupDescriptor of event.groupIds) {
const groupId = groupDescriptor.id;
const group = groups.get(groupId) || {};
// if we already have the latest version (it was us that performed
// the change) then we don't need to update anything either.
// @ts-expect-error ts-migrate(2339) FIXME: Property 'updatedAt' does not exist on type '{}'.
const { updatedAt } = group;
if (updatedAt === groupDescriptor.updatedAt) {
continue;
}
try {
await groups.fetch(groupId, {
force: true,
});
} catch (err) {
if (err.statusCode === 404 || err.statusCode === 403) {
groups.remove(groupId);
}
}
}
}
if (event.teamIds) {
await auth.fetch();
}
});
this.socket.on("pins.create", (event: any) => {
pins.add(event);
});
this.socket.on("pins.update", (event: any) => {
pins.add(event);
});
this.socket.on("pins.delete", (event: any) => {
pins.remove(event.modelId);
});
this.socket.on("stars.create", (event: any) => {
stars.add(event);
});
this.socket.on("stars.update", (event: any) => {
stars.add(event);
});
this.socket.on("stars.delete", (event: any) => {
stars.remove(event.modelId);
});
this.socket.on("documents.permanent_delete", (event: any) => {
documents.remove(event.documentId);
});
// received when a user is given access to a collection
// if the user is us then we go ahead and load the collection from API.
this.socket.on("collections.add_user", (event: any) => {
if (auth.user && event.userId === auth.user.id) {
collections.fetch(event.collectionId, {
force: true,
});
}
// Document policies might need updating as the permission changes
documents.inCollection(event.collectionId).forEach((document) => {
policies.remove(document.id);
});
});
// received when a user is removed from having access to a collection
// to keep state in sync we must update our UI if the user is us,
// or otherwise just remove any membership state we have for that user.
this.socket.on("collections.remove_user", (event: any) => {
if (auth.user && event.userId === auth.user.id) {
collections.remove(event.collectionId);
memberships.removeCollectionMemberships(event.collectionId);
documents.removeCollectionDocuments(event.collectionId);
} else {
memberships.remove(`${event.userId}-${event.collectionId}`);
}
});
this.socket.on("collections.update_index", (event: any) => {
const collection = collections.get(event.collectionId);
if (collection) {
collection.updateIndex(event.index);
}
});
this.socket.on("fileOperations.create", async (event: any) => {
const user = auth.user;
if (user) {
fileOperations.add({ ...event, user });
}
});
this.socket.on("fileOperations.update", async (event: any) => {
const user = auth.user;
if (user) {
fileOperations.add({ ...event, user });
}
});
// received a message from the API server that we should request
// to join a specific room. Forward that to the ws server.
this.socket.on("join", (event: any) => {
this.socket?.emit("join", event);
});
// received a message from the API server that we should request
// to leave a specific room. Forward that to the ws server.
this.socket.on("leave", (event: any) => {
this.socket?.emit("leave", event);
});
// received whenever we join a document room, the payload includes
// userIds that are present/viewing and those that are editing.
this.socket.on("document.presence", (event: any) => {
presence.init(event.documentId, event.userIds, event.editingIds);
});
// received whenever a new user joins a document room, aka they
// navigate to / start viewing a document
this.socket.on("user.join", (event: any) => {
presence.touch(event.documentId, event.userId, event.isEditing);
views.touch(event.documentId, event.userId);
});
// received whenever a new user leaves a document room, aka they
// navigate away / stop viewing a document
this.socket.on("user.leave", (event: any) => {
presence.leave(event.documentId, event.userId);
views.touch(event.documentId, event.userId);
});
// received when another client in a document room wants to change
// or update it's presence. Currently the only property is whether
// the client is in editing state or not.
this.socket.on("user.presence", (event: any) => {
presence.touch(event.documentId, event.userId, event.isEditing);
});
};
render() {
return (
<SocketContext.Provider value={this.socket}>
{this.props.children}
</SocketContext.Provider>
);
}
}
export default withStores(SocketProvider);
+3 -6
View File
@@ -1,17 +1,14 @@
import { m } from "framer-motion";
import * as React from "react";
import styled, { useTheme } from "styled-components";
import NavLinkWithChildrenFunc from "~/components/NavLink";
import NavLink from "~/components/NavLink";
type Props = Omit<
React.ComponentProps<typeof NavLinkWithChildrenFunc>,
"children"
> & {
type Props = Omit<React.ComponentProps<typeof NavLink>, "children"> & {
to: string;
exact?: boolean;
};
const TabLink = styled(NavLinkWithChildrenFunc)`
const TabLink = styled(NavLink)`
position: relative;
display: inline-flex;
align-items: center;
+2 -1
View File
@@ -1,3 +1,4 @@
import { observer } from "mobx-react";
import * as React from "react";
import { useHistory, useLocation } from "react-router-dom";
import scrollIntoView from "smooth-scroll-into-view-if-needed";
@@ -72,4 +73,4 @@ const TableFromParams = (
);
};
export default TableFromParams;
export default observer(TableFromParams);
@@ -1,12 +1,7 @@
import Tippy, { TippyProps } from "@tippy.js/react";
import { TFunctionResult } from "i18next";
import Tippy from "@tippy.js/react";
import * as React from "react";
import styled from "styled-components";
export type Props = Omit<TippyProps, "content" | "theme"> & {
tooltip: React.ReactChild | React.ReactChild[] | TFunctionResult;
shortcut?: React.ReactNode;
};
import { Props } from ".";
function Tooltip({ shortcut, tooltip, delay = 50, ...rest }: Props) {
let content = <>{tooltip}</>;
+22
View File
@@ -0,0 +1,22 @@
import type { TippyProps } from "@tippy.js/react";
import { TFunctionResult } from "i18next";
import React from "react";
export type Props = Omit<TippyProps, "content" | "theme"> & {
tooltip: React.ReactChild | React.ReactChild[] | TFunctionResult;
shortcut?: React.ReactNode;
};
const LazyTooltip = React.lazy(() => {
return import(/* webpackChunkName: "tooltip" */ "./Tooltip");
});
const Tooltip = (props: Props) => {
return (
<React.Suspense fallback={null}>
<LazyTooltip {...props} />
</React.Suspense>
);
};
export default Tooltip;
+448
View File
@@ -0,0 +1,448 @@
import invariant from "invariant";
import { find } from "lodash";
import { action, observable } from "mobx";
import { observer } from "mobx-react";
import * as React from "react";
import { io, Socket } from "socket.io-client";
import RootStore from "~/stores/RootStore";
import Collection from "~/models/Collection";
import Document from "~/models/Document";
import FileOperation from "~/models/FileOperation";
import Group from "~/models/Group";
import Pin from "~/models/Pin";
import Star from "~/models/Star";
import Subscription from "~/models/Subscription";
import Team from "~/models/Team";
import withStores from "~/components/withStores";
import {
PartialWithId,
WebsocketCollectionUpdateIndexEvent,
WebsocketCollectionUserEvent,
WebsocketEntitiesEvent,
WebsocketEntityDeletedEvent,
} from "~/types";
import { AuthorizationError, NotFoundError } from "~/utils/errors";
import { getVisibilityListener, getPageVisible } from "~/utils/pageVisibility";
type SocketWithAuthentication = Socket & {
authenticated?: boolean;
};
export const WebsocketContext = React.createContext<SocketWithAuthentication | null>(
null
);
type Props = RootStore;
@observer
class WebsocketProvider extends React.Component<Props> {
@observable
socket: SocketWithAuthentication | null;
componentDidMount() {
this.createConnection();
document.addEventListener(getVisibilityListener(), this.checkConnection);
}
componentWillUnmount() {
if (this.socket) {
this.socket.authenticated = false;
this.socket.disconnect();
}
document.removeEventListener(getVisibilityListener(), this.checkConnection);
}
checkConnection = () => {
if (this.socket?.disconnected && getPageVisible()) {
// null-ifying this reference is important, do not remove. Without it
// references to old sockets are potentially held in context
this.socket.close();
this.socket = null;
this.createConnection();
}
};
createConnection = () => {
this.socket = io(window.location.origin, {
path: "/realtime",
transports: ["websocket"],
reconnectionDelay: 1000,
reconnectionDelayMax: 30000,
});
invariant(this.socket, "Socket should be defined");
this.socket.authenticated = false;
const {
auth,
toasts,
documents,
collections,
groups,
pins,
stars,
memberships,
policies,
presence,
views,
subscriptions,
fileOperations,
} = this.props;
if (!auth.token) {
return;
}
this.socket.on("connect", () => {
// immediately send current users token to the websocket backend where it
// is verified, if all goes well an 'authenticated' message will be
// received in response
this.socket?.emit("authentication", {
token: auth.token,
});
});
this.socket.on("disconnect", () => {
// when the socket is disconnected we need to clear all presence state as
// it's no longer reliable.
presence.clear();
});
// on reconnection, reset the transports option, as the Websocket
// connection may have failed (caused by proxy, firewall, browser, ...)
this.socket.io.on("reconnect_attempt", () => {
if (this.socket) {
this.socket.io.opts.transports = auth?.team?.domain
? ["websocket"]
: ["websocket", "polling"];
}
});
this.socket.on("authenticated", () => {
if (this.socket) {
this.socket.authenticated = true;
}
});
this.socket.on("unauthorized", (err: Error) => {
if (this.socket) {
this.socket.authenticated = false;
}
toasts.showToast(err.message, {
type: "error",
});
throw err;
});
this.socket.on(
"entities",
action(async (event: WebsocketEntitiesEvent) => {
if (event.documentIds) {
for (const documentDescriptor of event.documentIds) {
const documentId = documentDescriptor.id;
let document = documents.get(documentId);
const previousTitle = document?.title;
// if we already have the latest version (it was us that performed
// the change) then we don't need to update anything either.
if (document?.updatedAt === documentDescriptor.updatedAt) {
continue;
}
// otherwise, grab the latest version of the document
try {
document = await documents.fetch(documentId, {
force: true,
});
} catch (err) {
if (
err instanceof AuthorizationError ||
err instanceof NotFoundError
) {
documents.remove(documentId);
return;
}
}
// if the title changed then we need to update the collection also
if (document && previousTitle !== document.title) {
if (!event.collectionIds) {
event.collectionIds = [];
}
const existing = find(event.collectionIds, {
id: document.collectionId,
});
if (!existing) {
event.collectionIds.push({
id: document.collectionId,
});
}
}
}
}
if (event.collectionIds) {
for (const collectionDescriptor of event.collectionIds) {
const collectionId = collectionDescriptor.id;
const collection = collections.get(collectionId);
// if we already have the latest version (it was us that performed
// the change) then we don't need to update anything either.
if (collection?.updatedAt === collectionDescriptor.updatedAt) {
continue;
}
try {
await collections.fetch(collectionId, {
force: true,
});
} catch (err) {
if (
err instanceof AuthorizationError ||
err instanceof NotFoundError
) {
documents.removeCollectionDocuments(collectionId);
memberships.removeCollectionMemberships(collectionId);
collections.remove(collectionId);
policies.remove(collectionId);
return;
}
}
}
}
})
);
this.socket.on(
"documents.update",
action(
(event: PartialWithId<Document> & { title: string; url: string }) => {
documents.add(event);
if (event.collectionId) {
const collection = collections.get(event.collectionId);
collection?.updateDocument(event);
}
}
)
);
this.socket.on(
"documents.archive",
action((event: PartialWithId<Document>) => {
documents.add(event);
policies.remove(event.id);
if (event.collectionId) {
const collection = collections.get(event.collectionId);
collection?.removeDocument(event.id);
}
})
);
this.socket.on(
"documents.delete",
action((event: PartialWithId<Document>) => {
documents.add(event);
policies.remove(event.id);
if (event.collectionId) {
const collection = collections.get(event.collectionId);
collection?.removeDocument(event.id);
}
})
);
this.socket.on(
"documents.permanent_delete",
(event: WebsocketEntityDeletedEvent) => {
documents.remove(event.modelId);
}
);
this.socket.on("groups.create", (event: PartialWithId<Group>) => {
groups.add(event);
});
this.socket.on("groups.update", (event: PartialWithId<Group>) => {
groups.add(event);
});
this.socket.on("groups.delete", (event: WebsocketEntityDeletedEvent) => {
groups.remove(event.modelId);
});
this.socket.on("collections.create", (event: PartialWithId<Collection>) => {
collections.add(event);
});
this.socket.on(
"collections.delete",
action((event: WebsocketEntityDeletedEvent) => {
const collectionId = event.modelId;
const deletedAt = new Date().toISOString();
const deletedDocuments = documents.inCollection(collectionId);
deletedDocuments.forEach((doc) => {
doc.deletedAt = deletedAt;
policies.remove(doc.id);
});
documents.removeCollectionDocuments(collectionId);
memberships.removeCollectionMemberships(collectionId);
collections.remove(collectionId);
policies.remove(collectionId);
})
);
this.socket.on("teams.update", (event: PartialWithId<Team>) => {
auth.updateTeam(event);
});
this.socket.on("pins.create", (event: PartialWithId<Pin>) => {
pins.add(event);
});
this.socket.on("pins.update", (event: PartialWithId<Pin>) => {
pins.add(event);
});
this.socket.on("pins.delete", (event: WebsocketEntityDeletedEvent) => {
pins.remove(event.modelId);
});
this.socket.on("stars.create", (event: PartialWithId<Star>) => {
stars.add(event);
});
this.socket.on("stars.update", (event: PartialWithId<Star>) => {
stars.add(event);
});
this.socket.on("stars.delete", (event: WebsocketEntityDeletedEvent) => {
stars.remove(event.modelId);
});
// received when a user is given access to a collection
// if the user is us then we go ahead and load the collection from API.
this.socket.on(
"collections.add_user",
action((event: WebsocketCollectionUserEvent) => {
if (auth.user && event.userId === auth.user.id) {
collections.fetch(event.collectionId, {
force: true,
});
}
// Document policies might need updating as the permission changes
documents.inCollection(event.collectionId).forEach((document) => {
policies.remove(document.id);
});
})
);
// received when a user is removed from having access to a collection
// to keep state in sync we must update our UI if the user is us,
// or otherwise just remove any membership state we have for that user.
this.socket.on(
"collections.remove_user",
action((event: WebsocketCollectionUserEvent) => {
if (auth.user && event.userId === auth.user.id) {
collections.remove(event.collectionId);
memberships.removeCollectionMemberships(event.collectionId);
documents.removeCollectionDocuments(event.collectionId);
} else {
memberships.remove(`${event.userId}-${event.collectionId}`);
}
})
);
this.socket.on(
"collections.update_index",
action((event: WebsocketCollectionUpdateIndexEvent) => {
const collection = collections.get(event.collectionId);
if (collection) {
collection.updateIndex(event.index);
}
})
);
this.socket.on(
"fileOperations.create",
(event: PartialWithId<FileOperation>) => {
fileOperations.add(event);
}
);
this.socket.on(
"fileOperations.update",
(event: PartialWithId<FileOperation>) => {
fileOperations.add(event);
}
);
this.socket.on(
"subscriptions.create",
(event: PartialWithId<Subscription>) => {
subscriptions.add(event);
}
);
this.socket.on(
"subscriptions.delete",
(event: WebsocketEntityDeletedEvent) => {
subscriptions.remove(event.modelId);
}
);
// received a message from the API server that we should request
// to join a specific room. Forward that to the ws server.
this.socket.on("join", (event: any) => {
this.socket?.emit("join", event);
});
// received a message from the API server that we should request
// to leave a specific room. Forward that to the ws server.
this.socket.on("leave", (event: any) => {
this.socket?.emit("leave", event);
});
// received whenever we join a document room, the payload includes
// userIds that are present/viewing and those that are editing.
this.socket.on("document.presence", (event: any) => {
presence.init(event.documentId, event.userIds, event.editingIds);
});
// received whenever a new user joins a document room, aka they
// navigate to / start viewing a document
this.socket.on("user.join", (event: any) => {
presence.touch(event.documentId, event.userId, event.isEditing);
views.touch(event.documentId, event.userId);
});
// received whenever a new user leaves a document room, aka they
// navigate away / stop viewing a document
this.socket.on("user.leave", (event: any) => {
presence.leave(event.documentId, event.userId);
views.touch(event.documentId, event.userId);
});
// received when another client in a document room wants to change
// or update it's presence. Currently the only property is whether
// the client is in editing state or not.
this.socket.on("user.presence", (event: any) => {
presence.touch(event.documentId, event.userId, event.isEditing);
});
};
render() {
return (
<WebsocketContext.Provider value={this.socket}>
{this.props.children}
</WebsocketContext.Provider>
);
}
}
export default withStores(WebsocketProvider);
+3 -5
View File
@@ -6,15 +6,13 @@ import useStores from "~/hooks/useStores";
type StoreProps = keyof RootStore;
function withStores<
P extends React.ComponentType<React.ComponentProps<P> & RootStore>,
P extends React.ComponentType<ResolvedProps & RootStore>,
ResolvedProps = JSX.LibraryManagedAttributes<
P,
Omit<React.ComponentProps<P>, StoreProps>
>
>(WrappedComponent: P): React.FC<Omit<ResolvedProps, StoreProps>> {
const ComponentWithStore = (
props: Omit<React.ComponentProps<P>, StoreProps>
) => {
>(WrappedComponent: P): React.FC<ResolvedProps> {
const ComponentWithStore = (props: ResolvedProps) => {
const stores = useStores();
return <WrappedComponent {...(props as any)} {...stores} />;
};
+17 -12
View File
@@ -7,12 +7,13 @@ import { Portal } from "react-portal";
import { VisuallyHidden } from "reakit/VisuallyHidden";
import styled from "styled-components";
import insertFiles from "@shared/editor/commands/insertFiles";
import { EmbedDescriptor } from "@shared/editor/embeds";
import { CommandFactory } from "@shared/editor/lib/Extension";
import filterExcessSeparators from "@shared/editor/lib/filterExcessSeparators";
import { EmbedDescriptor, MenuItem } from "@shared/editor/types";
import { MenuItem } from "@shared/editor/types";
import { depths } from "@shared/styles";
import { supportedImageMimeTypes } from "@shared/utils/files";
import getDataTransferFiles from "@shared/utils/getDataTransferFiles";
import { getEventFiles } from "@shared/utils/files";
import { AttachmentValidation } from "@shared/validations";
import Scrollable from "~/components/Scrollable";
import { Dictionary } from "~/hooks/useDictionary";
import Input from "./Input";
@@ -36,7 +37,7 @@ export type Props<T extends MenuItem = MenuItem> = {
onFileUploadStop?: () => void;
onShowToast: (message: string) => void;
onLinkToolbarOpen?: () => void;
onClose: () => void;
onClose: (insertNewLine?: boolean) => void;
onClearSearch: () => void;
embeds?: EmbedDescriptor[];
renderMenuItem: (
@@ -123,7 +124,7 @@ class CommandMenu<T = MenuItem> extends React.Component<Props<T>, State> {
if (item) {
this.insertItem(item);
} else {
this.props.onClose();
this.props.onClose(true);
}
}
@@ -182,7 +183,9 @@ class CommandMenu<T = MenuItem> extends React.Component<Props<T>, State> {
insertItem = (item: any) => {
switch (item.name) {
case "image":
return this.triggerFilePick(supportedImageMimeTypes.join(", "));
return this.triggerFilePick(
AttachmentValidation.imageContentTypes.join(", ")
);
case "attachment":
return this.triggerFilePick("*");
case "embed":
@@ -275,7 +278,7 @@ class CommandMenu<T = MenuItem> extends React.Component<Props<T>, State> {
};
handleFilePicked = (event: React.ChangeEvent<HTMLInputElement>) => {
const files = getDataTransferFiles(event);
const files = getEventFiles(event);
const {
view,
@@ -424,11 +427,13 @@ class CommandMenu<T = MenuItem> extends React.Component<Props<T>, State> {
const embedItems: EmbedDescriptor[] = [];
for (const embed of embeds) {
if (embed.title && embed.icon) {
embedItems.push({
...embed,
name: "embed",
});
if (embed.title) {
embedItems.push(
new EmbedDescriptor({
...embed,
name: "embed",
})
);
}
}
+10 -16
View File
@@ -11,8 +11,7 @@ import { setTextSelection } from "prosemirror-utils";
import { EditorView } from "prosemirror-view";
import * as React from "react";
import styled from "styled-components";
import isUrl from "@shared/editor/lib/isUrl";
import { isInternalUrl } from "@shared/utils/urls";
import { isInternalUrl, sanitizeUrl } from "@shared/utils/urls";
import Flex from "~/components/Flex";
import { Dictionary } from "~/hooks/useDictionary";
import { ToastOptions } from "~/types";
@@ -45,7 +44,7 @@ type Props = {
href: string,
event: React.MouseEvent<HTMLButtonElement>
) => void;
onShowToast: (message: string, options: ToastOptions) => void;
onShowToast: (message: string, options?: ToastOptions) => void;
view: EditorView;
};
@@ -71,7 +70,7 @@ class LinkEditor extends React.Component<Props, State> {
};
get href(): string {
return this.props.mark ? this.props.mark.attrs.href : "";
return sanitizeUrl(this.props.mark?.attrs.href) ?? "";
}
get suggestedLinkTitle(): string {
@@ -114,17 +113,7 @@ class LinkEditor extends React.Component<Props, State> {
this.discardInputValue = true;
const { from, to } = this.props;
// Make sure a protocol is added to the beginning of the input if it's
// likely an absolute URL that was entered without one.
if (
!isUrl(href) &&
!href.startsWith("/") &&
!href.startsWith("#") &&
!href.startsWith("mailto:")
) {
href = `https://${href}`;
}
href = sanitizeUrl(href) ?? "";
this.props.onSelectLink({ href, title, from, to });
};
@@ -240,7 +229,12 @@ class LinkEditor extends React.Component<Props, State> {
handleOpenLink = (event: React.MouseEvent<HTMLButtonElement>): void => {
event.preventDefault();
this.props.onClickLink(this.href, event);
try {
this.props.onClickLink(this.href, event);
} catch (err) {
this.props.onShowToast(this.props.dictionary.openLinkError);
}
};
handleCreateLink = async (value: string) => {
+91 -10
View File
@@ -1,6 +1,7 @@
/* eslint-disable no-irregular-whitespace */
import { lighten, transparentize } from "polished";
import { darken, lighten, transparentize } from "polished";
import styled from "styled-components";
import { depths } from "@shared/styles";
const EditorStyles = styled.div<{
rtl: boolean;
@@ -62,6 +63,15 @@ const EditorStyles = styled.div<{
margin-bottom: 0.25em;
}
// all of heading sizes are stepped down one from global styles, except h1
// which is between h1 and h2
h1 { font-size: 1.75em; }
h2 { font-size: 1.25em; }
h3 { font-size: 1em; }
h4 { font-size: 0.875em; }
h5 { font-size: 0.75em; }
h6 { font-size: 0.75em; }
.ProseMirror-yjs-cursor {
position: relative;
margin-left: -1px;
@@ -359,6 +369,7 @@ const EditorStyles = styled.div<{
.heading-actions {
opacity: 0;
z-index: ${depths.editorHeadingActions};
background: ${(props) => props.theme.background};
margin-${(props) => (props.rtl ? "right" : "left")}: -26px;
flex-direction: ${(props) => (props.rtl ? "row-reverse" : "row")};
@@ -405,6 +416,7 @@ const EditorStyles = styled.div<{
&.collapsed {
svg {
transform: rotate(${(props) => (props.rtl ? "90deg" : "-90deg")});
pointer-events: none;
}
transition-delay: 0.1s;
opacity: 1;
@@ -773,20 +785,45 @@ const EditorStyles = styled.div<{
select,
button {
background: ${(props) => props.theme.background};
color: ${(props) => props.theme.text};
border-width: 1px;
font-size: 13px;
display: none;
margin: 0;
padding: 0;
border: 0;
background: ${(props) => props.theme.buttonNeutralBackground};
color: ${(props) => props.theme.buttonNeutralText};
box-shadow: rgba(0, 0, 0, 0.07) 0px 1px 2px, ${(props) =>
props.theme.buttonNeutralBorder} 0 0 0 1px inset;
border-radius: 4px;
padding: 2px 4px;
height: 18px;
font-size: 13px;
font-weight: 500;
text-decoration: none;
flex-shrink: 0;
cursor: pointer;
user-select: none;
appearance: none !important;
padding: 6px 8px;
display: none;
&::-moz-focus-inner {
padding: 0;
border: 0;
}
&:hover:not(:disabled) {
background-color: ${(props) =>
darken(0.05, props.theme.buttonNeutralBackground)};
box-shadow: rgba(0, 0, 0, 0.07) 0px 1px 2px, ${(props) =>
props.theme.buttonNeutralBorder} 0 0 0 1px inset;
}
}
button {
padding: 2px 4px;
select {
background-image: url('data:image/svg+xml;utf8,<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" clip-rule="evenodd" d="M9.03087 9C8.20119 9 7.73238 9.95209 8.23824 10.6097L11.2074 14.4696C11.6077 14.99 12.3923 14.99 12.7926 14.4696L15.7618 10.6097C16.2676 9.95209 15.7988 9 14.9691 9L9.03087 9Z" fill="currentColor"/> </svg>');
background-repeat: no-repeat;
background-position: center right;
padding-right: 20px;
}
&:focus-within,
&:hover {
select {
display: ${(props) => (props.readOnly ? "none" : "inline")};
@@ -803,6 +840,49 @@ const EditorStyles = styled.div<{
button:active {
display: inline;
}
button.show-source-button {
display: none;
}
button.show-diagram-button {
display: inline;
}
&.code-hidden {
button,
select,
button.show-diagram-button {
display: none;
}
button.show-source-button {
display: inline;
}
pre {
display: none;
}
}
}
.mermaid-diagram-wrapper {
display: flex;
align-items: center;
justify-content: center;
background: ${(props) => props.theme.codeBackground};
border-radius: 6px;
border: 1px solid ${(props) => props.theme.codeBorder};
padding: 8px;
user-select: none;
cursor: default;
* {
font-family: ${(props) => props.theme.fontFamily};
}
&.diagram-hidden {
display: none;
}
}
pre {
@@ -1195,6 +1275,7 @@ const EditorStyles = styled.div<{
.placeholder:before,
.block-menu-trigger,
.heading-actions,
button.show-source-button,
h1:not(.placeholder):before,
h2:not(.placeholder):before,
h3:not(.placeholder):before,
+15 -3
View File
@@ -16,6 +16,7 @@ import { EditorState, Selection, Plugin, Transaction } from "prosemirror-state";
import { Decoration, EditorView } from "prosemirror-view";
import * as React from "react";
import { DefaultTheme, ThemeProps } from "styled-components";
import { EmbedDescriptor } from "@shared/editor/embeds";
import Extension, { CommandFactory } from "@shared/editor/lib/Extension";
import ExtensionManager from "@shared/editor/lib/ExtensionManager";
import getHeadings from "@shared/editor/lib/getHeadings";
@@ -25,8 +26,10 @@ import Mark from "@shared/editor/marks/Mark";
import Node from "@shared/editor/nodes/Node";
import ReactNode from "@shared/editor/nodes/ReactNode";
import fullExtensionsPackage from "@shared/editor/packages/full";
import { EmbedDescriptor, EventType } from "@shared/editor/types";
import { EventType } from "@shared/editor/types";
import { IntegrationType } from "@shared/types";
import EventEmitter from "@shared/utils/events";
import Integration from "~/models/Integration";
import Flex from "~/components/Flex";
import { Dictionary } from "~/hooks/useDictionary";
import Logger from "~/utils/Logger";
@@ -110,6 +113,8 @@ export type Props = {
onShowToast: (message: string) => void;
className?: string;
style?: React.CSSProperties;
embedIntegrations?: Integration<IntegrationType.Embed>[];
};
type State = {
@@ -430,7 +435,7 @@ export class Editor extends React.PureComponent<
state: this.createState(this.props.value),
editable: () => !this.props.readOnly,
nodeViews: this.nodeViews,
dispatchTransaction: function (transaction) {
dispatchTransaction(transaction) {
// callback is bound to have the view instance as its this binding
const { state, transactions } = this.state.applyTransaction(
transaction
@@ -554,7 +559,14 @@ export class Editor extends React.PureComponent<
this.setState({ blockMenuOpen: true, blockMenuSearch: search });
};
private handleCloseBlockMenu = () => {
private handleCloseBlockMenu = (insertNewLine?: boolean) => {
if (insertNewLine) {
const transaction = this.view.state.tr.split(
this.view.state.selection.to
);
this.view.dispatch(transaction);
this.view.focus();
}
if (!this.state.blockMenuOpen) {
return;
}
+15 -9
View File
@@ -14,6 +14,7 @@ import {
} from "outline-icons";
import { EditorState } from "prosemirror-state";
import { isInTable } from "prosemirror-tables";
import isInCode from "@shared/editor/queries/isInCode";
import isInList from "@shared/editor/queries/isInList";
import isMarkActive from "@shared/editor/queries/isMarkActive";
import isNodeActive from "@shared/editor/queries/isNodeActive";
@@ -28,6 +29,7 @@ export default function formattingMenuItems(
const { schema } = state;
const isTable = isInTable(state);
const isList = isInList(state);
const isCode = isInCode(state);
const allowBlocks = !isTable && !isList;
return [
@@ -47,19 +49,21 @@ export default function formattingMenuItems(
tooltip: dictionary.strong,
icon: BoldIcon,
active: isMarkActive(schema.marks.strong),
visible: !isCode,
},
{
name: "strikethrough",
tooltip: dictionary.strikethrough,
icon: StrikethroughIcon,
active: isMarkActive(schema.marks.strikethrough),
visible: !isCode,
},
{
name: "highlight",
tooltip: dictionary.mark,
icon: HighlightIcon,
active: isMarkActive(schema.marks.highlight),
visible: !isTemplate,
visible: !isTemplate && !isCode,
},
{
name: "code_inline",
@@ -69,7 +73,7 @@ export default function formattingMenuItems(
},
{
name: "separator",
visible: allowBlocks,
visible: allowBlocks && !isCode,
},
{
name: "heading",
@@ -77,7 +81,7 @@ export default function formattingMenuItems(
icon: Heading1Icon,
active: isNodeActive(schema.nodes.heading, { level: 1 }),
attrs: { level: 1 },
visible: allowBlocks,
visible: allowBlocks && !isCode,
},
{
name: "heading",
@@ -85,7 +89,7 @@ export default function formattingMenuItems(
icon: Heading2Icon,
active: isNodeActive(schema.nodes.heading, { level: 2 }),
attrs: { level: 2 },
visible: allowBlocks,
visible: allowBlocks && !isCode,
},
{
name: "blockquote",
@@ -93,11 +97,11 @@ export default function formattingMenuItems(
icon: BlockQuoteIcon,
active: isNodeActive(schema.nodes.blockquote),
attrs: { level: 2 },
visible: allowBlocks,
visible: allowBlocks && !isCode,
},
{
name: "separator",
visible: allowBlocks || isList,
visible: (allowBlocks || isList) && !isCode,
},
{
name: "checkbox_list",
@@ -105,24 +109,25 @@ export default function formattingMenuItems(
icon: TodoListIcon,
keywords: "checklist checkbox task",
active: isNodeActive(schema.nodes.checkbox_list),
visible: allowBlocks || isList,
visible: (allowBlocks || isList) && !isCode,
},
{
name: "bullet_list",
tooltip: dictionary.bulletList,
icon: BulletedListIcon,
active: isNodeActive(schema.nodes.bullet_list),
visible: allowBlocks || isList,
visible: (allowBlocks || isList) && !isCode,
},
{
name: "ordered_list",
tooltip: dictionary.orderedList,
icon: OrderedListIcon,
active: isNodeActive(schema.nodes.ordered_list),
visible: allowBlocks || isList,
visible: (allowBlocks || isList) && !isCode,
},
{
name: "separator",
visible: !isCode,
},
{
name: "link",
@@ -130,6 +135,7 @@ export default function formattingMenuItems(
icon: LinkIcon,
active: isMarkActive(schema.marks.link),
attrs: { href: "" },
visible: !isCode,
},
];
}
+33 -5
View File
@@ -9,11 +9,14 @@ import {
LinkIcon,
TeamIcon,
BeakerIcon,
BuildingBlocksIcon,
DownloadIcon,
WebhooksIcon,
} from "outline-icons";
import React from "react";
import { useTranslation } from "react-i18next";
import Details from "~/scenes/Settings/Details";
import Drawio from "~/scenes/Settings/Drawio";
import Export from "~/scenes/Settings/Export";
import Features from "~/scenes/Settings/Features";
import Groups from "~/scenes/Settings/Groups";
@@ -25,6 +28,7 @@ import Security from "~/scenes/Settings/Security";
import Shares from "~/scenes/Settings/Shares";
import Slack from "~/scenes/Settings/Slack";
import Tokens from "~/scenes/Settings/Tokens";
import Webhooks from "~/scenes/Settings/Webhooks";
import Zapier from "~/scenes/Settings/Zapier";
import SlackIcon from "~/components/SlackIcon";
import ZapierIcon from "~/components/ZapierIcon";
@@ -46,6 +50,7 @@ type SettingsPage =
| "Shares"
| "Import"
| "Export"
| "Webhooks"
| "Slack"
| "Zapier";
@@ -64,7 +69,7 @@ type ConfigType = {
const useAuthorizedSettingsConfig = () => {
const team = useCurrentTeam();
const can = usePolicy(team.id);
const can = usePolicy(team);
const { t } = useTranslation();
const config: ConfigType = React.useMemo(
@@ -146,7 +151,7 @@ const useAuthorizedSettingsConfig = () => {
name: t("Import"),
path: "/settings/import",
component: Import,
enabled: can.manage,
enabled: can.createImport,
group: t("Team"),
icon: NewDocumentIcon,
},
@@ -154,11 +159,27 @@ const useAuthorizedSettingsConfig = () => {
name: t("Export"),
path: "/settings/export",
component: Export,
enabled: can.export,
enabled: can.createExport,
group: t("Team"),
icon: DownloadIcon,
},
// Intergrations
// Integrations
Webhooks: {
name: t("Webhooks"),
path: "/settings/webhooks",
component: Webhooks,
enabled: can.createWebhookSubscription,
group: t("Integrations"),
icon: WebhooksIcon,
},
Drawio: {
name: t("Draw.io"),
path: "/settings/integrations/drawio",
component: Drawio,
enabled: can.update,
group: t("Integrations"),
icon: BuildingBlocksIcon,
},
Slack: {
name: "Slack",
path: "/settings/integrations/slack",
@@ -176,7 +197,14 @@ const useAuthorizedSettingsConfig = () => {
icon: ZapierIcon,
},
}),
[can.createApiKey, can.export, can.manage, can.update, t]
[
can.createApiKey,
can.createWebhookSubscription,
can.createExport,
can.createImport,
can.update,
t,
]
);
const enabledConfigs = React.useMemo(
+4
View File
@@ -18,6 +18,7 @@ export default function useDictionary() {
codeBlock: t("Code block"),
codeCopied: t("Copied to clipboard"),
codeInline: t("Code"),
copy: t("Copy"),
createLink: t("Create link"),
createLinkError: t("Sorry, an error occurred creating the link"),
createNewDoc: t("Create a new doc"),
@@ -52,6 +53,7 @@ export default function useDictionary() {
noResults: t("No results"),
openLink: t("Open link"),
goToLink: t("Go to link"),
openLinkError: t("Sorry, that type of link is not supported"),
orderedList: t("Ordered list"),
pageBreak: t("Page break"),
pasteLink: `${t("Paste a link")}`,
@@ -69,6 +71,8 @@ export default function useDictionary() {
table: t("Table"),
tip: t("Tip"),
tipNotice: t("Tip notice"),
showDiagram: t("Show diagram"),
showSource: t("Show source"),
warning: t("Warning"),
warningNotice: t("Warning notice"),
insertDate: t("Current date"),
+48
View File
@@ -0,0 +1,48 @@
import { find } from "lodash";
import * as React from "react";
import embeds, { EmbedDescriptor } from "@shared/editor/embeds";
import { IntegrationType } from "@shared/types";
import Integration from "~/models/Integration";
import Logger from "~/utils/Logger";
import useStores from "./useStores";
/**
* Hook to get all embed configuration for the current team
*
* @param loadIfMissing Should we load integration settings if they are not
* locally available
* @returns A list of embed descriptors
*/
export default function useEmbeds(loadIfMissing = false) {
const { integrations } = useStores();
React.useEffect(() => {
async function fetchEmbedIntegrations() {
try {
await integrations.fetchPage({
limit: 100,
type: IntegrationType.Embed,
});
} catch (err) {
Logger.error("Failed to fetch embed integrations", err);
}
}
!integrations.isLoaded && loadIfMissing && fetchEmbedIntegrations();
}, [integrations, loadIfMissing]);
return React.useMemo(
() =>
embeds.map((e) => {
const em: Integration<IntegrationType.Embed> | undefined = find(
integrations.orderedData,
(i) => i.service === e.component.name.toLowerCase()
);
return new EmbedDescriptor({
...e,
settings: em?.settings,
});
}),
[integrations.orderedData]
);
}
+26 -4
View File
@@ -1,12 +1,34 @@
import * as React from "react";
import BaseModel from "~/models/BaseModel";
import useStores from "./useStores";
/**
* Quick access to retrieve the abilities of a policy for a given entity
* Retrieve the abilities of a policy for a given entity, if the policy is not
* located in the store, it will be fetched from the server.
*
* @param entityId The entity id
* @returns The available abilities
* @param entity The model or model id
* @returns The policy for the model
*/
export default function usePolicy(entityId: string) {
export default function usePolicy(entity: string | BaseModel | undefined) {
const { policies } = useStores();
const triggered = React.useRef(false);
const entityId = entity
? typeof entity === "string"
? entity
: entity.id
: "";
React.useEffect(() => {
if (entity && typeof entity !== "string") {
// The policy for this model is missing and we haven't tried to fetch it
// yet, go ahead and do that now. The force flag is needed otherwise the
// network request will be skipped due to the model existing in the store
if (!policies.get(entity.id) && !triggered.current) {
triggered.current = true;
void entity.store.fetch(entity.id, { force: true });
}
}
}, [policies, entity]);
return policies.abilities(entityId);
}
+1 -1
View File
@@ -8,7 +8,7 @@ type Session = {
teamId: string;
};
function loadSessionsFromCookie(): Session[] {
export function loadSessionsFromCookie(): Session[] {
const sessions = JSON.parse(getCookie("sessions") || "{}");
return Object.keys(sessions).map((teamId) => ({
teamId,
+7 -7
View File
@@ -16,7 +16,7 @@ import { useTranslation } from "react-i18next";
import { useHistory } from "react-router-dom";
import { useMenuState, MenuButton, MenuButtonHTMLProps } from "reakit/Menu";
import { VisuallyHidden } from "reakit/VisuallyHidden";
import getDataTransferFiles from "@shared/utils/getDataTransferFiles";
import { getEventFiles } from "@shared/utils/files";
import Collection from "~/models/Collection";
import CollectionEdit from "~/scenes/CollectionEdit";
import CollectionExport from "~/scenes/CollectionExport";
@@ -117,8 +117,8 @@ function CollectionMenu({
);
const handleFilePicked = React.useCallback(
async (ev: React.FormEvent<HTMLInputElement>) => {
const files = getDataTransferFiles(ev);
async (ev: React.ChangeEvent<HTMLInputElement>) => {
const files = getEventFiles(ev);
// Because this is the onChange handler it's possible for the change to be
// from previously selecting a file to not selecting a file aka empty
@@ -187,8 +187,8 @@ function CollectionMenu({
);
const alphabeticalSort = collection.sort.field === "title";
const can = usePolicy(collection.id);
const canUserInTeam = usePolicy(team.id);
const can = usePolicy(collection);
const canUserInTeam = usePolicy(team);
const items: MenuItem[] = React.useMemo(
() => [
{
@@ -266,7 +266,7 @@ function CollectionMenu({
{
type: "button",
title: `${t("Export")}`,
visible: !!(collection && canUserInTeam.export),
visible: !!(collection && canUserInTeam.createExport),
onClick: handleExport,
icon: <ExportIcon />,
},
@@ -296,7 +296,7 @@ function CollectionMenu({
alphabeticalSort,
handleEdit,
handlePermissions,
canUserInTeam.export,
canUserInTeam.createExport,
handleExport,
handleDelete,
handleChangeSort,
+34 -196
View File
@@ -1,20 +1,11 @@
import { observer } from "mobx-react";
import {
EditIcon,
StarredIcon,
UnstarredIcon,
DuplicateIcon,
ArchiveIcon,
TrashIcon,
MoveIcon,
HistoryIcon,
UnpublishIcon,
PrintIcon,
ImportIcon,
NewDocumentIcon,
DownloadIcon,
RestoreIcon,
CrossIcon,
} from "outline-icons";
import * as React from "react";
import { useTranslation } from "react-i18next";
@@ -23,21 +14,31 @@ import { useMenuState, MenuButton, MenuButtonHTMLProps } from "reakit/Menu";
import { VisuallyHidden } from "reakit/VisuallyHidden";
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
import getDataTransferFiles from "@shared/utils/getDataTransferFiles";
import { getEventFiles } from "@shared/utils/files";
import Document from "~/models/Document";
import DocumentDelete from "~/scenes/DocumentDelete";
import DocumentMove from "~/scenes/DocumentMove";
import DocumentPermanentDelete from "~/scenes/DocumentPermanentDelete";
import CollectionIcon from "~/components/CollectionIcon";
import ContextMenu from "~/components/ContextMenu";
import OverflowMenuButton from "~/components/ContextMenu/OverflowMenuButton";
import Separator from "~/components/ContextMenu/Separator";
import Template from "~/components/ContextMenu/Template";
import Flex from "~/components/Flex";
import Modal from "~/components/Modal";
import Switch from "~/components/Switch";
import { actionToMenuItem } from "~/actions";
import { pinDocument, createTemplate } from "~/actions/definitions/documents";
import {
pinDocument,
createTemplate,
subscribeDocument,
unsubscribeDocument,
moveDocument,
deleteDocument,
permanentlyDeleteDocument,
downloadDocument,
importDocument,
starDocument,
unstarDocument,
duplicateDocument,
archiveDocument,
} from "~/actions/definitions/documents";
import useActionContext from "~/hooks/useActionContext";
import useCurrentTeam from "~/hooks/useCurrentTeam";
import useMobile from "~/hooks/useMobile";
@@ -94,39 +95,8 @@ function DocumentMenu({
});
const { t } = useTranslation();
const isMobile = useMobile();
const [renderModals, setRenderModals] = React.useState(false);
const [showDeleteModal, setShowDeleteModal] = React.useState(false);
const [
showPermanentDeleteModal,
setShowPermanentDeleteModal,
] = React.useState(false);
const [showMoveModal, setShowMoveModal] = React.useState(false);
const file = React.useRef<HTMLInputElement>(null);
const handleOpen = React.useCallback(() => {
setRenderModals(true);
if (onOpen) {
onOpen();
}
}, [onOpen]);
const handleDuplicate = React.useCallback(async () => {
const duped = await document.duplicate();
// when duplicating, go straight to the duplicated document content
history.push(duped.url);
showToast(t("Document duplicated"), {
type: "success",
});
}, [t, history, showToast, document]);
const handleArchive = React.useCallback(async () => {
await document.archive();
showToast(t("Document archived"), {
type: "success",
});
}, [showToast, t, document]);
const handleRestore = React.useCallback(
async (
ev: React.SyntheticEvent,
@@ -154,26 +124,8 @@ function DocumentMenu({
window.print();
}, [menu]);
const handleStar = React.useCallback(
(ev: React.SyntheticEvent) => {
ev.preventDefault();
ev.stopPropagation();
document.star();
},
[document]
);
const handleUnstar = React.useCallback(
(ev: React.SyntheticEvent) => {
ev.preventDefault();
ev.stopPropagation();
document.unstar();
},
[document]
);
const collection = collections.get(document.collectionId);
const can = usePolicy(document.id);
const can = usePolicy(document);
const canViewHistory = can.read && !can.restore;
const restoreItems = React.useMemo(
() => [
@@ -205,22 +157,9 @@ function DocumentMenu({
ev.stopPropagation();
}, []);
const handleImportDocument = React.useCallback(
(ev: React.SyntheticEvent) => {
ev.preventDefault();
ev.stopPropagation();
// simulate a click on the file upload input element
if (file.current) {
file.current.click();
}
},
[file]
);
const handleFilePicked = React.useCallback(
async (ev: React.FormEvent<HTMLInputElement>) => {
const files = getDataTransferFiles(ev);
async (ev: React.ChangeEvent<HTMLInputElement>) => {
const files = getEventFiles(ev);
// Because this is the onChange handler it's possible for the change to be
// from previously selecting a file to not selecting a file aka empty
@@ -280,7 +219,7 @@ function DocumentMenu({
<ContextMenu
{...menu}
aria-label={t("Document options")}
onOpen={handleOpen}
onOpen={onOpen}
onClose={onClose}
>
<Template
@@ -313,22 +252,10 @@ function DocumentMenu({
...restoreItems,
],
},
{
type: "button",
title: t("Unstar"),
onClick: handleUnstar,
visible: document.isStarred && !!can.unstar,
icon: <UnstarredIcon />,
},
{
type: "button",
title: t("Star"),
onClick: handleStar,
visible: !document.isStarred && !!can.star,
icon: <StarredIcon />,
},
// Pin document
actionToMenuItem(pinDocument, context),
actionToMenuItem(starDocument, context),
actionToMenuItem(unstarDocument, context),
actionToMenuItem(subscribeDocument, context),
actionToMenuItem(unsubscribeDocument, context),
{
type: "separator",
},
@@ -348,22 +275,9 @@ function DocumentMenu({
visible: !!can.createChildDocument,
icon: <NewDocumentIcon />,
},
{
type: "button",
title: t("Import document"),
visible: can.createChildDocument,
onClick: handleImportDocument,
icon: <ImportIcon />,
},
// Templatize document
actionToMenuItem(importDocument, context),
actionToMenuItem(createTemplate, context),
{
type: "button",
title: t("Duplicate"),
onClick: handleDuplicate,
visible: !!can.update,
icon: <DuplicateIcon />,
},
actionToMenuItem(duplicateDocument, context),
{
type: "button",
title: t("Unpublish"),
@@ -371,36 +285,14 @@ function DocumentMenu({
visible: !!can.unpublish,
icon: <UnpublishIcon />,
},
actionToMenuItem(archiveDocument, context),
actionToMenuItem(moveDocument, context),
actionToMenuItem(pinDocument, context),
{
type: "button",
title: t("Archive"),
onClick: handleArchive,
visible: !!can.archive,
icon: <ArchiveIcon />,
},
{
type: "button",
title: `${t("Move")}`,
onClick: () => setShowMoveModal(true),
visible: !!can.move,
icon: <MoveIcon />,
},
{
type: "button",
title: `${t("Delete")}`,
dangerous: true,
onClick: () => setShowDeleteModal(true),
visible: !!can.delete,
icon: <TrashIcon />,
},
{
type: "button",
title: `${t("Permanently delete")}`,
dangerous: true,
onClick: () => setShowPermanentDeleteModal(true),
visible: can.permanentDelete,
icon: <CrossIcon />,
type: "separator",
},
actionToMenuItem(deleteDocument, context),
actionToMenuItem(permanentlyDeleteDocument, context),
{
type: "separator",
},
@@ -413,13 +305,7 @@ function DocumentMenu({
visible: canViewHistory,
icon: <HistoryIcon />,
},
{
type: "button",
title: t("Download"),
onClick: document.download,
visible: !!can.download,
icon: <DownloadIcon />,
},
actionToMenuItem(downloadDocument, context),
{
type: "button",
title: t("Print"),
@@ -447,7 +333,7 @@ function DocumentMenu({
/>
</Style>
)}
{showDisplayOptions && !isMobile && (
{showDisplayOptions && !isMobile && can.update && (
<Style>
<ToggleMenuItem
width={26}
@@ -464,54 +350,6 @@ function DocumentMenu({
</>
)}
</ContextMenu>
{renderModals && (
<>
{can.move && (
<Modal
title={t("Move {{ documentName }}", {
documentName: document.noun,
})}
onRequestClose={() => setShowMoveModal(false)}
isOpen={showMoveModal}
>
<DocumentMove
document={document}
onRequestClose={() => setShowMoveModal(false)}
/>
</Modal>
)}
{can.delete && (
<Modal
title={t("Delete {{ documentName }}", {
documentName: document.noun,
})}
onRequestClose={() => setShowDeleteModal(false)}
isOpen={showDeleteModal}
isCentered
>
<DocumentDelete
document={document}
onSubmit={() => setShowDeleteModal(false)}
/>
</Modal>
)}
{can.permanentDelete && (
<Modal
title={t("Permanently delete {{ documentName }}", {
documentName: document.noun,
})}
onRequestClose={() => setShowPermanentDeleteModal(false)}
isOpen={showPermanentDeleteModal}
isCentered
>
<DocumentPermanentDelete
document={document}
onSubmit={() => setShowPermanentDeleteModal(false)}
/>
</Modal>
)}
</>
)}
</>
);
}
+1 -1
View File
@@ -24,7 +24,7 @@ function GroupMenu({ group, onMembers }: Props) {
});
const [editModalOpen, setEditModalOpen] = React.useState(false);
const [deleteModalOpen, setDeleteModalOpen] = React.useState(false);
const can = usePolicy(group.id);
const can = usePolicy(group);
return (
<>
+1 -1
View File
@@ -27,7 +27,7 @@ function NewDocumentMenu() {
const { t } = useTranslation();
const team = useCurrentTeam();
const { collections, policies } = useStores();
const can = usePolicy(team.id);
const can = usePolicy(team);
const items = React.useMemo(
() =>
collections.orderedData.reduce<MenuItem[]>((filtered, collection) => {
+1 -1
View File
@@ -22,7 +22,7 @@ function NewTemplateMenu() {
const { t } = useTranslation();
const team = useCurrentTeam();
const { collections, policies } = useStores();
const can = usePolicy(team.id);
const can = usePolicy(team);
const items = React.useMemo(
() =>
+5 -33
View File
@@ -2,11 +2,10 @@ import { observer } from "mobx-react";
import * as React from "react";
import { useTranslation } from "react-i18next";
import { MenuButton, useMenuState } from "reakit/Menu";
import styled from "styled-components";
import ContextMenu from "~/components/ContextMenu";
import Template from "~/components/ContextMenu/Template";
import { createAction } from "~/actions";
import { navigateToSettings, logout } from "~/actions/definitions/navigation";
import { changeTeam } from "~/actions/definitions/teams";
import useCurrentTeam from "~/hooks/useCurrentTeam";
import usePrevious from "~/hooks/usePrevious";
import useSessions from "~/hooks/useSessions";
@@ -32,32 +31,11 @@ const OrganizationMenu: React.FC = ({ children }) => {
}
}, [menu, theme, previousTheme]);
// NOTE: it's useful to memoize on the team id and session because the action
// menu is not cached at all.
const actions = React.useMemo(() => {
const otherSessions = sessions.filter(
(session) => session.teamId !== team.id && session.url !== team.url
);
return [
navigateToSettings,
separator(),
...(otherSessions.length
? [
createAction({
name: t("Switch team"),
section: "account",
children: otherSessions.map((session) => ({
id: session.url,
name: session.name,
section: "account",
icon: <Logo alt={session.name} src={session.logoUrl} />,
perform: () => (window.location.href = session.url),
})),
}),
]
: []),
logout,
];
}, [team.id, team.url, sessions, t]);
return [navigateToSettings, separator(), changeTeam, logout];
}, [team.id, sessions]);
return (
<>
@@ -69,10 +47,4 @@ const OrganizationMenu: React.FC = ({ children }) => {
);
};
const Logo = styled("img")`
border-radius: 2px;
width: 24px;
height: 24px;
`;
export default observer(OrganizationMenu);
+31 -3
View File
@@ -1,5 +1,6 @@
import { trim } from "lodash";
import { action, computed, observable } from "mobx";
import { CollectionPermission } from "@shared/types";
import { sortNavigationNodes } from "@shared/utils/collections";
import CollectionsStore from "~/stores/CollectionsStore";
import Document from "~/models/Document";
@@ -39,7 +40,7 @@ export default class Collection extends ParanoidModel {
@Field
@observable
permission: "read" | "read_write" | void;
permission: CollectionPermission | void;
@Field
@observable
@@ -101,8 +102,14 @@ export default class Collection extends ParanoidModel {
return sortNavigationNodes(this.documents, this.sort);
}
/**
* Updates the document identified by the given id in the collection in memory.
* Does not update the document in the database.
*
* @param document The document properties stored in the collection
*/
@action
updateDocument(document: Document) {
updateDocument(document: Pick<Document, "id" | "title" | "url">) {
const travelNodes = (nodes: NavigationNode[]) =>
nodes.forEach((node) => {
if (node.id === document.id) {
@@ -116,6 +123,27 @@ export default class Collection extends ParanoidModel {
travelNodes(this.documents);
}
/**
* Removes the document identified by the given id from the collection in
* memory. Does not remove the document from the database.
*
* @param documentId The id of the document to remove.
*/
@action
removeDocument(documentId: string) {
this.documents = this.documents.filter(function f(node): boolean {
if (node.id === documentId) {
return false;
}
if (node.children) {
node.children = node.children.filter(f);
}
return true;
});
}
@action
updateIndex(index: string) {
this.index = index;
@@ -188,7 +216,7 @@ export default class Collection extends ParanoidModel {
};
export = () => {
return client.get("/collections.export", {
return client.post("/collections.export", {
id: this.id,
});
};
+3 -7
View File
@@ -1,4 +1,5 @@
import { computed } from "mobx";
import { CollectionPermission } from "@shared/types";
import BaseModel from "./BaseModel";
class CollectionGroupMembership extends BaseModel {
@@ -8,16 +9,11 @@ class CollectionGroupMembership extends BaseModel {
collectionId: string;
permission: string;
permission: CollectionPermission;
@computed
get isEditor(): boolean {
return this.permission === "read_write";
}
@computed
get isMaintainer(): boolean {
return this.permission === "maintainer";
return this.permission === CollectionPermission.ReadWrite;
}
}
+40 -7
View File
@@ -155,6 +155,19 @@ export default class Document extends ParanoidModel {
);
}
/**
* Returns whether there is a subscription for this document in the store.
* Does not consider remote state.
*
* @returns True if there is a subscription, false otherwise.
*/
@computed
get isSubscribed(): boolean {
return !!this.store.rootStore.subscriptions.orderedData.find(
(subscription) => subscription.documentId === this.id
);
}
@computed
get isArchived(): boolean {
return !!this.archivedAt;
@@ -255,15 +268,15 @@ export default class Document extends ParanoidModel {
};
@action
pin = async (collectionId?: string) => {
await this.store.rootStore.pins.create({
pin = (collectionId?: string) => {
return this.store.rootStore.pins.create({
documentId: this.id,
...(collectionId ? { collectionId } : {}),
});
};
@action
unpin = async (collectionId?: string) => {
unpin = (collectionId?: string) => {
const pin = this.store.rootStore.pins.orderedData.find(
(pin) =>
pin.documentId === this.id &&
@@ -271,19 +284,39 @@ export default class Document extends ParanoidModel {
(!collectionId && !pin.collectionId))
);
await pin?.delete();
return pin?.delete();
};
@action
star = async () => {
star = () => {
return this.store.star(this);
};
@action
unstar = async () => {
unstar = () => {
return this.store.unstar(this);
};
/**
* Subscribes the current user to this document.
*
* @returns A promise that resolves when the subscription is created.
*/
@action
subscribe = () => {
return this.store.subscribe(this);
};
/**
* Unsubscribes the current user to this document.
*
* @returns A promise that resolves when the subscription is destroyed.
*/
@action
unsubscribe = (userId: string) => {
return this.store.unsubscribe(userId, this);
};
@action
view = () => {
// we don't record views for documents in the trash
@@ -304,7 +337,7 @@ export default class Document extends ParanoidModel {
};
@action
templatize = async () => {
templatize = () => {
return this.store.templatize(this.id);
};
+3 -8
View File
@@ -1,14 +1,9 @@
import { observable } from "mobx";
import type { IntegrationSettings } from "@shared/types";
import BaseModel from "~/models/BaseModel";
import Field from "./decorators/Field";
type Settings = {
url: string;
channel: string;
channelId: string;
};
class Integration extends BaseModel {
class Integration<T = unknown> extends BaseModel {
id: string;
type: string;
@@ -21,7 +16,7 @@ class Integration extends BaseModel {
@observable
events: string[];
settings: Settings;
settings: IntegrationSettings<T>;
}
export default Integration;
+3 -7
View File
@@ -1,4 +1,5 @@
import { computed } from "mobx";
import { CollectionPermission } from "@shared/types";
import BaseModel from "./BaseModel";
class Membership extends BaseModel {
@@ -8,16 +9,11 @@ class Membership extends BaseModel {
collectionId: string;
permission: string;
permission: CollectionPermission;
@computed
get isEditor(): boolean {
return this.permission === "read_write";
}
@computed
get isMaintainer(): boolean {
return this.permission === "maintainer";
return this.permission === CollectionPermission.ReadWrite;
}
}
+29
View File
@@ -0,0 +1,29 @@
import { observable } from "mobx";
import BaseModel from "./BaseModel";
import Field from "./decorators/Field";
/**
* A subscription represents a request for a user to receive notifications for
* a document.
*/
class Subscription extends BaseModel {
@Field
@observable
id: string;
/** The user subscribing */
userId: string;
/** The document being subscribed to */
documentId: string;
/** The event being subscribed to */
@Field
@observable
event: string;
createdAt: string;
updatedAt: string;
}
export default Subscription;
+1 -1
View File
@@ -1,5 +1,5 @@
import { computed, observable } from "mobx";
import { Role } from "@shared/types";
import type { Role } from "@shared/types";
import ParanoidModel from "./ParanoidModel";
import Field from "./decorators/Field";
+27
View File
@@ -0,0 +1,27 @@
import { observable } from "mobx";
import BaseModel from "./BaseModel";
import Field from "./decorators/Field";
class WebhookSubscription extends BaseModel {
@Field
@observable
id: string;
@Field
@observable
name: string;
@Field
@observable
url: string;
@Field
@observable
enabled: boolean;
@Field
@observable
events: string[];
}
export default WebhookSubscription;
+27 -9
View File
@@ -1,3 +1,4 @@
import { observer } from "mobx-react";
import * as React from "react";
import { Switch, Redirect, RouteComponentProps } from "react-router-dom";
import Archive from "~/scenes/Archive";
@@ -10,7 +11,9 @@ import Layout from "~/components/AuthenticatedLayout";
import CenteredContent from "~/components/CenteredContent";
import PlaceholderDocument from "~/components/PlaceholderDocument";
import Route from "~/components/ProfiledRoute";
import SocketProvider from "~/components/SocketProvider";
import WebsocketProvider from "~/components/WebsocketProvider";
import useCurrentTeam from "~/hooks/useCurrentTeam";
import usePolicy from "~/hooks/usePolicy";
import { matchDocumentSlug as slug } from "~/utils/routeHelpers";
const SettingsRoutes = React.lazy(
@@ -59,9 +62,12 @@ const RedirectDocument = ({
/>
);
export default function AuthenticatedRoutes() {
function AuthenticatedRoutes() {
const team = useCurrentTeam();
const can = usePolicy(team);
return (
<SocketProvider>
<WebsocketProvider>
<Layout>
<React.Suspense
fallback={
@@ -71,14 +77,24 @@ export default function AuthenticatedRoutes() {
}
>
<Switch>
{can.createDocument && (
<Route exact path="/templates" component={Templates} />
)}
{can.createDocument && (
<Route exact path="/templates/:sort" component={Templates} />
)}
{can.createDocument && (
<Route exact path="/drafts" component={Drafts} />
)}
{can.createDocument && (
<Route exact path="/archive" component={Archive} />
)}
{can.createDocument && (
<Route exact path="/trash" component={Trash} />
)}
<Redirect from="/dashboard" to="/home" />
<Route path="/home/:tab" component={Home} />
<Route path="/home" component={Home} />
<Route exact path="/templates" component={Templates} />
<Route exact path="/templates/:sort" component={Templates} />
<Route exact path="/drafts" component={Drafts} />
<Route exact path="/archive" component={Archive} />
<Route exact path="/trash" component={Trash} />
<Redirect exact from="/starred" to="/home" />
<Redirect exact from="/collections/*" to="/collection/*" />
<Route exact path="/collection/:id/new" component={DocumentNew} />
@@ -100,6 +116,8 @@ export default function AuthenticatedRoutes() {
</Switch>
</React.Suspense>
</Layout>
</SocketProvider>
</WebsocketProvider>
);
}
export default observer(AuthenticatedRoutes);
+1 -1
View File
@@ -18,7 +18,7 @@ type Props = {
function Actions({ collection }: Props) {
const { t } = useTranslation();
const can = usePolicy(collection.id);
const can = usePolicy(collection);
return (
<>
+1 -1
View File
@@ -20,7 +20,7 @@ type Props = {
function EmptyCollection({ collection }: Props) {
const { t } = useTranslation();
const can = usePolicy(collection.id);
const can = usePolicy(collection);
const collectionName = collection ? collection.name : "";
const [
+2
View File
@@ -3,6 +3,7 @@ import { observer } from "mobx-react";
import { useState } from "react";
import * as React from "react";
import { Trans, useTranslation } from "react-i18next";
import { CollectionValidation } from "@shared/validations";
import Button from "~/components/Button";
import Flex from "~/components/Flex";
import IconPicker from "~/components/IconPicker";
@@ -93,6 +94,7 @@ const CollectionEdit = ({ collectionId, onSubmit }: Props) => {
type="text"
label={t("Name")}
onChange={handleNameChange}
maxLength={CollectionValidation.maxNameLength}
value={name}
required
autoFocus
+3 -1
View File
@@ -25,7 +25,9 @@ function CollectionExport({ collection, onSubmit }: Props) {
setIsLoading(false);
showToast(
t("Export started, you will receive an email when its complete.")
t(
"Export started. If you have notifications enabled, you will receive an email when it's complete."
)
);
onSubmit();
},
+9 -4
View File
@@ -3,6 +3,10 @@ import { observable } from "mobx";
import { observer } from "mobx-react";
import * as React from "react";
import { withTranslation, Trans, WithTranslation } from "react-i18next";
import { randomElement } from "@shared/random";
import { CollectionPermission } from "@shared/types";
import { colorPalette } from "@shared/utils/collections";
import { CollectionValidation } from "@shared/validations";
import RootStore from "~/stores/RootStore";
import Collection from "~/models/Collection";
import Button from "~/components/Button";
@@ -29,13 +33,13 @@ class CollectionNew extends React.Component<Props> {
icon = "";
@observable
color = "#4E5C6E";
color = randomElement(colorPalette);
@observable
sharing = true;
@observable
permission = "read_write";
permission = CollectionPermission.ReadWrite;
@observable
isSaving: boolean;
@@ -97,8 +101,8 @@ class CollectionNew extends React.Component<Props> {
this.hasOpenedIconPicker = true;
};
handlePermissionChange = (newPermission: string) => {
this.permission = newPermission;
handlePermissionChange = (permission: CollectionPermission) => {
this.permission = permission;
};
handleSharingChange = (ev: React.ChangeEvent<HTMLInputElement>) => {
@@ -127,6 +131,7 @@ class CollectionNew extends React.Component<Props> {
type="text"
label={t("Name")}
onChange={this.handleNameChange}
maxLength={CollectionValidation.maxNameLength}
value={this.name}
required
autoFocus
@@ -59,7 +59,6 @@ class AddGroupsToCollection extends React.Component<Props> {
this.props.collectionGroupMemberships.create({
collectionId: this.props.collection.id,
groupId: group.id,
permission: "read_write",
});
this.props.toasts.showToast(
t("{{ groupName }} was added to the collection", {
@@ -57,7 +57,6 @@ class AddPeopleToCollection extends React.Component<Props> {
this.props.memberships.create({
collectionId: this.props.collection.id,
userId: user.id,
permission: "read_write",
});
this.props.toasts.showToast(
t("{{ userName }} was added to the collection", {
@@ -1,6 +1,7 @@
import * as React from "react";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
import { CollectionPermission } from "@shared/types";
import CollectionGroupMembership from "~/models/CollectionGroupMembership";
import Group from "~/models/Group";
import GroupListItem from "~/components/GroupListItem";
@@ -10,7 +11,7 @@ import CollectionGroupMemberMenu from "~/menus/CollectionGroupMemberMenu";
type Props = {
group: Group;
collectionGroupMembership: CollectionGroupMembership | null | undefined;
onUpdate: (permission: string) => void;
onUpdate: (permission: CollectionPermission) => void;
onRemove: () => void;
};
@@ -21,19 +22,6 @@ const CollectionGroupMemberListItem = ({
onRemove,
}: Props) => {
const { t } = useTranslation();
const PERMISSIONS = React.useMemo(
() => [
{
label: t("View only"),
value: "read",
},
{
label: t("View and edit"),
value: "read_write",
},
],
[t]
);
return (
<GroupListItem
@@ -43,7 +31,16 @@ const CollectionGroupMemberListItem = ({
<>
<Select
label={t("Permissions")}
options={PERMISSIONS}
options={[
{
label: t("View only"),
value: CollectionPermission.Read,
},
{
label: t("View and edit"),
value: CollectionPermission.ReadWrite,
},
]}
value={
collectionGroupMembership
? collectionGroupMembership.permission
@@ -1,6 +1,8 @@
import { observer } from "mobx-react";
import * as React from "react";
import { Trans, useTranslation } from "react-i18next";
import styled from "styled-components";
import { CollectionPermission } from "@shared/types";
import Membership from "~/models/Membership";
import User from "~/models/User";
import Avatar from "~/components/Avatar";
@@ -18,7 +20,7 @@ type Props = {
canEdit: boolean;
onAdd?: () => void;
onRemove?: () => void;
onUpdate?: (permission: string) => void;
onUpdate?: (permission: CollectionPermission) => void;
};
const MemberListItem = ({
@@ -30,19 +32,6 @@ const MemberListItem = ({
canEdit,
}: Props) => {
const { t } = useTranslation();
const PERMISSIONS = React.useMemo(
() => [
{
label: t("View only"),
value: "read",
},
{
label: t("View and edit"),
value: "read_write",
},
],
[t]
);
return (
<ListItem
@@ -66,7 +55,16 @@ const MemberListItem = ({
{onUpdate && (
<Select
label={t("Permissions")}
options={PERMISSIONS}
options={[
{
label: t("View only"),
value: CollectionPermission.Read,
},
{
label: t("View and edit"),
value: CollectionPermission.ReadWrite,
},
]}
value={membership ? membership.permission : undefined}
onChange={onUpdate}
disabled={!canEdit}
@@ -103,4 +101,4 @@ const Select = styled(InputSelect)`
}
` as React.ComponentType<SelectProps>;
export default MemberListItem;
export default observer(MemberListItem);
@@ -1,3 +1,4 @@
import { observer } from "mobx-react";
import { PlusIcon } from "outline-icons";
import * as React from "react";
import { Trans, useTranslation } from "react-i18next";
@@ -45,4 +46,4 @@ const UserListItem = ({ user, onAdd, canEdit }: Props) => {
);
};
export default UserListItem;
export default observer(UserListItem);
+7 -6
View File
@@ -3,6 +3,7 @@ import { PlusIcon } from "outline-icons";
import * as React from "react";
import { useTranslation, Trans } from "react-i18next";
import styled from "styled-components";
import { CollectionPermission } from "@shared/types";
import Collection from "~/models/Collection";
import Group from "~/models/Group";
import User from "~/models/User";
@@ -151,7 +152,7 @@ function CollectionPermissions({ collection }: Props) {
);
const handleChangePermission = React.useCallback(
async (permission: string) => {
async (permission: CollectionPermission) => {
try {
await collection.save({
permission,
@@ -218,9 +219,10 @@ function CollectionPermissions({ collection }: Props) {
}}
/>
)}
{collection.permission === "read" && (
{collection.permission === CollectionPermission.ReadWrite && (
<Trans
defaults="Team members can view documents in the <em>{{ collectionName }}</em> collection by default."
defaults="Team members can view and edit documents in the <em>{{ collectionName }}</em> collection by
default."
values={{
collectionName,
}}
@@ -229,10 +231,9 @@ function CollectionPermissions({ collection }: Props) {
}}
/>
)}
{collection.permission === "read_write" && (
{collection.permission === CollectionPermission.Read && (
<Trans
defaults="Team members can view and edit documents in the <em>{{ collectionName }}</em> collection by
default."
defaults="Team members can view documents in the <em>{{ collectionName }}</em> collection by default."
values={{
collectionName,
}}
+36 -3
View File
@@ -2,16 +2,21 @@ import { Location } from "history";
import { observer } from "mobx-react";
import * as React from "react";
import { Helmet } from "react-helmet";
import { useTranslation } from "react-i18next";
import { RouteComponentProps, useLocation } from "react-router-dom";
import { useTheme } from "styled-components";
import styled, { useTheme } from "styled-components";
import { setCookie } from "tiny-cookie";
import DocumentModel from "~/models/Document";
import Error404 from "~/scenes/Error404";
import ErrorOffline from "~/scenes/ErrorOffline";
import Layout from "~/components/Layout";
import Sidebar from "~/components/Sidebar/Shared";
import Text from "~/components/Text";
import useStores from "~/hooks/useStores";
import { NavigationNode } from "~/types";
import { OfflineError } from "~/utils/errors";
import { AuthorizationError, OfflineError } from "~/utils/errors";
import isCloudHosted from "~/utils/isCloudHosted";
import Login from "../Login";
import Document from "./components/Document";
import Loading from "./components/Loading";
@@ -73,6 +78,7 @@ function SharedDocumentScene(props: Props) {
const { ui } = useStores();
const theme = useTheme();
const location = useLocation();
const { t } = useTranslation();
const [response, setResponse] = React.useState<Response>();
const [error, setError] = React.useState<Error | null | undefined>();
const { documents } = useStores();
@@ -105,7 +111,29 @@ function SharedDocumentScene(props: Props) {
}, [documents, documentSlug, shareId, ui]);
if (error) {
return error instanceof OfflineError ? <ErrorOffline /> : <Error404 />;
if (error instanceof OfflineError) {
return <ErrorOffline />;
} else if (error instanceof AuthorizationError) {
setCookie("postLoginRedirectPath", props.location.pathname);
return (
<Login>
{(config) =>
config?.name && isCloudHosted ? (
<GetStarted>
{t(
"{{ teamName }} is using Outline to share documents, please login to continue.",
{
teamName: config.name,
}
)}
</GetStarted>
) : null
}
</Login>
);
} else {
return <Error404 />;
}
}
if (!response) {
@@ -137,4 +165,9 @@ function SharedDocumentScene(props: Props) {
);
}
const GetStarted = styled(Text)`
text-align: center;
margin-top: -8px;
`;
export default observer(SharedDocumentScene);
+11 -9
View File
@@ -57,15 +57,17 @@ export default function Contents({ headings, isFullWidth }: Props) {
<Heading>{t("Contents")}</Heading>
{headings.length ? (
<List>
{headings.map((heading) => (
<ListItem
key={heading.id}
level={heading.level - headingAdjustment}
active={activeSlug === heading.id}
>
<Link href={`#${heading.id}`}>{heading.title}</Link>
</ListItem>
))}
{headings
.filter((heading) => heading.level < 4)
.map((heading) => (
<ListItem
key={heading.id}
level={heading.level - headingAdjustment}
active={activeSlug === heading.id}
>
<Link href={`#${heading.id}`}>{heading.title}</Link>
</ListItem>
))}
</List>
) : (
<Empty>
+137 -185
View File
@@ -1,161 +1,134 @@
import invariant from "invariant";
import { observable } from "mobx";
import { observer } from "mobx-react";
import * as React from "react";
import { RouteComponentProps, StaticContext } from "react-router";
import RootStore from "~/stores/RootStore";
import { useLocation, RouteComponentProps, StaticContext } from "react-router";
import Document from "~/models/Document";
import Revision from "~/models/Revision";
import Error404 from "~/scenes/Error404";
import ErrorOffline from "~/scenes/ErrorOffline";
import withStores from "~/components/withStores";
import usePolicy from "~/hooks/usePolicy";
import useStores from "~/hooks/useStores";
import { NavigationNode } from "~/types";
import Logger from "~/utils/Logger";
import { NotFoundError, OfflineError } from "~/utils/errors";
import history from "~/utils/history";
import { matchDocumentEdit } from "~/utils/routeHelpers";
import HideSidebar from "./HideSidebar";
import Loading from "./Loading";
type Props = RootStore &
RouteComponentProps<
{
documentSlug: string;
revisionId?: string;
shareId?: string;
title?: string;
},
StaticContext,
{
title?: string;
}
> & {
children: (arg0: any) => React.ReactNode;
};
type Params = {
documentSlug: string;
revisionId?: string;
shareId?: string;
};
@observer
class DataLoader extends React.Component<Props> {
sharedTree: NavigationNode | null | undefined;
type LocationState = {
title?: string;
restore?: boolean;
revisionId?: string;
};
@observable
document: Document | null | undefined;
type Children = (options: {
document: Document;
revision: Revision | undefined;
abilities: Record<string, boolean>;
isEditing: boolean;
readOnly: boolean;
onCreateLink: (title: string) => Promise<string>;
sharedTree: NavigationNode | undefined;
}) => React.ReactNode;
@observable
revision: Revision | null | undefined;
type Props = RouteComponentProps<Params, StaticContext, LocationState> & {
children: Children;
};
@observable
shapshot: Blob | null | undefined;
function DataLoader({ match, children }: Props) {
const { ui, shares, documents, auth, revisions, subscriptions } = useStores();
const { team } = auth;
const [error, setError] = React.useState<Error | null>(null);
const { revisionId, shareId, documentSlug } = match.params;
@observable
error: Error | null | undefined;
// Allows loading by /doc/slug-<urlId> or /doc/<id>
const document =
documents.getByUrl(match.params.documentSlug) ??
documents.get(match.params.documentSlug);
componentDidMount() {
const { documents, match } = this.props;
this.document = documents.getByUrl(match.params.documentSlug);
this.sharedTree = this.document
? documents.getSharedTree(this.document.id)
: undefined;
this.loadDocument();
}
const revision = revisionId ? revisions.get(revisionId) : undefined;
const sharedTree = document
? documents.getSharedTree(document.id)
: undefined;
const isEditRoute = match.path === matchDocumentEdit;
const isEditing = isEditRoute || !!auth.team?.collaborativeEditing;
const can = usePolicy(document?.id);
const location = useLocation<LocationState>();
componentDidUpdate(prevProps: Props) {
// If we have the document in the store, but not it's policy then we need to
// reload from the server otherwise the UI will not know which authorizations
// the user has
if (this.document) {
const document = this.document;
const policy = this.props.policies.get(document.id);
if (
!policy &&
!this.error &&
this.props.auth.user &&
this.props.auth.user.id
) {
this.loadDocument();
}
}
// Also need to load the revision if it changes
const { revisionId } = this.props.match.params;
if (
prevProps.match.params.revisionId !== revisionId &&
revisionId &&
revisionId !== "latest"
) {
this.loadRevision();
}
}
get isEditRoute() {
return this.props.match.path === matchDocumentEdit;
}
get isEditing() {
return this.isEditRoute || this.props.auth?.team?.collaborativeEditing;
}
onCreateLink = async (title: string) => {
const document = this.document;
invariant(document, "document must be loaded to create link");
const newDocument = await this.props.documents.create({
collectionId: document.collectionId,
parentDocumentId: document.parentDocumentId,
title,
text: "",
});
return newDocument.url;
};
loadRevision = async () => {
const { revisionId } = this.props.match.params;
if (revisionId) {
this.revision = await this.props.revisions.fetch(revisionId);
}
};
loadDocument = async () => {
const { shareId, documentSlug, revisionId } = this.props.match.params;
// sets the document as active in the sidebar if we already have it loaded
if (this.document) {
this.props.ui.setActiveDocument(this.document);
}
try {
const response = await this.props.documents.fetchWithSharedTree(
documentSlug,
{
React.useEffect(() => {
async function fetchDocument() {
try {
await documents.fetchWithSharedTree(documentSlug, {
shareId,
}
);
this.sharedTree = response.sharedTree;
this.document = response.document;
if (revisionId && revisionId !== "latest") {
await this.loadRevision();
} else {
this.revision = undefined;
});
} catch (err) {
setError(err);
}
} catch (err) {
this.error = err;
return;
}
fetchDocument();
}, [ui, documents, document, shareId, documentSlug]);
const document = this.document;
React.useEffect(() => {
async function fetchRevision() {
if (revisionId && revisionId !== "latest") {
try {
await revisions.fetch(revisionId);
} catch (err) {
setError(err);
}
}
}
fetchRevision();
}, [revisions, revisionId]);
React.useEffect(() => {
async function fetchSubscription() {
if (document?.id) {
try {
await subscriptions.fetchPage({
documentId: document.id,
event: "documents.update",
});
} catch (err) {
Logger.error("Failed to fetch subscriptions", err);
}
}
}
fetchSubscription();
}, [document?.id, subscriptions]);
const onCreateLink = React.useCallback(
async (title: string) => {
if (!document) {
throw new Error("Document not loaded yet");
}
const newDocument = await documents.create({
collectionId: document.collectionId,
parentDocumentId: document.parentDocumentId,
title,
text: "",
});
return newDocument.url;
},
[document, documents]
);
React.useEffect(() => {
if (document) {
const can = this.props.policies.abilities(document.id);
// sets the document as active in the sidebar, ideally in the future this
// will be route driven.
this.props.ui.setActiveDocument(document);
// sets the current document as active in the sidebar
ui.setActiveDocument(document);
// If we're attempting to update an archived, deleted, or otherwise
// uneditable document then forward to the canonical read url.
if (!can.update && this.isEditRoute) {
if (!can.update && isEditRoute) {
history.push(document.url);
return;
}
@@ -163,72 +136,51 @@ class DataLoader extends React.Component<Props> {
// Prevents unauthorized request to load share information for the document
// when viewing a public share link
if (can.read) {
this.props.shares.fetch(document.id).catch((err) => {
shares.fetch(document.id).catch((err) => {
if (!(err instanceof NotFoundError)) {
throw err;
}
});
}
}
};
}, [can.read, can.update, document, isEditRoute, shares, ui]);
render() {
const { location, policies, auth, match, ui } = this.props;
const { revisionId } = match.params;
if (this.error) {
return this.error instanceof OfflineError ? (
<ErrorOffline />
) : (
<Error404 />
);
}
const team = auth.team;
const document = this.document;
const revision = this.revision;
if (!document || !team || (revisionId && !revision)) {
return (
<>
<Loading location={location} />
{this.isEditing && !team?.collaborativeEditing && (
<HideSidebar ui={ui} />
)}
</>
);
}
const abilities = policies.abilities(document.id);
// We do not want to remount the document when changing from view->edit
// on the multiplayer flag as the doc is guaranteed to be upto date.
const key = team.collaborativeEditing
? ""
: this.isEditing
? "editing"
: "read-only";
if (error) {
return error instanceof OfflineError ? <ErrorOffline /> : <Error404 />;
}
if (!document || !team || (revisionId && !revision)) {
return (
<React.Fragment key={key}>
{this.isEditing && !team.collaborativeEditing && (
<HideSidebar ui={ui} />
)}
{this.props.children({
document,
revision,
abilities,
isEditing: this.isEditing,
readOnly:
!this.isEditing ||
!abilities.update ||
document.isArchived ||
!!revisionId,
onCreateLink: this.onCreateLink,
sharedTree: this.sharedTree,
})}
</React.Fragment>
<>
<Loading location={location} />
{isEditing && !team?.collaborativeEditing && <HideSidebar ui={ui} />}
</>
);
}
// We do not want to remount the document when changing from view->edit
// on the multiplayer flag as the doc is guaranteed to be upto date.
const key = team.collaborativeEditing
? ""
: isEditing
? "editing"
: "read-only";
return (
<React.Fragment key={key}>
{isEditing && !team.collaborativeEditing && <HideSidebar ui={ui} />}
{children({
document,
revision,
abilities: can,
isEditing,
readOnly:
!isEditing || !can.update || document.isArchived || !!revisionId,
onCreateLink,
sharedTree,
})}
</React.Fragment>
);
}
export default withStores(DataLoader);
export default observer(DataLoader);
+13 -5
View File
@@ -55,13 +55,21 @@ import References from "./References";
const AUTOSAVE_DELAY = 3000;
type Params = {
documentSlug: string;
revisionId?: string;
shareId?: string;
};
type LocationState = {
title?: string;
restore?: boolean;
revisionId?: string;
};
type Props = WithTranslation &
RootStore &
RouteComponentProps<
Record<string, string>,
StaticContext,
{ restore?: boolean; revisionId?: string }
> & {
RouteComponentProps<Params, StaticContext, LocationState> & {
sharedTree?: NavigationNode;
abilities: Record<string, any>;
document: Document;
@@ -2,13 +2,13 @@ import { observer } from "mobx-react";
import * as React from "react";
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { MAX_TITLE_LENGTH } from "@shared/constants";
import { light } from "@shared/styles/theme";
import {
getCurrentDateAsString,
getCurrentDateTimeAsString,
getCurrentTimeAsString,
} from "@shared/utils/date";
import { DocumentValidation } from "@shared/validations";
import Document from "~/models/Document";
import ContentEditable, { RefHandle } from "~/components/ContentEditable";
import Star, { AnimatedStar } from "~/components/Star";
@@ -132,7 +132,7 @@ const EditableTitle = React.forwardRef(
$emojiWidth={emojiWidth}
$isStarred={document.isStarred}
autoFocus={!value}
maxLength={MAX_TITLE_LENGTH}
maxLength={DocumentValidation.maxTitleLength}
readOnly={readOnly}
dir="auto"
ref={ref}
+3 -1
View File
@@ -57,8 +57,10 @@ function DocumentEditor(props: Props, ref: React.RefObject<any>) {
}
}, [ref]);
// Save document when blurring title, but delay so that if clicking on a
// button this is allowed to execute first.
const handleBlur = React.useCallback(() => {
props.onSave({ autosave: true });
setTimeout(() => props.onSave({ autosave: true }), 250);
}, [props]);
const handleGoToNextInput = React.useCallback(
+1 -1
View File
@@ -100,7 +100,7 @@ function DocumentHeader({
}, [onSave]);
const { isDeleted, isTemplate } = document;
const can = usePolicy(document.id);
const can = usePolicy(document?.id);
const canToggleEmbeds = team?.documentEmbeds;
const canEdit = can.update && !isEditing;
const toc = (
+1 -5
View File
@@ -1,6 +1,5 @@
import { Location } from "history";
import * as React from "react";
import { useTranslation } from "react-i18next";
import CenteredContent from "~/components/CenteredContent";
import PageTitle from "~/components/PageTitle";
import PlaceholderDocument from "~/components/PlaceholderDocument";
@@ -11,12 +10,9 @@ type Props = {
};
export default function Loading({ location }: Props) {
const { t } = useTranslation();
return (
<Container column auto>
<PageTitle
title={location.state ? location.state.title : t("Untitled")}
/>
{location.state?.title && <PageTitle title={location.state.title} />}
<CenteredContent>
<PlaceholderDocument />
</CenteredContent>
@@ -139,6 +139,9 @@ function MultiplayerEditor({ onSynced, ...props }: Props, ref: any) {
});
if (debug) {
provider.on("close", (ev: MessageEvent) =>
Logger.debug("collaboration", "close", ev)
);
provider.on("message", (ev: MessageEvent) =>
Logger.debug("collaboration", "incoming", {
message: ev.message,
@@ -7,6 +7,7 @@ import Document from "~/models/Document";
import Button from "~/components/Button";
import Popover from "~/components/Popover";
import Tooltip from "~/components/Tooltip";
import useCurrentTeam from "~/hooks/useCurrentTeam";
import useStores from "~/hooks/useStores";
import SharePopover from "./SharePopover";
@@ -17,10 +18,12 @@ type Props = {
function ShareButton({ document }: Props) {
const { t } = useTranslation();
const { shares } = useStores();
const team = useCurrentTeam();
const share = shares.getByDocumentId(document.id);
const sharedParent = shares.getByDocumentParents(document.id);
const isPubliclyShared =
share?.published || (sharedParent?.published && !document.isDraft);
team.sharing &&
(share?.published || (sharedParent?.published && !document.isDraft));
const popover = usePopoverState({
gutter: 0,
+16 -10
View File
@@ -14,6 +14,7 @@ import Input from "~/components/Input";
import Notice from "~/components/Notice";
import Switch from "~/components/Switch";
import Text from "~/components/Text";
import useCurrentTeam from "~/hooks/useCurrentTeam";
import useKeyDown from "~/hooks/useKeyDown";
import usePolicy from "~/hooks/usePolicy";
import useStores from "~/hooks/useStores";
@@ -36,33 +37,35 @@ function SharePopover({
onRequestClose,
visible,
}: Props) {
const team = useCurrentTeam();
const { t } = useTranslation();
const { shares, auth } = useStores();
const { shares } = useStores();
const { showToast } = useToasts();
const [isCopied, setIsCopied] = React.useState(false);
const timeout = React.useRef<ReturnType<typeof setTimeout>>();
const buttonRef = React.useRef<HTMLButtonElement>(null);
const can = usePolicy(share ? share.id : "");
const documentAbilities = usePolicy(document.id);
const documentAbilities = usePolicy(document);
const canPublish =
can.update &&
!document.isTemplate &&
auth.team?.sharing &&
team.sharing &&
documentAbilities.share;
const isPubliclyShared =
(share && share.published) ||
(sharedParent && sharedParent.published && !document.isDraft);
team.sharing &&
((share && share.published) ||
(sharedParent && sharedParent.published && !document.isDraft));
useKeyDown("Escape", onRequestClose);
React.useEffect(() => {
if (visible) {
if (visible && team.sharing) {
document.share();
buttonRef.current?.focus();
}
return () => (timeout.current ? clearTimeout(timeout.current) : undefined);
}, [document, visible]);
}, [document, visible, team.sharing]);
const handlePublishedChange = React.useCallback(
async (event) => {
@@ -113,6 +116,9 @@ function SharePopover({
const userLocale = useUserLocale();
const locale = userLocale ? dateLocale(userLocale) : undefined;
const shareUrl = team.sharing
? share?.url ?? ""
: `${team.url}${document.url}`;
return (
<>
@@ -199,14 +205,14 @@ function SharePopover({
type="text"
label={t("Link")}
placeholder={`${t("Loading")}`}
value={share ? share.url : ""}
value={shareUrl}
labelHidden
readOnly
/>
<CopyToClipboard text={share ? share.url : ""} onCopy={handleCopied}>
<CopyToClipboard text={shareUrl} onCopy={handleCopied}>
<Button
type="submit"
disabled={isCopied || !share}
disabled={isCopied || (!share && team.sharing)}
ref={buttonRef}
primary
>
@@ -1,6 +1,6 @@
import * as React from "react";
import { USER_PRESENCE_INTERVAL } from "@shared/constants";
import { SocketContext } from "~/components/SocketProvider";
import { WebsocketContext } from "~/components/WebsocketProvider";
type Props = {
documentId: string;
@@ -8,9 +8,9 @@ type Props = {
};
export default class SocketPresence extends React.Component<Props> {
static contextType = SocketContext;
static contextType = WebsocketContext;
previousContext: typeof SocketContext;
previousContext: typeof WebsocketContext;
editingInterval: ReturnType<typeof setInterval>;

Some files were not shown because too many files have changed in this diff Show More