Compare commits

..

29 Commits

Author SHA1 Message Date
Anselm
5a85501919 Publish
- jazz-example-file-drop@0.0.60
 - jazz-example-pets@0.0.60
 - jazz-example-todo@0.0.60
 - jazz-example-twit@0.0.60
 - cojson@0.4.13
 - cojson-simple-sync@0.4.13
 - cojson-storage-indexeddb@0.4.13
 - cojson-storage-sqlite@0.4.13
 - jazz-autosub@0.4.13
 - jazz-browser@0.4.13
 - jazz-browser-auth-local@0.4.13
 - jazz-browser-media-images@0.4.13
 - jazz-react@0.4.13
 - jazz-react-auth-local@0.4.13
2023-10-06 17:31:14 +01:00
Anselm
97a4282e5e Merge branch 'backend-support' into data-throughput 2023-10-06 17:23:13 +01:00
Anselm
39c13b50a3 Update docs 2023-10-06 17:18:30 +01:00
Anselm
ad304e321b Lots of improvements for BinaryCoStreams & file-drop example 2023-10-06 17:09:58 +01:00
Anselm
72fce45b2b Publish
- jazz-example-pets@0.0.21
 - jazz-example-todo@0.0.45
 - jazz-example-twit@0.0.8
 - cojson@0.4.8
 - cojson-simple-sync@0.4.8
 - cojson-storage-indexeddb@0.4.8
 - cojson-storage-sqlite@0.4.8
 - jazz-autosub@0.4.8
 - jazz-browser@0.4.8
 - jazz-browser-auth-local@0.4.8
 - jazz-browser-media-images@0.4.9
 - jazz-react@0.4.8
 - jazz-react-auth-local@0.4.8
2023-10-04 22:01:28 +01:00
Anselm
1f49d7fda6 Actually fix circular issues for esbuild/vite 2023-10-04 22:00:38 +01:00
Anselm
eec8ee7027 Publish
- jazz-example-pets@0.0.20
 - jazz-example-todo@0.0.44
 - jazz-example-twit@0.0.7
 - cojson@0.4.7
 - cojson-simple-sync@0.4.7
 - cojson-storage-indexeddb@0.4.7
 - cojson-storage-sqlite@0.4.7
 - jazz-autosub@0.4.7
 - jazz-browser@0.4.7
 - jazz-browser-auth-local@0.4.7
 - jazz-browser-media-images@0.4.8
 - jazz-react@0.4.7
 - jazz-react-auth-local@0.4.7
2023-10-04 21:23:52 +01:00
Anselm
188eb2e1e3 Update docs 2023-10-04 21:23:28 +01:00
Anselm
62867b32d9 Get rid of more cyclic imports 2023-10-04 21:22:52 +01:00
Anselm
ccebd2447d Publish
- jazz-example-pets@0.0.19
 - jazz-example-todo@0.0.43
 - jazz-example-twit@0.0.6
 - cojson@0.4.6
 - cojson-simple-sync@0.4.6
 - cojson-storage-indexeddb@0.4.6
 - cojson-storage-sqlite@0.4.6
 - jazz-autosub@0.4.6
 - jazz-browser@0.4.6
 - jazz-browser-auth-local@0.4.6
 - jazz-browser-media-images@0.4.7
 - jazz-react@0.4.6
 - jazz-react-auth-local@0.4.6
2023-10-04 21:01:44 +01:00
Anselm
08dca75789 Address some circular deps in cojson typescript 2023-10-04 21:00:59 +01:00
Anselm
f1cd639a09 Add project list to todo example 2023-10-03 13:59:00 +01:00
Anselm Eickhoff
be18e4de14 Merge pull request #111 from gardencmp/autosub-api
Autosub API
2023-10-01 13:18:40 +01:00
Anselm
7e62c91d44 Publish
- jazz-example-pets@0.0.18
 - jazz-example-twit@0.0.5
 - jazz-browser-media-images@0.4.6
2023-10-01 12:27:10 +01:00
Anselm
b2d5a103b5 move image-blob-reduce types to proper deps 2023-10-01 12:26:53 +01:00
Anselm
4ee2cad39e Publish
- jazz-example-pets@0.0.17
 - jazz-example-todo@0.0.42
 - jazz-example-twit@0.0.4
 - cojson@0.4.5
 - cojson-simple-sync@0.4.5
 - cojson-storage-indexeddb@0.4.5
 - cojson-storage-sqlite@0.4.5
 - jazz-autosub@0.4.5
 - jazz-browser@0.4.5
 - jazz-browser-auth-local@0.4.5
 - jazz-browser-media-images@0.4.5
 - jazz-react@0.4.5
 - jazz-react-auth-local@0.4.5
2023-10-01 12:18:35 +01:00
Anselm
b7c8a0038b Rename syncedQueries -> autosub and clean up a lot of APIs 2023-10-01 12:16:56 +01:00
Anselm
8c27e8c379 doc fixes 2023-09-28 23:05:59 +01:00
Anselm Eickhoff
0133aa47ff Merge pull request #105 from gardencmp/example-twit
Twitter example
2023-09-28 11:51:38 +01:00
Anselm
5659c925a2 Change Twit html title 2023-09-28 11:44:44 +01:00
Anselm
27779ac792 Publish
- jazz-example-pets@0.0.16
 - jazz-example-todo@0.0.41
 - jazz-example-twit@0.0.3
 - cojson@0.4.1
 - cojson-simple-sync@0.4.1
 - cojson-storage-indexeddb@0.4.1
 - cojson-storage-sqlite@0.4.1
 - jazz-browser@0.4.1
 - jazz-browser-auth-local@0.4.1
 - jazz-browser-media-images@0.4.1
 - jazz-react@0.4.1
 - jazz-react-auth-local@0.4.1
2023-09-28 11:25:36 +01:00
Anselm
3f1bfa4629 Improve twit example 2023-09-28 11:25:09 +01:00
Anselm
15a693c3ed Simplify QueriedCoStream 2023-09-28 11:23:23 +01:00
Anselm
b1d620e145 Update docs 2023-09-28 11:23:06 +01:00
Anselm
478fbd0aa9 Bigger inputs on mobile 2023-09-27 22:21:19 +01:00
Anselm
ee906b7351 Add QR code to own profile 2023-09-27 22:13:55 +01:00
Anselm
dd15f21ccb Fix follow button 2023-09-27 21:51:20 +01:00
Anselm
d7cd5fda7c Actually deploy twit example 2023-09-27 21:43:07 +01:00
Anselm
174300b00f Deploy twit example 2023-09-27 21:39:30 +01:00
129 changed files with 15264 additions and 4573 deletions

View File

@@ -11,7 +11,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
example: ["todo", "pets"]
example: ["todo", "pets", "twit"]
steps:
- uses: actions/checkout@v3
@@ -58,7 +58,7 @@ jobs:
needs: build
strategy:
matrix:
example: ["todo", "pets"]
example: ["todo", "pets", "twit"]
steps:
- uses: actions/checkout@v3

10256
DOCS.md

File diff suppressed because it is too large Load Diff

View File

@@ -56,19 +56,19 @@ Jazz is open source and you can run your own sync & storage server, but to reall
### Building a new, entirely sync-based React app
1. Define your data model with [cojson Collaborative Values (CoValues)](./DOCS.md/#covalue).
2. Implement permission logic using [cojson Groups](./DOCS.md/#group).
3. Build a user interface with [jazz-react](./DOCS.md/#jazz-react)'s reactive [synced queries](./DOCS.md/#usesyncedqueryid).
1. Define your data model with [cojson Collaborative Values (CoValues)](./DOCS.md#covalue).
2. Implement permission logic using [cojson Groups](./DOCS.md#group).
3. Build a user interface with [jazz-react](./DOCS.md#jazz-react) and [auto-sub](./DOCS.md#useautosubid).
### Gradually adding sync to an existing React app
Gradually migrate app features to use sync:
1. Define data model for small aspect of your app with [cojson Collaborative Values (CoValues)](./DOCS.md/#covalue).
1. Define data model for small aspect of your app with [cojson Collaborative Values (CoValues)](./DOCS.md#covalue).
- Schema adapters/importers for Prisma/Drizzle/PostgreSQL introspection coming soon.
2. Map existing permission logic with [cojson Groups](./DOCS.md/#group) & integrate existing auth.
2. Map existing permission logic with [cojson Groups](./DOCS.md#group) & integrate existing auth.
- Auth integrations coming soon.
3. Replace some of the React state and API requests in your UI with [jazz-react](./DOCS.md/#jazz-react)'s reactive [synced queries](./DOCS.md/#usesyncedqueryid).
3. Replace some of the React state and API requests in your UI with [jazz-react](./DOCS.md#jazz-react) and [auto-sub](./DOCS.md#useautosubid).
# Example Apps
@@ -103,10 +103,10 @@ Demonstrates:
For now, docs are hosted in a single well-structured markdown file: [`./DOCS.md`](./DOCS.md).
- [Package Overview](./DOCS.md/#overview)
- [`jazz-react` API](./DOCS.md/#jazz-react)
- [`cojson` API](./DOCS.md/#cojson)
- [`jazz-react-media-images` API](./DOCS.md/#jazz-react-media-images)
- [Package Overview](./DOCS.md#overview)
- [`jazz-react` API](./DOCS.md#jazz-react)
- [`cojson` API](./DOCS.md#cojson)
- [`jazz-browser-media-images` API](./DOCS.md#jazz-browser-media-images)
In the future we'll build a dedicated docs page on the Jazz homepage.

View File

@@ -0,0 +1,18 @@
module.exports = {
root: true,
env: { browser: true, es2020: true },
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:react-hooks/recommended',
],
ignorePatterns: ['dist', '.eslintrc.cjs'],
parser: '@typescript-eslint/parser',
plugins: ['react-refresh'],
rules: {
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true },
],
},
}

24
examples/file-drop/.gitignore vendored Normal file
View File

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

View File

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

View File

@@ -0,0 +1,64 @@
# Jazz Todo List Example
Live version: https://example-todo.jazz.tools
## Installing & running the example locally
Start by checking out just the example app to a folder:
```bash
npx degit gardencmp/jazz/examples/todo jazz-example-todo
cd jazz-example-todo
```
(This ensures that you have the example app without git history or our multi-package monorepo)
Install dependencies:
```bash
npm install
```
Start the dev server:
```bash
npm run dev
```
## Structure
- [`src/basicComponents`](./src/basicComponents): simple components to build the UI, unrelated to Jazz (uses [shadcn/ui](https://ui.shadcn.com))
- [`src/components`](./src/components/): helper components that do contain Jazz-specific logic, but aren't very relevant to understand the basics of Jazz and CoJSON
- [`src/1_types.ts`](./src/1_types.ts),
[`src/2_main.tsx`](./src/2_main.tsx),
[`src/3_NewProjectForm.tsx`](./src/3_NewProjectForm.tsx),
[`src/4_ProjectTodoTable.tsx`](./src/4_ProjectTodoTable.tsx): the main files for this example, see the walkthrough below
## Walkthrough
### Main parts
1. Defining the data model with CoJSON: [`src/1_types.ts`](./src/1_types.ts)
2. The top-level provider `<WithJazz/>` and routing: [`src/2_main.tsx`](./src/2_main.tsx)
3. Creating a new todo project: [`src/3_NewProjectForm.tsx`](./src/3_NewProjectForm.tsx)
4. Reactively rendering a todo project as a table, adding and editing tasks: [`src/4_ProjectTodoTable.tsx`](./src/4_ProjectTodoTable.tsx)
### Helpers
- (not yet explained) Creating invite links/QR codes with `<InviteButton/>`: [`src/components/InviteButton.tsx`](./src/components/InviteButton.tsx)
This is the whole Todo List app!
## Questions / problems / feedback
If you have feedback, let us know on [Discord](https://discord.gg/utDMjHYg42) or open an issue or PR to fix something that seems wrong.
## Configuration: sync server
By default, the example app uses [Jazz Global Mesh](https://jazz.tools/mesh) (`wss://sync.jazz.tools`) - so cross-device use, invites and collaboration should just work.
You can also run a local sync server by running `npx cojson-simple-sync` and adding the query param `?sync=ws://localhost:4200` to the URL of the example app (for example: `http://localhost:5173/?sync=ws://localhost:4200`), or by setting the `sync` parameter of the `<WithJazz>` provider component in [./src/2_main.tsx](./src/2_main.tsx).

View File

@@ -0,0 +1,16 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "default",
"rsc": false,
"tsx": true,
"tailwind": {
"config": "tailwind.config.js",
"css": "src/index.css",
"baseColor": "stone",
"cssVariables": true
},
"aliases": {
"components": "@/basicComponents",
"utils": "@/basicComponents/lib/utils"
}
}

View File

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

View File

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

View File

@@ -0,0 +1,46 @@
{
"name": "jazz-example-file-drop",
"private": true,
"version": "0.0.60",
"type": "module",
"scripts": {
"dev": "vite --port 6610",
"build": "tsc && vite build",
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview"
},
"dependencies": {
"@radix-ui/react-checkbox": "^1.0.4",
"@radix-ui/react-slot": "^1.0.2",
"@radix-ui/react-toast": "^1.1.4",
"@types/qrcode": "^1.5.1",
"class-variance-authority": "^0.7.0",
"clsx": "^2.0.0",
"jazz-react": "^0.4.13",
"jazz-react-auth-local": "^0.4.13",
"lucide-react": "^0.274.0",
"qrcode": "^1.5.3",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router": "^6.16.0",
"react-router-dom": "^6.16.0",
"tailwind-merge": "^1.14.0",
"tailwindcss-animate": "^1.0.7",
"uniqolor": "^1.1.0"
},
"devDependencies": {
"@types/react": "^18.2.15",
"@types/react-dom": "^18.2.7",
"@typescript-eslint/eslint-plugin": "^6.0.0",
"@typescript-eslint/parser": "^6.0.0",
"@vitejs/plugin-react-swc": "^3.3.2",
"autoprefixer": "^10.4.14",
"eslint": "^8.45.0",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.3",
"postcss": "^8.4.27",
"tailwindcss": "^3.3.3",
"typescript": "^5.0.2",
"vite": "^4.4.5"
}
}

View File

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 KiB

View File

@@ -0,0 +1,5 @@
import { CoMap, BinaryCoStream } from "cojson";
export type FileBundle = CoMap<{
[filename: string]: BinaryCoStream['id']
}>;

View File

@@ -0,0 +1,188 @@
import React, { ChangeEvent, useCallback, useState } from "react";
import ReactDOM from "react-dom/client";
import {
RouterProvider,
createHashRouter,
useNavigate,
useParams,
} from "react-router-dom";
import "./index.css";
import { WithJazz, useJazz, useAcceptInvite, useAutoSub } from "jazz-react";
import { LocalAuth } from "jazz-react-auth-local";
import {
Button,
Input,
ThemeProvider,
TitleAndLogo,
} from "./basicComponents/index.ts";
import { PrettyAuthUI } from "./components/Auth.tsx";
import { FileBundle } from "./1_types.ts";
import {
createBinaryStreamFromBlob,
readBlobFromBinaryStream,
} from "jazz-browser";
import { DownloadIcon } from "lucide-react";
import { flushSync } from "react-dom";
const appName = "Jazz File Drop Example";
const auth = LocalAuth({
appName,
Component: PrettyAuthUI,
});
ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<ThemeProvider>
<TitleAndLogo name={appName} />
<div className="flex flex-col h-full items-center justify-start gap-10 pt-10 pb-10 px-5">
<WithJazz auth={auth}>
<App />
</WithJazz>
</div>
</ThemeProvider>
</React.StrictMode>
);
function App() {
// logOut logs out the AuthProvider passed to `<WithJazz/>` above.
const { logOut } = useJazz();
const router = createHashRouter([
{
path: "/",
element: <FileDropUI />,
},
{
path: "/bundle/:bundleId",
element: <FileDropUIPage />,
},
{
path: "/invite/*",
element: <p>Accepting invite...</p>,
},
]);
// `useAcceptInvite()` is a hook that accepts an invite link from the URL hash,
// and on success calls our callback where we navigate to the project that we were just invited to.
useAcceptInvite((bundleId) => router.navigate("/v/" + bundleId));
return (
<>
<RouterProvider router={router} />
<Button
onClick={() => router.navigate("/").then(logOut)}
variant="outline"
>
Log Out
</Button>
</>
);
}
export function FileDropUIPage() {
const { bundleId } = useParams<{ bundleId: FileBundle["id"] }>();
return <FileDropUI bundleId={bundleId} />;
}
export function FileDropUI({ bundleId }: { bundleId?: FileBundle["id"] }) {
const navigate = useNavigate();
const { me, localNode } = useJazz();
const fileBundle = useAutoSub(bundleId);
const [progressMessage, setProgressMessage] = useState<{
[name: string]: string;
}>({});
const onChange = useCallback(
(event: ChangeEvent<HTMLInputElement>) => {
let fileBundleToUse = fileBundle?.meta.coValue;
let isFirstUpload = false;
if (!fileBundleToUse) {
const group = me.createGroup().addMember("everyone", "reader");
fileBundleToUse = group.createMap<FileBundle>();
isFirstUpload = true;
}
const files = [...(event.target.files || [])];
Promise.all(
files.map((file) =>
createBinaryStreamFromBlob(
file,
fileBundleToUse.group,
{ type: "binary" },
(progress) =>
setProgressMessage((old) => ({
...old,
[file.name]: `Creating ${Math.round(
progress * 100
)}%`,
}))
).then((stream) => {
fileBundleToUse!.set(file.name, stream.id);
})
)
).then(() => {
if (isFirstUpload) {
navigate("/bundle/" + fileBundleToUse!.id);
}
});
event.target.value = "";
},
[me, navigate, fileBundle]
);
return (
<div className="max-w-full p-5 w-[40rem]">
<h1 className="text-3xl font-bold mb-5">File Drop</h1>
{[
...new Set([
...Object.keys(fileBundle || {}),
...Object.keys(progressMessage),
]),
].map((name) => (
<div className="mb-5 flex justify-between" key={name}>
{name} {progressMessage[name]}
<Button
size="sm"
disabled={!(name in (fileBundle || {}))}
onClick={() => {
const streamId = fileBundle?.meta.coValue.get(name);
streamId &&
readBlobFromBinaryStream(
streamId,
localNode,
false,
(progress) =>
setProgressMessage((old) => ({
...old,
[name]: `Loading ${Math.round(
progress * 100
)}%`,
}))
).then((blob) => {
if (!blob) return;
const url = URL.createObjectURL(blob);
window.open(url, "_blank");
});
}}
>
<DownloadIcon />
</Button>
</div>
))}
{(!fileBundle || fileBundle.meta.group.myRole() === "admin") && (
<Input type="file" onChange={onChange} multiple />
)}
</div>
);
}
/** Walkthrough: Continue with ./3_NewProjectForm.tsx */

View File

@@ -0,0 +1,39 @@
import { Input } from "@/basicComponents/ui/input";
import { Button } from "@/basicComponents/ui/button";
export function SubmittableInput({
onSubmit,
label,
placeholder,
disabled,
}: {
onSubmit: (text: string) => void;
label: string;
placeholder: string;
disabled?: boolean;
}) {
return (
<form
className="flex flex-row items-center gap-3"
onSubmit={(e) => {
e.preventDefault();
const textEl = e.currentTarget.elements.namedItem(
"text"
) as HTMLInputElement;
onSubmit(textEl.value);
textEl.value = "";
}}
>
<Input
className="-ml-3 -my-2 flex-grow flex-3 text-base"
name="text"
placeholder={placeholder}
autoComplete="off"
disabled={disabled}
/>
<Button asChild type="submit" className="flex-shrink flex-1 cursor-pointer">
<Input type="submit" value={label} disabled={disabled} />
</Button>
</form>
);
}

View File

@@ -0,0 +1,10 @@
import { Toaster } from ".";
export function TitleAndLogo({name}: {name: string}) {
return <>
<div className="flex items-center gap-2 justify-center mt-5">
<img src="jazz-logo.png" className="h-5" /> {name}
</div>
<Toaster />
</>
}

View File

@@ -0,0 +1,17 @@
export { Button } from "./ui/button";
export { Checkbox } from "./ui/checkbox";
export { Input } from "./ui/input";
export { Skeleton } from "./ui/skeleton";
export { Toaster } from "./ui/toaster";
export { useToast } from "./ui/use-toast";
export { SubmittableInput } from "./SubmittableInput";
export { TitleAndLogo } from "./TitleAndLogo";
export { ThemeProvider } from "./themeProvider";
export {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "./ui/table";

View File

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

View File

@@ -0,0 +1,72 @@
import { createContext, useContext, useEffect, useState } from "react";
type ThemeProviderProps = {
children: React.ReactNode;
defaultTheme?: string;
storageKey?: string;
};
type ThemeProviderState = {
theme: string;
setTheme: (theme: string) => void;
};
const initialState = {
theme: "system",
setTheme: () => null,
};
const ThemeProviderContext = createContext<ThemeProviderState>(initialState);
export function ThemeProvider({
children,
defaultTheme = "system",
storageKey = "vite-ui-theme",
...props
}: ThemeProviderProps) {
const [theme, setTheme] = useState(
() => localStorage.getItem(storageKey) || defaultTheme
);
useEffect(() => {
const root = window.document.documentElement;
root.classList.remove("light", "dark");
if (theme === "system") {
const systemTheme = window.matchMedia(
"(prefers-color-scheme: dark)"
).matches
? "dark"
: "light";
root.classList.add(systemTheme);
return;
}
root.classList.add(theme);
}, [theme]);
const value = {
theme,
setTheme: (theme: string) => {
localStorage.setItem(storageKey, theme);
setTheme(theme);
},
};
return (
<ThemeProviderContext.Provider {...props} value={value}>
{children}
</ThemeProviderContext.Provider>
);
}
export const useTheme = () => {
const context = useContext(ThemeProviderContext);
if (context === undefined)
throw new Error("useTheme must be used within a ThemeProvider");
return context;
};

View File

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

View File

@@ -0,0 +1,28 @@
import * as React from "react"
import * as CheckboxPrimitive from "@radix-ui/react-checkbox"
import { Check } from "lucide-react"
import { cn } from "@/basicComponents/lib/utils"
const Checkbox = React.forwardRef<
React.ElementRef<typeof CheckboxPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root>
>(({ className, ...props }, ref) => (
<CheckboxPrimitive.Root
ref={ref}
className={cn(
"peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",
className
)}
{...props}
>
<CheckboxPrimitive.Indicator
className={cn("flex items-center justify-center text-current")}
>
<Check className="h-4 w-4" />
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
))
Checkbox.displayName = CheckboxPrimitive.Root.displayName
export { Checkbox }

View File

@@ -0,0 +1,25 @@
import * as React from "react"
import { cn } from "@/basicComponents/lib/utils"
export interface InputProps
extends React.InputHTMLAttributes<HTMLInputElement> {}
const Input = React.forwardRef<HTMLInputElement, InputProps>(
({ className, type, ...props }, ref) => {
return (
<input
type={type}
className={cn(
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
className
)}
ref={ref}
{...props}
/>
)
}
)
Input.displayName = "Input"
export { Input }

View File

@@ -0,0 +1,15 @@
import { cn } from "@/basicComponents/lib/utils"
function Skeleton({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) {
return (
<div
className={cn("animate-pulse rounded-md bg-muted", className)}
{...props}
/>
)
}
export { Skeleton }

View File

@@ -0,0 +1,114 @@
import * as React from "react"
import { cn } from "@/basicComponents/lib/utils"
const Table = React.forwardRef<
HTMLTableElement,
React.HTMLAttributes<HTMLTableElement>
>(({ className, ...props }, ref) => (
<div className="w-full overflow-auto">
<table
ref={ref}
className={cn("w-full caption-bottom text-sm", className)}
{...props}
/>
</div>
))
Table.displayName = "Table"
const TableHeader = React.forwardRef<
HTMLTableSectionElement,
React.HTMLAttributes<HTMLTableSectionElement>
>(({ className, ...props }, ref) => (
<thead ref={ref} className={cn("[&_tr]:border-b", className)} {...props} />
))
TableHeader.displayName = "TableHeader"
const TableBody = React.forwardRef<
HTMLTableSectionElement,
React.HTMLAttributes<HTMLTableSectionElement>
>(({ className, ...props }, ref) => (
<tbody
ref={ref}
className={cn("[&_tr:last-child]:border-0", className)}
{...props}
/>
))
TableBody.displayName = "TableBody"
const TableFooter = React.forwardRef<
HTMLTableSectionElement,
React.HTMLAttributes<HTMLTableSectionElement>
>(({ className, ...props }, ref) => (
<tfoot
ref={ref}
className={cn("bg-primary font-medium text-primary-foreground", className)}
{...props}
/>
))
TableFooter.displayName = "TableFooter"
const TableRow = React.forwardRef<
HTMLTableRowElement,
React.HTMLAttributes<HTMLTableRowElement>
>(({ className, ...props }, ref) => (
<tr
ref={ref}
className={cn(
"border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",
className
)}
{...props}
/>
))
TableRow.displayName = "TableRow"
const TableHead = React.forwardRef<
HTMLTableCellElement,
React.ThHTMLAttributes<HTMLTableCellElement>
>(({ className, ...props }, ref) => (
<th
ref={ref}
className={cn(
"h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",
className
)}
{...props}
/>
))
TableHead.displayName = "TableHead"
const TableCell = React.forwardRef<
HTMLTableCellElement,
React.TdHTMLAttributes<HTMLTableCellElement>
>(({ className, ...props }, ref) => (
<td
ref={ref}
className={cn("p-4 align-middle [&:has([role=checkbox])]:pr-0", className)}
{...props}
/>
))
TableCell.displayName = "TableCell"
const TableCaption = React.forwardRef<
HTMLTableCaptionElement,
React.HTMLAttributes<HTMLTableCaptionElement>
>(({ className, ...props }, ref) => (
<caption
ref={ref}
className={cn("mt-4 text-sm text-muted-foreground", className)}
{...props}
/>
))
TableCaption.displayName = "TableCaption"
export {
Table,
TableHeader,
TableBody,
TableFooter,
TableHead,
TableRow,
TableCell,
TableCaption,
}

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,48 @@
import { useState } from "react";
import { LocalAuthComponent } from "jazz-react-auth-local";
import { Input, Button } from "../basicComponents";
export const PrettyAuthUI: LocalAuthComponent = ({
loading,
logIn,
signUp,
}) => {
const [username, setUsername] = useState<string>("");
return (
<div className="w-full h-full flex items-center justify-center p-5">
{loading ? (
<div>Loading...</div>
) : (
<div className="w-72 flex flex-col gap-4">
<form
className="w-72 flex flex-col gap-2"
onSubmit={(e) => {
e.preventDefault();
signUp(username);
}}
>
<Input
placeholder="Display name"
value={username}
onChange={(e) => setUsername(e.target.value)}
autoComplete="webauthn"
className="text-base"
/>
<Button asChild>
<Input
type="submit"
value="Sign Up as new account"
/>
</Button>
</form>
<Button onClick={logIn}>
Log In with existing account
</Button>
</div>
)}
</div>
);
};

View File

@@ -0,0 +1,45 @@
import { useState } from "react";
import QRCode from "qrcode";
import { useToast, Button } from "../basicComponents";
import { CoValue } from "cojson";
import { Resolved, createInviteLink } from "jazz-react";
export function InviteButton<T extends CoValue>({ value }: { value?: Resolved<T> }) {
const [existingInviteLink, setExistingInviteLink] = useState<string>();
const { toast } = useToast();
return (
value?.meta.group?.myRole() === "admin" && (
<Button
size="sm"
className="py-0"
disabled={!value.meta.group || !value.id}
variant="outline"
onClick={async () => {
let inviteLink = existingInviteLink;
if (value.meta.group && value.id && !inviteLink) {
inviteLink = createInviteLink(value, "writer");
setExistingInviteLink(inviteLink);
}
if (inviteLink) {
const qr = await QRCode.toDataURL(inviteLink, {
errorCorrectionLevel: "L",
});
navigator.clipboard.writeText(inviteLink).then(() =>
toast({
title: "Copied invite link to clipboard!",
description: (
<img src={qr} className="w-20 h-20" />
),
})
);
}
}}
>
Invite
</Button>
)
);
}

View File

@@ -0,0 +1,76 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
:root {
--background: 0 0% 100%;
--foreground: 20 14.3% 4.1%;
--card: 0 0% 100%;
--card-foreground: 20 14.3% 4.1%;
--popover: 0 0% 100%;
--popover-foreground: 20 14.3% 4.1%;
--primary: 24 9.8% 10%;
--primary-foreground: 60 9.1% 97.8%;
--secondary: 60 4.8% 95.9%;
--secondary-foreground: 24 9.8% 10%;
--muted: 60 4.8% 95.9%;
--muted-foreground: 25 5.3% 44.7%;
--accent: 60 4.8% 95.9%;
--accent-foreground: 24 9.8% 10%;
--destructive: 0 84.2% 60.2%;
--destructive-foreground: 60 9.1% 97.8%;
--border: 20 5.9% 90%;
--input: 20 5.9% 90%;
--ring: 20 14.3% 4.1%;
--radius: 0.5rem;
}
.dark {
--background: 20 14.3% 4.1%;
--foreground: 60 9.1% 97.8%;
--card: 20 14.3% 4.1%;
--card-foreground: 60 9.1% 97.8%;
--popover: 20 14.3% 4.1%;
--popover-foreground: 60 9.1% 97.8%;
--primary: 60 9.1% 97.8%;
--primary-foreground: 24 9.8% 10%;
--secondary: 12 6.5% 15.1%;
--secondary-foreground: 60 9.1% 97.8%;
--muted: 12 6.5% 15.1%;
--muted-foreground: 24 5.4% 63.9%;
--accent: 12 6.5% 15.1%;
--accent-foreground: 60 9.1% 97.8%;
--destructive: 0 62.8% 30.6%;
--destructive-foreground: 60 9.1% 97.8%;
--border: 12 6.5% 15.1%;
--input: 12 6.5% 15.1%;
--ring: 24 5.7% 82.9%;
}
}
@layer base {
* {
@apply border-border;
}
body {
@apply bg-background text-foreground;
}
}

1
examples/file-drop/src/vite-env.d.ts vendored Normal file
View File

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

View File

@@ -0,0 +1,76 @@
/** @type {import('tailwindcss').Config} */
module.exports = {
darkMode: ["class"],
content: [
'./pages/**/*.{ts,tsx}',
'./components/**/*.{ts,tsx}',
'./app/**/*.{ts,tsx}',
'./src/**/*.{ts,tsx}',
],
theme: {
container: {
center: true,
padding: "2rem",
screens: {
"2xl": "1400px",
},
},
extend: {
colors: {
border: "hsl(var(--border))",
input: "hsl(var(--input))",
ring: "hsl(var(--ring))",
background: "hsl(var(--background))",
foreground: "hsl(var(--foreground))",
primary: {
DEFAULT: "hsl(var(--primary))",
foreground: "hsl(var(--primary-foreground))",
},
secondary: {
DEFAULT: "hsl(var(--secondary))",
foreground: "hsl(var(--secondary-foreground))",
},
destructive: {
DEFAULT: "hsl(var(--destructive))",
foreground: "hsl(var(--destructive-foreground))",
},
muted: {
DEFAULT: "hsl(var(--muted))",
foreground: "hsl(var(--muted-foreground))",
},
accent: {
DEFAULT: "hsl(var(--accent))",
foreground: "hsl(var(--accent-foreground))",
},
popover: {
DEFAULT: "hsl(var(--popover))",
foreground: "hsl(var(--popover-foreground))",
},
card: {
DEFAULT: "hsl(var(--card))",
foreground: "hsl(var(--card-foreground))",
},
},
borderRadius: {
lg: "var(--radius)",
md: "calc(var(--radius) - 2px)",
sm: "calc(var(--radius) - 4px)",
},
keyframes: {
"accordion-down": {
from: { height: 0 },
to: { height: "var(--radix-accordion-content-height)" },
},
"accordion-up": {
from: { height: "var(--radix-accordion-content-height)" },
to: { height: 0 },
},
},
animation: {
"accordion-down": "accordion-down 0.2s ease-out",
"accordion-up": "accordion-up 0.2s ease-out",
},
},
},
plugins: [require("tailwindcss-animate")],
}

View File

@@ -0,0 +1,29 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2023", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}
},
"include": ["src"],
"references": [{ "path": "./tsconfig.node.json" }]
}

View File

@@ -0,0 +1,10 @@
{
"compilerOptions": {
"composite": true,
"skipLibCheck": true,
"module": "ESNext",
"moduleResolution": "bundler",
"allowSyntheticDefaultImports": true
},
"include": ["vite.config.ts"]
}

View File

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

View File

@@ -1,7 +1,7 @@
{
"name": "jazz-example-pets",
"private": true,
"version": "0.0.15",
"version": "0.0.60",
"type": "module",
"scripts": {
"dev": "vite",
@@ -16,9 +16,9 @@
"@types/qrcode": "^1.5.1",
"class-variance-authority": "^0.7.0",
"clsx": "^2.0.0",
"jazz-browser-media-images": "^0.4.0",
"jazz-react": "^0.4.0",
"jazz-react-auth-local": "^0.4.0",
"jazz-browser-media-images": "^0.4.13",
"jazz-react": "^0.4.13",
"jazz-react-auth-local": "^0.4.13",
"lucide-react": "^0.274.0",
"qrcode": "^1.5.3",
"react": "^18.2.0",

View File

@@ -1,10 +1,6 @@
import React from "react";
import ReactDOM from "react-dom/client";
import {
Link,
RouterProvider,
createHashRouter,
} from "react-router-dom";
import { Link, RouterProvider, createHashRouter } from "react-router-dom";
import "./index.css";
import { WithJazz, useJazz, useAcceptInvite } from "jazz-react";
@@ -100,19 +96,19 @@ export function PostOverview() {
return (
<>
root: {JSON.stringify(me.root?.coMap.asObject())}
posts: {JSON.stringify(me.root?.posts?.coList?.asArray())}
<h1>My posts</h1>
{myPosts?.length
? myPosts.map(
(post) =>
post && (
<Link key={post.id} to={"/pet/" + post.id}>
{post.name}
</Link>
)
)
: undefined}
{myPosts?.length ? (
<>
<h1>My posts</h1>
{myPosts.map(
(post) =>
post && (
<Link key={post.id} to={"/pet/" + post.id}>
{post.name}
</Link>
)
)}
</>
) : undefined}
<Link to="/new">New post</Link>
</>
);

View File

@@ -2,7 +2,7 @@ import { ChangeEvent, useCallback, useState } from "react";
import { useNavigate } from "react-router";
import { CoID, CoMap, Media, Profile } from "cojson";
import { useJazz, useSyncedQuery } from "jazz-react";
import { useAutoSub, useJazz } from "jazz-react";
import { BrowserImage, createImage } from "jazz-browser-media-images";
import { PetAccountRoot, PetPost, PetReactions } from "./1_types";
@@ -26,7 +26,7 @@ export function NewPetPostForm() {
CoID<PartialPetPost> | undefined
>(undefined);
const newPetPost = useSyncedQuery(newPostId);
const newPetPost = useAutoSub(newPostId);
const onChangeName = useCallback(
(name: string) => {
@@ -51,7 +51,7 @@ export function NewPetPostForm() {
const image = await createImage(
event.target.files[0],
newPetPost.group
newPetPost.meta.group
);
newPetPost.set({ image: image.id });

View File

@@ -1,6 +1,5 @@
import { useParams } from "react-router";
import { CoID, Queried } from "cojson";
import { useSyncedQuery } from "jazz-react";
import { CoID } from "cojson";
import { PetPost, ReactionType, REACTION_TYPES, PetReactions } from "./1_types";
@@ -8,6 +7,7 @@ import { ShareButton } from "./components/ShareButton";
import { Button, Skeleton } from "./basicComponents";
import { BrowserImage } from "jazz-browser-media-images";
import uniqolor from "uniqolor";
import { Resolved, useAutoSub } from "jazz-react";
/** Walkthrough: TODO
*/
@@ -24,7 +24,7 @@ const reactionEmojiMap: { [reaction in ReactionType]: string } = {
export function RatePetPostUI() {
const petPostID = useParams<{ petPostId: CoID<PetPost> }>().petPostId;
const petPost = useSyncedQuery(petPostID);
const petPost = useAutoSub(petPostID);
return (
<div className="flex flex-col gap-8">
@@ -63,7 +63,7 @@ export function RatePetPostUI() {
))}
</div>
{petPost?.group.myRole() === "admin" && petPost.reactions && (
{petPost?.meta.group.myRole() === "admin" && petPost.reactions && (
<ReactionOverview petReactions={petPost.reactions} />
)}
</div>
@@ -73,16 +73,16 @@ export function RatePetPostUI() {
function ReactionOverview({
petReactions,
}: {
petReactions: Queried<PetReactions>;
petReactions: Resolved<PetReactions>;
}) {
return (
<div>
<h2>Reactions</h2>
<div className="flex flex-col gap-1">
{REACTION_TYPES.map((reactionType) => {
const reactionsOfThisType = Object.values(
petReactions.perAccount
).filter(({ last }) => last === reactionType);
const reactionsOfThisType = petReactions.perAccount
.map(([, reaction]) => reaction)
.filter(({ last }) => last === reactionType);
if (reactionsOfThisType.length === 0) return null;

View File

@@ -2,18 +2,17 @@ import { useState } from "react";
import { PetPost } from "../1_types";
import { createInviteLink } from "jazz-react";
import { Resolved, createInviteLink } from "jazz-react";
import QRCode from "qrcode";
import { useToast, Button } from "../basicComponents";
import { Queried } from "cojson";
export function ShareButton({ petPost }: { petPost?: Queried<PetPost> }) {
export function ShareButton({ petPost }: { petPost?: Resolved<PetPost> }) {
const [existingInviteLink, setExistingInviteLink] = useState<string>();
const { toast } = useToast();
return (
petPost?.group.myRole() === "admin" && (
petPost?.meta.group.myRole() === "admin" && (
<Button
size="sm"
className="py-0"

View File

@@ -1,7 +1,7 @@
{
"name": "jazz-example-todo",
"private": true,
"version": "0.0.40",
"version": "0.0.60",
"type": "module",
"scripts": {
"dev": "vite",
@@ -16,8 +16,8 @@
"@types/qrcode": "^1.5.1",
"class-variance-authority": "^0.7.0",
"clsx": "^2.0.0",
"jazz-react": "^0.4.0",
"jazz-react-auth-local": "^0.4.0",
"jazz-react": "^0.4.13",
"jazz-react-auth-local": "^0.4.13",
"lucide-react": "^0.274.0",
"qrcode": "^1.5.3",
"react": "^18.2.0",

View File

@@ -1,6 +1,10 @@
import React from "react";
import ReactDOM from "react-dom/client";
import { RouterProvider, createHashRouter } from "react-router-dom";
import {
RouterProvider,
createHashRouter,
useNavigate,
} from "react-router-dom";
import "./index.css";
import { WithJazz, useJazz, useAcceptInvite } from "jazz-react";
@@ -14,8 +18,8 @@ import {
import { PrettyAuthUI } from "./components/Auth.tsx";
import { NewProjectForm } from "./3_NewProjectForm.tsx";
import { ProjectTodoTable } from "./4_ProjectTodoTable.tsx";
import { migration } from "./1_types.ts";
import { AccountMigration } from "cojson";
import { TodoAccountRoot, migration } from "./1_types.ts";
import { AccountMigration, Profile } from "cojson";
/**
* Walkthrough: The top-level provider `<WithJazz/>`
@@ -61,7 +65,7 @@ function App() {
const router = createHashRouter([
{
path: "/",
element: <NewProjectForm />,
element: <HomeScreen />,
},
{
path: "/project/:projectId",
@@ -91,4 +95,27 @@ function App() {
);
}
export function HomeScreen() {
const { me } = useJazz<Profile, TodoAccountRoot>();
const navigate = useNavigate();
return (
<>
{me.root?.projects?.length ? <h1>My Projects</h1> : null}
{me.root?.projects?.map((project) => {
return (
<Button
key={project?.id}
onClick={() => navigate("/project/" + project?.id)}
variant="ghost"
>
{project?.title}
</Button>
);
})}
<NewProjectForm />
</>
);
}
/** Walkthrough: Continue with ./3_NewProjectForm.tsx */

View File

@@ -2,17 +2,17 @@ import { useCallback } from "react";
import { useJazz } from "jazz-react";
import { ListOfTasks, TodoProject } from "./1_types";
import { ListOfTasks, TodoAccountRoot, TodoProject } from "./1_types";
import { SubmittableInput } from "./basicComponents";
import { useNavigate } from "react-router";
import { Profile } from "cojson";
export function NewProjectForm() {
// A `LocalNode` represents a local view of loaded & created CoValues.
// It is associated with a current user account, which will determine
// `me` represents the current user account, which will determine
// access rights to CoValues. We get it from the top-level provider `<WithJazz/>`.
const { localNode } = useJazz();
const { me } = useJazz<Profile, TodoAccountRoot>();
const navigate = useNavigate();
const createProject = useCallback(
@@ -22,7 +22,7 @@ export function NewProjectForm() {
// To create a new todo project, we first create a `Group`,
// which is a scope for defining access rights (reader/writer/admin)
// of its members, which will apply to all CoValues owned by that group.
const projectGroup = localNode.createGroup();
const projectGroup = me.createGroup();
// Then we create an empty todo project within that group
const project = projectGroup.createMap<TodoProject>({
@@ -30,9 +30,11 @@ export function NewProjectForm() {
tasks: projectGroup.createList<ListOfTasks>().id,
});
me.root?.projects?.append(project.id);
navigate("/project/" + project.id);
},
[localNode, navigate]
[me, navigate]
);
return (

View File

@@ -1,7 +1,6 @@
import { useCallback } from "react";
import { CoID, Queried } from "cojson";
import { useSyncedQuery } from "jazz-react";
import { CoID } from "cojson";
import { TodoProject, Task } from "./1_types";
@@ -20,11 +19,12 @@ import {
import { InviteButton } from "./components/InviteButton";
import uniqolor from "uniqolor";
import { useParams } from "react-router";
import { Resolved, useAutoSub } from "jazz-react";
/** Walkthrough: Reactively rendering a todo project as a table,
* adding and editing tasks
*
* Here in `<TodoTable/>`, we use `useSyncedQuery()` for the first time,
* Here in `<TodoTable/>`, we use `useAutoSub()` for the first time,
* in this case to load the CoValue for our `TodoProject` as well as
* the `ListOfTasks` referenced in it.
*/
@@ -32,11 +32,11 @@ import { useParams } from "react-router";
export function ProjectTodoTable() {
const projectId = useParams<{ projectId: CoID<TodoProject> }>().projectId;
// `useSyncedQuery()` reactively subscribes to updates to a CoValue's
// `useAutoSub()` reactively subscribes to updates to a CoValue's
// content - whether we create edits locally, load persisted data, or receive
// sync updates from other devices or participants!
// It also recursively resolves and subsribes to all referenced CoValues.
const project = useSyncedQuery(projectId);
const project = useAutoSub(projectId);
// `createTask` is similar to `createProject` we saw earlier, creating a new CoMap
// for a new task (in the same group as the project), and then
@@ -44,17 +44,17 @@ export function ProjectTodoTable() {
const createTask = useCallback(
(text: string) => {
if (!project?.tasks || !text) return;
const task = project.group.createMap<Task>({
const task = project.meta.group.createMap<Task>({
done: false,
text,
});
// project.tasks is immutable, but `append` will create an edit
// that will cause useSyncedQuery to rerender this component
// that will cause useAutoSub to rerender this component
// - here and on other devices!
project.tasks.append(task.id);
},
[project?.tasks, project?.group]
[project?.tasks, project?.meta.group]
);
return (
@@ -97,7 +97,7 @@ export function ProjectTodoTable() {
);
}
export function TaskRow({ task }: { task: Queried<Task> | undefined }) {
export function TaskRow({ task }: { task: Resolved<Task> | undefined }) {
return (
<TableRow>
<TableCell>
@@ -124,12 +124,12 @@ export function TaskRow({ task }: { task: Queried<Task> | undefined }) {
{
// Here we see for the first time how we can access edit history
// for a CoValue, and use it to display who created the task.
task?.edits.text?.by?.profile?.name ? (
task?.meta.edits.text?.by?.profile?.name ? (
<span
className="rounded-full py-0.5 px-2 text-xs"
style={uniqueColoring(task.edits.text.by.id)}
style={uniqueColoring(task.meta.edits.text.by.id)}
>
{task.edits.text.by.profile.name}
{task.meta.edits.text.by.profile.name}
</span>
) : (
<Skeleton className="mt-1 w-[50px] h-[1em] rounded-full" />

View File

@@ -1,25 +1,25 @@
import { useState } from "react";
import { createInviteLink } from "jazz-react";
import QRCode from "qrcode";
import { useToast, Button } from "../basicComponents";
import { CoValue, Queried } from "cojson";
import { CoValue } from "cojson";
import { Resolved, createInviteLink } from "jazz-react";
export function InviteButton<T extends CoValue>({ value }: { value: T | Queried<T> | undefined }) {
export function InviteButton<T extends CoValue>({ value }: { value?: Resolved<T> }) {
const [existingInviteLink, setExistingInviteLink] = useState<string>();
const { toast } = useToast();
return (
value?.group?.myRole() === "admin" && (
value?.meta.group?.myRole() === "admin" && (
<Button
size="sm"
className="py-0"
disabled={!value.group || !value.id}
disabled={!value.meta.group || !value.id}
variant="outline"
onClick={async () => {
let inviteLink = existingInviteLink;
if (value.group && value.id && !inviteLink) {
if (value.meta.group && value.id && !inviteLink) {
inviteLink = createInviteLink(value, "writer");
setExistingInviteLink(inviteLink);
}

View File

@@ -4,7 +4,7 @@
<meta charset="UTF-8" />
<link rel="icon" type="image/png" href="/jazz-logo.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Jazz Todo List Example</title>
<title>Twit</title>
</head>
<body>
<div id="root"></div>

View File

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

View File

@@ -1,7 +1,7 @@
{
"name": "jazz-example-twit",
"private": true,
"version": "0.0.2",
"version": "0.0.60",
"type": "module",
"scripts": {
"dev": "vite",
@@ -11,15 +11,16 @@
},
"dependencies": {
"@radix-ui/react-checkbox": "^1.0.4",
"@radix-ui/react-popover": "^1.0.7",
"@radix-ui/react-slot": "^1.0.2",
"@radix-ui/react-toast": "^1.1.4",
"@types/qrcode": "^1.5.1",
"class-variance-authority": "^0.7.0",
"clsx": "^2.0.0",
"javascript-time-ago": "^2.5.9",
"jazz-browser-media-images": "^0.4.0",
"jazz-react": "^0.4.0",
"jazz-react-auth-local": "^0.4.0",
"jazz-browser-media-images": "^0.4.13",
"jazz-react": "^0.4.13",
"jazz-react-auth-local": "^0.4.13",
"lucide-react": "^0.274.0",
"qrcode": "^1.5.3",
"react": "^18.2.0",

View File

@@ -1,34 +1,31 @@
import { CoMap, CoList, Media, CoStream, Group, ProfileMeta, AccountMigration, EVERYONE } from 'cojson';
import { CoMap, CoList, Media, CoStream, Group, AccountMigration, EVERYONE, Profile } from 'cojson';
export type Twit = CoMap<{
text?: string;
images?: ListOfImages['id'];
likes: LikeStream['id'];
quotedPost?: Twit['id'];
replies: ReplyStream['id'];
isRepostedIn: RepostedInStream['id'];
isReplyTo?: Twit['id'];
}>;
export type ListOfImages = CoList<Media.ImageDefinition['id']>;
export type LikeStream = CoStream<'❤️' | null>;
export type ReplyStream = CoStream<Twit['id']>;
export type RepostedInStream = CoStream<Twit['id']>;
export type ListOfTwits = CoList<Twit['id']>;
export type ListOfProfiles = CoList<TwitProfile['id']>;
export type StreamOfFollowers = CoStream<TwitProfile['id'] | null>;
export type TwitProfile = CoMap<
export type TwitProfile = Profile<
{
name: string;
bio: string;
avatar?: Media.ImageDefinition['id'];
twits: ListOfTwits['id'];
following: ListOfProfiles['id'];
followers: ListOfProfiles['id'];
followers: StreamOfFollowers['id'];
twitStyle?: { fontFamily: string; color: string };
},
ProfileMeta
}
>;
export type TwitAccountRoot = CoMap<{
@@ -61,7 +58,7 @@ export const migration: AccountMigration<TwitProfile, TwitAccountRoot> = (accoun
profile.set('twits', peopleWhoCanSeeMyTwits.createList<ListOfTwits>().id, 'trusting');
profile.set('following', peopleWhoCanSeeMyFollows.createList<ListOfProfiles>().id, 'trusting');
profile.set('followers', peopleWhoCanFollowMe.createList<ListOfProfiles>().id, 'trusting');
profile.set('followers', peopleWhoCanFollowMe.createStream<StreamOfFollowers>().id, 'trusting');
console.log('MIGRATION SUCCESSFUL!');
}
};

View File

@@ -1,49 +1,18 @@
import React, { useCallback, useEffect, useMemo } from 'react';
import React from 'react';
import ReactDOM from 'react-dom/client';
import { Link, RouterProvider, createHashRouter, useParams } from 'react-router-dom';
import { RouterProvider, createHashRouter } from 'react-router-dom';
import './index.css';
import { WithJazz, useJazz, useSyncedQuery } from 'jazz-react';
import { AccountMigration } from 'cojson';
import { WithJazz, useJazz } from 'jazz-react';
import { LocalAuth } from 'jazz-react-auth-local';
import {
AddTwitPicsInput,
BioInput,
Button,
ButtonWithCount,
ChooseProfilePicInput,
FollowerStatsContainer,
LargeProfilePicImg,
ProfileName,
ProfilePicImg,
ProfileTitleContainer,
ReactionsAndReplyContainer,
ReactionsContainer,
RepliesContainer,
SubtleProfileID,
SubtleRelativeTimeAgo,
ThemeProvider,
TitleAndLogo,
TwitImg,
TwitTextInput
} from './basicComponents/index.tsx';
import { Button, ThemeProvider, TitleAndLogo } from './basicComponents/index.tsx';
import { PrettyAuthUI } from './components/Auth.tsx';
import {
LikeStream,
ListOfImages,
ReplyStream,
RepostedInStream,
Twit,
TwitAccountRoot,
TwitProfile,
migration
} from './1_types.ts';
import { AccountMigration, CoID, Queried } from 'cojson';
import { BrowserImage, createImage } from 'jazz-browser-media-images';
import TimeAgo from 'javascript-time-ago';
import en from 'javascript-time-ago/locale/en.json';
import { HeartIcon, MessagesSquareIcon } from 'lucide-react';
TimeAgo.addDefaultLocale(en);
import { migration } from './1_dataModel.ts';
import { ChronoFeed } from './3_ChronoFeed.tsx';
import { ProfilePage } from './5_ProfilePage.tsx';
const appName = 'Jazz Twit Example';
@@ -65,30 +34,21 @@ ReactDOM.createRoot(document.getElementById('root')!).render(
</React.StrictMode>
);
/**
* Routing in `<App/>`
*
* <App> is the main app component, handling client-side routing based
* on the CoValue ID (CoID) of our TodoProject, stored in the URL hash
* - which can also contain invite links.
*/
function App() {
// logOut logs out the AuthProvider passed to `<WithJazz/>` above.
const { logOut } = useJazz();
const { me, logOut } = useJazz();
const router = createHashRouter([
{
path: '/',
element: <ChronoFeedUI />
},
{
path: '/me',
element: <MyProfile />
element: <ChronoFeed />
},
{
path: '/:profileId',
element: <UserProfile />
element: <ProfilePage />
},
{
path: '/me',
loader: () => router.navigate('/' + me.profile?.id)
}
]);
@@ -109,283 +69,3 @@ function App() {
</>
);
}
export function MyProfile() {
const { me } = useJazz<TwitProfile, TwitAccountRoot>();
return me.profile && <ProfileUI profileId={me.profile.id} />;
}
export function UserProfile() {
const { profileId } = useParams<{ profileId: CoID<TwitProfile> }>();
return profileId && <ProfileUI profileId={profileId} />;
}
export function ProfileUI({ profileId }: { profileId: CoID<TwitProfile> }) {
const { me } = useJazz<TwitProfile, TwitAccountRoot>();
const profile = useSyncedQuery(profileId);
const isMe = profile?.id == me.profile?.id;
const profileTwitsAndRepliedToTwits = useMemo(() => {
return profile?.twits?.map((twit, _, allTwits) =>
twit?.isReplyTo
? allTwits.some(
tw =>
tw?.id === twit?.isReplyTo?.id ||
tw?.id === twit?.isReplyTo?.isReplyTo?.id ||
tw?.id === twit?.isReplyTo?.isReplyTo?.isReplyTo?.id
)
? null
: twit?.isReplyTo
: twit
);
}, [profile?.twits]);
return (
<div>
<div className="py-2 mb-5 flex gap-2">
<div className="flex flex-col items-stretch">
<LargeProfilePicImg src={profile?.avatar?.as(BrowserImage)?.highestResSrcOrPlaceholder} />
{isMe && (
<ChooseProfilePicInput
onChange={(file: File) =>
me.root?.peopleWhoCanSeeMyTwits &&
createImage(file, me.root.peopleWhoCanSeeMyTwits.group, 256).then(image => {
me.profile?.set({ avatar: image.id }, 'trusting');
})
}
/>
)}
</div>
<div className="grow">
<ProfileTitleContainer>
<ProfileName>{profile?.name}</ProfileName>
<div className="ml-2 text-neutral-300 text-xs">{profile?.id}</div>
{!isMe && (
<Button
onClick={() => {
if (!profile?.followers || !me.profile?.following) return;
if (profile.followers.some(f => f?.id === me.profile?.id)) {
me.profile.following.append(profile.id);
profile.followers.append(me.profile.id);
} else {
me.profile.following.delete(me.profile.following.findIndex(f => f?.id === profile.id));
profile.followers.delete(profile.followers.findIndex(f => f?.id === me.profile?.id));
}
}}
className="ml-auto"
>
{profile?.followers?.some(f => f?.id === me.profile?.id) ? 'Unfollow' : 'Follow'}
</Button>
)}
</ProfileTitleContainer>
<div>
{isMe ? (
<BioInput
value={profile?.bio}
onChange={newBio => {
profile?.set({ bio: newBio }, 'trusting');
// prettier-ignore
if (newBio.startsWith('{')) {profile?.set('twitStyle', JSON.parse(newBio), 'trusting');} else {profile?.set('twitStyle', undefined, 'trusting');}
}}
/>
) : (
profile?.bio || '(No bio)'
)}
</div>
<FollowerStatsContainer>
{new Set(profile?.followers || []).size} Followers &mdash; {new Set(profile?.following || []).size}{' '}
Following
</FollowerStatsContainer>
</div>
</div>
{isMe && <CreateTwitForm className="mb-4" />}
{profileTwitsAndRepliedToTwits?.map(twit => twit && <TwitUI twit={twit} key={twit?.id} />)}
</div>
);
}
export function TwitUI({
twit,
alreadyInReplies: alreadyInReplies
}: {
twit?: Queried<Twit>;
alreadyInReplies?: boolean;
}) {
const [showReplyForm, setShowReplyForm] = React.useState(false);
const posterProfile = twit?.edits.text?.by?.profile as Queried<TwitProfile> | undefined;
return (
<div
className={'py-2 flex flex-col items-stretch' + (twit?.isReplyTo && !alreadyInReplies ? ' ml-14' : ' border-t')}
>
<div className="flex gap-2">
<ProfilePicImg
src={posterProfile?.avatar?.as(BrowserImage)?.highestResSrcOrPlaceholder}
smaller={!!twit?.isReplyTo}
/>
<div className="grow flex flex-col items-stretch">
<div className="flex items-baseline">
{posterProfile && (
<Link to={'/' + posterProfile.id} className="font-bold">
{posterProfile.name}
</Link>
)}
<SubtleProfileID>{posterProfile?.id}</SubtleProfileID>
<SubtleRelativeTimeAgo dateTime={twit?.edits.text?.at} />
</div>
<div style={posterProfile?.twitStyle}>{twit?.text}</div>
{twit?.quotedPost && (
<div className="border rounded">
<TwitUI twit={twit.quotedPost} />
</div>
)}
{twit?.images && (
<div className="flex gap-2 mt-2 max-w-full overflow-auto">
{twit.images.map(image => (
<TwitImg src={image?.as(BrowserImage)?.highestResSrcOrPlaceholder} key={image?.id} />
))}
</div>
)}
<ReactionsAndReplyContainer>
<ReactionsContainer>
<ButtonWithCount
active={twit?.likes?.me?.last === '❤️'}
onClick={() => twit?.likes?.push(twit?.likes?.me?.last ? null : '❤️')}
count={Object.values(twit?.likes?.perAccount || {}).filter(byAccount => byAccount.last === '❤️').length}
icon={<HeartIcon size="18" />}
activeIcon={<HeartIcon color="red" size="18" fill="red" />}
/>
<ButtonWithCount
onClick={() => setShowReplyForm(s => !s)}
count={Object.values(twit?.replies?.perSession || {}).flatMap(perSession => perSession.all).length}
icon={<MessagesSquareIcon size="18" />}
/>
</ReactionsContainer>
</ReactionsAndReplyContainer>
{showReplyForm && (
<CreateTwitForm inReplyTo={twit} onSubmit={() => setShowReplyForm(false)} className="mt-5" />
)}
</div>
</div>
<RepliesContainer>
{Object.values(twit?.replies?.perAccount || {})
.flatMap(byAccount => byAccount.all)
.sort((a, b) => b.at.getTime() - a.at.getTime())
.map(replyEntry => (
<TwitUI twit={replyEntry.value} key={replyEntry.value?.id} alreadyInReplies={!!twit?.isReplyTo} />
))}
</RepliesContainer>
</div>
);
}
export function ChronoFeedUI() {
const { me } = useJazz<TwitProfile, TwitAccountRoot>();
const myTwits = me.profile?.twits;
const twitsFromFollows = useMemo(
() => me.profile?.following?.flatMap(follow => follow?.twits || []) || [],
[me.profile?.following]
);
const allTwitsSorted = useMemo(
() =>
[...(myTwits || []), ...twitsFromFollows]
.flatMap(tw => (tw ? (tw.isReplyTo ? [] : tw) : []))
.sort((a, b) => (b.edits.text?.at?.getTime() || 0) - (a.edits.text?.at?.getTime() || 0)),
[myTwits, twitsFromFollows]
);
return (
<div className="flex flex-col items-stretch">
<CreateTwitForm className="mb-10" />
<h1 className="text-2xl mb-4">From people you follow</h1>
{allTwitsSorted?.map(twit => (
<TwitUI twit={twit} key={twit.id} />
))}
</div>
);
}
export function CreateTwitForm(
props: {
inReplyTo?: Queried<Twit>;
onSubmit?: () => void;
className?: string;
} = {}
) {
const { me } = useJazz<TwitProfile, TwitAccountRoot>();
const [pics, setPics] = React.useState<File[]>([]);
const onSubmit = useCallback(
(twitText: string) => {
const audience = me.root?.peopleWhoCanSeeMyTwits;
const interactors = me.root?.peopleWhoCanInteractWithMe;
if (!audience || !interactors) return;
const images = pics.length ? audience.createList<ListOfImages>() : undefined;
const twit = audience.createMap<Twit>({
text: twitText,
likes: interactors.createStream<LikeStream>().id,
replies: interactors.createStream<ReplyStream>().id,
isRepostedIn: interactors.createStream<RepostedInStream>().id,
images: images?.id
});
me.profile?.twits?.prepend(twit?.id as Twit['id']);
if (props.inReplyTo) {
props.inReplyTo.replies?.push(twit.id);
twit.set({ isReplyTo: props.inReplyTo.id });
}
pics.forEach(pic => {
createImage(pic, twit.group, 1024).then(image => {
images!.append(image.id);
});
});
setPics([]);
props.onSubmit?.();
},
[me.profile?.twits, me.root?.peopleWhoCanSeeMyTwits, me.root?.peopleWhoCanInteractWithMe, props, pics]
);
const [picPreviews, setPicPreviews] = React.useState<string[]>([]);
useEffect(() => {
const previews = pics.map(pic => URL.createObjectURL(pic));
setPicPreviews(previews);
return () => previews.forEach(preview => URL.revokeObjectURL(preview));
}, [pics]);
return (
<div className={props.className}>
<TwitTextInput onSubmit={onSubmit} submitButtonLabel={props.inReplyTo ? 'Reply!' : 'Twit!'} />
{picPreviews.length ? (
<div className="flex gap-2 mt-2">
{picPreviews.map(preview => (
<TwitImg src={preview} />
))}
</div>
) : (
<AddTwitPicsInput
onChange={(newPics: File[]) => {
setPics(newPics);
}}
/>
)}
</div>
);
}

View File

@@ -0,0 +1,35 @@
import { useMemo } from 'react';
import { useJazz } from 'jazz-react';
import { TwitAccountRoot, TwitProfile } from './1_dataModel.ts';
import { CreateTwitForm } from './6_CreateTwitForm.tsx';
import { TwitComponent } from './4_TwitComponent.tsx';
import { MainH1 } from './basicComponents/index.tsx';
export function ChronoFeed() {
const { me } = useJazz<TwitProfile, TwitAccountRoot>();
const myTwits = me.profile?.twits;
const twitsFromFollows = useMemo(
() => me.profile?.following?.flatMap(follow => follow?.twits || []) || [],
[me.profile?.following]
);
const allTwitsSorted = useMemo(
() =>
[...(myTwits || []), ...twitsFromFollows]
.flatMap(tw => (tw ? (tw.isReplyTo ? [] : tw) : []))
.sort((a, b) => (b.meta.edits.text?.at?.getTime() || 0) - (a.meta.edits.text?.at?.getTime() || 0)),
[myTwits, twitsFromFollows]
);
return (
<div className="flex flex-col items-stretch">
<CreateTwitForm className="mb-10" />
<MainH1>From people you follow</MainH1>
{allTwitsSorted?.map(twit => (
<TwitComponent twit={twit} key={twit.id} />
))}
</div>
);
}

View File

@@ -0,0 +1,101 @@
import React from 'react';
import { Link } from 'react-router-dom';
import {
ButtonWithCount,
ProfilePicImg,
ReactionsContainer,
RepliesContainer,
SubtleRelativeTimeAgo,
TwitContainer,
TwitWithRepliesContainer,
TwitImg,
TwitImgGallery,
TwitHeader,
TwitBody,
TwitText,
} from './basicComponents/index.tsx';
import { Twit, TwitProfile } from './1_dataModel.ts';
import { BrowserImage } from 'jazz-browser-media-images';
import { HeartIcon, MessagesSquareIcon } from 'lucide-react';
import { CreateTwitForm } from './6_CreateTwitForm.tsx';
import { Resolved } from 'jazz-react';
export function TwitComponent({
twit,
alreadyInReplies: alreadyInReplies
}: {
twit?: Resolved<Twit>;
alreadyInReplies?: boolean;
}) {
const [showReplyForm, setShowReplyForm] = React.useState(false);
const posterProfile = twit?.meta.edits.text?.by?.profile as Resolved<TwitProfile> | undefined;
const isTopLevel = !twit?.isReplyTo || alreadyInReplies;
return (
<TwitWithRepliesContainer isTopLevel={isTopLevel}>
<TwitContainer>
<ProfilePicImg
src={posterProfile?.avatar?.as(BrowserImage)?.highestResSrcOrPlaceholder}
linkTo={'/' + posterProfile?.id}
initial={posterProfile?.name[0]}
size={twit?.isReplyTo && "sm"}
/>
<TwitBody>
<TwitHeader>
<Link to={'/' + posterProfile?.id} className="font-bold hover:underline">
{posterProfile?.name}
</Link>
<SubtleRelativeTimeAgo dateTime={twit?.meta.edits.text?.at} />
</TwitHeader>
<TwitText style={posterProfile?.twitStyle}>
{/* This is where the tweet text goes */}
{twit?.text}
</TwitText>
{twit?.images && (
<TwitImgGallery>
{twit.images.map(image => (
<TwitImg src={image?.as(BrowserImage)?.highestResSrcOrPlaceholder} key={image?.id} />
))}
</TwitImgGallery>
)}
<ReactionsContainer>
<ButtonWithCount
active={twit?.likes?.me?.last === '❤️'}
onClick={() => twit?.likes?.push(twit?.likes?.me?.last ? null : '❤️')}
count={twit?.likes?.perAccount.filter(([, liked]) => liked.last === '❤️').length || 0}
icon={<HeartIcon size="18" />}
activeIcon={<HeartIcon color="red" size="18" fill="red" />}
/>
<ButtonWithCount
onClick={() => setShowReplyForm(s => !s)}
count={twit?.replies?.perAccount.flatMap(([, byAccount]) => byAccount.all).length || 0}
icon={<MessagesSquareIcon size="18" />}
/>
</ReactionsContainer>
</TwitBody>
</TwitContainer>
<RepliesContainer>
{showReplyForm && (
<CreateTwitForm
inReplyTo={twit}
onSubmit={() => setShowReplyForm(false)}
className={'mt-5 ' + (isTopLevel ? 'ml-14' : 'ml-12')}
/>
)}
{twit?.replies?.perAccount
.flatMap(([, byAccount]) => byAccount.all)
.sort((a, b) => b.at.getTime() - a.at.getTime())
.map(replyEntry => (
<TwitComponent twit={replyEntry.value} key={replyEntry.value?.id} alreadyInReplies={!!twit?.isReplyTo} />
))}
</RepliesContainer>
</TwitWithRepliesContainer>
);
}

View File

@@ -0,0 +1,127 @@
import { useEffect, useMemo, useState } from 'react';
import { useParams } from 'react-router-dom';
import { useJazz, useAutoSub } from 'jazz-react';
import QRCode from 'qrcode';
import {
BioInput,
ChooseProfilePicInput,
FollowerStatsContainer,
Popover,
ProfileName,
ProfilePicImg,
ProfileTitleContainer,
SmallInlineButton
} from './basicComponents/index.tsx';
import { TwitAccountRoot, TwitProfile } from './1_dataModel.ts';
import { CoID } from 'cojson';
import { BrowserImage, createImage } from 'jazz-browser-media-images';
import { FollowButton, FollowerList, FollowingList } from './7_FollowStuff.tsx';
import { CreateTwitForm } from './6_CreateTwitForm.tsx';
import { TwitComponent } from './4_TwitComponent.tsx';
import { PopoverContent, PopoverTrigger } from '@radix-ui/react-popover';
export function ProfilePage() {
const { profileId } = useParams<{ profileId: CoID<TwitProfile> }>();
const { me } = useJazz<TwitProfile, TwitAccountRoot>();
const profile = useAutoSub(profileId);
const isMe = profile?.id == me.profile?.id;
const profileTwitsAndRepliedToTwits = useMemo(() => {
return profile?.twits?.map((twit, _, allTwits) =>
twit?.isReplyTo
? allTwits.some(
tw =>
tw?.id === twit?.isReplyTo?.id ||
tw?.id === twit?.isReplyTo?.isReplyTo?.id ||
tw?.id === twit?.isReplyTo?.isReplyTo?.isReplyTo?.id
)
? null
: twit?.isReplyTo
: twit
);
}, [profile?.twits]);
const [qr, setQr] = useState<string>('');
useEffect(() => {
QRCode.toDataURL(
window.location.protocol + '//' + window.location.host + window.location.pathname + '#/' + profile?.id,
{
errorCorrectionLevel: 'L'
}
).then(setQr);
}, [profile?.id]);
return (
<div>
<div className="py-2 mb-5 flex gap-4">
<div className="flex flex-col items-stretch">
<ProfilePicImg
src={profile?.avatar?.as(BrowserImage)?.highestResSrcOrPlaceholder}
initial={profile?.name[0]}
size="xxl"
/>
{isMe && (
<ChooseProfilePicInput
onChange={(file: File) =>
me.root?.peopleWhoCanSeeMyTwits &&
createImage(file, me.root.peopleWhoCanSeeMyTwits, 256).then(image => {
me.profile?.set({ avatar: image.id }, 'trusting');
})
}
/>
)}
</div>
<div className="grow">
<ProfileTitleContainer>
<ProfileName>{profile?.name}</ProfileName>
{!isMe && <FollowButton profile={profile} />}
</ProfileTitleContainer>
<div>
{isMe ? (
<BioInput
value={profile?.bio}
onChange={newBio => {
profile?.set({ bio: newBio }, 'trusting');
// prettier-ignore
if (newBio.startsWith('{')) { profile?.set('twitStyle', JSON.parse(newBio), 'trusting'); } else { profile?.set('twitStyle', undefined, 'trusting'); }
}}
/>
) : (
profile?.bio || '(No bio)'
)}
</div>
<FollowerStatsContainer>
<Popover>
<PopoverTrigger>
<SmallInlineButton>
{profile?.followers?.perAccount?.filter(([, status]) => status.last).length} Followers
</SmallInlineButton>
</PopoverTrigger>
<PopoverContent>
<FollowerList profile={profile} />
</PopoverContent>
</Popover>
<span className="hidden md:block">&mdash;</span> <br className="md:hidden" />
<Popover>
<PopoverTrigger>
<SmallInlineButton>{new Set(profile?.following || []).size} Following</SmallInlineButton>
</PopoverTrigger>
<PopoverContent>
<FollowingList profile={profile} />
</PopoverContent>
</Popover>
</FollowerStatsContainer>
</div>
{isMe && <img src={qr} className="rounded w-28 h-28 -mr-3 dark:invert max-sm:w-16 max-sm:h-16" />}
</div>
{isMe && <CreateTwitForm className="mb-4" />}
{profileTwitsAndRepliedToTwits?.map(twit => twit && <TwitComponent twit={twit} key={twit?.id} />)}
</div>
);
}

View File

@@ -0,0 +1,73 @@
import React, { useCallback, useEffect } from 'react';
import { Resolved, useJazz } from 'jazz-react';
import { AddTwitPicsInput, TwitImg, TwitTextInput } from './basicComponents/index.tsx';
import { LikeStream, ListOfImages, ReplyStream, Twit, TwitAccountRoot, TwitProfile } from './1_dataModel.ts';
import { createImage } from 'jazz-browser-media-images';
export function CreateTwitForm(
props: {
inReplyTo?: Resolved<Twit>;
onSubmit?: () => void;
className?: string;
} = {}
) {
const { me } = useJazz<TwitProfile, TwitAccountRoot>();
const [pics, setPics] = React.useState<File[]>([]);
const onSubmit = useCallback(
(twitText: string) => {
const audience = me.root?.peopleWhoCanSeeMyTwits;
const interactors = me.root?.peopleWhoCanInteractWithMe;
if (!audience || !interactors) return;
const twit = audience.createMap<Twit>({
text: twitText,
likes: interactors.createStream<LikeStream>().id,
replies: interactors.createStream<ReplyStream>().id
});
me.profile?.twits?.prepend(twit?.id as Twit['id']);
if (props.inReplyTo) {
props.inReplyTo.replies?.push(twit.id);
twit.set({ isReplyTo: props.inReplyTo.id });
}
Promise.all(pics.map(pic => createImage(pic, twit.group, 1024))).then(createdPics => {
twit.set({ images: audience.createList<ListOfImages>(createdPics.map(pic => pic.id)).id });
});
setPics([]);
props.onSubmit?.();
},
[me.profile?.twits, me.root?.peopleWhoCanSeeMyTwits, me.root?.peopleWhoCanInteractWithMe, props, pics]
);
const [picPreviews, setPicPreviews] = React.useState<string[]>([]);
useEffect(() => {
const previews = pics.map(pic => URL.createObjectURL(pic));
setPicPreviews(previews);
return () => previews.forEach(preview => URL.revokeObjectURL(preview));
}, [pics]);
return (
<div className={props.className}>
<TwitTextInput onSubmit={onSubmit} submitButtonLabel={props.inReplyTo ? 'Reply!' : 'Twit!'} />
{picPreviews.length ? (
<div className="flex gap-2 mt-2">
{picPreviews.map(preview => (
<TwitImg src={preview} />
))}
</div>
) : (
<AddTwitPicsInput
onChange={(newPics: File[]) => {
setPics(newPics);
}}
/>
)}
</div>
);
}

View File

@@ -0,0 +1,80 @@
import { useCallback } from 'react';
import { Resolved, useJazz } from 'jazz-react';
import { Button, ProfilePicImg } from './basicComponents/index.tsx';
import { TwitAccountRoot, TwitProfile } from './1_dataModel.ts';
import { Link } from 'react-router-dom';
import { BrowserImage } from 'jazz-browser-media-images';
export function FollowButton({ profile }: { profile?: Resolved<TwitProfile> }) {
const { me } = useJazz<TwitProfile, TwitAccountRoot>();
const alreadyFollowing = profile?.followers?.perAccount?.some(([acc, status]) => acc === me.id && !!status.last);
const theyFollowMe = profile?.following?.some(f => f?.id === me.profile?.id);
const followOrUnfollow = useCallback(() => {
if (!profile?.followers || !me.profile?.following) return;
if (alreadyFollowing) {
me.profile.following.delete(me.profile.following.findIndex(f => f?.id === profile.id));
profile.followers.push(null);
} else {
me.profile.following.append(profile.id);
profile.followers.push(me.profile.id);
}
}, [alreadyFollowing, me.profile, profile]);
return profile?.id === me.profile?.id ? (
<div className="ml-auto text-neutral-500">That's you!</div>
) : (
<Button onClick={followOrUnfollow} className="ml-auto" variant={alreadyFollowing ? 'ghost' : 'default'}>
{alreadyFollowing ? 'Unfollow' : theyFollowMe ? 'Follow Back' : 'Follow'}
</Button>
);
}
export function FollowerList({ profile }: { profile?: Resolved<TwitProfile> }) {
return (
<div className="flex flex-col gap-4 p-4 bg-background rounded-lg border shadow-lg w-96 max-w-full m-2">
{profile?.followers?.perAccount.map(([, followEntry]) => {
const followerProfile = followEntry.last;
// not following anymore?
if (!followerProfile) return null;
return (
<div key={followerProfile.id} className="flex items-center">
<ProfilePicImg
src={followerProfile?.avatar?.as(BrowserImage)?.highestResSrcOrPlaceholder}
linkTo={'/' + followerProfile?.id}
initial={followerProfile?.name[0]}
/>
<Link to={'/' + followerProfile?.id} className="font-bold hover:underline">
{followerProfile?.name}
</Link>
<FollowButton profile={followerProfile} />
</div>
);
})}
</div>
);
}
export function FollowingList({ profile }: { profile?: Resolved<TwitProfile> }) {
return (
<div className="flex flex-col gap-4 p-4 bg-background rounded-lg border shadow-lg w-96 max-w-full m-2">
{[...new Set(profile?.following || [])].map(followingProfile => {
return (
<div key={followingProfile?.id} className="flex items-center">
<ProfilePicImg
src={followingProfile?.avatar?.as(BrowserImage)?.highestResSrcOrPlaceholder}
linkTo={'/' + followingProfile?.id}
initial={followingProfile?.name[0]}
/>
<Link to={'/' + followingProfile?.id} className="font-bold hover:underline">
{followingProfile?.name}
</Link>
<FollowButton profile={followingProfile} />
</div>
);
})}
</div>
);
}

View File

@@ -1,8 +1,9 @@
import ReactTimeAgo from 'react-time-ago';
import { Button } from './ui/button';
import { Button, ButtonProps } from './ui/button';
export { Button } from './ui/button';
export { Checkbox } from './ui/checkbox';
import { Input } from './ui/input';
import { Link } from 'react-router-dom';
export { Input } from './ui/input';
export { Skeleton } from './ui/skeleton';
export { Toaster } from './ui/toaster';
@@ -12,6 +13,11 @@ export { TitleAndLogo } from './TitleAndLogo';
export { ThemeProvider } from './themeProvider';
export { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from './ui/table';
export { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from './ui/card';
export { Popover, PopoverContent, PopoverTrigger } from './ui/popover';
import TimeAgo from 'javascript-time-ago';
import en from 'javascript-time-ago/locale/en.json';
TimeAgo.addDefaultLocale(en);
export function BioInput(props: { value?: string; onChange: (value: string) => void }) {
return (
@@ -23,7 +29,7 @@ export function BioInput(props: { value?: string; onChange: (value: string) => v
props.onChange(e.target.value);
}}
placeholder="Add a bio..."
className="w-full p-2 border rounded"
className="w-full p-2 border rounded max-md:text-base"
/>
);
}
@@ -59,23 +65,35 @@ export function ChooseProfilePicInput(props: { onChange: (file: File) => void })
);
}
export function LargeProfilePicImg(props: { src?: string }) {
return <img src={props.src} className="w-20 h-20 bg-neutral-200 rounded-full mr-2 object-cover" />;
}
export function ProfilePicImg(props: { src?: string; smaller?: boolean }) {
export function ProfilePicImg(props: { src?: string; size?: 'sm' | 'xxl'; linkTo?: string; initial?: string }) {
return (
<img
src={props.src}
className={'bg-neutral-200 rounded-full mr-2 object-cover shrink-0' + (props.smaller ? ' w-8 h-8' : ' w-10 h-10')}
/>
<Link to={props.linkTo || ''}>
{props.src ? (
<img
src={props.src}
className={
'bg-neutral-200 rounded-full mr-2 object-cover shrink-0' +
(props.size === 'sm' ? ' w-8 h-8' : props.size === 'xxl' ? ' w-20 h-20' : ' w-10 h-10')
}
/>
) : (
<div
className={
'bg-neutral-200 rounded-full mr-2 object-cover shrink-0 flex items-center justify-center text-neutral-700 ' +
(props.size === 'sm'
? ' w-8 h-8 text-[1.5rem]'
: props.size === 'xxl'
? ' w-20 h-20 text-[3.75rem]'
: ' w-10 h-10 text-[1.875rem]')
}
>
<div className="-mt-[8%]">{props.initial}</div>
</div>
)}
</Link>
);
}
export function SubtleProfileID(props: { children: React.ReactNode }) {
return <div className="ml-2 text-neutral-300 text-xs">{props.children}</div>;
}
export function SubtleRelativeTimeAgo(props: { dateTime?: Date }) {
return (
<div className="ml-auto text-neutral-300 text-xs whitespace-nowrap">
@@ -88,12 +106,8 @@ export function TwitImg(props: { src?: string }) {
return <img src={props.src} className="h-40 rounded object-cover" />;
}
export function ReactionsAndReplyContainer(props: { children: React.ReactNode }) {
return <div className="flex flex-col mt-2">{props.children}</div>;
}
export function ReactionsContainer(props: { children: React.ReactNode }) {
return <div className="flex gap-4">{props.children}</div>;
return <div className="flex gap-4 mt-2">{props.children}</div>;
}
export function RepliesContainer(props: { children: React.ReactNode }) {
@@ -140,7 +154,7 @@ export function TwitTextInput(props: { onSubmit: (text: string) => void; submitB
name="twitText"
placeholder="What's happenin'"
autoComplete="off"
className="p-2 border rounded grow"
className="p-2 border rounded grow max-md:text-base"
/>
<Button asChild>
<input type="submit" value={props.submitButtonLabel} />
@@ -167,3 +181,48 @@ export function AddTwitPicsInput(props: { onChange: (files: File[]) => void }) {
</Button>
);
}
export function TwitWithRepliesContainer(props: { children: React.ReactNode; isTopLevel?: boolean }) {
return (
<div className={'py-2 flex flex-col items-stretch' + (props.isTopLevel ? ' border-t' : ' ml-14')}>
{props.children}
</div>
);
}
export function TwitContainer(props: { children: React.ReactNode }) {
return <div className="flex gap-2">{props.children}</div>;
}
export function TwitBody(props: { children: React.ReactNode }) {
return <div className="grow flex flex-col items-stretch">{props.children}</div>;
}
export function TwitHeader(props: { children: React.ReactNode }) {
return <div className="flex items-baseline">{props.children}</div>;
}
export function TwitImgGallery(props: { children: React.ReactNode }) {
return <div className="flex gap-2 mt-2 max-w-full overflow-auto">{props.children}</div>;
}
export function TwitText(props: { children: React.ReactNode; style?: React.CSSProperties }) {
return <div style={props.style}>{props.children}</div>;
}
export function QuoteContainer(props: { children: React.ReactNode }) {
return <div className="border rounded">{props.children}</div>;
}
export function MainH1(props: { children: React.ReactNode }) {
return <h1 className="text-2xl mb-4">{props.children}</h1>;
}
export function SmallInlineButton(props: { children: React.ReactNode } & ButtonProps) {
const {children, ...rest} = props
return (
<Button variant={'ghost'} className="h-6 px-1 -mx-1" {...rest}>
{children}
</Button>
);
}

View File

@@ -0,0 +1,29 @@
import * as React from "react"
import * as PopoverPrimitive from "@radix-ui/react-popover"
import { cn } from "@/basicComponents/lib/utils"
const Popover = PopoverPrimitive.Root
const PopoverTrigger = PopoverPrimitive.Trigger
const PopoverContent = React.forwardRef<
React.ElementRef<typeof PopoverPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>
>(({ className, align = "center", sideOffset = 4, ...props }, ref) => (
<PopoverPrimitive.Portal>
<PopoverPrimitive.Content
ref={ref}
align={align}
sideOffset={sideOffset}
className={cn(
"z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
className
)}
{...props}
/>
</PopoverPrimitive.Portal>
))
PopoverContent.displayName = PopoverPrimitive.Content.displayName
export { Popover, PopoverTrigger, PopoverContent }

View File

@@ -12,6 +12,7 @@ async function main() {
cojson: "index.ts",
"jazz-browser": "index.ts",
"jazz-browser-media-images": "index.ts",
"jazz-autosub": "index.ts",
}).map(async ([packageName, entryPoint]) => {
const app = await Application.bootstrapWithPlugins({
entryPoints: [`packages/${packageName}/src/${entryPoint}`],

View File

@@ -0,0 +1,3 @@
{
"extends": "next/core-web-vitals"
}

35
homepage/homepage-jazz/.gitignore vendored Normal file
View File

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

View File

@@ -0,0 +1,36 @@
This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).
## Getting Started
First, run the development server:
```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
This project uses [`next/font`](https://nextjs.org/docs/basic-features/font-optimization) to automatically optimize and load Inter, a custom Google Font.
## Learn More
To learn more about Next.js, take a look at the following resources:
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome!
## Deploy on Vercel
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details.

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

View File

@@ -0,0 +1,27 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
:root {
--foreground-rgb: 0, 0, 0;
--background-start-rgb: 214, 219, 220;
--background-end-rgb: 255, 255, 255;
}
@media (prefers-color-scheme: dark) {
:root {
--foreground-rgb: 255, 255, 255;
--background-start-rgb: 0, 0, 0;
--background-end-rgb: 0, 0, 0;
}
}
body {
color: rgb(var(--foreground-rgb));
background: linear-gradient(
to bottom,
transparent,
rgb(var(--background-end-rgb))
)
rgb(var(--background-start-rgb));
}

View File

@@ -0,0 +1,22 @@
import './globals.css'
import type { Metadata } from 'next'
import { Inter } from 'next/font/google'
const inter = Inter({ subsets: ['latin'] })
export const metadata: Metadata = {
title: 'Create Next App',
description: 'Generated by create next app',
}
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body className={inter.className}>{children}</body>
</html>
)
}

View File

@@ -0,0 +1,113 @@
import Image from 'next/image'
export default function Home() {
return (
<main className="flex min-h-screen flex-col items-center justify-between p-24">
<div className="z-10 max-w-5xl w-full items-center justify-between font-mono text-sm lg:flex">
<p className="fixed left-0 top-0 flex w-full justify-center border-b border-gray-300 bg-gradient-to-b from-zinc-200 pb-6 pt-8 backdrop-blur-2xl dark:border-neutral-800 dark:bg-zinc-800/30 dark:from-inherit lg:static lg:w-auto lg:rounded-xl lg:border lg:bg-gray-200 lg:p-4 lg:dark:bg-zinc-800/30">
Get started by editing&nbsp;
<code className="font-mono font-bold">app/page.tsx</code>
</p>
<div className="fixed bottom-0 left-0 flex h-48 w-full items-end justify-center bg-gradient-to-t from-white via-white dark:from-black dark:via-black lg:static lg:h-auto lg:w-auto lg:bg-none">
<a
className="pointer-events-none flex place-items-center gap-2 p-8 lg:pointer-events-auto lg:p-0"
href="https://vercel.com?utm_source=create-next-app&utm_medium=appdir-template&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
By{' '}
<Image
src="/vercel.svg"
alt="Vercel Logo"
className="dark:invert"
width={100}
height={24}
priority
/>
</a>
</div>
</div>
<div className="relative flex place-items-center before:absolute before:h-[300px] before:w-[480px] before:-translate-x-1/2 before:rounded-full before:bg-gradient-radial before:from-white before:to-transparent before:blur-2xl before:content-[''] after:absolute after:-z-20 after:h-[180px] after:w-[240px] after:translate-x-1/3 after:bg-gradient-conic after:from-sky-200 after:via-blue-200 after:blur-2xl after:content-[''] before:dark:bg-gradient-to-br before:dark:from-transparent before:dark:to-blue-700 before:dark:opacity-10 after:dark:from-sky-900 after:dark:via-[#0141ff] after:dark:opacity-40 before:lg:h-[360px] z-[-1]">
<Image
className="relative dark:drop-shadow-[0_0_0.3rem_#ffffff70] dark:invert"
src="/next.svg"
alt="Next.js Logo"
width={180}
height={37}
priority
/>
</div>
<div className="mb-32 grid text-center lg:max-w-5xl lg:w-full lg:mb-0 lg:grid-cols-4 lg:text-left">
<a
href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template&utm_campaign=create-next-app"
className="group rounded-lg border border-transparent px-5 py-4 transition-colors hover:border-gray-300 hover:bg-gray-100 hover:dark:border-neutral-700 hover:dark:bg-neutral-800/30"
target="_blank"
rel="noopener noreferrer"
>
<h2 className={`mb-3 text-2xl font-semibold`}>
Docs{' '}
<span className="inline-block transition-transform group-hover:translate-x-1 motion-reduce:transform-none">
-&gt;
</span>
</h2>
<p className={`m-0 max-w-[30ch] text-sm opacity-50`}>
Find in-depth information about Next.js features and API.
</p>
</a>
<a
href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
className="group rounded-lg border border-transparent px-5 py-4 transition-colors hover:border-gray-300 hover:bg-gray-100 hover:dark:border-neutral-700 hover:dark:bg-neutral-800/30"
target="_blank"
rel="noopener noreferrer"
>
<h2 className={`mb-3 text-2xl font-semibold`}>
Learn{' '}
<span className="inline-block transition-transform group-hover:translate-x-1 motion-reduce:transform-none">
-&gt;
</span>
</h2>
<p className={`m-0 max-w-[30ch] text-sm opacity-50`}>
Learn about Next.js in an interactive course with&nbsp;quizzes!
</p>
</a>
<a
href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template&utm_campaign=create-next-app"
className="group rounded-lg border border-transparent px-5 py-4 transition-colors hover:border-gray-300 hover:bg-gray-100 hover:dark:border-neutral-700 hover:dark:bg-neutral-800/30"
target="_blank"
rel="noopener noreferrer"
>
<h2 className={`mb-3 text-2xl font-semibold`}>
Templates{' '}
<span className="inline-block transition-transform group-hover:translate-x-1 motion-reduce:transform-none">
-&gt;
</span>
</h2>
<p className={`m-0 max-w-[30ch] text-sm opacity-50`}>
Explore the Next.js 13 playground.
</p>
</a>
<a
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template&utm_campaign=create-next-app"
className="group rounded-lg border border-transparent px-5 py-4 transition-colors hover:border-gray-300 hover:bg-gray-100 hover:dark:border-neutral-700 hover:dark:bg-neutral-800/30"
target="_blank"
rel="noopener noreferrer"
>
<h2 className={`mb-3 text-2xl font-semibold`}>
Deploy{' '}
<span className="inline-block transition-transform group-hover:translate-x-1 motion-reduce:transform-none">
-&gt;
</span>
</h2>
<p className={`m-0 max-w-[30ch] text-sm opacity-50`}>
Instantly deploy your Next.js site to a shareable URL with Vercel.
</p>
</a>
</div>
</main>
)
}

View File

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

View File

@@ -0,0 +1,27 @@
{
"name": "homepage-jazz",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"react": "latest",
"react-dom": "latest",
"next": "latest"
},
"devDependencies": {
"typescript": "latest",
"@types/react": "latest",
"@types/node": "latest",
"@types/react-dom": "latest",
"autoprefixer": "latest",
"postcss": "latest",
"tailwindcss": "latest",
"eslint": "latest",
"eslint-config-next": "latest"
}
}

View File

@@ -0,0 +1,6 @@
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 283 64"><path fill="black" d="M141 16c-11 0-19 7-19 18s9 18 20 18c7 0 13-3 16-7l-7-5c-2 3-6 4-9 4-5 0-9-3-10-7h28v-3c0-11-8-18-19-18zm-9 15c1-4 4-7 9-7s8 3 9 7h-18zm117-15c-11 0-19 7-19 18s9 18 20 18c6 0 12-3 16-7l-8-5c-2 3-5 4-8 4-5 0-9-3-11-7h28l1-3c0-11-8-18-19-18zm-10 15c2-4 5-7 10-7s8 3 9 7h-19zm-39 3c0 6 4 10 10 10 4 0 7-2 9-5l8 5c-3 5-9 8-17 8-11 0-19-7-19-18s8-18 19-18c8 0 14 3 17 8l-8 5c-2-3-5-5-9-5-6 0-10 4-10 10zm83-29v46h-9V5h9zM37 0l37 64H0L37 0zm92 5-27 48L74 5h10l18 30 17-30h10zm59 12v10l-3-1c-6 0-10 4-10 10v15h-9V17h9v9c0-5 6-9 13-9z"/></svg>

After

Width:  |  Height:  |  Size: 629 B

View File

@@ -0,0 +1,20 @@
import type { Config } from 'tailwindcss'
const config: Config = {
content: [
'./pages/**/*.{js,ts,jsx,tsx,mdx}',
'./components/**/*.{js,ts,jsx,tsx,mdx}',
'./app/**/*.{js,ts,jsx,tsx,mdx}',
],
theme: {
extend: {
backgroundImage: {
'gradient-radial': 'radial-gradient(var(--tw-gradient-stops))',
'gradient-conic':
'conic-gradient(from 180deg at 50% 50%, var(--tw-gradient-stops))',
},
},
},
plugins: [],
}
export default config

View File

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

View File

@@ -4,7 +4,7 @@
"types": "src/index.ts",
"type": "module",
"license": "MIT",
"version": "0.4.0",
"version": "0.4.13",
"devDependencies": {
"@types/jest": "^29.5.3",
"@types/ws": "^8.5.5",
@@ -16,8 +16,8 @@
"typescript": "5.0.2"
},
"dependencies": {
"cojson": "^0.4.0",
"cojson-storage-sqlite": "^0.4.0",
"cojson": "^0.4.13",
"cojson-storage-sqlite": "^0.4.13",
"ws": "^8.13.0"
},
"scripts": {

View File

@@ -1,11 +1,11 @@
{
"name": "cojson-storage-indexeddb",
"version": "0.4.0",
"version": "0.4.13",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"types": "src/index.ts",
"license": "MIT",
"dependencies": {
"cojson": "^0.4.0",
"cojson": "^0.4.13",
"typescript": "^5.1.6"
},
"devDependencies": {
@@ -16,7 +16,7 @@
"scripts": {
"test": "vitest --browser chrome",
"lint": "eslint src/**/*.ts",
"build": "npm run lint && rm -rf ./dist && tsc --declaration --sourceMap --outDir dist",
"build": "npm run lint && rm -rf ./dist && tsc --sourceMap --outDir dist",
"prepublishOnly": "npm run build"
},
"gitHead": "33c27053293b4801b968c61d5c4c989f93a67d13"

View File

@@ -1,18 +1,18 @@
{
"name": "cojson-storage-sqlite",
"type": "module",
"version": "0.4.0",
"version": "0.4.13",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"types": "src/index.ts",
"license": "MIT",
"dependencies": {
"better-sqlite3": "^8.5.2",
"cojson": "^0.4.0",
"cojson": "^0.4.13",
"typescript": "^5.1.6"
},
"scripts": {
"lint": "eslint src/**/*.ts",
"build": "npm run lint && rm -rf ./dist && tsc --declaration --sourceMap --outDir dist",
"build": "npm run lint && rm -rf ./dist && tsc --sourceMap --outDir dist",
"prepublishOnly": "npm run build"
},
"devDependencies": {

View File

@@ -2,10 +2,10 @@
"name": "cojson",
"module": "dist/index.js",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"types": "src/index.ts",
"type": "module",
"license": "MIT",
"version": "0.4.0",
"version": "0.4.13",
"devDependencies": {
"@types/jest": "^29.5.3",
"@typescript-eslint/eslint-plugin": "^6.2.1",
@@ -26,7 +26,7 @@
"scripts": {
"test": "jest",
"lint": "eslint src/**/*.ts",
"build": "npm run lint && rm -rf ./dist && tsc --declaration --sourceMap --outDir dist",
"build": "npm run lint && rm -rf ./dist && tsc --sourceMap --outDir dist",
"prepublishOnly": "npm run build"
},
"jest": {

View File

@@ -1,11 +1,7 @@
import { JsonObject, JsonValue } from "./jsonValue.js";
import { RawCoID } from "./ids.js";
import { CoMap } from "./coValues/coMap.js";
import {
BinaryCoStream,
BinaryCoStreamMeta,
CoStream,
} from "./coValues/coStream.js";
import { BinaryCoStream, CoStream } from "./coValues/coStream.js";
import { CoList } from "./coValues/coList.js";
import { CoValueCore } from "./coValueCore.js";
import { Group } from "./coValues/group.js";
@@ -22,7 +18,7 @@ export interface CoValue {
/** Specifies which kind of `CoValue` this is */
type: string;
/** The `CoValue`'s (precisely typed) static metadata */
meta: JsonObject | null;
headerMeta: JsonObject | null;
/** The `Group` this `CoValue` belongs to (determining permissions) */
group: Group;
/** Returns an immutable JSON presentation of this `CoValue` */
@@ -38,7 +34,14 @@ export interface CoValue {
subscribe(listener: (coValue: this) => void): () => void;
}
export type AnyCoValue = CoMap | Group | Account | Profile | CoList | CoStream | BinaryCoStream;
export type AnyCoValue =
| CoMap
| Group
| Account
| Profile
| CoList
| CoStream
| BinaryCoStream;
export function expectMap(content: CoValue): CoMap {
if (content.type !== "comap") {
@@ -62,15 +65,4 @@ export function expectStream(content: CoValue): CoStream {
}
return content as CoStream;
}
export function isCoValue(
value: JsonValue | CoValue | undefined
): value is CoValue {
return (
value instanceof CoMap ||
value instanceof CoList ||
value instanceof CoStream ||
value instanceof BinaryCoStream
);
}
}

View File

@@ -1,7 +1,5 @@
import { randomBytes } from "@noble/hashes/utils";
import { AnyCoValue, CoValue } from "./coValue.js";
import { BinaryCoStream, CoStream } from "./coValues/coStream.js";
import { CoMap } from "./coValues/coMap.js";
import {
Encrypted,
Hash,
@@ -26,18 +24,19 @@ import {
determineValidTransactions,
isKeyForKeyField,
} from "./permissions.js";
import { Group, expectGroup } from "./coValues/group.js";
import { Group } from "./coValues/group.js";
import { LocalNode } from "./localNode.js";
import { CoValueKnownState, NewContentMessage } from "./sync.js";
import { AgentID, RawCoID, SessionID, TransactionID } from "./ids.js";
import { CoList } from "./coValues/coList.js";
import {
Account,
AccountID,
GeneralizedControlledAccount,
isAccountID,
} from "./coValues/account.js";
import { Stringified, stableStringify } from "./jsonStringify.js";
import { Stringified, parseJSON, stableStringify } from "./jsonStringify.js";
import { coreToCoValue } from "./coreToCoValue.js";
import { expectGroup } from "./typeUtils/expectGroup.js";
import { isAccountID } from "./typeUtils/isAccountID.js";
import { accountOrAgentIDfromSessionID } from "./typeUtils/accountOrAgentIDfromSessionID.js";
export const MAX_RECOMMENDED_TX_SIZE = 100 * 1024;
@@ -54,12 +53,6 @@ export function idforHeader(header: CoValueHeader): RawCoID {
return `co_z${hash.slice("shortHash_z".length)}`;
}
export function accountOrAgentIDfromSessionID(
sessionID: SessionID
): AccountID | AgentID {
return sessionID.split("_session")[0] as AccountID | AgentID;
}
export function newRandomSessionID(accountID: AccountID | AgentID): SessionID {
return `${accountID}_session_z${base58.encode(randomBytes(8))}`;
}
@@ -92,7 +85,7 @@ export type Transaction = PrivateTransaction | TrustingTransaction;
export type DecryptedTransaction = {
txID: TransactionID;
changes: Stringified<JsonValue[]>;
changes: JsonValue[];
madeAt: number;
};
@@ -107,7 +100,7 @@ export class CoValueCore {
listeners: Set<(content?: CoValue) => void> = new Set();
_decryptionCache: {
[key: Encrypted<JsonValue[], JsonValue>]:
| Stringified<JsonValue[]>
| JsonValue[]
| undefined;
} = {};
@@ -464,7 +457,7 @@ export class CoValueCore {
tx: this.nextTransactionID(),
});
this._decryptionCache[encrypted] = stableStringify(changes);
this._decryptionCache[encrypted] = changes;
transaction = {
privacy: "private",
@@ -517,31 +510,7 @@ export class CoValueCore {
return this._cachedContent;
}
let newContent;
if (this.header.type === "comap") {
if (this.header.ruleset.type === "group") {
if (
this.header.meta?.type === "account" &&
!options?.ignorePrivateTransactions
) {
newContent = new Account(this);
} else {
newContent = new Group(this, options);
}
} else {
newContent = new CoMap(this);
}
} else if (this.header.type === "colist") {
newContent = new CoList(this);
} else if (this.header.type === "costream") {
if (this.header.meta && this.header.meta.type === "binary") {
newContent = new BinaryCoStream(this);
} else {
newContent = new CoStream(this);
}
} else {
throw new Error(`Unknown coValue type ${this.header.type}`);
}
const newContent = coreToCoValue(this, options);
if (!options?.ignorePrivateTransactions) {
this._cachedContent = newContent;
@@ -561,7 +530,7 @@ export class CoValueCore {
return {
txID,
madeAt: tx.madeAt,
changes: tx.changes,
changes: parseJSON(tx.changes),
};
} else {
if (options?.ignorePrivateTransactions) {
@@ -576,14 +545,15 @@ export class CoValueCore {
this._decryptionCache[tx.encryptedChanges];
if (!decrytedChanges) {
decrytedChanges = decryptRawForTransaction(
const decryptedString = decryptRawForTransaction(
tx.encryptedChanges,
readKey,
{
in: this.id,
tx: txID,
}
);
)
decrytedChanges = decryptedString && parseJSON(decryptedString);
this._decryptionCache[tx.encryptedChanges] =
decrytedChanges;
}

View File

@@ -153,10 +153,6 @@ export class AnonymousControlledAccount
export type AccountMeta = { type: "account" };
export type AccountID = CoID<Account>;
export function isAccountID(id: AccountID | AgentID): id is AccountID {
return id.startsWith("co_");
}
export type ProfileShape = {
name: string;
};

View File

@@ -1,9 +1,10 @@
import { JsonObject, JsonValue } from "../jsonValue.js";
import { CoID, CoValue, isCoValue } from "../coValue.js";
import { CoValueCore, accountOrAgentIDfromSessionID } from "../coValueCore.js";
import { CoID, CoValue } from "../coValue.js";
import { isCoValue } from "../typeUtils/isCoValue.js";
import { CoValueCore } from "../coValueCore.js";
import { accountOrAgentIDfromSessionID } from "../typeUtils/accountOrAgentIDfromSessionID.js";
import { AgentID, SessionID, TransactionID } from "../ids.js";
import { AccountID } from "./account.js";
import { parseJSON } from "../jsonStringify.js";
import { Group } from "./group.js";
type OpID = TransactionID & { changeIdx: number };
@@ -93,9 +94,7 @@ export class CoListView<
changes,
madeAt,
} of this.core.getValidSortedTransactions()) {
for (const [changeIdx, changeUntyped] of parseJSON(
changes
).entries()) {
for (const [changeIdx, changeUntyped] of changes.entries()) {
const change = changeUntyped as ListOpPayload<Item>;
if (change.op === "pre" || change.op === "app") {
@@ -197,7 +196,7 @@ export class CoListView<
}
/** @category 6. Meta */
get meta(): Meta {
get headerMeta(): Meta {
return this.core.header.meta as Meta;
}

View File

@@ -1,10 +1,11 @@
import { JsonObject, JsonValue } from "../jsonValue.js";
import { AgentID, TransactionID } from "../ids.js";
import { CoID, CoValue, isCoValue } from "../coValue.js";
import { CoValueCore, accountOrAgentIDfromSessionID } from "../coValueCore.js";
import { CoID, CoValue } from "../coValue.js";
import { isCoValue } from "../typeUtils/isCoValue.js";
import { CoValueCore } from "../coValueCore.js";
import { accountOrAgentIDfromSessionID } from "../typeUtils/accountOrAgentIDfromSessionID.js";
import { AccountID } from "./account.js";
import { parseJSON } from "../jsonStringify.js";
import { Group } from "./group.js";
import type { Group } from "./group.js";
type MapOp<K extends string, V extends JsonValue | undefined> = {
txID: TransactionID;
@@ -58,9 +59,7 @@ export class CoMapView<
for (const { txID, changes, madeAt } of core.getValidSortedTransactions(
options
)) {
for (const [changeIdx, changeUntyped] of parseJSON(
changes
).entries()) {
for (const [changeIdx, changeUntyped] of changes.entries()) {
const change = changeUntyped as MapOpPayload<
keyof Shape & string,
Shape[keyof Shape & string]
@@ -84,7 +83,7 @@ export class CoMapView<
}
/** @category 6. Meta */
get meta(): Meta {
get headerMeta(): Meta {
return this.core.header.meta as Meta;
}
@@ -121,7 +120,7 @@ export class CoMapView<
* Get all keys currently in the map.
*
* @category 1. Reading */
keys<K extends (keyof Shape & string) = (keyof Shape & string)>(): K[] {
keys<K extends keyof Shape & string = keyof Shape & string>(): K[] {
const keys = Object.keys(this.ops) as K[];
if (this.atTimeFilter) {

View File

@@ -1,11 +1,13 @@
import { JsonObject, JsonValue } from "../jsonValue.js";
import { CoValue, CoID, isCoValue } from "../coValue.js";
import { CoValueCore, accountOrAgentIDfromSessionID } from "../coValueCore.js";
import { CoValue, CoID } from "../coValue.js";
import { isAccountID } from "../typeUtils/isAccountID.js";
import { isCoValue } from "../typeUtils/isCoValue.js";
import { CoValueCore } from "../coValueCore.js";
import { accountOrAgentIDfromSessionID } from "../typeUtils/accountOrAgentIDfromSessionID.js";
import { Group } from "./group.js";
import { AgentID, SessionID, TransactionID } from "../ids.js";
import { base64URLtoBytes, bytesToBase64url } from "../base64url.js";
import { AccountID } from "./account.js";
import { parseJSON } from "../jsonStringify.js";
export type BinaryStreamInfo = {
mimeType: string;
@@ -59,7 +61,7 @@ export class CoStreamView<
this.fillFromCoValue();
}
get meta(): Meta {
get headerMeta(): Meta {
return this.core.header.meta as Meta;
}
@@ -81,7 +83,7 @@ export class CoStreamView<
madeAt,
changes,
} of this.core.getValidSortedTransactions()) {
for (const changeUntyped of parseJSON(changes)) {
for (const changeUntyped of changes) {
const change = changeUntyped as Item;
let entries = this.items[txID.sessionID];
if (!entries) {
@@ -111,8 +113,8 @@ export class CoStreamView<
return Object.keys(this.items) as SessionID[];
}
accounts(): Set<AccountID | AgentID> {
return new Set(this.sessions().map(accountOrAgentIDfromSessionID));
accounts(): Set<AccountID> {
return new Set(this.sessions().map(accountOrAgentIDfromSessionID).filter(isAccountID));
}
nthItemIn(
@@ -290,10 +292,8 @@ export class BinaryCoStreamView<
extends CoStreamView<BinaryStreamItem, Meta>
implements CoValue
{
id!: CoID<this>;
getBinaryChunks(
allowUnfinished?: boolean
allowUnfinished?: boolean,
):
| (BinaryStreamInfo & { chunks: Uint8Array[]; finished: boolean })
| undefined {
@@ -318,6 +318,8 @@ export class BinaryCoStreamView<
let finished = false;
// let totalLength = 0;
let lastProgressUpdate = Date.now();
for (const item of items.slice(1)) {
if (item.type === "end") {
finished = true;
@@ -334,6 +336,10 @@ export class BinaryCoStreamView<
);
// totalLength += chunk.length;
chunks.push(chunk);
if (Date.now() - lastProgressUpdate > 100) {
lastProgressUpdate = Date.now();
}
}
// const after = performance.now();
@@ -361,36 +367,55 @@ export class BinaryCoStream<
/** @internal */
push(
item: BinaryStreamItem,
privacy: "private" | "trusting" = "private"
): this {
privacy?: "private" | "trusting",
): this
push(
item: BinaryStreamItem,
privacy: "private" | "trusting",
returnNewStream: true
): this
push(
item: BinaryStreamItem,
privacy: "private" | "trusting",
returnNewStream: false
): void
push(
item: BinaryStreamItem,
privacy: "private" | "trusting" = "private",
returnNewStream: boolean = true
): this | void {
this.core.makeTransaction([item], privacy);
return new BinaryCoStream(this.core) as this;
if (returnNewStream) {
return new BinaryCoStream(this.core) as this;
}
}
startBinaryStream(
settings: BinaryStreamInfo,
privacy: "private" | "trusting" = "private"
): this {
): void {
return this.push(
{
type: "start",
...settings,
} satisfies BinaryStreamStart,
privacy
privacy,
false
);
}
pushBinaryStreamChunk(
chunk: Uint8Array,
privacy: "private" | "trusting" = "private"
): this {
): void {
// const before = performance.now();
return this.push(
{
type: "chunk",
chunk: `binary_U${bytesToBase64url(chunk)}`,
} satisfies BinaryStreamChunk,
privacy
privacy,
false
);
// const after = performance.now();
// console.log(
@@ -404,7 +429,8 @@ export class BinaryCoStream<
{
type: "end",
} satisfies BinaryStreamEnd,
privacy
privacy,
true
);
}

View File

@@ -1,4 +1,4 @@
import { CoID, CoValue, expectMap } from "../coValue.js";
import { CoID } from "../coValue.js";
import { CoMap } from "./coMap.js";
import { CoList } from "./coList.js";
import { JsonObject } from "../jsonValue.js";
@@ -39,19 +39,6 @@ export type GroupShape<P extends Profile, R extends CoMap> = {
>;
};
export function expectGroup(content: CoValue): Group {
const map = expectMap(content);
if (map.core.header.ruleset.type !== "group") {
throw new Error("Expected group ruleset in group");
}
if (!(map instanceof Group)) {
throw new Error("Expected group");
}
return map;
}
/** A `Group` is a scope for permissions of its members (`"reader" | "writer" | "admin"`), applying to objects owned by that group.
*
* A `Group` object exposes methods for permission management and allows you to create new CoValues owned by that group.
@@ -277,7 +264,7 @@ export class Group<
*/
createMap<M extends CoMap>(
init?: M["_shape"],
meta?: M["meta"],
meta?: M["headerMeta"],
initPrivacy: "trusting" | "private" = "private"
): M {
let map = this.core.node
@@ -309,7 +296,7 @@ export class Group<
*/
createList<L extends CoList>(
init?: L["_item"][],
meta?: L["meta"],
meta?: L["headerMeta"],
initPrivacy: "trusting" | "private" = "private"
): L {
let list = this.core.node
@@ -334,7 +321,7 @@ export class Group<
}
/** @category 3. Value creation */
createStream<C extends CoStream>(meta?: C["meta"]): C {
createStream<C extends CoStream>(meta?: C["headerMeta"]): C {
return this.core.node
.createCoValue({
type: "costream",
@@ -350,7 +337,7 @@ export class Group<
/** @category 3. Value creation */
createBinaryStream<C extends BinaryCoStream>(
meta: C["meta"] = { type: "binary" }
meta: C["headerMeta"] = { type: "binary" }
): C {
return this.core.node
.createCoValue({

View File

@@ -0,0 +1,37 @@
import type { CoValueCore } from "./coValueCore.js";
import { Account } from "./coValues/account.js";
import { Group } from "./coValues/group.js";
import { CoMap } from "./coValues/coMap.js";
import { CoList } from "./coValues/coList.js";
import { CoStream } from "./coValues/coStream.js";
import { BinaryCoStream } from "./coValues/coStream.js";
export function coreToCoValue(
core: CoValueCore,
options?: { ignorePrivateTransactions: true }
) {
if (core.header.type === "comap") {
if (core.header.ruleset.type === "group") {
if (
core.header.meta?.type === "account" &&
!options?.ignorePrivateTransactions
) {
return new Account(core);
} else {
return new Group(core, options);
}
} else {
return new CoMap(core);
}
} else if (core.header.type === "colist") {
return new CoList(core);
} else if (core.header.type === "costream") {
if (core.header.meta && core.header.meta.type === "binary") {
return new BinaryCoStream(core);
} else {
return new CoStream(core);
}
} else {
throw new Error(`Unknown coValue type ${core.header.type}`);
}
}

View File

@@ -2,8 +2,8 @@ import {
CoValueCore,
newRandomSessionID,
MAX_RECOMMENDED_TX_SIZE,
accountOrAgentIDfromSessionID
} from "./coValueCore.js";
import { accountOrAgentIDfromSessionID } from "./typeUtils/accountOrAgentIDfromSessionID.js";
import { LocalNode } from "./localNode.js";
import type { CoValue } from "./coValue.js";
import { CoMap, MutableCoMap } from "./coValues/coMap.js";
@@ -30,20 +30,18 @@ import {
AnonymousControlledAccount,
ControlledAccount,
} from "./coValues/account.js";
import type { Role } from "./permissions.js";
import { rawCoIDtoBytes, rawCoIDfromBytes } from "./ids.js";
import { Group, expectGroup, EVERYONE } from "./coValues/group.js";
import { Group, EVERYONE } from "./coValues/group.js";
import type { Everyone } from "./coValues/group.js";
import { base64URLtoBytes, bytesToBase64url } from "./base64url.js";
import { parseJSON } from "./jsonStringify.js";
import { Account, Profile, isAccountID } from "./coValues/account.js";
import { Account, Profile } from "./coValues/account.js";
import { expectGroup } from "./typeUtils/expectGroup.js";
import { isAccountID } from "./typeUtils/isAccountID.js";
import type { SessionID, AgentID } from "./ids.js";
import type { CoID, AnyCoValue } from "./coValue.js";
import type { Queried, QueryExtension } from "./queries.js";
import type { QueriedCoStream } from "./queriedCoValues/queriedCoStream.js";
import type { QueriedCoList } from "./queriedCoValues/queriedCoList.js";
import type { QueriedCoMap } from "./queriedCoValues/queriedCoMap.js";
import { QueriedAccount } from "./queriedCoValues/queriedAccount.js";
import { QueriedGroup } from "./queriedCoValues/queriedGroup.js";
import type {
BinaryStreamInfo,
BinaryCoStreamMeta,
@@ -51,7 +49,12 @@ import type {
import type { JsonValue } from "./jsonValue.js";
import type { SyncMessage, Peer } from "./sync.js";
import type { AgentSecret } from "./crypto.js";
import type { AccountID, AccountMeta, AccountMigration, ProfileMeta } from "./coValues/account.js";
import type {
AccountID,
AccountMeta,
AccountMigration,
ProfileMeta,
} from "./coValues/account.js";
import type { InviteSecret } from "./coValues/group.js";
import type * as Media from "./media.js";
@@ -82,7 +85,9 @@ export const cojsonInternals = {
export {
LocalNode,
Group,
Role,
EVERYONE,
Everyone,
CoMap,
MutableCoMap,
CoList,
@@ -94,12 +99,6 @@ export {
CoValue,
CoID,
AnyCoValue,
Queried,
QueriedCoMap,
QueriedCoList,
QueriedCoStream,
QueriedGroup,
QueriedAccount,
Account,
AccountID,
AccountMeta,
@@ -113,7 +112,6 @@ export {
ControlledAccount,
cryptoReady as cojsonReady,
MAX_RECOMMENDED_TX_SIZE,
Value,
JsonValue,
Peer,
BinaryStreamInfo,
@@ -122,9 +120,12 @@ export {
AgentSecret,
InviteSecret,
SyncMessage,
QueryExtension,
};
export type {
Value,
}
// eslint-disable-next-line @typescript-eslint/no-namespace
export namespace CojsonInternalTypes {
export type CoValueKnownState = import("./sync.js").CoValueKnownState;
@@ -134,6 +135,7 @@ export namespace CojsonInternalTypes {
export type NewContentMessage = import("./sync.js").NewContentMessage;
export type CoValueHeader = import("./coValueCore.js").CoValueHeader;
export type Transaction = import("./coValueCore.js").Transaction;
export type TransactionID = import("./ids.js").TransactionID;
export type Signature = import("./crypto.js").Signature;
export type RawCoID = import("./ids.js").RawCoID;
export type ProfileShape = import("./coValues/account.js").ProfileShape;

View File

@@ -17,14 +17,11 @@ import {
import {
InviteSecret,
Group,
GroupShape,
expectGroup,
secretSeedFromInviteSecret,
} from "./coValues/group.js";
import { Peer, SyncManager } from "./sync.js";
import { AgentID, RawCoID, SessionID, isAgentID } from "./ids.js";
import { CoID } from "./coValue.js";
import { Queried, query } from "./queries.js";
import {
Account,
AccountMeta,
@@ -34,12 +31,11 @@ import {
AnonymousControlledAccount,
AccountID,
Profile,
isAccountID,
AccountMigration,
} from "./coValues/account.js";
import { CoMap } from "./coValues/coMap.js";
import { CoValue } from "./index.js";
import { QueriedAccount } from "./queriedCoValues/queriedAccount.js";
import { expectGroup } from "./typeUtils/expectGroup.js";
/** A `LocalNode` represents a local view of a set of loaded `CoValue`s, from the perspective of a particular account (or primitive cryptographic agent).
@@ -103,7 +99,8 @@ export class LocalNode {
newRandomSessionID(account.id)
);
const accountOnNodeWithAccount = nodeWithAccount.account as ControlledAccount<P, R, Meta>;
const accountOnNodeWithAccount =
nodeWithAccount.account as ControlledAccount<P, R, Meta>;
const profile = nodeWithAccount.expectProfileLoaded(
accountOnNodeWithAccount.id,
@@ -202,10 +199,10 @@ export class LocalNode {
}
/** @internal */
loadCoValue(id: RawCoID): Promise<CoValueCore> {
loadCoValue(id: RawCoID, onProgress?: (progress: number) => void): Promise<CoValueCore> {
let entry = this.coValues[id];
if (!entry) {
entry = newLoadingState();
entry = newLoadingState(onProgress);
this.coValues[id] = entry;
@@ -224,8 +221,8 @@ export class LocalNode {
*
* @category 3. Low-level
*/
async load<T extends CoValue>(id: CoID<T>): Promise<T> {
return (await this.loadCoValue(id)).getCurrentContent() as T;
async load<T extends CoValue>(id: CoID<T>, onProgress?: (progress: number) => void): Promise<T> {
return (await this.loadCoValue(id, onProgress)).getCurrentContent() as T;
}
/** @category 3. Low-level */
@@ -256,47 +253,6 @@ export class LocalNode {
};
}
/** @category 1. High-level */
query<T extends CoValue>(
id: CoID<T>,
callback: (update: Queried<T> | undefined) => void
): () => void;
query<
P extends Profile = Profile,
R extends CoMap = CoMap,
Meta extends AccountMeta = AccountMeta
>(
id: "me",
callback: (
update: QueriedAccount<Account<P, R, Meta>> | undefined
) => void
): () => void;
query(
id: CoID<CoValue> | "me",
callback: (
update: Queried<CoValue> | QueriedAccount | undefined
) => void
): () => void;
query(
id: CoID<CoValue> | "me",
callback: (
// TODO: sort this out
// eslint-disable-next-line @typescript-eslint/no-explicit-any
update: any
) => void
): () => void {
if (id === "me") {
const meId = this.account.id;
if (!isAccountID(meId)) {
throw new Error("Can only query 'me' for accounts");
}
return query(meId, this, callback);
} else {
return query(id, this, callback);
}
}
/** @deprecated Use Account.acceptInvite instead */
async acceptInvite<T extends CoValue>(
groupOrOwnedValueID: CoID<T>,
@@ -601,7 +557,10 @@ export class LocalNode {
if (account instanceof ControlledAccount) {
// To make sure that when we edit the account, we're modifying the correct sessions
const accountInNode = new ControlledAccount(newNode.expectCoValueLoaded(account.id), account.agentSecret);
const accountInNode = new ControlledAccount(
newNode.expectCoValueLoaded(account.id),
account.agentSecret
);
if (accountInNode.core.node !== newNode) {
throw new Error("Account's node is not the new node");
}
@@ -618,11 +577,12 @@ type CoValueState =
state: "loading";
done: Promise<CoValueCore>;
resolve: (coValue: CoValueCore) => void;
onProgress?: (progress: number) => void;
}
| { state: "loaded"; coValue: CoValueCore };
| { state: "loaded"; coValue: CoValueCore; onProgress?: (progress: number) => void; };
/** @internal */
export function newLoadingState(): CoValueState {
export function newLoadingState(onProgress?: (progress: number) => void): CoValueState {
let resolve: (coValue: CoValueCore) => void;
const promise = new Promise<CoValueCore>((r) => {
@@ -633,5 +593,6 @@ export function newLoadingState(): CoValueState {
state: "loading",
done: promise,
resolve: resolve!,
onProgress
};
}

View File

@@ -5,12 +5,13 @@ import { KeyID } from "./crypto.js";
import {
CoValueCore,
Transaction,
accountOrAgentIDfromSessionID,
} from "./coValueCore.js";
import { accountOrAgentIDfromSessionID } from "./typeUtils/accountOrAgentIDfromSessionID.js";
import { AgentID, RawCoID, SessionID, TransactionID } from "./ids.js";
import { Account, AccountID, Profile } from "./coValues/account.js";
import { parseJSON } from "./jsonStringify.js";
import { EVERYONE, Everyone, expectGroup } from "./coValues/group.js";
import { EVERYONE, Everyone } from "./coValues/group.js";
import { expectGroup } from "./typeUtils/expectGroup.js";
export type PermissionsDef =
| { type: "group"; initialAdmin: AccountID | AgentID }

View File

@@ -1,240 +0,0 @@
import { CoList, MutableCoList } from "../coValues/coList.js";
import { CoValueCore } from "../coValueCore.js";
import { Group } from "../coValues/group.js";
import { CoID, CoValue } from "../coValue.js";
import { TransactionID } from "../ids.js";
import { ValueOrSubQueried, QueryContext } from "../queries.js";
import { QueriedAccount } from "./queriedAccount.js";
export class QueriedCoList<L extends CoList> extends Array<
ValueOrSubQueried<L["_item"]>
> {
coList!: L;
id!: CoID<L>;
type!: "colist";
/** @internal */
constructor(coList: L, queryContext: QueryContext) {
if (!(coList instanceof CoList)) {
// this might be called from an intrinsic, like map, trying to create an empty array
// passing `0` as the only parameter
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return new Array(coList) as any;
}
super(
...coList
.asArray()
.map(
(item) =>
queryContext.queryIfCoID(item, [coList.id]) as ValueOrSubQueried<
L["_item"]
>
)
);
Object.defineProperties(this, {
coList: { get() {return coList} },
id: { value: coList.id },
type: { value: "colist" },
edits: {
value: [...this.keys()].map((i) => {
const edit = coList.editAt(i)!;
return queryContext.defineSubqueryPropertiesIn({
tx: edit.tx,
at: new Date(edit.at),
}, {
by: {value: edit.by, enumerable: true},
value: {value: edit.value, enumerable: true},
}, [coList.id]);
}),
},
deletions: {
value: coList.deletionEdits().map((deletion) => queryContext.defineSubqueryPropertiesIn({
tx: deletion.tx,
at: new Date(deletion.at),
}, {
by: {value: deletion.by, enumerable: true},
}, [coList.id])),
},
});
}
get meta(): L["meta"] {
return this.coList.meta;
}
get group(): Group {
return this.coList.group;
}
get core(): CoValueCore {
return this.coList.core;
}
append(
item: L["_item"],
after?: number,
privacy?: "private" | "trusting"
): L {
return this.coList.append(item, after, privacy);
}
prepend(
item: L["_item"],
before?: number,
privacy?: "private" | "trusting"
): L {
return this.coList.prepend(item, before, privacy);
}
delete(at: number, privacy?: "private" | "trusting"): L {
return this.coList.delete(at, privacy);
}
mutate(
mutator: (mutable: MutableCoList<L["_item"], L["meta"]>) => void
): L {
return this.coList.mutate(mutator);
}
edits!: {
by?: QueriedAccount;
tx: TransactionID;
at: Date;
value: L["_item"] extends CoValue
? CoID<L["_item"]>
: Exclude<L["_item"], CoValue>;
}[];
deletions!: {
by?: QueriedAccount;
tx: TransactionID;
at: Date;
}[];
/** @internal */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
static isArray(arg: any): arg is any[] {
return Array.isArray(arg);
}
/** @internal */
static from<T>(arrayLike: ArrayLike<T>): T[];
/** @internal */
static from<T, U>(
arrayLike: ArrayLike<T>,
mapfn: (v: T, k: number) => U,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
thisArg?: any
): U[];
/** @internal */
static from<T>(iterable: Iterable<T> | ArrayLike<T>): T[];
/** @internal */
static from<T, U>(
iterable: Iterable<T> | ArrayLike<T>,
mapfn: (v: T, k: number) => U,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
thisArg?: any
): U[];
/** @internal */
static from<T, U>(
_iterable: unknown,
_mapfn?: unknown,
_thisArg?: unknown
): T[] | U[] | T[] | U[] {
throw new Error("Array method 'from' not supported on QueriedCoList");
}
/** @internal */
static of<T>(..._items: T[]): T[] {
throw new Error("Array method 'of' not supported on QueriedCoList");
}
/** @internal */
pop(): ValueOrSubQueried<L["_item"]> | undefined {
throw new Error("Array method 'pop' not supported on QueriedCoList");
}
/** @internal */
push(..._items: ValueOrSubQueried<L["_item"]>[]): number {
throw new Error("Array method 'push' not supported on QueriedCoList");
}
/** @internal */
concat(
..._items: ConcatArray<ValueOrSubQueried<L["_item"]>>[]
): ValueOrSubQueried<L["_item"]>[];
/** @internal */
concat(
..._items: (
| ValueOrSubQueried<L["_item"]>
| ConcatArray<ValueOrSubQueried<L["_item"]>>
)[]
): ValueOrSubQueried<L["_item"]>[];
/** @internal */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
concat(..._items: any[]): ValueOrSubQueried<L["_item"]>[] {
throw new Error("Array method 'concat' not supported on QueriedCoList");
}
/** @internal */
reverse(): ValueOrSubQueried<L["_item"]>[] {
throw new Error(
"Array method 'reverse' not supported on QueriedCoList"
);
}
/** @internal */
shift(): ValueOrSubQueried<L["_item"]> | undefined {
throw new Error("Array method 'shift' not supported on QueriedCoList");
}
/** @internal */
sort(
_compareFn?:
| ((
a: ValueOrSubQueried<L["_item"]>,
b: ValueOrSubQueried<L["_item"]>
) => number)
| undefined
): this {
throw new Error("Array method 'sort' not supported on QueriedCoList");
}
/** @internal */
splice(
_start: number,
_deleteCount?: number | undefined
): ValueOrSubQueried<L["_item"]>[] {
throw new Error("Array method 'splice' not supported on QueriedCoList");
}
/** @internal */
unshift(..._items: ValueOrSubQueried<L["_item"]>[]): number {
throw new Error(
"Array method 'unshift' not supported on QueriedCoList"
);
}
/** @internal */
fill(
_value: ValueOrSubQueried<L["_item"]>,
_start?: number | undefined,
_end?: number | undefined
): this {
throw new Error("Array method 'fill' not supported on QueriedCoList");
}
/** @internal */
copyWithin(
_target: number,
_start: number,
_end?: number | undefined
): this {
throw new Error(
"Array method 'copyWithin' not supported on QueriedCoList"
);
}
}

View File

@@ -1,168 +0,0 @@
import { CoMap, MutableCoMap } from "../coValues/coMap.js";
import { CoValueCore } from "../coValueCore.js";
import { Group } from "../coValues/group.js";
import { CoID } from "../coValue.js";
import { TransactionID } from "../ids.js";
import { ValueOrSubQueried, QueryContext, QueryExtension } from "../queries.js";
import { QueriedAccount } from "./queriedAccount.js";
export type QueriedCoMap<M extends CoMap> = {
[K in keyof M["_shape"] & string]: ValueOrSubQueried<M["_shape"][K]>;
} & QueriedCoMapBase<M>;
export type QueriedCoMapEdit<M extends CoMap, K extends keyof M["_shape"]> = {
by?: QueriedAccount;
tx: TransactionID;
at: Date;
value: M["_shape"][K];
};
export class QueriedCoMapBase<M extends CoMap> {
coMap!: M;
id!: CoID<M>;
type!: "comap";
/** @internal */
static newWithKVPairs<M extends CoMap>(
coMap: M,
queryContext: QueryContext
): QueriedCoMap<M> {
const kv = {} as {
[K in keyof M["_shape"] & string]: ValueOrSubQueried<
M["_shape"][K]
>;
};
for (const key of coMap.keys()) {
const value = coMap.get(key);
if (value === undefined) continue;
queryContext.defineSubqueryPropertiesIn(
kv,
{
[key]: { value, enumerable: true },
},
[coMap.id]
);
}
return Object.assign(new QueriedCoMapBase(coMap, queryContext), kv);
}
/** @internal */
constructor(coMap: M, queryContext: QueryContext) {
Object.defineProperties(this, {
coMap: {
get() {
return coMap;
},
enumerable: false,
},
id: { value: coMap.id, enumerable: false },
type: { value: "comap", enumerable: false },
edits: {
value: Object.fromEntries(
coMap.keys().flatMap((key) => {
const edits = [...coMap.editsAt(key)].map((edit) =>
queryContext.defineSubqueryPropertiesIn(
{
tx: edit.tx,
at: new Date(edit.at),
},
{
by: { value: edit.by, enumerable: true },
value: {
value: edit.value,
enumerable: true,
},
},
[coMap.id]
)
);
const lastEdit = edits[edits.length - 1];
if (!lastEdit) return [];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const editsAtKey = {
by: lastEdit.by,
tx: lastEdit.tx,
at: lastEdit.at,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
value: lastEdit.value as any,
all: edits,
};
return [[key, editsAtKey]];
})
),
enumerable: false,
},
as: {
value: <O>(extension: QueryExtension<M, O>) => {
return queryContext.getOrCreateExtension(
coMap.id,
extension
);
},
enumerable: false,
},
});
}
edits!: {
[K in keyof M["_shape"] & string]:
| (QueriedCoMapEdit<M, K> & {
all: QueriedCoMapEdit<M, K>[];
})
| undefined;
};
get meta(): M["meta"] {
return this.coMap.meta;
}
get group(): Group {
return this.coMap.group;
}
get core(): CoValueCore {
return this.coMap.core;
}
set<K extends keyof M["_shape"] & string>(
key: K,
value: M["_shape"][K],
privacy?: "private" | "trusting"
): M;
set(
kv: {
[K in keyof M["_shape"] & string]?: M["_shape"][K];
},
privacy?: "private" | "trusting"
): M;
set<K extends keyof M["_shape"] & string>(
...args:
| [
{
[K in keyof M["_shape"] & string]?: M["_shape"][K];
},
("private" | "trusting")?
]
| [K, M["_shape"][K], ("private" | "trusting")?]
): M {
// eslint-disable-next-line @typescript-eslint/ban-types
return (this.coMap.set as Function)(...args);
}
delete(
key: keyof M["_shape"] & string,
privacy?: "private" | "trusting"
): M {
return this.coMap.delete(key, privacy);
}
mutate(
mutator: (mutable: MutableCoMap<M["_shape"], M["meta"]>) => void
): M {
return this.coMap.mutate(mutator);
}
as!: <O>(extension: QueryExtension<M, O>) => O | undefined;
}

View File

@@ -1,155 +0,0 @@
import { JsonValue } from "../jsonValue.js";
import { CoStream, MutableCoStream } from "../coValues/coStream.js";
import { CoValueCore } from "../coValueCore.js";
import { Group } from "../coValues/group.js";
import { AccountID, isAccountID } from "../coValues/account.js";
import { CoID, CoValue } from "../coValue.js";
import { SessionID, TransactionID } from "../ids.js";
import { ValueOrSubQueried, QueryContext } from "../queries.js";
import { QueriedAccount } from "./queriedAccount.js";
export type QueriedCoStreamItems<Item extends JsonValue | CoValue> = {
last?: ValueOrSubQueried<Item>;
by?: QueriedAccount;
tx?: TransactionID;
at?: Date;
all: {
value: ValueOrSubQueried<Item>;
by?: QueriedAccount;
tx: TransactionID;
at: Date;
}[];
};
export class QueriedCoStream<S extends CoStream> {
coStream!: S;
id: CoID<S>;
type = "costream" as const;
/** @internal */
constructor(coStream: S, queryContext: QueryContext) {
Object.defineProperty(this, "coStream", {
get() {
return coStream;
},
});
this.id = coStream.id;
this.perSession = Object.fromEntries(
coStream.sessions().map((sessionID) => {
const items = [...coStream.itemsIn(sessionID)].map((item) =>
queryContext.defineSubqueryPropertiesIn(
{
tx: item.tx,
at: new Date(item.at),
},
{
by: {
value: isAccountID(item.by)
? item.by
: (undefined as never),
enumerable: true,
},
value: {
value: item.value as S["_item"],
enumerable: true,
},
},
[coStream.id]
)
);
const lastItem = items[items.length - 1];
return [
sessionID,
{
get last() {
return lastItem?.value;
},
get by() {
return lastItem?.by;
},
tx: lastItem?.tx,
at: lastItem?.at,
all: items,
} satisfies QueriedCoStreamItems<S["_item"]>,
];
})
);
this.perAccount = Object.fromEntries(
[...coStream.accounts()].map((accountID) => {
const items = [...coStream.itemsBy(accountID)].map((item) => queryContext.defineSubqueryPropertiesIn(
{
tx: item.tx,
at: new Date(item.at),
},
{
by: {
value: isAccountID(item.by)
? item.by
: (undefined as never),
enumerable: true,
},
value: {
value: item.value as S["_item"],
enumerable: true,
},
},
[coStream.id]
));
const lastItem = items[items.length - 1];
return [
accountID,
{
get last() {
return lastItem?.value;
},
get by() {
return lastItem?.by;
},
tx: lastItem?.tx,
at: lastItem?.at,
all: items,
} satisfies QueriedCoStreamItems<S["_item"]>,
];
})
);
this.me = isAccountID(queryContext.node.account.id)
? this.perAccount[queryContext.node.account.id]
: undefined;
}
get meta(): S["meta"] {
return this.coStream.meta;
}
get group(): Group {
return this.coStream.group;
}
get core(): CoValueCore {
return this.coStream.core;
}
me?: QueriedCoStreamItems<S["_item"]>;
perAccount: {
[account: AccountID]: QueriedCoStreamItems<S["_item"]>;
};
perSession: {
[session: SessionID]: QueriedCoStreamItems<S["_item"]>;
};
push(item: S["_item"], privacy?: "private" | "trusting"): S {
return this.coStream.push(item, privacy);
}
mutate(
mutator: (mutable: MutableCoStream<S["_item"], S["meta"]>) => void
): S {
return this.coStream.mutate(mutator);
}
}

View File

@@ -1,90 +0,0 @@
import { Everyone, Group, InviteSecret } from "../coValues/group.js";
import { CoID } from "../coValue.js";
import { QueryContext, ValueOrSubQueried } from "../queries.js";
import { CoValueCore } from "../coValueCore.js";
import { Role } from "../permissions.js";
import { AccountID } from "../coValues/account.js";
import { CoMap } from "../coValues/coMap.js";
import { CoList } from "../coValues/coList.js";
import { CoStream } from "../coValues/coStream.js";
import { BinaryCoStream } from "../coValues/coStream.js";
export class QueriedGroup<G extends Group = Group> {
group!: G;
id!: CoID<G>;
type = "group" as const;
profile?: ValueOrSubQueried<G["_shape"]["profile"]>;
root?: ValueOrSubQueried<G["_shape"]["root"]>;
constructor(group: G, queryContext: QueryContext) {
const profileID = group.get("profile");
const rootID = group.get("root");
queryContext.defineSubqueryPropertiesIn(Object.defineProperties(this, {
group: {
get() {
return group;
},
enumerable: false,
},
id: { value: group.id, enumerable: false },
type: { value: "group", enumerable: false },
}), {
profile: {
value: profileID,
enumerable: false,
},
root: {
value: rootID,
enumerable: false,
},
}, [group.id]);
}
get meta(): G["meta"] {
return this.group.meta;
}
get core(): CoValueCore {
return this.group.core;
}
addMember(accountID: AccountID | Everyone, role: Role): G {
return this.group.addMember(accountID, role);
}
removeMember(accountID: AccountID): G {
return this.group.removeMember(accountID);
}
createInvite(role: "reader" | "writer" | "admin"): InviteSecret {
return this.group.createInvite(role);
}
createMap<M extends CoMap>(
init?: {
[K in keyof M["_shape"]]: M["_shape"][K];
},
meta?: M["meta"],
initPrivacy: "trusting" | "private" = "private"
): M {
return this.group.createMap(init, meta, initPrivacy);
}
createList<L extends CoList>(
init?: L["_item"][],
meta?: L["meta"],
initPrivacy: "trusting" | "private" = "private"
): L {
return this.group.createList(init, meta, initPrivacy);
}
createStream<C extends CoStream>(meta?: C["meta"]): C {
return this.group.createStream(meta);
}
createBinaryStream<C extends BinaryCoStream>(
meta: C["meta"] = { type: "binary" }
): C {
return this.group.createBinaryStream(meta);
}
}

View File

@@ -1,263 +0,0 @@
import { JsonValue } from "./jsonValue.js";
import { CoMap } from "./coValues/coMap.js";
import { CoStream } from "./coValues/coStream.js";
import { CoList } from "./coValues/coList.js";
import { Account, AccountID } from "./coValues/account.js";
import { CoID, CoValue } from "./coValue.js";
import { LocalNode } from "./localNode.js";
import {
QueriedCoMap,
QueriedCoMapBase,
} from "./queriedCoValues/queriedCoMap.js";
import { QueriedCoList } from "./queriedCoValues/queriedCoList.js";
import { QueriedCoStream } from "./queriedCoValues/queriedCoStream.js";
import { Group } from "./coValues/group.js";
import { QueriedAccount } from "./queriedCoValues/queriedAccount.js";
import { QueriedGroup } from "./queriedCoValues/queriedGroup.js";
export type Queried<T extends CoValue> = T extends CoMap
? T extends Account
? QueriedAccount<T>
: T extends Group
? QueriedGroup<T>
: QueriedCoMap<T>
: T extends CoList
? QueriedCoList<T>
: T extends CoStream
? T["meta"] extends { type: "binary" }
? never
: QueriedCoStream<T>
:
| QueriedAccount
| QueriedGroup
| QueriedCoMap<CoMap>
| QueriedCoList<CoList>
| QueriedCoStream<CoStream>;
export type ValueOrSubQueried<
V extends JsonValue | CoValue | CoID<CoValue> | undefined
> = V extends CoID<infer C>
? Queried<C> | undefined
: V extends CoValue
? Queried<V> | undefined
: V;
export interface CleanupCallbackAndUsable {
(): void;
[Symbol.dispose]: () => void;
}
export interface QueryExtension<T extends CoValue, O> {
id: string;
query(
base: T,
queryContext: QueryContext,
onUpdate: (value: O) => void
): () => void;
}
export class QueryContext {
values: {
[id: CoID<CoValue>]: {
lastUpdate: CoValue | undefined;
lastQueried: Queried<CoValue> | undefined;
render: () => void;
unsubscribe: () => void;
};
} = {};
extensions: {
[id: `${CoID<CoValue>}_${string}`]: {
lastOutput: unknown;
unsubscribe: () => void;
};
} = {};
node: LocalNode;
onUpdate: () => void;
constructor(node: LocalNode, onUpdate: () => void) {
this.node = node;
this.onUpdate = onUpdate;
}
query<T extends CoValue>(valueID: CoID<T>, alsoRender: CoID<CoValue>[]) {
let value = this.values[valueID];
if (!value) {
const render = () => {
let newQueried;
const lastUpdate = value!.lastUpdate;
if (lastUpdate instanceof CoMap) {
if (lastUpdate instanceof Account) {
newQueried = new QueriedAccount(
lastUpdate,
this
) as Queried<T>;
} else if (lastUpdate instanceof Group) {
newQueried = new QueriedGroup(
lastUpdate,
this
) as Queried<T>;
} else {
newQueried = QueriedCoMapBase.newWithKVPairs(
lastUpdate,
this
) as Queried<T>;
}
} else if (lastUpdate instanceof CoList) {
newQueried = new QueriedCoList(
lastUpdate,
this
) as Queried<T>;
} else if (lastUpdate instanceof CoStream) {
if (lastUpdate.meta?.type === "binary") {
// Querying binary string not yet implemented
} else {
newQueried = new QueriedCoStream(
lastUpdate,
this
) as Queried<T>;
}
}
// console.log(
// "Rendered ",
// valueID,
// lastUpdate?.constructor.name,
// newQueried
// );
value!.lastQueried = newQueried;
for (const alsoRenderID of alsoRender) {
// console.log("Also rendering", alsoRenderID);
this.values[alsoRenderID]?.render();
}
};
value = {
lastQueried: undefined,
lastUpdate: undefined,
render,
unsubscribe: this.node.subscribe(valueID, (valueUpdate) => {
value!.lastUpdate = valueUpdate;
value!.render();
this.onUpdate();
}),
};
this.values[valueID] = value;
}
return value.lastQueried as Queried<T> | undefined;
}
queryIfCoID<T extends JsonValue | undefined>(value: T, alsoRender: CoID<CoValue>[]): T extends CoID<infer C> ? Queried<C> | undefined : T {
if (typeof value === "string" && value.startsWith("co_")) {
return this.query(value as CoID<CoValue>, alsoRender) as T extends CoID<infer C> ? Queried<C> | undefined : never;
} else {
return value as T extends CoID<infer C> ? Queried<C> | undefined : T;
}
}
valueOrSubQueryPropertyDescriptor<T extends JsonValue | undefined>(
value: T,
alsoRender: CoID<CoValue>[]
): T extends CoID<infer C>
? { get(): Queried<C> | undefined }
: { value: T } {
if (typeof value === "string" && value.startsWith("co_")) {
// TODO: when we track render dirty status, we can actually return the queried value without a getter if it's up to date
return {
get: () => this.query(value as CoID<CoValue>, alsoRender),
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any;
} else {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return { value: value } as any;
}
}
defineSubqueryPropertiesIn<
O extends object,
P extends {
[key: string]: { value: JsonValue | undefined; enumerable: boolean };
}
>(
obj: O,
subqueryProps: P,
alsoRender: CoID<CoValue>[]
): O & {
[Key in keyof P]: ValueOrSubQueried<P[Key]["value"]>;
} {
for (const [key, descriptor] of Object.entries(subqueryProps)) {
Object.defineProperty(
obj,
key,
{
...this.valueOrSubQueryPropertyDescriptor(descriptor.value, alsoRender),
enumerable: descriptor.enumerable,
}
);
}
return obj as O & {
[Key in keyof P]: ValueOrSubQueried<P[Key]["value"]>
};
}
getOrCreateExtension<T extends CoValue, O>(
valueID: CoID<T>,
extension: QueryExtension<T, O>
): O | undefined {
const id = `${valueID}_${extension.id}`;
let ext = this.extensions[id as keyof typeof this.extensions];
if (!ext) {
ext = {
lastOutput: undefined,
unsubscribe: extension.query(
this.node
.expectCoValueLoaded(valueID)
.getCurrentContent() as T,
this,
(output) => {
ext!.lastOutput = output;
this.values[valueID]?.render();
this.onUpdate();
}
),
};
this.extensions[id as keyof typeof this.extensions] = ext;
}
return ext.lastOutput as O | undefined;
}
cleanup() {
for (const child of Object.values(this.values)) {
child.unsubscribe?.();
}
for (const extension of Object.values(this.extensions)) {
extension.unsubscribe();
}
}
}
export function query<T extends CoValue>(
id: CoID<T>,
node: LocalNode,
callback: (queried: Queried<T> | undefined) => void
): CleanupCallbackAndUsable {
// console.log("querying", id);
const context = new QueryContext(node, () => {
const rootQueried = context.values[id]?.lastQueried as
| Queried<T>
| undefined;
callback(rootQueried);
});
context.query(id, []);
const cleanup = function cleanup() {
context.cleanup();
} as CleanupCallbackAndUsable;
cleanup[Symbol.dispose] = cleanup;
return cleanup;
}

View File

@@ -225,12 +225,19 @@ export class SyncManager {
peer.optimisticKnownStates[id] || emptyKnownState(id);
const sendPieces = async () => {
let lastYield = performance.now();
for (const [_i, piece] of newContentPieces.entries()) {
// console.log(
// `${id} -> ${peer.id}: Sending content piece ${i + 1}/${newContentPieces.length} header: ${!!piece.header}`,
// // Object.values(piece.new).map((s) => s.newTransactions)
// );
await this.trySendToPeer(peer, piece);
if (performance.now() - lastYield > 10) {
await new Promise<void>((resolve) => {
setTimeout(resolve, 0);
});
lastYield = performance.now();
}
}
};
@@ -315,19 +322,20 @@ export class SyncManager {
trySendToPeer(peer: PeerState, msg: SyncMessage) {
return new Promise<void>((resolve) => {
const timeout = setTimeout(() => {
console.error(
new Error(
`Writing to peer ${peer.id} took >1s - this should never happen as write should resolve quickly or error`
)
);
resolve();
}, 1000);
const start = Date.now()
peer.outgoing
.write(msg)
.then(() => {
clearTimeout(timeout);
resolve();
const end = Date.now();
if (end - start > 1000) {
console.error(
new Error(
`Writing to peer "${peer.id}" took ${Math.round((Date.now() - start)/100)/10}s - this should never happen as write should resolve quickly or error`
)
);
} else {
resolve();
}
})
.catch((e) => {
console.error(
@@ -450,6 +458,7 @@ export class SyncManager {
entry = {
state: "loaded",
coValue: coValue,
onProgress: entry.onProgress
};
this.local.coValues[msg.id] = entry;
@@ -509,6 +518,11 @@ export class SyncManager {
);
}
const theirTotalnTxs = Object.values(peer.optimisticKnownStates[msg.id]?.sessions || {}).reduce((sum, nTxs) => sum + nTxs, 0);
const ourTotalnTxs = Object.values(coValue.sessions).reduce((sum, session) => sum + session.transactions.length, 0);
entry.onProgress?.(ourTotalnTxs / theirTotalnTxs);
if (!success) {
console.error(
"Failed to add transactions",
@@ -522,9 +536,9 @@ export class SyncManager {
continue;
}
peerOptimisticKnownState.sessions[sessionID] =
peerOptimisticKnownState.sessions[sessionID] = Math.max(peerOptimisticKnownState.sessions[sessionID] || 0,
newContentForSession.after +
newContentForSession.newTransactions.length;
newContentForSession.newTransactions.length);
}
if (resolveAfterDone) {

View File

@@ -315,14 +315,14 @@ test("Empty BinaryCoStream works", () => {
if (
content.type !== "costream" ||
content.meta?.type !== "binary" ||
content.headerMeta?.type !== "binary" ||
!(content instanceof BinaryCoStream)
) {
throw new Error("Expected binary stream");
}
expect(content.type).toEqual("costream");
expect(content.meta.type).toEqual("binary");
expect(content.headerMeta.type).toEqual("binary");
expect(content.toJSON()).toEqual({});
expect(content.getBinaryChunks()).toEqual(undefined);
});
@@ -341,7 +341,7 @@ test("Can push into BinaryCoStream", () => {
if (
content.type !== "costream" ||
content.meta?.type !== "binary" ||
content.headerMeta?.type !== "binary" ||
!(content instanceof BinaryCoStream)
) {
throw new Error("Expected binary stream");
@@ -398,7 +398,7 @@ test("When adding large transactions (small fraction of MAX_RECOMMENDED_TX_SIZE)
if (
content.type !== "costream" ||
content.meta?.type !== "binary" ||
content.headerMeta?.type !== "binary" ||
!(content instanceof BinaryCoStream)
) {
throw new Error("Expected binary stream");
@@ -474,7 +474,7 @@ test("When adding large transactions (bigger than MAX_RECOMMENDED_TX_SIZE), we s
if (
content.type !== "costream" ||
content.meta?.type !== "binary" ||
content.headerMeta?.type !== "binary" ||
!(content instanceof BinaryCoStream)
) {
throw new Error("Expected binary stream");

View File

@@ -46,6 +46,6 @@ test("Can create a BinaryCoStream in a group", () => {
const stream = group.createBinaryStream();
expect(stream.core.getCurrentContent().type).toEqual("costream");
expect(stream.meta.type).toEqual("binary");
expect(stream.headerMeta.type).toEqual("binary");
expect(stream instanceof BinaryCoStream).toEqual(true);
})

View File

@@ -1,337 +0,0 @@
import {
BinaryCoStream,
CoList,
CoMap,
CoStream,
Group,
LocalNode,
cojsonReady,
} from "..";
beforeEach(async () => {
await cojsonReady;
});
test("Queries with maps work", async () => {
const { node, accountID } =
LocalNode.withNewlyCreatedAccount({name: "Hermes Puggington"});
const group = node.createGroup();
let map = group.createMap<
CoMap<{
hello: "world";
subMap: CoMap<{
hello: "world" | "moon" | "sun";
id: string;
}>["id"];
}>
>();
const done = new Promise<void>((resolve) => {
const unsubQuery = node.query(map.id, (queriedMap) => {
// console.log("update", update);
if (queriedMap) {
expect(queriedMap.type).toBe("comap");
expect(queriedMap.id).toEqual(map.id);
expect(queriedMap.core).toEqual(map.core);
expect(queriedMap.group).toBeInstanceOf(Group);
expect(queriedMap.group.id).toBe(group.id);
expect(queriedMap.meta).toBe(null);
expect(queriedMap.hello).toBe("world");
expect(Object.keys(queriedMap)).toEqual(["hello", "subMap"]);
if (queriedMap.edits.hello?.by?.profile?.name) {
expect(queriedMap.edits.hello.by.id).toEqual(accountID);
expect(queriedMap.edits.hello.by.profile.id).toEqual(
node.expectProfileLoaded(accountID).id
);
expect(queriedMap.edits.hello.by.profile.name).toEqual(
"Hermes Puggington"
);
expect(queriedMap.edits.hello.by.isMe).toBe(true);
expect(queriedMap.edits.hello.tx).toEqual(
map.lastEditAt("hello")!.tx
);
expect(queriedMap.edits.hello.at).toEqual(
new Date(map.lastEditAt("hello")!.at)
);
if (queriedMap.subMap) {
expect(queriedMap.subMap.type).toBe("comap");
expect(queriedMap.subMap.id).toEqual("foreignID");
expect(queriedMap.subMap.core).toEqual(subMap.core);
expect(queriedMap.subMap.group).toBeInstanceOf(Group);
expect(queriedMap.subMap.group.id).toBe(group.id);
expect(queriedMap.subMap.meta).toBe(null);
if (queriedMap.subMap.hello === "moon") {
// console.log("got to 'moon'");
queriedMap.subMap.set("hello", "sun");
} else if (
queriedMap.subMap.hello === "sun" &&
queriedMap.subMap.edits.hello?.by?.profile?.name ===
"Hermes Puggington"
) {
// console.log("final update", queriedMap);
resolve();
unsubQuery();
}
}
}
}
});
});
map = map.set("hello", "world");
let subMap = group.createMap<
CoMap<{
hello: "world" | "moon" | "sun";
id: string;
}>
>();
map = map.set("subMap", subMap.id);
subMap = subMap.mutate((subMap) => {
subMap.set("hello", "world");
subMap.set("id", "foreignID");
});
subMap = subMap.set("hello", "moon");
await done;
});
test("Queries with lists work", () => {
const { node, accountID } =
LocalNode.withNewlyCreatedAccount({name: "Hermes Puggington"});
const group = node.createGroup();
let list = group.createList<CoList<string>>();
const done = new Promise<void>((resolve) => {
const unsubQuery = node.query(list.id, (queriedList) => {
if (queriedList) {
// console.log("update", queriedList, queriedList.edits);
expect(queriedList.type).toBe("colist");
expect(queriedList.id).toEqual(list.id);
expect(queriedList.core).toEqual(list.core);
expect(queriedList.group).toBeInstanceOf(Group);
expect(queriedList.group.id).toBe(group.id);
expect(queriedList.meta).toBe(null);
expect(queriedList[0]).toBe("hello");
expect(queriedList[1]).toBe("world");
expect(queriedList[2]).toBe("moon");
if (queriedList.edits[2]?.by?.profile?.name) {
expect(queriedList.edits[2].by.id).toEqual(accountID);
expect(queriedList.edits[2].by.profile.id).toEqual(
node.expectProfileLoaded(accountID).id
);
expect(queriedList.edits[2].by.profile.name).toEqual(
"Hermes Puggington"
);
expect(queriedList.edits[2].by.isMe).toBe(true);
expect(queriedList.edits[2].at).toBeInstanceOf(Date);
if (queriedList.length === 3) {
queriedList.append("sun");
} else if (
queriedList.length === 4 &&
queriedList.edits[3]?.by?.profile?.name ===
"Hermes Puggington"
) {
expect(queriedList[3]).toBe("sun");
// console.log("final update", queriedList);
resolve();
unsubQuery();
}
}
}
});
});
list = list.mutate((list) => {
list.append("hello");
list.append("world");
list.append("moon");
});
return done;
});
test("List of nested maps works", () => {
const { node } = LocalNode.withNewlyCreatedAccount({name: "Hermes Puggington"});
const group = node.createGroup();
let list = group.createList<CoList<CoMap<{ hello: "world" }>["id"]>>();
const done = new Promise<void>((resolve) => {
const unsubQuery = node.query(list.id, (queriedList) => {
if (queriedList && queriedList[0]) {
// console.log("update", queriedList);
expect(queriedList[0]).toMatchObject({
hello: "world",
id: list.get(0)!,
});
// console.log("final update", queriedList);
resolve();
unsubQuery();
}
});
});
list = list.append(
group.createMap<CoMap<{ hello: "world" }>>({
hello: "world",
}).id
);
return done;
});
test("Can call .map on a quieried coList", async () => {
const { node } = LocalNode.withNewlyCreatedAccount({name: "Hermes Puggington"});
const group = node.createGroup();
let list = group.createList<CoList<string>>();
const done = new Promise<void>((resolve) => {
const unsubQuery = node.query(list.id, (queriedList) => {
if (queriedList && queriedList[0]) {
// console.log("update", queriedList);
expect(queriedList.map((item) => item + "!!!")).toEqual([
"hello!!!",
"world!!!",
]);
// console.log("final update", queriedList);
resolve();
unsubQuery();
}
});
});
list = list.mutate((list) => {
list.append("hello");
list.append("world");
});
await done;
});
test("Queries with streams work", () => {
const { node, accountID } =
LocalNode.withNewlyCreatedAccount({name: "Hermes Puggington"});
const group = node.createGroup();
let stream = group.createStream<CoStream<string>>();
const done = new Promise<void>((resolve) => {
const unsubQuery = node.query(stream.id, (queriedStream) => {
if (queriedStream) {
// console.log("update", queriedStream);
if (queriedStream.me?.by?.profile?.name) {
expect(queriedStream.type).toBe("costream");
expect(queriedStream.id).toEqual(stream.id);
expect(queriedStream.core).toEqual(stream.core);
expect(queriedStream.group).toBeInstanceOf(Group);
expect(queriedStream.group.id).toBe(group.id);
expect(queriedStream.meta).toBe(null);
expect(queriedStream.perSession[node.currentSessionID].last).toEqual(
"world"
);
expect(queriedStream.perSession[node.currentSessionID].all[0].value).toEqual("hello");
expect(queriedStream.perSession[node.currentSessionID].all[0].at).toEqual(new Date(
stream.items[
node.currentSessionID
][0].madeAt
));
expect(queriedStream.perSession[node.currentSessionID].all[1].value).toEqual("world");
expect(queriedStream.perSession[node.currentSessionID].all[1].at).toEqual(new Date(
stream.items[
node.currentSessionID
][1].madeAt
));
expect(queriedStream.perSession[node.currentSessionID].by?.id).toEqual(accountID);
expect(queriedStream.perSession[node.currentSessionID].by?.profile?.id).toEqual(
node.expectProfileLoaded(accountID).id
);
expect(queriedStream.perSession[node.currentSessionID].by?.profile?.name).toEqual(
"Hermes Puggington"
);
expect(queriedStream.perSession[node.currentSessionID].by?.isMe).toBe(true);
expect(queriedStream.perSession[node.currentSessionID].at).toBeInstanceOf(Date);
expect(queriedStream.perAccount[accountID].last).toEqual(
"world"
);
expect(queriedStream.perAccount[accountID].all[0].value).toEqual("hello");
expect(queriedStream.perAccount[accountID].all[0].at).toEqual(new Date(
stream.items[
node.currentSessionID
][0].madeAt
));
expect(queriedStream.perAccount[accountID].all[1].value).toEqual("world");
expect(queriedStream.perAccount[accountID].all[1].at).toEqual(new Date(
stream.items[
node.currentSessionID
][1].madeAt
));
expect(queriedStream.perAccount[accountID].by?.id).toEqual(accountID);
expect(queriedStream.perAccount[accountID].by?.profile?.id).toEqual(
node.expectProfileLoaded(accountID).id
);
expect(queriedStream.perAccount[accountID].by?.profile?.name).toEqual(
"Hermes Puggington"
);
expect(queriedStream.perAccount[accountID].by?.isMe).toBe(true);
expect(queriedStream.perAccount[accountID].at).toBeInstanceOf(Date);
expect(queriedStream.me).toEqual(queriedStream.perAccount[accountID]);
// console.log("final update", queriedStream);
resolve();
unsubQuery();
}
}
});
});
stream = stream.push("hello");
stream = stream.push("world");
return done;
});
test("Streams of nested maps work", () => {
const { node } = LocalNode.withNewlyCreatedAccount({name:"Hermes Puggington"});
const group = node.createGroup();
let stream =
group.createStream<CoStream<CoMap<{ hello: "world" }>["id"]>>();
const done = new Promise<void>((resolve) => {
const unsubQuery = node.query(stream.id, (queriedStream) => {
if (queriedStream && queriedStream.me?.last) {
// console.log("update", queriedList);
expect(queriedStream.me.last).toMatchObject({
hello: "world",
id: map.id,
});
// console.log("final update", queriedList);
resolve();
unsubQuery();
}
});
});
const map = group.createMap<CoMap<{ hello: "world" }>>({
hello: "world",
});
stream = stream.push(map.id);
return done;
});

View File

@@ -1,7 +1,7 @@
import { AgentSecret, createdNowUnique, getAgentID, newRandomAgentSecret } from "../crypto.js";
import { newRandomSessionID } from "../coValueCore.js";
import { LocalNode } from "../localNode.js";
import { expectGroup } from "../coValues/group.js";
import { expectGroup } from "../typeUtils/expectGroup.js";
import { AnonymousControlledAccount } from "../coValues/account.js";
import { SessionID } from "../ids.js";
// @ts-ignore

View File

@@ -0,0 +1,9 @@
import { AgentID, SessionID } from "../ids.js";
import { AccountID } from "../coValues/account.js";
export function accountOrAgentIDfromSessionID(
sessionID: SessionID
): AccountID | AgentID {
return sessionID.split("_session")[0] as AccountID | AgentID;
}

View File

@@ -0,0 +1,15 @@
import { expectMap, type CoValue } from "../coValue.js";
import { Group } from "../coValues/group.js";
export function expectGroup(content: CoValue): Group {
const map = expectMap(content);
if (map.core.header.ruleset.type !== "group") {
throw new Error("Expected group ruleset in group");
}
if (!(map instanceof Group)) {
throw new Error("Expected group");
}
return map;
}

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