Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

Docs/dropzone cursor vue nuxt (#41553)

Jakub Andrzejewskib04da949aac0
diff --git a/apps/ui-library/config/docs.ts b/apps/ui-library/config/docs.ts
index 98a90cb62f1..680fc13deff 100644
--- a/apps/ui-library/config/docs.ts
+++ b/apps/ui-library/config/docs.ts
@@ -76,14 +76,14 @@ export const componentPages: SidebarNavGroup = {
},
{
title: 'Dropzone',
- supportedFrameworks: ['nextjs', 'react-router', 'tanstack', 'react'],
+ supportedFrameworks: ['nextjs', 'react-router', 'tanstack', 'react', 'vue', 'nuxtjs'],
href: '/docs/nextjs/dropzone',
items: [],
commandItemLabel: 'Dropzone (File Upload)',
},
{
title: 'Realtime Cursor',
- supportedFrameworks: ['nextjs', 'react-router', 'tanstack', 'react'],
+ supportedFrameworks: ['nextjs', 'react-router', 'tanstack', 'react', 'vue', 'nuxtjs'],
href: '/docs/nextjs/realtime-cursor',
items: [],
commandItemLabel: 'Realtime Cursor',
diff --git a/apps/ui-library/content/docs/nuxtjs/dropzone.mdx b/apps/ui-library/content/docs/nuxtjs/dropzone.mdx
new file mode 100644
index 00000000000..d960c6f7f13
--- /dev/null
+++ b/apps/ui-library/content/docs/nuxtjs/dropzone.mdx
@@ -0,0 +1,81 @@
+---
+title: Dropzone (File Upload)
+description: Displays a control for easier uploading of files directly to Supabase Storage
+---
+
+<ComponentPreview
+ name="dropzone-demo"
+ description="A file upload dropzone component that allows users to drag-and-drop files or select them manually. It supports multiple files, displays upload progress, previews images, and shows validation errors."
+ showCode={false}
+/>
+
+## Installation
+
+<BlockItem
+ name="dropzone-nuxtjs"
+ description="Displays a control for easier uploading of files directly to Supabase Storage"
+/>
+
+## Folder structure
+
+This block assumes that you have already installed a Supabase client for Nuxt from the previous step.
+
+<RegistryBlock itemName="dropzone-nuxtjs" />
+
+## Introduction
+
+Uploading files should be easy—this component handles the tricky parts for you.
+
+The File Upload component makes it easy to add file uploads to your app, with built-in support for drag-and-drop, file type restrictions, image previews, and configurable limits on file size and number of files. All the essentials, ready to go.
+
+**Features**
+
+- Drag-and-drop support
+- Multiple file uploads
+- File size and count limits
+- Image previews for supported file types
+- MIME type restrictions
+- Invalid file handling
+- Success and error states with clear feedback
+
+## Usage
+
+- Simply add this `<Dropzone />` component to your page and it will handle the rest.
+
+```html
+<script setup>
+ import { Dropzone, DropzoneEmptyState, DropzoneContent } from '@/components/dropzone'
+ import { useSupabaseUpload } from '@/composables/use-supabase-upload'
+
+ const upload = useSupabaseUpload({
+ bucketName: 'test',
+ path: 'test',
+ allowedMimeTypes: ['image/*'],
+ maxFiles: 2,
+ maxFileSize: 1000 * 1000 * 10, // 10MB,
+ })
+</script>
+
+<template>
+ <Dropzone v-bind="upload">
+ <DropzoneEmptyState />
+ <DropzoneContent />
+ </Dropzone>
+</template>
+```
+
+## Props
+
+| Prop | Type | Default | Description |
+| ------------------ | ---------- | ---------- | ---------------------------------------------------- |
+| `bucketName` | `string` | `null` | The name of the Supabase Storage bucket to upload to |
+| `path` | `string` | `null` | The path or subfolder to upload the file to |
+| `allowedMimeTypes` | `string[]` | `[]` | The MIME types to allow for upload |
+| `maxFiles` | `number` | `1` | Maximum number of files to upload |
+| `maxFileSize` | `number` | `Infinity` | Maximum file size in bytes |
+
+## Further reading
+
+- [Creating buckets](https://supabase.com/docs/guides/storage/buckets/creating-buckets)
+- [Access control](https://supabase.com/docs/guides/storage/security/access-control)
+- [Standard uploads](https://supabase.com/docs/guides/storage/uploads/standard-uploads)
diff --git a/apps/ui-library/content/docs/nuxtjs/realtime-cursor.mdx b/apps/ui-library/content/docs/nuxtjs/realtime-cursor.mdx
new file mode 100644
index 00000000000..e89d6da1100
--- /dev/null
+++ b/apps/ui-library/content/docs/nuxtjs/realtime-cursor.mdx
@@ -0,0 +1,66 @@
+---
+title: Realtime Cursor
+description: Real-time cursor sharing for collaborative applications
+---
+
+<div className="flex flex-row -space-x-px w-full">
+ <BlockPreview name="realtime-cursor-demo" isPair />
+ <BlockPreview name="realtime-cursor-demo" isPair />
+</div>
+
+## Installation
+
+<BlockItem
+ name="realtime-cursor-nuxtjs"
+ description="Renders realtime cursors from other users in a room."
+/>
+
+## Folder structure
+
+This block assumes that you have already installed a Supabase client for Nuxt from the previous step.
+
+<RegistryBlock itemName="realtime-cursor-nuxtjs" />
+
+## Introduction
+
+The Realtime Cursors component lets users share their cursor position with others in the same room—perfect for real-time collaboration. It handles all the setup and boilerplate for you, so you can add it to your app with minimal effort.
+
+**Features**
+
+- Broadcast cursor position to other users in the same room
+- Customizable cursor appearance
+- Presence detection (automatically joins/leaves users)
+- Low-latency updates using Supabase Realtime
+- Room-based isolation for scoped collaboration
+
+## Usage
+
+The Realtime Cursor component is designed to be used in a room. It can be used to build real-time collaborative applications. Add the `<RealtimeCursors />` component to your page and it will render realtime cursors from other users in the room.
+
+```html
+<script setup lang="ts">
+ import RealtimeCursors from '@/components/RealtimeCursors.vue'
+</script>
+
+<template>
+ <div class="w-full min-h-screen">
+ <RealtimeCursors roomName="macrodata_refinement_office" username="Mark Scout" />
+ </div>
+</template>
+```
+
+## Props
+
+| Prop | Type | Description |
+| ---------- | -------- | ---------------------------------------------------------- |
+| `roomName` | `string` | Unique identifier for the shared room or session. |
+| `username` | `string` | Name of the current user; used to track and label cursors. |
+
+## Further reading
+
+- [Realtime Broadcast](https://supabase.com/docs/guides/realtime/broadcast)
+- [Realtime authorization](https://supabase.com/docs/guides/realtime/authorization)
+
+### Smoother cursors
+
+While our Realtime Cursor component aims to keep things simple and lightweight, you may want to add smoother cursor animations for a more polished experience. Libraries like [perfect-cursors](https://github.com/steveruizok/perfect-cursors) can be integrated to add sophisticated interpolation between cursor positions. This is especially useful when dealing with network latency, as it creates fluid cursor movements even when position updates are received at longer intervals (e.g., every 50-80ms). The library handles the complex math of creating natural-looking cursor paths while maintaining performance.
diff --git a/apps/ui-library/content/docs/vue/dropzone.mdx b/apps/ui-library/content/docs/vue/dropzone.mdx
new file mode 100644
index 00000000000..f3eb934391b
--- /dev/null
+++ b/apps/ui-library/content/docs/vue/dropzone.mdx
@@ -0,0 +1,81 @@
+---
+title: Dropzone (File Upload)
+description: Displays a control for easier uploading of files directly to Supabase Storage
+---
+
+<ComponentPreview
+ name="dropzone-demo"
+ description="A file upload dropzone component that allows users to drag-and-drop files or select them manually. It supports multiple files, displays upload progress, previews images, and shows validation errors."
+ showCode={false}
+/>
+
+## Installation
+
+<BlockItem
+ name="dropzone-vue"
+ description="Displays a control for easier uploading of files directly to Supabase Storage"
+/>
+
+## Folder structure
+
+This block assumes that you have already installed a Supabase client for Vue from the previous step.
+
+<RegistryBlock itemName="dropzone-vue" />
+
+## Introduction
+
+Uploading files should be easy—this component handles the tricky parts for you.
+
+The File Upload component makes it easy to add file uploads to your app, with built-in support for drag-and-drop, file type restrictions, image previews, and configurable limits on file size and number of files. All the essentials, ready to go.
+
+**Features**
+
+- Drag-and-drop support
+- Multiple file uploads
+- File size and count limits
+- Image previews for supported file types
+- MIME type restrictions
+- Invalid file handling
+- Success and error states with clear feedback
+
+## Usage
+
+- Simply add this `<Dropzone />` component to your page and it will handle the rest.
+
+```html
+<script setup>
+ import { Dropzone, DropzoneEmptyState, DropzoneContent } from '@/components/dropzone'
+ import { useSupabaseUpload } from '@/composables/use-supabase-upload'
+
+ const upload = useSupabaseUpload({
+ bucketName: 'test',
+ path: 'test',
+ allowedMimeTypes: ['image/*'],
+ maxFiles: 2,
+ maxFileSize: 1000 * 1000 * 10, // 10MB,
+ })
+</script>
+
+<template>
+ <Dropzone v-bind="upload">
+ <DropzoneEmptyState />
+ <DropzoneContent />
+ </Dropzone>
+</template>
+```
+
+## Props
+
+| Prop | Type | Default | Description |
+| ------------------ | ---------- | ---------- | ---------------------------------------------------- |
+| `bucketName` | `string` | `null` | The name of the Supabase Storage bucket to upload to |
+| `path` | `string` | `null` | The path or subfolder to upload the file to |
+| `allowedMimeTypes` | `string[]` | `[]` | The MIME types to allow for upload |
+| `maxFiles` | `number` | `1` | Maximum number of files to upload |
+| `maxFileSize` | `number` | `Infinity` | Maximum file size in bytes |
+
+## Further reading
+
+- [Creating buckets](https://supabase.com/docs/guides/storage/buckets/creating-buckets)
+- [Access control](https://supabase.com/docs/guides/storage/security/access-control)
+- [Standard uploads](https://supabase.com/docs/guides/storage/uploads/standard-uploads)
diff --git a/apps/ui-library/content/docs/vue/realtime-cursor.mdx b/apps/ui-library/content/docs/vue/realtime-cursor.mdx
new file mode 100644
index 00000000000..281bfdd4337
--- /dev/null
+++ b/apps/ui-library/content/docs/vue/realtime-cursor.mdx
@@ -0,0 +1,66 @@
+---
+title: Realtime Cursor
+description: Real-time cursor sharing for collaborative applications
+---
+
+<div className="flex flex-row -space-x-px w-full">
+ <BlockPreview name="realtime-cursor-demo" isPair />
+ <BlockPreview name="realtime-cursor-demo" isPair />
+</div>
+
+## Installation
+
+<BlockItem
+ name="realtime-cursor-vue"
+ description="Renders realtime cursors from other users in a room."
+/>
+
+## Folder structure
+
+This block assumes that you have already installed a Supabase client for Vue from the previous step.
+
+<RegistryBlock itemName="realtime-cursor-vue" />
+
+## Introduction
+
+The Realtime Cursors component lets users share their cursor position with others in the same room—perfect for real-time collaboration. It handles all the setup and boilerplate for you, so you can add it to your app with minimal effort.
+
+**Features**
+
+- Broadcast cursor position to other users in the same room
+- Customizable cursor appearance
+- Presence detection (automatically joins/leaves users)
+- Low-latency updates using Supabase Realtime
+- Room-based isolation for scoped collaboration
+
+## Usage
+
+The Realtime Cursor component is designed to be used in a room. It can be used to build real-time collaborative applications. Add the `<RealtimeCursors />` component to your page and it will render realtime cursors from other users in the room.
+
+```html
+<script setup lang="ts">
+ import RealtimeCursors from '@/components/RealtimeCursors.vue'
+</script>
+
+<template>
+ <div class="w-full min-h-screen">
+ <RealtimeCursors roomName="macrodata_refinement_office" username="Mark Scout" />
+ </div>
+</template>
+```
+
+## Props
+
+| Prop | Type | Description |
+| ---------- | -------- | ---------------------------------------------------------- |
+| `roomName` | `string` | Unique identifier for the shared room or session. |
+| `username` | `string` | Name of the current user; used to track and label cursors. |
+
+## Further reading
+
+- [Realtime Broadcast](https://supabase.com/docs/guides/realtime/broadcast)
+- [Realtime authorization](https://supabase.com/docs/guides/realtime/authorization)
+
+### Smoother cursors
+
+While our Realtime Cursor component aims to keep things simple and lightweight, you may want to add smoother cursor animations for a more polished experience. Libraries like [perfect-cursors](https://github.com/steveruizok/perfect-cursors) can be integrated to add sophisticated interpolation between cursor positions. This is especially useful when dealing with network latency, as it creates fluid cursor movements even when position updates are received at longer intervals (e.g., every 50-80ms). The library handles the complex math of creating natural-looking cursor paths while maintaining performance.
diff --git a/apps/ui-library/public/llms.txt b/apps/ui-library/public/llms.txt
index 179a12011d2..02e7abd8fad 100644
--- a/apps/ui-library/public/llms.txt
+++ b/apps/ui-library/public/llms.txt
@@ -1,5 +1,5 @@
# Supabase UI Library
-Last updated: 2025-11-20T11:14:14.146Z
+Last updated: 2026-01-22T19:37:07.586Z
## Overview
Library of components for your project. The components integrate with Supabase and are shadcn compatible.
@@ -33,8 +33,12 @@ Library of components for your project. The components integrate with Supabase a
- Social authentication block for Next.js
- [Supabase Client Libraries](https://supabase.com/ui/docs/nuxtjs/client)
- Supabase client for Nuxt.js
+- [Dropzone (File Upload)](https://supabase.com/ui/docs/nuxtjs/dropzone)
+ - Displays a control for easier uploading of files directly to Supabase Storage
- [Password-based Authentication](https://supabase.com/ui/docs/nuxtjs/password-based-auth)
- Password-based authentication block for Nuxt.js
+- [Realtime Cursor](https://supabase.com/ui/docs/nuxtjs/realtime-cursor)
+ - Real-time cursor sharing for collaborative applications
- [Social Authentication](https://supabase.com/ui/docs/nuxtjs/social-auth)
- Social authentication block for Nuxt.js
- [Platform Kit](https://supabase.com/ui/docs/platform/platform-kit)
@@ -89,7 +93,11 @@ Library of components for your project. The components integrate with Supabase a
- Social authentication block for Tanstack Start
- [Supabase Client Libraries](https://supabase.com/ui/docs/vue/client)
- Supabase client for Vue Single Page Applications
+- [Dropzone (File Upload)](https://supabase.com/ui/docs/vue/dropzone)
+ - Displays a control for easier uploading of files directly to Supabase Storage
- [Password-based Authentication](https://supabase.com/ui/docs/vue/password-based-auth)
- Password-based authentication block for Vue Single Page Applications
+- [Realtime Cursor](https://supabase.com/ui/docs/vue/realtime-cursor)
+ - Real-time cursor sharing for collaborative applications
- [Social Authentication](https://supabase.com/ui/docs/vue/social-auth)
- Social authentication block for Vue Single Page Applications
diff --git a/apps/ui-library/public/r/ai-editor-rules.json b/apps/ui-library/public/r/ai-editor-rules.json
index 7d59f8be252..375824e29c8 100644
--- a/apps/ui-library/public/r/ai-editor-rules.json
+++ b/apps/ui-library/public/r/ai-editor-rules.json
@@ -33,7 +33,7 @@
},
{
"path": "registry/default/ai-editor-rules/writing-supabase-edge-functions.mdc",
- "content": "---\ndescription: Coding rules for Supabase Edge Functions\nalwaysApply: false\n---\n\n# Writing Supabase Edge Functions\n\nYou're an expert in writing TypeScript and Deno JavaScript runtime. Generate **high-quality Supabase Edge Functions** that adhere to the following best practices:\n\n## Guidelines\n\n1. Try to use Web APIs and Deno’s core APIs instead of external dependencies (eg: use fetch instead of Axios, use WebSockets API instead of node-ws)\n2. If you are reusing utility methods between Edge Functions, add them to `supabase/functions/_shared` and import using a relative path. Do NOT have cross dependencies between Edge Functions.\n3. Do NOT use bare specifiers when importing dependecnies. If you need to use an external dependency, make sure it's prefixed with either `npm:` or `jsr:`. For example, `@supabase/supabase-js` should be written as `npm:@supabase/supabase-js`.\n4. For external imports, always define a version. For example, `npm:@express` should be written as `npm:[email protected]`.\n5. For external dependencies, importing via `npm:` and `jsr:` is preferred. Minimize the use of imports from @`deno.land/x` , `esm.sh` and @`unpkg.com` . If you have a package from one of those CDNs, you can replace the CDN hostname with `npm:` specifier.\n6. You can also use Node built-in APIs. You will need to import them using `node:` specifier. For example, to import Node process: `import process from \"node:process\". Use Node APIs when you find gaps in Deno APIs.\n7. Do NOT use `import { serve } from \"https://deno.land/[email protected]/http/server.ts\"`. Instead use the built-in `Deno.serve`.\n8. Following environment variables (ie. secrets) are pre-populated in both local and hosted Supabase environments. Users don't need to manually set them:\n - SUPABASE_URL\n - SUPABASE_PUBLISHABLE_OR_ANON_KEY\n - SUPABASE_SERVICE_ROLE_KEY\n - SUPABASE_DB_URL\n9. To set other environment variables (ie. secrets) users can put them in a env file and run the `supabase secrets set --env-file path/to/env-file`\n10. A single Edge Function can handle multiple routes. It is recommended to use a library like Express or Hono to handle the routes as it's easier for developer to understand and maintain. Each route must be prefixed with `/function-name` so they are routed correctly.\n11. File write operations are ONLY permitted on `/tmp` directory. You can use either Deno or Node File APIs.\n12. Use `EdgeRuntime.waitUntil(promise)` static method to run long-running tasks in the background without blocking response to a request. Do NOT assume it is available in the request / execution context.\n\n## Example Templates\n\n### Simple Hello World Function\n\n```tsx\ninterface reqPayload {\n name: string\n}\n\nconsole.info('server started')\n\nDeno.serve(async (req: Request) => {\n const { name }: reqPayload = await req.json()\n const data = {\n message: `Hello ${name} from foo!`,\n }\n\n return new Response(JSON.stringify(data), {\n headers: { 'Content-Type': 'application/json', Connection: 'keep-alive' },\n })\n})\n```\n\n### Example Function using Node built-in API\n\n```tsx\nimport { randomBytes } from 'node:crypto'\nimport { createServer } from 'node:http'\nimport process from 'node:process'\n\nconst generateRandomString = (length) => {\n const buffer = randomBytes(length)\n return buffer.toString('hex')\n}\n\nconst randomString = generateRandomString(10)\nconsole.log(randomString)\n\nconst server = createServer((req, res) => {\n const message = `Hello`\n res.end(message)\n})\n\nserver.listen(9999)\n```\n\n### Using npm packages in Functions\n\n```tsx\nimport express from 'npm:[email protected]'\n\nconst app = express()\n\napp.get(/(.*)/, (req, res) => {\n res.send('Welcome to Supabase')\n})\n\napp.listen(8000)\n```\n\n### Generate embeddings using built-in @Supabase.ai API\n\n```tsx\nconst model = new Supabase.ai.Session('gte-small')\n\nDeno.serve(async (req: Request) => {\n const params = new URL(req.url).searchParams\n const input = params.get('text')\n const output = await model.run(input, { mean_pool: true, normalize: true })\n return new Response(JSON.stringify(output), {\n headers: {\n 'Content-Type': 'application/json',\n Connection: 'keep-alive',\n },\n })\n})\n```\n",
+ "content": "---\ndescription: Coding rules for Supabase Edge Functions\nalwaysApply: false\n---\n\n# Writing Supabase Edge Functions\n\nYou're an expert in writing TypeScript and Deno JavaScript runtime. Generate **high-quality Supabase Edge Functions** that adhere to the following best practices:\n\n## Guidelines\n\n1. Try to use Web APIs and Deno’s core APIs instead of external dependencies (eg: use fetch instead of Axios, use WebSockets API instead of node-ws)\n2. If you are reusing utility methods between Edge Functions, add them to `supabase/functions/_shared` and import using a relative path. Do NOT have cross dependencies between Edge Functions.\n3. Do NOT use bare specifiers when importing dependencies. If you need to use an external dependency, make sure it's prefixed with either `npm:` or `jsr:`. For example, `@supabase/supabase-js` should be written as `npm:@supabase/supabase-js`.\n4. For external imports, always define a version. For example, `npm:@express` should be written as `npm:[email protected]`.\n5. For external dependencies, importing via `npm:` and `jsr:` is preferred. Minimize the use of imports from @`deno.land/x` , `esm.sh` and @`unpkg.com` . If you have a package from one of those CDNs, you can replace the CDN hostname with `npm:` specifier.\n6. You can also use Node built-in APIs. You will need to import them using `node:` specifier. For example, to import Node process: `import process from \"node:process\". Use Node APIs when you find gaps in Deno APIs.\n7. Do NOT use `import { serve } from \"https://deno.land/[email protected]/http/server.ts\"`. Instead use the built-in `Deno.serve`.\n8. Following environment variables (ie. secrets) are pre-populated in both local and hosted Supabase environments. Users don't need to manually set them:\n - SUPABASE_URL\n - SUPABASE_PUBLISHABLE_OR_ANON_KEY\n - SUPABASE_SERVICE_ROLE_KEY\n - SUPABASE_DB_URL\n9. To set other environment variables (ie. secrets) users can put them in a env file and run the `supabase secrets set --env-file path/to/env-file`\n10. A single Edge Function can handle multiple routes. It is recommended to use a library like Express or Hono to handle the routes as it's easier for developer to understand and maintain. Each route must be prefixed with `/function-name` so they are routed correctly.\n11. File write operations are ONLY permitted on `/tmp` directory. You can use either Deno or Node File APIs.\n12. Use `EdgeRuntime.waitUntil(promise)` static method to run long-running tasks in the background without blocking response to a request. Do NOT assume it is available in the request / execution context.\n\n## Example Templates\n\n### Simple Hello World Function\n\n```tsx\ninterface reqPayload {\n name: string\n}\n\nconsole.info('server started')\n\nDeno.serve(async (req: Request) => {\n const { name }: reqPayload = await req.json()\n const data = {\n message: `Hello ${name} from foo!`,\n }\n\n return new Response(JSON.stringify(data), {\n headers: { 'Content-Type': 'application/json', Connection: 'keep-alive' },\n })\n})\n```\n\n### Example Function using Node built-in API\n\n```tsx\nimport { randomBytes } from 'node:crypto'\nimport { createServer } from 'node:http'\nimport process from 'node:process'\n\nconst generateRandomString = (length) => {\n const buffer = randomBytes(length)\n return buffer.toString('hex')\n}\n\nconst randomString = generateRandomString(10)\nconsole.log(randomString)\n\nconst server = createServer((req, res) => {\n const message = `Hello`\n res.end(message)\n})\n\nserver.listen(9999)\n```\n\n### Using npm packages in Functions\n\n```tsx\nimport express from 'npm:[email protected]'\n\nconst app = express()\n\napp.get(/(.*)/, (req, res) => {\n res.send('Welcome to Supabase')\n})\n\napp.listen(8000)\n```\n\n### Generate embeddings using built-in @Supabase.ai API\n\n```tsx\nconst model = new Supabase.ai.Session('gte-small')\n\nDeno.serve(async (req: Request) => {\n const params = new URL(req.url).searchParams\n const input = params.get('text')\n const output = await model.run(input, { mean_pool: true, normalize: true })\n return new Response(JSON.stringify(output), {\n headers: {\n 'Content-Type': 'application/json',\n Connection: 'keep-alive',\n },\n })\n})\n```\n",
"type": "registry:file",
"target": "~/.cursor/rules/writing-supabase-edge-functions.mdc"
},
diff --git a/apps/ui-library/public/r/dropzone-nuxtjs.json b/apps/ui-library/public/r/dropzone-nuxtjs.json
new file mode 100644
index 00000000000..75767efe597
--- /dev/null
+++ b/apps/ui-library/public/r/dropzone-nuxtjs.json
@@ -0,0 +1,41 @@
+{
+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",
+ "name": "dropzone-nuxtjs",
+ "type": "registry:block",
+ "title": "Dropzone (File Upload) for Nuxt and Supabase",
+ "description": "Displays a control for easier uploading of files directly to Supabase Storage.",
+ "dependencies": [
+ "@supabase/supabase-js@latest",
+ "@vueuse/core",
+ "lucide-vue-next"
+ ],
+ "registryDependencies": [
+ "button"
+ ],
+ "files": [
+ {
+ "path": "registry/default/dropzone/nuxtjs/app/components/dropzone.vue",
+ "content": "<script setup lang=\"ts\">\nimport { provide, inject } from 'vue'\nimport { cn } from \"@/lib/utils\"\n\ninterface File {\n name: string\n errors: Array<{ message: string }>\n size: number\n lastModified?: number\n type?: string\n preview?: string\n}\n\nexport interface DropzoneProps {\n className?: string\n isDragActive?: boolean\n isDragReject?: boolean\n isSuccess?: boolean\n maxFiles?: number\n maxFileSize?: number\n inputRef?: HTMLInputElement | null\n setFiles: (files: File[]) => void\n onUpload: () => Promise<void>\n loading?: boolean\n successes: string[]\n errors: Array<{ name: string; message: string }>\n files: File[]\n getRootProps: (options?: Record<string, unknown>) => Record<string, unknown>\n getInputProps: () => Record<string, unknown>\n}\n\nexport const formatBytes = (\n bytes: number,\n decimals = 2,\n size?: 'bytes' | 'KB' | 'MB' | 'GB' | 'TB' | 'PB' | 'EB' | 'ZB' | 'YB'\n) => {\n const k = 1000\n const dm = decimals < 0 ? 0 : decimals\n const sizes = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']\n\n if (!bytes || bytes < 0) return size ? `0 ${size}` : '0 bytes'\n\n const i = size\n ? Math.max(0, sizes.indexOf(size))\n : Math.max(0, Math.min(sizes.length - 1, Math.floor(Math.log(bytes) / Math.log(k))))\n\n return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]\n}\n\n\nconst DropzoneContext = Symbol('DropzoneContext')\n\nexport function useDropzoneContext() {\n const ctx = inject<DropzoneProps>(DropzoneContext)\n if (!ctx) throw new Error('useDropzoneContext must be used within <Dropzone>')\n return ctx\n}\n\nconst props = defineProps<DropzoneProps>()\n\nprovide(DropzoneContext, props)\n</script>\n\n<template>\n <div\n v-bind=\"props.getRootProps({\n class: cn(\n 'border-2 border-gray-300 rounded-lg p-6 text-center bg-card transition-colors duration-300 text-foreground',\n props.className,\n props.isSuccess ? 'border-solid' : 'border-dashed',\n props.isDragActive && 'border-primary bg-primary/10',\n ((props.isDragActive && props.isDragReject) ||\n (props.errors.length > 0 && !props.isSuccess) ||\n props.files.some(f => f.errors.length !== 0))\n && 'border-destructive bg-destructive/10'\n )\n })\"\n >\n <input v-bind=\"props.getInputProps()\" />\n <slot />\n </div>\n</template>\n",
+ "type": "registry:component",
+ "target": "app/components/dropzone.vue"
+ },
+ {
+ "path": "registry/default/dropzone/nuxtjs/app/components/dropzone-empty-state.vue",
+ "content": "<script setup lang=\"ts\">\nimport { Upload } from 'lucide-vue-next'\nimport { cn } from '@/lib/utils'\nimport { useDropzoneContext, formatBytes } from './dropzone.vue'\n\nconst props = defineProps<{ className?: string }>()\n\nconst { maxFiles, maxFileSize, inputRef, isSuccess } = useDropzoneContext()\n</script>\n\n<template>\n <div v-if=\"!isSuccess\" :class=\"cn('flex flex-col items-center gap-y-2', props.className)\">\n <Upload size=\"20\" class=\"text-muted-foreground\" aria-hidden=\"true\" />\n\n <p class=\"text-sm\">\n Upload{{ maxFiles > 1 ? ` ${maxFiles}` : '' }} file{{ maxFiles !== 1 ? 's' : '' }}\n </p>\n\n <div class=\"flex flex-col items-center gap-y-1\">\n <p class=\"text-xs text-muted-foreground\">\n Drag and drop or\n <button\n type=\"button\"\n class=\"underline cursor-pointer hover:text-foreground\"\n @click=\"inputRef?.click()\"\n >\n select file{{ maxFiles !== 1 ? 's' : '' }}\n </button>\n to upload\n </p>\n\n <p v-if=\"maxFileSize !== Infinity\" class=\"text-xs text-muted-foreground\">\n Maximum file size: {{ formatBytes(maxFileSize) }}\n </p>\n </div>\n </div>\n</template>\n",
+ "type": "registry:component",
+ "target": "app/components/dropzone-empty-state.vue"
+ },
+ {
+ "path": "registry/default/dropzone/nuxtjs/app/components/dropzone-content.vue",
+ "content": "<script setup lang=\"ts\">\nimport { cn } from '@/lib/utils'\nimport { Button } from '@/components/ui/button'\nimport { CheckCircle, File, Loader2, X } from 'lucide-vue-next'\nimport { formatBytes, useDropzoneContext } from './dropzone.vue'\nimport { computed } from 'vue';\n\nconst props = defineProps<{ className?: string }>()\n\nconst {\n files,\n setFiles,\n onUpload,\n loading,\n successes,\n errors,\n maxFileSize,\n maxFiles,\n isSuccess,\n} = useDropzoneContext()\n\nconst exceedMaxFiles = computed(() => files.length > maxFiles)\n\nconst fileErrorMessages = computed(() => new Map(errors.map(e => [e.name, e.message])))\n\nfunction formatFileErrors(file: typeof files[number]) {\n if (!file.errors || file.errors.length === 0) return ''\n return file.errors\n .map(e =>\n e.message.startsWith('File is larger than')\n ? `File is larger than ${formatBytes(maxFileSize)} (Size: ${formatBytes(file.size)})`\n : e.message\n )\n .join(', ')\n}\n\nfunction handleRemoveFile(filename: string) {\n setFiles(files.filter(f => f.name !== filename))\n}\n</script>\n\n<template>\n <div :class=\"cn('flex flex-col', props.className)\">\n <!-- Success State -->\n <div v-if=\"isSuccess\" class=\"flex flex-row items-center gap-x-2 justify-center\" role=\"status\" aria-live=\"polite\">\n <CheckCircle size=\"16\" class=\"text-primary\" aria-hidden=\"true\"/>\n <p class=\"text-primary text-sm\">\n Successfully uploaded {{ files.length }} file{{ files.length > 1 ? 's' : '' }}\n </p>\n </div>\n\n <!-- File list -->\n <template v-else>\n <div\n v-for=\"(file, idx) in files\"\n :key=\"file?.name + '-' + file?.lastModified + '-' + file?.size || file?.name + '-' + idx\"\n class=\"flex items-center gap-x-4 border-b py-2 first:mt-4 last:mb-4\"\n >\n <div v-if=\"file.type.startsWith('image/')\"\n class=\"h-10 w-10 rounded border overflow-hidden shrink-0 bg-muted flex items-center justify-center\">\n <img :src=\"file.preview\" :alt=\"file.name\" class=\"object-cover\" />\n </div>\n\n <div v-else class=\"h-10 w-10 rounded border bg-muted flex items-center justify-center\">\n <File size=\"18\" aria-hidden=\"true\" />\n </div>\n\n <div class=\"shrink grow flex flex-col items-start truncate\">\n <p class=\"text-sm truncate max-w-full\" :title=\"file.name\">\n {{ file.name }}\n </p>\n\n <!-- ARIA live region for status messages -->\n <div aria-live=\"polite\" aria-atomic=\"true\">\n <!-- Errors -->\n <p v-if=\"file.errors.length > 0\" class=\"text-xs text-destructive\">\n {{ formatFileErrors(file) }}\n </p>\n\n <!-- Uploading -->\n <p v-else-if=\"loading\" class=\"text-xs text-muted-foreground\">Uploading file...</p>\n\n <!-- Failed -->\n <p v-else-if=\"fileErrorMessages.has(file.name)\" class=\"text-xs text-destructive\">\n Failed to upload: {{ fileErrorMessages.get(file.name) }}\n </p>\n\n <!-- Success -->\n <p v-else-if=\"successes.includes(file.name)\" class=\"text-xs text-primary\">\n Successfully uploaded file\n </p>\n\n <!-- Normal -->\n <p v-else class=\"text-xs text-muted-foreground\">\n {{ formatBytes(file.size) }}\n </p>\n </div>\n </div>\n\n <Button\n v-if=\"!loading && !successes.includes(file.name)\"\n aria-label=\"Remove file Button\"\n size=\"icon\"\n variant=\"link\"\n class=\"shrink-0 text-muted-foreground hover:text-foreground\"\n @click=\"handleRemoveFile(file.name)\"\n >\n <X />\n </Button>\n </div>\n\n <!-- Too many files -->\n <p v-if=\"exceedMaxFiles\" class=\"text-sm text-left mt-2 text-destructive\">\n You may upload only up to {{ maxFiles }} files, please remove\n {{ files.length - maxFiles }} file(s).\n </p>\n\n <!-- Upload button -->\n <div v-if=\"files.length > 0 && !exceedMaxFiles\" class=\"mt-2\">\n <Button\n variant=\"outline\"\n :disabled=\"files.some(f => f.errors.length) || loading\"\n @click=\"onUpload\"\n >\n <Loader2 v-if=\"loading\" class=\"mr-2 h-4 w-4 animate-spin\" />\n <template v-if=\"loading\">Uploading...</template>\n <template v-else>Upload files</template>\n </Button>\n </div>\n </template>\n </div>\n</template>\n",
+ "type": "registry:component",
+ "target": "app/components/dropzone-content.vue"
+ },
+ {
+ "path": "registry/default/dropzone/nuxtjs/app/composables/useSupabaseUpload.ts",
+ "content": "import { ref, computed, watch, onUnmounted } from 'vue'\nimport { useDropZone } from '@vueuse/core'\nimport { createClient } from \"@/lib/supabase/client\"\n\nconst supabase = createClient()\n\nexport interface FileWithPreview extends File {\n preview?: string\n errors: { code: string; message: string }[]\n}\n\nexport type UseSupabaseUploadOptions = {\n bucketName: string\n path?: string\n allowedMimeTypes?: string[]\n maxFileSize?: number\n maxFiles?: number\n cacheControl?: number\n upsert?: boolean\n}\n\nfunction validateFileType(file: File, allowedTypes: string[]) {\n if (!allowedTypes.length) return []\n const isValid = allowedTypes.some(t =>\n t.endsWith('/*')\n ? file.type.startsWith(t.replace('/*', ''))\n : file.type === t\n )\n return isValid\n ? []\n : [{ code: 'invalid-type', message: 'Invalid file type' }]\n}\n\nfunction validateFileSize(file: File, maxSize: number) {\n return file.size > maxSize\n ? [{ code: 'file-too-large', message: `File is larger than allowed size` }]\n : []\n}\n\nexport function 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 = ref<FileWithPreview[]>([])\n const loading = ref(false)\n const errors = ref<{ name: string; message: string }[]>([])\n const successes = ref<string[]>([])\n\n const isSuccess = computed(() => {\n if (!errors.value.length && !successes.value.length) return false\n return !errors.value.length && successes.value.length === files.value.length\n })\n\n const dropZoneRef = ref<HTMLElement | null>(null)\n\n const { isOverDropZone } = useDropZone(dropZoneRef, {\n onDrop(droppedFiles: FileWithPreview[]) {\n if (!droppedFiles) return\n\n const newFiles: FileWithPreview[] = droppedFiles.map(file => ({\n ...(file as FileWithPreview),\n preview: URL.createObjectURL(file),\n errors: [\n ...validateFileType(file, allowedMimeTypes),\n ...validateFileSize(file, maxFileSize),\n ],\n }))\n\n files.value = [...files.value, ...newFiles]\n },\n })\n\n const onUpload = async () => {\n loading.value = true\n\n try {\n const filesWithErrors = errors.value.map(e => e.name)\n\n const filesToUpload =\n filesWithErrors.length > 0\n ? files.value.filter(\n f =>\n filesWithErrors.includes(f.name) ||\n !successes.value.includes(f.name)\n )\n : files.value\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\n return error\n ? { name: file.name, message: error.message }\n : { name: file.name, message: undefined }\n })\n )\n\n errors.value = responses.filter((r): r is { name: string; message: string } => r.message !== undefined)\n\n const successful = responses\n .filter(r => !r.message)\n .map(r => r.name)\n\n successes.value = Array.from(\n new Set([...successes.value, ...successful])\n )\n } catch (err) {\n console.error('Upload failed unexpectedly:', err)\n\n errors.value.push({\n name: 'upload',\n message: 'An unexpected error occurred during upload.',\n })\n } finally {\n loading.value = false\n }\n }\n\n\n watch(\n () => files.value.length,\n () => {\n if (!files.value.length) {\n errors.value = []\n successes.value = []\n }\n\n if (files.value.length > maxFiles) {\n errors.value.push({\n name: 'files',\n message: `You may upload up to ${maxFiles} files`,\n })\n }\n }\n )\n\n watch(\n files,\n (newFiles, oldFiles) => {\n const newPreviews = new Set(newFiles.map(f => f.preview))\n oldFiles.forEach(file => {\n if (file.preview && !newPreviews.has(file.preview)) {\n URL.revokeObjectURL(file.preview)\n }\n })\n },\n { deep: true }\n )\n\n onUnmounted(() => {\n files.value.forEach(file => {\n if (file.preview) {\n URL.revokeObjectURL(file.preview)\n }\n })\n })\n\n return {\n dropZoneRef,\n isOverDropZone,\n\n files,\n setFiles: (v: FileWithPreview[]) => (files.value = v),\n\n errors,\n setErrors: (v: { name: string; message: string }[]) => (errors.value = v),\n\n successes,\n isSuccess,\n loading,\n onUpload,\n\n maxFileSize,\n maxFiles,\n allowedMimeTypes,\n }\n}\n",
+ "type": "registry:component",
+ "target": "app/composables/useSupabaseUpload.ts"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/apps/ui-library/public/r/dropzone-vue.json b/apps/ui-library/public/r/dropzone-vue.json
new file mode 100644
index 00000000000..596e2fb612f
--- /dev/null
+++ b/apps/ui-library/public/r/dropzone-vue.json
@@ -0,0 +1,41 @@
+{
+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",
+ "name": "dropzone-vue",
+ "type": "registry:block",
+ "title": "Dropzone (File Upload) for Vue and Supabase",
+ "description": "Displays a control for easier uploading of files directly to Supabase Storage.",
+ "dependencies": [
+ "@supabase/supabase-js@latest",
+ "@vueuse/core",
+ "lucide-vue-next"
+ ],
+ "registryDependencies": [
+ "button"
+ ],
+ "files": [
+ {
+ "path": "registry/default/dropzone/vue/components/dropzone.vue",
+ "content": "<script setup lang=\"ts\">\nimport { provide, inject } from 'vue'\nimport { cn } from \"@/lib/utils\"\n\ninterface File {\n name: string\n errors: Array<{ message: string }>\n size: number\n lastModified?: number\n type?: string\n preview?: string\n}\n\nexport interface DropzoneProps {\n className?: string\n isDragActive?: boolean\n isDragReject?: boolean\n isSuccess?: boolean\n maxFiles?: number\n maxFileSize?: number\n inputRef?: HTMLInputElement | null\n setFiles: (files: File[]) => void\n onUpload: () => Promise<void>\n loading?: boolean\n successes: string[]\n errors: Array<{ name: string; message: string }>\n files: File[]\n getRootProps: (options?: Record<string, unknown>) => Record<string, unknown>\n getInputProps: () => Record<string, unknown>\n}\n\nexport const formatBytes = (\n bytes: number,\n decimals = 2,\n size?: 'bytes' | 'KB' | 'MB' | 'GB' | 'TB' | 'PB' | 'EB' | 'ZB' | 'YB'\n) => {\n const k = 1000\n const dm = decimals < 0 ? 0 : decimals\n const sizes = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']\n\n if (!bytes || bytes < 0) return size ? `0 ${size}` : '0 bytes'\n\n const i = size\n ? Math.max(0, sizes.indexOf(size))\n : Math.max(0, Math.min(sizes.length - 1, Math.floor(Math.log(bytes) / Math.log(k))))\n\n return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]\n}\n\n\nconst DropzoneContext = Symbol('DropzoneContext')\n\nexport function useDropzoneContext() {\n const ctx = inject<DropzoneProps>(DropzoneContext)\n if (!ctx) throw new Error('useDropzoneContext must be used within <Dropzone>')\n return ctx\n}\n\nconst props = defineProps<DropzoneProps>()\n\nprovide(DropzoneContext, props)\n</script>\n\n<template>\n <div\n v-bind=\"props.getRootProps({\n class: cn(\n 'border-2 border-gray-300 rounded-lg p-6 text-center bg-card transition-colors duration-300 text-foreground',\n props.className,\n props.isSuccess ? 'border-solid' : 'border-dashed',\n props.isDragActive && 'border-primary bg-primary/10',\n ((props.isDragActive && props.isDragReject) ||\n (props.errors.length > 0 && !props.isSuccess) ||\n props.files.some(f => f.errors.length !== 0))\n && 'border-destructive bg-destructive/10'\n )\n })\"\n >\n <input v-bind=\"props.getInputProps()\" />\n <slot />\n </div>\n</template>\n",
+ "type": "registry:component",
+ "target": "components/dropzone.vue"
+ },
+ {
+ "path": "registry/default/dropzone/vue/components/dropzone-empty-state.vue",
+ "content": "<script setup lang=\"ts\">\nimport { Upload } from 'lucide-vue-next'\nimport { cn } from '@/lib/utils'\nimport { useDropzoneContext, formatBytes } from './dropzone.vue'\n\nconst props = defineProps<{ className?: string }>()\n\nconst { maxFiles, maxFileSize, inputRef, isSuccess } = useDropzoneContext()\n</script>\n\n<template>\n <div v-if=\"!isSuccess\" :class=\"cn('flex flex-col items-center gap-y-2', props.className)\">\n <Upload size=\"20\" class=\"text-muted-foreground\" aria-hidden=\"true\"/>\n\n <p class=\"text-sm\">\n Upload{{ maxFiles > 1 ? ` ${maxFiles}` : '' }} file{{ maxFiles !== 1 ? 's' : '' }}\n </p>\n\n <div class=\"flex flex-col items-center gap-y-1\">\n <p class=\"text-xs text-muted-foreground\">\n Drag and drop or\n <button\n type=\"button\"\n class=\"underline cursor-pointer hover:text-foreground\"\n @click=\"inputRef?.click()\"\n >\n select file{{ maxFiles !== 1 ? 's' : '' }}\n </button>\n to upload\n </p>\n\n <p v-if=\"maxFileSize !== Infinity\" class=\"text-xs text-muted-foreground\">\n Maximum file size: {{ formatBytes(maxFileSize) }}\n </p>\n </div>\n </div>\n</template>\n",
+ "type": "registry:component",
+ "target": "components/dropzone-empty-state.vue"
+ },
+ {
+ "path": "registry/default/dropzone/vue/components/dropzone-content.vue",
+ "content": "<script setup lang=\"ts\">\nimport { cn } from '@/lib/utils'\nimport { Button } from '@/components/ui/button'\nimport { CheckCircle, File, Loader2, X } from 'lucide-vue-next'\nimport { formatBytes, useDropzoneContext } from './dropzone.vue'\nimport { computed } from 'vue';\n\nconst props = defineProps<{ className?: string }>()\n\nconst {\n files,\n setFiles,\n onUpload,\n loading,\n successes,\n errors,\n maxFileSize,\n maxFiles,\n isSuccess,\n} = useDropzoneContext()\n\nconst exceedMaxFiles = computed(() => files.length > maxFiles)\n\nconst fileErrorMessages = computed(() => new Map(errors.map(e => [e.name, e.message])))\n\nfunction formatFileErrors(file: typeof files[number]) {\n if (!file.errors || file.errors.length === 0) return ''\n return file.errors\n .map(e =>\n e.message.startsWith('File is larger than')\n ? `File is larger than ${formatBytes(maxFileSize)} (Size: ${formatBytes(file.size)})`\n : e.message\n )\n .join(', ')\n}\n\nfunction handleRemoveFile(filename: string) {\n setFiles(files.filter(f => f.name !== filename))\n}\n</script>\n\n<template>\n <div :class=\"cn('flex flex-col', props.className)\">\n <!-- Success State -->\n <div v-if=\"isSuccess\" class=\"flex flex-row items-center gap-x-2 justify-center\" role=\"status\" aria-live=\"polite\">\n <CheckCircle size=\"16\" class=\"text-primary\" aria-hidden=\"true\"/>\n <p class=\"text-primary text-sm\">\n Successfully uploaded {{ files.length }} file{{ files.length > 1 ? 's' : '' }}\n </p>\n </div>\n\n <!-- File list -->\n <template v-else>\n <div\n v-for=\"(file, idx) in files\"\n :key=\"file?.name + '-' + file?.lastModified + '-' + file?.size || file?.name + '-' + idx\"\n class=\"flex items-center gap-x-4 border-b py-2 first:mt-4 last:mb-4\"\n >\n <div v-if=\"file.type.startsWith('image/')\"\n class=\"h-10 w-10 rounded border overflow-hidden shrink-0 bg-muted flex items-center justify-center\">\n <img :src=\"file.preview\" :alt=\"file.name\" class=\"object-cover\" />\n </div>\n\n <div v-else class=\"h-10 w-10 rounded border bg-muted flex items-center justify-center\">\n <File size=\"18\" aria-hidden=\"true\" />\n </div>\n\n <div class=\"shrink grow flex flex-col items-start truncate\">\n <p class=\"text-sm truncate max-w-full\" :title=\"file.name\">\n {{ file.name }}\n </p>\n\n <!-- ARIA live region for status messages -->\n <div aria-live=\"polite\" aria-atomic=\"true\">\n <!-- Errors -->\n <p v-if=\"file.errors.length > 0\" class=\"text-xs text-destructive\">\n {{ formatFileErrors(file) }}\n </p>\n\n <!-- Uploading -->\n <p v-else-if=\"loading\" class=\"text-xs text-muted-foreground\">Uploading file...</p>\n\n <!-- Failed -->\n <p v-else-if=\"fileErrorMessages.has(file.name)\" class=\"text-xs text-destructive\">\n Failed to upload: {{ fileErrorMessages.get(file.name) }}\n </p>\n\n <!-- Success -->\n <p v-else-if=\"successes.includes(file.name)\" class=\"text-xs text-primary\">\n Successfully uploaded file\n </p>\n\n <!-- Normal -->\n <p v-else class=\"text-xs text-muted-foreground\">\n {{ formatBytes(file.size) }}\n </p>\n </div>\n </div>\n\n <Button\n v-if=\"!loading && !successes.includes(file.name)\"\n aria-label=\"Remove file Button\"\n size=\"icon\"\n variant=\"link\"\n class=\"shrink-0 text-muted-foreground hover:text-foreground\"\n @click=\"handleRemoveFile(file.name)\"\n >\n <X />\n </Button>\n </div>\n\n <!-- Too many files -->\n <p v-if=\"exceedMaxFiles\" class=\"text-sm text-left mt-2 text-destructive\">\n You may upload only up to {{ maxFiles }} files, please remove\n {{ files.length - maxFiles }} file(s).\n </p>\n\n <!-- Upload button -->\n <div v-if=\"files.length > 0 && !exceedMaxFiles\" class=\"mt-2\">\n <Button\n variant=\"outline\"\n :disabled=\"files.some(f => f.errors.length) || loading\"\n @click=\"onUpload\"\n >\n <Loader2 v-if=\"loading\" class=\"mr-2 h-4 w-4 animate-spin\" aria-hidden=\"true\" />\n <template v-if=\"loading\">Uploading...</template>\n <template v-else>Upload files</template>\n </Button>\n </div>\n </template>\n </div>\n</template>\n",
+ "type": "registry:component",
+ "target": "components/dropzone-content.vue"
+ },
+ {
+ "path": "registry/default/dropzone/vue/composables/useSupabaseUpload.ts",
+ "content": "import { ref, computed, watch, onUnmounted } from 'vue'\nimport { useDropZone } from '@vueuse/core'\nimport { createClient } from \"@/lib/supabase/client\"\n\nconst supabase = createClient()\n\nexport interface FileWithPreview extends File {\n preview?: string\n errors: { code: string; message: string }[]\n}\n\nexport type UseSupabaseUploadOptions = {\n bucketName: string\n path?: string\n allowedMimeTypes?: string[]\n maxFileSize?: number\n maxFiles?: number\n cacheControl?: number\n upsert?: boolean\n}\n\nfunction validateFileType(file: File, allowedTypes: string[]) {\n if (!allowedTypes.length) return []\n const isValid = allowedTypes.some(t =>\n t.endsWith('/*')\n ? file.type.startsWith(t.replace('/*', ''))\n : file.type === t\n )\n return isValid\n ? []\n : [{ code: 'invalid-type', message: 'Invalid file type' }]\n}\n\nfunction validateFileSize(file: File, maxSize: number) {\n return file.size > maxSize\n ? [{ code: 'file-too-large', message: `File is larger than allowed size` }]\n : []\n}\n\nexport function 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 = ref<FileWithPreview[]>([])\n const loading = ref(false)\n const errors = ref<{ name: string; message: string }[]>([])\n const successes = ref<string[]>([])\n\n const isSuccess = computed(() => {\n if (!errors.value.length && !successes.value.length) return false\n return !errors.value.length && successes.value.length === files.value.length\n })\n\n const dropZoneRef = ref<HTMLElement | null>(null)\n\n const { isOverDropZone } = useDropZone(dropZoneRef, {\n onDrop(droppedFiles: FileWithPreview[]) {\n if (!droppedFiles) return\n\n const newFiles: FileWithPreview[] = droppedFiles.map(file => ({\n ...(file as FileWithPreview),\n preview: URL.createObjectURL(file),\n errors: [\n ...validateFileType(file, allowedMimeTypes),\n ...validateFileSize(file, maxFileSize),\n ],\n }))\n\n files.value = [...files.value, ...newFiles]\n },\n })\n\n const onUpload = async () => {\n loading.value = true\n\n try {\n const filesWithErrors = errors.value.map(e => e.name)\n\n const filesToUpload =\n filesWithErrors.length > 0\n ? files.value.filter(\n f =>\n filesWithErrors.includes(f.name) ||\n !successes.value.includes(f.name)\n )\n : files.value\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\n return error\n ? { name: file.name, message: error.message }\n : { name: file.name, message: undefined }\n })\n )\n\n errors.value = responses.filter((r): r is { name: string; message: string } => r.message !== undefined)\n\n const successful = responses\n .filter(r => !r.message)\n .map(r => r.name)\n\n successes.value = Array.from(\n new Set([...successes.value, ...successful])\n )\n } catch (err) {\n console.error('Upload failed unexpectedly:', err)\n\n errors.value.push({\n name: 'upload',\n message: 'An unexpected error occurred during upload.',\n })\n } finally {\n loading.value = false\n }\n }\n\n\n watch(\n () => files.value.length,\n () => {\n if (!files.value.length) {\n errors.value = []\n successes.value = []\n }\n\n if (files.value.length > maxFiles) {\n errors.value.push({\n name: 'files',\n message: `You may upload up to ${maxFiles} files`,\n })\n }\n }\n )\n\n watch(\n files,\n (newFiles, oldFiles) => {\n const newPreviews = new Set(newFiles.map(f => f.preview))\n oldFiles.forEach(file => {\n if (file.preview && !newPreviews.has(file.preview)) {\n URL.revokeObjectURL(file.preview)\n }\n })\n },\n { deep: true }\n )\n\n onUnmounted(() => {\n files.value.forEach(file => {\n if (file.preview) {\n URL.revokeObjectURL(file.preview)\n }\n })\n })\n\n return {\n dropZoneRef,\n isOverDropZone,\n\n files,\n setFiles: (v: FileWithPreview[]) => (files.value = v),\n\n errors,\n setErrors: (v: { name: string; message: string }[]) => (errors.value = v),\n\n successes,\n isSuccess,\n loading,\n onUpload,\n\n maxFileSize,\n maxFiles,\n allowedMimeTypes,\n }\n}\n",
+ "type": "registry:component",
+ "target": "composables/useSupabaseUpload.ts"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/apps/ui-library/public/r/password-based-auth-react-router.json b/apps/ui-library/public/r/password-based-auth-react-router.json
index 5f24bcffc3e..a6d3e31ef17 100644
--- a/apps/ui-library/public/r/password-based-auth-react-router.json
+++ b/apps/ui-library/public/r/password-based-auth-react-router.json
@@ -55,7 +55,7 @@
},
{
"path": "registry/default/blocks/password-based-auth-react-router/app/routes/sign-up.tsx",
- "content": "import { createClient } from '@/registry/default/clients/react-router/lib/supabase/server'\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'\nimport { Input } from '@/registry/default/components/ui/input'\nimport { Label } from '@/registry/default/components/ui/label'\nimport { type ActionFunctionArgs, Link, redirect, useFetcher, useSearchParams } from 'react-router'\n\nexport const action = async ({ request }: ActionFunctionArgs) => {\n const { supabase } = createClient(request)\n\n const url = new URL(request.url)\n const origin = url.origin\n\n const formData = await request.formData()\n\n const email = formData.get('email') as string\n const password = formData.get('password') as string\n const repeatPassword = formData.get('repeat-password') as string\n\n if (!password) {\n return {\n error: 'Password is required',\n }\n }\n\n if (password !== repeatPassword) {\n return { error: 'Passwords do not match' }\n }\n\n const { error } = await supabase.auth.signUp({\n email,\n password,\n options: {\n emailRedirectTo: `${origin}/protected`,\n },\n })\n\n if (error) {\n return { error: error.message }\n }\n\n return redirect('/sign-up?success')\n}\n\nexport default function SignUp() {\n const fetcher = useFetcher<typeof action>()\n let [searchParams] = useSearchParams()\n\n const success = !!searchParams.has('success')\n const error = fetcher.data?.error\n const loading = fetcher.state === 'submitting'\n\n return (\n <div className=\"flex min-h-svh w-full items-center justify-center p-6 md:p-10\">\n <div className=\"w-full max-w-sm\">\n <div className=\"flex flex-col gap-6\">\n {success ? (\n <Card>\n <CardHeader>\n <CardTitle className=\"text-2xl\">Thank you for signing up!</CardTitle>\n <CardDescription>Check your email to confirm</CardDescription>\n </CardHeader>\n <CardContent>\n <p className=\"text-sm text-muted-foreground\">\n You've successfully signed up. Please check your email to confirm your account\n before signing in.\n </p>\n </CardContent>\n </Card>\n ) : (\n <Card>\n <CardHeader>\n <CardTitle className=\"text-2xl\">Sign up</CardTitle>\n <CardDescription>Create a new account</CardDescription>\n </CardHeader>\n <CardContent>\n <fetcher.Form method=\"post\">\n <div className=\"flex flex-col gap-6\">\n <div className=\"grid gap-2\">\n <Label htmlFor=\"email\">Email</Label>\n <Input\n id=\"email\"\n name=\"email\"\n type=\"email\"\n placeholder=\"[email protected]\"\n required\n />\n </div>\n <div className=\"grid gap-2\">\n <div className=\"flex items-center\">\n <Label htmlFor=\"password\">Password</Label>\n </div>\n <Input id=\"password\" name=\"password\" type=\"password\" required />\n </div>\n <div className=\"grid gap-2\">\n <div className=\"flex items-center\">\n <Label htmlFor=\"repeat-password\">Repeat Password</Label>\n </div>\n <Input id=\"repeat-password\" name=\"repeat-password\" type=\"password\" required />\n </div>\n {error && <p className=\"text-sm text-red-500\">{error}</p>}\n <Button type=\"submit\" className=\"w-full\" disabled={loading}>\n {loading ? 'Creating an account...' : 'Sign up'}\n </Button>\n </div>\n <div className=\"mt-4 text-center text-sm\">\n Already have an account?{' '}\n <Link to=\"/login\" className=\"underline underline-offset-4\">\n Login\n </Link>\n </div>\n </fetcher.Form>\n </CardContent>\n </Card>\n )}\n </div>\n </div>\n </div>\n )\n}\n",
+ "content": "import { createClient } from '@/registry/default/clients/react-router/lib/supabase/server'\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'\nimport { Input } from '@/registry/default/components/ui/input'\nimport { Label } from '@/registry/default/components/ui/label'\nimport { type ActionFunctionArgs, Link, redirect, useFetcher, useSearchParams } from 'react-router'\n\nexport const action = async ({ request }: ActionFunctionArgs) => {\n const { supabase } = createClient(request)\n\n const url = new URL(request.url)\n const origin = url.origin\n\n const formData = await request.formData()\n\n const email = formData.get('email') as string\n const password = formData.get('password') as string\n const repeatPassword = formData.get('repeat-password') as string\n\n if (!password) {\n return {\n error: 'Password is required',\n }\n }\n\n if (password !== repeatPassword) {\n return { error: 'Passwords do not match' }\n }\n\n const { error } = await supabase.auth.signUp({\n email,\n password,\n options: {\n emailRedirectTo: `${origin}/protected`,\n },\n })\n\n if (error) {\n return { error: error.message }\n }\n\n return redirect('/sign-up?success')\n}\n\nexport default function SignUp() {\n const fetcher = useFetcher<typeof action>()\n let [searchParams] = useSearchParams()\n\n const success = !!searchParams.has('success')\n const error = fetcher.data?.error\n const loading = fetcher.state === 'submitting'\n\n return (\n <div className=\"flex min-h-svh w-full items-center justify-center p-6 md:p-10\">\n <div className=\"w-full max-w-sm\">\n <div className=\"flex flex-col gap-6\">\n {success ? (\n <Card>\n <CardHeader>\n <CardTitle className=\"text-2xl\">Thank you for signing up!</CardTitle>\n <CardDescription>Check your email to confirm</CardDescription>\n </CardHeader>\n <CardContent>\n <p className=\"text-sm text-muted-foreground\">\n You&apos;ve successfully signed up. Please check your email to confirm your\n account before signing in.\n </p>\n </CardContent>\n </Card>\n ) : (\n <Card>\n <CardHeader>\n <CardTitle className=\"text-2xl\">Sign up</CardTitle>\n <CardDescription>Create a new account</CardDescription>\n </CardHeader>\n <CardContent>\n <fetcher.Form method=\"post\">\n <div className=\"flex flex-col gap-6\">\n <div className=\"grid gap-2\">\n <Label htmlFor=\"email\">Email</Label>\n <Input\n id=\"email\"\n name=\"email\"\n type=\"email\"\n placeholder=\"[email protected]\"\n required\n />\n </div>\n <div className=\"grid gap-2\">\n <div className=\"flex items-center\">\n <Label htmlFor=\"password\">Password</Label>\n </div>\n <Input id=\"password\" name=\"password\" type=\"password\" required />\n </div>\n <div className=\"grid gap-2\">\n <div className=\"flex items-center\">\n <Label htmlFor=\"repeat-password\">Repeat Password</Label>\n </div>\n <Input id=\"repeat-password\" name=\"repeat-password\" type=\"password\" required />\n </div>\n {error && <p className=\"text-sm text-red-500\">{error}</p>}\n <Button type=\"submit\" className=\"w-full\" disabled={loading}>\n {loading ? 'Creating an account...' : 'Sign up'}\n </Button>\n </div>\n <div className=\"mt-4 text-center text-sm\">\n Already have an account?{' '}\n <Link to=\"/login\" className=\"underline underline-offset-4\">\n Login\n </Link>\n </div>\n </fetcher.Form>\n </CardContent>\n </Card>\n )}\n </div>\n </div>\n </div>\n )\n}\n",
"type": "registry:file",
"target": "app/routes/sign-up.tsx"
},
diff --git a/apps/ui-library/public/r/password-based-auth-react.json b/apps/ui-library/public/r/password-based-auth-react.json
index a50604835e8..75fdd187e97 100644
--- a/apps/ui-library/public/r/password-based-auth-react.json
+++ b/apps/ui-library/public/r/password-based-auth-react.json
@@ -21,7 +21,7 @@
},
{
"path": "registry/default/blocks/password-based-auth-react/components/sign-up-form.tsx",
- "content": "import { 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'\nimport { Input } from '@/registry/default/components/ui/input'\nimport { Label } from '@/registry/default/components/ui/label'\nimport { useState } from 'react'\n\nexport function SignUpForm({ className, ...props }: React.ComponentPropsWithoutRef<'div'>) {\n const [email, setEmail] = useState('')\n const [password, setPassword] = useState('')\n const [repeatPassword, setRepeatPassword] = useState('')\n const [error, setError] = useState<string | null>(null)\n const [isLoading, setIsLoading] = useState(false)\n const [success, setSuccess] = useState(false)\n\n const handleSignUp = async (e: React.FormEvent) => {\n const supabase = createClient()\n e.preventDefault()\n setError(null)\n\n if (password !== repeatPassword) {\n setError('Passwords do not match')\n return\n }\n setIsLoading(true)\n\n try {\n const { error } = await supabase.auth.signUp({\n email,\n password,\n })\n if (error) throw error\n setSuccess(true)\n } catch (error: unknown) {\n setError(error instanceof Error ? error.message : 'An error occurred')\n } finally {\n setIsLoading(false)\n }\n }\n\n return (\n <div className={cn('flex flex-col gap-6', className)} {...props}>\n {success ? (\n <Card>\n <CardHeader>\n <CardTitle className=\"text-2xl\">Thank you for signing up!</CardTitle>\n <CardDescription>Check your email to confirm</CardDescription>\n </CardHeader>\n <CardContent>\n <p className=\"text-sm text-muted-foreground\">\n You've successfully signed up. Please check your email to confirm your account before\n signing in.\n </p>\n </CardContent>\n </Card>\n ) : (\n <Card>\n <CardHeader>\n <CardTitle className=\"text-2xl\">Sign up</CardTitle>\n <CardDescription>Create a new account</CardDescription>\n </CardHeader>\n <CardContent>\n <form onSubmit={handleSignUp}>\n <div className=\"flex flex-col gap-6\">\n <div className=\"grid gap-2\">\n <Label htmlFor=\"email\">Email</Label>\n <Input\n id=\"email\"\n type=\"email\"\n placeholder=\"[email protected]\"\n required\n value={email}\n onChange={(e) => setEmail(e.target.value)}\n />\n </div>\n <div className=\"grid gap-2\">\n <div className=\"flex items-center\">\n <Label htmlFor=\"password\">Password</Label>\n </div>\n <Input\n id=\"password\"\n type=\"password\"\n required\n value={password}\n onChange={(e) => setPassword(e.target.value)}\n />\n </div>\n <div className=\"grid gap-2\">\n <div className=\"flex items-center\">\n <Label htmlFor=\"repeat-password\">Repeat Password</Label>\n </div>\n <Input\n id=\"repeat-password\"\n type=\"password\"\n required\n value={repeatPassword}\n onChange={(e) => setRepeatPassword(e.target.value)}\n />\n </div>\n {error && <p className=\"text-sm text-red-500\">{error}</p>}\n <Button type=\"submit\" className=\"w-full\" disabled={isLoading}>\n {isLoading ? 'Creating an account...' : 'Sign up'}\n </Button>\n </div>\n <div className=\"mt-4 text-center text-sm\">\n Already have an account?{' '}\n <a href=\"/login\" className=\"underline underline-offset-4\">\n Login\n </a>\n </div>\n </form>\n </CardContent>\n </Card>\n )}\n </div>\n )\n}\n",
+ "content": "import { 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'\nimport { Input } from '@/registry/default/components/ui/input'\nimport { Label } from '@/registry/default/components/ui/label'\nimport { useState } from 'react'\n\nexport function SignUpForm({ className, ...props }: React.ComponentPropsWithoutRef<'div'>) {\n const [email, setEmail] = useState('')\n const [password, setPassword] = useState('')\n const [repeatPassword, setRepeatPassword] = useState('')\n const [error, setError] = useState<string | null>(null)\n const [isLoading, setIsLoading] = useState(false)\n const [success, setSuccess] = useState(false)\n\n const handleSignUp = async (e: React.FormEvent) => {\n const supabase = createClient()\n e.preventDefault()\n setError(null)\n\n if (password !== repeatPassword) {\n setError('Passwords do not match')\n return\n }\n setIsLoading(true)\n\n try {\n const { error } = await supabase.auth.signUp({\n email,\n password,\n })\n if (error) throw error\n setSuccess(true)\n } catch (error: unknown) {\n setError(error instanceof Error ? error.message : 'An error occurred')\n } finally {\n setIsLoading(false)\n }\n }\n\n return (\n <div className={cn('flex flex-col gap-6', className)} {...props}>\n {success ? (\n <Card>\n <CardHeader>\n <CardTitle className=\"text-2xl\">Thank you for signing up!</CardTitle>\n <CardDescription>Check your email to confirm</CardDescription>\n </CardHeader>\n <CardContent>\n <p className=\"text-sm text-muted-foreground\">\n You&apos;ve successfully signed up. Please check your email to confirm your account\n before signing in.\n </p>\n </CardContent>\n </Card>\n ) : (\n <Card>\n <CardHeader>\n <CardTitle className=\"text-2xl\">Sign up</CardTitle>\n <CardDescription>Create a new account</CardDescription>\n </CardHeader>\n <CardContent>\n <form onSubmit={handleSignUp}>\n <div className=\"flex flex-col gap-6\">\n <div className=\"grid gap-2\">\n <Label htmlFor=\"email\">Email</Label>\n <Input\n id=\"email\"\n type=\"email\"\n placeholder=\"[email protected]\"\n required\n value={email}\n onChange={(e) => setEmail(e.target.value)}\n />\n </div>\n <div className=\"grid gap-2\">\n <div className=\"flex items-center\">\n <Label htmlFor=\"password\">Password</Label>\n </div>\n <Input\n id=\"password\"\n type=\"password\"\n required\n value={password}\n onChange={(e) => setPassword(e.target.value)}\n />\n </div>\n <div className=\"grid gap-2\">\n <div className=\"flex items-center\">\n <Label htmlFor=\"repeat-password\">Repeat Password</Label>\n </div>\n <Input\n id=\"repeat-password\"\n type=\"password\"\n required\n value={repeatPassword}\n onChange={(e) => setRepeatPassword(e.target.value)}\n />\n </div>\n {error && <p className=\"text-sm text-red-500\">{error}</p>}\n <Button type=\"submit\" className=\"w-full\" disabled={isLoading}>\n {isLoading ? 'Creating an account...' : 'Sign up'}\n </Button>\n </div>\n <div className=\"mt-4 text-center text-sm\">\n Already have an account?{' '}\n <a href=\"/login\" className=\"underline underline-offset-4\">\n Login\n </a>\n </div>\n </form>\n </CardContent>\n </Card>\n )}\n </div>\n )\n}\n",
"type": "registry:component"
},
{
diff --git a/apps/ui-library/public/r/password-based-auth-tanstack.json b/apps/ui-library/public/r/password-based-auth-tanstack.json
index 0d84095b204..9c5efdba4de 100644
--- a/apps/ui-library/public/r/password-based-auth-tanstack.json
+++ b/apps/ui-library/public/r/password-based-auth-tanstack.json
@@ -58,7 +58,7 @@
},
{
"path": "registry/default/blocks/password-based-auth-tanstack/routes/sign-up-success.tsx",
- "content": "import {\n Card,\n CardContent,\n CardDescription,\n CardHeader,\n CardTitle,\n} from '@/registry/default/components/ui/card'\nimport { createFileRoute } from '@tanstack/react-router'\n\nexport const Route = createFileRoute('/sign-up-success')({\n component: SignUpSuccess,\n})\n\nfunction SignUpSuccess() {\n return (\n <div className=\"flex min-h-svh w-full items-center justify-center p-6 md:p-10\">\n <div className=\"w-full max-w-sm\">\n <div className=\"flex flex-col gap-6\">\n <Card>\n <CardHeader>\n <CardTitle className=\"text-2xl\">Thank you for signing up!</CardTitle>\n <CardDescription>Check your email to confirm</CardDescription>\n </CardHeader>\n <CardContent>\n <p className=\"text-sm text-muted-foreground\">\n You've successfully signed up. Please check your email to confirm your account\n before signing in.\n </p>\n </CardContent>\n </Card>\n </div>\n </div>\n </div>\n )\n}\n",
+ "content": "import {\n Card,\n CardContent,\n CardDescription,\n CardHeader,\n CardTitle,\n} from '@/registry/default/components/ui/card'\nimport { createFileRoute } from '@tanstack/react-router'\n\nexport const Route = createFileRoute('/sign-up-success')({\n component: SignUpSuccess,\n})\n\nfunction SignUpSuccess() {\n return (\n <div className=\"flex min-h-svh w-full items-center justify-center p-6 md:p-10\">\n <div className=\"w-full max-w-sm\">\n <div className=\"flex flex-col gap-6\">\n <Card>\n <CardHeader>\n <CardTitle className=\"text-2xl\">Thank you for signing up!</CardTitle>\n <CardDescription>Check your email to confirm</CardDescription>\n </CardHeader>\n <CardContent>\n <p className=\"text-sm text-muted-foreground\">\n You&apos;ve successfully signed up. Please check your email to confirm your account\n before signing in.\n </p>\n </CardContent>\n </Card>\n </div>\n </div>\n </div>\n )\n}\n",
"type": "registry:file",
"target": "routes/sign-up-success.tsx"
},
diff --git a/apps/ui-library/public/r/platform-kit-nextjs.json b/apps/ui-library/public/r/platform-kit-nextjs.json
index f840a00a150..1df40283f0f 100644
--- a/apps/ui-library/public/r/platform-kit-nextjs.json
+++ b/apps/ui-library/public/r/platform-kit-nextjs.json
@@ -50,7 +50,7 @@
},
{
"path": "registry/default/platform/platform-kit-nextjs/app/api/supabase-proxy/[...path]/route.ts",
- "content": "import { NextResponse } from 'next/server'\n\nasync function forwardToSupabaseAPI(request: Request, method: string, params: { path: string[] }) {\n if (!process.env.SUPABASE_MANAGEMENT_API_TOKEN) {\n console.error('Supabase Management API token is not configured.')\n return NextResponse.json({ message: 'Server configuration error.' }, { status: 500 })\n }\n\n const { path } = params\n const apiPath = path.join('/')\n\n const url = new URL(request.url)\n url.protocol = 'https'\n url.hostname = 'api.supabase.com'\n url.port = '443'\n url.pathname = apiPath\n\n const projectRef = path[2]\n\n // Implement your permission check here (e.g. check if the user is a member of the project)\n // In this example, everyone can access all projects\n const userHasPermissionForProject = Boolean(projectRef)\n\n if (!userHasPermissionForProject) {\n return NextResponse.json(\n { message: 'You do not have permission to access this project.' },\n { status: 403 }\n )\n }\n\n try {\n const forwardHeaders: HeadersInit = {\n Authorization: `Bearer ${process.env.SUPABASE_MANAGEMENT_API_TOKEN}`,\n }\n\n // Copy relevant headers from the original request\n const contentType = request.headers.get('content-type')\n if (contentType) {\n forwardHeaders['Content-Type'] = contentType\n }\n\n const fetchOptions: RequestInit = {\n method,\n headers: forwardHeaders,\n }\n\n // Include body for methods that support it\n if (method !== 'GET' && method !== 'HEAD') {\n try {\n const body = await request.text()\n if (body) {\n fetchOptions.body = body\n }\n } catch (error) {\n // Handle cases where body is not readable\n console.warn('Could not read request body:', error)\n }\n }\n\n const response = await fetch(url, fetchOptions)\n\n // Get response body\n const responseText = await response.text()\n let responseData\n\n try {\n responseData = responseText ? JSON.parse(responseText) : null\n } catch {\n responseData = responseText\n }\n\n // Return the response with the same status\n return NextResponse.json(responseData, { status: response.status })\n } catch (error: any) {\n console.error('Supabase API proxy error:', error)\n const errorMessage = error.message || 'An unexpected error occurred.'\n return NextResponse.json({ message: errorMessage }, { status: 500 })\n }\n}\n\nexport async function GET(request: Request, { params }: { params: Promise<{ path: string[] }> }) {\n const resolvedParams = await params\n return forwardToSupabaseAPI(request, 'GET', resolvedParams)\n}\n\nexport async function HEAD(request: Request, { params }: { params: Promise<{ path: string[] }> }) {\n const resolvedParams = await params\n return forwardToSupabaseAPI(request, 'HEAD', resolvedParams)\n}\n\nexport async function POST(request: Request, { params }: { params: Promise<{ path: string[] }> }) {\n const resolvedParams = await params\n return forwardToSupabaseAPI(request, 'POST', resolvedParams)\n}\n\nexport async function PUT(request: Request, { params }: { params: Promise<{ path: string[] }> }) {\n const resolvedParams = await params\n return forwardToSupabaseAPI(request, 'PUT', resolvedParams)\n}\n\nexport async function DELETE(\n request: Request,\n { params }: { params: Promise<{ path: string[] }> }\n) {\n const resolvedParams = await params\n return forwardToSupabaseAPI(request, 'DELETE', resolvedParams)\n}\n\nexport async function PATCH(request: Request, { params }: { params: Promise<{ path: string[] }> }) {\n const resolvedParams = await params\n return forwardToSupabaseAPI(request, 'PATCH', resolvedParams)\n}\n",
+ "content": "import { NextResponse } from 'next/server'\n\nasync function forwardToSupabaseAPI(request: Request, method: string, params: { path: string[] }) {\n // eslint-disable-next-line turbo/no-undeclared-env-vars\n if (!process.env.SUPABASE_MANAGEMENT_API_TOKEN) {\n console.error('Supabase Management API token is not configured.')\n return NextResponse.json({ message: 'Server configuration error.' }, { status: 500 })\n }\n\n const { path } = params\n const apiPath = path.join('/')\n\n const url = new URL(request.url)\n url.protocol = 'https'\n url.hostname = 'api.supabase.com'\n url.port = '443'\n url.pathname = apiPath\n\n const projectRef = path[2]\n\n // Implement your permission check here (e.g. check if the user is a member of the project)\n // In this example, everyone can access all projects\n const userHasPermissionForProject = Boolean(projectRef)\n\n if (!userHasPermissionForProject) {\n return NextResponse.json(\n { message: 'You do not have permission to access this project.' },\n { status: 403 }\n )\n }\n\n try {\n const forwardHeaders: HeadersInit = {\n // eslint-disable-next-line turbo/no-undeclared-env-vars\n Authorization: `Bearer ${process.env.SUPABASE_MANAGEMENT_API_TOKEN}`,\n }\n\n // Copy relevant headers from the original request\n const contentType = request.headers.get('content-type')\n if (contentType) {\n forwardHeaders['Content-Type'] = contentType\n }\n\n const fetchOptions: RequestInit = {\n method,\n headers: forwardHeaders,\n }\n\n // Include body for methods that support it\n if (method !== 'GET' && method !== 'HEAD') {\n try {\n const body = await request.text()\n if (body) {\n fetchOptions.body = body\n }\n } catch (error) {\n // Handle cases where body is not readable\n console.warn('Could not read request body:', error)\n }\n }\n\n const response = await fetch(url, fetchOptions)\n\n // Get response body\n const responseText = await response.text()\n let responseData\n\n try {\n responseData = responseText ? JSON.parse(responseText) : null\n } catch {\n responseData = responseText\n }\n\n // Return the response with the same status\n return NextResponse.json(responseData, { status: response.status })\n } catch (error: any) {\n console.error('Supabase API proxy error:', error)\n const errorMessage = error.message || 'An unexpected error occurred.'\n return NextResponse.json({ message: errorMessage }, { status: 500 })\n }\n}\n\nexport async function GET(request: Request, { params }: { params: Promise<{ path: string[] }> }) {\n const resolvedParams = await params\n return forwardToSupabaseAPI(request, 'GET', resolvedParams)\n}\n\nexport async function HEAD(request: Request, { params }: { params: Promise<{ path: string[] }> }) {\n const resolvedParams = await params\n return forwardToSupabaseAPI(request, 'HEAD', resolvedParams)\n}\n\nexport async function POST(request: Request, { params }: { params: Promise<{ path: string[] }> }) {\n const resolvedParams = await params\n return forwardToSupabaseAPI(request, 'POST', resolvedParams)\n}\n\nexport async function PUT(request: Request, { params }: { params: Promise<{ path: string[] }> }) {\n const resolvedParams = await params\n return forwardToSupabaseAPI(request, 'PUT', resolvedParams)\n}\n\nexport async function DELETE(\n request: Request,\n { params }: { params: Promise<{ path: string[] }> }\n) {\n const resolvedParams = await params\n return forwardToSupabaseAPI(request, 'DELETE', resolvedParams)\n}\n\nexport async function PATCH(request: Request, { params }: { params: Promise<{ path: string[] }> }) {\n const resolvedParams = await params\n return forwardToSupabaseAPI(request, 'PATCH', resolvedParams)\n}\n",
"type": "registry:page",
"target": "app/api/supabase-proxy/[...path]/route.ts"
},
@@ -106,7 +106,7 @@
},
{
"path": "registry/default/platform/platform-kit-nextjs/components/supabase-manager/suggestions.tsx",
- "content": "'use client'\n\nimport { useGetSuggestions } from '@/registry/default/platform/platform-kit-nextjs/hooks/use-suggestions'\nimport { Alert, AlertDescription, AlertTitle } from '@/registry/default/components/ui/alert'\nimport { Terminal } from 'lucide-react'\nimport { Badge } from '@/registry/default/components/ui/badge'\nimport { useMemo } from 'react'\n\nimport ReactMarkdown from 'react-markdown'\nimport { Skeleton } from '@/registry/default/components/ui/skeleton'\n\nexport function SuggestionsManager({ projectRef }: { projectRef: string }) {\n const { data: suggestions, isLoading, error } = useGetSuggestions(projectRef)\n\n const sortedSuggestions = useMemo(() => {\n if (!suggestions) return []\n const levelOrder = { ERROR: 1, WARN: 2, INFO: 3 }\n return [...suggestions].sort((a: any, b: any) => {\n const levelA = levelOrder[a.level as keyof typeof levelOrder] || 99\n const levelB = levelOrder[b.level as keyof typeof levelOrder] || 99\n return levelA - levelB\n })\n }, [suggestions])\n\n const getBadgeVariant = (level: 'ERROR' | 'WARN' | 'INFO') => {\n switch (level) {\n case 'ERROR':\n return 'destructive'\n case 'WARN':\n return 'secondary'\n default:\n return 'outline'\n }\n }\n\n return (\n <div className=\"p-6 pt-4 lg:p-12 lg:pt-12 max-w-3xl mx-auto\">\n <h2 className=\"text-base lg:text-xl font-semibold mb-1\">Suggestions</h2>\n <p className=\"text-muted-foreground mb-4 lg:mb-8 text-sm lg:text-base\">\n Improve your project's security and performance.\n </p>\n {isLoading && (\n <div className=\"space-y-2\">\n <Skeleton className=\"h-6 w-full\" />\n <Skeleton className=\"h-6 w-full\" />\n <Skeleton className=\"h-6 w-full\" />\n <Skeleton className=\"h-6 w-full\" />\n </div>\n )}\n {error && (\n <Alert variant=\"destructive\" className=\"mt-8\">\n <Terminal className=\"h-4 w-4\" />\n <AlertTitle>Error fetching suggestions</AlertTitle>\n <AlertDescription>\n {(error as any)?.message || 'An unexpected error occurred. Please try again.'}\n </AlertDescription>\n </Alert>\n )}\n {suggestions && (\n <div>\n {sortedSuggestions.length > 0 ? (\n <div>\n {sortedSuggestions.map((suggestion: any) => (\n <div\n key={suggestion.cache_key}\n className=\"py-4 border-b last:border-b-0 group relative\"\n >\n <div className=\"flex-1\">\n <div className=\"flex justify-start items-start gap-4\">\n <h4 className=\"font-semibold text-sm\">{suggestion.title}</h4>\n <div className=\"flex items-center gap-1\">\n <Badge variant={getBadgeVariant(suggestion.level)} className=\"shrink-0\">\n {suggestion.level}\n </Badge>\n {suggestion.type && (\n <Badge\n variant={suggestion.type === 'security' ? 'destructive' : 'secondary'}\n className=\"shrink-0\"\n >\n {suggestion.type.charAt(0).toUpperCase() + suggestion.type.slice(1)}\n </Badge>\n )}\n </div>\n </div>\n <div className=\"text-sm text-muted-foreground mt-2 prose prose-sm max-w-none\">\n <ReactMarkdown\n components={{\n code({ inline, children, ...props }: any) {\n return inline ? (\n <code className=\"bg-muted px-1 rounded\" {...props}>\n {children}\n </code>\n ) : (\n <pre className=\"bg-muted p-2 rounded overflow-x-auto\" {...props}>\n <code>{children}</code>\n </pre>\n )\n },\n }}\n >\n {suggestion.detail}\n </ReactMarkdown>\n </div>\n </div>\n </div>\n ))}\n </div>\n ) : (\n <Alert>\n <Terminal className=\"h-4 w-4\" />\n <AlertTitle>No suggestions found</AlertTitle>\n <AlertDescription>\n Your project looks good! No suggestions at this time.\n </AlertDescription>\n </Alert>\n )}\n </div>\n )}\n </div>\n )\n}\n",
+ "content": "'use client'\n\nimport { useGetSuggestions } from '@/registry/default/platform/platform-kit-nextjs/hooks/use-suggestions'\nimport { Alert, AlertDescription, AlertTitle } from '@/registry/default/components/ui/alert'\nimport { Terminal } from 'lucide-react'\nimport { Badge } from '@/registry/default/components/ui/badge'\nimport { useMemo } from 'react'\n\nimport ReactMarkdown from 'react-markdown'\nimport { Skeleton } from '@/registry/default/components/ui/skeleton'\n\nexport function SuggestionsManager({ projectRef }: { projectRef: string }) {\n const { data: suggestions, isLoading, error } = useGetSuggestions(projectRef)\n\n const sortedSuggestions = useMemo(() => {\n if (!suggestions) return []\n const levelOrder = { ERROR: 1, WARN: 2, INFO: 3 }\n return [...suggestions].sort((a: any, b: any) => {\n const levelA = levelOrder[a.level as keyof typeof levelOrder] || 99\n const levelB = levelOrder[b.level as keyof typeof levelOrder] || 99\n return levelA - levelB\n })\n }, [suggestions])\n\n const getBadgeVariant = (level: 'ERROR' | 'WARN' | 'INFO') => {\n switch (level) {\n case 'ERROR':\n return 'destructive'\n case 'WARN':\n return 'secondary'\n default:\n return 'outline'\n }\n }\n\n return (\n <div className=\"p-6 pt-4 lg:p-12 lg:pt-12 max-w-3xl mx-auto\">\n <h2 className=\"text-base lg:text-xl font-semibold mb-1\">Suggestions</h2>\n <p className=\"text-muted-foreground mb-4 lg:mb-8 text-sm lg:text-base\">\n Improve your project&apos;s security and performance.\n </p>\n {isLoading && (\n <div className=\"space-y-2\">\n <Skeleton className=\"h-6 w-full\" />\n <Skeleton className=\"h-6 w-full\" />\n <Skeleton className=\"h-6 w-full\" />\n <Skeleton className=\"h-6 w-full\" />\n </div>\n )}\n {error && (\n <Alert variant=\"destructive\" className=\"mt-8\">\n <Terminal className=\"h-4 w-4\" />\n <AlertTitle>Error fetching suggestions</AlertTitle>\n <AlertDescription>\n {(error as any)?.message || 'An unexpected error occurred. Please try again.'}\n </AlertDescription>\n </Alert>\n )}\n {suggestions && (\n <div>\n {sortedSuggestions.length > 0 ? (\n <div>\n {sortedSuggestions.map((suggestion: any) => (\n <div\n key={suggestion.cache_key}\n className=\"py-4 border-b last:border-b-0 group relative\"\n >\n <div className=\"flex-1\">\n <div className=\"flex justify-start items-start gap-4\">\n <h4 className=\"font-semibold text-sm\">{suggestion.title}</h4>\n <div className=\"flex items-center gap-1\">\n <Badge variant={getBadgeVariant(suggestion.level)} className=\"shrink-0\">\n {suggestion.level}\n </Badge>\n {suggestion.type && (\n <Badge\n variant={suggestion.type === 'security' ? 'destructive' : 'secondary'}\n className=\"shrink-0\"\n >\n {suggestion.type.charAt(0).toUpperCase() + suggestion.type.slice(1)}\n </Badge>\n )}\n </div>\n </div>\n <div className=\"text-sm text-muted-foreground mt-2 prose prose-sm max-w-none\">\n <ReactMarkdown\n components={{\n code({ inline, children, ...props }: any) {\n return inline ? (\n <code className=\"bg-muted px-1 rounded\" {...props}>\n {children}\n </code>\n ) : (\n <pre className=\"bg-muted p-2 rounded overflow-x-auto\" {...props}>\n <code>{children}</code>\n </pre>\n )\n },\n }}\n >\n {suggestion.detail}\n </ReactMarkdown>\n </div>\n </div>\n </div>\n ))}\n </div>\n ) : (\n <Alert>\n <Terminal className=\"h-4 w-4\" />\n <AlertTitle>No suggestions found</AlertTitle>\n <AlertDescription>\n Your project looks good! No suggestions at this time.\n </AlertDescription>\n </Alert>\n )}\n </div>\n )}\n </div>\n )\n}\n",
"type": "registry:component"
},
{
diff --git a/apps/ui-library/public/r/realtime-cursor-nuxtjs.json b/apps/ui-library/public/r/realtime-cursor-nuxtjs.json
new file mode 100644
index 00000000000..d5007491b67
--- /dev/null
+++ b/apps/ui-library/public/r/realtime-cursor-nuxtjs.json
@@ -0,0 +1,32 @@
+{
+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",
+ "name": "realtime-cursor-nuxtjs",
+ "type": "registry:component",
+ "title": "Realtime Cursor for Nuxt and Supabase",
+ "description": "Component which renders realtime cursors from other users in a room.",
+ "dependencies": [
+ "@supabase/supabase-js@latest",
+ "@vueuse/core",
+ "lucide-vue-next"
+ ],
+ "files": [
+ {
+ "path": "registry/default/realtime-cursor/nuxtjs/app/components/cursor.vue",
+ "content": "<script setup lang=\"ts\">\nimport { MousePointer2 } from 'lucide-vue-next'\nimport { cn } from '@/lib/utils'\nimport type { CSSProperties } from 'vue'\n\ndefineProps<{\n className?: string\n style?: CSSProperties\n color: string\n name: string\n}>()\n</script>\n\n<template>\n <div\n :class=\"cn('pointer-events-none', className)\"\n :style=\"style\"\n >\n <MousePointer2\n :color=\"color\"\n :fill=\"color\"\n :size=\"30\"\n />\n\n <div\n class=\"mt-1 px-2 py-1 rounded text-xs font-bold text-white text-center\"\n :style=\"{ backgroundColor: color }\"\n >\n {{ name }}\n </div>\n </div>\n</template>\n",
+ "type": "registry:component",
+ "target": "app/components/cursor.vue"
+ },
+ {
+ "path": "registry/default/realtime-cursor/nuxtjs/app/components/realtime-cursors.vue",
+ "content": "<script setup lang=\"ts\">\nimport { Cursor } from '@/components/cursor'\nimport { useRealtimeCursors } from '@/composables/useRealtimeCursors'\n\nconst THROTTLE_MS = 50\n\nconst props = defineProps<{\n roomName: string\n username: string\n}>()\n\nconst { cursors } = useRealtimeCursors({\n roomName: props.roomName,\n username: props.username,\n throttleMs: THROTTLE_MS,\n})\n</script>\n\n<template>\n <div>\n <Cursor\n v-for=\"(cursor, id) in cursors\"\n :key=\"id\"\n className=\"fixed transition-transform ease-in-out z-50\"\n :style=\"{\n transitionDuration: '20ms',\n top: '0px',\n left: '0px',\n transform: `translate(${cursor.position.x}px, ${cursor.position.y}px)`,\n }\"\n :color=\"cursor.color\"\n :name=\"cursor.user.name\"\n />\n </div>\n</template>\n",
+ "type": "registry:component",
+ "target": "app/components/realtime-cursors.vue"
+ },
+ {
+ "path": "registry/default/realtime-cursor/nuxtjs/app/composables/useRealtimeCursors.ts",
+ "content": "import { ref, reactive, onMounted, onUnmounted } from 'vue'\nimport { createClient } from '@/lib/supabase/client'\nimport { REALTIME_SUBSCRIBE_STATES, type RealtimeChannel } from '@supabase/supabase-js'\n\n/**\n * Throttle a callback to a certain delay.\n * It will only call the callback if the delay has passed,\n * using the arguments from the last call.\n */\nfunction useThrottleCallback<Params extends unknown[]>(\n callback: (...args: Params) => void,\n delay: number\n) {\n let lastCall = 0\n let timeout: ReturnType<typeof setTimeout> | null = null\n\n const run = (...args: Params) => {\n const now = Date.now()\n const remainingTime = delay - (now - lastCall)\n\n if (remainingTime <= 0) {\n if (timeout) {\n clearTimeout(timeout)\n timeout = null\n }\n lastCall = now\n callback(...args)\n } else if (!timeout) {\n timeout = setTimeout(() => {\n lastCall = Date.now()\n timeout = null\n callback(...args)\n }, remainingTime)\n }\n }\n\n const cancel = () => {\n if (timeout) {\n clearTimeout(timeout)\n timeout = null\n }\n }\n\n return { run, cancel }\n}\n\nconst supabase = createClient()\n\nconst generateRandomColor = () =>\n `hsl(${Math.floor(Math.random() * 360)}, 100%, 70%)`\n\nconst generateRandomNumber = () =>\n Math.floor(Math.random() * 100)\n\nconst EVENT_NAME = 'realtime-cursor-move'\n\nexport type CursorEventPayload = {\n position: { x: number; y: number }\n user: { id: number; name: string }\n color: string\n timestamp: number\n}\n\nexport function useRealtimeCursors({\n roomName,\n username,\n throttleMs,\n}: {\n roomName: string\n username: string\n throttleMs: number\n}) {\n const color = generateRandomColor()\n const userId = generateRandomNumber()\n\n const cursors = reactive<Record<string, CursorEventPayload>>({})\n const cursorPayload = ref<CursorEventPayload | null>(null)\n const channelRef = ref<RealtimeChannel | null>(null)\n\n const sendCursor = (event: MouseEvent) => {\n const payload: CursorEventPayload = {\n position: {\n x: event.clientX,\n y: event.clientY,\n },\n user: {\n id: userId,\n name: username,\n },\n color,\n timestamp: Date.now(),\n }\n\n cursorPayload.value = payload\n\n channelRef.value?.send({\n type: 'broadcast',\n event: EVENT_NAME,\n payload,\n })\n }\n\n const { run: handleMouseMove, cancel: cancelThrottle } =\n useThrottleCallback(sendCursor, throttleMs)\n\n onMounted(() => {\n const channel = supabase.channel(roomName)\n\n channel\n .on('system', {}, (payload: CursorEventPayload) => {\n console.error('Realtime system error:', payload)\n\n // Defensive cleanup\n Object.keys(cursors).forEach((k) => delete cursors[k])\n channelRef.value = null\n })\n .on('presence', { event: 'leave' }, ({ leftPresences }) => {\n leftPresences.forEach(({ key }) => {\n delete cursors[key]\n })\n })\n .on('presence', { event: 'join' }, () => {\n if (!cursorPayload.value) return\n\n channelRef.value?.send({\n type: 'broadcast',\n event: EVENT_NAME,\n payload: cursorPayload.value,\n })\n })\n .on('broadcast', { event: EVENT_NAME }, ({ payload }: { payload: CursorEventPayload }) => {\n if (payload.user.id === userId) return\n\n cursors[payload.user.id] = payload\n })\n .subscribe(async (status) => {\n if (status === REALTIME_SUBSCRIBE_STATES.SUBSCRIBED) {\n try {\n await channel.track({ key: userId })\n channelRef.value = channel\n } catch (err) {\n console.error('Failed to track presence for current user:', err)\n channelRef.value = null\n }\n } else {\n Object.keys(cursors).forEach((k) => delete cursors[k])\n channelRef.value = null\n }\n })\n\n window.addEventListener('mousemove', handleMouseMove)\n })\n\n onUnmounted(() => {\n window.removeEventListener('mousemove', handleMouseMove)\n\n cancelThrottle()\n\n if (channelRef.value) {\n channelRef.value.unsubscribe()\n channelRef.value = null\n }\n\n Object.keys(cursors).forEach((k) => delete cursors[k])\n })\n\n return { cursors }\n}\n",
+ "type": "registry:component",
+ "target": "app/composables/useRealtimeCursors.ts"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/apps/ui-library/public/r/realtime-cursor-vue.json b/apps/ui-library/public/r/realtime-cursor-vue.json
new file mode 100644
index 00000000000..9d4de1a8a46
--- /dev/null
+++ b/apps/ui-library/public/r/realtime-cursor-vue.json
@@ -0,0 +1,32 @@
+{
+ "$schema": "https://ui.shadcn.com/schema/registry-item.json",
+ "name": "realtime-cursor-vue",
+ "type": "registry:component",
+ "title": "Realtime Cursor for Vue and Supabase",
+ "description": "Component which renders realtime cursors from other users in a room.",
+ "dependencies": [
+ "@supabase/supabase-js@latest",
+ "@vueuse/core",
+ "lucide-vue-next"
+ ],
+ "files": [
+ {
+ "path": "registry/default/realtime-cursor/vue/components/cursor.vue",
+ "content": "<script setup lang=\"ts\">\nimport { MousePointer2 } from 'lucide-vue-next'\nimport { cn } from '@/lib/utils'\nimport type { CSSProperties } from 'vue'\n\ndefineProps<{\n className?: string\n style?: CSSProperties\n color: string\n name: string\n}>()\n</script>\n\n<template>\n <div\n :class=\"cn('pointer-events-none', className)\"\n :style=\"style\"\n >\n <MousePointer2\n :color=\"color\"\n :fill=\"color\"\n :size=\"30\"\n />\n\n <div\n class=\"mt-1 px-2 py-1 rounded text-xs font-bold text-white text-center\"\n :style=\"{ backgroundColor: color }\"\n >\n {{ name }}\n </div>\n </div>\n</template>\n",
+ "type": "registry:component",
+ "target": "components/cursor.vue"
+ },
+ {
+ "path": "registry/default/realtime-cursor/vue/components/realtime-cursors.vue",
+ "content": "<script setup lang=\"ts\">\nimport { Cursor } from '@/components/cursor'\nimport { useRealtimeCursors } from '@/composables/useRealtimeCursors'\n\nconst THROTTLE_MS = 50\n\nconst props = defineProps<{\n roomName: string\n username: string\n}>()\n\nconst { cursors } = useRealtimeCursors({\n roomName: props.roomName,\n username: props.username,\n throttleMs: THROTTLE_MS,\n})\n</script>\n\n<template>\n <div>\n <Cursor\n v-for=\"(cursor, id) in cursors\"\n :key=\"id\"\n className=\"fixed transition-transform ease-in-out z-50\"\n :style=\"{\n transitionDuration: '20ms',\n top: '0px',\n left: '0px',\n transform: `translate(${cursor.position.x}px, ${cursor.position.y}px)`,\n }\"\n :color=\"cursor.color\"\n :name=\"cursor.user.name\"\n />\n </div>\n</template>\n",
+ "type": "registry:component",
+ "target": "components/realtime-cursors.vue"
+ },
+ {
+ "path": "registry/default/realtime-cursor/vue/composables/useRealtimeCursors.ts",
+ "content": "import { ref, reactive, onMounted, onUnmounted } from 'vue'\nimport { createClient } from '@/lib/supabase/client'\nimport { REALTIME_SUBSCRIBE_STATES, type RealtimeChannel } from '@supabase/supabase-js'\n\n/**\n * Throttle a callback to a certain delay.\n * It will only call the callback if the delay has passed,\n * using the arguments from the last call.\n */\nfunction useThrottleCallback<Params extends unknown[]>(\n callback: (...args: Params) => void,\n delay: number\n) {\n let lastCall = 0\n let timeout: ReturnType<typeof setTimeout> | null = null\n\n const run = (...args: Params) => {\n const now = Date.now()\n const remainingTime = delay - (now - lastCall)\n\n if (remainingTime <= 0) {\n if (timeout) {\n clearTimeout(timeout)\n timeout = null\n }\n lastCall = now\n callback(...args)\n } else if (!timeout) {\n timeout = setTimeout(() => {\n lastCall = Date.now()\n timeout = null\n callback(...args)\n }, remainingTime)\n }\n }\n\n const cancel = () => {\n if (timeout) {\n clearTimeout(timeout)\n timeout = null\n }\n }\n\n return { run, cancel }\n}\n\nconst supabase = createClient()\n\nconst generateRandomColor = () =>\n `hsl(${Math.floor(Math.random() * 360)}, 100%, 70%)`\n\nconst generateRandomNumber = () =>\n Math.floor(Math.random() * 100)\n\nconst EVENT_NAME = 'realtime-cursor-move'\n\nexport type CursorEventPayload = {\n position: { x: number; y: number }\n user: { id: number; name: string }\n color: string\n timestamp: number\n}\n\nexport function useRealtimeCursors({\n roomName,\n username,\n throttleMs,\n}: {\n roomName: string\n username: string\n throttleMs: number\n}) {\n const color = generateRandomColor()\n const userId = generateRandomNumber()\n\n const cursors = reactive<Record<string, CursorEventPayload>>({})\n const cursorPayload = ref<CursorEventPayload | null>(null)\n const channelRef = ref<RealtimeChannel | null>(null)\n\n const sendCursor = (event: MouseEvent) => {\n const payload: CursorEventPayload = {\n position: {\n x: event.clientX,\n y: event.clientY,\n },\n user: {\n id: userId,\n name: username,\n },\n color,\n timestamp: Date.now(),\n }\n\n cursorPayload.value = payload\n\n channelRef.value?.send({\n type: 'broadcast',\n event: EVENT_NAME,\n payload,\n })\n }\n\n const { run: handleMouseMove, cancel: cancelThrottle } =\n useThrottleCallback(sendCursor, throttleMs)\n\n onMounted(() => {\n const channel = supabase.channel(roomName)\n\n channel\n .on('system', {}, (payload: CursorEventPayload) => {\n console.error('Realtime system error:', payload)\n\n // Defensive cleanup\n Object.keys(cursors).forEach((k) => delete cursors[k])\n channelRef.value = null\n })\n .on('presence', { event: 'leave' }, ({ leftPresences }) => {\n leftPresences.forEach(({ key }) => {\n delete cursors[key]\n })\n })\n .on('presence', { event: 'join' }, () => {\n if (!cursorPayload.value) return\n\n channelRef.value?.send({\n type: 'broadcast',\n event: EVENT_NAME,\n payload: cursorPayload.value,\n })\n })\n .on('broadcast', { event: EVENT_NAME }, ({ payload }: { payload: CursorEventPayload }) => {\n if (payload.user.id === userId) return\n\n cursors[payload.user.id] = payload\n })\n .subscribe(async (status) => {\n if (status === REALTIME_SUBSCRIBE_STATES.SUBSCRIBED) {\n try {\n await channel.track({ key: userId })\n channelRef.value = channel\n } catch (err) {\n console.error('Failed to track presence for current user:', err)\n channelRef.value = null\n }\n } else {\n Object.keys(cursors).forEach((k) => delete cursors[k])\n channelRef.value = null\n }\n })\n\n window.addEventListener('mousemove', handleMouseMove)\n })\n\n onUnmounted(() => {\n window.removeEventListener('mousemove', handleMouseMove)\n\n cancelThrottle()\n\n if (channelRef.value) {\n channelRef.value.unsubscribe()\n channelRef.value = null\n }\n\n Object.keys(cursors).forEach((k) => delete cursors[k])\n })\n\n return { cursors }\n}\n",
+ "type": "registry:component",
+ "target": "composables/useRealtimeCursors.ts"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/apps/ui-library/public/r/registry.json b/apps/ui-library/public/r/registry.json
index 595c4484a22..41edf2c6e6e 100644
--- a/apps/ui-library/public/r/registry.json
+++ b/apps/ui-library/public/r/registry.json
@@ -1949,6 +1949,134 @@
"@supabase/supabase-js@latest"
]
},
+ {
+ "name": "dropzone-nuxtjs",
+ "type": "registry:block",
+ "title": "Dropzone (File Upload) for Nuxt and Supabase",
+ "description": "Displays a control for easier uploading of files directly to Supabase Storage.",
+ "registryDependencies": [
+ "button"
+ ],
+ "files": [
+ {
+ "path": "registry/default/dropzone/nuxtjs/app/components/dropzone.vue",
+ "type": "registry:component",
+ "target": "app/components/dropzone.vue"
+ },
+ {
+ "path": "registry/default/dropzone/nuxtjs/app/components/dropzone-empty-state.vue",
+ "type": "registry:component",
+ "target": "app/components/dropzone-empty-state.vue"
+ },
+ {
+ "path": "registry/default/dropzone/nuxtjs/app/components/dropzone-content.vue",
+ "type": "registry:component",
+ "target": "app/components/dropzone-content.vue"
+ },
+ {
+ "path": "registry/default/dropzone/nuxtjs/app/composables/useSupabaseUpload.ts",
+ "type": "registry:component",
+ "target": "app/composables/useSupabaseUpload.ts"
+ }
+ ],
+ "dependencies": [
+ "@supabase/supabase-js@latest",
+ "@vueuse/core",
+ "lucide-vue-next"
+ ]
+ },
+ {
+ "name": "dropzone-vue",
+ "type": "registry:block",
+ "title": "Dropzone (File Upload) for Vue and Supabase",
+ "description": "Displays a control for easier uploading of files directly to Supabase Storage.",
+ "registryDependencies": [
+ "button"
+ ],
+ "files": [
+ {
+ "path": "registry/default/dropzone/vue/components/dropzone.vue",
+ "type": "registry:component",
+ "target": "components/dropzone.vue"
+ },
+ {
+ "path": "registry/default/dropzone/vue/components/dropzone-empty-state.vue",
+ "type": "registry:component",
+ "target": "components/dropzone-empty-state.vue"
+ },
+ {
+ "path": "registry/default/dropzone/vue/components/dropzone-content.vue",
+ "type": "registry:component",
+ "target": "components/dropzone-content.vue"
+ },
+ {
+ "path": "registry/default/dropzone/vue/composables/useSupabaseUpload.ts",
+ "type": "registry:component",
+ "target": "composables/useSupabaseUpload.ts"
+ }
+ ],
+ "dependencies": [
+ "@supabase/supabase-js@latest",
+ "@vueuse/core",
+ "lucide-vue-next"
+ ]
+ },
+ {
+ "name": "realtime-cursor-nuxtjs",
+ "type": "registry:component",
+ "title": "Realtime Cursor for Nuxt and Supabase",
+ "description": "Component which renders realtime cursors from other users in a room.",
+ "files": [
+ {
+ "path": "registry/default/realtime-cursor/nuxtjs/app/components/cursor.vue",
+ "type": "registry:component",
+ "target": "app/components/cursor.vue"
+ },
+ {
+ "path": "registry/default/realtime-cursor/nuxtjs/app/components/realtime-cursors.vue",
+ "type": "registry:component",
+ "target": "app/components/realtime-cursors.vue"
+ },
+ {
+ "path": "registry/default/realtime-cursor/nuxtjs/app/composables/useRealtimeCursors.ts",
+ "type": "registry:component",
+ "target": "app/composables/useRealtimeCursors.ts"
+ }
+ ],
+ "dependencies": [
+ "@supabase/supabase-js@latest",
+ "@vueuse/core",
+ "lucide-vue-next"
+ ]
+ },
+ {
+ "name": "realtime-cursor-vue",
+ "type": "registry:component",
+ "title": "Realtime Cursor for Vue and Supabase",
+ "description": "Component which renders realtime cursors from other users in a room.",
+ "files": [
+ {
+ "path": "registry/default/realtime-cursor/vue/components/cursor.vue",
+ "type": "registry:component",
+ "target": "components/cursor.vue"
+ },
+ {
+ "path": "registry/default/realtime-cursor/vue/components/realtime-cursors.vue",
+ "type": "registry:component",
+ "target": "components/realtime-cursors.vue"
+ },
+ {
+ "path": "registry/default/realtime-cursor/vue/composables/useRealtimeCursors.ts",
+ "type": "registry:component",
+ "target": "composables/useRealtimeCursors.ts"
+ }
+ ],
+ "dependencies": [
+ "@supabase/supabase-js@latest",
+ "@vueuse/core",
+ "lucide-vue-next"
+ ]
+ },
{
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
"name": "ai-editor-rules",
diff --git a/blocks/vue/package.json b/blocks/vue/package.json
index 6412d7024b8..1eea69f6a69 100644
--- a/blocks/vue/package.json
+++ b/blocks/vue/package.json
@@ -10,15 +10,17 @@
"typecheck": "tsc --noEmit -p tsconfig.json"
},
"dependencies": {
+ "@supabase/ssr": "^0.7.0",
+ "@supabase/supabase-js": "catalog:",
+ "@vueuse/core": "^14.1.0",
+ "class-variance-authority": "^0.7.1",
+ "clsx": "^2.1.1",
"h3": "^1.15.5",
+ "lucide-vue-next": "^0.562.0",
"nuxt": "^4.0.3",
- "class-variance-authority": "^0.7.1",
"tailwind-merge": "^3.3.1",
- "clsx": "^2.1.1",
"vue": "^3.5.21",
- "vue-router": "^4.5.1",
- "@supabase/ssr": "^0.7.0",
- "@supabase/supabase-js": "catalog:"
+ "vue-router": "^4.5.1"
},
"devDependencies": {
"shadcn": "^3.0.0",
diff --git a/blocks/vue/registry/default/dropzone/nuxtjs/app/components/dropzone-content.vue b/blocks/vue/registry/default/dropzone/nuxtjs/app/components/dropzone-content.vue
new file mode 100644
index 00000000000..079976099be
--- /dev/null
+++ b/blocks/vue/registry/default/dropzone/nuxtjs/app/components/dropzone-content.vue
@@ -0,0 +1,132 @@
+<script setup lang="ts">
+import { cn } from '@/lib/utils'
+import { Button } from '@/components/ui/button'
+import { CheckCircle, File, Loader2, X } from 'lucide-vue-next'
+import { formatBytes, useDropzoneContext } from './dropzone.vue'
+import { computed } from 'vue';
+
+const props = defineProps<{ className?: string }>()
+
+const {
+ files,
+ setFiles,
+ onUpload,
+ loading,
+ successes,
+ errors,
+ maxFileSize,
+ maxFiles,
+ isSuccess,
+} = useDropzoneContext()
+
+const exceedMaxFiles = computed(() => files.length > maxFiles)
+
+const fileErrorMessages = computed(() => new Map(errors.map(e => [e.name, e.message])))
+
+function formatFileErrors(file: typeof files[number]) {
+ if (!file.errors || file.errors.length === 0) return ''
+ return file.errors
+ .map(e =>
+ e.message.startsWith('File is larger than')
+ ? `File is larger than ${formatBytes(maxFileSize)} (Size: ${formatBytes(file.size)})`
+ : e.message
+ )
+ .join(', ')
+}
+
+function handleRemoveFile(filename: string) {
+ setFiles(files.filter(f => f.name !== filename))
+}
+</script>
+
+<template>
+ <div :class="cn('flex flex-col', props.className)">
+ <!-- Success State -->
+ <div v-if="isSuccess" class="flex flex-row items-center gap-x-2 justify-center" role="status" aria-live="polite">
+ <CheckCircle size="16" class="text-primary" aria-hidden="true"/>
+ <p class="text-primary text-sm">
+ Successfully uploaded {{ files.length }} file{{ files.length > 1 ? 's' : '' }}
+ </p>
+ </div>
+
+ <!-- File list -->
+ <template v-else>
+ <div
+ v-for="(file, idx) in files"
+ :key="file?.name + '-' + file?.lastModified + '-' + file?.size || file?.name + '-' + idx"
+ class="flex items-center gap-x-4 border-b py-2 first:mt-4 last:mb-4"
+ >
+ <div v-if="file.type.startsWith('image/')"
+ class="h-10 w-10 rounded border overflow-hidden shrink-0 bg-muted flex items-center justify-center">
+ <img :src="file.preview" :alt="file.name" class="object-cover" />
+ </div>
+
+ <div v-else class="h-10 w-10 rounded border bg-muted flex items-center justify-center">
+ <File size="18" aria-hidden="true" />
+ </div>
+
+ <div class="shrink grow flex flex-col items-start truncate">
+ <p class="text-sm truncate max-w-full" :title="file.name">
+ {{ file.name }}
+ </p>
+
+ <!-- ARIA live region for status messages -->
+ <div aria-live="polite" aria-atomic="true">
+ <!-- Errors -->
+ <p v-if="file.errors.length > 0" class="text-xs text-destructive">
+ {{ formatFileErrors(file) }}
+ </p>
+
+ <!-- Uploading -->
+ <p v-else-if="loading" class="text-xs text-muted-foreground">Uploading file...</p>
+
+ <!-- Failed -->
+ <p v-else-if="fileErrorMessages.has(file.name)" class="text-xs text-destructive">
+ Failed to upload: {{ fileErrorMessages.get(file.name) }}
+ </p>
+
+ <!-- Success -->
+ <p v-else-if="successes.includes(file.name)" class="text-xs text-primary">
+ Successfully uploaded file
+ </p>
+
+ <!-- Normal -->
+ <p v-else class="text-xs text-muted-foreground">
+ {{ formatBytes(file.size) }}
+ </p>
+ </div>
+ </div>
+
+ <Button
+ v-if="!loading && !successes.includes(file.name)"
+ aria-label="Remove file Button"
+ size="icon"
+ variant="link"
+ class="shrink-0 text-muted-foreground hover:text-foreground"
+ @click="handleRemoveFile(file.name)"
+ >
+ <X />
+ </Button>
+ </div>
+
+ <!-- Too many files -->
+ <p v-if="exceedMaxFiles" class="text-sm text-left mt-2 text-destructive">
+ You may upload only up to {{ maxFiles }} files, please remove
+ {{ files.length - maxFiles }} file(s).
+ </p>
+
+ <!-- Upload button -->
+ <div v-if="files.length > 0 && !exceedMaxFiles" class="mt-2">
+ <Button
+ variant="outline"
+ :disabled="files.some(f => f.errors.length) || loading"
+ @click="onUpload"
+ >
+ <Loader2 v-if="loading" class="mr-2 h-4 w-4 animate-spin" />
+ <template v-if="loading">Uploading...</template>
+ <template v-else>Upload files</template>
+ </Button>
+ </div>
+ </template>
+ </div>
+</template>
diff --git a/blocks/vue/registry/default/dropzone/nuxtjs/app/components/dropzone-empty-state.vue b/blocks/vue/registry/default/dropzone/nuxtjs/app/components/dropzone-empty-state.vue
new file mode 100644
index 00000000000..d288cfe6615
--- /dev/null
+++ b/blocks/vue/registry/default/dropzone/nuxtjs/app/components/dropzone-empty-state.vue
@@ -0,0 +1,37 @@
+<script setup lang="ts">
+import { Upload } from 'lucide-vue-next'
+import { cn } from '@/lib/utils'
+import { useDropzoneContext, formatBytes } from './dropzone.vue'
+
+const props = defineProps<{ className?: string }>()
+
+const { maxFiles, maxFileSize, inputRef, isSuccess } = useDropzoneContext()
+</script>
+
+<template>
+ <div v-if="!isSuccess" :class="cn('flex flex-col items-center gap-y-2', props.className)">
+ <Upload size="20" class="text-muted-foreground" aria-hidden="true" />
+
+ <p class="text-sm">
+ Upload{{ maxFiles > 1 ? ` ${maxFiles}` : '' }} file{{ maxFiles !== 1 ? 's' : '' }}
+ </p>
+
+ <div class="flex flex-col items-center gap-y-1">
+ <p class="text-xs text-muted-foreground">
+ Drag and drop or
+ <button
+ type="button"
+ class="underline cursor-pointer hover:text-foreground"
+ @click="inputRef?.click()"
+ >
+ select file{{ maxFiles !== 1 ? 's' : '' }}
+ </button>
+ to upload
+ </p>
+
+ <p v-if="maxFileSize !== Infinity" class="text-xs text-muted-foreground">
+ Maximum file size: {{ formatBytes(maxFileSize) }}
+ </p>
+ </div>
+ </div>
+</template>
diff --git a/blocks/vue/registry/default/dropzone/nuxtjs/app/components/dropzone.vue b/blocks/vue/registry/default/dropzone/nuxtjs/app/components/dropzone.vue
new file mode 100644
index 00000000000..ebd43607e57
--- /dev/null
+++ b/blocks/vue/registry/default/dropzone/nuxtjs/app/components/dropzone.vue
@@ -0,0 +1,83 @@
+<script setup lang="ts">
+import { provide, inject } from 'vue'
+import { cn } from '@/lib/utils'
+
+interface File {
+ name: string
+ errors: Array<{ message: string }>
+ size: number
+ lastModified?: number
+ type?: string
+ preview?: string
+}
+
+export interface DropzoneProps {
+ className?: string
+ isDragActive?: boolean
+ isDragReject?: boolean
+ isSuccess?: boolean
+ maxFiles?: number
+ maxFileSize?: number
+ inputRef?: HTMLInputElement | null
+ setFiles: (files: File[]) => void
+ onUpload: () => Promise<void>
+ loading?: boolean
+ successes: string[]
+ errors: Array<{ name: string; message: string }>
+ files: File[]
+ getRootProps: (options?: Record<string, unknown>) => Record<string, unknown>
+ getInputProps: () => Record<string, unknown>
+}
+
+export const formatBytes = (
+ bytes: number,
+ decimals = 2,
+ size?: 'bytes' | 'KB' | 'MB' | 'GB' | 'TB' | 'PB' | 'EB' | 'ZB' | 'YB'
+) => {
+ const k = 1000
+ const dm = decimals < 0 ? 0 : decimals
+ const sizes = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
+
+ if (!bytes || bytes < 0) return size ? `0 ${size}` : '0 bytes'
+
+ const i = size
+ ? Math.max(0, sizes.indexOf(size))
+ : Math.max(0, Math.min(sizes.length - 1, Math.floor(Math.log(bytes) / Math.log(k))))
+
+ return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]
+}
+
+const DropzoneContext = Symbol('DropzoneContext')
+
+export function useDropzoneContext() {
+ const ctx = inject<DropzoneProps>(DropzoneContext)
+ if (!ctx) throw new Error('useDropzoneContext must be used within <Dropzone>')
+ return ctx
+}
+
+const props = defineProps<DropzoneProps>()
+
+provide(DropzoneContext, props)
+</script>
+
+<template>
+ <div
+ v-bind="
+ props.getRootProps({
+ class: cn(
+ 'border-2 border-gray-300 rounded-lg p-6 text-center bg-card transition-colors duration-300 text-foreground',
+ props.className,
+ props.isSuccess ? 'border-solid' : 'border-dashed',
+ props.isDragActive && 'border-primary bg-primary/10',
+ ((props.isDragActive && props.isDragReject) ||
+ (props.errors.length > 0 && !props.isSuccess) ||
+ props.files.some((f) => f.errors.length !== 0)) &&
+ 'border-destructive bg-destructive/10'
+ ),
+ })
+ "
+ >
+ <input v-bind="props.getInputProps()" />
+ <slot />
+ </div>
+</template>
diff --git a/blocks/vue/registry/default/dropzone/nuxtjs/app/composables/useSupabaseUpload.ts b/blocks/vue/registry/default/dropzone/nuxtjs/app/composables/useSupabaseUpload.ts
new file mode 100644
index 00000000000..b057c6ef7cf
--- /dev/null
+++ b/blocks/vue/registry/default/dropzone/nuxtjs/app/composables/useSupabaseUpload.ts
@@ -0,0 +1,190 @@
+import { ref, computed, watch, onUnmounted } from 'vue'
+import { useDropZone } from '@vueuse/core'
+// @ts-ignore
+import { createClient } from "@/lib/supabase/client"
+
+const supabase = createClient()
+
+export interface FileWithPreview extends File {
+ preview?: string
+ errors: { code: string; message: string }[]
+}
+
+export type UseSupabaseUploadOptions = {
+ bucketName: string
+ path?: string
+ allowedMimeTypes?: string[]
+ maxFileSize?: number
+ maxFiles?: number
+ cacheControl?: number
+ upsert?: boolean
+}
+
+function validateFileType(file: File, allowedTypes: string[]) {
+ if (!allowedTypes.length) return []
+ const isValid = allowedTypes.some(t =>
+ t.endsWith('/*')
+ ? file.type.startsWith(t.replace('/*', ''))
+ : file.type === t
+ )
+ return isValid
+ ? []
+ : [{ code: 'invalid-type', message: 'Invalid file type' }]
+}
+
+function validateFileSize(file: File, maxSize: number) {
+ return file.size > maxSize
+ ? [{ code: 'file-too-large', message: `File is larger than allowed size` }]
+ : []
+}
+
+export function useSupabaseUpload(options: UseSupabaseUploadOptions) {
+ const {
+ bucketName,
+ path,
+ allowedMimeTypes = [],
+ maxFileSize = Number.POSITIVE_INFINITY,
+ maxFiles = 1,
+ cacheControl = 3600,
+ upsert = false,
+ } = options
+
+ const files = ref<FileWithPreview[]>([])
+ const loading = ref(false)
+ const errors = ref<{ name: string; message: string }[]>([])
+ const successes = ref<string[]>([])
+
+ const isSuccess = computed(() => {
+ if (!errors.value.length && !successes.value.length) return false
+ return !errors.value.length && successes.value.length === files.value.length
+ })
+
+ const dropZoneRef = ref<HTMLElement | null>(null)
+
+ const { isOverDropZone } = useDropZone(dropZoneRef, {
+ onDrop(droppedFiles: File[] | null) {
+ if (!droppedFiles) return
+
+ const newFiles: FileWithPreview[] = droppedFiles.map(file => ({
+ ...(file as FileWithPreview),
+ preview: URL.createObjectURL(file),
+ errors: [
+ ...validateFileType(file, allowedMimeTypes),
+ ...validateFileSize(file, maxFileSize),
+ ],
+ }))
+
+ files.value = [...files.value, ...newFiles]
+ },
+ })
+
+ const onUpload = async () => {
+ loading.value = true
+
+ try {
+ const filesWithErrors = errors.value.map(e => e.name)
+
+ const filesToUpload =
+ filesWithErrors.length > 0
+ ? files.value.filter(
+ f =>
+ filesWithErrors.includes(f.name) ||
+ !successes.value.includes(f.name)
+ )
+ : files.value
+
+ const responses = await Promise.all(
+ filesToUpload.map(async file => {
+ const { error } = await supabase.storage
+ .from(bucketName)
+ .upload(path ? `${path}/${file.name}` : file.name, file, {
+ cacheControl: cacheControl.toString(),
+ upsert,
+ })
+
+ return error
+ ? { name: file.name, message: error.message }
+ : { name: file.name, message: undefined }
+ })
+ )
+
+ errors.value = responses.filter((r): r is { name: string; message: string } => r.message !== undefined)
+
+ const successful = responses
+ .filter(r => !r.message)
+ .map(r => r.name)
+
+ successes.value = Array.from(
+ new Set([...successes.value, ...successful])
+ )
+ } catch (err) {
+ console.error('Upload failed unexpectedly:', err)
+
+ errors.value.push({
+ name: 'upload',
+ message: 'An unexpected error occurred during upload.',
+ })
+ } finally {
+ loading.value = false
+ }
+ }
+
+
+ watch(
+ () => files.value.length,
+ () => {
+ if (!files.value.length) {
+ errors.value = []
+ successes.value = []
+ }
+
+ if (files.value.length > maxFiles) {
+ errors.value.push({
+ name: 'files',
+ message: `You may upload up to ${maxFiles} files`,
+ })
+ }
+ }
+ )
+
+ watch(
+ files,
+ (newFiles, oldFiles) => {
+ const newPreviews = new Set(newFiles.map(f => f.preview))
+ oldFiles.forEach(file => {
+ if (file.preview && !newPreviews.has(file.preview)) {
+ URL.revokeObjectURL(file.preview)
+ }
+ })
+ },
+ { deep: true }
+ )
+
+ onUnmounted(() => {
+ files.value.forEach(file => {
+ if (file.preview) {
+ URL.revokeObjectURL(file.preview)
+ }
+ })
+ })
+
+ return {
+ dropZoneRef,
+ isOverDropZone,
+
+ files,
+ setFiles: (v: FileWithPreview[]) => (files.value = v),
+
+ errors,
+ setErrors: (v: { name: string; message: string }[]) => (errors.value = v),
+
+ successes,
+ isSuccess,
+ loading,
+ onUpload,
+
+ maxFileSize,
+ maxFiles,
+ allowedMimeTypes,
+ }
+}
diff --git a/blocks/vue/registry/default/dropzone/nuxtjs/registry-item.json b/blocks/vue/registry/default/dropzone/nuxtjs/registry-item.json
new file mode 100644
index 00000000000..e4be40a8c6c
--- /dev/null
+++ b/blocks/vue/registry/default/dropzone/nuxtjs/registry-item.json
@@ -0,0 +1,30 @@
+{
+ "name": "dropzone-nuxtjs",
+ "type": "registry:block",
+ "title": "Dropzone (File Upload) for Nuxt and Supabase",
+ "description": "Displays a control for easier uploading of files directly to Supabase Storage.",
+ "registryDependencies": ["button"],
+ "files": [
+ {
+ "path": "registry/default/dropzone/nuxtjs/app/components/dropzone.vue",
+ "type": "registry:component",
+ "target": "app/components/dropzone.vue"
+ },
+ {
+ "path": "registry/default/dropzone/nuxtjs/app/components/dropzone-empty-state.vue",
+ "type": "registry:component",
+ "target": "app/components/dropzone-empty-state.vue"
+ },
+ {
+ "path": "registry/default/dropzone/nuxtjs/app/components/dropzone-content.vue",
+ "type": "registry:component",
+ "target": "app/components/dropzone-content.vue"
+ },
+ {
+ "path": "registry/default/dropzone/nuxtjs/app/composables/useSupabaseUpload.ts",
+ "type": "registry:component",
+ "target": "app/composables/useSupabaseUpload.ts"
+ }
+ ],
+ "dependencies": ["@supabase/supabase-js@latest", "@vueuse/core", "lucide-vue-next"]
+}
\ No newline at end of file
diff --git a/blocks/vue/registry/default/dropzone/vue/components/dropzone-content.vue b/blocks/vue/registry/default/dropzone/vue/components/dropzone-content.vue
new file mode 100644
index 00000000000..7f1a3dc5bf2
--- /dev/null
+++ b/blocks/vue/registry/default/dropzone/vue/components/dropzone-content.vue
@@ -0,0 +1,132 @@
+<script setup lang="ts">
+import { cn } from '@/lib/utils'
+import { Button } from '@/components/ui/button'
+import { CheckCircle, File, Loader2, X } from 'lucide-vue-next'
+import { formatBytes, useDropzoneContext } from './dropzone.vue'
+import { computed } from 'vue';
+
+const props = defineProps<{ className?: string }>()
+
+const {
+ files,
+ setFiles,
+ onUpload,
+ loading,
+ successes,
+ errors,
+ maxFileSize,
+ maxFiles,
+ isSuccess,
+} = useDropzoneContext()
+
+const exceedMaxFiles = computed(() => files.length > maxFiles)
+
+const fileErrorMessages = computed(() => new Map(errors.map(e => [e.name, e.message])))
+
+function formatFileErrors(file: typeof files[number]) {
+ if (!file.errors || file.errors.length === 0) return ''
+ return file.errors
+ .map(e =>
+ e.message.startsWith('File is larger than')
+ ? `File is larger than ${formatBytes(maxFileSize)} (Size: ${formatBytes(file.size)})`
+ : e.message
+ )
+ .join(', ')
+}
+
+function handleRemoveFile(filename: string) {
+ setFiles(files.filter(f => f.name !== filename))
+}
+</script>
+
+<template>
+ <div :class="cn('flex flex-col', props.className)">
+ <!-- Success State -->
+ <div v-if="isSuccess" class="flex flex-row items-center gap-x-2 justify-center" role="status" aria-live="polite">
+ <CheckCircle size="16" class="text-primary" aria-hidden="true"/>
+ <p class="text-primary text-sm">
+ Successfully uploaded {{ files.length }} file{{ files.length > 1 ? 's' : '' }}
+ </p>
+ </div>
+
+ <!-- File list -->
+ <template v-else>
+ <div
+ v-for="(file, idx) in files"
+ :key="file?.name + '-' + file?.lastModified + '-' + file?.size || file?.name + '-' + idx"
+ class="flex items-center gap-x-4 border-b py-2 first:mt-4 last:mb-4"
+ >
+ <div v-if="file.type.startsWith('image/')"
+ class="h-10 w-10 rounded border overflow-hidden shrink-0 bg-muted flex items-center justify-center">
+ <img :src="file.preview" :alt="file.name" class="object-cover" />
+ </div>
+
+ <div v-else class="h-10 w-10 rounded border bg-muted flex items-center justify-center">
+ <File size="18" aria-hidden="true" />
+ </div>
+
+ <div class="shrink grow flex flex-col items-start truncate">
+ <p class="text-sm truncate max-w-full" :title="file.name">
+ {{ file.name }}
+ </p>
+
+ <!-- ARIA live region for status messages -->
+ <div aria-live="polite" aria-atomic="true">
+ <!-- Errors -->
+ <p v-if="file.errors.length > 0" class="text-xs text-destructive">
+ {{ formatFileErrors(file) }}
+ </p>
+
+ <!-- Uploading -->
+ <p v-else-if="loading" class="text-xs text-muted-foreground">Uploading file...</p>
+
+ <!-- Failed -->
+ <p v-else-if="fileErrorMessages.has(file.name)" class="text-xs text-destructive">
+ Failed to upload: {{ fileErrorMessages.get(file.name) }}
+ </p>
+
+ <!-- Success -->
+ <p v-else-if="successes.includes(file.name)" class="text-xs text-primary">
+ Successfully uploaded file
+ </p>
+
+ <!-- Normal -->
+ <p v-else class="text-xs text-muted-foreground">
+ {{ formatBytes(file.size) }}
+ </p>
+ </div>
+ </div>
+
+ <Button
+ v-if="!loading && !successes.includes(file.name)"
+ aria-label="Remove file Button"
+ size="icon"
+ variant="link"
+ class="shrink-0 text-muted-foreground hover:text-foreground"
+ @click="handleRemoveFile(file.name)"
+ >
+ <X />
+ </Button>
+ </div>
+
+ <!-- Too many files -->
+ <p v-if="exceedMaxFiles" class="text-sm text-left mt-2 text-destructive">
+ You may upload only up to {{ maxFiles }} files, please remove
+ {{ files.length - maxFiles }} file(s).
+ </p>
+
+ <!-- Upload button -->
+ <div v-if="files.length > 0 && !exceedMaxFiles" class="mt-2">
+ <Button
+ variant="outline"
+ :disabled="files.some(f => f.errors.length) || loading"
+ @click="onUpload"
+ >
+ <Loader2 v-if="loading" class="mr-2 h-4 w-4 animate-spin" aria-hidden="true" />
+ <template v-if="loading">Uploading...</template>
+ <template v-else>Upload files</template>
+ </Button>
+ </div>
+ </template>
+ </div>
+</template>
diff --git a/blocks/vue/registry/default/dropzone/vue/components/dropzone-empty-state.vue b/blocks/vue/registry/default/dropzone/vue/components/dropzone-empty-state.vue
new file mode 100644
index 00000000000..7c96dd495b9
--- /dev/null
+++ b/blocks/vue/registry/default/dropzone/vue/components/dropzone-empty-state.vue
@@ -0,0 +1,37 @@
+<script setup lang="ts">
+import { Upload } from 'lucide-vue-next'
+import { cn } from '@/lib/utils'
+import { useDropzoneContext, formatBytes } from './dropzone.vue'
+
+const props = defineProps<{ className?: string }>()
+
+const { maxFiles, maxFileSize, inputRef, isSuccess } = useDropzoneContext()
+</script>
+
+<template>
+ <div v-if="!isSuccess" :class="cn('flex flex-col items-center gap-y-2', props.className)">
+ <Upload size="20" class="text-muted-foreground" aria-hidden="true"/>
+
+ <p class="text-sm">
+ Upload{{ maxFiles > 1 ? ` ${maxFiles}` : '' }} file{{ maxFiles !== 1 ? 's' : '' }}
+ </p>
+
+ <div class="flex flex-col items-center gap-y-1">
+ <p class="text-xs text-muted-foreground">
+ Drag and drop or
+ <button
+ type="button"
+ class="underline cursor-pointer hover:text-foreground"
+ @click="inputRef?.click()"
+ >
+ select file{{ maxFiles !== 1 ? 's' : '' }}
+ </button>
+ to upload
+ </p>
+
+ <p v-if="maxFileSize !== Infinity" class="text-xs text-muted-foreground">
+ Maximum file size: {{ formatBytes(maxFileSize) }}
+ </p>
+ </div>
+ </div>
+</template>
diff --git a/blocks/vue/registry/default/dropzone/vue/components/dropzone.vue b/blocks/vue/registry/default/dropzone/vue/components/dropzone.vue
new file mode 100644
index 00000000000..107dd5bcd3d
--- /dev/null
+++ b/blocks/vue/registry/default/dropzone/vue/components/dropzone.vue
@@ -0,0 +1,82 @@
+<script setup lang="ts">
+import { provide, inject } from 'vue'
+import { cn } from "@/lib/utils"
+
+interface File {
+ name: string
+ errors: Array<{ message: string }>
+ size: number
+ lastModified?: number
+ type?: string
+ preview?: string
+}
+
+export interface DropzoneProps {
+ className?: string
+ isDragActive?: boolean
+ isDragReject?: boolean
+ isSuccess?: boolean
+ maxFiles?: number
+ maxFileSize?: number
+ inputRef?: HTMLInputElement | null
+ setFiles: (files: File[]) => void
+ onUpload: () => Promise<void>
+ loading?: boolean
+ successes: string[]
+ errors: Array<{ name: string; message: string }>
+ files: File[]
+ getRootProps: (options?: Record<string, unknown>) => Record<string, unknown>
+ getInputProps: () => Record<string, unknown>
+}
+
+export const formatBytes = (
+ bytes: number,
+ decimals = 2,
+ size?: 'bytes' | 'KB' | 'MB' | 'GB' | 'TB' | 'PB' | 'EB' | 'ZB' | 'YB'
+) => {
+ const k = 1000
+ const dm = decimals < 0 ? 0 : decimals
+ const sizes = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
+
+ if (!bytes || bytes < 0) return size ? `0 ${size}` : '0 bytes'
+
+ const i = size
+ ? Math.max(0, sizes.indexOf(size))
+ : Math.max(0, Math.min(sizes.length - 1, Math.floor(Math.log(bytes) / Math.log(k))))
+
+ return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]
+}
+
+
+const DropzoneContext = Symbol('DropzoneContext')
+
+export function useDropzoneContext() {
+ const ctx = inject<DropzoneProps>(DropzoneContext)
+ if (!ctx) throw new Error('useDropzoneContext must be used within <Dropzone>')
+ return ctx
+}
+
+const props = defineProps<DropzoneProps>()
+
+provide(DropzoneContext, props)
+</script>
+
+<template>
+ <div
+ v-bind="props.getRootProps({
+ class: cn(
+ 'border-2 border-gray-300 rounded-lg p-6 text-center bg-card transition-colors duration-300 text-foreground',
+ props.className,
+ props.isSuccess ? 'border-solid' : 'border-dashed',
+ props.isDragActive && 'border-primary bg-primary/10',
+ ((props.isDragActive && props.isDragReject) ||
+ (props.errors.length > 0 && !props.isSuccess) ||
+ props.files.some(f => f.errors.length !== 0))
+ && 'border-destructive bg-destructive/10'
+ )
+ })"
+ >
+ <input v-bind="props.getInputProps()" />
+ <slot />
+ </div>
+</template>
diff --git a/blocks/vue/registry/default/dropzone/vue/composables/useSupabaseUpload.ts b/blocks/vue/registry/default/dropzone/vue/composables/useSupabaseUpload.ts
new file mode 100644
index 00000000000..b057c6ef7cf
--- /dev/null
+++ b/blocks/vue/registry/default/dropzone/vue/composables/useSupabaseUpload.ts
@@ -0,0 +1,190 @@
+import { ref, computed, watch, onUnmounted } from 'vue'
+import { useDropZone } from '@vueuse/core'
+// @ts-ignore
+import { createClient } from "@/lib/supabase/client"
+
+const supabase = createClient()
+
+export interface FileWithPreview extends File {
+ preview?: string
+ errors: { code: string; message: string }[]
+}
+
+export type UseSupabaseUploadOptions = {
+ bucketName: string
+ path?: string
+ allowedMimeTypes?: string[]
+ maxFileSize?: number
+ maxFiles?: number
+ cacheControl?: number
+ upsert?: boolean
+}
+
+function validateFileType(file: File, allowedTypes: string[]) {
+ if (!allowedTypes.length) return []
+ const isValid = allowedTypes.some(t =>
+ t.endsWith('/*')
+ ? file.type.startsWith(t.replace('/*', ''))
+ : file.type === t
+ )
+ return isValid
+ ? []
+ : [{ code: 'invalid-type', message: 'Invalid file type' }]
+}
+
+function validateFileSize(file: File, maxSize: number) {
+ return file.size > maxSize
+ ? [{ code: 'file-too-large', message: `File is larger than allowed size` }]
+ : []
+}
+
+export function useSupabaseUpload(options: UseSupabaseUploadOptions) {
+ const {
+ bucketName,
+ path,
+ allowedMimeTypes = [],
+ maxFileSize = Number.POSITIVE_INFINITY,
+ maxFiles = 1,
+ cacheControl = 3600,
+ upsert = false,
+ } = options
+
+ const files = ref<FileWithPreview[]>([])
+ const loading = ref(false)
+ const errors = ref<{ name: string; message: string }[]>([])
+ const successes = ref<string[]>([])
+
+ const isSuccess = computed(() => {
+ if (!errors.value.length && !successes.value.length) return false
+ return !errors.value.length && successes.value.length === files.value.length
+ })
+
+ const dropZoneRef = ref<HTMLElement | null>(null)
+
+ const { isOverDropZone } = useDropZone(dropZoneRef, {
+ onDrop(droppedFiles: File[] | null) {
+ if (!droppedFiles) return
+
+ const newFiles: FileWithPreview[] = droppedFiles.map(file => ({
+ ...(file as FileWithPreview),
+ preview: URL.createObjectURL(file),
+ errors: [
+ ...validateFileType(file, allowedMimeTypes),
+ ...validateFileSize(file, maxFileSize),
+ ],
+ }))
+
+ files.value = [...files.value, ...newFiles]
+ },
+ })
+
+ const onUpload = async () => {
+ loading.value = true
+
+ try {
+ const filesWithErrors = errors.value.map(e => e.name)
+
+ const filesToUpload =
+ filesWithErrors.length > 0
+ ? files.value.filter(
+ f =>
+ filesWithErrors.includes(f.name) ||
+ !successes.value.includes(f.name)
+ )
+ : files.value
+
+ const responses = await Promise.all(
+ filesToUpload.map(async file => {
+ const { error } = await supabase.storage
+ .from(bucketName)
+ .upload(path ? `${path}/${file.name}` : file.name, file, {
+ cacheControl: cacheControl.toString(),
+ upsert,
+ })
+
+ return error
+ ? { name: file.name, message: error.message }
+ : { name: file.name, message: undefined }
+ })
+ )
+
+ errors.value = responses.filter((r): r is { name: string; message: string } => r.message !== undefined)
+
+ const successful = responses
+ .filter(r => !r.message)
+ .map(r => r.name)
+
+ successes.value = Array.from(
+ new Set([...successes.value, ...successful])
+ )
+ } catch (err) {
+ console.error('Upload failed unexpectedly:', err)
+
+ errors.value.push({
+ name: 'upload',
+ message: 'An unexpected error occurred during upload.',
+ })
+ } finally {
+ loading.value = false
+ }
+ }
+
+
+ watch(
+ () => files.value.length,
+ () => {
+ if (!files.value.length) {
+ errors.value = []
+ successes.value = []
+ }
+
+ if (files.value.length > maxFiles) {
+ errors.value.push({
+ name: 'files',
+ message: `You may upload up to ${maxFiles} files`,
+ })
+ }
+ }
+ )
+
+ watch(
+ files,
+ (newFiles, oldFiles) => {
+ const newPreviews = new Set(newFiles.map(f => f.preview))
+ oldFiles.forEach(file => {
+ if (file.preview && !newPreviews.has(file.preview)) {
+ URL.revokeObjectURL(file.preview)
+ }
+ })
+ },
+ { deep: true }
+ )
+
+ onUnmounted(() => {
+ files.value.forEach(file => {
+ if (file.preview) {
+ URL.revokeObjectURL(file.preview)
+ }
+ })
+ })
+
+ return {
+ dropZoneRef,
+ isOverDropZone,
+
+ files,
+ setFiles: (v: FileWithPreview[]) => (files.value = v),
+
+ errors,
+ setErrors: (v: { name: string; message: string }[]) => (errors.value = v),
+
+ successes,
+ isSuccess,
+ loading,
+ onUpload,
+
+ maxFileSize,
+ maxFiles,
+ allowedMimeTypes,
+ }
+}
diff --git a/blocks/vue/registry/default/dropzone/vue/registry-item.json b/blocks/vue/registry/default/dropzone/vue/registry-item.json
new file mode 100644
index 00000000000..03578ca5cce
--- /dev/null
+++ b/blocks/vue/registry/default/dropzone/vue/registry-item.json
@@ -0,0 +1,30 @@
+{
+ "name": "dropzone-vue",
+ "type": "registry:block",
+ "title": "Dropzone (File Upload) for Vue and Supabase",
+ "description": "Displays a control for easier uploading of files directly to Supabase Storage.",
+ "registryDependencies": ["button"],
+ "files": [
+ {
+ "path": "registry/default/dropzone/vue/components/dropzone.vue",
+ "type": "registry:component",
+ "target": "components/dropzone.vue"
+ },
+ {
+ "path": "registry/default/dropzone/vue/components/dropzone-empty-state.vue",
+ "type": "registry:component",
+ "target": "components/dropzone-empty-state.vue"
+ },
+ {
+ "path": "registry/default/dropzone/vue/components/dropzone-content.vue",
+ "type": "registry:component",
+ "target": "components/dropzone-content.vue"
+ },
+ {
+ "path": "registry/default/dropzone/vue/composables/useSupabaseUpload.ts",
+ "type": "registry:component",
+ "target": "composables/useSupabaseUpload.ts"
+ }
+ ],
+ "dependencies": ["@supabase/supabase-js@latest", "@vueuse/core", "lucide-vue-next"]
+}
\ No newline at end of file
diff --git a/blocks/vue/registry/default/realtime-cursor/nuxtjs/app/components/cursor.vue b/blocks/vue/registry/default/realtime-cursor/nuxtjs/app/components/cursor.vue
new file mode 100644
index 00000000000..2ac794bba46
--- /dev/null
+++ b/blocks/vue/registry/default/realtime-cursor/nuxtjs/app/components/cursor.vue
@@ -0,0 +1,33 @@
+<script setup lang="ts">
+import { MousePointer2 } from 'lucide-vue-next'
+import type { CSSProperties } from 'vue'
+// @ts-ignore
+import { cn } from '@/lib/utils'
+
+defineProps<{
+ className?: string
+ style?: CSSProperties
+ color: string
+ name: string
+}>()
+</script>
+
+<template>
+ <div
+ :class="cn('pointer-events-none', className)"
+ :style="style"
+ >
+ <MousePointer2
+ :color="color"
+ :fill="color"
+ :size="30"
+ />
+
+ <div
+ class="mt-1 px-2 py-1 rounded text-xs font-bold text-white text-center"
+ :style="{ backgroundColor: color }"
+ >
+ {{ name }}
+ </div>
+ </div>
+</template>
diff --git a/blocks/vue/registry/default/realtime-cursor/nuxtjs/app/components/realtime-cursors.vue b/blocks/vue/registry/default/realtime-cursor/nuxtjs/app/components/realtime-cursors.vue
new file mode 100644
index 00000000000..fe58ee10989
--- /dev/null
+++ b/blocks/vue/registry/default/realtime-cursor/nuxtjs/app/components/realtime-cursors.vue
@@ -0,0 +1,37 @@
+<script setup lang="ts">
+// @ts-ignore
+import { Cursor } from '@/components/cursor'
+// @ts-ignore
+import { useRealtimeCursors } from '@/composables/useRealtimeCursors'
+
+const THROTTLE_MS = 50
+
+const props = defineProps<{
+ roomName: string
+ username: string
+}>()
+
+const { cursors } = useRealtimeCursors({
+ roomName: props.roomName,
+ username: props.username,
+ throttleMs: THROTTLE_MS,
+})
+</script>
+
+<template>
+ <div>
+ <Cursor
+ v-for="(cursor, id) in cursors"
+ :key="id"
+ className="fixed transition-transform ease-in-out z-50"
+ :style="{
+ transitionDuration: '20ms',
+ top: '0px',
+ left: '0px',
+ transform: `translate(${cursor.position.x}px, ${cursor.position.y}px)`,
+ }"
+ :color="cursor.color"
+ :name="cursor.user.name"
+ />
+ </div>
+</template>
diff --git a/blocks/vue/registry/default/realtime-cursor/nuxtjs/app/composables/useRealtimeCursors.ts b/blocks/vue/registry/default/realtime-cursor/nuxtjs/app/composables/useRealtimeCursors.ts
new file mode 100644
index 00000000000..7fccf11e5c6
--- /dev/null
+++ b/blocks/vue/registry/default/realtime-cursor/nuxtjs/app/composables/useRealtimeCursors.ts
@@ -0,0 +1,169 @@
+import { ref, reactive, onMounted, onUnmounted } from 'vue'
+import { REALTIME_SUBSCRIBE_STATES, type RealtimeChannel } from '@supabase/supabase-js'
+// @ts-ignore
+import { createClient } from '@/lib/supabase/client'
+
+/**
+ * Throttle a callback to a certain delay.
+ * It will only call the callback if the delay has passed,
+ * using the arguments from the last call.
+ */
+function useThrottleCallback<Params extends unknown[]>(
+ callback: (...args: Params) => void,
+ delay: number
+) {
+ let lastCall = 0
+ let timeout: ReturnType<typeof setTimeout> | null = null
+
+ const run = (...args: Params) => {
+ const now = Date.now()
+ const remainingTime = delay - (now - lastCall)
+
+ if (remainingTime <= 0) {
+ if (timeout) {
+ clearTimeout(timeout)
+ timeout = null
+ }
+ lastCall = now
+ callback(...args)
+ } else if (!timeout) {
+ timeout = setTimeout(() => {
+ lastCall = Date.now()
+ timeout = null
+ callback(...args)
+ }, remainingTime)
+ }
+ }
+
+ const cancel = () => {
+ if (timeout) {
+ clearTimeout(timeout)
+ timeout = null
+ }
+ }
+
+ return { run, cancel }
+}
+
+const supabase = createClient()
+
+const generateRandomColor = () =>
+ `hsl(${Math.floor(Math.random() * 360)}, 100%, 70%)`
+
+const generateRandomNumber = () =>
+ Math.floor(Math.random() * 100)
+
+const EVENT_NAME = 'realtime-cursor-move'
+
+export type CursorEventPayload = {
+ position: { x: number; y: number }
+ user: { id: number; name: string }
+ color: string
+ timestamp: number
+}
+
+export function useRealtimeCursors({
+ roomName,
+ username,
+ throttleMs,
+}: {
+ roomName: string
+ username: string
+ throttleMs: number
+}) {
+ const color = generateRandomColor()
+ const userId = generateRandomNumber()
+
+ const cursors = reactive<Record<string, CursorEventPayload>>({})
+ const cursorPayload = ref<CursorEventPayload | null>(null)
+ const channelRef = ref<RealtimeChannel | null>(null)
+
+ const sendCursor = (event: MouseEvent) => {
+ const payload: CursorEventPayload = {
+ position: {
+ x: event.clientX,
+ y: event.clientY,
+ },
+ user: {
+ id: userId,
+ name: username,
+ },
+ color,
+ timestamp: Date.now(),
+ }
+
+ cursorPayload.value = payload
+
+ channelRef.value?.send({
+ type: 'broadcast',
+ event: EVENT_NAME,
+ payload,
+ })
+ }
+
+ const { run: handleMouseMove, cancel: cancelThrottle } =
+ useThrottleCallback(sendCursor, throttleMs)
+
+ onMounted(() => {
+ const channel = supabase.channel(roomName)
+
+ channel
+ .on('system', {}, (payload: CursorEventPayload) => {
+ console.error('Realtime system error:', payload)
+
+ // Defensive cleanup
+ Object.keys(cursors).forEach((k) => delete cursors[k])
+ channelRef.value = null
+ })
+ .on('presence', { event: 'leave' }, ({ leftPresences }: { leftPresences: Array<{ key: string }> }) => {
+ leftPresences.forEach(({ key }) => {
+ delete cursors[key]
+ })
+ })
+ .on('presence', { event: 'join' }, () => {
+ if (!cursorPayload.value) return
+
+ channelRef.value?.send({
+ type: 'broadcast',
+ event: EVENT_NAME,
+ payload: cursorPayload.value,
+ })
+ })
+ .on('broadcast', { event: EVENT_NAME }, ({ payload }: { payload: CursorEventPayload }) => {
+ if (payload.user.id === userId) return
+
+ cursors[payload.user.id] = payload
+ })
+ .subscribe(async (status: REALTIME_SUBSCRIBE_STATES) => {
+ if (status === REALTIME_SUBSCRIBE_STATES.SUBSCRIBED) {
+ try {
+ await channel.track({ key: userId })
+ channelRef.value = channel
+ } catch (err) {
+ console.error('Failed to track presence for current user:', err)
+ channelRef.value = null
+ }
+ } else {
+ Object.keys(cursors).forEach((k) => delete cursors[k])
+ channelRef.value = null
+ }
+ })
+
+ window.addEventListener('mousemove', handleMouseMove)
+ })
+
+ onUnmounted(() => {
+ window.removeEventListener('mousemove', handleMouseMove)
+
+ cancelThrottle()
+
+ if (channelRef.value) {
+ channelRef.value.unsubscribe()
+ channelRef.value = null
+ }
+
+ Object.keys(cursors).forEach((k) => delete cursors[k])
+ })
+
+ return { cursors }
+}
diff --git a/blocks/vue/registry/default/realtime-cursor/nuxtjs/registry-item.json b/blocks/vue/registry/default/realtime-cursor/nuxtjs/registry-item.json
new file mode 100644
index 00000000000..3a2adc71263
--- /dev/null
+++ b/blocks/vue/registry/default/realtime-cursor/nuxtjs/registry-item.json
@@ -0,0 +1,24 @@
+{
+ "name": "realtime-cursor-nuxtjs",
+ "type": "registry:component",
+ "title": "Realtime Cursor for Nuxt and Supabase",
+ "description": "Component which renders realtime cursors from other users in a room.",
+ "files": [
+ {
+ "path": "registry/default/realtime-cursor/nuxtjs/app/components/cursor.vue",
+ "type": "registry:component",
+ "target": "app/components/cursor.vue"
+ },
+ {
+ "path": "registry/default/realtime-cursor/nuxtjs/app/components/realtime-cursors.vue",
+ "type": "registry:component",
+ "target": "app/components/realtime-cursors.vue"
+ },
+ {
+ "path": "registry/default/realtime-cursor/nuxtjs/app/composables/useRealtimeCursors.ts",
+ "type": "registry:component",
+ "target": "app/composables/useRealtimeCursors.ts"
+ }
+ ],
+ "dependencies": ["@supabase/supabase-js@latest", "@vueuse/core", "lucide-vue-next"]
+}
\ No newline at end of file
diff --git a/blocks/vue/registry/default/realtime-cursor/vue/components/cursor.vue b/blocks/vue/registry/default/realtime-cursor/vue/components/cursor.vue
new file mode 100644
index 00000000000..2ac794bba46
--- /dev/null
+++ b/blocks/vue/registry/default/realtime-cursor/vue/components/cursor.vue
@@ -0,0 +1,33 @@
+<script setup lang="ts">
+import { MousePointer2 } from 'lucide-vue-next'
+import type { CSSProperties } from 'vue'
+// @ts-ignore
+import { cn } from '@/lib/utils'
+
+defineProps<{
+ className?: string
+ style?: CSSProperties
+ color: string
+ name: string
+}>()
+</script>
+
+<template>
+ <div
+ :class="cn('pointer-events-none', className)"
+ :style="style"
+ >
+ <MousePointer2
+ :color="color"
+ :fill="color"
+ :size="30"
+ />
+
+ <div
+ class="mt-1 px-2 py-1 rounded text-xs font-bold text-white text-center"
+ :style="{ backgroundColor: color }"
+ >
+ {{ name }}
+ </div>
+ </div>
+</template>
diff --git a/blocks/vue/registry/default/realtime-cursor/vue/components/realtime-cursors.vue b/blocks/vue/registry/default/realtime-cursor/vue/components/realtime-cursors.vue
new file mode 100644
index 00000000000..f74df808c64
--- /dev/null
+++ b/blocks/vue/registry/default/realtime-cursor/vue/components/realtime-cursors.vue
@@ -0,0 +1,37 @@
+<script setup lang="ts">
+ // @ts-ignore
+import { Cursor } from '@/components/cursor'
+// @ts-ignore
+import { useRealtimeCursors } from '@/composables/useRealtimeCursors'
+
+const THROTTLE_MS = 50
+
+const props = defineProps<{
+ roomName: string
+ username: string
+}>()
+
+const { cursors } = useRealtimeCursors({
+ roomName: props.roomName,
+ username: props.username,
+ throttleMs: THROTTLE_MS,
+})
+</script>
+
+<template>
+ <div>
+ <Cursor
+ v-for="(cursor, id) in cursors"
+ :key="id"
+ className="fixed transition-transform ease-in-out z-50"
+ :style="{
+ transitionDuration: '20ms',
+ top: '0px',
+ left: '0px',
+ transform: `translate(${cursor.position.x}px, ${cursor.position.y}px)`,
+ }"
+ :color="cursor.color"
+ :name="cursor.user.name"
+ />
+ </div>
+</template>
diff --git a/blocks/vue/registry/default/realtime-cursor/vue/composables/useRealtimeCursors.ts b/blocks/vue/registry/default/realtime-cursor/vue/composables/useRealtimeCursors.ts
new file mode 100644
index 00000000000..7fccf11e5c6
--- /dev/null
+++ b/blocks/vue/registry/default/realtime-cursor/vue/composables/useRealtimeCursors.ts
@@ -0,0 +1,169 @@
+import { ref, reactive, onMounted, onUnmounted } from 'vue'
+import { REALTIME_SUBSCRIBE_STATES, type RealtimeChannel } from '@supabase/supabase-js'
+// @ts-ignore
+import { createClient } from '@/lib/supabase/client'
+
+/**
+ * Throttle a callback to a certain delay.
+ * It will only call the callback if the delay has passed,
+ * using the arguments from the last call.
+ */
+function useThrottleCallback<Params extends unknown[]>(
+ callback: (...args: Params) => void,
+ delay: number
+) {
+ let lastCall = 0
+ let timeout: ReturnType<typeof setTimeout> | null = null
+
+ const run = (...args: Params) => {
+ const now = Date.now()
+ const remainingTime = delay - (now - lastCall)
+
+ if (remainingTime <= 0) {
+ if (timeout) {
+ clearTimeout(timeout)
+ timeout = null
+ }
+ lastCall = now
+ callback(...args)
+ } else if (!timeout) {
+ timeout = setTimeout(() => {
+ lastCall = Date.now()
+ timeout = null
+ callback(...args)
+ }, remainingTime)
+ }
+ }
+
+ const cancel = () => {
+ if (timeout) {
+ clearTimeout(timeout)
+ timeout = null
+ }
+ }
+
+ return { run, cancel }
+}
+
+const supabase = createClient()
+
+const generateRandomColor = () =>
+ `hsl(${Math.floor(Math.random() * 360)}, 100%, 70%)`
+
+const generateRandomNumber = () =>
+ Math.floor(Math.random() * 100)
+
+const EVENT_NAME = 'realtime-cursor-move'
+
+export type CursorEventPayload = {
+ position: { x: number; y: number }
+ user: { id: number; name: string }
+ color: string
+ timestamp: number
+}
+
+export function useRealtimeCursors({
+ roomName,
+ username,
+ throttleMs,
+}: {
+ roomName: string
+ username: string
+ throttleMs: number
+}) {
+ const color = generateRandomColor()
+ const userId = generateRandomNumber()
+
+ const cursors = reactive<Record<string, CursorEventPayload>>({})
+ const cursorPayload = ref<CursorEventPayload | null>(null)
+ const channelRef = ref<RealtimeChannel | null>(null)
+
+ const sendCursor = (event: MouseEvent) => {
+ const payload: CursorEventPayload = {
+ position: {
+ x: event.clientX,
+ y: event.clientY,
+ },
+ user: {
+ id: userId,
+ name: username,
+ },
+ color,
+ timestamp: Date.now(),
+ }
+
+ cursorPayload.value = payload
+
+ channelRef.value?.send({
+ type: 'broadcast',
+ event: EVENT_NAME,
+ payload,
+ })
+ }
+
+ const { run: handleMouseMove, cancel: cancelThrottle } =
+ useThrottleCallback(sendCursor, throttleMs)
+
+ onMounted(() => {
+ const channel = supabase.channel(roomName)
+
+ channel
+ .on('system', {}, (payload: CursorEventPayload) => {
+ console.error('Realtime system error:', payload)
+
+ // Defensive cleanup
+ Object.keys(cursors).forEach((k) => delete cursors[k])
+ channelRef.value = null
+ })
+ .on('presence', { event: 'leave' }, ({ leftPresences }: { leftPresences: Array<{ key: string }> }) => {
+ leftPresences.forEach(({ key }) => {
+ delete cursors[key]
+ })
+ })
+ .on('presence', { event: 'join' }, () => {
+ if (!cursorPayload.value) return
+
+ channelRef.value?.send({
+ type: 'broadcast',
+ event: EVENT_NAME,
+ payload: cursorPayload.value,
+ })
+ })
+ .on('broadcast', { event: EVENT_NAME }, ({ payload }: { payload: CursorEventPayload }) => {
+ if (payload.user.id === userId) return
+
+ cursors[payload.user.id] = payload
+ })
+ .subscribe(async (status: REALTIME_SUBSCRIBE_STATES) => {
+ if (status === REALTIME_SUBSCRIBE_STATES.SUBSCRIBED) {
+ try {
+ await channel.track({ key: userId })
+ channelRef.value = channel
+ } catch (err) {
+ console.error('Failed to track presence for current user:', err)
+ channelRef.value = null
+ }
+ } else {
+ Object.keys(cursors).forEach((k) => delete cursors[k])
+ channelRef.value = null
+ }
+ })
+
+ window.addEventListener('mousemove', handleMouseMove)
+ })
+
+ onUnmounted(() => {
+ window.removeEventListener('mousemove', handleMouseMove)
+
+ cancelThrottle()
+
+ if (channelRef.value) {
+ channelRef.value.unsubscribe()
+ channelRef.value = null
+ }
+
+ Object.keys(cursors).forEach((k) => delete cursors[k])
+ })
+
+ return { cursors }
+}
diff --git a/blocks/vue/registry/default/realtime-cursor/vue/registry-item.json b/blocks/vue/registry/default/realtime-cursor/vue/registry-item.json
new file mode 100644
index 00000000000..728f0007f76
--- /dev/null
+++ b/blocks/vue/registry/default/realtime-cursor/vue/registry-item.json
@@ -0,0 +1,24 @@
+{
+ "name": "realtime-cursor-vue",
+ "type": "registry:component",
+ "title": "Realtime Cursor for Vue and Supabase",
+ "description": "Component which renders realtime cursors from other users in a room.",
+ "files": [
+ {
+ "path": "registry/default/realtime-cursor/vue/components/cursor.vue",
+ "type": "registry:component",
+ "target": "components/cursor.vue"
+ },
+ {
+ "path": "registry/default/realtime-cursor/vue/components/realtime-cursors.vue",
+ "type": "registry:component",
+ "target": "components/realtime-cursors.vue"
+ },
+ {
+ "path": "registry/default/realtime-cursor/vue/composables/useRealtimeCursors.ts",
+ "type": "registry:component",
+ "target": "composables/useRealtimeCursors.ts"
+ }
+ ],
+ "dependencies": ["@supabase/supabase-js@latest", "@vueuse/core", "lucide-vue-next"]
+}
diff --git a/blocks/vue/registry/dropzone.ts b/blocks/vue/registry/dropzone.ts
new file mode 100644
index 00000000000..f3be8d0af41
--- /dev/null
+++ b/blocks/vue/registry/dropzone.ts
@@ -0,0 +1,6 @@
+import { type RegistryItem } from 'shadcn/schema'
+
+import nuxtjs from './default/dropzone/nuxtjs/registry-item.json' with { type: 'json' }
+import vue from './default/dropzone/vue/registry-item.json' with { type: 'json' }
+
+export const dropzone = [nuxtjs, vue] as RegistryItem[]
diff --git a/blocks/vue/registry/index.ts b/blocks/vue/registry/index.ts
index 0ce964f3b34..235404a5d7c 100644
--- a/blocks/vue/registry/index.ts
+++ b/blocks/vue/registry/index.ts
@@ -1,7 +1,9 @@
import { clients } from './clients'
+import { dropzone } from './dropzone'
import { passwordBasedAuth } from './password-based-auth'
+import { realtimeCursor } from './realtime-cursor'
import { socialAuth } from './social-auth'
-const blocks = [...clients, ...passwordBasedAuth, ...socialAuth]
+const blocks = [...clients, ...passwordBasedAuth, ...socialAuth, ...dropzone, ...realtimeCursor]
export { blocks }
diff --git a/blocks/vue/registry/realtime-cursor.ts b/blocks/vue/registry/realtime-cursor.ts
new file mode 100644
index 00000000000..9540c26c74f
--- /dev/null
+++ b/blocks/vue/registry/realtime-cursor.ts
@@ -0,0 +1,6 @@
+import { type RegistryItem } from 'shadcn/schema'
+
+import nuxtjs from './default/realtime-cursor/nuxtjs/registry-item.json' with { type: 'json' }
+import vue from './default/realtime-cursor/vue/registry-item.json' with { type: 'json' }
+
+export const realtimeCursor = [nuxtjs, vue] as RegistryItem[]
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 9a1e6d88148..aa8623e41db 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1876,6 +1876,9 @@ importers:
'@supabase/supabase-js':
specifier: 'catalog:'
version: 2.93.2
+ '@vueuse/core':
+ specifier: ^14.1.0
class-variance-authority:
specifier: ^0.7.1
version: 0.7.1
@@ -1885,6 +1888,9 @@ importers:
h3:
specifier: ^1.15.5
version: 1.15.5
+ lucide-vue-next:
+ specifier: ^0.562.0
nuxt:
specifier: ^4.0.3
@@ -9751,6 +9757,9 @@ packages:
resolution: {integrity: sha512-jg+97EGIcY9AGHJJRaaPVgetKDsrTgbRjQ5Msgjh/DQKEFl0DtyRr/VCOyD1T2R1MNeWPK/u7JoGhlDZnKBAfA==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-oIQLCGWtcFZy2JW77j9k8nHzAOpqMHLQejDA48XXMWH6tjCQHz5RCFz1bzsmROyL6PUm+LLnUiI4BCn221inxA==}
+
resolution: {integrity: sha512-JGpU6qiIJQKUuVSKx1GtQnHJGxRjtfGIhzO2ilq43VZZS//f1h1Sgexbdk+Lq+7569a6EYhOWrUpIruR/1Enmg==}
@@ -10032,6 +10041,19 @@ packages:
resolution: {integrity: sha512-+2k1EQpnYuVuu3N7atWyG3/xoFWIVJZq4Mz8XNOdScFI0etES75fbny/oU4lKWk/577P1zmg0ioYvpGEDZ3DLw==}
+ '@vueuse/[email protected]':
+ resolution: {integrity: sha512-rgBinKs07hAYyPF834mDTigH7BtPqvZ3Pryuzt1SD/lg5wEcWqvwzXXYGEDb2/cP0Sj5zSvHl3WkmMELr5kfWw==}
+ peerDependencies:
+ vue: ^3.5.0
+
+ '@vueuse/[email protected]':
+ resolution: {integrity: sha512-7hK4g015rWn2PhKcZ99NyT+ZD9sbwm7SGvp7k+k+rKGWnLjS/oQozoIZzWfCewSUeBmnJkIb+CNr7Zc/EyRnnA==}
+
+ '@vueuse/[email protected]':
+ resolution: {integrity: sha512-EcKxtYvn6gx1F8z9J5/rsg3+lTQnvOruQd8fUecW99DCK04BkWD7z5KQ/wTAx+DazyoEE9dJt/zV8OIEQbM6kw==}
+ peerDependencies:
+ vue: ^3.5.0
+
'@webassemblyjs/[email protected]':
resolution: {integrity: sha512-nuBEDgQfm1ccRp/8bCQrx1frohyufl4JlbMMZ4P1wpeOfDhF6FQkxZJ1b/e+PLwr6X1Nhw6OLme5usuBWYBvuQ==}
@@ -14610,6 +14632,11 @@ packages:
peerDependencies:
react: ^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0
+ resolution: {integrity: sha512-LN0BLGKMFulv0lnfK29r14DcngRUhIqdcaL0zXTt2o0oS9odlrjCGaU3/X9hIihOjjN8l8e+Y9G/famcNYaI7Q==}
+ peerDependencies:
+ vue: '>=3.0.1'
+
resolution: {integrity: sha512-zTU3DaZaF3Rt9rhN3uBMGQD3dD2/vFQqnvZCDv4dl5iOzq2IZQqTxu90r4E5J+nP70J3ilqVCrbho2eWaeW8Ow==}
@@ -29318,6 +29345,8 @@ snapshots:
'@types/[email protected]': {}
+ '@types/[email protected]': {}
+
'@types/[email protected]': {}
@@ -29763,6 +29792,19 @@ snapshots:
'@vue/[email protected]': {}
+ dependencies:
+ '@types/web-bluetooth': 0.0.21
+ '@vueuse/metadata': 14.1.0
+ '@vueuse/shared': 14.1.0([email protected]([email protected]))
+ vue: 3.5.21([email protected])
+
+ '@vueuse/[email protected]': {}
+
+ dependencies:
+ vue: 3.5.21([email protected])
+
'@webassemblyjs/[email protected]':
dependencies:
'@webassemblyjs/helper-numbers': 1.13.2
@@ -34898,6 +34940,10 @@ snapshots:
dependencies:
react: 18.3.1
+ dependencies:
+ vue: 3.5.21([email protected])
+