Compare commits

...

15 Commits

Author SHA1 Message Date
Anselm
c1dfac7260 Publish
- jazz-example-chat@0.0.44
 - jazz-example-file-drop@0.0.61
 - jazz-example-pets@0.0.61
 - jazz-example-todo@0.0.61
 - jazz-example-twit@0.0.61
 - hashroute@0.1.2
 - jazz-browser@0.4.14
 - jazz-browser-auth-local@0.4.14
 - jazz-browser-media-images@0.4.14
 - jazz-react@0.4.14
 - jazz-react-auth-local@0.4.14
2023-10-13 11:20:40 +01:00
Anselm
bf29cb3bae Make stuff mergeable 2023-10-13 11:20:07 +01:00
Anselm
a0a9b3f851 Merge branch 'main' into new-hp 2023-10-13 11:15:24 +01:00
Anselm
4c4deb22c9 Publish
- jazz-example-chat@0.0.43
 - jazz-example-pets@0.0.19
 - jazz-example-todo@0.0.43
 - jazz-example-twit@0.0.6
 - hashroute@0.1.1
 - 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-13 11:13:24 +01:00
Anselm
a42c497055 Small imrovements to chat example 2023-10-13 11:12:32 +01:00
Anselm
f1dcdb20bc lots of new hp improvements 2023-10-13 11:11:37 +01:00
Anselm Eickhoff
46330ae201 Merge pull request #117 from gardencmp:data-throughput
Improve data throughput of BinaryCoStreams
2023-10-09 11:26:56 +01:00
Anselm
bfe3595b4c Fix errors in file-drop example 2023-10-09 11:23:15 +01:00
Anselm
34c39e6a55 Scale down other examples and add file-drop 2023-10-09 11:12:17 +01:00
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
8c0b2da461 Start custom solution with nextjs & shiki-twoslash 2023-10-06 09:43:16 +01:00
Anselm
16b3e1381b Sketch of new homepage with nextra + chat example 2023-10-04 19:59:32 +01:00
142 changed files with 15323 additions and 1074 deletions

View File

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

287
DOCS.md
View File

@@ -54,6 +54,7 @@ export function WithJazz(props: {
children: ReactNode,
syncAddress?: string,
migration?: AccountMigration,
apiKey?: string,
}): Element
```
Top-level component that provides Jazz context to your whole app, so you can use Jazz hooks in your components.
@@ -67,6 +68,7 @@ Top-level component that provides Jazz context to your whole app, so you can use
| `props.auth` | An auth provider (renders login/sign-up UI if not logged in) - see available providers in the [Documentation](../../../DOCS.md#auth-providers) |
| `props.syncAddress?` | The address of the upstream syncing peer. Defaults to `wss://sync.jazz.tool` (Jazz Global Mesh). If not set explicitly, it can also be temporarily overwritten by setting the `sync` query parameter in the URL, like `https://your-app.example.net?sync=ws://localhost:4200`. |
| `props.migration?` | TODO: document |
| `props.apiKey?` | TODO: document |
##### Example:
@@ -265,6 +267,33 @@ TODO: document
----
## `DemoAuth({appName, appHostname?, Component?})`
<sup>(function in `jazz-react`)</sup>
```typescript
export function DemoAuth({
appName: string,
appHostname?: string,
Component?: DemoAuthComponent,
}): ReactAuthHook
```
TODO: document
### Parameters:
| name | description |
| ----: | ---- |
| `__namedParameters.appName` | TODO: document |
| `__namedParameters.appHostname?` | TODO: document |
| `__namedParameters.Component?` | TODO: document |
----
## `ResolvedAccount`
@@ -2696,13 +2725,14 @@ TODO: document
<details>
<summary><b><code>.load(id)</code></b> </summary>
<summary><b><code>.load(id, onProgress?)</code></b> </summary>
```typescript
class LocalNode {
load<T extends CoValue>(
id: CoID<T>
id: CoID<T>,
onProgress?: (progress: number) => void
): Promise<T> {...}
}
@@ -2719,6 +2749,7 @@ for listening to subsequent updates to the CoValue.
| ----: | ---- |
| `id` | TODO: document |
</details>
@@ -6428,6 +6459,88 @@ TODO: document
### `BinaryCoStream`: Methods
<details>
<summary><b><code>.push(item, privacy?)</code></b> </summary>
```typescript
class BinaryCoStream<Meta> {
push(
item: BinaryStreamItem,
privacy?: "private" | "trusting"
): BinaryCoStream<Meta> {...}
}
```
### Parameters:
| name | description |
| ----: | ---- |
| `item` | TODO: document |
| `privacy?` | TODO: document |
</details>
<details>
<summary><b><code>.push(item, privacy, returnNewStream)</code></b> <sub><sup>(undocumented)</sup></sub></summary>
```typescript
class BinaryCoStream<Meta> {
push(
item: BinaryStreamItem,
privacy: "private" | "trusting",
returnNewStream: true
): BinaryCoStream<Meta> {...}
}
```
TODO: document
### Parameters:
| name | description |
| ----: | ---- |
| `item` | TODO: document |
| `privacy` | TODO: document |
| `returnNewStream` | TODO: document |
</details>
<details>
<summary><b><code>.push(item, privacy, returnNewStream)</code></b> <sub><sup>(undocumented)</sup></sub></summary>
```typescript
class BinaryCoStream<Meta> {
push(
item: BinaryStreamItem,
privacy: "private" | "trusting",
returnNewStream: false
): void {...}
}
```
TODO: document
### Parameters:
| name | description |
| ----: | ---- |
| `item` | TODO: document |
| `privacy` | TODO: document |
| `returnNewStream` | TODO: document |
</details>
<details>
@@ -6439,7 +6552,7 @@ class BinaryCoStream<Meta> {
startBinaryStream(
settings: BinaryStreamInfo,
privacy?: "private" | "trusting" = "private"
): BinaryCoStream<Meta> {...}
): void {...}
}
```
@@ -6465,7 +6578,7 @@ class BinaryCoStream<Meta> {
pushBinaryStreamChunk(
chunk: Uint8Array,
privacy?: "private" | "trusting" = "private"
): BinaryCoStream<Meta> {...}
): void {...}
}
```
@@ -9416,7 +9529,7 @@ TODO: document
class CoValueCore {
_decryptionCache: {
[key: Encrypted<JsonValue[], JsonValue>]: Stringified<JsonValue[]> | undefined }
[key: Encrypted<JsonValue[], JsonValue>]: JsonValue[] | undefined }
}
```
@@ -10084,14 +10197,14 @@ TODO: document
----
## `createBinaryStreamFromBlob(blob, inGroup, meta?)`
## `createBinaryStreamFromBlob(blob, inGroup, meta?, onProgress?)`
<sup>(function in `jazz-browser`)</sup>
```typescript
export function createBinaryStreamFromBlob<C extends BinaryCoStream<BinaryCoStreamMeta>>(blob: Blob | File, inGroup: Group<Profile<ProfileShape, ProfileMeta>, CoMap<{
[key: string]: JsonValue | undefined }, null | JsonObject>, null | JsonObject> | ResolvedGroup<Group<Profile<ProfileShape, ProfileMeta>, CoMap<{
[key: string]: JsonValue | undefined }, null | JsonObject>, null | JsonObject>>, meta: C["headerMeta"]): Promise<C>
[key: string]: JsonValue | undefined }, null | JsonObject>, null | JsonObject>>, meta: C["headerMeta"], onProgress: (progress: number) => void): Promise<C>
```
TODO: document
@@ -10107,14 +10220,15 @@ TODO: document
----
## `readBlobFromBinaryStream(streamId, node, allowUnfinished?)`
## `readBlobFromBinaryStream(streamId, node, allowUnfinished?, onProgress?)`
<sup>(function in `jazz-browser`)</sup>
```typescript
export function readBlobFromBinaryStream<C extends BinaryCoStream<BinaryCoStreamMeta>>(streamId: CoID<C>, node: LocalNode, allowUnfinished: boolean): Promise<Blob | undefined>
export function readBlobFromBinaryStream<C extends BinaryCoStream<BinaryCoStreamMeta>>(streamId: CoID<C>, node: LocalNode, allowUnfinished: boolean, onProgress: (progress: number) => void): Promise<Blob | undefined>
```
TODO: document
@@ -10130,6 +10244,7 @@ TODO: document
----
## `autoSub(id, node, callback)`
@@ -10180,6 +10295,109 @@ TODO: document
----
## `BrowserDemoAuth`
<sup>(class in `jazz-browser`)</sup>
```typescript
export class BrowserDemoAuth implements AuthProvider {...}
```
TODO: document
### `BrowserDemoAuth`: Constructors
<details>
<summary><b><code>new BrowserDemoAuth</code></b>(driver, appName)</code></b> <sub><sup>(undocumented)</sup></sub></summary>
```typescript
class BrowserDemoAuth {
constructor(
driver: BrowserDemoAuthDriver,
appName: string
): BrowserDemoAuth {...}
}
```
TODO: document
### Parameters:
| name | description |
| ----: | ---- |
| `driver` | TODO: document |
| `appName` | TODO: document |
</details>
<br/>
### `BrowserDemoAuth`: Methods
<details>
<summary><b><code>.createNode(getSessionFor, initialPeers, migration?)</code></b> <sub><sup>(undocumented)</sup></sub></summary>
```typescript
class BrowserDemoAuth {
createNode(
getSessionFor: SessionProvider,
initialPeers: Peer[],
migration?: AccountMigration
): Promise<LocalNode> {...}
}
```
TODO: document
### Parameters:
| name | description |
| ----: | ---- |
| `getSessionFor` | TODO: document |
| `initialPeers` | TODO: document |
| `migration?` | TODO: document |
</details>
<br/>
### `BrowserDemoAuth`: Properties
<details>
<summary><b><code>.driver</code></b> <sub><sup>(undocumented)</sup></sub></summary>
```typescript
class BrowserDemoAuth {
driver: BrowserDemoAuthDriver
}
```
TODO: document
</details>
<details>
<summary><b><code>.appName</code></b> <sub><sup>(undocumented)</sup></sub></summary>
```typescript
class BrowserDemoAuth {
appName: string
}
```
TODO: document
</details>
----
## `ResolvedCoStream`
@@ -12708,6 +12926,57 @@ TODO: document
----
## `BrowserDemoAuthDriver`
<sup>(interface in `jazz-browser`)</sup>
```typescript
export interface BrowserDemoAuthDriver {...}
```
TODO: document
### `BrowserDemoAuthDriver`: Properties
<details>
<summary><b><code>.onReady</code></b> <sub><sup>(undocumented)</sup></sub></summary>
```typescript
interface BrowserDemoAuthDriver {
onReady: (next: {
signUp: (username: string) => Promise<void>,
existingUsers: string[],
logInAs: (existingUser: string) => Promise<void>,
}) => void
}
```
TODO: document
</details>
<details>
<summary><b><code>.onSignedIn</code></b> <sub><sup>(undocumented)</sup></sub></summary>
```typescript
interface BrowserDemoAuthDriver {
onSignedIn: (next: {
logOut: () => void,
}) => void
}
```
TODO: document
</details>
----
## `AutoSubExtension`

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/chat/.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?

4
examples/chat/Dockerfile Normal file
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/

64
examples/chat/README.md Normal file
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).

14
examples/chat/index.html Normal file
View File

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

View File

@@ -0,0 +1,56 @@
job "chat$BRANCH_SUFFIX" {
region = "global"
datacenters = ["*"]
group "static" {
count = 8
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 = "chat$BRANCH_SUFFIX"
port = "http"
provider = "consul"
}
resources {
cpu = 50 # MHz
memory = 50 # MB
}
}
}
}
# deploy bump 4

View File

@@ -0,0 +1,48 @@
{
"name": "jazz-example-chat",
"private": true,
"version": "0.0.44",
"type": "module",
"scripts": {
"dev": "vite",
"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",
"hashroute": "^0.1.2",
"jazz-react": "^0.4.14",
"jazz-react-auth-local": "^0.4.14",
"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",
"react-use": "^17.4.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

35
examples/chat/src/app.tsx Normal file
View File

@@ -0,0 +1,35 @@
import { WithJazz, useJazz, DemoAuth } from 'jazz-react';
import ReactDOM from 'react-dom/client';
import { HashRoute } from 'hashroute';
import { ChatWindow } from './chatWindow.tsx';
import { Chat } from './dataModel.ts';
ReactDOM.createRoot(document.getElementById('root')!).render(
<WithJazz auth={DemoAuth({ appName: 'Jazz Chat Example' })} apiKey="api_z9d034j3t34ht034ir">
<App />
</WithJazz>,
);
function App() {
return <div className='flex flex-col items-center justify-between w-screen h-screen p-2 dark:bg-black dark:text-white'>
<button onClick={useJazz().logOut} className='rounded mb-5 px-2 py-1 bg-stone-200 dark:bg-stone-800 dark:text-white self-end'>
Log Out
</button>
{HashRoute({
'/': <Home />,
'/chat/:id': (id) => <ChatWindow chatId={id as Chat['id']} />,
})}
</div>
}
function Home() {
const { me } = useJazz();
return <button className='rounded py-2 px-4 bg-stone-200 dark:bg-stone-800 dark:text-white my-auto'
onClick={() => {
const group = me.createGroup().addMember('everyone', 'writer');
const chat = group.createList<Chat>();
location.hash = '/chat/' + chat.id;
}}>
Create New Chat
</button>
}

View File

@@ -0,0 +1,43 @@
import { useAutoSub } from 'jazz-react';
import { Chat, Message } from './dataModel.ts';
export function ChatWindow(props: { chatId: Chat['id'] }) {
const chat = useAutoSub(props.chatId);
return chat ? <div className='w-full max-w-xl h-full flex flex-col items-stretch'>
{
chat.map((msg, i) => (
<ChatBubble key={msg?.id}
text={msg?.text}
by={chat.meta.edits[i].by?.profile?.name}
byMe={chat.meta.edits[i].by?.isMe}
at={chat.meta.edits[i].at} />
))
}
<ChatInput onSubmit={(text) => {
const msg = chat.meta.group.createMap<Message>({ text });
chat.append(msg.id);
}}/>
</div> : <div>Loading...</div>;
}
function ChatBubble(props: { text?: string, by?: string, at?: Date, byMe?: boolean }) {
return <div className={`${props.byMe ? 'items-end' : 'items-start'} flex flex-col`}>
<div className='rounded-xl bg-stone-100 dark:bg-stone-700 dark:text-white py-2 px-4 mt-2 min-w-[5rem]'>
{ props.text }
</div>
<div className='text-xs text-neutral-500 ml-2'>
{ props.by } { props.at?.getHours() }:{ props.at?.getMinutes() }
</div>
</div>;
}
function ChatInput(props: { onSubmit: (text: string) => void }) {
return <input className='rounded p-2 border mt-auto dark:bg-black dark:text-white dark:border-stone-700'
placeholder='Type a message and press Enter'
onKeyDown={({ key, currentTarget: input }) => {
if (key !== 'Enter' || !input.value) return;
props.onSubmit(input.value);
input.value = '';
}}/>
}

View File

@@ -0,0 +1,4 @@
import { CoMap, CoList } from 'cojson';
export type Chat = CoList<Message['id']>;
export type Message = CoMap<{ text: string }>;

View File

@@ -0,0 +1,78 @@
@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;
margin: 0;
padding: 0;
}
}

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

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

View File

@@ -0,0 +1,75 @@
/** @type {import('tailwindcss').Config} */
module.exports = {
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

@@ -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.61",
"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.14",
"jazz-react-auth-local": "^0.4.14",
"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,187 @@
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";
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

@@ -3,7 +3,7 @@ job "example-pets$BRANCH_SUFFIX" {
datacenters = ["*"]
group "static" {
count = 8
count = 4
network {
port "http" {

View File

@@ -1,7 +1,7 @@
{
"name": "jazz-example-pets",
"private": true,
"version": "0.0.21",
"version": "0.0.61",
"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.9",
"jazz-react": "^0.4.8",
"jazz-react-auth-local": "^0.4.8",
"jazz-browser-media-images": "^0.4.14",
"jazz-react": "^0.4.14",
"jazz-react-auth-local": "^0.4.14",
"lucide-react": "^0.274.0",
"qrcode": "^1.5.3",
"react": "^18.2.0",

View File

@@ -3,7 +3,7 @@ job "example-todo$BRANCH_SUFFIX" {
datacenters = ["*"]
group "static" {
count = 8
count = 4
network {
port "http" {

View File

@@ -1,7 +1,7 @@
{
"name": "jazz-example-todo",
"private": true,
"version": "0.0.45",
"version": "0.0.61",
"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.8",
"jazz-react-auth-local": "^0.4.8",
"jazz-react": "^0.4.14",
"jazz-react-auth-local": "^0.4.14",
"lucide-react": "^0.274.0",
"qrcode": "^1.5.3",
"react": "^18.2.0",

View File

@@ -3,7 +3,7 @@ job "twit$BRANCH_SUFFIX" {
datacenters = ["*"]
group "static" {
count = 8
count = 4
network {
port "http" {

View File

@@ -1,7 +1,7 @@
{
"name": "jazz-example-twit",
"private": true,
"version": "0.0.8",
"version": "0.0.61",
"type": "module",
"scripts": {
"dev": "vite",
@@ -18,9 +18,9 @@
"class-variance-authority": "^0.7.0",
"clsx": "^2.0.0",
"javascript-time-ago": "^2.5.9",
"jazz-browser-media-images": "^0.4.9",
"jazz-react": "^0.4.8",
"jazz-react-auth-local": "^0.4.8",
"jazz-browser-media-images": "^0.4.14",
"jazz-react": "^0.4.14",
"jazz-react-auth-local": "^0.4.14",
"lucide-react": "^0.274.0",
"qrcode": "^1.5.3",
"react": "^18.2.0",

694
genDocsMd.ts Normal file
View File

@@ -0,0 +1,694 @@
import { readFile, writeFile } from "fs/promises";
import { Application, JSONOutput, ReflectionKind } from "typedoc";
import { manuallyIgnore, indentEnd, indent } from "./generateDocs";
export async function genDocsMd() {
const packageDocs = Object.entries({
"jazz-react": "index.tsx",
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}`],
tsconfig: `packages/${packageName}/tsconfig.json`,
sort: ["required-first"],
groupOrder: ["Functions", "Classes", "TypeAliases", "Namespaces"],
categorizeByGroup: false,
});
const project = await app.convert();
if (!project) {
throw new Error("Failed to convert project" + packageName);
}
// Alternatively generate JSON output
await app.generateJson(project, `docsTmp/${packageName}.json`);
const docs = JSON.parse(
await readFile(`docsTmp/${packageName}.json`, "utf8")
) as JSONOutput.ProjectReflection;
return (
`# ${packageName}\n\n` +
docs
.groups!.map((group) => {
return group.children
?.flatMap((childId) => {
const child = docs.children!.find(
(child) => child.id === childId
)!;
if (manuallyIgnore.has(child.name) ||
child.comment?.blockTags?.some(
(tag) => tag.tag === "@deprecated" ||
tag.tag === "@internal" ||
tag.tag === "@ignore"
) ||
child.signatures?.every((signature) => signature.comment?.blockTags?.some(
(tag) => tag.tag === "@deprecated" ||
tag.tag === "@internal" ||
tag.tag === "@ignore"
)
)) {
return [];
}
return (
`## \`${renderChildName(
child
)}\`\n\n<sup>(${group.title
.toLowerCase()
.replace("bles", "ble")
.replace("ces", "ce")
.replace(/es$/, "")
.replace(
"ns",
"n"
)} in \`${packageName}\`)</sup>\n\n` +
renderChildType(child) +
(child.kind === ReflectionKind.Class ||
child.kind === ReflectionKind.Interface ||
child.kind === ReflectionKind.Namespace
? renderSummary(child.comment) +
renderExamples(child.comment) +
(child.categories || child.groups)
?.map((category) => renderChildCategory(
child,
category
)
)
.join("<br/>\n\n")
: child.kind === ReflectionKind.Function
? renderSummary(
child.signatures?.[0].comment
) +
renderParamComments(
child.signatures?.[0].parameters || []
) +
renderExamples(
child.signatures?.[0].comment
) +
"\n\n"
: "TODO: doc generator not implemented yet " +
child.kind)
);
})
.join("\n\n----\n\n");
})
.join("\n\n----\n\n")
);
function renderSummary(comment?: JSONOutput.Comment): string {
if (comment) {
return (
comment.summary
.map((token) => token.kind === "text" || token.kind === "code"
? token.text
: ""
)
.join("") +
"\n\n" +
"\n\n"
);
} else {
return "TODO: document\n\n";
}
}
function renderExamples(comment?: JSONOutput.Comment): string {
return (comment?.blockTags || [])
.map((blockTag) => blockTag.tag === "@example"
? "##### Example:\n\n" +
blockTag.content
.map((token) => token.kind === "text" || token.kind === "code"
? token.text
: ""
)
.join("") +
"\n\n"
: ""
)
.join("");
}
function renderParamComments(params: JSONOutput.ParameterReflection[]) {
const paramDocs = params.flatMap((param) => {
if (param.type?.type === "reflection") {
return param.type.declaration.children?.flatMap((child) => {
if (child.name === "children" &&
child.type?.type === "reference" &&
child.type?.name === "ReactNode") {
return [];
}
return (
`| \`${param.name}.${child.name}${child.flags.isOptional || child.defaultValue
? "?"
: ""}\` | ` +
(child.comment
? child.comment.summary
.map((token) => token.kind === "text" ||
token.kind === "code"
? token.text
: ""
)
.join("")
: "TODO: document") +
" |"
);
});
} else {
const comment = param.comment;
return [
`| \`${param.name}${param.flags.isOptional || param.defaultValue
? "?"
: ""}\` | ` +
(comment
? comment.summary
.map((token) => token.kind === "text" ||
token.kind === "code"
? token.text
: ""
)
.join("")
: "TODO: document ") +
" |",
];
}
});
if (paramDocs.length) {
return `### Parameters:\n\n| name | description |\n| ----: | ---- |\n${paramDocs.join(
"\n"
)}\n\n`;
}
}
function renderChildName(child: JSONOutput.DeclarationReflection) {
if (child.signatures) {
if (child.signatures[0].type?.type === "reference" &&
child.signatures[0].type.qualifiedName ===
"React.JSX.Element") {
return `<${child.name}/>`;
} else {
return (
child.name +
`(${(child.signatures[0].parameters || [])
.map(renderParamSimple)
.join(", ")})`
);
}
} else {
return child.name;
}
}
function renderChildType(
child: JSONOutput.DeclarationReflection
): string {
const isClass = child.kind === ReflectionKind.Class;
const isTypeAlias = child.kind === ReflectionKind.TypeAlias;
const isInterface = child.kind === ReflectionKind.Interface;
const isNamespace = child.kind === ReflectionKind.Namespace;
const isFunction = !!child.signatures;
const kind = isClass
? "class"
: isTypeAlias
? "type"
: isFunction
? "function"
: isInterface
? "interface"
: isNamespace
? "namespace"
: "";
return (
"```typescript\n" +
`export ${kind} ${child.name}` +
(child.typeParameters || child.signatures?.[0].typeParameter
? "<" +
(
child.typeParameters ||
child.signatures?.[0].typeParameter ||
[]
)
.map(renderTypeParam)
.join(", ") +
">"
: "") +
(child.extendedTypes
? " extends " +
child.extendedTypes.map(renderType).join(", ")
: "") +
(child.implementedTypes
? " implements " +
child.implementedTypes.map(renderType).join(", ")
: "") +
(isClass || isInterface || isNamespace
? " {...}"
: isTypeAlias
? ` = ${renderType(child.type)}`
: child.signatures
? `(${(child.signatures[0].parameters || [])
.map(renderParam)
.join(", ")}): ${renderType(
child.signatures[0].type
)}`
: "") +
"\n```\n"
);
}
function renderChildCategory(
child: JSONOutput.DeclarationReflection,
category: JSONOutput.ReflectionGroup
): string {
return (
`### \`${child.name}\`: ${category.title.replace(
/[^d]+\./,
""
)}\n\n` +
category.children
?.map((memberId) => {
const member = child.children!.find(
(member) => member.id === memberId
)!;
if (member.kind === 2048 || member.kind === 512) {
if (member.signatures?.every(
(sig) => sig.comment?.modifierTags?.includes(
"@internal"
) ||
sig.comment?.modifierTags?.includes(
"@deprecated"
)
)) {
return "";
} else {
return documentConstructorOrMethod(
member,
child
);
}
} else if (member.kind === 1024 ||
member.kind === 262144) {
if (member.comment?.modifierTags?.includes(
"@internal"
) ||
member.comment?.modifierTags?.includes(
"@deprecated"
)) {
return "";
} else {
return documentProperty(member, child);
}
} else if (member.kind === 2097152) {
if (member.comment?.modifierTags?.includes(
"@internal"
) ||
member.comment?.modifierTags?.includes(
"@deprecated"
)) {
return "";
} else {
return documentProperty(
{ ...member, flags: { isStatic: true } },
child
);
}
} else {
return "Unknown member kind " + member.kind;
}
})
.join("\n\n")
);
}
function renderType(t?: JSONOutput.SomeType): string {
if (!t) return "";
if (t.type === "reference") {
return (
t.name +
(t.typeArguments
? "<" + t.typeArguments.map(renderType).join(", ") + ">"
: "")
);
} else if (t.type === "intrinsic") {
return t.name;
} else if (t.type === "literal") {
return JSON.stringify(t.value);
} else if (t.type === "union") {
const seen = new Set<string>();
return t.types
.flatMap((t) => {
const rendered = t.type === "intersection" || t.type === "union"
? `(${renderType(t)})`
: renderType(t);
if (seen.has(rendered)) {
return [];
} else {
seen.add(rendered);
return [rendered];
}
})
.join(" | ");
} else if (t.type === "intersection") {
const seen = new Set<string>();
return t.types
.flatMap((t) => {
const rendered = t.type === "intersection" || t.type === "union"
? `(${renderType(t)})`
: renderType(t);
if (seen.has(rendered)) {
return [];
} else {
seen.add(rendered);
return [rendered];
}
})
.join(" & ");
} else if (t.type === "indexedAccess") {
return (
renderType(t.objectType) +
"[" +
renderType(t.indexType) +
"]"
);
} else if (t.type === "reflection") {
if (t.declaration.indexSignature) {
return (
`{${t.declaration.children
? t.declaration.children
.map(
(child) => ` ${child.name}${child.flags.isOptional
? "?"
: ""}: ${indentEnd(
renderType(child.type)
)},`
)
.join("\n")
: ""}\n [` +
t.declaration.indexSignature?.parameters?.[0].name +
": " +
renderType(
t.declaration.indexSignature?.parameters?.[0].type
) +
"]: " +
indentEnd(
renderType(t.declaration.indexSignature?.type)
) +
" }"
);
} else if (t.declaration.children) {
return `{\n${t.declaration.children
.map((child) => child.signatures
? child.signatures
.map(
(signature) => ` ${child.name}(${signature.parameters
? "\n " +
indent(
signature.parameters
.map((p) => indentEnd(
renderParam(
p
)
)
)
.join(",\n ")
) +
"\n )"
: "()"}: ${indentEnd(
renderType(signature.type)
)}`
)
.join("\n") + ",\n"
: ` ${child.name}${child.flags.isOptional ? "?" : ""}: ${indentEnd(renderType(child.type))},\n`
)
.join("")}}`;
} else if (t.declaration.signatures) {
return t.declaration.signatures
.map(
(signature) => `(${(signature.parameters || [])
.map(renderParam)
.join(", ")}) => ${renderType(
signature.type
)}`
)
.join("\n");
} else {
return "COMPLEX_TYPE_REFLECTION";
}
} else if (t.type === "array") {
return renderType(t.elementType) + "[]";
} else if (t.type === "tuple") {
return `[${t.elements?.map(renderType).join(", ")}]`;
} else if (t.type === "templateLiteral") {
const matchingNamedType = docs.children?.find(
(child) => child.variant === "declaration" &&
child.type?.type === "templateLiteral" &&
child.type.head === t.head &&
child.type.tail.every(
(piece, i) => piece[1] === t.tail[i][1]
)
);
if (matchingNamedType) {
return matchingNamedType.name;
} else {
if (t.head === "sealerSecret_z" &&
t.tail[0][1] === "/signerSecret_z") {
return "AgentSecret";
} else if (t.head === "sealer_z" &&
t.tail[0][1] === "/signer_z") {
if (t.tail[1] && t.tail[1][1] === "_session_z") {
return "SessionID";
} else {
return "AgentID";
}
} else {
return (
"`" +
t.head +
t.tail
.map(
(bit) => "${" + renderType(bit[0]) + "}" + bit[1]
)
.join("") +
"`"
);
}
}
} else if (t.type === "conditional") {
const trueRendered = renderType(t.trueType);
const falseRendered = renderType(t.falseType);
if (trueRendered.includes("\n") ||
falseRendered.includes("\n")) {
return (
renderType(t.checkType) +
" extends " +
renderType(t.extendsType) +
"\n ? " +
indentEnd(renderType(t.trueType)) +
"\n : " +
indentEnd(renderType(t.falseType))
);
} else {
return (
renderType(t.checkType) +
" extends " +
renderType(t.extendsType) +
" ? " +
renderType(t.trueType) +
" : " +
renderType(t.falseType)
);
}
} else if (t.type === "inferred") {
return "infer " + t.name;
} else if (t.type === "typeOperator") {
return t.operator + " " + renderType(t.target);
} else if (t.type === "mapped") {
return `{\n [${t.parameter} in ${renderType(
t.parameterType
)}]: ${indentEnd(renderType(t.templateType))}\n}`;
} else {
return "COMPLEX_TYPE_" + t.type;
}
}
// function renderTemplateLiteral(tempLit: JSONOutput.TemplateLiteralType) {
// return tempLit.head + tempLit.tail.map((piece) => piece[0] + piece[1]).join("");
// }
// function resolveTemplateLiteralPieceType(t: SomeType): string {
// if (t.type === "string") {
// return "${string}"
// }
// if (t.type === "reference") {
// const referencedType = docs.children?.find(
// (child) => child.name === t.name
// );
// }
// }
function renderTypeParam(
t?: JSONOutput.TypeParameterReflection
): string {
if (!t) return "";
return t.name + (t.type ? " extends " + renderType(t.type) : "");
}
function renderParam(param: JSONOutput.ParameterReflection) {
return param.name === "__namedParameters"
? renderType(param.type)
: `${param.name}: ${renderType(param.type)}`;
}
function renderParamSimple(param: JSONOutput.ParameterReflection) {
return param.name === "__namedParameters" &&
param.type?.type === "reflection"
? `{${param.type?.declaration.children
?.map(
(child) => child.name + (child.flags.isOptional ? "?" : "")
)
.join(", ")}}${param.flags.isOptional || param.defaultValue ? "?" : ""}`
: param.name +
(param.flags.isOptional || param.defaultValue ? "?" : "");
}
function documentConstructorOrMethod(
member: JSONOutput.DeclarationReflection,
child: JSONOutput.DeclarationReflection
) {
const isInClass = child.kind === 128;
const isInTypeDef = child.kind === 2097152;
const isInInterface = child.kind === 256;
const isInNamespace = child.kind === 4;
const isInFunction = !!child.signatures;
const inKind = isInClass
? "class"
: isInTypeDef
? "type"
: isInFunction
? "function"
: isInInterface
? "interface"
: isInNamespace
? "namespace"
: "";
const stem = member.name === "constructor"
? "new " + child.name + "</code></b>"
: (member.flags.isStatic ? child.name : "") +
"." +
member.name +
"";
return member.signatures
?.map((signature) => {
return (
`<details>\n<summary><b><code>${stem}(${(
signature?.parameters?.map(renderParamSimple) || []
).join(", ")})</code></b> ${member.inheritedFrom
? "<sub><sup>from <code>" +
member.inheritedFrom.name.split(".")[0] +
"</code></sup></sub> "
: ""} ${signature?.comment
? ""
: "<sub><sup>(undocumented)</sup></sub>"}</summary>\n\n` +
("```typescript\n" +
`${inKind} ${child.name}${child.typeParameters
? `<${child.typeParameters
.map((t) => t.name)
.join(", ")}>`
: ""} {\n\n${indent(
`${member.name}${signature.typeParameter
? `<${signature.typeParameter
.map(renderTypeParam)
.join(", ")}>`
: ""}(${(
signature.parameters?.map(
(param) => `\n ${param.name}${param.flags.isOptional ||
param.defaultValue
? "?"
: ""}: ${indentEnd(
renderType(param.type)
)}${param.defaultValue
? ` = ${param.defaultValue}`
: ""}`
) || []
).join(",") +
(signature.parameters?.length ? "\n" : "")}): ${renderType(signature.type)} {...}`
)}\n\n}\n` +
"```\n" +
renderSummary(signature.comment)) +
renderParamComments(signature.parameters || []) +
renderExamples(signature.comment) +
"</details>\n\n"
);
})
.join("\n\n");
}
function documentProperty(
member: JSONOutput.DeclarationReflection,
child: JSONOutput.DeclarationReflection
) {
const isInClass = child.kind === 128;
const isInTypeDef = child.kind === 2097152;
const isInInterface = child.kind === 256;
const isInNamespace = child.kind === 4;
const isInFunction = !!child.signatures;
const inKind = isInClass
? "class"
: isInTypeDef
? "type"
: isInFunction
? "function"
: isInInterface
? "interface"
: isInNamespace
? "namespace"
: "";
const stem = member.flags.isStatic ? child.name : "";
return (
`<details>\n<summary><b><code>${stem}.${member.name}</code></b> ${member.inheritedFrom
? "<sub><sup>from <code>" +
member.inheritedFrom.name.split(".")[0] +
"</code></sup></sub> "
: ""} ${member.comment ? "" : "<sub><sup>(undocumented)</sup></sub>"}</summary>\n\n` +
"```typescript\n" +
`${inKind} ${child.name}${child.typeParameters
? `<${child.typeParameters
.map((t) => t.name)
.join(", ")}>`
: ""} {\n\n${indent(
`${member.getSignature ? "get " : ""}${member.name}${member.getSignature ? "()" : ""}: ${renderType(member.type || member.getSignature?.type)}${member.getSignature ? " {...}" : ""}`
)}` +
"\n\n}\n```\n" +
renderSummary(member.comment) +
renderExamples(member.comment) +
"</details>\n\n"
);
}
});
const docsContent = await readFile("./DOCS.md", "utf8");
await writeFile(
"./DOCS.md",
docsContent.slice(
0,
docsContent.indexOf("<!-- AUTOGENERATED DOCS AFTER THIS POINT -->")
) +
"<!-- AUTOGENERATED DOCS AFTER THIS POINT -->\n" +
(await Promise.all(packageDocs)).join("\n\n\n")
);
}

View File

@@ -1,783 +1,19 @@
import { readFile, writeFile } from "fs/promises";
import { Application, JSONOutput, ReflectionKind } from "typedoc";
import { genDocsMd } from "./genDocsMd";
const manuallyIgnore = new Set(["CojsonInternalTypes"]);
export const manuallyIgnore = new Set(["CojsonInternalTypes"]);
async function main() {
// Application.bootstrap also exists, which will not load plugins
// Also accepts an array of option readers if you want to disable
// TypeDoc's tsconfig.json/package.json/typedoc.json option readers
const packageDocs = Object.entries({
"jazz-react": "index.tsx",
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}`],
tsconfig: `packages/${packageName}/tsconfig.json`,
sort: ["required-first"],
groupOrder: ["Functions", "Classes", "TypeAliases", "Namespaces"],
categorizeByGroup: false
});
const project = await app.convert();
if (!project) {
throw new Error("Failed to convert project" + packageName);
}
// Alternatively generate JSON output
await app.generateJson(project, `docsTmp/${packageName}.json`);
const docs = JSON.parse(
await readFile(`docsTmp/${packageName}.json`, "utf8")
) as JSONOutput.ProjectReflection;
return (
`# ${packageName}\n\n` +
docs
.groups!.map((group) => {
return group.children
?.flatMap((childId) => {
const child = docs.children!.find(
(child) => child.id === childId
)!;
if (
manuallyIgnore.has(child.name) ||
child.comment?.blockTags?.some(
(tag) =>
tag.tag === "@deprecated" ||
tag.tag === "@internal" ||
tag.tag === "@ignore"
) ||
child.signatures?.every((signature) =>
signature.comment?.blockTags?.some(
(tag) =>
tag.tag === "@deprecated" ||
tag.tag === "@internal" ||
tag.tag === "@ignore"
)
)
) {
return [];
}
return (
`## \`${renderChildName(
child
)}\`\n\n<sup>(${group.title
.toLowerCase()
.replace("bles", "ble")
.replace("ces", "ce")
.replace(/es$/, "")
.replace(
"ns",
"n"
)} in \`${packageName}\`)</sup>\n\n` +
renderChildType(child) +
(child.kind === ReflectionKind.Class ||
child.kind === ReflectionKind.Interface ||
child.kind === ReflectionKind.Namespace
? renderSummary(child.comment) +
renderExamples(child.comment) +
(child.categories || child.groups)
?.map((category) =>
renderChildCategory(child, category)
)
.join("<br/>\n\n")
: child.kind === ReflectionKind.Function
? renderSummary(
child.signatures?.[0].comment
) +
renderParamComments(
child.signatures?.[0].parameters || []
) +
renderExamples(
child.signatures?.[0].comment
) +
"\n\n"
: "TODO: doc generator not implemented yet " +
child.kind)
);
})
.join("\n\n----\n\n");
})
.join("\n\n----\n\n")
);
function renderSummary(comment?: JSONOutput.Comment): string {
if (comment) {
return (
comment.summary
.map((token) =>
token.kind === "text" || token.kind === "code"
? token.text
: ""
)
.join("") +
"\n\n" +
"\n\n"
);
} else {
return "TODO: document\n\n";
}
}
function renderExamples(comment?: JSONOutput.Comment): string {
return (comment?.blockTags || [])
.map((blockTag) =>
blockTag.tag === "@example"
? "##### Example:\n\n" +
blockTag.content
.map((token) =>
token.kind === "text" || token.kind === "code"
? token.text
: ""
)
.join("") +
"\n\n"
: ""
)
.join("");
}
function renderParamComments(params: JSONOutput.ParameterReflection[]) {
const paramDocs = params.flatMap((param) => {
if (param.type?.type === "reflection") {
return param.type.declaration.children?.flatMap((child) => {
if (
child.name === "children" &&
child.type?.type === "reference" &&
child.type?.name === "ReactNode"
) {
return [];
}
return (
`| \`${param.name}.${child.name}${
child.flags.isOptional || child.defaultValue
? "?"
: ""
}\` | ` +
(child.comment
? child.comment.summary
.map((token) =>
token.kind === "text" ||
token.kind === "code"
? token.text
: ""
)
.join("")
: "TODO: document") +
" |"
);
});
} else {
const comment = param.comment;
return [
`| \`${param.name}${
param.flags.isOptional || param.defaultValue
? "?"
: ""
}\` | ` +
(comment
? comment.summary
.map((token) =>
token.kind === "text" ||
token.kind === "code"
? token.text
: ""
)
.join("")
: "TODO: document ") +
" |",
];
}
});
if (paramDocs.length) {
return `### Parameters:\n\n| name | description |\n| ----: | ---- |\n${paramDocs.join(
"\n"
)}\n\n`;
}
}
function renderChildName(child: JSONOutput.DeclarationReflection) {
if (child.signatures) {
if (
child.signatures[0].type?.type === "reference" &&
child.signatures[0].type.qualifiedName ===
"React.JSX.Element"
) {
return `<${child.name}/>`;
} else {
return (
child.name +
`(${(child.signatures[0].parameters || [])
.map(renderParamSimple)
.join(", ")})`
);
}
} else {
return child.name;
}
}
function renderChildType(
child: JSONOutput.DeclarationReflection
): string {
const isClass = child.kind === ReflectionKind.Class;
const isTypeAlias = child.kind === ReflectionKind.TypeAlias;
const isInterface = child.kind === ReflectionKind.Interface;
const isNamespace = child.kind === ReflectionKind.Namespace;
const isFunction = !!child.signatures;
const kind = isClass
? "class"
: isTypeAlias
? "type"
: isFunction
? "function"
: isInterface
? "interface"
: isNamespace
? "namespace"
: "";
return (
"```typescript\n" +
`export ${kind} ${child.name}` +
((child.typeParameters || child.signatures?.[0].typeParameter)
? "<" +
(child.typeParameters || child.signatures?.[0].typeParameter || []).map(renderTypeParam).join(", ") +
">"
: "") +
(child.extendedTypes
? " extends " +
child.extendedTypes.map(renderType).join(", ")
: "") +
(child.implementedTypes
? " implements " +
child.implementedTypes.map(renderType).join(", ")
: "") +
(isClass || isInterface || isNamespace
? " {...}"
: isTypeAlias
? ` = ${renderType(child.type)}`
: child.signatures
? `(${(child.signatures[0].parameters || [])
.map(renderParam)
.join(", ")}): ${renderType(
child.signatures[0].type
)}`
: "") +
"\n```\n"
);
}
function renderChildCategory(
child: JSONOutput.DeclarationReflection,
category: JSONOutput.ReflectionGroup
): string {
return (
`### \`${child.name}\`: ${category.title.replace(/[^d]+\./, "")}\n\n` +
category.children
?.map((memberId) => {
const member = child.children!.find(
(member) => member.id === memberId
)!;
if (member.kind === 2048 || member.kind === 512) {
if (
member.signatures?.every(
(sig) =>
sig.comment?.modifierTags?.includes(
"@internal"
) ||
sig.comment?.modifierTags?.includes(
"@deprecated"
)
)
) {
return "";
} else {
return documentConstructorOrMethod(
member,
child
);
}
} else if (
member.kind === 1024 ||
member.kind === 262144
) {
if (
member.comment?.modifierTags?.includes(
"@internal"
) ||
member.comment?.modifierTags?.includes(
"@deprecated"
)
) {
return "";
} else {
return documentProperty(member, child);
}
} else if (member.kind === 2097152) {
if (
member.comment?.modifierTags?.includes(
"@internal"
) ||
member.comment?.modifierTags?.includes(
"@deprecated"
)
) {
return "";
} else {
return documentProperty(
{ ...member, flags: { isStatic: true } },
child
);
}
} else {
return "Unknown member kind " + member.kind;
}
})
.join("\n\n")
);
}
function renderType(t?: JSONOutput.SomeType): string {
if (!t) return "";
if (t.type === "reference") {
return (
t.name +
(t.typeArguments
? "<" + t.typeArguments.map(renderType).join(", ") + ">"
: "")
);
} else if (t.type === "intrinsic") {
return t.name;
} else if (t.type === "literal") {
return JSON.stringify(t.value);
} else if (t.type === "union") {
const seen = new Set<string>();
return t.types
.flatMap((t) => {
const rendered =
t.type === "intersection" || t.type === "union"
? `(${renderType(t)})`
: renderType(t);
if (seen.has(rendered)) {
return [];
} else {
seen.add(rendered);
return [rendered];
}
})
.join(" | ");
} else if (t.type === "intersection") {
const seen = new Set<string>();
return t.types
.flatMap((t) => {
const rendered =
t.type === "intersection" || t.type === "union"
? `(${renderType(t)})`
: renderType(t);
if (seen.has(rendered)) {
return [];
} else {
seen.add(rendered);
return [rendered];
}
})
.join(" & ");
} else if (t.type === "indexedAccess") {
return (
renderType(t.objectType) +
"[" +
renderType(t.indexType) +
"]"
);
} else if (t.type === "reflection") {
if (t.declaration.indexSignature) {
return (
`{${
t.declaration.children
? t.declaration.children
.map(
(child) =>
` ${child.name}${
child.flags.isOptional
? "?"
: ""
}: ${indentEnd(
renderType(child.type)
)},`
)
.join("\n")
: ""
}\n [` +
t.declaration.indexSignature?.parameters?.[0].name +
": " +
renderType(
t.declaration.indexSignature?.parameters?.[0].type
) +
"]: " +
indentEnd(
renderType(t.declaration.indexSignature?.type)
) +
" }"
);
} else if (t.declaration.children) {
return `{\n${t.declaration.children
.map((child) =>
child.signatures
? child.signatures
.map(
(signature) =>
` ${child.name}(${
signature.parameters
? "\n " +
indent(
signature.parameters
.map((p) =>
indentEnd(
renderParam(
p
)
)
)
.join(",\n ")
) +
"\n )"
: "()"
}: ${indentEnd(
renderType(signature.type)
)}`
)
.join("\n") + ",\n"
: ` ${child.name}${
child.flags.isOptional ? "?" : ""
}: ${indentEnd(renderType(child.type))},\n`
)
.join("")}}`;
} else if (t.declaration.signatures) {
return t.declaration.signatures
.map(
(signature) =>
`(${(signature.parameters || [])
.map(renderParam)
.join(", ")}) => ${renderType(
signature.type
)}`
)
.join("\n");
} else {
return "COMPLEX_TYPE_REFLECTION";
}
} else if (t.type === "array") {
return renderType(t.elementType) + "[]";
} else if (t.type === "tuple") {
return `[${t.elements?.map(renderType).join(", ")}]`;
} else if (t.type === "templateLiteral") {
const matchingNamedType = docs.children?.find(
(child) =>
child.variant === "declaration" &&
child.type?.type === "templateLiteral" &&
child.type.head === t.head &&
child.type.tail.every(
(piece, i) => piece[1] === t.tail[i][1]
)
);
if (matchingNamedType) {
return matchingNamedType.name;
} else {
if (
t.head === "sealerSecret_z" &&
t.tail[0][1] === "/signerSecret_z"
) {
return "AgentSecret";
} else if (
t.head === "sealer_z" &&
t.tail[0][1] === "/signer_z"
) {
if (t.tail[1] && t.tail[1][1] === "_session_z") {
return "SessionID";
} else {
return "AgentID";
}
} else {
return (
"`" +
t.head +
t.tail
.map(
(bit) =>
"${" + renderType(bit[0]) + "}" + bit[1]
)
.join("") +
"`"
);
}
}
} else if (t.type === "conditional") {
const trueRendered = renderType(t.trueType);
const falseRendered = renderType(t.falseType);
if (
trueRendered.includes("\n") ||
falseRendered.includes("\n")
) {
return (
renderType(t.checkType) +
" extends " +
renderType(t.extendsType) +
"\n ? " +
indentEnd(renderType(t.trueType)) +
"\n : " +
indentEnd(renderType(t.falseType))
);
} else {
return (
renderType(t.checkType) +
" extends " +
renderType(t.extendsType) +
" ? " +
renderType(t.trueType) +
" : " +
renderType(t.falseType)
);
}
} else if (t.type === "inferred") {
return "infer " + t.name;
} else if (t.type === "typeOperator") {
return t.operator + " " + renderType(t.target);
} else if (t.type === "mapped") {
return `{\n [${t.parameter} in ${renderType(
t.parameterType
)}]: ${indentEnd(renderType(t.templateType))}\n}`;
} else {
return "COMPLEX_TYPE_" + t.type;
}
}
// function renderTemplateLiteral(tempLit: JSONOutput.TemplateLiteralType) {
// return tempLit.head + tempLit.tail.map((piece) => piece[0] + piece[1]).join("");
// }
// function resolveTemplateLiteralPieceType(t: SomeType): string {
// if (t.type === "string") {
// return "${string}"
// }
// if (t.type === "reference") {
// const referencedType = docs.children?.find(
// (child) => child.name === t.name
// );
// }
// }
function renderTypeParam(
t?: JSONOutput.TypeParameterReflection
): string {
if (!t) return "";
return t.name + (t.type ? " extends " + renderType(t.type) : "");
}
function renderParam(param: JSONOutput.ParameterReflection) {
return param.name === "__namedParameters"
? renderType(param.type)
: `${param.name}: ${renderType(param.type)}`;
}
function renderParamSimple(param: JSONOutput.ParameterReflection) {
return param.name === "__namedParameters" &&
param.type?.type === "reflection"
? `{${param.type?.declaration.children
?.map(
(child) =>
child.name + (child.flags.isOptional ? "?" : "")
)
.join(", ")}}${
param.flags.isOptional || param.defaultValue ? "?" : ""
}`
: param.name +
(param.flags.isOptional || param.defaultValue ? "?" : "");
}
function documentConstructorOrMethod(
member: JSONOutput.DeclarationReflection,
child: JSONOutput.DeclarationReflection
) {
const isInClass = child.kind === 128;
const isInTypeDef = child.kind === 2097152;
const isInInterface = child.kind === 256;
const isInNamespace = child.kind === 4;
const isInFunction = !!child.signatures;
const inKind = isInClass
? "class"
: isInTypeDef
? "type"
: isInFunction
? "function"
: isInInterface
? "interface"
: isInNamespace
? "namespace"
: "";
const stem =
member.name === "constructor"
? "new " + child.name + "</code></b>"
: (member.flags.isStatic ? child.name : "") +
"." +
member.name +
"";
return member.signatures
?.map((signature) => {
return (
`<details>\n<summary><b><code>${stem}(${(
signature?.parameters?.map(renderParamSimple) || []
).join(", ")})</code></b> ${
member.inheritedFrom
? "<sub><sup>from <code>" +
member.inheritedFrom.name.split(".")[0] +
"</code></sup></sub> "
: ""
} ${
signature?.comment
? ""
: "<sub><sup>(undocumented)</sup></sub>"
}</summary>\n\n` +
("```typescript\n" +
`${inKind} ${child.name}${
child.typeParameters
? `<${child.typeParameters
.map((t) => t.name)
.join(", ")}>`
: ""
} {\n\n${indent(
`${member.name}${
signature.typeParameter
? `<${signature.typeParameter
.map(renderTypeParam)
.join(", ")}>`
: ""
}(${
(
signature.parameters?.map(
(param) =>
`\n ${param.name}${
param.flags.isOptional ||
param.defaultValue
? "?"
: ""
}: ${indentEnd(
renderType(param.type)
)}${
param.defaultValue
? ` = ${param.defaultValue}`
: ""
}`
) || []
).join(",") +
(signature.parameters?.length ? "\n" : "")
}): ${renderType(signature.type)} {...}`
)}\n\n}\n` +
"```\n" +
renderSummary(signature.comment)) +
renderParamComments(signature.parameters || []) +
renderExamples(signature.comment) +
"</details>\n\n"
);
})
.join("\n\n");
}
function documentProperty(
member: JSONOutput.DeclarationReflection,
child: JSONOutput.DeclarationReflection
) {
const isInClass = child.kind === 128;
const isInTypeDef = child.kind === 2097152;
const isInInterface = child.kind === 256;
const isInNamespace = child.kind === 4;
const isInFunction = !!child.signatures;
const inKind = isInClass
? "class"
: isInTypeDef
? "type"
: isInFunction
? "function"
: isInInterface
? "interface"
: isInNamespace
? "namespace"
: "";
const stem = member.flags.isStatic ? child.name : "";
return (
`<details>\n<summary><b><code>${stem}.${
member.name
}</code></b> ${
member.inheritedFrom
? "<sub><sup>from <code>" +
member.inheritedFrom.name.split(".")[0] +
"</code></sup></sub> "
: ""
} ${
member.comment ? "" : "<sub><sup>(undocumented)</sup></sub>"
}</summary>\n\n` +
"```typescript\n" +
`${inKind} ${child.name}${
child.typeParameters
? `<${child.typeParameters
.map((t) => t.name)
.join(", ")}>`
: ""
} {\n\n${indent(
`${member.getSignature ? "get " : ""}${member.name}${
member.getSignature ? "()" : ""
}: ${renderType(member.type || member.getSignature?.type)}${
member.getSignature ? " {...}" : ""
}`
)}` +
"\n\n}\n```\n" +
renderSummary(member.comment) +
renderExamples(member.comment) +
"</details>\n\n"
);
}
});
const docsContent = await readFile("./DOCS.md", "utf8");
await writeFile(
"./DOCS.md",
docsContent.slice(
0,
docsContent.indexOf("<!-- AUTOGENERATED DOCS AFTER THIS POINT -->")
) +
"<!-- AUTOGENERATED DOCS AFTER THIS POINT -->\n" +
(await Promise.all(packageDocs)).join("\n\n\n")
);
await genDocsMd();
}
function indent(text: string): string {
export function indent(text: string): string {
return text
.split("\n")
.map((line) => " " + line)
.join("\n");
}
function indentEnd(text: string): string {
export function indentEnd(text: string): string {
return text
.split("\n")
.map((line, i) => (i === 0 ? line : " " + line))

View File

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

35
homepage/homepage-jazz-old/.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,3 @@
{
"tabWidth": 2
}

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.

View File

@@ -0,0 +1,49 @@
"use client";
import { useLayoutEffect, useState, useRef, IframeHTMLAttributes } from "react";
export function ResponsiveIframe(
props: IframeHTMLAttributes<HTMLIFrameElement>
) {
const containerRef = useRef<HTMLDivElement>(null);
const [dimensions, setDimensions] = useState({ width: 0, height: 0 });
const [url, setUrl] = useState<string | undefined>(props.src);
useLayoutEffect(() => {
const listener = (e: MessageEvent) => {
console.log(e);
if (e.data.type === "navigate" && props.src?.startsWith(e.origin)) {
setUrl(e.data.url);
}
};
window.addEventListener("message", listener);
return () => {
window.removeEventListener("message", listener);
};
}, [props.src]);
useLayoutEffect(() => {
if (!containerRef.current) return;
const observer = new ResizeObserver(() => {
if (!containerRef.current) return;
setDimensions({
width: containerRef.current.offsetWidth,
height: containerRef.current.offsetHeight,
});
});
observer.observe(containerRef.current);
return () => {
observer.disconnect();
};
}, [containerRef]);
return (
<div className={"w-full h-full flex flex-col " + props.className} >
<input className="text-xs p-2" value={url} readOnly/>
<div className="flex-grow" ref={containerRef}>
<iframe {...props} className="" {...dimensions} allowFullScreen/>
</div>
</div>
);
}

View File

@@ -0,0 +1,51 @@
export function Slogan(props: { children: React.ReactNode, small?: boolean }) {
return (
<div className={"leading-snug mb-5 max-w-3xl text-neutral-700 dark:text-neutral-200 " + (props.small ? "text-lg mt-2" : "text-2xl mt-5")}>
{props.children}
</div>
);
}
export function Grid(props: { children: React.ReactNode }) {
return (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2 mt-10 items-stretch">
{props.children}
</div>
);
}
export function GridItem(props: {
children: React.ReactNode;
className?: string;
}) {
return (
<div
className={
(props.className || "") +
" [&>.nextra-code-block]:h-full [&>.nextra-code-block>pre]:h-full [&>.nextra-code-block>pre]:mb-0"
}
>
{props.children}
</div>
);
}
export function GridCard(props: {
children: React.ReactNode;
className?: string;
}) {
return (
<div
className={
"border border-stone-200 dark:border-stone-500 rounded-xl p-4 [&>h4]:mt-0 [&>h3]:mt-0 " +
props.className
}
>
{props.children}
</div>
);
}
export function GoogleLogo() {
return <svg className="w-3 h-3 inline align-baseline" viewBox="0 0 950 950" version="1.1" xmlns="http://www.w3.org/2000/svg"><path d="M915.2 448l-4.2-17.8H524V594h231.2c-24 114-135.4 174-226.4 174-66.2 0-136-27.8-182.2-72.6-47.4-46-77.6-113.8-77.6-183.6 0-69 31-138 76.2-183.4 45-45.2 113.2-70.8 181-70.8 77.6 0 133.2 41.2 154 60l116.4-115.8c-34.2-30-128-105.6-274.2-105.6-112.8 0-221 43.2-300 122C144.4 295.8 104 408 104 512s38.2 210.8 113.8 289c80.8 83.4 195.2 127 313 127 107.2 0 208.8-42 281.2-118.2 71.2-75 108-178.8 108-287.6 0-45.8-4.6-73-4.8-74.2z" fill="currentColor" /></svg>
}

View File

@@ -0,0 +1,9 @@
const withNextra = require('nextra')({
theme: 'nextra-theme-docs',
themeConfig: './theme.config.jsx',
mdxOptions: {
}
})
module.exports = withNextra()

View File

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

View File

@@ -0,0 +1,15 @@
import './globals.css'
import { Manrope } from 'next/font/google'
import { Inter } from 'next/font/google'
import localFont from 'next/font/local'
// If loading a variable font, you don't need to specify the font weight
const manrope = Manrope({ subsets: ['latin'], variable: '--font-manrope', })
const inter = Inter({ subsets: ['latin'], variable: '--font-inter', })
const pragmata = localFont({src: "../fonts/PragmataProR_0829.woff2", subsets: ['latin'], variable: '--font-pragmata'})
// This default export is required in a new `pages/_app.js` file.
export default function MyApp({ Component, pageProps }) {
return <div className={manrope.variable + " " + pragmata.variable + " " + inter.className + " font-[450]"}><Component {...pageProps} /></div>
}

View File

@@ -0,0 +1,41 @@
{
"index": {
"title": "Introduction",
"theme": {
"typesetting": "article",
"layout": "full"
},
"type": "page"
},
"examples": {
"title": "Example Gallery",
"theme": {
"typesetting": "article",
"layout": "full"
},
"type": "page"
},
"mesh": {
"title": "Global Mesh & Pricing",
"theme": {
"typesetting": "article",
"layout": "full"
},
"type": "page"
},
"guides": {
"title": "Guides",
"type": "page",
"theme": {
"breadcrumb": true,
"footer": true,
"sidebar": true,
"toc": true,
"pagination": true
}
},
"docs": {
"title": "API Docs",
"type": "page"
}
}

View File

@@ -0,0 +1 @@
# API docs

View File

@@ -0,0 +1 @@
# Something

View File

@@ -0,0 +1 @@
# Something else

View File

@@ -0,0 +1,162 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
body article.nextra-content h1 {
font-family: var(--font-manrope);
}
body article.nx-w-full h1 {
font-family: var(--font-manrope);
text-align: left;
@apply tracking-tight;
@apply text-6xl;
@apply font-medium;
}
body article.nx-w-full h1:first-of-type {
@apply mt-20;
}
body article.nx-w-full h2 {
font-family: var(--font-manrope);
text-align: left;
@apply tracking-tight;
@apply text-3xl;
@apply font-[600];
}
body article.nx-w-full p {
@apply max-w-3xl;
}
body pre code.nx-text-\[\.9em\] {
font-size: 0.8rem;
line-height: 1.35;
}
[style="color:var(--shiki-token-keyword)"]+[style="color:var(--shiki-token-string-expression)"]:after {
content: "⋯";
text-indent: 0;
display: block;
line-height: initial;
letter-spacing: normal;
outline: 1px solid var(--shiki-token-string-expression);
border-radius: 0.25rem;
margin-left: 0.1rem;
margin-right: 0.1rem;
}
[style="color:var(--shiki-token-keyword)"]+[style="color:var(--shiki-token-string-expression)"] {
position: relative;
opacity: 1;
display: inline-block;
text-indent: -9999px;
line-height: 0;
opacity: 0.5;
transition: opacity 0.2s;
}
[style="color:var(--shiki-token-keyword)"]+[style="color:var(--shiki-token-string-expression)"]:hover {
text-indent: 0;
line-height: initial;
opacity: 1;
}
[style="color:var(--shiki-token-keyword)"]+[style="color:var(--shiki-token-string-expression)"]:hover:after {
display: none;
}
body .nextra-card svg {
color: black;
opacity: 0.2;
transition: opacity 0.2s ease;
}
body .nextra-card:hover svg {
color: black;
opacity: 0.8;
}
.dark body .nextra-card svg {
color: white;
opacity: 0.4;
}
.dark body .nextra-card:hover svg {
color: white;
opacity: 0.8;
}
/* @media screen and (min-width: 80rem) {
body article.nx-w-full {
@apply -mx-32;
}
} */
:root {
--nextra-primary-hue: 30deg;
--nextra-primary-saturation: 15%;
}
/* .nextra-nav-container nav {
justify-content: flex-start;
max-width: 70rem;
} */
.nextra-nav-container nav :first-child {
margin-right: 0;
}
.nextra-nav-container nav a:not(:first-child) {
padding-left: 1rem;
padding-right: 1rem;
}
.nextra-search+* {
margin-left: auto;
}
body code, body kbd, body samp, body pre {
font-family: var(--font-pragmata);
}
body code[data-line-numbers]>.line {
padding-left: 0.25rem;
}
body code[data-line-numbers]>.line:before {
--tw-text-opacity: 0.3;
min-width: 1.5rem;
font-size: 0.7rem;
padding-right: 0.5rem;
position: relative;
top: 0.07rem;
}
body {
--shiki-color-text: #606060;
--shiki-color-background: transparent;
--shiki-token-constant: #00a5a5;
--shiki-token-string: #1aa245;
--shiki-token-comment: #aaa;
--shiki-token-keyword: #7b8bff;
--shiki-token-parameter: #ff9800;
--shiki-token-function: #445dd7;
--shiki-token-string-expression: #1aa245;
--shiki-token-punctuation: #969696;
--shiki-token-link: #1aa245;
}
.dark body {
--shiki-color-text: #d1d1d1;
--shiki-token-constant: #2DC9C9;
--shiki-token-string: #ffab70;
--shiki-token-comment: #6b737c;
--shiki-token-keyword: #7b8bff;
--shiki-token-parameter: #ff9800;
--shiki-token-function: #9BABFF;
--shiki-token-string-expression: #42BB69;
--shiki-token-punctuation: #bbb;
--shiki-token-link: #ffab70;
}

View File

@@ -0,0 +1 @@
# Guides

View File

@@ -0,0 +1,3 @@
{
"gettingStarted": "Getting Started"
}

View File

@@ -0,0 +1 @@
# Getting started

View File

@@ -0,0 +1,237 @@
import { Tabs, Cards, Card } from "nextra/components";
import { Slogan, Grid, GridItem, GridCard, GoogleLogo } from "../components";
import { ResponsiveIframe } from "../components/ResponsiveIframe";
import {
ArrowUpDownIcon,
UploadCloudIcon,
PlaneIcon,
MonitorSmartphoneIcon,
TextCursorIcon,
MousePointer2Icon,
GaugeIcon,
HandIcon
} from "lucide-react";
# Instant sync.
<Slogan>Go beyond request/response &mdash; ship modern apps with sync.</Slogan>
Jazz is an open-source toolkit for building apps with **sync** and **secure collaborative data.**
<h2 className="mt-24">Hard things are easy now.</h2>
Jazz takes what *backends* + *databases* + *CDNs* + *real-time infrastructure* do, generalizes the problem and solves it in a completely new way. (How? Keep reading.)
Because of that, with Jazz, you only build what makes your app *your app:*<br/>1. **Define your data model.** -> 2. **Add role-based permissions.** -> 3. **Build your UI.**
And you get **built-in capabilities** that took the &ldquo;big ones&rdquo; <small>(GDocs,&nbsp;Figma,&nbsp;Notion,&nbsp;Linear,&nbsp;&hellip;)</small> *years* to build:
<Cards>
<Card href="#" title="Cross-device sync" icon={<MonitorSmartphoneIcon />} />
<Card
href="#"
title="Real-time multiplayer"
icon={
<div className="w-6 h-6 flex flex-col">
<TextCursorIcon
size="10"
absoluteStrokeWidth
className="-scale-x-100 self-start -ml-1"
/>
<MousePointer2Icon size="15" absoluteStrokeWidth className="-mt-1 -mx-1.5 self-end"/>
<HandIcon size="15" absoluteStrokeWidth className="-mt-2 -mx-1.5 self-start"/>
</div>
}
/>
<Card href="#" title="Automatic granular data-fetching" icon={<ArrowUpDownIcon />} />
<Card href="#" title="Cloud persistence & Local storage" icon={<UploadCloudIcon />} />
<Card
href="#"
title="Offline support & sync-when-possible"
icon={<PlaneIcon />}
/>
<Card href="#" title="Fluid UI perf & 90% less loading" icon={<GaugeIcon />}/>
</Cards>
## First impressions&hellip;
<Slogan small>A chat app in 86 lines of code.</Slogan>
<Grid>
<GridItem>
```tsx filename="dataModel.ts" showLineNumbers
import { CoMap, CoList } from 'cojson';
export type Chat = CoList<Message['id']>;
export type Message = CoMap<{ text: string }>;
```
</GridItem>
<GridItem className="col-start-1">
```tsx filename="app.tsx" showLineNumbers
import { WithJazz, useJazz, DemoAuth } from 'jazz-react';
import ReactDOM from 'react-dom/client';
import { HashRoute } from 'hashroute';
import { ChatWindow } from './chatWindow.tsx';
import { Chat } from './dataModel.ts';
ReactDOM.createRoot(document.getElementById('root')!).render(
<WithJazz auth={DemoAuth({ appName: 'Chat' })}>
<App />
</WithJazz>,
);
function App() {
return <div className='flex flex-col items-center justify-between w-screen h-screen p-2 dark:bg-black dark:text-white'>
<button onClick={useJazz().logOut} className='rounded mb-5 px-2 py-1 bg-stone-200 dark:bg-stone-800 dark:text-white self-end'>
Log Out
</button>
{HashRoute({
'/': <Home />,
'/:id': (id) => <ChatWindow chatId={id as Chat['id']} />,
}, { reportToParentFrame: true })}
</div>
}
function Home() {
const { me } = useJazz();
// Groups determine access rights to values they own.
const createChat = () => {
const group = me.createGroup().addMember('everyone', 'writer');
const chat = group.createList<Chat>();
location.hash = '/' + chat.id;
};
return <button onClick={createChat} className='rounded py-2 px-4 bg-stone-200 dark:bg-stone-800 dark:text-white my-auto'>
Create New Chat
</button>
}
````
</GridItem>
<GridItem className="col-start-2 row-start-1 row-span-2">
```tsx filename="chatWindow.tsx" showLineNumbers
import { useAutoSub } from 'jazz-react';
import { Chat, Message } from './dataModel.ts';
export function ChatWindow({ chatId }: { chatId: Chat['id'] }) {
const chat = useAutoSub(chatId);
return chat ? <div className='w-full max-w-xl h-full flex flex-col items-stretch'>
{
chat.map((msg, i) => (
<ChatBubble key={msg?.id}
text={msg?.text}
by={chat.meta.edits[i].by?.profile?.name}
byMe={chat.meta.edits[i].by?.isMe}
time={chat.meta.edits[i].at} />
))
}
<ChatInput onSubmit={(text) => {
const msg = chat.meta.group.createMap<Message>({ text });
chat.append(msg.id);
}}/>
</div> : <div>Loading...</div>;
}
function ChatBubble({ text, by, time: t, byMe }:
{ text?: string, by?: string, time?: Date, byMe?: boolean }
) {
return <div className={`items-${byMe ? 'end' : 'start'} flex flex-col`}>
<div className='rounded-xl bg-stone-100 dark:bg-stone-700 dark:text-white py-2 px-4 mt-2 min-w-[5rem]'>
{ text }
</div>
<div className='text-xs text-neutral-500 ml-2'>
{ by } { t?.getHours() }:{ t?.getMinutes() }
</div>
</div>;
}
function ChatInput({ onSubmit }: { onSubmit: (text: string) => void }) {
return <input className='rounded p-2 border mt-auto dark:bg-black dark:text-white dark:border-stone-700'
placeholder='Type a message and press Enter'
onKeyDown={({ key, currentTarget: input }) => {
if (key !== 'Enter' || !input.value) return;
onSubmit(input.value);
input.value = '';
}}/>
}
````
</GridItem>
<ResponsiveIframe src="http://localhost:9999/" className="col-start-3 row-start-1 row-span-2 rounded-xl overflow-hidden border dark:border-stone-700 min-h-[50vh]"/>
</Grid>
## How does it work?
<Slogan small>Introducing: Secure collaborative data.</Slogan>
Jazz is built around **CoJSON,** a new abstraction that implements **multi-device co-editing,** **user identities & permissions** and **sync & persistence** in a standardized way with a high-level API.
This makes collaboration and secure access control feel like **inherent properties of your data** &mdash;&nbsp;so&nbsp;we're calling it &ldquo;secure collaborative data.&rdquo;
### Collaborative Values
<Slogan small>Your new building blocks.</Slogan>
- Data that multiple users can co-edit in real time or async with smart conflict resolution
<Grid>
<GridCard>
#### `CoMap`s - Key-value maps
</GridCard>
<GridCard>
#### `CoList`s - Ordered lists
</GridCard>
<GridCard>
#### `CoString`s - Plain-text
</GridCard>
<GridCard>
#### `CoText`s - Rich-text
- Generic collaborative markup format that prevents most editing conflicts
</GridCard>
<GridCard>
#### `CoStream`s - Per-user value streams
- Enforce per-user separation for user presence, social reactions, polls, replies etc.
</GridCard>
<GridCard>
#### `BinaryCoStream`s - file/media streams
- Create, reference and load even huge binary blobs or create live-streams without needing external services
</GridCard>
</Grid>
### Accounts & Groups
<Slogan small>First-class user identities & secure permissions.</Slogan>
- Simple API to define groups of users, their roles
- Verifiably enforced by encryption and signatures
## Jazz: batteries included.
<Grid>
<GridCard>
### Auto-sub
<Slogan small>Let your UI drive data-syncing</Slogan>
</GridCard>
<GridCard>
### Auth providers
</GridCard>
<GridCard>
### Two-way sync to your existing database
</GridCard>
</Grid>
## Global Mesh

View File

@@ -0,0 +1,7 @@
import { Slogan } from './index.mdx'
# Jazz Global Mesh
<Slogan>Serverless sync and storage for Jazz apps.</Slogan>
Real-time syncing infrastructure that scales up to millions of users. Pricing that scales down to zero.

View File

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

View File

@@ -0,0 +1,15 @@
module.exports = {
darkMode: 'class',
content: [
'./pages/**/*.{js,jsx,ts,tsx,md,mdx}',
'./components/**/*.{js,jsx,ts,tsx,md,mdx}',
'./theme.config.jsx'
],
theme: {
extend: {
display: ['var(--font-manrope)'],
mono: ['var(--font-pragmata)'],
}
},
plugins: []
}

View File

@@ -0,0 +1,62 @@
import Link from "next/link";
export default {
logo: (
<svg
width={386 / 4}
height={146 / 4}
viewBox="0 0 386 146"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M176.725 33.865H188.275V22.7H176.725V33.865ZM164.9 129.4H172.875C182.72 129.4 188.275 123.9 188.275 114.22V43.6H176.725V109.545C176.725 115.65 173.975 118.51 167.925 118.51H164.9V129.4ZM245.298 53.28C241.613 45.47 233.363 41.95 222.748 41.95C208.998 41.95 200.748 48.44 197.888 58.615L208.613 61.915C210.648 55.315 216.368 52.565 222.638 52.565C231.933 52.565 235.673 56.415 236.058 64.61C226.433 65.93 216.643 67.195 209.768 69.23C200.583 72.145 195.743 77.865 195.743 86.83C195.743 96.51 202.673 104.65 215.818 104.65C225.443 104.65 232.318 101.35 237.213 94.365V103H247.388V66.425C247.388 61.475 247.168 57.185 245.298 53.28ZM217.853 95.245C210.483 95.245 207.128 91.34 207.128 86.72C207.128 82.045 210.593 79.515 215.323 77.92C220.328 76.435 226.983 75.5 235.948 74.18C235.893 76.93 235.673 80.725 234.738 83.475C233.418 89.25 227.643 95.245 217.853 95.245ZM251.22 103H301.545V92.715H269.535L303.195 45.47V43.6H254.3V53.885H284.935L251.22 101.185V103ZM304.815 103H355.14V92.715H323.13L356.79 45.47V43.6H307.895V53.885H338.53L304.815 101.185V103Z"
fill="currentColor"
/>
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M136.179 44.8277C136.179 44.8277 136.179 44.8277 136.179 44.8276V21.168C117.931 28.5527 97.9854 32.6192 77.0897 32.6192C65.1466 32.6192 53.5138 31.2908 42.331 28.7737V51.4076C42.331 51.4076 42.331 51.4076 42.331 51.4076V81.1508C41.2955 80.4385 40.1568 79.8458 38.9405 79.3915C36.1732 78.358 33.128 78.0876 30.1902 78.6145C27.2524 79.1414 24.5539 80.4419 22.4358 82.3516C20.3178 84.2613 18.8754 86.6944 18.291 89.3433C17.7066 91.9921 18.0066 94.7377 19.1528 97.2329C20.2991 99.728 22.2403 101.861 24.7308 103.361C27.2214 104.862 30.1495 105.662 33.1448 105.662H33.1455C33.6061 105.662 33.8365 105.662 34.0314 105.659C44.5583 105.449 53.042 96.9656 53.2513 86.4386C53.2534 86.3306 53.2544 86.2116 53.2548 86.0486H53.2552V85.7149L53.2552 85.5521V82.0762L53.2552 53.1993C61.0533 54.2324 69.0092 54.7656 77.0897 54.7656C77.6696 54.7656 78.2489 54.7629 78.8276 54.7574V110.696C77.792 109.983 76.6533 109.391 75.437 108.936C72.6697 107.903 69.6246 107.632 66.6867 108.159C63.7489 108.686 61.0504 109.987 58.9323 111.896C56.8143 113.806 55.3719 116.239 54.7875 118.888C54.2032 121.537 54.5031 124.283 55.6494 126.778C56.7956 129.273 58.7368 131.405 61.2273 132.906C63.7179 134.406 66.646 135.207 69.6414 135.207C70.1024 135.207 70.3329 135.207 70.5279 135.203C81.0548 134.994 89.5385 126.51 89.7478 115.983C89.7517 115.788 89.7517 115.558 89.7517 115.097V111.621L89.7517 54.3266C101.962 53.4768 113.837 51.4075 125.255 48.2397V80.9017C124.219 80.1894 123.081 79.5966 121.864 79.1424C119.097 78.1089 116.052 77.8384 113.114 78.3653C110.176 78.8922 107.478 80.1927 105.36 82.1025C103.242 84.0122 101.799 86.4453 101.215 89.0941C100.631 91.743 100.931 94.4886 102.077 96.9837C103.223 99.4789 105.164 101.612 107.655 103.112C110.145 104.612 113.073 105.413 116.069 105.413C116.53 105.413 116.76 105.413 116.955 105.409C127.482 105.2 135.966 96.7164 136.175 86.1895C136.179 85.9945 136.179 85.764 136.179 85.3029V81.8271L136.179 44.8277Z"
fill="#3313F7"
/>
</svg>
),
project: {
link: "https://github.com/gardencmp/jazz",
},
docsRepositoryBase:
"https://github.com/gardencmp/jazz/tree/main/homepage/homepage-jazz",
chat: { link: "https://discord.gg/utDMjHYg42" },
navbar: {
extraContent: (
<Link
className="nx-p-2 nx-text-current"
href={"https://twitter.com/jazz_tools"}
target="_blank"
>
<svg width="24" height="24" viewBox="0 0 248 204">
<path
fill="currentColor"
d="M221.95 51.29c.15 2.17.15 4.34.15 6.53 0 66.73-50.8 143.69-143.69 143.69v-.04c-27.44.04-54.31-7.82-77.41-22.64 3.99.48 8 .72 12.02.73 22.74.02 44.83-7.61 62.72-21.66-21.61-.41-40.56-14.5-47.18-35.07a50.338 50.338 0 0 0 22.8-.87C27.8 117.2 10.85 96.5 10.85 72.46v-.64a50.18 50.18 0 0 0 22.92 6.32C11.58 63.31 4.74 33.79 18.14 10.71a143.333 143.333 0 0 0 104.08 52.76 50.532 50.532 0 0 1 14.61-48.25c20.34-19.12 52.33-18.14 71.45 2.19 11.31-2.23 22.15-6.38 32.07-12.26a50.69 50.69 0 0 1-22.2 27.93c10.01-1.18 19.79-3.86 29-7.95a102.594 102.594 0 0 1-25.2 26.16z"
/>
</svg>
</Link>
),
},
useNextSeoProps() {
return {
titleTemplate: "jazz %s",
};
},
footer: {
text: (
<span>
MIT {new Date().getFullYear()} ©{" "}
<a href="https://gcmp.io" target="_blank">
Garden Computing, Inc
</a>
.
</span>
),
}
};

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"]
}

File diff suppressed because it is too large Load Diff

View File

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

View File

@@ -1,22 +1,124 @@
import './globals.css'
import type { Metadata } from 'next'
import { Inter } from 'next/font/google'
import "./globals.css";
import type { Metadata } from "next";
import { ThemeProvider } from "@/components/themeProvider";
const inter = Inter({ subsets: ['latin'] })
import { Manrope } from "next/font/google";
import { Inter } from "next/font/google";
import localFont from "next/font/local";
import { GcmpLogo, JazzLogo } from "@/components/logos";
import { SiGithub, SiDiscord, SiTwitter } from "@icons-pack/react-simple-icons";
import { Nav } from "@/components/nav";
// If loading a variable font, you don't need to specify the font weight
const manrope = Manrope({ subsets: ["latin"], variable: "--font-manrope" });
const inter = Inter({ subsets: ["latin"], variable: "--font-inter" });
const pragmata = localFont({
src: "../fonts/PragmataProR_0829.woff2",
variable: "--font-pragmata",
});
export const metadata: Metadata = {
title: 'Create Next App',
description: 'Generated by create next app',
}
title: "Create Next App",
description: "Generated by create next app",
};
export default function RootLayout({
children,
children,
}: {
children: React.ReactNode
children: React.ReactNode;
}) {
return (
<html lang="en">
<body className={inter.className}>{children}</body>
</html>
)
return (
<html lang="en">
<body
className={[
manrope.variable,
pragmata.variable,
inter.className,
"flex flex-col items-center bg-stone-50 dark:bg-stone-950 overflow-x-hidden",
].join(" ")}
>
<ThemeProvider
attribute="class"
defaultTheme="system"
enableSystem
disableTransitionOnChange
>
<Nav
mainLogo={<JazzLogo className="w-24" />}
items={[
{ title: "Toolkit", href: "/" },
{ title: "Global Mesh", href: "/mesh" },
{ title: "Docs & Guides", href: "/docs" },
{
title: "Blog",
href: "https://gcmp.io/news",
firstOnRight: true,
},
{
title: "Releases",
href: "https://github.com/gardencmp/jazz/releases",
},
{
title: "Roadmap",
href: "https://github.com/orgs/gardencmp/projects/4/views/3",
},
{
title: "GitHub",
href: "https://github.com/gardencmp/jazz",
icon: <SiGithub className="w-5" />,
},
{
title: "Discord",
href: "https://discord.gg/utDMjHYg42",
icon: <SiDiscord className="w-5" />,
},
{
title: "X",
href: "https://x.com/jazz_tools",
icon: <SiTwitter className="w-5" />,
},
]}
/>
<main className="flex min-h-screen flex-col p-8 max-w-[80rem] w-full">
<article
className={[
"pt-20",
"prose lg:prose-lg max-w-none prose-stone dark:prose-invert",
"prose-headings:font-display",
"prose-h1:text-5xl lg:prose-h1:text-6xl prose-h1:font-medium prose-h1:tracking-tighter",
"prose-h2:text-2xl lg:prose-h2:text-3xl prose-h2:font-medium prose-h2:tracking-tight",
"prose-p:max-w-3xl prose-p:leading-snug",
"prose-strong:font-medium",
"prose-code:leading-tight prose-code:before:content-none prose-code:after:content-none prose-code:bg-stone-100 prose-code:dark:bg-stone-900 prose-code:p-1 prose-code:-my-1 prose-code:rounded",
].join(" ")}
>
{children}
</article>
</main>
<footer className="flex mt-10 min-h-[15rem] -mb-20 bg-stone-100 dark:bg-stone-900 text-stone-600 dark:text-stone-400 w-full justify-center">
<div className="p-8 max-w-[80rem] w-full flex gap-4">
<div className="flex-1 flex flex-col gap-2 text-sm">
<GcmpLogo monochrome className="w-32" />
<p className="mt-auto">
© 2023
<br />
Garden Computing, Inc.
</p>
</div>
<div className="flex-1 flex flex-col gap-2 text-sm">
{/* <h1 className="font-medium">Resources</h1> */}
</div>
<div className="flex-1 flex flex-col gap-2 text-sm">
{/* <h1 className="font-medium">Legal</h1> */}
</div>
<div className="flex-1 flex flex-col gap-2 text-sm">
{/* <h1 className="font-medium">Newsletter</h1> */}
</div>
</div>
</footer>
</ThemeProvider>
</body>
</html>
);
}

View File

@@ -0,0 +1,94 @@
import { Slogan, Grid, GridCard } from '@/components/forMdx';
import { Pricing } from '@/components/pricing';
# Jazz Global Mesh
<Slogan>Serverless sync & storage for Jazz apps.</Slogan>
Real-time sync and storage infrastructure that scales up to millions of users.<br/>
Pricing that scales down to zero.
## The first Collaboration Delivery Network
<Slogan small>Build demanding apps with write-heavy distributed state, backed by a new kind of cloud.</Slogan>
<Grid>
<GridCard>
#### Optimal mesh routing.
Get ultra-low latency between any group of users with our decentralized mesh interconnect.
</GridCard>
<GridCard>
#### Smart caching.
Give users instant load times, with their latest data state always cached close to them.
</GridCard>
<GridCard>
#### Blob storage & media streaming.
</GridCard>
</Grid>
## Pricing
<Slogan small></Slogan>
<Pricing />
### Transactions explained
## Global Footprint
Currently we are running endpoints in the following locations:
- Los Angeles
- New Jersey
- Frankfurt
- Singapore
## Custom Deployment Scenarios
<Slogan>You can rely on Global Mesh. But you don't have to.</Slogan>
<p>Because Jazz is open-source, you can optionally run your own sync nodes &mdash; in a variety of setups.</p>
<Grid>
<GridCard>
#### Global Mesh + Data Backup Node.
<p className="no-prose text-base">Connect your users to Global Mesh for all its benefits, but also run and connect your own data backup node (just in case.)</p>
<div className="text-sm">
Extra costs:
- Instance costs for the backup node.
- Moderate self-hosted storage costs.
- Every transaction is additionally synced to your backup node and counted as synced out.
</div>
</GridCard>
<GridCard>
#### Global Mesh + DIY Mesh.
<p className="no-prose text-base">Connect your users to Global Mesh, or your own nodes as a lower-performance fallback. The two networks stay in constant sync.</p>
<div className="text-sm">
Extra costs:
- N × instance cost for your sync nodes.
- Typically moderate self-hosted egress costs.
- High self-hosted storage costs.
- Every transaction is additionally synced to your DIY mesh and counted as synced out.
</div>
</GridCard>
<GridCard>
#### Completely DIY Mesh.
<p className="no-prose text-base">Build your own network of sync and storage nodes.
Handle networking, security and backups yourself.</p>
<div className="text-sm">
Costs:
- N × instance cost for your sync nodes.
- Very high self-hosted egress costs.
- High self-hosted storage costs.
</div>
</GridCard>
</Grid>

View File

@@ -0,0 +1,175 @@
import {
Slogan,
Grid,
GridItem,
GridFeature,
GridCard,
MultiplayerIcon,
ResponsiveIframe,
ComingSoonBadge
} from "@/components/forMdx";
import {
ListTreeIcon,
UploadCloudIcon,
PlaneIcon,
MonitorSmartphoneIcon,
GaugeIcon,
} from "lucide-react";
import {
DataModel_ts,
App_tsx,
ChatWindow_tsx,
} from "@/codeSamples/examples/chat/src";
# Instant sync.
<Slogan>Go beyond request/response &mdash; ship modern apps with sync.</Slogan>
Jazz is an open-source toolkit for building apps with **sync** & **secure collaborative data.**
<h2 className="md:mt-24">Hard things are easy now.</h2>
Jazz replaces APIs, DBs and message queues with **a single new abstraction: CoJSON**.
And you get **built-in capabilities** that took best-in-class apps years to build:
<Grid className="-mt-2">
<GridFeature icon={<MonitorSmartphoneIcon />}>Cross-device sync</GridFeature>
<GridFeature icon={<MultiplayerIcon/>}>Real-time multiplayer</GridFeature>
<GridFeature icon={<ListTreeIcon />}>Automatic granular datafetching</GridFeature>
<GridFeature icon={<UploadCloudIcon />}>Cloud persistence<br/>& local storage</GridFeature>
<GridFeature icon={<PlaneIcon />}>Offline support<br/>& sync-when-possible</GridFeature>
<GridFeature icon={<GaugeIcon />}>Fluid UI performance<br/>& 90% less loading</GridFeature>
</Grid>
<div className="-mx-[calc(min(0,(100vw-95rem)/2))]">
### First impressions: A chat app in 82 lines of code.
<Grid className="mt-0">
<GridItem>
<DataModel_ts/>
</GridItem>
<GridItem className="md:col-start-1">
<App_tsx/>
</GridItem>
<GridItem className="md:col-start-2 md:row-start-1 md:row-span-2">
<ChatWindow_tsx/>
</GridItem>
<ResponsiveIframe src="http://localhost:9999/" className="lg:col-start-3 lg:row-start-1 lg:row-span-2 rounded-xl overflow-hidden min-h-[50vh]"/>
</Grid>
</div>
## A new standard for secure collaborative data.
Jazz is built around **CoJSON,** a new abstraction that implements **multi-device co-editing,** **user identities,** **permissions,** **sync** and **persistence** in a standardized way.
CoJSON makes collaboration and secure access control feel like **inherent properties of your data**.
### Collaborative Values
<Slogan small>Your new building blocks.</Slogan>
Collaborative Values (CoValues) **can be edited as if they were simple local data,** but they're **automatically encrypted, signed** and **synced** between participants.
CoValues also **retain their full edit history,** including author metadata and potential editing conflicts. This makes it **super simple to build collaborative and social features.**
<Grid className="lg:gap-y-8">
<GridCard>
### `CoMap`
<div className="text-sm">
- Collaborative key-value map
- Possible values:
- Immutable JSON & IDs of other CoValues
</div>
</GridCard>
<GridCard>
### `CoList`
<div className="text-sm">
- Collaborative ordered list
- Possible items:
- Immutable JSON & IDs of other CoValues
</div>
</GridCard>
<GridItem className="col-span-full lg:col-span-1 mb-10 lg:ml-4 [&>p]:m-0">
The bread and butter of datastructures, with collaboration built-in. You can build whole apps with just these.
</GridItem>
<GridCard>
### `CoString`
<div className="text-sm">
- Collaborative plain-text
- Implemented as a CoList of unicode graphemes
</div>
</GridCard>
<GridCard>
### `CoText`
<div className="text-sm">
- Collaborative rich-text & generic markup format
- Based on CoString + collaborative markup ranges
- Gracefully prevents most editing conflicts
- Rendered as markdown, HTML, JSX, etc.
</div>
</GridCard>
<GridItem className="col-span-full lg:col-span-1 mb-10 lg:ml-4 [&>p]:m-0">
A shocking amount of UI is text editing. CoJSON offers correct, versatile primitives.
</GridItem>
<GridCard>
### `CoStream`
<div className="text-sm">
- Collection of independent per-user items streams:
- Immutable JSON & IDs of other CoValues
- Can be used for user presence, social reactions, polls, replies etc.
</div>
</GridCard>
<GridCard>
### `BinaryCoStream`
<div className="text-sm">
- File/media stream
- Create, reference and load binary blobs or do live-streams without external services
</div>
</GridCard>
<GridItem className="col-span-full lg:col-span-1 mb-10 lg:ml-4 [&>p]:m-0">
The secret weapons of
</GridItem>
</Grid>
### Accounts & Groups
<Slogan small>First-class user identities & secure permissions.</Slogan>
- Simple API to define groups of users, their roles
- Verifiably enforced by encryption and signatures
## Jazz: batteries included.
<Grid>
<GridCard>
### Auto-sub
<Slogan small>Let your UI drive data-syncing</Slogan>
</GridCard>
<GridCard>
### Auth providers <ComingSoonBadge/>
<Slogan small>Plug and play different kinds of auth.</Slogan>
</GridCard>
<GridCard>
### Two-way sync to your DB <ComingSoonBadge/>
<Slogan small>Migrate to Jazz feature-by-feature.</Slogan>
</GridCard>
</Grid>
## Global Mesh

View File

@@ -1,113 +0,0 @@
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>
)
}

File diff suppressed because one or more lines are too long

View File

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

View File

@@ -0,0 +1,67 @@
"use client";
import { useLayoutEffect, useState, useRef, IframeHTMLAttributes } from "react";
export function ResponsiveIframe(
props: IframeHTMLAttributes<HTMLIFrameElement>
) {
const containerRef = useRef<HTMLDivElement>(null);
const [dimensions, setDimensions] = useState({ width: 0, height: 0 });
const [url, setUrl] = useState<string | undefined>(props.src);
useLayoutEffect(() => {
const listener = (e: MessageEvent) => {
console.log(e);
if (e.data.type === "navigate" && props.src?.startsWith(e.origin)) {
setUrl(e.data.url);
}
};
window.addEventListener("message", listener);
return () => {
window.removeEventListener("message", listener);
};
}, [props.src]);
useLayoutEffect(() => {
if (!containerRef.current) return;
const observer = new ResizeObserver(() => {
if (!containerRef.current) return;
setDimensions({
width: containerRef.current.offsetWidth,
height: containerRef.current.offsetHeight,
});
});
observer.observe(containerRef.current);
return () => {
observer.disconnect();
};
}, [containerRef]);
return (
<div
className={
"w-full h-full flex flex-col items-stretch border border-stone-200 dark:border-stone-800 " +
props.className
}
>
<div className="rounded-t-xl bg-stone-100 dark:bg-stone-900 py-1.5 px-10 flex">
<input
className="text-xs px-1 py-0.5 bg-stone-100 dark:bg-stone-900 outline outline-1 outline-stone-200 dark:outline-stone-800 w-full rounded text-center"
value={url?.replace("http://", "").replace("https://", "")}
onClick={(e) => e.currentTarget.select()}
onBlur={(e) => e.currentTarget.setSelectionRange(0, 0)}
readOnly
/>
</div>
<div className="flex-grow" ref={containerRef}>
<iframe
{...props}
className="dark:bg-black"
{...dimensions}
allowFullScreen
/>
</div>
</div>
);
}

View File

@@ -0,0 +1,114 @@
export function Slogan(props: { children: ReactNode; small?: boolean }) {
return (
<div
className={[
"leading-snug mb-5 max-w-3xl text-stone-700 dark:text-stone-200",
props.small ? "text-lg lg:text-xl -mt-2" : "text-xl lg:text-2xl -mt-5",
].join(" ")}
>
{props.children}
</div>
);
}
export function Grid({
className,
children,
}: {
className?: string;
children: ReactNode;
}) {
return (
<div
className={cn(
"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",
"mt-10 items-stretch",
className
)}
>
{children}
</div>
);
}
export function GridItem(props: { children: ReactNode; className?: string }) {
return <div className={props.className || ""}>{props.children}</div>;
}
export function GridFeature(props: {
icon: ReactNode;
children: ReactNode;
className?: string;
}) {
return (
<div
className={[
"p-4 flex items-center gap-2",
"not-prose text-base",
"border border-stone-200 dark:border-stone-800 rounded-xl shadow-sm",
props.className || "",
].join(" ")}
>
<div className="text-stone-500 mr-2">{props.icon}</div>
{props.children}
</div>
);
}
export function GridCard(props: { children: ReactNode; className?: string }) {
return (
<div
className={[
"p-4 [&>h4]:mt-0 [&>h3]:mt-0 [&>:last-child]:mb-0",
"border border-stone-200 dark:border-stone-800 rounded-xl shadow-sm",
props.className,
].join(" ")}
>
{props.children}
</div>
);
}
export function MultiplayerIcon() {
return (
<div className="w-8 h-8 -my-1 -mr-2 relative">
<TextCursorIcon
size="12"
absoluteStrokeWidth
strokeWidth={1.8}
className="absolute top-0 left-0.5 -z-10"
/>
<MousePointer2Icon
size="16"
absoluteStrokeWidth
strokeWidth={1.8}
className="absolute top-1.5 right-1 -z-10"
/>
<HandIcon
size="16"
absoluteStrokeWidth
strokeWidth={1.8}
className="absolute bottom-0 left-0 -z-10"
/>
</div>
);
}
export function ComingSoonBadge() {
return (
<span className="bg-stone-100 dark:bg-stone-900 text-stone-500 dark:text-stone-400 border border-stone-300 dark:border-stone-700 text-[0.6rem] px-1 py-0.5 rounded-xl align-text-top">
Coming&nbsp;soon
</span>
);
}
import { IframeHTMLAttributes, ReactNode } from "react";
import { ResponsiveIframe as ResponsiveIframeClient } from "./ResponsiveIframe";
import { HandIcon, MousePointer2Icon, TextCursorIcon } from "lucide-react";
import { cn } from "@/lib/utils";
export function ResponsiveIframe(
props: IframeHTMLAttributes<HTMLIFrameElement>
) {
return <ResponsiveIframeClient {...props} />;
}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,240 @@
"use client";
import { cn } from "@/lib/utils";
import { MenuIcon, SearchIcon, XIcon } from "lucide-react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { ReactNode, useLayoutEffect, useRef, useState } from "react";
export function Nav({
mainLogo,
items,
}: {
mainLogo: ReactNode;
items: {
href: string;
icon?: ReactNode;
title: string;
firstOnRight?: boolean;
}[];
}) {
const [menuOpen, setMenuOpen] = useState(false);
const [searchOpen, setSearchOpen] = useState(false);
const searchRef = useRef<HTMLInputElement>(null);
useLayoutEffect(() => {
searchOpen && searchRef.current?.focus();
}, [searchOpen]);
return (
<>
<nav
className={[
"hidden md:flex sticky left-0 right-0 top-0 max-sm:bottom-0 w-full justify-center",
"bg-stone-50/70 dark:bg-stone-950/70 border-b max-sm:border-t border-stone-50 dark:border-b-stone-950 backdrop-blur-md",
"max-h-none overflow-hidden transition[max-height] duration-300 ease-in-out",
menuOpen ? "h-[100dvh]" : "h-16",
].join(" ")}
>
<div className="flex flex-wrap px-8 items-center max-sm:justify-between lg:gap-2 max-w-[80rem] w-full">
<div className="flex items-center flex-shrink">
<NavLinkLogo prominent href="/" className="-ml-2">
{mainLogo}
</NavLinkLogo>
</div>
{items.map((item, i) =>
"icon" in item ? (
<NavLinkLogo key={i} href={item.href}>
{item.icon}
</NavLinkLogo>
) : (
<NavLink
key={i}
href={item.href}
className={cn(
"max-sm:w-full",
item.firstOnRight ? "md:ml-auto" : ""
)}
>
{item.title}
</NavLink>
)
)}
</div>
</nav>
<div className="md:hidden px-4 flex items-center self-stretch dark:text-white">
<NavLinkLogo
prominent
href="/"
className="mr-auto"
>
{mainLogo}
</NavLinkLogo>
<button
className="flex p-3 rounded-xl"
onMouseDown={() => {
setMenuOpen((o) => !o);
setSearchOpen(false);
}}
>
<MenuIcon className="" />
</button>
</div>
<div
onClick={() => {
setMenuOpen(false);
setSearchOpen(false);
}}
className={cn(
menuOpen || searchOpen ? "block" : "hidden",
"fixed top-0 bottom-0 left-0 right-0 bg-stone-200/80 dark:bg-black/80 w-full h-full"
)}
></div>
<nav
className={cn(
"md:hidden fixed flex flex-col items-end bottom-4 right-4",
"bg-stone-50 dark:bg-stone-925 dark:text-white border border-stone-100 dark:border-stone-900 dark:outline dark:outline-1 dark:outline-black/60 rounded-lg shadow-lg",
menuOpen || searchOpen ? "left-4" : ""
)}
>
<div
className={cn(
menuOpen ? "flex" : "hidden",
"flex-wrap px-2 pb-2"
)}
>
<div className="flex items-center w-full border-b border-stone-100 dark:border-stone-900">
<NavLinkLogo
prominent
href="/"
className="-ml-4 mr-auto"
onClick={() => setMenuOpen(false)}
>
{mainLogo}
</NavLinkLogo>
{items
.filter((item) => "icon" in item)
.map((item, i) => (
<NavLinkLogo key={i} href={item.href}>
{item.icon}
</NavLinkLogo>
))}
</div>
{items
.filter((item) => !("icon" in item))
.map((item, i) => (
<NavLink
key={i}
href={item.href}
onClick={() => setMenuOpen(false)}
className={cn(
"max-sm:w-full border-b border-stone-100 dark:border-stone-900",
item.firstOnRight ? "md:ml-auto" : ""
)}
>
{item.title}
</NavLink>
))}
</div>
<div className="flex items-center self-stretch justify-end">
<input
type="text"
className={cn(
menuOpen || searchOpen ? "" : "hidden",
"ml-2 border border-stone-200 dark:border-stone-900 px-2 py-1 rounded w-full"
)}
placeholder="Search docs..."
ref={searchRef}
/>
<button
className="flex p-3 rounded-xl"
onClick={() => {
setSearchOpen(true);
}}
onBlur={(e) => {
if (!e.currentTarget.value) {
setSearchOpen(false);
}
}}
>
<SearchIcon className="" />
</button>
<button
className="flex p-3 rounded-xl"
onMouseDown={() => {
setMenuOpen((o) => !o);
setSearchOpen(false);
}}
>
{(menuOpen || searchOpen) ? <XIcon/>: <MenuIcon className="" />}
</button>
</div>
</nav>
</>
);
}
export function NavLink({
href,
className,
children,
onClick,
}: {
href: string;
className?: string;
children: ReactNode;
onClick?: () => void;
}) {
const path = usePathname();
return (
<Link
href={href}
className={[
"px-2 lg:px-4 py-3 text-sm",
className,
path === href
? "font-medium text-black dark:text-white cursor-default"
: "text-stone-600 dark:text-stone-400 hover:text-black dark:hover:text-white transition-colors hover:transition-none",
].join(" ")}
onClick={onClick}
>
{children}
</Link>
);
}
export function NavLinkLogo({
href,
className,
children,
prominent,
onClick,
}: {
href: string;
className?: string;
children: ReactNode;
prominent?: boolean;
onClick?: () => void;
}) {
const path = usePathname();
return (
<Link
href={href}
className={[
"max-sm:px-4 px-2 lg:px-3 py-3 transition-opacity hover:transition-none",
path === href
? "cursor-default"
: prominent
? "hover:opacity-50"
: "opacity-60 hover:opacity-100",
"text-black dark:text-white",
className,
].join(" ")}
onClick={onClick}
>
{children}
</Link>
);
}

View File

@@ -0,0 +1,84 @@
import { ComingSoonBadge, Grid, GridCard, GridItem } from "./forMdx";
export function Pricing() {
const pricePer1MtxSyncedOut = 2;
const pricePer1MtxStored = 4;
const pricePerTxSyncedOut = pricePer1MtxSyncedOut / 1_000_000;
const pricePerTxStored = pricePer1MtxStored / 1_000_000;
const worstCaseBytesPerTx = 200_000;
const avgCaseBytesPerTx = 10_000;
const worstCaseCostPerTBstorage = 20;
const worstCaseCostPerTxStored =
worstCaseBytesPerTx * (worstCaseCostPerTBstorage / 1_000_000_000_000);
const avgCaseCostPerTxStored =
avgCaseBytesPerTx * (worstCaseCostPerTBstorage / 1_000_000_000_000);
const costPerTBEgress = 5;
const serverCost = 30;
const txOutPerSecondPerServer = 100;
const txPerMonthPerServer = txOutPerSecondPerServer * 60 * 60 * 24 * 30;
const worstCaseCostPerTxSyncedOut =
worstCaseBytesPerTx * (costPerTBEgress / 1_000_000_000_000) +
serverCost / txPerMonthPerServer;
const avgCaseCostPerTxSyncedOut =
avgCaseBytesPerTx * (costPerTBEgress / 1_000_000_000_000) +
serverCost / txPerMonthPerServer;
const recommendedSyncToStorageRatio = 0.2;
const freeTierSyncedOut = 100_000;
const freeTierStored = freeTierSyncedOut / recommendedSyncToStorageRatio;
const proTierSyncedOut = 500_000;
const proTierStored = proTierSyncedOut / recommendedSyncToStorageRatio;
return (
<Grid>
<GridCard>
<h3>Free Tier</h3>
<p className="text-lg line-through">Any usage under $2/mo is free!</p>
<p className="text-lg font-medium bg-amber-200 dark:bg-amber-800 px-2 py-1 rounded">Until we implement API keys and billing all usage of Global Mesh is free!</p>
</GridCard>
<GridCard>
<h3>Unlimited <ComingSoonBadge/></h3>
<p className="text-lg line-through">
{fmt$(pricePer1MtxSyncedOut)} per 1,000,000 transactions
synced out
{/* <br />
Avg cost: {fmt$(avgCaseCostPerTxSyncedOut * 1_000_000)}
<br />
Worst cost: {fmt$(worstCaseCostPerTxSyncedOut * 1_000_000)} */}
<br/>
{fmt$(pricePer1MtxStored)}
<small>/mo</small> per 1,000,000 transactions stored
{/* <br />
Avg cost: {fmt$(avgCaseCostPerTxStored * 1_000_000)}
<br />
Worst cost: {fmt$(worstCaseCostPerTxStored * 1_000_000)} */}
</p>
<p className="text-sm">Transactions usually represent individual user actions, or up to 100KB of binary data.</p>
</GridCard>
<GridCard>
<h3>Enterprise</h3>
<p className="text-sm">Custom deployment in the cloud, your private cloud, on-premises or hybrids?</p>
<p className="text-sm">SLAs and dedicated support? White-glove integration services?</p>
</GridCard>
</Grid>
);
}
function fmt(num: number) {
return num.toLocaleString("en-US", {});
}
function fmt$(num: number) {
return (
"$" +
num.toLocaleString("en-US", {
maximumSignificantDigits: 3,
})
);
}

View File

@@ -0,0 +1,9 @@
"use client"
import * as React from "react"
import { ThemeProvider as NextThemesProvider } from "next-themes"
import { type ThemeProviderProps } from "next-themes/dist/types"
export function ThemeProvider({ children, ...props }: ThemeProviderProps) {
return <NextThemesProvider {...props}>{children}</NextThemesProvider>
}

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