Compare commits

...

299 Commits

Author SHA1 Message Date
daniel31x13 5303d63e4b add option to disable preservation 2024-11-17 16:06:05 -05:00
Daniel 05a30e1ec6 Merge pull request #867 from clemenstyp/fixed-placeholder
fixed placeholder in german translation (delete collection)
2024-11-16 09:13:21 -05:00
daniel31x13 b1a55785b5 import dates as well 2024-11-16 08:58:03 -05:00
Clemens Eyhoff 24b47e9d4b fixed an other uppercase placeholder 2024-11-16 14:49:07 +01:00
Clemens Eyhoff 34d19f9dbe fixed placeholder (was upper case) 2024-11-16 12:46:44 +01:00
Daniel 95dddd7da0 Merge pull request #859 from linkwarden/dev
Dev
2024-11-14 15:45:17 -05:00
daniel31x13 1a949ecdc6 bug fix 2024-11-14 15:44:31 -05:00
daniel31x13 2e6f1c207c bug fixed 2024-11-14 15:43:37 -05:00
Daniel 6aa0fa9465 Merge pull request #857 from linkwarden/dev
minor UI improvement
2024-11-14 11:01:41 -05:00
daniel31x13 8677df0340 minor UI improvement 2024-11-14 11:01:02 -05:00
Daniel 125f6ac619 Merge pull request #856 from linkwarden/dev
update version
2024-11-14 08:51:33 -05:00
daniel31x13 89ecf5c529 update version 2024-11-14 08:50:52 -05:00
Daniel fa78d6057f Merge pull request #855 from linkwarden/dev
bug fix
2024-11-14 08:50:10 -05:00
daniel31x13 cfc28be898 bug fix 2024-11-14 08:48:18 -05:00
Daniel c8efd4f9db Merge pull request #852 from linkwarden/dev
created check-branch.yml
2024-11-14 02:43:50 -05:00
daniel31x13 ada4e53b46 created check-branch.yml 2024-11-14 02:42:01 -05:00
Daniel 91494b0188 Merge pull request #849 from linkwarden/dev
increase staticPageGenerationTimeout
2024-11-13 22:20:17 -05:00
daniel31x13 e9fd6ec4d5 increase staticPageGenerationTimeout 2024-11-13 22:19:18 -05:00
Daniel f08f4058dc Merge pull request #846 from linkwarden/dev
update Dockerfile
2024-11-13 09:23:59 -05:00
daniel31x13 d60200205a update Dockerfile 2024-11-13 09:23:22 -05:00
Daniel de38eb2963 Merge pull request #845 from linkwarden/dev
revert dockerfile to working state
2024-11-13 06:14:46 -05:00
daniel31x13 f22dd4535d revert dockerfile to working state 2024-11-13 06:12:39 -05:00
Daniel 043589b301 Merge pull request #841 from linkwarden/dev
update version number
2024-11-13 00:01:50 -05:00
daniel31x13 4556827d79 update version number 2024-11-13 00:01:12 -05:00
Daniel 98ebd6d7bc Merge pull request #840 from linkwarden/dev
Dev
2024-11-12 23:59:47 -05:00
daniel31x13 0a3ca4a1d4 Merge branch 'dev' of https://github.com/linkwarden/linkwarden into dev 2024-11-12 23:58:53 -05:00
daniel31x13 106410f55a revert change 2024-11-12 23:58:50 -05:00
Daniel 1ffe1b68a9 Merge pull request #839 from linkwarden/dev
Dev
2024-11-12 23:15:52 -05:00
Daniel 91ab0e609b Merge pull request #833 from click0/Ukrainian-translation
Corrected Ukrainian translation for November 12, 2024
2024-11-12 23:13:38 -05:00
daniel31x13 cbb7a666cd bug fix 2024-11-12 23:12:20 -05:00
Daniel e8cf14334f Merge pull request #838 from linkwarden/dev
added status badges
2024-11-12 22:50:33 -05:00
daniel31x13 019790791b added status badges 2024-11-12 22:49:38 -05:00
Daniel e41ba2668f Merge pull request #837 from linkwarden/dev
bug fix
2024-11-12 22:18:25 -05:00
daniel31x13 66a09fdc4b bug fix 2024-11-12 22:16:42 -05:00
Daniel e50143ca7e Merge pull request #835 from linkwarden/dev
minor change
2024-11-12 18:22:28 -05:00
daniel31x13 162b120e55 minor change 2024-11-12 18:21:58 -05:00
Daniel b4dd47aa37 Merge pull request #834 from linkwarden/dev
updated README
2024-11-12 17:40:32 -05:00
daniel31x13 256c232a85 updated README 2024-11-12 17:39:48 -05:00
vlad11 b7ddf22662 Corrected Ukrainian translation for November 12, 2024
Signed-off-by: vlad11 <admin@support.od.ua>
2024-11-13 00:12:32 +02:00
Daniel 5f60e9833e Merge pull request #831 from linkwarden/dev
bug fix
2024-11-12 16:18:15 -05:00
daniel31x13 ceed23ff51 bug fix 2024-11-12 16:17:38 -05:00
daniel31x13 a4c83dc82f small fix 2024-11-12 08:36:40 -05:00
daniel31x13 46f81ebf25 add info to inviteModal 2024-11-10 16:42:04 -05:00
daniel31x13 0ac5009a4a minor change 2024-11-10 00:27:13 -05:00
daniel31x13 6842da4283 new feature: open all links 2024-11-09 23:59:12 -05:00
daniel31x13 78ecf3ddb5 bug fix 2024-11-09 23:33:13 -05:00
daniel31x13 e39645e135 bug fix 2024-11-09 23:11:03 -05:00
daniel31x13 836360f99d bug fixed 2024-11-09 23:07:01 -05:00
daniel31x13 9c9fd969bc minor fix 2024-11-09 15:27:15 -05:00
daniel31x13 213105942b minor change 2024-11-09 15:02:59 -05:00
daniel31x13 0b7acb35b7 minor change 2024-11-09 14:14:13 -05:00
daniel31x13 9b58ea5c98 minor change 2024-11-09 13:45:11 -05:00
daniel31x13 c85c3bb0d7 minor fix 2024-11-08 18:03:00 -05:00
daniel31x13 7ca574b76f bug fixes 2024-11-08 17:57:50 -05:00
daniel31x13 8593df4673 bug fixed 2024-11-08 17:21:20 -05:00
daniel31x13 ddc2079f4b minor fix 2024-11-08 12:25:31 -05:00
daniel31x13 0de5caffa1 minor fix 2024-11-08 05:24:18 -05:00
daniel31x13 b14e77bdf9 minor fix 2024-11-08 04:48:31 -05:00
daniel31x13 8d366ae7d8 minor fix 2024-11-07 16:54:51 -05:00
daniel31x13 a18938ba2a minor fix 2024-11-07 16:46:26 -05:00
daniel31x13 6eac8423f8 added survey 2024-11-07 11:09:36 -05:00
daniel31x13 cbf93dcf06 minor improvement 2024-11-07 07:32:06 -05:00
daniel31x13 2993347dc7 sleeker dashboard items 2024-11-07 02:09:56 -05:00
daniel31x13 cc45c8fc3e minor improvement 2024-11-07 01:17:30 -05:00
daniel31x13 d5602a09cd minor fix 2024-11-07 01:14:23 -05:00
daniel31x13 736e98ac7d improvements 2024-11-07 01:12:05 -05:00
daniel31x13 7eaff332a9 bug fixed 2024-11-07 00:20:57 -05:00
daniel31x13 7931e2d7b6 better logic when showing link icons 2024-11-07 00:19:12 -05:00
daniel31x13 ac3888f9b3 icon picker is now much more efficient 2024-11-06 23:57:20 -05:00
daniel31x13 ac8add8c5d small improvement 2024-11-06 22:53:21 -05:00
daniel31x13 a6a0f6965b bug fixed 2024-11-06 03:36:02 -05:00
Daniel b2c5c3c6dd Merge pull request #792 from jvanbruegge/prisma-update
Update prisma to v5
2024-11-03 14:20:24 -05:00
Daniel 4555874725 Merge branch 'dev' into prisma-update 2024-11-03 14:19:28 -05:00
daniel31x13 0f5b70eda7 update prisma 2024-11-03 03:59:39 -05:00
daniel31x13 d1c3748681 minor improvement 2024-11-03 03:34:21 -05:00
Daniel 2524139113 Merge pull request #816 from linkwarden/main
Merge main to dev
2024-11-03 03:19:40 -05:00
Daniel 6c2b86fc4b Merge branch 'dev' into main 2024-11-03 03:19:29 -05:00
Daniel d0e0526655 Merge pull request #815 from Green-Kite/dev
update german translation
2024-11-03 03:10:40 -05:00
Green-Kite 43e94ebd0b update german translation
updated german translation
2024-11-03 07:24:38 +01:00
Daniel aeafe6e15d Merge pull request #789 from jvanbruegge/playwright-path
Allow to specify a custom playwright browser path
2024-11-02 21:59:12 -04:00
daniel31x13 5ec221d87d update .env.sample 2024-11-02 21:58:44 -04:00
Daniel d6d6442bc4 Merge pull request #809 from Green-Kite/dev
update german translation
2024-11-02 20:57:31 -04:00
Daniel d12d12518e Merge pull request #636 from bjoerndot/tags-in-public-collection
Tags in public collection
2024-11-02 20:55:16 -04:00
daniel31x13 02ced62832 final change 2024-11-02 20:45:31 -04:00
daniel31x13 4febe1ace5 minor changes 2024-11-02 20:43:53 -04:00
daniel31x13 2e1e94112f make tags visible on public collections 2024-11-02 18:16:38 -04:00
daniel31x13 d86bbcd940 minor fix 2024-11-02 18:07:16 -04:00
daniel31x13 eed80ca812 add migration 2024-11-02 18:01:36 -04:00
Daniel 394251c1f1 Merge branch 'dev' into tags-in-public-collection 2024-11-02 17:56:43 -04:00
Daniel 68cdde91ad Merge pull request #813 from linkwarden/feat/team-support
Feat/seats support
2024-11-02 17:52:17 -04:00
Green-Kite 1ef286a38c update german translation
German translation updated
2024-11-01 10:08:14 +01:00
daniel31x13 508844dd9d bug fixes 2024-10-30 16:47:40 -04:00
daniel31x13 fa1f9873d5 minor change 2024-10-30 13:56:07 -04:00
Oliver Schwamb 891803547e retrieve all links for collection 2024-10-30 12:10:53 +01:00
Oliver Schwamb 24d45f8e8e Merge remote-tracking branch 'upstream/dev' into tags-in-public-collection 2024-10-30 12:10:30 +01:00
daniel31x13 f95350405c rename variable 2024-10-29 18:14:35 -04:00
daniel31x13 665019dc59 finalizing team support 2024-10-29 18:08:47 -04:00
daniel31x13 b09de5a8af updated verify max link logic 2024-10-26 13:44:52 -04:00
daniel31x13 cfd33e9bd1 bug fixed 2024-10-26 10:58:27 -04:00
daniel31x13 d3d2d5069e add member onboarding 2024-10-26 09:42:21 -04:00
daniel31x13 cffc74caa4 add team invitation functionality [WIP] 2024-10-21 13:59:05 -04:00
Jan van Brügge 3cd8eadee3 Update prisma to v5 2024-10-08 16:25:36 +01:00
daniel31x13 d146ec296c bug fixed 2024-10-07 23:43:44 -04:00
Jan van Brügge fb4aa42eef Allow to specify a custom playwright browser path 2024-10-07 15:05:48 +01:00
daniel31x13 f68582e28c bug fixed 2024-10-07 00:57:36 -04:00
daniel31x13 d042c82cb0 add subscription webhook 2024-10-06 01:59:31 -04:00
Daniel 8738dd45e9 Merge pull request #771 from click0/main
Corrected Ukrainian translation.
2024-09-19 14:13:37 -04:00
Vladyslav V. Prodan 839de18d7a Merge branch 'linkwarden:main' into main 2024-09-19 00:46:06 +03:00
vlad11 2ba0851fee Corrected Ukrainian translation.
Signed-off-by: vlad11 <admin@support.od.ua>
2024-09-19 00:36:16 +03:00
daniel31x13 d99972a335 minor fix 2024-09-18 12:10:45 -04:00
daniel31x13 e071b9eb07 minor fix 2024-09-18 11:39:31 -04:00
daniel31x13 eb00d151b7 added locale to the config file 2024-09-18 11:06:31 -04:00
Daniel 22aaa52b3e Merge pull request #770 from bennyz327/dev
feat(lang): add traditional chinese translate
2024-09-18 11:04:03 -04:00
Benny Chou 4541277b28 feat(lang): add traditional chinese translate 2024-09-18 15:21:19 +08:00
Daniel 39faece9d7 Merge pull request #769 from linkwarden/main
Merge pull request #766 from linkwarden/daniel31x13-patch-1
2024-09-17 14:08:44 -04:00
daniel31x13 a21b0760de remove unused type 2024-09-17 14:06:03 -04:00
daniel31x13 04149fe86b Merge branch 'dev' of https://github.com/linkwarden/linkwarden into dev 2024-09-17 14:03:07 -04:00
daniel31x13 ff6e71d494 add schema validation for PUT requests 2024-09-17 14:03:05 -04:00
Daniel 5b02c1cfc9 Merge pull request #765 from ochtum/dev
Translated the added IDs.
2024-09-15 13:53:00 -04:00
Daniel 1ff13e8aa0 Merge pull request #767 from linkwarden/daniel31x13-patch-1
Update .env.sample
2024-09-15 13:52:47 -04:00
Daniel eaf4524598 Merge pull request #766 from linkwarden/daniel31x13-patch-1
Update .env.sample
2024-09-15 13:52:17 -04:00
Daniel a276065288 Update .env.sample 2024-09-15 13:51:09 -04:00
daniel31x13 1cf7421b76 added zod for post requests 2024-09-14 16:00:19 -04:00
武田 淳一 ed4a334024 Translated the added IDs. 2024-09-14 13:24:29 +09:00
Daniel a5b1952e0d Merge pull request #710 from arran4/patch-1
Please 'EXPOSE' port 3000
2024-09-13 01:57:56 -04:00
Daniel 01826b1634 Merge branch 'dev' into patch-1 2024-09-13 01:57:39 -04:00
daniel31x13 3b17d4ddfe bug fixed 2024-09-13 00:37:58 -04:00
Daniel f104fa095f Merge pull request #672 from jlssmt/logging
disabled query logging as default
2024-09-12 23:36:01 -04:00
Daniel b08e6690f3 Merge pull request #689 from stumpylog/chore/update-actions
Chore: Updates actions to their latest versions
2024-09-12 23:16:27 -04:00
Daniel 33a654d21a Merge pull request #688 from stumpylog/feature/docker-file-reduce
fix: reduce Docker image size
2024-09-12 23:06:08 -04:00
Daniel e1262142f8 Merge pull request #764 from click0/main
Corrected Ukrainian translation for September 12, 2024.
2024-09-12 19:04:50 -04:00
vlad11 0a43279665 Corrected Ukrainian translation for September 12, 2024.
Signed-off-by: vlad11 <admin@support.od.ua>
2024-09-13 01:29:34 +03:00
daniel31x13 5491ac74a5 add nl and tr translations 2024-09-12 17:06:36 -04:00
Daniel bbcfca4cde Merge pull request #716 from kgnfth/main
feat(translations): Add Dutch and Turkish translations
2024-09-12 17:05:19 -04:00
daniel31x13 bf9a7d4fa0 add german translation 2024-09-12 17:01:38 -04:00
Daniel edf4e489ec Merge pull request #711 from Green-Kite/main
Add German Translation
2024-09-12 17:00:49 -04:00
daniel31x13 20c5a20851 add spanish translation 2024-09-12 17:00:26 -04:00
Daniel 6f47a20e87 Merge pull request #717 from joser93/es-patch-1
Patch for Spanish translation.
2024-09-12 16:56:31 -04:00
Daniel 384937e210 Merge pull request #714 from phampyk/main
Added Spanish translation
2024-09-12 16:54:58 -04:00
Daniel d22d989c91 Merge pull request #724 from ochtum/main
Created Japanese Translate
2024-09-12 16:53:24 -04:00
Daniel 4e0294322f Merge branch 'dev' into main 2024-09-12 16:53:12 -04:00
daniel31x13 75d5061bdf minor fix 2024-09-12 16:52:26 -04:00
Daniel 0150a9a6e3 Merge pull request #762 from rdeavila/dev
Update pt-BR translation
2024-09-12 16:49:38 -04:00
Daniel 87b79ffbac Merge pull request #726 from CoffeeAnon/feat/set-max-workers
Add Configurable Playwright Concurrency via Environment Variable
2024-09-12 16:43:32 -04:00
Rodrigo de Avila 5a40677191 Update pt-BR translation 2024-09-12 17:42:17 -03:00
Daniel 95ce2f30a8 Merge pull request #734 from click0/main
Added Ukranian translation
2024-09-12 16:33:28 -04:00
Daniel e6a0ecbab5 Merge branch 'dev' into main 2024-09-12 16:32:39 -04:00
daniel31x13 e4c9cf8a38 add locale to config 2024-09-12 16:30:20 -04:00
Daniel eaca3d7453 Merge pull request #746 from rdeavila/main
Add Brazilian Portuguese (pt-BR) support
2024-09-12 16:18:06 -04:00
Rodrigo de Avila fbe3642be4 Merge branch 'linkwarden:main' into main 2024-09-12 17:16:22 -03:00
daniel31x13 bc32abbb92 Merge branch 'main' into dev
merge main to dev
2024-09-12 16:10:35 -04:00
daniel31x13 38f731f313 minor change 2024-09-12 15:46:16 -04:00
daniel31x13 aaf3590542 members with edit permission can now refresh preservation as well + bug fix 2024-09-12 15:30:15 -04:00
daniel31x13 8bb6e32bfa urls are now editable 2024-09-12 15:03:14 -04:00
daniel31x13 7bd3872195 bug fixed + optimizations 2024-09-12 13:47:18 -04:00
daniel31x13 906779010e collection closing bug fixed 2024-09-12 12:46:38 -04:00
daniel31x13 b0f87e8659 bug fixed 2024-09-12 11:59:20 -04:00
daniel31x13 653b1bc396 bug fix 2024-09-11 02:29:50 -04:00
daniel31x13 9b1506a64e add pin to hover view + add number of pins to dashboard + bug fixes 2024-09-11 01:38:38 -04:00
daniel31x13 fb1869ca7a fix dashboard bug 2024-09-10 00:09:33 -04:00
daniel31x13 5e7835b4d5 minor improvement 2024-09-09 23:27:55 -04:00
daniel31x13 0a91c47f83 minor change 2024-09-09 23:07:22 -04:00
daniel31x13 dc9db05e75 fully implemented the custom slider for the number of columns to show 2024-09-09 23:05:57 -04:00
daniel31x13 e1149c2733 minor fix 2024-09-09 19:16:28 -04:00
daniel31x13 0591d7c134 remove unused import 2024-09-09 19:09:09 -04:00
daniel31x13 4602269dd8 add number of columns slider 2024-09-09 19:05:30 -04:00
daniel31x13 9ae6a22236 minor improvement 2024-09-09 12:18:45 -04:00
daniel31x13 442da02956 minor fix 2024-09-04 23:17:58 -04:00
daniel31x13 dfcc271343 bug fix 2024-09-04 23:02:19 -04:00
daniel31x13 43d50dfd1b minor change 2024-09-04 22:39:10 -04:00
daniel31x13 40bb3e6fae fix build error 2024-09-04 22:29:54 -04:00
Daniel 3e077fa247 Merge pull request #754 from linkwarden/feat/customizable-links
Feat/customizable links
2024-09-04 22:20:16 -04:00
daniel31x13 3de8872f26 upload preview functionality 2024-09-04 22:19:40 -04:00
daniel31x13 e9072bba51 minor improvement 2024-08-30 18:10:50 -04:00
daniel31x13 d20c915970 improved edit view 2024-08-30 17:29:15 -04:00
daniel31x13 1a378de267 minor improvement 2024-08-30 10:54:27 -04:00
daniel31x13 d594159c15 minor improvement 2024-08-30 10:47:29 -04:00
daniel31x13 aee10fa406 better edit view 2024-08-30 02:38:58 -04:00
daniel31x13 820d686c37 minor improvement 2024-08-29 18:26:15 -04:00
daniel31x13 4189062c4c bug fixed 2024-08-29 12:53:37 -04:00
Daniel 1461caf68a Merge pull request #748 from linkwarden/hotfix
bug fix
2024-08-29 12:49:48 -04:00
daniel31x13 e7c7fedf8b bug fix 2024-08-29 12:47:23 -04:00
daniel31x13 b7adbbc86f improvements 2024-08-28 20:48:35 -04:00
daniel31x13 975716937f minor improvement 2024-08-28 20:30:57 -04:00
daniel31x13 2d0e52f65b better looking detail modal 2024-08-28 20:22:11 -04:00
Rodrigo de Avila e9afe0ef25 Add Brazilian Portuguese (pt-BR) support 2024-08-28 10:26:27 -03:00
José Roberto Sánchez a38133d618 Improved translations based on comments from @jmiguelr 2024-08-27 11:32:15 -06:00
daniel31x13 6498ae794b custom preview initial commit 2024-08-26 21:04:52 -04:00
daniel31x13 0371695eb3 choose to show which detail in each views 2024-08-26 19:56:04 -04:00
daniel31x13 9ae9c7c81a refactored view dropdown 2024-08-26 18:47:10 -04:00
daniel31x13 642374c2e5 remove commented code 2024-08-26 16:22:59 -04:00
daniel31x13 f368c2aa81 less padding for list view 2024-08-26 16:11:02 -04:00
daniel31x13 fae9e95fa9 added custom icons for links 2024-08-24 15:50:29 -04:00
Daniel 03639adc22 Merge pull request #735 from IsaacWise06/issue-691
Add new collection drop down
2024-08-22 22:48:56 -04:00
Isaac Wise 9fe829771d Add new collection drop down 2024-08-22 17:09:14 -05:00
vlad11 ed7b268c2b Created Ukranian Translate.
Signed-off-by: vlad11 <admin@support.od.ua>
2024-08-22 03:07:25 +03:00
daniel31x13 bf1a6efd2e custom icons fully implemented for collections 2024-08-20 19:25:35 -04:00
daniel31x13 6df2e44213 added translation to icon picker component + other fixes and improvements 2024-08-20 18:11:20 -04:00
daniel31x13 ae2324ecd3 progressed icon picker component 2024-08-20 16:59:01 -04:00
daniel31x13 accbd4cbfa bug fixes 2024-08-19 23:53:43 -04:00
Daniel 5f4e0d4262 Merge pull request #731 from linkwarden/hotfix
bugs fixed
2024-08-19 23:37:30 -04:00
daniel31x13 c072fed99f bugs fixed 2024-08-19 23:36:28 -04:00
Daniel b4a9f917b5 Merge pull request #728 from linkwarden/hotfix
hotfix
2024-08-19 19:30:26 -04:00
daniel31x13 078e5ba95f minor change 2024-08-19 19:30:01 -04:00
daniel31x13 495509c888 bug fix 2024-08-19 19:25:13 -04:00
daniel31x13 dc388ebba5 improved iconPicker component + other improvements 2024-08-19 18:14:09 -04:00
Dan Jacobsen 21578bac8d feat: add configurable max workers 2024-08-19 12:44:59 -07:00
武田 淳一 1062e07065 Created Japanese Translate 2024-08-20 00:50:07 +09:00
daniel31x13 2893d3caf2 minor improvement 2024-08-18 16:52:08 -04:00
Daniel 9f74f62330 Merge pull request #722 from linkwarden/dev
Dev
2024-08-18 16:41:48 -04:00
Daniel c6e3147bb6 Merge pull request #678 from IsaacWise06/fixes
General Fixes
2024-08-18 16:40:48 -04:00
daniel31x13 1260e8c093 fixes 2024-08-18 16:39:43 -04:00
Daniel 5cb4bdced3 Merge pull request #721 from linkwarden/feat/customizable-links
small improvements
2024-08-18 14:47:55 -04:00
Daniel 03b4240b8b Merge pull request #720 from linkwarden/revert-719-feat/customizable-links
Revert "Feat/customizable links"
2024-08-18 14:47:29 -04:00
Daniel 9a3e82470a Revert "Feat/customizable links" 2024-08-18 14:46:52 -04:00
Daniel ee2319996b Merge pull request #719 from linkwarden/feat/customizable-links
Feat/customizable links
2024-08-18 14:46:21 -04:00
daniel31x13 c979adfe69 small improvements 2024-08-18 14:45:40 -04:00
Isaac Wise 2b83522eaa Merge branch 'dev' into fixes 2024-08-18 13:21:02 -05:00
Daniel 8c738d4a99 Merge pull request #718 from linkwarden/feat/customizable-links
Feat/customizable links
2024-08-18 14:11:47 -04:00
Isaac Wise 63678b7f1e format 2024-08-18 13:06:36 -05:00
Isaac Wise b73e845299 Fix building 2024-08-18 13:06:19 -05:00
Isaac Wise 898b126231 Fix merge conflicts 2024-08-18 13:03:09 -05:00
daniel31x13 17d1cb45e3 minor improvement 2024-08-18 13:49:33 -04:00
José Roberto Sánchez 0aad2d9e4b Change email and fixed some typos. Overall is a good translation and I hope is merged soon. :D 2024-08-18 11:07:13 -06:00
daniel31x13 c18a5f4162 added details drawer 2024-08-18 02:55:59 -04:00
Teal'c df7814385a feat(translations): Add Dutch and Turkish translations
- Added Dutch (nl) translations.
- Added Turkish (tr) translations.

#216
2024-08-18 04:39:35 +03:00
Ana d568f22e00 Upload Spanish translation 2024-08-18 00:42:33 +01:00
Green-Kite 6bd1c90417 Create German Translation
updated German translation
2024-08-17 09:57:57 +02:00
daniel31x13 a40026040c icon picker component 2024-08-16 23:00:37 -04:00
Arran Ubels 334ad9f3dc Please 'EXPOSE' port 3000
This is so I can setup up Synology correctly
2024-08-17 11:56:00 +10:00
Daniel f944345745 Merge pull request #708 from linkwarden/dev
bump version
2024-08-16 13:45:28 -04:00
daniel31x13 6b647573f0 bump version 2024-08-16 13:44:53 -04:00
Daniel d81493e021 Merge pull request #707 from linkwarden/dev
bug fix
2024-08-16 13:43:57 -04:00
daniel31x13 03f4523d57 bug fix 2024-08-16 13:42:55 -04:00
Daniel c24e76adac Merge pull request #706 from linkwarden/dev
v2.7.0
2024-08-16 12:36:43 -04:00
daniel31x13 5d26617251 bug fixed 2024-08-16 12:35:04 -04:00
daniel31x13 0e47ad9920 bump version 2024-08-15 16:42:36 -04:00
daniel31x13 ca45076b6c minor fix 2024-08-15 15:37:47 -04:00
Daniel 3bf6dcad2f Merge pull request #692 from phillibl/main
Update [...nextauth].ts to allow existing SSO user sign
2024-08-15 13:45:07 -04:00
daniel31x13 23860b8511 minor fix 2024-08-15 11:00:29 -04:00
daniel31x13 8758976f8d minor fix 2024-08-15 10:30:44 -04:00
Daniel 550dbd2bf0 Merge pull request #704 from shichen437/dev
feat(lang): add chinese translate
2024-08-15 08:49:26 -04:00
shichen437 04d2b3c6b2 feat(lang): add chinese translate 2024-08-15 17:20:46 +08:00
Trenton Holmes cc1c17363b Also install a single browser (Chromium) through Playwright 2024-08-14 19:48:16 -07:00
daniel31x13 7bd0e29538 small improvement 2024-08-14 20:07:06 -04:00
daniel31x13 5baf55694c minor improvement 2024-08-14 19:23:51 -04:00
daniel31x13 193a70c6e8 fix dropdown text wrapping in other languages 2024-08-14 19:13:19 -04:00
daniel31x13 5b430cf31e add french translation 2024-08-14 17:49:53 -04:00
Daniel 684609a1dd Merge pull request #654 from zarevskaya/patch-1
Add french translation
2024-08-14 17:43:15 -04:00
Daniel ebb2016915 Merge pull request #671 from jlssmt/main
handle undefined
2024-08-14 17:40:28 -04:00
daniel31x13 c103b66694 Merge branch 'dev' of https://github.com/linkwarden/linkwarden into dev 2024-08-14 17:26:40 -04:00
daniel31x13 863bcc3838 bug fixed 2024-08-14 17:26:38 -04:00
Daniel 66b0aacc3f Merge pull request #660 from IsaacWise06/issue-646
fix(collections): Redirect to dashboard or login for non-public collections
2024-08-14 17:04:25 -04:00
Daniel 299498ffa6 Merge pull request #703 from linkwarden/chore/react-query-implementation
Chore/react query implementation
2024-08-14 16:45:40 -04:00
daniel31x13 8031432995 bug fix 2024-08-14 16:44:07 -04:00
daniel31x13 9cc3a7206e changes and improvements 2024-08-14 15:22:28 -04:00
daniel31x13 d15d965139 added skeleton loading 2024-08-14 13:14:06 -04:00
daniel31x13 bc04ea0fe8 fixed other views alongside card view 2024-08-13 03:19:28 -04:00
daniel31x13 bd34dacf21 bugs fixed 2024-08-13 03:01:02 -04:00
daniel31x13 80f366cd7b refactored link state management + a lot of other changes... 2024-08-13 00:08:57 -04:00
phillibl c5602dc79f Merge pull request #1 from phillibl/phillibl-SSO-user-signin
Update [...nextauth].ts to allow existing SSO user sign
2024-08-07 05:44:19 -04:00
phillibl 0158e58d90 Update [...nextauth].ts
Fixed issue where sign in would fail for existing user if DISABLE_NEW_SSO_USERS  = true
2024-08-07 05:29:10 -04:00
Trenton Holmes 602f399119 Updates actions to their latest versions 2024-08-04 15:15:33 -07:00
Trenton Holmes 012caab606 Use multi-stage building for the monolith binary 2024-08-04 15:01:54 -07:00
jlssmt 102690fc10 handle undefined 2024-08-02 09:07:13 +02:00
daniel31x13 a73e5fa6c6 add initialData to queries 2024-08-01 18:40:08 -04:00
daniel31x13 75b1ae738f remove unused code 2024-08-01 17:43:46 -04:00
daniel31x13 8563a09a07 refactor token store 2024-08-01 17:42:57 -04:00
daniel31x13 da8dc83b8f refactor tags store 2024-08-01 17:23:51 -04:00
daniel31x13 e889509697 refactor (admin/)users store 2024-08-01 16:54:19 -04:00
Daniel 237499fd03 Merge pull request #684 from linkwarden/daniel31x13-patch-1
Update README
2024-08-01 15:55:20 -04:00
Daniel 9a287d1aef Merge pull request #683 from linkwarden/daniel31x13-patch-1
Update README.md
2024-08-01 15:54:29 -04:00
Daniel 299a2331ff Update README.md 2024-08-01 15:54:00 -04:00
daniel31x13 be5400f7cb rename users hook to user 2024-07-31 14:15:50 -04:00
daniel31x13 099bc9e054 remove old code 2024-07-30 23:23:58 -04:00
daniel31x13 5c5dd967c4 refactor account store + much smoother collection listing updates 2024-07-30 23:19:29 -04:00
daniel31x13 d1ed33b532 bug fix 2024-07-30 14:59:18 -04:00
daniel31x13 05c5bdf63c refactor collections store 2024-07-30 14:57:09 -04:00
Isaac Wise a1248fe62f Fix issue with link action dropdown 2024-07-27 20:19:24 -05:00
Isaac Wise 8f7e0b8d09 Remove type assertions 2024-07-27 20:01:51 -05:00
Isaac Wise 9d91d2064b Merge branch 'linkwarden:main' into issue-646 2024-07-27 17:57:25 -05:00
Isaac Wise d631754b50 Keep any types for selects 2024-07-27 17:45:54 -05:00
Isaac Wise 94be3a7448 format 2024-07-27 17:41:13 -05:00
Isaac Wise 4faf389a2b Fix more types and use logical ANDs 2024-07-27 17:40:07 -05:00
Isaac Wise ff31732ba3 remove more ternaries 2024-07-27 16:17:38 -05:00
Isaac Wise fa051c0d4d Merge branch 'linkwarden:main' into fixes 2024-07-26 16:42:51 -05:00
Isaac Wise 02cb93065f Redact all ids when exporting data 2024-07-26 16:41:19 -05:00
Isaac Wise 0b8a9b4310 Fix some any types 2024-07-25 18:58:52 -05:00
jlssmt ce1aa5a0ec disabled query logging as default 2024-07-25 23:19:33 +02:00
Isaac Wise e79b98d3b0 Replace useless ternarys with logical ANDs 2024-07-22 22:34:36 -05:00
Isaac Wise 7d43ed52a4 format 2024-07-22 17:50:24 -05:00
Isaac Wise 614653bf29 Merge branch 'linkwarden:main' into issue-646 2024-07-22 17:41:34 -05:00
Isaac Wise 1b9dafbe47 Handle 400 error code when accesing a non public collection 2024-07-22 17:39:38 -05:00
zarev abc93f1bf9 Update common.json
Correction
2024-07-20 09:55:51 +02:00
zarev c23964a46d Create common.json
In french, if you want it ;)
2024-07-19 22:37:46 +02:00
Oliver Schwamb abb73f80bd Reworked access to tags as public viewer 2024-07-10 10:22:58 +02:00
Oliver Schwamb e8d0cce58a Added allLinksOfCollection to linksStore
Removed duplicated tags
Fixed overflow for line
added disclosure for tags in public collection
2024-07-09 13:50:08 +02:00
Oliver Schwamb e045c18b7d Only show tags within collection 2024-07-05 10:50:32 +02:00
Oliver Schwamb a1f48bbd79 Tags in public collection 2024-07-05 10:40:40 +02:00
221 changed files with 13685 additions and 4650 deletions
+7 -3
View File
@@ -1,11 +1,12 @@
NEXTAUTH_SECRET=very_sensitive_secret
NEXTAUTH_URL=http://localhost:3000/api/v1/auth NEXTAUTH_URL=http://localhost:3000/api/v1/auth
NEXTAUTH_SECRET=
# Manual installation database settings # Manual installation database settings
DATABASE_URL=postgresql://user:password@localhost:5432/linkwarden # Example: DATABASE_URL=postgresql://user:password@localhost:5432/linkwarden
DATABASE_URL=
# Docker installation database settings # Docker installation database settings
POSTGRES_PASSWORD=super_secret_password POSTGRES_PASSWORD=
# Additional Optional Settings # Additional Optional Settings
PAGINATION_TAKE_COUNT= PAGINATION_TAKE_COUNT=
@@ -33,6 +34,9 @@ SCREENSHOT_MAX_BUFFER=
READABILITY_MAX_BUFFER= READABILITY_MAX_BUFFER=
PREVIEW_MAX_BUFFER= PREVIEW_MAX_BUFFER=
IMPORT_LIMIT= IMPORT_LIMIT=
PLAYWRIGHT_LAUNCH_OPTIONS_EXECUTABLE_PATH=
MAX_WORKERS=
DISABLE_PRESERVATION=
# AWS S3 Settings # AWS S3 Settings
SPACES_KEY= SPACES_KEY=
+18
View File
@@ -0,0 +1,18 @@
name: Check pull request source branch
on:
pull_request_target:
types:
- opened
- reopened
- synchronize
- edited
jobs:
check-branches:
runs-on: ubuntu-latest
steps:
- name: Check branches
run: |
if [ ${{ github.head_ref }} != "dev" ] && [ ${{ github.base_ref }} == "main" ]; then
echo "Merge requests to main branch are only allowed from dev branch. Please rebase your changes to dev branch."
exit 1
fi
+3 -3
View File
@@ -59,10 +59,10 @@ jobs:
--health-retries 5 --health-retries 5
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v4
- name: Use Node.js - name: Use Node.js
uses: actions/setup-node@v3 uses: actions/setup-node@v4
with: with:
node-version: "18" node-version: "18"
cache: 'yarn' cache: 'yarn'
@@ -135,7 +135,7 @@ jobs:
- name: Run Tests - name: Run Tests
run: npx playwright test --grep ${{ matrix.test_case }} run: npx playwright test --grep ${{ matrix.test_case }}
- uses: actions/upload-artifact@v3 - uses: actions/upload-artifact@v4
if: always() if: always()
with: with:
name: playwright-report name: playwright-report
+3 -2
View File
@@ -1,6 +1,7 @@
name: Create and publish a container image on release name: Create and publish a container image on release
on: on:
workflow_dispatch:
push: push:
tags: tags:
- "*" - "*"
@@ -27,7 +28,7 @@ jobs:
uses: docker/setup-buildx-action@v3 uses: docker/setup-buildx-action@v3
- name: Log in to the Container registry - name: Log in to the Container registry
uses: docker/login-action@v2 uses: docker/login-action@v3
with: with:
registry: ${{ env.REGISTRY }} registry: ${{ env.REGISTRY }}
username: ${{ github.actor }} username: ${{ github.actor }}
@@ -40,7 +41,7 @@ jobs:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
- name: Build and push Docker image - name: Build and push Docker image
uses: docker/build-push-action@v3 uses: docker/build-push-action@v6
with: with:
context: . context: .
push: true push: true
+22 -20
View File
@@ -1,4 +1,16 @@
FROM node:18.18-bullseye-slim # Stage: monolith-builder
# Purpose: Uses the Rust image to build monolith
# Notes:
# - Fine to leave extra here, as only the resulting binary is copied out
FROM docker.io/rust:1.80-bullseye AS monolith-builder
RUN set -eux && cargo install --locked monolith
# Stage: main-app
# Purpose: Compiles the frontend and
# Notes:
# - Nothing extra should be left here. All commands should cleanup
FROM node:18.18-bullseye-slim AS main-app
ARG DEBIAN_FRONTEND=noninteractive ARG DEBIAN_FRONTEND=noninteractive
@@ -8,33 +20,23 @@ WORKDIR /data
COPY ./package.json ./yarn.lock ./playwright.config.ts ./ COPY ./package.json ./yarn.lock ./playwright.config.ts ./
RUN --mount=type=cache,sharing=locked,target=/usr/local/share/.cache/yarn yarn install --network-timeout 10000000 RUN --mount=type=cache,sharing=locked,target=/usr/local/share/.cache/yarn \
set -eux && \
yarn install --network-timeout 10000000
RUN apt-get update # Copy the compiled monolith binary from the builder stage
COPY --from=monolith-builder /usr/local/cargo/bin/monolith /usr/local/bin/monolith
RUN apt-get install -y \ RUN set -eux && \
build-essential \ npx playwright install --with-deps chromium && \
curl \
libssl-dev \
pkg-config
RUN apt-get update
RUN curl https://sh.rustup.rs -sSf | bash -s -- -y
ENV PATH="/root/.cargo/bin:${PATH}"
RUN cargo install monolith
RUN npx playwright install-deps && \
apt-get clean && \ apt-get clean && \
yarn cache clean yarn cache clean
RUN yarn playwright install
COPY . . COPY . .
RUN yarn prisma generate && \ RUN yarn prisma generate && \
yarn build yarn build
EXPOSE 3000
CMD yarn prisma migrate deploy && yarn start CMD yarn prisma migrate deploy && yarn start
+19 -8
View File
@@ -1,17 +1,21 @@
<div align="center"> <div align="center">
<img src="./assets/logo.png" width="100px" /> <img src="./assets/logo.png" width="100px" />
<h1>Linkwarden</h1> <h1>Linkwarden</h1>
<h3>Bookmark Preservation for Individuals and Teams</h3>
<a href="https://discord.com/invite/CtuYV47nuJ"><img src="https://img.shields.io/discord/1117993124669702164?logo=discord&style=flat" alt="Discord"></a> <a href="https://discord.com/invite/CtuYV47nuJ"><img src="https://img.shields.io/discord/1117993124669702164?logo=discord&style=flat" alt="Discord"></a>
<a href="https://twitter.com/LinkwardenHQ"><img src="https://img.shields.io/twitter/follow/linkwarden" alt="Twitter"></a> <a href="https://twitter.com/LinkwardenHQ"><img src="https://img.shields.io/twitter/follow/linkwarden" alt="Twitter"></a> <a href="https://news.ycombinator.com/item?id=36942308"><img src="https://img.shields.io/badge/Hacker%20News-280-%23FF6600"></img></a>
<img alt="GitHub commits since latest release" src="https://img.shields.io/github/commits-since/linkwarden/linkwarden/latest/dev?style=for-the-badge&label=COMMITS%20SINCE%20LATEST%20RELEASE"> <a href="https://github.com/linkwarden/linkwarden/actions/workflows/release-container.yml"><img alt="GitHub Actions Workflow Status" src="https://img.shields.io/github/actions/workflow/status/linkwarden/linkwarden/release-container.yml"></a>
<a href="https://opencollective.com/linkwarden"><img src="https://img.shields.io/opencollective/all/linkwarden" alt="Open Collective"></a>
</div> </div>
<div align='center'> <div align='center'>
[Website](https://linkwarden.app) | [Getting Started](https://docs.linkwarden.app) | [Features](https://github.com/linkwarden/linkwarden#features) | [Roadmap](https://github.com/orgs/linkwarden/projects/1) | [Support ❤](https://github.com/linkwarden/linkwarden#support-) [« LAUNCH DEMO »](https://demo.linkwarden.app)
[Cloud](https://cloud.linkwarden.app) · [Website](https://linkwarden.app) · [Features](https://github.com/linkwarden/linkwarden#features)
</div> </div>
@@ -24,7 +28,7 @@ The objective is to organize useful webpages and articles you find across the we
Additionally, Linkwarden is designed with collaboration in mind, sharing links with the public and/or allowing multiple users to work together seamlessly. Additionally, Linkwarden is designed with collaboration in mind, sharing links with the public and/or allowing multiple users to work together seamlessly.
> [!TIP] > [!TIP]
> Our official [Cloud](https://linkwarden.app/#pricing) offering provides the simplest way to begin using Linkwarden and it's the preferred choice for many due to its time-saving benefits. <br> Your subscription supports our hosting infrastructure and ongoing development. <br> Alternatively, if you prefer [self-hosting](https://docs.linkwarden.app/self-hosting/installation) Linkwarden, no problem! You'll still have access to all the premium features. > Our official [Cloud](https://linkwarden.app/#pricing) offering provides the simplest way to begin using Linkwarden and it's the preferred choice for many due to its time-saving benefits. <br> Your subscription supports our hosting infrastructure and ongoing development. <br> Alternatively, if you prefer self-hosting Linkwarden, you can do so by following our [Installation documentation](https://docs.linkwarden.app/self-hosting/installation).
<img src="./assets/dashboard.png" /> <img src="./assets/dashboard.png" />
@@ -68,13 +72,20 @@ We've forked the old version from the current repository into [this repo](https:
- 📱 Responsive design and supports most modern browsers. - 📱 Responsive design and supports most modern browsers.
- 🌓 Dark/Light mode support. - 🌓 Dark/Light mode support.
- 🧩 Browser extension, managed by the community. [Star it here!](https://github.com/linkwarden/browser-extension) - 🧩 Browser extension, managed by the community. [Star it here!](https://github.com/linkwarden/browser-extension)
- 🔄 Browser Synchronization (using [Floccus](https://floccus.org)!)
- ⬇️ Import and export your bookmarks. - ⬇️ Import and export your bookmarks.
- 🔐 SSO integration. (Enterprise and Self-hosted users only) - 🔐 SSO integration. (Enterprise and Self-hosted users only)
- 📦 Installable Progressive Web App (PWA). - 📦 Installable Progressive Web App (PWA).
- 🍎 iOS Shortcut to save links to Linkwarden. - 🍏 iOS and MacOS Apps, maintained by [JGeek00](https://github.com/JGeek00).
- 🍎 iOS Shortcut to save Links to Linkwarden.
- 🔑 API keys. - 🔑 API keys.
- ✅ Bulk actions. - ✅ Bulk actions.
- ✨ And so many more features! - 👥 User administration.
- 🌐 Support for Other Languages (i18n).
- 📁 Image and PDF Uploads.
- 🎨 Custom Icons for Links and Collections.
- ⚙️ Customizable View and Adjustable Columns.
- ✨ And many more features. (Literally!)
## Like what we're doing? Give us a Star ⭐ ## Like what we're doing? Give us a Star ⭐
@@ -98,7 +109,7 @@ We _usually_ go after the [popular suggestions](https://github.com/linkwarden/li
Make sure to check out our [public roadmap](https://github.com/orgs/linkwarden/projects/1). Make sure to check out our [public roadmap](https://github.com/orgs/linkwarden/projects/1).
## Docs ## Documentation
For information on how to get started or to set up your own instance, please visit the [documentation](https://docs.linkwarden.app). For information on how to get started or to set up your own instance, please visit the [documentation](https://docs.linkwarden.app).
@@ -110,7 +121,7 @@ If you want to contribute, Thanks! Start by checking our [public roadmap](https:
If you found a security vulnerability, please do **not** create a public issue, instead send an email to [security@linkwarden.app](mailto:security@linkwarden.app) stating the vulnerability. Thanks! If you found a security vulnerability, please do **not** create a public issue, instead send an email to [security@linkwarden.app](mailto:security@linkwarden.app) stating the vulnerability. Thanks!
## Support ## Support <3
Other than using our official [Cloud](https://linkwarden.app/#pricing) offering, any [donations](https://opencollective.com/linkwarden) are highly appreciated as well! Other than using our official [Cloud](https://linkwarden.app/#pricing) offering, any [donations](https://opencollective.com/linkwarden) are highly appreciated as well!
+38 -39
View File
@@ -1,26 +1,28 @@
import Link from "next/link"; import Link from "next/link";
import { CollectionIncludingMembersAndLinkCount } from "@/types/global"; import {
AccountSettings,
CollectionIncludingMembersAndLinkCount,
} from "@/types/global";
import React, { useEffect, useState } from "react"; import React, { useEffect, useState } from "react";
import ProfilePhoto from "./ProfilePhoto"; import ProfilePhoto from "./ProfilePhoto";
import usePermissions from "@/hooks/usePermissions"; import usePermissions from "@/hooks/usePermissions";
import useLocalSettingsStore from "@/store/localSettings"; import useLocalSettingsStore from "@/store/localSettings";
import getPublicUserData from "@/lib/client/getPublicUserData"; import getPublicUserData from "@/lib/client/getPublicUserData";
import useAccountStore from "@/store/account";
import EditCollectionModal from "./ModalContent/EditCollectionModal"; import EditCollectionModal from "./ModalContent/EditCollectionModal";
import EditCollectionSharingModal from "./ModalContent/EditCollectionSharingModal"; import EditCollectionSharingModal from "./ModalContent/EditCollectionSharingModal";
import DeleteCollectionModal from "./ModalContent/DeleteCollectionModal"; import DeleteCollectionModal from "./ModalContent/DeleteCollectionModal";
import { dropdownTriggerer } from "@/lib/client/utils"; import { dropdownTriggerer } from "@/lib/client/utils";
import { useTranslation } from "next-i18next"; import { useTranslation } from "next-i18next";
import { useUser } from "@/hooks/store/user";
type Props = { export default function CollectionCard({
collection,
}: {
collection: CollectionIncludingMembersAndLinkCount; collection: CollectionIncludingMembersAndLinkCount;
className?: string; }) {
};
export default function CollectionCard({ collection, className }: Props) {
const { t } = useTranslation(); const { t } = useTranslation();
const { settings } = useLocalSettingsStore(); const { settings } = useLocalSettingsStore();
const { account } = useAccountStore(); const { data: user = {} } = useUser();
const formattedDate = new Date(collection.createdAt as string).toLocaleString( const formattedDate = new Date(collection.createdAt as string).toLocaleString(
"en-US", "en-US",
@@ -33,30 +35,24 @@ export default function CollectionCard({ collection, className }: Props) {
const permissions = usePermissions(collection.id as number); const permissions = usePermissions(collection.id as number);
const [collectionOwner, setCollectionOwner] = useState({ const [collectionOwner, setCollectionOwner] = useState<
id: null as unknown as number, Partial<AccountSettings>
name: "", >({});
username: "",
image: "",
archiveAsScreenshot: undefined as unknown as boolean,
archiveAsMonolith: undefined as unknown as boolean,
archiveAsPDF: undefined as unknown as boolean,
});
useEffect(() => { useEffect(() => {
const fetchOwner = async () => { const fetchOwner = async () => {
if (collection && collection.ownerId !== account.id) { if (collection && collection.ownerId !== user.id) {
const owner = await getPublicUserData(collection.ownerId as number); const owner = await getPublicUserData(collection.ownerId as number);
setCollectionOwner(owner); setCollectionOwner(owner);
} else if (collection && collection.ownerId === account.id) { } else if (collection && collection.ownerId === user.id) {
setCollectionOwner({ setCollectionOwner({
id: account.id as number, id: user.id as number,
name: account.name, name: user.name,
username: account.username as string, username: user.username as string,
image: account.image as string, image: user.image as string,
archiveAsScreenshot: account.archiveAsScreenshot as boolean, archiveAsScreenshot: user.archiveAsScreenshot as boolean,
archiveAsMonolith: account.archiveAsMonolith as boolean, archiveAsMonolith: user.archiveAsMonolith as boolean,
archiveAsPDF: account.archiveAsPDF as boolean, archiveAsPDF: user.archiveAsPDF as boolean,
}); });
} }
}; };
@@ -80,7 +76,7 @@ export default function CollectionCard({ collection, className }: Props) {
> >
<i className="bi-three-dots text-xl" title="More"></i> <i className="bi-three-dots text-xl" title="More"></i>
</div> </div>
<ul className="dropdown-content z-[30] menu shadow bg-base-200 border border-neutral-content rounded-box w-52 mt-1"> <ul className="dropdown-content z-[30] menu shadow bg-base-200 border border-neutral-content rounded-box mt-1">
{permissions === true && ( {permissions === true && (
<li> <li>
<div <div
@@ -90,6 +86,7 @@ export default function CollectionCard({ collection, className }: Props) {
(document?.activeElement as HTMLElement)?.blur(); (document?.activeElement as HTMLElement)?.blur();
setEditCollectionModal(true); setEditCollectionModal(true);
}} }}
className="whitespace-nowrap"
> >
{t("edit_collection_info")} {t("edit_collection_info")}
</div> </div>
@@ -103,6 +100,7 @@ export default function CollectionCard({ collection, className }: Props) {
(document?.activeElement as HTMLElement)?.blur(); (document?.activeElement as HTMLElement)?.blur();
setEditCollectionSharingModal(true); setEditCollectionSharingModal(true);
}} }}
className="whitespace-nowrap"
> >
{permissions === true {permissions === true
? t("share_and_collaborate") ? t("share_and_collaborate")
@@ -117,6 +115,7 @@ export default function CollectionCard({ collection, className }: Props) {
(document?.activeElement as HTMLElement)?.blur(); (document?.activeElement as HTMLElement)?.blur();
setDeleteCollectionModal(true); setDeleteCollectionModal(true);
}} }}
className="whitespace-nowrap"
> >
{permissions === true {permissions === true
? t("delete_collection") ? t("delete_collection")
@@ -129,12 +128,12 @@ export default function CollectionCard({ collection, className }: Props) {
className="flex items-center absolute bottom-3 left-3 z-10 btn px-2 btn-ghost rounded-full" className="flex items-center absolute bottom-3 left-3 z-10 btn px-2 btn-ghost rounded-full"
onClick={() => setEditCollectionSharingModal(true)} onClick={() => setEditCollectionSharingModal(true)}
> >
{collectionOwner.id ? ( {collectionOwner.id && (
<ProfilePhoto <ProfilePhoto
src={collectionOwner.image || undefined} src={collectionOwner.image || undefined}
name={collectionOwner.name} name={collectionOwner.name}
/> />
) : undefined} )}
{collection.members {collection.members
.sort((a, b) => (a.userId as number) - (b.userId as number)) .sort((a, b) => (a.userId as number) - (b.userId as number))
.map((e, i) => { .map((e, i) => {
@@ -148,13 +147,13 @@ export default function CollectionCard({ collection, className }: Props) {
); );
}) })
.slice(0, 3)} .slice(0, 3)}
{collection.members.length - 3 > 0 ? ( {collection.members.length - 3 > 0 && (
<div className={`avatar drop-shadow-md placeholder -ml-3`}> <div className={`avatar drop-shadow-md placeholder -ml-3`}>
<div className="bg-base-100 text-neutral rounded-full w-8 h-8 ring-2 ring-neutral-content"> <div className="bg-base-100 text-neutral rounded-full w-8 h-8 ring-2 ring-neutral-content">
<span>+{collection.members.length - 3}</span> <span>+{collection.members.length - 3}</span>
</div> </div>
</div> </div>
) : null} )}
</div> </div>
<Link <Link
href={`/collections/${collection.id}`} href={`/collections/${collection.id}`}
@@ -178,12 +177,12 @@ export default function CollectionCard({ collection, className }: Props) {
<div className="flex justify-end items-center"> <div className="flex justify-end items-center">
<div className="text-right"> <div className="text-right">
<div className="font-bold text-sm flex justify-end gap-1 items-center"> <div className="font-bold text-sm flex justify-end gap-1 items-center">
{collection.isPublic ? ( {collection.isPublic && (
<i <i
className="bi-globe2 drop-shadow text-neutral" className="bi-globe2 drop-shadow text-neutral"
title="This collection is being shared publicly." title="This collection is being shared publicly."
></i> ></i>
) : undefined} )}
<i <i
className="bi-link-45deg text-lg text-neutral" className="bi-link-45deg text-lg text-neutral"
title="This collection is being shared publicly." title="This collection is being shared publicly."
@@ -203,24 +202,24 @@ export default function CollectionCard({ collection, className }: Props) {
</div> </div>
</div> </div>
</Link> </Link>
{editCollectionModal ? ( {editCollectionModal && (
<EditCollectionModal <EditCollectionModal
onClose={() => setEditCollectionModal(false)} onClose={() => setEditCollectionModal(false)}
activeCollection={collection} activeCollection={collection}
/> />
) : undefined} )}
{editCollectionSharingModal ? ( {editCollectionSharingModal && (
<EditCollectionSharingModal <EditCollectionSharingModal
onClose={() => setEditCollectionSharingModal(false)} onClose={() => setEditCollectionSharingModal(false)}
activeCollection={collection} activeCollection={collection}
/> />
) : undefined} )}
{deleteCollectionModal ? ( {deleteCollectionModal && (
<DeleteCollectionModal <DeleteCollectionModal
onClose={() => setDeleteCollectionModal(false)} onClose={() => setDeleteCollectionModal(false)}
activeCollection={collection} activeCollection={collection}
/> />
) : undefined} )}
</div> </div>
); );
} }
+86 -57
View File
@@ -9,14 +9,16 @@ import Tree, {
TreeSourcePosition, TreeSourcePosition,
TreeDestinationPosition, TreeDestinationPosition,
} from "@atlaskit/tree"; } from "@atlaskit/tree";
import useCollectionStore from "@/store/collections";
import { Collection } from "@prisma/client"; import { Collection } from "@prisma/client";
import Link from "next/link"; import Link from "next/link";
import { CollectionIncludingMembersAndLinkCount } from "@/types/global"; import { CollectionIncludingMembersAndLinkCount } from "@/types/global";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import useAccountStore from "@/store/account";
import toast from "react-hot-toast"; import toast from "react-hot-toast";
import { useTranslation } from "next-i18next"; import { useTranslation } from "next-i18next";
import { useCollections, useUpdateCollection } from "@/hooks/store/collections";
import { useUpdateUser, useUser } from "@/hooks/store/user";
import Icon from "./Icon";
import { IconWeight } from "@phosphor-icons/react";
interface ExtendedTreeItem extends TreeItem { interface ExtendedTreeItem extends TreeItem {
data: Collection; data: Collection;
@@ -24,53 +26,51 @@ interface ExtendedTreeItem extends TreeItem {
const CollectionListing = () => { const CollectionListing = () => {
const { t } = useTranslation(); const { t } = useTranslation();
const { collections, updateCollection } = useCollectionStore(); const updateCollection = useUpdateCollection();
const { account, updateAccount } = useAccountStore(); const { data: collections = [], isLoading } = useCollections();
const { data: user = {}, refetch } = useUser();
const updateUser = useUpdateUser();
const router = useRouter(); const router = useRouter();
const currentPath = router.asPath; const currentPath = router.asPath;
const [tree, setTree] = useState<TreeData | undefined>();
const initialTree = useMemo(() => { const initialTree = useMemo(() => {
if (collections.length > 0) { if (collections.length > 0) {
return buildTreeFromCollections( return buildTreeFromCollections(
collections, collections,
router, router,
account.collectionOrder tree,
user.collectionOrder
); );
} } else return undefined;
return undefined; }, [collections, user, router]);
}, [collections, router]);
const [tree, setTree] = useState(initialTree);
useEffect(() => { useEffect(() => {
setTree(initialTree); setTree(initialTree);
}, [initialTree]); }, [initialTree]);
useEffect(() => { useEffect(() => {
if (account.username) { if (user.username) {
refetch();
if ( if (
(!account.collectionOrder || account.collectionOrder.length === 0) && (!user.collectionOrder || user.collectionOrder.length === 0) &&
collections.length > 0 collections.length > 0
) )
updateAccount({ updateUser.mutate({
...account, ...user,
collectionOrder: collections collectionOrder: collections
.filter( .filter((e) => e.parentId === null)
(e) => .map((e) => e.id as number),
e.parentId === null ||
!collections.find((i) => i.id === e.parentId)
) // Filter out collections with non-null parentId
.map((e) => e.id as number), // Use "as number" to assert that e.id is a number
}); });
else { else {
const newCollectionOrder: number[] = [ const newCollectionOrder: number[] = [...(user.collectionOrder || [])];
...(account.collectionOrder || []),
];
// Start with collections that are in both account.collectionOrder and collections // Start with collections that are in both account.collectionOrder and collections
const existingCollectionIds = collections.map((c) => c.id as number); const existingCollectionIds = collections.map((c) => c.id as number);
const filteredCollectionOrder = account.collectionOrder.filter((id) => const filteredCollectionOrder = user.collectionOrder.filter((id: any) =>
existingCollectionIds.includes(id) existingCollectionIds.includes(id)
); );
@@ -78,7 +78,7 @@ const CollectionListing = () => {
collections.forEach((collection) => { collections.forEach((collection) => {
if ( if (
!filteredCollectionOrder.includes(collection.id as number) && !filteredCollectionOrder.includes(collection.id as number) &&
(!collection.parentId || collection.ownerId === account.id) (!collection.parentId || collection.ownerId === user.id)
) { ) {
filteredCollectionOrder.push(collection.id as number); filteredCollectionOrder.push(collection.id as number);
} }
@@ -87,16 +87,16 @@ const CollectionListing = () => {
// check if the newCollectionOrder is the same as the old one // check if the newCollectionOrder is the same as the old one
if ( if (
JSON.stringify(newCollectionOrder) !== JSON.stringify(newCollectionOrder) !==
JSON.stringify(account.collectionOrder) JSON.stringify(user.collectionOrder)
) { ) {
updateAccount({ updateUser.mutateAsync({
...account, ...user,
collectionOrder: newCollectionOrder, collectionOrder: newCollectionOrder,
}); });
} }
} }
} }
}, [collections]); }, [user, collections]);
const onExpand = (movedCollectionId: ItemId) => { const onExpand = (movedCollectionId: ItemId) => {
setTree((currentTree) => setTree((currentTree) =>
@@ -138,9 +138,9 @@ const CollectionListing = () => {
); );
if ( if (
(movedCollection?.ownerId !== account.id && (movedCollection?.ownerId !== user.id &&
destination.parentId !== source.parentId) || destination.parentId !== source.parentId) ||
(destinationCollection?.ownerId !== account.id && (destinationCollection?.ownerId !== user.id &&
destination.parentId !== "root") destination.parentId !== "root")
) { ) {
return toast.error(t("cant_change_collection_you_dont_own")); return toast.error(t("cant_change_collection_you_dont_own"));
@@ -148,18 +148,25 @@ const CollectionListing = () => {
setTree((currentTree) => moveItemOnTree(currentTree!, source, destination)); setTree((currentTree) => moveItemOnTree(currentTree!, source, destination));
const updatedCollectionOrder = [...account.collectionOrder]; const updatedCollectionOrder = [...user.collectionOrder];
if (source.parentId !== destination.parentId) { if (source.parentId !== destination.parentId) {
await updateCollection({ await updateCollection.mutateAsync(
...movedCollection, {
parentId: ...movedCollection,
destination.parentId && destination.parentId !== "root" parentId:
? Number(destination.parentId) destination.parentId && destination.parentId !== "root"
: destination.parentId === "root" ? Number(destination.parentId)
? "root" : destination.parentId === "root"
: null, ? "root"
} as any); : null,
},
{
onError: (error) => {
toast.error(error.message);
},
}
);
} }
if ( if (
@@ -172,8 +179,8 @@ const CollectionListing = () => {
updatedCollectionOrder.splice(destination.index, 0, movedCollectionId); updatedCollectionOrder.splice(destination.index, 0, movedCollectionId);
await updateAccount({ await updateUser.mutateAsync({
...account, ...user,
collectionOrder: updatedCollectionOrder, collectionOrder: updatedCollectionOrder,
}); });
} else if ( } else if (
@@ -182,8 +189,8 @@ const CollectionListing = () => {
) { ) {
updatedCollectionOrder.splice(destination.index, 0, movedCollectionId); updatedCollectionOrder.splice(destination.index, 0, movedCollectionId);
await updateAccount({ updateUser.mutate({
...account, ...user,
collectionOrder: updatedCollectionOrder, collectionOrder: updatedCollectionOrder,
}); });
} else if ( } else if (
@@ -193,14 +200,22 @@ const CollectionListing = () => {
) { ) {
updatedCollectionOrder.splice(source.index, 1); updatedCollectionOrder.splice(source.index, 1);
await updateAccount({ await updateUser.mutateAsync({
...account, ...user,
collectionOrder: updatedCollectionOrder, collectionOrder: updatedCollectionOrder,
}); });
} }
}; };
if (!tree) { if (isLoading) {
return (
<div className="flex flex-col gap-4">
<div className="skeleton h-4 w-full"></div>
<div className="skeleton h-4 w-full"></div>
<div className="skeleton h-4 w-full"></div>
</div>
);
} else if (!tree) {
return ( return (
<p className="text-neutral text-xs font-semibold truncate w-full px-2 mt-5 mb-8"> <p className="text-neutral text-xs font-semibold truncate w-full px-2 mt-5 mb-8">
{t("you_have_no_collections")} {t("you_have_no_collections")}
@@ -237,7 +252,7 @@ const renderItem = (
: "hover:bg-neutral/20" : "hover:bg-neutral/20"
} duration-100 flex gap-1 items-center pr-2 pl-1 rounded-md`} } duration-100 flex gap-1 items-center pr-2 pl-1 rounded-md`}
> >
{Icon(item as ExtendedTreeItem, onExpand, onCollapse)} {Dropdown(item as ExtendedTreeItem, onExpand, onCollapse)}
<Link <Link
href={`/collections/${collection.id}`} href={`/collections/${collection.id}`}
@@ -247,18 +262,29 @@ const renderItem = (
<div <div
className={`py-1 cursor-pointer flex items-center gap-2 w-full rounded-md h-8 capitalize`} className={`py-1 cursor-pointer flex items-center gap-2 w-full rounded-md h-8 capitalize`}
> >
<i {collection.icon ? (
className="bi-folder-fill text-2xl drop-shadow" <Icon
style={{ color: collection.color }} icon={collection.icon}
></i> size={30}
weight={(collection.iconWeight || "regular") as IconWeight}
color={collection.color}
className="-mr-[0.15rem]"
/>
) : (
<i
className="bi-folder-fill text-2xl"
style={{ color: collection.color }}
></i>
)}
<p className="truncate w-full">{collection.name}</p> <p className="truncate w-full">{collection.name}</p>
{collection.isPublic ? ( {collection.isPublic && (
<i <i
className="bi-globe2 text-sm text-black/50 dark:text-white/50 drop-shadow" className="bi-globe2 text-sm text-black/50 dark:text-white/50 drop-shadow"
title="This collection is being shared publicly." title="This collection is being shared publicly."
></i> ></i>
) : undefined} )}
<div className="drop-shadow text-neutral text-xs"> <div className="drop-shadow text-neutral text-xs">
{collection._count?.links} {collection._count?.links}
</div> </div>
@@ -269,7 +295,7 @@ const renderItem = (
); );
}; };
const Icon = ( const Dropdown = (
item: ExtendedTreeItem, item: ExtendedTreeItem,
onExpand: (id: ItemId) => void, onExpand: (id: ItemId) => void,
onCollapse: (id: ItemId) => void onCollapse: (id: ItemId) => void
@@ -292,6 +318,7 @@ const Icon = (
const buildTreeFromCollections = ( const buildTreeFromCollections = (
collections: CollectionIncludingMembersAndLinkCount[], collections: CollectionIncludingMembersAndLinkCount[],
router: ReturnType<typeof useRouter>, router: ReturnType<typeof useRouter>,
tree?: TreeData,
order?: number[] order?: number[]
): TreeData => { ): TreeData => {
if (order) { if (order) {
@@ -306,13 +333,15 @@ const buildTreeFromCollections = (
id: collection.id, id: collection.id,
children: [], children: [],
hasChildren: false, hasChildren: false,
isExpanded: false, isExpanded: tree?.items[collection.id as number]?.isExpanded || false,
data: { data: {
id: collection.id, id: collection.id,
parentId: collection.parentId, parentId: collection.parentId,
name: collection.name, name: collection.name,
description: collection.description, description: collection.description,
color: collection.color, color: collection.color,
icon: collection.icon,
iconWeight: collection.iconWeight,
isPublic: collection.isPublic, isPublic: collection.isPublic,
ownerId: collection.ownerId, ownerId: collection.ownerId,
createdAt: collection.createdAt, createdAt: collection.createdAt,
+32
View File
@@ -0,0 +1,32 @@
import React, { useState } from "react";
type Props = {
text: string;
};
const CopyButton: React.FC<Props> = ({ text }) => {
const [copied, setCopied] = useState(false);
const handleCopy = async () => {
try {
await navigator.clipboard.writeText(text);
setCopied(true);
setTimeout(() => {
setCopied(false);
}, 1000);
} catch (err) {
console.log(err);
}
};
return (
<div
className={`text-xl text-neutral btn btn-sm btn-square btn-ghost ${
copied ? "bi-check2 text-success" : "bi-copy"
}`}
onClick={handleCopy}
></div>
);
};
export default CopyButton;
+6 -4
View File
@@ -8,13 +8,15 @@ export default function dashboardItem({
icon: string; icon: string;
}) { }) {
return ( return (
<div className="flex items-center"> <div className="flex items-center justify-between w-full rounded-2xl border border-neutral-content p-3 bg-gradient-to-tr from-neutral-content/70 to-50% to-base-200">
<div className="w-[4rem] aspect-square flex justify-center items-center bg-primary/20 rounded-xl select-none"> <div className="w-14 aspect-square flex justify-center items-center bg-primary/20 rounded-xl select-none">
<i className={`${icon} text-primary text-3xl drop-shadow`}></i> <i className={`${icon} text-primary text-3xl drop-shadow`}></i>
</div> </div>
<div className="ml-4 flex flex-col justify-center"> <div className="ml-4 flex flex-col justify-center">
<p className="text-neutral text-xs tracking-wider">{name}</p> <p className="text-neutral text-xs tracking-wider text-right">{name}</p>
<p className="font-thin text-5xl text-primary mt-0.5">{value}</p> <p className="font-thin text-4xl text-primary mt-0.5 text-right">
{value || 0}
</p>
</div> </div>
</div> </div>
); );
+81
View File
@@ -0,0 +1,81 @@
import React, { ReactNode, useEffect } from "react";
import { Drawer as D } from "vaul";
import clsx from "clsx";
type Props = {
toggleDrawer: Function;
children: ReactNode;
className?: string;
dismissible?: boolean;
};
export default function Drawer({
toggleDrawer,
className,
children,
dismissible = true,
}: Props) {
const [drawerIsOpen, setDrawerIsOpen] = React.useState(true);
useEffect(() => {
if (window.innerWidth >= 640) {
document.body.style.overflow = "hidden";
document.body.style.position = "relative";
return () => {
document.body.style.overflow = "auto";
document.body.style.position = "";
};
}
}, []);
if (window.innerWidth < 640) {
return (
<D.Root
open={drawerIsOpen}
onClose={() => dismissible && setDrawerIsOpen(false)}
onAnimationEnd={(isOpen) => !isOpen && toggleDrawer()}
dismissible={dismissible}
>
<D.Portal>
<D.Overlay className="fixed inset-0 bg-black/40" />
<D.Content className="flex flex-col rounded-t-2xl mt-24 fixed bottom-0 left-0 right-0 z-30 h-[90%] !select-auto focus:outline-none">
<div
className={clsx(
"p-4 bg-base-100 rounded-t-2xl flex-1 border-neutral-content border-t overflow-y-auto",
className
)}
data-testid="mobile-modal-container"
>
<div data-testid="mobile-modal-slider" />
{children}
</div>
</D.Content>
</D.Portal>
</D.Root>
);
} else {
return (
<D.Root
open={drawerIsOpen}
onClose={() => dismissible && setDrawerIsOpen(false)}
onAnimationEnd={(isOpen) => !isOpen && toggleDrawer()}
dismissible={dismissible}
direction="right"
>
<D.Portal>
<D.Overlay className="fixed inset-0 bg-black/10 z-20" />
<D.Content className="bg-white flex flex-col h-full w-2/5 min-w-[30rem] mt-24 fixed bottom-0 right-0 z-40 !select-auto focus:outline-none">
<div
className={clsx(
"p-4 bg-base-100 flex-1 border-neutral-content border-l overflow-y-auto",
className
)}
>
{children}
</div>
</D.Content>
</D.Portal>
</D.Root>
);
}
}
+42 -40
View File
@@ -60,47 +60,49 @@ export default function Dropdown({
} }
}, [points, dropdownHeight]); }, [points, dropdownHeight]);
return !points || pos ? ( return (
<ClickAwayHandler (!points || pos) && (
onMount={(e) => { <ClickAwayHandler
setDropdownHeight(e.height); onMount={(e) => {
setDropdownWidth(e.width); setDropdownHeight(e.height);
}} setDropdownWidth(e.width);
style={ }}
points style={
? { points
position: "fixed", ? {
top: `${pos?.y}px`, position: "fixed",
left: `${pos?.x}px`, top: `${pos?.y}px`,
} left: `${pos?.x}px`,
: undefined }
} : undefined
onClickOutside={onClickOutside} }
className={`${ onClickOutside={onClickOutside}
className || "" className={`${
} py-1 shadow-md border border-neutral-content bg-base-200 rounded-md flex flex-col z-20`} className || ""
> } py-1 shadow-md border border-neutral-content bg-base-200 rounded-md flex flex-col z-20`}
{items.map((e, i) => { >
const inner = e && ( {items.map((e, i) => {
<div className="cursor-pointer rounded-md"> const inner = e && (
<div className="flex items-center gap-2 py-1 px-2 hover:bg-base-100 duration-100"> <div className="cursor-pointer rounded-md">
<p className="select-none">{e.name}</p> <div className="flex items-center gap-2 py-1 px-2 hover:bg-base-100 duration-100">
<p className="select-none">{e.name}</p>
</div>
</div> </div>
</div> );
);
return e && e.href ? ( return e && e.href ? (
<Link key={i} href={e.href}> <Link key={i} href={e.href}>
{inner}
</Link>
) : (
e && (
<div key={i} onClick={e.onClick}>
{inner} {inner}
</div> </Link>
) ) : (
); e && (
})} <div key={i} onClick={e.onClick}>
</ClickAwayHandler> {inner}
) : null; </div>
)
);
})}
</ClickAwayHandler>
)
);
} }
+35 -23
View File
@@ -1,6 +1,8 @@
import { dropdownTriggerer } from "@/lib/client/utils"; import { dropdownTriggerer } from "@/lib/client/utils";
import React from "react"; import React, { useEffect } from "react";
import { useTranslation } from "next-i18next"; import { useTranslation } from "next-i18next";
import { resetInfiniteQueryPagination } from "@/hooks/store/links";
import { useQueryClient } from "@tanstack/react-query";
type Props = { type Props = {
setSearchFilter: Function; setSearchFilter: Function;
@@ -18,6 +20,7 @@ export default function FilterSearchDropdown({
searchFilter, searchFilter,
}: Props) { }: Props) {
const { t } = useTranslation(); const { t } = useTranslation();
const queryClient = useQueryClient();
return ( return (
<div className="dropdown dropdown-bottom dropdown-end"> <div className="dropdown dropdown-bottom dropdown-end">
@@ -29,7 +32,7 @@ export default function FilterSearchDropdown({
> >
<i className="bi-funnel text-neutral text-2xl"></i> <i className="bi-funnel text-neutral text-2xl"></i>
</div> </div>
<ul className="dropdown-content z-[30] menu shadow bg-base-200 border border-neutral-content rounded-box w-56 mt-1"> <ul className="dropdown-content z-[30] menu shadow bg-base-200 border border-neutral-content rounded-box mt-1">
<li> <li>
<label <label
className="label cursor-pointer flex justify-start" className="label cursor-pointer flex justify-start"
@@ -41,11 +44,12 @@ export default function FilterSearchDropdown({
name="search-filter-checkbox" name="search-filter-checkbox"
className="checkbox checkbox-primary" className="checkbox checkbox-primary"
checked={searchFilter.name} checked={searchFilter.name}
onChange={() => onChange={() => {
setSearchFilter({ ...searchFilter, name: !searchFilter.name }) resetInfiniteQueryPagination(queryClient, ["links"]);
} setSearchFilter({ ...searchFilter, name: !searchFilter.name });
}}
/> />
<span className="label-text">{t("name")}</span> <span className="label-text whitespace-nowrap">{t("name")}</span>
</label> </label>
</li> </li>
<li> <li>
@@ -59,11 +63,12 @@ export default function FilterSearchDropdown({
name="search-filter-checkbox" name="search-filter-checkbox"
className="checkbox checkbox-primary" className="checkbox checkbox-primary"
checked={searchFilter.url} checked={searchFilter.url}
onChange={() => onChange={() => {
setSearchFilter({ ...searchFilter, url: !searchFilter.url }) resetInfiniteQueryPagination(queryClient, ["links"]);
} setSearchFilter({ ...searchFilter, url: !searchFilter.url });
}}
/> />
<span className="label-text">{t("link")}</span> <span className="label-text whitespace-nowrap">{t("link")}</span>
</label> </label>
</li> </li>
<li> <li>
@@ -77,14 +82,17 @@ export default function FilterSearchDropdown({
name="search-filter-checkbox" name="search-filter-checkbox"
className="checkbox checkbox-primary" className="checkbox checkbox-primary"
checked={searchFilter.description} checked={searchFilter.description}
onChange={() => onChange={() => {
resetInfiniteQueryPagination(queryClient, ["links"]);
setSearchFilter({ setSearchFilter({
...searchFilter, ...searchFilter,
description: !searchFilter.description, description: !searchFilter.description,
}) });
} }}
/> />
<span className="label-text">{t("description")}</span> <span className="label-text whitespace-nowrap">
{t("description")}
</span>
</label> </label>
</li> </li>
<li> <li>
@@ -98,11 +106,12 @@ export default function FilterSearchDropdown({
name="search-filter-checkbox" name="search-filter-checkbox"
className="checkbox checkbox-primary" className="checkbox checkbox-primary"
checked={searchFilter.tags} checked={searchFilter.tags}
onChange={() => onChange={() => {
setSearchFilter({ ...searchFilter, tags: !searchFilter.tags }) resetInfiniteQueryPagination(queryClient, ["links"]);
} setSearchFilter({ ...searchFilter, tags: !searchFilter.tags });
}}
/> />
<span className="label-text">{t("tags")}</span> <span className="label-text whitespace-nowrap">{t("tags")}</span>
</label> </label>
</li> </li>
<li> <li>
@@ -116,15 +125,18 @@ export default function FilterSearchDropdown({
name="search-filter-checkbox" name="search-filter-checkbox"
className="checkbox checkbox-primary" className="checkbox checkbox-primary"
checked={searchFilter.textContent} checked={searchFilter.textContent}
onChange={() => onChange={() => {
resetInfiniteQueryPagination(queryClient, ["links"]);
setSearchFilter({ setSearchFilter({
...searchFilter, ...searchFilter,
textContent: !searchFilter.textContent, textContent: !searchFilter.textContent,
}) });
} }}
/> />
<span className="label-text">{t("full_content")}</span> <span className="label-text whitespace-nowrap">
<div className="ml-auto badge badge-sm badge-neutral"> {t("full_content")}
</span>
<div className="ml-auto badge badge-sm badge-neutral whitespace-nowrap">
{t("slower")} {t("slower")}
</div> </div>
</label> </label>
+18
View File
@@ -0,0 +1,18 @@
import React, { forwardRef } from "react";
import * as Icons from "@phosphor-icons/react";
type Props = {
icon: string;
} & Icons.IconProps;
const Icon = forwardRef<SVGSVGElement, Props>(({ icon, ...rest }, ref) => {
const IconComponent: any = Icons[icon as keyof typeof Icons];
if (!IconComponent) {
return null;
} else return <IconComponent ref={ref} {...rest} />;
});
Icon.displayName = "Icon";
export default Icon;
+91
View File
@@ -0,0 +1,91 @@
import { icons } from "@/lib/client/icons";
import Fuse from "fuse.js";
import { forwardRef, useMemo } from "react";
import { FixedSizeGrid as Grid } from "react-window";
const fuse = new Fuse(icons, {
keys: [{ name: "name", weight: 4 }, "tags", "categories"],
threshold: 0.2,
useExtendedSearch: true,
});
type Props = {
query: string;
color: string;
weight: "light" | "regular" | "bold" | "fill" | "duotone" | "thin";
iconName?: string;
setIconName: Function;
};
const IconGrid = ({ query, color, weight, iconName, setIconName }: Props) => {
const filteredIcons = useMemo(() => {
if (!query) {
return icons;
}
return fuse.search(query).map((result) => result.item);
}, [query]);
const columnCount = 6;
const rowCount = Math.ceil(filteredIcons.length / columnCount);
const GUTTER_SIZE = 5;
const Cell = ({ columnIndex, rowIndex, style }: any) => {
const index = rowIndex * columnCount + columnIndex;
if (index >= filteredIcons.length) return null; // Prevent overflow
const icon = filteredIcons[index];
const IconComponent = icon.Icon;
return (
<div
style={{
...style,
left: style.left + GUTTER_SIZE,
top: style.top + GUTTER_SIZE,
width: style.width - GUTTER_SIZE,
height: style.height - GUTTER_SIZE,
}}
onClick={() => setIconName(icon.pascal_name)}
className={`cursor-pointer p-[6px] rounded-lg bg-base-100 w-full ${
icon.pascal_name === iconName
? "outline outline-1 outline-primary"
: ""
}`}
>
<IconComponent size={32} weight={weight} color={color} />
</div>
);
};
const InnerElementType = forwardRef(({ style, ...rest }: any, ref) => (
<div
ref={ref}
style={{
...style,
paddingLeft: GUTTER_SIZE,
paddingTop: GUTTER_SIZE,
}}
{...rest}
/>
));
InnerElementType.displayName = "InnerElementType";
return (
<Grid
columnCount={columnCount}
rowCount={rowCount}
columnWidth={50}
rowHeight={50}
innerElementType={InnerElementType}
width={320}
height={158}
itemData={filteredIcons}
className="hide-scrollbar ml-[4px] w-fit"
>
{Cell}
</Grid>
);
};
export default IconGrid;
+83
View File
@@ -0,0 +1,83 @@
import React, { useState } from "react";
import TextInput from "./TextInput";
import Popover from "./Popover";
import { HexColorPicker } from "react-colorful";
import { useTranslation } from "next-i18next";
import Icon from "./Icon";
import { IconWeight } from "@phosphor-icons/react";
import IconGrid from "./IconGrid";
import IconPopover from "./IconPopover";
import clsx from "clsx";
type Props = {
alignment?: string;
color: string;
setColor: Function;
iconName?: string;
setIconName: Function;
weight: "light" | "regular" | "bold" | "fill" | "duotone" | "thin";
setWeight: Function;
hideDefaultIcon?: boolean;
reset: Function;
className?: string;
};
const IconPicker = ({
alignment,
color,
setColor,
iconName,
setIconName,
weight,
setWeight,
hideDefaultIcon,
className,
reset,
}: Props) => {
const { t } = useTranslation();
const [iconPicker, setIconPicker] = useState(false);
return (
<div className="relative">
<div
onClick={() => setIconPicker(!iconPicker)}
className="btn btn-square w-20 h-20"
>
{iconName ? (
<Icon
icon={iconName}
size={60}
weight={(weight || "regular") as IconWeight}
color={color || "#0ea5e9"}
/>
) : !iconName && hideDefaultIcon ? (
<p className="p-1">{t("set_custom_icon")}</p>
) : (
<i
className="bi-folder-fill text-6xl"
style={{ color: color || "#0ea5e9" }}
></i>
)}
</div>
{iconPicker && (
<IconPopover
alignment={alignment}
color={color}
setColor={setColor}
iconName={iconName}
setIconName={setIconName}
weight={weight}
setWeight={setWeight}
reset={reset}
onClose={() => setIconPicker(false)}
className={clsx(
className,
alignment || "lg:-translate-x-1/3 top-20 left-0"
)}
/>
)}
</div>
);
};
export default IconPicker;
+147
View File
@@ -0,0 +1,147 @@
import React, { useState } from "react";
import TextInput from "./TextInput";
import Popover from "./Popover";
import { HexColorPicker } from "react-colorful";
import { useTranslation } from "next-i18next";
import IconGrid from "./IconGrid";
import clsx from "clsx";
type Props = {
alignment?: string;
color: string;
setColor: Function;
iconName?: string;
setIconName: Function;
weight: "light" | "regular" | "bold" | "fill" | "duotone" | "thin";
setWeight: Function;
reset: Function;
className?: string;
onClose: Function;
};
const IconPopover = ({
alignment,
color,
setColor,
iconName,
setIconName,
weight,
setWeight,
reset,
className,
onClose,
}: Props) => {
const { t } = useTranslation();
const [query, setQuery] = useState("");
return (
<Popover
onClose={() => onClose()}
className={clsx(
className,
"fade-in bg-base-200 border border-neutral-content p-3 w-[22.5rem] rounded-lg shadow-md"
)}
>
<div className="flex flex-col gap-3 w-full h-full">
<TextInput
className="p-2 rounded w-full h-7 text-sm"
placeholder={t("search")}
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
<div className="grid grid-cols-6 gap-1 w-full overflow-y-auto h-44 border border-neutral-content bg-base-100 rounded-md p-2">
<IconGrid
query={query}
color={color}
weight={weight}
iconName={iconName}
setIconName={setIconName}
/>
</div>
<div className="flex gap-3 color-picker w-full justify-between">
<HexColorPicker
color={color}
onChange={(e) => setColor(e)}
className="border border-neutral-content rounded-lg"
/>
<div className="grid grid-cols-2 gap-3 text-sm">
<label className="flex items-center cursor-pointer">
<input
type="radio"
className="radio radio-primary mr-2"
value="regular"
checked={weight === "regular"}
onChange={() => setWeight("regular")}
/>
{t("regular")}
</label>
<label className="flex items-center cursor-pointer">
<input
type="radio"
className="radio radio-primary mr-2"
value="thin"
checked={weight === "thin"}
onChange={() => setWeight("thin")}
/>
{t("thin")}
</label>
<label className="flex items-center cursor-pointer">
<input
type="radio"
className="radio radio-primary mr-2"
value="light"
checked={weight === "light"}
onChange={() => setWeight("light")}
/>
{t("light_icon")}
</label>
<label className="flex items-center cursor-pointer">
<input
type="radio"
className="radio radio-primary mr-2"
value="bold"
checked={weight === "bold"}
onChange={() => setWeight("bold")}
/>
{t("bold")}
</label>
<label className="flex items-center cursor-pointer">
<input
type="radio"
className="radio radio-primary mr-2"
value="fill"
checked={weight === "fill"}
onChange={() => setWeight("fill")}
/>
{t("fill")}
</label>
<label className="flex items-center cursor-pointer">
<input
type="radio"
className="radio radio-primary mr-2"
value="duotone"
checked={weight === "duotone"}
onChange={() => setWeight("duotone")}
/>
{t("duotone")}
</label>
</div>
</div>
<div className="flex flex-row gap-2 justify-between items-center mt-2">
<div
className="btn btn-ghost btn-xs w-fit"
onClick={reset as React.MouseEventHandler<HTMLDivElement>}
>
{t("reset_defaults")}
</div>
<p className="text-neutral text-xs">{t("click_out_to_apply")}</p>
</div>
</div>
</Popover>
);
};
export default IconPopover;
+12 -3
View File
@@ -1,10 +1,10 @@
import useCollectionStore from "@/store/collections";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { styles } from "./styles"; import { styles } from "./styles";
import { Options } from "./types"; import { Options } from "./types";
import CreatableSelect from "react-select/creatable"; import CreatableSelect from "react-select/creatable";
import Select from "react-select"; import Select from "react-select";
import { useCollections } from "@/hooks/store/collections";
type Props = { type Props = {
onChange: any; onChange: any;
@@ -16,6 +16,8 @@ type Props = {
} }
| undefined; | undefined;
creatable?: boolean; creatable?: boolean;
autoFocus?: boolean;
onBlur?: any;
}; };
export default function CollectionSelection({ export default function CollectionSelection({
@@ -23,8 +25,11 @@ export default function CollectionSelection({
defaultValue, defaultValue,
showDefaultValue = true, showDefaultValue = true,
creatable = true, creatable = true,
autoFocus,
onBlur,
}: Props) { }: Props) {
const { collections } = useCollectionStore(); const { data: collections = [] } = useCollections();
const router = useRouter(); const router = useRouter();
const [options, setOptions] = useState<Options[]>([]); const [options, setOptions] = useState<Options[]>([]);
@@ -75,7 +80,7 @@ export default function CollectionSelection({
return ( return (
<div <div
{...innerProps} {...innerProps}
className="px-2 py-2 last:border-0 border-b border-neutral-content hover:bg-neutral-content cursor-pointer" className="px-2 py-2 last:border-0 border-b border-neutral-content hover:bg-neutral-content duration-100 cursor-pointer"
> >
<div className="flex w-full justify-between items-center"> <div className="flex w-full justify-between items-center">
<span>{data.label}</span> <span>{data.label}</span>
@@ -103,6 +108,8 @@ export default function CollectionSelection({
onChange={onChange} onChange={onChange}
options={options} options={options}
styles={styles} styles={styles}
autoFocus={autoFocus}
onBlur={onBlur}
defaultValue={showDefaultValue ? defaultValue : null} defaultValue={showDefaultValue ? defaultValue : null}
components={{ components={{
Option: customOption, Option: customOption,
@@ -119,7 +126,9 @@ export default function CollectionSelection({
onChange={onChange} onChange={onChange}
options={options} options={options}
styles={styles} styles={styles}
autoFocus={autoFocus}
defaultValue={showDefaultValue ? defaultValue : null} defaultValue={showDefaultValue ? defaultValue : null}
onBlur={onBlur}
components={{ components={{
Option: customOption, Option: customOption,
}} }}
+14 -6
View File
@@ -1,24 +1,31 @@
import useTagStore from "@/store/tags";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import CreatableSelect from "react-select/creatable"; import CreatableSelect from "react-select/creatable";
import { styles } from "./styles"; import { styles } from "./styles";
import { Options } from "./types"; import { Options } from "./types";
import { useTags } from "@/hooks/store/tags";
type Props = { type Props = {
onChange: any; onChange: any;
defaultValue?: { defaultValue?: {
value: number; value?: number;
label: string; label: string;
}[]; }[];
autoFocus?: boolean;
onBlur?: any;
}; };
export default function TagSelection({ onChange, defaultValue }: Props) { export default function TagSelection({
const { tags } = useTagStore(); onChange,
defaultValue,
autoFocus,
onBlur,
}: Props) {
const { data: tags = [] } = useTags();
const [options, setOptions] = useState<Options[]>([]); const [options, setOptions] = useState<Options[]>([]);
useEffect(() => { useEffect(() => {
const formatedCollections = tags.map((e) => { const formatedCollections = tags.map((e: any) => {
return { value: e.id, label: e.name }; return { value: e.id, label: e.name };
}); });
@@ -34,8 +41,9 @@ export default function TagSelection({ onChange, defaultValue }: Props) {
options={options} options={options}
styles={styles} styles={styles}
defaultValue={defaultValue} defaultValue={defaultValue}
// menuPosition="fixed"
isMulti isMulti
autoFocus={autoFocus}
onBlur={onBlur}
/> />
); );
} }
+19 -6
View File
@@ -14,7 +14,11 @@ export const styles: StylesConfig = {
? "oklch(var(--p))" ? "oklch(var(--p))"
: "oklch(var(--nc))", : "oklch(var(--nc))",
}, },
transition: "all 50ms", transition: "all 100ms",
}),
menu: (styles) => ({
...styles,
zIndex: 10,
}), }),
control: (styles, state) => ({ control: (styles, state) => ({
...styles, ...styles,
@@ -50,19 +54,28 @@ export const styles: StylesConfig = {
multiValue: (styles) => { multiValue: (styles) => {
return { return {
...styles, ...styles,
backgroundColor: "#0ea5e9", backgroundColor: "oklch(var(--b2))",
color: "white", color: "oklch(var(--bc))",
display: "flex",
alignItems: "center",
gap: "0.1rem",
marginRight: "0.4rem",
}; };
}, },
multiValueLabel: (styles) => ({ multiValueLabel: (styles) => ({
...styles, ...styles,
color: "white", color: "oklch(var(--bc))",
}), }),
multiValueRemove: (styles) => ({ multiValueRemove: (styles) => ({
...styles, ...styles,
height: "1.2rem",
width: "1.2rem",
borderRadius: "100px",
transition: "all 100ms",
color: "oklch(var(--w))",
":hover": { ":hover": {
color: "white", color: "red",
backgroundColor: "#38bdf8", backgroundColor: "oklch(var(--nc))",
}, },
}), }),
menuPortal: (base) => ({ ...base, zIndex: 9999 }), menuPortal: (base) => ({ ...base, zIndex: 9999 }),
+1 -1
View File
@@ -8,7 +8,7 @@ const InstallApp = (props: Props) => {
const [isOpen, setIsOpen] = useState(true); const [isOpen, setIsOpen] = useState(true);
return isOpen && !isPWA() ? ( return isOpen && !isPWA() ? (
<div className="absolute left-0 right-0 bottom-10 w-full p-5"> <div className="fixed left-0 right-0 bottom-10 w-full px-5">
<div className="mx-auto w-fit p-2 flex justify-between gap-2 items-center border border-neutral-content rounded-xl bg-base-300 backdrop-blur-md bg-opacity-80 max-w-md"> <div className="mx-auto w-fit p-2 flex justify-between gap-2 items-center border border-neutral-content rounded-xl bg-base-300 backdrop-blur-md bg-opacity-80 max-w-md">
<svg <svg
xmlns="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg"
+687
View File
@@ -0,0 +1,687 @@
import React, { useEffect, useState } from "react";
import {
LinkIncludingShortenedCollectionAndTags,
ArchivedFormat,
} from "@/types/global";
import Link from "next/link";
import {
pdfAvailable,
readabilityAvailable,
monolithAvailable,
screenshotAvailable,
previewAvailable,
} from "@/lib/shared/getArchiveValidity";
import PreservedFormatRow from "@/components/PreserverdFormatRow";
import getPublicUserData from "@/lib/client/getPublicUserData";
import { useTranslation } from "next-i18next";
import { BeatLoader } from "react-spinners";
import { useUser } from "@/hooks/store/user";
import {
useGetLink,
useUpdateLink,
useUpdatePreview,
} from "@/hooks/store/links";
import LinkIcon from "./LinkViews/LinkComponents/LinkIcon";
import CopyButton from "./CopyButton";
import { useRouter } from "next/router";
import Icon from "./Icon";
import { IconWeight } from "@phosphor-icons/react";
import Image from "next/image";
import clsx from "clsx";
import toast from "react-hot-toast";
import CollectionSelection from "./InputSelect/CollectionSelection";
import TagSelection from "./InputSelect/TagSelection";
import unescapeString from "@/lib/client/unescapeString";
import IconPopover from "./IconPopover";
import TextInput from "./TextInput";
import usePermissions from "@/hooks/usePermissions";
type Props = {
className?: string;
activeLink: LinkIncludingShortenedCollectionAndTags;
standalone?: boolean;
mode?: "view" | "edit";
setMode?: Function;
onUpdateArchive?: Function;
};
export default function LinkDetails({
className,
activeLink,
standalone,
mode = "view",
setMode,
onUpdateArchive,
}: Props) {
const [link, setLink] =
useState<LinkIncludingShortenedCollectionAndTags>(activeLink);
useEffect(() => {
setLink(activeLink);
}, [activeLink]);
const permissions = usePermissions(link.collection.id as number);
const { t } = useTranslation();
const getLink = useGetLink();
const { data: user = {} } = useUser();
const [collectionOwner, setCollectionOwner] = useState({
id: null as unknown as number,
name: "",
username: "",
image: "",
archiveAsScreenshot: undefined as unknown as boolean,
archiveAsMonolith: undefined as unknown as boolean,
archiveAsPDF: undefined as unknown as boolean,
});
useEffect(() => {
const fetchOwner = async () => {
if (link.collection.ownerId !== user.id) {
const owner = await getPublicUserData(
link.collection.ownerId as number
);
setCollectionOwner(owner);
} else if (link.collection.ownerId === user.id) {
setCollectionOwner({
id: user.id as number,
name: user.name,
username: user.username as string,
image: user.image as string,
archiveAsScreenshot: user.archiveAsScreenshot as boolean,
archiveAsMonolith: user.archiveAsScreenshot as boolean,
archiveAsPDF: user.archiveAsPDF as boolean,
});
}
};
fetchOwner();
}, [link.collection.ownerId]);
const isReady = () => {
return (
link &&
(collectionOwner.archiveAsScreenshot === true
? link.pdf && link.pdf !== "pending"
: true) &&
(collectionOwner.archiveAsMonolith === true
? link.monolith && link.monolith !== "pending"
: true) &&
(collectionOwner.archiveAsPDF === true
? link.pdf && link.pdf !== "pending"
: true) &&
link.readable &&
link.readable !== "pending"
);
};
const atLeastOneFormatAvailable = () => {
return (
screenshotAvailable(link) ||
pdfAvailable(link) ||
readabilityAvailable(link) ||
monolithAvailable(link)
);
};
useEffect(() => {
(async () => {
await getLink.mutateAsync({
id: link.id as number,
});
})();
let interval: any;
if (!isReady()) {
interval = setInterval(async () => {
await getLink.mutateAsync({
id: link.id as number,
});
}, 5000);
} else {
if (interval) {
clearInterval(interval);
}
}
return () => {
if (interval) {
clearInterval(interval);
}
};
}, [link.monolith]);
const router = useRouter();
const isPublicRoute = router.pathname.startsWith("/public") ? true : false;
const updateLink = useUpdateLink();
const updatePreview = useUpdatePreview();
const submit = async (e?: any) => {
e?.preventDefault();
const { updatedAt: b, ...oldLink } = activeLink;
const { updatedAt: a, ...newLink } = link;
if (JSON.stringify(oldLink) === JSON.stringify(newLink)) {
return;
}
const load = toast.loading(t("updating"));
await updateLink.mutateAsync(link, {
onSettled: (data, error) => {
toast.dismiss(load);
if (error) {
toast.error(error.message);
} else {
toast.success(t("updated"));
setMode && setMode("view");
setLink(data);
}
},
});
};
const setCollection = (e: any) => {
if (e?.__isNew__) e.value = null;
setLink({
...link,
collection: { id: e?.value, name: e?.label, ownerId: e?.ownerId },
});
};
const setTags = (e: any) => {
const tagNames = e.map((e: any) => ({ name: e.label }));
setLink({ ...link, tags: tagNames });
};
const [iconPopover, setIconPopover] = useState(false);
return (
<div className={clsx(className)} data-vaul-no-drag>
<div
className={clsx(
standalone && "sm:border sm:border-neutral-content sm:rounded-2xl p-5"
)}
>
<div
className={clsx(
"overflow-hidden select-none relative group h-40 opacity-80",
standalone
? "sm:max-w-xl -mx-5 -mt-5 sm:rounded-t-2xl"
: "-mx-4 -mt-4"
)}
>
{previewAvailable(link) ? (
<Image
src={`/api/v1/archives/${link.id}?format=${ArchivedFormat.jpeg}&preview=true&updatedAt=${link.updatedAt}`}
width={1280}
height={720}
alt=""
className="object-cover scale-105 object-center h-full"
style={{
filter: "blur(1px)",
}}
onError={(e) => {
const target = e.target as HTMLElement;
target.style.display = "none";
}}
/>
) : link.preview === "unavailable" ? (
<div className="bg-gray-50 duration-100 h-40"></div>
) : (
<div className="duration-100 h-40 skeleton rounded-none"></div>
)}
{!standalone &&
(permissions === true || permissions?.canUpdate) &&
!isPublicRoute && (
<div className="absolute top-0 bottom-0 left-0 right-0 opacity-0 group-hover:opacity-100 duration-100 flex justify-end items-end">
<label className="btn btn-xs mb-2 mr-3 opacity-50 hover:opacity-100">
{t("upload_preview_image")}
<input
type="file"
accept="image/jpg, image/jpeg, image/png"
onChange={async (e) => {
const file = e.target.files?.[0];
if (!file) return;
const load = toast.loading(t("updating"));
await updatePreview.mutateAsync(
{
linkId: link.id as number,
file,
},
{
onSettled: (data, error) => {
toast.dismiss(load);
if (error) {
toast.error(error.message);
} else {
toast.success(t("updated"));
setLink({ updatedAt: data.updatedAt, ...link });
}
},
}
);
}}
className="hidden"
/>
</label>
</div>
)}
</div>
{!standalone &&
(permissions === true || permissions?.canUpdate) &&
!isPublicRoute ? (
<div className="-mt-14 ml-8 relative w-fit pb-2">
<div className="tooltip tooltip-bottom" data-tip={t("change_icon")}>
<LinkIcon
link={link}
className="hover:bg-opacity-70 duration-100 cursor-pointer"
onClick={() => setIconPopover(true)}
/>
</div>
{iconPopover && (
<IconPopover
color={link.color || "#006796"}
setColor={(color: string) => setLink({ ...link, color })}
weight={(link.iconWeight || "regular") as IconWeight}
setWeight={(iconWeight: string) =>
setLink({ ...link, iconWeight })
}
iconName={link.icon as string}
setIconName={(icon: string) => setLink({ ...link, icon })}
reset={() =>
setLink({
...link,
color: "",
icon: "",
iconWeight: "",
})
}
className="top-12"
onClose={() => {
setIconPopover(false);
submit();
}}
/>
)}
</div>
) : (
<div className="-mt-14 ml-8 relative w-fit pb-2">
<LinkIcon link={link} onClick={() => setIconPopover(true)} />
</div>
)}
<div className="max-w-xl sm:px-8 p-5 pb-8 pt-2">
{mode === "view" && (
<div className="text-xl mt-2 pr-7">
<p
className={clsx("relative w-fit", !link.name && "text-neutral")}
>
{unescapeString(link.name) || t("untitled")}
</p>
</div>
)}
{mode === "edit" && (
<>
<br />
<div>
<p className="text-sm mb-2 text-neutral relative w-fit flex justify-between">
{t("name")}
</p>
<TextInput
value={link.name}
onChange={(e) => setLink({ ...link, name: e.target.value })}
placeholder={t("placeholder_example_link")}
className="bg-base-200"
/>
</div>
</>
)}
{link.url && mode === "view" ? (
<>
<br />
<p className="text-sm mb-2 text-neutral">{t("link")}</p>
<div className="relative">
<div className="rounded-md p-2 bg-base-200 hide-scrollbar overflow-x-auto whitespace-nowrap flex justify-between items-center gap-2 pr-14">
<Link href={link.url} title={link.url} target="_blank">
{link.url}
</Link>
<div className="absolute right-0 px-2 bg-base-200">
<CopyButton text={link.url} />
</div>
</div>
</div>
</>
) : activeLink.url ? (
<>
<br />
<div>
<p className="text-sm mb-2 text-neutral relative w-fit flex justify-between">
{t("link")}
</p>
<TextInput
value={link.url || ""}
onChange={(e) => setLink({ ...link, url: e.target.value })}
placeholder={t("placeholder_example_link")}
className="bg-base-200"
/>
</div>
</>
) : undefined}
<br />
<div className="relative">
<p className="text-sm mb-2 text-neutral relative w-fit flex justify-between">
{t("collection")}
</p>
{mode === "view" ? (
<div className="relative">
<Link
href={
isPublicRoute
? `/public/collections/${link.collection.id}`
: `/collections/${link.collection.id}`
}
className="rounded-md p-2 bg-base-200 border border-base-200 hide-scrollbar overflow-x-auto whitespace-nowrap flex justify-between items-center gap-2 pr-14"
>
<p>{link.collection.name}</p>
<div className="absolute right-0 px-2 bg-base-200">
{link.collection.icon ? (
<Icon
icon={link.collection.icon}
size={30}
weight={
(link.collection.iconWeight ||
"regular") as IconWeight
}
color={link.collection.color}
/>
) : (
<i
className="bi-folder-fill text-2xl"
style={{ color: link.collection.color }}
></i>
)}
</div>
</Link>
</div>
) : (
<CollectionSelection
onChange={setCollection}
defaultValue={
link.collection.id
? { value: link.collection.id, label: link.collection.name }
: { value: null as unknown as number, label: "Unorganized" }
}
creatable={false}
/>
)}
</div>
<br />
<div className="relative">
<p className="text-sm mb-2 text-neutral relative w-fit flex justify-between">
{t("tags")}
</p>
{mode === "view" ? (
<div className="flex gap-2 flex-wrap rounded-md p-2 bg-base-200 border border-base-200 w-full text-xs">
{link.tags && link.tags[0] ? (
link.tags.map((tag) =>
isPublicRoute ? (
<div
key={tag.id}
className="bg-base-200 p-1 hover:bg-neutral-content rounded-md duration-100"
>
{tag.name}
</div>
) : (
<Link
href={"/tags/" + tag.id}
key={tag.id}
className="bg-base-200 p-1 hover:bg-neutral-content btn btn-xs btn-ghost rounded-md"
>
{tag.name}
</Link>
)
)
) : (
<div className="text-neutral text-base">{t("no_tags")}</div>
)}
</div>
) : (
<TagSelection
onChange={setTags}
defaultValue={link.tags.map((e) => ({
label: e.name,
value: e.id,
}))}
/>
)}
</div>
<br />
<div className="relative">
<p className="text-sm mb-2 text-neutral relative w-fit flex justify-between">
{t("description")}
</p>
{mode === "view" ? (
<div className="rounded-md p-2 bg-base-200 hyphens-auto">
{link.description ? (
<p>{link.description}</p>
) : (
<p className="text-neutral">{t("no_description_provided")}</p>
)}
</div>
) : (
<textarea
value={unescapeString(link.description) as string}
onChange={(e) =>
setLink({ ...link, description: e.target.value })
}
placeholder={t("link_description_placeholder")}
className="resize-none w-full rounded-md p-2 h-32 border-neutral-content bg-base-200 focus:border-primary border-solid border outline-none duration-100"
/>
)}
</div>
{mode === "view" && (
<div>
<br />
<div className="flex gap-1 items-center mb-2">
<p
className="text-sm text-neutral"
title={t("available_formats")}
>
{link.url ? t("preserved_formats") : t("file")}
</p>
{onUpdateArchive &&
(permissions === true || permissions?.canUpdate) &&
!isPublicRoute && (
<div
className="tooltip tooltip-bottom"
data-tip={t("refresh_preserved_formats")}
>
<button
className="btn btn-xs btn-ghost btn-square text-neutral"
onClick={() => onUpdateArchive()}
>
<i className="bi-arrow-clockwise text-sm" />
</button>
</div>
)}
</div>
<div className={`flex flex-col rounded-md p-3 bg-base-200`}>
{monolithAvailable(link) ? (
<>
<PreservedFormatRow
name={t("webpage")}
icon={"bi-filetype-html"}
format={ArchivedFormat.monolith}
link={link}
downloadable={true}
/>
<hr className="m-3 border-t border-neutral-content" />
</>
) : undefined}
{screenshotAvailable(link) ? (
<>
<PreservedFormatRow
name={t("screenshot")}
icon={"bi-file-earmark-image"}
format={
link?.image?.endsWith("png")
? ArchivedFormat.png
: ArchivedFormat.jpeg
}
link={link}
downloadable={true}
/>
<hr className="m-3 border-t border-neutral-content" />
</>
) : undefined}
{pdfAvailable(link) ? (
<>
<PreservedFormatRow
name={t("pdf")}
icon={"bi-file-earmark-pdf"}
format={ArchivedFormat.pdf}
link={link}
downloadable={true}
/>
<hr className="m-3 border-t border-neutral-content" />
</>
) : undefined}
{readabilityAvailable(link) ? (
<>
<PreservedFormatRow
name={t("readable")}
icon={"bi-file-earmark-text"}
format={ArchivedFormat.readability}
link={link}
/>
<hr className="m-3 border-t border-neutral-content" />
</>
) : undefined}
{!isReady() && !atLeastOneFormatAvailable() ? (
<div
className={`w-full h-full flex flex-col justify-center p-10`}
>
<BeatLoader
color="oklch(var(--p))"
className="mx-auto mb-3"
size={30}
/>
<p className="text-center text-2xl">
{t("preservation_in_queue")}
</p>
<p className="text-center text-lg">
{t("check_back_later")}
</p>
</div>
) : link.url && !isReady() && atLeastOneFormatAvailable() ? (
<div
className={`w-full h-full flex flex-col justify-center p-5`}
>
<BeatLoader
color="oklch(var(--p))"
className="mx-auto mb-3"
size={20}
/>
<p className="text-center">{t("there_are_more_formats")}</p>
<p className="text-center text-sm">
{t("check_back_later")}
</p>
</div>
) : undefined}
{link.url && (
<Link
href={`https://web.archive.org/web/${link?.url?.replace(
/(^\w+:|^)\/\//,
""
)}`}
target="_blank"
className="text-neutral mx-auto duration-100 hover:opacity-60 flex gap-2 w-1/2 justify-center items-center text-sm"
>
<p className="whitespace-nowrap">
{t("view_latest_snapshot")}
</p>
<i className="bi-box-arrow-up-right" />
</Link>
)}
</div>
</div>
)}
{mode === "view" ? (
<>
<br />
<p className="text-neutral text-xs text-center">
{t("saved")}{" "}
{new Date(link.createdAt || "").toLocaleDateString("en-US", {
month: "short",
day: "numeric",
year: "numeric",
})}{" "}
at{" "}
{new Date(link.createdAt || "").toLocaleTimeString("en-US", {
hour: "numeric",
minute: "numeric",
})}
</p>
</>
) : (
<>
<br />
<div className="flex justify-end items-center">
<button
className={clsx(
"btn btn-accent text-white",
JSON.stringify(activeLink) === JSON.stringify(link)
? "btn-disabled"
: "dark:border-violet-400"
)}
onClick={submit}
>
{t("save_changes")}
</button>
</div>
</>
)}
</div>
</div>
</div>
);
}
+71 -60
View File
@@ -5,17 +5,18 @@ import ViewDropdown from "./ViewDropdown";
import { TFunction } from "i18next"; import { TFunction } from "i18next";
import BulkDeleteLinksModal from "./ModalContent/BulkDeleteLinksModal"; import BulkDeleteLinksModal from "./ModalContent/BulkDeleteLinksModal";
import BulkEditLinksModal from "./ModalContent/BulkEditLinksModal"; import BulkEditLinksModal from "./ModalContent/BulkEditLinksModal";
import toast from "react-hot-toast";
import useCollectivePermissions from "@/hooks/useCollectivePermissions"; import useCollectivePermissions from "@/hooks/useCollectivePermissions";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import useLinkStore from "@/store/links"; import useLinkStore from "@/store/links";
import { Sort } from "@/types/global"; import { Sort, ViewMode } from "@/types/global";
import { useBulkDeleteLinks, useLinks } from "@/hooks/store/links";
import toast from "react-hot-toast";
type Props = { type Props = {
children: React.ReactNode; children: React.ReactNode;
t: TFunction<"translation", undefined>; t: TFunction<"translation", undefined>;
viewMode: string; viewMode: ViewMode;
setViewMode: Dispatch<SetStateAction<string>>; setViewMode: Dispatch<SetStateAction<ViewMode>>;
searchFilter?: { searchFilter?: {
name: boolean; name: boolean;
url: boolean; url: boolean;
@@ -48,8 +49,11 @@ const LinkListOptions = ({
editMode, editMode,
setEditMode, setEditMode,
}: Props) => { }: Props) => {
const { links, selectedLinks, setSelectedLinks, deleteLinksById } = const { selectedLinks, setSelectedLinks } = useLinkStore();
useLinkStore();
const deleteLinksById = useBulkDeleteLinks();
const { links } = useLinks();
const router = useRouter(); const router = useRouter();
@@ -73,23 +77,23 @@ const LinkListOptions = ({
}; };
const bulkDeleteLinks = async () => { const bulkDeleteLinks = async () => {
const load = toast.loading(t("deleting_selections")); const load = toast.loading(t("deleting"));
const response = await deleteLinksById( await deleteLinksById.mutateAsync(
selectedLinks.map((link) => link.id as number) selectedLinks.map((link) => link.id as number),
{
onSettled: (data, error) => {
toast.dismiss(load);
if (error) {
toast.error(error.message);
} else {
setSelectedLinks([]);
toast.success(t("deleted"));
}
},
}
); );
toast.dismiss(load);
if (response.ok) {
toast.success(
selectedLinks.length === 1
? t("link_deleted")
: t("links_deleted", { count: selectedLinks.length })
);
} else {
toast.error(response.data as string);
}
}; };
return ( return (
@@ -99,57 +103,64 @@ const LinkListOptions = ({
<div className="flex gap-3 items-center justify-end"> <div className="flex gap-3 items-center justify-end">
<div className="flex gap-2 items-center mt-2"> <div className="flex gap-2 items-center mt-2">
{links.length > 0 && editMode !== undefined && setEditMode && ( {links &&
<div links.length > 0 &&
role="button" editMode !== undefined &&
onClick={() => { setEditMode && (
setEditMode(!editMode); <div
setSelectedLinks([]); role="button"
}} onClick={() => {
className={`btn btn-square btn-sm btn-ghost ${ setEditMode(!editMode);
editMode setSelectedLinks([]);
? "bg-primary/20 hover:bg-primary/20" }}
: "hover:bg-neutral/20" className={`btn btn-square btn-sm btn-ghost ${
}`} editMode
> ? "bg-primary/20 hover:bg-primary/20"
<i className="bi-pencil-fill text-neutral text-xl"></i> : "hover:bg-neutral/20"
</div> }`}
)} >
<i className="bi-pencil-fill text-neutral text-xl"></i>
</div>
)}
{searchFilter && setSearchFilter && ( {searchFilter && setSearchFilter && (
<FilterSearchDropdown <FilterSearchDropdown
searchFilter={searchFilter} searchFilter={searchFilter}
setSearchFilter={setSearchFilter} setSearchFilter={setSearchFilter}
/> />
)} )}
<SortDropdown sortBy={sortBy} setSort={setSortBy} t={t} /> <SortDropdown
sortBy={sortBy}
setSort={(value) => {
setSortBy(value);
}}
t={t}
/>
<ViewDropdown viewMode={viewMode} setViewMode={setViewMode} /> <ViewDropdown viewMode={viewMode} setViewMode={setViewMode} />
</div> </div>
</div> </div>
</div> </div>
{editMode && links.length > 0 && ( {links && editMode && links.length > 0 && (
<div className="w-full flex justify-between items-center min-h-[32px]"> <div className="w-full flex justify-between items-center min-h-[32px]">
{links.length > 0 && ( <div className="flex gap-3 ml-3">
<div className="flex gap-3 ml-3"> <input
<input type="checkbox"
type="checkbox" className="checkbox checkbox-primary"
className="checkbox checkbox-primary" onChange={() => handleSelectAll()}
onChange={() => handleSelectAll()} checked={
checked={ selectedLinks.length === links.length && links.length > 0
selectedLinks.length === links.length && links.length > 0 }
} />
/> {selectedLinks.length > 0 ? (
{selectedLinks.length > 0 ? ( <span>
<span> {selectedLinks.length === 1
{selectedLinks.length === 1 ? t("link_selected")
? t("link_selected") : t("links_selected", { count: selectedLinks.length })}
: t("links_selected", { count: selectedLinks.length })} </span>
</span> ) : (
) : ( <span>{t("nothing_selected")}</span>
<span>{t("nothing_selected")}</span> )}
)} </div>
</div>
)}
<div className="flex gap-3"> <div className="flex gap-3">
<button <button
onClick={() => setBulkEditLinksModal(true)} onClick={() => setBulkEditLinksModal(true)}
-39
View File
@@ -1,39 +0,0 @@
import LinkCard from "@/components/LinkViews/LinkCard";
import { LinkIncludingShortenedCollectionAndTags } from "@/types/global";
import { link } from "fs";
import { GridLoader } from "react-spinners";
export default function CardView({
links,
editMode,
isLoading,
}: {
links: LinkIncludingShortenedCollectionAndTags[];
editMode?: boolean;
isLoading?: boolean;
}) {
return (
<div className="grid min-[1901px]:grid-cols-5 min-[1501px]:grid-cols-4 min-[881px]:grid-cols-3 min-[551px]:grid-cols-2 grid-cols-1 gap-5 pb-5">
{links.map((e, i) => {
return (
<LinkCard
key={i}
link={e}
count={i}
flipDropdown={i === links.length - 1}
editMode={editMode}
/>
);
})}
{isLoading && links.length > 0 && (
<GridLoader
color="oklch(var(--p))"
loading={true}
size={20}
className="fixed top-5 right-5 opacity-50 z-30"
/>
)}
</div>
);
}
-38
View File
@@ -1,38 +0,0 @@
import LinkList from "@/components/LinkViews/LinkList";
import { LinkIncludingShortenedCollectionAndTags } from "@/types/global";
import { GridLoader } from "react-spinners";
export default function ListView({
links,
editMode,
isLoading,
}: {
links: LinkIncludingShortenedCollectionAndTags[];
editMode?: boolean;
isLoading?: boolean;
}) {
return (
<div className="flex gap-1 flex-col">
{links.map((e, i) => {
return (
<LinkList
key={i}
link={e}
count={i}
flipDropdown={i === links.length - 1}
editMode={editMode}
/>
);
})}
{isLoading && links.length > 0 && (
<GridLoader
color="oklch(var(--p))"
loading={true}
size={20}
className="fixed top-5 right-5 opacity-50 z-30"
/>
)}
</div>
);
}
@@ -1,58 +0,0 @@
import LinkMasonry from "@/components/LinkViews/LinkMasonry";
import { LinkIncludingShortenedCollectionAndTags } from "@/types/global";
import { GridLoader } from "react-spinners";
import Masonry from "react-masonry-css";
import resolveConfig from "tailwindcss/resolveConfig";
import tailwindConfig from "../../../tailwind.config.js";
import { useMemo } from "react";
export default function MasonryView({
links,
editMode,
isLoading,
}: {
links: LinkIncludingShortenedCollectionAndTags[];
editMode?: boolean;
isLoading?: boolean;
}) {
const fullConfig = resolveConfig(tailwindConfig as any);
const breakpointColumnsObj = useMemo(() => {
return {
default: 5,
1900: 4,
1500: 3,
880: 2,
550: 1,
};
}, []);
return (
<Masonry
breakpointCols={breakpointColumnsObj}
columnClassName="flex flex-col gap-5 !w-full"
className="grid min-[1901px]:grid-cols-5 min-[1501px]:grid-cols-4 min-[881px]:grid-cols-3 min-[551px]:grid-cols-2 grid-cols-1 gap-5 pb-5"
>
{links.map((e, i) => {
return (
<LinkMasonry
key={i}
link={e}
count={i}
flipDropdown={i === links.length - 1}
editMode={editMode}
/>
);
})}
{isLoading && links.length > 0 && (
<GridLoader
color="oklch(var(--p))"
loading={true}
size={20}
className="fixed top-5 right-5 opacity-50 z-30"
/>
)}
</Masonry>
);
}
-254
View File
@@ -1,254 +0,0 @@
import {
ArchivedFormat,
CollectionIncludingMembersAndLinkCount,
LinkIncludingShortenedCollectionAndTags,
} from "@/types/global";
import { useEffect, useRef, useState } from "react";
import useLinkStore from "@/store/links";
import useCollectionStore from "@/store/collections";
import unescapeString from "@/lib/client/unescapeString";
import LinkActions from "@/components/LinkViews/LinkComponents/LinkActions";
import LinkDate from "@/components/LinkViews/LinkComponents/LinkDate";
import LinkCollection from "@/components/LinkViews/LinkComponents/LinkCollection";
import Image from "next/image";
import { previewAvailable } from "@/lib/shared/getArchiveValidity";
import Link from "next/link";
import LinkIcon from "./LinkComponents/LinkIcon";
import useOnScreen from "@/hooks/useOnScreen";
import { generateLinkHref } from "@/lib/client/generateLinkHref";
import useAccountStore from "@/store/account";
import usePermissions from "@/hooks/usePermissions";
import toast from "react-hot-toast";
import LinkTypeBadge from "./LinkComponents/LinkTypeBadge";
import { useTranslation } from "next-i18next";
type Props = {
link: LinkIncludingShortenedCollectionAndTags;
count: number;
className?: string;
flipDropdown?: boolean;
editMode?: boolean;
};
export default function LinkCard({ link, flipDropdown, editMode }: Props) {
const { t } = useTranslation();
const viewMode = localStorage.getItem("viewMode") || "card";
const { collections } = useCollectionStore();
const { account } = useAccountStore();
const { links, getLink, setSelectedLinks, selectedLinks } = useLinkStore();
useEffect(() => {
if (!editMode) {
setSelectedLinks([]);
}
}, [editMode]);
const handleCheckboxClick = (
link: LinkIncludingShortenedCollectionAndTags
) => {
if (selectedLinks.includes(link)) {
setSelectedLinks(selectedLinks.filter((e) => e !== link));
} else {
setSelectedLinks([...selectedLinks, link]);
}
};
let shortendURL;
try {
if (link.url) {
shortendURL = new URL(link.url).host.toLowerCase();
}
} catch (error) {
console.log(error);
}
const [collection, setCollection] =
useState<CollectionIncludingMembersAndLinkCount>(
collections.find(
(e) => e.id === link.collection.id
) as CollectionIncludingMembersAndLinkCount
);
useEffect(() => {
setCollection(
collections.find(
(e) => e.id === link.collection.id
) as CollectionIncludingMembersAndLinkCount
);
}, [collections, links]);
const ref = useRef<HTMLDivElement>(null);
const isVisible = useOnScreen(ref);
const permissions = usePermissions(collection?.id as number);
useEffect(() => {
let interval: any;
if (
isVisible &&
!link.preview?.startsWith("archives") &&
link.preview !== "unavailable"
) {
interval = setInterval(async () => {
getLink(link.id as number);
}, 5000);
}
return () => {
if (interval) {
clearInterval(interval);
}
};
}, [isVisible, link.preview]);
const [showInfo, setShowInfo] = useState(false);
const selectedStyle = selectedLinks.some(
(selectedLink) => selectedLink.id === link.id
)
? "border-primary bg-base-300"
: "border-neutral-content";
const selectable =
editMode &&
(permissions === true || permissions?.canCreate || permissions?.canDelete);
return (
<div
ref={ref}
className={`${selectedStyle} border border-solid border-neutral-content bg-base-200 shadow-md hover:shadow-none duration-100 rounded-2xl relative`}
onClick={() =>
selectable
? handleCheckboxClick(link)
: editMode
? toast.error(t("link_selection_error"))
: undefined
}
>
<div
className="rounded-2xl cursor-pointer h-full flex flex-col justify-between"
onClick={() =>
!editMode && window.open(generateLinkHref(link, account), "_blank")
}
>
<div>
<div className="relative rounded-t-2xl h-40 overflow-hidden">
{previewAvailable(link) ? (
<Image
src={`/api/v1/archives/${link.id}?format=${ArchivedFormat.jpeg}&preview=true`}
width={1280}
height={720}
alt=""
className="rounded-t-2xl select-none object-cover z-10 h-40 w-full shadow opacity-80 scale-105"
style={
link.type !== "image" ? { filter: "blur(1px)" } : undefined
}
draggable="false"
onError={(e) => {
const target = e.target as HTMLElement;
target.style.display = "none";
}}
/>
) : link.preview === "unavailable" ? (
<div className="bg-gray-50 duration-100 h-40 bg-opacity-80"></div>
) : (
<div className="duration-100 h-40 bg-opacity-80 skeleton rounded-none"></div>
)}
{link.type !== "image" && (
<div className="absolute top-0 left-0 right-0 bottom-0 rounded-t-2xl flex items-center justify-center shadow rounded-md">
<LinkIcon link={link} />
</div>
)}
</div>
<hr className="divider my-0 border-t border-neutral-content h-[1px]" />
</div>
<div className="flex flex-col justify-between h-full">
<div className="p-3 flex flex-col gap-2">
<p className="truncate w-full pr-9 text-primary text-sm">
{unescapeString(link.name)}
</p>
<LinkTypeBadge link={link} />
</div>
<div>
<hr className="divider mt-2 mb-1 last:hidden border-t border-neutral-content h-[1px]" />
<div className="flex justify-between text-xs text-neutral px-3 pb-1 gap-2">
<div className="cursor-pointer truncate">
{collection && (
<LinkCollection link={link} collection={collection} />
)}
</div>
<LinkDate link={link} />
</div>
</div>
</div>
</div>
{showInfo && (
<div className="p-3 absolute z-30 top-0 left-0 right-0 bottom-0 bg-base-200 rounded-[0.9rem] fade-in overflow-y-auto">
<div
onClick={() => setShowInfo(!showInfo)}
className=" float-right btn btn-sm outline-none btn-circle btn-ghost z-10"
>
<i className="bi-x text-neutral text-2xl"></i>
</div>
<p className="text-neutral text-lg font-semibold">
{t("description")}
</p>
<hr className="divider my-2 border-t border-neutral-content h-[1px]" />
<p>
{link.description ? (
unescapeString(link.description)
) : (
<span className="text-neutral text-sm">
{t("no_description")}
</span>
)}
</p>
{link.tags && link.tags[0] && (
<>
<p className="text-neutral text-lg mt-3 font-semibold">
{t("tags")}
</p>
<hr className="divider my-2 border-t border-neutral-content h-[1px]" />
<div className="flex gap-3 items-center flex-wrap mt-2 truncate relative">
<div className="flex gap-1 items-center flex-wrap">
{link.tags.map((e, i) => (
<Link
href={"/tags/" + e.id}
key={i}
onClick={(e) => {
e.stopPropagation();
}}
className="btn btn-xs btn-ghost truncate max-w-[19rem]"
>
#{e.name}
</Link>
))}
</div>
</div>
</>
)}
</div>
)}
<LinkActions
link={link}
collection={collection}
position="top-[10.75rem] right-3"
toggleShowInfo={() => setShowInfo(!showInfo)}
linkInfo={showInfo}
flipDropdown={flipDropdown}
/>
</div>
);
}
@@ -4,192 +4,189 @@ import {
LinkIncludingShortenedCollectionAndTags, LinkIncludingShortenedCollectionAndTags,
} from "@/types/global"; } from "@/types/global";
import usePermissions from "@/hooks/usePermissions"; import usePermissions from "@/hooks/usePermissions";
import EditLinkModal from "@/components/ModalContent/EditLinkModal";
import DeleteLinkModal from "@/components/ModalContent/DeleteLinkModal"; import DeleteLinkModal from "@/components/ModalContent/DeleteLinkModal";
import PreservedFormatsModal from "@/components/ModalContent/PreservedFormatsModal";
import useLinkStore from "@/store/links";
import { toast } from "react-hot-toast";
import useAccountStore from "@/store/account";
import { dropdownTriggerer } from "@/lib/client/utils"; import { dropdownTriggerer } from "@/lib/client/utils";
import { useTranslation } from "next-i18next"; import { useTranslation } from "next-i18next";
import { useDeleteLink, useGetLink } from "@/hooks/store/links";
import toast from "react-hot-toast";
import LinkModal from "@/components/ModalContent/LinkModal";
import { useRouter } from "next/router";
import clsx from "clsx";
import usePinLink from "@/lib/client/pinLink";
type Props = { type Props = {
link: LinkIncludingShortenedCollectionAndTags; link: LinkIncludingShortenedCollectionAndTags;
collection: CollectionIncludingMembersAndLinkCount; collection: CollectionIncludingMembersAndLinkCount;
position?: string; btnStyle?: string;
toggleShowInfo?: () => void;
linkInfo?: boolean;
alignToTop?: boolean;
flipDropdown?: boolean;
}; };
export default function LinkActions({ export default function LinkActions({ link, btnStyle }: Props) {
link,
toggleShowInfo,
position,
linkInfo,
alignToTop,
flipDropdown,
}: Props) {
const { t } = useTranslation(); const { t } = useTranslation();
const permissions = usePermissions(link.collection.id as number); const permissions = usePermissions(link.collection.id as number);
const getLink = useGetLink();
const pinLink = usePinLink();
const [editLinkModal, setEditLinkModal] = useState(false); const [editLinkModal, setEditLinkModal] = useState(false);
const [linkModal, setLinkModal] = useState(false);
const [deleteLinkModal, setDeleteLinkModal] = useState(false); const [deleteLinkModal, setDeleteLinkModal] = useState(false);
const [preservedFormatsModal, setPreservedFormatsModal] = useState(false);
const { account } = useAccountStore(); const deleteLink = useDeleteLink();
const { removeLink, updateLink } = useLinkStore(); const updateArchive = async () => {
const load = toast.loading(t("sending_request"));
const pinLink = async () => { const response = await fetch(`/api/v1/links/${link?.id}/archive`, {
const isAlreadyPinned = link?.pinnedBy && link.pinnedBy[0]; method: "PUT",
const load = toast.loading(t("applying"));
const response = await updateLink({
...link,
pinnedBy: isAlreadyPinned ? undefined : [{ id: account.id }],
}); });
const data = await response.json();
toast.dismiss(load); toast.dismiss(load);
if (response.ok) { if (response.ok) {
toast.success(isAlreadyPinned ? t("link_unpinned") : t("link_unpinned")); await getLink.mutateAsync({ id: link.id as number });
} else {
toast.error(response.data as string); toast.success(t("link_being_archived"));
} } else toast.error(data.response);
}; };
const deleteLink = async () => { const router = useRouter();
const load = toast.loading(t("deleting"));
const response = await removeLink(link.id as number); const isPublicRoute = router.pathname.startsWith("/public") ? true : false;
toast.dismiss(load);
if (response.ok) {
toast.success(t("deleted"));
} else {
toast.error(response.data as string);
}
};
return ( return (
<> <>
<div {isPublicRoute ? (
className={`dropdown dropdown-left absolute ${
position || "top-3 right-3"
} ${alignToTop ? "" : "dropdown-end"} z-20`}
>
<div <div
tabIndex={0} className="absolute top-3 right-3 group-hover:opacity-100 group-focus-within:opacity-100 opacity-0 duration-100"
role="button"
onMouseDown={dropdownTriggerer} onMouseDown={dropdownTriggerer}
className="btn btn-ghost btn-sm btn-square text-neutral" onClick={() => setLinkModal(true)}
> >
<i title="More" className="bi-three-dots text-xl" /> <div className={clsx("btn btn-sm btn-square text-neutral", btnStyle)}>
<i title="More" className="bi-info-circle text-xl" />
</div>
</div> </div>
<ul ) : (
className={`dropdown-content z-[20] menu shadow bg-base-200 border border-neutral-content rounded-box w-44 mr-1 ${ <div
alignToTop ? "" : "translate-y-10" className={`dropdown dropdown-end absolute top-3 right-3 group-hover:opacity-100 group-focus-within:opacity-100 opacity-0 duration-100 z-20`}
}`}
> >
<li> <div
<div tabIndex={0}
role="button" role="button"
tabIndex={0} onMouseDown={dropdownTriggerer}
onClick={() => { className={clsx("btn btn-sm btn-square text-neutral", btnStyle)}
(document?.activeElement as HTMLElement)?.blur(); >
pinLink(); <i title="More" className="bi-three-dots text-xl" />
}} </div>
> <ul
{link?.pinnedBy && link.pinnedBy[0] className={
? t("unpin") "dropdown-content z-[20] menu shadow bg-base-200 border border-neutral-content rounded-box mt-1"
: t("pin_to_dashboard")} }
</div> >
</li>
{linkInfo !== undefined && toggleShowInfo ? (
<li> <li>
<div <div
role="button" role="button"
tabIndex={0} tabIndex={0}
onClick={() => { onClick={() => {
(document?.activeElement as HTMLElement)?.blur(); (document?.activeElement as HTMLElement)?.blur();
toggleShowInfo(); pinLink(link);
}} }}
className="whitespace-nowrap"
> >
{!linkInfo ? t("show_link_details") : t("hide_link_details")} {link?.pinnedBy && link.pinnedBy[0]
? t("unpin")
: t("pin_to_dashboard")}
</div> </div>
</li> </li>
) : undefined}
{permissions === true || permissions?.canUpdate ? (
<li> <li>
<div <div
role="button" role="button"
tabIndex={0} tabIndex={0}
onClick={() => { onClick={() => {
(document?.activeElement as HTMLElement)?.blur(); (document?.activeElement as HTMLElement)?.blur();
setEditLinkModal(true); setLinkModal(true);
}} }}
className="whitespace-nowrap"
> >
{t("edit_link")} {t("show_link_details")}
</div> </div>
</li> </li>
) : undefined} {(permissions === true || permissions?.canUpdate) && (
{link.type === "url" && ( <li>
<li> <div
<div role="button"
role="button" tabIndex={0}
tabIndex={0} onClick={() => {
onClick={() => { (document?.activeElement as HTMLElement)?.blur();
(document?.activeElement as HTMLElement)?.blur(); setEditLinkModal(true);
setPreservedFormatsModal(true); }}
}} className="whitespace-nowrap"
> >
{t("preserved_formats")} {t("edit_link")}
</div> </div>
</li> </li>
)} )}
{permissions === true || permissions?.canDelete ? ( {(permissions === true || permissions?.canDelete) && (
<li> <li>
<div <div
role="button" role="button"
tabIndex={0} tabIndex={0}
onClick={(e) => { onClick={async (e) => {
(document?.activeElement as HTMLElement)?.blur(); (document?.activeElement as HTMLElement)?.blur();
e.shiftKey ? deleteLink() : setDeleteLinkModal(true); console.log(e.shiftKey);
}} e.shiftKey
> ? (async () => {
{t("delete")} const load = toast.loading(t("deleting"));
</div>
</li>
) : undefined}
</ul>
</div>
{editLinkModal ? ( await deleteLink.mutateAsync(link.id as number, {
<EditLinkModal onSettled: (data, error) => {
toast.dismiss(load);
if (error) {
toast.error(error.message);
} else {
toast.success(t("deleted"));
}
},
});
})()
: setDeleteLinkModal(true);
}}
className="whitespace-nowrap"
>
{t("delete")}
</div>
</li>
)}
</ul>
</div>
)}
{editLinkModal && (
<LinkModal
onClose={() => setEditLinkModal(false)} onClose={() => setEditLinkModal(false)}
activeLink={link} onPin={() => pinLink(link)}
onUpdateArchive={updateArchive}
onDelete={() => setDeleteLinkModal(true)}
link={link}
activeMode="edit"
/> />
) : undefined} )}
{deleteLinkModal ? ( {deleteLinkModal && (
<DeleteLinkModal <DeleteLinkModal
onClose={() => setDeleteLinkModal(false)} onClose={() => setDeleteLinkModal(false)}
activeLink={link} activeLink={link}
/> />
) : undefined} )}
{preservedFormatsModal ? ( {linkModal && (
<PreservedFormatsModal <LinkModal
onClose={() => setPreservedFormatsModal(false)} onClose={() => setLinkModal(false)}
activeLink={link} onPin={() => pinLink(link)}
onUpdateArchive={updateArchive}
onDelete={() => setDeleteLinkModal(true)}
link={link}
/> />
) : undefined} )}
{/* {expandedLink ? (
<ExpandedLink onClose={() => setExpandedLink(false)} link={link} />
) : undefined} */}
</> </>
); );
} }
@@ -0,0 +1,241 @@
import {
ArchivedFormat,
CollectionIncludingMembersAndLinkCount,
LinkIncludingShortenedCollectionAndTags,
} from "@/types/global";
import { useEffect, useMemo, useRef, useState } from "react";
import useLinkStore from "@/store/links";
import unescapeString from "@/lib/client/unescapeString";
import LinkActions from "@/components/LinkViews/LinkComponents/LinkActions";
import LinkDate from "@/components/LinkViews/LinkComponents/LinkDate";
import LinkCollection from "@/components/LinkViews/LinkComponents/LinkCollection";
import Image from "next/image";
import { previewAvailable } from "@/lib/shared/getArchiveValidity";
import LinkIcon from "./LinkIcon";
import useOnScreen from "@/hooks/useOnScreen";
import { generateLinkHref } from "@/lib/client/generateLinkHref";
import usePermissions from "@/hooks/usePermissions";
import toast from "react-hot-toast";
import LinkTypeBadge from "./LinkTypeBadge";
import { useTranslation } from "next-i18next";
import { useCollections } from "@/hooks/store/collections";
import { useUser } from "@/hooks/store/user";
import { useGetLink, useLinks } from "@/hooks/store/links";
import { useRouter } from "next/router";
import useLocalSettingsStore from "@/store/localSettings";
import LinkPin from "./LinkPin";
type Props = {
link: LinkIncludingShortenedCollectionAndTags;
count: number;
columns: number;
className?: string;
editMode?: boolean;
};
export default function LinkCard({ link, columns, editMode }: Props) {
const { t } = useTranslation();
const heightMap = {
1: "h-44",
2: "h-40",
3: "h-36",
4: "h-32",
5: "h-28",
6: "h-24",
7: "h-20",
8: "h-20",
};
const imageHeightClass = useMemo(
() => (columns ? heightMap[columns as keyof typeof heightMap] : "h-40"),
[columns]
);
const { data: collections = [] } = useCollections();
const { data: user = {} } = useUser();
const { setSelectedLinks, selectedLinks } = useLinkStore();
const {
settings: { show },
} = useLocalSettingsStore();
const {
data: { data: links = [] },
} = useLinks();
const getLink = useGetLink();
useEffect(() => {
if (!editMode) {
setSelectedLinks([]);
}
}, [editMode]);
const handleCheckboxClick = (
link: LinkIncludingShortenedCollectionAndTags
) => {
if (selectedLinks.includes(link)) {
setSelectedLinks(selectedLinks.filter((e) => e !== link));
} else {
setSelectedLinks([...selectedLinks, link]);
}
};
let shortendURL;
try {
if (link.url) {
shortendURL = new URL(link.url).host.toLowerCase();
}
} catch (error) {
console.log(error);
}
const [collection, setCollection] =
useState<CollectionIncludingMembersAndLinkCount>(
collections.find(
(e) => e.id === link.collection.id
) as CollectionIncludingMembersAndLinkCount
);
useEffect(() => {
setCollection(
collections.find(
(e) => e.id === link.collection.id
) as CollectionIncludingMembersAndLinkCount
);
}, [collections, links]);
const ref = useRef<HTMLDivElement>(null);
const isVisible = useOnScreen(ref);
const permissions = usePermissions(collection?.id as number);
const router = useRouter();
const isPublicRoute = router.pathname.startsWith("/public") ? true : false;
useEffect(() => {
let interval: NodeJS.Timeout | null = null;
if (
isVisible &&
!link.preview?.startsWith("archives") &&
link.preview !== "unavailable"
) {
interval = setInterval(async () => {
getLink.mutateAsync({
id: link.id as number,
isPublicRoute: isPublicRoute,
});
}, 5000);
}
return () => {
if (interval) {
clearInterval(interval);
}
};
}, [isVisible, link.preview]);
const selectedStyle = selectedLinks.some(
(selectedLink) => selectedLink.id === link.id
)
? "border-primary bg-base-300"
: "border-neutral-content";
const selectable =
editMode &&
(permissions === true || permissions?.canCreate || permissions?.canDelete);
return (
<div
ref={ref}
className={`${selectedStyle} border border-solid border-neutral-content bg-base-200 shadow-md hover:shadow-none duration-100 rounded-2xl relative group`}
onClick={() =>
selectable
? handleCheckboxClick(link)
: editMode
? toast.error(t("link_selection_error"))
: undefined
}
>
<div
className="rounded-2xl cursor-pointer h-full flex flex-col justify-between"
onClick={() =>
!editMode && window.open(generateLinkHref(link, user), "_blank")
}
>
{show.image && (
<div>
<div
className={`relative rounded-t-2xl ${imageHeightClass} overflow-hidden`}
>
{previewAvailable(link) ? (
<Image
src={`/api/v1/archives/${link.id}?format=${ArchivedFormat.jpeg}&preview=true&updatedAt=${link.updatedAt}`}
width={1280}
height={720}
alt=""
className={`rounded-t-2xl select-none object-cover z-10 ${imageHeightClass} w-full shadow opacity-80 scale-105`}
style={show.icon ? { filter: "blur(1px)" } : undefined}
draggable="false"
onError={(e) => {
const target = e.target as HTMLElement;
target.style.display = "none";
}}
/>
) : link.preview === "unavailable" ? (
<div
className={`bg-gray-50 ${imageHeightClass} bg-opacity-80`}
></div>
) : (
<div
className={`${imageHeightClass} bg-opacity-80 skeleton rounded-none`}
></div>
)}
{show.icon && (
<div className="absolute top-0 left-0 right-0 bottom-0 rounded-t-2xl flex items-center justify-center rounded-md">
<LinkIcon link={link} />
</div>
)}
</div>
<hr className="divider my-0 border-t border-neutral-content h-[1px]" />
</div>
)}
<div className="flex flex-col justify-between h-full min-h-24">
<div className="p-3 flex flex-col gap-2">
{show.name && (
<p className="truncate w-full text-primary text-sm">
{unescapeString(link.name)}
</p>
)}
{show.link && <LinkTypeBadge link={link} />}
</div>
{(show.collection || show.date) && (
<div>
<hr className="divider mt-2 mb-1 last:hidden border-t border-neutral-content h-[1px]" />
<div className="flex justify-between items-center text-xs text-neutral px-3 pb-1 gap-2">
{show.collection && !isPublicRoute && (
<div className="cursor-pointer truncate">
<LinkCollection link={link} collection={collection} />
</div>
)}
{show.date && <LinkDate link={link} />}
</div>
</div>
)}
</div>
</div>
{/* Overlay on hover */}
<div className="absolute pointer-events-none top-0 left-0 right-0 bottom-0 bg-base-100 bg-opacity-0 group-hover:bg-opacity-20 group-focus-within:opacity-20 rounded-2xl duration-100"></div>
<LinkActions link={link} collection={collection} />
{!isPublicRoute && <LinkPin link={link} />}
</div>
);
}
@@ -1,7 +1,9 @@
import Icon from "@/components/Icon";
import { import {
CollectionIncludingMembersAndLinkCount, CollectionIncludingMembersAndLinkCount,
LinkIncludingShortenedCollectionAndTags, LinkIncludingShortenedCollectionAndTags,
} from "@/types/global"; } from "@/types/global";
import { IconWeight } from "@phosphor-icons/react";
import Link from "next/link"; import Link from "next/link";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import React from "react"; import React from "react";
@@ -15,20 +17,33 @@ export default function LinkCollection({
}) { }) {
const router = useRouter(); const router = useRouter();
return ( const isPublicRoute = router.pathname.startsWith("/public") ? true : false;
<Link
href={`/collections/${link.collection.id}`} return !isPublicRoute && collection?.name ? (
onClick={(e) => { <>
e.stopPropagation(); <Link
}} href={`/collections/${link.collection.id}`}
className="flex items-center gap-1 max-w-full w-fit hover:opacity-70 duration-100 select-none" onClick={(e) => {
title={collection?.name} e.stopPropagation();
> }}
<i className="flex items-center gap-1 max-w-full w-fit hover:opacity-70 duration-100 select-none"
className="bi-folder-fill text-lg drop-shadow" title={collection?.name}
style={{ color: collection?.color }} >
></i> {link.collection.icon ? (
<p className="truncate capitalize">{collection?.name}</p> <Icon
</Link> icon={link.collection.icon}
); size={20}
weight={(link.collection.iconWeight || "regular") as IconWeight}
color={link.collection.color}
/>
) : (
<i
className="bi-folder-fill text-lg"
style={{ color: link.collection.color }}
></i>
)}
<p className="truncate capitalize">{collection?.name}</p>
</Link>
</>
) : null;
} }
@@ -1,73 +1,75 @@
import { LinkIncludingShortenedCollectionAndTags } from "@/types/global"; import { LinkIncludingShortenedCollectionAndTags } from "@/types/global";
import Image from "next/image"; import Image from "next/image";
import isValidUrl from "@/lib/shared/isValidUrl"; import isValidUrl from "@/lib/shared/isValidUrl";
import React from "react"; import React, { useState } from "react";
import Icon from "@/components/Icon";
import { IconWeight } from "@phosphor-icons/react";
import clsx from "clsx";
export default function LinkIcon({ export default function LinkIcon({
link, link,
className, className,
size, hideBackground,
onClick,
}: { }: {
link: LinkIncludingShortenedCollectionAndTags; link: LinkIncludingShortenedCollectionAndTags;
className?: string; className?: string;
size?: "small" | "medium"; hideBackground?: boolean;
onClick?: Function;
}) { }) {
let iconClasses: string = let iconClasses: string = clsx(
"bg-white shadow rounded-md border-[2px] flex item-center justify-center border-white select-none z-10 " + "rounded flex item-center justify-center shadow select-none z-10 w-12 h-12",
(className || ""); !hideBackground && "rounded-md bg-white backdrop-blur-lg bg-opacity-50 p-1",
className
let dimension; );
switch (size) {
case "small":
dimension = " w-8 h-8";
break;
case "medium":
dimension = " w-12 h-12";
break;
default:
size = "medium";
dimension = " w-12 h-12";
break;
}
const url = const url =
isValidUrl(link.url || "") && link.url ? new URL(link.url) : undefined; isValidUrl(link.url || "") && link.url ? new URL(link.url) : undefined;
const [showFavicon, setShowFavicon] = React.useState<boolean>(true); const [faviconLoaded, setFaviconLoaded] = useState(false);
return ( return (
<> <div onClick={() => onClick && onClick()}>
{link.type === "url" && url ? ( {link.icon ? (
showFavicon ? ( <div className={iconClasses}>
<Icon
icon={link.icon}
size={30}
weight={(link.iconWeight || "regular") as IconWeight}
color={link.color || "#006796"}
className="m-auto"
/>
</div>
) : link.type === "url" && url ? (
<>
<Image <Image
src={`https://t2.gstatic.com/faviconV2?client=SOCIAL&type=FAVICON&fallback_opts=TYPE,SIZE,URL&url=${link.url}&size=32`} src={`https://t2.gstatic.com/faviconV2?client=SOCIAL&type=FAVICON&fallback_opts=TYPE,SIZE,URL&url=${link.url}&size=32`}
width={64} width={64}
height={64} height={64}
alt="" alt=""
className={iconClasses + dimension} className={clsx(
iconClasses,
faviconLoaded ? "" : "absolute opacity-0"
)}
draggable="false" draggable="false"
onError={() => { onLoadingComplete={() => setFaviconLoaded(true)}
setShowFavicon(false); onError={() => setFaviconLoaded(false)}
}}
/> />
) : ( {!faviconLoaded && (
<LinkPlaceholderIcon <LinkPlaceholderIcon
iconClasses={iconClasses + dimension} iconClasses={iconClasses}
size={size} icon="bi-link-45deg"
icon="bi-link-45deg" />
/> )}
) </>
) : link.type === "pdf" ? ( ) : link.type === "pdf" ? (
<LinkPlaceholderIcon <LinkPlaceholderIcon
iconClasses={iconClasses + dimension} iconClasses={iconClasses}
size={size}
icon="bi-file-earmark-pdf" icon="bi-file-earmark-pdf"
/> />
) : link.type === "image" ? ( ) : link.type === "image" ? (
<LinkPlaceholderIcon <LinkPlaceholderIcon
iconClasses={iconClasses + dimension} iconClasses={iconClasses}
size={size}
icon="bi-file-earmark-image" icon="bi-file-earmark-image"
/> />
) : // : link.type === "monolith" ? ( ) : // : link.type === "monolith" ? (
@@ -78,25 +80,19 @@ export default function LinkIcon({
// /> // />
// ) // )
undefined} undefined}
</> </div>
); );
} }
const LinkPlaceholderIcon = ({ const LinkPlaceholderIcon = ({
iconClasses, iconClasses,
size,
icon, icon,
}: { }: {
iconClasses: string; iconClasses: string;
size?: "small" | "medium";
icon: string; icon: string;
}) => { }) => {
return ( return (
<div <div className={clsx(iconClasses, "aspect-square text-4xl text-[#006796]")}>
className={`${
size === "small" ? "text-2xl" : "text-4xl"
} text-black aspect-square ${iconClasses}`}
>
<i className={`${icon} m-auto`}></i> <i className={`${icon} m-auto`}></i>
</div> </div>
); );
@@ -4,7 +4,6 @@ import {
} from "@/types/global"; } from "@/types/global";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import useLinkStore from "@/store/links"; import useLinkStore from "@/store/links";
import useCollectionStore from "@/store/collections";
import unescapeString from "@/lib/client/unescapeString"; import unescapeString from "@/lib/client/unescapeString";
import LinkActions from "@/components/LinkViews/LinkComponents/LinkActions"; import LinkActions from "@/components/LinkViews/LinkComponents/LinkActions";
import LinkDate from "@/components/LinkViews/LinkComponents/LinkDate"; import LinkDate from "@/components/LinkViews/LinkComponents/LinkDate";
@@ -12,30 +11,37 @@ import LinkCollection from "@/components/LinkViews/LinkComponents/LinkCollection
import LinkIcon from "@/components/LinkViews/LinkComponents/LinkIcon"; import LinkIcon from "@/components/LinkViews/LinkComponents/LinkIcon";
import { isPWA } from "@/lib/client/utils"; import { isPWA } from "@/lib/client/utils";
import { generateLinkHref } from "@/lib/client/generateLinkHref"; import { generateLinkHref } from "@/lib/client/generateLinkHref";
import useAccountStore from "@/store/account";
import usePermissions from "@/hooks/usePermissions"; import usePermissions from "@/hooks/usePermissions";
import toast from "react-hot-toast"; import toast from "react-hot-toast";
import LinkTypeBadge from "./LinkComponents/LinkTypeBadge"; import LinkTypeBadge from "./LinkTypeBadge";
import { useTranslation } from "next-i18next"; import { useTranslation } from "next-i18next";
import { useCollections } from "@/hooks/store/collections";
import { useUser } from "@/hooks/store/user";
import { useLinks } from "@/hooks/store/links";
import useLocalSettingsStore from "@/store/localSettings";
import LinkPin from "./LinkPin";
import { useRouter } from "next/router";
type Props = { type Props = {
link: LinkIncludingShortenedCollectionAndTags; link: LinkIncludingShortenedCollectionAndTags;
count: number; count: number;
className?: string; className?: string;
flipDropdown?: boolean;
editMode?: boolean; editMode?: boolean;
}; };
export default function LinkCardCompact({ export default function LinkCardCompact({ link, editMode }: Props) {
link,
flipDropdown,
editMode,
}: Props) {
const { t } = useTranslation(); const { t } = useTranslation();
const { collections } = useCollectionStore(); const { data: collections = [] } = useCollections();
const { account } = useAccountStore();
const { links, setSelectedLinks, selectedLinks } = useLinkStore(); const { data: user = {} } = useUser();
const { setSelectedLinks, selectedLinks } = useLinkStore();
const {
settings: { show },
} = useLocalSettingsStore();
const { links } = useLinks();
useEffect(() => { useEffect(() => {
if (!editMode) { if (!editMode) {
@@ -76,8 +82,6 @@ export default function LinkCardCompact({
const permissions = usePermissions(collection?.id as number); const permissions = usePermissions(collection?.id as number);
const [showInfo, setShowInfo] = useState(false);
const selectedStyle = selectedLinks.some( const selectedStyle = selectedLinks.some(
(selectedLink) => selectedLink.id === link.id (selectedLink) => selectedLink.id === link.id
) )
@@ -88,12 +92,15 @@ export default function LinkCardCompact({
editMode && editMode &&
(permissions === true || permissions?.canCreate || permissions?.canDelete); (permissions === true || permissions?.canCreate || permissions?.canDelete);
const router = useRouter();
let isPublic = router.pathname.startsWith("/public") ? true : undefined;
return ( return (
<> <>
<div <div
className={`${selectedStyle} border relative items-center flex ${ className={`${selectedStyle} rounded-md border relative group items-center flex ${
!showInfo && !isPWA() ? "hover:bg-base-300 p-3" : "py-3" !isPWA() ? "hover:bg-base-300 px-2 py-1" : "py-1"
} duration-200 rounded-lg w-full`} } duration-200 w-full`}
onClick={() => onClick={() =>
selectable selectable
? handleCheckboxClick(link) ? handleCheckboxClick(link)
@@ -102,67 +109,40 @@ export default function LinkCardCompact({
: undefined : undefined
} }
> >
{/* {showCheckbox &&
editMode &&
(permissions === true ||
permissions?.canCreate ||
permissions?.canDelete) && (
<input
type="checkbox"
className="checkbox checkbox-primary my-auto mr-2"
checked={selectedLinks.some(
(selectedLink) => selectedLink.id === link.id
)}
onChange={() => handleCheckboxClick(link)}
/>
)} */}
<div <div
className="flex items-center cursor-pointer w-full" className="flex items-center cursor-pointer w-full min-h-12"
onClick={() => onClick={() =>
!editMode && window.open(generateLinkHref(link, account), "_blank") !editMode && window.open(generateLinkHref(link, user), "_blank")
} }
> >
<div className="shrink-0"> {show.icon && (
<LinkIcon link={link} className="w-12 h-12 text-4xl" /> <div className="shrink-0">
</div> <LinkIcon link={link} hideBackground />
</div>
)}
<div className="w-[calc(100%-56px)] ml-2"> <div className="w-[calc(100%-56px)] ml-2">
<p className="line-clamp-1 mr-8 text-primary select-none"> {show.name && (
{link.name ? ( <p className="line-clamp-1 mr-8 text-primary select-none">
unescapeString(link.name) {unescapeString(link.name)}
) : ( </p>
<div className="mt-2"> )}
<LinkTypeBadge link={link} />
</div>
)}
</p>
<div className="mt-1 flex flex-col sm:flex-row sm:items-center gap-2 text-xs text-neutral"> <div className="mt-1 flex flex-col sm:flex-row sm:items-center gap-2 text-xs text-neutral">
<div className="flex items-center gap-x-3 text-neutral flex-wrap"> <div className="flex items-center gap-x-3 text-neutral flex-wrap">
{collection ? ( {show.link && <LinkTypeBadge link={link} />}
{show.collection && (
<LinkCollection link={link} collection={collection} /> <LinkCollection link={link} collection={collection} />
) : undefined} )}
{link.name && <LinkTypeBadge link={link} />} {show.date && <LinkDate link={link} />}
<LinkDate link={link} />
</div> </div>
</div> </div>
</div> </div>
</div> </div>
<LinkActions {!isPublic && <LinkPin link={link} btnStyle="btn-ghost" />}
link={link} <LinkActions link={link} collection={collection} btnStyle="btn-ghost" />
collection={collection}
position="top-3 right-3"
flipDropdown={flipDropdown}
// toggleShowInfo={() => setShowInfo(!showInfo)}
// linkInfo={showInfo}
/>
</div> </div>
<div <div className="last:hidden rounded-none my-0 mx-1 border-t border-base-300 h-[1px]"></div>
className="last:hidden rounded-none"
style={{
borderTop: "1px solid var(--fallback-bc,oklch(var(--bc)/0.1))",
}}
></div>
</> </>
); );
} }
@@ -0,0 +1,252 @@
import {
ArchivedFormat,
CollectionIncludingMembersAndLinkCount,
LinkIncludingShortenedCollectionAndTags,
} from "@/types/global";
import { useEffect, useMemo, useRef, useState } from "react";
import useLinkStore from "@/store/links";
import unescapeString from "@/lib/client/unescapeString";
import LinkActions from "@/components/LinkViews/LinkComponents/LinkActions";
import LinkDate from "@/components/LinkViews/LinkComponents/LinkDate";
import LinkCollection from "@/components/LinkViews/LinkComponents/LinkCollection";
import Image from "next/image";
import { previewAvailable } from "@/lib/shared/getArchiveValidity";
import Link from "next/link";
import LinkIcon from "./LinkIcon";
import useOnScreen from "@/hooks/useOnScreen";
import { generateLinkHref } from "@/lib/client/generateLinkHref";
import usePermissions from "@/hooks/usePermissions";
import toast from "react-hot-toast";
import LinkTypeBadge from "./LinkTypeBadge";
import { useTranslation } from "next-i18next";
import { useCollections } from "@/hooks/store/collections";
import { useUser } from "@/hooks/store/user";
import { useGetLink, useLinks } from "@/hooks/store/links";
import useLocalSettingsStore from "@/store/localSettings";
import clsx from "clsx";
import LinkPin from "./LinkPin";
import { useRouter } from "next/router";
type Props = {
link: LinkIncludingShortenedCollectionAndTags;
columns: number;
editMode?: boolean;
};
export default function LinkMasonry({ link, editMode, columns }: Props) {
const { t } = useTranslation();
const heightMap = {
1: "h-44",
2: "h-40",
3: "h-36",
4: "h-32",
5: "h-28",
6: "h-24",
7: "h-20",
8: "h-20",
};
const imageHeightClass = useMemo(
() => (columns ? heightMap[columns as keyof typeof heightMap] : "h-40"),
[columns]
);
const { data: collections = [] } = useCollections();
const { data: user = {} } = useUser();
const { setSelectedLinks, selectedLinks } = useLinkStore();
const {
settings: { show },
} = useLocalSettingsStore();
const { links } = useLinks();
const getLink = useGetLink();
useEffect(() => {
if (!editMode) {
setSelectedLinks([]);
}
}, [editMode]);
const handleCheckboxClick = (
link: LinkIncludingShortenedCollectionAndTags
) => {
if (selectedLinks.includes(link)) {
setSelectedLinks(selectedLinks.filter((e) => e !== link));
} else {
setSelectedLinks([...selectedLinks, link]);
}
};
let shortendURL;
try {
if (link.url) {
shortendURL = new URL(link.url).host.toLowerCase();
}
} catch (error) {
console.log(error);
}
const [collection, setCollection] =
useState<CollectionIncludingMembersAndLinkCount>(
collections.find(
(e) => e.id === link.collection.id
) as CollectionIncludingMembersAndLinkCount
);
useEffect(() => {
setCollection(
collections.find(
(e) => e.id === link.collection.id
) as CollectionIncludingMembersAndLinkCount
);
}, [collections, links]);
const ref = useRef<HTMLDivElement>(null);
const isVisible = useOnScreen(ref);
const permissions = usePermissions(collection?.id as number);
const router = useRouter();
let isPublic = router.pathname.startsWith("/public") ? true : undefined;
useEffect(() => {
let interval: NodeJS.Timeout | null = null;
if (
isVisible &&
!link.preview?.startsWith("archives") &&
link.preview !== "unavailable"
) {
interval = setInterval(async () => {
getLink.mutateAsync({ id: link.id as number });
}, 5000);
}
return () => {
if (interval) {
clearInterval(interval);
}
};
}, [isVisible, link.preview]);
const selectedStyle = selectedLinks.some(
(selectedLink) => selectedLink.id === link.id
)
? "border-primary bg-base-300"
: "border-neutral-content";
const selectable =
editMode &&
(permissions === true || permissions?.canCreate || permissions?.canDelete);
return (
<div
ref={ref}
className={`${selectedStyle} border border-solid border-neutral-content bg-base-200 shadow-md hover:shadow-none duration-100 rounded-2xl relative group`}
onClick={() =>
selectable
? handleCheckboxClick(link)
: editMode
? toast.error(t("link_selection_error"))
: undefined
}
>
<div
className="rounded-2xl cursor-pointer"
onClick={() =>
!editMode && window.open(generateLinkHref(link, user), "_blank")
}
>
{show.image && previewAvailable(link) && (
<div>
<div className="relative rounded-t-2xl overflow-hidden">
{previewAvailable(link) ? (
<Image
src={`/api/v1/archives/${link.id}?format=${ArchivedFormat.jpeg}&preview=true&updatedAt=${link.updatedAt}`}
width={1280}
height={720}
alt=""
className={`rounded-t-2xl select-none object-cover z-10 ${imageHeightClass} w-full shadow opacity-80 scale-105`}
style={show.icon ? { filter: "blur(1px)" } : undefined}
draggable="false"
onError={(e) => {
const target = e.target as HTMLElement;
target.style.display = "none";
}}
/>
) : link.preview === "unavailable" ? null : (
<div
className={`duration-100 ${imageHeightClass} bg-opacity-80 skeleton rounded-none`}
></div>
)}
{show.icon && (
<div className="absolute top-0 left-0 right-0 bottom-0 rounded-t-2xl flex items-center justify-center rounded-md">
<LinkIcon link={link} />
</div>
)}
</div>
<hr className="divider my-0 border-t border-neutral-content h-[1px]" />
</div>
)}
<div className="p-3 flex flex-col gap-2 h-full min-h-14">
{show.name && (
<p className="hyphens-auto w-full text-primary text-sm">
{unescapeString(link.name)}
</p>
)}
{show.link && <LinkTypeBadge link={link} />}
{show.description && link.description && (
<p className={clsx("hyphens-auto text-sm w-full")}>
{unescapeString(link.description)}
</p>
)}
{show.tags && link.tags && link.tags[0] && (
<div className="flex gap-1 items-center flex-wrap">
{link.tags.map((e, i) => (
<Link
href={"/tags/" + e.id}
key={i}
onClick={(e) => {
e.stopPropagation();
}}
className="btn btn-xs btn-ghost truncate max-w-[19rem]"
>
#{e.name}
</Link>
))}
</div>
)}
</div>
{(show.collection || show.date) && (
<div>
<hr className="divider mt-2 mb-1 last:hidden border-t border-neutral-content h-[1px]" />
<div className="flex flex-wrap justify-between items-center text-xs text-neutral px-3 pb-1 w-full gap-x-2">
{!isPublic && show.collection && (
<div className="cursor-pointer truncate">
<LinkCollection link={link} collection={collection} />
</div>
)}
{show.date && <LinkDate link={link} />}
</div>
</div>
)}
</div>
{/* Overlay on hover */}
<div className="absolute pointer-events-none top-0 left-0 right-0 bottom-0 bg-base-100 bg-opacity-0 group-hover:bg-opacity-20 group-focus-within:opacity-20 rounded-2xl duration-100"></div>
<LinkActions link={link} collection={collection} />
{!isPublic && <LinkPin link={link} />}
</div>
);
}
@@ -0,0 +1,34 @@
import { LinkIncludingShortenedCollectionAndTags } from "@/types/global";
import { useRouter } from "next/router";
import clsx from "clsx";
import usePinLink from "@/lib/client/pinLink";
type Props = {
link: LinkIncludingShortenedCollectionAndTags;
btnStyle?: string;
};
export default function LinkPin({ link, btnStyle }: Props) {
const pinLink = usePinLink();
const router = useRouter();
const isPublicRoute = router.pathname.startsWith("/public") ? true : false;
const isAlreadyPinned = link?.pinnedBy && link.pinnedBy[0] ? true : false;
return (
<div
className="absolute top-3 right-[3.25rem] group-hover:opacity-100 group-focus-within:opacity-100 opacity-0 duration-100"
onClick={() => pinLink(link)}
>
<div className={clsx("btn btn-sm btn-square text-neutral", btnStyle)}>
<i
title="Pin"
className={clsx(
"text-xl",
isAlreadyPinned ? "bi-pin-fill" : "bi-pin"
)}
/>
</div>
</div>
);
}
-271
View File
@@ -1,271 +0,0 @@
import {
ArchivedFormat,
CollectionIncludingMembersAndLinkCount,
LinkIncludingShortenedCollectionAndTags,
} from "@/types/global";
import { useEffect, useRef, useState } from "react";
import useLinkStore from "@/store/links";
import useCollectionStore from "@/store/collections";
import unescapeString from "@/lib/client/unescapeString";
import LinkActions from "@/components/LinkViews/LinkComponents/LinkActions";
import LinkDate from "@/components/LinkViews/LinkComponents/LinkDate";
import LinkCollection from "@/components/LinkViews/LinkComponents/LinkCollection";
import Image from "next/image";
import { previewAvailable } from "@/lib/shared/getArchiveValidity";
import Link from "next/link";
import LinkIcon from "./LinkComponents/LinkIcon";
import useOnScreen from "@/hooks/useOnScreen";
import { generateLinkHref } from "@/lib/client/generateLinkHref";
import useAccountStore from "@/store/account";
import usePermissions from "@/hooks/usePermissions";
import toast from "react-hot-toast";
import LinkTypeBadge from "./LinkComponents/LinkTypeBadge";
import { useTranslation } from "next-i18next";
type Props = {
link: LinkIncludingShortenedCollectionAndTags;
count: number;
className?: string;
flipDropdown?: boolean;
editMode?: boolean;
};
export default function LinkMasonry({ link, flipDropdown, editMode }: Props) {
const { t } = useTranslation();
const { collections } = useCollectionStore();
const { account } = useAccountStore();
const { links, getLink, setSelectedLinks, selectedLinks } = useLinkStore();
useEffect(() => {
if (!editMode) {
setSelectedLinks([]);
}
}, [editMode]);
const handleCheckboxClick = (
link: LinkIncludingShortenedCollectionAndTags
) => {
if (selectedLinks.includes(link)) {
setSelectedLinks(selectedLinks.filter((e) => e !== link));
} else {
setSelectedLinks([...selectedLinks, link]);
}
};
let shortendURL;
try {
if (link.url) {
shortendURL = new URL(link.url).host.toLowerCase();
}
} catch (error) {
console.log(error);
}
const [collection, setCollection] =
useState<CollectionIncludingMembersAndLinkCount>(
collections.find(
(e) => e.id === link.collection.id
) as CollectionIncludingMembersAndLinkCount
);
useEffect(() => {
setCollection(
collections.find(
(e) => e.id === link.collection.id
) as CollectionIncludingMembersAndLinkCount
);
}, [collections, links]);
const ref = useRef<HTMLDivElement>(null);
const isVisible = useOnScreen(ref);
const permissions = usePermissions(collection?.id as number);
useEffect(() => {
let interval: any;
if (
isVisible &&
!link.preview?.startsWith("archives") &&
link.preview !== "unavailable"
) {
interval = setInterval(async () => {
getLink(link.id as number);
}, 5000);
}
return () => {
if (interval) {
clearInterval(interval);
}
};
}, [isVisible, link.preview]);
const [showInfo, setShowInfo] = useState(false);
const selectedStyle = selectedLinks.some(
(selectedLink) => selectedLink.id === link.id
)
? "border-primary bg-base-300"
: "border-neutral-content";
const selectable =
editMode &&
(permissions === true || permissions?.canCreate || permissions?.canDelete);
return (
<div
ref={ref}
className={`${selectedStyle} border border-solid border-neutral-content bg-base-200 shadow-md hover:shadow-none duration-100 rounded-2xl relative`}
onClick={() =>
selectable
? handleCheckboxClick(link)
: editMode
? toast.error(t("link_selection_error"))
: undefined
}
>
<div
className="rounded-2xl cursor-pointer"
onClick={() =>
!editMode && window.open(generateLinkHref(link, account), "_blank")
}
>
<div className="relative rounded-t-2xl overflow-hidden">
{previewAvailable(link) ? (
<Image
src={`/api/v1/archives/${link.id}?format=${ArchivedFormat.jpeg}&preview=true`}
width={1280}
height={720}
alt=""
className="rounded-t-2xl select-none object-cover z-10 h-40 w-full shadow opacity-80 scale-105"
style={
link.type !== "image" ? { filter: "blur(1px)" } : undefined
}
draggable="false"
onError={(e) => {
const target = e.target as HTMLElement;
target.style.display = "none";
}}
/>
) : link.preview === "unavailable" ? null : (
<div className="duration-100 h-40 bg-opacity-80 skeleton rounded-none"></div>
)}
{link.type !== "image" && (
<div className="absolute top-0 left-0 right-0 bottom-0 rounded-t-2xl flex items-center justify-center shadow rounded-md">
<LinkIcon link={link} />
</div>
)}
</div>
{link.preview !== "unavailable" && (
<hr className="divider my-0 last:hidden border-t border-neutral-content h-[1px]" />
)}
<div className="p-3 flex flex-col gap-2">
<p className="hyphens-auto w-full pr-9 text-primary text-sm">
{unescapeString(link.name)}
</p>
<LinkTypeBadge link={link} />
{link.description && (
<p className="hyphens-auto text-sm">
{unescapeString(link.description)}
</p>
)}
{link.tags && link.tags[0] && (
<div className="flex gap-1 items-center flex-wrap">
{link.tags.map((e, i) => (
<Link
href={"/tags/" + e.id}
key={i}
onClick={(e) => {
e.stopPropagation();
}}
className="btn btn-xs btn-ghost truncate max-w-[19rem]"
>
#{e.name}
</Link>
))}
</div>
)}
</div>
<hr className="divider mt-2 mb-1 last:hidden border-t border-neutral-content h-[1px]" />
<div className="flex flex-wrap justify-between text-xs text-neutral px-3 pb-1 w-full gap-x-2">
{collection && <LinkCollection link={link} collection={collection} />}
<LinkDate link={link} />
</div>
</div>
{showInfo && (
<div className="p-3 absolute z-30 top-0 left-0 right-0 bottom-0 bg-base-200 rounded-2xl fade-in overflow-y-auto">
<div
onClick={() => setShowInfo(!showInfo)}
className=" float-right btn btn-sm outline-none btn-circle btn-ghost z-10"
>
<i className="bi-x text-neutral text-2xl"></i>
</div>
<p className="text-neutral text-lg font-semibold">
{t("description")}
</p>
<hr className="divider my-2 last:hidden border-t border-neutral-content h-[1px]" />
<p>
{link.description ? (
unescapeString(link.description)
) : (
<span className="text-neutral text-sm">
{t("no_description")}
</span>
)}
</p>
{link.tags && link.tags[0] && (
<>
<p className="text-neutral text-lg mt-3 font-semibold">
{t("tags")}
</p>
<hr className="divider my-2 last:hidden border-t border-neutral-content h-[1px]" />
<div className="flex gap-3 items-center flex-wrap mt-2 truncate relative">
<div className="flex gap-1 items-center flex-wrap">
{link.tags.map((e, i) => (
<Link
href={"/tags/" + e.id}
key={i}
onClick={(e) => {
e.stopPropagation();
}}
className="btn btn-xs btn-ghost truncate max-w-[19rem]"
>
#{e.name}
</Link>
))}
</div>
</div>
</>
)}
</div>
)}
<LinkActions
link={link}
collection={collection}
position={
link.preview !== "unavailable"
? "top-[10.75rem] right-3"
: "top-[.75rem] right-3"
}
toggleShowInfo={() => setShowInfo(!showInfo)}
linkInfo={showInfo}
flipDropdown={flipDropdown}
/>
</div>
);
}
+336
View File
@@ -0,0 +1,336 @@
import LinkCard from "@/components/LinkViews/LinkComponents/LinkCard";
import {
LinkIncludingShortenedCollectionAndTags,
ViewMode,
} from "@/types/global";
import { useEffect, useState } from "react";
import { useInView } from "react-intersection-observer";
import LinkMasonry from "@/components/LinkViews/LinkComponents/LinkMasonry";
import Masonry from "react-masonry-css";
import resolveConfig from "tailwindcss/resolveConfig";
import tailwindConfig from "../../tailwind.config.js";
import { useMemo } from "react";
import LinkList from "@/components/LinkViews/LinkComponents/LinkList";
import useLocalSettingsStore from "@/store/localSettings";
export function CardView({
links,
editMode,
isLoading,
placeholders,
hasNextPage,
placeHolderRef,
}: {
links?: LinkIncludingShortenedCollectionAndTags[];
editMode?: boolean;
isLoading?: boolean;
placeholders?: number[];
hasNextPage?: boolean;
placeHolderRef?: any;
}) {
const settings = useLocalSettingsStore((state) => state.settings);
const gridMap = {
1: "grid-cols-1",
2: "grid-cols-2",
3: "grid-cols-3",
4: "grid-cols-4",
5: "grid-cols-5",
6: "grid-cols-6",
7: "grid-cols-7",
8: "grid-cols-8",
};
const getColumnCount = () => {
const width = window.innerWidth;
if (width >= 1901) return 5;
if (width >= 1501) return 4;
if (width >= 881) return 3;
if (width >= 551) return 2;
return 1;
};
const [columnCount, setColumnCount] = useState(
settings.columns || getColumnCount()
);
const gridColClass = useMemo(
() => gridMap[columnCount as keyof typeof gridMap],
[columnCount]
);
useEffect(() => {
const handleResize = () => {
if (settings.columns === 0) {
// Only recalculate if zustandColumns is zero
setColumnCount(getColumnCount());
}
};
if (settings.columns === 0) {
window.addEventListener("resize", handleResize);
}
setColumnCount(settings.columns || getColumnCount());
return () => {
if (settings.columns === 0) {
window.removeEventListener("resize", handleResize);
}
};
}, [settings.columns]);
return (
<div className={`${gridColClass} grid gap-5 pb-5`}>
{links?.map((e, i) => {
return (
<LinkCard
key={i}
link={e}
count={i}
editMode={editMode}
columns={columnCount}
/>
);
})}
{(hasNextPage || isLoading) &&
placeholders?.map((e, i) => {
return (
<div
className="flex flex-col gap-4"
ref={e === 1 ? placeHolderRef : undefined}
key={i}
>
<div className="skeleton h-40 w-full"></div>
<div className="skeleton h-3 w-2/3"></div>
<div className="skeleton h-3 w-full"></div>
<div className="skeleton h-3 w-full"></div>
<div className="skeleton h-3 w-1/3"></div>
</div>
);
})}
</div>
);
}
export function MasonryView({
links,
editMode,
isLoading,
placeholders,
hasNextPage,
placeHolderRef,
}: {
links?: LinkIncludingShortenedCollectionAndTags[];
editMode?: boolean;
isLoading?: boolean;
placeholders?: number[];
hasNextPage?: boolean;
placeHolderRef?: any;
}) {
const settings = useLocalSettingsStore((state) => state.settings);
const gridMap = {
1: "grid-cols-1",
2: "grid-cols-2",
3: "grid-cols-3",
4: "grid-cols-4",
5: "grid-cols-5",
6: "grid-cols-6",
7: "grid-cols-7",
8: "grid-cols-8",
};
const getColumnCount = () => {
const width = window.innerWidth;
if (width >= 1901) return 5;
if (width >= 1501) return 4;
if (width >= 881) return 3;
if (width >= 551) return 2;
return 1;
};
const [columnCount, setColumnCount] = useState(
settings.columns || getColumnCount()
);
const gridColClass = useMemo(
() => gridMap[columnCount as keyof typeof gridMap],
[columnCount]
);
useEffect(() => {
const handleResize = () => {
if (settings.columns === 0) {
// Only recalculate if zustandColumns is zero
setColumnCount(getColumnCount());
}
};
if (settings.columns === 0) {
window.addEventListener("resize", handleResize);
}
setColumnCount(settings.columns || getColumnCount());
return () => {
if (settings.columns === 0) {
window.removeEventListener("resize", handleResize);
}
};
}, [settings.columns]);
const fullConfig = resolveConfig(tailwindConfig as any);
const breakpointColumnsObj = useMemo(() => {
return {
default: 5,
1900: 4,
1500: 3,
880: 2,
550: 1,
};
}, []);
return (
<Masonry
breakpointCols={
settings.columns === 0 ? breakpointColumnsObj : columnCount
}
columnClassName="flex flex-col gap-5 !w-full"
className={`${gridColClass} grid gap-5 pb-5`}
>
{links?.map((e, i) => {
return (
<LinkMasonry
key={i}
link={e}
editMode={editMode}
columns={columnCount}
/>
);
})}
{(hasNextPage || isLoading) &&
placeholders?.map((e, i) => {
return (
<div
className="flex flex-col gap-4"
ref={e === 1 ? placeHolderRef : undefined}
key={i}
>
<div className="skeleton h-40 w-full"></div>
<div className="skeleton h-3 w-2/3"></div>
<div className="skeleton h-3 w-full"></div>
<div className="skeleton h-3 w-full"></div>
<div className="skeleton h-3 w-1/3"></div>
</div>
);
})}
</Masonry>
);
}
export function ListView({
links,
editMode,
isLoading,
placeholders,
hasNextPage,
placeHolderRef,
}: {
links?: LinkIncludingShortenedCollectionAndTags[];
editMode?: boolean;
isLoading?: boolean;
placeholders?: number[];
hasNextPage?: boolean;
placeHolderRef?: any;
}) {
return (
<div className="flex flex-col">
{links?.map((e, i) => {
return <LinkList key={i} link={e} count={i} editMode={editMode} />;
})}
{(hasNextPage || isLoading) &&
placeholders?.map((e, i) => {
return (
<div
ref={e === 1 ? placeHolderRef : undefined}
key={i}
className="flex gap-2 py-2 px-1"
>
<div className="skeleton h-12 w-12"></div>
<div className="flex flex-col gap-3 w-full">
<div className="skeleton h-2 w-2/3"></div>
<div className="skeleton h-2 w-full"></div>
<div className="skeleton h-2 w-1/3"></div>
</div>
</div>
);
})}
</div>
);
}
export default function Links({
layout,
links,
editMode,
placeholderCount,
useData,
}: {
layout: ViewMode;
links?: LinkIncludingShortenedCollectionAndTags[];
editMode?: boolean;
placeholderCount?: number;
useData?: any;
}) {
const { ref, inView } = useInView();
useEffect(() => {
if (inView && useData?.fetchNextPage && useData?.hasNextPage) {
useData.fetchNextPage();
}
}, [useData, inView]);
if (layout === ViewMode.List) {
return (
<ListView
links={links}
editMode={editMode}
isLoading={useData?.isLoading}
placeholders={placeholderCountToArray(placeholderCount)}
hasNextPage={useData?.hasNextPage}
placeHolderRef={ref}
/>
);
} else if (layout === ViewMode.Masonry) {
return (
<MasonryView
links={links}
editMode={editMode}
isLoading={useData?.isLoading}
placeholders={placeholderCountToArray(placeholderCount)}
hasNextPage={useData?.hasNextPage}
placeHolderRef={ref}
/>
);
} else {
// Default to card view
return (
<CardView
links={links}
editMode={editMode}
isLoading={useData?.isLoading}
placeholders={placeholderCountToArray(placeholderCount)}
hasNextPage={useData?.hasNextPage}
placeHolderRef={ref}
/>
);
}
}
const placeholderCountToArray = (num?: number) =>
num ? Array.from({ length: num }, (_, i) => i + 1) : [];
+9 -8
View File
@@ -41,7 +41,7 @@ export default function MobileNavigation({}: Props) {
<i className="bi-plus text-5xl pointer-events-none"></i> <i className="bi-plus text-5xl pointer-events-none"></i>
</span> </span>
</div> </div>
<ul className="dropdown-content z-[1] menu shadow bg-base-200 border border-neutral-content rounded-box w-40 mb-1 -ml-12"> <ul className="dropdown-content z-[1] menu shadow bg-base-200 border border-neutral-content rounded-box mb-1 -ml-12">
<li> <li>
<div <div
onClick={() => { onClick={() => {
@@ -50,6 +50,7 @@ export default function MobileNavigation({}: Props) {
}} }}
tabIndex={0} tabIndex={0}
role="button" role="button"
className="whitespace-nowrap"
> >
{t("new_link")} {t("new_link")}
</div> </div>
@@ -62,6 +63,7 @@ export default function MobileNavigation({}: Props) {
}} }}
tabIndex={0} tabIndex={0}
role="button" role="button"
className="whitespace-nowrap"
> >
{t("upload_file")} {t("upload_file")}
</div> </div>
@@ -74,6 +76,7 @@ export default function MobileNavigation({}: Props) {
}} }}
tabIndex={0} tabIndex={0}
role="button" role="button"
className="whitespace-nowrap"
> >
{t("new_collection")} {t("new_collection")}
</div> </div>
@@ -84,15 +87,13 @@ export default function MobileNavigation({}: Props) {
<MobileNavigationButton href={`/collections`} icon={"bi-folder"} /> <MobileNavigationButton href={`/collections`} icon={"bi-folder"} />
</div> </div>
</div> </div>
{newLinkModal ? ( {newLinkModal && <NewLinkModal onClose={() => setNewLinkModal(false)} />}
<NewLinkModal onClose={() => setNewLinkModal(false)} /> {newCollectionModal && (
) : undefined}
{newCollectionModal ? (
<NewCollectionModal onClose={() => setNewCollectionModal(false)} /> <NewCollectionModal onClose={() => setNewCollectionModal(false)} />
) : undefined} )}
{uploadFileModal ? ( {uploadFileModal && (
<UploadFileModal onClose={() => setUploadFileModal(false)} /> <UploadFileModal onClose={() => setUploadFileModal(false)} />
) : undefined} )}
</> </>
); );
} }
+13 -16
View File
@@ -32,28 +32,25 @@ export default function Modal({
return ( return (
<Drawer.Root <Drawer.Root
open={drawerIsOpen} open={drawerIsOpen}
onClose={() => dismissible && setTimeout(() => toggleModal(), 100)} onClose={() => dismissible && setDrawerIsOpen(false)}
onAnimationEnd={(isOpen) => !isOpen && toggleModal()}
dismissible={dismissible} dismissible={dismissible}
> >
<Drawer.Portal> <Drawer.Portal>
<Drawer.Overlay className="fixed inset-0 bg-black/40" /> <Drawer.Overlay className="fixed inset-0 bg-black/40" />
<ClickAwayHandler <Drawer.Content className="flex flex-col rounded-t-2xl h-[90%] mt-24 fixed bottom-0 left-0 right-0 z-30">
onClickOutside={() => dismissible && setDrawerIsOpen(false)} <div
> className="p-4 bg-base-100 rounded-t-2xl flex-1 border-neutral-content border-t overflow-y-auto"
<Drawer.Content className="flex flex-col rounded-t-2xl min-h-max mt-24 fixed bottom-0 left-0 right-0 z-30"> data-testid="mobile-modal-container"
>
<div <div
className="p-4 bg-base-100 rounded-t-2xl flex-1 border-neutral-content border-t overflow-y-auto" className="mx-auto w-12 h-1.5 flex-shrink-0 rounded-full bg-neutral mb-5"
data-testid="mobile-modal-container" data-testid="mobile-modal-slider"
> />
<div
className="mx-auto w-12 h-1.5 flex-shrink-0 rounded-full bg-neutral mb-5"
data-testid="mobile-modal-slider"
/>
{children} {children}
</div> </div>
</Drawer.Content> </Drawer.Content>
</ClickAwayHandler>
</Drawer.Portal> </Drawer.Portal>
</Drawer.Root> </Drawer.Root>
); );
@@ -1,9 +1,10 @@
import React from "react"; import React from "react";
import useLinkStore from "@/store/links"; import useLinkStore from "@/store/links";
import toast from "react-hot-toast";
import Modal from "../Modal"; import Modal from "../Modal";
import Button from "../ui/Button"; import Button from "../ui/Button";
import { useTranslation } from "next-i18next"; import { useTranslation } from "next-i18next";
import { useBulkDeleteLinks } from "@/hooks/store/links";
import toast from "react-hot-toast";
type Props = { type Props = {
onClose: Function; onClose: Function;
@@ -11,22 +12,29 @@ type Props = {
export default function BulkDeleteLinksModal({ onClose }: Props) { export default function BulkDeleteLinksModal({ onClose }: Props) {
const { t } = useTranslation(); const { t } = useTranslation();
const { selectedLinks, setSelectedLinks, deleteLinksById } = useLinkStore(); const { selectedLinks, setSelectedLinks } = useLinkStore();
const deleteLinksById = useBulkDeleteLinks();
const deleteLink = async () => { const deleteLink = async () => {
const load = toast.loading(t("deleting")); const load = toast.loading(t("deleting"));
const response = await deleteLinksById( await deleteLinksById.mutateAsync(
selectedLinks.map((link) => link.id as number) selectedLinks.map((link) => link.id as number),
{
onSettled: (data, error) => {
toast.dismiss(load);
if (error) {
toast.error(error.message);
} else {
setSelectedLinks([]);
onClose();
toast.success(t("deleted"));
}
},
}
); );
toast.dismiss(load);
if (response.ok) {
toast.success(t("deleted"));
setSelectedLinks([]);
onClose();
} else toast.error(response.data as string);
}; };
return ( return (
+23 -16
View File
@@ -6,6 +6,7 @@ import { LinkIncludingShortenedCollectionAndTags } from "@/types/global";
import toast from "react-hot-toast"; import toast from "react-hot-toast";
import Modal from "../Modal"; import Modal from "../Modal";
import { useTranslation } from "next-i18next"; import { useTranslation } from "next-i18next";
import { useBulkEditLinks } from "@/hooks/store/links";
type Props = { type Props = {
onClose: Function; onClose: Function;
@@ -13,13 +14,14 @@ type Props = {
export default function BulkEditLinksModal({ onClose }: Props) { export default function BulkEditLinksModal({ onClose }: Props) {
const { t } = useTranslation(); const { t } = useTranslation();
const { updateLinks, selectedLinks, setSelectedLinks } = useLinkStore(); const { selectedLinks, setSelectedLinks } = useLinkStore();
const [submitLoader, setSubmitLoader] = useState(false); const [submitLoader, setSubmitLoader] = useState(false);
const [removePreviousTags, setRemovePreviousTags] = useState(false); const [removePreviousTags, setRemovePreviousTags] = useState(false);
const [updatedValues, setUpdatedValues] = useState< const [updatedValues, setUpdatedValues] = useState<
Pick<LinkIncludingShortenedCollectionAndTags, "tags" | "collectionId"> Pick<LinkIncludingShortenedCollectionAndTags, "tags" | "collectionId">
>({ tags: [] }); >({ tags: [] });
const updateLinks = useBulkEditLinks();
const setCollection = (e: any) => { const setCollection = (e: any) => {
const collectionId = e?.value || null; const collectionId = e?.value || null;
setUpdatedValues((prevValues) => ({ ...prevValues, collectionId })); setUpdatedValues((prevValues) => ({ ...prevValues, collectionId }));
@@ -36,22 +38,27 @@ export default function BulkEditLinksModal({ onClose }: Props) {
const load = toast.loading(t("updating")); const load = toast.loading(t("updating"));
const response = await updateLinks( await updateLinks.mutateAsync(
selectedLinks, {
removePreviousTags, links: selectedLinks,
updatedValues newData: updatedValues,
removePreviousTags,
},
{
onSettled: (data, error) => {
setSubmitLoader(false);
toast.dismiss(load);
if (error) {
toast.error(error.message);
} else {
setSelectedLinks([]);
onClose();
toast.success(t("updated"));
}
},
}
); );
toast.dismiss(load);
if (response.ok) {
toast.success(t("updated"));
setSelectedLinks([]);
onClose();
} else toast.error(response.data as string);
setSubmitLoader(false);
return response;
} }
}; };
@@ -1,13 +1,13 @@
import React, { useEffect, useState } from "react"; import React, { useEffect, useState } from "react";
import TextInput from "@/components/TextInput"; import TextInput from "@/components/TextInput";
import useCollectionStore from "@/store/collections";
import toast from "react-hot-toast";
import { CollectionIncludingMembersAndLinkCount } from "@/types/global"; import { CollectionIncludingMembersAndLinkCount } from "@/types/global";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import usePermissions from "@/hooks/usePermissions"; import usePermissions from "@/hooks/usePermissions";
import Modal from "../Modal"; import Modal from "../Modal";
import Button from "../ui/Button"; import Button from "../ui/Button";
import { useTranslation } from "next-i18next"; import { useTranslation } from "next-i18next";
import { useDeleteCollection } from "@/hooks/store/collections";
import toast from "react-hot-toast";
type Props = { type Props = {
onClose: Function; onClose: Function;
@@ -22,7 +22,6 @@ export default function DeleteCollectionModal({
const [collection, setCollection] = const [collection, setCollection] =
useState<CollectionIncludingMembersAndLinkCount>(activeCollection); useState<CollectionIncludingMembersAndLinkCount>(activeCollection);
const [submitLoader, setSubmitLoader] = useState(false); const [submitLoader, setSubmitLoader] = useState(false);
const { removeCollection } = useCollectionStore();
const router = useRouter(); const router = useRouter();
const [inputField, setInputField] = useState(""); const [inputField, setInputField] = useState("");
const permissions = usePermissions(collection.id as number); const permissions = usePermissions(collection.id as number);
@@ -31,6 +30,8 @@ export default function DeleteCollectionModal({
setCollection(activeCollection); setCollection(activeCollection);
}, []); }, []);
const deleteCollection = useDeleteCollection();
const submit = async () => { const submit = async () => {
if (permissions === true && collection.name !== inputField) return; if (permissions === true && collection.name !== inputField) return;
if (!submitLoader) { if (!submitLoader) {
@@ -41,19 +42,20 @@ export default function DeleteCollectionModal({
const load = toast.loading(t("deleting_collection")); const load = toast.loading(t("deleting_collection"));
let response = await removeCollection(collection.id as number); deleteCollection.mutateAsync(collection.id as number, {
onSettled: (data, error) => {
setSubmitLoader(false);
toast.dismiss(load);
toast.dismiss(load); if (error) {
toast.error(error.message);
if (response.ok) { } else {
toast.success(t("deleted")); onClose();
onClose(); toast.success(t("deleted"));
router.push("/collections"); router.push("/collections");
} else { }
toast.error(response.data as string); },
} });
setSubmitLoader(false);
} }
}; };
+20 -19
View File
@@ -1,11 +1,11 @@
import React, { useEffect, useState } from "react"; import React, { useEffect, useState } from "react";
import useLinkStore from "@/store/links";
import { LinkIncludingShortenedCollectionAndTags } from "@/types/global"; import { LinkIncludingShortenedCollectionAndTags } from "@/types/global";
import toast from "react-hot-toast";
import Modal from "../Modal"; import Modal from "../Modal";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import Button from "../ui/Button"; import Button from "../ui/Button";
import { useTranslation } from "next-i18next"; import { useTranslation } from "next-i18next";
import { useDeleteLink } from "@/hooks/store/links";
import toast from "react-hot-toast";
type Props = { type Props = {
onClose: Function; onClose: Function;
@@ -16,31 +16,32 @@ export default function DeleteLinkModal({ onClose, activeLink }: Props) {
const { t } = useTranslation(); const { t } = useTranslation();
const [link, setLink] = const [link, setLink] =
useState<LinkIncludingShortenedCollectionAndTags>(activeLink); useState<LinkIncludingShortenedCollectionAndTags>(activeLink);
const { removeLink } = useLinkStore();
const deleteLink = useDeleteLink();
const router = useRouter(); const router = useRouter();
useEffect(() => { useEffect(() => {
setLink(activeLink); setLink(activeLink);
}, []); }, []);
const deleteLink = async () => { const submit = async () => {
const load = toast.loading(t("deleting")); const load = toast.loading(t("deleting"));
const response = await removeLink(link.id as number); await deleteLink.mutateAsync(link.id as number, {
onSettled: (data, error) => {
toast.dismiss(load);
toast.dismiss(load); if (error) {
toast.error(error.message);
if (response.ok) { } else {
toast.success(t("deleted")); if (router.pathname.startsWith("/links/[id]")) {
} else { router.push("/dashboard");
toast.error(response.data as string); }
} toast.success(t("deleted"));
onClose();
if (router.pathname.startsWith("/links/[id]")) { }
router.push("/dashboard"); },
} });
onClose();
}; };
return ( return (
@@ -61,7 +62,7 @@ export default function DeleteLinkModal({ onClose, activeLink }: Props) {
<p>{t("shift_key_tip")}</p> <p>{t("shift_key_tip")}</p>
<Button className="ml-auto" intent="destructive" onClick={deleteLink}> <Button className="ml-auto" intent="destructive" onClick={submit}>
<i className="bi-trash text-xl" /> <i className="bi-trash text-xl" />
{t("delete")} {t("delete")}
</Button> </Button>
+33 -23
View File
@@ -1,8 +1,9 @@
import toast from "react-hot-toast";
import Modal from "../Modal"; import Modal from "../Modal";
import useUserStore from "@/store/admin/users";
import Button from "../ui/Button"; import Button from "../ui/Button";
import { useTranslation } from "next-i18next"; import { useTranslation } from "next-i18next";
import { useDeleteUser } from "@/hooks/store/admin/users";
import { useState } from "react";
import { useSession } from "next-auth/react";
type Props = { type Props = {
onClose: Function; onClose: Function;
@@ -11,43 +12,52 @@ type Props = {
export default function DeleteUserModal({ onClose, userId }: Props) { export default function DeleteUserModal({ onClose, userId }: Props) {
const { t } = useTranslation(); const { t } = useTranslation();
const { removeUser } = useUserStore();
const deleteUser = async () => { const [submitLoader, setSubmitLoader] = useState(false);
const load = toast.loading(t("deleting_user")); const deleteUser = useDeleteUser();
const response = await removeUser(userId); const submit = async () => {
if (!submitLoader) {
setSubmitLoader(true);
toast.dismiss(load); await deleteUser.mutateAsync(userId, {
onSuccess: () => {
if (response.ok) { onClose();
toast.success(t("user_deleted")); },
} else { onSettled: (data, error) => {
toast.error(response.data as string); setSubmitLoader(false);
},
});
} }
onClose();
}; };
const { data } = useSession();
const isAdmin = data?.user?.id === Number(process.env.NEXT_PUBLIC_ADMIN);
return ( return (
<Modal toggleModal={onClose}> <Modal toggleModal={onClose}>
<p className="text-xl font-thin text-red-500">{t("delete_user")}</p> <p className="text-xl font-thin text-red-500">
{isAdmin ? t("delete_user") : t("remove_user")}
</p>
<div className="divider mb-3 mt-1"></div> <div className="divider mb-3 mt-1"></div>
<div className="flex flex-col gap-3"> <div className="flex flex-col gap-3">
<p>{t("confirm_user_deletion")}</p> <p>{t("confirm_user_deletion")}</p>
<p>{t("confirm_user_removal_desc")}</p>
<div role="alert" className="alert alert-warning"> {isAdmin && (
<i className="bi-exclamation-triangle text-xl" /> <div role="alert" className="alert alert-warning">
<span> <i className="bi-exclamation-triangle text-xl" />
<b>{t("warning")}:</b> {t("irreversible_action_warning")} <span>
</span> <b>{t("warning")}:</b> {t("irreversible_action_warning")}
</div> </span>
</div>
)}
<Button className="ml-auto" intent="destructive" onClick={deleteUser}> <Button className="ml-auto" intent="destructive" onClick={submit}>
<i className="bi-trash text-xl" /> <i className="bi-trash text-xl" />
{t("delete_confirmation")} {isAdmin ? t("delete_confirmation") : t("confirm")}
</Button> </Button>
</div> </div>
</Modal> </Modal>
+44 -43
View File
@@ -1,11 +1,12 @@
import React, { useState } from "react"; import React, { useState } from "react";
import TextInput from "@/components/TextInput"; import TextInput from "@/components/TextInput";
import useCollectionStore from "@/store/collections";
import toast from "react-hot-toast";
import { HexColorPicker } from "react-colorful";
import { CollectionIncludingMembersAndLinkCount } from "@/types/global"; import { CollectionIncludingMembersAndLinkCount } from "@/types/global";
import Modal from "../Modal"; import Modal from "../Modal";
import { useTranslation } from "next-i18next"; import { useTranslation } from "next-i18next";
import { useUpdateCollection } from "@/hooks/store/collections";
import toast from "react-hot-toast";
import IconPicker from "../IconPicker";
import { IconWeight } from "@phosphor-icons/react";
type Props = { type Props = {
onClose: Function; onClose: Function;
@@ -21,7 +22,7 @@ export default function EditCollectionModal({
useState<CollectionIncludingMembersAndLinkCount>(activeCollection); useState<CollectionIncludingMembersAndLinkCount>(activeCollection);
const [submitLoader, setSubmitLoader] = useState(false); const [submitLoader, setSubmitLoader] = useState(false);
const { updateCollection } = useCollectionStore(); const updateCollection = useUpdateCollection();
const submit = async () => { const submit = async () => {
if (!submitLoader) { if (!submitLoader) {
@@ -32,16 +33,19 @@ export default function EditCollectionModal({
const load = toast.loading(t("updating_collection")); const load = toast.loading(t("updating_collection"));
let response = await updateCollection(collection as any); await updateCollection.mutateAsync(collection, {
onSettled: (data, error) => {
setSubmitLoader(false);
toast.dismiss(load);
toast.dismiss(load); if (error) {
toast.error(error.message);
if (response.ok) { } else {
toast.success(t("updated")); onClose();
onClose(); toast.success(t("updated"));
} else toast.error(response.data as string); }
},
setSubmitLoader(false); });
} }
}; };
@@ -52,10 +56,32 @@ export default function EditCollectionModal({
<div className="divider mb-3 mt-1"></div> <div className="divider mb-3 mt-1"></div>
<div className="flex flex-col gap-3"> <div className="flex flex-col gap-3">
<div className="flex flex-col sm:flex-row gap-3"> <div className="flex flex-col gap-3">
<div className="w-full"> <div className="flex gap-3 items-end">
<p className="mb-2">{t("name")}</p> <IconPicker
<div className="flex flex-col gap-3"> color={collection.color}
setColor={(color: string) =>
setCollection({ ...collection, color })
}
weight={(collection.iconWeight || "regular") as IconWeight}
setWeight={(iconWeight: string) =>
setCollection({ ...collection, iconWeight })
}
iconName={collection.icon as string}
setIconName={(icon: string) =>
setCollection({ ...collection, icon })
}
reset={() =>
setCollection({
...collection,
color: "#0ea5e9",
icon: "",
iconWeight: "",
})
}
/>
<div className="w-full">
<p className="mb-2">{t("name")}</p>
<TextInput <TextInput
className="bg-base-200" className="bg-base-200"
value={collection.name} value={collection.name}
@@ -64,38 +90,13 @@ export default function EditCollectionModal({
setCollection({ ...collection, name: e.target.value }) setCollection({ ...collection, name: e.target.value })
} }
/> />
<div>
<p className="w-full mb-2">{t("color")}</p>
<div className="color-picker flex justify-between items-center">
<HexColorPicker
color={collection.color}
onChange={(color) =>
setCollection({ ...collection, color })
}
/>
<div className="flex flex-col gap-2 items-center w-32">
<i
className="bi-folder-fill text-5xl"
style={{ color: collection.color }}
></i>
<div
className="btn btn-ghost btn-xs"
onClick={() =>
setCollection({ ...collection, color: "#0ea5e9" })
}
>
{t("reset")}
</div>
</div>
</div>
</div>
</div> </div>
</div> </div>
<div className="w-full"> <div className="w-full">
<p className="mb-2">{t("description")}</p> <p className="mb-2">{t("description")}</p>
<textarea <textarea
className="w-full h-[13rem] resize-none border rounded-md duration-100 bg-base-200 p-2 outline-none border-neutral-content focus:border-primary" className="w-full h-32 resize-none border rounded-md duration-100 bg-base-200 p-2 outline-none border-neutral-content focus:border-primary"
placeholder={t("collection_description_placeholder")} placeholder={t("collection_description_placeholder")}
value={collection.description} value={collection.description}
onChange={(e) => onChange={(e) =>
@@ -1,16 +1,22 @@
import React, { useEffect, useState } from "react"; import React, { useEffect, useState } from "react";
import TextInput from "@/components/TextInput"; import TextInput from "@/components/TextInput";
import useCollectionStore from "@/store/collections";
import toast from "react-hot-toast"; import toast from "react-hot-toast";
import { CollectionIncludingMembersAndLinkCount, Member } from "@/types/global"; import {
AccountSettings,
CollectionIncludingMembersAndLinkCount,
Member,
} from "@/types/global";
import getPublicUserData from "@/lib/client/getPublicUserData"; import getPublicUserData from "@/lib/client/getPublicUserData";
import useAccountStore from "@/store/account";
import usePermissions from "@/hooks/usePermissions"; import usePermissions from "@/hooks/usePermissions";
import ProfilePhoto from "../ProfilePhoto"; import ProfilePhoto from "../ProfilePhoto";
import addMemberToCollection from "@/lib/client/addMemberToCollection"; import addMemberToCollection from "@/lib/client/addMemberToCollection";
import Modal from "../Modal"; import Modal from "../Modal";
import { dropdownTriggerer } from "@/lib/client/utils"; import { dropdownTriggerer } from "@/lib/client/utils";
import { useTranslation } from "next-i18next"; import { useTranslation } from "next-i18next";
import { useUpdateCollection } from "@/hooks/store/collections";
import { useUser } from "@/hooks/store/user";
import CopyButton from "../CopyButton";
import { useRouter } from "next/router";
type Props = { type Props = {
onClose: Function; onClose: Function;
@@ -27,7 +33,7 @@ export default function EditCollectionSharingModal({
useState<CollectionIncludingMembersAndLinkCount>(activeCollection); useState<CollectionIncludingMembersAndLinkCount>(activeCollection);
const [submitLoader, setSubmitLoader] = useState(false); const [submitLoader, setSubmitLoader] = useState(false);
const { updateCollection } = useCollectionStore(); const updateCollection = useUpdateCollection();
const submit = async () => { const submit = async () => {
if (!submitLoader) { if (!submitLoader) {
@@ -36,41 +42,36 @@ export default function EditCollectionSharingModal({
setSubmitLoader(true); setSubmitLoader(true);
const load = toast.loading(t("updating")); const load = toast.loading(t("updating_collection"));
let response; await updateCollection.mutateAsync(collection, {
onSettled: (data, error) => {
setSubmitLoader(false);
toast.dismiss(load);
response = await updateCollection(collection as any); if (error) {
toast.error(error.message);
toast.dismiss(load); } else {
onClose();
if (response.ok) { toast.success(t("updated"));
toast.success(t("updated")); }
onClose(); },
} else toast.error(response.data as string); });
setSubmitLoader(false);
} }
}; };
const { account } = useAccountStore(); const { data: user = {} } = useUser();
const permissions = usePermissions(collection.id as number); const permissions = usePermissions(collection.id as number);
const currentURL = new URL(document.URL); const currentURL = new URL(document.URL);
const publicCollectionURL = `${currentURL.origin}/public/collections/${collection.id}`; const publicCollectionURL = `${currentURL.origin}/public/collections/${collection.id}`;
const [memberUsername, setMemberUsername] = useState(""); const [memberIdentifier, setMemberIdentifier] = useState("");
const [collectionOwner, setCollectionOwner] = useState({ const [collectionOwner, setCollectionOwner] = useState<
id: null as unknown as number, Partial<AccountSettings>
name: "", >({});
username: "",
image: "",
archiveAsScreenshot: undefined as unknown as boolean,
archiveAsMonolith: undefined as unknown as boolean,
archiveAsPDF: undefined as unknown as boolean,
});
useEffect(() => { useEffect(() => {
const fetchOwner = async () => { const fetchOwner = async () => {
@@ -91,19 +92,25 @@ export default function EditCollectionSharingModal({
members: [...collection.members, newMember], members: [...collection.members, newMember],
}); });
setMemberUsername(""); setMemberIdentifier("");
}; };
const router = useRouter();
const isPublicRoute = router.pathname.startsWith("/public") ? true : false;
return ( return (
<Modal toggleModal={onClose}> <Modal toggleModal={onClose}>
<p className="text-xl font-thin"> <p className="text-xl font-thin">
{permissions === true ? t("share_and_collaborate") : t("team")} {permissions === true && !isPublicRoute
? t("share_and_collaborate")
: t("team")}
</p> </p>
<div className="divider mb-3 mt-1"></div> <div className="divider mb-3 mt-1"></div>
<div className="flex flex-col gap-3"> <div className="flex flex-col gap-3">
{permissions === true && ( {permissions === true && !isPublicRoute && (
<div> <div>
<p>{t("make_collection_public")}</p> <p>{t("make_collection_public")}</p>
@@ -130,43 +137,35 @@ export default function EditCollectionSharingModal({
</div> </div>
)} )}
{collection.isPublic ? ( {collection.isPublic && (
<div className={permissions === true ? "pl-5" : ""}> <div>
<p className="mb-2">{t("sharable_link_guide")}</p> <p className="mb-2">{t("sharable_link")}</p>
<div <div className="w-full hide-scrollbar overflow-x-auto whitespace-nowrap rounded-md p-2 bg-base-200 border-neutral-content border-solid border flex items-center gap-2 justify-between">
onClick={() => {
try {
navigator.clipboard
.writeText(publicCollectionURL)
.then(() => toast.success(t("copied")));
} catch (err) {
console.log(err);
}
}}
className="w-full hide-scrollbar overflow-x-auto whitespace-nowrap rounded-md p-2 bg-base-200 border-neutral-content border-solid border outline-none hover:border-primary dark:hover:border-primary duration-100 cursor-text"
>
{publicCollectionURL} {publicCollectionURL}
<CopyButton text={publicCollectionURL} />
</div> </div>
</div> </div>
) : null} )}
{permissions === true && <div className="divider my-3"></div>} {permissions === true && !isPublicRoute && (
<div className="divider my-3"></div>
)}
{permissions === true && ( {permissions === true && !isPublicRoute && (
<> <>
<p>{t("members")}</p> <p>{t("members")}</p>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<TextInput <TextInput
value={memberUsername || ""} value={memberIdentifier || ""}
className="bg-base-200" className="bg-base-200"
placeholder={t("members_username_placeholder")} placeholder={t("add_member_placeholder")}
onChange={(e) => setMemberUsername(e.target.value)} onChange={(e) => setMemberIdentifier(e.target.value)}
onKeyDown={(e) => onKeyDown={(e) =>
e.key === "Enter" && e.key === "Enter" &&
addMemberToCollection( addMemberToCollection(
account.username as string, user,
memberUsername || "", memberIdentifier.replace(/^@/, "") || "",
collection, collection,
setMemberState, setMemberState,
t t
@@ -177,8 +176,8 @@ export default function EditCollectionSharingModal({
<div <div
onClick={() => onClick={() =>
addMemberToCollection( addMemberToCollection(
account.username as string, user,
memberUsername || "", memberIdentifier.replace(/^@/, "") || "",
collection, collection,
setMemberState, setMemberState,
t t
@@ -264,7 +263,7 @@ export default function EditCollectionSharingModal({
</div> </div>
<div className={"flex items-center gap-2"}> <div className={"flex items-center gap-2"}>
{permissions === true ? ( {permissions === true && !isPublicRoute ? (
<div className="dropdown dropdown-bottom dropdown-end"> <div className="dropdown dropdown-bottom dropdown-end">
<div <div
tabIndex={0} tabIndex={0}
@@ -275,7 +274,7 @@ export default function EditCollectionSharingModal({
{roleLabel} {roleLabel}
<i className="bi-chevron-down"></i> <i className="bi-chevron-down"></i>
</div> </div>
<ul className="dropdown-content z-[30] menu shadow bg-base-200 border border-neutral-content rounded-xl w-64 mt-1"> <ul className="dropdown-content z-[30] menu shadow bg-base-200 border border-neutral-content rounded-xl mt-1">
<li> <li>
<label <label
className="label cursor-pointer flex justify-start" className="label cursor-pointer flex justify-start"
@@ -314,10 +313,12 @@ export default function EditCollectionSharingModal({
}} }}
/> />
<div> <div>
<p className="font-bold"> <p className="font-bold whitespace-nowrap">
{t("viewer")} {t("viewer")}
</p> </p>
<p>{t("viewer_desc")}</p> <p className="whitespace-nowrap">
{t("viewer_desc")}
</p>
</div> </div>
</label> </label>
</li> </li>
@@ -359,10 +360,12 @@ export default function EditCollectionSharingModal({
}} }}
/> />
<div> <div>
<p className="font-bold"> <p className="font-bold whitespace-nowrap">
{t("contributor")} {t("contributor")}
</p> </p>
<p>{t("contributor_desc")}</p> <p className="whitespace-nowrap">
{t("contributor_desc")}
</p>
</div> </div>
</label> </label>
</li> </li>
@@ -404,10 +407,12 @@ export default function EditCollectionSharingModal({
}} }}
/> />
<div> <div>
<p className="font-bold"> <p className="font-bold whitespace-nowrap">
{t("admin")} {t("admin")}
</p> </p>
<p>{t("admin_desc")}</p> <p className="whitespace-nowrap">
{t("admin_desc")}
</p>
</div> </div>
</label> </label>
</li> </li>
@@ -419,7 +424,7 @@ export default function EditCollectionSharingModal({
</p> </p>
)} )}
{permissions === true && ( {permissions === true && !isPublicRoute && (
<i <i
className={ className={
"bi-x text-xl btn btn-sm btn-square btn-ghost text-neutral hover:text-red-500 dark:hover:text-red-500 duration-100 cursor-pointer" "bi-x text-xl btn btn-sm btn-square btn-ghost text-neutral hover:text-red-500 dark:hover:text-red-500 duration-100 cursor-pointer"
@@ -450,7 +455,7 @@ export default function EditCollectionSharingModal({
</> </>
)} )}
{permissions === true && ( {permissions === true && !isPublicRoute && (
<button <button
className="btn btn-accent dark:border-violet-400 text-white w-fit ml-auto mt-3" className="btn btn-accent dark:border-violet-400 text-white w-fit ml-auto mt-3"
onClick={submit} onClick={submit}
-149
View File
@@ -1,149 +0,0 @@
import React, { useEffect, useState } from "react";
import CollectionSelection from "@/components/InputSelect/CollectionSelection";
import TagSelection from "@/components/InputSelect/TagSelection";
import TextInput from "@/components/TextInput";
import unescapeString from "@/lib/client/unescapeString";
import useLinkStore from "@/store/links";
import { LinkIncludingShortenedCollectionAndTags } from "@/types/global";
import toast from "react-hot-toast";
import Link from "next/link";
import Modal from "../Modal";
import { useTranslation } from "next-i18next";
type Props = {
onClose: Function;
activeLink: LinkIncludingShortenedCollectionAndTags;
};
export default function EditLinkModal({ onClose, activeLink }: Props) {
const { t } = useTranslation();
const [link, setLink] =
useState<LinkIncludingShortenedCollectionAndTags>(activeLink);
let shortenedURL;
try {
shortenedURL = new URL(link.url || "").host.toLowerCase();
} catch (error) {
console.log(error);
}
const { updateLink } = useLinkStore();
const [submitLoader, setSubmitLoader] = useState(false);
const setCollection = (e: any) => {
if (e?.__isNew__) e.value = null;
setLink({
...link,
collection: { id: e?.value, name: e?.label, ownerId: e?.ownerId },
});
};
const setTags = (e: any) => {
const tagNames = e.map((e: any) => ({ name: e.label }));
setLink({ ...link, tags: tagNames });
};
useEffect(() => {
setLink(activeLink);
}, []);
const submit = async () => {
if (!submitLoader) {
setSubmitLoader(true);
const load = toast.loading(t("updating"));
let response = await updateLink(link);
toast.dismiss(load);
if (response.ok) {
toast.success(t("updated"));
onClose();
} else {
toast.error(response.data as string);
}
setSubmitLoader(false);
return response;
}
};
return (
<Modal toggleModal={onClose}>
<p className="text-xl font-thin">{t("edit_link")}</p>
<div className="divider mb-3 mt-1"></div>
{link.url ? (
<Link
href={link.url}
className="truncate text-neutral flex gap-2 mb-5 w-fit max-w-full"
title={link.url}
target="_blank"
>
<i className="bi-link-45deg text-xl" />
<p>{shortenedURL}</p>
</Link>
) : undefined}
<div className="w-full">
<p className="mb-2">{t("name")}</p>
<TextInput
value={link.name}
onChange={(e) => setLink({ ...link, name: e.target.value })}
placeholder={t("placeholder_example_link")}
className="bg-base-200"
/>
</div>
<div className="mt-5">
<div className="grid sm:grid-cols-2 gap-3">
<div>
<p className="mb-2">{t("collection")}</p>
{link.collection.name ? (
<CollectionSelection
onChange={setCollection}
defaultValue={
link.collection.id
? { value: link.collection.id, label: link.collection.name }
: { value: null as unknown as number, label: "Unorganized" }
}
creatable={false}
/>
) : null}
</div>
<div>
<p className="mb-2">{t("tags")}</p>
<TagSelection
onChange={setTags}
defaultValue={link.tags.map((e) => ({
label: e.name,
value: e.id,
}))}
/>
</div>
<div className="sm:col-span-2">
<p className="mb-2">{t("description")}</p>
<textarea
value={unescapeString(link.description) as string}
onChange={(e) =>
setLink({ ...link, description: e.target.value })
}
placeholder={t("link_description_placeholder")}
className="resize-none w-full rounded-md p-2 border-neutral-content bg-base-200 focus:border-sky-300 dark:focus:border-sky-600 border-solid border outline-none duration-100"
/>
</div>
</div>
</div>
<div className="flex justify-end items-center mt-5">
<button
className="btn btn-accent dark:border-violet-400 text-white"
onClick={submit}
>
{t("save_changes")}
</button>
</div>
</Modal>
);
}
+131
View File
@@ -0,0 +1,131 @@
import toast from "react-hot-toast";
import Modal from "../Modal";
import TextInput from "../TextInput";
import { FormEvent, useState } from "react";
import { useTranslation, Trans } from "next-i18next";
import { useAddUser } from "@/hooks/store/admin/users";
import Link from "next/link";
import { signIn } from "next-auth/react";
type Props = {
onClose: Function;
};
type FormData = {
username?: string;
email?: string;
invite: boolean;
};
const emailEnabled = process.env.NEXT_PUBLIC_EMAIL_PROVIDER === "true";
export default function InviteModal({ onClose }: Props) {
const { t } = useTranslation();
const addUser = useAddUser();
const [form, setForm] = useState<FormData>({
username: emailEnabled ? undefined : "",
email: emailEnabled ? "" : undefined,
invite: true,
});
const [submitLoader, setSubmitLoader] = useState(false);
async function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (!submitLoader) {
const checkFields = () => {
if (emailEnabled) {
return form.email !== "";
} else {
return form.username !== "";
}
};
if (checkFields()) {
setSubmitLoader(true);
await addUser.mutateAsync(form, {
onSettled: () => {
setSubmitLoader(false);
},
onSuccess: async () => {
await signIn("invite", {
email: form.email,
callbackUrl: "/member-onboarding",
redirect: false,
});
onClose();
},
});
} else {
toast.error(t("fill_all_fields_error"));
}
}
}
return (
<Modal toggleModal={onClose}>
<p className="text-xl font-thin">{t("invite_user")}</p>
<div className="divider mb-3 mt-1"></div>
<p className="mb-3">{t("invite_user_desc")}</p>
<form onSubmit={submit}>
{emailEnabled ? (
<div>
<TextInput
placeholder={t("placeholder_email")}
className="bg-base-200"
onChange={(e) => setForm({ ...form, email: e.target.value })}
value={form.email}
/>
</div>
) : (
<div>
<p className="mb-2">
{t("username")}{" "}
{emailEnabled && (
<span className="text-xs text-neutral">{t("optional")}</span>
)}
</p>
<TextInput
placeholder={t("placeholder_john")}
className="bg-base-200"
onChange={(e) => setForm({ ...form, username: e.target.value })}
value={form.username}
/>
</div>
)}
<div role="note" className="alert alert-note mt-5">
<i className="bi-exclamation-triangle text-xl" />
<span>
<p>{t("invite_user_note")}</p>
<p className="mb-1">
{t("invite_user_price", {
price: 4,
priceAnnual: 36,
})}
</p>
<Link
href="https://docs.linkwarden.app/billing/seats#how-seats-affect-billing"
className="font-semibold whitespace-nowrap hover:opacity-80 duration-100"
target="_blank"
>
{t("learn_more")} <i className="bi-box-arrow-up-right"></i>
</Link>
</span>
</div>
<div className="flex justify-between items-center mt-5">
<button
className="btn btn-accent dark:border-violet-400 text-white ml-auto"
type="submit"
>
{t("send_invitation")}
</button>
</div>
</form>
</Modal>
);
}
+186
View File
@@ -0,0 +1,186 @@
import React, { useState } from "react";
import { LinkIncludingShortenedCollectionAndTags } from "@/types/global";
import { useTranslation } from "next-i18next";
import { useDeleteLink } from "@/hooks/store/links";
import Drawer from "../Drawer";
import LinkDetails from "../LinkDetails";
import Link from "next/link";
import usePermissions from "@/hooks/usePermissions";
import { useRouter } from "next/router";
import { dropdownTriggerer } from "@/lib/client/utils";
import toast from "react-hot-toast";
import clsx from "clsx";
type Props = {
onClose: Function;
onDelete: Function;
onUpdateArchive: Function;
onPin: Function;
link: LinkIncludingShortenedCollectionAndTags;
activeMode?: "view" | "edit";
};
export default function LinkModal({
onClose,
onDelete,
onUpdateArchive,
onPin,
link,
activeMode,
}: Props) {
const { t } = useTranslation();
const permissions = usePermissions(link.collection.id as number);
const router = useRouter();
const isPublicRoute = router.pathname.startsWith("/public") ? true : false;
const deleteLink = useDeleteLink();
const [mode, setMode] = useState<"view" | "edit">(activeMode || "view");
return (
<Drawer
toggleDrawer={onClose}
className="sm:h-screen items-center relative"
>
<div className="absolute top-3 left-0 right-0 flex justify-between px-3">
<div
className="bi-x text-xl btn btn-sm btn-circle text-base-content opacity-50 hover:opacity-100 z-10"
onClick={() => onClose()}
></div>
{(permissions === true || permissions?.canUpdate) && !isPublicRoute && (
<div className="flex gap-1 h-8 rounded-full bg-neutral-content bg-opacity-50 text-base-content p-1 text-xs duration-100 select-none z-10">
<div
className={clsx(
"py-1 px-2 cursor-pointer duration-100 rounded-full font-semibold",
mode === "view" && "bg-primary bg-opacity-50"
)}
onClick={() => {
setMode("view");
}}
>
View
</div>
<div
className={clsx(
"py-1 px-2 cursor-pointer duration-100 rounded-full font-semibold",
mode === "edit" && "bg-primary bg-opacity-50"
)}
onClick={() => {
setMode("edit");
}}
>
Edit
</div>
</div>
)}
<div className="flex gap-2">
{!isPublicRoute && (
<div className={`dropdown dropdown-end z-20`}>
<div
tabIndex={0}
role="button"
onMouseDown={dropdownTriggerer}
className="btn btn-sm btn-circle text-base-content opacity-50 hover:opacity-100 z-10"
>
<i title="More" className="bi-three-dots text-xl" />
</div>
<ul
className={`dropdown-content z-[20] menu shadow bg-base-200 border border-neutral-content rounded-box`}
>
{
<li>
<div
role="button"
tabIndex={0}
onClick={() => {
(document?.activeElement as HTMLElement)?.blur();
onPin();
}}
className="whitespace-nowrap"
>
{link?.pinnedBy && link.pinnedBy[0]
? t("unpin")
: t("pin_to_dashboard")}
</div>
</li>
}
{link.type === "url" &&
(permissions === true || permissions?.canUpdate) && (
<li>
<div
role="button"
tabIndex={0}
onClick={() => {
(document?.activeElement as HTMLElement)?.blur();
onUpdateArchive();
}}
className="whitespace-nowrap"
>
{t("refresh_preserved_formats")}
</div>
</li>
)}
{(permissions === true || permissions?.canDelete) && (
<li>
<div
role="button"
tabIndex={0}
onClick={async (e) => {
(document?.activeElement as HTMLElement)?.blur();
console.log(e.shiftKey);
if (e.shiftKey) {
const load = toast.loading(t("deleting"));
await deleteLink.mutateAsync(link.id as number, {
onSettled: (data, error) => {
toast.dismiss(load);
if (error) {
toast.error(error.message);
} else {
toast.success(t("deleted"));
}
},
});
onClose();
} else {
onDelete();
onClose();
}
}}
className="whitespace-nowrap"
>
{t("delete")}
</div>
</li>
)}
</ul>
</div>
)}
{link.url && (
<Link
href={link.url}
target="_blank"
className="bi-box-arrow-up-right btn-circle text-base-content opacity-50 hover:opacity-100 btn btn-sm select-none z-10"
></Link>
)}
</div>
</div>
<div className="w-full">
<LinkDetails
activeLink={link}
className="sm:mt-0 -mt-11"
mode={mode}
setMode={(mode: "view" | "edit") => setMode(mode)}
onUpdateArchive={onUpdateArchive}
/>
</div>
</Drawer>
);
}
+45 -49
View File
@@ -1,14 +1,13 @@
import React, { useEffect, useState } from "react"; import React, { useEffect, useState } from "react";
import TextInput from "@/components/TextInput"; import TextInput from "@/components/TextInput";
import useCollectionStore from "@/store/collections";
import toast from "react-hot-toast";
import { HexColorPicker } from "react-colorful";
import { Collection } from "@prisma/client"; import { Collection } from "@prisma/client";
import Modal from "../Modal"; import Modal from "../Modal";
import { CollectionIncludingMembersAndLinkCount } from "@/types/global"; import { CollectionIncludingMembersAndLinkCount } from "@/types/global";
import useAccountStore from "@/store/account";
import { useSession } from "next-auth/react";
import { useTranslation } from "next-i18next"; import { useTranslation } from "next-i18next";
import { useCreateCollection } from "@/hooks/store/collections";
import toast from "react-hot-toast";
import IconPicker from "../IconPicker";
import { IconWeight } from "@phosphor-icons/react";
type Props = { type Props = {
onClose: Function; onClose: Function;
@@ -25,15 +24,14 @@ export default function NewCollectionModal({ onClose, parent }: Props) {
} as Partial<Collection>; } as Partial<Collection>;
const [collection, setCollection] = useState<Partial<Collection>>(initial); const [collection, setCollection] = useState<Partial<Collection>>(initial);
const { setAccount } = useAccountStore();
const { data } = useSession();
useEffect(() => { useEffect(() => {
setCollection(initial); setCollection(initial);
}, []); }, []);
const [submitLoader, setSubmitLoader] = useState(false); const [submitLoader, setSubmitLoader] = useState(false);
const { addCollection } = useCollectionStore();
const createCollection = useCreateCollection();
const submit = async () => { const submit = async () => {
if (submitLoader) return; if (submitLoader) return;
@@ -43,18 +41,19 @@ export default function NewCollectionModal({ onClose, parent }: Props) {
const load = toast.loading(t("creating")); const load = toast.loading(t("creating"));
let response = await addCollection(collection as any); await createCollection.mutateAsync(collection, {
toast.dismiss(load); onSettled: (data, error) => {
setSubmitLoader(false);
toast.dismiss(load);
if (response.ok) { if (error) {
toast.success(t("created_success")); toast.error(error.message);
if (response.data) { } else {
setAccount(data?.user.id as number); onClose();
onClose(); toast.success(t("created"));
} }
} else toast.error(response.data as string); },
});
setSubmitLoader(false);
}; };
return ( return (
@@ -73,10 +72,32 @@ export default function NewCollectionModal({ onClose, parent }: Props) {
<div className="divider mb-3 mt-1"></div> <div className="divider mb-3 mt-1"></div>
<div className="flex flex-col gap-3"> <div className="flex flex-col gap-3">
<div className="flex flex-col sm:flex-row gap-3"> <div className="flex flex-col gap-3">
<div className="w-full"> <div className="flex gap-3 items-end">
<p className="mb-2">{t("name")}</p> <IconPicker
<div className="flex flex-col gap-2"> color={collection.color || "#0ea5e9"}
setColor={(color: string) =>
setCollection({ ...collection, color })
}
weight={(collection.iconWeight || "regular") as IconWeight}
setWeight={(iconWeight: string) =>
setCollection({ ...collection, iconWeight })
}
iconName={collection.icon as string}
setIconName={(icon: string) =>
setCollection({ ...collection, icon })
}
reset={() =>
setCollection({
...collection,
color: "#0ea5e9",
icon: "",
iconWeight: "",
})
}
/>
<div className="w-full">
<p className="mb-2">{t("name")}</p>
<TextInput <TextInput
className="bg-base-200" className="bg-base-200"
value={collection.name} value={collection.name}
@@ -85,38 +106,13 @@ export default function NewCollectionModal({ onClose, parent }: Props) {
setCollection({ ...collection, name: e.target.value }) setCollection({ ...collection, name: e.target.value })
} }
/> />
<div>
<p className="w-full mb-2">{t("color")}</p>
<div className="color-picker flex justify-between items-center">
<HexColorPicker
color={collection.color}
onChange={(color) =>
setCollection({ ...collection, color })
}
/>
<div className="flex flex-col gap-2 items-center w-32">
<i
className={"bi-folder-fill text-5xl"}
style={{ color: collection.color }}
></i>
<div
className="btn btn-ghost btn-xs"
onClick={() =>
setCollection({ ...collection, color: "#0ea5e9" })
}
>
{t("reset")}
</div>
</div>
</div>
</div>
</div> </div>
</div> </div>
<div className="w-full"> <div className="w-full">
<p className="mb-2">{t("description")}</p> <p className="mb-2">{t("description")}</p>
<textarea <textarea
className="w-full h-[13rem] resize-none border rounded-md duration-100 bg-base-200 p-2 outline-none border-neutral-content focus:border-primary" className="w-full h-32 resize-none border rounded-md duration-100 bg-base-200 p-2 outline-none border-neutral-content focus:border-primary"
placeholder={t("collection_description_placeholder")} placeholder={t("collection_description_placeholder")}
value={collection.description} value={collection.description}
onChange={(e) => onChange={(e) =>
+41 -47
View File
@@ -1,17 +1,15 @@
import React, { useEffect, useState } from "react"; import React, { useEffect, useState } from "react";
import { Toaster } from "react-hot-toast";
import CollectionSelection from "@/components/InputSelect/CollectionSelection"; import CollectionSelection from "@/components/InputSelect/CollectionSelection";
import TagSelection from "@/components/InputSelect/TagSelection"; import TagSelection from "@/components/InputSelect/TagSelection";
import TextInput from "@/components/TextInput"; import TextInput from "@/components/TextInput";
import unescapeString from "@/lib/client/unescapeString"; import unescapeString from "@/lib/client/unescapeString";
import useCollectionStore from "@/store/collections";
import useLinkStore from "@/store/links";
import { LinkIncludingShortenedCollectionAndTags } from "@/types/global";
import { useSession } from "next-auth/react";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import toast from "react-hot-toast";
import Modal from "../Modal"; import Modal from "../Modal";
import { useTranslation } from "next-i18next"; import { useTranslation } from "next-i18next";
import { useCollections } from "@/hooks/store/collections";
import { useAddLink } from "@/hooks/store/links";
import toast from "react-hot-toast";
import { PostLinkSchemaType } from "@/lib/shared/schemaValidation";
type Props = { type Props = {
onClose: Function; onClose: Function;
@@ -19,38 +17,32 @@ type Props = {
export default function NewLinkModal({ onClose }: Props) { export default function NewLinkModal({ onClose }: Props) {
const { t } = useTranslation(); const { t } = useTranslation();
const { data } = useSession();
const initial = { const initial = {
name: "", name: "",
url: "", url: "",
description: "", description: "",
type: "url", type: "url",
tags: [], tags: [],
preview: "",
image: "",
pdf: "",
readable: "",
monolith: "",
textContent: "",
collection: { collection: {
id: undefined,
name: "", name: "",
ownerId: data?.user.id as number,
}, },
} as LinkIncludingShortenedCollectionAndTags; } as PostLinkSchemaType;
const [link, setLink] = useState<PostLinkSchemaType>(initial);
const addLink = useAddLink();
const [link, setLink] =
useState<LinkIncludingShortenedCollectionAndTags>(initial);
const { addLink } = useLinkStore();
const [submitLoader, setSubmitLoader] = useState(false); const [submitLoader, setSubmitLoader] = useState(false);
const [optionsExpanded, setOptionsExpanded] = useState(false); const [optionsExpanded, setOptionsExpanded] = useState(false);
const router = useRouter(); const router = useRouter();
const { collections } = useCollectionStore(); const { data: collections = [] } = useCollections();
const setCollection = (e: any) => { const setCollection = (e: any) => {
if (e?.__isNew__) e.value = null; if (e?.__isNew__) e.value = undefined;
setLink({ setLink({
...link, ...link,
collection: { id: e?.value, name: e?.label, ownerId: e?.ownerId }, collection: { id: e?.value, name: e?.label },
}); });
}; };
@@ -60,43 +52,45 @@ export default function NewLinkModal({ onClose }: Props) {
}; };
useEffect(() => { useEffect(() => {
if (router.query.id) { if (router.pathname.startsWith("/collections/") && router.query.id) {
const currentCollection = collections.find( const currentCollection = collections.find(
(e) => e.id == Number(router.query.id) (e) => e.id == Number(router.query.id)
); );
if (
currentCollection && if (currentCollection && currentCollection.ownerId)
currentCollection.ownerId &&
router.asPath.startsWith("/collections/")
)
setLink({ setLink({
...initial, ...initial,
collection: { collection: {
id: currentCollection.id, id: currentCollection.id,
name: currentCollection.name, name: currentCollection.name,
ownerId: currentCollection.ownerId,
}, },
}); });
} else } else
setLink({ setLink({
...initial, ...initial,
collection: { name: "Unorganized", ownerId: data?.user.id as number }, collection: { name: "Unorganized" },
}); });
}, []); }, []);
const submit = async () => { const submit = async () => {
if (!submitLoader) { if (!submitLoader) {
setSubmitLoader(true); setSubmitLoader(true);
const load = toast.loading(t("creating_link")); const load = toast.loading(t("creating_link"));
const response = await addLink(link);
toast.dismiss(load); await addLink.mutateAsync(link, {
if (response.ok) { onSettled: (data, error) => {
toast.success(t("link_created")); setSubmitLoader(false);
onClose(); toast.dismiss(load);
} else {
toast.error(response.data as string); if (error) {
} toast.error(t(error.message));
setSubmitLoader(false); } else {
onClose();
toast.success(t("link_created"));
}
},
});
} }
}; };
@@ -116,19 +110,19 @@ export default function NewLinkModal({ onClose }: Props) {
</div> </div>
<div className="sm:col-span-2 col-span-5"> <div className="sm:col-span-2 col-span-5">
<p className="mb-2">{t("collection")}</p> <p className="mb-2">{t("collection")}</p>
{link.collection.name ? ( {link.collection?.name && (
<CollectionSelection <CollectionSelection
onChange={setCollection} onChange={setCollection}
defaultValue={{ defaultValue={{
label: link.collection.name, value: link.collection?.id,
value: link.collection.id, label: link.collection?.name || "Unorganized",
}} }}
/> />
) : null} )}
</div> </div>
</div> </div>
<div className={"mt-2"}> <div className={"mt-2"}>
{optionsExpanded ? ( {optionsExpanded && (
<div className="mt-5"> <div className="mt-5">
<div className="grid sm:grid-cols-2 gap-3"> <div className="grid sm:grid-cols-2 gap-3">
<div> <div>
@@ -144,7 +138,7 @@ export default function NewLinkModal({ onClose }: Props) {
<p className="mb-2">{t("tags")}</p> <p className="mb-2">{t("tags")}</p>
<TagSelection <TagSelection
onChange={setTags} onChange={setTags}
defaultValue={link.tags.map((e) => ({ defaultValue={link.tags?.map((e) => ({
label: e.name, label: e.name,
value: e.id, value: e.id,
}))} }))}
@@ -153,17 +147,17 @@ export default function NewLinkModal({ onClose }: Props) {
<div className="sm:col-span-2"> <div className="sm:col-span-2">
<p className="mb-2">{t("description")}</p> <p className="mb-2">{t("description")}</p>
<textarea <textarea
value={unescapeString(link.description) as string} value={unescapeString(link.description || "") || ""}
onChange={(e) => onChange={(e) =>
setLink({ ...link, description: e.target.value }) setLink({ ...link, description: e.target.value })
} }
placeholder={t("link_description_placeholder")} placeholder={t("link_description_placeholder")}
className="resize-none w-full rounded-md p-2 border-neutral-content bg-base-200 focus:border-primary border-solid border outline-none duration-100" className="resize-none w-full h-32 rounded-md p-2 border-neutral-content bg-base-200 focus:border-primary border-solid border outline-none duration-100"
/> />
</div> </div>
</div> </div>
</div> </div>
) : undefined} )}
</div> </div>
<div className="flex justify-between items-center mt-5"> <div className="flex justify-between items-center mt-5">
<div <div
+39 -32
View File
@@ -3,10 +3,11 @@ import TextInput from "@/components/TextInput";
import { TokenExpiry } from "@/types/global"; import { TokenExpiry } from "@/types/global";
import toast from "react-hot-toast"; import toast from "react-hot-toast";
import Modal from "../Modal"; import Modal from "../Modal";
import useTokenStore from "@/store/tokens";
import { dropdownTriggerer } from "@/lib/client/utils"; import { dropdownTriggerer } from "@/lib/client/utils";
import Button from "../ui/Button"; import Button from "../ui/Button";
import { useTranslation } from "next-i18next"; import { useTranslation } from "next-i18next";
import { useAddToken } from "@/hooks/store/tokens";
import CopyButton from "../CopyButton";
type Props = { type Props = {
onClose: Function; onClose: Function;
@@ -15,7 +16,7 @@ type Props = {
export default function NewTokenModal({ onClose }: Props) { export default function NewTokenModal({ onClose }: Props) {
const { t } = useTranslation(); const { t } = useTranslation();
const [newToken, setNewToken] = useState(""); const [newToken, setNewToken] = useState("");
const { addToken } = useTokenStore(); const addToken = useAddToken();
const initial = { const initial = {
name: "", name: "",
@@ -28,18 +29,21 @@ export default function NewTokenModal({ onClose }: Props) {
const submit = async () => { const submit = async () => {
if (!submitLoader) { if (!submitLoader) {
setSubmitLoader(true); setSubmitLoader(true);
const load = toast.loading(t("creating_token")); const load = toast.loading(t("creating_token"));
const { ok, data } = await addToken(token); await addToken.mutateAsync(token, {
onSettled: (data, error) => {
setSubmitLoader(false);
toast.dismiss(load);
toast.dismiss(load); if (error) {
toast.error(error.message);
if (ok) { } else {
toast.success(t("token_created")); setNewToken(data.secretKey);
setNewToken((data as any).secretKey); }
} else toast.error(data as string); },
});
setSubmitLoader(false);
} }
}; };
@@ -64,21 +68,14 @@ export default function NewTokenModal({ onClose }: Props) {
<div className="flex flex-col justify-center space-y-4"> <div className="flex flex-col justify-center space-y-4">
<p className="text-xl font-thin">{t("access_token_created")}</p> <p className="text-xl font-thin">{t("access_token_created")}</p>
<p>{t("token_creation_notice")}</p> <p>{t("token_creation_notice")}</p>
<TextInput <div className="relative">
spellCheck={false} <div className="w-full hide-scrollbar overflow-x-auto whitespace-nowrap rounded-md p-2 bg-base-200 border-neutral-content border-solid border flex items-center gap-2 justify-between pr-14">
value={newToken} {newToken}
onChange={() => {}} <div className="absolute right-0 px-2 border-neutral-content border-solid border-r bg-base-200">
className="w-full" <CopyButton text={newToken} />
/> </div>
<button </div>
onClick={() => { </div>
navigator.clipboard.writeText(newToken);
toast.success(t("copied_to_clipboard"));
}}
className="btn btn-primary w-fit mx-auto"
>
{t("copy_to_clipboard")}
</button>
</div> </div>
) : ( ) : (
<> <>
@@ -111,7 +108,7 @@ export default function NewTokenModal({ onClose }: Props) {
> >
{getLabel(token.expires)} {getLabel(token.expires)}
</Button> </Button>
<ul className="dropdown-content z-[30] menu shadow bg-base-200 border border-neutral-content rounded-xl w-full sm:w-52 mt-1"> <ul className="dropdown-content z-[30] menu shadow bg-base-200 border border-neutral-content rounded-xl mt-1">
<li> <li>
<label <label
className="label cursor-pointer flex justify-start" className="label cursor-pointer flex justify-start"
@@ -131,7 +128,9 @@ export default function NewTokenModal({ onClose }: Props) {
}); });
}} }}
/> />
<span className="label-text">{t("7_days")}</span> <span className="label-text whitespace-nowrap">
{t("7_days")}
</span>
</label> </label>
</li> </li>
<li> <li>
@@ -150,7 +149,9 @@ export default function NewTokenModal({ onClose }: Props) {
setToken({ ...token, expires: TokenExpiry.oneMonth }); setToken({ ...token, expires: TokenExpiry.oneMonth });
}} }}
/> />
<span className="label-text">{t("30_days")}</span> <span className="label-text whitespace-nowrap">
{t("30_days")}
</span>
</label> </label>
</li> </li>
<li> <li>
@@ -172,7 +173,9 @@ export default function NewTokenModal({ onClose }: Props) {
}); });
}} }}
/> />
<span className="label-text">{t("60_days")}</span> <span className="label-text whitespace-nowrap">
{t("60_days")}
</span>
</label> </label>
</li> </li>
<li> <li>
@@ -194,7 +197,9 @@ export default function NewTokenModal({ onClose }: Props) {
}); });
}} }}
/> />
<span className="label-text">{t("90_days")}</span> <span className="label-text whitespace-nowrap">
{t("90_days")}
</span>
</label> </label>
</li> </li>
<li> <li>
@@ -213,7 +218,9 @@ export default function NewTokenModal({ onClose }: Props) {
setToken({ ...token, expires: TokenExpiry.never }); setToken({ ...token, expires: TokenExpiry.never });
}} }}
/> />
<span className="label-text">{t("no_expiration")}</span> <span className="label-text whitespace-nowrap">
{t("no_expiration")}
</span>
</label> </label>
</li> </li>
</ul> </ul>
+17 -20
View File
@@ -1,9 +1,9 @@
import toast from "react-hot-toast"; import toast from "react-hot-toast";
import Modal from "../Modal"; import Modal from "../Modal";
import useUserStore from "@/store/admin/users";
import TextInput from "../TextInput"; import TextInput from "../TextInput";
import { FormEvent, useState } from "react"; import { FormEvent, useState } from "react";
import { useTranslation, Trans } from "next-i18next"; import { useTranslation, Trans } from "next-i18next";
import { useAddUser } from "@/hooks/store/admin/users";
type Props = { type Props = {
onClose: Function; onClose: Function;
@@ -20,7 +20,9 @@ const emailEnabled = process.env.NEXT_PUBLIC_EMAIL_PROVIDER === "true";
export default function NewUserModal({ onClose }: Props) { export default function NewUserModal({ onClose }: Props) {
const { t } = useTranslation(); const { t } = useTranslation();
const { addUser } = useUserStore();
const addUser = useAddUser();
const [form, setForm] = useState<FormData>({ const [form, setForm] = useState<FormData>({
name: "", name: "",
username: "", username: "",
@@ -33,6 +35,9 @@ export default function NewUserModal({ onClose }: Props) {
event.preventDefault(); event.preventDefault();
if (!submitLoader) { if (!submitLoader) {
if (form.password.length < 8)
return toast.error(t("password_length_error"));
const checkFields = () => { const checkFields = () => {
if (emailEnabled) { if (emailEnabled) {
return form.name !== "" && form.email !== "" && form.password !== ""; return form.name !== "" && form.email !== "" && form.password !== "";
@@ -44,24 +49,16 @@ export default function NewUserModal({ onClose }: Props) {
}; };
if (checkFields()) { if (checkFields()) {
if (form.password.length < 8)
return toast.error(t("password_length_error"));
setSubmitLoader(true); setSubmitLoader(true);
const load = toast.loading(t("creating_account")); await addUser.mutateAsync(form, {
onSuccess: () => {
const response = await addUser(form); onClose();
},
toast.dismiss(load); onSettled: () => {
setSubmitLoader(false); setSubmitLoader(false);
},
if (response.ok) { });
toast.success(t("user_created"));
onClose();
} else {
toast.error(response.data as string);
}
} else { } else {
toast.error(t("fill_all_fields_error")); toast.error(t("fill_all_fields_error"));
} }
@@ -86,7 +83,7 @@ export default function NewUserModal({ onClose }: Props) {
/> />
</div> </div>
{emailEnabled ? ( {emailEnabled && (
<div> <div>
<p className="mb-2">{t("email")}</p> <p className="mb-2">{t("email")}</p>
<TextInput <TextInput
@@ -96,7 +93,7 @@ export default function NewUserModal({ onClose }: Props) {
value={form.email} value={form.email}
/> />
</div> </div>
) : undefined} )}
<div> <div>
<p className="mb-2"> <p className="mb-2">
@@ -1,258 +0,0 @@
import React, { useEffect, useState } from "react";
import useLinkStore from "@/store/links";
import {
LinkIncludingShortenedCollectionAndTags,
ArchivedFormat,
} from "@/types/global";
import toast from "react-hot-toast";
import Link from "next/link";
import Modal from "../Modal";
import { useRouter } from "next/router";
import { useSession } from "next-auth/react";
import {
pdfAvailable,
readabilityAvailable,
monolithAvailable,
screenshotAvailable,
} from "@/lib/shared/getArchiveValidity";
import PreservedFormatRow from "@/components/PreserverdFormatRow";
import useAccountStore from "@/store/account";
import getPublicUserData from "@/lib/client/getPublicUserData";
import { useTranslation } from "next-i18next";
import { BeatLoader } from "react-spinners";
type Props = {
onClose: Function;
activeLink: LinkIncludingShortenedCollectionAndTags;
};
export default function PreservedFormatsModal({ onClose, activeLink }: Props) {
const { t } = useTranslation();
const session = useSession();
const { getLink } = useLinkStore();
const { account } = useAccountStore();
const [link, setLink] =
useState<LinkIncludingShortenedCollectionAndTags>(activeLink);
const router = useRouter();
let isPublic = router.pathname.startsWith("/public") ? true : undefined;
const [collectionOwner, setCollectionOwner] = useState({
id: null as unknown as number,
name: "",
username: "",
image: "",
archiveAsScreenshot: undefined as unknown as boolean,
archiveAsMonolith: undefined as unknown as boolean,
archiveAsPDF: undefined as unknown as boolean,
});
useEffect(() => {
const fetchOwner = async () => {
if (link.collection.ownerId !== account.id) {
const owner = await getPublicUserData(
link.collection.ownerId as number
);
setCollectionOwner(owner);
} else if (link.collection.ownerId === account.id) {
setCollectionOwner({
id: account.id as number,
name: account.name,
username: account.username as string,
image: account.image as string,
archiveAsScreenshot: account.archiveAsScreenshot as boolean,
archiveAsMonolith: account.archiveAsScreenshot as boolean,
archiveAsPDF: account.archiveAsPDF as boolean,
});
}
};
fetchOwner();
}, [link.collection.ownerId]);
const isReady = () => {
return (
link &&
(collectionOwner.archiveAsScreenshot === true
? link.pdf && link.pdf !== "pending"
: true) &&
(collectionOwner.archiveAsMonolith === true
? link.monolith && link.monolith !== "pending"
: true) &&
(collectionOwner.archiveAsPDF === true
? link.pdf && link.pdf !== "pending"
: true) &&
link.readable &&
link.readable !== "pending"
);
};
const atLeastOneFormatAvailable = () => {
return (
screenshotAvailable(link) ||
pdfAvailable(link) ||
readabilityAvailable(link) ||
monolithAvailable(link)
);
};
useEffect(() => {
(async () => {
const data = await getLink(link.id as number, isPublic);
setLink(
(data as any).response as LinkIncludingShortenedCollectionAndTags
);
})();
let interval: any;
if (!isReady()) {
interval = setInterval(async () => {
const data = await getLink(link.id as number, isPublic);
setLink(
(data as any).response as LinkIncludingShortenedCollectionAndTags
);
}, 5000);
} else {
if (interval) {
clearInterval(interval);
}
}
return () => {
if (interval) {
clearInterval(interval);
}
};
}, [link?.monolith]);
const updateArchive = async () => {
const load = toast.loading(t("sending_request"));
const response = await fetch(`/api/v1/links/${link?.id}/archive`, {
method: "PUT",
});
const data = await response.json();
toast.dismiss(load);
if (response.ok) {
const newLink = await getLink(link?.id as number);
setLink(
(newLink as any).response as LinkIncludingShortenedCollectionAndTags
);
toast.success(t("link_being_archived"));
} else toast.error(data.response);
};
return (
<Modal toggleModal={onClose}>
<p className="text-xl font-thin">{t("preserved_formats")}</p>
<div className="divider mb-2 mt-1"></div>
{screenshotAvailable(link) ||
pdfAvailable(link) ||
readabilityAvailable(link) ||
monolithAvailable(link) ? (
<p className="mb-3">{t("available_formats")}</p>
) : (
""
)}
<div className={`flex flex-col gap-3`}>
{monolithAvailable(link) ? (
<PreservedFormatRow
name={t("webpage")}
icon={"bi-filetype-html"}
format={ArchivedFormat.monolith}
activeLink={link}
downloadable={true}
/>
) : undefined}
{screenshotAvailable(link) ? (
<PreservedFormatRow
name={t("screenshot")}
icon={"bi-file-earmark-image"}
format={
link?.image?.endsWith("png")
? ArchivedFormat.png
: ArchivedFormat.jpeg
}
activeLink={link}
downloadable={true}
/>
) : undefined}
{pdfAvailable(link) ? (
<PreservedFormatRow
name={t("pdf")}
icon={"bi-file-earmark-pdf"}
format={ArchivedFormat.pdf}
activeLink={link}
downloadable={true}
/>
) : undefined}
{readabilityAvailable(link) ? (
<PreservedFormatRow
name={t("readable")}
icon={"bi-file-earmark-text"}
format={ArchivedFormat.readability}
activeLink={link}
/>
) : undefined}
{!isReady() && !atLeastOneFormatAvailable() ? (
<div className={`w-full h-full flex flex-col justify-center p-10`}>
<BeatLoader
color="oklch(var(--p))"
className="mx-auto mb-3"
size={30}
/>
<p className="text-center text-2xl">{t("preservation_in_queue")}</p>
<p className="text-center text-lg">{t("check_back_later")}</p>
</div>
) : !isReady() && atLeastOneFormatAvailable() ? (
<div className={`w-full h-full flex flex-col justify-center p-5`}>
<BeatLoader
color="oklch(var(--p))"
className="mx-auto mb-3"
size={20}
/>
<p className="text-center">{t("there_are_more_formats")}</p>
<p className="text-center text-sm">{t("check_back_later")}</p>
</div>
) : undefined}
<div
className={`flex flex-col sm:flex-row gap-3 items-center justify-center ${
isReady() ? "sm:mt " : ""
}`}
>
<Link
href={`https://web.archive.org/web/${link?.url?.replace(
/(^\w+:|^)\/\//,
""
)}`}
target="_blank"
className="text-neutral duration-100 hover:opacity-60 flex gap-2 w-1/2 justify-center items-center text-sm"
>
<p className="whitespace-nowrap">{t("view_latest_snapshot")}</p>
<i className="bi-box-arrow-up-right" />
</Link>
{link?.collection.ownerId === session.data?.user.id && (
<div className="btn btn-outline" onClick={updateArchive}>
<div>
<p>{t("refresh_preserved_formats")}</p>
<p className="text-xs">
{t("this_deletes_current_preservations")}
</p>
</div>
</div>
)}
</div>
</div>
</Modal>
);
}
+14 -13
View File
@@ -1,10 +1,10 @@
import React, { useEffect, useState } from "react"; import React, { useEffect, useState } from "react";
import useTokenStore from "@/store/tokens";
import toast from "react-hot-toast";
import Modal from "../Modal"; import Modal from "../Modal";
import Button from "../ui/Button"; import Button from "../ui/Button";
import { useTranslation } from "next-i18next"; import { useTranslation } from "next-i18next";
import { AccessToken } from "@prisma/client"; import { AccessToken } from "@prisma/client";
import { useRevokeToken } from "@/hooks/store/tokens";
import toast from "react-hot-toast";
type Props = { type Props = {
onClose: Function; onClose: Function;
@@ -15,7 +15,7 @@ export default function DeleteTokenModal({ onClose, activeToken }: Props) {
const { t } = useTranslation(); const { t } = useTranslation();
const [token, setToken] = useState<AccessToken>(activeToken); const [token, setToken] = useState<AccessToken>(activeToken);
const { revokeToken } = useTokenStore(); const revokeToken = useRevokeToken();
useEffect(() => { useEffect(() => {
setToken(activeToken); setToken(activeToken);
@@ -24,17 +24,18 @@ export default function DeleteTokenModal({ onClose, activeToken }: Props) {
const deleteLink = async () => { const deleteLink = async () => {
const load = toast.loading(t("deleting")); const load = toast.loading(t("deleting"));
const response = await revokeToken(token.id as number); await revokeToken.mutateAsync(token.id, {
onSettled: (data, error) => {
toast.dismiss(load);
toast.dismiss(load); if (error) {
toast.error(error.message);
if (response.ok) { } else {
toast.success(t("token_revoked")); onClose();
} else { toast.success(t("token_revoked"));
toast.error(response.data as string); }
} },
});
onClose();
}; };
return ( return (
+67
View File
@@ -0,0 +1,67 @@
import React, { useState } from "react";
import Modal from "../Modal";
import Button from "../ui/Button";
import { useTranslation } from "next-i18next";
type Props = {
onClose: Function;
submit: Function;
};
export default function SurveyModal({ onClose, submit }: Props) {
const { t } = useTranslation();
const [referer, setReferrer] = useState("rather_not_say");
const [other, setOther] = useState("");
return (
<Modal toggleModal={onClose}>
<p className="text-xl font-thin">{t("quick_survey")}</p>
<div className="divider mb-3 mt-1"></div>
<div className="flex flex-col gap-4">
<p>{t("how_did_you_discover_linkwarden")}</p>
<select
onChange={(e) => {
setReferrer(e.target.value);
setOther("");
}}
className="select border border-neutral-content focus:outline-none focus:border-primary duration-100 w-full bg-base-200 rounded-[0.375rem] min-h-0 h-[2.625rem] leading-4 p-2"
>
<option value="rather_not_say">{t("rather_not_say")}</option>
<option value="search_engine">{t("search_engine")}</option>
<option value="people_recommendation">
{t("people_recommendation")}
</option>
<option value="reddit">{t("reddit")}</option>
<option value="github">{t("github")}</option>
<option value="twitter">{t("twitter")}</option>
<option value="mastodon">{t("mastodon")}</option>
<option value="lemmy">{t("lemmy")}</option>
<option value="other">{t("other")}</option>
</select>
{referer === "other" && (
<input
type="text"
placeholder={t("please_specify")}
onChange={(e) => {
setOther(e.target.value);
}}
value={other}
className="input border border-neutral-content focus:border-primary focus:outline-none duration-100 w-full bg-base-200 rounded-[0.375rem] min-h-0 h-[2.625rem] leading-4 p-2"
/>
)}
<Button
className="ml-auto mt-3"
intent="accent"
onClick={() => submit(referer, other)}
>
{t("submit")}
</Button>
</div>
</Modal>
);
}
+40 -42
View File
@@ -3,8 +3,6 @@ import CollectionSelection from "@/components/InputSelect/CollectionSelection";
import TagSelection from "@/components/InputSelect/TagSelection"; import TagSelection from "@/components/InputSelect/TagSelection";
import TextInput from "@/components/TextInput"; import TextInput from "@/components/TextInput";
import unescapeString from "@/lib/client/unescapeString"; import unescapeString from "@/lib/client/unescapeString";
import useCollectionStore from "@/store/collections";
import useLinkStore from "@/store/links";
import { import {
LinkIncludingShortenedCollectionAndTags, LinkIncludingShortenedCollectionAndTags,
ArchivedFormat, ArchivedFormat,
@@ -14,6 +12,9 @@ import { useRouter } from "next/router";
import toast from "react-hot-toast"; import toast from "react-hot-toast";
import Modal from "../Modal"; import Modal from "../Modal";
import { useTranslation } from "next-i18next"; import { useTranslation } from "next-i18next";
import { useCollections } from "@/hooks/store/collections";
import { useUploadFile } from "@/hooks/store/links";
import { PostLinkSchemaType } from "@/lib/shared/schemaValidation";
type Props = { type Props = {
onClose: Function; onClose: Function;
@@ -25,38 +26,30 @@ export default function UploadFileModal({ onClose }: Props) {
const initial = { const initial = {
name: "", name: "",
url: "",
description: "", description: "",
type: "url", type: "url",
tags: [], tags: [],
preview: "",
image: "",
pdf: "",
readable: "",
monolith: "",
textContent: "",
collection: { collection: {
id: undefined,
name: "", name: "",
ownerId: data?.user.id as number,
}, },
} as LinkIncludingShortenedCollectionAndTags; } as PostLinkSchemaType;
const [link, setLink] = const [link, setLink] = useState<PostLinkSchemaType>(initial);
useState<LinkIncludingShortenedCollectionAndTags>(initial);
const [file, setFile] = useState<File>(); const [file, setFile] = useState<File>();
const { uploadFile } = useLinkStore(); const uploadFile = useUploadFile();
const [submitLoader, setSubmitLoader] = useState(false); const [submitLoader, setSubmitLoader] = useState(false);
const [optionsExpanded, setOptionsExpanded] = useState(false); const [optionsExpanded, setOptionsExpanded] = useState(false);
const router = useRouter(); const router = useRouter();
const { collections } = useCollectionStore(); const { data: collections = [] } = useCollections();
const setCollection = (e: any) => { const setCollection = (e: any) => {
if (e?.__isNew__) e.value = null; if (e?.__isNew__) e.value = undefined;
setLink({ setLink({
...link, ...link,
collection: { id: e?.value, name: e?.label, ownerId: e?.ownerId }, collection: { id: e?.value, name: e?.label },
}); });
}; };
@@ -70,10 +63,11 @@ export default function UploadFileModal({ onClose }: Props) {
useEffect(() => { useEffect(() => {
setOptionsExpanded(false); setOptionsExpanded(false);
if (router.query.id) { if (router.pathname.startsWith("/collections/") && router.query.id) {
const currentCollection = collections.find( const currentCollection = collections.find(
(e) => e.id == Number(router.query.id) (e) => e.id == Number(router.query.id)
); );
if ( if (
currentCollection && currentCollection &&
currentCollection.ownerId && currentCollection.ownerId &&
@@ -84,13 +78,12 @@ export default function UploadFileModal({ onClose }: Props) {
collection: { collection: {
id: currentCollection.id, id: currentCollection.id,
name: currentCollection.name, name: currentCollection.name,
ownerId: currentCollection.ownerId,
}, },
}); });
} else } else
setLink({ setLink({
...initial, ...initial,
collection: { name: "Unorganized", ownerId: data?.user.id as number }, collection: { name: "Unorganized" },
}); });
}, [router, collections]); }, [router, collections]);
@@ -115,20 +108,25 @@ export default function UploadFileModal({ onClose }: Props) {
// } // }
setSubmitLoader(true); setSubmitLoader(true);
const load = toast.loading(t("creating")); const load = toast.loading(t("creating"));
const response = await uploadFile(link, file); await uploadFile.mutateAsync(
{ link, file },
{
onSettled: (data, error) => {
setSubmitLoader(false);
toast.dismiss(load);
toast.dismiss(load); if (error) {
if (response.ok) { toast.error(error.message);
toast.success(t("created_success")); } else {
onClose(); onClose();
} else { toast.success(t("created_success"));
toast.error(response.data as string); }
} },
}
setSubmitLoader(false); );
return response;
} }
}; };
@@ -144,7 +142,7 @@ export default function UploadFileModal({ onClose }: Props) {
<label className="btn h-10 btn-sm w-full border border-neutral-content hover:border-neutral-content flex justify-between"> <label className="btn h-10 btn-sm w-full border border-neutral-content hover:border-neutral-content flex justify-between">
<input <input
type="file" type="file"
accept=".pdf,.png,.jpg,.jpeg,.html" accept=".pdf,.png,.jpg,.jpeg"
className="cursor-pointer custom-file-input" className="cursor-pointer custom-file-input"
onChange={(e) => e.target.files && setFile(e.target.files[0])} onChange={(e) => e.target.files && setFile(e.target.files[0])}
/> />
@@ -157,18 +155,18 @@ export default function UploadFileModal({ onClose }: Props) {
</div> </div>
<div className="sm:col-span-2 col-span-5"> <div className="sm:col-span-2 col-span-5">
<p className="mb-2">{t("collection")}</p> <p className="mb-2">{t("collection")}</p>
{link.collection.name ? ( {link.collection?.name && (
<CollectionSelection <CollectionSelection
onChange={setCollection} onChange={setCollection}
defaultValue={{ defaultValue={{
label: link.collection.name, value: link.collection?.id,
value: link.collection.id, label: link.collection?.name || "Unorganized",
}} }}
/> />
) : null} )}
</div> </div>
</div> </div>
{optionsExpanded ? ( {optionsExpanded && (
<div className="mt-5"> <div className="mt-5">
<div className="grid sm:grid-cols-2 gap-3"> <div className="grid sm:grid-cols-2 gap-3">
<div> <div>
@@ -184,26 +182,26 @@ export default function UploadFileModal({ onClose }: Props) {
<p className="mb-2">{t("tags")}</p> <p className="mb-2">{t("tags")}</p>
<TagSelection <TagSelection
onChange={setTags} onChange={setTags}
defaultValue={link.tags.map((e) => ({ defaultValue={link.tags?.map((e) => ({
label: e.name,
value: e.id, value: e.id,
label: e.name,
}))} }))}
/> />
</div> </div>
<div className="sm:col-span-2"> <div className="sm:col-span-2">
<p className="mb-2">{t("description")}</p> <p className="mb-2">{t("description")}</p>
<textarea <textarea
value={unescapeString(link.description) as string} value={unescapeString(link.description || "") || ""}
onChange={(e) => onChange={(e) =>
setLink({ ...link, description: e.target.value }) setLink({ ...link, description: e.target.value })
} }
placeholder={t("description_placeholder")} placeholder={t("description_placeholder")}
className="resize-none w-full rounded-md p-2 border-neutral-content bg-base-200 focus:border-sky-300 dark:focus:border-sky-600 border-solid border outline-none duration-100" className="resize-none w-full h-32 rounded-md p-2 border-neutral-content bg-base-200 focus:border-primary border-solid border outline-none duration-100"
/> />
</div> </div>
</div> </div>
</div> </div>
) : undefined} )}
<div className="flex justify-between items-center mt-5"> <div className="flex justify-between items-center mt-5">
<div <div
onClick={() => setOptionsExpanded(!optionsExpanded)} onClick={() => setOptionsExpanded(!optionsExpanded)}
+11 -10
View File
@@ -66,7 +66,7 @@ export default function Navbar() {
</span> </span>
</div> </div>
</div> </div>
<ul className="dropdown-content z-[1] menu shadow bg-base-200 border border-neutral-content rounded-box w-40 mt-1"> <ul className="dropdown-content z-[1] menu shadow bg-base-200 border border-neutral-content rounded-box mt-1">
<li> <li>
<div <div
onClick={() => { onClick={() => {
@@ -75,6 +75,7 @@ export default function Navbar() {
}} }}
tabIndex={0} tabIndex={0}
role="button" role="button"
className="whitespace-nowrap"
> >
{t("new_link")} {t("new_link")}
</div> </div>
@@ -87,6 +88,7 @@ export default function Navbar() {
}} }}
tabIndex={0} tabIndex={0}
role="button" role="button"
className="whitespace-nowrap"
> >
{t("upload_file")} {t("upload_file")}
</div> </div>
@@ -99,6 +101,7 @@ export default function Navbar() {
}} }}
tabIndex={0} tabIndex={0}
role="button" role="button"
className="whitespace-nowrap"
> >
{t("new_collection")} {t("new_collection")}
</div> </div>
@@ -111,7 +114,7 @@ export default function Navbar() {
<MobileNavigation /> <MobileNavigation />
{sidebar ? ( {sidebar && (
<div className="fixed top-0 bottom-0 right-0 left-0 bg-black bg-opacity-10 backdrop-blur-sm flex items-center fade-in z-40"> <div className="fixed top-0 bottom-0 right-0 left-0 bg-black bg-opacity-10 backdrop-blur-sm flex items-center fade-in z-40">
<ClickAwayHandler className="h-full" onClickOutside={toggleSidebar}> <ClickAwayHandler className="h-full" onClickOutside={toggleSidebar}>
<div className="slide-right h-full shadow-lg"> <div className="slide-right h-full shadow-lg">
@@ -119,16 +122,14 @@ export default function Navbar() {
</div> </div>
</ClickAwayHandler> </ClickAwayHandler>
</div> </div>
) : null} )}
{newLinkModal ? ( {newLinkModal && <NewLinkModal onClose={() => setNewLinkModal(false)} />}
<NewLinkModal onClose={() => setNewLinkModal(false)} /> {newCollectionModal && (
) : undefined}
{newCollectionModal ? (
<NewCollectionModal onClose={() => setNewCollectionModal(false)} /> <NewCollectionModal onClose={() => setNewCollectionModal(false)} />
) : undefined} )}
{uploadFileModal ? ( {uploadFileModal && (
<UploadFileModal onClose={() => setUploadFileModal(false)} /> <UploadFileModal onClose={() => setUploadFileModal(false)} />
) : undefined} )}
</div> </div>
); );
} }
+1 -3
View File
@@ -39,9 +39,7 @@ export default function NoLinksFound({ text }: Props) {
</span> </span>
</div> </div>
</div> </div>
{newLinkModal ? ( {newLinkModal && <NewLinkModal onClose={() => setNewLinkModal(false)} />}
<NewLinkModal onClose={() => setNewLinkModal(false)} />
) : undefined}
</div> </div>
); );
} }
+21
View File
@@ -0,0 +1,21 @@
import React from "react";
import ClickAwayHandler from "./ClickAwayHandler";
type Props = {
children: React.ReactNode;
onClose: Function;
className?: string;
};
const Popover = ({ children, className, onClose }: Props) => {
return (
<ClickAwayHandler
onClickOutside={() => onClose()}
className={`absolute z-50 ${className || ""}`}
>
{children}
</ClickAwayHandler>
);
};
export default Popover;
+7 -48
View File
@@ -1,19 +1,15 @@
import React, { useEffect, useState } from "react";
import useLinkStore from "@/store/links";
import { import {
ArchivedFormat, ArchivedFormat,
LinkIncludingShortenedCollectionAndTags, LinkIncludingShortenedCollectionAndTags,
} from "@/types/global"; } from "@/types/global";
import toast from "react-hot-toast";
import Link from "next/link"; import Link from "next/link";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import { useSession } from "next-auth/react";
type Props = { type Props = {
name: string; name: string;
icon: string; icon: string;
format: ArchivedFormat; format: ArchivedFormat;
activeLink: LinkIncludingShortenedCollectionAndTags; link: LinkIncludingShortenedCollectionAndTags;
downloadable?: boolean; downloadable?: boolean;
}; };
@@ -21,48 +17,13 @@ export default function PreservedFormatRow({
name, name,
icon, icon,
format, format,
activeLink, link,
downloadable, downloadable,
}: Props) { }: Props) {
const session = useSession();
const { getLink } = useLinkStore();
const [link, setLink] =
useState<LinkIncludingShortenedCollectionAndTags>(activeLink);
const router = useRouter(); const router = useRouter();
let isPublic = router.pathname.startsWith("/public") ? true : undefined; let isPublic = router.pathname.startsWith("/public") ? true : undefined;
useEffect(() => {
(async () => {
const data = await getLink(link.id as number, isPublic);
setLink(
(data as any).response as LinkIncludingShortenedCollectionAndTags
);
})();
let interval: any;
if (link?.image === "pending" || link?.pdf === "pending") {
interval = setInterval(async () => {
const data = await getLink(link.id as number, isPublic);
setLink(
(data as any).response as LinkIncludingShortenedCollectionAndTags
);
}, 5000);
} else {
if (interval) {
clearInterval(interval);
}
}
return () => {
if (interval) {
clearInterval(interval);
}
};
}, [link?.image, link?.pdf, link?.readable, link?.monolith]);
const handleDownload = () => { const handleDownload = () => {
const path = `/api/v1/archives/${link?.id}?format=${format}`; const path = `/api/v1/archives/${link?.id}?format=${format}`;
fetch(path) fetch(path)
@@ -88,11 +49,9 @@ export default function PreservedFormatRow({
}; };
return ( return (
<div className="flex justify-between items-center pr-1 border border-neutral-content rounded-md"> <div className="flex justify-between items-center">
<div className="flex gap-2 items-center"> <div className="flex gap-2 items-center">
<div className="bg-primary text-primary-content p-2 rounded-l-md"> <i className={`${icon} text-2xl text-primary`} />
<i className={`${icon} text-2xl`} />
</div>
<p>{name}</p> <p>{name}</p>
</div> </div>
@@ -100,7 +59,7 @@ export default function PreservedFormatRow({
{downloadable || false ? ( {downloadable || false ? (
<div <div
onClick={() => handleDownload()} onClick={() => handleDownload()}
className="btn btn-sm btn-square" className="btn btn-sm btn-square btn-ghost"
> >
<i className="bi-cloud-arrow-down text-xl text-neutral" /> <i className="bi-cloud-arrow-down text-xl text-neutral" />
</div> </div>
@@ -111,9 +70,9 @@ export default function PreservedFormatRow({
isPublic ? "/public" : "" isPublic ? "/public" : ""
}/preserved/${link?.id}?format=${format}`} }/preserved/${link?.id}?format=${format}`}
target="_blank" target="_blank"
className="btn btn-sm btn-square" className="btn btn-sm btn-square btn-ghost"
> >
<i className="bi-box-arrow-up-right text-xl text-neutral" /> <i className="bi-box-arrow-up-right text-lg text-neutral" />
</Link> </Link>
</div> </div>
</div> </div>
+11 -9
View File
@@ -1,17 +1,17 @@
import useLocalSettingsStore from "@/store/localSettings"; import useLocalSettingsStore from "@/store/localSettings";
import { dropdownTriggerer } from "@/lib/client/utils"; import { dropdownTriggerer } from "@/lib/client/utils";
import ProfilePhoto from "./ProfilePhoto"; import ProfilePhoto from "./ProfilePhoto";
import useAccountStore from "@/store/account";
import Link from "next/link"; import Link from "next/link";
import { signOut } from "next-auth/react"; import { signOut } from "next-auth/react";
import { useTranslation } from "next-i18next"; import { useTranslation } from "next-i18next";
import { useUser } from "@/hooks/store/user";
export default function ProfileDropdown() { export default function ProfileDropdown() {
const { t } = useTranslation(); const { t } = useTranslation();
const { settings, updateSettings } = useLocalSettingsStore(); const { settings, updateSettings } = useLocalSettingsStore();
const { account } = useAccountStore(); const { data: user = {} } = useUser();
const isAdmin = account.id === Number(process.env.NEXT_PUBLIC_ADMIN || 1); const isAdmin = user.id === Number(process.env.NEXT_PUBLIC_ADMIN || 1);
const handleToggle = () => { const handleToggle = () => {
const newTheme = settings.theme === "dark" ? "light" : "dark"; const newTheme = settings.theme === "dark" ? "light" : "dark";
@@ -27,14 +27,12 @@ export default function ProfileDropdown() {
className="btn btn-circle btn-ghost" className="btn btn-circle btn-ghost"
> >
<ProfilePhoto <ProfilePhoto
src={account.image ? account.image : undefined} src={user.image ? user.image : undefined}
priority={true} priority={true}
/> />
</div> </div>
<ul <ul
className={`dropdown-content z-[1] menu shadow bg-base-200 border border-neutral-content rounded-box ${ className={`dropdown-content z-[1] menu shadow bg-base-200 border border-neutral-content rounded-box mt-1`}
isAdmin ? "w-48" : "w-40"
} mt-1`}
> >
<li> <li>
<Link <Link
@@ -42,6 +40,7 @@ export default function ProfileDropdown() {
onClick={() => (document?.activeElement as HTMLElement)?.blur()} onClick={() => (document?.activeElement as HTMLElement)?.blur()}
tabIndex={0} tabIndex={0}
role="button" role="button"
className="whitespace-nowrap"
> >
{t("settings")} {t("settings")}
</Link> </Link>
@@ -54,24 +53,26 @@ export default function ProfileDropdown() {
}} }}
tabIndex={0} tabIndex={0}
role="button" role="button"
className="whitespace-nowrap"
> >
{t("switch_to", { {t("switch_to", {
theme: settings.theme === "light" ? t("dark") : t("light"), theme: settings.theme === "light" ? t("dark") : t("light"),
})} })}
</div> </div>
</li> </li>
{isAdmin ? ( {isAdmin && (
<li> <li>
<Link <Link
href="/admin" href="/admin"
onClick={() => (document?.activeElement as HTMLElement)?.blur()} onClick={() => (document?.activeElement as HTMLElement)?.blur()}
tabIndex={0} tabIndex={0}
role="button" role="button"
className="whitespace-nowrap"
> >
{t("server_administration")} {t("server_administration")}
</Link> </Link>
</li> </li>
) : null} )}
<li> <li>
<div <div
onClick={() => { onClick={() => {
@@ -80,6 +81,7 @@ export default function ProfileDropdown() {
}} }}
tabIndex={0} tabIndex={0}
role="button" role="button"
className="whitespace-nowrap"
> >
{t("logout")} {t("logout")}
</div> </div>
+1 -1
View File
@@ -5,7 +5,7 @@ type Props = {
src?: string; src?: string;
className?: string; className?: string;
priority?: boolean; priority?: boolean;
name?: string; name?: string | null;
large?: boolean; large?: boolean;
}; };
+33 -32
View File
@@ -1,10 +1,8 @@
import unescapeString from "@/lib/client/unescapeString"; import unescapeString from "@/lib/client/unescapeString";
import { readabilityAvailable } from "@/lib/shared/getArchiveValidity"; import { readabilityAvailable } from "@/lib/shared/getArchiveValidity";
import isValidUrl from "@/lib/shared/isValidUrl"; import isValidUrl from "@/lib/shared/isValidUrl";
import useLinkStore from "@/store/links";
import { import {
ArchivedFormat, ArchivedFormat,
CollectionIncludingMembersAndLinkCount,
LinkIncludingShortenedCollectionAndTags, LinkIncludingShortenedCollectionAndTags,
} from "@/types/global"; } from "@/types/global";
import ColorThief, { RGBColor } from "colorthief"; import ColorThief, { RGBColor } from "colorthief";
@@ -12,10 +10,11 @@ import DOMPurify from "dompurify";
import Image from "next/image"; import Image from "next/image";
import Link from "next/link"; import Link from "next/link";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import React, { useEffect, useMemo, useState } from "react"; import React, { useEffect, useState } from "react";
import LinkActions from "./LinkViews/LinkComponents/LinkActions";
import useCollectionStore from "@/store/collections";
import { useTranslation } from "next-i18next"; import { useTranslation } from "next-i18next";
import { useGetLink } from "@/hooks/store/links";
import { IconWeight } from "@phosphor-icons/react";
import Icon from "./Icon";
type LinkContent = { type LinkContent = {
title: string; title: string;
@@ -45,14 +44,7 @@ export default function ReadableView({ link }: Props) {
const router = useRouter(); const router = useRouter();
const { getLink } = useLinkStore(); const getLink = useGetLink();
const { collections } = useCollectionStore();
const collection = useMemo(() => {
return collections.find(
(e) => e.id === link.collection.id
) as CollectionIncludingMembersAndLinkCount;
}, [collections, link]);
useEffect(() => { useEffect(() => {
const fetchLinkContent = async () => { const fetchLinkContent = async () => {
@@ -73,9 +65,9 @@ export default function ReadableView({ link }: Props) {
}, [link]); }, [link]);
useEffect(() => { useEffect(() => {
if (link) getLink(link?.id as number); if (link) getLink.mutateAsync({ id: link.id as number });
let interval: any; let interval: NodeJS.Timeout | null = null;
if ( if (
link && link &&
(link?.image === "pending" || (link?.image === "pending" ||
@@ -87,7 +79,13 @@ export default function ReadableView({ link }: Props) {
!link?.readable || !link?.readable ||
!link?.monolith) !link?.monolith)
) { ) {
interval = setInterval(() => getLink(link.id as number), 5000); interval = setInterval(
() =>
getLink.mutateAsync({
id: link.id as number,
}),
5000
);
} else { } else {
if (interval) { if (interval) {
clearInterval(interval); clearInterval(interval);
@@ -183,7 +181,7 @@ export default function ReadableView({ link }: Props) {
link?.name || link?.description || link?.url || "" link?.name || link?.description || link?.url || ""
)} )}
</p> </p>
{link?.url ? ( {link?.url && (
<Link <Link
href={link?.url || ""} href={link?.url || ""}
title={link?.url} title={link?.url}
@@ -192,11 +190,10 @@ export default function ReadableView({ link }: Props) {
> >
<i className="bi-link-45deg"></i> <i className="bi-link-45deg"></i>
{isValidUrl(link?.url || "") {isValidUrl(link?.url || "") &&
? new URL(link?.url as string).host new URL(link?.url as string).host}
: undefined}
</Link> </Link>
) : undefined} )}
</div> </div>
</div> </div>
@@ -205,10 +202,21 @@ export default function ReadableView({ link }: Props) {
href={`/collections/${link?.collection.id}`} href={`/collections/${link?.collection.id}`}
className="flex items-center gap-1 cursor-pointer hover:opacity-60 duration-100 mr-2 z-10" className="flex items-center gap-1 cursor-pointer hover:opacity-60 duration-100 mr-2 z-10"
> >
<i {link.collection.icon ? (
className="bi-folder-fill drop-shadow text-2xl" <Icon
style={{ color: link?.collection.color }} icon={link.collection.icon}
></i> size={30}
weight={
(link.collection.iconWeight || "regular") as IconWeight
}
color={link.collection.color}
/>
) : (
<i
className="bi-folder-fill text-2xl"
style={{ color: link.collection.color }}
></i>
)}
<p <p
title={link?.collection.name} title={link?.collection.name}
className="text-lg truncate max-w-[12rem]" className="text-lg truncate max-w-[12rem]"
@@ -240,13 +248,6 @@ export default function ReadableView({ link }: Props) {
{link?.name ? <p>{unescapeString(link?.description)}</p> : undefined} {link?.name ? <p>{unescapeString(link?.description)}</p> : undefined}
</div> </div>
<LinkActions
link={link}
collection={collection}
position="top-3 right-3"
alignToTop
/>
</div> </div>
<div className="flex flex-col gap-5 h-full"> <div className="flex flex-col gap-5 h-full">
+4 -1
View File
@@ -2,11 +2,14 @@ import Link from "next/link";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import React, { useEffect, useState } from "react"; import React, { useEffect, useState } from "react";
import { useTranslation } from "next-i18next"; import { useTranslation } from "next-i18next";
import { useUser } from "@/hooks/store/user";
export default function SettingsSidebar({ className }: { className?: string }) { export default function SettingsSidebar({ className }: { className?: string }) {
const { t } = useTranslation(); const { t } = useTranslation();
const LINKWARDEN_VERSION = process.env.version; const LINKWARDEN_VERSION = process.env.version;
const { data: user } = useUser();
const router = useRouter(); const router = useRouter();
const [active, setActive] = useState(""); const [active, setActive] = useState("");
@@ -73,7 +76,7 @@ export default function SettingsSidebar({ className }: { className?: string }) {
</div> </div>
</Link> </Link>
{process.env.NEXT_PUBLIC_STRIPE && ( {process.env.NEXT_PUBLIC_STRIPE && !user.parentSubscriptionId && (
<Link href="/settings/billing"> <Link href="/settings/billing">
<div <div
className={`${ className={`${
+14 -7
View File
@@ -1,5 +1,3 @@
import useCollectionStore from "@/store/collections";
import useTagStore from "@/store/tags";
import Link from "next/link"; import Link from "next/link";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
@@ -7,6 +5,8 @@ import { Disclosure, Transition } from "@headlessui/react";
import SidebarHighlightLink from "@/components/SidebarHighlightLink"; import SidebarHighlightLink from "@/components/SidebarHighlightLink";
import CollectionListing from "@/components/CollectionListing"; import CollectionListing from "@/components/CollectionListing";
import { useTranslation } from "next-i18next"; import { useTranslation } from "next-i18next";
import { useCollections } from "@/hooks/store/collections";
import { useTags } from "@/hooks/store/tags";
export default function Sidebar({ className }: { className?: string }) { export default function Sidebar({ className }: { className?: string }) {
const { t } = useTranslation(); const { t } = useTranslation();
@@ -22,8 +22,9 @@ export default function Sidebar({ className }: { className?: string }) {
} }
); );
const { collections } = useCollectionStore(); const { data: collections } = useCollections();
const { tags } = useTagStore();
const { data: tags = [], isLoading } = useTags();
const [active, setActive] = useState(""); const [active, setActive] = useState("");
const router = useRouter(); const router = useRouter();
@@ -127,10 +128,16 @@ export default function Sidebar({ className }: { className?: string }) {
leaveTo="transform opacity-0 -translate-y-3" leaveTo="transform opacity-0 -translate-y-3"
> >
<Disclosure.Panel className="flex flex-col gap-1"> <Disclosure.Panel className="flex flex-col gap-1">
{tags[0] ? ( {isLoading ? (
<div className="flex flex-col gap-4">
<div className="skeleton h-4 w-full"></div>
<div className="skeleton h-4 w-full"></div>
<div className="skeleton h-4 w-full"></div>
</div>
) : tags[0] ? (
tags tags
.sort((a, b) => a.name.localeCompare(b.name)) .sort((a: any, b: any) => a.name.localeCompare(b.name))
.map((e, i) => { .map((e: any, i: any) => {
return ( return (
<Link key={i} href={`/tags/${e.id}`}> <Link key={i} href={`/tags/${e.id}`}>
<div <div
+2 -1
View File
@@ -14,6 +14,7 @@ export default function SidebarHighlightLink({
return ( return (
<Link href={href}> <Link href={href}>
<div <div
title={title}
className={`${ className={`${
active || false active || false
? "bg-primary/20" ? "bg-primary/20"
@@ -28,7 +29,7 @@ export default function SidebarHighlightLink({
<i className={`${icon} text-primary text-2xl drop-shadow`}></i> <i className={`${icon} text-primary text-2xl drop-shadow`}></i>
</div> </div>
<div className={"mt-1"}> <div className={"mt-1"}>
<p className="truncate w-full font-semibold text-sm">{title}</p> <p className="truncate w-full font-semibold text-xs">{title}</p>
</div> </div>
</div> </div>
</Link> </Link>
+50 -14
View File
@@ -1,7 +1,10 @@
import React, { Dispatch, SetStateAction } from "react"; import React, { Dispatch, SetStateAction, useEffect } from "react";
import { Sort } from "@/types/global"; import { Sort } from "@/types/global";
import { dropdownTriggerer } from "@/lib/client/utils"; import { dropdownTriggerer } from "@/lib/client/utils";
import { TFunction } from "i18next"; import { TFunction } from "i18next";
import useLocalSettingsStore from "@/store/localSettings";
import { resetInfiniteQueryPagination } from "@/hooks/store/links";
import { useQueryClient } from "@tanstack/react-query";
type Props = { type Props = {
sortBy: Sort; sortBy: Sort;
@@ -10,6 +13,13 @@ type Props = {
}; };
export default function SortDropdown({ sortBy, setSort, t }: Props) { export default function SortDropdown({ sortBy, setSort, t }: Props) {
const { updateSettings } = useLocalSettingsStore();
const queryClient = useQueryClient();
useEffect(() => {
updateSettings({ sortBy });
}, [sortBy]);
return ( return (
<div className="dropdown dropdown-bottom dropdown-end"> <div className="dropdown dropdown-bottom dropdown-end">
<div <div
@@ -20,7 +30,7 @@ export default function SortDropdown({ sortBy, setSort, t }: Props) {
> >
<i className="bi-chevron-expand text-neutral text-2xl"></i> <i className="bi-chevron-expand text-neutral text-2xl"></i>
</div> </div>
<ul className="dropdown-content z-[30] menu shadow bg-base-200 border border-neutral-content rounded-xl w-52 mt-1"> <ul className="dropdown-content z-[30] menu shadow bg-base-200 border border-neutral-content rounded-xl mt-1">
<li> <li>
<label <label
className="label cursor-pointer flex justify-start" className="label cursor-pointer flex justify-start"
@@ -32,9 +42,14 @@ export default function SortDropdown({ sortBy, setSort, t }: Props) {
name="sort-radio" name="sort-radio"
className="radio checked:bg-primary" className="radio checked:bg-primary"
checked={sortBy === Sort.DateNewestFirst} checked={sortBy === Sort.DateNewestFirst}
onChange={() => setSort(Sort.DateNewestFirst)} onChange={() => {
resetInfiniteQueryPagination(queryClient, ["links"]);
setSort(Sort.DateNewestFirst);
}}
/> />
<span className="label-text">{t("date_newest_first")}</span> <span className="label-text whitespace-nowrap">
{t("date_newest_first")}
</span>
</label> </label>
</li> </li>
<li> <li>
@@ -48,9 +63,14 @@ export default function SortDropdown({ sortBy, setSort, t }: Props) {
name="sort-radio" name="sort-radio"
className="radio checked:bg-primary" className="radio checked:bg-primary"
checked={sortBy === Sort.DateOldestFirst} checked={sortBy === Sort.DateOldestFirst}
onChange={() => setSort(Sort.DateOldestFirst)} onChange={() => {
resetInfiniteQueryPagination(queryClient, ["links"]);
setSort(Sort.DateOldestFirst);
}}
/> />
<span className="label-text">{t("date_oldest_first")}</span> <span className="label-text whitespace-nowrap">
{t("date_oldest_first")}
</span>
</label> </label>
</li> </li>
<li> <li>
@@ -64,9 +84,12 @@ export default function SortDropdown({ sortBy, setSort, t }: Props) {
name="sort-radio" name="sort-radio"
className="radio checked:bg-primary" className="radio checked:bg-primary"
checked={sortBy === Sort.NameAZ} checked={sortBy === Sort.NameAZ}
onChange={() => setSort(Sort.NameAZ)} onChange={() => {
resetInfiniteQueryPagination(queryClient, ["links"]);
setSort(Sort.NameAZ);
}}
/> />
<span className="label-text">{t("name_az")}</span> <span className="label-text whitespace-nowrap">{t("name_az")}</span>
</label> </label>
</li> </li>
<li> <li>
@@ -80,9 +103,12 @@ export default function SortDropdown({ sortBy, setSort, t }: Props) {
name="sort-radio" name="sort-radio"
className="radio checked:bg-primary" className="radio checked:bg-primary"
checked={sortBy === Sort.NameZA} checked={sortBy === Sort.NameZA}
onChange={() => setSort(Sort.NameZA)} onChange={() => {
resetInfiniteQueryPagination(queryClient, ["links"]);
setSort(Sort.NameZA);
}}
/> />
<span className="label-text">{t("name_za")}</span> <span className="label-text whitespace-nowrap">{t("name_za")}</span>
</label> </label>
</li> </li>
<li> <li>
@@ -96,9 +122,14 @@ export default function SortDropdown({ sortBy, setSort, t }: Props) {
name="sort-radio" name="sort-radio"
className="radio checked:bg-primary" className="radio checked:bg-primary"
checked={sortBy === Sort.DescriptionAZ} checked={sortBy === Sort.DescriptionAZ}
onChange={() => setSort(Sort.DescriptionAZ)} onChange={() => {
resetInfiniteQueryPagination(queryClient, ["links"]);
setSort(Sort.DescriptionAZ);
}}
/> />
<span className="label-text">{t("description_az")}</span> <span className="label-text whitespace-nowrap">
{t("description_az")}
</span>
</label> </label>
</li> </li>
<li> <li>
@@ -112,9 +143,14 @@ export default function SortDropdown({ sortBy, setSort, t }: Props) {
name="sort-radio" name="sort-radio"
className="radio checked:bg-primary" className="radio checked:bg-primary"
checked={sortBy === Sort.DescriptionZA} checked={sortBy === Sort.DescriptionZA}
onChange={() => setSort(Sort.DescriptionZA)} onChange={() => {
resetInfiniteQueryPagination(queryClient, ["links"]);
setSort(Sort.DescriptionZA);
}}
/> />
<span className="label-text">{t("description_za")}</span> <span className="label-text whitespace-nowrap">
{t("description_za")}
</span>
</label> </label>
</li> </li>
</ul> </ul>
+13 -7
View File
@@ -1,28 +1,34 @@
import useLocalSettingsStore from "@/store/localSettings"; import useLocalSettingsStore from "@/store/localSettings";
import { useEffect, useState } from "react"; import { useEffect, useState, ChangeEvent } from "react";
import { useTranslation } from "next-i18next"; import { useTranslation } from "next-i18next";
import clsx from "clsx";
type Props = { type Props = {
className?: string; className?: string;
align?: "left" | "right";
}; };
export default function ToggleDarkMode({ className }: Props) { export default function ToggleDarkMode({ className, align }: Props) {
const { t } = useTranslation(); const { t } = useTranslation();
const { settings, updateSettings } = useLocalSettingsStore(); const { settings, updateSettings } = useLocalSettingsStore();
const [theme, setTheme] = useState(localStorage.getItem("theme")); const [theme, setTheme] = useState<string | null>(
localStorage.getItem("theme")
);
const handleToggle = (e: any) => { const handleToggle = (e: ChangeEvent<HTMLInputElement>) => {
setTheme(e.target.checked ? "dark" : "light"); setTheme(e.target.checked ? "dark" : "light");
}; };
useEffect(() => { useEffect(() => {
updateSettings({ theme: theme as string }); if (theme) {
updateSettings({ theme });
}
}, [theme]); }, [theme]);
return ( return (
<div <div
className="tooltip tooltip-bottom" className={clsx("tooltip", align ? `tooltip-${align}` : "tooltip-bottom")}
data-tip={t("switch_to", { data-tip={t("switch_to", {
theme: settings.theme === "light" ? "Dark" : "Light", theme: settings.theme === "light" ? "Dark" : "Light",
})} })}
@@ -34,7 +40,7 @@ export default function ToggleDarkMode({ className }: Props) {
type="checkbox" type="checkbox"
onChange={handleToggle} onChange={handleToggle}
className="theme-controller" className="theme-controller"
checked={localStorage.getItem("theme") === "light" ? false : true} checked={theme === "dark"}
/> />
<i className="bi-sun-fill text-xl swap-on"></i> <i className="bi-sun-fill text-xl swap-on"></i>
<i className="bi-moon-fill text-xl swap-off"></i> <i className="bi-moon-fill text-xl swap-off"></i>
+2 -2
View File
@@ -74,12 +74,12 @@ const UserListing = (
</tbody> </tbody>
</table> </table>
{deleteUserModal.isOpen && deleteUserModal.userId ? ( {deleteUserModal.isOpen && deleteUserModal.userId && (
<DeleteUserModal <DeleteUserModal
onClose={() => setDeleteUserModal({ isOpen: false, userId: null })} onClose={() => setDeleteUserModal({ isOpen: false, userId: null })}
userId={deleteUserModal.userId} userId={deleteUserModal.userId}
/> />
) : null} )}
</div> </div>
); );
}; };
+130 -55
View File
@@ -1,72 +1,147 @@
import React, { Dispatch, SetStateAction, useEffect } from "react"; import React, { Dispatch, SetStateAction, useEffect } from "react";
import useLocalSettingsStore from "@/store/localSettings"; import useLocalSettingsStore from "@/store/localSettings";
import { ViewMode } from "@/types/global"; import { ViewMode } from "@/types/global";
import { dropdownTriggerer } from "@/lib/client/utils";
import { useTranslation } from "next-i18next";
type Props = { type Props = {
viewMode: string; viewMode: ViewMode;
setViewMode: Dispatch<SetStateAction<string>>; setViewMode: Dispatch<SetStateAction<ViewMode>>;
}; };
export default function ViewDropdown({ viewMode, setViewMode }: Props) { export default function ViewDropdown({ viewMode, setViewMode }: Props) {
const { updateSettings } = useLocalSettingsStore(); const { settings, updateSettings } = useLocalSettingsStore((state) => state);
const { t } = useTranslation();
const onChangeViewMode = (
e: React.MouseEvent<HTMLButtonElement>,
viewMode: ViewMode
) => {
setViewMode(viewMode);
};
useEffect(() => { useEffect(() => {
updateSettings({ viewMode: viewMode as ViewMode }); updateSettings({ viewMode });
}, [viewMode]); }, [viewMode, updateSettings]);
const onChangeViewMode = (mode: ViewMode) => {
setViewMode(mode);
updateSettings({ viewMode });
};
const toggleShowSetting = (setting: keyof typeof settings.show) => {
const newShowSettings = {
...settings.show,
[setting]: !settings.show[setting],
};
updateSettings({ show: newShowSettings });
};
const onColumnsChange = (e: React.ChangeEvent<HTMLInputElement>) => {
updateSettings({ columns: Number(e.target.value) });
};
return ( return (
<div className="p-1 flex flex-row gap-1 border border-neutral-content rounded-[0.625rem]"> <div className="dropdown dropdown-bottom dropdown-end">
<button <div
onClick={(e) => onChangeViewMode(e, ViewMode.Card)} tabIndex={0}
className={`btn btn-square btn-sm btn-ghost ${ role="button"
viewMode == ViewMode.Card onMouseDown={dropdownTriggerer}
? "bg-primary/20 hover:bg-primary/20" className="btn btn-sm btn-square btn-ghost border-none"
: "hover:bg-neutral/20"
}`}
> >
<i className="bi-grid w-4 h-4 text-neutral"></i> {viewMode === ViewMode.Card ? (
</button> <i className="bi-grid w-4 h-4 text-neutral"></i>
) : viewMode === ViewMode.Masonry ? (
<button <i className="bi-columns-gap w-4 h-4 text-neutral"></i>
onClick={(e) => onChangeViewMode(e, ViewMode.Masonry)} ) : (
className={`btn btn-square btn-sm btn-ghost ${ <i className="bi-view-stacked w-4 h-4 text-neutral"></i>
viewMode == ViewMode.Masonry )}
? "bg-primary/20 hover:bg-primary/20" </div>
: "hover:bg-neutral/20" <ul
}`} tabIndex={0}
className="dropdown-content z-[30] menu shadow bg-base-200 min-w-52 border border-neutral-content rounded-xl mt-1"
> >
<i className="bi bi-columns-gap w-4 h-4 text-neutral"></i> <p className="mb-1 text-sm text-neutral">{t("view")}</p>
</button> <div className="p-1 flex w-full justify-between gap-1 border border-neutral-content rounded-[0.625rem]">
<button
<button onClick={(e) => onChangeViewMode(ViewMode.Card)}
onClick={(e) => onChangeViewMode(e, ViewMode.List)} className={`btn w-[31%] btn-sm btn-ghost ${
className={`btn btn-square btn-sm btn-ghost ${ viewMode === ViewMode.Card
viewMode == ViewMode.List ? "bg-primary/20 hover:bg-primary/20"
? "bg-primary/20 hover:bg-primary/20" : "hover:bg-neutral/20"
: "hover:bg-neutral/20" }`}
}`} >
> <i className="bi-grid text-lg text-neutral"></i>
<i className="bi bi-view-stacked w-4 h-4 text-neutral"></i> </button>
</button> <button
onClick={(e) => onChangeViewMode(ViewMode.Masonry)}
{/* <button className={`btn w-[31%] btn-sm btn-ghost ${
onClick={(e) => onChangeViewMode(e, ViewMode.Grid)} viewMode === ViewMode.Masonry
className={`btn btn-square btn-sm btn-ghost ${ ? "bg-primary/20 hover:bg-primary/20"
viewMode == ViewMode.Grid : "hover:bg-neutral/20"
? "bg-primary/20 hover:bg-primary/20" }`}
: "hover:bg-neutral/20" >
}`} <i className="bi-columns-gap text-lg text-neutral"></i>
> </button>
<i className="bi-columns-gap w-4 h-4 text-neutral"></i> <button
</button> */} onClick={(e) => onChangeViewMode(ViewMode.List)}
className={`btn w-[31%] btn-sm btn-ghost ${
viewMode === ViewMode.List
? "bg-primary/20 hover:bg-primary/20"
: "hover:bg-neutral/20"
}`}
>
<i className="bi-view-stacked text-lg text-neutral"></i>
</button>
</div>
<p className="mb-1 mt-2 text-sm text-neutral">{t("show")}</p>
{Object.entries(settings.show)
.filter((e) =>
settings.viewMode === ViewMode.List // Hide tags, image, and description checkboxes in list view
? e[0] !== "tags" && e[0] !== "image" && e[0] !== "description"
: settings.viewMode === ViewMode.Card // Hide tags and description checkboxes in card view
? e[0] !== "tags" && e[0] !== "description"
: true
)
.map(([key, value]) => (
<li key={key}>
<label className="label cursor-pointer flex justify-start">
<input
type="checkbox"
className="checkbox checkbox-primary"
checked={value}
onChange={() =>
toggleShowSetting(key as keyof typeof settings.show)
}
/>
<span className="label-text whitespace-nowrap">{t(key)}</span>
</label>
</li>
))}
{settings.viewMode !== ViewMode.List && (
<>
<p className="mb-1 mt-2 text-sm text-neutral">
{t("columns")}:{" "}
{settings.columns === 0 ? t("default") : settings.columns}
</p>
<div>
<input
type="range"
min={0}
max="8"
value={settings.columns}
onChange={(e) => onColumnsChange(e)}
className="range range-xs range-primary"
step="1"
/>
<div className="flex w-full justify-between px-2 text-xs text-neutral select-none">
<span>|</span>
<span>|</span>
<span>|</span>
<span>|</span>
<span>|</span>
<span>|</span>
<span>|</span>
<span>|</span>
<span>|</span>
</div>
</div>
</>
)}
</ul>
</div> </div>
); );
} }
+17
View File
@@ -0,0 +1,17 @@
import clsx from "clsx";
import React from "react";
type Props = {
className?: string;
vertical?: boolean;
};
function Divider({ className, vertical = false }: Props) {
return vertical ? (
<hr className={clsx("border-neutral-content border-l h-full", className)} />
) : (
<hr className={clsx("border-neutral-content border-t", className)} />
);
}
export default Divider;
+272
View File
@@ -0,0 +1,272 @@
import React from "react";
type Props = {
className?: string;
color: string;
size: string;
};
const Loader = (props: Props) => {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 100 100"
preserveAspectRatio="xMidYMid"
width={props.size}
height={props.size}
className={props.className}
style={{
shapeRendering: "auto",
display: "block",
background: "rgba(255, 255, 255, 0)",
}}
xmlnsXlink="http://www.w3.org/1999/xlink"
>
<g>
<g transform="rotate(0 50 50)">
<rect
fill={props.color}
height="12"
width="6"
ry="1.8"
rx="1.8"
y="24"
x="47"
>
<animate
repeatCount="indefinite"
begin="-0.9166666666666666s"
dur="1s"
keyTimes="0;1"
values="1;0"
attributeName="opacity"
></animate>
</rect>
</g>
<g transform="rotate(30 50 50)">
<rect
fill={props.color}
height="12"
width="6"
ry="1.8"
rx="1.8"
y="24"
x="47"
>
<animate
repeatCount="indefinite"
begin="-0.8333333333333334s"
dur="1s"
keyTimes="0;1"
values="1;0"
attributeName="opacity"
></animate>
</rect>
</g>
<g transform="rotate(60 50 50)">
<rect
fill={props.color}
height="12"
width="6"
ry="1.8"
rx="1.8"
y="24"
x="47"
>
<animate
repeatCount="indefinite"
begin="-0.75s"
dur="1s"
keyTimes="0;1"
values="1;0"
attributeName="opacity"
></animate>
</rect>
</g>
<g transform="rotate(90 50 50)">
<rect
fill={props.color}
height="12"
width="6"
ry="1.8"
rx="1.8"
y="24"
x="47"
>
<animate
repeatCount="indefinite"
begin="-0.6666666666666666s"
dur="1s"
keyTimes="0;1"
values="1;0"
attributeName="opacity"
></animate>
</rect>
</g>
<g transform="rotate(120 50 50)">
<rect
fill={props.color}
height="12"
width="6"
ry="1.8"
rx="1.8"
y="24"
x="47"
>
<animate
repeatCount="indefinite"
begin="-0.5833333333333334s"
dur="1s"
keyTimes="0;1"
values="1;0"
attributeName="opacity"
></animate>
</rect>
</g>
<g transform="rotate(150 50 50)">
<rect
fill={props.color}
height="12"
width="6"
ry="1.8"
rx="1.8"
y="24"
x="47"
>
<animate
repeatCount="indefinite"
begin="-0.5s"
dur="1s"
keyTimes="0;1"
values="1;0"
attributeName="opacity"
></animate>
</rect>
</g>
<g transform="rotate(180 50 50)">
<rect
fill={props.color}
height="12"
width="6"
ry="1.8"
rx="1.8"
y="24"
x="47"
>
<animate
repeatCount="indefinite"
begin="-0.4166666666666667s"
dur="1s"
keyTimes="0;1"
values="1;0"
attributeName="opacity"
></animate>
</rect>
</g>
<g transform="rotate(210 50 50)">
<rect
fill={props.color}
height="12"
width="6"
ry="1.8"
rx="1.8"
y="24"
x="47"
>
<animate
repeatCount="indefinite"
begin="-0.3333333333333333s"
dur="1s"
keyTimes="0;1"
values="1;0"
attributeName="opacity"
></animate>
</rect>
</g>
<g transform="rotate(240 50 50)">
<rect
fill={props.color}
height="12"
width="6"
ry="1.8"
rx="1.8"
y="24"
x="47"
>
<animate
repeatCount="indefinite"
begin="-0.25s"
dur="1s"
keyTimes="0;1"
values="1;0"
attributeName="opacity"
></animate>
</rect>
</g>
<g transform="rotate(270 50 50)">
<rect
fill={props.color}
height="12"
width="6"
ry="1.8"
rx="1.8"
y="24"
x="47"
>
<animate
repeatCount="indefinite"
begin="-0.16666666666666666s"
dur="1s"
keyTimes="0;1"
values="1;0"
attributeName="opacity"
></animate>
</rect>
</g>
<g transform="rotate(300 50 50)">
<rect
fill={props.color}
height="12"
width="6"
ry="1.8"
rx="1.8"
y="24"
x="47"
>
<animate
repeatCount="indefinite"
begin="-0.08333333333333333s"
dur="1s"
keyTimes="0;1"
values="1;0"
attributeName="opacity"
></animate>
</rect>
</g>
<g transform="rotate(330 50 50)">
<rect
fill={props.color}
height="12"
width="6"
ry="1.8"
rx="1.8"
y="24"
x="47"
>
<animate
repeatCount="indefinite"
begin="0s"
dur="1s"
keyTimes="0;1"
values="1;0"
attributeName="opacity"
></animate>
</rect>
</g>
<g></g>
</g>
</svg>
);
};
export default Loader;
+6 -8
View File
@@ -2,19 +2,17 @@ import axios, { AxiosError } from "axios"
axios.defaults.baseURL = "http://localhost:3000" axios.defaults.baseURL = "http://localhost:3000"
export async function seedUser (username?: string, password?: string, name?: string) { export async function seedUser(username?: string, password?: string, name?: string) {
try { try {
return await axios.post("/api/v1/users", { return await axios.post("/api/v1/users", {
username: username || "test", username: username || "test",
password: password || "password", password: password || "password",
name: name || "Test User", name: name || "Test User",
}) })
} catch (e: any) { } catch (error) {
if (e instanceof AxiosError) { const axiosError = error as AxiosError;
if (e.response?.status === 400) { if (axiosError && axiosError.response?.status === 400) return
return
} throw error
}
throw e
} }
} }
+88
View File
@@ -0,0 +1,88 @@
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import toast from "react-hot-toast";
import { useTranslation } from "next-i18next";
import { useSession } from "next-auth/react";
const useUsers = () => {
const { status } = useSession();
return useQuery({
queryKey: ["users"],
queryFn: async () => {
const response = await fetch("/api/v1/users");
if (!response.ok) {
throw new Error("Failed to fetch users.");
}
const data = await response.json();
return data.response;
},
enabled: status === "authenticated",
});
};
const useAddUser = () => {
const queryClient = useQueryClient();
const { t } = useTranslation();
return useMutation({
mutationFn: async (body: any) => {
const load = toast.loading(t("creating_account"));
const response = await fetch("/api/v1/users", {
method: "POST",
body: JSON.stringify(body),
headers: {
"Content-Type": "application/json",
},
});
const data = await response.json();
if (!response.ok) throw new Error(data.response);
toast.dismiss(load);
return data.response;
},
onSuccess: (data) => {
queryClient.setQueryData(["users"], (oldData: any) => [...oldData, data]);
toast.success(t("user_created"));
},
onError: (error) => {
toast.error(error.message);
},
});
};
const useDeleteUser = () => {
const queryClient = useQueryClient();
const { t } = useTranslation();
return useMutation({
mutationFn: async (userId: number) => {
const load = toast.loading(t("deleting_user"));
const response = await fetch(`/api/v1/users/${userId}`, {
method: "DELETE",
});
const data = await response.json();
if (!response.ok) throw new Error(data.response);
toast.dismiss(load);
return data.response;
},
onSuccess: (data, variables) => {
queryClient.setQueryData(["users"], (oldData: any) =>
oldData.filter((user: any) => user.id !== variables)
);
toast.success(t("user_deleted"));
},
onError: (error) => {
toast.error(error.message);
},
});
};
export { useUsers, useAddUser, useDeleteUser };
+116
View File
@@ -0,0 +1,116 @@
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { CollectionIncludingMembersAndLinkCount } from "@/types/global";
import { useSession } from "next-auth/react";
const useCollections = () => {
const { status } = useSession();
return useQuery({
queryKey: ["collections"],
queryFn: async (): Promise<CollectionIncludingMembersAndLinkCount[]> => {
const response = await fetch("/api/v1/collections");
const data = await response.json();
return data.response;
},
enabled: status === "authenticated",
});
};
const useCreateCollection = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (body: any) => {
const response = await fetch("/api/v1/collections", {
body: JSON.stringify(body),
headers: {
"Content-Type": "application/json",
},
method: "POST",
});
const data = await response.json();
if (!response.ok) throw new Error(data.response);
return data.response;
},
onSuccess: (data) => {
return queryClient.setQueryData(["collections"], (oldData: any) => {
return [...oldData, data];
});
},
});
};
const useUpdateCollection = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (body: any) => {
const response = await fetch(`/api/v1/collections/${body.id}`, {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(body),
});
const data = await response.json();
if (!response.ok) throw new Error(data.response);
return data.response;
},
onSuccess: (data) => {
{
return queryClient.setQueryData(["collections"], (oldData: any) => {
return oldData.map((collection: any) =>
collection.id === data.id ? data : collection
);
});
}
},
// onMutate: async (data) => {
// await queryClient.cancelQueries({ queryKey: ["collections"] });
// queryClient.setQueryData(["collections"], (oldData: any) => {
// return oldData.map((collection: any) =>
// collection.id === data.id ? data : collection
// )
// });
// },
});
};
const useDeleteCollection = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (id: number) => {
const response = await fetch(`/api/v1/collections/${id}`, {
method: "DELETE",
headers: {
"Content-Type": "application/json",
},
});
const data = await response.json();
if (!response.ok) throw new Error(data.response);
return data.response;
},
onSuccess: (data) => {
return queryClient.setQueryData(["collections"], (oldData: any) => {
return oldData.filter((collection: any) => collection.id !== data.id);
});
},
});
};
export {
useCollections,
useCreateCollection,
useUpdateCollection,
useDeleteCollection,
};
+19
View File
@@ -0,0 +1,19 @@
import { useQuery } from "@tanstack/react-query";
import { useSession } from "next-auth/react";
const useDashboardData = () => {
const { status } = useSession();
return useQuery({
queryKey: ["dashboardData"],
queryFn: async () => {
const response = await fetch("/api/v2/dashboard");
const data = await response.json();
return data.data;
},
enabled: status === "authenticated",
});
};
export { useDashboardData };
+565
View File
@@ -0,0 +1,565 @@
import {
InfiniteData,
useInfiniteQuery,
UseInfiniteQueryResult,
useQueryClient,
useMutation,
} from "@tanstack/react-query";
import { useMemo } from "react";
import {
ArchivedFormat,
LinkIncludingShortenedCollectionAndTags,
LinkRequestQuery,
} from "@/types/global";
import { useRouter } from "next/router";
import { useSession } from "next-auth/react";
import { PostLinkSchemaType } from "@/lib/shared/schemaValidation";
const useLinks = (params: LinkRequestQuery = {}) => {
const router = useRouter();
const queryParamsObject = {
sort: params.sort ?? Number(window.localStorage.getItem("sortBy")) ?? 0,
collectionId:
params.collectionId ?? router.pathname === "/collections/[id]"
? router.query.id
: undefined,
tagId:
params.tagId ?? router.pathname === "/tags/[id]"
? router.query.id
: undefined,
pinnedOnly:
params.pinnedOnly ?? router.pathname === "/links/pinned"
? true
: undefined,
searchQueryString: params.searchQueryString,
searchByName: params.searchByName,
searchByUrl: params.searchByUrl,
searchByDescription: params.searchByDescription,
searchByTextContent: params.searchByTextContent,
searchByTags: params.searchByTags,
} as LinkRequestQuery;
const queryString = buildQueryString(queryParamsObject);
const { data, ...rest } = useFetchLinks(queryString);
const links = useMemo(() => {
return data?.pages.reduce((acc, page) => {
return [...acc, ...page];
}, []);
}, [data]);
return {
links,
data: { ...data, ...rest },
} as {
links: LinkIncludingShortenedCollectionAndTags[];
data: UseInfiniteQueryResult<InfiniteData<any, unknown>, Error>;
};
};
const useFetchLinks = (params: string) => {
const { status } = useSession();
return useInfiniteQuery({
queryKey: ["links", { params }],
queryFn: async (params) => {
const response = await fetch(
"/api/v1/links?cursor=" +
params.pageParam +
((params.queryKey[1] as any).params
? "&" + (params.queryKey[1] as any).params
: "")
);
const data = await response.json();
return data.response;
},
initialPageParam: 0,
refetchOnWindowFocus: false,
getNextPageParam: (lastPage) => {
if (lastPage.length === 0) {
return undefined;
}
return lastPage.at(-1).id;
},
enabled: status === "authenticated",
});
};
const buildQueryString = (params: LinkRequestQuery) => {
return Object.keys(params)
.filter((key) => params[key as keyof LinkRequestQuery] !== undefined)
.map(
(key) =>
`${encodeURIComponent(key)}=${encodeURIComponent(
params[key as keyof LinkRequestQuery] as string
)}`
)
.join("&");
};
const useAddLink = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (link: PostLinkSchemaType) => {
if (link.url || link.type === "url") {
try {
new URL(link.url || "");
} catch (error) {
throw new Error("invalid_url_guide");
}
}
const response = await fetch("/api/v1/links", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(link),
});
const data = await response.json();
if (!response.ok) throw new Error(data.response);
return data.response;
},
onSuccess: (data) => {
queryClient.setQueryData(["dashboardData"], (oldData: any) => {
if (!oldData?.links) return undefined;
return {
...oldData,
links: [data, ...oldData?.links],
};
});
queryClient.setQueriesData({ queryKey: ["links"] }, (oldData: any) => {
if (!oldData) return undefined;
return {
pages: [[data, ...oldData?.pages[0]], ...oldData?.pages.slice(1)],
pageParams: oldData?.pageParams,
};
});
queryClient.invalidateQueries({ queryKey: ["collections"] });
queryClient.invalidateQueries({ queryKey: ["tags"] });
queryClient.invalidateQueries({ queryKey: ["publicLinks"] });
},
});
};
const useUpdateLink = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (link: LinkIncludingShortenedCollectionAndTags) => {
const response = await fetch(`/api/v1/links/${link.id}`, {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(link),
});
const data = await response.json();
if (!response.ok) throw new Error(data.response);
return data.response;
},
onSuccess: (data) => {
// queryClient.setQueryData(["dashboardData"], (oldData: any) => {
// if (!oldData?.links) return undefined;
// return oldData.links.map((e: any) => (e.id === data.id ? data : e));
// });
// queryClient.setQueriesData({ queryKey: ["links"] }, (oldData: any) => {
// if (!oldData) return undefined;
// return {
// pages: oldData.pages.map((page: any) =>
// page.map((item: any) => (item.id === data.id ? data : item))
// ),
// pageParams: oldData.pageParams,
// };
// });
queryClient.invalidateQueries({ queryKey: ["links"] }); // Temporary workaround
queryClient.invalidateQueries({ queryKey: ["dashboardData"] }); // Temporary workaround
queryClient.invalidateQueries({ queryKey: ["collections"] });
queryClient.invalidateQueries({ queryKey: ["tags"] });
queryClient.invalidateQueries({ queryKey: ["publicLinks"] });
},
});
};
const useDeleteLink = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (id: number) => {
const response = await fetch(`/api/v1/links/${id}`, {
method: "DELETE",
});
const data = await response.json();
if (!response.ok) throw new Error(data.response);
return data.response;
},
onSuccess: (data) => {
queryClient.setQueryData(["dashboardData"], (oldData: any) => {
if (!oldData?.links) return undefined;
return {
...oldData,
links: oldData.links.filter((e: any) => e.id !== data.id),
};
});
queryClient.setQueriesData({ queryKey: ["links"] }, (oldData: any) => {
if (!oldData) return undefined;
return {
pages: oldData.pages.map((page: any) =>
page.filter((item: any) => item.id !== data.id)
),
pageParams: oldData.pageParams,
};
});
queryClient.invalidateQueries({ queryKey: ["collections"] });
queryClient.invalidateQueries({ queryKey: ["tags"] });
queryClient.invalidateQueries({ queryKey: ["publicLinks"] });
},
});
};
const useGetLink = () => {
const queryClient = useQueryClient();
const router = useRouter();
return useMutation({
mutationFn: async ({
id,
isPublicRoute = router.pathname.startsWith("/public") ? true : undefined,
}: {
id: number;
isPublicRoute?: boolean;
}) => {
const path = isPublicRoute
? `/api/v1/public/links/${id}`
: `/api/v1/links/${id}`;
const response = await fetch(path);
const data = await response.json();
if (!response.ok) throw new Error(data.response);
return data.response;
},
onSuccess: (data) => {
queryClient.setQueryData(["dashboardData"], (oldData: any) => {
if (!oldData?.links) return undefined;
return {
...oldData,
links: oldData.links.map((e: any) => (e.id === data.id ? data : e)),
};
});
queryClient.setQueriesData({ queryKey: ["links"] }, (oldData: any) => {
if (!oldData) return undefined;
return {
pages: oldData.pages.map((page: any) =>
page.map((item: any) => (item.id === data.id ? data : item))
),
pageParams: oldData.pageParams,
};
});
queryClient.setQueriesData(
{ queryKey: ["publicLinks"] },
(oldData: any) => {
if (!oldData) return undefined;
return {
pages: oldData.pages.map((page: any) =>
page.map((item: any) => (item.id === data.id ? data : item))
),
pageParams: oldData.pageParams,
};
}
);
// queryClient.invalidateQueries({ queryKey: ["publicLinks"] });
},
});
};
const useBulkDeleteLinks = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (linkIds: number[]) => {
const response = await fetch("/api/v1/links", {
method: "DELETE",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ linkIds }),
});
const data = await response.json();
if (!response.ok) throw new Error(data.response);
return linkIds;
},
onSuccess: (data) => {
queryClient.setQueryData(["dashboardData"], (oldData: any) => {
if (!oldData?.links) return undefined;
return oldData.links.filter((e: any) => !data.includes(e.id));
});
queryClient.setQueriesData({ queryKey: ["links"] }, (oldData: any) => {
if (!oldData) return undefined;
return {
pages: oldData.pages.map((page: any) =>
page.filter((item: any) => !data.includes(item.id))
),
pageParams: oldData.pageParams,
};
});
queryClient.invalidateQueries({ queryKey: ["collections"] });
queryClient.invalidateQueries({ queryKey: ["tags"] });
queryClient.invalidateQueries({ queryKey: ["publicLinks"] });
},
});
};
const useUploadFile = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async ({ link, file }: any) => {
let fileType: ArchivedFormat | null = null;
let linkType: "url" | "image" | "pdf" | null = null;
if (file?.type === "image/jpg" || file.type === "image/jpeg") {
fileType = ArchivedFormat.jpeg;
linkType = "image";
} else if (file.type === "image/png") {
fileType = ArchivedFormat.png;
linkType = "image";
} else if (file.type === "application/pdf") {
fileType = ArchivedFormat.pdf;
linkType = "pdf";
} else {
return { ok: false, data: "Invalid file type." };
}
const response = await fetch("/api/v1/links", {
body: JSON.stringify({
...link,
type: linkType,
name: link.name ? link.name : file.name,
}),
headers: {
"Content-Type": "application/json",
},
method: "POST",
});
const data = await response.json();
if (!response.ok) throw new Error(data.response);
if (response.ok) {
const formBody = new FormData();
file && formBody.append("file", file);
await fetch(
`/api/v1/archives/${(data as any).response.id}?format=${fileType}`,
{
body: formBody,
method: "POST",
}
);
}
return data.response;
},
onSuccess: (data) => {
queryClient.setQueryData(["dashboardData"], (oldData: any) => {
if (!oldData?.links) return undefined;
return {
...oldData,
links: [data, ...oldData?.links],
};
});
queryClient.setQueriesData({ queryKey: ["links"] }, (oldData: any) => {
if (!oldData) return undefined;
return {
pages: [[data, ...oldData?.pages[0]], ...oldData?.pages.slice(1)],
pageParams: oldData?.pageParams,
};
});
queryClient.invalidateQueries({ queryKey: ["collections"] });
queryClient.invalidateQueries({ queryKey: ["tags"] });
queryClient.invalidateQueries({ queryKey: ["publicLinks"] });
},
});
};
const useUpdatePreview = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async ({ linkId, file }: { linkId: number; file: File }) => {
const formBody = new FormData();
if (!linkId || !file)
throw new Error("Error generating preview: Invalid parameters");
formBody.append("file", file);
const res = await fetch(
`/api/v1/archives/${linkId}?format=` + ArchivedFormat.jpeg,
{
body: formBody,
method: "PUT",
}
);
const data = res.json();
return data;
},
onSuccess: (data) => {
queryClient.setQueryData(["dashboardData"], (oldData: any) => {
if (!oldData?.links) return undefined;
return {
...oldData,
links: oldData.links.map((e: any) =>
e.id === data.response.id
? {
...e,
preview: `archives/preview/${e.collectionId}/${e.id}.jpeg`,
}
: e
),
};
});
queryClient.setQueriesData({ queryKey: ["links"] }, (oldData: any) => {
if (!oldData) return undefined;
return {
pages: oldData.pages.map((page: any) =>
page.map((item: any) =>
item.id === data.response.id
? {
...item,
preview: `archives/preview/${item.collectionId}/${item.id}.jpeg`,
updatedAt: new Date().toISOString(),
}
: item
)
),
pageParams: oldData.pageParams,
};
});
},
});
};
const useBulkEditLinks = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async ({
links,
newData,
removePreviousTags,
}: {
links: LinkIncludingShortenedCollectionAndTags[];
newData: Pick<
LinkIncludingShortenedCollectionAndTags,
"tags" | "collectionId"
>;
removePreviousTags: boolean;
}) => {
const response = await fetch("/api/v1/links", {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ links, newData, removePreviousTags }),
});
const data = await response.json();
if (!response.ok) throw new Error(data.response);
return data.response;
},
onSuccess: (data, { links, newData, removePreviousTags }) => {
// TODO: Fix these
// queryClient.setQueryData(["dashboardData"], (oldData: any) => {
// if (!oldData?.links) return undefined;
// return oldData.links.map((e: any) =>
// data.find((d: any) => d.id === e.id) ? data : e
// );
// });
// queryClient.setQueriesData({ queryKey: ["links"] }, (oldData: any) => {
// if (!oldData) return undefined;
// return {
// pages: oldData.pages.map((page: any) => for (item of links) {
// page.map((item: any) => (item.id === data.id ? data : item))
// }
// ),
// pageParams: oldData.pageParams,
// };
// });
queryClient.invalidateQueries({ queryKey: ["links"] }); // Temporary workaround
queryClient.invalidateQueries({ queryKey: ["dashboardData"] }); // Temporary workaround
queryClient.invalidateQueries({ queryKey: ["collections"] });
queryClient.invalidateQueries({ queryKey: ["tags"] });
queryClient.invalidateQueries({ queryKey: ["publicLinks"] });
},
});
};
const resetInfiniteQueryPagination = async (
queryClient: any,
queryKey: any
) => {
queryClient.setQueriesData({ queryKey }, (oldData: any) => {
if (!oldData) return undefined;
return {
pages: oldData.pages.slice(0, 1),
pageParams: oldData.pageParams.slice(0, 1),
};
});
await queryClient.invalidateQueries(queryKey);
};
export {
useLinks,
useAddLink,
useUpdateLink,
useDeleteLink,
useBulkDeleteLinks,
useUploadFile,
useGetLink,
useBulkEditLinks,
resetInfiniteQueryPagination,
useUpdatePreview,
};
+93
View File
@@ -0,0 +1,93 @@
import {
InfiniteData,
useInfiniteQuery,
UseInfiniteQueryResult,
} from "@tanstack/react-query";
import { useMemo } from "react";
import {
LinkIncludingShortenedCollectionAndTags,
LinkRequestQuery,
} from "@/types/global";
import { useRouter } from "next/router";
const usePublicLinks = (params: LinkRequestQuery = {}) => {
const router = useRouter();
const queryParamsObject = {
sort: params.sort ?? Number(window.localStorage.getItem("sortBy")) ?? 0,
collectionId: params.collectionId ?? router.query.id,
tagId:
params.tagId ?? router.pathname === "/tags/[id]"
? router.query.id
: undefined,
pinnedOnly:
params.pinnedOnly ?? router.pathname === "/links/pinned"
? true
: undefined,
searchQueryString: params.searchQueryString,
searchByName: params.searchByName,
searchByUrl: params.searchByUrl,
searchByDescription: params.searchByDescription,
searchByTextContent: params.searchByTextContent,
searchByTags: params.searchByTags,
} as LinkRequestQuery;
const queryString = buildQueryString(queryParamsObject);
const { data, ...rest } = useFetchLinks(queryString);
const links = useMemo(() => {
return data?.pages.reduce((acc, page) => {
return [...acc, ...page];
}, []);
}, [data]);
return {
links,
data: { ...data, ...rest },
} as {
links: LinkIncludingShortenedCollectionAndTags[];
data: UseInfiniteQueryResult<InfiniteData<any, unknown>, Error>;
};
};
const useFetchLinks = (params: string) => {
return useInfiniteQuery({
queryKey: ["links", { params }],
queryFn: async (params) => {
const response = await fetch(
"/api/v1/public/collections/links?cursor=" +
params.pageParam +
((params.queryKey[1] as any).params
? "&" + (params.queryKey[1] as any).params
: "")
);
const data = await response.json();
return data.response;
},
initialPageParam: 0,
refetchOnWindowFocus: false,
getNextPageParam: (lastPage) => {
if (lastPage.length === 0) {
return undefined;
}
return lastPage.at(-1).id;
},
});
};
const buildQueryString = (params: LinkRequestQuery) => {
return Object.keys(params)
.filter((key) => params[key as keyof LinkRequestQuery] !== undefined)
.map(
(key) =>
`${encodeURIComponent(key)}=${encodeURIComponent(
params[key as keyof LinkRequestQuery] as string
)}`
)
.join("&");
};
export { usePublicLinks };
+29
View File
@@ -0,0 +1,29 @@
import { Tag } from "@prisma/client";
import { useQuery, UseQueryResult } from "@tanstack/react-query";
import { useSession } from "next-auth/react";
import { useRouter } from "next/router";
type TagIncludingCount = Tag & { _count: { links: number } };
const usePublicTags = (): UseQueryResult<TagIncludingCount[]> => {
const { status } = useSession();
const router = useRouter();
return useQuery({
queryKey: ["tags"],
queryFn: async () => {
const response = await fetch(
"/api/v1/public/collections/tags" +
"?collectionId=" +
router.query.id || ""
);
if (!response.ok) throw new Error("Failed to fetch tags.");
const data = await response.json();
return data.response;
},
});
};
export { usePublicTags };
+71
View File
@@ -0,0 +1,71 @@
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { TagIncludingLinkCount } from "@/types/global";
import { useSession } from "next-auth/react";
const useTags = () => {
const { status } = useSession();
return useQuery({
queryKey: ["tags"],
queryFn: async () => {
const response = await fetch("/api/v1/tags");
if (!response.ok) throw new Error("Failed to fetch tags.");
const data = await response.json();
return data.response;
},
enabled: status === "authenticated",
});
};
const useUpdateTag = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (tag: TagIncludingLinkCount) => {
const response = await fetch(`/api/v1/tags/${tag.id}`, {
body: JSON.stringify(tag),
headers: {
"Content-Type": "application/json",
},
method: "PUT",
});
const data = await response.json();
if (!response.ok) throw new Error(data.response);
return data.response;
},
onSuccess: (data) => {
queryClient.setQueryData(["tags"], (oldData: any) =>
oldData.map((tag: TagIncludingLinkCount) =>
tag.id === data.id ? data : tag
)
);
},
});
};
const useRemoveTag = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (tagId: number) => {
const response = await fetch(`/api/v1/tags/${tagId}`, {
method: "DELETE",
});
const data = await response.json();
if (!response.ok) throw new Error(data.response);
return data.response;
},
onSuccess: (data, variables) => {
queryClient.setQueryData(["tags"], (oldData: any) =>
oldData.filter((tag: TagIncludingLinkCount) => tag.id !== variables)
);
},
});
};
export { useTags, useUpdateTag, useRemoveTag };
+71
View File
@@ -0,0 +1,71 @@
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { AccessToken } from "@prisma/client";
import { useSession } from "next-auth/react";
const useTokens = () => {
const { status } = useSession();
return useQuery({
queryKey: ["tokens"],
queryFn: async () => {
const response = await fetch("/api/v1/tokens");
if (!response.ok) throw new Error("Failed to fetch tokens.");
const data = await response.json();
return data.response as AccessToken[];
},
enabled: status === "authenticated",
});
};
const useAddToken = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (body: Partial<AccessToken>) => {
const response = await fetch("/api/v1/tokens", {
body: JSON.stringify(body),
method: "POST",
headers: {
"Content-Type": "application/json",
},
});
const data = await response.json();
if (!response.ok) throw new Error(data.response);
return data.response;
},
onSuccess: (data) => {
queryClient.setQueryData(["tokens"], (oldData: AccessToken[]) => [
...oldData,
data.token,
]);
},
});
};
const useRevokeToken = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (tokenId: number) => {
const response = await fetch(`/api/v1/tokens/${tokenId}`, {
method: "DELETE",
});
const data = await response.json();
if (!response.ok) throw new Error(data.response);
return data.response;
},
onSuccess: (data, variables) => {
queryClient.setQueryData(["tokens"], (oldData: AccessToken[]) =>
oldData.filter((token: Partial<AccessToken>) => token.id !== variables)
);
},
});
};
export { useTokens, useAddToken, useRevokeToken };
+53
View File
@@ -0,0 +1,53 @@
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useSession } from "next-auth/react";
const useUser = () => {
const { data, status } = useSession();
const userId = data?.user.id;
return useQuery({
queryKey: ["user"],
queryFn: async () => {
const response = await fetch(`/api/v1/users/${userId}`);
if (!response.ok) throw new Error("Failed to fetch user data.");
const data = await response.json();
return data.response;
},
enabled: !!userId && status === "authenticated",
placeholderData: {},
});
};
const useUpdateUser = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (user: any) => {
const response = await fetch(`/api/v1/users/${user.id}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(user),
});
const data = await response.json();
if (!response.ok) throw new Error(data.response);
return data;
},
onSuccess: (data) => {
queryClient.setQueryData(["user"], data.response);
},
onMutate: async (user) => {
await queryClient.cancelQueries({ queryKey: ["user"] });
queryClient.setQueryData(["user"], (oldData: any) => {
return { ...oldData, ...user };
});
},
});
};
export { useUser, useUpdateUser };
+7 -7
View File
@@ -1,12 +1,12 @@
import useAccountStore from "@/store/account";
import useCollectionStore from "@/store/collections";
import { Member } from "@/types/global"; import { Member } from "@/types/global";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { useCollections } from "./store/collections";
import { useUser } from "./store/user";
export default function useCollectivePermissions(collectionIds: number[]) { export default function useCollectivePermissions(collectionIds: number[]) {
const { collections } = useCollectionStore(); const { data: collections = [] } = useCollections();
const { account } = useAccountStore(); const { data: user = {} } = useUser();
const [permissions, setPermissions] = useState<Member | true>(); const [permissions, setPermissions] = useState<Member | true>();
useEffect(() => { useEffect(() => {
@@ -15,7 +15,7 @@ export default function useCollectivePermissions(collectionIds: number[]) {
if (collection) { if (collection) {
let getPermission: Member | undefined = collection.members.find( let getPermission: Member | undefined = collection.members.find(
(e) => e.userId === account.id (e) => e.userId === user.id
); );
if ( if (
@@ -25,10 +25,10 @@ export default function useCollectivePermissions(collectionIds: number[]) {
) )
getPermission = undefined; getPermission = undefined;
setPermissions(account.id === collection.ownerId || getPermission); setPermissions(user.id === collection.ownerId || getPermission);
} }
} }
}, [account, collections, collectionIds]); }, [user, collections, collectionIds]);
return permissions; return permissions;
} }
-20
View File
@@ -1,34 +1,14 @@
import useCollectionStore from "@/store/collections";
import { useEffect } from "react"; import { useEffect } from "react";
import { useSession } from "next-auth/react"; import { useSession } from "next-auth/react";
import useTagStore from "@/store/tags";
import useAccountStore from "@/store/account";
import useLocalSettingsStore from "@/store/localSettings"; import useLocalSettingsStore from "@/store/localSettings";
export default function useInitialData() { export default function useInitialData() {
const { status, data } = useSession(); const { status, data } = useSession();
const { setCollections } = useCollectionStore();
const { setTags } = useTagStore();
// const { setLinks } = useLinkStore();
const { account, setAccount } = useAccountStore();
const { setSettings } = useLocalSettingsStore(); const { setSettings } = useLocalSettingsStore();
useEffect(() => { useEffect(() => {
setSettings(); setSettings();
if (status === "authenticated") {
// Get account info
setAccount(data?.user.id as number);
}
}, [status, data]); }, [status, data]);
// Get the rest of the data
useEffect(() => {
if (account.id && (!process.env.NEXT_PUBLIC_STRIPE || account.username)) {
setCollections();
setTags();
// setLinks();
}
}, [account]);
return status; return status;
} }
-103
View File
@@ -1,103 +0,0 @@
import { LinkRequestQuery } from "@/types/global";
import { useEffect, useState } from "react";
import useDetectPageBottom from "./useDetectPageBottom";
import { useRouter } from "next/router";
import useLinkStore from "@/store/links";
export default function useLinks(
{
sort,
collectionId,
tagId,
pinnedOnly,
searchQueryString,
searchByName,
searchByUrl,
searchByDescription,
searchByTags,
searchByTextContent,
}: LinkRequestQuery = { sort: 0 }
) {
const { links, setLinks, resetLinks, selectedLinks, setSelectedLinks } =
useLinkStore();
const router = useRouter();
const [isLoading, setIsLoading] = useState(true);
const { reachedBottom, setReachedBottom } = useDetectPageBottom();
const getLinks = async (isInitialCall: boolean, cursor?: number) => {
const params = {
sort,
cursor,
collectionId,
tagId,
pinnedOnly,
searchQueryString,
searchByName,
searchByUrl,
searchByDescription,
searchByTags,
searchByTextContent,
};
const buildQueryString = (params: LinkRequestQuery) => {
return Object.keys(params)
.filter((key) => params[key as keyof LinkRequestQuery] !== undefined)
.map(
(key) =>
`${encodeURIComponent(key)}=${encodeURIComponent(
params[key as keyof LinkRequestQuery] as string
)}`
)
.join("&");
};
let queryString = buildQueryString(params);
let basePath;
if (router.pathname === "/dashboard") basePath = "/api/v1/dashboard";
else if (router.pathname.startsWith("/public/collections/[id]")) {
queryString = queryString + "&collectionId=" + router.query.id;
basePath = "/api/v1/public/collections/links";
} else basePath = "/api/v1/links";
setIsLoading(true);
const response = await fetch(`${basePath}?${queryString}`);
const data = await response.json();
setIsLoading(false);
if (response.ok) setLinks(data.response, isInitialCall);
};
useEffect(() => {
// Save the selected links before resetting the links
// and then restore the selected links after resetting the links
const previouslySelected = selectedLinks;
resetLinks();
setSelectedLinks(previouslySelected);
getLinks(true);
}, [
router,
sort,
searchQueryString,
searchByName,
searchByUrl,
searchByDescription,
searchByTextContent,
searchByTags,
]);
useEffect(() => {
if (reachedBottom) getLinks(false, links?.at(-1)?.id);
setReachedBottom(false);
}, [reachedBottom]);
return { isLoading };
}
+7 -7
View File
@@ -1,12 +1,12 @@
import useAccountStore from "@/store/account";
import useCollectionStore from "@/store/collections";
import { Member } from "@/types/global"; import { Member } from "@/types/global";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { useCollections } from "./store/collections";
import { useUser } from "./store/user";
export default function usePermissions(collectionId: number) { export default function usePermissions(collectionId: number) {
const { collections } = useCollectionStore(); const { data: collections = [] } = useCollections();
const { account } = useAccountStore(); const { data: user = {} } = useUser();
const [permissions, setPermissions] = useState<Member | true>(); const [permissions, setPermissions] = useState<Member | true>();
useEffect(() => { useEffect(() => {
@@ -14,7 +14,7 @@ export default function usePermissions(collectionId: number) {
if (collection) { if (collection) {
let getPermission: Member | undefined = collection.members.find( let getPermission: Member | undefined = collection.members.find(
(e) => e.userId === account.id (e) => e.userId === user.id
); );
if ( if (
@@ -24,9 +24,9 @@ export default function usePermissions(collectionId: number) {
) )
getPermission = undefined; getPermission = undefined;
setPermissions(account.id === collection.ownerId || getPermission); setPermissions(user.id === collection.ownerId || getPermission);
} }
}, [account, collections, collectionId]); }, [user, collections, collectionId]);
return permissions; return permissions;
} }
+9 -4
View File
@@ -2,7 +2,7 @@ import { ReactNode, useEffect, useState } from "react";
import { useRouter } from "next/router"; import { useRouter } from "next/router";
import { useSession } from "next-auth/react"; import { useSession } from "next-auth/react";
import useInitialData from "@/hooks/useInitialData"; import useInitialData from "@/hooks/useInitialData";
import useAccountStore from "@/store/account"; import { useUser } from "@/hooks/store/user";
interface Props { interface Props {
children: ReactNode; children: ReactNode;
@@ -14,7 +14,7 @@ export default function AuthRedirect({ children }: Props) {
const router = useRouter(); const router = useRouter();
const { status } = useSession(); const { status } = useSession();
const [shouldRenderChildren, setShouldRenderChildren] = useState(false); const [shouldRenderChildren, setShouldRenderChildren] = useState(false);
const { account } = useAccountStore(); const { data: user = {} } = useUser();
useInitialData(); useInitialData();
@@ -23,7 +23,10 @@ export default function AuthRedirect({ children }: Props) {
const isUnauthenticated = status === "unauthenticated"; const isUnauthenticated = status === "unauthenticated";
const isPublicPage = router.pathname.startsWith("/public"); const isPublicPage = router.pathname.startsWith("/public");
const hasInactiveSubscription = const hasInactiveSubscription =
account.id && !account.subscription?.active && stripeEnabled; user.id &&
!user.subscription?.active &&
!user.parentSubscription?.active &&
stripeEnabled;
// There are better ways of doing this... but this one works for now // There are better ways of doing this... but this one works for now
const routes = [ const routes = [
@@ -49,6 +52,8 @@ export default function AuthRedirect({ children }: Props) {
} else { } else {
if (isLoggedIn && hasInactiveSubscription) { if (isLoggedIn && hasInactiveSubscription) {
redirectTo("/subscribe"); redirectTo("/subscribe");
} else if (isLoggedIn && !user.name && user.parentSubscriptionId) {
redirectTo("/member-onboarding");
} else if ( } else if (
isLoggedIn && isLoggedIn &&
!routes.some((e) => router.pathname.startsWith(e.path) && e.isProtected) !routes.some((e) => router.pathname.startsWith(e.path) && e.isProtected)
@@ -63,7 +68,7 @@ export default function AuthRedirect({ children }: Props) {
setShouldRenderChildren(true); setShouldRenderChildren(true);
} }
} }
}, [status, account, router.pathname]); }, [status, user, router.pathname]);
function redirectTo(destination: string) { function redirectTo(destination: string) {
router.push(destination).then(() => setShouldRenderChildren(true)); router.push(destination).then(() => setShouldRenderChildren(true));
+4 -4
View File
@@ -23,7 +23,7 @@ export default function CenteredForm({
data-testid={dataTestId} data-testid={dataTestId}
> >
<div className="m-auto flex flex-col gap-2 w-full"> <div className="m-auto flex flex-col gap-2 w-full">
{settings.theme ? ( {settings.theme && (
<Image <Image
src={`/linkwarden_${ src={`/linkwarden_${
settings.theme === "dark" ? "dark" : "light" settings.theme === "dark" ? "dark" : "light"
@@ -33,12 +33,12 @@ export default function CenteredForm({
alt="Linkwarden" alt="Linkwarden"
className="h-12 w-fit mx-auto" className="h-12 w-fit mx-auto"
/> />
) : undefined} )}
{text ? ( {text && (
<p className="text-lg max-w-[30rem] min-w-80 w-full mx-auto font-semibold px-2 text-center"> <p className="text-lg max-w-[30rem] min-w-80 w-full mx-auto font-semibold px-2 text-center">
{text} {text}
</p> </p>
) : undefined} )}
{children} {children}
<p className="text-center text-xs text-neutral mb-5"> <p className="text-center text-xs text-neutral mb-5">
<Trans <Trans
+2 -2
View File
@@ -34,9 +34,9 @@ export default function MainLayout({ children }: Props) {
return ( return (
<div className="flex" data-testid="dashboard-wrapper"> <div className="flex" data-testid="dashboard-wrapper">
{showAnnouncement ? ( {showAnnouncement && (
<Announcement toggleAnnouncementBar={toggleAnnouncementBar} /> <Announcement toggleAnnouncementBar={toggleAnnouncementBar} />
) : undefined} )}
<div className="hidden lg:block"> <div className="hidden lg:block">
<Sidebar className={`fixed top-0`} /> <Sidebar className={`fixed top-0`} />
</div> </div>
+2 -2
View File
@@ -54,7 +54,7 @@ export default function SettingsLayout({ children }: Props) {
{children} {children}
{sidebar ? ( {sidebar && (
<div className="fixed top-0 bottom-0 right-0 left-0 bg-black bg-opacity-10 backdrop-blur-sm flex items-center fade-in z-30"> <div className="fixed top-0 bottom-0 right-0 left-0 bg-black bg-opacity-10 backdrop-blur-sm flex items-center fade-in z-30">
<ClickAwayHandler <ClickAwayHandler
className="h-full" className="h-full"
@@ -65,7 +65,7 @@ export default function SettingsLayout({ children }: Props) {
</div> </div>
</ClickAwayHandler> </ClickAwayHandler>
</div> </div>
) : null} )}
</div> </div>
</div> </div>
</> </>
+17
View File
@@ -21,6 +21,19 @@ type LinksAndCollectionAndOwner = Link & {
const BROWSER_TIMEOUT = Number(process.env.BROWSER_TIMEOUT) || 5; const BROWSER_TIMEOUT = Number(process.env.BROWSER_TIMEOUT) || 5;
export default async function archiveHandler(link: LinksAndCollectionAndOwner) { export default async function archiveHandler(link: LinksAndCollectionAndOwner) {
if (process.env.DISABLE_PRESERVATION === "true")
return await prisma.link.update({
where: { id: link.id },
data: {
lastPreserved: new Date().toISOString(),
readable: "unavailable",
image: "unavailable",
monolith: "unavailable",
pdf: "unavailable",
preview: "unavailable",
},
});
const timeoutPromise = new Promise((_, reject) => { const timeoutPromise = new Promise((_, reject) => {
setTimeout( setTimeout(
() => () =>
@@ -43,6 +56,10 @@ export default async function archiveHandler(link: LinksAndCollectionAndOwner) {
password: process.env.PROXY_PASSWORD, password: process.env.PROXY_PASSWORD,
}; };
} }
if (process.env.PLAYWRIGHT_LAUNCH_OPTIONS_EXECUTABLE_PATH) {
browserOptions.executablePath =
process.env.PLAYWRIGHT_LAUNCH_OPTIONS_EXECUTABLE_PATH;
}
const browser = await chromium.launch(browserOptions); const browser = await chromium.launch(browserOptions);
const context = await browser.newContext({ const context = await browser.newContext({
-53
View File
@@ -1,53 +0,0 @@
import Stripe from "stripe";
const MONTHLY_PRICE_ID = process.env.MONTHLY_PRICE_ID;
const YEARLY_PRICE_ID = process.env.YEARLY_PRICE_ID;
const STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY;
export default async function checkSubscriptionByEmail(email: string) {
let active: boolean | undefined,
stripeSubscriptionId: string | undefined,
currentPeriodStart: number | undefined,
currentPeriodEnd: number | undefined;
if (!STRIPE_SECRET_KEY)
return {
active,
stripeSubscriptionId,
currentPeriodStart,
currentPeriodEnd,
};
const stripe = new Stripe(STRIPE_SECRET_KEY, {
apiVersion: "2022-11-15",
});
console.log("Request made to Stripe by:", email);
const listByEmail = await stripe.customers.list({
email: email.toLowerCase(),
expand: ["data.subscriptions"],
});
listByEmail.data.some((customer) => {
customer.subscriptions?.data.some((subscription) => {
subscription.current_period_end;
active =
subscription.items.data.some(
(e) =>
(e.price.id === MONTHLY_PRICE_ID && e.price.active === true) ||
(e.price.id === YEARLY_PRICE_ID && e.price.active === true)
) || false;
stripeSubscriptionId = subscription.id;
currentPeriodStart = subscription.current_period_start * 1000;
currentPeriodEnd = subscription.current_period_end * 1000;
});
});
return {
active: active || false,
stripeSubscriptionId,
currentPeriodStart,
currentPeriodEnd,
};
}
@@ -57,8 +57,8 @@ export default async function deleteCollection(
}, },
}); });
await removeFolder({ filePath: `archives/${collectionId}` }); removeFolder({ filePath: `archives/${collectionId}` });
await removeFolder({ filePath: `archives/preview/${collectionId}` }); removeFolder({ filePath: `archives/preview/${collectionId}` });
await removeFromOrders(userId, collectionId); await removeFromOrders(userId, collectionId);
@@ -100,8 +100,8 @@ async function deleteSubCollections(collectionId: number) {
where: { id: subCollection.id }, where: { id: subCollection.id },
}); });
await removeFolder({ filePath: `archives/${subCollection.id}` }); removeFolder({ filePath: `archives/${subCollection.id}` });
await removeFolder({ filePath: `archives/preview/${subCollection.id}` }); removeFolder({ filePath: `archives/preview/${subCollection.id}` });
} }
} }
@@ -1,15 +1,31 @@
import { prisma } from "@/lib/api/db"; import { prisma } from "@/lib/api/db";
import { CollectionIncludingMembersAndLinkCount } from "@/types/global";
import getPermission from "@/lib/api/getPermission"; import getPermission from "@/lib/api/getPermission";
import {
UpdateCollectionSchema,
UpdateCollectionSchemaType,
} from "@/lib/shared/schemaValidation";
export default async function updateCollection( export default async function updateCollection(
userId: number, userId: number,
collectionId: number, collectionId: number,
data: CollectionIncludingMembersAndLinkCount body: UpdateCollectionSchemaType
) { ) {
if (!collectionId) if (!collectionId)
return { response: "Please choose a valid collection.", status: 401 }; return { response: "Please choose a valid collection.", status: 401 };
const dataValidation = UpdateCollectionSchema.safeParse(body);
if (!dataValidation.success) {
return {
response: `Error: ${
dataValidation.error.issues[0].message
} [${dataValidation.error.issues[0].path.join(", ")}]`,
status: 400,
};
}
const data = dataValidation.data;
const collectionIsAccessible = await getPermission({ const collectionIsAccessible = await getPermission({
userId, userId,
collectionId, collectionId,
@@ -18,10 +34,8 @@ export default async function updateCollection(
if (!(collectionIsAccessible?.ownerId === userId)) if (!(collectionIsAccessible?.ownerId === userId))
return { response: "Collection is not accessible.", status: 401 }; return { response: "Collection is not accessible.", status: 401 };
console.log(data);
if (data.parentId) { if (data.parentId) {
if (data.parentId !== ("root" as any)) { if (data.parentId !== "root") {
const findParentCollection = await prisma.collection.findUnique({ const findParentCollection = await prisma.collection.findUnique({
where: { where: {
id: data.parentId, id: data.parentId,
@@ -44,6 +58,12 @@ export default async function updateCollection(
} }
} }
const uniqueMembers = data.members.filter(
(e, i, a) =>
a.findIndex((el) => el.userId === e.userId) === i &&
e.userId !== collectionIsAccessible.ownerId
);
const updatedCollection = await prisma.$transaction(async () => { const updatedCollection = await prisma.$transaction(async () => {
await prisma.usersAndCollections.deleteMany({ await prisma.usersAndCollections.deleteMany({
where: { where: {
@@ -61,22 +81,24 @@ export default async function updateCollection(
name: data.name.trim(), name: data.name.trim(),
description: data.description, description: data.description,
color: data.color, color: data.color,
icon: data.icon,
iconWeight: data.iconWeight,
isPublic: data.isPublic, isPublic: data.isPublic,
parent: parent:
data.parentId && data.parentId !== ("root" as any) data.parentId && data.parentId !== "root"
? { ? {
connect: { connect: {
id: data.parentId, id: data.parentId,
}, },
} }
: data.parentId === ("root" as any) : data.parentId === "root"
? { ? {
disconnect: true, disconnect: true,
} }
: undefined, : undefined,
members: { members: {
create: data.members.map((e) => ({ create: uniqueMembers.map((e) => ({
user: { connect: { id: e.user.id || e.userId } }, user: { connect: { id: e.userId } },
canCreate: e.canCreate, canCreate: e.canCreate,
canUpdate: e.canUpdate, canUpdate: e.canUpdate,
canDelete: e.canDelete, canDelete: e.canDelete,
@@ -1,16 +1,26 @@
import { prisma } from "@/lib/api/db"; import { prisma } from "@/lib/api/db";
import { CollectionIncludingMembersAndLinkCount } from "@/types/global";
import createFolder from "@/lib/api/storage/createFolder"; import createFolder from "@/lib/api/storage/createFolder";
import {
PostCollectionSchema,
PostCollectionSchemaType,
} from "@/lib/shared/schemaValidation";
export default async function postCollection( export default async function postCollection(
collection: CollectionIncludingMembersAndLinkCount, body: PostCollectionSchemaType,
userId: number userId: number
) { ) {
if (!collection || collection.name.trim() === "") const dataValidation = PostCollectionSchema.safeParse(body);
if (!dataValidation.success) {
return { return {
response: "Please enter a valid collection.", response: `Error: ${
dataValidation.error.issues[0].message
} [${dataValidation.error.issues[0].path.join(", ")}]`,
status: 400, status: 400,
}; };
}
const collection = dataValidation.data;
if (collection.parentId) { if (collection.parentId) {
const findParentCollection = await prisma.collection.findUnique({ const findParentCollection = await prisma.collection.findUnique({
@@ -34,14 +44,11 @@ export default async function postCollection(
const newCollection = await prisma.collection.create({ const newCollection = await prisma.collection.create({
data: { data: {
owner: {
connect: {
id: userId,
},
},
name: collection.name.trim(), name: collection.name.trim(),
description: collection.description, description: collection.description,
color: collection.color, color: collection.color,
icon: collection.icon,
iconWeight: collection.iconWeight,
parent: collection.parentId parent: collection.parentId
? { ? {
connect: { connect: {
@@ -49,6 +56,16 @@ export default async function postCollection(
}, },
} }
: undefined, : undefined,
owner: {
connect: {
id: userId,
},
},
createdBy: {
connect: {
id: userId,
},
},
}, },
include: { include: {
_count: { _count: {
@@ -1,11 +1,11 @@
import { prisma } from "@/lib/api/db"; import { prisma } from "@/lib/api/db";
import { LinkRequestQuery, Sort } from "@/types/global"; import { LinkRequestQuery, Order, Sort } from "@/types/global";
export default async function getDashboardData( export default async function getDashboardData(
userId: number, userId: number,
query: LinkRequestQuery query: LinkRequestQuery
) { ) {
let order: any; let order: Order = { id: "desc" };
if (query.sort === Sort.DateNewestFirst) order = { id: "desc" }; if (query.sort === Sort.DateNewestFirst) order = { id: "desc" };
else if (query.sort === Sort.DateOldestFirst) order = { id: "asc" }; else if (query.sort === Sort.DateOldestFirst) order = { id: "asc" };
else if (query.sort === Sort.NameAZ) order = { name: "asc" }; else if (query.sort === Sort.NameAZ) order = { name: "asc" };
@@ -42,7 +42,7 @@ export default async function getDashboardData(
select: { id: true }, select: { id: true },
}, },
}, },
orderBy: order || { id: "desc" }, orderBy: order,
}); });
const recentlyAddedLinks = await prisma.link.findMany({ const recentlyAddedLinks = await prisma.link.findMany({
@@ -67,10 +67,18 @@ export default async function getDashboardData(
select: { id: true }, select: { id: true },
}, },
}, },
orderBy: order || { id: "desc" }, orderBy: order,
}); });
const links = [...recentlyAddedLinks, ...pinnedLinks].sort( const combinedLinks = [...recentlyAddedLinks, ...pinnedLinks];
const uniqueLinks = Array.from(
combinedLinks
.reduce((map, item) => map.set(item.id, item), new Map())
.values()
);
const links = uniqueLinks.sort(
(a, b) => (new Date(b.id) as any) - (new Date(a.id) as any) (a, b) => (new Date(b.id) as any) - (new Date(a.id) as any)
); );
@@ -1,5 +1,5 @@
import { prisma } from "@/lib/api/db"; import { prisma } from "@/lib/api/db";
import { LinkRequestQuery, Sort } from "@/types/global"; import { LinkRequestQuery, Order, Sort } from "@/types/global";
type Response<D> = type Response<D> =
| { | {
@@ -17,7 +17,7 @@ export default async function getDashboardData(
userId: number, userId: number,
query: LinkRequestQuery query: LinkRequestQuery
): Promise<Response<any>> { ): Promise<Response<any>> {
let order: any; let order: Order = { id: "desc" };
if (query.sort === Sort.DateNewestFirst) order = { id: "desc" }; if (query.sort === Sort.DateNewestFirst) order = { id: "desc" };
else if (query.sort === Sort.DateOldestFirst) order = { id: "asc" }; else if (query.sort === Sort.DateOldestFirst) order = { id: "asc" };
else if (query.sort === Sort.NameAZ) order = { name: "asc" }; else if (query.sort === Sort.NameAZ) order = { name: "asc" };
@@ -48,7 +48,7 @@ export default async function getDashboardData(
}); });
const pinnedLinks = await prisma.link.findMany({ const pinnedLinks = await prisma.link.findMany({
take: 10, take: 16,
where: { where: {
AND: [ AND: [
{ {
@@ -80,7 +80,7 @@ export default async function getDashboardData(
}); });
const recentlyAddedLinks = await prisma.link.findMany({ const recentlyAddedLinks = await prisma.link.findMany({
take: 10, take: 16,
where: { where: {
collection: { collection: {
OR: [ OR: [
@@ -105,12 +105,17 @@ export default async function getDashboardData(
}); });
const links = [...recentlyAddedLinks, ...pinnedLinks].sort( const links = [...recentlyAddedLinks, ...pinnedLinks].sort(
(a, b) => (new Date(b.id) as any) - (new Date(a.id) as any) (a, b) => new Date(b.id).getTime() - new Date(a.id).getTime()
);
// Make sure links are unique
const uniqueLinks = links.filter(
(link, index, self) => index === self.findIndex((t) => t.id === link.id)
); );
return { return {
data: { data: {
links, links: uniqueLinks,
numberOfPinnedLinks, numberOfPinnedLinks,
}, },
message: "Dashboard data fetched successfully.", message: "Dashboard data fetched successfully.",
@@ -1,9 +1,10 @@
import { LinkIncludingShortenedCollectionAndTags } from "@/types/global"; import { LinkIncludingShortenedCollectionAndTags } from "@/types/global";
import updateLinkById from "../linkId/updateLinkById"; import updateLinkById from "../linkId/updateLinkById";
import { UpdateLinkSchemaType } from "@/lib/shared/schemaValidation";
export default async function updateLinks( export default async function updateLinks(
userId: number, userId: number,
links: LinkIncludingShortenedCollectionAndTags[], links: UpdateLinkSchemaType[],
removePreviousTags: boolean, removePreviousTags: boolean,
newData: Pick< newData: Pick<
LinkIncludingShortenedCollectionAndTags, LinkIncludingShortenedCollectionAndTags,
@@ -22,7 +23,7 @@ export default async function updateLinks(
updatedTags = [...(newData.tags ?? [])]; updatedTags = [...(newData.tags ?? [])];
} }
const updatedData: LinkIncludingShortenedCollectionAndTags = { const updatedData: UpdateLinkSchemaType = {
...link, ...link,
tags: updatedTags, tags: updatedTags,
collection: { collection: {
+3 -3
View File
@@ -1,11 +1,11 @@
import { prisma } from "@/lib/api/db"; import { prisma } from "@/lib/api/db";
import { LinkRequestQuery, Sort } from "@/types/global"; import { LinkRequestQuery, Order, Sort } from "@/types/global";
export default async function getLink(userId: number, query: LinkRequestQuery) { export default async function getLink(userId: number, query: LinkRequestQuery) {
const POSTGRES_IS_ENABLED = const POSTGRES_IS_ENABLED =
process.env.DATABASE_URL?.startsWith("postgresql"); process.env.DATABASE_URL?.startsWith("postgresql");
let order: any; let order: Order = { id: "desc" };
if (query.sort === Sort.DateNewestFirst) order = { id: "desc" }; if (query.sort === Sort.DateNewestFirst) order = { id: "desc" };
else if (query.sort === Sort.DateOldestFirst) order = { id: "asc" }; else if (query.sort === Sort.DateOldestFirst) order = { id: "asc" };
else if (query.sort === Sort.NameAZ) order = { name: "asc" }; else if (query.sort === Sort.NameAZ) order = { name: "asc" };
@@ -146,7 +146,7 @@ export default async function getLink(userId: number, query: LinkRequestQuery) {
select: { id: true }, select: { id: true },
}, },
}, },
orderBy: order || { id: "desc" }, orderBy: order,
}); });
return { response: links, status: 200 }; return { response: links, status: 200 };
@@ -1,19 +1,30 @@
import { prisma } from "@/lib/api/db"; import { prisma } from "@/lib/api/db";
import { LinkIncludingShortenedCollectionAndTags } from "@/types/global";
import { UsersAndCollections } from "@prisma/client"; import { UsersAndCollections } from "@prisma/client";
import getPermission from "@/lib/api/getPermission"; import getPermission from "@/lib/api/getPermission";
import { moveFiles } from "@/lib/api/manageLinkFiles"; import { moveFiles, removeFiles } from "@/lib/api/manageLinkFiles";
import isValidUrl from "@/lib/shared/isValidUrl";
import {
UpdateLinkSchema,
UpdateLinkSchemaType,
} from "@/lib/shared/schemaValidation";
export default async function updateLinkById( export default async function updateLinkById(
userId: number, userId: number,
linkId: number, linkId: number,
data: LinkIncludingShortenedCollectionAndTags body: UpdateLinkSchemaType
) { ) {
if (!data || !data.collection.id) const dataValidation = UpdateLinkSchema.safeParse(body);
if (!dataValidation.success) {
return { return {
response: "Please choose a valid link and collection.", response: `Error: ${
status: 401, dataValidation.error.issues[0].message
} [${dataValidation.error.issues[0].path.join(", ")}]`,
status: 400,
}; };
}
const data = dataValidation.data;
const collectionIsAccessible = await getPermission({ userId, linkId }); const collectionIsAccessible = await getPermission({ userId, linkId });
@@ -25,17 +36,18 @@ export default async function updateLinkById(
(e: UsersAndCollections) => e.userId === userId (e: UsersAndCollections) => e.userId === userId
); );
// If the user is able to create a link, they can pin it to their dashboard only. // If the user is part of a collection, they can pin it to their dashboard
if (canPinPermission) { if (canPinPermission && data.pinnedBy && data.pinnedBy[0]) {
const updatedLink = await prisma.link.update({ const updatedLink = await prisma.link.update({
where: { where: {
id: linkId, id: linkId,
}, },
data: { data: {
pinnedBy: pinnedBy: data?.pinnedBy
data?.pinnedBy && data.pinnedBy[0] ? data.pinnedBy[0]?.id === userId
? { connect: { id: userId } } ? { connect: { id: userId } }
: { disconnect: { id: userId } }, : { disconnect: { id: userId } }
: undefined,
}, },
include: { include: {
collection: true, collection: true,
@@ -48,7 +60,7 @@ export default async function updateLinkById(
}, },
}); });
// return { response: updatedLink, status: 200 }; return { response: updatedLink, status: 200 };
} }
const targetCollectionIsAccessible = await getPermission({ const targetCollectionIsAccessible = await getPermission({
@@ -62,11 +74,9 @@ export default async function updateLinkById(
const targetCollectionMatchesData = data.collection.id const targetCollectionMatchesData = data.collection.id
? data.collection.id === targetCollectionIsAccessible?.id ? data.collection.id === targetCollectionIsAccessible?.id
: true && data.collection.name : true && data.collection.ownerId
? data.collection.name === targetCollectionIsAccessible?.name ? data.collection.ownerId === targetCollectionIsAccessible?.ownerId
: true && data.collection.ownerId : true;
? data.collection.ownerId === targetCollectionIsAccessible?.ownerId
: true;
if (!targetCollectionMatchesData) if (!targetCollectionMatchesData)
return { return {
@@ -89,13 +99,41 @@ export default async function updateLinkById(
status: 401, status: 401,
}; };
else { else {
const oldLink = await prisma.link.findUnique({
where: {
id: linkId,
},
});
if (
data.url &&
oldLink &&
oldLink?.url !== data.url &&
isValidUrl(data.url)
) {
await removeFiles(oldLink.id, oldLink.collectionId);
} else if (oldLink?.url !== data.url)
return {
response: "Invalid URL.",
status: 401,
};
const updatedLink = await prisma.link.update({ const updatedLink = await prisma.link.update({
where: { where: {
id: linkId, id: linkId,
}, },
data: { data: {
name: data.name, name: data.name,
url: data.url,
description: data.description, description: data.description,
icon: data.icon,
iconWeight: data.iconWeight,
color: data.color,
image: oldLink?.url !== data.url ? null : undefined,
pdf: oldLink?.url !== data.url ? null : undefined,
readable: oldLink?.url !== data.url ? null : undefined,
monolith: oldLink?.url !== data.url ? null : undefined,
preview: oldLink?.url !== data.url ? null : undefined,
collection: { collection: {
connect: { connect: {
id: data.collection.id, id: data.collection.id,
@@ -120,10 +158,11 @@ export default async function updateLinkById(
}, },
})), })),
}, },
pinnedBy: pinnedBy: data?.pinnedBy
data?.pinnedBy && data.pinnedBy[0] ? data.pinnedBy[0]?.id === userId
? { connect: { id: userId } } ? { connect: { id: userId } }
: { disconnect: { id: userId } }, : { disconnect: { id: userId } }
: undefined,
}, },
include: { include: {
tags: true, tags: true,

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