diff --git a/apps/ui-library/__registry__/index.tsx b/apps/ui-library/__registry__/index.tsx index 7cd9c0996e9..9fd1ea56dd3 100644 --- a/apps/ui-library/__registry__/index.tsx +++ b/apps/ui-library/__registry__/index.tsx @@ -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")), } diff --git a/apps/ui-library/app/example/realtime-flow-demo/page.tsx b/apps/ui-library/app/example/realtime-flow-demo/page.tsx new file mode 100644 index 00000000000..8937fbb0ac9 --- /dev/null +++ b/apps/ui-library/app/example/realtime-flow-demo/page.tsx @@ -0,0 +1,9 @@ +'use client' + +import Demo from '@/registry/default/examples/realtime-flow-demo' + +const RealtimeFlowDemoPage = () => { + return +} + +export default RealtimeFlowDemoPage diff --git a/apps/ui-library/components/dual-realtime-flow.tsx b/apps/ui-library/components/dual-realtime-flow.tsx new file mode 100644 index 00000000000..7ebd76cc83b --- /dev/null +++ b/apps/ui-library/components/dual-realtime-flow.tsx @@ -0,0 +1,14 @@ +'use client' + +import { BlockPreview } from './block-preview' + +export function DualRealtimeFlow() { + return ( + <> +
+ + +
+ + ) +} diff --git a/apps/ui-library/components/mdx-components.tsx b/apps/ui-library/components/mdx-components.tsx index 78b880db9d8..41e9c272bf3 100644 --- a/apps/ui-library/components/mdx-components.tsx +++ b/apps/ui-library/components/mdx-components.tsx @@ -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, } diff --git a/apps/ui-library/config/docs.ts b/apps/ui-library/config/docs.ts index 77203ce9a60..acdc71c46d6 100644 --- a/apps/ui-library/config/docs.ts +++ b/apps/ui-library/config/docs.ts @@ -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'], diff --git a/apps/ui-library/content/docs/nextjs/realtime-flow.mdx b/apps/ui-library/content/docs/nextjs/realtime-flow.mdx new file mode 100644 index 00000000000..06b2725ab00 --- /dev/null +++ b/apps/ui-library/content/docs/nextjs/realtime-flow.mdx @@ -0,0 +1,224 @@ +--- +title: Realtime Flow +description: Real-time flow diagram editor for collaborative applications +--- + + + +## Installation + + + +## Folder structure + + + +## 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 +} +``` + +### 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 ( + + ) +} +``` + +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 ( + + ) +} +``` + +### 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 ( + + + + + + + ) +} +``` + +`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/) diff --git a/apps/ui-library/content/docs/react-router/realtime-flow.mdx b/apps/ui-library/content/docs/react-router/realtime-flow.mdx new file mode 100644 index 00000000000..9ea1ffaba9b --- /dev/null +++ b/apps/ui-library/content/docs/react-router/realtime-flow.mdx @@ -0,0 +1,224 @@ +--- +title: Realtime Flow +description: Real-time flow diagram editor for collaborative applications +--- + + + +## Installation + + + +## Folder structure + + + +## 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 +} +``` + +### 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 ( + + ) +} +``` + +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 ( + + ) +} +``` + +### 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 ( + + + + + + + ) +} +``` + +`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/) diff --git a/apps/ui-library/content/docs/react/realtime-flow.mdx b/apps/ui-library/content/docs/react/realtime-flow.mdx new file mode 100644 index 00000000000..c1429fae3a8 --- /dev/null +++ b/apps/ui-library/content/docs/react/realtime-flow.mdx @@ -0,0 +1,224 @@ +--- +title: Realtime Flow +description: Real-time flow diagram editor for collaborative applications +--- + + + +## Installation + + + +## Folder structure + + + +## 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 +} +``` + +### 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 ( + + ) +} +``` + +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 ( + + ) +} +``` + +### 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 ( + + + + + + + ) +} +``` + +`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/) diff --git a/apps/ui-library/content/docs/tanstack/realtime-flow.mdx b/apps/ui-library/content/docs/tanstack/realtime-flow.mdx new file mode 100644 index 00000000000..97f75ca55c2 --- /dev/null +++ b/apps/ui-library/content/docs/tanstack/realtime-flow.mdx @@ -0,0 +1,224 @@ +--- +title: Realtime Flow +description: Real-time flow diagram editor for collaborative applications +--- + + + +## Installation + + + +## Folder structure + + + +## 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 +} +``` + +### 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 ( + + ) +} +``` + +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 ( + + ) +} +``` + +### 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 ( + + + + + + + ) +} +``` + +`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/) diff --git a/apps/ui-library/package.json b/apps/ui-library/package.json index 5e4ef838361..1f8432004a7 100644 --- a/apps/ui-library/package.json +++ b/apps/ui-library/package.json @@ -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", diff --git a/apps/ui-library/public/r/current-user-avatar-react-router.json b/apps/ui-library/public/r/current-user-avatar-react-router.json index f8ebac349bb..a72cab41385 100644 --- a/apps/ui-library/public/r/current-user-avatar-react-router.json +++ b/apps/ui-library/public/r/current-user-avatar-react-router.json @@ -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(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(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(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(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" }, { diff --git a/apps/ui-library/public/r/current-user-avatar-react.json b/apps/ui-library/public/r/current-user-avatar-react.json index 2c4d3ed974e..5ef7bfb6c37 100644 --- a/apps/ui-library/public/r/current-user-avatar-react.json +++ b/apps/ui-library/public/r/current-user-avatar-react.json @@ -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(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(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(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(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" }, { diff --git a/apps/ui-library/public/r/current-user-avatar-tanstack.json b/apps/ui-library/public/r/current-user-avatar-tanstack.json index 505f3dd6a57..f8f6800f8e5 100644 --- a/apps/ui-library/public/r/current-user-avatar-tanstack.json +++ b/apps/ui-library/public/r/current-user-avatar-tanstack.json @@ -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(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(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(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(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" }, { diff --git a/apps/ui-library/public/r/dropzone-react-router.json b/apps/ui-library/public/r/dropzone-react-router.json index 55ae71c48b5..8812d3553d2 100644 --- a/apps/ui-library/public/r/dropzone-react-router.json +++ b/apps/ui-library/public/r/dropzone-react-router.json @@ -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= 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\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([])\n const [loading, setLoading] = useState(false)\n const [errors, setErrors] = useState<{ name: string; message: string }[]>([])\n const [successes, setSuccesses] = useState([])\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 newSuccesses = Array.from(\n new Set([...successes, ...responseSuccesses.map((x) => x.name)])\n )\n setSuccesses(newSuccesses)\n\n setLoading(false)\n }, [files, path, bucketName, errors, successes])\n\n useEffect(() => {\n if (files.length === 0) {\n setErrors([])\n }\n\n // If the number of files doesn't exceed the maxFiles parameter, remove the error 'Too many files' from each file\n if (files.length <= maxFiles) {\n let changed = false\n const newFiles = files.map((file) => {\n if (file.errors.some((e) => e.code === 'too-many-files')) {\n file.errors = file.errors.filter((e) => e.code !== 'too-many-files')\n changed = true\n }\n return file\n })\n if (changed) {\n setFiles(newFiles)\n }\n }\n }, [files.length, setFiles, maxFiles])\n\n return {\n files,\n setFiles,\n successes,\n isSuccess,\n loading,\n errors,\n setErrors,\n onUpload,\n maxFileSize: maxFileSize,\n maxFiles: maxFiles,\n allowedMimeTypes,\n ...dropzoneProps,\n }\n}\n\nexport { useSupabaseUpload, type UseSupabaseUploadOptions, type UseSupabaseUploadReturn }\n", + "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= 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\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([])\n const [loading, setLoading] = useState(false)\n const [errors, setErrors] = useState<{ name: string; message: string }[]>([])\n const [successes, setSuccesses] = useState([])\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 newSuccesses = Array.from(\n new Set([...successes, ...responseSuccesses.map((x) => x.name)])\n )\n setSuccesses(newSuccesses)\n\n setLoading(false)\n }, [files, path, bucketName, errors, successes])\n\n useEffect(() => {\n if (files.length === 0) {\n setErrors([])\n }\n\n // If the number of files doesn't exceed the maxFiles parameter, remove the error 'Too many files' from each file\n if (files.length <= maxFiles) {\n let changed = false\n const newFiles = files.map((file) => {\n if (file.errors.some((e) => e.code === 'too-many-files')) {\n file.errors = file.errors.filter((e) => e.code !== 'too-many-files')\n changed = true\n }\n return file\n })\n if (changed) {\n setFiles(newFiles)\n }\n }\n }, [files.length, setFiles, maxFiles])\n\n return {\n files,\n setFiles,\n successes,\n isSuccess,\n loading,\n errors,\n setErrors,\n onUpload,\n maxFileSize: maxFileSize,\n maxFiles: maxFiles,\n allowedMimeTypes,\n ...dropzoneProps,\n }\n}\n\nexport { useSupabaseUpload, type UseSupabaseUploadOptions, type UseSupabaseUploadReturn }\n", "type": "registry:hook" }, { diff --git a/apps/ui-library/public/r/dropzone-react.json b/apps/ui-library/public/r/dropzone-react.json index 5005e769cc1..201b6b437d6 100644 --- a/apps/ui-library/public/r/dropzone-react.json +++ b/apps/ui-library/public/r/dropzone-react.json @@ -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= 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\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([])\n const [loading, setLoading] = useState(false)\n const [errors, setErrors] = useState<{ name: string; message: string }[]>([])\n const [successes, setSuccesses] = useState([])\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 newSuccesses = Array.from(\n new Set([...successes, ...responseSuccesses.map((x) => x.name)])\n )\n setSuccesses(newSuccesses)\n\n setLoading(false)\n }, [files, path, bucketName, errors, successes])\n\n useEffect(() => {\n if (files.length === 0) {\n setErrors([])\n }\n\n // If the number of files doesn't exceed the maxFiles parameter, remove the error 'Too many files' from each file\n if (files.length <= maxFiles) {\n let changed = false\n const newFiles = files.map((file) => {\n if (file.errors.some((e) => e.code === 'too-many-files')) {\n file.errors = file.errors.filter((e) => e.code !== 'too-many-files')\n changed = true\n }\n return file\n })\n if (changed) {\n setFiles(newFiles)\n }\n }\n }, [files.length, setFiles, maxFiles])\n\n return {\n files,\n setFiles,\n successes,\n isSuccess,\n loading,\n errors,\n setErrors,\n onUpload,\n maxFileSize: maxFileSize,\n maxFiles: maxFiles,\n allowedMimeTypes,\n ...dropzoneProps,\n }\n}\n\nexport { useSupabaseUpload, type UseSupabaseUploadOptions, type UseSupabaseUploadReturn }\n", + "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= 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\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([])\n const [loading, setLoading] = useState(false)\n const [errors, setErrors] = useState<{ name: string; message: string }[]>([])\n const [successes, setSuccesses] = useState([])\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 newSuccesses = Array.from(\n new Set([...successes, ...responseSuccesses.map((x) => x.name)])\n )\n setSuccesses(newSuccesses)\n\n setLoading(false)\n }, [files, path, bucketName, errors, successes])\n\n useEffect(() => {\n if (files.length === 0) {\n setErrors([])\n }\n\n // If the number of files doesn't exceed the maxFiles parameter, remove the error 'Too many files' from each file\n if (files.length <= maxFiles) {\n let changed = false\n const newFiles = files.map((file) => {\n if (file.errors.some((e) => e.code === 'too-many-files')) {\n file.errors = file.errors.filter((e) => e.code !== 'too-many-files')\n changed = true\n }\n return file\n })\n if (changed) {\n setFiles(newFiles)\n }\n }\n }, [files.length, setFiles, maxFiles])\n\n return {\n files,\n setFiles,\n successes,\n isSuccess,\n loading,\n errors,\n setErrors,\n onUpload,\n maxFileSize: maxFileSize,\n maxFiles: maxFiles,\n allowedMimeTypes,\n ...dropzoneProps,\n }\n}\n\nexport { useSupabaseUpload, type UseSupabaseUploadOptions, type UseSupabaseUploadReturn }\n", "type": "registry:hook" }, { diff --git a/apps/ui-library/public/r/dropzone-tanstack.json b/apps/ui-library/public/r/dropzone-tanstack.json index a58c4f1d9f5..26bf15d7eff 100644 --- a/apps/ui-library/public/r/dropzone-tanstack.json +++ b/apps/ui-library/public/r/dropzone-tanstack.json @@ -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= 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\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([])\n const [loading, setLoading] = useState(false)\n const [errors, setErrors] = useState<{ name: string; message: string }[]>([])\n const [successes, setSuccesses] = useState([])\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 newSuccesses = Array.from(\n new Set([...successes, ...responseSuccesses.map((x) => x.name)])\n )\n setSuccesses(newSuccesses)\n\n setLoading(false)\n }, [files, path, bucketName, errors, successes])\n\n useEffect(() => {\n if (files.length === 0) {\n setErrors([])\n }\n\n // If the number of files doesn't exceed the maxFiles parameter, remove the error 'Too many files' from each file\n if (files.length <= maxFiles) {\n let changed = false\n const newFiles = files.map((file) => {\n if (file.errors.some((e) => e.code === 'too-many-files')) {\n file.errors = file.errors.filter((e) => e.code !== 'too-many-files')\n changed = true\n }\n return file\n })\n if (changed) {\n setFiles(newFiles)\n }\n }\n }, [files.length, setFiles, maxFiles])\n\n return {\n files,\n setFiles,\n successes,\n isSuccess,\n loading,\n errors,\n setErrors,\n onUpload,\n maxFileSize: maxFileSize,\n maxFiles: maxFiles,\n allowedMimeTypes,\n ...dropzoneProps,\n }\n}\n\nexport { useSupabaseUpload, type UseSupabaseUploadOptions, type UseSupabaseUploadReturn }\n", + "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= 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\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([])\n const [loading, setLoading] = useState(false)\n const [errors, setErrors] = useState<{ name: string; message: string }[]>([])\n const [successes, setSuccesses] = useState([])\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 newSuccesses = Array.from(\n new Set([...successes, ...responseSuccesses.map((x) => x.name)])\n )\n setSuccesses(newSuccesses)\n\n setLoading(false)\n }, [files, path, bucketName, errors, successes])\n\n useEffect(() => {\n if (files.length === 0) {\n setErrors([])\n }\n\n // If the number of files doesn't exceed the maxFiles parameter, remove the error 'Too many files' from each file\n if (files.length <= maxFiles) {\n let changed = false\n const newFiles = files.map((file) => {\n if (file.errors.some((e) => e.code === 'too-many-files')) {\n file.errors = file.errors.filter((e) => e.code !== 'too-many-files')\n changed = true\n }\n return file\n })\n if (changed) {\n setFiles(newFiles)\n }\n }\n }, [files.length, setFiles, maxFiles])\n\n return {\n files,\n setFiles,\n successes,\n isSuccess,\n loading,\n errors,\n setErrors,\n onUpload,\n maxFileSize: maxFileSize,\n maxFiles: maxFiles,\n allowedMimeTypes,\n ...dropzoneProps,\n }\n}\n\nexport { useSupabaseUpload, type UseSupabaseUploadOptions, type UseSupabaseUploadReturn }\n", "type": "registry:hook" }, { diff --git a/apps/ui-library/public/r/realtime-avatar-stack-react-router.json b/apps/ui-library/public/r/realtime-avatar-stack-react-router.json index 01a135c6761..b147ec812ec 100644 --- a/apps/ui-library/public/r/realtime-avatar-stack-react-router.json +++ b/apps/ui-library/public/r/realtime-avatar-stack-react-router.json @@ -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>({})\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\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>({})\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\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(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(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(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(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" }, { diff --git a/apps/ui-library/public/r/realtime-avatar-stack-react.json b/apps/ui-library/public/r/realtime-avatar-stack-react.json index 31aaa2fc425..8d5f4c36318 100644 --- a/apps/ui-library/public/r/realtime-avatar-stack-react.json +++ b/apps/ui-library/public/r/realtime-avatar-stack-react.json @@ -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>({})\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\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>({})\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\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(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(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(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(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" }, { diff --git a/apps/ui-library/public/r/realtime-avatar-stack-tanstack.json b/apps/ui-library/public/r/realtime-avatar-stack-tanstack.json index 13c883dcb42..698adeb38c5 100644 --- a/apps/ui-library/public/r/realtime-avatar-stack-tanstack.json +++ b/apps/ui-library/public/r/realtime-avatar-stack-tanstack.json @@ -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>({})\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\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>({})\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\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(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(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(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(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" }, { diff --git a/apps/ui-library/public/r/realtime-chat-react-router.json b/apps/ui-library/public/r/realtime-chat-react-router.json index 03d6f440570..278c76177b2 100644 --- a/apps/ui-library/public/r/realtime-chat-react-router.json +++ b/apps/ui-library/public/r/realtime-chat-react-router.json @@ -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([])\n const [channel, setChannel] = useState | 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([])\n const [channel, setChannel] = useState | 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" }, { diff --git a/apps/ui-library/public/r/realtime-chat-react.json b/apps/ui-library/public/r/realtime-chat-react.json index 48d4257d0ed..cead680819d 100644 --- a/apps/ui-library/public/r/realtime-chat-react.json +++ b/apps/ui-library/public/r/realtime-chat-react.json @@ -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([])\n const [channel, setChannel] = useState | 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([])\n const [channel, setChannel] = useState | 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" }, { diff --git a/apps/ui-library/public/r/realtime-chat-tanstack.json b/apps/ui-library/public/r/realtime-chat-tanstack.json index 081050218e3..6f3271da8b1 100644 --- a/apps/ui-library/public/r/realtime-chat-tanstack.json +++ b/apps/ui-library/public/r/realtime-chat-tanstack.json @@ -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([])\n const [channel, setChannel] = useState | 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([])\n const [channel, setChannel] = useState | 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" }, { diff --git a/apps/ui-library/public/r/realtime-cursor-react-router.json b/apps/ui-library/public/r/realtime-cursor-react-router.json index 9d9c134f773..be0b588c737 100644 --- a/apps/ui-library/public/r/realtime-cursor-react-router.json +++ b/apps/ui-library/public/r/realtime-cursor-react-router.json @@ -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 = (\n callback: (...args: Params) => Return,\n delay: number\n) => {\n const lastCall = useRef(0)\n const timeout = useRef(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>({})\n const cursorPayload = useRef(null)\n\n const channelRef = useRef(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 = (\n callback: (...args: Params) => Return,\n delay: number\n) => {\n const lastCall = useRef(0)\n const timeout = useRef(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>({})\n const cursorPayload = useRef(null)\n\n const channelRef = useRef(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" }, { diff --git a/apps/ui-library/public/r/realtime-cursor-react.json b/apps/ui-library/public/r/realtime-cursor-react.json index 0dfa9f63368..1f93ba97a67 100644 --- a/apps/ui-library/public/r/realtime-cursor-react.json +++ b/apps/ui-library/public/r/realtime-cursor-react.json @@ -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 = (\n callback: (...args: Params) => Return,\n delay: number\n) => {\n const lastCall = useRef(0)\n const timeout = useRef(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>({})\n const cursorPayload = useRef(null)\n\n const channelRef = useRef(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 = (\n callback: (...args: Params) => Return,\n delay: number\n) => {\n const lastCall = useRef(0)\n const timeout = useRef(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>({})\n const cursorPayload = useRef(null)\n\n const channelRef = useRef(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" }, { diff --git a/apps/ui-library/public/r/realtime-cursor-tanstack.json b/apps/ui-library/public/r/realtime-cursor-tanstack.json index 67f6c9274bf..431a97ac8b8 100644 --- a/apps/ui-library/public/r/realtime-cursor-tanstack.json +++ b/apps/ui-library/public/r/realtime-cursor-tanstack.json @@ -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 = (\n callback: (...args: Params) => Return,\n delay: number\n) => {\n const lastCall = useRef(0)\n const timeout = useRef(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>({})\n const cursorPayload = useRef(null)\n\n const channelRef = useRef(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 = (\n callback: (...args: Params) => Return,\n delay: number\n) => {\n const lastCall = useRef(0)\n const timeout = useRef(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>({})\n const cursorPayload = useRef(null)\n\n const channelRef = useRef(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" }, { diff --git a/apps/ui-library/public/r/realtime-flow-nextjs.json b/apps/ui-library/public/r/realtime-flow-nextjs.json new file mode 100644 index 00000000000..7249b12d55a --- /dev/null +++ b/apps/ui-library/public/r/realtime-flow-nextjs.json @@ -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 | ((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([])\n const [edges, setEdgesState] = useState([])\n const [synced, setSynced] = useState(false)\n const [syncError, setSyncError] = useState(null)\n\n const docRef = useRef(null)\n const providerRef = useRef(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('nodes')\n const yEdges = doc.getMap('edges')\n const initialNodesForChannel = initialNodesRef.current\n const initialEdgesForChannel = initialEdgesRef.current\n let initialSyncTimer: ReturnType | 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) => {\n if (event.transaction.origin === 'local') return\n hasRemoteActivity = true\n syncNodesFromYjs()\n }\n\n const edgesObserver = (event: Y.YMapEvent) => {\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', () => {\n hasRemoteActivity = true\n markSynced()\n })\n provider.on('error', (error) => {\n markSyncError(error)\n })\n }\n\n docRef.current = doc\n providerRef.current = provider\n\n return () => {\n clearInitialSyncTimer()\n yNodes.unobserve(nodesObserver)\n yEdges.unobserve(edgesObserver)\n provider.destroy()\n doc.destroy()\n docRef.current = null\n providerRef.current = null\n syncedRef.current = false\n setSynced(false)\n setSyncError(null)\n }\n }, [channel, awareness, persistence])\n\n const syncNodesToYjs = useCallback((updated: Node[]) => {\n const doc = docRef.current\n if (!doc || !syncedRef.current) return\n\n const yNodes = doc.getMap('nodes')\n doc.transact(() => {\n const newIds = new Set(updated.map((n) => n.id))\n for (const key of Array.from(yNodes.keys())) {\n if (!newIds.has(key)) yNodes.delete(key)\n }\n for (const node of updated) {\n yNodes.set(node.id, JSON.stringify(node))\n }\n }, 'local')\n }, [])\n\n const syncEdgesToYjs = useCallback((updated: Edge[]) => {\n const doc = docRef.current\n if (!doc || !syncedRef.current) return\n\n const yEdges = doc.getMap('edges')\n doc.transact(() => {\n const newIds = new Set(updated.map((e) => e.id))\n for (const key of Array.from(yEdges.keys())) {\n if (!newIds.has(key)) yEdges.delete(key)\n }\n for (const edge of updated) {\n yEdges.set(edge.id, JSON.stringify(edge))\n }\n }, 'local')\n }, [])\n\n const setNodes = useCallback(\n (nodesOrUpdater: SetStateAction) => {\n setNodesState((current) => {\n const updated =\n typeof nodesOrUpdater === 'function' ? nodesOrUpdater(current) : nodesOrUpdater\n syncNodesToYjs(updated)\n return updated\n })\n },\n [syncNodesToYjs]\n )\n\n const setEdges = useCallback(\n (edgesOrUpdater: SetStateAction) => {\n setEdgesState((current) => {\n const updated =\n typeof edgesOrUpdater === 'function' ? edgesOrUpdater(current) : edgesOrUpdater\n syncEdgesToYjs(updated)\n return updated\n })\n },\n [syncEdgesToYjs]\n )\n\n const onNodesChange = useCallback((changes: NodeChange[]) => {\n setNodesState((currentNodes) => {\n const updated = applyNodeChanges(changes, currentNodes)\n\n const doc = docRef.current\n if (!doc || !syncedRef.current) return updated\n\n const yNodes = doc.getMap('nodes')\n\n doc.transact(() => {\n for (const change of changes) {\n if (change.type === 'remove') {\n yNodes.delete(change.id)\n } else if (change.type === 'add') {\n yNodes.set(change.item.id, JSON.stringify(change.item))\n } else {\n const node = updated.find((n) => n.id === change.id)\n if (node) {\n yNodes.set(node.id, JSON.stringify(node))\n }\n }\n }\n }, 'local')\n\n return updated\n })\n }, [])\n\n const onEdgesChange = useCallback((changes: EdgeChange[]) => {\n setEdgesState((currentEdges) => {\n const updated = applyEdgeChanges(changes, currentEdges)\n\n const doc = docRef.current\n if (!doc || !syncedRef.current) return updated\n\n const yEdges = doc.getMap('edges')\n\n doc.transact(() => {\n for (const change of changes) {\n if (change.type === 'remove') {\n yEdges.delete(change.id)\n } else if (change.type === 'add') {\n yEdges.set(change.item.id, JSON.stringify(change.item))\n } else {\n const edge = updated.find((e) => e.id === change.id)\n if (edge) {\n yEdges.set(edge.id, JSON.stringify(edge))\n }\n }\n }\n }, 'local')\n\n return updated\n })\n }, [])\n\n const onConnect = useCallback((connection: Connection) => {\n setEdgesState((currentEdges) => {\n const updated = addEdge(connection, currentEdges)\n\n const doc = docRef.current\n if (!doc || !syncedRef.current) return updated\n\n const yEdges = doc.getMap('edges')\n const newEdge = updated.find((e) => !currentEdges.some((ce) => ce.id === e.id))\n\n if (newEdge) {\n doc.transact(() => {\n yEdges.set(newEdge.id, JSON.stringify(newEdge))\n }, 'local')\n }\n\n return updated\n })\n }, [])\n\n return {\n nodes,\n edges,\n synced,\n syncError,\n onNodesChange,\n onEdgesChange,\n onConnect,\n setNodes,\n setEdges,\n }\n}\n", + "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
\n \n \n \n \n {!synced && !syncError && }\n {!synced && syncError && }\n
\n )\n}\n\nconst RealtimeFlow = (props: RealtimeFlowProps) => (\n \n \n \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`." +} \ No newline at end of file diff --git a/apps/ui-library/public/r/realtime-flow-react-router.json b/apps/ui-library/public/r/realtime-flow-react-router.json new file mode 100644 index 00000000000..ce15230ed9f --- /dev/null +++ b/apps/ui-library/public/r/realtime-flow-react-router.json @@ -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 | ((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([])\n const [edges, setEdgesState] = useState([])\n const [synced, setSynced] = useState(false)\n const [syncError, setSyncError] = useState(null)\n\n const docRef = useRef(null)\n const providerRef = useRef(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('nodes')\n const yEdges = doc.getMap('edges')\n const initialNodesForChannel = initialNodesRef.current\n const initialEdgesForChannel = initialEdgesRef.current\n let initialSyncTimer: ReturnType | 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) => {\n if (event.transaction.origin === 'local') return\n hasRemoteActivity = true\n syncNodesFromYjs()\n }\n\n const edgesObserver = (event: Y.YMapEvent) => {\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', () => {\n hasRemoteActivity = true\n markSynced()\n })\n provider.on('error', (error) => {\n markSyncError(error)\n })\n }\n\n docRef.current = doc\n providerRef.current = provider\n\n return () => {\n clearInitialSyncTimer()\n yNodes.unobserve(nodesObserver)\n yEdges.unobserve(edgesObserver)\n provider.destroy()\n doc.destroy()\n docRef.current = null\n providerRef.current = null\n syncedRef.current = false\n setSynced(false)\n setSyncError(null)\n }\n }, [channel, awareness, persistence])\n\n const syncNodesToYjs = useCallback((updated: Node[]) => {\n const doc = docRef.current\n if (!doc || !syncedRef.current) return\n\n const yNodes = doc.getMap('nodes')\n doc.transact(() => {\n const newIds = new Set(updated.map((n) => n.id))\n for (const key of Array.from(yNodes.keys())) {\n if (!newIds.has(key)) yNodes.delete(key)\n }\n for (const node of updated) {\n yNodes.set(node.id, JSON.stringify(node))\n }\n }, 'local')\n }, [])\n\n const syncEdgesToYjs = useCallback((updated: Edge[]) => {\n const doc = docRef.current\n if (!doc || !syncedRef.current) return\n\n const yEdges = doc.getMap('edges')\n doc.transact(() => {\n const newIds = new Set(updated.map((e) => e.id))\n for (const key of Array.from(yEdges.keys())) {\n if (!newIds.has(key)) yEdges.delete(key)\n }\n for (const edge of updated) {\n yEdges.set(edge.id, JSON.stringify(edge))\n }\n }, 'local')\n }, [])\n\n const setNodes = useCallback(\n (nodesOrUpdater: SetStateAction) => {\n setNodesState((current) => {\n const updated =\n typeof nodesOrUpdater === 'function' ? nodesOrUpdater(current) : nodesOrUpdater\n syncNodesToYjs(updated)\n return updated\n })\n },\n [syncNodesToYjs]\n )\n\n const setEdges = useCallback(\n (edgesOrUpdater: SetStateAction) => {\n setEdgesState((current) => {\n const updated =\n typeof edgesOrUpdater === 'function' ? edgesOrUpdater(current) : edgesOrUpdater\n syncEdgesToYjs(updated)\n return updated\n })\n },\n [syncEdgesToYjs]\n )\n\n const onNodesChange = useCallback((changes: NodeChange[]) => {\n setNodesState((currentNodes) => {\n const updated = applyNodeChanges(changes, currentNodes)\n\n const doc = docRef.current\n if (!doc || !syncedRef.current) return updated\n\n const yNodes = doc.getMap('nodes')\n\n doc.transact(() => {\n for (const change of changes) {\n if (change.type === 'remove') {\n yNodes.delete(change.id)\n } else if (change.type === 'add') {\n yNodes.set(change.item.id, JSON.stringify(change.item))\n } else {\n const node = updated.find((n) => n.id === change.id)\n if (node) {\n yNodes.set(node.id, JSON.stringify(node))\n }\n }\n }\n }, 'local')\n\n return updated\n })\n }, [])\n\n const onEdgesChange = useCallback((changes: EdgeChange[]) => {\n setEdgesState((currentEdges) => {\n const updated = applyEdgeChanges(changes, currentEdges)\n\n const doc = docRef.current\n if (!doc || !syncedRef.current) return updated\n\n const yEdges = doc.getMap('edges')\n\n doc.transact(() => {\n for (const change of changes) {\n if (change.type === 'remove') {\n yEdges.delete(change.id)\n } else if (change.type === 'add') {\n yEdges.set(change.item.id, JSON.stringify(change.item))\n } else {\n const edge = updated.find((e) => e.id === change.id)\n if (edge) {\n yEdges.set(edge.id, JSON.stringify(edge))\n }\n }\n }\n }, 'local')\n\n return updated\n })\n }, [])\n\n const onConnect = useCallback((connection: Connection) => {\n setEdgesState((currentEdges) => {\n const updated = addEdge(connection, currentEdges)\n\n const doc = docRef.current\n if (!doc || !syncedRef.current) return updated\n\n const yEdges = doc.getMap('edges')\n const newEdge = updated.find((e) => !currentEdges.some((ce) => ce.id === e.id))\n\n if (newEdge) {\n doc.transact(() => {\n yEdges.set(newEdge.id, JSON.stringify(newEdge))\n }, 'local')\n }\n\n return updated\n })\n }, [])\n\n return {\n nodes,\n edges,\n synced,\n syncError,\n onNodesChange,\n onEdgesChange,\n onConnect,\n setNodes,\n setEdges,\n }\n}\n", + "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
\n \n \n \n \n {!synced && !syncError && }\n {!synced && syncError && }\n
\n )\n}\n\nconst RealtimeFlow = (props: RealtimeFlowProps) => (\n \n \n \n)\n\nexport { RealtimeFlow }\n", + "type": "registry:component" + }, + { + "path": "registry/default/clients/react-router/lib/supabase/client.ts", + "content": "/// \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`." +} \ No newline at end of file diff --git a/apps/ui-library/public/r/realtime-flow-react.json b/apps/ui-library/public/r/realtime-flow-react.json new file mode 100644 index 00000000000..45589267799 --- /dev/null +++ b/apps/ui-library/public/r/realtime-flow-react.json @@ -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 | ((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([])\n const [edges, setEdgesState] = useState([])\n const [synced, setSynced] = useState(false)\n const [syncError, setSyncError] = useState(null)\n\n const docRef = useRef(null)\n const providerRef = useRef(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('nodes')\n const yEdges = doc.getMap('edges')\n const initialNodesForChannel = initialNodesRef.current\n const initialEdgesForChannel = initialEdgesRef.current\n let initialSyncTimer: ReturnType | 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) => {\n if (event.transaction.origin === 'local') return\n hasRemoteActivity = true\n syncNodesFromYjs()\n }\n\n const edgesObserver = (event: Y.YMapEvent) => {\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', () => {\n hasRemoteActivity = true\n markSynced()\n })\n provider.on('error', (error) => {\n markSyncError(error)\n })\n }\n\n docRef.current = doc\n providerRef.current = provider\n\n return () => {\n clearInitialSyncTimer()\n yNodes.unobserve(nodesObserver)\n yEdges.unobserve(edgesObserver)\n provider.destroy()\n doc.destroy()\n docRef.current = null\n providerRef.current = null\n syncedRef.current = false\n setSynced(false)\n setSyncError(null)\n }\n }, [channel, awareness, persistence])\n\n const syncNodesToYjs = useCallback((updated: Node[]) => {\n const doc = docRef.current\n if (!doc || !syncedRef.current) return\n\n const yNodes = doc.getMap('nodes')\n doc.transact(() => {\n const newIds = new Set(updated.map((n) => n.id))\n for (const key of Array.from(yNodes.keys())) {\n if (!newIds.has(key)) yNodes.delete(key)\n }\n for (const node of updated) {\n yNodes.set(node.id, JSON.stringify(node))\n }\n }, 'local')\n }, [])\n\n const syncEdgesToYjs = useCallback((updated: Edge[]) => {\n const doc = docRef.current\n if (!doc || !syncedRef.current) return\n\n const yEdges = doc.getMap('edges')\n doc.transact(() => {\n const newIds = new Set(updated.map((e) => e.id))\n for (const key of Array.from(yEdges.keys())) {\n if (!newIds.has(key)) yEdges.delete(key)\n }\n for (const edge of updated) {\n yEdges.set(edge.id, JSON.stringify(edge))\n }\n }, 'local')\n }, [])\n\n const setNodes = useCallback(\n (nodesOrUpdater: SetStateAction) => {\n setNodesState((current) => {\n const updated =\n typeof nodesOrUpdater === 'function' ? nodesOrUpdater(current) : nodesOrUpdater\n syncNodesToYjs(updated)\n return updated\n })\n },\n [syncNodesToYjs]\n )\n\n const setEdges = useCallback(\n (edgesOrUpdater: SetStateAction) => {\n setEdgesState((current) => {\n const updated =\n typeof edgesOrUpdater === 'function' ? edgesOrUpdater(current) : edgesOrUpdater\n syncEdgesToYjs(updated)\n return updated\n })\n },\n [syncEdgesToYjs]\n )\n\n const onNodesChange = useCallback((changes: NodeChange[]) => {\n setNodesState((currentNodes) => {\n const updated = applyNodeChanges(changes, currentNodes)\n\n const doc = docRef.current\n if (!doc || !syncedRef.current) return updated\n\n const yNodes = doc.getMap('nodes')\n\n doc.transact(() => {\n for (const change of changes) {\n if (change.type === 'remove') {\n yNodes.delete(change.id)\n } else if (change.type === 'add') {\n yNodes.set(change.item.id, JSON.stringify(change.item))\n } else {\n const node = updated.find((n) => n.id === change.id)\n if (node) {\n yNodes.set(node.id, JSON.stringify(node))\n }\n }\n }\n }, 'local')\n\n return updated\n })\n }, [])\n\n const onEdgesChange = useCallback((changes: EdgeChange[]) => {\n setEdgesState((currentEdges) => {\n const updated = applyEdgeChanges(changes, currentEdges)\n\n const doc = docRef.current\n if (!doc || !syncedRef.current) return updated\n\n const yEdges = doc.getMap('edges')\n\n doc.transact(() => {\n for (const change of changes) {\n if (change.type === 'remove') {\n yEdges.delete(change.id)\n } else if (change.type === 'add') {\n yEdges.set(change.item.id, JSON.stringify(change.item))\n } else {\n const edge = updated.find((e) => e.id === change.id)\n if (edge) {\n yEdges.set(edge.id, JSON.stringify(edge))\n }\n }\n }\n }, 'local')\n\n return updated\n })\n }, [])\n\n const onConnect = useCallback((connection: Connection) => {\n setEdgesState((currentEdges) => {\n const updated = addEdge(connection, currentEdges)\n\n const doc = docRef.current\n if (!doc || !syncedRef.current) return updated\n\n const yEdges = doc.getMap('edges')\n const newEdge = updated.find((e) => !currentEdges.some((ce) => ce.id === e.id))\n\n if (newEdge) {\n doc.transact(() => {\n yEdges.set(newEdge.id, JSON.stringify(newEdge))\n }, 'local')\n }\n\n return updated\n })\n }, [])\n\n return {\n nodes,\n edges,\n synced,\n syncError,\n onNodesChange,\n onEdgesChange,\n onConnect,\n setNodes,\n setEdges,\n }\n}\n", + "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
\n \n \n \n \n {!synced && !syncError && }\n {!synced && syncError && }\n
\n )\n}\n\nconst RealtimeFlow = (props: RealtimeFlowProps) => (\n \n \n \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`." +} \ No newline at end of file diff --git a/apps/ui-library/public/r/realtime-flow-tanstack.json b/apps/ui-library/public/r/realtime-flow-tanstack.json new file mode 100644 index 00000000000..391937d303e --- /dev/null +++ b/apps/ui-library/public/r/realtime-flow-tanstack.json @@ -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 | ((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([])\n const [edges, setEdgesState] = useState([])\n const [synced, setSynced] = useState(false)\n const [syncError, setSyncError] = useState(null)\n\n const docRef = useRef(null)\n const providerRef = useRef(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('nodes')\n const yEdges = doc.getMap('edges')\n const initialNodesForChannel = initialNodesRef.current\n const initialEdgesForChannel = initialEdgesRef.current\n let initialSyncTimer: ReturnType | 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) => {\n if (event.transaction.origin === 'local') return\n hasRemoteActivity = true\n syncNodesFromYjs()\n }\n\n const edgesObserver = (event: Y.YMapEvent) => {\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', () => {\n hasRemoteActivity = true\n markSynced()\n })\n provider.on('error', (error) => {\n markSyncError(error)\n })\n }\n\n docRef.current = doc\n providerRef.current = provider\n\n return () => {\n clearInitialSyncTimer()\n yNodes.unobserve(nodesObserver)\n yEdges.unobserve(edgesObserver)\n provider.destroy()\n doc.destroy()\n docRef.current = null\n providerRef.current = null\n syncedRef.current = false\n setSynced(false)\n setSyncError(null)\n }\n }, [channel, awareness, persistence])\n\n const syncNodesToYjs = useCallback((updated: Node[]) => {\n const doc = docRef.current\n if (!doc || !syncedRef.current) return\n\n const yNodes = doc.getMap('nodes')\n doc.transact(() => {\n const newIds = new Set(updated.map((n) => n.id))\n for (const key of Array.from(yNodes.keys())) {\n if (!newIds.has(key)) yNodes.delete(key)\n }\n for (const node of updated) {\n yNodes.set(node.id, JSON.stringify(node))\n }\n }, 'local')\n }, [])\n\n const syncEdgesToYjs = useCallback((updated: Edge[]) => {\n const doc = docRef.current\n if (!doc || !syncedRef.current) return\n\n const yEdges = doc.getMap('edges')\n doc.transact(() => {\n const newIds = new Set(updated.map((e) => e.id))\n for (const key of Array.from(yEdges.keys())) {\n if (!newIds.has(key)) yEdges.delete(key)\n }\n for (const edge of updated) {\n yEdges.set(edge.id, JSON.stringify(edge))\n }\n }, 'local')\n }, [])\n\n const setNodes = useCallback(\n (nodesOrUpdater: SetStateAction) => {\n setNodesState((current) => {\n const updated =\n typeof nodesOrUpdater === 'function' ? nodesOrUpdater(current) : nodesOrUpdater\n syncNodesToYjs(updated)\n return updated\n })\n },\n [syncNodesToYjs]\n )\n\n const setEdges = useCallback(\n (edgesOrUpdater: SetStateAction) => {\n setEdgesState((current) => {\n const updated =\n typeof edgesOrUpdater === 'function' ? edgesOrUpdater(current) : edgesOrUpdater\n syncEdgesToYjs(updated)\n return updated\n })\n },\n [syncEdgesToYjs]\n )\n\n const onNodesChange = useCallback((changes: NodeChange[]) => {\n setNodesState((currentNodes) => {\n const updated = applyNodeChanges(changes, currentNodes)\n\n const doc = docRef.current\n if (!doc || !syncedRef.current) return updated\n\n const yNodes = doc.getMap('nodes')\n\n doc.transact(() => {\n for (const change of changes) {\n if (change.type === 'remove') {\n yNodes.delete(change.id)\n } else if (change.type === 'add') {\n yNodes.set(change.item.id, JSON.stringify(change.item))\n } else {\n const node = updated.find((n) => n.id === change.id)\n if (node) {\n yNodes.set(node.id, JSON.stringify(node))\n }\n }\n }\n }, 'local')\n\n return updated\n })\n }, [])\n\n const onEdgesChange = useCallback((changes: EdgeChange[]) => {\n setEdgesState((currentEdges) => {\n const updated = applyEdgeChanges(changes, currentEdges)\n\n const doc = docRef.current\n if (!doc || !syncedRef.current) return updated\n\n const yEdges = doc.getMap('edges')\n\n doc.transact(() => {\n for (const change of changes) {\n if (change.type === 'remove') {\n yEdges.delete(change.id)\n } else if (change.type === 'add') {\n yEdges.set(change.item.id, JSON.stringify(change.item))\n } else {\n const edge = updated.find((e) => e.id === change.id)\n if (edge) {\n yEdges.set(edge.id, JSON.stringify(edge))\n }\n }\n }\n }, 'local')\n\n return updated\n })\n }, [])\n\n const onConnect = useCallback((connection: Connection) => {\n setEdgesState((currentEdges) => {\n const updated = addEdge(connection, currentEdges)\n\n const doc = docRef.current\n if (!doc || !syncedRef.current) return updated\n\n const yEdges = doc.getMap('edges')\n const newEdge = updated.find((e) => !currentEdges.some((ce) => ce.id === e.id))\n\n if (newEdge) {\n doc.transact(() => {\n yEdges.set(newEdge.id, JSON.stringify(newEdge))\n }, 'local')\n }\n\n return updated\n })\n }, [])\n\n return {\n nodes,\n edges,\n synced,\n syncError,\n onNodesChange,\n onEdgesChange,\n onConnect,\n setNodes,\n setEdges,\n }\n}\n", + "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
\n \n \n \n \n {!synced && !syncError && }\n {!synced && syncError && }\n
\n )\n}\n\nconst RealtimeFlow = (props: RealtimeFlowProps) => (\n \n \n \n)\n\nexport { RealtimeFlow }\n", + "type": "registry:component" + }, + { + "path": "registry/default/clients/tanstack/lib/supabase/client.ts", + "content": "/// \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`." +} \ No newline at end of file diff --git a/apps/ui-library/public/r/realtime-monaco-react-router.json b/apps/ui-library/public/r/realtime-monaco-react-router.json index 55eee0edccc..ffbe1d4e689 100644 --- a/apps/ui-library/public/r/realtime-monaco-react-router.json +++ b/apps/ui-library/public/r/realtime-monaco-react-router.json @@ -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(null)\n const providerRef = useRef(null)\n const bindingRef = useRef(null)\n const userRef = useRef<{ color: string } | null>(null)\n const styleRef = useRef(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(null)\n const providerRef = useRef(null)\n const bindingRef = useRef(null)\n const userRef = useRef<{ color: string } | null>(null)\n const styleRef = useRef(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" }, { diff --git a/apps/ui-library/public/r/realtime-monaco-react.json b/apps/ui-library/public/r/realtime-monaco-react.json index a2645c9fb21..f28fab47b3e 100644 --- a/apps/ui-library/public/r/realtime-monaco-react.json +++ b/apps/ui-library/public/r/realtime-monaco-react.json @@ -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(null)\n const providerRef = useRef(null)\n const bindingRef = useRef(null)\n const userRef = useRef<{ color: string } | null>(null)\n const styleRef = useRef(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(null)\n const providerRef = useRef(null)\n const bindingRef = useRef(null)\n const userRef = useRef<{ color: string } | null>(null)\n const styleRef = useRef(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" }, { diff --git a/apps/ui-library/public/r/realtime-monaco-tanstack.json b/apps/ui-library/public/r/realtime-monaco-tanstack.json index e03695557ef..34f1f22d7f6 100644 --- a/apps/ui-library/public/r/realtime-monaco-tanstack.json +++ b/apps/ui-library/public/r/realtime-monaco-tanstack.json @@ -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(null)\n const providerRef = useRef(null)\n const bindingRef = useRef(null)\n const userRef = useRef<{ color: string } | null>(null)\n const styleRef = useRef(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(null)\n const providerRef = useRef(null)\n const bindingRef = useRef(null)\n const userRef = useRef<{ color: string } | null>(null)\n const styleRef = useRef(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" }, { diff --git a/apps/ui-library/public/r/registry.json b/apps/ui-library/public/r/registry.json index f6785bf6c4b..1123bf32cd7 100644 --- a/apps/ui-library/public/r/registry.json +++ b/apps/ui-library/public/r/registry.json @@ -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", diff --git a/apps/ui-library/public/r/social-auth-react.json b/apps/ui-library/public/r/social-auth-react.json index c2d0283d20b..d11394b8249 100644 --- a/apps/ui-library/public/r/social-auth-react.json +++ b/apps/ui-library/public/r/social-auth-react.json @@ -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(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
\n \n \n Welcome!\n Sign in to your account to continue\n \n \n
\n
\n {error &&

{error}

}\n \n
\n
\n
\n
\n
\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(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
\n \n \n Welcome!\n Sign in to your account to continue\n \n \n
\n
\n {error &&

{error}

}\n \n
\n
\n
\n
\n
\n )\n}\n", "type": "registry:component" }, { diff --git a/apps/ui-library/registry/blocks.ts b/apps/ui-library/registry/blocks.ts index 513875a7f5c..4be38f7085a 100644 --- a/apps/ui-library/registry/blocks.ts +++ b/apps/ui-library/registry/blocks.ts @@ -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, diff --git a/apps/ui-library/registry/default/blocks/realtime-flow/components/realtime-flow-overlay.tsx b/apps/ui-library/registry/default/blocks/realtime-flow/components/realtime-flow-overlay.tsx new file mode 100644 index 00000000000..d7d595787b9 --- /dev/null +++ b/apps/ui-library/registry/default/blocks/realtime-flow/components/realtime-flow-overlay.tsx @@ -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 ( +
+ + {status === 'error' ? message || 'Failed to sync flow' : 'Syncing…'} + +
+ ) +} + +export { RealtimeFlowOverlay } diff --git a/apps/ui-library/registry/default/blocks/realtime-flow/components/realtime-flow.tsx b/apps/ui-library/registry/default/blocks/realtime-flow/components/realtime-flow.tsx new file mode 100644 index 00000000000..3e7a74da315 --- /dev/null +++ b/apps/ui-library/registry/default/blocks/realtime-flow/components/realtime-flow.tsx @@ -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 ( +
+ + + + + {!synced && !syncError && } + {!synced && syncError && } +
+ ) +} + +const RealtimeFlow = (props: RealtimeFlowProps) => ( + + + +) + +export { RealtimeFlow } diff --git a/apps/ui-library/registry/default/blocks/realtime-flow/hooks/use-realtime-flow.ts b/apps/ui-library/registry/default/blocks/realtime-flow/hooks/use-realtime-flow.ts new file mode 100644 index 00000000000..093c300ffa9 --- /dev/null +++ b/apps/ui-library/registry/default/blocks/realtime-flow/hooks/use-realtime-flow.ts @@ -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 | ((prev: T) => T) + +const INITIAL_SYNC_MS = 350 + +export function useRealtimeFlow({ + channel, + persistence, + awareness = true, + initialNodes = [], + initialEdges = [], +}: UseRealtimeFlowOptions) { + const [nodes, setNodesState] = useState([]) + const [edges, setEdgesState] = useState([]) + const [synced, setSynced] = useState(false) + const [syncError, setSyncError] = useState(null) + + const docRef = useRef(null) + const providerRef = useRef(null) + const syncedRef = useRef(false) + const initialNodesRef = useRef(initialNodes) + const initialEdgesRef = useRef(initialEdges) + + useEffect(() => { + const doc = new Y.Doc() + const yNodes = doc.getMap('nodes') + const yEdges = doc.getMap('edges') + const initialNodesForChannel = initialNodesRef.current + const initialEdgesForChannel = initialEdgesRef.current + let initialSyncTimer: ReturnType | 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) => { + if (event.transaction.origin === 'local') return + hasRemoteActivity = true + syncNodesFromYjs() + } + + const edgesObserver = (event: Y.YMapEvent) => { + 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('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('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) => { + setNodesState((current) => { + const updated = + typeof nodesOrUpdater === 'function' ? nodesOrUpdater(current) : nodesOrUpdater + syncNodesToYjs(updated) + return updated + }) + }, + [syncNodesToYjs] + ) + + const setEdges = useCallback( + (edgesOrUpdater: SetStateAction) => { + 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('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('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('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, + } +} diff --git a/apps/ui-library/registry/default/blocks/realtime-flow/registry-item.json b/apps/ui-library/registry/default/blocks/realtime-flow/registry-item.json new file mode 100644 index 00000000000..fda9fd94e72 --- /dev/null +++ b/apps/ui-library/registry/default/blocks/realtime-flow/registry-item.json @@ -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" + } + ] +} diff --git a/apps/ui-library/registry/default/examples/realtime-flow-demo.tsx b/apps/ui-library/registry/default/examples/realtime-flow-demo.tsx new file mode 100644 index 00000000000..a788202aeec --- /dev/null +++ b/apps/ui-library/registry/default/examples/realtime-flow-demo.tsx @@ -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>) => { + return ( +
+ +
+ data.onLabelChange?.(event.target.value)} + placeholder="Write something..." + /> +
+ +
+
+ +
+ ) +}) + +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 ( + +
+
+ +
+
+ + + + + {!synced && !syncError && } + {!synced && syncError && } +
+
+
+ ) +} + +export default RealtimeFlowDemo diff --git a/apps/ui-library/registry/examples.ts b/apps/ui-library/registry/examples.ts index 83e3fcd837f..dfee11870a5 100644 --- a/apps/ui-library/registry/examples.ts +++ b/apps/ui-library/registry/examples.ts @@ -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', diff --git a/apps/ui-library/scripts/clean-registry.ts b/apps/ui-library/scripts/clean-registry.ts index e891d972865..ea9a44cbd9d 100644 --- a/apps/ui-library/scripts/clean-registry.ts +++ b/apps/ui-library/scripts/clean-registry.ts @@ -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 = { + 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}`) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b821bd39fc9..01ab841096e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -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