Compare commits

...

92 Commits

Author SHA1 Message Date
Anselm
99565ed03a Release 2024-10-09 17:34:10 +01:00
Anselm Eickhoff
1d3b9f9152 Merge pull request #469 from gardencmp/trishalim-jazz-342
Add book shelf example
2024-10-09 17:30:41 +01:00
Anselm
c3f4e6baec Add changeset for package export order changes 2024-10-09 17:30:10 +01:00
Anselm Eickhoff
7f0d24b113 Merge pull request #516 from gardencmp/anselm-jazz-371
Make feature copy more succinct
2024-10-09 17:26:36 +01:00
Anselm
52a649a352 Revert 2nd paragraph in local-first storage 2024-10-09 17:25:51 +01:00
Anselm
d4a89c4328 Shorten and clean up feature section 2024-10-09 17:06:04 +01:00
Trisha Lim
b15a295a73 Update lock file, fix error "Default condition should be last one" 2024-10-09 12:12:13 +01:00
Trisha Lim
fe384dfff6 Add book shelf example 2024-10-09 11:48:59 +01:00
Anselm Eickhoff
863eb73ad1 Merge pull request #484 from gardencmp/feature/chat-e2e
test: add basic e2e tests for the chat app
2024-10-09 10:55:09 +01:00
Anselm Eickhoff
5a41a9e7b9 Merge pull request #464 from gardencmp/feature/music-remake
feat: ui refresh for the music player
2024-10-09 10:50:52 +01:00
Anselm Eickhoff
f89e2772bc Fix expected Sign up button label 2024-10-09 10:49:09 +01:00
Anselm Eickhoff
7ca45c4a24 Merge pull request #494 from gardencmp/turbo-config-changes
Add build task as dependency for dev and test
2024-10-09 10:45:12 +01:00
Anselm Eickhoff
b4449b92bb Merge branch 'main' into feature/chat-e2e 2024-10-09 10:41:42 +01:00
Guido D'Orsi
10738a7c3d chore: update pkg 2024-10-09 11:41:17 +02:00
Anselm Eickhoff
08fdb0316a Merge pull request #492 from gardencmp/feature/co-json-types
fix(co.json): allow interface types as generic argument
2024-10-09 10:41:06 +01:00
Guido D'Orsi
6ebc5967f4 Merge remote-tracking branch 'origin/main' into feature/music-remake 2024-10-09 11:40:26 +02:00
Anselm
11a3da61e1 Fix jazz-run dev dep in chat example 2024-10-09 10:39:18 +01:00
Anselm Eickhoff
ef1592dbee Merge pull request #513 from gardencmp/test/pets-with-local-sync
test(pets): run tests using local sync
2024-10-09 10:35:44 +01:00
Anselm
d9152ed556 Add changeset 2024-10-09 10:31:38 +01:00
Anselm
509c8fad3f Merge branch 'main' into feature/co-json-types 2024-10-09 10:30:28 +01:00
Anselm Eickhoff
19b4f6d21d Merge pull request #510 from gardencmp/trishalim-jazz-370
Rename mesh to "Jazz Mesh", move section higher in the home page
2024-10-09 10:26:47 +01:00
Anselm
d705ef7e14 Release jazz-run 2024-10-09 10:19:36 +01:00
Guido D'Orsi
b99cc2a665 test(pets): run tests using local sync 2024-10-09 11:01:13 +02:00
Anselm Eickhoff
4e6e87aadd Merge pull request #512 from gardencmp/fix/jazz-run 2024-10-09 08:44:35 +01:00
Guido D'Orsi
561924f18f fix(jazz-run): fix broken import 2024-10-09 09:40:53 +02:00
Trisha Lim
80d5c32405 Update Jazz Mesh subheading 2024-10-08 18:04:12 +01:00
Trisha Lim
4b33a13758 Move Jazz Mesh section up the home page 2024-10-08 18:01:18 +01:00
Trisha Lim
8878c1eebd Fix home page spacing 2024-10-08 17:55:55 +01:00
Trisha Lim
c10ad968f9 Change "ours" to "Jazz Mesh" in diagram 2024-10-08 17:53:42 +01:00
Trisha Lim
a19b817818 Rename "Sync & Storage Mesh" to "Jazz Mesh" 2024-10-08 17:53:26 +01:00
Anselm Eickhoff
7192b142a3 Merge pull request #509 from gardencmp/fix/feature-section-layout 2024-10-08 17:19:09 +01:00
Trisha Lim
fc34a18934 Fix layout in homepage feature section 2024-10-08 17:08:40 +01:00
Anselm Eickhoff
d7ce6fa254 Merge branch 'main' into feature/co-json-types 2024-10-08 17:01:00 +01:00
Anselm Eickhoff
ed94e2ca2c Merge pull request #453 from gardencmp/trishalim-jazz-336
Fix scroll issue on chat example app if there are many users
2024-10-08 16:46:08 +01:00
Anselm Eickhoff
0c6e05e7ab Merge pull request #483 from gardencmp/trishalim-jazz-354
Make example code in package API reference readable
2024-10-08 16:44:21 +01:00
Anselm Eickhoff
a6e966438b Merge branch 'main' into trishalim-jazz-354 2024-10-08 16:39:07 +01:00
Anselm Eickhoff
f668bc05f2 Merge pull request #476 from davidvasandani/patch-1
fix: path issues
2024-10-08 16:37:31 +01:00
Anselm Eickhoff
4d95f8ea8e Merge pull request #477 from gardencmp/trishalim-jazz-348
Add copy button for code snippets
2024-10-08 16:37:05 +01:00
Anselm Eickhoff
9172558481 Merge pull request #508 from gardencmp/remove-top-cta
Remove top-level CTA buttons
2024-10-08 16:36:25 +01:00
Trisha Lim
fbdf091dd8 Remove top-level CTA buttons 2024-10-08 16:32:02 +01:00
Anselm Eickhoff
16c4fad514 Merge pull request #449 from gardencmp/trishalim-jazz-287
Homepage: redesign hero, add diagrams
2024-10-08 16:27:25 +01:00
Anselm
6e7591ab38 Last copy changes 2024-10-08 16:21:05 +01:00
Anselm
a85875bc53 Fix lint issues 2024-10-08 15:15:58 +01:00
Anselm
e1b25750b9 New feature copy 2024-10-08 15:06:17 +01:00
Anselm Eickhoff
eae6c27566 Merge pull request #497 from gardencmp/467-create-codate-shortcut
Add co.Date and update test
2024-10-08 14:31:22 +01:00
Anselm
f66079ea22 Fix lockfile 2024-10-08 12:18:49 +01:00
Anselm Eickhoff
2a35761401 Merge pull request #503 from gardencmp/fix/chat-height
Wrap text in chat message
2024-10-08 13:17:41 +02:00
Anselm
103a82075d Parent-frame friendlier navigation 2024-10-08 12:16:08 +01:00
Anselm
e85ab79026 Manually trigger hashchange event for now 2024-10-08 12:06:57 +01:00
Anselm
5f3680e749 Manually trigger hashchange for now 2024-10-08 12:06:27 +01:00
Trisha Lim
5956217b41 Revert "Fix: can't find input box in mobile til scrolling down"
This reverts commit 7295abeac5.
2024-10-08 12:02:41 +01:00
Anselm
03c0d81ca1 Stop chat example from creating history entries 2024-10-08 12:00:44 +01:00
Trisha Lim
0d53f378a0 Wrap text in chat app 2024-10-08 11:46:54 +01:00
Anselm
428ec8c170 Limit number of messages and scroll to bottom 2024-10-08 11:31:50 +01:00
Anselm Eickhoff
4cc442babc Merge pull request #500 from gardencmp/trishalim-jazz-365
Set 2048 character limit per message to chat app
2024-10-08 12:13:29 +02:00
Anselm Eickhoff
1f9b94c0c7 Apply suggestions from code review
Let's clamp to 10 lines
2024-10-08 11:11:27 +01:00
Trisha Lim
4c9d2b5a41 Limit chat messages to display 20 lines max 2024-10-08 11:08:11 +01:00
Trisha Lim
183e384819 Center align loading text in chat app 2024-10-08 11:08:11 +01:00
Trisha Lim
7295abeac5 Fix: can't find input box in mobile til scrolling down 2024-10-08 11:08:11 +01:00
Trisha Lim
77f1351000 Set 2048 character limit per message to chat app 2024-10-08 11:00:15 +01:00
Anselm Eickhoff
ba3e09a2a0 Merge pull request #501 from gardencmp/fix/chat-crash
fix(localNode): do not crash the app when we fail to resolve the account agent
2024-10-08 11:59:38 +02:00
Guido D'Orsi
21890eb99d fix(localNode): do not crash the app when we fail to resolve the account agent 2024-10-08 11:55:15 +02:00
Guido D'Orsi
489de02696 chore: update lockfile 2024-10-08 11:54:38 +02:00
Guido D'Orsi
4c3be94376 chore: update lockfile 2024-10-07 19:30:47 +02:00
Benjamin S. Leveritt
37180974a8 chore: update pnpm lock 2024-10-07 17:43:35 +01:00
Benjamin S. Leveritt
8cf1aa5ac4 Add co.Date and update test 2024-10-07 17:30:26 +01:00
Guido D'Orsi
7aee91eb83 fix(co.json): accept optional types 2024-10-07 16:38:55 +02:00
Guido D'Orsi
8890c84d39 fix(co.json): accept types with optional parameters 2024-10-07 16:38:55 +02:00
Guido D'Orsi
2b301c723b chore(jsonValue): fix typo in a comment 2024-10-07 16:38:55 +02:00
Guido D'Orsi
6e7f4facbd fix(co.json): allow nested interface types 2024-10-07 16:38:55 +02:00
Guido D'Orsi
a2ec72eab2 fix(co.json): disallow functions and Regexp 2024-10-07 16:38:55 +02:00
Guido D'Orsi
7ac660820f fix(co.json): allow interface types as generic argument 2024-10-07 16:38:55 +02:00
Benjamin S. Leveritt
72c33640f6 Add build task as dependency for dev and test 2024-10-07 15:16:06 +01:00
Trisha Lim
92e9ea50d4 Fix scroll issue on chat example app if there are many users 2024-10-07 14:55:18 +01:00
Trisha Lim
d1c4f16df0 Change "Sign up as new account" to "Sign up" 2024-10-07 14:44:41 +01:00
Guido D'Orsi
079963fb47 chore(chat): add a sr-only label to the message box 2024-10-06 11:35:39 +02:00
Guido D'Orsi
82f0ebaf6f test: add basic e2e tests for the chat app 2024-10-04 19:28:22 +02:00
Trisha Lim
3772ef9645 Don't wrap code in the middle of paragraph 2024-10-04 17:18:24 +01:00
Trisha Lim
0e67bdccfc Fix spacing in mobile menu hamburger icon 2024-10-04 17:13:42 +01:00
Trisha Lim
39e33f4fac Make example code in package API reference readable 2024-10-04 17:13:42 +01:00
Trisha Lim
f2f10c58d7 Add copy button for code snippets 2024-10-02 20:43:05 +01:00
David Vasandani
3d77fff140 fix: path issues 2024-10-02 09:50:11 -07:00
Guido D'Orsi
abbda85c16 feat: clean up unused files and optimize subscriptions 2024-10-01 19:42:38 +02:00
Guido D'Orsi
625ddd5db9 feat: ui refresh for the music player 2024-10-01 16:30:05 +02:00
Trisha Lim
9e1fa1adc6 Update illustration copy to be lowercase 2024-10-01 11:33:10 +01:00
Trisha Lim
f290f7716e Fix logo not center aligned 2024-09-27 12:48:11 +01:00
Trisha Lim
3a83fdf005 Button hover styles 2024-09-26 19:06:42 +01:00
Trisha Lim
88ca9fe406 Make arrow more subtle 2024-09-26 19:06:42 +01:00
Trisha Lim
00e5847fbe Add CTA buttons to bottom of home page 2024-09-26 19:06:42 +01:00
Trisha Lim
7d54bc8cdd Add button component 2024-09-26 19:06:42 +01:00
Trisha Lim
b684ca1fd6 Add diagram for light mode 2024-09-26 19:06:42 +01:00
Trisha Lim
3c934e97ac Add diagram to homepage, rewrite copy 2024-09-26 19:06:42 +01:00
160 changed files with 6234 additions and 1119 deletions

View File

@@ -10,9 +10,10 @@ jobs:
test:
timeout-minutes: 60
runs-on: ubuntu-latest
continue-on-error: true
strategy:
matrix:
project: ["e2e/BinaryCoStream", "e2e/CoValues", "examples/pets"]
project: ["e2e/BinaryCoStream", "e2e/CoValues", "examples/chat", "examples/pets"]
steps:
- uses: actions/checkout@v3
@@ -45,8 +46,12 @@ jobs:
run: pnpm install --frozen-lockfile
- name: Pnpm Build
run: pnpm turbo build;
run: pnpm turbo build
working-directory: ./${{ matrix.project }}
- name: Build jazz-run
run: pnpm exec turbo build && chmod +x dist/index.js;
working-directory: ./packages/jazz-run
- name: Install Playwright Browsers
run: pnpm exec playwright install --with-deps

View File

@@ -41,7 +41,7 @@ jobs:
run: pnpm install --frozen-lockfile
- name: Pnpm Build
run: pnpm turbo build;
run: pnpm turbo build
- name: Unit Tests
run: pnpm test

View File

@@ -1,5 +1,22 @@
# @jazz-e2e/binarycostream
## 0.0.86
### Patch Changes
- Updated dependencies [c3f4e6b]
- Updated dependencies [d9152ed]
- jazz-tools@0.8.5
- cojson@0.8.5
- jazz-react@0.8.5
## 0.0.85
### Patch Changes
- Updated dependencies
- hash-slash@0.2.1
## 0.0.84
### Patch Changes

View File

@@ -1,7 +1,7 @@
{
"name": "@jazz-e2e/binarycostream",
"private": true,
"version": "0.0.84",
"version": "0.0.86",
"type": "module",
"scripts": {
"dev": "vite",
@@ -14,11 +14,11 @@
"*.{js,jsx,mdx,json}": "prettier --write"
},
"dependencies": {
"cojson": "workspace:0.8.3",
"hash-slash": "workspace:0.2.0",
"cojson": "workspace:0.8.5",
"hash-slash": "workspace:0.2.1",
"is-ci": "^3.0.1",
"jazz-react": "workspace:0.8.3",
"jazz-tools": "workspace:0.8.3",
"jazz-react": "workspace:0.8.5",
"jazz-tools": "workspace:0.8.5",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},

View File

@@ -1,5 +1,22 @@
# @jazz-e2e/covalues
## 0.0.85
### Patch Changes
- Updated dependencies [c3f4e6b]
- Updated dependencies [d9152ed]
- jazz-tools@0.8.5
- cojson@0.8.5
- jazz-react@0.8.5
## 0.0.84
### Patch Changes
- Updated dependencies
- hash-slash@0.2.1
## 0.0.83
### Patch Changes

View File

@@ -1,7 +1,7 @@
{
"name": "@jazz-e2e/covalues",
"private": true,
"version": "0.0.83",
"version": "0.0.85",
"type": "module",
"scripts": {
"dev": "vite",

View File

@@ -0,0 +1,11 @@
{
"extends": [
"next/core-web-vitals",
"prettier",
"plugin:prettier/recommended"
],
"plugins": ["prettier"],
"rules": {
"prettier/prettier": ["error"]
}
}

36
examples/book-shelf/.gitignore vendored Normal file
View File

@@ -0,0 +1,36 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
.yarn/install-state.gz
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# local env files
.env*.local
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts

View File

@@ -0,0 +1,11 @@
{
"tabWidth": 2,
"useTabs": false,
"semi": true,
"singleQuote": false,
"trailingComma": "es5",
"bracketSpacing": true,
"arrowParens": "avoid",
"printWidth": 80,
"plugins": ["prettier-plugin-tailwindcss"]
}

View File

@@ -0,0 +1,11 @@
# jazz-example-book-shelf
## 0.1.1
### Patch Changes
- Updated dependencies [c3f4e6b]
- Updated dependencies [d9152ed]
- jazz-tools@0.8.5
- jazz-browser-media-images@0.8.5
- jazz-react@0.8.5

View File

@@ -0,0 +1,4 @@
FROM caddy:2.7.3-alpine
LABEL org.opencontainers.image.source="https://github.com/gardencmp/jazz"
COPY ./dist /usr/share/caddy/

View File

@@ -0,0 +1,41 @@
# Jazz Book Shelf Example
## 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`
Install dependencies:
```bash
pnpm install
```
Go to the `examples/book-shelf` directory.
```bash
cd examples/book-shelf
```
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 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/components/JazzAndAuth.tsx](./src/2_main.tsx).

View File

@@ -0,0 +1,56 @@
job "example-bookShelf$BRANCH_SUFFIX" {
region = "global"
datacenters = ["*"]
group "static" {
count = 4
network {
port "http" {
to = 80
}
}
constraint {
attribute = "${node.class}"
operator = "="
value = "mesh"
}
spread {
attribute = "${node.datacenter}"
weight = 100
}
constraint {
distinct_hosts = true
}
task "server" {
driver = "docker"
config {
image = "$DOCKER_TAG"
ports = ["http"]
auth = {
username = "$DOCKER_USER"
password = "$DOCKER_PASSWORD"
}
}
service {
tags = ["public"]
name = "example-bookShelf$BRANCH_SUFFIX"
port = "http"
provider = "consul"
}
resources {
cpu = 50 # MHz
memory = 50 # MB
}
}
}
}
# deploy bump 4

5
examples/book-shelf/next-env.d.ts vendored Normal file
View File

@@ -0,0 +1,5 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.

View File

@@ -0,0 +1,4 @@
/** @type {import('next').NextConfig} */
const nextConfig = {};
export default nextConfig;

View File

@@ -0,0 +1,35 @@
{
"name": "jazz-example-book-shelf",
"version": "0.1.1",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint",
"format": "prettier --write ."
},
"dependencies": {
"clsx": "^2.0.0",
"jazz-browser-media-images": "workspace:0.8.5",
"jazz-react": "workspace:0.8.5",
"jazz-tools": "workspace:0.8.5",
"next": "14.2.5",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"@types/node": "^22.5.1",
"@types/react": "^18.2.19",
"@types/react-dom": "^18.2.7",
"eslint": "^8.46.0",
"eslint-config-next": "14.2.5",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-prettier": "^5.2.1",
"postcss": "^8.4.27",
"prettier": "^3.1.1",
"prettier-plugin-tailwindcss": "^0.6.5",
"tailwindcss": "3.3.2",
"typescript": "^5.3.3"
}
}

View File

@@ -0,0 +1,8 @@
/** @type {import('postcss-load-config').Config} */
const config = {
plugins: {
tailwindcss: {},
},
};
export default config;

View File

@@ -0,0 +1,136 @@
"use client";
import { ChangeEvent, useState } from "react";
import { BookReview, ListOfBookReviews } from "@/schema";
import { useAccount } from "@/components/JazzAndAuth";
import { useRouter } from "next/navigation";
import RatingInput from "@/components/RatingInput";
import { createImage } from "jazz-browser-media-images";
import { Group, ImageDefinition } from "jazz-tools";
import { Container } from "@/components/Container";
import { Button } from "@/components/Button";
export default function AddBookReview() {
const { me } = useAccount();
const [title, setTitle] = useState("");
const [author, setAuthor] = useState("");
const [review, setReview] = useState("");
const [rating, setRating] = useState(0);
const [dateRead, setDateRead] = useState(
new Date().toISOString().split("T")[0]
);
const [coverImage, setCoverImage] = useState<ImageDefinition | undefined>();
const router = useRouter();
const onDateChange = (event: ChangeEvent<HTMLInputElement>) => {
const date = new Date(event.currentTarget.value)
.toISOString()
.split("T")[0];
setDateRead(date);
};
const onImageChange = (event: ChangeEvent<HTMLInputElement>) => {
const file = event.currentTarget.files?.[0];
const group = Group.create({ owner: me });
group.addMember("everyone", "reader");
if (file) {
createImage(file, { owner: group }).then(image => {
setCoverImage(image);
});
}
};
const onSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
if (!me?.profile) return;
const bookReview = BookReview.create(
{
title,
author,
review,
rating,
dateRead: new Date(dateRead),
cover: coverImage,
},
{
owner: me.profile._owner,
}
);
if (!me.profile.bookReviews) {
me.profile.bookReviews = ListOfBookReviews.create([], {
owner: me.profile._owner,
});
}
me.profile.bookReviews.push(bookReview);
router.push("/");
};
return (
<Container className="grid max-w-lg gap-8 py-8">
<h1 className="text-lg font-semibold text-black">Add book review</h1>
<form action="" className="grid gap-4" onSubmit={onSubmit}>
<label className="grid gap-1 text-sm text-gray-600">
Cover
<input type="file" onChange={onImageChange} />
</label>
<label className="grid gap-1 text-sm text-gray-600">
Title
<input
className="rounded border border-gray-300 px-2 py-1 shadow-sm"
type="text"
value={title}
required
onChange={e => setTitle(e.target.value)}
></input>
</label>
<label className="grid gap-1 text-sm text-gray-600">
Author
<input
className="rounded border border-gray-300 px-2 py-1 shadow-sm"
type="text"
value={author}
required
onChange={e => setAuthor(e.target.value)}
></input>
</label>
<label className="grid gap-1 text-sm text-gray-600">
Date read
<input
className="rounded border border-gray-300 px-2 py-1 shadow-sm"
type="date"
value={dateRead}
required
onChange={onDateChange}
/>
</label>
<div className="grid gap-1 text-sm text-gray-600">
Rating
<RatingInput value={rating} onChange={rating => setRating(rating)} />
</div>
<label className="grid gap-1 text-sm text-gray-600">
Review
<textarea
className="rounded border border-gray-300 px-2 py-1 shadow-sm"
value={review}
onChange={e => setReview(e.target.value)}
></textarea>
</label>
<Button variant="primary" type="submit">
Add
</Button>
</form>
</Container>
);
}

View File

@@ -0,0 +1,172 @@
"use client";
import { useCoState } from "@/components/JazzAndAuth";
import { BookReview } from "@/schema";
import { Group, ID } from "jazz-tools";
import { BookCover } from "@/components/BookCover";
import clsx from "clsx";
import RatingInput from "@/components/RatingInput";
import Rating from "@/components/Rating";
import { Container } from "@/components/Container";
const BookReviewTitle = ({
bookReview,
readOnly,
}: {
bookReview: BookReview;
readOnly: boolean;
}) => {
const className = "font-serif text-2xl font-bold lg:text-4xl";
if (readOnly) {
return <h1 className={className}>{bookReview.title}</h1>;
}
return (
<input
value={bookReview.title}
placeholder="Book title"
className={clsx(
className,
"w-full rounded border border-transparent px-2 py-1 hover:border-gray-300 hover:shadow-sm"
)}
onChange={e => (bookReview.title = e.target.value)}
></input>
);
};
const BookReviewAuthor = ({
bookReview,
readOnly,
}: {
bookReview: BookReview;
readOnly: boolean;
}) => {
const className = "text-gray-700";
if (readOnly) {
return <p className={className}>by {bookReview.author}</p>;
}
return (
<input
value={bookReview.author}
placeholder="Author"
className={clsx(
className,
"w-full rounded border border-transparent px-2 py-1 hover:border-gray-300 hover:shadow-sm"
)}
onChange={e => (bookReview.author = e.target.value)}
></input>
);
};
const BookReviewDateRead = ({
bookReview,
readOnly,
}: {
bookReview: BookReview;
readOnly: boolean;
}) => {
const className = "text-gray-700 max-w-[10rem]";
if (readOnly) {
return (
bookReview.dateRead && (
<p className={className}>{bookReview.dateRead.toLocaleDateString()}</p>
)
);
}
return (
<input
type="date"
value={bookReview.dateRead?.toISOString().split("T")[0]}
placeholder="Date read"
className={clsx(
className,
"w-full rounded border border-transparent px-2 py-1 hover:border-gray-300 hover:shadow-sm"
)}
onChange={e => {
const date = new Date(e.target.value);
bookReview.dateRead = date;
}}
></input>
);
};
const BookReviewReview = ({
bookReview,
readOnly,
}: {
bookReview: BookReview;
readOnly: boolean;
}) => {
const className = "text-sm leading-relaxed text-gray-600";
if (readOnly) {
if (bookReview.review) {
return <p className={className}>{bookReview.review}</p>;
}
}
return (
<textarea
value={bookReview.review}
placeholder="Write your review here..."
className={clsx(
className,
"w-full rounded border border-transparent px-2 py-1 hover:border-gray-300 hover:shadow-sm"
)}
onChange={e => (bookReview.review = e.target.value)}
></textarea>
);
};
const BookReviewRating = ({
bookReview,
readOnly,
}: {
bookReview: BookReview;
readOnly: boolean;
}) => {
const className = "text-2xl sm:mx-0";
if (readOnly) {
return <Rating className={className} rating={bookReview.rating} />;
}
return (
<RatingInput
className={clsx(className, "p-2")}
onChange={rating => (bookReview.rating = rating)}
value={bookReview.rating}
/>
);
};
export default function Page({ params }: { params: { slug: string } }) {
const bookReview = useCoState(BookReview, params.slug as ID<BookReview>);
if (!bookReview) return <></>;
const readOnly = !(bookReview._owner.castAs(Group).myRole() === "admin");
return (
<Container className="grid gap-12 py-8">
<div className="flex flex-col gap-6 sm:flex-row md:gap-10">
<div className="w-[180px]">
<BookCover bookReview={bookReview} readOnly={readOnly} />
</div>
<div className="-mx-2 grid max-w-lg flex-1 gap-3 sm:mx-0">
<BookReviewTitle bookReview={bookReview} readOnly={readOnly} />
<BookReviewAuthor bookReview={bookReview} readOnly={readOnly} />
<BookReviewDateRead bookReview={bookReview} readOnly={readOnly} />
<BookReviewRating bookReview={bookReview} readOnly={readOnly} />
<BookReviewReview bookReview={bookReview} readOnly={readOnly} />
</div>
</div>
</Container>
);
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

View File

@@ -0,0 +1,13 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
:focus {
@apply outline-none;
}
:focus-visible {
@apply ring-2 ring-purple-600/75 dark:ring-2 dark:ring-white/75;
}
}

View File

@@ -0,0 +1,39 @@
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css";
import { JazzAndAuth } from "@/components/JazzAndAuth";
import { Nav } from "@/components/Nav";
import { Fraunces } from "next/font/google";
import clsx from "clsx";
const fraunces = Fraunces({
subsets: ["latin"],
display: "swap",
variable: "--font-fraunces",
});
const inter = Inter({ subsets: ["latin"] });
export const metadata: Metadata = {
title: "Jazz Book Shelf",
description: "Jazz Book Shelf",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<body className={clsx(inter.className, fraunces.variable)}>
<JazzAndAuth>
<header>
<Nav />
</header>
<main>{children}</main>
</JazzAndAuth>
</body>
</html>
);
}

View File

@@ -0,0 +1,27 @@
"use client";
import { useAccount } from "@/components/JazzAndAuth";
import UserProfile from "@/components/UserProfile";
import { JazzAccount } from "@/schema";
import { ID } from "jazz-tools";
import { Container } from "@/components/Container";
export default function Home() {
const { me } = useAccount();
return (
<Container className="grid gap-12 py-8">
<UserProfile id={me?.id as ID<JazzAccount>} />
<label className="flex flex-wrap items-center gap-3">
Share your profile:
<input
type="text"
className="w-full rounded border p-1"
value={`http://localhost:3000/user/${me?.id}`}
readOnly
/>
</label>
</Container>
);
}

View File

@@ -0,0 +1,14 @@
import UserProfile from "@/components/UserProfile";
import { JazzAccount } from "@/schema";
import { ID } from "jazz-tools";
import { Container } from "@/components/Container";
export default function Page({ params }: { params: { slug: string } }) {
const { slug } = params;
return (
<Container className="py-8">
<UserProfile id={slug as ID<JazzAccount>} />
</Container>
);
}

View File

@@ -0,0 +1,134 @@
import { ProgressiveImg } from "jazz-react";
import { BookReview } from "@/schema";
import { ChangeEvent, useRef, useState } from "react";
import { Group, ImageDefinition } from "jazz-tools";
import { createImage } from "jazz-browser-media-images";
import { useAccount } from "@/components/JazzAndAuth";
import clsx from "clsx";
import PlusIcon from "@/components/icons/PlusIcon";
import { Button } from "@/components/Button";
const BookCoverContainer = ({
children,
className = "",
}: {
children: React.ReactNode;
className?: string;
}) => {
return (
<div className={clsx("h-[240px] lg:h-[260px]", className)}>{children}</div>
);
};
const MockCover = ({ bookReview }: { bookReview: BookReview }) => {
return (
<div className="flex h-full flex-col items-center justify-center gap-3 rounded-l-sm rounded-r-md bg-gray-100 px-3 text-center shadow-lg">
<p className="font-medium">{bookReview.title}</p>
<p className="text-xs">{bookReview.author}</p>
</div>
);
};
export function BookCoverReadOnly({
bookReview,
className,
}: {
bookReview: BookReview;
className?: string;
}) {
if (bookReview.cover) {
return (
<BookCoverContainer className={className}>
<ProgressiveImg image={bookReview.cover}>
{({ src }) => (
<img
className="max-h-full max-w-full rounded-l-sm rounded-r-md shadow-lg"
src={src}
/>
)}
</ProgressiveImg>
</BookCoverContainer>
);
}
return (
<BookCoverContainer className={className}>
<MockCover bookReview={bookReview} />
</BookCoverContainer>
);
}
export function BookCoverInput({ bookReview }: { bookReview: BookReview }) {
const { me } = useAccount();
const inputRef = useRef<HTMLInputElement>(null);
const onImageChange = (event: ChangeEvent<HTMLInputElement>) => {
if (!me?.profile) return;
const file = event.currentTarget.files?.[0];
if (file) {
createImage(file, { owner: me.profile._owner }).then(image => {
bookReview.cover = image;
});
}
};
const onUploadClick = () => {
inputRef.current?.click();
};
const remove = () => {
bookReview.cover = null;
};
if (bookReview.cover) {
return (
<div className="group relative inline-block">
<BookCoverReadOnly
className="transition-opacity group-hover:opacity-40"
bookReview={bookReview}
/>
<div className="absolute left-0 top-0 hidden h-full w-full items-center justify-center rounded-l-sm rounded-r-md group-hover:flex">
<Button
variant="tertiary"
type="button"
className="shadow"
onClick={remove}
>
Remove
</Button>
</div>
</div>
);
}
return (
<BookCoverContainer className="flex w-[180px] flex-col justify-center rounded-l-sm rounded-r-md bg-gray-100 p-3 shadow-lg">
<button
className="flex h-full w-full flex-col items-center justify-center gap-3 text-gray-500 transition-colors hover:text-gray-600"
type="button"
onClick={onUploadClick}
>
<PlusIcon className="h-10 w-10" />
Upload book cover
</button>
<label className="sr-only">
Cover
<input ref={inputRef} type="file" onChange={onImageChange} />
</label>
</BookCoverContainer>
);
}
export function BookCover({
bookReview,
readOnly,
}: {
bookReview: BookReview;
readOnly?: boolean;
}) {
if (readOnly) return <BookCoverReadOnly bookReview={bookReview} />;
return <BookCoverInput bookReview={bookReview} />;
}

View File

@@ -0,0 +1,30 @@
import { BookReview } from "@/schema";
import Rating from "@/components/Rating";
import { Group } from "jazz-tools";
import RatingInput from "@/components/RatingInput";
import { BookCover } from "@/components/BookCover";
export function BookReviewHeader({ bookReview }: { bookReview: BookReview }) {
const { title, author, rating, review, dateRead } = bookReview;
return (
<div className="grid gap-5">
<div>
<h1 className="mb-1 font-serif text-2xl font-bold md:mb-3 lg:text-4xl">
{title}
</h1>
<p className="text-gray-500">by {author}</p>
</div>
{bookReview._owner.castAs(Group).myRole() === "admin" ? (
<RatingInput
onChange={rating => (bookReview.rating = rating)}
value={rating}
/>
) : (
<Rating className="mx-auto text-2xl sm:mx-0" rating={rating} />
)}
</div>
);
}

View File

@@ -0,0 +1,35 @@
"use client";
import { BookReview } from "../schema";
import { ID } from "jazz-tools";
import { useCoState } from "@/components/JazzAndAuth";
import Link from "next/link";
import { BookCover, BookCoverReadOnly } from "@/components/BookCover";
import StarIcon from "@/components/icons/StarIcon";
export function BookReviewThumbnail({ id }: { id: ID<BookReview> }) {
const bookReview = useCoState(BookReview, id);
if (!bookReview) return <></>;
return (
<div className="inline-flex shrink-0 gap-4 rounded border p-4 sm:block sm:space-y-6 sm:border-0 sm:p-0 md:w-[200px]">
<Link href={`/book/${bookReview.id}`} className="sm:block sm:flex-1">
<BookCoverReadOnly bookReview={bookReview} />
</Link>
<div className="flex-1">
<Link href={`/book/${bookReview.id}`}>
<h2 className="mb-1 text-sm font-medium">{bookReview.title}</h2>
</Link>
<div className="mb-2 flex flex-col gap-2 text-sm text-gray-500 sm:flex-row sm:items-center">
<p>{bookReview.author}</p>
<div className="flex items-center gap-0.5 text-xs font-semibold leading-none">
<StarIcon className="-mt-px text-base text-yellow-400" />
{bookReview.rating}
</div>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,65 @@
import Link from "next/link";
import type { ComponentProps } from "react";
import clsx from "clsx";
interface Props {
variant?: "primary" | "secondary" | "tertiary";
className?: string;
size?: "sm" | "md" | "lg";
}
interface AnchorProps
extends Props,
React.AnchorHTMLAttributes<HTMLAnchorElement> {
href: string;
}
type ButtonProps = ComponentProps<"button"> & Props;
export function Button(props: AnchorProps | ButtonProps) {
const {
className: customClassName = "",
variant = "primary",
children,
size = "md",
} = props;
const variantClassNames = {
base: "inline-flex gap-2 items-center justify-center rounded-full overflow-hidden transition-colors",
primary:
"bg-purple-300 font-medium text-purple-950 px-4 py-2 rounded-full hover:bg-purple-200",
secondary:
"rounded-full bg-slate-100 font-medium text-slate-600 hover:bg-slate-200",
tertiary: "rounded-full bg-white text-purple-950 font-medium",
};
const sizeClassNames = {
sm: "py-1.5 px-3 text-sm",
md: "py-2 px-5",
lg: "py-2 md:py-2.5 px-6 md:text-lg",
};
const className = clsx(
customClassName,
variantClassNames.base,
variantClassNames[variant],
sizeClassNames[size]
);
if (!!(props as AnchorProps).href) {
const anchorProps = props as AnchorProps;
return (
<Link href={anchorProps.href} className={className}>
{children}
</Link>
);
}
const buttonProps = props as ButtonProps;
return (
<button {...buttonProps} className={className}>
{children}
</button>
);
}

View File

@@ -0,0 +1,13 @@
import clsx from "clsx";
export function Container({
children,
className,
}: {
children: React.ReactNode;
className?: string;
}) {
return (
<div className={clsx("mx-auto max-w-4xl px-4", className)}>{children}</div>
);
}

View File

@@ -0,0 +1,29 @@
"use client";
import { createJazzReactApp, useDemoAuth, DemoAuthBasicUI } from "jazz-react";
import { JazzAccount } from "@/schema";
const Jazz = createJazzReactApp({
AccountSchema: JazzAccount,
});
export const { useAccount, useCoState } = Jazz;
export function JazzAndAuth({ children }: { children: React.ReactNode }) {
const [auth, authState] = useDemoAuth();
return (
<>
<Jazz.Provider
auth={auth}
// replace `you@example.com` with your email as a temporary API key
peer="wss://mesh.jazz.tools/?key=you@example.com"
>
{children}
</Jazz.Provider>
{authState.state !== "signedIn" && (
<DemoAuthBasicUI appName="Jazz Book Shelf" state={authState} />
)}
</>
);
}

View File

@@ -0,0 +1,26 @@
"use client";
import { useAccount } from "@/components/JazzAndAuth";
import Link from "next/link";
import { Container } from "@/components/Container";
import { Button } from "@/components/Button";
export function Nav() {
const { me, logOut } = useAccount();
return (
<nav className="border-b py-3">
<Container className="flex items-center justify-between gap-12 text-sm">
<Link href="/" className="font-serif text-lg font-semibold">
Jazz Book Shelf
</Link>
<div className="flex items-center gap-4 text-sm">
<p>{me?.profile?.name}</p>
<Button variant="secondary" onClick={logOut}>
Log out
</Button>
</div>
</Container>
</nav>
);
}

View File

@@ -0,0 +1,21 @@
import StarIcon from "@/components/icons/StarIcon";
import StarOutlineIcon from "@/components/icons/StarOutlineIcon";
export default function Rating({
rating,
className = "",
}: {
rating?: number;
className?: string;
}) {
const max = 5;
const outline = max - (rating || 0);
return (
<div className={`inline-flex gap-0.5 text-yellow-400 ${className}`}>
{rating ? [...Array(rating)].map((x, i) => <StarIcon key={i} />) : <></>}
{[...Array(outline)].map((x, i) => (
<StarOutlineIcon key={i} />
))}
</div>
);
}

View File

@@ -0,0 +1,47 @@
"use client";
import StarOutlineIcon from "@/components/icons/StarOutlineIcon";
import StarIcon from "@/components/icons/StarIcon";
import clsx from "clsx";
interface RatingInputProps {
value?: number;
onChange: (value: number) => void;
className?: string;
}
export default function RatingInput({
value = 0,
onChange,
className,
}: RatingInputProps) {
const handleChange = (newRating: number) => {
onChange(newRating > 5 ? 5 : newRating);
};
return (
<div className={clsx(className, "flex gap-0.5 text-2xl text-yellow-400")}>
{[...Array(5)].map((_, i) => {
return i < value ? (
<button
type="button"
className="focus:outline-none"
onClick={() => handleChange(i + 1)}
key={i}
>
<StarIcon />
</button>
) : (
<button
type="button"
className="focus:outline-none"
onClick={() => handleChange(i + 1)}
key={i}
>
<StarOutlineIcon />
</button>
);
})}
</div>
);
}

View File

@@ -0,0 +1,39 @@
"use client";
import { useCoState } from "@/components/JazzAndAuth";
import { Group, ID } from "jazz-tools";
import { JazzAccount, JazzProfile, ListOfBookReviews } from "@/schema";
import { BookReviewThumbnail } from "@/components/BookReviewThumbnail";
import { Button } from "@/components/Button";
export default function UserProfile({ id }: { id: ID<JazzAccount> }) {
const user = useCoState(JazzAccount, id);
const profile = useCoState(JazzProfile, user?.profile?.id);
const bookReviews = useCoState(
ListOfBookReviews,
user?.profile?._refs.bookReviews?.id,
[{}]
);
return (
<div className="grid gap-4">
<div className="flex items-center justify-between">
<h1 className="font-serif text-lg font-medium sm:text-2xl">
{profile?.name}&apos;s book shelf
</h1>
{profile?._owner.castAs(Group).myRole() === "admin" && (
<Button href="/add" variant="primary">
Add book
</Button>
)}
</div>
<div className="grid gap-4 md:grid-cols-4">
{bookReviews?.map(bookReview => (
<BookReviewThumbnail key={bookReview.id} id={bookReview.id} />
))}
</div>
</div>
);
}

View File

@@ -0,0 +1,20 @@
export default function PlusIcon({ className }: { className?: string }) {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
strokeWidth={1.5}
stroke="currentColor"
className={className}
width="1em"
height="1em"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M12 4.5v15m7.5-7.5h-15"
/>
</svg>
);
}

View File

@@ -0,0 +1,18 @@
export default function StarIcon({ className }: { className?: string }) {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
fill="currentColor"
className={className}
width="1em"
height="1em"
>
<path
fillRule="evenodd"
d="M10.788 3.21c.448-1.077 1.976-1.077 2.424 0l2.082 5.006 5.404.434c1.164.093 1.636 1.545.749 2.305l-4.117 3.527 1.257 5.273c.271 1.136-.964 2.033-1.96 1.425L12 18.354 7.373 21.18c-.996.608-2.231-.29-1.96-1.425l1.257-5.273-4.117-3.527c-.887-.76-.415-2.212.749-2.305l5.404-.434 2.082-5.005Z"
clipRule="evenodd"
/>
</svg>
);
}

View File

@@ -0,0 +1,20 @@
export default function StarOutlineIcon({ className }: { className?: string }) {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
strokeWidth={1.5}
stroke="currentColor"
className={className}
width="1em"
height="1em"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M11.48 3.499a.562.562 0 0 1 1.04 0l2.125 5.111a.563.563 0 0 0 .475.345l5.518.442c.499.04.701.663.321.988l-4.204 3.602a.563.563 0 0 0-.182.557l1.285 5.385a.562.562 0 0 1-.84.61l-4.725-2.885a.562.562 0 0 0-.586 0L6.982 20.54a.562.562 0 0 1-.84-.61l1.285-5.386a.562.562 0 0 0-.182-.557l-4.204-3.602a.562.562 0 0 1 .321-.988l5.518-.442a.563.563 0 0 0 .475-.345L11.48 3.5Z"
/>
</svg>
);
}

View File

@@ -0,0 +1,37 @@
import {
CoMap,
co,
CoList,
Account,
Profile,
ImageDefinition,
Encoders,
} from "jazz-tools";
export class BookReview extends CoMap {
title = co.string;
author = co.string;
rating = co.number;
dateRead? = co.encoded(Encoders.Date);
review? = co.string;
cover? = co.ref(ImageDefinition, { optional: true });
}
export class ListOfBookReviews extends CoList.Of(co.ref(BookReview)) {}
/** The profile is an app-specific per-user public `CoMap`
* where you can store top-level objects for that user */
export class JazzProfile extends Profile {
bookReviews = co.ref(ListOfBookReviews);
}
export class JazzAccount extends Account {
profile = co.ref(JazzProfile);
/** 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.
*/
migrate(this: JazzAccount, creationProps?: { name: string }) {
super.migrate(creationProps);
}
}

View File

@@ -0,0 +1,25 @@
import type { Config } from "tailwindcss";
const colors = require("tailwindcss/colors");
const config: Config = {
content: [
"./src/pages/**/*.{js,ts,jsx,tsx,mdx}",
"./src/components/**/*.{js,ts,jsx,tsx,mdx}",
"./src/app/**/*.{js,ts,jsx,tsx,mdx}",
],
theme: {
extend: {
fontFamily: {
serif: ["var(--font-fraunces)"],
},
colors: {
purple: {
...colors.purple,
950: "#211f5a",
},
},
},
},
plugins: [],
};
export default config;

View File

@@ -0,0 +1,28 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2023", "DOM", "DOM.Iterable"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./src/*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}

View File

@@ -1,5 +1,23 @@
# jazz-example-chat
## 0.0.85
### Patch Changes
- Updated dependencies [c3f4e6b]
- Updated dependencies [d9152ed]
- jazz-tools@0.8.5
- cojson@0.8.5
- jazz-react@0.8.5
- jazz-react-auth-clerk@0.8.5
## 0.0.84
### Patch Changes
- Updated dependencies
- hash-slash@0.2.1
## 0.0.83
### Patch Changes

View File

@@ -1,7 +1,7 @@
{
"name": "jazz-example-chat-clerk",
"private": true,
"version": "0.0.83",
"version": "0.0.85",
"type": "module",
"scripts": {
"dev": "vite",
@@ -21,11 +21,11 @@
"@radix-ui/react-toast": "^1.1.4",
"class-variance-authority": "^0.7.0",
"clsx": "^2.0.0",
"cojson": "workspace:0.8.3",
"hash-slash": "workspace:0.2.0",
"jazz-react": "workspace:0.8.3",
"jazz-react-auth-clerk": "workspace:0.8.3",
"jazz-tools": "workspace:0.8.3",
"cojson": "workspace:0.8.5",
"hash-slash": "workspace:0.2.1",
"jazz-react": "workspace:0.8.5",
"jazz-react-auth-clerk": "workspace:0.8.5",
"jazz-tools": "workspace:0.8.5",
"lucide-react": "^0.274.0",
"qrcode": "^1.5.3",
"react": "^18.2.0",

View File

@@ -7,13 +7,14 @@ import { AppContainer, TopBar } from "./ui.tsx";
export function App() {
const { me, logOut } = useAccount();
const router = useIframeHashRouter();
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;
router.navigate("/#/chat/" + chat.id);
};
return (
@@ -21,7 +22,7 @@ export function App() {
<TopBar>
{me?.profile?.name} · <button onClick={logOut}>Log out</button>
</TopBar>
{useIframeHashRouter().route({
{router.route({
"/": () => createChat() as never,
"/chat/:id": id => <ChatScreen chatID={id as ID<Chat>} />,
})}

View File

@@ -1,5 +1,14 @@
# chat-rn
## 1.0.2
### Patch Changes
- Updated dependencies [c3f4e6b]
- Updated dependencies [d9152ed]
- jazz-react-native@0.8.5
- jazz-tools@0.8.5
## 1.0.1
### Patch Changes

View File

@@ -1,6 +1,6 @@
{
"name": "chat-rn",
"version": "1.0.1",
"version": "1.0.2",
"main": "index.js",
"scripts": {
"start": "expo start",

View File

@@ -23,4 +23,9 @@ dist-ssr
*.sln
*.sw?
sync-db/
sync-db/
/test-results/
/playwright-report/
/blob-report/
/playwright/.cache/

View File

@@ -1,5 +1,23 @@
# jazz-example-chat
## 0.0.87
### Patch Changes
- Updated dependencies [c3f4e6b]
- Updated dependencies [d9152ed]
- jazz-tools@0.8.5
- cojson@0.8.5
- jazz-react@0.8.5
## 0.0.86
### Patch Changes
- Parent-frame friendlier naviation
- Updated dependencies
- hash-slash@0.2.1
## 0.0.85
### Patch Changes

View File

@@ -1,5 +1,5 @@
<!doctype html>
<html lang="en">
<html lang="en" class="h-full">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/png" href="/jazz-logo.png" />
@@ -7,8 +7,8 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Jazz Chat Example</title>
</head>
<body>
<div id="root"></div>
<body class="h-full">
<div id="root" class="h-full"></div>
<script type="module" src="/src/app.tsx"></script>
</body>
</html>

View File

@@ -1,14 +1,16 @@
{
"name": "jazz-example-chat",
"private": true,
"version": "0.0.85",
"version": "0.0.87",
"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"
"preview": "vite preview",
"test": "playwright test",
"test:ui": "playwright test --ui"
},
"lint-staged": {
"*.{ts,tsx}": "eslint --fix",
@@ -20,10 +22,10 @@
"@radix-ui/react-toast": "^1.1.4",
"class-variance-authority": "^0.7.0",
"clsx": "^2.0.0",
"cojson": "workspace:0.8.3",
"hash-slash": "workspace:0.2.0",
"jazz-react": "workspace:0.8.3",
"jazz-tools": "workspace:0.8.3",
"cojson": "workspace:0.8.5",
"hash-slash": "workspace:0.2.1",
"jazz-react": "workspace:0.8.5",
"jazz-tools": "workspace:0.8.5",
"lucide-react": "^0.274.0",
"qrcode": "^1.5.3",
"react": "^18.2.0",
@@ -36,6 +38,7 @@
"uniqolor": "^1.1.0"
},
"devDependencies": {
"@playwright/test": "^1.46.1",
"@types/qrcode": "^1.5.1",
"@types/react": "^18.2.19",
"@types/react-dom": "^18.2.7",
@@ -46,6 +49,7 @@
"eslint": "^8.46.0",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.3",
"is-ci": "^3.0.1",
"postcss": "^8.4.27",
"tailwindcss": "3.3.2",
"typescript": "^5.3.3",

View File

@@ -0,0 +1,50 @@
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",
permissions: ["clipboard-read", "clipboard-write"],
},
/* 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

@@ -7,13 +7,14 @@ import { AppContainer, TopBar } from "./ui.tsx";
export function App() {
const { me, logOut } = useAccount();
const router = useIframeHashRouter();
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;
router.navigate("/#/chat/" + chat.id);
};
return (
@@ -21,7 +22,7 @@ export function App() {
<TopBar>
<p>{me?.profile?.name}</p> · <button onClick={logOut}>Log out</button>
</TopBar>
{useIframeHashRouter().route({
{router.route({
"/": () => createChat() as never,
"/chat/:id": id => <ChatScreen chatID={id as ID<Chat>} />,
})}

View File

@@ -9,18 +9,31 @@ import {
ChatInput,
EmptyChatMessage,
} from "./ui.tsx";
import { useState } from "react";
export function ChatScreen(props: { chatID: ID<Chat> }) {
const chat = useCoState(Chat, props.chatID, [{}]);
const [showNLastMessages, setShowNLastMessages] = useState(30);
return chat ? (
<>
<ChatBody>
{chat.length > 0 ? (
chat.map(msg => <ChatBubble msg={msg} key={msg.id} />)
chat
.slice(-showNLastMessages)
.reverse() // this plus flex-col-reverse on ChatBody gives us scroll-to-bottom behavior
.map(msg => <ChatBubble msg={msg} key={msg.id} />)
) : (
<EmptyChatMessage />
)}
{chat.length > showNLastMessages && (
<button
className="px-4 py-1 block mx-auto my-2 border rounded"
onClick={() => setShowNLastMessages(showNLastMessages + 10)}
>
Show more
</button>
)}
</ChatBody>
<ChatInput
onSubmit={text => {
@@ -29,7 +42,7 @@ export function ChatScreen(props: { chatID: ID<Chat> }) {
/>
</>
) : (
<div>Loading...</div>
<div className="flex-1 flex justify-center items-center">Loading...</div>
);
}

View File

@@ -17,7 +17,10 @@ function JazzAndAuth({ children }: { children: React.ReactNode }) {
>
{children}
</Jazz.Provider>
{state.state !== "signedIn" && <DemoAuthBasicUI appName="Jazz Chat" state={state} />}
{
state.state !== "signedIn"
&& <DemoAuthBasicUI appName="Jazz Chat" state={state} />
}
</>
);
}

View File

@@ -1,3 +1,5 @@
import { useId } from "react";
export function AppContainer(props: { children: React.ReactNode }) {
return (
<div className="flex flex-col justify-between w-screen h-screen bg-stone-50 dark:bg-black dark:text-white">
@@ -16,7 +18,7 @@ export function TopBar(props: { children: React.ReactNode }) {
export function ChatBody(props: { children: React.ReactNode }) {
return (
<div className="flex-1 overflow-y-auto">
<div className="flex-1 overflow-y-auto flex flex-col-reverse" role="application">
{props.children}
</div>
);
@@ -31,12 +33,12 @@ export function BubbleContainer(props: {
fromMe: boolean | undefined;
}) {
const align = props.fromMe ? "items-end" : "items-start";
return <div className={`${align} flex flex-col m-2`}>{props.children}</div>;
return <div className={`${align} flex flex-col m-2`} role="row">{props.children}</div>;
}
export function BubbleBody(props: { children: React.ReactNode }) {
return (
<div className="rounded-2xl text-sm bg-white dark:bg-stone-700 dark:text-white py-1 px-3 shadow-sm">
<div className="rounded-2xl text-sm line-clamp-10 text-ellipsis bg-white max-w-full whitespace-pre-wrap dark:bg-stone-700 dark:text-white py-1 px-3 shadow-sm">
{props.children}
</div>
);
@@ -51,11 +53,16 @@ export function BubbleInfo(props: { by: string | undefined; madeAt: Date }) {
}
export function ChatInput(props: { onSubmit: (text: string) => void }) {
const inputId = useId();
return (
<div className="p-3 bg-white border-t shadow-2xl mt-auto dark:bg-transparent dark:border-stone-800">
<label className="sr-only" htmlFor={inputId}>Type a message and press Enter</label>
<input
id={inputId}
className="rounded-full py-2 px-4 text-sm border block w-full dark:bg-black dark:text-white dark:border-stone-700"
placeholder="Type a message and press Enter"
maxLength={2048}
onKeyDown={({ key, currentTarget: input }) => {
if (key !== "Enter" || !input.value) return;
props.onSubmit(input.value);

View File

@@ -69,6 +69,9 @@ module.exports = {
"accordion-down": "accordion-down 0.2s ease-out",
"accordion-up": "accordion-up 0.2s ease-out",
},
lineClamp: {
10: '10',
},
},
},
plugins: [require("tailwindcss-animate")],

View File

@@ -0,0 +1,50 @@
import { test } from "@playwright/test";
import { LoginPage } from "./pages/LoginPage";
import { ChatPage } from "./pages/ChatPage";
test("chat between two users", async ({ page }) => {
const loginPage = new LoginPage(page);
const mario = "S. Mario";
const luigi = "Luigi";
await loginPage.goto();
await loginPage.fillUsername(mario);
await loginPage.signup();
const chatPage = new ChatPage(page);
const message1ByMario = "Hello Luigi, are you ready to save the princess?"
await chatPage.sendMessage(message1ByMario);
await chatPage.expectMessageRow(message1ByMario);
const roomURL = page.url();
await chatPage.logout();
await loginPage.expectLoaded();
await loginPage.fillUsername(luigi);
await loginPage.signup();
await page.goto(roomURL);
await chatPage.expectMessageRow(message1ByMario);
const message2ByLuigi = "No, I'm not ready yet. I'm still trying to find the key to the castle."
await chatPage.sendMessage(message2ByLuigi);
await chatPage.expectMessageRow(message2ByLuigi);
// This breaks with (Error: Error reading from peer storage, handling msg)
// await chatPage.logout();
// await loginPage.loginAs(mario);
// await chatPage.expectLoaded();
// await page.goto(roomURL);
// await chatPage.expectMessageRow(message1ByMario);
// await chatPage.expectMessageRow(message2ByLuigi);
});

View File

@@ -0,0 +1,35 @@
import { Page, Locator, expect } from "@playwright/test";
export class ChatPage {
readonly page: Page;
readonly messageInput: Locator;
readonly logoutButton: Locator;
constructor(page: Page) {
this.page = page;
this.messageInput = page.getByRole("textbox", {
name: "Type a message and press Enter"
});
this.logoutButton = page.getByRole("button", {
name: "Log out",
});
}
async sendMessage(message: string) {
await this.messageInput.fill(message);
await this.messageInput.press("Enter");
}
async expectLoaded() {
await expect(this.messageInput).toBeVisible();
}
async expectMessageRow(message: string) {
await expect(this.page.getByText(message)).toBeVisible();
}
async logout() {
await this.logoutButton.click();
await this.page.goto("/");
}
}

View File

@@ -0,0 +1,40 @@
import { Page, Locator, expect } from "@playwright/test";
export class LoginPage {
readonly page: Page;
readonly usernameInput: Locator;
readonly signupButton: Locator;
constructor(page: Page) {
this.page = page;
this.usernameInput = page.getByRole("textbox");
this.signupButton = page.getByRole("button", {
name: "Sign up",
});
}
async goto() {
this.page.goto("/");
}
async fillUsername(value: string) {
await this.usernameInput.clear();
await this.usernameInput.fill(value);
}
async loginAs(value: string) {
await this.page
.getByRole("button", {
name: `Log in as "${value}"`,
})
.click();
}
async signup() {
await this.signupButton.click();
}
async expectLoaded() {
await expect(this.signupButton).toBeVisible();
}
}

View File

@@ -1,5 +1,21 @@
# jazz-example-inspector
## 0.0.63
### Patch Changes
- Updated dependencies [c3f4e6b]
- Updated dependencies [d9152ed]
- cojson@0.8.5
- cojson-transport-ws@0.8.5
## 0.0.62
### Patch Changes
- Updated dependencies
- hash-slash@0.2.1
## 0.0.61
### Patch Changes

View File

@@ -1,7 +1,7 @@
{
"name": "jazz-inspector",
"private": true,
"version": "0.0.61",
"version": "0.0.63",
"type": "module",
"scripts": {
"dev": "vite",
@@ -15,9 +15,9 @@
"@radix-ui/react-toast": "^1.1.4",
"class-variance-authority": "^0.7.0",
"clsx": "^2.0.0",
"cojson": "workspace:0.8.3",
"cojson-transport-ws": "workspace:0.8.3",
"hash-slash": "workspace:0.2.0",
"cojson": "workspace:0.8.5",
"cojson-transport-ws": "workspace:0.8.5",
"hash-slash": "workspace:0.2.1",
"lucide-react": "^0.274.0",
"qrcode": "^1.5.3",
"react": "^18.2.0",

View File

@@ -1,5 +1,14 @@
# jazz-example-musicplayer
## 0.0.7
### Patch Changes
- Updated dependencies [c3f4e6b]
- Updated dependencies [d9152ed]
- jazz-tools@0.8.5
- jazz-react@0.8.5
## 0.0.6
### Patch Changes

View File

@@ -10,14 +10,14 @@ Start by checking out `jazz`
```bash
git clone https://github.com/gardencmp/jazz.git
cd jazz/examples/musicPlayer
cd jazz/examples/music-player
pnpm pack --pack-destination /tmp
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
mkdir -p ~/jazz-examples/music-player # or any other directory
tar -xf /tmp/jazz-example-music-player-* --strip-components 1 -C ~/jazz-examples/music-player
cd ~/jazz-examples/music-player
```
This ensures that you have the example app without git history and independent of the Jazz multi-package monorepo.
This ensures you have the example app without git history and independent of the Jazz multi-package monorepo.
Install dependencies:

View File

@@ -10,7 +10,7 @@
"cssVariables": true
},
"aliases": {
"components": "@/basicComponents",
"utils": "@/basicComponents/lib/utils"
"components": "@/components",
"utils": "@/lib/utils"
}
}

View File

@@ -1,7 +1,7 @@
{
"name": "jazz-example-music-player",
"private": true,
"version": "0.0.6",
"version": "0.0.7",
"type": "module",
"scripts": {
"dev": "vite",
@@ -15,10 +15,14 @@
"*.{js,jsx,mdx,json}": "prettier --write"
},
"dependencies": {
"@radix-ui/react-dropdown-menu": "^2.1.1",
"@radix-ui/react-slot": "^1.0.2",
"@radix-ui/react-toast": "^1.1.4",
"class-variance-authority": "^0.7.0",
"clsx": "^2.0.0",
"jazz-react": "workspace:0.8.3",
"jazz-tools": "workspace:0.8.3",
"jazz-react": "workspace:0.8.5",
"jazz-tools": "workspace:0.8.5",
"lucide-react": "^0.274.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router": "^6.16.0",

View File

@@ -2,13 +2,10 @@
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 { Toaster } from "@/components/ui/toaster"
import { useMediaPlayer } from "./5_useMediaPlayer";
import { HomePage } from "./3_HomePage";
import { InvitePage } from "./6_InvitePage";
import { PlayerControls } from "./components/PlayerControls";
import "./index.css";
@@ -38,31 +35,6 @@ function Main() {
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: "/",
@@ -70,7 +42,7 @@ function Main() {
},
{
path: "/playlist/:playlistId",
element: <PlaylistPage mediaPlayer={mediaPlayer} />,
element: <HomePage mediaPlayer={mediaPlayer} />,
},
{
path: "/invite/*",
@@ -80,20 +52,9 @@ function Main() {
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} />
<Toaster />
</>
);
}

View File

@@ -0,0 +1,144 @@
import { useAccount, useCoState } from "./2_main";
import { MediaPlayer } from "./5_useMediaPlayer";
import { MusicTrackRow } from "./components/MusicTrackRow";
import { usePlayState } from "./lib/audio/usePlayState";
import { SidePanel } from "./components/SidePanel";
import { FileUploadButton } from "./components/FileUploadButton";
import { Button } from "./components/ui/button";
import { createNewPlaylist, uploadMusicTracks } from "./4_actions";
import { useNavigate, useParams } from "react-router";
import { ID } from "jazz-tools";
import { Playlist } from "./1_schema";
import { createInviteLink } from "jazz-react";
import { useToast } from "@/hooks/use-toast"
export function HomePage({ mediaPlayer }: { mediaPlayer: MediaPlayer }) {
/**
* `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({
root: {
rootPlaylist: {},
playlists: [],
},
});
const navigate = useNavigate();
const playState = usePlayState();
const isPlaying = playState.value === "play";
const { toast } = useToast()
async function handleFileLoad(files: FileList) {
if (!me) return;
/**
* Follow this function definition to see how we update
* values in Jazz and manage files!
*/
await uploadMusicTracks(me, files);
}
async function handleCreatePlaylist() {
if (!me) return;
const playlist = await createNewPlaylist(me);
navigate(`/playlist/${playlist.id}`);
}
const params = useParams<{ playlistId: ID<Playlist> }>();
const playlistId = params.playlistId ?? me?.root._refs.rootPlaylist.id;
const playlist = useCoState(Playlist, playlistId, {
tracks: [],
});
const isRootPlaylist = !params.playlistId;
const isPlaylistOwner = playlist?._owner.myRole() === "admin";
const isActivePlaylist = playlistId === me?.root.activePlaylist?.id;
const handlePlaylistTitleChange = (
evt: React.ChangeEvent<HTMLInputElement>,
) => {
if (!playlist) return;
playlist.title = evt.target.value;
};
const handlePlaylistShareClick = async () => {
if (!isPlaylistOwner) return;
const inviteLink = createInviteLink(playlist, "reader");
await navigator.clipboard.writeText(inviteLink);
toast({
title: "Invite link copied into the clipboard",
});
};
return (
<div className="flex flex-col h-screen text-gray-800 bg-blue-50">
<div className="flex flex-1 overflow-hidden">
<SidePanel />
<main className="flex-1 p-6 overflow-y-auto">
<div className="flex items-center justify-between mb-6">
{isRootPlaylist ? (
<h1 className="text-2xl font-bold text-blue-800">
All tracks
</h1>
) : (
<input
value={playlist?.title ?? ""}
onChange={handlePlaylistTitleChange}
className="text-2xl font-bold text-blue-800 bg-transparent"
disabled={!isPlaylistOwner}
/>
)}
<div className="flex items-center space-x-4">
{isRootPlaylist && (
<>
<FileUploadButton
onFileLoad={handleFileLoad}
>
Add file
</FileUploadButton>
<Button onClick={handleCreatePlaylist}>
Create new playlist
</Button>
</>
)}
{!isRootPlaylist && (
<Button onClick={handlePlaylistShareClick}>
Share playlist
</Button>
)}
</div>
</div>
<ul className="flex flex-col">
{playlist?.tracks?.map(
(track) =>
track && (
<MusicTrackRow
trackId={track.id}
key={track.id}
isLoading={
mediaPlayer.loading === track.id
}
isPlaying={
mediaPlayer.activeTrackId ===
track.id && isActivePlaylist && isPlaying
}
onClick={() => {
mediaPlayer.setActiveTrack(track, playlist);
}}
showAddToPlaylist={isRootPlaylist}
/>
),
)}
</ul>
</main>
</div>
</div>
);
}

View File

@@ -92,6 +92,8 @@ export async function addTrackToPlaylist(
) {
if (!account) return;
if (playlist.tracks?.some((t) => t?._refs.sourceTrack.id === track.id)) return;
/**
* Since musicTracks are created as private values (see uploadMusicTracks)
* to make them shareable as part of the playlist we are cloning them

View File

@@ -1,60 +0,0 @@
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

@@ -1,6 +1,6 @@
import { usePlayMedia } from "@/lib/audio/usePlayMedia";
import { usePlayState } from "@/lib/audio/usePlayState";
import { useAccount, useCoState } from "./2_main";
import { useAccount } from "./2_main";
import { MusicTrack, Playlist } from "@/1_schema";
import { useRef, useState } from "react";
import { getNextTrack, getPrevTrack } from "./lib/getters";
@@ -14,7 +14,7 @@ export function useMediaPlayer() {
const [loading, setLoading] = useState<ID<MusicTrack> | null>(null);
const activeTrack = useCoState(MusicTrack, me?.root?._refs.activeTrack?.id);
const activeTrackId = me?.root?._refs.activeTrack?.id
// Reference used to avoid out-of-order track loads
const lastLoadedTrackId = useRef<ID<MusicTrack> | null>(null);
@@ -71,7 +71,7 @@ export function useMediaPlayer() {
if (!me?.root) return;
if (
activeTrack?.id === track.id &&
activeTrackId === track.id &&
lastLoadedTrackId.current !== null
) {
playState.toggle();
@@ -88,7 +88,7 @@ export function useMediaPlayer() {
}
return {
activeTrack,
activeTrackId,
setActiveTrack,
playNextTrack,
playPrevTrack,

View File

@@ -1,84 +0,0 @@
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

@@ -1,20 +0,0 @@
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

@@ -1,13 +0,0 @@
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

@@ -1,79 +0,0 @@
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

@@ -1,4 +1,5 @@
import { ReactNode } from "react";
import { Button } from "./ui/button";
export function FileUploadButton(props: {
onFileLoad: (files: FileList) => Promise<void>;
@@ -13,11 +14,11 @@ export function FileUploadButton(props: {
}
return (
<button className="bg-blue-300 hover:cursor-pointer flex items-center">
<Button>
<label className="flex items-center cursor-pointer p-2">
<input type="file" onChange={handleFileLoad} multiple hidden />
{props.children}
</label>
</button>
</Button>
);
}

View File

@@ -1,35 +1,69 @@
import { MusicTrack } from "@/1_schema";
import { MusicTrack, Playlist } from "@/1_schema";
import { cn } from "@/lib/utils";
import {
DropdownMenu,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuItem,
} from "@/components/ui/dropdown-menu";
import { MoreHorizontal } from "lucide-react";
import { ChangeEvent } from "react";
import { Button } from "./ui/button";
import { useAccount, useCoState } from "@/2_main";
import { addTrackToPlaylist } from "@/4_actions";
import { ID } from "jazz-tools";
export function MusicTrackRow({
track,
trackId,
isLoading,
isPlaying,
onClick,
showAddToPlaylist,
}: {
track: MusicTrack;
trackId: ID<MusicTrack>;
isLoading: boolean;
isPlaying: boolean;
onClick: (track: MusicTrack) => void;
showAddToPlaylist: boolean;
}) {
const track = useCoState(MusicTrack, trackId);
function handleTrackTitleChange(evt: ChangeEvent<HTMLInputElement>) {
if (!track) return;
track.title = evt.target.value;
}
const { me } = useAccount({
root: {
playlists: [{}],
},
});
const playlists = me?.root.playlists ?? [];
function handleTrackClick() {
if (!track) return;
onClick(track);
}
function handleAddToPlaylist(playlist: Playlist) {
if (!track) return;
addTrackToPlaylist(playlist, track, me);
}
return (
<li
className={
"flex gap-1 hover:bg-slate-200 group py-2 px-2 cursor-pointer"
}
onClick={() => onClick(track)}
onClick={handleTrackClick}
>
<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)}
onClick={handleTrackClick}
>
{isLoading ? (
<div className="animate-spin">߷</div>
@@ -39,17 +73,44 @@ export function MusicTrackRow({
"▶️"
)}
</button>
<div className="relative" onClick={(evt) => evt.stopPropagation()}>
<div
className="relative flex-grow"
onClick={(evt) => evt.stopPropagation()}
>
<input
className="absolute w-full h-full left-0 bg-transparent px-1"
value={track.title}
value={track?.title}
onChange={handleTrackTitleChange}
spellCheck="false"
/>
<span className="opacity-0 px-1 w-fit pointer-events-none whitespace-pre">
{track.title}
{track?.title}
</span>
</div>
<div onClick={(evt) => evt.stopPropagation()}>
{showAddToPlaylist && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" className="h-8 w-8 p-0">
<span className="sr-only">Open menu</span>
<MoreHorizontal className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
{playlists.map((playlist, index) => (
<DropdownMenuItem
key={index}
onSelect={() =>
handleAddToPlaylist(playlist)
}
>
Add to {playlist.title}
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
)}
</div>
</li>
);
}

View File

@@ -1,9 +1,11 @@
import { MediaPlayer } from "@/4_useMediaPlayer";
import { MediaPlayer } from "@/5_useMediaPlayer";
import { usePlayState } from "@/lib/audio/usePlayState";
import { Waveform } from "./Waveform";
import { useAccount } from "@/2_main";
import { useAccount, useCoState } from "@/2_main";
import { useMediaEndListener } from "@/lib/audio/useMediaEndListener";
import { useKeyboardListener } from "@/lib/useKeyboardListener";
import { Pause, Play, SkipBack, SkipForward } from "lucide-react";
import { MusicTrack } from "@/1_schema";
export function PlayerControls({ mediaPlayer }: { mediaPlayer: MediaPlayer }) {
const playState = usePlayState();
@@ -22,32 +24,51 @@ export function PlayerControls({ mediaPlayer }: { mediaPlayer: MediaPlayer }) {
playState.toggle();
});
if (!mediaPlayer.activeTrack) return null;
const activeTrack = useCoState(MusicTrack, mediaPlayer.activeTrackId, {
waveform: {}
});
const activeTrackTitle = mediaPlayer.activeTrack.title;
if (!activeTrack) return null;
const head = activePlaylist?.title
? `${activePlaylist.title} / ${activeTrackTitle}`
: activeTrackTitle;
const activeTrackTitle = activeTrack.title;
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>
<footer className="flex items-center justify-between p-4 gap-4 bg-white border-t border-gray-200 fixed bottom-0 left-0 right-0 w-full">
<div className="flex justify-center items-center space-x-2">
<div className="flex items-center space-x-4">
<button
onClick={mediaPlayer.playPrevTrack}
className="text-blue-600 hover:text-blue-800"
>
<SkipBack size={20} />
</button>
<button
onClick={playState.toggle}
className="w-[42px] h-[42px] flex items-center justify-center bg-blue-600 rounded-full text-white hover:bg-blue-700"
>
{isPlaying ? (
<Pause size={24} fill="currentColor" />
) : (
<Play size={24} fill="currentColor" />
)}
</button>
<button
onClick={mediaPlayer.playNextTrack}
className="text-blue-600 hover:text-blue-800"
>
<SkipForward size={20} />
</button>
</div>
<Waveform track={mediaPlayer.activeTrack} height={30} />
</div>
</div>
<div className=" sm:hidden md:flex flex-col flex-shrink-1 items-center w-[75%]">
<Waveform track={activeTrack} height={30} />
</div>
<div className="flex flex-col items-end gap-1 text-right min-w-fit w-[25%]">
<h4 className="font-medium text-blue-800">
{activeTrackTitle}
</h4>
<p className="text-sm text-gray-600">{activePlaylist?.title || "All tracks"}</p>
</div>
</footer>
);
}

View File

@@ -0,0 +1,92 @@
import { useAccount } from "@/2_main";
import { useNavigate, useParams } from "react-router";
export function SidePanel() {
const { playlistId } = useParams();
const navigate = useNavigate();
const { me } = useAccount({
root: {
playlists: [{}],
},
});
function handleAllTracksClick(
evt: React.MouseEvent<HTMLAnchorElement>,
) {
evt.preventDefault();
navigate(`/`);
}
function handlePlaylistClick(
evt: React.MouseEvent<HTMLAnchorElement>,
playlistId: string,
) {
evt.preventDefault();
navigate(`/playlist/${playlistId}`);
}
return (
<aside className="w-64 p-6 bg-white overflow-y-auto">
<div className="flex items-center mb-6">
<svg
className="w-8 h-8 mr-2"
viewBox="0 0 24 24"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M9 18V5l12-2v13"
stroke="#3b82f6"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
/>
<path
d="M6 15H3c-1.1 0-2 .9-2 2v4c0 1.1.9 2 2 2h3c1.1 0 2-.9 2-2v-4c0-1.1-.9-2-2-2zM18 13h-3c-1.1 0-2 .9-2 2v4c0 1.1.9 2 2 2h3c1.1 0 2-.9 2-2v-4c0-1.1-.9-2-2-2z"
fill="#3b82f6"
/>
</svg>
<span className="text-xl font-bold text-blue-600">
Music Player
</span>
</div>
<nav>
<h2 className="mb-2 text-sm font-semibold text-gray-600">
Playlists
</h2>
<ul className="space-y-1">
<li>
<a
href="#"
className={`block px-2 py-1 text-sm rounded ${
!playlistId
? "bg-blue-100 text-blue-600"
: "hover:bg-blue-100"
}`}
onClick={handleAllTracksClick}
>
All tracks
</a>
</li>
{me?.root.playlists.map((playlist, index) => (
<li key={index}>
<a
href="#"
className={`block px-2 py-1 text-sm rounded ${
playlist.id === playlistId
? "bg-blue-100 text-blue-600"
: "hover:bg-blue-100"
}`}
onClick={(evt) =>
handlePlaylistClick(evt, playlist.id)
}
>
{playlist.title}
</a>
</li>
))}
</ul>
</nav>
</aside>
);
}

View File

@@ -0,0 +1,56 @@
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const buttonVariants = cva(
"inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90",
destructive:
"bg-destructive text-destructive-foreground hover:bg-destructive/90",
outline:
"border border-input bg-background hover:bg-accent hover:text-accent-foreground",
secondary:
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost: "hover:bg-accent hover:text-accent-foreground",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-10 px-4 py-2",
sm: "h-9 rounded-md px-3",
lg: "h-11 rounded-md px-8",
icon: "h-10 w-10",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
asChild?: boolean
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : "button"
return (
<Comp
className={cn(buttonVariants({ variant, size, className }))}
ref={ref}
{...props}
/>
)
}
)
Button.displayName = "Button"
export { Button, buttonVariants }

View File

@@ -0,0 +1,198 @@
import * as React from "react"
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu"
import { Check, ChevronRight, Circle } from "lucide-react"
import { cn } from "@/lib/utils"
const DropdownMenu = DropdownMenuPrimitive.Root
const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger
const DropdownMenuGroup = DropdownMenuPrimitive.Group
const DropdownMenuPortal = DropdownMenuPrimitive.Portal
const DropdownMenuSub = DropdownMenuPrimitive.Sub
const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup
const DropdownMenuSubTrigger = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.SubTrigger>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubTrigger> & {
inset?: boolean
}
>(({ className, inset, children, ...props }, ref) => (
<DropdownMenuPrimitive.SubTrigger
ref={ref}
className={cn(
"flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent",
inset && "pl-8",
className
)}
{...props}
>
{children}
<ChevronRight className="ml-auto h-4 w-4" />
</DropdownMenuPrimitive.SubTrigger>
))
DropdownMenuSubTrigger.displayName =
DropdownMenuPrimitive.SubTrigger.displayName
const DropdownMenuSubContent = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.SubContent>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubContent>
>(({ className, ...props }, ref) => (
<DropdownMenuPrimitive.SubContent
ref={ref}
className={cn(
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
className
)}
{...props}
/>
))
DropdownMenuSubContent.displayName =
DropdownMenuPrimitive.SubContent.displayName
const DropdownMenuContent = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Content>
>(({ className, sideOffset = 4, ...props }, ref) => (
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Content
ref={ref}
sideOffset={sideOffset}
className={cn(
"z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
className
)}
{...props}
/>
</DropdownMenuPrimitive.Portal>
))
DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName
const DropdownMenuItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item> & {
inset?: boolean
}
>(({ className, inset, ...props }, ref) => (
<DropdownMenuPrimitive.Item
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
inset && "pl-8",
className
)}
{...props}
/>
))
DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName
const DropdownMenuCheckboxItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.CheckboxItem>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.CheckboxItem>
>(({ className, children, checked, ...props }, ref) => (
<DropdownMenuPrimitive.CheckboxItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
checked={checked}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.CheckboxItem>
))
DropdownMenuCheckboxItem.displayName =
DropdownMenuPrimitive.CheckboxItem.displayName
const DropdownMenuRadioItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.RadioItem>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.RadioItem>
>(({ className, children, ...props }, ref) => (
<DropdownMenuPrimitive.RadioItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<Circle className="h-2 w-2 fill-current" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.RadioItem>
))
DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName
const DropdownMenuLabel = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Label> & {
inset?: boolean
}
>(({ className, inset, ...props }, ref) => (
<DropdownMenuPrimitive.Label
ref={ref}
className={cn(
"px-2 py-1.5 text-sm font-semibold",
inset && "pl-8",
className
)}
{...props}
/>
))
DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName
const DropdownMenuSeparator = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Separator>
>(({ className, ...props }, ref) => (
<DropdownMenuPrimitive.Separator
ref={ref}
className={cn("-mx-1 my-1 h-px bg-muted", className)}
{...props}
/>
))
DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName
const DropdownMenuShortcut = ({
className,
...props
}: React.HTMLAttributes<HTMLSpanElement>) => {
return (
<span
className={cn("ml-auto text-xs tracking-widest opacity-60", className)}
{...props}
/>
)
}
DropdownMenuShortcut.displayName = "DropdownMenuShortcut"
export {
DropdownMenu,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuCheckboxItem,
DropdownMenuRadioItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuGroup,
DropdownMenuPortal,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuRadioGroup,
}

View File

@@ -0,0 +1,127 @@
import * as React from "react"
import * as ToastPrimitives from "@radix-ui/react-toast"
import { cva, type VariantProps } from "class-variance-authority"
import { X } from "lucide-react"
import { cn } from "@/lib/utils"
const ToastProvider = ToastPrimitives.Provider
const ToastViewport = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Viewport>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Viewport>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Viewport
ref={ref}
className={cn(
"fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",
className
)}
{...props}
/>
))
ToastViewport.displayName = ToastPrimitives.Viewport.displayName
const toastVariants = cva(
"group pointer-events-auto relative flex w-full items-center justify-between space-x-4 overflow-hidden rounded-md border p-6 pr-8 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",
{
variants: {
variant: {
default: "border bg-background text-foreground",
destructive:
"destructive group border-destructive bg-destructive text-destructive-foreground",
},
},
defaultVariants: {
variant: "default",
},
}
)
const Toast = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Root>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Root> &
VariantProps<typeof toastVariants>
>(({ className, variant, ...props }, ref) => {
return (
<ToastPrimitives.Root
ref={ref}
className={cn(toastVariants({ variant }), className)}
{...props}
/>
)
})
Toast.displayName = ToastPrimitives.Root.displayName
const ToastAction = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Action>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Action>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Action
ref={ref}
className={cn(
"inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium ring-offset-background transition-colors hover:bg-secondary focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",
className
)}
{...props}
/>
))
ToastAction.displayName = ToastPrimitives.Action.displayName
const ToastClose = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Close>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Close>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Close
ref={ref}
className={cn(
"absolute right-2 top-2 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-2 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",
className
)}
toast-close=""
{...props}
>
<X className="h-4 w-4" />
</ToastPrimitives.Close>
))
ToastClose.displayName = ToastPrimitives.Close.displayName
const ToastTitle = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Title>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Title>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Title
ref={ref}
className={cn("text-sm font-semibold", className)}
{...props}
/>
))
ToastTitle.displayName = ToastPrimitives.Title.displayName
const ToastDescription = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Description>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Description>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Description
ref={ref}
className={cn("text-sm opacity-90", className)}
{...props}
/>
))
ToastDescription.displayName = ToastPrimitives.Description.displayName
type ToastProps = React.ComponentPropsWithoutRef<typeof Toast>
type ToastActionElement = React.ReactElement<typeof ToastAction>
export {
type ToastProps,
type ToastActionElement,
ToastProvider,
ToastViewport,
Toast,
ToastTitle,
ToastDescription,
ToastClose,
ToastAction,
}

View File

@@ -0,0 +1,33 @@
import { useToast } from "@/hooks/use-toast"
import {
Toast,
ToastClose,
ToastDescription,
ToastProvider,
ToastTitle,
ToastViewport,
} from "@/components/ui/toast"
export function Toaster() {
const { toasts } = useToast()
return (
<ToastProvider>
{toasts.map(function ({ id, title, description, action, ...props }) {
return (
<Toast key={id} {...props}>
<div className="grid gap-1">
{title && <ToastTitle>{title}</ToastTitle>}
{description && (
<ToastDescription>{description}</ToastDescription>
)}
</div>
{action}
<ToastClose />
</Toast>
)
})}
<ToastViewport />
</ToastProvider>
)
}

View File

@@ -0,0 +1,191 @@
import * as React from "react"
import type {
ToastActionElement,
ToastProps,
} from "@/components/ui/toast"
const TOAST_LIMIT = 1
const TOAST_REMOVE_DELAY = 1000000
type ToasterToast = ToastProps & {
id: string
title?: React.ReactNode
description?: React.ReactNode
action?: ToastActionElement
}
const actionTypes = {
ADD_TOAST: "ADD_TOAST",
UPDATE_TOAST: "UPDATE_TOAST",
DISMISS_TOAST: "DISMISS_TOAST",
REMOVE_TOAST: "REMOVE_TOAST",
} as const
let count = 0
function genId() {
count = (count + 1) % Number.MAX_SAFE_INTEGER
return count.toString()
}
type ActionType = typeof actionTypes
type Action =
| {
type: ActionType["ADD_TOAST"]
toast: ToasterToast
}
| {
type: ActionType["UPDATE_TOAST"]
toast: Partial<ToasterToast>
}
| {
type: ActionType["DISMISS_TOAST"]
toastId?: ToasterToast["id"]
}
| {
type: ActionType["REMOVE_TOAST"]
toastId?: ToasterToast["id"]
}
interface State {
toasts: ToasterToast[]
}
const toastTimeouts = new Map<string, ReturnType<typeof setTimeout>>()
const addToRemoveQueue = (toastId: string) => {
if (toastTimeouts.has(toastId)) {
return
}
const timeout = setTimeout(() => {
toastTimeouts.delete(toastId)
dispatch({
type: "REMOVE_TOAST",
toastId: toastId,
})
}, TOAST_REMOVE_DELAY)
toastTimeouts.set(toastId, timeout)
}
export const reducer = (state: State, action: Action): State => {
switch (action.type) {
case "ADD_TOAST":
return {
...state,
toasts: [action.toast, ...state.toasts].slice(0, TOAST_LIMIT),
}
case "UPDATE_TOAST":
return {
...state,
toasts: state.toasts.map((t) =>
t.id === action.toast.id ? { ...t, ...action.toast } : t
),
}
case "DISMISS_TOAST": {
const { toastId } = action
// ! Side effects ! - This could be extracted into a dismissToast() action,
// but I'll keep it here for simplicity
if (toastId) {
addToRemoveQueue(toastId)
} else {
state.toasts.forEach((toast) => {
addToRemoveQueue(toast.id)
})
}
return {
...state,
toasts: state.toasts.map((t) =>
t.id === toastId || toastId === undefined
? {
...t,
open: false,
}
: t
),
}
}
case "REMOVE_TOAST":
if (action.toastId === undefined) {
return {
...state,
toasts: [],
}
}
return {
...state,
toasts: state.toasts.filter((t) => t.id !== action.toastId),
}
}
}
const listeners: Array<(state: State) => void> = []
let memoryState: State = { toasts: [] }
function dispatch(action: Action) {
memoryState = reducer(memoryState, action)
listeners.forEach((listener) => {
listener(memoryState)
})
}
type Toast = Omit<ToasterToast, "id">
function toast({ ...props }: Toast) {
const id = genId()
const update = (props: ToasterToast) =>
dispatch({
type: "UPDATE_TOAST",
toast: { ...props, id },
})
const dismiss = () => dispatch({ type: "DISMISS_TOAST", toastId: id })
dispatch({
type: "ADD_TOAST",
toast: {
...props,
id,
open: true,
onOpenChange: (open) => {
if (!open) dismiss()
},
},
})
return {
id: id,
dismiss,
update,
}
}
function useToast() {
const [state, setState] = React.useState<State>(memoryState)
React.useEffect(() => {
listeners.push(setState)
return () => {
const index = listeners.indexOf(setState)
if (index > -1) {
listeners.splice(index, 1)
}
}
}, [state])
return {
...state,
toast,
dismiss: (toastId?: string) => dispatch({ type: "DISMISS_TOAST", toastId }),
}
}
export { useToast, toast }

View File

@@ -1,7 +1,7 @@
/* eslint-disable react-hooks/exhaustive-deps */
import { useEffect } from "react";
import { useAccount } from "../2_main";
import { uploadMusicTracks } from "@/3_actions";
import { uploadMusicTracks } from "@/4_actions";
import { MusicaAccount } from "@/1_schema";
export function useUploadExampleData() {

View File

@@ -1,5 +1,14 @@
# jazz-password-manager
## 0.0.6
### Patch Changes
- Updated dependencies [c3f4e6b]
- Updated dependencies [d9152ed]
- jazz-tools@0.8.5
- jazz-react@0.8.5
## 0.0.5
### Patch Changes

View File

@@ -1,7 +1,7 @@
{
"name": "jazz-password-manager",
"private": true,
"version": "0.0.5",
"version": "0.0.6",
"type": "module",
"scripts": {
"dev": "vite",
@@ -11,8 +11,8 @@
"clean-install": "rm -rf node_modules pnpm-lock.yaml && pnpm install"
},
"dependencies": {
"jazz-react": "workspace:0.8.3",
"jazz-tools": "workspace:0.8.3",
"jazz-react": "workspace:0.8.5",
"jazz-tools": "workspace:0.8.5",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-hook-form": "^7.41.5",

View File

@@ -1,5 +1,15 @@
# jazz-example-pets
## 0.0.104
### Patch Changes
- Updated dependencies [c3f4e6b]
- Updated dependencies [d9152ed]
- jazz-tools@0.8.5
- jazz-browser-media-images@0.8.5
- jazz-react@0.8.5
## 0.0.103
### Patch Changes

View File

@@ -1,7 +1,7 @@
{
"name": "jazz-example-pets",
"private": true,
"version": "0.0.103",
"version": "0.0.104",
"type": "module",
"scripts": {
"dev": "vite",
@@ -9,6 +9,7 @@
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"format": "prettier --write './src/**/*.{ts,tsx}'",
"preview": "vite preview",
"sync": "jazz-run sync",
"test": "playwright test",
"test:ui": "playwright test --ui"
},
@@ -22,9 +23,9 @@
"@radix-ui/react-toast": "^1.1.4",
"class-variance-authority": "^0.7.0",
"clsx": "^2.0.0",
"jazz-browser-media-images": "workspace:0.8.3",
"jazz-react": "workspace:0.8.3",
"jazz-tools": "workspace:0.8.3",
"jazz-browser-media-images": "workspace:0.8.5",
"jazz-react": "workspace:0.8.5",
"jazz-tools": "workspace:0.8.5",
"lucide-react": "^0.274.0",
"qrcode": "^1.5.3",
"react": "^18.2.0",
@@ -49,6 +50,7 @@
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.3",
"is-ci": "^3.0.1",
"jazz-run": "workspace:0.8.5",
"postcss": "^8.4.27",
"tailwindcss": "3.3.2",
"typescript": "^5.3.3",

View File

@@ -27,7 +27,7 @@ export default defineConfig({
/* 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",
baseURL: "http://localhost:5173/?peer=ws://localhost:1234",
/* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
trace: "on-first-retry",
@@ -43,8 +43,16 @@ export default defineConfig({
],
/* Run your local dev server before starting the tests */
webServer: isCI ? {
command: "pnpm preview",
url: "http://localhost:4173/",
} : undefined,
webServer: [
{
command: "pnpm preview --port 5173",
url: "http://localhost:5173/",
reuseExistingServer: !isCI,
},
{
command: "pnpm sync --in-memory --port 1234",
url: "http://localhost:1234/health",
reuseExistingServer: !isCI,
},
],
});

View File

@@ -3,17 +3,23 @@ import ReactDOM from "react-dom/client";
import { Link, RouterProvider, createHashRouter } from "react-router-dom";
import "./index.css";
import {
createJazzReactApp,
DemoAuthBasicUI,
useDemoAuth,
} from "jazz-react";
import { createJazzReactApp, DemoAuthBasicUI, useDemoAuth } from "jazz-react";
import { Button, ThemeProvider, TitleAndLogo } from "./basicComponents/index.ts";
import {
Button,
ThemeProvider,
TitleAndLogo,
} from "./basicComponents/index.ts";
import { NewPetPostForm } from "./3_NewPetPostForm.tsx";
import { RatePetPostUI } from "./4_RatePetPostUI.tsx";
import { PetAccount, PetPost } from "./1_schema.ts";
const peer =
(new URL(window.location.href).searchParams.get(
"peer",
) as `ws://${string}`) ??
"wss://mesh.jazz.tools/?key=music-player-example-jazz@gcmp.io";
/** Walkthrough: The top-level provider `<Jazz.Provider/>`
*
* This shows how to use the top-level provider `<Jazz.Provider/>`,
@@ -34,7 +40,7 @@ function JazzAndAuth({ children }: { children: React.ReactNode }) {
<>
<Jazz.Provider
auth={auth}
peer="wss://mesh.jazz.tools/?key=pets-example-jazz@gcmp.io"
peer={peer}
>
{children}
</Jazz.Provider>

View File

@@ -9,7 +9,7 @@ export class LoginPage {
this.page = page;
this.usernameInput = page.getByRole("textbox");
this.signupButton = page.getByRole("button", {
name: "Sign up as new account",
name: "Sign up",
});
}
@@ -25,7 +25,7 @@ export class LoginPage {
async loginAs(value: string) {
await this.page
.getByRole("button", {
name: `Log in as "${value}"`,
name: value,
})
.click();
}

View File

@@ -1,5 +1,14 @@
# jazz-example-todo
## 0.0.103
### Patch Changes
- Updated dependencies [c3f4e6b]
- Updated dependencies [d9152ed]
- jazz-tools@0.8.5
- jazz-react@0.8.5
## 0.0.102
### Patch Changes

View File

@@ -1,7 +1,7 @@
{
"name": "jazz-example-todo",
"private": true,
"version": "0.0.102",
"version": "0.0.103",
"type": "module",
"scripts": {
"dev": "vite",
@@ -20,8 +20,8 @@
"@radix-ui/react-toast": "^1.1.4",
"class-variance-authority": "^0.7.0",
"clsx": "^2.0.0",
"jazz-react": "workspace:0.8.3",
"jazz-tools": "workspace:0.8.3",
"jazz-react": "workspace:0.8.5",
"jazz-tools": "workspace:0.8.5",
"lucide-react": "^0.274.0",
"qrcode": "^1.5.3",
"react": "^18.2.0",

View File

@@ -8,10 +8,13 @@ export function BreadCrumb({
items: { title: string; href: string }[];
}) {
const pathName = usePathname();
const title = items.find((item) => item.href === pathName)?.title;
if (!title) return null;
return (
<span className="text-sm font-bold">
{items.find((item) => item.href === pathName)?.title}
<span className="text-sm font-semibold">
{title}
</span>
);
}

View File

@@ -15,7 +15,7 @@ export function GappedGrid({
<div
className={clsx(
"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4",
"mb-10 items-stretch",
"items-stretch",
className
)}
>

View File

@@ -4,10 +4,9 @@ export function HairlineBleedGrid({ children }: { children: React.ReactNode }) {
return (
<div
className={clsx(
"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6",
"mb-10",
"grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4",
"items-stretch",
"gap-[1px]",
"gap-px",
"rounded-xl",
"overflow-hidden",
"bg-stone-50 dark:bg-stone-950",

View File

@@ -5,14 +5,7 @@ import clsx from "clsx";
function H1Sub({ children }: { children: React.ReactNode }) {
return (
<p
className={clsx(
"text-3xl lg:text-4xl",
"leading-snug",
"tracking-tight",
"mb-5",
"max-w-4xl",
"text-stone-700 dark:text-stone-500"
)}
className="text-lg text-pretty leading-relaxed max-w-3xl dark:text-stone-200 md:text-xl"
>
{children}
</p>

View File

@@ -4,24 +4,29 @@ import { LucideIcon } from "lucide-react";
export function LabelledFeatureIcon({
label,
icon: Icon,
explanation
}: {
label: string;
icon: LucideIcon;
explanation: React.ReactNode;
}) {
return (
<div
className={clsx(
"p-4 flex flex-col items-center justify-center gap-2",
"p-4 flex flex-col gap-3",
"not-prose text-base",
"border border-stone-200 dark:border-stone-900 rounded-xl"
)}
>
<div className="text-stone-500 mr-2">
<Icon strokeWidth={1} strokeLinecap="butt" size={40} />
<div>
<Icon className="text-stone-500" strokeWidth={1} strokeLinecap="butt" size={40} />
</div>
<div className="text-sm text-stone-700 md:text-base dark:text-stone-300">
<div className="text-stone-900 font-medium md:text-base dark:text-stone-100">
{label}
</div>
<div className="leading-relaxed space-y-3 text-sm">
{explanation}
</div>
</div>
);
}

View File

@@ -5,7 +5,6 @@ export function Prose(props: { children: ReactNode; className?: string }) {
return (
<div
className={clsx(
"mb-4",
"max-w-4xl prose-stone dark:prose-invert",
"prose-headings:font-display",
"lg:prose-h1:text-5xl prose-h1:font-medium prose-h1:tracking-tight",
@@ -13,7 +12,7 @@ export function Prose(props: { children: ReactNode; className?: string }) {
"prose-p:leading-snug",
"prose-strong:font-medium",
"prose-code:font-normal prose-code:before:content-none prose-code:after:content-none prose-code:bg-stone-100 prose-code:dark:bg-stone-900 prose-code:p-1 prose-code:rounded",
"prose-pre:border prose-pre:p-0 prose-pre:bg-white prose-pre:dark:bg-stone-900 dark:prose-pre:border-stone-800",
"prose-pre:border prose-pre:p-0 prose-pre:bg-stone-50 prose-pre:dark:bg-stone-900 dark:prose-pre:border-stone-800",
"prose-pre:text-black dark:prose-pre:text-white",
props.className || "prose"
)}

View File

@@ -38,7 +38,7 @@ export function Nav({
className={[
clsx(
"hidden md:flex sticky left-0 right-0 top-0 max-sm:bottom-0 w-full justify-center",
"bg-stone-50 dark:bg-stone-950 border-b max-sm:border-t border-stone-50 dark:border-b-stone-950",
"bg-white dark:bg-stone-950 border-b max-sm:border-t border-stone-50 dark:border-b-stone-950",
"max-h-none overflow-hidden transition[max-height] duration-300 ease-in-out",
"z-50",
menuOpen ? "h-[100dvh]" : "h-16"
@@ -81,13 +81,13 @@ export function Nav({
{mainLogo}
</NavLinkLogo>
<button
className="flex p-3 rounded-xl items-center"
className="flex gap-2 p-3 rounded-xl items-center"
onMouseDown={() => {
setMenuOpen((o) => !o);
setSearchOpen(false);
}}
>
<MenuIcon className="mr-2" />
<MenuIcon />
<BreadCrumb items={items} />
</button>
</div>
@@ -144,16 +144,14 @@ export function Nav({
.filter((item) => !("icon" in item))
.slice(0, 3)
.map((item, i) => (
<>
<NavLink
key={i}
href={item.href}
onClick={() => setMenuOpen(false)}
newTab={item.newTab}
>
{item.title}
</NavLink>
</>
<NavLink
key={i}
href={item.href}
onClick={() => setMenuOpen(false)}
newTab={item.newTab}
>
{item.title}
</NavLink>
))}
</div>
@@ -198,7 +196,7 @@ export function Nav({
<SearchIcon className="" />
</button> */}
<button
className="flex p-3 rounded-xl items-center"
className="flex gap-2 p-3 rounded-xl items-center"
onMouseDown={() => {
setMenuOpen((o) => !o);
setSearchOpen(false);
@@ -208,7 +206,7 @@ export function Nav({
<XIcon />
) : (
<>
<MenuIcon className="mr-2" />
<MenuIcon />
<BreadCrumb items={items} />
</>
)}

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