Compare commits

..

48 Commits

Author SHA1 Message Date
Guido D'Orsi
4019918b2b feat: re-export createImage on jazz-react 2025-03-27 09:48:49 +01:00
Guido D'Orsi
7b0d10a293 Merge pull request #1734 from garden-co/feat/optimize-group-role
perf: optimize Group.roleOf getter and made the transactions validation incremental for CoMap and CoFeed
2025-03-26 17:58:40 +01:00
Guido D'Orsi
156fba66e3 perf: optimize determineValidTransactions for when all the transactions are already known 2025-03-26 14:49:55 +01:00
Guido D'Orsi
95d6928d91 perf: made the transactions validation incremental for CoMap and CoFeed 2025-03-26 14:25:51 +01:00
Guido D'Orsi
2b94bc8af0 perf: optimize Group.roleOf getter 2025-03-26 14:08:24 +01:00
Guido D'Orsi
6e56a4351f Merge pull request #1733 from garden-co/fix/throw-invalid-ids
fix: handle invalid or undefined id
2025-03-26 11:56:17 +01:00
Guido D'Orsi
2013846d7b fix: ignore messages with an invalid or undefined id 2025-03-26 11:47:11 +01:00
Guido D'Orsi
2957362ab0 fix: throw when loading a coValue with an invalid or undefined id 2025-03-26 11:46:54 +01:00
Benjamin S. Leveritt
b23969ed0e Merge pull request #1706 from garden-co/1704-multi-cursor-example
1704 multi cursor example
2025-03-26 07:05:50 +00:00
Benjamin S. Leveritt
023fb4e1c7 Limit name length 2025-03-26 07:01:05 +00:00
Benjamin S. Leveritt
73963a7056 Tweak patch note 2025-03-26 07:00:52 +00:00
James Vickery
2b0d1b0e32 jazz-tools patch 2025-03-25 20:34:44 +00:00
James Vickery
5aad79005d rm tests 2025-03-25 20:29:09 +00:00
James Vickery
35cc6137e7 bits and bobs 2025-03-25 19:32:30 +00:00
Benjamin S. Leveritt
8d3849e27b Bury your dead 2025-03-25 12:57:46 +00:00
Benjamin S. Leveritt
92ca86ac75 Rename Cursor 2025-03-25 12:45:17 +00:00
Benjamin S. Leveritt
654a5caf69 Rename user detail getters 2025-03-25 12:42:13 +00:00
Benjamin S. Leveritt
a4f2e99370 Moves to useCoState 2025-03-25 12:38:57 +00:00
Trisha Lim
de11fdd07a collapse upgrade guides on side nav 2025-03-25 18:14:42 +07:00
Benjamin S. Leveritt
1b18801133 Fix depth indentation 2025-03-25 18:14:42 +07:00
Trisha Lim
02f3c31205 make framework selector sticky, add gradient to bottom 2025-03-25 18:14:42 +07:00
Trisha Lim
e5af81bf27 reduce spacing in TOC to match left nav 2025-03-25 18:14:42 +07:00
Guido D'Orsi
e13b9d2689 Merge pull request #1721 from garden-co/image-targetWidth
docs: replace maxWidth with targetWidth as the go-to API for defining  the target resolution
2025-03-25 11:02:31 +01:00
Guido D'Orsi
523196acdd Merge pull request #1723 from garden-co/fix/inspector-no-data
fix: inspector shows "no data" when there's data
2025-03-25 10:26:05 +01:00
Benjamin S. Leveritt
24d291b65f Add changable names 2025-03-25 07:38:54 +00:00
Trisha Lim
3367787f37 fix embedded inspector bg color 2025-03-25 13:55:09 +07:00
Trisha Lim
e7ae1359c0 fix: no data shown on comap if navigating from colist 2025-03-25 13:42:40 +07:00
Benjamin S. Leveritt
55e81849fe Checks for anon 2025-03-24 20:25:52 +00:00
Benjamin S. Leveritt
a2ad4a7dc3 Add random name labels 2025-03-24 20:23:17 +00:00
Benjamin S. Leveritt
dbaa1dfe3f Fix import order 2025-03-24 17:55:08 +00:00
Benjamin S. Leveritt
452d5f3030 Adds interpolation to the remote cursors 2025-03-24 17:53:03 +00:00
Benjamin S. Leveritt
16263442a7 Refactor ids into .env 2025-03-24 17:24:01 +00:00
Benjamin S. Leveritt
15384db02d Working cursors 2025-03-24 15:40:26 +00:00
Benjamin S. Leveritt
fa13fbf247 Debugging cursors 2025-03-24 15:30:39 +00:00
James Vickery
291562aafe replace useRef with useCallback 2025-03-24 14:43:24 +00:00
Benjamin S. Leveritt
b8ff6d2195 Adds some remote cursors 2025-03-24 14:29:50 +00:00
Guido D'Orsi
f0483b2500 docs: replace maxWidth with targetWidth as the go-to API for defining the target resolution 2025-03-24 14:16:51 +01:00
Benjamin S. Leveritt
90138a6848 Simplify schema 2025-03-24 11:50:27 +00:00
James Vickery
b55c276296 update vercel.json app name 2025-03-24 08:55:44 +00:00
Benjamin S. Leveritt
539f2b23ef Fix formatting 2025-03-24 08:55:44 +00:00
Benjamin S. Leveritt
daea669cb2 Adds global Cursors feed 2025-03-24 08:55:44 +00:00
James Vickery
55793722ff throttled onCursorMove 2025-03-24 08:55:44 +00:00
James Vickery
849f716700 cursors and stuff! 2025-03-24 08:55:43 +00:00
James Vickery
39d50ef040 a super cool draggable canvas 2025-03-24 08:55:43 +00:00
Benjamin S. Leveritt
73b120637c Add pointer tracking 2025-03-24 08:55:43 +00:00
Benjamin S. Leveritt
f41f61ffd3 Add canvas 2025-03-24 08:55:43 +00:00
Benjamin S. Leveritt
3436728416 Add example app 2025-03-24 08:55:43 +00:00
Trisha Lim
7ad2210a7f fix select component attributes 2025-03-24 15:14:49 +07:00
186 changed files with 4002 additions and 4012 deletions

View File

@@ -1,6 +0,0 @@
---
"jazz-tools": minor
"cojson": minor
---
Check CoValue access permissions when loading

View File

@@ -1,5 +0,0 @@
---
"jazz-tools": minor
---
Implement new API for deep loading

View File

@@ -1,5 +0,0 @@
---
"jazz-tools": minor
---
The .load function now returns `null` on error

View File

@@ -1,5 +0,0 @@
---
"cojson": minor
---
Return the EVERYONE role if the account is not direct a member of the group

View File

@@ -0,0 +1,5 @@
---
"cojson": patch
---
Performance: optimize Group.roleOf getter and made the transactions validation incremental for CoMap and CoFeed

View File

@@ -0,0 +1,5 @@
---
"jazz-react": patch
---
Re-export createImage from jazz-browser-media-images

View File

@@ -0,0 +1,5 @@
---
"cojson": patch
---
Throw an error when the user tries to load an invalid or undefined id

View File

@@ -0,0 +1,5 @@
---
"jazz-tools": patch
---
Export CoFeedEntry type

View File

@@ -1,5 +0,0 @@
---
"jazz-vue": patch
---
Fix types compilation for useAccount

View File

@@ -28,7 +28,7 @@ export default function Conversation() {
const { me } = useAccount(); const { me } = useAccount();
const [chat, setChat] = useState<Chat>(); const [chat, setChat] = useState<Chat>();
const [message, setMessage] = useState(""); const [message, setMessage] = useState("");
const loadedChat = useCoState(Chat, chat?.id, { resolve: { $each: true } }); const loadedChat = useCoState(Chat, chat?.id, [{}]);
const navigation = useNavigation(); const navigation = useNavigation();
const [isUploading, setIsUploading] = useState(false); const [isUploading, setIsUploading] = useState(false);
@@ -71,7 +71,7 @@ export default function Conversation() {
const loadChat = async (chatId: ID<Chat>) => { const loadChat = async (chatId: ID<Chat>) => {
try { try {
const chat = await Chat.load(chatId, me); const chat = await Chat.load(chatId, me, []);
setChat(chat); setChat(chat);
} catch (error) { } catch (error) {
console.log("Error loading chat", error); console.log("Error loading chat", error);

View File

@@ -20,7 +20,7 @@ import { Chat, Message } from "./schema";
export default function ChatScreen({ navigation }: { navigation: any }) { export default function ChatScreen({ navigation }: { navigation: any }) {
const { me, logOut } = useAccount(); const { me, logOut } = useAccount();
const [chatId, setChatId] = useState<ID<Chat>>(); const [chatId, setChatId] = useState<ID<Chat>>();
const loadedChat = useCoState(Chat, chatId, { resolve: { $each: true } }); const loadedChat = useCoState(Chat, chatId, [{}]);
const [message, setMessage] = useState(""); const [message, setMessage] = useState("");
const profile = useCoState(Profile, me._refs.profile?.id, {}); const profile = useCoState(Profile, me._refs.profile?.id, {});

View File

@@ -49,7 +49,7 @@ export default defineComponent({
}, },
}, },
setup(props) { setup(props) {
const chat = useCoState(Chat, props.chatId, { resolve: { $each: true } }); const chat = useCoState(Chat, props.chatId, [{}]);
const showNLastMessages = ref(30); const showNLastMessages = ref(30);
const displayedMessages = computed(() => { const displayedMessages = computed(() => {

View File

@@ -15,7 +15,6 @@
"dependencies": { "dependencies": {
"clsx": "^2.0.0", "clsx": "^2.0.0",
"hash-slash": "workspace:*", "hash-slash": "workspace:*",
"jazz-browser-media-images": "workspace:*",
"jazz-inspector": "workspace:*", "jazz-inspector": "workspace:*",
"jazz-react": "workspace:*", "jazz-react": "workspace:*",
"jazz-tools": "workspace:*", "jazz-tools": "workspace:*",

View File

@@ -1,5 +1,4 @@
import { createImage } from "jazz-browser-media-images"; import { createImage, useAccount, useCoState } from "jazz-react";
import { useAccount, useCoState } from "jazz-react";
import { Account, ID } from "jazz-tools"; import { Account, ID } from "jazz-tools";
import { useState } from "react"; import { useState } from "react";
import { Chat, Message } from "./schema.ts"; import { Chat, Message } from "./schema.ts";
@@ -17,8 +16,8 @@ import {
} from "./ui.tsx"; } from "./ui.tsx";
export function ChatScreen(props: { chatID: ID<Chat> }) { export function ChatScreen(props: { chatID: ID<Chat> }) {
const chat = useCoState(Chat, props.chatID, { resolve: { $each: true } });
const account = useAccount(); const account = useAccount();
const chat = useCoState(Chat, props.chatID, [{}]);
const [showNLastMessages, setShowNLastMessages] = useState(30); const [showNLastMessages, setShowNLastMessages] = useState(30);
if (!chat) if (!chat)

View File

@@ -12,7 +12,6 @@
}, },
"dependencies": { "dependencies": {
"hash-slash": "workspace:*", "hash-slash": "workspace:*",
"jazz-browser-media-images": "workspace:*",
"jazz-react": "workspace:*", "jazz-react": "workspace:*",
"jazz-tools": "workspace:*", "jazz-tools": "workspace:*",
"react": "^18.3.1", "react": "^18.3.1",

View File

@@ -12,9 +12,7 @@ import {
} from "./schema.ts"; } from "./schema.ts";
export function CreateOrder() { export function CreateOrder() {
const { me } = useAccount({ const { me } = useAccount({ root: { draft: {}, orders: [] } });
resolve: { root: { draft: true, orders: true } },
});
const router = useIframeHashRouter(); const router = useIframeHashRouter();
const [errors, setErrors] = useState<string[]>([]); const [errors, setErrors] = useState<string[]>([]);
@@ -62,7 +60,7 @@ function CreateOrderForm({
onSave: (draft: DraftBubbleTeaOrder) => void; onSave: (draft: DraftBubbleTeaOrder) => void;
}) { }) {
const draft = useCoState(DraftBubbleTeaOrder, id, { const draft = useCoState(DraftBubbleTeaOrder, id, {
resolve: { addOns: true }, addOns: [],
}); });
if (!draft) return; if (!draft) return;

View File

@@ -2,7 +2,7 @@ import { useAccount } from "jazz-react";
export function DraftIndicator() { export function DraftIndicator() {
const { me } = useAccount({ const { me } = useAccount({
resolve: { root: { draft: true } }, root: { draft: {} },
}); });
if (me?.root.draft?.hasChanges) { if (me?.root.draft?.hasChanges) {

View File

@@ -6,7 +6,7 @@ import { OrderThumbnail } from "./OrderThumbnail.tsx";
import { BubbleTeaOrder } from "./schema.ts"; import { BubbleTeaOrder } from "./schema.ts";
export function EditOrder(props: { id: ID<BubbleTeaOrder> }) { export function EditOrder(props: { id: ID<BubbleTeaOrder> }) {
const order = useCoState(BubbleTeaOrder, props.id); const order = useCoState(BubbleTeaOrder, props.id, []);
if (!order) return; if (!order) return;

View File

@@ -4,7 +4,7 @@ import { OrderThumbnail } from "./OrderThumbnail.tsx";
export function Orders() { export function Orders() {
const { me } = useAccount({ const { me } = useAccount({
resolve: { root: { orders: true } }, root: { orders: [] },
}); });
return ( return (

View File

@@ -11,7 +11,6 @@
"format-and-lint:fix": "biome check . --write" "format-and-lint:fix": "biome check . --write"
}, },
"dependencies": { "dependencies": {
"jazz-browser-media-images": "workspace:*",
"jazz-react": "workspace:*", "jazz-react": "workspace:*",
"jazz-tools": "workspace:*", "jazz-tools": "workspace:*",
"react": "^18.3.1", "react": "^18.3.1",

View File

@@ -1,5 +1,4 @@
import { createImage } from "jazz-browser-media-images"; import { ProgressiveImg, createImage, useAccount } from "jazz-react";
import { ProgressiveImg, useAccount } from "jazz-react";
import { ChangeEvent, useEffect, useRef, useState } from "react"; import { ChangeEvent, useEffect, useRef, useState } from "react";
export default function ImageUpload() { export default function ImageUpload() {

View File

@@ -0,0 +1,3 @@
VITE_CURSOR_FEED_ID=multi-cursors-250425-1708
VITE_GROUP_ID=co_zXE8C8sd9QxEbxnt3neRvFRPFUc
VITE_OLD_CURSOR_AGE_SECONDS=36000

View File

@@ -0,0 +1,3 @@
VITE_CURSOR_FEED_ID=example-cursor-feed-id
VITE_GROUP_ID=co_example-group-id
VITE_OLD_CURSOR_AGE_SECONDS=5

28
examples/multi-cursors/.gitignore vendored Normal file
View File

@@ -0,0 +1,28 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
/test-results/
/playwright-report/
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
playwright-report

View File

@@ -0,0 +1,3 @@
# Multi-cursor example
An example app of using Jazz for showing multiple-cursors on a simple canvas.

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

View File

@@ -0,0 +1,16 @@
<!doctype html>
<html lang="en" class="h-full">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/png" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Jazz | Multi-cursors</title>
</head>
<body class="h-full flex flex-col">
<div id="root" class="align-self-center flex-1"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

View File

@@ -0,0 +1,35 @@
{
"name": "multi-cursors",
"private": true,
"version": "0.0.58",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"preview": "vite preview",
"test:e2e": "playwright test",
"test:e2e:ui": "playwright test --ui",
"format-and-lint": "biome check .",
"format-and-lint:fix": "biome check . --write"
},
"dependencies": {
"@react-spring/web": "^9.7.5",
"jazz-react": "workspace:*",
"jazz-tools": "workspace:*",
"react": "^18.3.1",
"react-dom": "^18.3.1"
},
"devDependencies": {
"@biomejs/biome": "1.9.4",
"@types/react": "^18.3.12",
"@types/react-dom": "^18.3.1",
"@vitejs/plugin-react": "^4.3.3",
"autoprefixer": "^10.4.20",
"globals": "^15.11.0",
"is-ci": "^3.0.1",
"postcss": "^8.4.27",
"tailwindcss": "^3.4.17",
"typescript": "~5.6.2",
"vite": "^6.0.11"
}
}

View File

@@ -0,0 +1,6 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};

View File

@@ -0,0 +1,65 @@
import { useAccount } from "jazz-react";
import { Group, type ID } from "jazz-tools";
import { useEffect, useState } from "react";
import { Logo } from "./Logo";
import Container from "./components/Container";
import { CursorFeed } from "./schema";
import { getName } from "./utils/getName";
import { loadCursorContainer } from "./utils/loadCursorContainer";
const cursorFeedIDToLoad = import.meta.env.VITE_CURSOR_FEED_ID;
const groupIDToLoad = import.meta.env.VITE_GROUP_ID;
function App() {
const { me } = useAccount();
const [loaded, setLoaded] = useState(false);
const [cursorFeedID, setCursorFeedID] = useState<ID<CursorFeed> | null>(null);
useEffect(() => {
if (!me?.id) return;
const loadCursorFeed = async () => {
const id = await loadCursorContainer(
me,
cursorFeedIDToLoad as ID<CursorFeed>,
groupIDToLoad as ID<Group>,
);
if (id) {
setCursorFeedID(id);
setLoaded(true);
}
};
loadCursorFeed();
}, [me?.id]);
return (
<>
<main className="h-screen">
{loaded && cursorFeedID ? (
<Container cursorFeedID={cursorFeedID} />
) : (
<div>Loading...</div>
)}
</main>
<footer className="fixed bottom-4 right-4 flex items-center gap-4">
<input
type="text"
value={getName(me?.profile?.name, me?.sessionID)}
onChange={(e) => {
if (!me?.profile) return;
me.profile.name = e.target.value;
}}
placeholder="Your name"
className="px-2 py-1 rounded border pointer-events-auto"
autoComplete="off"
maxLength={32}
/>
<div className="pointer-events-none">
<Logo />
</div>
</footer>
</>
);
}
export default App;

View File

@@ -0,0 +1,21 @@
export function Logo() {
return (
<svg
viewBox="0 0 386 146"
fill="none"
xmlns="http://www.w3.org/2000/svg"
className="text-black w-48 mx-auto"
>
<path
d="M176.725 33.865H188.275V22.7H176.725V33.865ZM164.9 129.4H172.875C182.72 129.4 188.275 123.9 188.275 114.22V43.6H176.725V109.545C176.725 115.65 173.975 118.51 167.925 118.51H164.9V129.4ZM245.298 53.28C241.613 45.47 233.363 41.95 222.748 41.95C208.998 41.95 200.748 48.44 197.888 58.615L208.613 61.915C210.648 55.315 216.368 52.565 222.638 52.565C231.933 52.565 235.673 56.415 236.058 64.61C226.433 65.93 216.643 67.195 209.768 69.23C200.583 72.145 195.743 77.865 195.743 86.83C195.743 96.51 202.673 104.65 215.818 104.65C225.443 104.65 232.318 101.35 237.213 94.365V103H247.388V66.425C247.388 61.475 247.168 57.185 245.298 53.28ZM217.853 95.245C210.483 95.245 207.128 91.34 207.128 86.72C207.128 82.045 210.593 79.515 215.323 77.92C220.328 76.435 226.983 75.5 235.948 74.18C235.893 76.93 235.673 80.725 234.738 83.475C233.418 89.25 227.643 95.245 217.853 95.245ZM251.22 103H301.545V92.715H269.535L303.195 45.47V43.6H254.3V53.885H284.935L251.22 101.185V103ZM304.815 103H355.14V92.715H323.13L356.79 45.47V43.6H307.895V53.885H338.53L304.815 101.185V103Z"
fill="currentColor"
/>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M136.179 44.8277C136.179 44.8277 136.179 44.8277 136.179 44.8276V21.168C117.931 28.5527 97.9854 32.6192 77.0897 32.6192C65.1466 32.6192 53.5138 31.2908 42.331 28.7737V51.4076C42.331 51.4076 42.331 51.4076 42.331 51.4076V81.1508C41.2955 80.4385 40.1568 79.8458 38.9405 79.3915C36.1732 78.358 33.128 78.0876 30.1902 78.6145C27.2524 79.1414 24.5539 80.4419 22.4358 82.3516C20.3178 84.2613 18.8754 86.6944 18.291 89.3433C17.7066 91.9921 18.0066 94.7377 19.1528 97.2329C20.2991 99.728 22.2403 101.861 24.7308 103.361C27.2214 104.862 30.1495 105.662 33.1448 105.662H33.1455C33.6061 105.662 33.8365 105.662 34.0314 105.659C44.5583 105.449 53.042 96.9656 53.2513 86.4386C53.2534 86.3306 53.2544 86.2116 53.2548 86.0486H53.2552V85.7149L53.2552 85.5521V82.0762L53.2552 53.1993C61.0533 54.2324 69.0092 54.7656 77.0897 54.7656C77.6696 54.7656 78.2489 54.7629 78.8276 54.7574V110.696C77.792 109.983 76.6533 109.391 75.437 108.936C72.6697 107.903 69.6246 107.632 66.6867 108.159C63.7489 108.686 61.0504 109.987 58.9323 111.896C56.8143 113.806 55.3719 116.239 54.7875 118.888C54.2032 121.537 54.5031 124.283 55.6494 126.778C56.7956 129.273 58.7368 131.405 61.2273 132.906C63.7179 134.406 66.646 135.207 69.6414 135.207C70.1024 135.207 70.3329 135.207 70.5279 135.203C81.0548 134.994 89.5385 126.51 89.7478 115.983C89.7517 115.788 89.7517 115.558 89.7517 115.097V111.621L89.7517 54.3266C101.962 53.4768 113.837 51.4075 125.255 48.2397V80.9017C124.219 80.1894 123.081 79.5966 121.864 79.1424C119.097 78.1089 116.052 77.8384 113.114 78.3653C110.176 78.8922 107.478 80.1927 105.36 82.1025C103.242 84.0122 101.799 86.4453 101.215 89.0941C100.631 91.743 100.931 94.4886 102.077 96.9837C103.223 99.4789 105.164 101.612 107.655 103.112C110.145 104.612 113.073 105.413 116.069 105.413C116.53 105.413 116.76 105.413 116.955 105.409C127.482 105.2 135.966 96.7164 136.175 86.1895C136.179 85.9945 136.179 85.764 136.179 85.3029V81.8271L136.179 44.8277Z"
fill="#3313F7"
/>
</svg>
);
}

View File

@@ -0,0 +1 @@
export const apiKey = "jazz-multi-cursors@garden.co";

View File

@@ -0,0 +1,76 @@
import { useAccount } from "jazz-react";
import { CoFeedEntry, co } from "jazz-tools";
import { CursorMoveEvent, useCanvas } from "../hooks/useCanvas";
import { Cursor as CursorType } from "../types";
import { getColor } from "../utils/getColor";
import { getName } from "../utils/getName";
import { CanvasBackground } from "./CanvasBackground";
import { CanvasDemoContent } from "./CanvasDemoContent";
import { Cursor } from "./Cursor";
const OLD_CURSOR_AGE_SECONDS = Number(
import.meta.env.VITE_OLD_CURSOR_AGE_SECONDS,
);
interface CanvasProps {
remoteCursors: CoFeedEntry<co<CursorType>>[];
onCursorMove: (move: CursorMoveEvent) => void;
name: string;
}
function Canvas({ remoteCursors, onCursorMove, name }: CanvasProps) {
const { me } = useAccount();
const {
svgProps,
isDragging,
isMouseOver,
mousePosition,
bgPosition,
dottedGridSize,
} = useCanvas({ onCursorMove });
return (
<svg width="100%" height="100%" {...svgProps}>
<CanvasBackground
bgPosition={bgPosition}
dottedGridSize={dottedGridSize}
/>
<CanvasDemoContent />
{remoteCursors.map((entry) => {
if (
entry.tx.sessionID === me?.sessionID ||
(OLD_CURSOR_AGE_SECONDS &&
entry.madeAt < new Date(Date.now() - 1000 * OLD_CURSOR_AGE_SECONDS))
) {
return null;
}
return (
<Cursor
key={entry.tx.sessionID}
position={entry.value.position}
color={getColor(entry.tx.sessionID)}
isDragging={false}
isRemote={true}
name={getName(entry.by?.profile?.name, entry.tx.sessionID)}
/>
);
})}
{isMouseOver ? (
<Cursor
position={mousePosition}
color="#FF69B4"
isDragging={isDragging}
isRemote={false}
name={name}
/>
) : null}
</svg>
);
}
export default Canvas;

View File

@@ -0,0 +1,33 @@
interface CanvasBackgroundProps {
bgPosition: { x: number; y: number };
dottedGridSize: number;
}
export function CanvasBackground({
bgPosition,
dottedGridSize,
}: CanvasBackgroundProps) {
const bgProps = { x: "-10000", y: "-10000", width: "20000", height: "20000" };
return (
<>
<defs>
<pattern
id="dottedGrid"
width={dottedGridSize}
height={dottedGridSize}
patternUnits="userSpaceOnUse"
patternContentUnits="userSpaceOnUse"
>
<circle cx="20" cy="20" r="2" fill="oklch(0.923 0.003 48.717)" />
</pattern>
</defs>
{/* backgrounds using translate to appear infinite by moving it to visible area */}
<g transform={`translate(${bgPosition.x}, ${bgPosition.y})`}>
<rect {...bgProps} fill="oklch(0.97 0.001 106.424)" />
<rect {...bgProps} fill="url(#dottedGrid)" />
</g>
</>
);
}

View File

@@ -0,0 +1,19 @@
export function CanvasDemoContent() {
return (
<>
<circle cx={0} cy={0} r="200" fill="oklch(0.985 0.001 106.423)" />
<text
x={0}
y={0}
textAnchor="middle"
dominantBaseline="middle"
fontSize="32"
fontFamily="ui-monospace, SFMono-Regular, SF Mono, Menlo, Consolas, Liberation Mono, monospace"
fill="#3318F7"
>
Hello, World!
</text>
</>
);
}

View File

@@ -0,0 +1,30 @@
import { useAccount, useCoState } from "jazz-react";
import { ID } from "jazz-tools";
import { CursorFeed } from "../schema";
import { getName } from "../utils/getName";
import Canvas from "./Canvas";
/** A higher order component that wraps the canvas. */
function Container({ cursorFeedID }: { cursorFeedID: ID<CursorFeed> }) {
const { me } = useAccount();
const cursors = useCoState(CursorFeed, cursorFeedID, []);
return (
<Canvas
onCursorMove={(move) => {
if (!(cursors && me)) return;
cursors.push({
position: {
x: move.position.x,
y: move.position.y,
},
});
}}
remoteCursors={Object.values(cursors?.perSession ?? {})}
name={getName(me?.profile?.name, me?.sessionID)}
/>
);
}
export default Container;

View File

@@ -0,0 +1,64 @@
import { animated, to, useSpring } from "@react-spring/web";
interface CursorProps {
position: { x: number; y: number };
color: string;
isDragging: boolean;
isRemote: boolean;
name: string;
}
export function Cursor({
position,
color,
isDragging,
isRemote,
name,
}: CursorProps) {
const springs = useSpring({
x: position.x,
y: position.y,
immediate: !isRemote,
config: {
tension: 170,
friction: 26,
},
});
return (
<animated.g
transform={to(
[springs.x, springs.y],
(x: number, y: number) => `translate(${x}, ${y})`,
)}
>
<polygon
points="0,0 0,20 14.3,14.3"
fill={
isDragging ? color : `color-mix(in oklch, ${color}, transparent 56%)`
}
stroke={color}
strokeWidth="3"
strokeLinecap="round"
strokeLinejoin="round"
/>
<text
x="10"
y="25"
fill={color}
stroke="white"
strokeWidth="3"
strokeLinejoin="round"
paintOrder="stroke"
fontSize="14"
dominantBaseline="hanging"
style={{
fontFamily: "Inter, Manrope, system-ui, sans-serif",
fontWeight: 500,
}}
>
{name}
</text>
</animated.g>
);
}

View File

@@ -0,0 +1,138 @@
import { useCallback, useEffect, useState } from "react";
import { throttleTime } from "../utils/throttleTime";
export interface CursorMoveEvent {
position: { x: number; y: number };
isDragging: boolean;
}
export function useCanvas({
onCursorMove,
throttleMs = 100,
}: {
onCursorMove: (event: CursorMoveEvent) => void;
throttleMs?: number;
}) {
const [viewBox, setViewBox] = useState({
x: 0,
y: 0,
width: window.innerWidth,
height: window.innerHeight,
});
const [isDragging, setIsDragging] = useState(false);
const [isMouseOver, setIsMouseOver] = useState(false);
const [dragStart, setDragStart] = useState({ x: 0, y: 0 });
const [mousePosition, setMousePosition] = useState({ x: 0, y: 0 });
const onCursorMoveThrottled = useCallback(
throttleTime((move: CursorMoveEvent) => onCursorMove(move), throttleMs),
[onCursorMove, throttleMs],
);
useEffect(() => {
const handleResize = () => {
setViewBox((prev) => ({
...prev,
width: window.innerWidth,
height: window.innerHeight,
}));
};
setViewBox((prev) => ({
...prev,
x: -window.innerWidth / 2,
y: -window.innerHeight / 2,
}));
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, []);
const handleMouseDown = (e: React.MouseEvent<SVGSVGElement>) => {
setIsDragging(true);
setDragStart({
x: e.clientX,
y: e.clientY,
});
onCursorMoveThrottled({
position: mousePosition,
isDragging: true,
});
};
const handleMouseUp = () => {
setIsDragging(false);
onCursorMoveThrottled({
position: mousePosition,
isDragging: false,
});
};
const handleMouseEnter = () => setIsMouseOver(true);
const handleMouseLeave = () => {
setIsMouseOver(false);
setIsDragging(false);
onCursorMoveThrottled({
position: mousePosition,
isDragging: false,
});
};
const handleMouseMove = (e: React.MouseEvent<SVGSVGElement>) => {
const svg = e.currentTarget;
const ctm = svg.getScreenCTM();
if (!ctm) throw new Error("can't get SVG screen CTM");
const point = svg.createSVGPoint();
point.x = e.clientX;
point.y = e.clientY;
const svgPoint = point.matrixTransform(ctm.inverse());
setMousePosition(svgPoint);
onCursorMoveThrottled({
position: svgPoint,
isDragging,
});
if (!isDragging) return;
const dx = e.clientX - dragStart.x;
const dy = e.clientY - dragStart.y;
setViewBox((prev) => ({ ...prev, x: prev.x - dx, y: prev.y - dy }));
setDragStart({ x: e.clientX, y: e.clientY });
};
const dottedGridSize = 40;
const bgPosition = {
x: Math.floor(viewBox.x / dottedGridSize) * dottedGridSize,
y: Math.floor(viewBox.y / dottedGridSize) * dottedGridSize,
};
const handlers = {
onMouseDown: handleMouseDown,
onMouseUp: handleMouseUp,
onMouseEnter: handleMouseEnter,
onMouseLeave: handleMouseLeave,
onMouseMove: handleMouseMove,
};
const svgProps: React.SVGProps<SVGSVGElement> = {
...handlers,
viewBox: `${viewBox.x} ${viewBox.y} ${viewBox.width} ${viewBox.height}`,
className: "select-none cursor-none",
};
return {
svgProps,
isDragging,
isMouseOver,
mousePosition,
bgPosition,
dottedGridSize,
};
}

View File

@@ -0,0 +1,3 @@
@tailwind base;
@tailwind components;
@tailwind utilities;

View File

@@ -0,0 +1,27 @@
import { JazzProvider } from "jazz-react";
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App.tsx";
import "./index.css";
import { apiKey } from "./apiKey.ts";
import { CursorAccount } from "./schema.ts";
declare module "jazz-react" {
export interface Register {
Account: CursorAccount;
}
}
createRoot(document.getElementById("root")!).render(
<StrictMode>
<JazzProvider
sync={{
peer: `wss://cloud.jazz.tools/?key=${apiKey}`,
when: "always",
}}
AccountSchema={CursorAccount}
>
<App />
</JazzProvider>
</StrictMode>,
);

View File

@@ -0,0 +1,51 @@
import { Account, CoFeed, CoMap, Group, Profile, co } from "jazz-tools";
import type { Camera, Cursor } from "./types";
export class CursorFeed extends CoFeed.Of(co.json<Cursor>()) {}
export class CursorProfile extends Profile {
name = co.string;
}
export class CursorRoot extends CoMap {
camera = co.json<Camera>();
cursors = co.ref(CursorFeed);
}
export class CursorContainer extends CoMap {
cursorFeed = co.ref(CursorFeed);
}
export class CursorAccount extends Account {
profile = co.ref(CursorProfile);
root = co.ref(CursorRoot);
/** 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: CursorAccount) {
if (this.root === undefined) {
this.root = CursorRoot.create({
camera: {
position: {
x: 0,
y: 0,
},
},
cursors: CursorFeed.create([]),
});
}
if (this.profile === undefined) {
const group = Group.create();
group.addMember("everyone", "reader"); // The profile info is visible to everyone
this.profile = CursorProfile.create(
{
name: "Anonymous user",
},
group,
);
}
}
}

20
examples/multi-cursors/src/types.d.ts vendored Normal file
View File

@@ -0,0 +1,20 @@
export type Vec2 = {
x: number;
y: number;
};
export type Cursor = {
position: Vec2;
};
export type Camera = {
position: Vec2;
};
export type RemoteCursor = Cursor & {
id: ID;
color: string;
name: string;
isRemote: true;
isDragging: boolean;
};

View File

@@ -0,0 +1,29 @@
/**
* Converts a string (like a coID) to a consistent color with controlled brightness
* Uses Oklch color model for better perceptual uniformity
* @param str - The string to convert to a color (typically a coID)
* @returns An Oklch color string
*/
export const getColor = (str: string): string => {
// Simple hash function to get a number from a string
let hash = 0;
for (let i = 0; i < str.length; i++) {
hash = str.charCodeAt(i) + ((hash << 5) - hash);
}
// Convert to a positive number
hash = Math.abs(hash);
// Use the hash to determine the hue (0-360)
// This spreads colors around the entire color wheel
const hue = hash % 360;
// Use fixed values for lightness and chroma to ensure consistent brightness
// Lightness: 0.65 gives good visibility on both light and dark backgrounds
// Chroma: 0.15 gives vibrant but not overpowering colors
const lightness = 0.65;
const chroma = 0.15;
// Return the color as an Oklch string
return `oklch(${lightness} ${chroma} ${hue})`;
};

View File

@@ -0,0 +1,44 @@
import { Account, ID, SessionID } from "jazz-tools";
const animals = [
"elephant",
"penguin",
"giraffe",
"octopus",
"kangaroo",
"dolphin",
"cheetah",
"koala",
"platypus",
"pangolin",
"tiger",
"zebra",
"panda",
"lion",
"honey badger",
"hippo",
];
/**
* Get a psuedo-random username.
* @param str The string to get the username from.
* @returns A psuedo-random username.
*/
export function getRandomUsername(str: string) {
return `Anonymous ${animals[Math.abs(str.split("").reduce((acc, char) => acc + char.charCodeAt(0), 0)) % animals.length]}`;
}
/**
* Get the name of a user. If the name is "Anonymous user" or not set, return a random username.
* @param name The name of the user.
* @param id The id of the user.
* @returns The psuedo-random name of the user.
*/
export function getName(
name: string | undefined,
id: ID<Account> | SessionID | undefined,
) {
if (name === "Anonymous user" || !name || !id)
return getRandomUsername(id ?? "");
return name;
}

View File

@@ -0,0 +1,65 @@
import { Account, Group, type ID } from "jazz-tools";
import { CursorContainer, CursorFeed } from "../schema";
export async function loadGroup(me: Account, groupID: ID<Group>) {
const group = await Group.load(groupID, {});
if (group === undefined) {
const group = Group.create({
owner: me,
});
group.addMember("everyone", "writer");
console.log("Created group:", group.id);
return group;
}
return group;
}
/**
* Loads the cursor container for the given cursor feed ID.
* If the cursor container does not exist, it creates a new one.
* If the cursor container exists, it loads the existing one.
* @param me - The account of the current user.
* @param cursorFeedID - The ID of the cursor feed.
* @param groupID - The ID of the group.
*/
export async function loadCursorContainer(
me: Account,
cursorFeedID: ID<CursorFeed>,
groupID: ID<Group>,
): Promise<ID<CursorFeed> | undefined> {
if (!me) return;
const group = await loadGroup(me, groupID);
const cursorContainerID = CursorContainer.findUnique(
cursorFeedID,
group?.id as ID<Group>,
);
const cursorContainer = await CursorContainer.load(cursorContainerID, {
cursorFeed: [],
});
if (cursorContainer === undefined) {
console.log("Global cursors does not exist, creating...");
const cursorContainer = CursorContainer.create(
{
cursorFeed: CursorFeed.create([], {
owner: group,
}),
},
{
owner: group,
unique: cursorFeedID,
},
);
console.log("Created global cursors", cursorContainer.id);
if (cursorContainer.cursorFeed === null) {
throw new Error("cursorFeed is null");
}
return cursorContainer.cursorFeed.id;
} else {
console.log(
"Global cursors already exists, loading...",
cursorContainer.id,
);
return cursorContainer.cursorFeed.id;
}
}

View File

@@ -0,0 +1,68 @@
/**
* Options for the throttleTime function
*/
interface ThrottleOptions {
/** Whether to invoke on the leading edge of the timeout (default: true) */
leading?: boolean;
/** Whether to invoke on the trailing edge of the timeout (default: true) */
trailing?: boolean;
}
/**
* Creates a throttled function that only invokes the provided function
* at most once per every `wait` milliseconds.
*
* @param func - The function to throttle
* @param wait - The number of milliseconds to throttle invocations to
* @param options - The options object
* @returns Returns the new throttled function
*/
export function throttleTime<T extends (...args: any[]) => any>(
func: T,
wait: number,
options: ThrottleOptions = {},
): (...args: Parameters<T>) => ReturnType<T> | undefined {
const { leading = true, trailing = true } = options;
let timeout: NodeJS.Timeout | null = null;
let previous = 0;
let result: ReturnType<T> | undefined;
let context: any;
let args: Parameters<T>;
const later = (): void => {
previous = !leading ? 0 : Date.now();
timeout = null;
result = func.apply(context, args);
if (!timeout) context = args = null!;
};
return function throttled(
this: any,
...params: Parameters<T>
): ReturnType<T> | undefined {
const now = Date.now();
if (!previous && !leading) previous = now;
const remaining = wait - (now - previous);
context = this;
args = params;
if (remaining <= 0 || remaining > wait) {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
previous = now;
result = func.apply(context, args);
if (!timeout) context = args = null!;
} else if (!timeout && trailing) {
timeout = setTimeout(later, remaining);
}
return result;
};
}

View File

@@ -0,0 +1 @@
/// <reference types="vite/client" />

View File

@@ -0,0 +1,23 @@
import type { Config } from "tailwindcss";
const config: Config = {
content: ["./index.html", "./src/**/*.{js,ts,jsx,tsx}"],
theme: {
extend: {
container: {
center: true,
padding: {
DEFAULT: "0.75rem",
sm: "1rem",
},
screens: {
lg: "600px",
xl: "600px",
},
},
},
},
plugins: [],
} as const;
export default config;

View File

@@ -0,0 +1,24 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2023", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
"moduleResolution": "Bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["src"]
}

View File

@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}

View File

@@ -0,0 +1,22 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "ES2022",
"lib": ["ES2023"],
"module": "ESNext",
"skipLibCheck": true,
"moduleResolution": "Bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["vite.config.ts"]
}

View File

@@ -0,0 +1,8 @@
{
"build": {
"env": {
"APP_NAME": "multi-cursors"
}
},
"ignoreCommand": "node ../../ignore-vercel-build.js"
}

View File

@@ -0,0 +1,7 @@
import react from "@vitejs/plugin-react";
import { defineConfig } from "vite";
// https://vite.dev/config/
export default defineConfig({
plugins: [react()],
});

View File

@@ -24,7 +24,10 @@ export function HomePage({ mediaPlayer }: { mediaPlayer: MediaPlayer }) {
* access rights to CoValues. We get it from the top-level provider `<WithJazz/>`. * access rights to CoValues. We get it from the top-level provider `<WithJazz/>`.
*/ */
const { me } = useAccount({ const { me } = useAccount({
resolve: { root: { rootPlaylist: true, playlists: true } }, root: {
rootPlaylist: {},
playlists: [],
},
}); });
const navigate = useNavigate(); const navigate = useNavigate();
@@ -48,9 +51,8 @@ export function HomePage({ mediaPlayer }: { mediaPlayer: MediaPlayer }) {
const params = useParams<{ playlistId: ID<Playlist> }>(); const params = useParams<{ playlistId: ID<Playlist> }>();
const playlistId = params.playlistId ?? me?.root._refs.rootPlaylist.id; const playlistId = params.playlistId ?? me?.root._refs.rootPlaylist.id;
const playlist = useCoState(Playlist, playlistId, { const playlist = useCoState(Playlist, playlistId, {
resolve: { tracks: true }, tracks: [],
}); });
const isRootPlaylist = !params.playlistId; const isRootPlaylist = !params.playlistId;

View File

@@ -27,11 +27,9 @@ export async function uploadMusicTracks(
isExampleTrack: boolean = false, isExampleTrack: boolean = false,
) { ) {
const { root } = await MusicaAccount.getMe().ensureLoaded({ const { root } = await MusicaAccount.getMe().ensureLoaded({
resolve: {
root: { root: {
rootPlaylist: { rootPlaylist: {
tracks: true, tracks: [],
},
}, },
}, },
}); });
@@ -67,10 +65,8 @@ export async function uploadMusicTracks(
export async function createNewPlaylist() { export async function createNewPlaylist() {
const { root } = await MusicaAccount.getMe().ensureLoaded({ const { root } = await MusicaAccount.getMe().ensureLoaded({
resolve: {
root: { root: {
playlists: true, playlists: [],
},
}, },
}); });
@@ -153,11 +149,9 @@ export async function updateMusicTrackTitle(track: MusicTrack, title: string) {
export async function updateActivePlaylist(playlist?: Playlist) { export async function updateActivePlaylist(playlist?: Playlist) {
const { root } = await MusicaAccount.getMe().ensureLoaded({ const { root } = await MusicaAccount.getMe().ensureLoaded({
resolve: {
root: { root: {
activePlaylist: true, activePlaylist: {},
rootPlaylist: true, rootPlaylist: {},
},
}, },
}); });
@@ -166,9 +160,7 @@ export async function updateActivePlaylist(playlist?: Playlist) {
export async function updateActiveTrack(track: MusicTrack) { export async function updateActiveTrack(track: MusicTrack) {
const { root } = await MusicaAccount.getMe().ensureLoaded({ const { root } = await MusicaAccount.getMe().ensureLoaded({
resolve: {
root: {}, root: {},
},
}); });
root.activeTrack = track; root.activeTrack = track;
@@ -178,23 +170,17 @@ export async function onAnonymousAccountDiscarded(
anonymousAccount: MusicaAccount, anonymousAccount: MusicaAccount,
) { ) {
const { root: anonymousAccountRoot } = await anonymousAccount.ensureLoaded({ const { root: anonymousAccountRoot } = await anonymousAccount.ensureLoaded({
resolve: {
root: { root: {
rootPlaylist: { rootPlaylist: {
tracks: { tracks: [{}],
$each: true,
},
},
}, },
}, },
}); });
const me = await MusicaAccount.getMe().ensureLoaded({ const me = await MusicaAccount.getMe().ensureLoaded({
resolve: {
root: { root: {
rootPlaylist: { rootPlaylist: {
tracks: true, tracks: [],
},
}, },
}, },
}); });
@@ -211,10 +197,8 @@ export async function onAnonymousAccountDiscarded(
export async function deletePlaylist(playlistId: string) { export async function deletePlaylist(playlistId: string) {
const { root } = await MusicaAccount.getMe().ensureLoaded({ const { root } = await MusicaAccount.getMe().ensureLoaded({
resolve: {
root: { root: {
playlists: true, playlists: [],
},
}, },
}); });

View File

@@ -9,7 +9,7 @@ import { getNextTrack, getPrevTrack } from "./lib/getters";
export function useMediaPlayer() { export function useMediaPlayer() {
const { me } = useAccount({ const { me } = useAccount({
resolve: { root: true }, root: {},
}); });
const playState = usePlayState(); const playState = usePlayState();

View File

@@ -16,10 +16,8 @@ export function InvitePage() {
const playlist = await Playlist.load(playlistId, {}); const playlist = await Playlist.load(playlistId, {});
const me = await MusicaAccount.getMe().ensureLoaded({ const me = await MusicaAccount.getMe().ensureLoaded({
resolve: {
root: { root: {
playlists: true, playlists: [],
},
}, },
}); });

View File

@@ -22,13 +22,9 @@ export function AuthModal({ open, onOpenChange }: AuthModalProps) {
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const { me } = useAccount({ const { me } = useAccount({
resolve: {
root: { root: {
rootPlaylist: { rootPlaylist: {
tracks: { tracks: [{}],
$each: true,
},
},
}, },
}, },
}); });

View File

@@ -30,7 +30,9 @@ export function MusicTrackRow({
const track = useCoState(MusicTrack, trackId); const track = useCoState(MusicTrack, trackId);
const { me } = useAccount({ const { me } = useAccount({
resolve: { root: { playlists: { $each: true } } }, root: {
playlists: [{}],
},
}); });
const playlists = me?.root.playlists ?? []; const playlists = me?.root.playlists ?? [];

View File

@@ -12,7 +12,9 @@ export function PlayerControls({ mediaPlayer }: { mediaPlayer: MediaPlayer }) {
const isPlaying = playState.value === "play"; const isPlaying = playState.value === "play";
const activePlaylist = useAccount({ const activePlaylist = useAccount({
resolve: { root: { activePlaylist: true } }, root: {
activePlaylist: {},
},
}).me?.root.activePlaylist; }).me?.root.activePlaylist;
useMediaEndListener(mediaPlayer.playNextTrack); useMediaEndListener(mediaPlayer.playNextTrack);
@@ -23,7 +25,7 @@ export function PlayerControls({ mediaPlayer }: { mediaPlayer: MediaPlayer }) {
}); });
const activeTrack = useCoState(MusicTrack, mediaPlayer.activeTrackId, { const activeTrack = useCoState(MusicTrack, mediaPlayer.activeTrackId, {
resolve: { waveform: true }, waveform: {},
}); });
if (!activeTrack) return null; if (!activeTrack) return null;

View File

@@ -8,7 +8,9 @@ export function SidePanel() {
const { playlistId } = useParams(); const { playlistId } = useParams();
const navigate = useNavigate(); const navigate = useNavigate();
const { me } = useAccount({ const { me } = useAccount({
resolve: { root: { playlists: { $each: true } } }, root: {
playlists: [{}],
},
}); });
function handleAllTracksClick(evt: React.MouseEvent<HTMLAnchorElement>) { function handleAllTracksClick(evt: React.MouseEvent<HTMLAnchorElement>) {

View File

@@ -8,6 +8,7 @@ export function Waveform(props: { track: MusicTrack; height: number }) {
const waveformData = useCoState( const waveformData = useCoState(
MusicTrackWaveform, MusicTrackWaveform,
track._refs.waveform.id, track._refs.waveform.id,
{},
)?.data; )?.data;
const duration = track.duration; const duration = track.duration;

View File

@@ -2,11 +2,9 @@ import { MusicaAccount } from "../1_schema";
export async function getNextTrack() { export async function getNextTrack() {
const me = await MusicaAccount.getMe().ensureLoaded({ const me = await MusicaAccount.getMe().ensureLoaded({
resolve: {
root: { root: {
activePlaylist: { activePlaylist: {
tracks: true, tracks: [],
},
}, },
}, },
}); });
@@ -23,11 +21,9 @@ export async function getNextTrack() {
export async function getPrevTrack() { export async function getPrevTrack() {
const me = await MusicaAccount.getMe().ensureLoaded({ const me = await MusicaAccount.getMe().ensureLoaded({
resolve: {
root: { root: {
activePlaylist: { activePlaylist: {
tracks: true, tracks: [],
},
}, },
}, },
}); });

View File

@@ -13,7 +13,7 @@ export function useUploadExampleData() {
async function uploadOnboardingData() { async function uploadOnboardingData() {
const me = await MusicaAccount.getMe().ensureLoaded({ const me = await MusicaAccount.getMe().ensureLoaded({
resolve: { root: true }, root: {},
}); });
if (me.root.exampleDataLoaded) return; if (me.root.exampleDataLoaded) return;

View File

@@ -5,11 +5,11 @@ import { Organization } from "./schema.ts";
export function AcceptInvitePage() { export function AcceptInvitePage() {
const navigate = useNavigate(); const navigate = useNavigate();
const { me } = useAccount({ resolve: { root: { organizations: true } } }); const { me } = useAccount({ root: { organizations: [] } });
const onAccept = (organizationId: ID<Organization>) => { const onAccept = (organizationId: ID<Organization>) => {
if (me?.root?.organizations) { if (me?.root?.organizations) {
Organization.load(organizationId).then((organization) => { Organization.load(organizationId, me, []).then((organization) => {
if (organization) { if (organization) {
// avoid duplicates // avoid duplicates
const ids = me.root.organizations.map( const ids = me.root.organizations.map(

View File

@@ -5,7 +5,7 @@ import { Heading } from "./components/Heading.tsx";
export function HomePage() { export function HomePage() {
const { me } = useAccount({ const { me } = useAccount({
resolve: { root: { organizations: true } }, root: { organizations: [{}] },
}); });
if (!me?.root.organizations) return; if (!me?.root.organizations) return;

View File

@@ -3,7 +3,7 @@ import { UserIcon } from "lucide-react";
export function Layout({ children }: { children: React.ReactNode }) { export function Layout({ children }: { children: React.ReactNode }) {
const { me, logOut } = useAccount({ const { me, logOut } = useAccount({
resolve: { root: { draftOrganization: true } }, root: { draftOrganization: {} },
}); });
return ( return (

View File

@@ -13,7 +13,7 @@ export function OrganizationPage() {
.organizationId; .organizationId;
const organization = useCoState(Organization, paramOrganizationId, { const organization = useCoState(Organization, paramOrganizationId, {
resolve: { projects: true }, projects: [],
}); });
if (!organization) return <p>Loading organization...</p>; if (!organization) return <p>Loading organization...</p>;

View File

@@ -8,7 +8,7 @@ import { OrganizationForm } from "./OrganizationForm.tsx";
export function CreateOrganization() { export function CreateOrganization() {
const { me } = useAccount({ const { me } = useAccount({
resolve: { root: { draftOrganization: true, organizations: true } }, root: { draftOrganization: {}, organizations: [] },
}); });
const [errors, setErrors] = useState<string[]>([]); const [errors, setErrors] = useState<string[]>([]);
const navigate = useNavigate(); const navigate = useNavigate();

View File

@@ -7,7 +7,7 @@ import { Organization } from "../schema.ts";
export function OrganizationSelector({ className }: { className?: string }) { export function OrganizationSelector({ className }: { className?: string }) {
const { me } = useAccount({ const { me } = useAccount({
resolve: { root: { organizations: { $each: true } } }, root: { organizations: [{}] },
}); });
const navigate = useNavigate(); const navigate = useNavigate();

View File

@@ -43,11 +43,9 @@ const VaultPage: React.FC = () => {
(item): item is Exclude<typeof item, null> => !!item, (item): item is Exclude<typeof item, null> => !!item,
) || [], ) || [],
); );
const folders = useCoState(FolderList, me.root?._refs.folders?.id, { const folders = useCoState(FolderList, me.root?._refs.folders?.id, [
resolve: { { items: [{}] },
$each: { items: { $each: true } }, ]);
},
});
const [selectedFolder, setSelectedFolder] = useState<Folder | undefined>(); const [selectedFolder, setSelectedFolder] = useState<Folder | undefined>();
const [isNewItemModalOpen, setIsNewItemModalOpen] = useState(false); const [isNewItemModalOpen, setIsNewItemModalOpen] = useState(false);

View File

@@ -60,9 +60,11 @@ export async function addSharedFolder(
me: PasswordManagerAccount, me: PasswordManagerAccount,
) { ) {
const [sharedFolder, account] = await Promise.all([ const [sharedFolder, account] = await Promise.all([
Folder.load(sharedFolderId), Folder.load(sharedFolderId, me, {}),
PasswordManagerAccount.load(me.id, { PasswordManagerAccount.load(me.id, me, {
resolve: { root: { folders: true } }, root: {
folders: [],
},
}), }),
]); ]);

View File

@@ -19,7 +19,6 @@
"@radix-ui/react-toast": "^1.1.4", "@radix-ui/react-toast": "^1.1.4",
"class-variance-authority": "^0.7.0", "class-variance-authority": "^0.7.0",
"clsx": "^2.0.0", "clsx": "^2.0.0",
"jazz-browser-media-images": "workspace:0.11.6",
"jazz-react": "workspace:0.11.6", "jazz-react": "workspace:0.11.6",
"jazz-tools": "workspace:0.11.6", "jazz-tools": "workspace:0.11.6",
"lucide-react": "^0.274.0", "lucide-react": "^0.274.0",

View File

@@ -1,10 +1,8 @@
import { createImage } from "jazz-browser-media-images";
/* eslint-disable react-hooks/exhaustive-deps */
import { ChangeEvent, useCallback, useState } from "react"; import { ChangeEvent, useCallback, useState } from "react";
import { useNavigate } from "react-router"; import { useNavigate } from "react-router";
import { ProgressiveImg } from "jazz-react"; import { ProgressiveImg } from "jazz-react";
import { useAccount, useCoState } from "jazz-react"; import { createImage, useAccount, useCoState } from "jazz-react";
import { CoMap, Group, ID, ImageDefinition, co } from "jazz-tools"; import { CoMap, Group, ID, ImageDefinition, co } from "jazz-tools";
import { PetPost, PetReactions } from "./1_schema"; import { PetPost, PetReactions } from "./1_schema";
import { Button, Input } from "./basicComponents"; import { Button, Input } from "./basicComponents";

View File

@@ -12,7 +12,6 @@
}, },
"dependencies": { "dependencies": {
"hash-slash": "workspace:*", "hash-slash": "workspace:*",
"jazz-browser-media-images": "workspace:*",
"jazz-react": "workspace:*", "jazz-react": "workspace:*",
"jazz-tools": "workspace:*", "jazz-tools": "workspace:*",
"react": "^18.3.1", "react": "^18.3.1",

View File

@@ -14,7 +14,7 @@ const reactionEmojiMap: {
}; };
export function ReactionsScreen(props: { id: ID<Reactions> }) { export function ReactionsScreen(props: { id: ID<Reactions> }) {
const reactions = useCoState(Reactions, props.id); const reactions = useCoState(Reactions, props.id, []);
if (!reactions) return; if (!reactions) return;

View File

@@ -72,9 +72,7 @@ import { Folder, FolderList, ToDoItem, ToDoList } from "../schema";
const { me } = useAccount(); const { me } = useAccount();
const computedFoldersId = computed(() => me.value?.root?.folders?.id); const computedFoldersId = computed(() => me.value?.root?.folders?.id);
const folders = useCoState(FolderList, computedFoldersId, { const folders = useCoState(FolderList, computedFoldersId, [{ items: [{}] }]);
resolve: { $each: { items: true } },
});
const selectedFolder = ref<Folder>(); const selectedFolder = ref<Folder>();
const newFolderName = ref(""); const newFolderName = ref("");

View File

@@ -121,7 +121,7 @@ export default function App() {
function HomeScreen() { function HomeScreen() {
const { me } = useAccount({ const { me } = useAccount({
resolve: { root: { projects: { $each: true } } }, root: { projects: [{}] },
}); });
const navigate = useNavigate(); const navigate = useNavigate();

View File

@@ -4,9 +4,7 @@ import { ID } from "jazz-tools";
import { IssueComponent } from "./Issue.tsx"; import { IssueComponent } from "./Issue.tsx";
import { Issue, Project } from "./schema.ts"; import { Issue, Project } from "./schema.ts";
export function ProjectComponent({ projectID }: { projectID: ID<Project> }) { export function ProjectComponent({ projectID }: { projectID: ID<Project> }) {
const project = useCoState(Project, projectID, { const project = useCoState(Project, projectID, { issues: [{}] });
resolve: { issues: { $each: true } },
});
if (!project) return; if (!project) return;

View File

@@ -49,7 +49,7 @@ function highlightPlugin() {
token.content.includes("// old"), token.content.includes("// old"),
); );
const isBinnedLine = line.some((token) => const isBinnedLine = line.some((token) =>
token.content.includes("// [!code --]"), token.content.includes("// *bin*"),
); );
const isHighlighted = line.some((token) => const isHighlighted = line.some((token) =>
token.content.includes("// *highlight*"), token.content.includes("// *highlight*"),
@@ -70,7 +70,7 @@ function highlightPlugin() {
line line
.map((token) => { .map((token) => {
let color = isHighlighted ? "currentColor" : token.color; let color = isHighlighted ? "currentColor" : token.color;
return `<span style="color: ${color};${isSubduedLine ? "opacity: 0.4;" : ""}">${escape(token.content.replace("// old", "").replace("// [!code --]", "").replace("// *highlight*", ""))}</span>`; return `<span style="color: ${color};${isSubduedLine ? "opacity: 0.4;" : ""}">${escape(token.content.replace("// old", "").replace("// *bin*", "").replace("// *highlight*", ""))}</span>`;
}) })
.join("") + .join("") +
"</span>" "</span>"

View File

@@ -331,7 +331,7 @@ This works because CoValues
<CodeGroup> <CodeGroup>
```ts ```ts
const unsub = issue.subscribe({ resolve: true }, (updatedIssue) => console.log(updatedIssue)); const unsub = issue.subscribe([], (updatedIssue) => console.log(updatedIssue));
``` ```
</CodeGroup> </CodeGroup>
@@ -339,7 +339,7 @@ This works because CoValues
<CodeGroup> <CodeGroup>
```ts ```ts
const unsub = Issue.subscribe(issueID, me, { resolve: true }, (updatedIssue) => { const unsub = Issue.subscribe(issueID, me, [], (updatedIssue) => {
console.log(updatedIssue); console.log(updatedIssue);
}); });
``` ```
@@ -358,7 +358,7 @@ This works because CoValues
function useCoState<V extends CoValue>(Schema: CoValueClass<V>, id?: ID<V>): V | undefined { function useCoState<V extends CoValue>(Schema: CoValueClass<V>, id?: ID<V>): V | undefined {
const [value, setValue] = useState<V>(); const [value, setValue] = useState<V>();
useEffect(() => Schema.subscribe(id, { resolve: true }, setValue), [id]); useEffect(() => Schema.subscribe(id, [], setValue), [id]);
return value; return value;
} }
@@ -454,7 +454,7 @@ function App() { // old
const issue = useCoState(Issue, issueID); // old const issue = useCoState(Issue, issueID); // old
// old // old
const createIssue = () => { // old const createIssue = () => { // old
const group = Group.create(); const group = Group.create({ owner: me });
group.addMember("everyone", "writer"); group.addMember("everyone", "writer");
// old // old
const newIssue = Issue.create( // old const newIssue = Issue.create( // old
@@ -543,7 +543,7 @@ function App() { // old
(window.location.search?.replace("?project=", "") || undefined) as ID<Project> | undefined (window.location.search?.replace("?project=", "") || undefined) as ID<Project> | undefined
); );
// old // old
const issue = useCoState(Issue, issueID); // [!code --] const issue = useCoState(Issue, issueID); // *bin*
// old // old
const createProject = () => { const createProject = () => {
const group = Group.create(); const group = Group.create();
@@ -605,8 +605,6 @@ export function ProjectComponent({ projectID }: { projectID: ID<Project> }) {
<button onClick={createAndAddIssue}>Create Issue</button> <button onClick={createAndAddIssue}>Create Issue</button>
</div> </div>
</div> </div>
) : project === null ? (
<div>Project not found or access denied</div>
) : ( ) : (
<div>Loading project...</div> <div>Loading project...</div>
); );
@@ -622,7 +620,7 @@ Two things to note here:
- We only need to use `useCoState` on the Project, and the nested `ListOfIssues` and each `Issue` will be **automatically loaded and subscribed to when we access them.** - We only need to use `useCoState` on the Project, and the nested `ListOfIssues` and each `Issue` will be **automatically loaded and subscribed to when we access them.**
- However, because either the `Project`, `ListOfIssues`, or each `Issue` might not be loaded yet, we have to check for them being defined. - However, because either the `Project`, `ListOfIssues`, or each `Issue` might not be loaded yet, we have to check for them being defined.
### Precise resolve queries ### Precise loading depths
The load-and-subscribe-on-access is a convenient way to have your rendering drive data loading (including in nested components!) and lets you quickly chuck UIs together without worrying too much about the shape of all data you'll need. The load-and-subscribe-on-access is a convenient way to have your rendering drive data loading (including in nested components!) and lets you quickly chuck UIs together without worrying too much about the shape of all data you'll need.
@@ -637,7 +635,7 @@ import { IssueComponent } from "./Issue.tsx"; // old
import { useCoState } from "jazz-react"; // old import { useCoState } from "jazz-react"; // old
// old // old
export function ProjectComponent({ projectID }: { projectID: ID<Project> }) {// old export function ProjectComponent({ projectID }: { projectID: ID<Project> }) {// old
const project = useCoState(Project, projectID, { resolve: { issues: { $each: true } } }); const project = useCoState(Project, projectID, { issues: [{}] });
const createAndAddIssue = () => {// old const createAndAddIssue = () => {// old
project?.issues.push(Issue.create({ project?.issues.push(Issue.create({
@@ -665,7 +663,7 @@ export function ProjectComponent({ projectID }: { projectID: ID<Project> }) {//
``` ```
</CodeGroup> </CodeGroup>
The resolve query `{ resolve: { issues: { $each: true } } }` means "in `Project`, load `issues` and load each item in `issues` deeply". (Since an `Issue` doesn't have any further references, "deeply" actually means all its properties will be available). The loading-depth spec `{ issues: [{}] }` means "in `Project`, load `issues` and load each item in `issues` shallowly". (Since an `Issue` doesn't have any further references, "shallowly" actually means all its properties will be available).
- Now, we can get rid of a lot of conditional accesses because we know that once `project` is loaded, `project.issues` and each `Issue` in it will be loaded as well. - Now, we can get rid of a lot of conditional accesses because we know that once `project` is loaded, `project.issues` and each `Issue` in it will be loaded as well.
- This also results in only one rerender and visual update when everything is loaded, which is faster (especially for long lists) and gives you more control over the loading UX. - This also results in only one rerender and visual update when everything is loaded, which is faster (especially for long lists) and gives you more control over the loading UX.
@@ -712,7 +710,7 @@ function App() { // old
// old // old
const createProject = () => { // old const createProject = () => { // old
const group = Group.create(); // old const group = Group.create(); // old
group.addMember("everyone", "writer"); // [!code --] group.addMember("everyone", "writer"); // *bin*
// old // old
const newProject = Project.create( // old const newProject = Project.create( // old
{ // old { // old
@@ -749,7 +747,7 @@ import { createInviteLink } from "jazz-react";
// old // old
export function ProjectComponent({ projectID }: { projectID: ID<Project> }) {// old export function ProjectComponent({ projectID }: { projectID: ID<Project> }) {// old
const project = useCoState(Project, projectID, { resolve: { issues: { $each: true } } }); // old const project = useCoState(Project, projectID, { issues: [{}] }); // old
const { me } = useAccount(); const { me } = useAccount();

View File

@@ -286,7 +286,7 @@ To display images, use the `ProgressiveImg` component from `jazz-react-native`.
import { Image } from "react-native"; import { Image } from "react-native";
// Inside your render function: // Inside your render function:
<ProgressiveImg image={someCovalue.image} maxWidth={1024}> <ProgressiveImg image={someCovalue.image} targetWidth={1024}>
{({ src, res, originalSize }) => ( {({ src, res, originalSize }) => (
<Image <Image
source={{ uri: src }} source={{ uri: src }}
@@ -305,7 +305,7 @@ To display images, use the `ProgressiveImg` component from `jazz-react-native`.
The `ProgressiveImg` component: The `ProgressiveImg` component:
- Automatically handles different image formats - Automatically handles different image formats
- Provides progressive loading with placeholder images - Provides progressive loading with placeholder images
- Supports different resolutions based on the `maxWidth` prop - Supports different resolutions based on the `targetWidth` prop
- Works seamlessly with React Native's `Image` component - Works seamlessly with React Native's `Image` component
For a complete implementation example, see the [Chat Example](https://github.com/garden-co/jazz/blob/main/examples/chat-rn-clerk/app/chat/[chatId].tsx). For a complete implementation example, see the [Chat Example](https://github.com/garden-co/jazz/blob/main/examples/chat-rn-clerk/app/chat/[chatId].tsx).

View File

@@ -112,7 +112,7 @@ declare module "jazz-react" {// old
## Resolving CoValues starting at `profile` or `root` ## Resolving CoValues starting at `profile` or `root`
<ContentByFramework framework="react"> <ContentByFramework framework="react">
To use per-user data in your app, you typically use `useAccount` somewhere in a high-level component, specifying which references to resolve using a resolve query (see [Subscribing & deep loading](/docs/using-covalues/subscription-and-loading)). To use per-user data in your app, you typically use `useAccount` somewhere in a high-level component, specifying which references to resolve using a depth-spec (see [Subscribing & deep loading](/docs/using-covalues/subscription-and-loading)).
<CodeGroup> <CodeGroup>
{/* prettier-ignore */} {/* prettier-ignore */}

View File

@@ -29,9 +29,9 @@ Here is what's changed in this release:
{/* prettier-ignore */} {/* prettier-ignore */}
```tsx ```tsx
<JazzProvider <JazzProvider
auth={authMethod} // removed // [!code --] auth={authMethod} // removed // *bin*
peer="wss://cloud.jazz.tools/?key=you@example.com" // moved into sync // [!code --] peer="wss://cloud.jazz.tools/?key=you@example.com" // moved into sync // *bin*
sync={{ peer: "wss://cloud.jazz.tools/?key=you@example.com" }} // [!code ++] sync={{ peer: "wss://cloud.jazz.tools/?key=you@example.com" }} // *add*
> >
<App /> <App />
</JazzProvider> </JazzProvider>

View File

@@ -1,299 +0,0 @@
import { CodeGroup } from '@/components/forMdx'
export const metadata = { title: "Jazz 0.12.0 - Deeply resolved data" };
# Jazz 0.12.0 - Deeply resolved data
Jazz 0.12.0 makes it easier and safer to load nested data. You can now specify exactly which nested data you want to load, and Jazz will check permissions and handle missing data gracefully. This helps catch errors earlier during development and makes your code more reliable.
## What's new?
- New resolve API for a more type-safe deep loading
- A single, consistent load option for all loading methods
- Improved permission checks on deep loading
- Easier type safety with the `Resolved` type helper
## Breaking changes
### New Resolve API
We're introducing a new resolve API for deep loading, more friendly to TypeScript, IDE autocompletion and LLMs.
**Major changes:**
1. Functions and hooks for loading now take the resolve query as an explicit nested `resolve` prop
2. Shallowly loading a collection is now done with `true` instead of `[]` or `{}`
<CodeGroup>
```tsx twoslash
// @noErrors: 2451
import { CoMap, CoList, co, Account } from "jazz-tools";
import { useAccount } from "jazz-react";
class AccountRoot extends CoMap { friends = co.ref(ListOfAccounts); }
class ListOfAccounts extends CoList.Of(co.ref(Account)) {}
class MyAppAccount extends Account { root = co.ref(AccountRoot);}
declare module "jazz-react" { interface Register { Account: MyAppAccount; } }
// ---cut-before---
// Before
// @ts-expect-error
const { me } = useAccount({ root: { friends: [] } }); // [!code --]
// After
const { me } = useAccount({ // [!code ++]
resolve: { root: { friends: true } } // [!code ++]
}); // [!code ++]
```
</CodeGroup>
3. For collections, resolving items deeply is now done with a special `$each` key.
For a `CoList`:
<CodeGroup>
```tsx twoslash
// @noErrors: 2451
import { CoList, co, ID, CoMap } from "jazz-tools";
import { useCoState } from "jazz-react";
// ---cut-before---
class Task extends CoMap { }
class ListOfTasks extends CoList.Of(co.ref(Task)) {}
const id = "co_123" as ID<Task>;
// Before
// @ts-expect-error
const tasks = useCoState(ListOfTasks, id, [{}]); // [!code --]
// After
const tasks = useCoState(ListOfTasks, id, { resolve: { $each: true } }); // [!code ++]
```
</CodeGroup>
For a `CoMap.Record`:
<CodeGroup>
```tsx twoslash
// @noErrors: 2451
import { CoMap, co, Account, ID } from "jazz-tools";
import { useCoState } from "jazz-react";
class MyAppAccount extends Account {}
const id = "co_123" as ID<UsersByUsername>;
// ---cut-before---
class UsersByUsername extends CoMap.Record(co.ref(MyAppAccount)) {}
// Before
// @ts-expect-error
const usersByUsername = useCoState(UsersByUsername, id, [{}]); // [!code --]
// After
const usersByUsername = useCoState(UsersByUsername, id, { // [!code ++]
resolve: { $each: true } // [!code ++]
}); // [!code ++]
```
</CodeGroup>
Nested loading &mdash; note how it's now less terse, but more readable:
<CodeGroup>
```tsx twoslash
// @noErrors: 2451
import { CoList, CoMap, co, Account, ID } from "jazz-tools";
import { useCoState } from "jazz-react";
const id = "co_123" as ID<ListOfTasks>;
// ---cut-before---
class Org extends CoMap {
name = co.string;
}
class Assignee extends CoMap {
name = co.string;
org = co.ref(Org);
}
class ListOfAssignees extends CoList.Of(co.ref(Assignee)) {}
class Task extends CoMap {
content = co.string;
assignees = co.ref(ListOfAssignees);
}
class ListOfTasks extends CoList.Of(co.ref(Task)) {}
// Before
// @ts-expect-error
const tasksWithAssigneesAndTheirOrgs = useCoState(ListOfTasks, id, [{ // [!code --]
assignees: [{ org: {}}]} // [!code --]
]); // [!code --]
// After
const tasksWithAssigneesAndTheirOrgs = useCoState(ListOfTasks, id, { // [!code ++]
resolve: { // [!code ++]
$each: { // [!code ++]
assignees: { // [!code ++]
$each: { org: true } // [!code ++]
} // [!code ++]
} // [!code ++]
} // [!code ++]
}); // [!code ++]
```
</CodeGroup>
It's also a lot more auto-complete friendly:
<CodeGroup>
```tsx twoslash
// @noErrors: 2451 2353 2581
import { CoList, CoMap, co, ID } from "jazz-tools";
import { useCoState } from "jazz-react";
class Org extends CoMap { name = co.string; }
class Assignee extends CoMap { org = co.ref(Org); }
class ListOfAssignees extends CoList.Of(co.ref(Assignee)) {}
class Task extends CoMap { assignees = co.ref(ListOfAssignees); }
class ListOfTasks extends CoList.Of(co.ref(Task)) {}
const id = "co_123" as ID<ListOfTasks>;
// ---cut-before---
const tasksWithAssigneesAndTheirOrgs = useCoState(ListOfTasks, id, {
resolve: {
$each: {
assignees: {
$
// ^|
}
}
}
});
```
</CodeGroup>
### A single, consistent load option
The new API works across all loading methods, and separating out the resolve query means
other options with default values are easier to manage, for example: loading a value as a specific account instead of using the implicit current account:
<CodeGroup>
```ts twoslash
// @noErrors: 2451
import { co, Account, CoMap, CoList, ID } from "jazz-tools";
class Track extends CoMap {}
class ListOfTracks extends CoList.Of(co.ref(Track)) {}
class Playlist extends CoMap { tracks = co.ref(ListOfTracks); }
const id = "co_123" as ID<Playlist>;
const otherAccount = {} as Account;
// ---cut-before---
// Before
// @ts-expect-error
Playlist.load(id, otherAccount, { // [!code --]
tracks: [], // [!code --]
}); // [!code --]
// After
Playlist.load(id, { // [!code ++]
loadAs: otherAccount, // [!code ++]
resolve: { tracks: true } // [!code ++]
}); // [!code ++]
```
</CodeGroup>
### Improved permission checks on deep loading
Now `useCoState` will return `null` when the current user lacks permissions to load requested data.
Previously, `useCoState` would return `undefined` if the current user lacked permissions, making it hard to tell if the value is loading or if it's missing.
Now `undefined` means that the value is definitely loading, and `null` means that the value is temporarily missing.
We also have implemented a more granular permission checking, where if an *optional* CoValue cannot be accessed, `useCoState` will return the data stripped of that CoValue.
**Note:** The state handling around loading and error states will become more detailed and easy-to-handle in future releases, so this is just a small step towards consistency.
<CodeGroup>
{/* prettier-ignore */}
```tsx twoslash
// @noErrors: 2451
import React from "react";
import { CoList, CoMap, co, ID } from "jazz-tools";
import { useCoState } from "jazz-react";
class Track extends CoMap {}
function TrackComponent({ track }: { track: Track }) {return ""}
// ---cut-before---
class ListOfTracks extends CoList.Of(co.optional.ref(Track)) {}
function TrackListComponent({ id }: { id: ID<ListOfTracks> }) {
// Before (ambiguous states)
// @ts-expect-error
const tracks = useCoState(ListOfTracks, id, [{}]); // [!code --]
if (tracks === undefined) return <div>Loading or access denied</div>; // [!code --]
if (tracks === null) return <div>Not found</div>; // [!code --]
// After
const tracks = useCoState(ListOfTracks, id, { resolve: { $each: true } }); // [!code ++]
if (tracks === undefined) return <div>Loading...</div>; // [!code ++]
if (tracks === null) return <div>Not found or access denied</div>; // [!code ++]
// This will only show tracks that we have access to and that are loaded.
return tracks.map(track => track && <TrackComponent track={track} />);
}
```
</CodeGroup>
The same change is applied to the load function, so now it returns `null` instead of `undefined` when the value is missing.
<CodeGroup>
```tsx twoslash
// @noErrors: 2451
import { CoMap, co, ID } from "jazz-tools";
import { useAccount } from "jazz-react";
class MyCoMap extends CoMap {}
const id = "co_123" as ID<MyCoMap>;
// ---cut-before---
// Before
// @ts-expect-error
const map = await MyCoMap.load(id);
if (map === undefined) {
throw new Error("Map not found");
}
// After
const map = await MyCoMap.load(id);
if (map === null) {
throw new Error("Map not found or access denied");
}
```
</CodeGroup>
## New Features
### The `Resolved` type helper
The new `Resolved` type can be used to define what kind of deeply loaded data you expect in your parameters, using the same resolve query syntax as the new loading APIs:
<CodeGroup>
```tsx twoslash
// @noErrors: 2451
import React from "react";
import { Resolved, CoMap, CoList, co } from "jazz-tools";
class Track extends CoMap {}
class ListOfTracks extends CoList.Of(co.ref(Track)) {}
class Playlist extends CoMap { tracks = co.ref(ListOfTracks); }
function TrackComponent({ track }: { track: Track }) {return ""}
// ---cut-before---
type PlaylistResolved = Resolved<Playlist, {
tracks: { $each: true }
}>;
function TrackListComponent({ playlist }: { playlist: PlaylistResolved }) {
// Safe access to resolved tracks
return playlist.tracks.map(track => <TrackComponent track={track} />);
}
```
</CodeGroup>

View File

@@ -25,9 +25,9 @@ So we decided to remove `createJazzRNApp` step and to provide the types through
import { JazzProvider, useDemoAuth, DemoAuthBasicUI } from "jazz-react-native"; import { JazzProvider, useDemoAuth, DemoAuthBasicUI } from "jazz-react-native";
import { MyAppAccount } from "./schema"; import { MyAppAccount } from "./schema";
// Remove these lines // [!code --] // Remove these lines // *bin*
const Jazz = createJazzRNApp({ AccountSchema: MyAppAccount }); // [!code --] const Jazz = createJazzRNApp({ AccountSchema: MyAppAccount }); // *bin*
export const { useAccount, useCoState } = Jazz; // [!code --] export const { useAccount, useCoState } = Jazz; // *bin*
export function JazzAndAuth({ children }: { children: React.ReactNode }) { // old export function JazzAndAuth({ children }: { children: React.ReactNode }) { // old
const [auth, state] = useDemoAuth(); // old const [auth, state] = useDemoAuth(); // old
@@ -66,8 +66,8 @@ This change improves IDE intellisense support and simplifies imports:
{/* prettier-ignore */} {/* prettier-ignore */}
```tsx ```tsx
// Replace local imports with "jazz-react-native" imports // Replace local imports with "jazz-react-native" imports
import { useAccount } from "./main"; // [!code --] import { useAccount } from "./main"; // *bin*
import { useAccount } from "jazz-react-native"; // [!code ++] import { useAccount } from "jazz-react-native"; // *add*
export function Hello() { export function Hello() {
const { me } = useAccount(); const { me } = useAccount();

View File

@@ -24,9 +24,9 @@ So we decided to remove `createJazzReactApp` step and to provide the types throu
import { JazzProvider, usePasskeyAuth, PasskeyAuthBasicUI } from "jazz-react"; import { JazzProvider, usePasskeyAuth, PasskeyAuthBasicUI } from "jazz-react";
import { MyAppAccount } from "./schema"; import { MyAppAccount } from "./schema";
// Remove these lines // [!code --] // Remove these lines // *bin*
const Jazz = createJazzReactApp({ AccountSchema: MyAppAccount }); // [!code --] const Jazz = createJazzReactApp({ AccountSchema: MyAppAccount }); // *bin*
export const { useAccount, useCoState } = Jazz; // [!code --] export const { useAccount, useCoState } = Jazz; // *bin*
export function JazzAndAuth({ children }: { children: React.ReactNode }) { // old export function JazzAndAuth({ children }: { children: React.ReactNode }) { // old
const [passkeyAuth, passKeyState] = usePasskeyAuth({ appName }); // old const [passkeyAuth, passKeyState] = usePasskeyAuth({ appName }); // old
@@ -37,7 +37,7 @@ So we decided to remove `createJazzReactApp` step and to provide the types throu
<JazzProvider <JazzProvider
auth={passkeyAuth} // old auth={passkeyAuth} // old
peer="wss://cloud.jazz.tools/?key=you@example.com" // old peer="wss://cloud.jazz.tools/?key=you@example.com" // old
AccountSchema={MyAppAccount} {/* The custom Account schema is passed here */} // [!code ++] AccountSchema={MyAppAccount} {/* The custom Account schema is passed here */} // *add*
> >
{children} // old {children} // old
</JazzProvider> </JazzProvider>
@@ -47,11 +47,11 @@ So we decided to remove `createJazzReactApp` step and to provide the types throu
} }
// Register the Account schema so `useAccount` returns our custom `MyAppAccount` // Register the Account schema so `useAccount` returns our custom `MyAppAccount`
declare module "jazz-react" { // [!code ++] declare module "jazz-react" { // *add*
interface Register { // [!code ++] interface Register { // *add*
Account: MyAppAccount; // [!code ++] Account: MyAppAccount; // *add*
} // [!code ++] } // *add*
} // [!code ++] } // *add*
``` ```
</CodeGroup> </CodeGroup>
@@ -65,8 +65,8 @@ This change improves IDE intellisense support and simplifies imports:
{/* prettier-ignore */} {/* prettier-ignore */}
```tsx ```tsx
// Replace local imports with "jazz-react" imports // Replace local imports with "jazz-react" imports
import { useAccount } from "./main"; // [!code --] import { useAccount } from "./main"; // *bin*
import { useAccount } from "jazz-react"; // [!code ++] import { useAccount } from "jazz-react"; // *add*
export function Hello() { export function Hello() {
const { me } = useAccount(); const { me } = useAccount();

View File

@@ -32,7 +32,7 @@ So we decided to remove `createJazzApp` step and to provide the types through na
</script> </script>
<script lang="ts"> <script lang="ts">
import { Provider } from '$lib/jazz'; // [!code --] import { Provider } from '$lib/jazz'; // *bin*
import { JazzProvider } from 'jazz-svelte'; import { JazzProvider } from 'jazz-svelte';
// Example configuration for authentication and peer connection // Example configuration for authentication and peer connection
@@ -62,8 +62,8 @@ So we decided to remove `createJazzApp` step and to provide the types through na
```svelte ```svelte
<script lang="ts"> <script lang="ts">
import { useAccount } from '$lib/jazz'; // [!code --] import { useAccount } from '$lib/jazz'; // *bin*
import { useAccount } from 'jazz-svelte'; // [!code ++] import { useAccount } from 'jazz-svelte'; // *add*
const { me } = useAccount(); const { me } = useAccount();
</script> </script>

View File

@@ -28,10 +28,10 @@ import App from "./App.vue"; // old
import router from "./router"; // old import router from "./router"; // old
import { ToDoAccount } from "./schema"; // old import { ToDoAccount } from "./schema"; // old
// Remove these lines // [!code --] // Remove these lines // *bin*
const Jazz = createJazzVueApp<ToDoAccount>({ AccountSchema: ToDoAccount }); // [!code --] const Jazz = createJazzVueApp<ToDoAccount>({ AccountSchema: ToDoAccount }); // *bin*
export const { useAccount, useCoState } = Jazz; // [!code --] export const { useAccount, useCoState } = Jazz; // *bin*
const { JazzProvider } = Jazz; // [!code --] const { JazzProvider } = Jazz; // *bin*
const RootComponent = defineComponent({ // old const RootComponent = defineComponent({ // old
name: "RootComponent", // old name: "RootComponent", // old
@@ -86,8 +86,8 @@ This change improves IDE intellisense support and simplifies imports:
<script setup lang="ts"> <script setup lang="ts">
// Replace local imports with "jazz-vue" imports // Replace local imports with "jazz-vue" imports
import { useAccount } from "./main"; // [!code --] import { useAccount } from "./main"; // *bin*
import { useAccount } from "jazz-vue"; // [!code ++] import { useAccount } from "jazz-vue"; // *add*
const { me, logOut } = useAccount(); const { me, logOut } = useAccount();
</script> </script>

View File

@@ -152,8 +152,8 @@ if (highestRes) {
} }
// Or constrain by maximum width // Or constrain by maximum width
const maxWidth = window.innerWidth; const targetWidth = window.innerWidth;
const appropriateRes = image.highestResAvailable({ maxWidth }); const appropriateRes = image.highestResAvailable({ targetWidth });
``` ```
</CodeGroup> </CodeGroup>
@@ -188,7 +188,7 @@ if (image.placeholderDataURL) {
// Then load the best resolution for the current display // Then load the best resolution for the current display
const screenWidth = window.innerWidth; const screenWidth = window.innerWidth;
const bestRes = image.highestResAvailable({ maxWidth: screenWidth }); const bestRes = image.highestResAvailable({ targetWidth: screenWidth });
if (bestRes) { if (bestRes) {
const blob = bestRes.stream.toBlob(); const blob = bestRes.stream.toBlob();

View File

@@ -91,7 +91,7 @@ function GalleryView({ image }) {
return ( return (
<ProgressiveImg <ProgressiveImg
image={image} // The image definition to load image={image} // The image definition to load
maxWidth={800} // Limit to resolutions up to 800px wide targetWidth={800} // Looks for the best available resolution for a 800px image
> >
{({ src }) => ( {({ src }) => (
<Image <Image
@@ -137,7 +137,7 @@ function CustomImageComponent({ image }) {
originalSize // The original size of the image originalSize // The original size of the image
} = useProgressiveImg({ } = useProgressiveImg({
image: image, // The image definition to load image: image, // The image definition to load
maxWidth: 800 // Limit to resolutions up to 800px wide targetWidth: 800 // Limit to resolutions up to 800px wide
}); });
// When image is not available yet // When image is not available yet

View File

@@ -80,7 +80,7 @@ function GalleryView({ image }) {
<div className="image-container"> <div className="image-container">
<ProgressiveImg <ProgressiveImg
image={image} // The image definition to load image={image} // The image definition to load
maxWidth={800} // Limit to resolutions up to 800px wide targetWidth={800} // Looks for the best available resolution for a 800px image
> >
{({ src }) => ( {({ src }) => (
<img <img
@@ -118,7 +118,7 @@ function CustomImageComponent({ image }) {
originalSize // The original size of the image originalSize // The original size of the image
} = useProgressiveImg({ } = useProgressiveImg({
image: image, // The image definition to load image: image, // The image definition to load
maxWidth: 800 // Limit to resolutions up to 800px wide targetWidth: 800 // Limit to resolutions up to 800px wide
}); });
// When image is not available yet // When image is not available yet

View File

@@ -1,8 +1,8 @@
import { CodeGroup } from "@/components/forMdx"; import { CodeGroup } from "@/components/forMdx";
export const metadata = { title: "History & time-travel" }; export const metadata = { title: "Metadata & time-travel" };
# History & time-travel # Metadata & time-travel
One of Jazz's most powerful features is that every CoValue automatically tracks its complete edit history. This means you can see who changed what and when, examine the state of your data at any point in time, and build features like audit logs, activity feeds, and undo/redo functionality. This page explores how to access and work with the rich metadata that comes with every CoValue. One of Jazz's most powerful features is that every CoValue automatically tracks its complete edit history. This means you can see who changed what and when, examine the state of your data at any point in time, and build features like audit logs, activity feeds, and undo/redo functionality. This page explores how to access and work with the rich metadata that comes with every CoValue.

View File

@@ -0,0 +1,272 @@
import { CodeGroup, ComingSoon, ContentByFramework } from "@/components/forMdx";
export const metadata = { title: "Reading from CoValues" };
# Reading from CoValues
Jazz lets you access your collaborative data with familiar JavaScript patterns while providing TypeScript type safety. Once you have a CoValue, you can read its values, traverse references, and iterate through collections using the same syntax you'd use with regular objects and arrays. This page covers how to read from different types of CoValues and handle loading states effectively.
<CodeGroup>
```ts
class Project extends CoMap {
name = co.string;
tasks = co.ref(ListOfTasks);
lead = co.optional.ref(TeamMember);
status = co.literal("planning", "active", "completed");
}
// Reading basic fields
console.log(project.name); // "Spring Garden Planning"
console.log(project.status); // "active"
// Reading from lists
for (const task of project.tasks) {
console.log(task.title); // "Plant tomato seedlings"
}
// Checking if an optional field exists
if (project.lead) {
console.log(project.lead.name); // "Maria Chen"
}
```
</CodeGroup>
## Different Types of CoValues
Jazz provides several CoValue types to represent different kinds of data. Each type has its own access patterns, but they all maintain the familiar JavaScript syntax you already know.
### CoMaps
`CoMap`s work like JavaScript objects, providing named properties you can access with dot notation. These are the most common CoValue type and form the foundation of most Jazz data models:
<CodeGroup>
```ts
class TeamMember extends CoMap {
name = co.string;
role = co.string;
active = co.boolean;
}
console.log(member.name); // "Maria Chen"
console.log(member.role); // "Garden Coordinator"
console.log(member.active); // true
```
</CodeGroup>
### CoLists
`CoList`s work like JavaScript arrays, supporting indexed access, iteration methods, and length properties. They're perfect for ordered collections of items where the order matters:
<CodeGroup>
```ts
class ListOfTasks extends CoList.Of(co.ref(Task)) {}
// Access items by index
console.log(tasks[0].title); // "Plant tomato seedlings"
// Use array methods
tasks.forEach(task => {
console.log(task.title); // "Plant tomato seedlings"
});
// Get list length
console.log(tasks.length); // 3
```
</CodeGroup>
### CoFeeds
`CoFeed`s provide a specialized way to track data from different sessions (tabs, devices, app instances). They're ideal for activity logs, presence indicators, or other session-specific streams of information. Each account can have multiple sessions, and each session maintains its own append-only log.
## Type Safety with CoValues
CoValues are fully typed in TypeScript, giving you the same autocomplete and error checking you'd expect from regular objects. This type safety helps catch errors at compile time rather than runtime, making your application more robust. Here's how the type system works with CoValues:
<CodeGroup>
```ts
class Project extends CoMap {
name = co.string;
memberCount = co.number;
priority = co.literal("low", "medium", "high");
lead = co.optional.ref(TeamMember);
tasks = co.ref(ListOfTasks);
}
// TypeScript knows exactly what fields exist
const project = await Project.load(gardenProjectId);
project.name = "Community Garden"; // ✓ string
project.memberCount = "few"; // ✗ Type error: expected number
project.priority = "urgent"; // ✗ Type error: must be low/medium/high
// Optional fields are handled safely
if (project.lead) {
console.log(project.lead.name); // Type safe
}
// Lists with specific item types
project.tasks.forEach(task => {
// TypeScript knows each task's structure
console.log(`${task.title}: ${task.status}`); // "Plant herbs: in-progress"
});
```
</CodeGroup>
## Loading States
When you load a CoValue, it might not be immediately available due to network latency or data size. Jazz provides patterns to handle these loading states gracefully, and TypeScript helps ensure you check for availability before accessing properties:
<CodeGroup>
```ts
const project = await Project.load(gardenProjectId);
if (!project) {
return "Data still loading";
}
```
</CodeGroup>
<ContentByFramework framework="react">
And in React, `useCoState` provides a similar pattern to allow you to wait for a CoValue to be loaded before accessing it:
<CodeGroup>
```tsx
// Type shows this might be `undefined` while loading
const project = useCoState(Project, gardenProjectId, {
tasks: [{}]
});
if (!project) {
return <div>Loading project data...</div>;
}
// TypeScript now knows project exists and has tasks loaded
return <div>{project.tasks.length}</div>;
```
</CodeGroup>
</ContentByFramework>
### Accessing Nested CoValues
Nested CoValues need special handling for loading and access. Since each reference might need to be loaded separately, you need patterns to manage these dependencies and handle loading states appropriately throughout your object graph.
<CodeGroup>
```ts
class Project extends CoMap {
name = co.string;
tasks = co.ref(ListOfTasks);
resources = co.optional.ref(ResourceList);
}
class Task extends CoMap {
title = co.string;
status = co.literal("todo", "in-progress", "completed");
subtasks = co.ref(ListOfSubtasks);
}
```
</CodeGroup>
### Loading
Loading nested data efficiently is important for performance. Jazz provides depth specifications to control exactly how much of your object graph is loaded, from shallow loading of just the top-level object to deep loading of complex nested structures:
<CodeGroup>
```ts
// Basic load - tasks won't be loaded yet
const project = await Project.load(gardenProjectId);
// Load with nested data
const projectWithTasks = await Project.load(gardenProjectId, { tasks: {} });
// Deep load pattern
const fullyLoaded = await Project.load(gardenProjectId, {
tasks: {
subtasks: {}
}
});
```
</CodeGroup>
More details on loading and subscribing to CoValues can be found in [Subscribing](/docs/using-covalues/subscribing-and-deep-loading).
### Handling Loading States
Unloaded references return `undefined`. This means you need to check for undefined values before trying to access properties of nested CoValues.
For general JavaScript/TypeScript usage, here's a pattern that works across any context:
<CodeGroup>
```ts
// Generic pattern for handling nested data
function processTaskData(project) {
// Check if project and its tasks are loaded
if (!project || !project.tasks) {
return "Data still loading";
}
// Safe to process tasks
const completedTasks = project.tasks.filter(task =>
task && task.status === "completed"
);
// Check for subtasks before accessing them
const subtaskCount = completedTasks.reduce((count, task) => {
if (!(task && task.subtasks)) return count
return count + task.subtasks.length;
}, 0);
return {
completedCount: completedTasks.length,
subtaskCount: subtaskCount
};
}
```
</CodeGroup>
<ContentByFramework framework="react">
Handle these loading states in your components:
<CodeGroup>
```tsx
// React pattern for handling nested data
function TaskList({ project }: { project: Project }) {
if (!project.tasks) {
return <div>Loading tasks...</div>;
}
return (
<div>
{project.tasks.map(task => {
// Handle potentially missing nested data
if (!task.subtasks) {
return <div key={task.id}>Loading subtasks...</div>;
}
return (
<div key={task.id}>
{task.title}: {task.subtasks.length} subtasks
</div>
);
})}
</div>
);
}
```
</CodeGroup>
</ContentByFramework>
Note: We're working on making these patterns more explicit and robust. We'll provide clearer loading states and better error handling patterns. For now, be defensive with your checks for `undefined`.
<CodeGroup>
```ts
// Current safest pattern for deep access
function getSubtasks(project: Project, taskTitle: string) {
const task = project.tasks?.find(t => t.title === taskTitle);
const subtasks = task?.subtasks;
if (!subtasks) {
return null; // Could mean loading or error
}
return subtasks.map(st => st.title);
}
```
</CodeGroup>
Stay tuned for updates to this API - we're working on making these patterns more robust and explicit.

View File

@@ -4,29 +4,14 @@ export const metadata = { title: "Subscriptions & Deep Loading" };
# Subscriptions & Deep Loading # Subscriptions & Deep Loading
Jazz's Collaborative Values (such as [CoMaps](/docs/using-covalues/comaps) or [CoLists](/docs/using-covalues/colists)) work like reactive state. By subscribing to them, you can react to both local and remote updates. This is the main way to consume data in your application. When working with collaborative applications, you need to know when data changes and ensure you have all the necessary related data. Jazz provides powerful subscription and deep loading capabilities that make it easy to keep your UI in sync with the underlying data and efficiently load complex object graphs.
Subscriptions also take care of loading CoValues that are not yet loaded locally and can do so *deeply* &mdash; by resolving nested CoValues. To make use of this, we'll show you how to specify the depth of data you need with resolve queries. ## Understanding Subscriptions
With each update you can also handle loading states and inaccessible CoValues. Subscriptions in Jazz allow you to react to changes in CoValues. When a CoValue changes, all subscribers are notified with the updated value. This is essential for building reactive UIs that stay in sync with collaborative data.
## Manual subscriptions
You can subscribe to a CoValue from anywhere in your code (if you have its ID) by using `CoValue.subscribe()`.
<ContentByFramework framework="vanilla">
If you're using React in your project, check out our [React hooks](/docs/react/using-covalues/subscription-and-loading#subscription-hooks) which provide a more streamlined experience with automatic subscription management.
</ContentByFramework>
<ContentByFramework framework={["react", "react-native"]}>
**Note:** Unless you're using vanilla JavaScript, this is only used outside of React components - for example in server-side code or in tests. See the section below for convenient subscription *hooks* that you typically use in React.
</ContentByFramework>
<CodeGroup> <CodeGroup>
```ts twoslash ```ts
import { ID, CoMap, co } from "jazz-tools";
const taskId = "co_123" as ID<Task>;
// ---cut-before---
class Task extends CoMap { class Task extends CoMap {
title = co.string; title = co.string;
description = co.string; description = co.string;
@@ -37,82 +22,144 @@ class Task extends CoMap {
// ... // ...
// Subscribe to a Task by ID // Subscribe to a Task by ID
const unsubscribe = Task.subscribe(taskId, (updatedTask) => { const unsubscribe = Task.subscribe(taskId, { /* loading depth */ }, (updatedTask) => {
console.log("Task updated:", updatedTask.title); console.log("Task updated:", updatedTask.title);
console.log("New status:", updatedTask.status); console.log("New status:", updatedTask.status);
}); });
// Clean up when you're done // Later, when you're done:
unsubscribe(); unsubscribe();
``` ```
</CodeGroup> </CodeGroup>
If you already have a CoValue instance, you can subscribe to it by calling its `subscribe` method. ### Static vs. Instance Subscriptions
There are two main ways to subscribe to CoValues:
1. **Static Subscription** - When you have an ID but don't have the CoValue loaded yet:
<CodeGroup> <CodeGroup>
```ts twoslash ```ts
import { ID, CoMap, co } from "jazz-tools"; // Subscribe by ID (static method)
const unsubscribe = Task.subscribe(taskId, { /* loading depth */ }, (task) => {
if (task) {
console.log("Task loaded/updated:", task.title);
}
});
```
</CodeGroup>
class Task extends CoMap { 2. **Instance Subscription** - When you already have a CoValue instance:
title = co.string;
description = co.string; <CodeGroup>
status = co.literal("todo", "in-progress", "completed"); ```ts
assignedTo = co.optional.string; // Subscribe to an instance (instance method)
}
const otherProps = {} as any;
// ---cut-before---
const task = Task.create({ const task = Task.create({
status: "todo",
title: "Cut the grass", title: "Cut the grass",
...otherProps
}); });
if (task) {
const unsubscribe = task.subscribe((updatedTask) => { const unsubscribe = task.subscribe({ /* loading depth */ }, (updatedTask) => {
console.log("Task updated:", updatedTask.title); console.log("Task updated:", updatedTask.title);
}); });
}
// Clean up when you're done
unsubscribe();
``` ```
</CodeGroup> </CodeGroup>
<ContentByFramework framework={["react", "react-native"]}> ## Deep Loading
## Subscription hooks
### `useCoState` When working with related CoValues (like tasks in a project), you often need to load not just the top-level object but also its nested references. Jazz provides a flexible mechanism for specifying exactly how much of the object graph to load.
Jazz provides a `useCoState` hook that provides a convenient way to subscribe to CoValues and handle loading states: ### Loading Depth Specifications
Loading depth specifications let you declare exactly which references to load and how deep to go:
<CodeGroup> <CodeGroup>
```tsx twoslash ```ts
import React from "react";
import { ID, CoMap, co, CoList } from "jazz-tools";
class Task extends CoMap {
title = co.string;
status = co.literal("todo", "in-progress", "completed");
}
class Project extends CoMap { class Project extends CoMap {
name = co.string; name = co.string;
tasks = co.ref(ListOfTasks); tasks = co.ref(ListOfTasks);
owner = co.ref(TeamMember);
} }
class ListOfTasks extends CoList.Of(co.ref(Task)) {}
// ---cut-before--- class Task extends CoMap {
import { useCoState } from "jazz-react"; title = co.string;
subtasks = co.ref(ListOfSubtasks);
assignee = co.optional.ref(TeamMember);
}
// Load just the project, not its tasks
const project = await Project.load(projectId, {});
// Load the project and its tasks (but not subtasks)
const projectWithTasks = await Project.load(projectId, {
tasks: {}
});
// Load the project, its tasks, and their subtasks
const projectDeep = await Project.load(projectId, {
tasks: {
subtasks: {}
}
});
// Load the project, its tasks, and task assignees
const projectWithAssignees = await Project.load(projectId, {
tasks: {
assignee: {}
}
});
// Complex loading pattern: load project, tasks with their subtasks, and the project owner
const fullyLoaded = await Project.load(projectId, {
tasks: {
subtasks: {}
},
owner: {}
});
```
</CodeGroup>
The depth specification object mirrors the structure of your data model, making it intuitive to express which parts of the graph you want to load.
### Array Notation for Lists
For lists, you can use array notation to specify how to load the items:
<CodeGroup>
```ts
// Load project with all tasks but load each task shallowly
const project = await Project.load(projectId, {
tasks: [{}]
});
// Load project with tasks and load subtasks for each task
const project = await Project.load(projectId, {
tasks: [{
subtasks: [{}]
}]
});
```
</CodeGroup>
## Framework Integration
<ContentByFramework framework="react">
### React Integration with useCoState
In React applications, the `useCoState` hook provides a convenient way to subscribe to CoValues and handle loading states:
<CodeGroup>
```tsx
function GardenPlanner({ projectId }: { projectId: ID<Project> }) { function GardenPlanner({ projectId }: { projectId: ID<Project> }) {
// Subscribe to a project and its tasks // Subscribe to a project and its tasks
const project = useCoState(Project, projectId, { const project = useCoState(Project, projectId, {
resolve: { tasks: [{}]
tasks: { $each: true },
},
}); });
// Handle loading state
if (!project) { if (!project) {
return project === null return <div>Loading garden project...</div>;
? "Project not found or not accessible"
: "Loading project ...";
} }
return ( return (
@@ -126,7 +173,7 @@ function GardenPlanner({ projectId }: { projectId: ID<Project> }) {
function TaskList({ tasks }: { tasks: Task[] }) { function TaskList({ tasks }: { tasks: Task[] }) {
return ( return (
<ul> <ul>
{tasks.map((task) => ( {tasks.map(task => (
<li key={task.id}> <li key={task.id}>
<span>{task.title}</span> <span>{task.title}</span>
<span>{task.status}</span> <span>{task.status}</span>
@@ -139,510 +186,90 @@ function TaskList({ tasks }: { tasks: Task[] }) {
</CodeGroup> </CodeGroup>
The `useCoState` hook handles subscribing when the component mounts and unsubscribing when it unmounts, making it easy to keep your UI in sync with the underlying data. The `useCoState` hook handles subscribing when the component mounts and unsubscribing when it unmounts, making it easy to keep your UI in sync with the underlying data.
</ContentByFramework>
### `useAccount` <ContentByFramework framework="vue">
### Vue Integration
`useAccount` is used to access the current user's account. In Vue applications, you can use the `useCoState` composable to subscribe to CoValues:
You can use this at the top-level of your app to subscribe to the current user's [account profile and root](../schemas/accounts-and-migrations#covalues-as-a-graph-of-data-rooted-in-accounts).
Like `useCoState`, you can specify a resolve query to also subscribe to CoValues referenced in the account profile or root.
<CodeGroup> <CodeGroup>
```tsx twoslash ```vue
import React from "react"; <script setup>
import { ID, CoMap, co, CoList, Account } from "jazz-tools"; import { useCoState } from 'jazz-vue';
class Task extends CoMap {
title = co.string;
}
class ListOfTasks extends CoList.Of(co.ref(Task)) {}
class Project extends CoMap {
name = co.string;
tasks = co.ref(ListOfTasks);
}
class ListOfProjects extends CoList.Of(co.ref(Project)) {}
class AccountRoot extends CoMap { const props = defineProps({
myProjects = co.ref(ListOfProjects); projectId: String
} });
class MyAppAccount extends Account {
root = co.ref(AccountRoot);
}
declare module "jazz-react" { interface Register { Account: MyAppAccount; } }
// ---cut-before---
import { useAccount } from "jazz-react";
function ProjectList() { // Subscribe to a project and its tasks
const { me } = useAccount({ const project = useCoState(Project, props.projectId, {
resolve: { tasks: [{}]
profile: true, });
root: { </script>
myProjects: {
$each: {
tasks: true
}
}
},
},
});
if (!me) { <template>
return <div>Loading...</div>; <div v-if="project">
} <h1>{{ project.name }}</h1>
return <div>
<h1>{me.profile.name}'s projects</h1>
<ul> <ul>
{me.root.myProjects.map(project => ( <li v-for="task in project.tasks" :key="task.id">
<li key={project.id}> {{ task.title }} - {{ task.status }}
{project.name} ({project.tasks.length} tasks)
</li> </li>
))}
</ul> </ul>
</div> </div>
} <div v-else>
Loading garden project...
</div>
</template>
``` ```
</CodeGroup> </CodeGroup>
</ContentByFramework> </ContentByFramework>
## Loading States and Permission Checking <ContentByFramework framework="svelte">
### Svelte Integration
When subscribing to or loading a CoValue, you need to handle three possible states: In Svelte applications, you can use the `useCoState` function to subscribe to CoValues:
- `undefined`: The initial loading state, indicating the value is being fetched
- `null`: The CoValue was not found or is not accessible (e.g., due to permissions)
- `Value`: The successfully loaded CoValue instance
This allows you to handle loading, error, and success states in your application:
<CodeGroup> <CodeGroup>
```ts twoslash ```svelte
import { ID, CoMap, co } from "jazz-tools"; <script>
class Task extends CoMap { import { useCoState } from 'jazz-svelte';
title = co.string;
}
const taskId = "co_123" as ID<Task>; export let projectId;
// ---cut-before---
Task.subscribe(taskId, (task) => {
if (task === undefined) {
console.log("Task is loading...");
} else if (task === null) {
console.log("Task not found or not accessible");
} else {
console.log("Task loaded:", task.title);
}
});
```
</CodeGroup>
## Deep Loading // Subscribe to a project and its tasks
const project = useCoState(Project, projectId, {
tasks: [{}]
});
</script>
When working with related CoValues (like tasks in a project), you often need to load not just the top-level object but also its nested references. This is especially important when working with [CoMaps](/docs/using-covalues/comaps) that contain references to other CoValues or with [CoLists](/docs/using-covalues/colists) that contain multiple items. Jazz provides a flexible mechanism for specifying exactly how much of the object graph to load. {#if $project}
<h1>{$project.name}</h1>
### Resolve queries
Resolve queries let you declare exactly which references to load and how deep to go using the `resolve` property:
<CodeGroup>
```ts twoslash
import { ID, CoMap, co, CoList } from "jazz-tools";
const projectId = "co_123" as ID<Project>;
// ---cut-before---
class Project extends CoMap {
name = co.string;
tasks = co.ref(ListOfTasks);
owner = co.ref(TeamMember);
}
class Task extends CoMap {
title = co.string;
subtasks = co.ref(ListOfTasks);
assignee = co.optional.ref(TeamMember);
}
class TeamMember extends CoMap {
name = co.string;
}
class ListOfTasks extends CoList.Of(co.ref(Task)) {}
// Load just the project, not its references
const project = await Project.load(projectId);
if (!project) { throw new Error("Project not found or not accessible"); }
// string - primitive fields are always loaded
project.name;
// undefined | null | ListOfTasks - non-requested references might not be loaded, or inaccessible
project.tasks;
// Load the project and shallowly load its list of tasks
const projectWithTasksShallow = await Project.load(projectId, {
resolve: {
tasks: true
}
});
if (!projectWithTasksShallow) { throw new Error("Project or required references not found or not accessible"); }
// ListOfTasks - shallowly loaded
projectWithTasksShallow.tasks;
// number - length of the list
projectWithTasksShallow.tasks.length;
// undefined | null | Task - items might not be loaded, or inaccessible
projectWithTasksShallow.tasks[0];
// Load the project and its tasks
const projectWithTasks = await Project.load(projectId, {
resolve: {
tasks: {
$each: true
}
}
});
if (!projectWithTasks) { throw new Error("Project or required references not found or not accessible"); }
// ListOfTasks - fully loaded
projectWithTasks.tasks;
// Task - fully loaded
projectWithTasks.tasks[0];
// string - primitive fields are always loaded
projectWithTasks.tasks[0].title;
// undefined | null | ListOfTasks - subtasks might not be loaded, or inaccessible
projectWithTasks.tasks[0].subtasks;
// Load the project, its tasks, and their subtasks
const projectDeep = await Project.load(projectId, {
resolve: {
tasks: {
$each: {
subtasks: {
$each: true
},
assignee: true
}
}
}
});
if (!projectDeep) { throw new Error("Project or required references not found or not accessible"); }
// string - primitive fields are always loaded
projectDeep.tasks[0].subtasks[0].title;
// undefined | null | TeamMember - since assignee is optional:
// TeamMember - set and definitely loaded
// null - set but unavailable/inaccessible
// undefined - not set, or loading (in case of subscription)
projectDeep.tasks[0].assignee;
```
</CodeGroup>
The resolve query defines which parts of the graph you want to load, making it intuitive to express complex loading patterns.
### Loading states and permissions
When loading data with references, the load operation will fail if one of the references is unavailable or if the user doesn't have read access to it. Let's explore what happens in various scenarios:
#### Resolved References
When a user tries to load a reference they don't have access to:
<CodeGroup>
```typescript twoslash
import { ID, CoMap, co, CoList } from "jazz-tools";
class Project extends CoMap {
name = co.string;
tasks = co.ref(ListOfTasks);
owner = co.ref(TeamMember);
}
class Task extends CoMap {
title = co.string;
subtasks = co.ref(ListOfTasks);
assignee = co.optional.ref(TeamMember);
}
class TeamMember extends CoMap {
name = co.string;
}
class ListOfTasks extends CoList.Of(co.ref(Task)) {}
const taskId = "co_123" as ID<Task>;
// ---cut-before---
// If assignee is not accessible to the user:
const task = await Task.load(taskId, {
resolve: { assignee: true }
});
task // => null
```
</CodeGroup>
The load operation will fail and return `null` if any requested reference is inaccessible. This maintains data consistency by ensuring all requested references are available before returning the object.
The behavior is the same for optional and required references.
#### List References
When a list contains references to items the user can't access:
<CodeGroup>
```typescript twoslash
import { ID, CoMap, co, CoList } from "jazz-tools";
class Project extends CoMap {
name = co.string;
tasks = co.ref(ListOfTasks);
owner = co.ref(TeamMember);
}
class Task extends CoMap {
title = co.string;
subtasks = co.ref(ListOfTasks);
assignee = co.optional.ref(TeamMember);
}
class TeamMember extends CoMap {
name = co.string;
}
class ListOfTasks extends CoList.Of(co.ref(Task)) {}
const projectId = "co_123" as ID<Project>;
// ---cut-before---
// If any item in the list is not accessible:
const project = await Project.load(projectId, {
resolve: { tasks: { $each: true } }
});
project // => null
```
</CodeGroup>
If any item in a list is inaccessible to the user, the entire load operation will fail and return `null`. This is because lists expect all their items to be accessible - a partially loaded list could lead to data inconsistencies.
#### Reading a non-resolved inaccessible reference
When trying to load an object with an inaccessible reference without directly resolving it:
<CodeGroup>
```typescript twoslash
import { ID, CoMap, co, CoList } from "jazz-tools";
class Project extends CoMap {
name = co.string;
tasks = co.ref(ListOfTasks);
owner = co.ref(TeamMember);
}
class Task extends CoMap {
title = co.string;
subtasks = co.ref(ListOfTasks);
assignee = co.optional.ref(TeamMember);
}
class TeamMember extends CoMap {
name = co.string;
}
class ListOfTasks extends CoList.Of(co.ref(Task)) {}
const projectId = "co_123" as ID<Project>;
// ---cut-before---
const project = await Project.load(projectId, {
resolve: true
});
project // => Project
// The user doesn't have access to the owner
project?.owner // => always null
```
</CodeGroup>
The load operation will succeed and return the object, but the inaccessible reference will always be `null`.
## Type Safety with Resolved Type
Jazz provides the `Resolved` type to help you define and enforce the structure of deeply loaded data in your application. This makes it easier to ensure that components receive the data they expect with proper TypeScript validation.
The `Resolved` type is especially useful when passing data between components, as it guarantees that all necessary nested data has been loaded:
<ContentByFramework framework="react">
<CodeGroup>
```tsx twoslash
import React from "react";
import { ID, CoMap, co, CoList, Resolved } from "jazz-tools";
class Project extends CoMap {
name = co.string;
tasks = co.ref(ListOfTasks);
owner = co.ref(TeamMember);
}
class Task extends CoMap {
title = co.string;
subtasks = co.ref(ListOfTasks);
assignee = co.optional.ref(TeamMember);
}
class TeamMember extends CoMap {
name = co.string;
}
class ListOfTasks extends CoList.Of(co.ref(Task)) {}
// ---cut-before---
// Define a type that includes resolved nested data
type ProjectWithTasks = Resolved<Project, {
tasks: { $each: true }
}>;
// Component that expects a fully resolved project
function TaskList({ project }: { project: ProjectWithTasks }) {
// TypeScript knows tasks are loaded, so this is type-safe
return (
<ul> <ul>
{project.tasks.map(task => ( {#each $project.tasks as task (task.id)}
<li key={task.id}>{task.title}</li> <li>{task.title} - {task.status}</li>
))} {/each}
</ul> </ul>
); {:else}
} <div>Loading garden project...</div>
{/if}
// For more complex resolutions
type FullyLoadedProject = Resolved<Project, {
tasks: {
$each: {
subtasks: true,
assignee: true
}
},
owner: true
}>;
// Function that requires deeply resolved data
function processProject(project: FullyLoadedProject) {
// Safe access to all resolved properties
console.log(`Project ${project.name} owned by ${project.owner.name}`);
project.tasks.forEach(task => {
console.log(`Task: ${task.title}, Assigned to: ${task.assignee?.name}`);
console.log(`Subtasks: ${task.subtasks.length}`);
});
}
``` ```
</CodeGroup> </CodeGroup>
</ContentByFramework> </ContentByFramework>
<ContentByFramework framework="vanilla">
<CodeGroup>
```ts twoslash
import { ID, CoMap, co, CoList, Resolved } from "jazz-tools";
class Project extends CoMap {
name = co.string;
tasks = co.ref(ListOfTasks);
owner = co.ref(TeamMember);
}
class Task extends CoMap {
title = co.string;
subtasks = co.ref(ListOfTasks);
assignee = co.optional.ref(TeamMember);
}
class TeamMember extends CoMap {
name = co.string;
}
class ListOfTasks extends CoList.Of(co.ref(Task)) {}
// ---cut-before---
// Define a type that includes resolved nested data
type ProjectWithTasks = Resolved<Project, {
tasks: { $each: true }
}>;
// Function that expects resolved data
async function taskList({project}: {project: ProjectWithTasks}) {
// TypeScript knows tasks are loaded, so this is type-safe
return project.tasks
.map(task => task.title)
.join(`\n - `);
}
// For more complex resolutions
type FullyLoadedProject = Resolved<Project, {
tasks: {
$each: {
title: true,
subtasks: true,
assignee: true
}
},
owner: true
}>;
// Function that requires deeply resolved data
function processProject(project: FullyLoadedProject) {
// Safe access to all resolved properties
console.log(`Project ${project.name} owned by ${project.owner.name}`);
project.tasks.forEach(task => {
console.log(`Task: ${task.title}, Assigned to: ${task.assignee?.name}`);
console.log(`Subtasks: ${task.subtasks.length}`);
});
}
```
</CodeGroup>
</ContentByFramework>
Using the `Resolved` type helps catch errors at compile time rather than runtime, ensuring that your components and functions receive data with the proper resolution depth. This is especially useful for larger applications where data is passed between many components.
## Ensuring Data is Loaded ## Ensuring Data is Loaded
Sometimes you need to make sure data is loaded before proceeding with an operation. The `ensureLoaded` method lets you guarantee that a CoValue and its referenced data are loaded to a specific depth: Sometimes you need to make sure data is loaded before proceeding with an operation. The `ensureLoaded` method lets you guarantee that a CoValue and its referenced data are loaded to a specific depth:
<CodeGroup> <CodeGroup>
```ts twoslash ```ts
import { ID, CoMap, co, CoList, Resolved } from "jazz-tools";
class Project extends CoMap {
name = co.string;
tasks = co.ref(ListOfTasks);
owner = co.ref(TeamMember);
}
class Task extends CoMap {
title = co.string;
status = co.literal("todo", "in-progress", "completed");
subtasks = co.ref(ListOfTasks);
assignee = co.optional.ref(TeamMember);
}
class TeamMember extends CoMap {
name = co.string;
}
class ListOfTasks extends CoList.Of(co.ref(Task)) {}
// ---cut-before---
async function completeAllTasks(projectId: ID<Project>) { async function completeAllTasks(projectId: ID<Project>) {
// Ensure the project is loaded // Ensure the project and its tasks are loaded
const project = await Project.load(projectId, { resolve: true }); const project = await Project.load(projectId, {});
if (!project) return; if (!project) return;
// Ensure tasks are loaded
const loadedProject = await project.ensureLoaded({ const loadedProject = await project.ensureLoaded({
resolve: { tasks: [{}]
tasks: {
$each: true
}
}
}); });
// Now we can safely access and modify tasks // Now we can safely access and modify tasks
@@ -653,12 +280,61 @@ async function completeAllTasks(projectId: ID<Project>) {
``` ```
</CodeGroup> </CodeGroup>
## Performance Considerations
Loading depth is directly related to performance. Loading too much data can slow down your application, while loading too little can lead to "undefined" references. Here are some guidelines:
- **Load only what you need** for the current view or operation
- **Preload data** that will be needed soon to improve perceived performance
- Use **caching** to avoid reloading data that hasn't changed
{/* TODO: Add a note about supporting pagination */}
<CodeGroup>
```ts
// Bad: Loading everything deeply
const project = await Project.load(projectId, {
tasks: [{
subtasks: [{
comments: [{}]
}]
}],
members: [{}],
resources: [{}]
});
// Better: Loading only what's needed for the current view
const project = await Project.load(projectId, {
tasks: [{}] // Just load the tasks shallowly
});
// Later, when a task is selected:
const task = await Task.load(selectedTaskId, {
subtasks: [{}] // Now load its subtasks
});
```
</CodeGroup>
## Using a Loading Cache
By default, Jazz maintains a cache of loaded CoValues to avoid unnecessary network requests. This means that if you've already loaded a CoValue, subsequent load requests will use the cached version unless you explicitly request a refresh.
<CodeGroup>
```ts
// First load: fetches from network or local storage
const project = await Project.load(projectId, {});
// Later loads: uses cached version if available
const sameProject = await Project.load(projectId, {});
```
</CodeGroup>
## Best Practices ## Best Practices
1. **Be explicit about resolution depths**: Always specify exactly what you need 1. **Be explicit about loading depths**: Always specify exactly what you need
2. **Use framework integrations**: They handle subscription lifecycle automatically 2. **Clean up subscriptions**: Always store and call the unsubscribe function when you're done
3. **Clean up subscriptions**: Always store and call the unsubscribe function when you're done 3. **Handle loading states**: Check for undefined/null before accessing properties
4. **Handle all loading states**: Check for undefined (loading), null (not found), and success states 4. **Use framework integrations**: They handle subscription lifecycle automatically
5. **Use the Resolved type**: Add compile-time type safety for components that require specific resolution patterns 5. **Balance depth and performance**: Load only what you need for the current view
By effectively using subscriptions and deep loading, you can build responsive, collaborative applications that handle complex data relationships while maintaining good performance.

View File

@@ -0,0 +1,175 @@
export const metadata = { title: "Writing & deleting CoValues" };
import { CodeGroup } from "@/components/forMdx";
# Writing & deleting CoValues
Collaborative applications need ways to update and remove data. Jazz makes this simple by treating CoValues like regular JavaScript objects while handling all the complexity of syncing changes in the background. This page covers how to modify CoValues, work with collections, handle concurrent edits, and properly remove data when needed.
## Writing to CoValues
Once you have a CoValue, modifying it is straightforward. You can update fields like regular JavaScript properties. Changes are applied locally first for immediate feedback, then synchronized to other users with access to the same CoValues. This approach provides a natural programming model while handling all the distributed systems complexity behind the scenes.
<CodeGroup>
```ts
class Task extends CoMap {
title = co.string;
status = co.literal("todo", "in-progress", "completed");
assignee = co.optional.string;
}
//...
// Update fields
task.status = "in-progress"; // Direct assignment
task.assignee = "Alex"; // Optional field
```
</CodeGroup>
### Working with Lists
CoLists support familiar array operations, making it easy to work with collections of data. You can add, remove, and modify items using the standard JavaScript array methods, while Jazz handles the collaborative aspects automatically. These operations work correctly even when multiple users are making changes simultaneously.
<CodeGroup>
```ts
class Project extends CoMap {
name = co.string;
tasks = co.ref(ListOfTasks);
}
//...
// Add items
project.tasks.push(Task.create({
title: "Build raised beds",
status: "todo"
}));
// Remove items
project.tasks.splice(2, 1); // Remove third task
// Update items
project.tasks[0].status = "in-progress";
// Bulk updates
project.tasks.forEach(task => {
if (task.status === "todo") {
task.status = "in-progress";
}
});
```
</CodeGroup>
Changes sync automatically to everyone with access. Any edits you make are immediately visible in your local view and propagate to other users as they sync.
## Concurrent Edits
CoValues use [CRDTs](/docs/schemas/covalues#defining-schemas-covalues) to handle concurrent edits smoothly. In most cases, you don't need to think about conflicts - Jazz handles them automatically. This conflict resolution happens transparently, allowing multiple users to make changes simultaneously without disruption or data loss.
<CodeGroup>
```ts
class Dashboard extends CoMap {
activeProjects = co.number;
status = co.literal("active", "maintenance");
notifications = co.ref(ListOfNotifications);
}
//...
// Multiple users can edit simultaneously
// Last-write-wins for simple fields
dashboard.status = "maintenance"; // Local change is immediate
dashboard.activeProjects = 5; // Syncs automatically
// Lists handle concurrent edits too
dashboard.notifications.push(Notification.create({
timestamp: new Date(),
message: "System update scheduled"
}));
```
</CodeGroup>
## Deleting CoValues
There are a few ways to delete CoValues, from simple field removal to full cleanup. Jazz provides flexible options for removing data depending on your needs. You can remove references while keeping the underlying data, remove items from lists, or completely delete CoValues when they're no longer needed.
<CodeGroup>
```ts
class Project extends CoMap {
tasks = co.ref(ListOfTasks);
resources = co.optional.ref(ListOfResources);
}
//...
// Remove a reference
project.resources = null; // Removes the reference but resources still exist
// Remove from a list
project.tasks.splice(2, 1); // Removes third team member from list
```
</CodeGroup>
### Best Practices
- Load everything you plan to delete
- Check permissions before attempting deletes
- Consider soft deletes for recoverable data
## Removing Data in CoValues
You can delete fields from any `CoMap` to remove specific properties while keeping the CoValue itself. This is useful when you need to clear certain data without affecting the rest of your object structure. The deletion operations are also synchronized to all users with access.
<CodeGroup>
```ts
class Project extends CoMap {
name = co.string;
team = co.ref(ListOfMembers);
budget = co.optional.ref(Budget);
}
//...
// Delete fields from a regular CoMap
delete project.budget; // Removes the budget reference
// Delete from a record-type CoMap
class ProjectTags extends CoMap.Record(co.string) {}
const projectTags = ProjectTags.create({
"priority-high": "High priority tasks",
});
delete projectTags["priority-high"]; // Removes specific tag
```
</CodeGroup>
For `CoList`s, use array methods:
<CodeGroup>
```ts
// Remove from lists using splice
project.team.splice(2, 1); // Removes third team member
```
</CodeGroup>
### Restoring Data
For data you might want to restore later, consider using status fields instead of permanent deletion. This "soft delete" pattern is common in applications where users might need to recover previously removed items. By using a boolean field to mark items as archived or deleted, you maintain the ability to restore them later.
<CodeGroup>
```ts
class Task extends CoMap {
title = co.string;
archived = co.boolean;
}
// Mark as archived
task.archived = true;
// Restore later
task.archived = false; // Task is back in the active list!
```
</CodeGroup>
Removed data remains in the edit history. If you need to handle sensitive information, plan your data model accordingly.

View File

@@ -3,7 +3,11 @@ import DocsLayout from "@/components/docs/DocsLayout";
import { DocNav } from "@/components/docs/nav"; import { DocNav } from "@/components/docs/nav";
import { Prose } from "gcmp-design-system/src/app/components/molecules/Prose"; import { Prose } from "gcmp-design-system/src/app/components/molecules/Prose";
export default function Layout({ children }: { children: React.ReactNode }) { export default function Layout({
children,
}: {
children: React.ReactNode;
}) {
return ( return (
<TocProvider> <TocProvider>
<DocsLayout nav={<DocNav />}> <DocsLayout nav={<DocNav />}>

View File

@@ -10,59 +10,17 @@
:focus-visible { :focus-visible {
@apply ring-2 ring-blue/75 dark:ring-blue-400/75; @apply ring-2 ring-blue/75 dark:ring-blue-400/75;
} }
details > summary {
@apply cursor-pointer;
&.list-none::-webkit-details-marker,
&.list-none::marker {
display: none;
}
}
} }
pre.shiki { @layer components {
height: 100%; @import "shiki.css";
padding-top: 1em;
padding-bottom: 1em;
} }
.twoslash-popup-code pre.shiki {
padding: 0.2em;
font-size: 0.8em;
}
.twoslash-hover {
position: initial !important;
}
pre.shiki .line {
display: inline-block;
width: 100%;
padding-left: 1em;
line-height: 1.5;
cursor: text;
}
.twoslash-popup-code pre.shiki .line {
display: inline;
padding-left: 0;
}
html.dark .shiki {
color: var(--shiki-dark) !important;
background-color: var(--shiki-dark-bg) !important;
/* Optional, if you also want font styles */
font-style: var(--shiki-dark-font-style) !important;
font-weight: var(--shiki-dark-font-weight) !important;
text-decoration: var(--shiki-dark-text-decoration) !important;
}
html.dark .shiki span {
color: var(--shiki-dark) !important;
/* Optional, if you also want font styles */
font-style: var(--shiki-dark-font-style) !important;
font-weight: var(--shiki-dark-font-weight) !important;
text-decoration: var(--shiki-dark-text-decoration) !important;
}
.shiki .line.diff.remove {
background-color: rgba(255, 0, 0, 0.1) !important;
}
.shiki .line.diff.add {
background-color: rgba(0, 255, 0, 0.1) !important;
}
@import "@shikijs/twoslash/style-rich.css";

View File

@@ -0,0 +1,330 @@
pre.shiki {
overflow: hidden;
height: 100%;
}
pre.shiki:hover .dim {
opacity: 1;
}
pre.shiki div.dim {
opacity: 0.5;
}
pre.shiki div.dim,
pre.shiki div.highlight {
margin: 0;
padding: 0;
}
pre.shiki div.highlight {
opacity: 1;
background-color: #f1f8ff;
}
pre.shiki div.line {
/* min-height: 1rem; */
counter-increment: lineNumber 1;
}
pre.shiki div.line::before {
content: counter(lineNumber);
display: inline-block;
vertical-align: middle;
width: 1.3rem;
padding-right: 0.3rem;
text-align: right;
transition: color 0.3s;
@apply text-stone-200/70 dark:text-stone-900 text-[0.65rem];
}
pre.shiki div.line:hover::before {
@apply text-stone-400 dark:text-stone-600;
}
/** Don't show the language identifiers */
pre.shiki .language-id {
display: none;
}
/** When you mouse over the pre, show the underlines */
pre.twoslash:hover data-lsp {
@apply border-dotted border-b border-stone-300 dark:border-stone-700;
}
/** The tooltip-like which provides the LSP response */
pre.twoslash data-lsp::before {
content: attr(lsp);
position: absolute;
transform: translate(0, 1.2rem);
max-width: 30rem;
@apply text-xs px-1.5 py-1 rounded border shadow-lg overflow-hidden whitespace-pre-wrap text-stone-700 bg-stone-50 dark:text-stone-200 dark:bg-stone-950;
text-align: left;
z-index: 100;
opacity: 0;
transition: opacity 0.3s;
pointer-events: none;
display: none;
}
pre.twoslash data-lsp:hover::before {
display: block;
opacity: 1;
pointer-events: visible;
width: auto;
height: auto;
}
.shiki-outer {
@apply shadow-sm rounded-xl;
}
.shiki-filename {
@apply px-3 py-2 bg-stone-100 text-stone-700 dark:bg-stone-900 dark:text-stone-300 rounded-t-xl text-xs;
}
pre .code-container {
@apply overflow-auto p-2 pl-0 bg-white dark:bg-stone-950 rounded-b-xl text-xs h-full leading-5;
}
/* The try button */
pre .code-container > a {
position: absolute;
right: 8px;
bottom: 8px;
border-radius: 4px;
border: 1px solid #719af4;
padding: 0 8px;
color: #719af4;
text-decoration: none;
opacity: 0;
transition-timing-function: ease;
transition: opacity 0.3s;
}
/* Respect no animations */
@media (prefers-reduced-motion: reduce) {
pre .code-container > a {
transition: none;
}
}
pre .code-container > a:hover {
color: white;
background-color: #719af4;
}
pre .code-container:hover a {
opacity: 1;
}
pre code {
white-space: pre;
}
pre code a {
text-decoration: none;
}
pre data-err {
/* Extracted from VS Code */
background: url("data:image/svg+xml,%3Csvg%20xmlns%3D'http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg'%20viewBox%3D'0%200%206%203'%20enable-background%3D'new%200%200%206%203'%20height%3D'3'%20width%3D'6'%3E%3Cg%20fill%3D'%23c94824'%3E%3Cpolygon%20points%3D'5.5%2C0%202.5%2C3%201.1%2C3%204.1%2C0'%2F%3E%3Cpolygon%20points%3D'4%2C0%206%2C2%206%2C0.6%205.4%2C0'%2F%3E%3Cpolygon%20points%3D'0%2C2%201%2C3%202.4%2C3%200%2C0.6'%2F%3E%3C%2Fg%3E%3C%2Fsvg%3E")
repeat-x bottom left;
padding-bottom: 3px;
}
pre .query {
margin-bottom: 10px;
color: #137998;
display: inline-block;
}
/* In order to have the 'popped out' style design and to not break the layout
/* we need to place a fake and un-selectable copy of the error which _isn't_ broken out
/* behind the actual error message.
/* This sections keeps both of those two in in sync */
pre .error,
pre .error-behind {
margin-left: -14px;
margin-top: 8px;
margin-bottom: 4px;
padding: 6px;
padding-left: 14px;
width: calc(100% - 20px);
white-space: pre-wrap;
display: block;
}
pre .error {
position: absolute;
background-color: #fee;
border-left: 2px solid #bf1818;
/* Give the space to the error code */
display: flex;
align-items: center;
color: black;
}
pre .error .code {
display: none;
}
pre .error-behind {
user-select: none;
visibility: transparent;
color: #fee;
}
/* Queries */
pre .arrow {
/* Transparent background */
background-color: #eee;
position: relative;
top: -7px;
margin-left: 0.1rem;
/* Edges */
border-left: 1px solid #eee;
border-top: 1px solid #eee;
transform: translateY(25%) rotate(45deg);
/* Size */
height: 8px;
width: 8px;
}
pre .popover {
margin-bottom: 10px;
background-color: #eee;
display: inline-block;
padding: 0 0.5rem 0.3rem;
margin-top: 10px;
border-radius: 3px;
}
/* Completion */
pre .inline-completions ul.dropdown {
display: inline-block;
position: absolute;
width: 240px;
background-color: gainsboro;
color: grey;
padding-top: 4px;
font-family: var(--code-font);
font-size: 0.8rem;
margin: 0;
padding: 0;
border-left: 4px solid #4b9edd;
}
pre .inline-completions ul.dropdown::before {
background-color: #4b9edd;
width: 2px;
position: absolute;
top: -1.2rem;
left: -3px;
content: " ";
}
pre .inline-completions ul.dropdown li {
overflow-x: hidden;
padding-left: 4px;
margin-bottom: 4px;
}
pre .inline-completions ul.dropdown li.deprecated {
text-decoration: line-through;
}
pre .inline-completions ul.dropdown li span.result-found {
color: #4b9edd;
}
pre .inline-completions ul.dropdown li span.result {
width: 100px;
color: black;
display: inline-block;
}
.dark-theme .markdown pre {
background-color: #d8d8d8;
border-color: #ddd;
filter: invert(98%) hue-rotate(180deg);
}
data-lsp {
/* Ensures there's no 1px jump when the hover happens */
border-bottom: 1px dotted transparent;
/* Fades in unobtrusively */
transition-timing-function: ease;
transition: border-color 0.3s;
}
/* Respect people's wishes to not have animations */
@media (prefers-reduced-motion: reduce) {
data-lsp {
transition: none;
}
}
/** Annotations support, providing a tool for meta commentary */
.tag-container {
position: relative;
}
.tag-container .twoslash-annotation {
position: absolute;
font-family: "JetBrains Mono", Menlo, Monaco, Consolas, Courier New, monospace;
right: -10px;
/** Default annotation text to 200px */
width: 200px;
color: #187abf;
background-color: #fcf3d9 bb;
}
.tag-container .twoslash-annotation p {
text-align: left;
font-size: 0.8rem;
line-height: 0.9rem;
}
.tag-container .twoslash-annotation svg {
float: left;
margin-left: -44px;
}
.tag-container .twoslash-annotation.left {
right: auto;
left: -200px;
}
.tag-container .twoslash-annotation.left svg {
float: right;
margin-right: -5px;
}
/** Support for showing console log/warn/errors inline */
pre .logger {
display: flex;
align-items: center;
color: black;
padding: 6px;
padding-left: 8px;
width: calc(100% - 19px);
white-space: pre-wrap;
}
pre .logger svg {
margin-right: 9px;
}
pre .logger.error-log {
background-color: #fee;
border-left: 2px solid #bf1818;
}
pre .logger.warn-log {
background-color: #ffe;
border-left: 2px solid #eae662;
}
pre .logger.log-log {
background-color: #e9e9e9;
border-left: 2px solid #ababab;
}
pre .logger.log-log svg {
margin-left: 6px;
margin-right: 9px;
}
body {
--shiki-color-text: #606060;
--shiki-color-background: transparent;
--shiki-token-constant: #00a5a5;
--shiki-token-string: #4e3a2c;
--shiki-token-comment: #aaa;
--shiki-token-keyword: #7b8bff;
--shiki-token-parameter: #ff9800;
--shiki-token-function: #445dd7;
--shiki-token-string-expression: #38a35f;
--shiki-token-punctuation: #969696;
--shiki-token-link: #1aa245;
}
.dark body {
--shiki-color-text: #d1d1d1;
--shiki-token-constant: #2dc9c9;
--shiki-token-string: #feb179;
--shiki-token-comment: #6b737c;
--shiki-token-keyword: #7b8bff;
--shiki-token-parameter: #ff9800;
--shiki-token-function: #9babff;
--shiki-token-string-expression: #42bb69;
--shiki-token-punctuation: #bbb;
--shiki-token-link: #ffab70;
}

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