Compare commits

...

184 Commits

Author SHA1 Message Date
Anselm
9c8038ffb6 Release 2024-09-22 14:06:04 -07:00
Anselm
a524cd38a1 Don't use peerDeps for internal packages at all 2024-09-22 14:05:16 -07:00
Anselm
70960e917d Manually fix precise workspace dep versions 2024-09-22 13:53:45 -07:00
Anselm
a28d899e5c retroactively create minor changes 2024-09-22 13:43:07 -07:00
Anselm
20ef6474d4 Try forcing correct peerDep bumping 2024-09-22 13:42:11 -07:00
Anselm Eickhoff
6947593414 Merge pull request #326 from gardencmp/anselm-jazz-182
Auth refactor & Clerk integration
2024-09-22 13:11:47 -07:00
Anselm
23369dce80 Pre-release 2024-09-22 13:03:21 -07:00
Anselm
a7cd61ce75 Fix guide 2024-09-22 13:02:09 -07:00
Anselm
c702d632a2 Fix some auth state handling with logout and jazz-react 2024-09-22 12:14:06 -07:00
Anselm
9b90ae195c Add logout functionality to jazz-react (and example apps) 2024-09-22 11:50:05 -07:00
Anselm
7820232282 Add logOut to auth methods again 2024-09-22 11:37:35 -07:00
Anselm
32d588451a Mostly fix pet example 2024-09-22 11:04:13 -07:00
Anselm
ae56765efa Make password manager buildable 2024-09-22 10:18:44 -07:00
Anselm
467decfcce Fix e2e test issues with new context API 2024-09-22 10:12:19 -07:00
Anselm
2ab17d0569 Fix sherif lints 2024-09-22 09:54:07 -07:00
Anselm
543517f80a Some more merge work 2024-09-22 09:52:20 -07:00
Anselm
9ef0be665e Merge branch 'main' into anselm-jazz-182 2024-09-22 09:37:10 -07:00
Anselm
87ef6d5064 Pre-release 2024-09-22 09:06:01 -07:00
Anselm
e2ec51d3db Merge branch 'trishalim-jazz-311' 2024-09-22 08:50:17 -07:00
Anselm Eickhoff
566be392da Merge pull request #412 from gardencmp/trishalim-jazz-312
Fix footer overlaps side nav in docs
2024-09-22 08:47:08 -07:00
Anselm
7497ed2a7c Clean up nav related components and fix footer after botched merge 2024-09-22 07:16:36 -07:00
Anselm
13b0dfc38f Merge branch 'main' into trishalim-jazz-312 2024-09-22 07:09:52 -07:00
Anselm Eickhoff
1debe44cf1 Merge pull request #424 from gardencmp/feature/binarycostream-reconnection-test
test(BinaryCoStream): add a reconnection e2e test
2024-09-22 06:53:07 -07:00
Anselm Eickhoff
b737e14069 Merge pull request #411 from gardencmp/trishalim-jazz-311
Create separate pages for each section in the docs
2024-09-20 11:45:55 -07:00
Anselm
82fd148370 Add static params for packages 2024-09-20 10:58:12 -07:00
Guido D'Orsi
d0fc6dbc13 test(BinaryCoStrea): add a reconnection e2e test 2024-09-20 18:35:01 +02:00
Trisha Lim
f588c3f265 Move packages documentation to separate routes 2024-09-20 17:26:43 +01:00
Anselm Eickhoff
659e80bbf4 Merge pull request #356 from gardencmp/anselm-jazz-284
Design system setup
2024-09-20 16:15:50 +01:00
Anselm
3585e2acde Fix lint and dep errors 2024-09-20 07:44:13 -07:00
Anselm
98554523c8 Kind of start using components on the docs/guide page 2024-09-20 14:45:04 +01:00
Anselm
dbeaa35110 Use/extract components for mesh page 2024-09-20 14:30:11 +01:00
Anselm
61c719c728 Merge branch 'main' into anselm-jazz-284 2024-09-20 14:05:07 +01:00
Anselm Eickhoff
48fddecd30 Merge pull request #420 from gardencmp/trishalim-jazz-313 2024-09-20 10:57:49 +01:00
Trisha Lim
f5779077df Fix horizontal overflow on tablet in docs 2024-09-19 18:43:26 +01:00
Trisha Lim
5149fb6fbf Fix horizontal overflow on tablet in docs 2024-09-19 17:51:16 +01:00
Trisha Lim
dcc6134180 Clip text that is too long 2024-09-19 16:28:17 +01:00
Trisha Lim
ecb336829d Fix footer overlaps side nav in docs 2024-09-19 16:28:17 +01:00
Trisha Lim
2778f919a6 Use dynamic route for packages 2024-09-19 16:05:25 +01:00
Trisha Lim
ab6fcc7a7a Add metadata to each package page 2024-09-19 12:29:37 +01:00
Trisha Lim
aa284802ab Use Link instead of anchor tag 2024-09-19 11:40:15 +01:00
Trisha Lim
a6af56bc2e Add section for "Simple Public Sharing" 2024-09-19 11:36:29 +01:00
Anselm Eickhoff
751f0b4d10 Merge pull request #410 from gardencmp/feature/fix-playlist-invitation-add 2024-09-19 08:30:03 +01:00
Trisha Lim
a233eb6396 Remove sections that don't exist 2024-09-18 21:01:52 +01:00
Trisha Lim
c91d9b99be Move packages documentation to separate routes 2024-09-18 20:52:58 +01:00
Guido D'Orsi
a5b798a257 fix(musicPlayer): fix the playlist check on invitation 2024-09-18 21:48:44 +02:00
Anselm Eickhoff
18b71442ca Merge pull request #394 from gardencmp/gudorsi-jazz-300
fix(BinaryCoStream): set the stream content message as low priority in the WS outgoing channel
2024-09-18 17:36:52 +01:00
Guido D'Orsi
f350e902a8 changeset 2024-09-18 18:35:39 +02:00
Guido D'Orsi
38a6447887 fix(priority): group detection and only set binary costream as low 2024-09-18 18:29:27 +02:00
Anselm Eickhoff
39da70558b Merge pull request #408 from gardencmp/trishalim-jazz-310
Separate chat code example to 2 tabs
2024-09-18 16:50:34 +01:00
Anselm Eickhoff
73f62966ed Merge pull request #405 from gardencmp/trishalim-jazz-309
Change mono font to Commit Mono
2024-09-18 16:47:35 +01:00
Trisha Lim
c41e035b67 Change mono font to Commit Mono 2024-09-18 16:43:05 +01:00
Trisha Lim
f4c466ea30 Change mono font to IBM Plex Mono 2024-09-18 16:43:05 +01:00
Trisha Lim
91e9a267f0 Match accent color with Jazz logo 2024-09-18 16:33:53 +01:00
Trisha Lim
d1ec24a05b Dark mode styling 2024-09-18 16:28:38 +01:00
Guido D'Orsi
657159e034 chore(PeerState): sort attributes declaration 2024-09-18 17:20:41 +02:00
Guido D'Orsi
0327913e53 chore: comments 2024-09-18 17:19:06 +02:00
Trisha Lim
5ad9d652be Fix build, rewrite ChatCodeExample to CodeExampleTabs 2024-09-18 16:16:02 +01:00
Guido D'Orsi
3cde94a94b chore: fix sync.test.ts type errors 2024-09-18 16:59:20 +02:00
Guido D'Orsi
a7f036c71f Merge remote-tracking branch 'origin/main' into gudorsi-jazz-300 2024-09-18 16:58:21 +02:00
Guido D'Orsi
20b47ad8af feat: simpler priority system and extract content priority from headers 2024-09-18 16:55:05 +02:00
Trisha Lim
6f2eac383d Styling code area 2024-09-18 15:43:27 +01:00
Trisha Lim
5d40e83297 Design tabs for chat code example 2024-09-18 14:19:57 +01:00
Anselm Eickhoff
7721ccffaf Merge pull request #403 from gardencmp/JAZZ-308/check-example-app-urls
fix(examples): updated URLs for example apps
2024-09-17 14:24:56 +01:00
pax-k
aa7edc8e3f fix(examples): updated URLs for example apps 2024-09-17 16:23:33 +03:00
Anselm Eickhoff
bba1728988 Merge pull request #399 from gardencmp/JAZZ-305/integrate-test-coverage
feat: added test coverage
2024-09-17 09:16:24 +01:00
Guido D'Orsi
f1dff3e3fd test: fix sync.test.ts tests 2024-09-16 23:47:48 +02:00
Guido D'Orsi
d5604b9eb5 chore: generalize PriorityBasedMessageQueue 2024-09-16 23:40:16 +02:00
Guido D'Orsi
3acf61e2c3 feat: move the priority management from the websocket peer to the peer state 2024-09-16 23:37:57 +02:00
Guido D'Orsi
3a0d25d048 feat: extract PeerState and refactor it into a class 2024-09-16 23:37:57 +02:00
Guido D'Orsi
28720043a4 chore(cojson-transport-ws): add tests and split code 2024-09-16 23:37:57 +02:00
Guido D'Orsi
79491353da fix: fixes errors in sync due the extra push param 2024-09-16 23:37:57 +02:00
Guido D'Orsi
35eb8829ea feat(cojson-transport-ws): interleaved weighed round robin 2024-09-16 23:37:57 +02:00
Guido D'Orsi
5cd38d5974 fix(BinaryCoStream): set the stream content message as low priority in the WS outgoing stream 2024-09-16 23:37:57 +02:00
pax-k
30f1fa1557 feat: added test coverage 2024-09-16 20:48:18 +03:00
Anselm Eickhoff
fe035c3b3f Merge pull request #392 from gardencmp/feature/BinaryCoStream-e2e-ci+
chore: run e2e/BinaryCoStream tests on CI
2024-09-16 16:31:02 +01:00
Guido D'Orsi
1efe8ee6c7 chore: run e2e/BinaryCoStream tests on CI 2024-09-12 18:36:15 +02:00
Guido D'Orsi
f410a8540b fix: in the BinaryCoStream e2e test retry failed subscribes 2024-09-12 18:35:37 +02:00
Anselm Eickhoff
acb6249292 Merge pull request #385 from gardencmp/feature/sync-duration-test 2024-09-11 09:46:01 +01:00
Guido D'Orsi
77c38a1c4b chore(ci): remove BinaryCoStream from the CI tests 2024-09-10 18:14:11 +02:00
Guido D'Orsi
6e1d56a9b0 feat: add more size choices and reduce the default to 1KB 2024-09-10 18:14:11 +02:00
Guido D'Orsi
d10a7b9c76 test: e2e tests for the BinaryCoStream sync 2024-09-10 18:14:11 +02:00
Anselm Eickhoff
209f295399 Merge pull request #388 from gardencmp/feature/auth-laoding 2024-09-09 18:39:10 +01:00
Guido D'Orsi
cac2ec9aa1 changeset 2024-09-09 19:06:43 +02:00
Guido D'Orsi
30a9e7a94f fix(jazz-react): mark the auth as loading when authState is not ready 2024-09-09 19:05:52 +02:00
Anselm Eickhoff
af5adc37ca Merge pull request #386 from gardencmp/fix/music-player-example 2024-09-09 11:51:04 +01:00
Guido D'Orsi
af12226998 fix(musicPlayer): move the upload of example data outside of the initial migration 2024-09-09 12:24:27 +02:00
Anselm
6a147c2d28 Pre-release 2024-09-06 20:39:14 +01:00
Anselm Eickhoff
b8bf440f84 Merge pull request #384 from gardencmp/fix-lockfile 2024-09-06 17:31:58 +01:00
Anselm
c2b62a0fee Pre-release 2024-09-06 16:49:42 +01:00
Anselm
301458e713 Make anonymous auth work better 2024-09-06 16:48:22 +01:00
Guido D'Orsi
5198a249d1 fix: align deps 2024-09-06 16:51:46 +02:00
Guido D'Orsi
918322bc4a fix lockfile 2024-09-06 16:50:30 +02:00
Anselm Eickhoff
b66791d81a Merge pull request #383 from gardencmp/feature/monorepo-improvements
test(deepLoading): fix skipped test
2024-09-06 15:47:04 +01:00
Anselm Eickhoff
a2fbd9ed22 Merge pull request #334 from gardencmp/feature/music-player-example
feat(example): add a music player example
2024-09-06 15:34:17 +01:00
Guido D'Orsi
89111c5bf3 test(deepLoading): fix skipped test 2024-09-06 16:05:41 +02:00
Anselm
1a979b64b3 Implement guest auth 2024-09-05 18:37:24 +01:00
Anselm Eickhoff
d4a358d0f9 Merge pull request #382 from gardencmp/feature/monorepo-improvements 2024-09-05 16:53:43 +01:00
Guido D'Orsi
daf24d65f6 chore: fix or skip failing tests 2024-09-05 17:44:50 +02:00
Guido D'Orsi
9517cef183 chore: fix monorepo linting action 2024-09-05 17:38:17 +02:00
Guido D'Orsi
f70950cc82 feat(ci): run unit tests on PR 2024-09-05 17:17:53 +02:00
Guido D'Orsi
ec3dffa3e4 feat: add sherif to check monorepo dependencies 2024-09-05 17:17:35 +02:00
Guido D'Orsi
207bea3c1c tiny typo 2024-09-04 23:55:33 +02:00
Guido D'Orsi
fcae20d77c feat(musicPlayer): walkthrough until 3_actions 2024-09-04 23:54:22 +02:00
Guido D'Orsi
0a542941ad feat: add docs on the schema file 2024-09-04 23:54:06 +02:00
Guido D'Orsi
5dceef8c03 fix: avoid adding duplicate playlists when accepting 2024-09-04 23:54:06 +02:00
Guido D'Orsi
fb01eb42f1 fix: remove the example audio auto-delete 2024-09-04 23:54:06 +02:00
Guido D'Orsi
e1e3a8352e docs: update the README.md and cleanup the changelog 2024-09-04 23:54:06 +02:00
Guido D'Orsi
09678c4277 chore: merge jazz and main 2024-09-04 23:54:06 +02:00
Guido D'Orsi
5b83669368 feat: other UI improvements 2024-09-04 23:54:06 +02:00
Guido D'Orsi
30c8c922a3 feat: improve the click areas and add the Space keybinding 2024-09-04 23:54:06 +02:00
Guido D'Orsi
e05b327eb5 feat: player controls, example audio and ui fixes 2024-09-04 23:54:06 +02:00
Guido D'Orsi
06665cbbf7 feat: improve the add to playlist section nand invitation flow 2024-09-04 23:54:06 +02:00
Guido D'Orsi
c0425df2ee fix: make the playlist invite work 2024-09-04 23:54:06 +02:00
Guido D'Orsi
42cbef8063 feat(music-player): implement playlist page and sharing 2024-09-04 23:54:06 +02:00
Guido D'Orsi
d1abf06621 feat: improve the playing stability and clean up the code 2024-09-04 23:54:06 +02:00
Guido D'Orsi
1c00020859 feat: implement the basic interactions with the player (upload and play) 2024-09-04 23:54:06 +02:00
Guido D'Orsi
00dd9cea99 feat: setup the boilerplate for the musicPlayer example 2024-09-04 23:54:04 +02:00
Anselm Eickhoff
607cd0ab97 Merge pull request #367 from gardencmp/gudorsi-jazz-141 2024-09-04 21:06:05 +01:00
Anselm Eickhoff
9f65e56b21 Update forty-plants-kiss.md 2024-09-04 21:05:13 +01:00
Anselm Eickhoff
82c5d1bf5c Merge pull request #376 from gardencmp/JAZZ-295/implement-password-manager-demo 2024-09-04 16:49:49 +01:00
pax-k
deda3e571f fix(password-manager): tsconfig 2024-09-04 18:03:43 +03:00
Anselm Eickhoff
2d4039c5d2 Merge pull request #378 from gardencmp/JAZZ-296/data-in-inspector-flashes-into-view-then-disappears
fix(inspector): subscribe to latent covalues instead of loading them immediately
2024-09-04 14:24:52 +01:00
pax-k
63dd9190a2 chore: format 2024-09-04 16:16:33 +03:00
pax-k
3dfa630923 chore: cleanup 2024-09-04 16:08:08 +03:00
pax-k
63daf6af09 chore: changeset 2024-09-04 16:00:42 +03:00
pax-k
c85ccd96aa fix(inspector): subscribe to latent covalues instead of loading them immediately 2024-09-04 15:58:48 +03:00
Anselm
8b7b57fe2c Move newRandomSessionID to CryptoProvider 2024-09-04 11:41:02 +01:00
Guido D'Orsi
403b430ee4 chore: changeset 2024-09-03 18:34:04 +02:00
pax-k
f58845ef74 fix(password-manager): correct main script reference 2024-09-03 17:19:23 +03:00
pax-k
38fad35945 chore: password manager demo cleanup 2024-09-03 15:58:40 +03:00
pax-k
2533740a7c feat: password manager demo (wip) 2024-09-03 13:21:20 +03:00
Guido D'Orsi
109a7d6128 chore: use Effect.never to keep the server up, remove LocalNode comment 2024-09-03 11:45:10 +02:00
Anselm Eickhoff
ec1906e262 Merge pull request #368 from gardencmp/JAZZ-278/investigate-bug-when-assigning-null-values-to-corefs-in-applydiff 2024-09-03 09:24:46 +01:00
Anselm
ad40b883eb Pre-release 2024-09-02 17:29:47 +01:00
Anselm
1c64ae1bba First sketch of creating and finding unique CoMaps 2024-09-02 17:28:03 +01:00
pax-k
6f8028253d chore: changeset 2024-09-02 17:50:54 +03:00
pax-k
0704a76006 fix: handle null values for co.refs 2024-09-02 16:49:53 +03:00
Anselm Eickhoff
ab93a0b679 Fix #353 2024-09-02 12:11:24 +01:00
Guido D'Orsi
ed85560547 feat: rename command and add persistence 2024-09-02 11:36:52 +02:00
Guido D'Orsi
a242adf3b3 docs: update cojson-simple-sync command 2024-09-01 17:12:53 +02:00
Guido D'Orsi
1a9c7ecefd feat(jazz-run): add a command to spin a local sync server 2024-09-01 17:10:29 +02:00
Anselm Eickhoff
aded528a27 Merge pull request #357 from gardencmp/gudorsi-jazz-281 2024-08-31 17:50:00 +01:00
Guido D'Orsi
152ae9865e chore(ci): debug error with artifacts 2024-08-31 18:21:24 +02:00
Guido D'Orsi
8bd92b44f5 chore(ci): increase expect timeout to 15000 on CI 2024-08-31 17:06:11 +02:00
Guido D'Orsi
8d15e04fd0 chore(ci): fix Install Playwright Browsers 2024-08-30 19:41:07 +02:00
Guido D'Orsi
b7f3ece0f1 chore: fix action indentation 2024-08-30 19:38:32 +02:00
Guido D'Orsi
4c94ae3da2 test(pets): test incoming reaction 2024-08-30 19:34:14 +02:00
Guido D'Orsi
cd23ce0a51 feat: github action for playwright tests 2024-08-30 19:19:07 +02:00
Guido D'Orsi
8538036af7 test(pets): use pom 2024-08-30 19:13:35 +02:00
Anselm
6ee7133924 Homepage mostly extracted 2024-08-30 16:23:28 +01:00
Anselm
4fa19ece52 Pull nav into design system 2024-08-29 19:22:21 +01:00
Anselm
875ac4b84f An attempt to pull out copy and make the landign page tsx again 2024-08-29 19:09:53 +01:00
Anselm
346e797447 Pull out more stuff 2024-08-29 18:51:17 +01:00
Anselm
6ce20517bc Pre-release 2024-08-29 14:38:27 +01:00
Anselm
9509ceb975 Make me context optional 2024-08-29 14:37:52 +01:00
Anselm
bcec3be423 Pre-release 2024-08-29 14:23:07 +01:00
Anselm
e3958d1609 Rest of clerk & auth implementation + some fixes and patches 2024-08-29 14:21:22 +01:00
Anselm
7f6d778301 First extraction 🏗️ 2024-08-29 11:20:17 +01:00
Guido D'Orsi
40287a5682 feat(pets): add an e2e test suite 2024-08-29 02:26:28 +02:00
Anselm
bcfe4b794e Basic connection to design system 2024-08-28 19:03:51 +01:00
Anselm
7a27193ceb Include design system in homepage pnpm workspace 2024-08-28 18:36:36 +01:00
Anselm
6db14cefa0 Merge remote-tracking branch 'sammii-design-system/main' into anselm-jazz-284 2024-08-28 18:33:32 +01:00
Anselm
b57e1a64ac Move into subfolders in preparation of move into monorepo 2024-08-28 18:29:38 +01:00
Sammii
a1b83cceea whipping up a design system 2024-08-28 17:59:39 +01:00
Anselm
0fc7291178 Make it mostly work 2024-08-28 17:39:48 +01:00
Sammii
cd29438304 create next app 2024-08-28 15:01:15 +01:00
Samantha Haylock
7695a817ca first commit 2024-08-27 10:41:32 +01:00
Anselm
51d1cc677b Refactor all browser auth methods to new API 2024-08-23 15:56:09 +01:00
Anselm
0cf7a7aa85 Merge branch 'main' into anselm-jazz-182 2024-08-23 11:20:49 +01:00
Anselm Eickhoff
2ddce1a2de Merge pull request #327 from gardencmp/gudorsi-jazz-254 2024-08-22 19:36:30 +01:00
Guido D'Orsi
49a8b54a8a Add changesets 2024-08-22 20:33:51 +02:00
Anselm Eickhoff
04b15c7d4a Merge pull request #345 from gardencmp/gudorsi-jazz-261 2024-08-22 18:37:37 +01:00
Guido D'Orsi
5909e7e894 fix(pets): set the ownership of reactions to the write group 2024-08-22 19:25:30 +02:00
Anselm Eickhoff
7a3d519970 Merge pull request #337 from gardencmp/feat/jazz-255-loadasblob
fix(BinaryCoStream): resolve the loadAsBlob call only when the stream id ended
2024-08-22 15:00:13 +01:00
Anselm
35bbcd94e6 Add changesets 2024-08-22 14:59:40 +01:00
Anselm Eickhoff
f6629b2b58 Merge pull request #336 from gardencmp/anselm-jazz-264
Adopt neverthrow throughout cojson
2024-08-22 14:34:45 +01:00
Anselm Eickhoff
311ed74709 Delete oldExamples directory 2024-08-22 13:45:57 +01:00
Anselm Eickhoff
c86301fcfd Delete oldPackages/jazz-browser-auth0 directory 2024-08-22 13:45:47 +01:00
Guido D'Orsi
627e04151d fix(CoMapInit): type validation on falsy values for required refs 2024-08-22 02:35:58 +02:00
Anselm Eickhoff
4cd68c1930 minimal inspector readme 2024-08-21 11:20:39 +01:00
Guido D'Orsi
f1f3607e28 test(BinaryCoStream): add tests for loadAsBlob 2024-08-20 19:46:13 +02:00
Guido D'Orsi
7b9f503b9e test(coStream): add tests for isBinaryStreamEnded 2024-08-20 19:35:11 +02:00
Guido D'Orsi
a18f44399c fix(BinaryCoStream): resolve the loadAsBlob call only when the stream is ended 2024-08-20 19:20:36 +02:00
Anselm
0503479fcf Auth refactor and clerk WIP 2024-08-19 10:48:01 +01:00
418 changed files with 14152 additions and 8412 deletions

View File

@@ -9,6 +9,8 @@
"jazz-tools",
"jazz-browser",
"jazz-browser-media-images",
"jazz-browser-auth-clerk",
"jazz-react-auth-clerk",
"jazz-react",
"jazz-nodejs",
"jazz-run",
@@ -20,5 +22,8 @@
"access": "public",
"baseBranch": "main",
"updateInternalDependencies": "patch",
"ignore": []
"ignore": [],
"___experimentalUnsafeOptions_WILL_CHANGE_IN_PATCH": {
"onlyUpdatePeerDependentsWhenOutOfRange": true
}
}

View File

@@ -17,15 +17,32 @@ jobs:
with:
submodules: true
- uses: pnpm/action-setup@v2
with:
version: 8
- name: Enable corepack
run: corepack enable
- uses: actions/setup-node@v3
- name: Install Node.js
uses: actions/setup-node@v3
with:
node-version: 16
node-version-file: '.node-version'
cache: 'pnpm'
- name: Get pnpm store directory
shell: bash
run: |
echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV
- uses: actions/cache@v3
name: Setup pnpm cache
with:
path: ${{ env.STORE_PATH }}
key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}
restore-keys: |
${{ runner.os }}-pnpm-store-
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2

21
.github/workflows/monorepo-linting.yml vendored Normal file
View File

@@ -0,0 +1,21 @@
name: Monorepo linting
on:
pull_request:
types: [opened, synchronize, reopened]
jobs:
monorepo-linting:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Install Node.js
uses: actions/setup-node@v3
with:
node-version-file: '.node-version'
- name: Run sherif
run: npx sherif@1.0.0

64
.github/workflows/playwright.yml vendored Normal file
View File

@@ -0,0 +1,64 @@
name: Playwright Tests
on:
push:
branches: ["main"]
pull_request:
types: [opened, synchronize, reopened]
jobs:
test:
timeout-minutes: 60
runs-on: ubuntu-latest
strategy:
matrix:
project: ["e2e/BinaryCoStream", "examples/pets"]
steps:
- uses: actions/checkout@v3
with:
submodules: true
- name: Enable corepack
run: corepack enable
- name: Install Node.js
uses: actions/setup-node@v3
with:
node-version-file: '.node-version'
cache: 'pnpm'
- name: Get pnpm store directory
shell: bash
run: |
echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV
- uses: actions/cache@v3
name: Setup pnpm cache
with:
path: ${{ env.STORE_PATH }}
key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}
restore-keys: |
${{ runner.os }}-pnpm-store-
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Pnpm Build
run: pnpm turbo build;
working-directory: ./${{ matrix.project }}
- name: Install Playwright Browsers
run: pnpm exec playwright install --with-deps
working-directory: ./${{ matrix.project }}
- name: Run Playwright tests
run: pnpm exec playwright test
working-directory: ./${{ matrix.project }}
- uses: actions/upload-artifact@v4
if: failure()
with:
name: ${{ hashFiles(format('{0}/package.json', matrix.project)) }}-playwright-report
path: ./${{ matrix.project }}/playwright-report/
retention-days: 30

47
.github/workflows/unit-test.yml vendored Normal file
View File

@@ -0,0 +1,47 @@
name: Unit Tests
on:
pull_request:
types: [opened, synchronize, reopened]
push:
branches:
- 'main'
jobs:
unit-tests:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Enable corepack
run: corepack enable
- name: Install Node.js
uses: actions/setup-node@v3
with:
node-version-file: '.node-version'
cache: 'pnpm'
- name: Get pnpm store directory
shell: bash
run: |
echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV
- uses: actions/cache@v3
name: Setup pnpm cache
with:
path: ${{ env.STORE_PATH }}
key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}
restore-keys: |
${{ runner.os }}-pnpm-store-
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Pnpm Build
run: pnpm turbo build;
- name: Unit Tests
run: pnpm test

3
.gitignore vendored
View File

@@ -3,4 +3,5 @@ yarn-error.log
lerna-debug.log
docsTmp
.DS_Store
.turbo
.turbo
coverage

1
.node-version Normal file
View File

@@ -0,0 +1 @@
20

View File

@@ -23,5 +23,8 @@ dist-ssr
*.sln
*.sw?
.env
TwitAllTwitsCreatorCredentials.json
sync-db/
/test-results/
/playwright-report/
/blob-report/
/playwright/.cache/

View File

@@ -0,0 +1,34 @@
{
"name": "@jazz-e2e/binarycostream",
"private": true,
"version": "0.0.81",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview",
"test": "playwright test",
"test:ui": "playwright test --ui"
},
"lint-staged": {
"*.{js,jsx,mdx,json}": "prettier --write"
},
"dependencies": {
"cojson": "workspace:0.7.35-guest-auth.5",
"hash-slash": "workspace:0.2.0",
"is-ci": "^3.0.1",
"jazz-react": "workspace:0.7.35-guest-auth.6",
"jazz-tools": "workspace:0.7.35-guest-auth.6",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"@playwright/test": "^1.46.1",
"@types/node": "^22.5.1",
"@types/react": "^18.2.19",
"@types/react-dom": "^18.2.7",
"@vitejs/plugin-react-swc": "^3.3.2",
"typescript": "^5.3.3",
"vite": "^5.0.10"
}
}

View File

@@ -0,0 +1,49 @@
import { defineConfig, devices } from "@playwright/test";
import isCI from "is-ci";
/**
* Read environment variables from file.
* https://github.com/motdotla/dotenv
*/
// import dotenv from 'dotenv';
// dotenv.config({ path: path.resolve(__dirname, '.env') });
/**
* See https://playwright.dev/docs/test-configuration.
*/
export default defineConfig({
testDir: "./tests",
/* Run tests in files in parallel */
fullyParallel: true,
/* Fail the build on CI if you accidentally left test.only in the source code. */
forbidOnly: isCI,
/* Retry on CI only */
retries: isCI ? 2 : 0,
/* Opt out of parallel tests on CI. */
workers: isCI ? 1 : undefined,
/* Reporter to use. See https://playwright.dev/docs/test-reporters */
reporter: "html",
/* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
use: {
/* Base URL to use in actions like `await page.goto('/')`. */
baseURL: isCI ? "http://localhost:4173/" : "http://localhost:5173",
/* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
trace: "on-first-retry",
},
/* Configure projects for major browsers */
projects: [
{
name: "chromium",
use: { ...devices["Desktop Chrome"] },
},
],
/* Run your local dev server before starting the tests */
webServer: isCI ? {
command: "pnpm preview",
url: "http://localhost:4173/",
} : undefined,
});

View File

@@ -0,0 +1,42 @@
import { Account, BinaryCoStream, ID } from "jazz-tools";
import { useEffect } from "react";
import { useAccount, useCoState } from "./jazz";
import { UploadedFile } from "./schema";
import { waitForCoValue } from "./lib/waitForCoValue";
async function getUploadedFile(
me: Account,
uploadedFileId: ID<UploadedFile>) {
const uploadedFile = await waitForCoValue(UploadedFile, uploadedFileId, me, Boolean, {})
uploadedFile.coMapDownloaded = true;
await BinaryCoStream.loadAsBlob(uploadedFile._refs.file.id, me);
return uploadedFile;
}
export function DownloaderPeer(props: { testCoMapId: ID<UploadedFile> }) {
const account = useAccount();
const testCoMap = useCoState(UploadedFile, props.testCoMapId, {});
useEffect(() => {
getUploadedFile(account.me, props.testCoMapId).then(value => {
value.syncCompleted = true;
});
}, []);
return (
<>
<h1>Downloader Peer</h1>
<div>Fetching: {props.testCoMapId}</div>
<div data-testid="result">
Covalue: {Boolean(testCoMap?.id) ? "Downloaded" : "Not Downloaded"}
</div>
<div data-testid="result">
File:{" "}
{Boolean(testCoMap?.syncCompleted) ? "Downloaded" : "Not Downloaded"}
</div>
</>
);
}

View File

@@ -0,0 +1,86 @@
import { ID } from "jazz-tools";
import { useEffect, useState } from "react";
import { useAccount, useCoState } from "./jazz";
import { createCredentiallessIframe } from "./lib/createCredentiallessIframe";
import { generateTestFile } from "./lib/generateTestFile";
import { getDownloaderPeerUrl } from "./lib/getDownloaderPeerUrl";
import { UploadedFile } from "./schema";
import { waitForCoValue } from "./lib/waitForCoValue";
import { getDefaultFileSize, getIsAutoUpload } from "./lib/searchParams";
import { BytesRadioGroup } from "./lib/BytesRadioGroup";
export function UploaderPeer() {
const account = useAccount();
const [uploadedFileId, setUploadedFileId] = useState<
ID<UploadedFile> | undefined
>(undefined);
const [syncDuration, setSyncDuration] = useState<number | null>(null);
const [bytes, setBytes] = useState(getDefaultFileSize);
const testFile = useCoState(UploadedFile, uploadedFileId, {});
async function uploadTestFile() {
if (!account) return;
// Mark the sync start
performance.mark("sync-start");
const file = await generateTestFile(account.me, bytes);
// Create a credential-less iframe to spawn the downloader peer
const iframe = createCredentiallessIframe(getDownloaderPeerUrl(file));
document.body.appendChild(iframe);
setSyncDuration(null);
setUploadedFileId(file.id);
// The downloader peer will set the syncCompleted to true when the download is complete.
// We use this to measure the sync duration.
await waitForCoValue(
UploadedFile,
file.id,
account.me,
(value) => value.syncCompleted,
{}
);
iframe.remove();
// Calculate the sync duration
performance.mark("sync-end");
const measure = performance.measure("sync", "sync-start", "sync-end");
setSyncDuration(measure.duration);
}
useEffect(() => {
if (getIsAutoUpload()) {
uploadTestFile();
}
}, []);
return (
<>
<BytesRadioGroup selectedValue={bytes} onChange={setBytes} />
<button onClick={uploadTestFile}>Upload Test File</button>
{uploadedFileId && <div>{uploadedFileId}</div>}
{syncDuration && (
<div data-testid="sync-duration">
Sync Duration: {syncDuration.toFixed(2)}ms
</div>
)}
{uploadedFileId && (
<div data-testid="result">
Sync Completed: {String(Boolean(syncDuration))}
</div>
)}
{testFile?.coMapDownloaded && (
<div data-testid="co-map-downloaded">
CoMap synced!
</div>
)}
</>
);
}

View File

@@ -0,0 +1,24 @@
import React from "react";
import ReactDOM from "react-dom/client";
import { DownloaderPeer } from "./DownloaderPeer";
import { UploaderPeer } from "./UploaderPeer";
import { getValueId } from "./lib/searchParams";
import { AuthAndJazz } from "./jazz";
function Main() {
const valueId = getValueId();
if (valueId) {
return <DownloaderPeer testCoMapId={valueId} />;
}
return <UploaderPeer />;
}
ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<AuthAndJazz>
<Main />
</AuthAndJazz>
</React.StrictMode>,
);

View File

@@ -0,0 +1,28 @@
import { createJazzReactApp } from "jazz-react";
import { getValueId } from "./lib/searchParams";
import { ephemeralCredentialsAuth } from "jazz-tools";
import { useState } from "react";
const key = getValueId()
? `downloader-e2e@jazz.tools`
: `uploader-e2e@jazz.tools`;
const localSync = new URLSearchParams(location.search).has("localSync");
const Jazz = createJazzReactApp();
export const { useAccount, useCoState } = Jazz;
export function AuthAndJazz({ children }: { children: React.ReactNode }) {
const [ephemeralAuth] = useState(ephemeralCredentialsAuth())
return (
<Jazz.Provider auth={ephemeralAuth} peer={
localSync
? `ws://localhost:4200?key=${key}`
: `wss://mesh.jazz.tools/?key=${key}`
}>
{children}
</Jazz.Provider>
);
}

View File

@@ -0,0 +1,67 @@
export function BytesRadioGroup(props: {
selectedValue: number;
onChange: (value: number) => void;
}) {
return (
<p>
<BytesRadioInput
label="1KB"
value={1e3}
selectedValue={props.selectedValue}
onChange={props.onChange} />
<BytesRadioInput
label="10KB"
value={1e4}
selectedValue={props.selectedValue}
onChange={props.onChange} />
<BytesRadioInput
label="100KB"
value={1e5}
selectedValue={props.selectedValue}
onChange={props.onChange} />
<BytesRadioInput
label="150KB"
value={1e5 + 5e4}
selectedValue={props.selectedValue}
onChange={props.onChange} />
<BytesRadioInput
label="200KB"
value={2e6}
selectedValue={props.selectedValue}
onChange={props.onChange} />
<BytesRadioInput
label="500KB"
value={5e6}
selectedValue={props.selectedValue}
onChange={props.onChange} />
<BytesRadioInput
label="1MB"
value={1e6}
selectedValue={props.selectedValue}
onChange={props.onChange} />
<BytesRadioInput
label="10MB"
value={1e7}
selectedValue={props.selectedValue}
onChange={props.onChange} />
</p>
);
}
function BytesRadioInput(props: {
label: string;
value: number;
selectedValue: number;
onChange: (value: number) => void;
}) {
return (
<label>
<input
type="radio"
name="bytes"
value={props.value}
checked={props.value === props.selectedValue}
onChange={() => props.onChange(props.value)} />
{props.label}
</label>
);
}

View File

@@ -0,0 +1,21 @@
/**
* Creates a credentialess iframe that can be used to test the sync
* in an isolated environment. (no storage sharing)
*
* see: https://developer.mozilla.org/en-US/docs/Web/Security/IFrame_credentialless
*/
export function createCredentiallessIframe(url: string) {
const iframe = document.createElement("iframe");
// @ts-ignore
iframe.credentialless = true;
iframe.src = url;
iframe.style.width = "300px";
iframe.style.height = "300px";
iframe.style.border = "1px solid black";
iframe.style.position = "absolute";
iframe.style.top = "0";
iframe.style.right = "0";
iframe.setAttribute("data-testid", "downloader-peer");
return iframe;
}

View File

@@ -0,0 +1,27 @@
import { Account, Group, BinaryCoStream } from "jazz-tools";
import { UploadedFile } from "../schema";
export async function generateTestFile(me: Account, bytes: number) {
const group = Group.create({ owner: me });
group.addMember("everyone", "writer");
const ownership = { owner: group };
const testFile = UploadedFile.create(
{
file: await BinaryCoStream.createFromBlob(
new Blob(['1'.repeat(bytes)], { type: 'image/png' }),
ownership
),
syncCompleted: false,
coMapDownloaded: false,
},
ownership
);
const url = new URL(window.location.href);
url.searchParams.set("valueId", testFile.id);
return testFile;
}

View File

@@ -0,0 +1,8 @@
import { UploadedFile } from "src/schema";
export function getDownloaderPeerUrl(value: UploadedFile) {
const url = new URL(window.location.href);
url.searchParams.set("valueId", value.id);
return url.toString();
}

View File

@@ -0,0 +1,14 @@
import { ID } from "jazz-tools";
import { UploadedFile } from "../schema";
export function getValueId() {
return new URLSearchParams(location.search).get("valueId") as ID<UploadedFile> | undefined ?? undefined;
}
export function getIsAutoUpload() {
return new URLSearchParams(location.search).has("auto");
}
export function getDefaultFileSize() {
return parseInt(new URLSearchParams(location.search).get("fileSize") ?? 1e3.toString());
}

View File

@@ -0,0 +1,39 @@
import {
Account,
CoValue,
CoValueClass,
DepthsIn,
ID,
subscribeToCoValue,
} from "jazz-tools";
export function waitForCoValue<T extends CoValue>(
coMap: CoValueClass<T>,
valueId: ID<T>,
account: Account,
predicate: (value: T) => boolean,
depth: DepthsIn<T>
) {
return new Promise<T>((resolve) => {
function subscribe() {
const unsubscribe = subscribeToCoValue(
coMap,
valueId,
account,
depth,
(value) => {
if (predicate(value)) {
resolve(value);
unsubscribe();
}
},
() => {
unsubscribe();
setTimeout(subscribe, 100);
}
);
}
subscribe();
});
}

View File

@@ -0,0 +1,7 @@
import { BinaryCoStream, co, CoMap } from "jazz-tools";
export class UploadedFile extends CoMap {
file = co.ref(BinaryCoStream);
syncCompleted = co.boolean;
coMapDownloaded = co.boolean;
}

View File

@@ -0,0 +1,36 @@
import { test, expect } from "@playwright/test";
import { setTimeout } from "node:timers/promises";
test.describe("BinaryCoStream - Sync", () => {
test("should sync a file between the two peers", async ({ page }) => {
await page.goto("/");
await page.getByRole("button", { name: "Upload Test File" }).click();
await page.getByTestId("sync-duration").waitFor();
await expect(page.getByTestId("result")).toHaveText("Sync Completed: true");
});
test("should handle reconnections", async ({ page, browser }) => {
const context = browser.contexts()[0];
await page.goto("/?fileSize=" + 1e6); // 1MB file
await page.getByRole("button", { name: "Upload Test File" }).click();
// Wait for the coMapDonwloaded signal to ensure that the iframe is loaded
await page.getByTestId("co-map-downloaded").waitFor();
await context.setOffline(true);
// Wait for the ping system to detect the offline state
await setTimeout(10000);
await context.setOffline(false);
// Wait for the sync to complete
await page.getByTestId("sync-duration").waitFor();
await expect(page.getByTestId("result")).toHaveText("Sync Completed: true");
});
});

View File

@@ -19,11 +19,7 @@
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}
"baseUrl": "."
},
"include": ["src"],
"references": [{ "path": "./tsconfig.node.json" }]
}

View File

@@ -1,15 +1,9 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react-swc'
import path from "path";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
},
},
build: {
minify: false
}

1
examples/chat-clerk/.env Normal file
View File

@@ -0,0 +1 @@
VITE_CLERK_PUBLISHABLE_KEY=pk_test_ZXZpZGVudC1kYW5lLTg5LmNsZXJrLmFjY291bnRzLmRldiQ

View File

@@ -9,10 +9,5 @@ module.exports = {
ignorePatterns: ['dist', '.eslintrc.cjs'],
parser: '@typescript-eslint/parser',
plugins: ['react-refresh'],
rules: {
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true },
],
},
rules: {},
}

View File

@@ -0,0 +1,790 @@
# jazz-example-chat
## 0.0.80
### Patch Changes
- bcec3be: Implement Clerk auth method + example
- Updated dependencies [6a147c2]
- Updated dependencies [ad40b88]
- Updated dependencies [23369dc]
- Updated dependencies [c2b62a0]
- Updated dependencies [bcec3be]
- Updated dependencies [1a979b6]
- Updated dependencies [bcec3be]
- Updated dependencies [6ce2051]
- cojson@0.8.0
- jazz-tools@0.8.0
- jazz-react@0.8.0
- jazz-react-auth-clerk@0.8.0
## 0.0.80-guest-auth.6
### Patch Changes
- Updated dependencies
- jazz-react@0.7.35-guest-auth.6
- jazz-tools@0.7.35-guest-auth.6
- jazz-react-auth-clerk@0.7.35-guest-auth.6
## 0.0.80-guest-auth.5
### Patch Changes
- Updated dependencies
- cojson@0.7.35-guest-auth.5
- jazz-react@0.7.35-guest-auth.5
- jazz-react-auth-clerk@0.7.35-guest-auth.5
- jazz-tools@0.7.35-guest-auth.5
## 0.0.80-guest-auth.4
### Patch Changes
- Updated dependencies
- jazz-react@0.7.35-guest-auth.4
- jazz-tools@0.7.35-guest-auth.4
- jazz-react-auth-clerk@0.7.35-guest-auth.4
## 0.0.80-guest-auth.3
### Patch Changes
- Updated dependencies
- jazz-react@0.7.35-guest-auth.3
- jazz-tools@0.7.35-guest-auth.3
- jazz-react-auth-clerk@0.7.33-guest-auth.3
## 0.0.80-unique.2
### Patch Changes
- Updated dependencies
- jazz-tools@0.7.35-unique.2
- cojson@0.7.35-unique.2
- jazz-react@0.7.35-unique.2
- jazz-react-auth-clerk@0.7.33-unique.2
## 0.0.80-new-auth.1
### Patch Changes
- Updated dependencies
- jazz-react@0.7.35-new-auth.1
- jazz-react-auth-clerk@0.7.33-new-auth.1
## 0.0.80-new-auth.0
### Patch Changes
- Implement Clerk auth method + example
- Updated dependencies
- Updated dependencies
- jazz-react-auth-clerk@0.7.33-new-auth.0
- jazz-react@0.7.35-new-auth.0
- jazz-tools@0.7.35-new-auth.0
## 0.0.79
### Patch Changes
- Updated dependencies
- jazz-tools@0.7.32
- jazz-react@0.7.32
## 0.0.78
### Patch Changes
- Updated dependencies
- cojson@0.7.31
- jazz-react@0.7.31
- jazz-tools@0.7.31
## 0.0.77
### Patch Changes
- jazz-react@0.7.30
## 0.0.76
### Patch Changes
- Updated dependencies
- cojson@0.7.29
- jazz-react@0.7.29
- jazz-tools@0.7.29
## 0.0.75
### Patch Changes
- Updated dependencies
- cojson@0.7.28
- jazz-react@0.7.28
- jazz-tools@0.7.28
## 0.0.74
### Patch Changes
- jazz-react@0.7.27
## 0.0.73
### Patch Changes
- Updated dependencies
- cojson@0.7.26
- jazz-react@0.7.26
- jazz-tools@0.7.26
## 0.0.72
### Patch Changes
- Updated dependencies
- jazz-tools@0.7.25
- jazz-react@0.7.25
## 0.0.71
### Patch Changes
- Updated dependencies
- jazz-tools@0.7.24
- jazz-react@0.7.24
## 0.0.70
### Patch Changes
- Updated dependencies
- cojson@0.7.23
- jazz-react@0.7.23
- jazz-tools@0.7.23
## 0.0.69
### Patch Changes
- jazz-react@0.7.22
## 0.0.68
### Patch Changes
- Updated dependencies
- jazz-tools@0.7.21
- jazz-react@0.7.21
## 0.0.67
### Patch Changes
- Updated dependencies
- jazz-tools@0.7.20
- jazz-react@0.7.20
## 0.0.66
### Patch Changes
- Updated dependencies
- jazz-tools@0.7.19
- jazz-react@0.7.19
## 0.0.65
### Patch Changes
- Updated dependencies
- cojson@0.7.18
- jazz-react@0.7.18
- jazz-tools@0.7.18
## 0.0.64
### Patch Changes
- Updated dependencies
- cojson@0.7.17
- jazz-react@0.7.17
- jazz-tools@0.7.17
## 0.0.63
### Patch Changes
- Updated dependencies
- jazz-tools@0.7.16
- jazz-react@0.7.16
## 0.0.62
### Patch Changes
- Updated dependencies
- jazz-react@0.7.15
## 0.0.61
### Patch Changes
- Updated dependencies
- cojson@0.7.14
- jazz-tools@0.7.14
- jazz-react@0.7.14
## 0.0.60
### Patch Changes
- Updated dependencies
- jazz-tools@0.7.13
- jazz-react@0.7.13
## 0.0.59
### Patch Changes
- Updated dependencies
- jazz-tools@0.7.12
- jazz-react@0.7.12
## 0.0.58
### Patch Changes
- Updated dependencies
- cojson@0.7.11
- jazz-react@0.7.11
- jazz-tools@0.7.11
## 0.0.57
### Patch Changes
- Updated dependencies
- cojson@0.7.10
- jazz-react@0.7.10
- jazz-tools@0.7.10
## 0.0.56
### Patch Changes
- Updated dependencies
- cojson@0.7.9
- jazz-react@0.7.9
- jazz-tools@0.7.9
## 0.0.55
### Patch Changes
- Updated dependencies
- jazz-tools@0.7.8
- jazz-react@0.7.8
## 0.0.54
### Patch Changes
- Updated dependencies [9fdc91c]
- jazz-react@0.7.7
## 0.0.53
### Patch Changes
- Updated dependencies
- jazz-tools@0.7.6
- jazz-react@0.7.6
## 0.0.52
### Patch Changes
- Updated dependencies
- jazz-react@0.7.5
## 0.0.51
### Patch Changes
- Updated dependencies
- jazz-react@0.7.4
## 0.0.50
### Patch Changes
- Updated dependencies
- jazz-tools@0.7.3
- jazz-react@0.7.3
## 0.0.49
### Patch Changes
- Updated dependencies
- jazz-react@0.7.2
## 0.0.48
### Patch Changes
- Updated dependencies
- jazz-tools@0.7.1
- jazz-react@0.7.1
## 0.0.47
### Patch Changes
- Updated dependencies [8636319]
- Updated dependencies [1a35307]
- Updated dependencies [8636319]
- Updated dependencies [1a35307]
- Updated dependencies [96c494f]
- Updated dependencies [59c18c3]
- Updated dependencies [19f52b7]
- Updated dependencies [8636319]
- Updated dependencies [1a35307]
- Updated dependencies [d8fe2b1]
- Updated dependencies [19004b4]
- Updated dependencies [a78f168]
- Updated dependencies [1200aae]
- Updated dependencies [60d5ca2]
- Updated dependencies [52675c9]
- Updated dependencies [129e2c1]
- Updated dependencies [6d49e9b]
- Updated dependencies [1cfa279]
- Updated dependencies [704af7d]
- Updated dependencies [e97f730]
- Updated dependencies [1a35307]
- Updated dependencies [460478f]
- Updated dependencies [6b0418f]
- Updated dependencies [e299c3e]
- Updated dependencies [ed5643a]
- Updated dependencies [bde684f]
- Updated dependencies [bf0f8ec]
- Updated dependencies [c4151fc]
- Updated dependencies [63374cc]
- Updated dependencies [8636319]
- Updated dependencies [01ac646]
- Updated dependencies [a5e68a4]
- Updated dependencies [8636319]
- Updated dependencies [952982e]
- Updated dependencies [1a35307]
- Updated dependencies [5fa277c]
- Updated dependencies [60d5ca2]
- Updated dependencies [21771c4]
- Updated dependencies [77c2b56]
- Updated dependencies [63374cc]
- Updated dependencies [d2e03ff]
- Updated dependencies [354bdcd]
- Updated dependencies [ece35b3]
- Updated dependencies [60d5ca2]
- Updated dependencies [69ac514]
- Updated dependencies [f8a5c46]
- Updated dependencies [f0f6f1b]
- Updated dependencies [e5eed5b]
- Updated dependencies [1a44f87]
- Updated dependencies [627d895]
- Updated dependencies [1200aae]
- Updated dependencies [63374cc]
- Updated dependencies [ece35b3]
- Updated dependencies [38d4410]
- Updated dependencies [85d2b62]
- Updated dependencies [fd86c11]
- Updated dependencies [52675c9]
- jazz-tools@0.7.0
- cojson@0.7.0
- jazz-react@0.7.0
- hash-slash@0.2.0
## 0.0.47-alpha.42
### Patch Changes
- Updated dependencies
- jazz-tools@0.7.0-alpha.42
- cojson@0.7.0-alpha.42
- jazz-react@0.7.0-alpha.42
## 0.0.47-alpha.41
### Patch Changes
- jazz-tools@0.7.0-alpha.41
- jazz-react@0.7.0-alpha.41
## 0.0.47-alpha.40
### Patch Changes
- Updated dependencies
- jazz-react@0.7.0-alpha.40
## 0.0.47-alpha.39
### Patch Changes
- Updated dependencies
- cojson@0.7.0-alpha.39
- jazz-react@0.7.0-alpha.39
- jazz-tools@0.7.0-alpha.39
## 0.0.47-alpha.38
### Patch Changes
- Updated dependencies
- Updated dependencies
- Updated dependencies
- Updated dependencies
- Updated dependencies
- jazz-tools@0.7.0-alpha.38
- jazz-react@0.7.0-alpha.38
- cojson@0.7.0-alpha.38
## 0.0.47-alpha.37
### Patch Changes
- Updated dependencies
- jazz-react@0.7.0-alpha.37
- cojson@0.7.0-alpha.37
- jazz-tools@0.7.0-alpha.37
## 0.0.47-alpha.36
### Patch Changes
- Updated dependencies [1a35307]
- Updated dependencies [1a35307]
- Updated dependencies [1a35307]
- Updated dependencies [1a35307]
- Updated dependencies [6b0418f]
- Updated dependencies [1a35307]
- cojson@0.7.0-alpha.36
- jazz-tools@0.7.0-alpha.36
- jazz-react@0.7.0-alpha.36
## 0.0.47-alpha.35
### Patch Changes
- Updated dependencies
- Updated dependencies
- cojson@0.7.0-alpha.35
- jazz-tools@0.7.0-alpha.35
- jazz-react@0.7.0-alpha.35
## 0.0.47-alpha.34
### Patch Changes
- Updated dependencies
- jazz-tools@0.7.0-alpha.34
- jazz-react@0.7.0-alpha.34
## 0.0.47-alpha.33
### Patch Changes
- Updated dependencies
- jazz-react@0.7.0-alpha.33
## 0.0.47-alpha.32
### Patch Changes
- Updated dependencies
- Updated dependencies
- Updated dependencies
- hash-slash@0.2.0-alpha.3
- jazz-tools@0.7.0-alpha.32
- jazz-react@0.7.0-alpha.32
## 0.0.47-alpha.31
### Patch Changes
- Updated dependencies
- jazz-tools@0.7.0-alpha.31
- jazz-react@0.7.0-alpha.31
## 0.0.47-alpha.30
### Patch Changes
- Updated dependencies
- jazz-tools@0.7.0-alpha.30
- jazz-react@0.7.0-alpha.30
## 0.0.47-alpha.29
### Patch Changes
- Updated dependencies
- jazz-tools@0.7.0-alpha.29
- cojson@0.7.0-alpha.29
- jazz-react@0.7.0-alpha.29
## 0.0.47-alpha.28
### Patch Changes
- Updated dependencies
- jazz-tools@0.7.0-alpha.28
- cojson@0.7.0-alpha.28
- jazz-react@0.7.0-alpha.28
## 0.0.47-alpha.27
### Patch Changes
- Updated dependencies
- Updated dependencies
- jazz-tools@0.7.0-alpha.27
- cojson@0.7.0-alpha.27
- jazz-react@0.7.0-alpha.27
## 0.0.47-alpha.26
### Patch Changes
- Updated dependencies
- jazz-tools@0.7.0-alpha.26
- jazz-react@0.7.0-alpha.26
## 0.0.47-alpha.25
### Patch Changes
- Updated dependencies
- jazz-tools@0.7.0-alpha.25
- jazz-react@0.7.0-alpha.25
## 0.0.47-alpha.24
### Patch Changes
- Updated dependencies
- Updated dependencies
- Updated dependencies
- jazz-tools@0.7.0-alpha.24
- cojson@0.7.0-alpha.24
- jazz-react@0.7.0-alpha.24
## 0.0.47-alpha.23
### Patch Changes
- Updated dependencies
- jazz-tools@0.7.0-alpha.23
- jazz-react@0.7.0-alpha.23
## 0.0.47-alpha.22
### Patch Changes
- Updated dependencies
- jazz-tools@0.7.0-alpha.22
- jazz-react@0.7.0-alpha.22
## 0.0.47-alpha.21
### Patch Changes
- Updated dependencies
- jazz-react@0.7.0-alpha.21
- jazz-tools@0.7.0-alpha.21
## 0.0.47-alpha.20
### Patch Changes
- Updated dependencies
- Updated dependencies
- jazz-react@0.7.0-alpha.20
- jazz-tools@0.7.0-alpha.20
## 0.0.47-alpha.19
### Patch Changes
- Updated dependencies
- jazz-tools@0.7.0-alpha.19
- jazz-react@0.7.0-alpha.19
## 0.0.47-alpha.18
### Patch Changes
- jazz-react@0.7.0-alpha.18
## 0.0.47-alpha.17
### Patch Changes
- Updated dependencies
- jazz-tools@0.7.0-alpha.17
- jazz-react@0.7.0-alpha.17
## 0.0.47-alpha.16
### Patch Changes
- Updated dependencies
- jazz-tools@0.7.0-alpha.16
- jazz-react@0.7.0-alpha.16
## 0.0.47-alpha.15
### Patch Changes
- Updated dependencies
- jazz-tools@0.7.0-alpha.15
- jazz-react@0.7.0-alpha.15
## 0.0.47-alpha.14
### Patch Changes
- Updated dependencies
- jazz-tools@0.7.0-alpha.14
- jazz-react@0.7.0-alpha.14
## 0.0.47-alpha.13
### Patch Changes
- Updated dependencies
- jazz-tools@0.7.0-alpha.13
- jazz-react@0.7.0-alpha.13
## 0.0.47-alpha.12
### Patch Changes
- Updated dependencies
- jazz-react@0.7.0-alpha.12
- jazz-tools@0.7.0-alpha.12
## 0.0.47-alpha.11
### Patch Changes
- Updated dependencies
- jazz-react@0.7.0-alpha.11
- jazz-tools@0.7.0-alpha.11
- cojson@0.7.0-alpha.11
## 0.0.47-alpha.10
### Patch Changes
- Updated dependencies
- jazz-react@0.7.0-alpha.10
- jazz-tools@0.7.0-alpha.10
- cojson@0.7.0-alpha.10
## 0.0.47-alpha.9
### Patch Changes
- Updated dependencies
- jazz-react@0.7.0-alpha.9
- jazz-tools@0.7.0-alpha.9
## 0.0.47-alpha.8
### Patch Changes
- Updated dependencies
- jazz-react@0.7.0-alpha.8
- jazz-tools@0.7.0-alpha.8
## 0.0.47-alpha.7
### Patch Changes
- Updated dependencies
- jazz-react@0.7.0-alpha.7
- jazz-tools@0.7.0-alpha.7
- cojson@0.7.0-alpha.7
## 0.0.47-alpha.6
### Patch Changes
- Updated dependencies
- jazz-react@0.7.0-alpha.6
- jazz-tools@0.7.0-alpha.6
## 0.0.47-alpha.5
### Patch Changes
- Updated dependencies
- jazz-react@0.7.0-alpha.5
- jazz-tools@0.7.0-alpha.5
- cojson@0.7.0-alpha.5
## 0.0.47-alpha.4
### Patch Changes
- Updated dependencies
- jazz-tools@0.7.0-alpha.4
- jazz-react@0.7.0-alpha.4
## 0.0.47-alpha.3
### Patch Changes
- Updated dependencies
- jazz-tools@0.7.0-alpha.3
- jazz-react@0.7.0-alpha.3
## 0.0.47-alpha.2
### Patch Changes
- Updated dependencies
- hash-slash@0.2.0-alpha.2
- jazz-react@0.7.0-alpha.2
- jazz-tools@0.7.0-alpha.2
## 0.0.47-alpha.1
### Patch Changes
- Updated dependencies
- hash-slash@0.2.0-alpha.1
- jazz-react@0.7.0-alpha.1
- jazz-tools@0.7.0-alpha.1
- cojson@0.7.0-alpha.1
## 0.0.47-alpha.0
### Patch Changes
- Updated dependencies
- hash-slash@0.2.0-alpha.0
- jazz-react@0.7.0-alpha.0
- jazz-tools@0.7.0-alpha.0
- cojson@0.7.0-alpha.0
## 0.0.46
### Patch Changes
- Updated dependencies
- jazz-react@0.5.0
- jazz-react-auth-local@0.4.16

View File

@@ -1,6 +1,6 @@
# Jazz Twit Example
# Jazz Chat Example
Live version: https://twit.jazz.tools
Live version: https://example-chat.jazz.tools
## Installing & running the example locally
@@ -9,11 +9,11 @@ Live version: https://twit.jazz.tools
Start by checking out `jazz`
```bash
git clone https://github.com/gardencmp/jazz.git
cd jazz/examples/twit
cd jazz/examples/chat
pnpm pack --pack-destination /tmp
mkdir -p ~/jazz-examples/twit # or any other directory
tar -xf /tmp/jazz-example-twit-* --strip-components 1 -C ~/jazz-examples/twit
cd ~/jazz-examples/twit
mkdir -p ~/jazz-examples/chat # or any other directory
tar -xf /tmp/jazz-example-chat-* --strip-components 1 -C ~/jazz-examples/chat
cd ~/jazz-examples/chat
```
This ensures that you have the example app without git history and independent of the Jazz multi-package monorepo.

View File

@@ -3,11 +3,12 @@
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/png" href="/jazz-logo.png" />
<link rel="stylesheet" href="/src/index.css" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Jazz File Drop Example</title>
<title>Jazz Chat Example</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/2_main.tsx"></script>
<script type="module" src="/src/app.tsx"></script>
</body>
</html>

View File

@@ -1,26 +1,34 @@
{
"name": "jazz-example-chat-passphrase",
"name": "jazz-example-chat-clerk",
"private": true,
"version": "0.0.48-alpha.0",
"version": "0.0.80",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"format": "echo 'chat example is codegolfed'",
"preview": "vite preview"
},
"lint-staged": {
"*.{ts,tsx}": "eslint --fix",
"*.{js,jsx,mdx,json}": "prettier --write"
},
"dependencies": {
"@clerk/clerk-react": "^5.4.1",
"@radix-ui/react-checkbox": "^1.0.4",
"@radix-ui/react-slot": "^1.0.2",
"@radix-ui/react-toast": "^1.1.4",
"@scure/bip39": "^1.2.2",
"class-variance-authority": "^0.7.0",
"clsx": "^2.0.0",
"cojson": "workspace:*",
"hash-slash": "workspace:*",
"jazz-react": "workspace:*",
"cojson": "workspace:0.8.0",
"hash-slash": "workspace:0.2.0",
"jazz-react": "workspace:0.8.0",
"jazz-react-auth-clerk": "workspace:0.8.0",
"jazz-tools": "workspace:0.8.0",
"lucide-react": "^0.274.0",
"qrcode": "^1.5.3",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router": "^6.16.0",
"react-router-dom": "^6.16.0",
@@ -31,19 +39,18 @@
},
"devDependencies": {
"@types/qrcode": "^1.5.1",
"@types/react": "^18.2.15",
"@types/react": "^18.2.19",
"@types/react-dom": "^18.2.7",
"@typescript-eslint/eslint-plugin": "^6.0.0",
"@typescript-eslint/parser": "^6.0.0",
"@typescript-eslint/eslint-plugin": "^6.2.1",
"@typescript-eslint/parser": "^6.2.1",
"@vitejs/plugin-react-swc": "^3.3.2",
"autoprefixer": "^10.4.14",
"eslint": "^8.45.0",
"eslint": "^8.46.0",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.3",
"postcss": "^8.4.27",
"react": "^18.2.0",
"tailwindcss": "^3.3.3",
"typescript": "^5.0.2",
"vite": "^4.4.5"
"typescript": "^5.3.3",
"vite": "^5.0.10"
}
}

View File

Before

Width:  |  Height:  |  Size: 7.3 KiB

After

Width:  |  Height:  |  Size: 7.3 KiB

View File

@@ -0,0 +1,85 @@
import { CoMap, CoList, co, Group, ID } from "jazz-tools";
import { createJazzReactApp } from "jazz-react";
import { useJazzClerkAuth } from "jazz-react-auth-clerk";
import { createRoot } from "react-dom/client";
import { useIframeHashRouter } from "hash-slash";
import { ChatScreen } from "./chatScreen.tsx";
import { StrictMode } from "react";
import {
ClerkProvider,
SignInButton,
useAuth,
useClerk,
} from "@clerk/clerk-react";
export class Message extends CoMap {
text = co.string;
}
export class Chat extends CoList.Of(co.ref(Message)) {}
const Jazz = createJazzReactApp();
export const { useAccount, useCoState } = Jazz;
function AuthAndJazz({ children }: { children: React.ReactNode }) {
const clerk = useClerk();
const [auth, state] = useJazzClerkAuth(clerk);
return (
<>
{state.errors.map((error) => (
<div key={error}>{error}</div>
))}
{auth ? (
<Jazz.Provider
auth={auth}
peer="wss://mesh.jazz.tools/?key=chat-example-jazz-clerk@gcmp.io"
>
{children}
</Jazz.Provider>
) : (
<SignInButton />
)}
</>
);
}
function App() {
const { signOut } = useAuth();
const { me } = useAccount();
const createChat = () => {
if (!me) return;
const group = Group.create({ owner: me });
group.addMember("everyone", "writer");
const chat = Chat.create([], { owner: group });
location.hash = "/chat/" + chat.id;
};
return (
<div className="flex flex-col items-center justify-between w-screen h-screen p-2 dark:bg-black dark:text-white">
<div className="rounded mb-5 px-2 py-1 text-sm self-end">
{me?.profile?.name} ·{" "}
<button onClick={() => signOut()}>Log Out</button>
</div>
{useIframeHashRouter().route({
"/": () => createChat() as never,
"/chat/:id": (id) => <ChatScreen chatID={id as ID<Chat>} />,
})}
</div>
);
}
createRoot(document.getElementById("root")!).render(
<StrictMode>
<ClerkProvider
publishableKey={import.meta.env.VITE_CLERK_PUBLISHABLE_KEY}
afterSignOutUrl="/"
>
<AuthAndJazz>
<App />
</AuthAndJazz>
</ClerkProvider>
</StrictMode>
);

View File

@@ -0,0 +1,42 @@
import { ID } from 'jazz-tools';
import { Chat, Message, useCoState } from './app.tsx';
export function ChatScreen(props: { chatID: ID<Chat> }) {
const chat = useCoState(Chat, props.chatID, [{}]);
return chat ? <div className='w-full max-w-xl h-full flex flex-col items-stretch'>
{chat.length > 0
? chat.map((msg) => <ChatBubble msg={msg} key={msg.id} />)
: <div className='m-auto text-sm'>(Empty chat)</div>}
<ChatInput onSubmit={(text) => {
chat.push(
Message.create({ text }, { owner: chat._owner })
);
}} />
</div> : <div>Loading...</div>;
}
function ChatBubble(props: { msg: Message }) {
const lastEdit = props.msg._edits.text;
const align = lastEdit.by?.isMe ? 'items-end' : 'items-start';
return <div className={`${align} flex flex-col`}>
<div className='rounded-xl bg-stone-100 dark:bg-stone-700 dark:text-white py-2 px-4 mt-2 min-w-[5rem]'>
{ props.msg.text }
</div>
<div className='text-xs text-neutral-500 ml-2'>
{ lastEdit.by?.profile?.name }{' '}
{ lastEdit.madeAt?.toLocaleTimeString() }
</div>
</div>;
}
function ChatInput(props: { onSubmit: (text: string) => void }) {
return <input className='rounded p-2 border mt-auto dark:bg-black dark:text-white border-stone-300 dark:border-stone-700'
placeholder='Type a message and press Enter'
onKeyDown={({ key, currentTarget: input }) => {
if (key !== 'Enter' || !input.value) return;
props.onSubmit(input.value);
input.value = '';
}} />;
}

View File

@@ -22,3 +22,5 @@ dist-ssr
*.njsproj
*.sln
*.sw?
sync-db/

View File

@@ -1,5 +1,42 @@
# jazz-example-chat
## 0.0.82
### Patch Changes
- Updated dependencies [6a147c2]
- Updated dependencies [ad40b88]
- Updated dependencies [23369dc]
- Updated dependencies [c2b62a0]
- Updated dependencies [1a979b6]
- Updated dependencies [bcec3be]
- Updated dependencies [6ce2051]
- cojson@0.8.0
- jazz-tools@0.8.0
- jazz-react@0.8.0
## 0.0.82-guest-auth.6
### Patch Changes
- Updated dependencies
- jazz-react@0.7.35-guest-auth.6
- jazz-tools@0.7.35-guest-auth.6
## 0.0.82
### Patch Changes
- Updated dependencies [49a8b54]
- Updated dependencies [35bbcd9]
- Updated dependencies [6f80282]
- Updated dependencies [35bbcd9]
- Updated dependencies [cac2ec9]
- Updated dependencies [f350e90]
- jazz-tools@0.7.35
- cojson@0.7.35
- jazz-react@0.7.35
## 0.0.81
### Patch Changes

View File

@@ -39,4 +39,4 @@ If you have feedback, let us know on [Discord](https://discord.gg/utDMjHYg42) or
By default, the example app uses [Jazz Global Mesh](https://jazz.tools/mesh) (`wss://sync.jazz.tools`) - so cross-device use, invites and collaboration should just work.
You can also run a local sync server by running `npx cojson-simple-sync` and adding the query param `?sync=ws://localhost:4200` to the URL of the example app (for example: `http://localhost:5173/?sync=ws://localhost:4200`), or by setting the `sync` parameter of the `<Jazz.Provider>` provider component in [./src/2_main.tsx](./src/2_main.tsx).
You can also run a local sync server by running `npx jazz-run sync` and adding the query param `?sync=ws://localhost:4200` to the URL of the example app (for example: `http://localhost:5173/?peer=ws://localhost:4200`), or by setting the `sync` parameter of the `<Jazz.Provider>` provider component in [./src/2_main.tsx](./src/2_main.tsx).

View File

@@ -1,7 +1,7 @@
{
"name": "jazz-example-chat",
"private": true,
"version": "0.0.81",
"version": "0.0.82",
"type": "module",
"scripts": {
"dev": "vite",
@@ -18,13 +18,12 @@
"@radix-ui/react-checkbox": "^1.0.4",
"@radix-ui/react-slot": "^1.0.2",
"@radix-ui/react-toast": "^1.1.4",
"@types/qrcode": "^1.5.1",
"class-variance-authority": "^0.7.0",
"clsx": "^2.0.0",
"hash-slash": "workspace:*",
"jazz-tools": "workspace:*",
"jazz-react": "workspace:*",
"cojson": "workspace:*",
"cojson": "workspace:0.8.0",
"hash-slash": "workspace:0.2.0",
"jazz-react": "workspace:0.8.0",
"jazz-tools": "workspace:0.8.0",
"lucide-react": "^0.274.0",
"qrcode": "^1.5.3",
"react": "^18.2.0",
@@ -37,18 +36,19 @@
"uniqolor": "^1.1.0"
},
"devDependencies": {
"@types/react": "^18.2.15",
"@types/qrcode": "^1.5.1",
"@types/react": "^18.2.19",
"@types/react-dom": "^18.2.7",
"@typescript-eslint/eslint-plugin": "^6.0.0",
"@typescript-eslint/parser": "^6.0.0",
"@typescript-eslint/eslint-plugin": "^6.2.1",
"@typescript-eslint/parser": "^6.2.1",
"@vitejs/plugin-react-swc": "^3.3.2",
"autoprefixer": "^10.4.14",
"eslint": "^8.45.0",
"eslint": "^8.46.0",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.3",
"postcss": "^8.4.27",
"tailwindcss": "^3.3.3",
"typescript": "^5.0.2",
"typescript": "^5.3.3",
"vite": "^5.0.10"
}
}

View File

@@ -1,43 +1,65 @@
import { CoMap, CoList, co, Group, ID } from "jazz-tools";
import { createJazzReactContext, DemoAuth } from "jazz-react";
import { createJazzReactApp, DemoAuthBasicUI, useDemoAuth } from "jazz-react";
import { createRoot } from "react-dom/client";
import { useIframeHashRouter } from "hash-slash";
import { ChatScreen } from "./chatScreen.tsx";
import { StrictMode } from "react";
export class Message extends CoMap {
text = co.string;
text = co.string;
}
export class Chat extends CoList.Of(co.ref(Message)) {}
const Jazz = createJazzReactContext({
auth: DemoAuth({ appName: "Jazz Chat" }),
peer: `wss://mesh.jazz.tools/?key=you@example.com`
});
const Jazz = createJazzReactApp();
export const { useAccount, useCoState } = Jazz;
function App() {
const { me, logOut } = useAccount();
const { me, logOut } = useAccount();
const createChat = () => {
const group = Group.create({ owner: me });
group.addMember("everyone", "writer");
const chat = Chat.create([], { owner: group });
location.hash = "/chat/" + chat.id;
};
const createChat = () => {
if (!me) return;
const group = Group.create({ owner: me });
group.addMember("everyone", "writer");
const chat = Chat.create([], { owner: group });
location.hash = "/chat/" + chat.id;
};
return <div className="flex flex-col items-center justify-between w-screen h-screen p-2 dark:bg-black dark:text-white">
<div className="rounded mb-5 px-2 py-1 text-sm self-end">
{me.profile?.name} · <button onClick={logOut}>Log Out</button>
</div>
{useIframeHashRouter().route({
'/': () => createChat() as never,
'/chat/:id': (id) => <ChatScreen chatID={id as ID<Chat>} />
})}
</div>;
return (
<div className="flex flex-col items-center justify-between w-screen h-screen p-2 dark:bg-black dark:text-white">
<div className="rounded mb-5 px-2 py-1 text-sm self-end">
{me?.profile?.name} ·{" "}
<button onClick={logOut}>Log Out</button>
</div>
{useIframeHashRouter().route({
"/": () => createChat() as never,
"/chat/:id": (id) => <ChatScreen chatID={id as ID<Chat>} />,
})}
</div>
);
}
createRoot(document.getElementById("root")!)
.render(<StrictMode><Jazz.Provider><App/></Jazz.Provider></StrictMode>);
function AuthAndJazz({ children }: { children: React.ReactNode }) {
const [auth, state] = useDemoAuth();
return (
<Jazz.Provider
auth={auth}
peer="wss://mesh.jazz.tools/?key=chat-example-jazz@gcmp.io"
>
{state.state === "signedIn" ? (
children
) : (
<DemoAuthBasicUI appName="Jazz Chat" state={state} />
)}
</Jazz.Provider>
);
}
createRoot(document.getElementById("root")!).render(
<StrictMode>
<AuthAndJazz>
<App />
</AuthAndJazz>
</StrictMode>
);

View File

@@ -22,3 +22,5 @@ dist-ssr
*.njsproj
*.sln
*.sw?
sync-db/

View File

@@ -1,4 +1,23 @@
# jazz-example-chat
# jazz-example-inspector
## 0.0.60
### Patch Changes
- Updated dependencies [6a147c2]
- Updated dependencies [ad40b88]
- cojson@0.8.0
- cojson-transport-ws@0.8.0
## 0.0.60
### Patch Changes
- 63daf6a: fix(inspector): subscribe to latent covalues instead of loading them immediately
- Updated dependencies [35bbcd9]
- Updated dependencies [f350e90]
- cojson@0.7.35
- cojson-transport-ws@0.7.35
## 0.0.59

View File

@@ -1,42 +1,7 @@
# Jazz Chat Example
# Jazz Inspector
Live version: https://example-chat.jazz.tools
Live address: https://inspector.jazz.tools
## Installing & running the example locally
Use this to visually inspect a Jazz account or other CoValue.
(this requires `pnpm` to be installed, see [https://pnpm.io/installation](https://pnpm.io/installation))
Start by checking out `jazz`
```bash
git clone https://github.com/gardencmp/jazz.git
cd jazz/examples/chat
pnpm pack --pack-destination /tmp
mkdir -p ~/jazz-examples/chat # or any other directory
tar -xf /tmp/jazz-example-chat-* --strip-components 1 -C ~/jazz-examples/chat
cd ~/jazz-examples/chat
```
This ensures that you have the example app without git history and independent of the Jazz multi-package monorepo.
Install dependencies:
```bash
pnpm install
```
Start the dev server:
```bash
pnpm dev
```
## Questions / problems / feedback
If you have feedback, let us know on [Discord](https://discord.gg/utDMjHYg42) or open an issue or PR to fix something that seems wrong.
## Configuration: sync server
By default, the example app uses [Jazz Global Mesh](https://jazz.tools/mesh) (`wss://sync.jazz.tools`) - so cross-device use, invites and collaboration should just work.
You can also run a local sync server by running `npx cojson-simple-sync` and adding the query param `?sync=ws://localhost:4200` to the URL of the example app (for example: `http://localhost:5173/?sync=ws://localhost:4200`), or by setting the `sync` parameter of the `<WithJazz>` provider component in [./src/2_main.tsx](./src/2_main.tsx).
For now, you can get your account credentials from the `jazz-logged-in-secret` local-storage key from within your Jazz app.

View File

@@ -1,7 +1,7 @@
{
"name": "jazz-inspector",
"private": true,
"version": "0.0.59",
"version": "0.0.60",
"type": "module",
"scripts": {
"dev": "vite",
@@ -13,12 +13,11 @@
"@radix-ui/react-checkbox": "^1.0.4",
"@radix-ui/react-slot": "^1.0.2",
"@radix-ui/react-toast": "^1.1.4",
"@types/qrcode": "^1.5.1",
"class-variance-authority": "^0.7.0",
"clsx": "^2.0.0",
"hash-slash": "workspace:*",
"cojson": "workspace:*",
"cojson-transport-ws": "workspace:*",
"cojson": "workspace:0.8.0",
"cojson-transport-ws": "workspace:0.8.0",
"hash-slash": "workspace:0.2.0",
"lucide-react": "^0.274.0",
"qrcode": "^1.5.3",
"react": "^18.2.0",
@@ -31,18 +30,19 @@
"uniqolor": "^1.1.0"
},
"devDependencies": {
"@types/react": "^18.2.15",
"@types/qrcode": "^1.5.1",
"@types/react": "^18.2.19",
"@types/react-dom": "^18.2.7",
"@typescript-eslint/eslint-plugin": "^6.0.0",
"@typescript-eslint/parser": "^6.0.0",
"@typescript-eslint/eslint-plugin": "^6.2.1",
"@typescript-eslint/parser": "^6.2.1",
"@vitejs/plugin-react-swc": "^3.3.2",
"autoprefixer": "^10.4.14",
"eslint": "^8.45.0",
"eslint": "^8.46.0",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.3",
"postcss": "^8.4.27",
"tailwindcss": "^3.3.3",
"typescript": "^5.0.2",
"typescript": "^5.3.3",
"vite": "^5.0.10"
}
}

View File

@@ -5,8 +5,7 @@ import {
RawCoValue,
RawAccount,
AgentSecret,
AccountID,
cojsonInternals,
RawAccountID,
WasmCrypto,
} from "cojson";
import { createWebSocketPeer } from "cojson-transport-ws";
@@ -69,7 +68,7 @@ export default function CoJsonViewerApp() {
const node = await LocalNode.withLoadedAccount({
accountID: currentAccount.id,
accountSecret: currentAccount.secret,
sessionID: cojsonInternals.newRandomSessionID(
sessionID: crypto.newRandomSessionID(
currentAccount.id,
),
peersToLoadFrom: [wsPeer],
@@ -82,7 +81,7 @@ export default function CoJsonViewerApp() {
});
}, [currentAccount, goToIndex]);
const addAccount = (id: AccountID, secret: AgentSecret) => {
const addAccount = (id: RawAccountID, secret: AgentSecret) => {
const newAccount = { id, secret };
setAccounts([...accounts, newAccount]);
setCurrentAccount(newAccount);
@@ -238,14 +237,14 @@ function AccountSwitcher({
function AddAccountForm({
addAccount,
}: {
addAccount: (id: AccountID, secret: AgentSecret) => void;
addAccount: (id: RawAccountID, secret: AgentSecret) => void;
}) {
const [id, setId] = useState("");
const [secret, setSecret] = useState("");
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
addAccount(id as AccountID, secret as AgentSecret);
addAccount(id as RawAccountID, secret as AgentSecret);
setId("");
setSecret("");
};

View File

@@ -104,6 +104,54 @@ export async function resolveCoValue(
};
}
function subscribeToCoValue(
coValueId: CoID<RawCoValue>,
node: LocalNode,
callback: (result: Awaited<ReturnType<typeof resolveCoValue>>) => void,
) {
return node.subscribe(coValueId, (value) => {
if (value === "unavailable") {
callback({
value: undefined,
snapshot: "unavailable",
type: null,
extendedType: undefined,
});
} else {
const snapshot = value.toJSON() as JSONObject;
const type = value.type as CoJsonType;
let extendedType: ExtendedCoJsonType | undefined;
if (type === "comap") {
if (isBrowserImage(snapshot)) {
extendedType = "image";
} else if (isAccount(snapshot)) {
extendedType = "account";
} else if (isGroup(snapshot)) {
extendedType = "group";
} else {
const children = Object.values(snapshot).slice(0, 10);
if (
children.every(
(c) => typeof c === "string" && c.startsWith("co_"),
) &&
children.length > 3
) {
extendedType = "record";
}
}
}
callback({
value,
snapshot,
type,
extendedType,
});
}
});
}
export function useResolvedCoValue(
coValueId: CoID<RawCoValue>,
node: LocalNode,
@@ -112,7 +160,17 @@ export function useResolvedCoValue(
useState<Awaited<ReturnType<typeof resolveCoValue>>>();
useEffect(() => {
resolveCoValue(coValueId, node).then(setResult);
let isMounted = true;
const unsubscribe = subscribeToCoValue(coValueId, node, (newResult) => {
if (isMounted) {
setResult(newResult);
}
});
return () => {
isMounted = false;
unsubscribe();
};
}, [coValueId, node]);
return (
@@ -134,18 +192,30 @@ export function useResolvedCoValues(
>([]);
useEffect(() => {
console.log("RETECHING", coValueIds);
const fetchResults = async () => {
if (coValueIds.length === 0) return;
const resolvedValues = await Promise.all(
coValueIds.map((coValueId) => resolveCoValue(coValueId, node)),
let isMounted = true;
const unsubscribes: (() => void)[] = [];
coValueIds.forEach((coValueId, index) => {
const unsubscribe = subscribeToCoValue(
coValueId,
node,
(newResult) => {
if (isMounted) {
setResults((prevResults) => {
const newResults = [...prevResults];
newResults[index] = newResult;
return newResults;
});
}
},
);
unsubscribes.push(unsubscribe);
});
console.log({ resolvedValues });
setResults(resolvedValues);
return () => {
isMounted = false;
unsubscribes.forEach((unsubscribe) => unsubscribe());
};
fetchResults();
}, [coValueIds, node]);
return results;

View File

@@ -5,6 +5,7 @@ module.exports = {
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:react-hooks/recommended',
'prettier'
],
ignorePatterns: ['dist', '.eslintrc.cjs'],
parser: '@typescript-eslint/parser',

View File

@@ -0,0 +1,9 @@
/** @type {import("prettier").Config} */
const config = {
trailingComma: "all",
tabWidth: 4,
semi: true,
singleQuote: false,
};
export default config;

View File

@@ -0,0 +1,34 @@
# jazz-example-musicplayer
## 0.0.3
### Patch Changes
- Updated dependencies [ad40b88]
- Updated dependencies [23369dc]
- Updated dependencies [c2b62a0]
- Updated dependencies [1a979b6]
- Updated dependencies [bcec3be]
- Updated dependencies [6ce2051]
- jazz-tools@0.8.0
- jazz-react@0.8.0
## 0.0.3-guest-auth.0
### Patch Changes
- Updated dependencies
- jazz-react@0.7.35-guest-auth.6
- jazz-tools@0.7.35-guest-auth.6
## 0.0.2
### Patch Changes
- Updated dependencies [49a8b54]
- Updated dependencies [6f80282]
- Updated dependencies [35bbcd9]
- Updated dependencies [cac2ec9]
- Updated dependencies [f350e90]
- jazz-tools@0.7.35
- jazz-react@0.7.35

View File

@@ -1,19 +1,20 @@
# Jazz Chat Example (with passphrase auth)
# Jazz Music Player Example
Live version: https://example-chat-passphrase.jazz.tools
Live version: https://music-demo.jazz.tools
## Installing & running the example locally
(this requires `pnpm` to be installed, see [https://pnpm.io/installation](https://pnpm.io/installation))
Start by checking out `jazz`
```bash
git clone https://github.com/gardencmp/jazz.git
cd jazz/examples/chat-passphrase
cd jazz/examples/musicPlayer
pnpm pack --pack-destination /tmp
mkdir -p ~/jazz-examples/chat-passphrase # or any other directory
tar -xf /tmp/jazz-example-chat-passphrase-* --strip-components 1 -C ~/jazz-examples/chat-passphrase
cd ~/jazz-examples/chat-passphrase
mkdir -p ~/jazz-examples/musicPlayer # or any other directory
tar -xf /tmp/jazz-example-musicPlayer-* --strip-components 1 -C ~/jazz-examples/musicPlayer
cd ~/jazz-examples/musicPlayer
```
This ensures that you have the example app without git history and independent of the Jazz multi-package monorepo.
@@ -34,9 +35,8 @@ pnpm dev
If you have feedback, let us know on [Discord](https://discord.gg/utDMjHYg42) or open an issue or PR to fix something that seems wrong.
## Configuration: sync server
By default, the example app uses [Jazz Global Mesh](https://jazz.tools/mesh) (`wss://sync.jazz.tools`) - so cross-device use, invites and collaboration should just work.
You can also run a local sync server by running `npx cojson-simple-sync` and adding the query param `?sync=ws://localhost:4200` to the URL of the example app (for example: `http://localhost:5173/?sync=ws://localhost:4200`), or by setting the `sync` parameter of the `<Jazz.Provider>` provider component in [./src/2_main.tsx](./src/2_main.tsx).
You can also run a local sync server by running `npx cojson-simple-sync` and adding the query param `?sync=ws://localhost:4200` to the URL of the example app (for example: `http://localhost:5173/?peer=ws://localhost:4200`), or by setting the `sync` parameter of the `<Jazz.Provider>` provider component in [./src/2_main.tsx](./src/2_main.tsx).

View File

@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/png" href="/jazz-logo.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Jazz - Music Player example</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/2_main.tsx"></script>
</body>
</html>

View File

@@ -1,4 +1,4 @@
job "twit$BRANCH_SUFFIX" {
job "example-musicPlayer$BRANCH_SUFFIX" {
region = "global"
datacenters = ["*"]
@@ -41,7 +41,7 @@ job "twit$BRANCH_SUFFIX" {
service {
tags = ["public"]
name = "twit$BRANCH_SUFFIX"
name = "example-pets$BRANCH_SUFFIX"
port = "http"
provider = "consul"
}

View File

@@ -0,0 +1,44 @@
{
"name": "jazz-example-music-player",
"private": true,
"version": "0.0.3",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"format": "prettier --write './src/**/*.{ts,tsx}'",
"preview": "vite preview"
},
"lint-staged": {
"*.{ts,tsx}": "eslint --fix",
"*.{js,jsx,mdx,json}": "prettier --write"
},
"dependencies": {
"class-variance-authority": "^0.7.0",
"clsx": "^2.0.0",
"jazz-react": "workspace:0.8.0",
"jazz-tools": "workspace:0.8.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router": "^6.16.0",
"react-router-dom": "^6.16.0",
"tailwind-merge": "^1.14.0",
"tailwindcss-animate": "^1.0.7"
},
"devDependencies": {
"@types/react": "^18.2.19",
"@types/react-dom": "^18.2.7",
"@typescript-eslint/eslint-plugin": "^6.2.1",
"@typescript-eslint/parser": "^6.2.1",
"@vitejs/plugin-react-swc": "^3.3.2",
"autoprefixer": "^10.4.14",
"eslint": "^8.46.0",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.3",
"postcss": "^8.4.27",
"tailwindcss": "^3.3.3",
"typescript": "^5.3.3",
"vite": "^5.0.10"
}
}

Binary file not shown.

View File

Before

Width:  |  Height:  |  Size: 7.3 KiB

After

Width:  |  Height:  |  Size: 7.3 KiB

View File

@@ -0,0 +1,124 @@
import {
CoMap,
CoList,
BinaryCoStream,
co,
Profile,
Account,
} from "jazz-tools";
/** Walkthrough: Defining the data model with CoJSON
*
* Here, we define our main data model of tasks, lists of tasks and projects
* using CoJSON's collaborative map and list types, CoMap & CoList.
*
* CoMap values and CoLists items can contain:
* - arbitrary immutable JSON
* - other CoValues
**/
export class MusicTrack extends CoMap {
/**
* Attributes are defined as class properties
* and you can get the types from the `co` module
* here we are defining the title and duration for our music track
*
* Tip: try to follow the co.string defintion to discover the other available primitives!
*/
title = co.string;
duration = co.number;
/**
* With `co.ref` you can define relations between your coValues.
*
* Attributes are required by default unless you mark them as optional.
*/
sourceTrack = co.optional.ref(MusicTrack);
/**
* In Jazz you can files using BinaryCoStream.
*
* As for any other coValue the music files we put inside BinaryCoStream
* is available offline and end-to-end encrypted 😉
*/
file = co.ref(BinaryCoStream);
waveform = co.ref(MusicTrackWaveform);
}
export class MusicTrackWaveform extends CoMap {
data = co.json<number[]>();
}
/**
* CoList is the collaborative version of Array
*
* They are strongly typed and accept only the type you define here
* as "CoList.Of" argument
*/
export class ListOfTracks extends CoList.Of(co.ref(MusicTrack)) {}
export class Playlist extends CoMap {
title = co.string;
tracks = co.ref(ListOfTracks);
}
export class ListOfPlaylists extends CoList.Of(co.ref(Playlist)) {}
/** The account root is an app-specific per-user private `CoMap`
* where you can store top-level objects for that user */
export class MusicaAccountRoot extends CoMap {
// The root playlist works as container for the tracks that
// the user has uploaded
rootPlaylist = co.ref(Playlist);
// Here we store the list of playlists that the user has created
// or that has been invited to
playlists = co.ref(ListOfPlaylists);
// We store the active track and playlist as coValue here
// so when the user reloads the page can see the last played
// track and playlist
// You can also add the position in time if you want make it possible
// to resume the song
activeTrack = co.optional.ref(MusicTrack);
activePlaylist = co.ref(Playlist);
exampleDataLoaded = co.optional.boolean;
}
export class MusicaAccount extends Account {
profile = co.ref(Profile);
root = co.ref(MusicaAccountRoot);
/**
* The account migration is run on account creation and on every log-in.
* You can use it to set up the account root and any other initial CoValues you need.
*/
async migrate(creationProps?: { name: string }) {
super.migrate(creationProps);
if (!this._refs.root) {
const ownership = { owner: this };
const tracks = ListOfTracks.create([], ownership);
const rootPlaylist = Playlist.create(
{
tracks,
title: "",
},
ownership,
);
this.root = MusicaAccountRoot.create(
{
rootPlaylist,
playlists: ListOfPlaylists.create([], ownership),
activeTrack: null,
activePlaylist: rootPlaylist,
exampleDataLoaded: false,
},
ownership,
);
}
}
}
/** Walkthrough: Continue with ./2_main.tsx */

View File

@@ -0,0 +1,115 @@
import React from "react";
import ReactDOM from "react-dom/client";
import { createHashRouter, RouterProvider } from "react-router-dom";
import { useMediaPlayer } from "./4_useMediaPlayer";
import { HomePage } from "./5_HomePage";
import { createNewPlaylist, uploadMusicTracks } from "./3_actions";
import { PlaylistPage } from "./6_PlaylistPage";
import { InvitePage } from "./7_InvitePage";
import { Button } from "./basicComponents/Button";
import { FileUploadButton } from "./basicComponents/FileUploadButton";
import { PlayerControls } from "./components/PlayerControls";
import "./index.css";
import { MusicaAccount } from "@/1_schema";
import { createJazzReactApp, DemoAuthBasicUI, useDemoAuth } from "jazz-react";
import { useUploadExampleData } from "./lib/useUploadExampleData";
/**
* Walkthrough: The top-level provider `<Jazz.Provider/>`
*
* This shows how to use the top-level provider `<Jazz.Provider/>`,
* which provides the rest of the app with a controlled account (used through `useAccount` later).
* Here we use `DemoAuth` which is great for prototyping you app without wasting time on figuring out
* the best way to do auth.
*
* `<Jazz.Provider/>` also runs our account migration
*/
const Jazz = createJazzReactApp({
AccountSchema: MusicaAccount
});
export const { useAccount, useCoState, useAcceptInvite } = Jazz;
function Main() {
const mediaPlayer = useMediaPlayer();
useUploadExampleData();
/**
* `me` represents the current user account, which will determine
* access rights to CoValues. We get it from the top-level provider `<WithJazz/>`.
*/
const { me } = useAccount();
async function handleFileLoad(files: FileList) {
if (!me) return;
/**
* Follow this function definition to see how we update
* values in Jazz and manage files!
*/
/** Walkthrough: Continue with ./3_actions.ts */
await uploadMusicTracks(me, files);
}
async function handleCreatePlaylist() {
if (!me) return;
const playlist = await createNewPlaylist(me);
router.navigate(`/playlist/${playlist.id}`);
}
const router = createHashRouter([
{
path: "/",
element: <HomePage mediaPlayer={mediaPlayer} />,
},
{
path: "/playlist/:playlistId",
element: <PlaylistPage mediaPlayer={mediaPlayer} />,
},
{
path: "/invite/*",
element: <InvitePage />,
},
]);
return (
<>
<div className="flex items-center bg-gray-300">
<img src="jazz-logo.png" className="px-3 h-[20px]" />
<div className="text-nowrap">Jazz music player</div>
<div className="flex w-full gap-1 justify-end">
<FileUploadButton onFileLoad={handleFileLoad}>
Add file
</FileUploadButton>
<Button onClick={handleCreatePlaylist}>
Create new playlist
</Button>
</div>
</div>
<RouterProvider router={router} />
<PlayerControls mediaPlayer={mediaPlayer} />
</>
);
}
function AuthAndJazz({ children }: { children: React.ReactNode }) {
const [auth, state] = useDemoAuth();
return (
<Jazz.Provider auth={auth} peer="wss://mesh.jazz.tools/?key=music-player-example-jazz@gcmp.io">
{state.state === "signedIn" ? children : <DemoAuthBasicUI appName="Jazz Music Player" state={state} />}
</Jazz.Provider>
);
}
ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<AuthAndJazz>
<Main />
</AuthAndJazz>
</React.StrictMode>,
);

View File

@@ -0,0 +1,128 @@
import { getAudioFileData } from "@/lib/audio/getAudioFileData";
import { BinaryCoStream, Group } from "jazz-tools";
import {
ListOfTracks,
MusicaAccount,
MusicTrack,
MusicTrackWaveform,
Playlist,
} from "./1_schema";
/**
* Walkthrough: Actions
*
* With Jazz is very simple to update the state, you
* just mutate the values and we take care of triggering
* the updates and sync and persist the values you change.
*
* We have grouped the complex updates here in an actions file
* just to keep them separated from the components.
*
* Jazz is very unopinionated in this sense and you can adopt the
* pattern that best fits your app.
*/
export async function uploadMusicTracks(
account: MusicaAccount,
files: Iterable<File>,
) {
// The ownership object defines the user that owns the created coValues
// by setting the ownership with "account" we configure the coValues to be private
const ownership = {
owner: account,
};
for (const file of files) {
const data = await getAudioFileData(file);
// We transform the file blob into a BinaryCoStream
// making it a collaborative value that is encrypted, easy
// to share across devices and users and available offline!
const binaryCoStream = await BinaryCoStream.createFromBlob(
file,
ownership,
);
const musicTrack = MusicTrack.create(
{
file: binaryCoStream,
duration: data.duration,
waveform: MusicTrackWaveform.create(
{ data: data.waveform },
ownership,
),
title: file.name,
},
ownership,
);
// The newly created musicTrack can be associated to the
// user track list using a simple push call
account.root?.rootPlaylist?.tracks?.push(musicTrack);
}
}
export async function createNewPlaylist(account: MusicaAccount) {
// Since playlists are meant to be shared we associate them
// to a group which will contain the keys required to get
// access to the "owned" values
const playlistGroup = Group.create({ owner: account });
const ownership = { owner: playlistGroup };
const playlist = Playlist.create(
{
title: "New Playlist",
tracks: ListOfTracks.create([], ownership),
},
ownership,
);
// Again, we associate the new playlist to the
// user by pushing it into the playlists CoList
account.root?.playlists?.push(playlist);
return playlist;
}
export async function addTrackToPlaylist(
playlist: Playlist,
track: MusicTrack,
account: MusicaAccount | undefined,
) {
if (!account) return;
/**
* Since musicTracks are created as private values (see uploadMusicTracks)
* to make them shareable as part of the playlist we are cloning them
* and setting the playlist group as owner of the clone
*
* In the future it will be possible to "inherit" the parent group so you
* won't need to clone values to have this kind of sharing granularity
*/
const ownership = { owner: playlist._owner };
const blob = await BinaryCoStream.loadAsBlob(track._refs.file.id, account);
const waveform = await MusicTrackWaveform.load(
track._refs.waveform.id,
account,
{},
);
if (!blob || !waveform) return;
const trackClone = MusicTrack.create(
{
file: await BinaryCoStream.createFromBlob(blob, ownership),
duration: track.duration,
waveform: MusicTrackWaveform.create(
{ data: waveform.data },
ownership,
),
title: track.title,
sourceTrack: track,
},
ownership,
);
playlist.tracks?.push(trackClone);
}

View File

@@ -0,0 +1,99 @@
import { usePlayMedia } from "@/lib/audio/usePlayMedia";
import { usePlayState } from "@/lib/audio/usePlayState";
import { useAccount, useCoState } from "./2_main";
import { MusicTrack, Playlist } from "@/1_schema";
import { useRef, useState } from "react";
import { getNextTrack, getPrevTrack } from "./lib/getters";
import { BinaryCoStream, ID } from "jazz-tools";
export function useMediaPlayer() {
const { me } = useAccount();
const playState = usePlayState();
const playMedia = usePlayMedia();
const [loading, setLoading] = useState<ID<MusicTrack> | null>(null);
const activeTrack = useCoState(MusicTrack, me?.root?._refs.activeTrack?.id);
// Reference used to avoid out-of-order track loads
const lastLoadedTrackId = useRef<ID<MusicTrack> | null>(null);
async function loadTrack(track: MusicTrack) {
if (!me.root) return;
lastLoadedTrackId.current = track.id;
setLoading(track.id);
const file = await BinaryCoStream.loadAsBlob(track._refs.file.id, me);
if (!file) {
setLoading(null);
return;
}
// Check if another track has been loaded during
// the file download
if (lastLoadedTrackId.current !== track.id) {
return;
}
me.root.activeTrack = track;
await playMedia(file);
setLoading(null);
}
async function playNextTrack() {
if (!me?.root) return;
const track = await getNextTrack(me);
if (track) {
me.root.activeTrack = track;
await loadTrack(track);
}
}
async function playPrevTrack() {
if (!me?.root) return;
const track = await getPrevTrack(me);
if (track) {
await loadTrack(track);
}
}
async function setActiveTrack(track: MusicTrack, playlist?: Playlist) {
if (!me?.root) return;
if (
activeTrack?.id === track.id &&
lastLoadedTrackId.current !== null
) {
playState.toggle();
return;
}
me.root.activePlaylist = playlist ?? me.root.rootPlaylist;
await loadTrack(track);
if (playState.value === "pause") {
playState.toggle();
}
}
return {
activeTrack,
setActiveTrack,
playNextTrack,
playPrevTrack,
loading,
};
}
export type MediaPlayer = ReturnType<typeof useMediaPlayer>;

View File

@@ -0,0 +1,60 @@
import { useAccount } from "./2_main";
import { MediaPlayer } from "./4_useMediaPlayer";
import { Link } from "./basicComponents/Link";
import { MusicTrackRow } from "./components/MusicTrackRow";
import { usePlayState } from "./lib/audio/usePlayState";
export function HomePage({ mediaPlayer }: { mediaPlayer: MediaPlayer }) {
const { me } = useAccount({
root: {
rootPlaylist: {
tracks: [{}],
},
playlists: [{}],
},
});
const tracks = me?.root.rootPlaylist.tracks;
const playState = usePlayState();
const isPlaying = playState.value === "play";
const playlists = me?.root.playlists;
return (
<>
{playlists && playlists.length > 0 && (
<div className="p-3">
<b>Playlists</b>
<div className="flex py-6 gap-6">
{playlists.map((playlist) => (
<Link
key={playlist.id}
to={`/playlist/${playlist.id}`}
>
{playlist.title}
</Link>
))}
</div>
</div>
)}
<ul className="flex flex-col">
{tracks?.map(
(track) =>
track && (
<MusicTrackRow
track={track}
key={track.id}
isLoading={mediaPlayer.loading === track.id}
isPlaying={
mediaPlayer.activeTrack?.id === track.id &&
isPlaying
}
onClick={mediaPlayer.setActiveTrack}
/>
),
)}
</ul>
</>
);
}

View File

@@ -0,0 +1,84 @@
import { createInviteLink } from "jazz-react";
import { ID } from "jazz-tools";
import { ChangeEvent } from "react";
import { useParams } from "react-router";
import { useAccount, useCoState } from "./2_main";
import { Playlist } from "./1_schema";
import { MediaPlayer } from "./4_useMediaPlayer";
import { addTrackToPlaylist } from "./3_actions";
import { Button } from "./basicComponents/Button";
import { Link } from "./basicComponents/Link";
import { MusicTrackRow } from "./components/MusicTrackRow";
import { usePlayState } from "./lib/audio/usePlayState";
import { AddTracksToPlaylistSection } from "./components/AddTracksToPlaylistSection";
export function PlaylistPage({ mediaPlayer }: { mediaPlayer: MediaPlayer }) {
const { playlistId } = useParams<{ playlistId: ID<Playlist> }>();
const playlist = useCoState(Playlist, playlistId, {
tracks: [{}],
});
const { me } = useAccount();
const playState = usePlayState();
const isPlaying = playState.value === "play";
if (!playlist) return null;
const handlePlaylistTitleChange = (evt: ChangeEvent<HTMLInputElement>) => {
playlist.title = evt.target.value;
};
const handlePlaylistShareClick = async () => {
if (playlist._owner.myRole() !== "admin") return;
const inviteLink = createInviteLink(playlist, "reader");
await navigator.clipboard.writeText(inviteLink);
alert(`Invite link copied into the clipboard`);
};
return (
<>
<div className="flex bg-gray-200">
<Link to="/">Back</Link>
<input
className="w-full bg-transparent p-1 m-1"
value={playlist.title}
onChange={handlePlaylistTitleChange}
/>
<Button onClick={handlePlaylistShareClick}>Share</Button>
</div>
<ul className="flex flex-col py-6">
{playlist.tracks?.map(
(track) =>
track && (
<MusicTrackRow
track={track}
key={track.id}
isLoading={mediaPlayer.loading === track.id}
isPlaying={
mediaPlayer.activeTrack?.id === track.id &&
isPlaying
}
onClick={() => {
mediaPlayer.setActiveTrack(track, playlist);
}}
/>
),
)}
</ul>
<AddTracksToPlaylistSection
playlist={playlist}
onTrackClick={(track) =>
addTrackToPlaylist(playlist, track, me)
}
/>
</>
);
}

View File

@@ -0,0 +1,38 @@
import { ID } from "jazz-tools";
import { useCallback } from "react";
import { useNavigate } from "react-router-dom";
import { useAcceptInvite, useAccount } from "./2_main";
import { Playlist } from "./1_schema";
export function InvitePage() {
const navigate = useNavigate();
const { me } = useAccount({
root: {
playlists: [],
},
});
useAcceptInvite({
invitedObjectSchema: Playlist,
onAccept: useCallback(
async (playlistId: ID<Playlist>) => {
if (!me) return;
const playlist = await Playlist.load(playlistId, me, {});
if (
playlist &&
!me.root.playlists.some((item) => playlist.id === item?.id)
) {
me.root.playlists.push(playlist);
}
navigate("/playlist/" + playlistId);
},
[navigate, me],
),
});
return <p>Accepting invite....</p>;
}

View File

@@ -0,0 +1,20 @@
import { cn } from "@/lib/utils";
import { ReactNode } from "react";
export function Button(props: {
className?: string;
onClick?: () => void;
children: ReactNode;
}) {
return (
<button
onClick={props.onClick}
className={cn(
"p-2 bg-blue-300 hover:cursor-pointer flex items-center",
props.className,
)}
>
{props.children}
</button>
);
}

View File

@@ -0,0 +1,23 @@
import { ReactNode } from "react";
export function FileUploadButton(props: {
onFileLoad: (files: FileList) => Promise<void>;
children: ReactNode;
}) {
async function handleFileLoad(evt: React.ChangeEvent<HTMLInputElement>) {
if (!evt.target.files) return;
await props.onFileLoad(evt.target.files);
evt.target.value = "";
}
return (
<button className="bg-blue-300 hover:cursor-pointer flex items-center">
<label className="flex items-center cursor-pointer p-2">
<input type="file" onChange={handleFileLoad} multiple hidden />
{props.children}
</label>
</button>
);
}

View File

@@ -0,0 +1,13 @@
import { ReactNode } from "react";
import { Link as RouterLink } from "react-router-dom";
export function Link(props: { to: string; children: ReactNode }) {
return (
<RouterLink
to={props.to}
className="p-2 w-fit bg-blue-300 hover:cursor-pointer flex items-center"
>
{props.children}
</RouterLink>
);
}

View File

@@ -0,0 +1,79 @@
import { useAccount, useCoState } from "@/2_main";
import { Playlist, MusicTrack, ListOfTracks } from "@/1_schema";
import { Button } from "@/basicComponents/Button";
import { useState } from "react";
export function AddTracksToPlaylistSection({
playlist,
onTrackClick,
}: {
playlist: Playlist;
onTrackClick: (track: MusicTrack) => Promise<void>;
}) {
const { me } = useAccount({
root: {
rootPlaylist: {
tracks: [{}],
},
},
});
const listOfTracks = useCoState(ListOfTracks, playlist._refs.tracks.id, []);
const currentTracksIds = new Set(
listOfTracks?.map((track) => track?._refs.sourceTrack?.id),
);
const tracksToAdd = me?.root.rootPlaylist.tracks.filter(
(track) => !currentTracksIds.has(track.id),
);
if (!tracksToAdd?.length) return null;
return (
<div>
Add tracks to the playlist
<ul className="flex flex-col px-1 py-6 gap-6">
{tracksToAdd.map((track) => (
<li
key={track.id}
className={"flex items-center gap-6 bg-slate-200"}
>
<AddTrackButton
track={track}
onTrackClick={onTrackClick}
/>
{track.title}
</li>
))}
</ul>
</div>
);
}
function AddTrackButton({
track,
onTrackClick,
}: {
track: MusicTrack;
onTrackClick: (track: MusicTrack) => Promise<void>;
}) {
const [isLoading, setLoading] = useState(false);
async function handleClick() {
if (isLoading) return;
setLoading(true);
try {
await onTrackClick(track);
} finally {
setLoading(false);
}
}
return (
<Button className="py-2 px-4" onClick={handleClick}>
{isLoading ? <div className="animate-spin">߷</div> : "+"}
</Button>
);
}

View File

@@ -0,0 +1,55 @@
import { MusicTrack } from "@/1_schema";
import { cn } from "@/lib/utils";
import { ChangeEvent } from "react";
export function MusicTrackRow({
track,
isLoading,
isPlaying,
onClick,
}: {
track: MusicTrack;
isLoading: boolean;
isPlaying: boolean;
onClick: (track: MusicTrack) => void;
}) {
function handleTrackTitleChange(evt: ChangeEvent<HTMLInputElement>) {
track.title = evt.target.value;
}
return (
<li
className={
"flex gap-1 hover:bg-slate-200 group py-2 px-2 cursor-pointer"
}
onClick={() => onClick(track)}
>
<button
className={cn(
"flex items-center justify-center bg-transparent w-8 h-8 ",
!isPlaying && "group-hover:bg-slate-300 rounded-full",
)}
onClick={() => onClick(track)}
>
{isLoading ? (
<div className="animate-spin">߷</div>
) : isPlaying ? (
"⏸️"
) : (
"▶️"
)}
</button>
<div className="relative" onClick={(evt) => evt.stopPropagation()}>
<input
className="absolute w-full h-full left-0 bg-transparent px-1"
value={track.title}
onChange={handleTrackTitleChange}
spellCheck="false"
/>
<span className="opacity-0 px-1 w-fit pointer-events-none whitespace-pre">
{track.title}
</span>
</div>
</li>
);
}

View File

@@ -0,0 +1,53 @@
import { MediaPlayer } from "@/4_useMediaPlayer";
import { usePlayState } from "@/lib/audio/usePlayState";
import { Waveform } from "./Waveform";
import { useAccount } from "@/2_main";
import { useMediaEndListener } from "@/lib/audio/useMediaEndListener";
import { useKeyboardListener } from "@/lib/useKeyboardListener";
export function PlayerControls({ mediaPlayer }: { mediaPlayer: MediaPlayer }) {
const playState = usePlayState();
const isPlaying = playState.value === "play";
const activePlaylist = useAccount({
root: {
activePlaylist: {},
},
}).me?.root.activePlaylist;
useMediaEndListener(mediaPlayer.playNextTrack);
useKeyboardListener("Space", () => {
if (document.activeElement !== document.body) return;
playState.toggle();
});
if (!mediaPlayer.activeTrack) return null;
const activeTrackTitle = mediaPlayer.activeTrack.title;
const head = activePlaylist?.title
? `${activePlaylist.title} / ${activeTrackTitle}`
: activeTrackTitle;
return (
<div className=" flex flex-col fixed bottom-0 left-0 border-t-2 w-full p-4 gap-3">
<div>Playling: {head}</div>
<div className="flex items-center w-full">
<div className="flex flex-shrink gap-3 text-xl">
{" "}
<button onClick={mediaPlayer.playPrevTrack}></button>
{mediaPlayer.loading ? (
<div className="animate-spin">߷</div>
) : !isPlaying ? (
<button onClick={playState.toggle}></button>
) : (
<button onClick={playState.toggle}></button>
)}
<button onClick={mediaPlayer.playNextTrack}></button>
</div>
<Waveform track={mediaPlayer.activeTrack} height={30} />
</div>
</div>
);
}

View File

@@ -0,0 +1,60 @@
import { useCoState } from "@/2_main";
import { MusicTrack, MusicTrackWaveform } from "@/1_schema";
import { usePlayerCurrentTime } from "@/lib/audio/usePlayerCurrentTime";
import { cn } from "@/lib/utils";
export function Waveform(props: { track: MusicTrack; height: number }) {
const { track, height } = props;
const waveformData = useCoState(
MusicTrackWaveform,
track._refs.waveform.id,
{},
)?.data;
const duration = track.duration;
const currentTime = usePlayerCurrentTime();
if (!waveformData) {
return (
<div
style={{
height,
}}
/>
);
}
const barCount = waveformData.length;
const activeBar = Math.ceil(barCount * (currentTime.value / duration));
function seek(i: number) {
currentTime.setValue((i / barCount) * duration);
}
return (
<div
className="flex justify-center items-end w-full"
style={{
height,
gap: 1,
}}
>
{waveformData.map((value, i) => (
<button
type="button"
key={i}
onClick={() => seek(i)}
className={cn(
"w-1 transition-colors rounded-none rounded-t-lg min-h-1",
activeBar >= i ? "bg-gray-500" : "bg-gray-300",
"hover:bg-black hover:border-1 hover:border-solid hover:border-black",
"focus-visible:outline-black focus:outline-none",
)}
style={{
height: height * value,
}}
/>
))}
</div>
);
}

View File

@@ -0,0 +1,56 @@
import { createContext, useContext } from "react";
export class AudioManager {
mediaElement: HTMLAudioElement;
audioObjectURL: string | null = null;
constructor() {
const mediaElement = new Audio();
this.mediaElement = mediaElement;
}
async unloadCurrentAudio() {
if (this.audioObjectURL) {
URL.revokeObjectURL(this.audioObjectURL);
this.audioObjectURL = null;
}
}
async loadAudio(file: Blob) {
await this.unloadCurrentAudio();
const { mediaElement } = this;
const audioObjectURL = URL.createObjectURL(file);
this.audioObjectURL = audioObjectURL;
mediaElement.src = audioObjectURL;
}
play() {
if (this.mediaElement.ended) {
this.mediaElement.fastSeek(0);
}
this.mediaElement.play();
}
pause() {
this.mediaElement.pause();
}
destroy() {
this.unloadCurrentAudio();
this.mediaElement.pause();
}
}
const context = createContext<AudioManager>(new AudioManager());
export function useAudioManager() {
return useContext(context);
}
export const AudionManagerProvider = context.Provider;

View File

@@ -0,0 +1,45 @@
export async function getAudioFileData(file: Blob, samples = 200) {
const ctx = new AudioContext();
const buffer = await file.arrayBuffer();
const decodedAudio = await ctx.decodeAudioData(buffer);
return {
waveform: transformDecodedAudioToWaveformData(decodedAudio, samples),
duration: decodedAudio.duration,
};
}
const transformDecodedAudioToWaveformData = (
audioBuffer: AudioBuffer,
samples: number,
) => {
const rawData = audioBuffer.getChannelData(0); // We only need to work with one channel of data
const blockSize = Math.floor(rawData.length / samples); // the number of samples in each subdivision
const sampledData: number[] = new Array(samples);
let max = 0;
for (let i = 0; i < samples; i++) {
const blockStart = blockSize * i; // the location of the first sample in the block
let sum = 0;
for (let j = 0; j < blockSize; j++) {
sum = sum + Math.abs(rawData[blockStart + j]); // find the sum of all the samples in the block
}
const sampledValue = sum / blockSize; // divide the sum by the block size to get the average
if (max < sampledValue) {
max = sampledValue;
}
sampledData[i] = sampledValue;
}
const multiplier = max ** -1;
for (let i = 0; i < samples; i++) {
sampledData[i] = sampledData[i] * multiplier;
}
return sampledData;
};

View File

@@ -0,0 +1,14 @@
import { useEffect } from "react";
import { useAudioManager } from "./AudioManager";
export function useMediaEndListener(callback: () => void) {
const audioManager = useAudioManager();
useEffect(() => {
audioManager.mediaElement.addEventListener("ended", callback);
return () => {
audioManager.mediaElement.removeEventListener("ended", callback);
};
}, [audioManager, callback]);
}

View File

@@ -0,0 +1,24 @@
import { useRef } from "react";
import { useAudioManager } from "./AudioManager";
export function usePlayMedia() {
const audioManager = useAudioManager();
const previousMediaLoad = useRef<Promise<unknown>>();
async function playMedia(file: Blob) {
// Wait for the previous load to finish
// to avoid to incur into concurrency issues
await previousMediaLoad.current;
const promise = audioManager.loadAudio(file);
previousMediaLoad.current = promise;
await promise;
audioManager.play();
}
return playMedia;
}

View File

@@ -0,0 +1,39 @@
import { useLayoutEffect, useState } from "react";
import { useAudioManager } from "./AudioManager";
export type PlayState = "pause" | "play";
export function usePlayState() {
const audioManager = useAudioManager();
const [value, setValue] = useState<PlayState>("pause");
useLayoutEffect(() => {
setValue(audioManager.mediaElement.paused ? "pause" : "play");
const onPlay = () => {
setValue("play");
};
const onPause = () => {
setValue("pause");
};
audioManager.mediaElement.addEventListener("play", onPlay);
audioManager.mediaElement.addEventListener("pause", onPause);
return () => {
audioManager.mediaElement.removeEventListener("play", onPlay);
audioManager.mediaElement.removeEventListener("pause", onPause);
};
}, [audioManager]);
function togglePlayState() {
if (value === "pause") {
audioManager.play();
} else {
audioManager.pause();
}
}
return { value, toggle: togglePlayState };
}

View File

@@ -0,0 +1,32 @@
import { useLayoutEffect, useState } from "react";
import { useAudioManager } from "./AudioManager";
export function usePlayerCurrentTime() {
const audioManager = useAudioManager();
const [value, setValue] = useState<number>(0);
useLayoutEffect(() => {
setValue(audioManager.mediaElement.currentTime);
const onTimeUpdate = () => {
setValue(audioManager.mediaElement.currentTime);
};
audioManager.mediaElement.addEventListener("timeupdate", onTimeUpdate);
return () => {
audioManager.mediaElement.removeEventListener("timeupdate", onTimeUpdate);
};
}, [audioManager]);
function setCurrentTime(time: number) {
if (audioManager.mediaElement.paused) audioManager.play();
audioManager.mediaElement.currentTime = time;
}
return {
value,
setValue: setCurrentTime,
};
}

View File

@@ -0,0 +1,30 @@
import { MusicaAccount } from "../1_schema";
export async function getNextTrack(account: MusicaAccount) {
if (!account.root?.activePlaylist?.tracks) return;
const tracks = account.root.activePlaylist.tracks;
const activeTrack = account.root._refs.activeTrack;
const currentIndex = tracks.findIndex(
(item) => item?.id === activeTrack.id,
);
const nextIndex = (currentIndex + 1) % tracks.length;
return tracks[nextIndex];
}
export async function getPrevTrack(account: MusicaAccount) {
if (!account.root?.activePlaylist?.tracks) return;
const tracks = account.root.activePlaylist.tracks;
const activeTrack = account.root._refs.activeTrack;
const currentIndex = tracks.findIndex(
(item) => item?.id === activeTrack.id,
);
const previousIndex = (currentIndex - 1 + tracks.length) % tracks.length;
return tracks[previousIndex];
}

View File

@@ -0,0 +1,16 @@
import { useEffect } from "react";
export function useKeyboardListener(code: string, callback: () => void) {
useEffect(() => {
const handler = (evt: KeyboardEvent) => {
if (evt.code === code) {
callback();
}
};
window.addEventListener("keyup", handler);
return () => {
window.removeEventListener("keyup", handler);
};
}, [callback, code]);
}

View File

@@ -0,0 +1,28 @@
import { useEffect } from "react";
import { useAccount } from "../2_main";
import { uploadMusicTracks } from "@/3_actions";
import { MusicaAccount } from "@/1_schema";
export function useUploadExampleData() {
const { me } = useAccount({
root: {}
});
const shouldUploadOnboardingData = me?.root?.exampleDataLoaded === false;
useEffect(() => {
if (me?.root && shouldUploadOnboardingData) {
me.root.exampleDataLoaded = true;
uploadOnboardingData(me).then(() => {
me.root.exampleDataLoaded = true;
});
}
}, [shouldUploadOnboardingData])
}
async function uploadOnboardingData(me: MusicaAccount) {
const trackFile = await (await fetch("/example.mp3")).blob();
return uploadMusicTracks(me, [new File([trackFile], "Example song")]);
}

View File

@@ -1,6 +1,6 @@
import { type ClassValue, clsx } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}

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