mirror of
https://github.com/supabase/supabase.git
synced 2026-10-05 09:25:06 +03:00
feat: add Realtime Flow component (#44273)
## I have read the [CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md) file. YES ## What kind of change does this PR introduce? Feature, docs update ## What is the new behavior? This PR introduces a new `RealtimeFlow` component and hook to the UI library for building collaborative React Flow with Supabase Realtime: - keeps nodes and edges in sync across multiple connected clients in real time - uses Yjs with `@supabase-labs/y-supabase` to propagate flow updates - supports optional persistence, so a flow can be restored from previously saved shared state ## Additional context https://github.com/user-attachments/assets/90d3a381-6f9c-427f-a493-5d91c2141462 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Collaborative "Realtime Flow" diagram editor with syncing overlays and a dual-view demo component * Interactive demo page and registry example for live editing (add/remove/rename nodes) * Framework-ready registry packages for Next.js, React, React Router, and TanStack * **Documentation** * Comprehensive docs added for Next.js, React, React Router, and TanStack (usage, persistence, hook API) * **Chores** * Added runtime dependency for the flow component package [](https://app.coderabbit.ai/change-stack/supabase/supabase/pull/44273) <!-- end of auto-generated comment: release notes by coderabbit.ai -->
This commit is contained in:
1 parent
033daf223c
commit
b79a64e301
43 files changed
+1980
-28
No files matched your search
@@ -15,6 +15,10 @@ export const Index = {
|
||||
component: React.lazy(() => import("@/registry/default/examples/realtime-cursor-demo.tsx")),
|
||||
}
|
||||
,
|
||||
"realtime-flow-demo": {
|
||||
component: React.lazy(() => import("@/registry/default/examples/realtime-flow-demo.tsx")),
|
||||
}
|
||||
,
|
||||
"realtime-monaco-demo": {
|
||||
component: React.lazy(() => import("@/registry/default/examples/realtime-monaco-demo.tsx")),
|
||||
}
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
'use client'
|
||||
|
||||
import Demo from '@/registry/default/examples/realtime-flow-demo'
|
||||
|
||||
const RealtimeFlowDemoPage = () => {
|
||||
return <Demo />
|
||||
}
|
||||
|
||||
export default RealtimeFlowDemoPage
|
||||
@@ -0,0 +1,14 @@
|
||||
'use client'
|
||||
|
||||
import { BlockPreview } from './block-preview'
|
||||
|
||||
export function DualRealtimeFlow() {
|
||||
return (
|
||||
<>
|
||||
<div className="flex flex-row -space-x-px w-full">
|
||||
<BlockPreview name="realtime-flow-demo" isPair />
|
||||
<BlockPreview name="realtime-flow-demo" isPair />
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import { Callout } from './callout'
|
||||
import { ComponentPreview } from './component-preview'
|
||||
import { CopyButton } from './copy-button'
|
||||
import { DualRealtimeChat } from './dual-realtime-chat'
|
||||
import { DualRealtimeFlow } from './dual-realtime-flow'
|
||||
import { DualRealtimeMonaco } from './dual-realtime-monaco'
|
||||
import { RegistryBlock } from './registry-block'
|
||||
import { StyleWrapper } from './style-wrapper'
|
||||
@@ -174,6 +175,7 @@ const components = {
|
||||
BlockItem,
|
||||
BlockPreview,
|
||||
DualRealtimeChat,
|
||||
DualRealtimeFlow,
|
||||
DualRealtimeMonaco,
|
||||
TanstackDBGenerator,
|
||||
}
|
||||
|
||||
@@ -94,8 +94,17 @@ export const componentPages: SidebarNavGroup = {
|
||||
supportedFrameworks: ['nextjs', 'react-router', 'tanstack', 'react'],
|
||||
href: '/docs/nextjs/realtime-monaco',
|
||||
items: [],
|
||||
new: true,
|
||||
commandItemLabel: 'Realtime Monaco',
|
||||
},
|
||||
{
|
||||
title: 'Realtime Flow',
|
||||
supportedFrameworks: ['nextjs', 'react-router', 'tanstack', 'react'],
|
||||
href: '/docs/nextjs/realtime-flow',
|
||||
items: [],
|
||||
new: true,
|
||||
commandItemLabel: 'Realtime Flow',
|
||||
},
|
||||
{
|
||||
title: 'Current User Avatar',
|
||||
supportedFrameworks: ['nextjs', 'react-router', 'tanstack', 'react', 'vue', 'nuxtjs'],
|
||||
|
||||
@@ -0,0 +1,224 @@
|
||||
---
|
||||
title: Realtime Flow
|
||||
description: Real-time flow diagram editor for collaborative applications
|
||||
---
|
||||
|
||||
<DualRealtimeFlow />
|
||||
|
||||
## Installation
|
||||
|
||||
<BlockItem
|
||||
name="realtime-flow-nextjs"
|
||||
description="Real-time flow diagram editor for collaborative applications."
|
||||
/>
|
||||
|
||||
## Folder structure
|
||||
|
||||
<RegistryBlock itemName="realtime-flow-nextjs" />
|
||||
|
||||
## Introduction
|
||||
|
||||
The Realtime Flow component provides a collaborative diagram editor powered by [React Flow](https://reactflow.dev/) and [Yjs](https://yjs.dev/). It uses [`@supabase-labs/y-supabase`](https://github.com/supabase-community/y-supabase) under the hood to sync diagram state across clients through Supabase Realtime.
|
||||
|
||||
**Features**
|
||||
|
||||
- Real-time node and edge synchronization via Supabase Realtime broadcast
|
||||
- Drag nodes, create connections, and delete elements collaboratively
|
||||
- Optional persistence to Postgres so diagrams survive page reloads
|
||||
- Supports custom node and edge types
|
||||
- Room-based isolation for scoped collaboration
|
||||
|
||||
## How it works under the hood
|
||||
|
||||
The component creates a [Yjs](https://yjs.dev/) document with two shared maps — one for nodes and one for edges — and connects it to a Supabase Realtime channel using `SupabaseProvider` from `@supabase-labs/y-supabase`. Each node and edge is stored by its ID in the respective `Y.Map`, enabling per-element conflict resolution.
|
||||
|
||||
When a user drags a node, creates a connection, or deletes an element, the change is applied to the local React Flow state and simultaneously written to the Yjs document. Remote changes from other clients are observed and applied to the local state automatically.
|
||||
|
||||
When **persistence** is enabled, the full Yjs document state is saved to a Postgres table so it can be restored when clients reconnect.
|
||||
|
||||
## Usage
|
||||
|
||||
### Basic usage
|
||||
|
||||
```tsx
|
||||
import { RealtimeFlow } from '@/components/realtime-flow'
|
||||
|
||||
const nodes = [
|
||||
{ id: '1', position: { x: 0, y: 0 }, data: { label: 'Node A' } },
|
||||
{ id: '2', position: { x: 250, y: 150 }, data: { label: 'Node B' } },
|
||||
]
|
||||
|
||||
const edges = [{ id: 'e1-2', source: '1', target: '2' }]
|
||||
|
||||
export default function FlowPage() {
|
||||
return <RealtimeFlow channel="realtime-flow-demo" initialNodes={nodes} initialEdges={edges} />
|
||||
}
|
||||
```
|
||||
|
||||
### With persistence
|
||||
|
||||
Enable persistence to save the diagram to your Supabase database. This requires a table to store the Yjs document state.
|
||||
|
||||
First, create the required table in your Supabase project:
|
||||
|
||||
```sql
|
||||
create table yjs_documents (
|
||||
room text primary key,
|
||||
state text not null
|
||||
);
|
||||
```
|
||||
|
||||
Then pass `persistence` to the component:
|
||||
|
||||
```tsx
|
||||
import { RealtimeFlow } from '@/components/realtime-flow'
|
||||
|
||||
export default function FlowPage() {
|
||||
return (
|
||||
<RealtimeFlow
|
||||
channel="realtime-flow-demo"
|
||||
initialNodes={nodes}
|
||||
initialEdges={edges}
|
||||
persistence
|
||||
/>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
You can also pass a `SupabasePersistenceOptions` object:
|
||||
|
||||
```tsx
|
||||
import type { SupabasePersistenceOptions } from '@supabase-labs/y-supabase'
|
||||
|
||||
const persistenceOptions = {
|
||||
table: 'yjs_documents',
|
||||
roomColumn: 'room',
|
||||
stateColumn: 'state',
|
||||
storeTimeout: 2000,
|
||||
} satisfies SupabasePersistenceOptions
|
||||
|
||||
export default function FlowPage() {
|
||||
return (
|
||||
<RealtimeFlow
|
||||
channel="realtime-flow-demo"
|
||||
initialNodes={nodes}
|
||||
initialEdges={edges}
|
||||
persistence={persistenceOptions}
|
||||
/>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### Using the hook for full control
|
||||
|
||||
If you need programmatic access to nodes and edges (e.g. adding nodes, custom node types with editable data), use the `useRealtimeFlow` hook directly instead of the component:
|
||||
|
||||
```tsx
|
||||
import {
|
||||
ReactFlow,
|
||||
ReactFlowProvider,
|
||||
Background,
|
||||
Controls,
|
||||
type Node,
|
||||
type Edge,
|
||||
} from '@xyflow/react'
|
||||
import { useRealtimeFlow } from '@/hooks/use-realtime-flow'
|
||||
|
||||
const initialNodes: Node[] = [
|
||||
{ id: '1', position: { x: 0, y: 0 }, data: { label: 'Node A' } },
|
||||
{ id: '2', position: { x: 250, y: 150 }, data: { label: 'Node B' } },
|
||||
]
|
||||
|
||||
export default function FlowPage() {
|
||||
const { nodes, edges, synced, onNodesChange, onEdgesChange, onConnect, setNodes, setEdges } =
|
||||
useRealtimeFlow({
|
||||
channel: 'my-flow',
|
||||
initialNodes,
|
||||
})
|
||||
|
||||
return (
|
||||
<ReactFlowProvider>
|
||||
<ReactFlow
|
||||
nodes={synced ? nodes : []}
|
||||
edges={synced ? edges : []}
|
||||
onNodesChange={synced ? onNodesChange : undefined}
|
||||
onEdgesChange={synced ? onEdgesChange : undefined}
|
||||
onConnect={synced ? onConnect : undefined}
|
||||
fitView
|
||||
>
|
||||
<Background />
|
||||
<Controls />
|
||||
</ReactFlow>
|
||||
</ReactFlowProvider>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
`setNodes` and `setEdges` accept a new array or an updater function, just like React's `useState`:
|
||||
|
||||
```tsx
|
||||
// Add a node
|
||||
setNodes((prev) => [...prev, newNode])
|
||||
|
||||
// Update a node
|
||||
setNodes((prev) => prev.map((n) => (n.id === '1' ? { ...n, data: { label: 'Updated' } } : n)))
|
||||
|
||||
// Remove a node and its connected edges
|
||||
setNodes((prev) => prev.filter((n) => n.id !== '1'))
|
||||
setEdges((prev) => prev.filter((e) => e.source !== '1' && e.target !== '1'))
|
||||
```
|
||||
|
||||
## RealtimeFlow Props
|
||||
|
||||
| Prop | Type | Description |
|
||||
| --------------- | --------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `channel` | `string` | Unique channel name used to sync diagram state between collaborators in the same session. |
|
||||
| `initialNodes?` | `Node[]` | Initial nodes to populate the diagram. Only used if no existing state is found after sync. |
|
||||
| `initialEdges?` | `Edge[]` | Initial edges to populate the diagram. Only used if no existing state is found after sync. |
|
||||
| `height?` | `string \| number` | Height of the flow container. Accepts a pixel number or CSS string (e.g. `"100%"`). Defaults to `550`. |
|
||||
| `className?` | `string` | CSS class applied to the flow wrapper element. |
|
||||
| `style?` | `React.CSSProperties` | Inline styles applied to the flow wrapper element. |
|
||||
| `persistence?` | `boolean \| SupabasePersistenceOptions` | Persists diagram state to Supabase so it survives page reloads. Pass `true` for defaults or an options object for fine-grained control. |
|
||||
| `nodeTypes?` | `NodeTypes` | Custom node type definitions for React Flow. |
|
||||
| `edgeTypes?` | `EdgeTypes` | Custom edge type definitions for React Flow. |
|
||||
|
||||
## useRealtimeFlow Options
|
||||
|
||||
| Option | Type | Description |
|
||||
| --------------- | --------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `channel` | `string` | Unique channel name used to sync diagram state between collaborators in the same session. |
|
||||
| `initialNodes?` | `Node[]` | Initial nodes to populate the diagram. Only used if no existing state is found after sync. |
|
||||
| `initialEdges?` | `Edge[]` | Initial edges to populate the diagram. Only used if no existing state is found after sync. |
|
||||
| `awareness?` | `boolean \| Awareness` | Enables presence tracking between users. Pass `false` to disable or a custom `Awareness` instance. Defaults to `true`. |
|
||||
| `persistence?` | `boolean \| SupabasePersistenceOptions` | Persists diagram state to Supabase so it survives page reloads. Pass `true` for defaults or an options object for fine-grained control. |
|
||||
|
||||
## useRealtimeFlow Return Value
|
||||
|
||||
| Property | Type | Description |
|
||||
| --------------- | ----------------------------------------------------- | ---------------------------------------------------------------------- |
|
||||
| `nodes` | `Node[]` | Current nodes array, kept in sync across all connected clients. |
|
||||
| `edges` | `Edge[]` | Current edges array, kept in sync across all connected clients. |
|
||||
| `synced` | `boolean` | Whether the initial sync has completed. Render empty state until true. |
|
||||
| `onNodesChange` | `(changes: NodeChange[]) => void` | Pass directly to React Flow's `onNodesChange` prop. |
|
||||
| `onEdgesChange` | `(changes: EdgeChange[]) => void` | Pass directly to React Flow's `onEdgesChange` prop. |
|
||||
| `onConnect` | `(connection: Connection) => void` | Pass directly to React Flow's `onConnect` prop. |
|
||||
| `setNodes` | `(nodes: Node[] \| (prev: Node[]) => Node[]) => void` | Update nodes programmatically. Changes are synced to all clients. |
|
||||
| `setEdges` | `(edges: Edge[] \| (prev: Edge[]) => Edge[]) => void` | Update edges programmatically. Changes are synced to all clients. |
|
||||
|
||||
### SupabasePersistenceOptions
|
||||
|
||||
| Option | Type | Default | Description |
|
||||
| -------------- | -------- | ----------------- | --------------------------------------------------- |
|
||||
| `table` | `string` | `'yjs_documents'` | Name of the Postgres table used to store documents. |
|
||||
| `schema` | `string` | `'public'` | Schema where the table is located. |
|
||||
| `roomColumn` | `string` | `'room'` | Column used as the document identifier. |
|
||||
| `stateColumn` | `string` | `'state'` | Column used to store the binary Yjs state. |
|
||||
| `storeTimeout` | `number` | `1000` | Debounce delay (ms) before persisting changes. |
|
||||
|
||||
## Further reading
|
||||
|
||||
- [Realtime Broadcast](https://supabase.com/docs/guides/realtime/broadcast)
|
||||
- [Realtime authorization](https://supabase.com/docs/guides/realtime/authorization)
|
||||
- [`@supabase-labs/y-supabase`](https://github.com/supabase-community/y-supabase)
|
||||
- [Yjs documentation](https://docs.yjs.dev/)
|
||||
- [React Flow documentation](https://reactflow.dev/)
|
||||
@@ -0,0 +1,224 @@
|
||||
---
|
||||
title: Realtime Flow
|
||||
description: Real-time flow diagram editor for collaborative applications
|
||||
---
|
||||
|
||||
<DualRealtimeFlow />
|
||||
|
||||
## Installation
|
||||
|
||||
<BlockItem
|
||||
name="realtime-flow-react-router"
|
||||
description="Real-time flow diagram editor for collaborative applications."
|
||||
/>
|
||||
|
||||
## Folder structure
|
||||
|
||||
<RegistryBlock itemName="realtime-flow-react-router" />
|
||||
|
||||
## Introduction
|
||||
|
||||
The Realtime Flow component provides a collaborative diagram editor powered by [React Flow](https://reactflow.dev/) and [Yjs](https://yjs.dev/). It uses [`@supabase-labs/y-supabase`](https://github.com/supabase-community/y-supabase) under the hood to sync diagram state across clients through Supabase Realtime.
|
||||
|
||||
**Features**
|
||||
|
||||
- Real-time node and edge synchronization via Supabase Realtime broadcast
|
||||
- Drag nodes, create connections, and delete elements collaboratively
|
||||
- Optional persistence to Postgres so diagrams survive page reloads
|
||||
- Supports custom node and edge types
|
||||
- Room-based isolation for scoped collaboration
|
||||
|
||||
## How it works under the hood
|
||||
|
||||
The component creates a [Yjs](https://yjs.dev/) document with two shared maps — one for nodes and one for edges — and connects it to a Supabase Realtime channel using `SupabaseProvider` from `@supabase-labs/y-supabase`. Each node and edge is stored by its ID in the respective `Y.Map`, enabling per-element conflict resolution.
|
||||
|
||||
When a user drags a node, creates a connection, or deletes an element, the change is applied to the local React Flow state and simultaneously written to the Yjs document. Remote changes from other clients are observed and applied to the local state automatically.
|
||||
|
||||
When **persistence** is enabled, the full Yjs document state is saved to a Postgres table so it can be restored when clients reconnect.
|
||||
|
||||
## Usage
|
||||
|
||||
### Basic usage
|
||||
|
||||
```tsx
|
||||
import { RealtimeFlow } from '@/components/realtime-flow'
|
||||
|
||||
const nodes = [
|
||||
{ id: '1', position: { x: 0, y: 0 }, data: { label: 'Node A' } },
|
||||
{ id: '2', position: { x: 250, y: 150 }, data: { label: 'Node B' } },
|
||||
]
|
||||
|
||||
const edges = [{ id: 'e1-2', source: '1', target: '2' }]
|
||||
|
||||
export default function FlowPage() {
|
||||
return <RealtimeFlow channel="realtime-flow-demo" initialNodes={nodes} initialEdges={edges} />
|
||||
}
|
||||
```
|
||||
|
||||
### With persistence
|
||||
|
||||
Enable persistence to save the diagram to your Supabase database. This requires a table to store the Yjs document state.
|
||||
|
||||
First, create the required table in your Supabase project:
|
||||
|
||||
```sql
|
||||
create table yjs_documents (
|
||||
room text primary key,
|
||||
state text not null
|
||||
);
|
||||
```
|
||||
|
||||
Then pass `persistence` to the component:
|
||||
|
||||
```tsx
|
||||
import { RealtimeFlow } from '@/components/realtime-flow'
|
||||
|
||||
export default function FlowPage() {
|
||||
return (
|
||||
<RealtimeFlow
|
||||
channel="realtime-flow-demo"
|
||||
initialNodes={nodes}
|
||||
initialEdges={edges}
|
||||
persistence
|
||||
/>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
You can also pass a `SupabasePersistenceOptions` object:
|
||||
|
||||
```tsx
|
||||
import type { SupabasePersistenceOptions } from '@supabase-labs/y-supabase'
|
||||
|
||||
const persistenceOptions = {
|
||||
table: 'yjs_documents',
|
||||
roomColumn: 'room',
|
||||
stateColumn: 'state',
|
||||
storeTimeout: 2000,
|
||||
} satisfies SupabasePersistenceOptions
|
||||
|
||||
export default function FlowPage() {
|
||||
return (
|
||||
<RealtimeFlow
|
||||
channel="realtime-flow-demo"
|
||||
initialNodes={nodes}
|
||||
initialEdges={edges}
|
||||
persistence={persistenceOptions}
|
||||
/>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### Using the hook for full control
|
||||
|
||||
If you need programmatic access to nodes and edges (e.g. adding nodes, custom node types with editable data), use the `useRealtimeFlow` hook directly instead of the component:
|
||||
|
||||
```tsx
|
||||
import {
|
||||
ReactFlow,
|
||||
ReactFlowProvider,
|
||||
Background,
|
||||
Controls,
|
||||
type Node,
|
||||
type Edge,
|
||||
} from '@xyflow/react'
|
||||
import { useRealtimeFlow } from '@/hooks/use-realtime-flow'
|
||||
|
||||
const initialNodes: Node[] = [
|
||||
{ id: '1', position: { x: 0, y: 0 }, data: { label: 'Node A' } },
|
||||
{ id: '2', position: { x: 250, y: 150 }, data: { label: 'Node B' } },
|
||||
]
|
||||
|
||||
export default function FlowPage() {
|
||||
const { nodes, edges, synced, onNodesChange, onEdgesChange, onConnect, setNodes, setEdges } =
|
||||
useRealtimeFlow({
|
||||
channel: 'my-flow',
|
||||
initialNodes,
|
||||
})
|
||||
|
||||
return (
|
||||
<ReactFlowProvider>
|
||||
<ReactFlow
|
||||
nodes={synced ? nodes : []}
|
||||
edges={synced ? edges : []}
|
||||
onNodesChange={synced ? onNodesChange : undefined}
|
||||
onEdgesChange={synced ? onEdgesChange : undefined}
|
||||
onConnect={synced ? onConnect : undefined}
|
||||
fitView
|
||||
>
|
||||
<Background />
|
||||
<Controls />
|
||||
</ReactFlow>
|
||||
</ReactFlowProvider>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
`setNodes` and `setEdges` accept a new array or an updater function, just like React's `useState`:
|
||||
|
||||
```tsx
|
||||
// Add a node
|
||||
setNodes((prev) => [...prev, newNode])
|
||||
|
||||
// Update a node
|
||||
setNodes((prev) => prev.map((n) => (n.id === '1' ? { ...n, data: { label: 'Updated' } } : n)))
|
||||
|
||||
// Remove a node and its connected edges
|
||||
setNodes((prev) => prev.filter((n) => n.id !== '1'))
|
||||
setEdges((prev) => prev.filter((e) => e.source !== '1' && e.target !== '1'))
|
||||
```
|
||||
|
||||
## RealtimeFlow Props
|
||||
|
||||
| Prop | Type | Description |
|
||||
| --------------- | --------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `channel` | `string` | Unique channel name used to sync diagram state between collaborators in the same session. |
|
||||
| `initialNodes?` | `Node[]` | Initial nodes to populate the diagram. Only used if no existing state is found after sync. |
|
||||
| `initialEdges?` | `Edge[]` | Initial edges to populate the diagram. Only used if no existing state is found after sync. |
|
||||
| `height?` | `string \| number` | Height of the flow container. Accepts a pixel number or CSS string (e.g. `"100%"`). Defaults to `550`. |
|
||||
| `className?` | `string` | CSS class applied to the flow wrapper element. |
|
||||
| `style?` | `React.CSSProperties` | Inline styles applied to the flow wrapper element. |
|
||||
| `persistence?` | `boolean \| SupabasePersistenceOptions` | Persists diagram state to Supabase so it survives page reloads. Pass `true` for defaults or an options object for fine-grained control. |
|
||||
| `nodeTypes?` | `NodeTypes` | Custom node type definitions for React Flow. |
|
||||
| `edgeTypes?` | `EdgeTypes` | Custom edge type definitions for React Flow. |
|
||||
|
||||
## useRealtimeFlow Options
|
||||
|
||||
| Option | Type | Description |
|
||||
| --------------- | --------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `channel` | `string` | Unique channel name used to sync diagram state between collaborators in the same session. |
|
||||
| `initialNodes?` | `Node[]` | Initial nodes to populate the diagram. Only used if no existing state is found after sync. |
|
||||
| `initialEdges?` | `Edge[]` | Initial edges to populate the diagram. Only used if no existing state is found after sync. |
|
||||
| `awareness?` | `boolean \| Awareness` | Enables presence tracking between users. Pass `false` to disable or a custom `Awareness` instance. Defaults to `true`. |
|
||||
| `persistence?` | `boolean \| SupabasePersistenceOptions` | Persists diagram state to Supabase so it survives page reloads. Pass `true` for defaults or an options object for fine-grained control. |
|
||||
|
||||
## useRealtimeFlow Return Value
|
||||
|
||||
| Property | Type | Description |
|
||||
| --------------- | ----------------------------------------------------- | ---------------------------------------------------------------------- |
|
||||
| `nodes` | `Node[]` | Current nodes array, kept in sync across all connected clients. |
|
||||
| `edges` | `Edge[]` | Current edges array, kept in sync across all connected clients. |
|
||||
| `synced` | `boolean` | Whether the initial sync has completed. Render empty state until true. |
|
||||
| `onNodesChange` | `(changes: NodeChange[]) => void` | Pass directly to React Flow's `onNodesChange` prop. |
|
||||
| `onEdgesChange` | `(changes: EdgeChange[]) => void` | Pass directly to React Flow's `onEdgesChange` prop. |
|
||||
| `onConnect` | `(connection: Connection) => void` | Pass directly to React Flow's `onConnect` prop. |
|
||||
| `setNodes` | `(nodes: Node[] \| (prev: Node[]) => Node[]) => void` | Update nodes programmatically. Changes are synced to all clients. |
|
||||
| `setEdges` | `(edges: Edge[] \| (prev: Edge[]) => Edge[]) => void` | Update edges programmatically. Changes are synced to all clients. |
|
||||
|
||||
### SupabasePersistenceOptions
|
||||
|
||||
| Option | Type | Default | Description |
|
||||
| -------------- | -------- | ----------------- | --------------------------------------------------- |
|
||||
| `table` | `string` | `'yjs_documents'` | Name of the Postgres table used to store documents. |
|
||||
| `schema` | `string` | `'public'` | Schema where the table is located. |
|
||||
| `roomColumn` | `string` | `'room'` | Column used as the document identifier. |
|
||||
| `stateColumn` | `string` | `'state'` | Column used to store the binary Yjs state. |
|
||||
| `storeTimeout` | `number` | `1000` | Debounce delay (ms) before persisting changes. |
|
||||
|
||||
## Further reading
|
||||
|
||||
- [Realtime Broadcast](https://supabase.com/docs/guides/realtime/broadcast)
|
||||
- [Realtime authorization](https://supabase.com/docs/guides/realtime/authorization)
|
||||
- [`@supabase-labs/y-supabase`](https://github.com/supabase-community/y-supabase)
|
||||
- [Yjs documentation](https://docs.yjs.dev/)
|
||||
- [React Flow documentation](https://reactflow.dev/)
|
||||
@@ -0,0 +1,224 @@
|
||||
---
|
||||
title: Realtime Flow
|
||||
description: Real-time flow diagram editor for collaborative applications
|
||||
---
|
||||
|
||||
<DualRealtimeFlow />
|
||||
|
||||
## Installation
|
||||
|
||||
<BlockItem
|
||||
name="realtime-flow-react"
|
||||
description="Real-time flow diagram editor for collaborative applications."
|
||||
/>
|
||||
|
||||
## Folder structure
|
||||
|
||||
<RegistryBlock itemName="realtime-flow-react" />
|
||||
|
||||
## Introduction
|
||||
|
||||
The Realtime Flow component provides a collaborative diagram editor powered by [React Flow](https://reactflow.dev/) and [Yjs](https://yjs.dev/). It uses [`@supabase-labs/y-supabase`](https://github.com/supabase-community/y-supabase) under the hood to sync diagram state across clients through Supabase Realtime.
|
||||
|
||||
**Features**
|
||||
|
||||
- Real-time node and edge synchronization via Supabase Realtime broadcast
|
||||
- Drag nodes, create connections, and delete elements collaboratively
|
||||
- Optional persistence to Postgres so diagrams survive page reloads
|
||||
- Supports custom node and edge types
|
||||
- Room-based isolation for scoped collaboration
|
||||
|
||||
## How it works under the hood
|
||||
|
||||
The component creates a [Yjs](https://yjs.dev/) document with two shared maps — one for nodes and one for edges — and connects it to a Supabase Realtime channel using `SupabaseProvider` from `@supabase-labs/y-supabase`. Each node and edge is stored by its ID in the respective `Y.Map`, enabling per-element conflict resolution.
|
||||
|
||||
When a user drags a node, creates a connection, or deletes an element, the change is applied to the local React Flow state and simultaneously written to the Yjs document. Remote changes from other clients are observed and applied to the local state automatically.
|
||||
|
||||
When **persistence** is enabled, the full Yjs document state is saved to a Postgres table so it can be restored when clients reconnect.
|
||||
|
||||
## Usage
|
||||
|
||||
### Basic usage
|
||||
|
||||
```tsx
|
||||
import { RealtimeFlow } from '@/components/realtime-flow'
|
||||
|
||||
const nodes = [
|
||||
{ id: '1', position: { x: 0, y: 0 }, data: { label: 'Node A' } },
|
||||
{ id: '2', position: { x: 250, y: 150 }, data: { label: 'Node B' } },
|
||||
]
|
||||
|
||||
const edges = [{ id: 'e1-2', source: '1', target: '2' }]
|
||||
|
||||
export default function FlowPage() {
|
||||
return <RealtimeFlow channel="realtime-flow-demo" initialNodes={nodes} initialEdges={edges} />
|
||||
}
|
||||
```
|
||||
|
||||
### With persistence
|
||||
|
||||
Enable persistence to save the diagram to your Supabase database. This requires a table to store the Yjs document state.
|
||||
|
||||
First, create the required table in your Supabase project:
|
||||
|
||||
```sql
|
||||
create table yjs_documents (
|
||||
room text primary key,
|
||||
state text not null
|
||||
);
|
||||
```
|
||||
|
||||
Then pass `persistence` to the component:
|
||||
|
||||
```tsx
|
||||
import { RealtimeFlow } from '@/components/realtime-flow'
|
||||
|
||||
export default function FlowPage() {
|
||||
return (
|
||||
<RealtimeFlow
|
||||
channel="realtime-flow-demo"
|
||||
initialNodes={nodes}
|
||||
initialEdges={edges}
|
||||
persistence
|
||||
/>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
You can also pass a `SupabasePersistenceOptions` object:
|
||||
|
||||
```tsx
|
||||
import type { SupabasePersistenceOptions } from '@supabase-labs/y-supabase'
|
||||
|
||||
const persistenceOptions = {
|
||||
table: 'yjs_documents',
|
||||
roomColumn: 'room',
|
||||
stateColumn: 'state',
|
||||
storeTimeout: 2000,
|
||||
} satisfies SupabasePersistenceOptions
|
||||
|
||||
export default function FlowPage() {
|
||||
return (
|
||||
<RealtimeFlow
|
||||
channel="realtime-flow-demo"
|
||||
initialNodes={nodes}
|
||||
initialEdges={edges}
|
||||
persistence={persistenceOptions}
|
||||
/>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### Using the hook for full control
|
||||
|
||||
If you need programmatic access to nodes and edges (e.g. adding nodes, custom node types with editable data), use the `useRealtimeFlow` hook directly instead of the component:
|
||||
|
||||
```tsx
|
||||
import {
|
||||
ReactFlow,
|
||||
ReactFlowProvider,
|
||||
Background,
|
||||
Controls,
|
||||
type Node,
|
||||
type Edge,
|
||||
} from '@xyflow/react'
|
||||
import { useRealtimeFlow } from '@/hooks/use-realtime-flow'
|
||||
|
||||
const initialNodes: Node[] = [
|
||||
{ id: '1', position: { x: 0, y: 0 }, data: { label: 'Node A' } },
|
||||
{ id: '2', position: { x: 250, y: 150 }, data: { label: 'Node B' } },
|
||||
]
|
||||
|
||||
export default function FlowPage() {
|
||||
const { nodes, edges, synced, onNodesChange, onEdgesChange, onConnect, setNodes, setEdges } =
|
||||
useRealtimeFlow({
|
||||
channel: 'my-flow',
|
||||
initialNodes,
|
||||
})
|
||||
|
||||
return (
|
||||
<ReactFlowProvider>
|
||||
<ReactFlow
|
||||
nodes={synced ? nodes : []}
|
||||
edges={synced ? edges : []}
|
||||
onNodesChange={synced ? onNodesChange : undefined}
|
||||
onEdgesChange={synced ? onEdgesChange : undefined}
|
||||
onConnect={synced ? onConnect : undefined}
|
||||
fitView
|
||||
>
|
||||
<Background />
|
||||
<Controls />
|
||||
</ReactFlow>
|
||||
</ReactFlowProvider>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
`setNodes` and `setEdges` accept a new array or an updater function, just like React's `useState`:
|
||||
|
||||
```tsx
|
||||
// Add a node
|
||||
setNodes((prev) => [...prev, newNode])
|
||||
|
||||
// Update a node
|
||||
setNodes((prev) => prev.map((n) => (n.id === '1' ? { ...n, data: { label: 'Updated' } } : n)))
|
||||
|
||||
// Remove a node and its connected edges
|
||||
setNodes((prev) => prev.filter((n) => n.id !== '1'))
|
||||
setEdges((prev) => prev.filter((e) => e.source !== '1' && e.target !== '1'))
|
||||
```
|
||||
|
||||
## RealtimeFlow Props
|
||||
|
||||
| Prop | Type | Description |
|
||||
| --------------- | --------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `channel` | `string` | Unique channel name used to sync diagram state between collaborators in the same session. |
|
||||
| `initialNodes?` | `Node[]` | Initial nodes to populate the diagram. Only used if no existing state is found after sync. |
|
||||
| `initialEdges?` | `Edge[]` | Initial edges to populate the diagram. Only used if no existing state is found after sync. |
|
||||
| `height?` | `string \| number` | Height of the flow container. Accepts a pixel number or CSS string (e.g. `"100%"`). Defaults to `550`. |
|
||||
| `className?` | `string` | CSS class applied to the flow wrapper element. |
|
||||
| `style?` | `React.CSSProperties` | Inline styles applied to the flow wrapper element. |
|
||||
| `persistence?` | `boolean \| SupabasePersistenceOptions` | Persists diagram state to Supabase so it survives page reloads. Pass `true` for defaults or an options object for fine-grained control. |
|
||||
| `nodeTypes?` | `NodeTypes` | Custom node type definitions for React Flow. |
|
||||
| `edgeTypes?` | `EdgeTypes` | Custom edge type definitions for React Flow. |
|
||||
|
||||
## useRealtimeFlow Options
|
||||
|
||||
| Option | Type | Description |
|
||||
| --------------- | --------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `channel` | `string` | Unique channel name used to sync diagram state between collaborators in the same session. |
|
||||
| `initialNodes?` | `Node[]` | Initial nodes to populate the diagram. Only used if no existing state is found after sync. |
|
||||
| `initialEdges?` | `Edge[]` | Initial edges to populate the diagram. Only used if no existing state is found after sync. |
|
||||
| `awareness?` | `boolean \| Awareness` | Enables presence tracking between users. Pass `false` to disable or a custom `Awareness` instance. Defaults to `true`. |
|
||||
| `persistence?` | `boolean \| SupabasePersistenceOptions` | Persists diagram state to Supabase so it survives page reloads. Pass `true` for defaults or an options object for fine-grained control. |
|
||||
|
||||
## useRealtimeFlow Return Value
|
||||
|
||||
| Property | Type | Description |
|
||||
| --------------- | ----------------------------------------------------- | ---------------------------------------------------------------------- |
|
||||
| `nodes` | `Node[]` | Current nodes array, kept in sync across all connected clients. |
|
||||
| `edges` | `Edge[]` | Current edges array, kept in sync across all connected clients. |
|
||||
| `synced` | `boolean` | Whether the initial sync has completed. Render empty state until true. |
|
||||
| `onNodesChange` | `(changes: NodeChange[]) => void` | Pass directly to React Flow's `onNodesChange` prop. |
|
||||
| `onEdgesChange` | `(changes: EdgeChange[]) => void` | Pass directly to React Flow's `onEdgesChange` prop. |
|
||||
| `onConnect` | `(connection: Connection) => void` | Pass directly to React Flow's `onConnect` prop. |
|
||||
| `setNodes` | `(nodes: Node[] \| (prev: Node[]) => Node[]) => void` | Update nodes programmatically. Changes are synced to all clients. |
|
||||
| `setEdges` | `(edges: Edge[] \| (prev: Edge[]) => Edge[]) => void` | Update edges programmatically. Changes are synced to all clients. |
|
||||
|
||||
### SupabasePersistenceOptions
|
||||
|
||||
| Option | Type | Default | Description |
|
||||
| -------------- | -------- | ----------------- | --------------------------------------------------- |
|
||||
| `table` | `string` | `'yjs_documents'` | Name of the Postgres table used to store documents. |
|
||||
| `schema` | `string` | `'public'` | Schema where the table is located. |
|
||||
| `roomColumn` | `string` | `'room'` | Column used as the document identifier. |
|
||||
| `stateColumn` | `string` | `'state'` | Column used to store the binary Yjs state. |
|
||||
| `storeTimeout` | `number` | `1000` | Debounce delay (ms) before persisting changes. |
|
||||
|
||||
## Further reading
|
||||
|
||||
- [Realtime Broadcast](https://supabase.com/docs/guides/realtime/broadcast)
|
||||
- [Realtime authorization](https://supabase.com/docs/guides/realtime/authorization)
|
||||
- [`@supabase-labs/y-supabase`](https://github.com/supabase-community/y-supabase)
|
||||
- [Yjs documentation](https://docs.yjs.dev/)
|
||||
- [React Flow documentation](https://reactflow.dev/)
|
||||
@@ -0,0 +1,224 @@
|
||||
---
|
||||
title: Realtime Flow
|
||||
description: Real-time flow diagram editor for collaborative applications
|
||||
---
|
||||
|
||||
<DualRealtimeFlow />
|
||||
|
||||
## Installation
|
||||
|
||||
<BlockItem
|
||||
name="realtime-flow-tanstack"
|
||||
description="Real-time flow diagram editor for collaborative applications."
|
||||
/>
|
||||
|
||||
## Folder structure
|
||||
|
||||
<RegistryBlock itemName="realtime-flow-tanstack" />
|
||||
|
||||
## Introduction
|
||||
|
||||
The Realtime Flow component provides a collaborative diagram editor powered by [React Flow](https://reactflow.dev/) and [Yjs](https://yjs.dev/). It uses [`@supabase-labs/y-supabase`](https://github.com/supabase-community/y-supabase) under the hood to sync diagram state across clients through Supabase Realtime.
|
||||
|
||||
**Features**
|
||||
|
||||
- Real-time node and edge synchronization via Supabase Realtime broadcast
|
||||
- Drag nodes, create connections, and delete elements collaboratively
|
||||
- Optional persistence to Postgres so diagrams survive page reloads
|
||||
- Supports custom node and edge types
|
||||
- Room-based isolation for scoped collaboration
|
||||
|
||||
## How it works under the hood
|
||||
|
||||
The component creates a [Yjs](https://yjs.dev/) document with two shared maps — one for nodes and one for edges — and connects it to a Supabase Realtime channel using `SupabaseProvider` from `@supabase-labs/y-supabase`. Each node and edge is stored by its ID in the respective `Y.Map`, enabling per-element conflict resolution.
|
||||
|
||||
When a user drags a node, creates a connection, or deletes an element, the change is applied to the local React Flow state and simultaneously written to the Yjs document. Remote changes from other clients are observed and applied to the local state automatically.
|
||||
|
||||
When **persistence** is enabled, the full Yjs document state is saved to a Postgres table so it can be restored when clients reconnect.
|
||||
|
||||
## Usage
|
||||
|
||||
### Basic usage
|
||||
|
||||
```tsx
|
||||
import { RealtimeFlow } from '@/components/realtime-flow'
|
||||
|
||||
const nodes = [
|
||||
{ id: '1', position: { x: 0, y: 0 }, data: { label: 'Node A' } },
|
||||
{ id: '2', position: { x: 250, y: 150 }, data: { label: 'Node B' } },
|
||||
]
|
||||
|
||||
const edges = [{ id: 'e1-2', source: '1', target: '2' }]
|
||||
|
||||
export default function FlowPage() {
|
||||
return <RealtimeFlow channel="realtime-flow-demo" initialNodes={nodes} initialEdges={edges} />
|
||||
}
|
||||
```
|
||||
|
||||
### With persistence
|
||||
|
||||
Enable persistence to save the diagram to your Supabase database. This requires a table to store the Yjs document state.
|
||||
|
||||
First, create the required table in your Supabase project:
|
||||
|
||||
```sql
|
||||
create table yjs_documents (
|
||||
room text primary key,
|
||||
state text not null
|
||||
);
|
||||
```
|
||||
|
||||
Then pass `persistence` to the component:
|
||||
|
||||
```tsx
|
||||
import { RealtimeFlow } from '@/components/realtime-flow'
|
||||
|
||||
export default function FlowPage() {
|
||||
return (
|
||||
<RealtimeFlow
|
||||
channel="realtime-flow-demo"
|
||||
initialNodes={nodes}
|
||||
initialEdges={edges}
|
||||
persistence
|
||||
/>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
You can also pass a `SupabasePersistenceOptions` object:
|
||||
|
||||
```tsx
|
||||
import type { SupabasePersistenceOptions } from '@supabase-labs/y-supabase'
|
||||
|
||||
const persistenceOptions = {
|
||||
table: 'yjs_documents',
|
||||
roomColumn: 'room',
|
||||
stateColumn: 'state',
|
||||
storeTimeout: 2000,
|
||||
} satisfies SupabasePersistenceOptions
|
||||
|
||||
export default function FlowPage() {
|
||||
return (
|
||||
<RealtimeFlow
|
||||
channel="realtime-flow-demo"
|
||||
initialNodes={nodes}
|
||||
initialEdges={edges}
|
||||
persistence={persistenceOptions}
|
||||
/>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### Using the hook for full control
|
||||
|
||||
If you need programmatic access to nodes and edges (e.g. adding nodes, custom node types with editable data), use the `useRealtimeFlow` hook directly instead of the component:
|
||||
|
||||
```tsx
|
||||
import {
|
||||
ReactFlow,
|
||||
ReactFlowProvider,
|
||||
Background,
|
||||
Controls,
|
||||
type Node,
|
||||
type Edge,
|
||||
} from '@xyflow/react'
|
||||
import { useRealtimeFlow } from '@/hooks/use-realtime-flow'
|
||||
|
||||
const initialNodes: Node[] = [
|
||||
{ id: '1', position: { x: 0, y: 0 }, data: { label: 'Node A' } },
|
||||
{ id: '2', position: { x: 250, y: 150 }, data: { label: 'Node B' } },
|
||||
]
|
||||
|
||||
export default function FlowPage() {
|
||||
const { nodes, edges, synced, onNodesChange, onEdgesChange, onConnect, setNodes, setEdges } =
|
||||
useRealtimeFlow({
|
||||
channel: 'my-flow',
|
||||
initialNodes,
|
||||
})
|
||||
|
||||
return (
|
||||
<ReactFlowProvider>
|
||||
<ReactFlow
|
||||
nodes={synced ? nodes : []}
|
||||
edges={synced ? edges : []}
|
||||
onNodesChange={synced ? onNodesChange : undefined}
|
||||
onEdgesChange={synced ? onEdgesChange : undefined}
|
||||
onConnect={synced ? onConnect : undefined}
|
||||
fitView
|
||||
>
|
||||
<Background />
|
||||
<Controls />
|
||||
</ReactFlow>
|
||||
</ReactFlowProvider>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
`setNodes` and `setEdges` accept a new array or an updater function, just like React's `useState`:
|
||||
|
||||
```tsx
|
||||
// Add a node
|
||||
setNodes((prev) => [...prev, newNode])
|
||||
|
||||
// Update a node
|
||||
setNodes((prev) => prev.map((n) => (n.id === '1' ? { ...n, data: { label: 'Updated' } } : n)))
|
||||
|
||||
// Remove a node and its connected edges
|
||||
setNodes((prev) => prev.filter((n) => n.id !== '1'))
|
||||
setEdges((prev) => prev.filter((e) => e.source !== '1' && e.target !== '1'))
|
||||
```
|
||||
|
||||
## RealtimeFlow Props
|
||||
|
||||
| Prop | Type | Description |
|
||||
| --------------- | --------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `channel` | `string` | Unique channel name used to sync diagram state between collaborators in the same session. |
|
||||
| `initialNodes?` | `Node[]` | Initial nodes to populate the diagram. Only used if no existing state is found after sync. |
|
||||
| `initialEdges?` | `Edge[]` | Initial edges to populate the diagram. Only used if no existing state is found after sync. |
|
||||
| `height?` | `string \| number` | Height of the flow container. Accepts a pixel number or CSS string (e.g. `"100%"`). Defaults to `550`. |
|
||||
| `className?` | `string` | CSS class applied to the flow wrapper element. |
|
||||
| `style?` | `React.CSSProperties` | Inline styles applied to the flow wrapper element. |
|
||||
| `persistence?` | `boolean \| SupabasePersistenceOptions` | Persists diagram state to Supabase so it survives page reloads. Pass `true` for defaults or an options object for fine-grained control. |
|
||||
| `nodeTypes?` | `NodeTypes` | Custom node type definitions for React Flow. |
|
||||
| `edgeTypes?` | `EdgeTypes` | Custom edge type definitions for React Flow. |
|
||||
|
||||
## useRealtimeFlow Options
|
||||
|
||||
| Option | Type | Description |
|
||||
| --------------- | --------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `channel` | `string` | Unique channel name used to sync diagram state between collaborators in the same session. |
|
||||
| `initialNodes?` | `Node[]` | Initial nodes to populate the diagram. Only used if no existing state is found after sync. |
|
||||
| `initialEdges?` | `Edge[]` | Initial edges to populate the diagram. Only used if no existing state is found after sync. |
|
||||
| `awareness?` | `boolean \| Awareness` | Enables presence tracking between users. Pass `false` to disable or a custom `Awareness` instance. Defaults to `true`. |
|
||||
| `persistence?` | `boolean \| SupabasePersistenceOptions` | Persists diagram state to Supabase so it survives page reloads. Pass `true` for defaults or an options object for fine-grained control. |
|
||||
|
||||
## useRealtimeFlow Return Value
|
||||
|
||||
| Property | Type | Description |
|
||||
| --------------- | ----------------------------------------------------- | ---------------------------------------------------------------------- |
|
||||
| `nodes` | `Node[]` | Current nodes array, kept in sync across all connected clients. |
|
||||
| `edges` | `Edge[]` | Current edges array, kept in sync across all connected clients. |
|
||||
| `synced` | `boolean` | Whether the initial sync has completed. Render empty state until true. |
|
||||
| `onNodesChange` | `(changes: NodeChange[]) => void` | Pass directly to React Flow's `onNodesChange` prop. |
|
||||
| `onEdgesChange` | `(changes: EdgeChange[]) => void` | Pass directly to React Flow's `onEdgesChange` prop. |
|
||||
| `onConnect` | `(connection: Connection) => void` | Pass directly to React Flow's `onConnect` prop. |
|
||||
| `setNodes` | `(nodes: Node[] \| (prev: Node[]) => Node[]) => void` | Update nodes programmatically. Changes are synced to all clients. |
|
||||
| `setEdges` | `(edges: Edge[] \| (prev: Edge[]) => Edge[]) => void` | Update edges programmatically. Changes are synced to all clients. |
|
||||
|
||||
### SupabasePersistenceOptions
|
||||
|
||||
| Option | Type | Default | Description |
|
||||
| -------------- | -------- | ----------------- | --------------------------------------------------- |
|
||||
| `table` | `string` | `'yjs_documents'` | Name of the Postgres table used to store documents. |
|
||||
| `schema` | `string` | `'public'` | Schema where the table is located. |
|
||||
| `roomColumn` | `string` | `'room'` | Column used as the document identifier. |
|
||||
| `stateColumn` | `string` | `'state'` | Column used to store the binary Yjs state. |
|
||||
| `storeTimeout` | `number` | `1000` | Debounce delay (ms) before persisting changes. |
|
||||
|
||||
## Further reading
|
||||
|
||||
- [Realtime Broadcast](https://supabase.com/docs/guides/realtime/broadcast)
|
||||
- [Realtime authorization](https://supabase.com/docs/guides/realtime/authorization)
|
||||
- [`@supabase-labs/y-supabase`](https://github.com/supabase-community/y-supabase)
|
||||
- [Yjs documentation](https://docs.yjs.dev/)
|
||||
- [React Flow documentation](https://reactflow.dev/)
|
||||
@@ -26,6 +26,7 @@
|
||||
"@supabase/supa-mdx-lint": "0.2.6-alpha",
|
||||
"@supabase/vue-blocks": "workspace:*",
|
||||
"@tanstack/react-query": "^5.83.0",
|
||||
"@xyflow/react": "^12.10.1",
|
||||
"api-types": "workspace:*",
|
||||
"axios": "^1.12.0",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
|
||||
@@ -19,12 +19,12 @@
|
||||
},
|
||||
{
|
||||
"path": "registry/default/blocks/current-user-avatar/hooks/use-current-user-name.ts",
|
||||
"content": "import { useEffect, useState } from 'react'\n\nimport { createClient } from '@/registry/default/clients/nextjs/lib/supabase/client'\n\nexport const useCurrentUserName = () => {\n const [name, setName] = useState<string | null>(null)\n\n useEffect(() => {\n const fetchProfileName = async () => {\n const { data, error } = await createClient().auth.getSession()\n if (error) {\n console.error(error)\n }\n\n setName(data.session?.user.user_metadata.full_name ?? '?')\n }\n\n fetchProfileName()\n }, [])\n\n return name || '?'\n}\n",
|
||||
"content": "import { useEffect, useState } from 'react'\n\nimport { createClient } from '@/registry/default/clients/react-router/lib/supabase/client'\n\nexport const useCurrentUserName = () => {\n const [name, setName] = useState<string | null>(null)\n\n useEffect(() => {\n const fetchProfileName = async () => {\n const { data, error } = await createClient().auth.getSession()\n if (error) {\n console.error(error)\n }\n\n setName(data.session?.user.user_metadata.full_name ?? '?')\n }\n\n fetchProfileName()\n }, [])\n\n return name || '?'\n}\n",
|
||||
"type": "registry:hook"
|
||||
},
|
||||
{
|
||||
"path": "registry/default/blocks/current-user-avatar/hooks/use-current-user-image.ts",
|
||||
"content": "import { useEffect, useState } from 'react'\n\nimport { createClient } from '@/registry/default/clients/nextjs/lib/supabase/client'\n\nexport const useCurrentUserImage = () => {\n const [image, setImage] = useState<string | null>(null)\n\n useEffect(() => {\n const fetchUserImage = async () => {\n const { data, error } = await createClient().auth.getSession()\n if (error) {\n console.error(error)\n }\n\n setImage(data.session?.user.user_metadata.avatar_url ?? null)\n }\n fetchUserImage()\n }, [])\n\n return image\n}\n",
|
||||
"content": "import { useEffect, useState } from 'react'\n\nimport { createClient } from '@/registry/default/clients/react-router/lib/supabase/client'\n\nexport const useCurrentUserImage = () => {\n const [image, setImage] = useState<string | null>(null)\n\n useEffect(() => {\n const fetchUserImage = async () => {\n const { data, error } = await createClient().auth.getSession()\n if (error) {\n console.error(error)\n }\n\n setImage(data.session?.user.user_metadata.avatar_url ?? null)\n }\n fetchUserImage()\n }, [])\n\n return image\n}\n",
|
||||
"type": "registry:hook"
|
||||
},
|
||||
{
|
||||
|
||||
@@ -18,12 +18,12 @@
|
||||
},
|
||||
{
|
||||
"path": "registry/default/blocks/current-user-avatar/hooks/use-current-user-name.ts",
|
||||
"content": "import { useEffect, useState } from 'react'\n\nimport { createClient } from '@/registry/default/clients/nextjs/lib/supabase/client'\n\nexport const useCurrentUserName = () => {\n const [name, setName] = useState<string | null>(null)\n\n useEffect(() => {\n const fetchProfileName = async () => {\n const { data, error } = await createClient().auth.getSession()\n if (error) {\n console.error(error)\n }\n\n setName(data.session?.user.user_metadata.full_name ?? '?')\n }\n\n fetchProfileName()\n }, [])\n\n return name || '?'\n}\n",
|
||||
"content": "import { useEffect, useState } from 'react'\n\nimport { createClient } from '@/registry/default/clients/react/lib/supabase/client'\n\nexport const useCurrentUserName = () => {\n const [name, setName] = useState<string | null>(null)\n\n useEffect(() => {\n const fetchProfileName = async () => {\n const { data, error } = await createClient().auth.getSession()\n if (error) {\n console.error(error)\n }\n\n setName(data.session?.user.user_metadata.full_name ?? '?')\n }\n\n fetchProfileName()\n }, [])\n\n return name || '?'\n}\n",
|
||||
"type": "registry:hook"
|
||||
},
|
||||
{
|
||||
"path": "registry/default/blocks/current-user-avatar/hooks/use-current-user-image.ts",
|
||||
"content": "import { useEffect, useState } from 'react'\n\nimport { createClient } from '@/registry/default/clients/nextjs/lib/supabase/client'\n\nexport const useCurrentUserImage = () => {\n const [image, setImage] = useState<string | null>(null)\n\n useEffect(() => {\n const fetchUserImage = async () => {\n const { data, error } = await createClient().auth.getSession()\n if (error) {\n console.error(error)\n }\n\n setImage(data.session?.user.user_metadata.avatar_url ?? null)\n }\n fetchUserImage()\n }, [])\n\n return image\n}\n",
|
||||
"content": "import { useEffect, useState } from 'react'\n\nimport { createClient } from '@/registry/default/clients/react/lib/supabase/client'\n\nexport const useCurrentUserImage = () => {\n const [image, setImage] = useState<string | null>(null)\n\n useEffect(() => {\n const fetchUserImage = async () => {\n const { data, error } = await createClient().auth.getSession()\n if (error) {\n console.error(error)\n }\n\n setImage(data.session?.user.user_metadata.avatar_url ?? null)\n }\n fetchUserImage()\n }, [])\n\n return image\n}\n",
|
||||
"type": "registry:hook"
|
||||
},
|
||||
{
|
||||
|
||||
@@ -19,12 +19,12 @@
|
||||
},
|
||||
{
|
||||
"path": "registry/default/blocks/current-user-avatar/hooks/use-current-user-name.ts",
|
||||
"content": "import { useEffect, useState } from 'react'\n\nimport { createClient } from '@/registry/default/clients/nextjs/lib/supabase/client'\n\nexport const useCurrentUserName = () => {\n const [name, setName] = useState<string | null>(null)\n\n useEffect(() => {\n const fetchProfileName = async () => {\n const { data, error } = await createClient().auth.getSession()\n if (error) {\n console.error(error)\n }\n\n setName(data.session?.user.user_metadata.full_name ?? '?')\n }\n\n fetchProfileName()\n }, [])\n\n return name || '?'\n}\n",
|
||||
"content": "import { useEffect, useState } from 'react'\n\nimport { createClient } from '@/registry/default/clients/tanstack/lib/supabase/client'\n\nexport const useCurrentUserName = () => {\n const [name, setName] = useState<string | null>(null)\n\n useEffect(() => {\n const fetchProfileName = async () => {\n const { data, error } = await createClient().auth.getSession()\n if (error) {\n console.error(error)\n }\n\n setName(data.session?.user.user_metadata.full_name ?? '?')\n }\n\n fetchProfileName()\n }, [])\n\n return name || '?'\n}\n",
|
||||
"type": "registry:hook"
|
||||
},
|
||||
{
|
||||
"path": "registry/default/blocks/current-user-avatar/hooks/use-current-user-image.ts",
|
||||
"content": "import { useEffect, useState } from 'react'\n\nimport { createClient } from '@/registry/default/clients/nextjs/lib/supabase/client'\n\nexport const useCurrentUserImage = () => {\n const [image, setImage] = useState<string | null>(null)\n\n useEffect(() => {\n const fetchUserImage = async () => {\n const { data, error } = await createClient().auth.getSession()\n if (error) {\n console.error(error)\n }\n\n setImage(data.session?.user.user_metadata.avatar_url ?? null)\n }\n fetchUserImage()\n }, [])\n\n return image\n}\n",
|
||||
"content": "import { useEffect, useState } from 'react'\n\nimport { createClient } from '@/registry/default/clients/tanstack/lib/supabase/client'\n\nexport const useCurrentUserImage = () => {\n const [image, setImage] = useState<string | null>(null)\n\n useEffect(() => {\n const fetchUserImage = async () => {\n const { data, error } = await createClient().auth.getSession()\n if (error) {\n console.error(error)\n }\n\n setImage(data.session?.user.user_metadata.avatar_url ?? null)\n }\n fetchUserImage()\n }, [])\n\n return image\n}\n",
|
||||
"type": "registry:hook"
|
||||
},
|
||||
{
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
},
|
||||
{
|
||||
"path": "registry/default/blocks/dropzone/hooks/use-supabase-upload.ts",
|
||||
"content": "import { useCallback, useEffect, useMemo, useState } from 'react'\nimport { useDropzone, type FileError, type FileRejection } from 'react-dropzone'\n\nimport { createClient } from '@/registry/default/clients/nextjs/lib/supabase/client'\n\nconst supabase = createClient()\n\ninterface FileWithPreview extends File {\n preview?: string\n errors: readonly FileError[]\n}\n\ntype UseSupabaseUploadOptions = {\n /**\n * Name of bucket to upload files to in your Supabase project\n */\n bucketName: string\n /**\n * Folder to upload files to in the specified bucket within your Supabase project.\n *\n * Defaults to uploading files to the root of the bucket\n *\n * e.g If specified path is `test`, your file will be uploaded as `test/file_name`\n */\n path?: string\n /**\n * Allowed MIME types for each file upload (e.g `image/png`, `text/html`, etc). Wildcards are also supported (e.g `image/*`).\n *\n * Defaults to allowing uploading of all MIME types.\n */\n allowedMimeTypes?: string[]\n /**\n * Maximum upload size of each file allowed in bytes. (e.g 1000 bytes = 1 KB)\n */\n maxFileSize?: number\n /**\n * Maximum number of files allowed per upload.\n */\n maxFiles?: number\n /**\n * The number of seconds the asset is cached in the browser and in the Supabase CDN.\n *\n * This is set in the Cache-Control: max-age=<seconds> header. Defaults to 3600 seconds.\n */\n cacheControl?: number\n /**\n * When set to true, the file is overwritten if it exists.\n *\n * When set to false, an error is thrown if the object already exists. Defaults to `false`\n */\n upsert?: boolean\n}\n\ntype UseSupabaseUploadReturn = ReturnType<typeof useSupabaseUpload>\n\nconst useSupabaseUpload = (options: UseSupabaseUploadOptions) => {\n const {\n bucketName,\n path,\n allowedMimeTypes = [],\n maxFileSize = Number.POSITIVE_INFINITY,\n maxFiles = 1,\n cacheControl = 3600,\n upsert = false,\n } = options\n\n const [files, setFiles] = useState<FileWithPreview[]>([])\n const [loading, setLoading] = useState<boolean>(false)\n const [errors, setErrors] = useState<{ name: string; message: string }[]>([])\n const [successes, setSuccesses] = useState<string[]>([])\n\n const isSuccess = useMemo(() => {\n if (errors.length === 0 && successes.length === 0) {\n return false\n }\n if (errors.length === 0 && successes.length === files.length) {\n return true\n }\n return false\n }, [errors.length, successes.length, files.length])\n\n const onDrop = useCallback(\n (acceptedFiles: File[], fileRejections: FileRejection[]) => {\n const validFiles = acceptedFiles\n .filter((file) => !files.find((x) => x.name === file.name))\n .map((file) => {\n ;(file as FileWithPreview).preview = URL.createObjectURL(file)\n ;(file as FileWithPreview).errors = []\n return file as FileWithPreview\n })\n\n const invalidFiles = fileRejections.map(({ file, errors }) => {\n ;(file as FileWithPreview).preview = URL.createObjectURL(file)\n ;(file as FileWithPreview).errors = errors\n return file as FileWithPreview\n })\n\n const newFiles = [...files, ...validFiles, ...invalidFiles]\n\n setFiles(newFiles)\n },\n [files, setFiles]\n )\n\n const dropzoneProps = useDropzone({\n onDrop,\n noClick: true,\n accept: allowedMimeTypes.reduce((acc, type) => ({ ...acc, [type]: [] }), {}),\n maxSize: maxFileSize,\n maxFiles: maxFiles,\n multiple: maxFiles !== 1,\n })\n\n const onUpload = useCallback(async () => {\n setLoading(true)\n\n // [Joshen] This is to support handling partial successes\n // If any files didn't upload for any reason, hitting \"Upload\" again will only upload the files that had errors\n const filesWithErrors = errors.map((x) => x.name)\n const filesToUpload =\n filesWithErrors.length > 0\n ? [\n ...files.filter((f) => filesWithErrors.includes(f.name)),\n ...files.filter((f) => !successes.includes(f.name)),\n ]\n : files\n\n const responses = await Promise.all(\n filesToUpload.map(async (file) => {\n const { error } = await supabase.storage\n .from(bucketName)\n .upload(!!path ? `${path}/${file.name}` : file.name, file, {\n cacheControl: cacheControl.toString(),\n upsert,\n })\n if (error) {\n return { name: file.name, message: error.message }\n } else {\n return { name: file.name, message: undefined }\n }\n })\n )\n\n const responseErrors = responses.filter((x) => x.message !== undefined)\n // if there were errors previously, this function tried to upload the files again so we should clear/overwrite the existing errors.\n setErrors(responseErrors)\n\n const responseSuccesses = responses.filter((x) => x.message === undefined)\n const newSLine truncated
|
||||
"content": "import { useCallback, useEffect, useMemo, useState } from 'react'\nimport { useDropzone, type FileError, type FileRejection } from 'react-dropzone'\n\nimport { createClient } from '@/registry/default/clients/react-router/lib/supabase/client'\n\nconst supabase = createClient()\n\ninterface FileWithPreview extends File {\n preview?: string\n errors: readonly FileError[]\n}\n\ntype UseSupabaseUploadOptions = {\n /**\n * Name of bucket to upload files to in your Supabase project\n */\n bucketName: string\n /**\n * Folder to upload files to in the specified bucket within your Supabase project.\n *\n * Defaults to uploading files to the root of the bucket\n *\n * e.g If specified path is `test`, your file will be uploaded as `test/file_name`\n */\n path?: string\n /**\n * Allowed MIME types for each file upload (e.g `image/png`, `text/html`, etc). Wildcards are also supported (e.g `image/*`).\n *\n * Defaults to allowing uploading of all MIME types.\n */\n allowedMimeTypes?: string[]\n /**\n * Maximum upload size of each file allowed in bytes. (e.g 1000 bytes = 1 KB)\n */\n maxFileSize?: number\n /**\n * Maximum number of files allowed per upload.\n */\n maxFiles?: number\n /**\n * The number of seconds the asset is cached in the browser and in the Supabase CDN.\n *\n * This is set in the Cache-Control: max-age=<seconds> header. Defaults to 3600 seconds.\n */\n cacheControl?: number\n /**\n * When set to true, the file is overwritten if it exists.\n *\n * When set to false, an error is thrown if the object already exists. Defaults to `false`\n */\n upsert?: boolean\n}\n\ntype UseSupabaseUploadReturn = ReturnType<typeof useSupabaseUpload>\n\nconst useSupabaseUpload = (options: UseSupabaseUploadOptions) => {\n const {\n bucketName,\n path,\n allowedMimeTypes = [],\n maxFileSize = Number.POSITIVE_INFINITY,\n maxFiles = 1,\n cacheControl = 3600,\n upsert = false,\n } = options\n\n const [files, setFiles] = useState<FileWithPreview[]>([])\n const [loading, setLoading] = useState<boolean>(false)\n const [errors, setErrors] = useState<{ name: string; message: string }[]>([])\n const [successes, setSuccesses] = useState<string[]>([])\n\n const isSuccess = useMemo(() => {\n if (errors.length === 0 && successes.length === 0) {\n return false\n }\n if (errors.length === 0 && successes.length === files.length) {\n return true\n }\n return false\n }, [errors.length, successes.length, files.length])\n\n const onDrop = useCallback(\n (acceptedFiles: File[], fileRejections: FileRejection[]) => {\n const validFiles = acceptedFiles\n .filter((file) => !files.find((x) => x.name === file.name))\n .map((file) => {\n ;(file as FileWithPreview).preview = URL.createObjectURL(file)\n ;(file as FileWithPreview).errors = []\n return file as FileWithPreview\n })\n\n const invalidFiles = fileRejections.map(({ file, errors }) => {\n ;(file as FileWithPreview).preview = URL.createObjectURL(file)\n ;(file as FileWithPreview).errors = errors\n return file as FileWithPreview\n })\n\n const newFiles = [...files, ...validFiles, ...invalidFiles]\n\n setFiles(newFiles)\n },\n [files, setFiles]\n )\n\n const dropzoneProps = useDropzone({\n onDrop,\n noClick: true,\n accept: allowedMimeTypes.reduce((acc, type) => ({ ...acc, [type]: [] }), {}),\n maxSize: maxFileSize,\n maxFiles: maxFiles,\n multiple: maxFiles !== 1,\n })\n\n const onUpload = useCallback(async () => {\n setLoading(true)\n\n // [Joshen] This is to support handling partial successes\n // If any files didn't upload for any reason, hitting \"Upload\" again will only upload the files that had errors\n const filesWithErrors = errors.map((x) => x.name)\n const filesToUpload =\n filesWithErrors.length > 0\n ? [\n ...files.filter((f) => filesWithErrors.includes(f.name)),\n ...files.filter((f) => !successes.includes(f.name)),\n ]\n : files\n\n const responses = await Promise.all(\n filesToUpload.map(async (file) => {\n const { error } = await supabase.storage\n .from(bucketName)\n .upload(!!path ? `${path}/${file.name}` : file.name, file, {\n cacheControl: cacheControl.toString(),\n upsert,\n })\n if (error) {\n return { name: file.name, message: error.message }\n } else {\n return { name: file.name, message: undefined }\n }\n })\n )\n\n const responseErrors = responses.filter((x) => x.message !== undefined)\n // if there were errors previously, this function tried to upload the files again so we should clear/overwrite the existing errors.\n setErrors(responseErrors)\n\n const responseSuccesses = responses.filter((x) => x.message === undefined)\n consLine truncated
|
||||
"type": "registry:hook"
|
||||
},
|
||||
{
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
},
|
||||
{
|
||||
"path": "registry/default/blocks/dropzone/hooks/use-supabase-upload.ts",
|
||||
"content": "import { useCallback, useEffect, useMemo, useState } from 'react'\nimport { useDropzone, type FileError, type FileRejection } from 'react-dropzone'\n\nimport { createClient } from '@/registry/default/clients/nextjs/lib/supabase/client'\n\nconst supabase = createClient()\n\ninterface FileWithPreview extends File {\n preview?: string\n errors: readonly FileError[]\n}\n\ntype UseSupabaseUploadOptions = {\n /**\n * Name of bucket to upload files to in your Supabase project\n */\n bucketName: string\n /**\n * Folder to upload files to in the specified bucket within your Supabase project.\n *\n * Defaults to uploading files to the root of the bucket\n *\n * e.g If specified path is `test`, your file will be uploaded as `test/file_name`\n */\n path?: string\n /**\n * Allowed MIME types for each file upload (e.g `image/png`, `text/html`, etc). Wildcards are also supported (e.g `image/*`).\n *\n * Defaults to allowing uploading of all MIME types.\n */\n allowedMimeTypes?: string[]\n /**\n * Maximum upload size of each file allowed in bytes. (e.g 1000 bytes = 1 KB)\n */\n maxFileSize?: number\n /**\n * Maximum number of files allowed per upload.\n */\n maxFiles?: number\n /**\n * The number of seconds the asset is cached in the browser and in the Supabase CDN.\n *\n * This is set in the Cache-Control: max-age=<seconds> header. Defaults to 3600 seconds.\n */\n cacheControl?: number\n /**\n * When set to true, the file is overwritten if it exists.\n *\n * When set to false, an error is thrown if the object already exists. Defaults to `false`\n */\n upsert?: boolean\n}\n\ntype UseSupabaseUploadReturn = ReturnType<typeof useSupabaseUpload>\n\nconst useSupabaseUpload = (options: UseSupabaseUploadOptions) => {\n const {\n bucketName,\n path,\n allowedMimeTypes = [],\n maxFileSize = Number.POSITIVE_INFINITY,\n maxFiles = 1,\n cacheControl = 3600,\n upsert = false,\n } = options\n\n const [files, setFiles] = useState<FileWithPreview[]>([])\n const [loading, setLoading] = useState<boolean>(false)\n const [errors, setErrors] = useState<{ name: string; message: string }[]>([])\n const [successes, setSuccesses] = useState<string[]>([])\n\n const isSuccess = useMemo(() => {\n if (errors.length === 0 && successes.length === 0) {\n return false\n }\n if (errors.length === 0 && successes.length === files.length) {\n return true\n }\n return false\n }, [errors.length, successes.length, files.length])\n\n const onDrop = useCallback(\n (acceptedFiles: File[], fileRejections: FileRejection[]) => {\n const validFiles = acceptedFiles\n .filter((file) => !files.find((x) => x.name === file.name))\n .map((file) => {\n ;(file as FileWithPreview).preview = URL.createObjectURL(file)\n ;(file as FileWithPreview).errors = []\n return file as FileWithPreview\n })\n\n const invalidFiles = fileRejections.map(({ file, errors }) => {\n ;(file as FileWithPreview).preview = URL.createObjectURL(file)\n ;(file as FileWithPreview).errors = errors\n return file as FileWithPreview\n })\n\n const newFiles = [...files, ...validFiles, ...invalidFiles]\n\n setFiles(newFiles)\n },\n [files, setFiles]\n )\n\n const dropzoneProps = useDropzone({\n onDrop,\n noClick: true,\n accept: allowedMimeTypes.reduce((acc, type) => ({ ...acc, [type]: [] }), {}),\n maxSize: maxFileSize,\n maxFiles: maxFiles,\n multiple: maxFiles !== 1,\n })\n\n const onUpload = useCallback(async () => {\n setLoading(true)\n\n // [Joshen] This is to support handling partial successes\n // If any files didn't upload for any reason, hitting \"Upload\" again will only upload the files that had errors\n const filesWithErrors = errors.map((x) => x.name)\n const filesToUpload =\n filesWithErrors.length > 0\n ? [\n ...files.filter((f) => filesWithErrors.includes(f.name)),\n ...files.filter((f) => !successes.includes(f.name)),\n ]\n : files\n\n const responses = await Promise.all(\n filesToUpload.map(async (file) => {\n const { error } = await supabase.storage\n .from(bucketName)\n .upload(!!path ? `${path}/${file.name}` : file.name, file, {\n cacheControl: cacheControl.toString(),\n upsert,\n })\n if (error) {\n return { name: file.name, message: error.message }\n } else {\n return { name: file.name, message: undefined }\n }\n })\n )\n\n const responseErrors = responses.filter((x) => x.message !== undefined)\n // if there were errors previously, this function tried to upload the files again so we should clear/overwrite the existing errors.\n setErrors(responseErrors)\n\n const responseSuccesses = responses.filter((x) => x.message === undefined)\n const newSLine truncated
|
||||
"content": "import { useCallback, useEffect, useMemo, useState } from 'react'\nimport { useDropzone, type FileError, type FileRejection } from 'react-dropzone'\n\nimport { createClient } from '@/registry/default/clients/react/lib/supabase/client'\n\nconst supabase = createClient()\n\ninterface FileWithPreview extends File {\n preview?: string\n errors: readonly FileError[]\n}\n\ntype UseSupabaseUploadOptions = {\n /**\n * Name of bucket to upload files to in your Supabase project\n */\n bucketName: string\n /**\n * Folder to upload files to in the specified bucket within your Supabase project.\n *\n * Defaults to uploading files to the root of the bucket\n *\n * e.g If specified path is `test`, your file will be uploaded as `test/file_name`\n */\n path?: string\n /**\n * Allowed MIME types for each file upload (e.g `image/png`, `text/html`, etc). Wildcards are also supported (e.g `image/*`).\n *\n * Defaults to allowing uploading of all MIME types.\n */\n allowedMimeTypes?: string[]\n /**\n * Maximum upload size of each file allowed in bytes. (e.g 1000 bytes = 1 KB)\n */\n maxFileSize?: number\n /**\n * Maximum number of files allowed per upload.\n */\n maxFiles?: number\n /**\n * The number of seconds the asset is cached in the browser and in the Supabase CDN.\n *\n * This is set in the Cache-Control: max-age=<seconds> header. Defaults to 3600 seconds.\n */\n cacheControl?: number\n /**\n * When set to true, the file is overwritten if it exists.\n *\n * When set to false, an error is thrown if the object already exists. Defaults to `false`\n */\n upsert?: boolean\n}\n\ntype UseSupabaseUploadReturn = ReturnType<typeof useSupabaseUpload>\n\nconst useSupabaseUpload = (options: UseSupabaseUploadOptions) => {\n const {\n bucketName,\n path,\n allowedMimeTypes = [],\n maxFileSize = Number.POSITIVE_INFINITY,\n maxFiles = 1,\n cacheControl = 3600,\n upsert = false,\n } = options\n\n const [files, setFiles] = useState<FileWithPreview[]>([])\n const [loading, setLoading] = useState<boolean>(false)\n const [errors, setErrors] = useState<{ name: string; message: string }[]>([])\n const [successes, setSuccesses] = useState<string[]>([])\n\n const isSuccess = useMemo(() => {\n if (errors.length === 0 && successes.length === 0) {\n return false\n }\n if (errors.length === 0 && successes.length === files.length) {\n return true\n }\n return false\n }, [errors.length, successes.length, files.length])\n\n const onDrop = useCallback(\n (acceptedFiles: File[], fileRejections: FileRejection[]) => {\n const validFiles = acceptedFiles\n .filter((file) => !files.find((x) => x.name === file.name))\n .map((file) => {\n ;(file as FileWithPreview).preview = URL.createObjectURL(file)\n ;(file as FileWithPreview).errors = []\n return file as FileWithPreview\n })\n\n const invalidFiles = fileRejections.map(({ file, errors }) => {\n ;(file as FileWithPreview).preview = URL.createObjectURL(file)\n ;(file as FileWithPreview).errors = errors\n return file as FileWithPreview\n })\n\n const newFiles = [...files, ...validFiles, ...invalidFiles]\n\n setFiles(newFiles)\n },\n [files, setFiles]\n )\n\n const dropzoneProps = useDropzone({\n onDrop,\n noClick: true,\n accept: allowedMimeTypes.reduce((acc, type) => ({ ...acc, [type]: [] }), {}),\n maxSize: maxFileSize,\n maxFiles: maxFiles,\n multiple: maxFiles !== 1,\n })\n\n const onUpload = useCallback(async () => {\n setLoading(true)\n\n // [Joshen] This is to support handling partial successes\n // If any files didn't upload for any reason, hitting \"Upload\" again will only upload the files that had errors\n const filesWithErrors = errors.map((x) => x.name)\n const filesToUpload =\n filesWithErrors.length > 0\n ? [\n ...files.filter((f) => filesWithErrors.includes(f.name)),\n ...files.filter((f) => !successes.includes(f.name)),\n ]\n : files\n\n const responses = await Promise.all(\n filesToUpload.map(async (file) => {\n const { error } = await supabase.storage\n .from(bucketName)\n .upload(!!path ? `${path}/${file.name}` : file.name, file, {\n cacheControl: cacheControl.toString(),\n upsert,\n })\n if (error) {\n return { name: file.name, message: error.message }\n } else {\n return { name: file.name, message: undefined }\n }\n })\n )\n\n const responseErrors = responses.filter((x) => x.message !== undefined)\n // if there were errors previously, this function tried to upload the files again so we should clear/overwrite the existing errors.\n setErrors(responseErrors)\n\n const responseSuccesses = responses.filter((x) => x.message === undefined)\n const newSuLine truncated
|
||||
"type": "registry:hook"
|
||||
},
|
||||
{
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
},
|
||||
{
|
||||
"path": "registry/default/blocks/dropzone/hooks/use-supabase-upload.ts",
|
||||
"content": "import { useCallback, useEffect, useMemo, useState } from 'react'\nimport { useDropzone, type FileError, type FileRejection } from 'react-dropzone'\n\nimport { createClient } from '@/registry/default/clients/nextjs/lib/supabase/client'\n\nconst supabase = createClient()\n\ninterface FileWithPreview extends File {\n preview?: string\n errors: readonly FileError[]\n}\n\ntype UseSupabaseUploadOptions = {\n /**\n * Name of bucket to upload files to in your Supabase project\n */\n bucketName: string\n /**\n * Folder to upload files to in the specified bucket within your Supabase project.\n *\n * Defaults to uploading files to the root of the bucket\n *\n * e.g If specified path is `test`, your file will be uploaded as `test/file_name`\n */\n path?: string\n /**\n * Allowed MIME types for each file upload (e.g `image/png`, `text/html`, etc). Wildcards are also supported (e.g `image/*`).\n *\n * Defaults to allowing uploading of all MIME types.\n */\n allowedMimeTypes?: string[]\n /**\n * Maximum upload size of each file allowed in bytes. (e.g 1000 bytes = 1 KB)\n */\n maxFileSize?: number\n /**\n * Maximum number of files allowed per upload.\n */\n maxFiles?: number\n /**\n * The number of seconds the asset is cached in the browser and in the Supabase CDN.\n *\n * This is set in the Cache-Control: max-age=<seconds> header. Defaults to 3600 seconds.\n */\n cacheControl?: number\n /**\n * When set to true, the file is overwritten if it exists.\n *\n * When set to false, an error is thrown if the object already exists. Defaults to `false`\n */\n upsert?: boolean\n}\n\ntype UseSupabaseUploadReturn = ReturnType<typeof useSupabaseUpload>\n\nconst useSupabaseUpload = (options: UseSupabaseUploadOptions) => {\n const {\n bucketName,\n path,\n allowedMimeTypes = [],\n maxFileSize = Number.POSITIVE_INFINITY,\n maxFiles = 1,\n cacheControl = 3600,\n upsert = false,\n } = options\n\n const [files, setFiles] = useState<FileWithPreview[]>([])\n const [loading, setLoading] = useState<boolean>(false)\n const [errors, setErrors] = useState<{ name: string; message: string }[]>([])\n const [successes, setSuccesses] = useState<string[]>([])\n\n const isSuccess = useMemo(() => {\n if (errors.length === 0 && successes.length === 0) {\n return false\n }\n if (errors.length === 0 && successes.length === files.length) {\n return true\n }\n return false\n }, [errors.length, successes.length, files.length])\n\n const onDrop = useCallback(\n (acceptedFiles: File[], fileRejections: FileRejection[]) => {\n const validFiles = acceptedFiles\n .filter((file) => !files.find((x) => x.name === file.name))\n .map((file) => {\n ;(file as FileWithPreview).preview = URL.createObjectURL(file)\n ;(file as FileWithPreview).errors = []\n return file as FileWithPreview\n })\n\n const invalidFiles = fileRejections.map(({ file, errors }) => {\n ;(file as FileWithPreview).preview = URL.createObjectURL(file)\n ;(file as FileWithPreview).errors = errors\n return file as FileWithPreview\n })\n\n const newFiles = [...files, ...validFiles, ...invalidFiles]\n\n setFiles(newFiles)\n },\n [files, setFiles]\n )\n\n const dropzoneProps = useDropzone({\n onDrop,\n noClick: true,\n accept: allowedMimeTypes.reduce((acc, type) => ({ ...acc, [type]: [] }), {}),\n maxSize: maxFileSize,\n maxFiles: maxFiles,\n multiple: maxFiles !== 1,\n })\n\n const onUpload = useCallback(async () => {\n setLoading(true)\n\n // [Joshen] This is to support handling partial successes\n // If any files didn't upload for any reason, hitting \"Upload\" again will only upload the files that had errors\n const filesWithErrors = errors.map((x) => x.name)\n const filesToUpload =\n filesWithErrors.length > 0\n ? [\n ...files.filter((f) => filesWithErrors.includes(f.name)),\n ...files.filter((f) => !successes.includes(f.name)),\n ]\n : files\n\n const responses = await Promise.all(\n filesToUpload.map(async (file) => {\n const { error } = await supabase.storage\n .from(bucketName)\n .upload(!!path ? `${path}/${file.name}` : file.name, file, {\n cacheControl: cacheControl.toString(),\n upsert,\n })\n if (error) {\n return { name: file.name, message: error.message }\n } else {\n return { name: file.name, message: undefined }\n }\n })\n )\n\n const responseErrors = responses.filter((x) => x.message !== undefined)\n // if there were errors previously, this function tried to upload the files again so we should clear/overwrite the existing errors.\n setErrors(responseErrors)\n\n const responseSuccesses = responses.filter((x) => x.message === undefined)\n const newSLine truncated
|
||||
"content": "import { useCallback, useEffect, useMemo, useState } from 'react'\nimport { useDropzone, type FileError, type FileRejection } from 'react-dropzone'\n\nimport { createClient } from '@/registry/default/clients/tanstack/lib/supabase/client'\n\nconst supabase = createClient()\n\ninterface FileWithPreview extends File {\n preview?: string\n errors: readonly FileError[]\n}\n\ntype UseSupabaseUploadOptions = {\n /**\n * Name of bucket to upload files to in your Supabase project\n */\n bucketName: string\n /**\n * Folder to upload files to in the specified bucket within your Supabase project.\n *\n * Defaults to uploading files to the root of the bucket\n *\n * e.g If specified path is `test`, your file will be uploaded as `test/file_name`\n */\n path?: string\n /**\n * Allowed MIME types for each file upload (e.g `image/png`, `text/html`, etc). Wildcards are also supported (e.g `image/*`).\n *\n * Defaults to allowing uploading of all MIME types.\n */\n allowedMimeTypes?: string[]\n /**\n * Maximum upload size of each file allowed in bytes. (e.g 1000 bytes = 1 KB)\n */\n maxFileSize?: number\n /**\n * Maximum number of files allowed per upload.\n */\n maxFiles?: number\n /**\n * The number of seconds the asset is cached in the browser and in the Supabase CDN.\n *\n * This is set in the Cache-Control: max-age=<seconds> header. Defaults to 3600 seconds.\n */\n cacheControl?: number\n /**\n * When set to true, the file is overwritten if it exists.\n *\n * When set to false, an error is thrown if the object already exists. Defaults to `false`\n */\n upsert?: boolean\n}\n\ntype UseSupabaseUploadReturn = ReturnType<typeof useSupabaseUpload>\n\nconst useSupabaseUpload = (options: UseSupabaseUploadOptions) => {\n const {\n bucketName,\n path,\n allowedMimeTypes = [],\n maxFileSize = Number.POSITIVE_INFINITY,\n maxFiles = 1,\n cacheControl = 3600,\n upsert = false,\n } = options\n\n const [files, setFiles] = useState<FileWithPreview[]>([])\n const [loading, setLoading] = useState<boolean>(false)\n const [errors, setErrors] = useState<{ name: string; message: string }[]>([])\n const [successes, setSuccesses] = useState<string[]>([])\n\n const isSuccess = useMemo(() => {\n if (errors.length === 0 && successes.length === 0) {\n return false\n }\n if (errors.length === 0 && successes.length === files.length) {\n return true\n }\n return false\n }, [errors.length, successes.length, files.length])\n\n const onDrop = useCallback(\n (acceptedFiles: File[], fileRejections: FileRejection[]) => {\n const validFiles = acceptedFiles\n .filter((file) => !files.find((x) => x.name === file.name))\n .map((file) => {\n ;(file as FileWithPreview).preview = URL.createObjectURL(file)\n ;(file as FileWithPreview).errors = []\n return file as FileWithPreview\n })\n\n const invalidFiles = fileRejections.map(({ file, errors }) => {\n ;(file as FileWithPreview).preview = URL.createObjectURL(file)\n ;(file as FileWithPreview).errors = errors\n return file as FileWithPreview\n })\n\n const newFiles = [...files, ...validFiles, ...invalidFiles]\n\n setFiles(newFiles)\n },\n [files, setFiles]\n )\n\n const dropzoneProps = useDropzone({\n onDrop,\n noClick: true,\n accept: allowedMimeTypes.reduce((acc, type) => ({ ...acc, [type]: [] }), {}),\n maxSize: maxFileSize,\n maxFiles: maxFiles,\n multiple: maxFiles !== 1,\n })\n\n const onUpload = useCallback(async () => {\n setLoading(true)\n\n // [Joshen] This is to support handling partial successes\n // If any files didn't upload for any reason, hitting \"Upload\" again will only upload the files that had errors\n const filesWithErrors = errors.map((x) => x.name)\n const filesToUpload =\n filesWithErrors.length > 0\n ? [\n ...files.filter((f) => filesWithErrors.includes(f.name)),\n ...files.filter((f) => !successes.includes(f.name)),\n ]\n : files\n\n const responses = await Promise.all(\n filesToUpload.map(async (file) => {\n const { error } = await supabase.storage\n .from(bucketName)\n .upload(!!path ? `${path}/${file.name}` : file.name, file, {\n cacheControl: cacheControl.toString(),\n upsert,\n })\n if (error) {\n return { name: file.name, message: error.message }\n } else {\n return { name: file.name, message: undefined }\n }\n })\n )\n\n const responseErrors = responses.filter((x) => x.message !== undefined)\n // if there were errors previously, this function tried to upload the files again so we should clear/overwrite the existing errors.\n setErrors(responseErrors)\n\n const responseSuccesses = responses.filter((x) => x.message === undefined)\n const neLine truncated
|
||||
"type": "registry:hook"
|
||||
},
|
||||
{
|
||||
|
||||
@@ -25,17 +25,17 @@
|
||||
},
|
||||
{
|
||||
"path": "registry/default/blocks/realtime-avatar-stack/hooks/use-realtime-presence-room.ts",
|
||||
"content": "'use client'\n\nimport { REALTIME_SUBSCRIBE_STATES } from '@supabase/supabase-js'\nimport { useEffect, useState } from 'react'\n\nimport { useCurrentUserImage } from '@/registry/default/blocks/current-user-avatar/hooks/use-current-user-image'\nimport { useCurrentUserName } from '@/registry/default/blocks/current-user-avatar/hooks/use-current-user-name'\nimport { createClient } from '@/registry/default/clients/nextjs/lib/supabase/client'\n\nconst supabase = createClient()\n\nexport type RealtimeUser = {\n id: string\n name: string\n image: string\n}\n\nexport const useRealtimePresenceRoom = (roomName: string) => {\n const currentUserImage = useCurrentUserImage()\n const currentUserName = useCurrentUserName()\n\n const [users, setUsers] = useState<Record<string, RealtimeUser>>({})\n\n useEffect(() => {\n const room = supabase.channel(roomName)\n\n room\n .on('presence', { event: 'sync' }, () => {\n const newState = room.presenceState<{ image: string; name: string }>()\n\n const newUsers = Object.fromEntries(\n Object.entries(newState).map(([key, values]) => [\n key,\n { name: values[0].name, image: values[0].image },\n ])\n ) as Record<string, RealtimeUser>\n setUsers(newUsers)\n })\n .subscribe(async (status) => {\n if (status === REALTIME_SUBSCRIBE_STATES.SUBSCRIBED) {\n await room.track({\n name: currentUserName,\n image: currentUserImage,\n })\n } else {\n setUsers({})\n }\n })\n\n return () => {\n room.unsubscribe()\n }\n }, [roomName, currentUserName, currentUserImage])\n\n return { users }\n}\n",
|
||||
"content": "'use client'\n\nimport { REALTIME_SUBSCRIBE_STATES } from '@supabase/supabase-js'\nimport { useEffect, useState } from 'react'\n\nimport { useCurrentUserImage } from '@/registry/default/blocks/current-user-avatar/hooks/use-current-user-image'\nimport { useCurrentUserName } from '@/registry/default/blocks/current-user-avatar/hooks/use-current-user-name'\nimport { createClient } from '@/registry/default/clients/react-router/lib/supabase/client'\n\nconst supabase = createClient()\n\nexport type RealtimeUser = {\n id: string\n name: string\n image: string\n}\n\nexport const useRealtimePresenceRoom = (roomName: string) => {\n const currentUserImage = useCurrentUserImage()\n const currentUserName = useCurrentUserName()\n\n const [users, setUsers] = useState<Record<string, RealtimeUser>>({})\n\n useEffect(() => {\n const room = supabase.channel(roomName)\n\n room\n .on('presence', { event: 'sync' }, () => {\n const newState = room.presenceState<{ image: string; name: string }>()\n\n const newUsers = Object.fromEntries(\n Object.entries(newState).map(([key, values]) => [\n key,\n { name: values[0].name, image: values[0].image },\n ])\n ) as Record<string, RealtimeUser>\n setUsers(newUsers)\n })\n .subscribe(async (status) => {\n if (status === REALTIME_SUBSCRIBE_STATES.SUBSCRIBED) {\n await room.track({\n name: currentUserName,\n image: currentUserImage,\n })\n } else {\n setUsers({})\n }\n })\n\n return () => {\n room.unsubscribe()\n }\n }, [roomName, currentUserName, currentUserImage])\n\n return { users }\n}\n",
|
||||
"type": "registry:hook"
|
||||
},
|
||||
{
|
||||
"path": "registry/default/blocks/current-user-avatar/hooks/use-current-user-name.ts",
|
||||
"content": "import { useEffect, useState } from 'react'\n\nimport { createClient } from '@/registry/default/clients/nextjs/lib/supabase/client'\n\nexport const useCurrentUserName = () => {\n const [name, setName] = useState<string | null>(null)\n\n useEffect(() => {\n const fetchProfileName = async () => {\n const { data, error } = await createClient().auth.getSession()\n if (error) {\n console.error(error)\n }\n\n setName(data.session?.user.user_metadata.full_name ?? '?')\n }\n\n fetchProfileName()\n }, [])\n\n return name || '?'\n}\n",
|
||||
"content": "import { useEffect, useState } from 'react'\n\nimport { createClient } from '@/registry/default/clients/react-router/lib/supabase/client'\n\nexport const useCurrentUserName = () => {\n const [name, setName] = useState<string | null>(null)\n\n useEffect(() => {\n const fetchProfileName = async () => {\n const { data, error } = await createClient().auth.getSession()\n if (error) {\n console.error(error)\n }\n\n setName(data.session?.user.user_metadata.full_name ?? '?')\n }\n\n fetchProfileName()\n }, [])\n\n return name || '?'\n}\n",
|
||||
"type": "registry:hook"
|
||||
},
|
||||
{
|
||||
"path": "registry/default/blocks/current-user-avatar/hooks/use-current-user-image.ts",
|
||||
"content": "import { useEffect, useState } from 'react'\n\nimport { createClient } from '@/registry/default/clients/nextjs/lib/supabase/client'\n\nexport const useCurrentUserImage = () => {\n const [image, setImage] = useState<string | null>(null)\n\n useEffect(() => {\n const fetchUserImage = async () => {\n const { data, error } = await createClient().auth.getSession()\n if (error) {\n console.error(error)\n }\n\n setImage(data.session?.user.user_metadata.avatar_url ?? null)\n }\n fetchUserImage()\n }, [])\n\n return image\n}\n",
|
||||
"content": "import { useEffect, useState } from 'react'\n\nimport { createClient } from '@/registry/default/clients/react-router/lib/supabase/client'\n\nexport const useCurrentUserImage = () => {\n const [image, setImage] = useState<string | null>(null)\n\n useEffect(() => {\n const fetchUserImage = async () => {\n const { data, error } = await createClient().auth.getSession()\n if (error) {\n console.error(error)\n }\n\n setImage(data.session?.user.user_metadata.avatar_url ?? null)\n }\n fetchUserImage()\n }, [])\n\n return image\n}\n",
|
||||
"type": "registry:hook"
|
||||
},
|
||||
{
|
||||
|
||||
@@ -24,17 +24,17 @@
|
||||
},
|
||||
{
|
||||
"path": "registry/default/blocks/realtime-avatar-stack/hooks/use-realtime-presence-room.ts",
|
||||
"content": "'use client'\n\nimport { REALTIME_SUBSCRIBE_STATES } from '@supabase/supabase-js'\nimport { useEffect, useState } from 'react'\n\nimport { useCurrentUserImage } from '@/registry/default/blocks/current-user-avatar/hooks/use-current-user-image'\nimport { useCurrentUserName } from '@/registry/default/blocks/current-user-avatar/hooks/use-current-user-name'\nimport { createClient } from '@/registry/default/clients/nextjs/lib/supabase/client'\n\nconst supabase = createClient()\n\nexport type RealtimeUser = {\n id: string\n name: string\n image: string\n}\n\nexport const useRealtimePresenceRoom = (roomName: string) => {\n const currentUserImage = useCurrentUserImage()\n const currentUserName = useCurrentUserName()\n\n const [users, setUsers] = useState<Record<string, RealtimeUser>>({})\n\n useEffect(() => {\n const room = supabase.channel(roomName)\n\n room\n .on('presence', { event: 'sync' }, () => {\n const newState = room.presenceState<{ image: string; name: string }>()\n\n const newUsers = Object.fromEntries(\n Object.entries(newState).map(([key, values]) => [\n key,\n { name: values[0].name, image: values[0].image },\n ])\n ) as Record<string, RealtimeUser>\n setUsers(newUsers)\n })\n .subscribe(async (status) => {\n if (status === REALTIME_SUBSCRIBE_STATES.SUBSCRIBED) {\n await room.track({\n name: currentUserName,\n image: currentUserImage,\n })\n } else {\n setUsers({})\n }\n })\n\n return () => {\n room.unsubscribe()\n }\n }, [roomName, currentUserName, currentUserImage])\n\n return { users }\n}\n",
|
||||
"content": "'use client'\n\nimport { REALTIME_SUBSCRIBE_STATES } from '@supabase/supabase-js'\nimport { useEffect, useState } from 'react'\n\nimport { useCurrentUserImage } from '@/registry/default/blocks/current-user-avatar/hooks/use-current-user-image'\nimport { useCurrentUserName } from '@/registry/default/blocks/current-user-avatar/hooks/use-current-user-name'\nimport { createClient } from '@/registry/default/clients/react/lib/supabase/client'\n\nconst supabase = createClient()\n\nexport type RealtimeUser = {\n id: string\n name: string\n image: string\n}\n\nexport const useRealtimePresenceRoom = (roomName: string) => {\n const currentUserImage = useCurrentUserImage()\n const currentUserName = useCurrentUserName()\n\n const [users, setUsers] = useState<Record<string, RealtimeUser>>({})\n\n useEffect(() => {\n const room = supabase.channel(roomName)\n\n room\n .on('presence', { event: 'sync' }, () => {\n const newState = room.presenceState<{ image: string; name: string }>()\n\n const newUsers = Object.fromEntries(\n Object.entries(newState).map(([key, values]) => [\n key,\n { name: values[0].name, image: values[0].image },\n ])\n ) as Record<string, RealtimeUser>\n setUsers(newUsers)\n })\n .subscribe(async (status) => {\n if (status === REALTIME_SUBSCRIBE_STATES.SUBSCRIBED) {\n await room.track({\n name: currentUserName,\n image: currentUserImage,\n })\n } else {\n setUsers({})\n }\n })\n\n return () => {\n room.unsubscribe()\n }\n }, [roomName, currentUserName, currentUserImage])\n\n return { users }\n}\n",
|
||||
"type": "registry:hook"
|
||||
},
|
||||
{
|
||||
"path": "registry/default/blocks/current-user-avatar/hooks/use-current-user-name.ts",
|
||||
"content": "import { useEffect, useState } from 'react'\n\nimport { createClient } from '@/registry/default/clients/nextjs/lib/supabase/client'\n\nexport const useCurrentUserName = () => {\n const [name, setName] = useState<string | null>(null)\n\n useEffect(() => {\n const fetchProfileName = async () => {\n const { data, error } = await createClient().auth.getSession()\n if (error) {\n console.error(error)\n }\n\n setName(data.session?.user.user_metadata.full_name ?? '?')\n }\n\n fetchProfileName()\n }, [])\n\n return name || '?'\n}\n",
|
||||
"content": "import { useEffect, useState } from 'react'\n\nimport { createClient } from '@/registry/default/clients/react/lib/supabase/client'\n\nexport const useCurrentUserName = () => {\n const [name, setName] = useState<string | null>(null)\n\n useEffect(() => {\n const fetchProfileName = async () => {\n const { data, error } = await createClient().auth.getSession()\n if (error) {\n console.error(error)\n }\n\n setName(data.session?.user.user_metadata.full_name ?? '?')\n }\n\n fetchProfileName()\n }, [])\n\n return name || '?'\n}\n",
|
||||
"type": "registry:hook"
|
||||
},
|
||||
{
|
||||
"path": "registry/default/blocks/current-user-avatar/hooks/use-current-user-image.ts",
|
||||
"content": "import { useEffect, useState } from 'react'\n\nimport { createClient } from '@/registry/default/clients/nextjs/lib/supabase/client'\n\nexport const useCurrentUserImage = () => {\n const [image, setImage] = useState<string | null>(null)\n\n useEffect(() => {\n const fetchUserImage = async () => {\n const { data, error } = await createClient().auth.getSession()\n if (error) {\n console.error(error)\n }\n\n setImage(data.session?.user.user_metadata.avatar_url ?? null)\n }\n fetchUserImage()\n }, [])\n\n return image\n}\n",
|
||||
"content": "import { useEffect, useState } from 'react'\n\nimport { createClient } from '@/registry/default/clients/react/lib/supabase/client'\n\nexport const useCurrentUserImage = () => {\n const [image, setImage] = useState<string | null>(null)\n\n useEffect(() => {\n const fetchUserImage = async () => {\n const { data, error } = await createClient().auth.getSession()\n if (error) {\n console.error(error)\n }\n\n setImage(data.session?.user.user_metadata.avatar_url ?? null)\n }\n fetchUserImage()\n }, [])\n\n return image\n}\n",
|
||||
"type": "registry:hook"
|
||||
},
|
||||
{
|
||||
|
||||
@@ -25,17 +25,17 @@
|
||||
},
|
||||
{
|
||||
"path": "registry/default/blocks/realtime-avatar-stack/hooks/use-realtime-presence-room.ts",
|
||||
"content": "'use client'\n\nimport { REALTIME_SUBSCRIBE_STATES } from '@supabase/supabase-js'\nimport { useEffect, useState } from 'react'\n\nimport { useCurrentUserImage } from '@/registry/default/blocks/current-user-avatar/hooks/use-current-user-image'\nimport { useCurrentUserName } from '@/registry/default/blocks/current-user-avatar/hooks/use-current-user-name'\nimport { createClient } from '@/registry/default/clients/nextjs/lib/supabase/client'\n\nconst supabase = createClient()\n\nexport type RealtimeUser = {\n id: string\n name: string\n image: string\n}\n\nexport const useRealtimePresenceRoom = (roomName: string) => {\n const currentUserImage = useCurrentUserImage()\n const currentUserName = useCurrentUserName()\n\n const [users, setUsers] = useState<Record<string, RealtimeUser>>({})\n\n useEffect(() => {\n const room = supabase.channel(roomName)\n\n room\n .on('presence', { event: 'sync' }, () => {\n const newState = room.presenceState<{ image: string; name: string }>()\n\n const newUsers = Object.fromEntries(\n Object.entries(newState).map(([key, values]) => [\n key,\n { name: values[0].name, image: values[0].image },\n ])\n ) as Record<string, RealtimeUser>\n setUsers(newUsers)\n })\n .subscribe(async (status) => {\n if (status === REALTIME_SUBSCRIBE_STATES.SUBSCRIBED) {\n await room.track({\n name: currentUserName,\n image: currentUserImage,\n })\n } else {\n setUsers({})\n }\n })\n\n return () => {\n room.unsubscribe()\n }\n }, [roomName, currentUserName, currentUserImage])\n\n return { users }\n}\n",
|
||||
"content": "'use client'\n\nimport { REALTIME_SUBSCRIBE_STATES } from '@supabase/supabase-js'\nimport { useEffect, useState } from 'react'\n\nimport { useCurrentUserImage } from '@/registry/default/blocks/current-user-avatar/hooks/use-current-user-image'\nimport { useCurrentUserName } from '@/registry/default/blocks/current-user-avatar/hooks/use-current-user-name'\nimport { createClient } from '@/registry/default/clients/tanstack/lib/supabase/client'\n\nconst supabase = createClient()\n\nexport type RealtimeUser = {\n id: string\n name: string\n image: string\n}\n\nexport const useRealtimePresenceRoom = (roomName: string) => {\n const currentUserImage = useCurrentUserImage()\n const currentUserName = useCurrentUserName()\n\n const [users, setUsers] = useState<Record<string, RealtimeUser>>({})\n\n useEffect(() => {\n const room = supabase.channel(roomName)\n\n room\n .on('presence', { event: 'sync' }, () => {\n const newState = room.presenceState<{ image: string; name: string }>()\n\n const newUsers = Object.fromEntries(\n Object.entries(newState).map(([key, values]) => [\n key,\n { name: values[0].name, image: values[0].image },\n ])\n ) as Record<string, RealtimeUser>\n setUsers(newUsers)\n })\n .subscribe(async (status) => {\n if (status === REALTIME_SUBSCRIBE_STATES.SUBSCRIBED) {\n await room.track({\n name: currentUserName,\n image: currentUserImage,\n })\n } else {\n setUsers({})\n }\n })\n\n return () => {\n room.unsubscribe()\n }\n }, [roomName, currentUserName, currentUserImage])\n\n return { users }\n}\n",
|
||||
"type": "registry:hook"
|
||||
},
|
||||
{
|
||||
"path": "registry/default/blocks/current-user-avatar/hooks/use-current-user-name.ts",
|
||||
"content": "import { useEffect, useState } from 'react'\n\nimport { createClient } from '@/registry/default/clients/nextjs/lib/supabase/client'\n\nexport const useCurrentUserName = () => {\n const [name, setName] = useState<string | null>(null)\n\n useEffect(() => {\n const fetchProfileName = async () => {\n const { data, error } = await createClient().auth.getSession()\n if (error) {\n console.error(error)\n }\n\n setName(data.session?.user.user_metadata.full_name ?? '?')\n }\n\n fetchProfileName()\n }, [])\n\n return name || '?'\n}\n",
|
||||
"content": "import { useEffect, useState } from 'react'\n\nimport { createClient } from '@/registry/default/clients/tanstack/lib/supabase/client'\n\nexport const useCurrentUserName = () => {\n const [name, setName] = useState<string | null>(null)\n\n useEffect(() => {\n const fetchProfileName = async () => {\n const { data, error } = await createClient().auth.getSession()\n if (error) {\n console.error(error)\n }\n\n setName(data.session?.user.user_metadata.full_name ?? '?')\n }\n\n fetchProfileName()\n }, [])\n\n return name || '?'\n}\n",
|
||||
"type": "registry:hook"
|
||||
},
|
||||
{
|
||||
"path": "registry/default/blocks/current-user-avatar/hooks/use-current-user-image.ts",
|
||||
"content": "import { useEffect, useState } from 'react'\n\nimport { createClient } from '@/registry/default/clients/nextjs/lib/supabase/client'\n\nexport const useCurrentUserImage = () => {\n const [image, setImage] = useState<string | null>(null)\n\n useEffect(() => {\n const fetchUserImage = async () => {\n const { data, error } = await createClient().auth.getSession()\n if (error) {\n console.error(error)\n }\n\n setImage(data.session?.user.user_metadata.avatar_url ?? null)\n }\n fetchUserImage()\n }, [])\n\n return image\n}\n",
|
||||
"content": "import { useEffect, useState } from 'react'\n\nimport { createClient } from '@/registry/default/clients/tanstack/lib/supabase/client'\n\nexport const useCurrentUserImage = () => {\n const [image, setImage] = useState<string | null>(null)\n\n useEffect(() => {\n const fetchUserImage = async () => {\n const { data, error } = await createClient().auth.getSession()\n if (error) {\n console.error(error)\n }\n\n setImage(data.session?.user.user_metadata.avatar_url ?? null)\n }\n fetchUserImage()\n }, [])\n\n return image\n}\n",
|
||||
"type": "registry:hook"
|
||||
},
|
||||
{
|
||||
|
||||
@@ -26,7 +26,7 @@
|
||||
},
|
||||
{
|
||||
"path": "registry/default/blocks/realtime-chat/hooks/use-realtime-chat.tsx",
|
||||
"content": "'use client'\n\nimport { useCallback, useEffect, useState } from 'react'\n\nimport { createClient } from '@/registry/default/clients/nextjs/lib/supabase/client'\n\ninterface UseRealtimeChatProps {\n roomName: string\n username: string\n}\n\nexport interface ChatMessage {\n id: string\n content: string\n user: {\n name: string\n }\n createdAt: string\n}\n\nconst EVENT_MESSAGE_TYPE = 'message'\n\nexport function useRealtimeChat({ roomName, username }: UseRealtimeChatProps) {\n const supabase = createClient()\n const [messages, setMessages] = useState<ChatMessage[]>([])\n const [channel, setChannel] = useState<ReturnType<typeof supabase.channel> | null>(null)\n const [isConnected, setIsConnected] = useState(false)\n\n useEffect(() => {\n const newChannel = supabase.channel(roomName)\n\n newChannel\n .on('broadcast', { event: EVENT_MESSAGE_TYPE }, (payload) => {\n setMessages((current) => [...current, payload.payload as ChatMessage])\n })\n .subscribe(async (status) => {\n if (status === 'SUBSCRIBED') {\n setIsConnected(true)\n } else {\n setIsConnected(false)\n }\n })\n\n setChannel(newChannel)\n\n return () => {\n supabase.removeChannel(newChannel)\n }\n }, [roomName, username, supabase])\n\n const sendMessage = useCallback(\n async (content: string) => {\n if (!channel || !isConnected) return\n\n const message: ChatMessage = {\n id: crypto.randomUUID(),\n content,\n user: {\n name: username,\n },\n createdAt: new Date().toISOString(),\n }\n\n // Update local state immediately for the sender\n setMessages((current) => [...current, message])\n\n await channel.send({\n type: 'broadcast',\n event: EVENT_MESSAGE_TYPE,\n payload: message,\n })\n },\n [channel, isConnected, username]\n )\n\n return { messages, sendMessage, isConnected }\n}\n",
|
||||
"content": "'use client'\n\nimport { useCallback, useEffect, useState } from 'react'\n\nimport { createClient } from '@/registry/default/clients/react-router/lib/supabase/client'\n\ninterface UseRealtimeChatProps {\n roomName: string\n username: string\n}\n\nexport interface ChatMessage {\n id: string\n content: string\n user: {\n name: string\n }\n createdAt: string\n}\n\nconst EVENT_MESSAGE_TYPE = 'message'\n\nexport function useRealtimeChat({ roomName, username }: UseRealtimeChatProps) {\n const supabase = createClient()\n const [messages, setMessages] = useState<ChatMessage[]>([])\n const [channel, setChannel] = useState<ReturnType<typeof supabase.channel> | null>(null)\n const [isConnected, setIsConnected] = useState(false)\n\n useEffect(() => {\n const newChannel = supabase.channel(roomName)\n\n newChannel\n .on('broadcast', { event: EVENT_MESSAGE_TYPE }, (payload) => {\n setMessages((current) => [...current, payload.payload as ChatMessage])\n })\n .subscribe(async (status) => {\n if (status === 'SUBSCRIBED') {\n setIsConnected(true)\n } else {\n setIsConnected(false)\n }\n })\n\n setChannel(newChannel)\n\n return () => {\n supabase.removeChannel(newChannel)\n }\n }, [roomName, username, supabase])\n\n const sendMessage = useCallback(\n async (content: string) => {\n if (!channel || !isConnected) return\n\n const message: ChatMessage = {\n id: crypto.randomUUID(),\n content,\n user: {\n name: username,\n },\n createdAt: new Date().toISOString(),\n }\n\n // Update local state immediately for the sender\n setMessages((current) => [...current, message])\n\n await channel.send({\n type: 'broadcast',\n event: EVENT_MESSAGE_TYPE,\n payload: message,\n })\n },\n [channel, isConnected, username]\n )\n\n return { messages, sendMessage, isConnected }\n}\n",
|
||||
"type": "registry:hook"
|
||||
},
|
||||
{
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
},
|
||||
{
|
||||
"path": "registry/default/blocks/realtime-chat/hooks/use-realtime-chat.tsx",
|
||||
"content": "'use client'\n\nimport { useCallback, useEffect, useState } from 'react'\n\nimport { createClient } from '@/registry/default/clients/nextjs/lib/supabase/client'\n\ninterface UseRealtimeChatProps {\n roomName: string\n username: string\n}\n\nexport interface ChatMessage {\n id: string\n content: string\n user: {\n name: string\n }\n createdAt: string\n}\n\nconst EVENT_MESSAGE_TYPE = 'message'\n\nexport function useRealtimeChat({ roomName, username }: UseRealtimeChatProps) {\n const supabase = createClient()\n const [messages, setMessages] = useState<ChatMessage[]>([])\n const [channel, setChannel] = useState<ReturnType<typeof supabase.channel> | null>(null)\n const [isConnected, setIsConnected] = useState(false)\n\n useEffect(() => {\n const newChannel = supabase.channel(roomName)\n\n newChannel\n .on('broadcast', { event: EVENT_MESSAGE_TYPE }, (payload) => {\n setMessages((current) => [...current, payload.payload as ChatMessage])\n })\n .subscribe(async (status) => {\n if (status === 'SUBSCRIBED') {\n setIsConnected(true)\n } else {\n setIsConnected(false)\n }\n })\n\n setChannel(newChannel)\n\n return () => {\n supabase.removeChannel(newChannel)\n }\n }, [roomName, username, supabase])\n\n const sendMessage = useCallback(\n async (content: string) => {\n if (!channel || !isConnected) return\n\n const message: ChatMessage = {\n id: crypto.randomUUID(),\n content,\n user: {\n name: username,\n },\n createdAt: new Date().toISOString(),\n }\n\n // Update local state immediately for the sender\n setMessages((current) => [...current, message])\n\n await channel.send({\n type: 'broadcast',\n event: EVENT_MESSAGE_TYPE,\n payload: message,\n })\n },\n [channel, isConnected, username]\n )\n\n return { messages, sendMessage, isConnected }\n}\n",
|
||||
"content": "'use client'\n\nimport { useCallback, useEffect, useState } from 'react'\n\nimport { createClient } from '@/registry/default/clients/react/lib/supabase/client'\n\ninterface UseRealtimeChatProps {\n roomName: string\n username: string\n}\n\nexport interface ChatMessage {\n id: string\n content: string\n user: {\n name: string\n }\n createdAt: string\n}\n\nconst EVENT_MESSAGE_TYPE = 'message'\n\nexport function useRealtimeChat({ roomName, username }: UseRealtimeChatProps) {\n const supabase = createClient()\n const [messages, setMessages] = useState<ChatMessage[]>([])\n const [channel, setChannel] = useState<ReturnType<typeof supabase.channel> | null>(null)\n const [isConnected, setIsConnected] = useState(false)\n\n useEffect(() => {\n const newChannel = supabase.channel(roomName)\n\n newChannel\n .on('broadcast', { event: EVENT_MESSAGE_TYPE }, (payload) => {\n setMessages((current) => [...current, payload.payload as ChatMessage])\n })\n .subscribe(async (status) => {\n if (status === 'SUBSCRIBED') {\n setIsConnected(true)\n } else {\n setIsConnected(false)\n }\n })\n\n setChannel(newChannel)\n\n return () => {\n supabase.removeChannel(newChannel)\n }\n }, [roomName, username, supabase])\n\n const sendMessage = useCallback(\n async (content: string) => {\n if (!channel || !isConnected) return\n\n const message: ChatMessage = {\n id: crypto.randomUUID(),\n content,\n user: {\n name: username,\n },\n createdAt: new Date().toISOString(),\n }\n\n // Update local state immediately for the sender\n setMessages((current) => [...current, message])\n\n await channel.send({\n type: 'broadcast',\n event: EVENT_MESSAGE_TYPE,\n payload: message,\n })\n },\n [channel, isConnected, username]\n )\n\n return { messages, sendMessage, isConnected }\n}\n",
|
||||
"type": "registry:hook"
|
||||
},
|
||||
{
|
||||
|
||||
@@ -26,7 +26,7 @@
|
||||
},
|
||||
{
|
||||
"path": "registry/default/blocks/realtime-chat/hooks/use-realtime-chat.tsx",
|
||||
"content": "'use client'\n\nimport { useCallback, useEffect, useState } from 'react'\n\nimport { createClient } from '@/registry/default/clients/nextjs/lib/supabase/client'\n\ninterface UseRealtimeChatProps {\n roomName: string\n username: string\n}\n\nexport interface ChatMessage {\n id: string\n content: string\n user: {\n name: string\n }\n createdAt: string\n}\n\nconst EVENT_MESSAGE_TYPE = 'message'\n\nexport function useRealtimeChat({ roomName, username }: UseRealtimeChatProps) {\n const supabase = createClient()\n const [messages, setMessages] = useState<ChatMessage[]>([])\n const [channel, setChannel] = useState<ReturnType<typeof supabase.channel> | null>(null)\n const [isConnected, setIsConnected] = useState(false)\n\n useEffect(() => {\n const newChannel = supabase.channel(roomName)\n\n newChannel\n .on('broadcast', { event: EVENT_MESSAGE_TYPE }, (payload) => {\n setMessages((current) => [...current, payload.payload as ChatMessage])\n })\n .subscribe(async (status) => {\n if (status === 'SUBSCRIBED') {\n setIsConnected(true)\n } else {\n setIsConnected(false)\n }\n })\n\n setChannel(newChannel)\n\n return () => {\n supabase.removeChannel(newChannel)\n }\n }, [roomName, username, supabase])\n\n const sendMessage = useCallback(\n async (content: string) => {\n if (!channel || !isConnected) return\n\n const message: ChatMessage = {\n id: crypto.randomUUID(),\n content,\n user: {\n name: username,\n },\n createdAt: new Date().toISOString(),\n }\n\n // Update local state immediately for the sender\n setMessages((current) => [...current, message])\n\n await channel.send({\n type: 'broadcast',\n event: EVENT_MESSAGE_TYPE,\n payload: message,\n })\n },\n [channel, isConnected, username]\n )\n\n return { messages, sendMessage, isConnected }\n}\n",
|
||||
"content": "'use client'\n\nimport { useCallback, useEffect, useState } from 'react'\n\nimport { createClient } from '@/registry/default/clients/tanstack/lib/supabase/client'\n\ninterface UseRealtimeChatProps {\n roomName: string\n username: string\n}\n\nexport interface ChatMessage {\n id: string\n content: string\n user: {\n name: string\n }\n createdAt: string\n}\n\nconst EVENT_MESSAGE_TYPE = 'message'\n\nexport function useRealtimeChat({ roomName, username }: UseRealtimeChatProps) {\n const supabase = createClient()\n const [messages, setMessages] = useState<ChatMessage[]>([])\n const [channel, setChannel] = useState<ReturnType<typeof supabase.channel> | null>(null)\n const [isConnected, setIsConnected] = useState(false)\n\n useEffect(() => {\n const newChannel = supabase.channel(roomName)\n\n newChannel\n .on('broadcast', { event: EVENT_MESSAGE_TYPE }, (payload) => {\n setMessages((current) => [...current, payload.payload as ChatMessage])\n })\n .subscribe(async (status) => {\n if (status === 'SUBSCRIBED') {\n setIsConnected(true)\n } else {\n setIsConnected(false)\n }\n })\n\n setChannel(newChannel)\n\n return () => {\n supabase.removeChannel(newChannel)\n }\n }, [roomName, username, supabase])\n\n const sendMessage = useCallback(\n async (content: string) => {\n if (!channel || !isConnected) return\n\n const message: ChatMessage = {\n id: crypto.randomUUID(),\n content,\n user: {\n name: username,\n },\n createdAt: new Date().toISOString(),\n }\n\n // Update local state immediately for the sender\n setMessages((current) => [...current, message])\n\n await channel.send({\n type: 'broadcast',\n event: EVENT_MESSAGE_TYPE,\n payload: message,\n })\n },\n [channel, isConnected, username]\n )\n\n return { messages, sendMessage, isConnected }\n}\n",
|
||||
"type": "registry:hook"
|
||||
},
|
||||
{
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
},
|
||||
{
|
||||
"path": "registry/default/blocks/realtime-cursor/hooks/use-realtime-cursors.ts",
|
||||
"content": "import { REALTIME_SUBSCRIBE_STATES, RealtimeChannel } from '@supabase/supabase-js'\nimport { useCallback, useEffect, useRef, useState } from 'react'\n\nimport { createClient } from '@/registry/default/clients/nextjs/lib/supabase/client'\n\n/**\n * Throttle a callback to a certain delay, It will only call the callback if the delay has passed, with the arguments\n * from the last call\n */\nconst useThrottleCallback = <Params extends unknown[], Return>(\n callback: (...args: Params) => Return,\n delay: number\n) => {\n const lastCall = useRef(0)\n const timeout = useRef<NodeJS.Timeout | null>(null)\n\n return useCallback(\n (...args: Params) => {\n const now = Date.now()\n const remainingTime = delay - (now - lastCall.current)\n\n if (remainingTime <= 0) {\n if (timeout.current) {\n clearTimeout(timeout.current)\n timeout.current = null\n }\n lastCall.current = now\n callback(...args)\n } else if (!timeout.current) {\n timeout.current = setTimeout(() => {\n lastCall.current = Date.now()\n timeout.current = null\n callback(...args)\n }, remainingTime)\n }\n },\n [callback, delay]\n )\n}\n\nconst supabase = createClient()\n\nconst generateRandomColor = () => `hsl(${Math.floor(Math.random() * 360)}, 100%, 70%)`\n\nconst generateRandomNumber = () => Math.floor(Math.random() * 100)\n\nconst EVENT_NAME = 'realtime-cursor-move'\n\ntype CursorEventPayload = {\n position: {\n x: number\n y: number\n }\n user: {\n id: number\n name: string\n }\n color: string\n timestamp: number\n}\n\nexport const useRealtimeCursors = ({\n roomName,\n username,\n throttleMs,\n}: {\n roomName: string\n username: string\n throttleMs: number\n}) => {\n const [color] = useState(generateRandomColor())\n const [userId] = useState(generateRandomNumber())\n const [cursors, setCursors] = useState<Record<string, CursorEventPayload>>({})\n const cursorPayload = useRef<CursorEventPayload | null>(null)\n\n const channelRef = useRef<RealtimeChannel | null>(null)\n\n const callback = useCallback(\n (event: MouseEvent) => {\n const { clientX, clientY } = event\n\n const payload: CursorEventPayload = {\n position: {\n x: clientX,\n y: clientY,\n },\n user: {\n id: userId,\n name: username,\n },\n color: color,\n timestamp: new Date().getTime(),\n }\n\n cursorPayload.current = payload\n\n channelRef.current?.send({\n type: 'broadcast',\n event: EVENT_NAME,\n payload: payload,\n })\n },\n [color, userId, username]\n )\n\n const handleMouseMove = useThrottleCallback(callback, throttleMs)\n\n useEffect(() => {\n const channel = supabase.channel(roomName)\n\n channel\n .on('presence', { event: 'leave' }, ({ leftPresences }) => {\n leftPresences.forEach(function (element) {\n // Remove cursor when user leaves\n setCursors((prev) => {\n if (prev[element.key]) {\n delete prev[element.key]\n }\n\n return { ...prev }\n })\n })\n })\n .on('presence', { event: 'join' }, () => {\n if (!cursorPayload.current) return\n\n // All cursors broadcast their position when a new cursor joins\n channelRef.current?.send({\n type: 'broadcast',\n event: EVENT_NAME,\n payload: cursorPayload.current,\n })\n })\n .on('broadcast', { event: EVENT_NAME }, (data: { payload: CursorEventPayload }) => {\n const { user } = data.payload\n // Don't render your own cursor\n if (user.id === userId) return\n\n setCursors((prev) => {\n if (prev[userId]) {\n delete prev[userId]\n }\n\n return {\n ...prev,\n [user.id]: data.payload,\n }\n })\n })\n .subscribe(async (status) => {\n if (status === REALTIME_SUBSCRIBE_STATES.SUBSCRIBED) {\n await channel.track({ key: userId })\n channelRef.current = channel\n } else {\n setCursors({})\n channelRef.current = null\n }\n })\n\n return () => {\n channel.unsubscribe()\n channelRef.current = null\n }\n }, [])\n\n useEffect(() => {\n // Add event listener for mousemove\n window.addEventListener('mousemove', handleMouseMove)\n\n // Cleanup on unmount\n return () => {\n window.removeEventListener('mousemove', handleMouseMove)\n }\n }, [handleMouseMove])\n\n return { cursors }\n}\n",
|
||||
"content": "import { REALTIME_SUBSCRIBE_STATES, RealtimeChannel } from '@supabase/supabase-js'\nimport { useCallback, useEffect, useRef, useState } from 'react'\n\nimport { createClient } from '@/registry/default/clients/react-router/lib/supabase/client'\n\n/**\n * Throttle a callback to a certain delay, It will only call the callback if the delay has passed, with the arguments\n * from the last call\n */\nconst useThrottleCallback = <Params extends unknown[], Return>(\n callback: (...args: Params) => Return,\n delay: number\n) => {\n const lastCall = useRef(0)\n const timeout = useRef<NodeJS.Timeout | null>(null)\n\n return useCallback(\n (...args: Params) => {\n const now = Date.now()\n const remainingTime = delay - (now - lastCall.current)\n\n if (remainingTime <= 0) {\n if (timeout.current) {\n clearTimeout(timeout.current)\n timeout.current = null\n }\n lastCall.current = now\n callback(...args)\n } else if (!timeout.current) {\n timeout.current = setTimeout(() => {\n lastCall.current = Date.now()\n timeout.current = null\n callback(...args)\n }, remainingTime)\n }\n },\n [callback, delay]\n )\n}\n\nconst supabase = createClient()\n\nconst generateRandomColor = () => `hsl(${Math.floor(Math.random() * 360)}, 100%, 70%)`\n\nconst generateRandomNumber = () => Math.floor(Math.random() * 100)\n\nconst EVENT_NAME = 'realtime-cursor-move'\n\ntype CursorEventPayload = {\n position: {\n x: number\n y: number\n }\n user: {\n id: number\n name: string\n }\n color: string\n timestamp: number\n}\n\nexport const useRealtimeCursors = ({\n roomName,\n username,\n throttleMs,\n}: {\n roomName: string\n username: string\n throttleMs: number\n}) => {\n const [color] = useState(generateRandomColor())\n const [userId] = useState(generateRandomNumber())\n const [cursors, setCursors] = useState<Record<string, CursorEventPayload>>({})\n const cursorPayload = useRef<CursorEventPayload | null>(null)\n\n const channelRef = useRef<RealtimeChannel | null>(null)\n\n const callback = useCallback(\n (event: MouseEvent) => {\n const { clientX, clientY } = event\n\n const payload: CursorEventPayload = {\n position: {\n x: clientX,\n y: clientY,\n },\n user: {\n id: userId,\n name: username,\n },\n color: color,\n timestamp: new Date().getTime(),\n }\n\n cursorPayload.current = payload\n\n channelRef.current?.send({\n type: 'broadcast',\n event: EVENT_NAME,\n payload: payload,\n })\n },\n [color, userId, username]\n )\n\n const handleMouseMove = useThrottleCallback(callback, throttleMs)\n\n useEffect(() => {\n const channel = supabase.channel(roomName)\n\n channel\n .on('presence', { event: 'leave' }, ({ leftPresences }) => {\n leftPresences.forEach(function (element) {\n // Remove cursor when user leaves\n setCursors((prev) => {\n if (prev[element.key]) {\n delete prev[element.key]\n }\n\n return { ...prev }\n })\n })\n })\n .on('presence', { event: 'join' }, () => {\n if (!cursorPayload.current) return\n\n // All cursors broadcast their position when a new cursor joins\n channelRef.current?.send({\n type: 'broadcast',\n event: EVENT_NAME,\n payload: cursorPayload.current,\n })\n })\n .on('broadcast', { event: EVENT_NAME }, (data: { payload: CursorEventPayload }) => {\n const { user } = data.payload\n // Don't render your own cursor\n if (user.id === userId) return\n\n setCursors((prev) => {\n if (prev[userId]) {\n delete prev[userId]\n }\n\n return {\n ...prev,\n [user.id]: data.payload,\n }\n })\n })\n .subscribe(async (status) => {\n if (status === REALTIME_SUBSCRIBE_STATES.SUBSCRIBED) {\n await channel.track({ key: userId })\n channelRef.current = channel\n } else {\n setCursors({})\n channelRef.current = null\n }\n })\n\n return () => {\n channel.unsubscribe()\n channelRef.current = null\n }\n }, [])\n\n useEffect(() => {\n // Add event listener for mousemove\n window.addEventListener('mousemove', handleMouseMove)\n\n // Cleanup on unmount\n return () => {\n window.removeEventListener('mousemove', handleMouseMove)\n }\n }, [handleMouseMove])\n\n return { cursors }\n}\n",
|
||||
"type": "registry:hook"
|
||||
},
|
||||
{
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
},
|
||||
{
|
||||
"path": "registry/default/blocks/realtime-cursor/hooks/use-realtime-cursors.ts",
|
||||
"content": "import { REALTIME_SUBSCRIBE_STATES, RealtimeChannel } from '@supabase/supabase-js'\nimport { useCallback, useEffect, useRef, useState } from 'react'\n\nimport { createClient } from '@/registry/default/clients/nextjs/lib/supabase/client'\n\n/**\n * Throttle a callback to a certain delay, It will only call the callback if the delay has passed, with the arguments\n * from the last call\n */\nconst useThrottleCallback = <Params extends unknown[], Return>(\n callback: (...args: Params) => Return,\n delay: number\n) => {\n const lastCall = useRef(0)\n const timeout = useRef<NodeJS.Timeout | null>(null)\n\n return useCallback(\n (...args: Params) => {\n const now = Date.now()\n const remainingTime = delay - (now - lastCall.current)\n\n if (remainingTime <= 0) {\n if (timeout.current) {\n clearTimeout(timeout.current)\n timeout.current = null\n }\n lastCall.current = now\n callback(...args)\n } else if (!timeout.current) {\n timeout.current = setTimeout(() => {\n lastCall.current = Date.now()\n timeout.current = null\n callback(...args)\n }, remainingTime)\n }\n },\n [callback, delay]\n )\n}\n\nconst supabase = createClient()\n\nconst generateRandomColor = () => `hsl(${Math.floor(Math.random() * 360)}, 100%, 70%)`\n\nconst generateRandomNumber = () => Math.floor(Math.random() * 100)\n\nconst EVENT_NAME = 'realtime-cursor-move'\n\ntype CursorEventPayload = {\n position: {\n x: number\n y: number\n }\n user: {\n id: number\n name: string\n }\n color: string\n timestamp: number\n}\n\nexport const useRealtimeCursors = ({\n roomName,\n username,\n throttleMs,\n}: {\n roomName: string\n username: string\n throttleMs: number\n}) => {\n const [color] = useState(generateRandomColor())\n const [userId] = useState(generateRandomNumber())\n const [cursors, setCursors] = useState<Record<string, CursorEventPayload>>({})\n const cursorPayload = useRef<CursorEventPayload | null>(null)\n\n const channelRef = useRef<RealtimeChannel | null>(null)\n\n const callback = useCallback(\n (event: MouseEvent) => {\n const { clientX, clientY } = event\n\n const payload: CursorEventPayload = {\n position: {\n x: clientX,\n y: clientY,\n },\n user: {\n id: userId,\n name: username,\n },\n color: color,\n timestamp: new Date().getTime(),\n }\n\n cursorPayload.current = payload\n\n channelRef.current?.send({\n type: 'broadcast',\n event: EVENT_NAME,\n payload: payload,\n })\n },\n [color, userId, username]\n )\n\n const handleMouseMove = useThrottleCallback(callback, throttleMs)\n\n useEffect(() => {\n const channel = supabase.channel(roomName)\n\n channel\n .on('presence', { event: 'leave' }, ({ leftPresences }) => {\n leftPresences.forEach(function (element) {\n // Remove cursor when user leaves\n setCursors((prev) => {\n if (prev[element.key]) {\n delete prev[element.key]\n }\n\n return { ...prev }\n })\n })\n })\n .on('presence', { event: 'join' }, () => {\n if (!cursorPayload.current) return\n\n // All cursors broadcast their position when a new cursor joins\n channelRef.current?.send({\n type: 'broadcast',\n event: EVENT_NAME,\n payload: cursorPayload.current,\n })\n })\n .on('broadcast', { event: EVENT_NAME }, (data: { payload: CursorEventPayload }) => {\n const { user } = data.payload\n // Don't render your own cursor\n if (user.id === userId) return\n\n setCursors((prev) => {\n if (prev[userId]) {\n delete prev[userId]\n }\n\n return {\n ...prev,\n [user.id]: data.payload,\n }\n })\n })\n .subscribe(async (status) => {\n if (status === REALTIME_SUBSCRIBE_STATES.SUBSCRIBED) {\n await channel.track({ key: userId })\n channelRef.current = channel\n } else {\n setCursors({})\n channelRef.current = null\n }\n })\n\n return () => {\n channel.unsubscribe()\n channelRef.current = null\n }\n }, [])\n\n useEffect(() => {\n // Add event listener for mousemove\n window.addEventListener('mousemove', handleMouseMove)\n\n // Cleanup on unmount\n return () => {\n window.removeEventListener('mousemove', handleMouseMove)\n }\n }, [handleMouseMove])\n\n return { cursors }\n}\n",
|
||||
"content": "import { REALTIME_SUBSCRIBE_STATES, RealtimeChannel } from '@supabase/supabase-js'\nimport { useCallback, useEffect, useRef, useState } from 'react'\n\nimport { createClient } from '@/registry/default/clients/react/lib/supabase/client'\n\n/**\n * Throttle a callback to a certain delay, It will only call the callback if the delay has passed, with the arguments\n * from the last call\n */\nconst useThrottleCallback = <Params extends unknown[], Return>(\n callback: (...args: Params) => Return,\n delay: number\n) => {\n const lastCall = useRef(0)\n const timeout = useRef<NodeJS.Timeout | null>(null)\n\n return useCallback(\n (...args: Params) => {\n const now = Date.now()\n const remainingTime = delay - (now - lastCall.current)\n\n if (remainingTime <= 0) {\n if (timeout.current) {\n clearTimeout(timeout.current)\n timeout.current = null\n }\n lastCall.current = now\n callback(...args)\n } else if (!timeout.current) {\n timeout.current = setTimeout(() => {\n lastCall.current = Date.now()\n timeout.current = null\n callback(...args)\n }, remainingTime)\n }\n },\n [callback, delay]\n )\n}\n\nconst supabase = createClient()\n\nconst generateRandomColor = () => `hsl(${Math.floor(Math.random() * 360)}, 100%, 70%)`\n\nconst generateRandomNumber = () => Math.floor(Math.random() * 100)\n\nconst EVENT_NAME = 'realtime-cursor-move'\n\ntype CursorEventPayload = {\n position: {\n x: number\n y: number\n }\n user: {\n id: number\n name: string\n }\n color: string\n timestamp: number\n}\n\nexport const useRealtimeCursors = ({\n roomName,\n username,\n throttleMs,\n}: {\n roomName: string\n username: string\n throttleMs: number\n}) => {\n const [color] = useState(generateRandomColor())\n const [userId] = useState(generateRandomNumber())\n const [cursors, setCursors] = useState<Record<string, CursorEventPayload>>({})\n const cursorPayload = useRef<CursorEventPayload | null>(null)\n\n const channelRef = useRef<RealtimeChannel | null>(null)\n\n const callback = useCallback(\n (event: MouseEvent) => {\n const { clientX, clientY } = event\n\n const payload: CursorEventPayload = {\n position: {\n x: clientX,\n y: clientY,\n },\n user: {\n id: userId,\n name: username,\n },\n color: color,\n timestamp: new Date().getTime(),\n }\n\n cursorPayload.current = payload\n\n channelRef.current?.send({\n type: 'broadcast',\n event: EVENT_NAME,\n payload: payload,\n })\n },\n [color, userId, username]\n )\n\n const handleMouseMove = useThrottleCallback(callback, throttleMs)\n\n useEffect(() => {\n const channel = supabase.channel(roomName)\n\n channel\n .on('presence', { event: 'leave' }, ({ leftPresences }) => {\n leftPresences.forEach(function (element) {\n // Remove cursor when user leaves\n setCursors((prev) => {\n if (prev[element.key]) {\n delete prev[element.key]\n }\n\n return { ...prev }\n })\n })\n })\n .on('presence', { event: 'join' }, () => {\n if (!cursorPayload.current) return\n\n // All cursors broadcast their position when a new cursor joins\n channelRef.current?.send({\n type: 'broadcast',\n event: EVENT_NAME,\n payload: cursorPayload.current,\n })\n })\n .on('broadcast', { event: EVENT_NAME }, (data: { payload: CursorEventPayload }) => {\n const { user } = data.payload\n // Don't render your own cursor\n if (user.id === userId) return\n\n setCursors((prev) => {\n if (prev[userId]) {\n delete prev[userId]\n }\n\n return {\n ...prev,\n [user.id]: data.payload,\n }\n })\n })\n .subscribe(async (status) => {\n if (status === REALTIME_SUBSCRIBE_STATES.SUBSCRIBED) {\n await channel.track({ key: userId })\n channelRef.current = channel\n } else {\n setCursors({})\n channelRef.current = null\n }\n })\n\n return () => {\n channel.unsubscribe()\n channelRef.current = null\n }\n }, [])\n\n useEffect(() => {\n // Add event listener for mousemove\n window.addEventListener('mousemove', handleMouseMove)\n\n // Cleanup on unmount\n return () => {\n window.removeEventListener('mousemove', handleMouseMove)\n }\n }, [handleMouseMove])\n\n return { cursors }\n}\n",
|
||||
"type": "registry:hook"
|
||||
},
|
||||
{
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
},
|
||||
{
|
||||
"path": "registry/default/blocks/realtime-cursor/hooks/use-realtime-cursors.ts",
|
||||
"content": "import { REALTIME_SUBSCRIBE_STATES, RealtimeChannel } from '@supabase/supabase-js'\nimport { useCallback, useEffect, useRef, useState } from 'react'\n\nimport { createClient } from '@/registry/default/clients/nextjs/lib/supabase/client'\n\n/**\n * Throttle a callback to a certain delay, It will only call the callback if the delay has passed, with the arguments\n * from the last call\n */\nconst useThrottleCallback = <Params extends unknown[], Return>(\n callback: (...args: Params) => Return,\n delay: number\n) => {\n const lastCall = useRef(0)\n const timeout = useRef<NodeJS.Timeout | null>(null)\n\n return useCallback(\n (...args: Params) => {\n const now = Date.now()\n const remainingTime = delay - (now - lastCall.current)\n\n if (remainingTime <= 0) {\n if (timeout.current) {\n clearTimeout(timeout.current)\n timeout.current = null\n }\n lastCall.current = now\n callback(...args)\n } else if (!timeout.current) {\n timeout.current = setTimeout(() => {\n lastCall.current = Date.now()\n timeout.current = null\n callback(...args)\n }, remainingTime)\n }\n },\n [callback, delay]\n )\n}\n\nconst supabase = createClient()\n\nconst generateRandomColor = () => `hsl(${Math.floor(Math.random() * 360)}, 100%, 70%)`\n\nconst generateRandomNumber = () => Math.floor(Math.random() * 100)\n\nconst EVENT_NAME = 'realtime-cursor-move'\n\ntype CursorEventPayload = {\n position: {\n x: number\n y: number\n }\n user: {\n id: number\n name: string\n }\n color: string\n timestamp: number\n}\n\nexport const useRealtimeCursors = ({\n roomName,\n username,\n throttleMs,\n}: {\n roomName: string\n username: string\n throttleMs: number\n}) => {\n const [color] = useState(generateRandomColor())\n const [userId] = useState(generateRandomNumber())\n const [cursors, setCursors] = useState<Record<string, CursorEventPayload>>({})\n const cursorPayload = useRef<CursorEventPayload | null>(null)\n\n const channelRef = useRef<RealtimeChannel | null>(null)\n\n const callback = useCallback(\n (event: MouseEvent) => {\n const { clientX, clientY } = event\n\n const payload: CursorEventPayload = {\n position: {\n x: clientX,\n y: clientY,\n },\n user: {\n id: userId,\n name: username,\n },\n color: color,\n timestamp: new Date().getTime(),\n }\n\n cursorPayload.current = payload\n\n channelRef.current?.send({\n type: 'broadcast',\n event: EVENT_NAME,\n payload: payload,\n })\n },\n [color, userId, username]\n )\n\n const handleMouseMove = useThrottleCallback(callback, throttleMs)\n\n useEffect(() => {\n const channel = supabase.channel(roomName)\n\n channel\n .on('presence', { event: 'leave' }, ({ leftPresences }) => {\n leftPresences.forEach(function (element) {\n // Remove cursor when user leaves\n setCursors((prev) => {\n if (prev[element.key]) {\n delete prev[element.key]\n }\n\n return { ...prev }\n })\n })\n })\n .on('presence', { event: 'join' }, () => {\n if (!cursorPayload.current) return\n\n // All cursors broadcast their position when a new cursor joins\n channelRef.current?.send({\n type: 'broadcast',\n event: EVENT_NAME,\n payload: cursorPayload.current,\n })\n })\n .on('broadcast', { event: EVENT_NAME }, (data: { payload: CursorEventPayload }) => {\n const { user } = data.payload\n // Don't render your own cursor\n if (user.id === userId) return\n\n setCursors((prev) => {\n if (prev[userId]) {\n delete prev[userId]\n }\n\n return {\n ...prev,\n [user.id]: data.payload,\n }\n })\n })\n .subscribe(async (status) => {\n if (status === REALTIME_SUBSCRIBE_STATES.SUBSCRIBED) {\n await channel.track({ key: userId })\n channelRef.current = channel\n } else {\n setCursors({})\n channelRef.current = null\n }\n })\n\n return () => {\n channel.unsubscribe()\n channelRef.current = null\n }\n }, [])\n\n useEffect(() => {\n // Add event listener for mousemove\n window.addEventListener('mousemove', handleMouseMove)\n\n // Cleanup on unmount\n return () => {\n window.removeEventListener('mousemove', handleMouseMove)\n }\n }, [handleMouseMove])\n\n return { cursors }\n}\n",
|
||||
"content": "import { REALTIME_SUBSCRIBE_STATES, RealtimeChannel } from '@supabase/supabase-js'\nimport { useCallback, useEffect, useRef, useState } from 'react'\n\nimport { createClient } from '@/registry/default/clients/tanstack/lib/supabase/client'\n\n/**\n * Throttle a callback to a certain delay, It will only call the callback if the delay has passed, with the arguments\n * from the last call\n */\nconst useThrottleCallback = <Params extends unknown[], Return>(\n callback: (...args: Params) => Return,\n delay: number\n) => {\n const lastCall = useRef(0)\n const timeout = useRef<NodeJS.Timeout | null>(null)\n\n return useCallback(\n (...args: Params) => {\n const now = Date.now()\n const remainingTime = delay - (now - lastCall.current)\n\n if (remainingTime <= 0) {\n if (timeout.current) {\n clearTimeout(timeout.current)\n timeout.current = null\n }\n lastCall.current = now\n callback(...args)\n } else if (!timeout.current) {\n timeout.current = setTimeout(() => {\n lastCall.current = Date.now()\n timeout.current = null\n callback(...args)\n }, remainingTime)\n }\n },\n [callback, delay]\n )\n}\n\nconst supabase = createClient()\n\nconst generateRandomColor = () => `hsl(${Math.floor(Math.random() * 360)}, 100%, 70%)`\n\nconst generateRandomNumber = () => Math.floor(Math.random() * 100)\n\nconst EVENT_NAME = 'realtime-cursor-move'\n\ntype CursorEventPayload = {\n position: {\n x: number\n y: number\n }\n user: {\n id: number\n name: string\n }\n color: string\n timestamp: number\n}\n\nexport const useRealtimeCursors = ({\n roomName,\n username,\n throttleMs,\n}: {\n roomName: string\n username: string\n throttleMs: number\n}) => {\n const [color] = useState(generateRandomColor())\n const [userId] = useState(generateRandomNumber())\n const [cursors, setCursors] = useState<Record<string, CursorEventPayload>>({})\n const cursorPayload = useRef<CursorEventPayload | null>(null)\n\n const channelRef = useRef<RealtimeChannel | null>(null)\n\n const callback = useCallback(\n (event: MouseEvent) => {\n const { clientX, clientY } = event\n\n const payload: CursorEventPayload = {\n position: {\n x: clientX,\n y: clientY,\n },\n user: {\n id: userId,\n name: username,\n },\n color: color,\n timestamp: new Date().getTime(),\n }\n\n cursorPayload.current = payload\n\n channelRef.current?.send({\n type: 'broadcast',\n event: EVENT_NAME,\n payload: payload,\n })\n },\n [color, userId, username]\n )\n\n const handleMouseMove = useThrottleCallback(callback, throttleMs)\n\n useEffect(() => {\n const channel = supabase.channel(roomName)\n\n channel\n .on('presence', { event: 'leave' }, ({ leftPresences }) => {\n leftPresences.forEach(function (element) {\n // Remove cursor when user leaves\n setCursors((prev) => {\n if (prev[element.key]) {\n delete prev[element.key]\n }\n\n return { ...prev }\n })\n })\n })\n .on('presence', { event: 'join' }, () => {\n if (!cursorPayload.current) return\n\n // All cursors broadcast their position when a new cursor joins\n channelRef.current?.send({\n type: 'broadcast',\n event: EVENT_NAME,\n payload: cursorPayload.current,\n })\n })\n .on('broadcast', { event: EVENT_NAME }, (data: { payload: CursorEventPayload }) => {\n const { user } = data.payload\n // Don't render your own cursor\n if (user.id === userId) return\n\n setCursors((prev) => {\n if (prev[userId]) {\n delete prev[userId]\n }\n\n return {\n ...prev,\n [user.id]: data.payload,\n }\n })\n })\n .subscribe(async (status) => {\n if (status === REALTIME_SUBSCRIBE_STATES.SUBSCRIBED) {\n await channel.track({ key: userId })\n channelRef.current = channel\n } else {\n setCursors({})\n channelRef.current = null\n }\n })\n\n return () => {\n channel.unsubscribe()\n channelRef.current = null\n }\n }, [])\n\n useEffect(() => {\n // Add event listener for mousemove\n window.addEventListener('mousemove', handleMouseMove)\n\n // Cleanup on unmount\n return () => {\n window.removeEventListener('mousemove', handleMouseMove)\n }\n }, [handleMouseMove])\n\n return { cursors }\n}\n",
|
||||
"type": "registry:hook"
|
||||
},
|
||||
{
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
{
|
||||
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
||||
"name": "realtime-flow-nextjs",
|
||||
"type": "registry:component",
|
||||
"title": "Realtime Flow",
|
||||
"description": "Real-time flow diagram editor for collaborative applications.",
|
||||
"dependencies": [
|
||||
"@xyflow/react@latest",
|
||||
"@supabase-labs/y-supabase@latest",
|
||||
"y-protocols@latest",
|
||||
"yjs@latest",
|
||||
"@supabase/ssr@latest",
|
||||
"@supabase/supabase-js@latest"
|
||||
],
|
||||
"registryDependencies": [],
|
||||
"files": [
|
||||
{
|
||||
"path": "registry/default/blocks/realtime-flow/hooks/use-realtime-flow.ts",
|
||||
"content": "'use client'\n\nimport { type SupabasePersistenceOptions, SupabaseProvider } from '@supabase-labs/y-supabase'\nimport {\n type Edge,\n type Node,\n type NodeChange,\n type EdgeChange,\n type Connection,\n applyNodeChanges,\n applyEdgeChanges,\n addEdge,\n} from '@xyflow/react'\nimport { useCallback, useEffect, useRef, useState } from 'react'\nimport { Awareness } from 'y-protocols/awareness'\nimport * as Y from 'yjs'\n\nimport { createClient } from '@/registry/default/clients/nextjs/lib/supabase/client'\n\ntype UseRealtimeFlowOptions = {\n channel: string\n persistence?: boolean | SupabasePersistenceOptions\n awareness?: boolean | Awareness\n initialNodes?: Node[]\n initialEdges?: Edge[]\n}\n\ntype SetStateAction<T> = T | ((prev: T) => T)\n\nconst INITIAL_SYNC_MS = 350\n\nexport function useRealtimeFlow({\n channel,\n persistence,\n awareness = true,\n initialNodes = [],\n initialEdges = [],\n}: UseRealtimeFlowOptions) {\n const [nodes, setNodesState] = useState<Node[]>([])\n const [edges, setEdgesState] = useState<Edge[]>([])\n const [synced, setSynced] = useState(false)\n const [syncError, setSyncError] = useState<string | null>(null)\n\n const docRef = useRef<Y.Doc | null>(null)\n const providerRef = useRef<SupabaseProvider | null>(null)\n const syncedRef = useRef(false)\n const initialNodesRef = useRef(initialNodes)\n const initialEdgesRef = useRef(initialEdges)\n\n useEffect(() => {\n const doc = new Y.Doc()\n const yNodes = doc.getMap<string>('nodes')\n const yEdges = doc.getMap<string>('edges')\n const initialNodesForChannel = initialNodesRef.current\n const initialEdgesForChannel = initialEdgesRef.current\n let initialSyncTimer: ReturnType<typeof setTimeout> | null = null\n let hasRemoteActivity = false\n\n const supabase = createClient()\n const provider = new SupabaseProvider(channel, doc, supabase as any, {\n awareness,\n persistence,\n })\n\n // Sync Y.Map state to React state\n const syncNodesFromYjs = () => {\n const parsed: Node[] = []\n yNodes.forEach((value) => {\n try {\n parsed.push(JSON.parse(value))\n } catch {}\n })\n setNodesState(parsed)\n }\n\n const syncEdgesFromYjs = () => {\n const parsed: Edge[] = []\n yEdges.forEach((value) => {\n try {\n parsed.push(JSON.parse(value))\n } catch {}\n })\n setEdgesState(parsed)\n }\n\n const clearInitialSyncTimer = () => {\n if (initialSyncTimer) {\n clearTimeout(initialSyncTimer)\n initialSyncTimer = null\n }\n }\n\n const clearSyncError = () => {\n setSyncError(null)\n }\n\n const seedInitialState = () => {\n if (yNodes.size === 0 && initialNodesForChannel.length > 0) {\n doc.transact(() => {\n for (const node of initialNodesForChannel) {\n yNodes.set(node.id, JSON.stringify(node))\n }\n }, 'local')\n }\n\n if (yEdges.size === 0 && initialEdgesForChannel.length > 0) {\n doc.transact(() => {\n for (const edge of initialEdgesForChannel) {\n yEdges.set(edge.id, JSON.stringify(edge))\n }\n }, 'local')\n }\n }\n\n const nodesObserver = (event: Y.YMapEvent<string>) => {\n if (event.transaction.origin === 'local') return\n hasRemoteActivity = true\n syncNodesFromYjs()\n }\n\n const edgesObserver = (event: Y.YMapEvent<string>) => {\n if (event.transaction.origin === 'local') return\n hasRemoteActivity = true\n syncEdgesFromYjs()\n }\n\n yNodes.observe(nodesObserver)\n yEdges.observe(edgesObserver)\n\n const markSynced = (shouldSeed = false) => {\n if (syncedRef.current) return\n clearInitialSyncTimer()\n clearSyncError()\n syncedRef.current = true\n\n if (shouldSeed && !hasRemoteActivity) {\n seedInitialState()\n }\n\n // Sync React state from Yjs (includes seeded initial data if applied)\n syncNodesFromYjs()\n syncEdgesFromYjs()\n setSynced(true)\n }\n\n const markSyncError = (error: Error) => {\n clearInitialSyncTimer()\n if (syncedRef.current) return\n setSyncError(error.message || 'Failed to sync flow')\n }\n\n const persistenceInstance = provider.getPersistence()\n if (persistenceInstance) {\n // With persistence: wait for persisted state to load\n if (persistenceInstance.synced) {\n markSynced()\n } else {\n persistenceInstance.on('synced', () => {\n markSynced()\n })\n persistenceInstance.on('error', (error) => {\n markSyncError(error)\n })\n }\n } else {\n provider.on('connect', () => {\n clearSyncError()\n clearInitialSyncTimer()\n initialSyncTimer = setTimeout(() => {\n markSynced(true)\n }, INITIAL_SYNC_MS)\n })\n provider.on('message', () => {\Line truncated
|
||||
"type": "registry:hook"
|
||||
},
|
||||
{
|
||||
"path": "registry/default/blocks/realtime-flow/components/realtime-flow.tsx",
|
||||
"content": "'use client'\n\nimport {\n ReactFlow,\n ReactFlowProvider,\n Background,\n Controls,\n type Node,\n type Edge,\n type NodeTypes,\n type EdgeTypes,\n} from '@xyflow/react'\nimport '@xyflow/react/dist/style.css'\nimport type { SupabasePersistenceOptions } from '@supabase-labs/y-supabase'\n\nimport { RealtimeFlowOverlay } from './realtime-flow-overlay'\nimport { useRealtimeFlow } from '../hooks/use-realtime-flow'\n\ntype RealtimeFlowProps = {\n channel: string\n className?: string\n style?: React.CSSProperties\n persistence?: boolean | SupabasePersistenceOptions\n initialNodes?: Node[]\n initialEdges?: Edge[]\n nodeTypes?: NodeTypes\n edgeTypes?: EdgeTypes\n height?: string | number\n}\n\nconst DEFAULT_HEIGHT = 550\n\nconst RealtimeFlowContent = ({\n channel,\n className,\n style,\n persistence,\n initialNodes,\n initialEdges,\n nodeTypes,\n edgeTypes,\n height = DEFAULT_HEIGHT,\n}: RealtimeFlowProps) => {\n const { nodes, edges, synced, syncError, onNodesChange, onEdgesChange, onConnect } =\n useRealtimeFlow({\n channel,\n persistence,\n initialNodes,\n initialEdges,\n })\n\n return (\n <div style={{ height, position: 'relative', ...style }} className={className}>\n <ReactFlow\n nodes={synced ? nodes : []}\n edges={synced ? edges : []}\n onNodesChange={synced ? onNodesChange : undefined}\n onEdgesChange={synced ? onEdgesChange : undefined}\n onConnect={synced ? onConnect : undefined}\n nodeTypes={nodeTypes}\n edgeTypes={edgeTypes}\n fitView\n >\n <Background />\n <Controls />\n </ReactFlow>\n {!synced && !syncError && <RealtimeFlowOverlay status=\"syncing\" />}\n {!synced && syncError && <RealtimeFlowOverlay status=\"error\" message={syncError} />}\n </div>\n )\n}\n\nconst RealtimeFlow = (props: RealtimeFlowProps) => (\n <ReactFlowProvider>\n <RealtimeFlowContent {...props} />\n </ReactFlowProvider>\n)\n\nexport { RealtimeFlow }\n",
|
||||
"type": "registry:component"
|
||||
},
|
||||
{
|
||||
"path": "registry/default/clients/nextjs/lib/supabase/client.ts",
|
||||
"content": "import { createBrowserClient } from '@supabase/ssr'\n\nexport function createClient() {\n return createBrowserClient(\n process.env.NEXT_PUBLIC_SUPABASE_URL!,\n process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!\n )\n}\n",
|
||||
"type": "registry:lib"
|
||||
},
|
||||
{
|
||||
"path": "registry/default/clients/nextjs/lib/supabase/middleware.ts",
|
||||
"content": "import { createServerClient } from '@supabase/ssr'\nimport { NextResponse, type NextRequest } from 'next/server'\n\nexport async function updateSession(request: NextRequest) {\n let supabaseResponse = NextResponse.next({\n request,\n })\n\n // With Fluid compute, don't put this client in a global environment\n // variable. Always create a new one on each request.\n const supabase = createServerClient(\n process.env.NEXT_PUBLIC_SUPABASE_URL!,\n process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!,\n {\n cookies: {\n getAll() {\n return request.cookies.getAll()\n },\n setAll(cookiesToSet) {\n cookiesToSet.forEach(({ name, value }) => request.cookies.set(name, value))\n supabaseResponse = NextResponse.next({\n request,\n })\n cookiesToSet.forEach(({ name, value, options }) =>\n supabaseResponse.cookies.set(name, value, options)\n )\n },\n },\n }\n )\n\n // Do not run code between createServerClient and\n // supabase.auth.getClaims(). A simple mistake could make it very hard to debug\n // issues with users being randomly logged out.\n\n // IMPORTANT: If you remove getClaims() and you use server-side rendering\n // with the Supabase client, your users may be randomly logged out.\n const { data } = await supabase.auth.getClaims()\n const user = data?.claims\n\n if (\n !user &&\n !request.nextUrl.pathname.startsWith('/login') &&\n !request.nextUrl.pathname.startsWith('/auth')\n ) {\n // no user, potentially respond by redirecting the user to the login page\n const url = request.nextUrl.clone()\n url.pathname = '/auth/login'\n return NextResponse.redirect(url)\n }\n\n // IMPORTANT: You *must* return the supabaseResponse object as it is.\n // If you're creating a new response object with NextResponse.next() make sure to:\n // 1. Pass the request in it, like so:\n // const myNewResponse = NextResponse.next({ request })\n // 2. Copy over the cookies, like so:\n // myNewResponse.cookies.setAll(supabaseResponse.cookies.getAll())\n // 3. Change the myNewResponse object to fit your needs, but avoid changing\n // the cookies!\n // 4. Finally:\n // return myNewResponse\n // If this is not done, you may be causing the browser and server to go out\n // of sync and terminate the user's session prematurely!\n\n return supabaseResponse\n}\n",
|
||||
"type": "registry:lib"
|
||||
},
|
||||
{
|
||||
"path": "registry/default/clients/nextjs/lib/supabase/server.ts",
|
||||
"content": "import { createServerClient } from '@supabase/ssr'\nimport { cookies } from 'next/headers'\n\n/**\n * If using Fluid compute: Don't put this client in a global variable. Always create a new client within each\n * function when using it.\n */\nexport async function createClient() {\n const cookieStore = await cookies()\n\n return createServerClient(\n process.env.NEXT_PUBLIC_SUPABASE_URL!,\n process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!,\n {\n cookies: {\n getAll() {\n return cookieStore.getAll()\n },\n setAll(cookiesToSet) {\n try {\n cookiesToSet.forEach(({ name, value, options }) =>\n cookieStore.set(name, value, options)\n )\n } catch {\n // The `setAll` method was called from a Server Component.\n // This can be ignored if you have middleware refreshing\n // user sessions.\n }\n },\n },\n }\n )\n}\n",
|
||||
"type": "registry:lib"
|
||||
}
|
||||
],
|
||||
"envVars": {
|
||||
"NEXT_PUBLIC_SUPABASE_URL": "",
|
||||
"NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY": ""
|
||||
},
|
||||
"docs": "You'll need to set the following environment variables in your project: `NEXT_PUBLIC_SUPABASE_URL` and `NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY`."
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
{
|
||||
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
||||
"name": "realtime-flow-react-router",
|
||||
"type": "registry:component",
|
||||
"title": "Realtime Flow",
|
||||
"description": "Real-time flow diagram editor for collaborative applications.",
|
||||
"dependencies": [
|
||||
"@xyflow/react@latest",
|
||||
"@supabase-labs/y-supabase@latest",
|
||||
"y-protocols@latest",
|
||||
"yjs@latest",
|
||||
"@supabase/ssr@latest",
|
||||
"@supabase/supabase-js@latest"
|
||||
],
|
||||
"registryDependencies": [],
|
||||
"files": [
|
||||
{
|
||||
"path": "registry/default/blocks/realtime-flow/hooks/use-realtime-flow.ts",
|
||||
"content": "'use client'\n\nimport { type SupabasePersistenceOptions, SupabaseProvider } from '@supabase-labs/y-supabase'\nimport {\n type Edge,\n type Node,\n type NodeChange,\n type EdgeChange,\n type Connection,\n applyNodeChanges,\n applyEdgeChanges,\n addEdge,\n} from '@xyflow/react'\nimport { useCallback, useEffect, useRef, useState } from 'react'\nimport { Awareness } from 'y-protocols/awareness'\nimport * as Y from 'yjs'\n\nimport { createClient } from '@/registry/default/clients/react-router/lib/supabase/client'\n\ntype UseRealtimeFlowOptions = {\n channel: string\n persistence?: boolean | SupabasePersistenceOptions\n awareness?: boolean | Awareness\n initialNodes?: Node[]\n initialEdges?: Edge[]\n}\n\ntype SetStateAction<T> = T | ((prev: T) => T)\n\nconst INITIAL_SYNC_MS = 350\n\nexport function useRealtimeFlow({\n channel,\n persistence,\n awareness = true,\n initialNodes = [],\n initialEdges = [],\n}: UseRealtimeFlowOptions) {\n const [nodes, setNodesState] = useState<Node[]>([])\n const [edges, setEdgesState] = useState<Edge[]>([])\n const [synced, setSynced] = useState(false)\n const [syncError, setSyncError] = useState<string | null>(null)\n\n const docRef = useRef<Y.Doc | null>(null)\n const providerRef = useRef<SupabaseProvider | null>(null)\n const syncedRef = useRef(false)\n const initialNodesRef = useRef(initialNodes)\n const initialEdgesRef = useRef(initialEdges)\n\n useEffect(() => {\n const doc = new Y.Doc()\n const yNodes = doc.getMap<string>('nodes')\n const yEdges = doc.getMap<string>('edges')\n const initialNodesForChannel = initialNodesRef.current\n const initialEdgesForChannel = initialEdgesRef.current\n let initialSyncTimer: ReturnType<typeof setTimeout> | null = null\n let hasRemoteActivity = false\n\n const supabase = createClient()\n const provider = new SupabaseProvider(channel, doc, supabase as any, {\n awareness,\n persistence,\n })\n\n // Sync Y.Map state to React state\n const syncNodesFromYjs = () => {\n const parsed: Node[] = []\n yNodes.forEach((value) => {\n try {\n parsed.push(JSON.parse(value))\n } catch {}\n })\n setNodesState(parsed)\n }\n\n const syncEdgesFromYjs = () => {\n const parsed: Edge[] = []\n yEdges.forEach((value) => {\n try {\n parsed.push(JSON.parse(value))\n } catch {}\n })\n setEdgesState(parsed)\n }\n\n const clearInitialSyncTimer = () => {\n if (initialSyncTimer) {\n clearTimeout(initialSyncTimer)\n initialSyncTimer = null\n }\n }\n\n const clearSyncError = () => {\n setSyncError(null)\n }\n\n const seedInitialState = () => {\n if (yNodes.size === 0 && initialNodesForChannel.length > 0) {\n doc.transact(() => {\n for (const node of initialNodesForChannel) {\n yNodes.set(node.id, JSON.stringify(node))\n }\n }, 'local')\n }\n\n if (yEdges.size === 0 && initialEdgesForChannel.length > 0) {\n doc.transact(() => {\n for (const edge of initialEdgesForChannel) {\n yEdges.set(edge.id, JSON.stringify(edge))\n }\n }, 'local')\n }\n }\n\n const nodesObserver = (event: Y.YMapEvent<string>) => {\n if (event.transaction.origin === 'local') return\n hasRemoteActivity = true\n syncNodesFromYjs()\n }\n\n const edgesObserver = (event: Y.YMapEvent<string>) => {\n if (event.transaction.origin === 'local') return\n hasRemoteActivity = true\n syncEdgesFromYjs()\n }\n\n yNodes.observe(nodesObserver)\n yEdges.observe(edgesObserver)\n\n const markSynced = (shouldSeed = false) => {\n if (syncedRef.current) return\n clearInitialSyncTimer()\n clearSyncError()\n syncedRef.current = true\n\n if (shouldSeed && !hasRemoteActivity) {\n seedInitialState()\n }\n\n // Sync React state from Yjs (includes seeded initial data if applied)\n syncNodesFromYjs()\n syncEdgesFromYjs()\n setSynced(true)\n }\n\n const markSyncError = (error: Error) => {\n clearInitialSyncTimer()\n if (syncedRef.current) return\n setSyncError(error.message || 'Failed to sync flow')\n }\n\n const persistenceInstance = provider.getPersistence()\n if (persistenceInstance) {\n // With persistence: wait for persisted state to load\n if (persistenceInstance.synced) {\n markSynced()\n } else {\n persistenceInstance.on('synced', () => {\n markSynced()\n })\n persistenceInstance.on('error', (error) => {\n markSyncError(error)\n })\n }\n } else {\n provider.on('connect', () => {\n clearSyncError()\n clearInitialSyncTimer()\n initialSyncTimer = setTimeout(() => {\n markSynced(true)\n }, INITIAL_SYNC_MS)\n })\n provider.on('message', ()Line truncated
|
||||
"type": "registry:hook"
|
||||
},
|
||||
{
|
||||
"path": "registry/default/blocks/realtime-flow/components/realtime-flow.tsx",
|
||||
"content": "'use client'\n\nimport {\n ReactFlow,\n ReactFlowProvider,\n Background,\n Controls,\n type Node,\n type Edge,\n type NodeTypes,\n type EdgeTypes,\n} from '@xyflow/react'\nimport '@xyflow/react/dist/style.css'\nimport type { SupabasePersistenceOptions } from '@supabase-labs/y-supabase'\n\nimport { RealtimeFlowOverlay } from './realtime-flow-overlay'\nimport { useRealtimeFlow } from '../hooks/use-realtime-flow'\n\ntype RealtimeFlowProps = {\n channel: string\n className?: string\n style?: React.CSSProperties\n persistence?: boolean | SupabasePersistenceOptions\n initialNodes?: Node[]\n initialEdges?: Edge[]\n nodeTypes?: NodeTypes\n edgeTypes?: EdgeTypes\n height?: string | number\n}\n\nconst DEFAULT_HEIGHT = 550\n\nconst RealtimeFlowContent = ({\n channel,\n className,\n style,\n persistence,\n initialNodes,\n initialEdges,\n nodeTypes,\n edgeTypes,\n height = DEFAULT_HEIGHT,\n}: RealtimeFlowProps) => {\n const { nodes, edges, synced, syncError, onNodesChange, onEdgesChange, onConnect } =\n useRealtimeFlow({\n channel,\n persistence,\n initialNodes,\n initialEdges,\n })\n\n return (\n <div style={{ height, position: 'relative', ...style }} className={className}>\n <ReactFlow\n nodes={synced ? nodes : []}\n edges={synced ? edges : []}\n onNodesChange={synced ? onNodesChange : undefined}\n onEdgesChange={synced ? onEdgesChange : undefined}\n onConnect={synced ? onConnect : undefined}\n nodeTypes={nodeTypes}\n edgeTypes={edgeTypes}\n fitView\n >\n <Background />\n <Controls />\n </ReactFlow>\n {!synced && !syncError && <RealtimeFlowOverlay status=\"syncing\" />}\n {!synced && syncError && <RealtimeFlowOverlay status=\"error\" message={syncError} />}\n </div>\n )\n}\n\nconst RealtimeFlow = (props: RealtimeFlowProps) => (\n <ReactFlowProvider>\n <RealtimeFlowContent {...props} />\n </ReactFlowProvider>\n)\n\nexport { RealtimeFlow }\n",
|
||||
"type": "registry:component"
|
||||
},
|
||||
{
|
||||
"path": "registry/default/clients/react-router/lib/supabase/client.ts",
|
||||
"content": "/// <reference types=\"vite/types/importMeta.d.ts\" />\nimport { createBrowserClient } from '@supabase/ssr'\n\nexport function createClient() {\n return createBrowserClient(\n import.meta.env.VITE_SUPABASE_URL!,\n import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY!\n )\n}\n",
|
||||
"type": "registry:lib"
|
||||
},
|
||||
{
|
||||
"path": "registry/default/clients/react-router/lib/supabase/server.ts",
|
||||
"content": "import { createServerClient, parseCookieHeader, serializeCookieHeader } from '@supabase/ssr'\n\nexport function createClient(request: Request) {\n const headers = new Headers()\n\n const supabase = createServerClient(\n process.env.VITE_SUPABASE_URL!,\n process.env.VITE_SUPABASE_PUBLISHABLE_KEY!,\n {\n cookies: {\n getAll() {\n return parseCookieHeader(request.headers.get('Cookie') ?? '') as {\n name: string\n value: string\n }[]\n },\n setAll(cookiesToSet) {\n cookiesToSet.forEach(({ name, value, options }) =>\n headers.append('Set-Cookie', serializeCookieHeader(name, value, options))\n )\n },\n },\n }\n )\n\n return { supabase, headers }\n}\n",
|
||||
"type": "registry:lib"
|
||||
}
|
||||
],
|
||||
"envVars": {
|
||||
"VITE_SUPABASE_URL": "",
|
||||
"VITE_SUPABASE_PUBLISHABLE_KEY": ""
|
||||
},
|
||||
"docs": "You'll need to set the following environment variables in your project: `VITE_SUPABASE_URL` and `VITE_SUPABASE_PUBLISHABLE_KEY`."
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
||||
"name": "realtime-flow-react",
|
||||
"type": "registry:component",
|
||||
"title": "Realtime Flow",
|
||||
"description": "Real-time flow diagram editor for collaborative applications.",
|
||||
"dependencies": [
|
||||
"@xyflow/react@latest",
|
||||
"@supabase-labs/y-supabase@latest",
|
||||
"y-protocols@latest",
|
||||
"yjs@latest",
|
||||
"@supabase/supabase-js@latest"
|
||||
],
|
||||
"registryDependencies": [],
|
||||
"files": [
|
||||
{
|
||||
"path": "registry/default/blocks/realtime-flow/hooks/use-realtime-flow.ts",
|
||||
"content": "'use client'\n\nimport { type SupabasePersistenceOptions, SupabaseProvider } from '@supabase-labs/y-supabase'\nimport {\n type Edge,\n type Node,\n type NodeChange,\n type EdgeChange,\n type Connection,\n applyNodeChanges,\n applyEdgeChanges,\n addEdge,\n} from '@xyflow/react'\nimport { useCallback, useEffect, useRef, useState } from 'react'\nimport { Awareness } from 'y-protocols/awareness'\nimport * as Y from 'yjs'\n\nimport { createClient } from '@/registry/default/clients/react/lib/supabase/client'\n\ntype UseRealtimeFlowOptions = {\n channel: string\n persistence?: boolean | SupabasePersistenceOptions\n awareness?: boolean | Awareness\n initialNodes?: Node[]\n initialEdges?: Edge[]\n}\n\ntype SetStateAction<T> = T | ((prev: T) => T)\n\nconst INITIAL_SYNC_MS = 350\n\nexport function useRealtimeFlow({\n channel,\n persistence,\n awareness = true,\n initialNodes = [],\n initialEdges = [],\n}: UseRealtimeFlowOptions) {\n const [nodes, setNodesState] = useState<Node[]>([])\n const [edges, setEdgesState] = useState<Edge[]>([])\n const [synced, setSynced] = useState(false)\n const [syncError, setSyncError] = useState<string | null>(null)\n\n const docRef = useRef<Y.Doc | null>(null)\n const providerRef = useRef<SupabaseProvider | null>(null)\n const syncedRef = useRef(false)\n const initialNodesRef = useRef(initialNodes)\n const initialEdgesRef = useRef(initialEdges)\n\n useEffect(() => {\n const doc = new Y.Doc()\n const yNodes = doc.getMap<string>('nodes')\n const yEdges = doc.getMap<string>('edges')\n const initialNodesForChannel = initialNodesRef.current\n const initialEdgesForChannel = initialEdgesRef.current\n let initialSyncTimer: ReturnType<typeof setTimeout> | null = null\n let hasRemoteActivity = false\n\n const supabase = createClient()\n const provider = new SupabaseProvider(channel, doc, supabase as any, {\n awareness,\n persistence,\n })\n\n // Sync Y.Map state to React state\n const syncNodesFromYjs = () => {\n const parsed: Node[] = []\n yNodes.forEach((value) => {\n try {\n parsed.push(JSON.parse(value))\n } catch {}\n })\n setNodesState(parsed)\n }\n\n const syncEdgesFromYjs = () => {\n const parsed: Edge[] = []\n yEdges.forEach((value) => {\n try {\n parsed.push(JSON.parse(value))\n } catch {}\n })\n setEdgesState(parsed)\n }\n\n const clearInitialSyncTimer = () => {\n if (initialSyncTimer) {\n clearTimeout(initialSyncTimer)\n initialSyncTimer = null\n }\n }\n\n const clearSyncError = () => {\n setSyncError(null)\n }\n\n const seedInitialState = () => {\n if (yNodes.size === 0 && initialNodesForChannel.length > 0) {\n doc.transact(() => {\n for (const node of initialNodesForChannel) {\n yNodes.set(node.id, JSON.stringify(node))\n }\n }, 'local')\n }\n\n if (yEdges.size === 0 && initialEdgesForChannel.length > 0) {\n doc.transact(() => {\n for (const edge of initialEdgesForChannel) {\n yEdges.set(edge.id, JSON.stringify(edge))\n }\n }, 'local')\n }\n }\n\n const nodesObserver = (event: Y.YMapEvent<string>) => {\n if (event.transaction.origin === 'local') return\n hasRemoteActivity = true\n syncNodesFromYjs()\n }\n\n const edgesObserver = (event: Y.YMapEvent<string>) => {\n if (event.transaction.origin === 'local') return\n hasRemoteActivity = true\n syncEdgesFromYjs()\n }\n\n yNodes.observe(nodesObserver)\n yEdges.observe(edgesObserver)\n\n const markSynced = (shouldSeed = false) => {\n if (syncedRef.current) return\n clearInitialSyncTimer()\n clearSyncError()\n syncedRef.current = true\n\n if (shouldSeed && !hasRemoteActivity) {\n seedInitialState()\n }\n\n // Sync React state from Yjs (includes seeded initial data if applied)\n syncNodesFromYjs()\n syncEdgesFromYjs()\n setSynced(true)\n }\n\n const markSyncError = (error: Error) => {\n clearInitialSyncTimer()\n if (syncedRef.current) return\n setSyncError(error.message || 'Failed to sync flow')\n }\n\n const persistenceInstance = provider.getPersistence()\n if (persistenceInstance) {\n // With persistence: wait for persisted state to load\n if (persistenceInstance.synced) {\n markSynced()\n } else {\n persistenceInstance.on('synced', () => {\n markSynced()\n })\n persistenceInstance.on('error', (error) => {\n markSyncError(error)\n })\n }\n } else {\n provider.on('connect', () => {\n clearSyncError()\n clearInitialSyncTimer()\n initialSyncTimer = setTimeout(() => {\n markSynced(true)\n }, INITIAL_SYNC_MS)\n })\n provider.on('message', () => {\nLine truncated
|
||||
"type": "registry:hook"
|
||||
},
|
||||
{
|
||||
"path": "registry/default/blocks/realtime-flow/components/realtime-flow.tsx",
|
||||
"content": "'use client'\n\nimport {\n ReactFlow,\n ReactFlowProvider,\n Background,\n Controls,\n type Node,\n type Edge,\n type NodeTypes,\n type EdgeTypes,\n} from '@xyflow/react'\nimport '@xyflow/react/dist/style.css'\nimport type { SupabasePersistenceOptions } from '@supabase-labs/y-supabase'\n\nimport { RealtimeFlowOverlay } from './realtime-flow-overlay'\nimport { useRealtimeFlow } from '../hooks/use-realtime-flow'\n\ntype RealtimeFlowProps = {\n channel: string\n className?: string\n style?: React.CSSProperties\n persistence?: boolean | SupabasePersistenceOptions\n initialNodes?: Node[]\n initialEdges?: Edge[]\n nodeTypes?: NodeTypes\n edgeTypes?: EdgeTypes\n height?: string | number\n}\n\nconst DEFAULT_HEIGHT = 550\n\nconst RealtimeFlowContent = ({\n channel,\n className,\n style,\n persistence,\n initialNodes,\n initialEdges,\n nodeTypes,\n edgeTypes,\n height = DEFAULT_HEIGHT,\n}: RealtimeFlowProps) => {\n const { nodes, edges, synced, syncError, onNodesChange, onEdgesChange, onConnect } =\n useRealtimeFlow({\n channel,\n persistence,\n initialNodes,\n initialEdges,\n })\n\n return (\n <div style={{ height, position: 'relative', ...style }} className={className}>\n <ReactFlow\n nodes={synced ? nodes : []}\n edges={synced ? edges : []}\n onNodesChange={synced ? onNodesChange : undefined}\n onEdgesChange={synced ? onEdgesChange : undefined}\n onConnect={synced ? onConnect : undefined}\n nodeTypes={nodeTypes}\n edgeTypes={edgeTypes}\n fitView\n >\n <Background />\n <Controls />\n </ReactFlow>\n {!synced && !syncError && <RealtimeFlowOverlay status=\"syncing\" />}\n {!synced && syncError && <RealtimeFlowOverlay status=\"error\" message={syncError} />}\n </div>\n )\n}\n\nconst RealtimeFlow = (props: RealtimeFlowProps) => (\n <ReactFlowProvider>\n <RealtimeFlowContent {...props} />\n </ReactFlowProvider>\n)\n\nexport { RealtimeFlow }\n",
|
||||
"type": "registry:component"
|
||||
},
|
||||
{
|
||||
"path": "registry/default/clients/react/lib/supabase/client.ts",
|
||||
"content": "import { createClient as createSupabaseClient } from '@supabase/supabase-js'\n\nexport function createClient() {\n return createSupabaseClient(\n import.meta.env.VITE_SUPABASE_URL!,\n import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY!\n )\n}\n",
|
||||
"type": "registry:lib"
|
||||
}
|
||||
],
|
||||
"envVars": {
|
||||
"VITE_SUPABASE_URL": "",
|
||||
"VITE_SUPABASE_PUBLISHABLE_KEY": ""
|
||||
},
|
||||
"docs": "You'll need to set the following environment variables in your project: `VITE_SUPABASE_URL` and `VITE_SUPABASE_PUBLISHABLE_KEY`."
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
{
|
||||
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
||||
"name": "realtime-flow-tanstack",
|
||||
"type": "registry:component",
|
||||
"title": "Realtime Flow",
|
||||
"description": "Real-time flow diagram editor for collaborative applications.",
|
||||
"dependencies": [
|
||||
"@xyflow/react@latest",
|
||||
"@supabase-labs/y-supabase@latest",
|
||||
"y-protocols@latest",
|
||||
"yjs@latest",
|
||||
"@supabase/ssr@latest",
|
||||
"@supabase/supabase-js@latest"
|
||||
],
|
||||
"registryDependencies": [],
|
||||
"files": [
|
||||
{
|
||||
"path": "registry/default/blocks/realtime-flow/hooks/use-realtime-flow.ts",
|
||||
"content": "'use client'\n\nimport { type SupabasePersistenceOptions, SupabaseProvider } from '@supabase-labs/y-supabase'\nimport {\n type Edge,\n type Node,\n type NodeChange,\n type EdgeChange,\n type Connection,\n applyNodeChanges,\n applyEdgeChanges,\n addEdge,\n} from '@xyflow/react'\nimport { useCallback, useEffect, useRef, useState } from 'react'\nimport { Awareness } from 'y-protocols/awareness'\nimport * as Y from 'yjs'\n\nimport { createClient } from '@/registry/default/clients/tanstack/lib/supabase/client'\n\ntype UseRealtimeFlowOptions = {\n channel: string\n persistence?: boolean | SupabasePersistenceOptions\n awareness?: boolean | Awareness\n initialNodes?: Node[]\n initialEdges?: Edge[]\n}\n\ntype SetStateAction<T> = T | ((prev: T) => T)\n\nconst INITIAL_SYNC_MS = 350\n\nexport function useRealtimeFlow({\n channel,\n persistence,\n awareness = true,\n initialNodes = [],\n initialEdges = [],\n}: UseRealtimeFlowOptions) {\n const [nodes, setNodesState] = useState<Node[]>([])\n const [edges, setEdgesState] = useState<Edge[]>([])\n const [synced, setSynced] = useState(false)\n const [syncError, setSyncError] = useState<string | null>(null)\n\n const docRef = useRef<Y.Doc | null>(null)\n const providerRef = useRef<SupabaseProvider | null>(null)\n const syncedRef = useRef(false)\n const initialNodesRef = useRef(initialNodes)\n const initialEdgesRef = useRef(initialEdges)\n\n useEffect(() => {\n const doc = new Y.Doc()\n const yNodes = doc.getMap<string>('nodes')\n const yEdges = doc.getMap<string>('edges')\n const initialNodesForChannel = initialNodesRef.current\n const initialEdgesForChannel = initialEdgesRef.current\n let initialSyncTimer: ReturnType<typeof setTimeout> | null = null\n let hasRemoteActivity = false\n\n const supabase = createClient()\n const provider = new SupabaseProvider(channel, doc, supabase as any, {\n awareness,\n persistence,\n })\n\n // Sync Y.Map state to React state\n const syncNodesFromYjs = () => {\n const parsed: Node[] = []\n yNodes.forEach((value) => {\n try {\n parsed.push(JSON.parse(value))\n } catch {}\n })\n setNodesState(parsed)\n }\n\n const syncEdgesFromYjs = () => {\n const parsed: Edge[] = []\n yEdges.forEach((value) => {\n try {\n parsed.push(JSON.parse(value))\n } catch {}\n })\n setEdgesState(parsed)\n }\n\n const clearInitialSyncTimer = () => {\n if (initialSyncTimer) {\n clearTimeout(initialSyncTimer)\n initialSyncTimer = null\n }\n }\n\n const clearSyncError = () => {\n setSyncError(null)\n }\n\n const seedInitialState = () => {\n if (yNodes.size === 0 && initialNodesForChannel.length > 0) {\n doc.transact(() => {\n for (const node of initialNodesForChannel) {\n yNodes.set(node.id, JSON.stringify(node))\n }\n }, 'local')\n }\n\n if (yEdges.size === 0 && initialEdgesForChannel.length > 0) {\n doc.transact(() => {\n for (const edge of initialEdgesForChannel) {\n yEdges.set(edge.id, JSON.stringify(edge))\n }\n }, 'local')\n }\n }\n\n const nodesObserver = (event: Y.YMapEvent<string>) => {\n if (event.transaction.origin === 'local') return\n hasRemoteActivity = true\n syncNodesFromYjs()\n }\n\n const edgesObserver = (event: Y.YMapEvent<string>) => {\n if (event.transaction.origin === 'local') return\n hasRemoteActivity = true\n syncEdgesFromYjs()\n }\n\n yNodes.observe(nodesObserver)\n yEdges.observe(edgesObserver)\n\n const markSynced = (shouldSeed = false) => {\n if (syncedRef.current) return\n clearInitialSyncTimer()\n clearSyncError()\n syncedRef.current = true\n\n if (shouldSeed && !hasRemoteActivity) {\n seedInitialState()\n }\n\n // Sync React state from Yjs (includes seeded initial data if applied)\n syncNodesFromYjs()\n syncEdgesFromYjs()\n setSynced(true)\n }\n\n const markSyncError = (error: Error) => {\n clearInitialSyncTimer()\n if (syncedRef.current) return\n setSyncError(error.message || 'Failed to sync flow')\n }\n\n const persistenceInstance = provider.getPersistence()\n if (persistenceInstance) {\n // With persistence: wait for persisted state to load\n if (persistenceInstance.synced) {\n markSynced()\n } else {\n persistenceInstance.on('synced', () => {\n markSynced()\n })\n persistenceInstance.on('error', (error) => {\n markSyncError(error)\n })\n }\n } else {\n provider.on('connect', () => {\n clearSyncError()\n clearInitialSyncTimer()\n initialSyncTimer = setTimeout(() => {\n markSynced(true)\n }, INITIAL_SYNC_MS)\n })\n provider.on('message', () => Line truncated
|
||||
"type": "registry:hook"
|
||||
},
|
||||
{
|
||||
"path": "registry/default/blocks/realtime-flow/components/realtime-flow.tsx",
|
||||
"content": "'use client'\n\nimport {\n ReactFlow,\n ReactFlowProvider,\n Background,\n Controls,\n type Node,\n type Edge,\n type NodeTypes,\n type EdgeTypes,\n} from '@xyflow/react'\nimport '@xyflow/react/dist/style.css'\nimport type { SupabasePersistenceOptions } from '@supabase-labs/y-supabase'\n\nimport { RealtimeFlowOverlay } from './realtime-flow-overlay'\nimport { useRealtimeFlow } from '../hooks/use-realtime-flow'\n\ntype RealtimeFlowProps = {\n channel: string\n className?: string\n style?: React.CSSProperties\n persistence?: boolean | SupabasePersistenceOptions\n initialNodes?: Node[]\n initialEdges?: Edge[]\n nodeTypes?: NodeTypes\n edgeTypes?: EdgeTypes\n height?: string | number\n}\n\nconst DEFAULT_HEIGHT = 550\n\nconst RealtimeFlowContent = ({\n channel,\n className,\n style,\n persistence,\n initialNodes,\n initialEdges,\n nodeTypes,\n edgeTypes,\n height = DEFAULT_HEIGHT,\n}: RealtimeFlowProps) => {\n const { nodes, edges, synced, syncError, onNodesChange, onEdgesChange, onConnect } =\n useRealtimeFlow({\n channel,\n persistence,\n initialNodes,\n initialEdges,\n })\n\n return (\n <div style={{ height, position: 'relative', ...style }} className={className}>\n <ReactFlow\n nodes={synced ? nodes : []}\n edges={synced ? edges : []}\n onNodesChange={synced ? onNodesChange : undefined}\n onEdgesChange={synced ? onEdgesChange : undefined}\n onConnect={synced ? onConnect : undefined}\n nodeTypes={nodeTypes}\n edgeTypes={edgeTypes}\n fitView\n >\n <Background />\n <Controls />\n </ReactFlow>\n {!synced && !syncError && <RealtimeFlowOverlay status=\"syncing\" />}\n {!synced && syncError && <RealtimeFlowOverlay status=\"error\" message={syncError} />}\n </div>\n )\n}\n\nconst RealtimeFlow = (props: RealtimeFlowProps) => (\n <ReactFlowProvider>\n <RealtimeFlowContent {...props} />\n </ReactFlowProvider>\n)\n\nexport { RealtimeFlow }\n",
|
||||
"type": "registry:component"
|
||||
},
|
||||
{
|
||||
"path": "registry/default/clients/tanstack/lib/supabase/client.ts",
|
||||
"content": "/// <reference types=\"vite/types/importMeta.d.ts\" />\nimport { createBrowserClient } from '@supabase/ssr'\n\nexport function createClient() {\n return createBrowserClient(\n import.meta.env.VITE_SUPABASE_URL!,\n import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY!\n )\n}\n",
|
||||
"type": "registry:lib"
|
||||
},
|
||||
{
|
||||
"path": "registry/default/clients/tanstack/lib/supabase/server.ts",
|
||||
"content": "import { createServerClient } from '@supabase/ssr'\nimport { getCookies, setCookie } from '@tanstack/react-start/server'\n\nexport function createClient() {\n return createServerClient(\n process.env.VITE_SUPABASE_URL!,\n process.env.VITE_SUPABASE_PUBLISHABLE_KEY!,\n {\n cookies: {\n getAll() {\n return Object.entries(getCookies()).map(\n ([name, value]) =>\n ({\n name,\n value,\n }) as { name: string; value: string }\n )\n },\n setAll(cookies) {\n cookies.forEach((cookie) => {\n setCookie(cookie.name, cookie.value)\n })\n },\n },\n }\n )\n}\n",
|
||||
"type": "registry:lib"
|
||||
}
|
||||
],
|
||||
"envVars": {
|
||||
"VITE_SUPABASE_URL": "",
|
||||
"VITE_SUPABASE_PUBLISHABLE_KEY": ""
|
||||
},
|
||||
"docs": "You'll need to set the following environment variables in your project: `VITE_SUPABASE_URL` and `VITE_SUPABASE_PUBLISHABLE_KEY`."
|
||||
}
|
||||
@@ -15,7 +15,7 @@
|
||||
"files": [
|
||||
{
|
||||
"path": "registry/default/blocks/realtime-monaco/hooks/use-connect-on-mount.ts",
|
||||
"content": "'use client'\n\nimport { SupabasePersistenceOptions, SupabaseProvider } from '@supabase-labs/y-supabase'\nimport type { editor as MonacoEditor } from 'monaco-editor'\nimport { useCallback, useEffect, useRef } from 'react'\nimport { MonacoBinding } from 'y-monaco'\nimport { Awareness } from 'y-protocols/awareness'\nimport * as Y from 'yjs'\n\nimport { createClient } from '@/registry/default/clients/nextjs/lib/supabase/client'\n\ntype UseConnectOnMountOptions = {\n channel: string\n persistence?: boolean | SupabasePersistenceOptions\n awareness?: boolean | Awareness\n}\n\nconst generateRandomColor = () => `hsl(${Math.floor(Math.random() * 360)}, 80%, 60%)`\n\nexport function useConnectOnMount({\n channel,\n persistence,\n awareness = true,\n}: UseConnectOnMountOptions) {\n const docRef = useRef<Y.Doc | null>(null)\n const providerRef = useRef<SupabaseProvider | null>(null)\n const bindingRef = useRef<MonacoBinding | null>(null)\n const userRef = useRef<{ color: string } | null>(null)\n const styleRef = useRef<HTMLStyleElement | null>(null)\n const awarenessHandlerRef = useRef<(() => void) | null>(null)\n\n const connectOnMount = useCallback(\n (editor: MonacoEditor.IStandaloneCodeEditor) => {\n if (bindingRef.current) return\n\n const model = editor.getModel()\n if (!model) return\n\n const doc = new Y.Doc()\n const yText = doc.getText('monaco')\n const supabase = createClient()\n const provider = new SupabaseProvider(channel, doc, supabase as any, {\n awareness,\n persistence,\n })\n const providerAwareness = provider.getAwareness()\n\n if (providerAwareness) {\n if (!userRef.current) {\n userRef.current = {\n color: generateRandomColor(),\n }\n }\n providerAwareness.setLocalStateField('user', userRef.current)\n\n const applyAwarenessStyles = () => {\n if (!styleRef.current) {\n styleRef.current = document.createElement('style')\n styleRef.current.setAttribute('data-monaco-y-cursors', 'true')\n document.head.appendChild(styleRef.current)\n }\n\n let css = `\n .yRemoteSelection {\n background-color: var(--y-remote-selection-color, rgba(0, 0, 0, 0.2));\n opacity: 0.2;\n }\n .yRemoteSelectionHead {\n border-left: 2px solid var(--y-remote-selection-color, rgba(0, 0, 0, 0.7));\n margin-left: -1px;\n box-sizing: border-box;\n }\n `\n\n providerAwareness.getStates().forEach((state, clientId) => {\n const color = state?.user?.color\n const isValidHsl = /^hsl\\(\\d{1,3},\\s*\\d{1,3}%,\\s*\\d{1,3}%\\)$/.test(color)\n\n if (!isValidHsl) return\n if (!color) return\n\n css += `\n .yRemoteSelection-${clientId}, .yRemoteSelectionHead-${clientId} {\n --y-remote-selection-color: ${color};\n }\n `\n })\n\n styleRef.current.textContent = css\n }\n\n awarenessHandlerRef.current = applyAwarenessStyles\n applyAwarenessStyles()\n providerAwareness.on('update', applyAwarenessStyles)\n }\n\n docRef.current = doc\n providerRef.current = provider\n bindingRef.current = new MonacoBinding(yText, model, new Set([editor]), providerAwareness)\n },\n [channel]\n )\n\n useEffect(() => {\n return () => {\n if (awarenessHandlerRef.current && providerRef.current) {\n const awareness = providerRef.current.getAwareness()\n awareness?.off('update', awarenessHandlerRef.current)\n }\n styleRef.current?.remove()\n bindingRef.current?.destroy()\n bindingRef.current = null\n providerRef.current?.destroy()\n providerRef.current = null\n docRef.current?.destroy()\n docRef.current = null\n }\n }, [])\n\n return { connectOnMount }\n}\n",
|
||||
"content": "'use client'\n\nimport { SupabasePersistenceOptions, SupabaseProvider } from '@supabase-labs/y-supabase'\nimport type { editor as MonacoEditor } from 'monaco-editor'\nimport { useCallback, useEffect, useRef } from 'react'\nimport { MonacoBinding } from 'y-monaco'\nimport { Awareness } from 'y-protocols/awareness'\nimport * as Y from 'yjs'\n\nimport { createClient } from '@/registry/default/clients/react-router/lib/supabase/client'\n\ntype UseConnectOnMountOptions = {\n channel: string\n persistence?: boolean | SupabasePersistenceOptions\n awareness?: boolean | Awareness\n}\n\nconst generateRandomColor = () => `hsl(${Math.floor(Math.random() * 360)}, 80%, 60%)`\n\nexport function useConnectOnMount({\n channel,\n persistence,\n awareness = true,\n}: UseConnectOnMountOptions) {\n const docRef = useRef<Y.Doc | null>(null)\n const providerRef = useRef<SupabaseProvider | null>(null)\n const bindingRef = useRef<MonacoBinding | null>(null)\n const userRef = useRef<{ color: string } | null>(null)\n const styleRef = useRef<HTMLStyleElement | null>(null)\n const awarenessHandlerRef = useRef<(() => void) | null>(null)\n\n const connectOnMount = useCallback(\n (editor: MonacoEditor.IStandaloneCodeEditor) => {\n if (bindingRef.current) return\n\n const model = editor.getModel()\n if (!model) return\n\n const doc = new Y.Doc()\n const yText = doc.getText('monaco')\n const supabase = createClient()\n const provider = new SupabaseProvider(channel, doc, supabase as any, {\n awareness,\n persistence,\n })\n const providerAwareness = provider.getAwareness()\n\n if (providerAwareness) {\n if (!userRef.current) {\n userRef.current = {\n color: generateRandomColor(),\n }\n }\n providerAwareness.setLocalStateField('user', userRef.current)\n\n const applyAwarenessStyles = () => {\n if (!styleRef.current) {\n styleRef.current = document.createElement('style')\n styleRef.current.setAttribute('data-monaco-y-cursors', 'true')\n document.head.appendChild(styleRef.current)\n }\n\n let css = `\n .yRemoteSelection {\n background-color: var(--y-remote-selection-color, rgba(0, 0, 0, 0.2));\n opacity: 0.2;\n }\n .yRemoteSelectionHead {\n border-left: 2px solid var(--y-remote-selection-color, rgba(0, 0, 0, 0.7));\n margin-left: -1px;\n box-sizing: border-box;\n }\n `\n\n providerAwareness.getStates().forEach((state, clientId) => {\n const color = state?.user?.color\n const isValidHsl = /^hsl\\(\\d{1,3},\\s*\\d{1,3}%,\\s*\\d{1,3}%\\)$/.test(color)\n\n if (!isValidHsl) return\n if (!color) return\n\n css += `\n .yRemoteSelection-${clientId}, .yRemoteSelectionHead-${clientId} {\n --y-remote-selection-color: ${color};\n }\n `\n })\n\n styleRef.current.textContent = css\n }\n\n awarenessHandlerRef.current = applyAwarenessStyles\n applyAwarenessStyles()\n providerAwareness.on('update', applyAwarenessStyles)\n }\n\n docRef.current = doc\n providerRef.current = provider\n bindingRef.current = new MonacoBinding(yText, model, new Set([editor]), providerAwareness)\n },\n [channel]\n )\n\n useEffect(() => {\n return () => {\n if (awarenessHandlerRef.current && providerRef.current) {\n const awareness = providerRef.current.getAwareness()\n awareness?.off('update', awarenessHandlerRef.current)\n }\n styleRef.current?.remove()\n bindingRef.current?.destroy()\n bindingRef.current = null\n providerRef.current?.destroy()\n providerRef.current = null\n docRef.current?.destroy()\n docRef.current = null\n }\n }, [])\n\n return { connectOnMount }\n}\n",
|
||||
"type": "registry:hook"
|
||||
},
|
||||
{
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
"files": [
|
||||
{
|
||||
"path": "registry/default/blocks/realtime-monaco/hooks/use-connect-on-mount.ts",
|
||||
"content": "'use client'\n\nimport { SupabasePersistenceOptions, SupabaseProvider } from '@supabase-labs/y-supabase'\nimport type { editor as MonacoEditor } from 'monaco-editor'\nimport { useCallback, useEffect, useRef } from 'react'\nimport { MonacoBinding } from 'y-monaco'\nimport { Awareness } from 'y-protocols/awareness'\nimport * as Y from 'yjs'\n\nimport { createClient } from '@/registry/default/clients/nextjs/lib/supabase/client'\n\ntype UseConnectOnMountOptions = {\n channel: string\n persistence?: boolean | SupabasePersistenceOptions\n awareness?: boolean | Awareness\n}\n\nconst generateRandomColor = () => `hsl(${Math.floor(Math.random() * 360)}, 80%, 60%)`\n\nexport function useConnectOnMount({\n channel,\n persistence,\n awareness = true,\n}: UseConnectOnMountOptions) {\n const docRef = useRef<Y.Doc | null>(null)\n const providerRef = useRef<SupabaseProvider | null>(null)\n const bindingRef = useRef<MonacoBinding | null>(null)\n const userRef = useRef<{ color: string } | null>(null)\n const styleRef = useRef<HTMLStyleElement | null>(null)\n const awarenessHandlerRef = useRef<(() => void) | null>(null)\n\n const connectOnMount = useCallback(\n (editor: MonacoEditor.IStandaloneCodeEditor) => {\n if (bindingRef.current) return\n\n const model = editor.getModel()\n if (!model) return\n\n const doc = new Y.Doc()\n const yText = doc.getText('monaco')\n const supabase = createClient()\n const provider = new SupabaseProvider(channel, doc, supabase as any, {\n awareness,\n persistence,\n })\n const providerAwareness = provider.getAwareness()\n\n if (providerAwareness) {\n if (!userRef.current) {\n userRef.current = {\n color: generateRandomColor(),\n }\n }\n providerAwareness.setLocalStateField('user', userRef.current)\n\n const applyAwarenessStyles = () => {\n if (!styleRef.current) {\n styleRef.current = document.createElement('style')\n styleRef.current.setAttribute('data-monaco-y-cursors', 'true')\n document.head.appendChild(styleRef.current)\n }\n\n let css = `\n .yRemoteSelection {\n background-color: var(--y-remote-selection-color, rgba(0, 0, 0, 0.2));\n opacity: 0.2;\n }\n .yRemoteSelectionHead {\n border-left: 2px solid var(--y-remote-selection-color, rgba(0, 0, 0, 0.7));\n margin-left: -1px;\n box-sizing: border-box;\n }\n `\n\n providerAwareness.getStates().forEach((state, clientId) => {\n const color = state?.user?.color\n const isValidHsl = /^hsl\\(\\d{1,3},\\s*\\d{1,3}%,\\s*\\d{1,3}%\\)$/.test(color)\n\n if (!isValidHsl) return\n if (!color) return\n\n css += `\n .yRemoteSelection-${clientId}, .yRemoteSelectionHead-${clientId} {\n --y-remote-selection-color: ${color};\n }\n `\n })\n\n styleRef.current.textContent = css\n }\n\n awarenessHandlerRef.current = applyAwarenessStyles\n applyAwarenessStyles()\n providerAwareness.on('update', applyAwarenessStyles)\n }\n\n docRef.current = doc\n providerRef.current = provider\n bindingRef.current = new MonacoBinding(yText, model, new Set([editor]), providerAwareness)\n },\n [channel]\n )\n\n useEffect(() => {\n return () => {\n if (awarenessHandlerRef.current && providerRef.current) {\n const awareness = providerRef.current.getAwareness()\n awareness?.off('update', awarenessHandlerRef.current)\n }\n styleRef.current?.remove()\n bindingRef.current?.destroy()\n bindingRef.current = null\n providerRef.current?.destroy()\n providerRef.current = null\n docRef.current?.destroy()\n docRef.current = null\n }\n }, [])\n\n return { connectOnMount }\n}\n",
|
||||
"content": "'use client'\n\nimport { SupabasePersistenceOptions, SupabaseProvider } from '@supabase-labs/y-supabase'\nimport type { editor as MonacoEditor } from 'monaco-editor'\nimport { useCallback, useEffect, useRef } from 'react'\nimport { MonacoBinding } from 'y-monaco'\nimport { Awareness } from 'y-protocols/awareness'\nimport * as Y from 'yjs'\n\nimport { createClient } from '@/registry/default/clients/react/lib/supabase/client'\n\ntype UseConnectOnMountOptions = {\n channel: string\n persistence?: boolean | SupabasePersistenceOptions\n awareness?: boolean | Awareness\n}\n\nconst generateRandomColor = () => `hsl(${Math.floor(Math.random() * 360)}, 80%, 60%)`\n\nexport function useConnectOnMount({\n channel,\n persistence,\n awareness = true,\n}: UseConnectOnMountOptions) {\n const docRef = useRef<Y.Doc | null>(null)\n const providerRef = useRef<SupabaseProvider | null>(null)\n const bindingRef = useRef<MonacoBinding | null>(null)\n const userRef = useRef<{ color: string } | null>(null)\n const styleRef = useRef<HTMLStyleElement | null>(null)\n const awarenessHandlerRef = useRef<(() => void) | null>(null)\n\n const connectOnMount = useCallback(\n (editor: MonacoEditor.IStandaloneCodeEditor) => {\n if (bindingRef.current) return\n\n const model = editor.getModel()\n if (!model) return\n\n const doc = new Y.Doc()\n const yText = doc.getText('monaco')\n const supabase = createClient()\n const provider = new SupabaseProvider(channel, doc, supabase as any, {\n awareness,\n persistence,\n })\n const providerAwareness = provider.getAwareness()\n\n if (providerAwareness) {\n if (!userRef.current) {\n userRef.current = {\n color: generateRandomColor(),\n }\n }\n providerAwareness.setLocalStateField('user', userRef.current)\n\n const applyAwarenessStyles = () => {\n if (!styleRef.current) {\n styleRef.current = document.createElement('style')\n styleRef.current.setAttribute('data-monaco-y-cursors', 'true')\n document.head.appendChild(styleRef.current)\n }\n\n let css = `\n .yRemoteSelection {\n background-color: var(--y-remote-selection-color, rgba(0, 0, 0, 0.2));\n opacity: 0.2;\n }\n .yRemoteSelectionHead {\n border-left: 2px solid var(--y-remote-selection-color, rgba(0, 0, 0, 0.7));\n margin-left: -1px;\n box-sizing: border-box;\n }\n `\n\n providerAwareness.getStates().forEach((state, clientId) => {\n const color = state?.user?.color\n const isValidHsl = /^hsl\\(\\d{1,3},\\s*\\d{1,3}%,\\s*\\d{1,3}%\\)$/.test(color)\n\n if (!isValidHsl) return\n if (!color) return\n\n css += `\n .yRemoteSelection-${clientId}, .yRemoteSelectionHead-${clientId} {\n --y-remote-selection-color: ${color};\n }\n `\n })\n\n styleRef.current.textContent = css\n }\n\n awarenessHandlerRef.current = applyAwarenessStyles\n applyAwarenessStyles()\n providerAwareness.on('update', applyAwarenessStyles)\n }\n\n docRef.current = doc\n providerRef.current = provider\n bindingRef.current = new MonacoBinding(yText, model, new Set([editor]), providerAwareness)\n },\n [channel]\n )\n\n useEffect(() => {\n return () => {\n if (awarenessHandlerRef.current && providerRef.current) {\n const awareness = providerRef.current.getAwareness()\n awareness?.off('update', awarenessHandlerRef.current)\n }\n styleRef.current?.remove()\n bindingRef.current?.destroy()\n bindingRef.current = null\n providerRef.current?.destroy()\n providerRef.current = null\n docRef.current?.destroy()\n docRef.current = null\n }\n }, [])\n\n return { connectOnMount }\n}\n",
|
||||
"type": "registry:hook"
|
||||
},
|
||||
{
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
"files": [
|
||||
{
|
||||
"path": "registry/default/blocks/realtime-monaco/hooks/use-connect-on-mount.ts",
|
||||
"content": "'use client'\n\nimport { SupabasePersistenceOptions, SupabaseProvider } from '@supabase-labs/y-supabase'\nimport type { editor as MonacoEditor } from 'monaco-editor'\nimport { useCallback, useEffect, useRef } from 'react'\nimport { MonacoBinding } from 'y-monaco'\nimport { Awareness } from 'y-protocols/awareness'\nimport * as Y from 'yjs'\n\nimport { createClient } from '@/registry/default/clients/nextjs/lib/supabase/client'\n\ntype UseConnectOnMountOptions = {\n channel: string\n persistence?: boolean | SupabasePersistenceOptions\n awareness?: boolean | Awareness\n}\n\nconst generateRandomColor = () => `hsl(${Math.floor(Math.random() * 360)}, 80%, 60%)`\n\nexport function useConnectOnMount({\n channel,\n persistence,\n awareness = true,\n}: UseConnectOnMountOptions) {\n const docRef = useRef<Y.Doc | null>(null)\n const providerRef = useRef<SupabaseProvider | null>(null)\n const bindingRef = useRef<MonacoBinding | null>(null)\n const userRef = useRef<{ color: string } | null>(null)\n const styleRef = useRef<HTMLStyleElement | null>(null)\n const awarenessHandlerRef = useRef<(() => void) | null>(null)\n\n const connectOnMount = useCallback(\n (editor: MonacoEditor.IStandaloneCodeEditor) => {\n if (bindingRef.current) return\n\n const model = editor.getModel()\n if (!model) return\n\n const doc = new Y.Doc()\n const yText = doc.getText('monaco')\n const supabase = createClient()\n const provider = new SupabaseProvider(channel, doc, supabase as any, {\n awareness,\n persistence,\n })\n const providerAwareness = provider.getAwareness()\n\n if (providerAwareness) {\n if (!userRef.current) {\n userRef.current = {\n color: generateRandomColor(),\n }\n }\n providerAwareness.setLocalStateField('user', userRef.current)\n\n const applyAwarenessStyles = () => {\n if (!styleRef.current) {\n styleRef.current = document.createElement('style')\n styleRef.current.setAttribute('data-monaco-y-cursors', 'true')\n document.head.appendChild(styleRef.current)\n }\n\n let css = `\n .yRemoteSelection {\n background-color: var(--y-remote-selection-color, rgba(0, 0, 0, 0.2));\n opacity: 0.2;\n }\n .yRemoteSelectionHead {\n border-left: 2px solid var(--y-remote-selection-color, rgba(0, 0, 0, 0.7));\n margin-left: -1px;\n box-sizing: border-box;\n }\n `\n\n providerAwareness.getStates().forEach((state, clientId) => {\n const color = state?.user?.color\n const isValidHsl = /^hsl\\(\\d{1,3},\\s*\\d{1,3}%,\\s*\\d{1,3}%\\)$/.test(color)\n\n if (!isValidHsl) return\n if (!color) return\n\n css += `\n .yRemoteSelection-${clientId}, .yRemoteSelectionHead-${clientId} {\n --y-remote-selection-color: ${color};\n }\n `\n })\n\n styleRef.current.textContent = css\n }\n\n awarenessHandlerRef.current = applyAwarenessStyles\n applyAwarenessStyles()\n providerAwareness.on('update', applyAwarenessStyles)\n }\n\n docRef.current = doc\n providerRef.current = provider\n bindingRef.current = new MonacoBinding(yText, model, new Set([editor]), providerAwareness)\n },\n [channel]\n )\n\n useEffect(() => {\n return () => {\n if (awarenessHandlerRef.current && providerRef.current) {\n const awareness = providerRef.current.getAwareness()\n awareness?.off('update', awarenessHandlerRef.current)\n }\n styleRef.current?.remove()\n bindingRef.current?.destroy()\n bindingRef.current = null\n providerRef.current?.destroy()\n providerRef.current = null\n docRef.current?.destroy()\n docRef.current = null\n }\n }, [])\n\n return { connectOnMount }\n}\n",
|
||||
"content": "'use client'\n\nimport { SupabasePersistenceOptions, SupabaseProvider } from '@supabase-labs/y-supabase'\nimport type { editor as MonacoEditor } from 'monaco-editor'\nimport { useCallback, useEffect, useRef } from 'react'\nimport { MonacoBinding } from 'y-monaco'\nimport { Awareness } from 'y-protocols/awareness'\nimport * as Y from 'yjs'\n\nimport { createClient } from '@/registry/default/clients/tanstack/lib/supabase/client'\n\ntype UseConnectOnMountOptions = {\n channel: string\n persistence?: boolean | SupabasePersistenceOptions\n awareness?: boolean | Awareness\n}\n\nconst generateRandomColor = () => `hsl(${Math.floor(Math.random() * 360)}, 80%, 60%)`\n\nexport function useConnectOnMount({\n channel,\n persistence,\n awareness = true,\n}: UseConnectOnMountOptions) {\n const docRef = useRef<Y.Doc | null>(null)\n const providerRef = useRef<SupabaseProvider | null>(null)\n const bindingRef = useRef<MonacoBinding | null>(null)\n const userRef = useRef<{ color: string } | null>(null)\n const styleRef = useRef<HTMLStyleElement | null>(null)\n const awarenessHandlerRef = useRef<(() => void) | null>(null)\n\n const connectOnMount = useCallback(\n (editor: MonacoEditor.IStandaloneCodeEditor) => {\n if (bindingRef.current) return\n\n const model = editor.getModel()\n if (!model) return\n\n const doc = new Y.Doc()\n const yText = doc.getText('monaco')\n const supabase = createClient()\n const provider = new SupabaseProvider(channel, doc, supabase as any, {\n awareness,\n persistence,\n })\n const providerAwareness = provider.getAwareness()\n\n if (providerAwareness) {\n if (!userRef.current) {\n userRef.current = {\n color: generateRandomColor(),\n }\n }\n providerAwareness.setLocalStateField('user', userRef.current)\n\n const applyAwarenessStyles = () => {\n if (!styleRef.current) {\n styleRef.current = document.createElement('style')\n styleRef.current.setAttribute('data-monaco-y-cursors', 'true')\n document.head.appendChild(styleRef.current)\n }\n\n let css = `\n .yRemoteSelection {\n background-color: var(--y-remote-selection-color, rgba(0, 0, 0, 0.2));\n opacity: 0.2;\n }\n .yRemoteSelectionHead {\n border-left: 2px solid var(--y-remote-selection-color, rgba(0, 0, 0, 0.7));\n margin-left: -1px;\n box-sizing: border-box;\n }\n `\n\n providerAwareness.getStates().forEach((state, clientId) => {\n const color = state?.user?.color\n const isValidHsl = /^hsl\\(\\d{1,3},\\s*\\d{1,3}%,\\s*\\d{1,3}%\\)$/.test(color)\n\n if (!isValidHsl) return\n if (!color) return\n\n css += `\n .yRemoteSelection-${clientId}, .yRemoteSelectionHead-${clientId} {\n --y-remote-selection-color: ${color};\n }\n `\n })\n\n styleRef.current.textContent = css\n }\n\n awarenessHandlerRef.current = applyAwarenessStyles\n applyAwarenessStyles()\n providerAwareness.on('update', applyAwarenessStyles)\n }\n\n docRef.current = doc\n providerRef.current = provider\n bindingRef.current = new MonacoBinding(yText, model, new Set([editor]), providerAwareness)\n },\n [channel]\n )\n\n useEffect(() => {\n return () => {\n if (awarenessHandlerRef.current && providerRef.current) {\n const awareness = providerRef.current.getAwareness()\n awareness?.off('update', awarenessHandlerRef.current)\n }\n styleRef.current?.remove()\n bindingRef.current?.destroy()\n bindingRef.current = null\n providerRef.current?.destroy()\n providerRef.current = null\n docRef.current?.destroy()\n docRef.current = null\n }\n }, [])\n\n return { connectOnMount }\n}\n",
|
||||
"type": "registry:hook"
|
||||
},
|
||||
{
|
||||
|
||||
@@ -1399,6 +1399,161 @@
|
||||
"VITE_SUPABASE_PUBLISHABLE_KEY": ""
|
||||
}
|
||||
},
|
||||
{
|
||||
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
||||
"name": "realtime-flow-nextjs",
|
||||
"type": "registry:component",
|
||||
"title": "Realtime Flow",
|
||||
"description": "Real-time flow diagram editor for collaborative applications.",
|
||||
"registryDependencies": [],
|
||||
"dependencies": [
|
||||
"@xyflow/react@latest",
|
||||
"@supabase-labs/y-supabase@latest",
|
||||
"y-protocols@latest",
|
||||
"yjs@latest",
|
||||
"@supabase/ssr@latest",
|
||||
"@supabase/supabase-js@latest"
|
||||
],
|
||||
"files": [
|
||||
{
|
||||
"path": "registry/default/blocks/realtime-flow/hooks/use-realtime-flow.ts",
|
||||
"type": "registry:hook"
|
||||
},
|
||||
{
|
||||
"path": "registry/default/blocks/realtime-flow/components/realtime-flow.tsx",
|
||||
"type": "registry:component"
|
||||
},
|
||||
{
|
||||
"path": "registry/default/clients/nextjs/lib/supabase/client.ts",
|
||||
"type": "registry:lib"
|
||||
},
|
||||
{
|
||||
"path": "registry/default/clients/nextjs/lib/supabase/middleware.ts",
|
||||
"type": "registry:lib"
|
||||
},
|
||||
{
|
||||
"path": "registry/default/clients/nextjs/lib/supabase/server.ts",
|
||||
"type": "registry:lib"
|
||||
}
|
||||
],
|
||||
"docs": "You'll need to set the following environment variables in your project: `NEXT_PUBLIC_SUPABASE_URL` and `NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY`.",
|
||||
"envVars": {
|
||||
"NEXT_PUBLIC_SUPABASE_URL": "",
|
||||
"NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY": ""
|
||||
}
|
||||
},
|
||||
{
|
||||
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
||||
"name": "realtime-flow-react",
|
||||
"type": "registry:component",
|
||||
"title": "Realtime Flow",
|
||||
"description": "Real-time flow diagram editor for collaborative applications.",
|
||||
"registryDependencies": [],
|
||||
"dependencies": [
|
||||
"@xyflow/react@latest",
|
||||
"@supabase-labs/y-supabase@latest",
|
||||
"y-protocols@latest",
|
||||
"yjs@latest",
|
||||
"@supabase/supabase-js@latest"
|
||||
],
|
||||
"files": [
|
||||
{
|
||||
"path": "registry/default/blocks/realtime-flow/hooks/use-realtime-flow.ts",
|
||||
"type": "registry:hook"
|
||||
},
|
||||
{
|
||||
"path": "registry/default/blocks/realtime-flow/components/realtime-flow.tsx",
|
||||
"type": "registry:component"
|
||||
},
|
||||
{
|
||||
"path": "registry/default/clients/react/lib/supabase/client.ts",
|
||||
"type": "registry:lib"
|
||||
}
|
||||
],
|
||||
"docs": "You'll need to set the following environment variables in your project: `VITE_SUPABASE_URL` and `VITE_SUPABASE_PUBLISHABLE_KEY`.",
|
||||
"envVars": {
|
||||
"VITE_SUPABASE_URL": "",
|
||||
"VITE_SUPABASE_PUBLISHABLE_KEY": ""
|
||||
}
|
||||
},
|
||||
{
|
||||
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
||||
"name": "realtime-flow-react-router",
|
||||
"type": "registry:component",
|
||||
"title": "Realtime Flow",
|
||||
"description": "Real-time flow diagram editor for collaborative applications.",
|
||||
"registryDependencies": [],
|
||||
"dependencies": [
|
||||
"@xyflow/react@latest",
|
||||
"@supabase-labs/y-supabase@latest",
|
||||
"y-protocols@latest",
|
||||
"yjs@latest",
|
||||
"@supabase/ssr@latest",
|
||||
"@supabase/supabase-js@latest"
|
||||
],
|
||||
"files": [
|
||||
{
|
||||
"path": "registry/default/blocks/realtime-flow/hooks/use-realtime-flow.ts",
|
||||
"type": "registry:hook"
|
||||
},
|
||||
{
|
||||
"path": "registry/default/blocks/realtime-flow/components/realtime-flow.tsx",
|
||||
"type": "registry:component"
|
||||
},
|
||||
{
|
||||
"path": "registry/default/clients/react-router/lib/supabase/client.ts",
|
||||
"type": "registry:lib"
|
||||
},
|
||||
{
|
||||
"path": "registry/default/clients/react-router/lib/supabase/server.ts",
|
||||
"type": "registry:lib"
|
||||
}
|
||||
],
|
||||
"docs": "You'll need to set the following environment variables in your project: `VITE_SUPABASE_URL` and `VITE_SUPABASE_PUBLISHABLE_KEY`.",
|
||||
"envVars": {
|
||||
"VITE_SUPABASE_URL": "",
|
||||
"VITE_SUPABASE_PUBLISHABLE_KEY": ""
|
||||
}
|
||||
},
|
||||
{
|
||||
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
||||
"name": "realtime-flow-tanstack",
|
||||
"type": "registry:component",
|
||||
"title": "Realtime Flow",
|
||||
"description": "Real-time flow diagram editor for collaborative applications.",
|
||||
"registryDependencies": [],
|
||||
"dependencies": [
|
||||
"@xyflow/react@latest",
|
||||
"@supabase-labs/y-supabase@latest",
|
||||
"y-protocols@latest",
|
||||
"yjs@latest",
|
||||
"@supabase/ssr@latest",
|
||||
"@supabase/supabase-js@latest"
|
||||
],
|
||||
"files": [
|
||||
{
|
||||
"path": "registry/default/blocks/realtime-flow/hooks/use-realtime-flow.ts",
|
||||
"type": "registry:hook"
|
||||
},
|
||||
{
|
||||
"path": "registry/default/blocks/realtime-flow/components/realtime-flow.tsx",
|
||||
"type": "registry:component"
|
||||
},
|
||||
{
|
||||
"path": "registry/default/clients/tanstack/lib/supabase/client.ts",
|
||||
"type": "registry:lib"
|
||||
},
|
||||
{
|
||||
"path": "registry/default/clients/tanstack/lib/supabase/server.ts",
|
||||
"type": "registry:lib"
|
||||
}
|
||||
],
|
||||
"docs": "You'll need to set the following environment variables in your project: `VITE_SUPABASE_URL` and `VITE_SUPABASE_PUBLISHABLE_KEY`.",
|
||||
"envVars": {
|
||||
"VITE_SUPABASE_URL": "",
|
||||
"VITE_SUPABASE_PUBLISHABLE_KEY": ""
|
||||
}
|
||||
},
|
||||
{
|
||||
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
||||
"name": "realtime-monaco-nextjs",
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
"files": [
|
||||
{
|
||||
"path": "registry/default/blocks/social-auth-react/components/login-form.tsx",
|
||||
"content": "'use client'\n\nimport { useState } from 'react'\n\nimport { cn } from '@/lib/utils'\nimport { createClient } from '@/registry/default/clients/nextjs/lib/supabase/client'\nimport { Button } from '@/registry/default/components/ui/button'\nimport {\n Card,\n CardContent,\n CardDescription,\n CardHeader,\n CardTitle,\n} from '@/registry/default/components/ui/card'\n\nexport function LoginForm({ className, ...props }: React.ComponentPropsWithoutRef<'div'>) {\n const [error, setError] = useState<string | null>(null)\n const [isLoading, setIsLoading] = useState(false)\n\n const handleSocialLogin = async (e: React.FormEvent) => {\n e.preventDefault()\n const supabase = createClient()\n setIsLoading(true)\n setError(null)\n\n try {\n const { error } = await supabase.auth.signInWithOAuth({\n provider: 'github',\n })\n\n if (error) throw error\n location.href = '/protected'\n } catch (error: unknown) {\n setError(error instanceof Error ? error.message : 'An error occurred')\n setIsLoading(false)\n }\n }\n\n return (\n <div className={cn('flex flex-col gap-6', className)} {...props}>\n <Card>\n <CardHeader>\n <CardTitle className=\"text-2xl\">Welcome!</CardTitle>\n <CardDescription>Sign in to your account to continue</CardDescription>\n </CardHeader>\n <CardContent>\n <form onSubmit={handleSocialLogin}>\n <div className=\"flex flex-col gap-6\">\n {error && <p className=\"text-sm text-destructive-500\">{error}</p>}\n <Button type=\"submit\" className=\"w-full\" disabled={isLoading}>\n {isLoading ? 'Logging in...' : 'Continue with GitHub'}\n </Button>\n </div>\n </form>\n </CardContent>\n </Card>\n </div>\n )\n}\n",
|
||||
"content": "'use client'\n\nimport { useState } from 'react'\n\nimport { cn } from '@/lib/utils'\nimport { createClient } from '@/registry/default/clients/react/lib/supabase/client'\nimport { Button } from '@/registry/default/components/ui/button'\nimport {\n Card,\n CardContent,\n CardDescription,\n CardHeader,\n CardTitle,\n} from '@/registry/default/components/ui/card'\n\nexport function LoginForm({ className, ...props }: React.ComponentPropsWithoutRef<'div'>) {\n const [error, setError] = useState<string | null>(null)\n const [isLoading, setIsLoading] = useState(false)\n\n const handleSocialLogin = async (e: React.FormEvent) => {\n e.preventDefault()\n const supabase = createClient()\n setIsLoading(true)\n setError(null)\n\n try {\n const { error } = await supabase.auth.signInWithOAuth({\n provider: 'github',\n })\n\n if (error) throw error\n location.href = '/protected'\n } catch (error: unknown) {\n setError(error instanceof Error ? error.message : 'An error occurred')\n setIsLoading(false)\n }\n }\n\n return (\n <div className={cn('flex flex-col gap-6', className)} {...props}>\n <Card>\n <CardHeader>\n <CardTitle className=\"text-2xl\">Welcome!</CardTitle>\n <CardDescription>Sign in to your account to continue</CardDescription>\n </CardHeader>\n <CardContent>\n <form onSubmit={handleSocialLogin}>\n <div className=\"flex flex-col gap-6\">\n {error && <p className=\"text-sm text-destructive-500\">{error}</p>}\n <Button type=\"submit\" className=\"w-full\" disabled={isLoading}>\n {isLoading ? 'Logging in...' : 'Continue with GitHub'}\n </Button>\n </div>\n </form>\n </CardContent>\n </Card>\n </div>\n )\n}\n",
|
||||
"type": "registry:component"
|
||||
},
|
||||
{
|
||||
|
||||
@@ -11,6 +11,7 @@ import passwordBasedAuthTanstack from './default/blocks/password-based-auth-tans
|
||||
import realtimeAvatarStack from './default/blocks/realtime-avatar-stack/registry-item.json' with { type: 'json' }
|
||||
import realtimeChat from './default/blocks/realtime-chat/registry-item.json' with { type: 'json' }
|
||||
import realtimeCursor from './default/blocks/realtime-cursor/registry-item.json' with { type: 'json' }
|
||||
import realtimeFlow from './default/blocks/realtime-flow/registry-item.json' with { type: 'json' }
|
||||
import realtimeMonaco from './default/blocks/realtime-monaco/registry-item.json' with { type: 'json' }
|
||||
import socialAuthNextjs from './default/blocks/social-auth-nextjs/registry-item.json' with { type: 'json' }
|
||||
import socialAuthReactRouter from './default/blocks/social-auth-react-router/registry-item.json' with { type: 'json' }
|
||||
@@ -52,6 +53,7 @@ export const blocks = [
|
||||
...combine(currentUserAvatar as RegistryItem),
|
||||
...combine(realtimeAvatarStack as RegistryItem),
|
||||
...combine(realtimeChat as RegistryItem),
|
||||
...combine(realtimeFlow as RegistryItem),
|
||||
...combine(realtimeMonaco as RegistryItem),
|
||||
// infinite query hook is intentionally not combined with the clients since it depends on clients having database types.
|
||||
infiniteQueryHook as RegistryItem,
|
||||
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
'use client'
|
||||
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
type RealtimeFlowOverlayProps = {
|
||||
status: 'syncing' | 'error'
|
||||
message?: string
|
||||
className?: string
|
||||
}
|
||||
|
||||
const RealtimeFlowOverlay = ({ status, message, className }: RealtimeFlowOverlayProps) => {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'absolute inset-0 z-10 flex items-center justify-center bg-background/80 px-6 text-center backdrop-blur-[2px]',
|
||||
className
|
||||
)}
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
'text-sm',
|
||||
status === 'error' ? 'font-medium text-destructive' : 'text-muted-foreground'
|
||||
)}
|
||||
>
|
||||
{status === 'error' ? message || 'Failed to sync flow' : 'Syncing…'}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export { RealtimeFlowOverlay }
|
||||
@@ -0,0 +1,79 @@
|
||||
'use client'
|
||||
|
||||
import {
|
||||
ReactFlow,
|
||||
ReactFlowProvider,
|
||||
Background,
|
||||
Controls,
|
||||
type Node,
|
||||
type Edge,
|
||||
type NodeTypes,
|
||||
type EdgeTypes,
|
||||
} from '@xyflow/react'
|
||||
import '@xyflow/react/dist/style.css'
|
||||
import type { SupabasePersistenceOptions } from '@supabase-labs/y-supabase'
|
||||
|
||||
import { RealtimeFlowOverlay } from './realtime-flow-overlay'
|
||||
import { useRealtimeFlow } from '../hooks/use-realtime-flow'
|
||||
|
||||
type RealtimeFlowProps = {
|
||||
channel: string
|
||||
className?: string
|
||||
style?: React.CSSProperties
|
||||
persistence?: boolean | SupabasePersistenceOptions
|
||||
initialNodes?: Node[]
|
||||
initialEdges?: Edge[]
|
||||
nodeTypes?: NodeTypes
|
||||
edgeTypes?: EdgeTypes
|
||||
height?: string | number
|
||||
}
|
||||
|
||||
const DEFAULT_HEIGHT = 550
|
||||
|
||||
const RealtimeFlowContent = ({
|
||||
channel,
|
||||
className,
|
||||
style,
|
||||
persistence,
|
||||
initialNodes,
|
||||
initialEdges,
|
||||
nodeTypes,
|
||||
edgeTypes,
|
||||
height = DEFAULT_HEIGHT,
|
||||
}: RealtimeFlowProps) => {
|
||||
const { nodes, edges, synced, syncError, onNodesChange, onEdgesChange, onConnect } =
|
||||
useRealtimeFlow({
|
||||
channel,
|
||||
persistence,
|
||||
initialNodes,
|
||||
initialEdges,
|
||||
})
|
||||
|
||||
return (
|
||||
<div style={{ height, position: 'relative', ...style }} className={className}>
|
||||
<ReactFlow
|
||||
nodes={synced ? nodes : []}
|
||||
edges={synced ? edges : []}
|
||||
onNodesChange={synced ? onNodesChange : undefined}
|
||||
onEdgesChange={synced ? onEdgesChange : undefined}
|
||||
onConnect={synced ? onConnect : undefined}
|
||||
nodeTypes={nodeTypes}
|
||||
edgeTypes={edgeTypes}
|
||||
fitView
|
||||
>
|
||||
<Background />
|
||||
<Controls />
|
||||
</ReactFlow>
|
||||
{!synced && !syncError && <RealtimeFlowOverlay status="syncing" />}
|
||||
{!synced && syncError && <RealtimeFlowOverlay status="error" message={syncError} />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const RealtimeFlow = (props: RealtimeFlowProps) => (
|
||||
<ReactFlowProvider>
|
||||
<RealtimeFlowContent {...props} />
|
||||
</ReactFlowProvider>
|
||||
)
|
||||
|
||||
export { RealtimeFlow }
|
||||
@@ -0,0 +1,342 @@
|
||||
'use client'
|
||||
|
||||
import { type SupabasePersistenceOptions, SupabaseProvider } from '@supabase-labs/y-supabase'
|
||||
import {
|
||||
type Edge,
|
||||
type Node,
|
||||
type NodeChange,
|
||||
type EdgeChange,
|
||||
type Connection,
|
||||
applyNodeChanges,
|
||||
applyEdgeChanges,
|
||||
addEdge,
|
||||
} from '@xyflow/react'
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { Awareness } from 'y-protocols/awareness'
|
||||
import * as Y from 'yjs'
|
||||
|
||||
import { createClient } from '@/registry/default/clients/nextjs/lib/supabase/client'
|
||||
|
||||
type UseRealtimeFlowOptions = {
|
||||
channel: string
|
||||
persistence?: boolean | SupabasePersistenceOptions
|
||||
awareness?: boolean | Awareness
|
||||
initialNodes?: Node[]
|
||||
initialEdges?: Edge[]
|
||||
}
|
||||
|
||||
type SetStateAction<T> = T | ((prev: T) => T)
|
||||
|
||||
const INITIAL_SYNC_MS = 350
|
||||
|
||||
export function useRealtimeFlow({
|
||||
channel,
|
||||
persistence,
|
||||
awareness = true,
|
||||
initialNodes = [],
|
||||
initialEdges = [],
|
||||
}: UseRealtimeFlowOptions) {
|
||||
const [nodes, setNodesState] = useState<Node[]>([])
|
||||
const [edges, setEdgesState] = useState<Edge[]>([])
|
||||
const [synced, setSynced] = useState(false)
|
||||
const [syncError, setSyncError] = useState<string | null>(null)
|
||||
|
||||
const docRef = useRef<Y.Doc | null>(null)
|
||||
const providerRef = useRef<SupabaseProvider | null>(null)
|
||||
const syncedRef = useRef(false)
|
||||
const initialNodesRef = useRef(initialNodes)
|
||||
const initialEdgesRef = useRef(initialEdges)
|
||||
|
||||
useEffect(() => {
|
||||
const doc = new Y.Doc()
|
||||
const yNodes = doc.getMap<string>('nodes')
|
||||
const yEdges = doc.getMap<string>('edges')
|
||||
const initialNodesForChannel = initialNodesRef.current
|
||||
const initialEdgesForChannel = initialEdgesRef.current
|
||||
let initialSyncTimer: ReturnType<typeof setTimeout> | null = null
|
||||
let hasRemoteActivity = false
|
||||
|
||||
const supabase = createClient()
|
||||
const provider = new SupabaseProvider(channel, doc, supabase as any, {
|
||||
awareness,
|
||||
persistence,
|
||||
})
|
||||
|
||||
// Sync Y.Map state to React state
|
||||
const syncNodesFromYjs = () => {
|
||||
const parsed: Node[] = []
|
||||
yNodes.forEach((value) => {
|
||||
try {
|
||||
parsed.push(JSON.parse(value))
|
||||
} catch {}
|
||||
})
|
||||
setNodesState(parsed)
|
||||
}
|
||||
|
||||
const syncEdgesFromYjs = () => {
|
||||
const parsed: Edge[] = []
|
||||
yEdges.forEach((value) => {
|
||||
try {
|
||||
parsed.push(JSON.parse(value))
|
||||
} catch {}
|
||||
})
|
||||
setEdgesState(parsed)
|
||||
}
|
||||
|
||||
const clearInitialSyncTimer = () => {
|
||||
if (initialSyncTimer) {
|
||||
clearTimeout(initialSyncTimer)
|
||||
initialSyncTimer = null
|
||||
}
|
||||
}
|
||||
|
||||
const clearSyncError = () => {
|
||||
setSyncError(null)
|
||||
}
|
||||
|
||||
const seedInitialState = () => {
|
||||
if (yNodes.size === 0 && initialNodesForChannel.length > 0) {
|
||||
doc.transact(() => {
|
||||
for (const node of initialNodesForChannel) {
|
||||
yNodes.set(node.id, JSON.stringify(node))
|
||||
}
|
||||
}, 'local')
|
||||
}
|
||||
|
||||
if (yEdges.size === 0 && initialEdgesForChannel.length > 0) {
|
||||
doc.transact(() => {
|
||||
for (const edge of initialEdgesForChannel) {
|
||||
yEdges.set(edge.id, JSON.stringify(edge))
|
||||
}
|
||||
}, 'local')
|
||||
}
|
||||
}
|
||||
|
||||
const nodesObserver = (event: Y.YMapEvent<string>) => {
|
||||
if (event.transaction.origin === 'local') return
|
||||
hasRemoteActivity = true
|
||||
syncNodesFromYjs()
|
||||
}
|
||||
|
||||
const edgesObserver = (event: Y.YMapEvent<string>) => {
|
||||
if (event.transaction.origin === 'local') return
|
||||
hasRemoteActivity = true
|
||||
syncEdgesFromYjs()
|
||||
}
|
||||
|
||||
yNodes.observe(nodesObserver)
|
||||
yEdges.observe(edgesObserver)
|
||||
|
||||
const markSynced = (shouldSeed = false) => {
|
||||
if (syncedRef.current) return
|
||||
clearInitialSyncTimer()
|
||||
clearSyncError()
|
||||
syncedRef.current = true
|
||||
|
||||
if (shouldSeed && !hasRemoteActivity) {
|
||||
seedInitialState()
|
||||
}
|
||||
|
||||
// Sync React state from Yjs (includes seeded initial data if applied)
|
||||
syncNodesFromYjs()
|
||||
syncEdgesFromYjs()
|
||||
setSynced(true)
|
||||
}
|
||||
|
||||
const markSyncError = (error: Error) => {
|
||||
clearInitialSyncTimer()
|
||||
if (syncedRef.current) return
|
||||
setSyncError(error.message || 'Failed to sync flow')
|
||||
}
|
||||
|
||||
const persistenceInstance = provider.getPersistence()
|
||||
if (persistenceInstance) {
|
||||
// With persistence: wait for persisted state to load
|
||||
if (persistenceInstance.synced) {
|
||||
markSynced()
|
||||
} else {
|
||||
persistenceInstance.on('synced', () => {
|
||||
markSynced()
|
||||
})
|
||||
persistenceInstance.on('error', (error) => {
|
||||
markSyncError(error)
|
||||
})
|
||||
}
|
||||
} else {
|
||||
provider.on('connect', () => {
|
||||
clearSyncError()
|
||||
clearInitialSyncTimer()
|
||||
initialSyncTimer = setTimeout(() => {
|
||||
markSynced(true)
|
||||
}, INITIAL_SYNC_MS)
|
||||
})
|
||||
provider.on('message', () => {
|
||||
hasRemoteActivity = true
|
||||
markSynced()
|
||||
})
|
||||
provider.on('error', (error) => {
|
||||
markSyncError(error)
|
||||
})
|
||||
}
|
||||
|
||||
docRef.current = doc
|
||||
providerRef.current = provider
|
||||
|
||||
return () => {
|
||||
clearInitialSyncTimer()
|
||||
yNodes.unobserve(nodesObserver)
|
||||
yEdges.unobserve(edgesObserver)
|
||||
provider.destroy()
|
||||
doc.destroy()
|
||||
docRef.current = null
|
||||
providerRef.current = null
|
||||
syncedRef.current = false
|
||||
setSynced(false)
|
||||
setSyncError(null)
|
||||
}
|
||||
}, [channel, awareness, persistence])
|
||||
|
||||
const syncNodesToYjs = useCallback((updated: Node[]) => {
|
||||
const doc = docRef.current
|
||||
if (!doc || !syncedRef.current) return
|
||||
|
||||
const yNodes = doc.getMap<string>('nodes')
|
||||
doc.transact(() => {
|
||||
const newIds = new Set(updated.map((n) => n.id))
|
||||
for (const key of Array.from(yNodes.keys())) {
|
||||
if (!newIds.has(key)) yNodes.delete(key)
|
||||
}
|
||||
for (const node of updated) {
|
||||
yNodes.set(node.id, JSON.stringify(node))
|
||||
}
|
||||
}, 'local')
|
||||
}, [])
|
||||
|
||||
const syncEdgesToYjs = useCallback((updated: Edge[]) => {
|
||||
const doc = docRef.current
|
||||
if (!doc || !syncedRef.current) return
|
||||
|
||||
const yEdges = doc.getMap<string>('edges')
|
||||
doc.transact(() => {
|
||||
const newIds = new Set(updated.map((e) => e.id))
|
||||
for (const key of Array.from(yEdges.keys())) {
|
||||
if (!newIds.has(key)) yEdges.delete(key)
|
||||
}
|
||||
for (const edge of updated) {
|
||||
yEdges.set(edge.id, JSON.stringify(edge))
|
||||
}
|
||||
}, 'local')
|
||||
}, [])
|
||||
|
||||
const setNodes = useCallback(
|
||||
(nodesOrUpdater: SetStateAction<Node[]>) => {
|
||||
setNodesState((current) => {
|
||||
const updated =
|
||||
typeof nodesOrUpdater === 'function' ? nodesOrUpdater(current) : nodesOrUpdater
|
||||
syncNodesToYjs(updated)
|
||||
return updated
|
||||
})
|
||||
},
|
||||
[syncNodesToYjs]
|
||||
)
|
||||
|
||||
const setEdges = useCallback(
|
||||
(edgesOrUpdater: SetStateAction<Edge[]>) => {
|
||||
setEdgesState((current) => {
|
||||
const updated =
|
||||
typeof edgesOrUpdater === 'function' ? edgesOrUpdater(current) : edgesOrUpdater
|
||||
syncEdgesToYjs(updated)
|
||||
return updated
|
||||
})
|
||||
},
|
||||
[syncEdgesToYjs]
|
||||
)
|
||||
|
||||
const onNodesChange = useCallback((changes: NodeChange[]) => {
|
||||
setNodesState((currentNodes) => {
|
||||
const updated = applyNodeChanges(changes, currentNodes)
|
||||
|
||||
const doc = docRef.current
|
||||
if (!doc || !syncedRef.current) return updated
|
||||
|
||||
const yNodes = doc.getMap<string>('nodes')
|
||||
|
||||
doc.transact(() => {
|
||||
for (const change of changes) {
|
||||
if (change.type === 'remove') {
|
||||
yNodes.delete(change.id)
|
||||
} else if (change.type === 'add') {
|
||||
yNodes.set(change.item.id, JSON.stringify(change.item))
|
||||
} else {
|
||||
const node = updated.find((n) => n.id === change.id)
|
||||
if (node) {
|
||||
yNodes.set(node.id, JSON.stringify(node))
|
||||
}
|
||||
}
|
||||
}
|
||||
}, 'local')
|
||||
|
||||
return updated
|
||||
})
|
||||
}, [])
|
||||
|
||||
const onEdgesChange = useCallback((changes: EdgeChange[]) => {
|
||||
setEdgesState((currentEdges) => {
|
||||
const updated = applyEdgeChanges(changes, currentEdges)
|
||||
|
||||
const doc = docRef.current
|
||||
if (!doc || !syncedRef.current) return updated
|
||||
|
||||
const yEdges = doc.getMap<string>('edges')
|
||||
|
||||
doc.transact(() => {
|
||||
for (const change of changes) {
|
||||
if (change.type === 'remove') {
|
||||
yEdges.delete(change.id)
|
||||
} else if (change.type === 'add') {
|
||||
yEdges.set(change.item.id, JSON.stringify(change.item))
|
||||
} else {
|
||||
const edge = updated.find((e) => e.id === change.id)
|
||||
if (edge) {
|
||||
yEdges.set(edge.id, JSON.stringify(edge))
|
||||
}
|
||||
}
|
||||
}
|
||||
}, 'local')
|
||||
|
||||
return updated
|
||||
})
|
||||
}, [])
|
||||
|
||||
const onConnect = useCallback((connection: Connection) => {
|
||||
setEdgesState((currentEdges) => {
|
||||
const updated = addEdge(connection, currentEdges)
|
||||
|
||||
const doc = docRef.current
|
||||
if (!doc || !syncedRef.current) return updated
|
||||
|
||||
const yEdges = doc.getMap<string>('edges')
|
||||
const newEdge = updated.find((e) => !currentEdges.some((ce) => ce.id === e.id))
|
||||
|
||||
if (newEdge) {
|
||||
doc.transact(() => {
|
||||
yEdges.set(newEdge.id, JSON.stringify(newEdge))
|
||||
}, 'local')
|
||||
}
|
||||
|
||||
return updated
|
||||
})
|
||||
}, [])
|
||||
|
||||
return {
|
||||
nodes,
|
||||
edges,
|
||||
synced,
|
||||
syncError,
|
||||
onNodesChange,
|
||||
onEdgesChange,
|
||||
onConnect,
|
||||
setNodes,
|
||||
setEdges,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
||||
"name": "realtime-flow",
|
||||
"type": "registry:component",
|
||||
"title": "Realtime Flow",
|
||||
"description": "Real-time flow diagram editor for collaborative applications.",
|
||||
"registryDependencies": [],
|
||||
"dependencies": [
|
||||
"@xyflow/react@latest",
|
||||
"@supabase-labs/y-supabase@latest",
|
||||
"y-protocols@latest",
|
||||
"yjs@latest"
|
||||
],
|
||||
"files": [
|
||||
{
|
||||
"path": "registry/default/blocks/realtime-flow/hooks/use-realtime-flow.ts",
|
||||
"type": "registry:hook"
|
||||
},
|
||||
{
|
||||
"path": "registry/default/blocks/realtime-flow/components/realtime-flow.tsx",
|
||||
"type": "registry:component"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
'use client'
|
||||
|
||||
import {
|
||||
Background,
|
||||
Controls,
|
||||
Handle,
|
||||
Position,
|
||||
ReactFlow,
|
||||
ReactFlowProvider,
|
||||
type Edge,
|
||||
type Node,
|
||||
type NodeProps,
|
||||
} from '@xyflow/react'
|
||||
import '@xyflow/react/dist/style.css'
|
||||
import { memo, useMemo, useRef } from 'react'
|
||||
|
||||
import { RealtimeFlowOverlay } from '../blocks/realtime-flow/components/realtime-flow-overlay'
|
||||
import { useRealtimeFlow } from '../blocks/realtime-flow/hooks/use-realtime-flow'
|
||||
import { Button } from '../components/ui/button'
|
||||
|
||||
const NODE_Y_BASE = 80
|
||||
const NODE_X_BASE = 80
|
||||
const FLOW_NODE_STYLE = {
|
||||
backgroundColor: 'hsl(var(--card))',
|
||||
borderColor: 'hsl(var(--border))',
|
||||
color: 'hsl(var(--card-foreground))',
|
||||
}
|
||||
|
||||
type EditableNodeData = {
|
||||
label: string
|
||||
onLabelChange?: (value: string) => void
|
||||
onRemove?: () => void
|
||||
}
|
||||
|
||||
const EditableNode = memo(({ data }: NodeProps<Node<EditableNodeData>>) => {
|
||||
return (
|
||||
<div className="min-w-56 rounded-xl border border-border bg-card p-3 text-card-foreground shadow-sm">
|
||||
<Handle type="target" position={Position.Top} />
|
||||
<div className="space-y-3">
|
||||
<input
|
||||
className="w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm text-foreground outline-none placeholder:text-muted-foreground"
|
||||
value={data.label}
|
||||
onChange={(event) => data.onLabelChange?.(event.target.value)}
|
||||
placeholder="Write something..."
|
||||
/>
|
||||
<div className="flex justify-end">
|
||||
<Button type="button" size="sm" variant="secondary" onClick={() => data.onRemove?.()}>
|
||||
Remove
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<Handle type="source" position={Position.Bottom} />
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
EditableNode.displayName = 'EditableNode'
|
||||
|
||||
const nodeTypes = {
|
||||
editable: EditableNode,
|
||||
}
|
||||
|
||||
const INITIAL_NODES: Node[] = [
|
||||
{
|
||||
id: 'node-1',
|
||||
type: 'editable',
|
||||
position: { x: 100, y: 100 },
|
||||
data: { label: 'Node 1' },
|
||||
style: FLOW_NODE_STYLE,
|
||||
},
|
||||
{
|
||||
id: 'node-2',
|
||||
type: 'editable',
|
||||
position: { x: 100, y: 300 },
|
||||
data: { label: 'Node 2' },
|
||||
style: FLOW_NODE_STYLE,
|
||||
},
|
||||
]
|
||||
|
||||
const INITIAL_EDGES: Edge[] = [
|
||||
{
|
||||
id: 'edge-1-2',
|
||||
source: 'node-1',
|
||||
target: 'node-2',
|
||||
},
|
||||
]
|
||||
|
||||
const RealtimeFlowDemo = () => {
|
||||
const nextNodeIndexRef = useRef(3)
|
||||
const {
|
||||
nodes,
|
||||
edges,
|
||||
synced,
|
||||
syncError,
|
||||
onNodesChange,
|
||||
onEdgesChange,
|
||||
onConnect,
|
||||
setNodes,
|
||||
setEdges,
|
||||
} = useRealtimeFlow({
|
||||
channel: 'realtime-flow-demo',
|
||||
initialNodes: INITIAL_NODES,
|
||||
initialEdges: INITIAL_EDGES,
|
||||
})
|
||||
|
||||
const displayNodes = useMemo(
|
||||
() =>
|
||||
nodes.map((node) => ({
|
||||
...node,
|
||||
type: 'editable',
|
||||
data: {
|
||||
...(node.data as EditableNodeData),
|
||||
onLabelChange: (value: string) => {
|
||||
setNodes((prev) =>
|
||||
prev.map((n) =>
|
||||
n.id === node.id
|
||||
? { ...n, data: { ...(n.data as EditableNodeData), label: value } }
|
||||
: n
|
||||
)
|
||||
)
|
||||
},
|
||||
onRemove: () => {
|
||||
setNodes((prev) => prev.filter((n) => n.id !== node.id))
|
||||
setEdges((prev) => prev.filter((e) => e.source !== node.id && e.target !== node.id))
|
||||
},
|
||||
},
|
||||
})),
|
||||
[nodes, setNodes, setEdges]
|
||||
)
|
||||
|
||||
return (
|
||||
<ReactFlowProvider>
|
||||
<div className="p-4 space-y-4">
|
||||
<div className="flex justify-end">
|
||||
<Button
|
||||
disabled={!synced}
|
||||
onClick={() => {
|
||||
const nodeNumber = nextNodeIndexRef.current
|
||||
const node: Node = {
|
||||
id: crypto.randomUUID(),
|
||||
type: 'editable',
|
||||
position: {
|
||||
x: NODE_X_BASE,
|
||||
y: NODE_Y_BASE * nodeNumber,
|
||||
},
|
||||
data: {
|
||||
label: `Node ${nodeNumber}`,
|
||||
},
|
||||
style: FLOW_NODE_STYLE,
|
||||
}
|
||||
|
||||
setNodes((prev) => [...prev, node])
|
||||
nextNodeIndexRef.current += 1
|
||||
}}
|
||||
>
|
||||
Add node
|
||||
</Button>
|
||||
</div>
|
||||
<div className="relative h-[550px]">
|
||||
<ReactFlow
|
||||
nodes={synced ? displayNodes : []}
|
||||
edges={synced ? edges : []}
|
||||
onNodesChange={synced ? onNodesChange : undefined}
|
||||
onEdgesChange={synced ? onEdgesChange : undefined}
|
||||
onConnect={synced ? onConnect : undefined}
|
||||
nodeTypes={nodeTypes}
|
||||
fitView
|
||||
>
|
||||
<Background />
|
||||
<Controls />
|
||||
</ReactFlow>
|
||||
{!synced && !syncError && <RealtimeFlowOverlay status="syncing" />}
|
||||
{!synced && syncError && <RealtimeFlowOverlay status="error" message={syncError} />}
|
||||
</div>
|
||||
</div>
|
||||
</ReactFlowProvider>
|
||||
)
|
||||
}
|
||||
|
||||
export default RealtimeFlowDemo
|
||||
@@ -23,6 +23,17 @@ export const examples: RegistryItem[] = [
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'realtime-flow-demo',
|
||||
type: 'registry:example',
|
||||
registryDependencies: [],
|
||||
files: [
|
||||
{
|
||||
path: 'registry/default/examples/realtime-flow-demo.tsx',
|
||||
type: 'registry:example',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'realtime-monaco-demo',
|
||||
type: 'registry:example',
|
||||
|
||||
@@ -21,6 +21,25 @@ function processJsonFile(filePath: string) {
|
||||
// Replace the file origin path to exclude the monorepo structure
|
||||
.replaceAll('node_modules/@supabase/vue-blocks/', '')
|
||||
|
||||
// Blocks that combine() across all client variants hard-code the nextjs
|
||||
// client path in their source. Rewrite that import per-variant so each
|
||||
// generated artifact points at the client file it actually bundles.
|
||||
const variantClientMap: Record<string, string> = {
|
||||
react: 'react',
|
||||
'react-router': 'react-router',
|
||||
tanstack: 'tanstack',
|
||||
}
|
||||
const baseName = path.basename(filePath, '.json')
|
||||
for (const [suffix, clientDir] of Object.entries(variantClientMap)) {
|
||||
if (baseName.endsWith(`-${suffix}`)) {
|
||||
stringified = stringified.replaceAll(
|
||||
'@/registry/default/clients/nextjs/lib/supabase/client',
|
||||
`@/registry/default/clients/${clientDir}/lib/supabase/client`
|
||||
)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// Write back to file
|
||||
fs.writeFileSync(filePath, stringified)
|
||||
console.log(`✓ Updated ${filePath}`)
|
||||
|
||||
Generated
+3
@@ -1392,6 +1392,9 @@ importers:
|
||||
'@tanstack/react-query':
|
||||
specifier: ^5.83.0
|
||||
version: 5.83.0(react@19.2.6)
|
||||
'@xyflow/react':
|
||||
specifier: ^12.10.1
|
||||
version: 12.10.1(@types/react@19.2.14)(immer@10.1.1)(react-dom@19.2.6(react@19.2.6))(react@19.2.6)
|
||||
api-types:
|
||||
specifier: workspace:*
|
||||
version: link:../../packages/api-types
|
||||
|
||||
Reference in new issue
Block a user