### Complete Setup Example (Other Frameworks)
Source: https://velt.dev/docs/async-collaboration/comments/standalone-components/comment-thread/setup
An example for other frameworks showing how to retrieve comments and prepare for rendering comment threads. Includes subscription management.
```js
const commentElement = client.getCommentElement();
let subscription = commentElement.getAllCommentAnnotations().subscribe((comments) => {
// If you are using pure html, inject
// In other frameworks, you can loop over the comments inside the template itself
});
//To unsubscribe from the subscription:
subscription?.unsubscribe()
```
--------------------------------
### Complete React/Next.js Setup Example
Source: https://velt.dev/docs/async-collaboration/arrows/setup
A full example demonstrating the placement of VeltArrows and VeltArrowTool components in a React/Next.js application.
```javascript
import { VeltArrows, VeltArrowTool } from '@veltdev/react';
function YourComponent() {
return (
)
}
```
--------------------------------
### Complete Setup Example (React/Next.js)
Source: https://velt.dev/docs/async-collaboration/comments/standalone-components/comment-thread/setup
A full example demonstrating how to import Velt components and render comment threads within a React/Next.js document.
```jsx
import { VeltCommentThread, useCommentAnnotations } from '@veltdev/react';
export default function YourDocument() {
let commentAnnotations = useCommentAnnotations()
return (
{commentAnnotations.map((x,i) => )}
)
}
```
--------------------------------
### Complete HTML Setup Example
Source: https://velt.dev/docs/async-collaboration/arrows/setup
A full HTML example showing how to integrate Velt Arrows using custom elements and the Velt SDK.
```html
Collaboration App
```
--------------------------------
### Simple HTML Setup with Velt SDK
Source: https://velt.dev/docs/get-started/quickstart
A minimal HTML setup for integrating Velt. This example focuses on loading the SDK and initializing it.
```html
My Collaborative App
My Collaborative App
```
--------------------------------
### Complete Freestyle Setup Example (React)
Source: https://velt.dev/docs/async-collaboration/comments/setup/freestyle
A full example demonstrating the integration of VeltProvider, VeltComments, and VeltCommentTool in a React application.
```jsx
import {
VeltProvider,
VeltComments,
VeltCommentTool
} from '@veltdev/react';
export default function App() {
return (
);
}
```
--------------------------------
### Initiate Velt Installation via AI Chat
Source: https://velt.dev/docs/get-started/mcp-installer
Starts the Velt installation process by sending a command to your AI chat. The AI will then guide you through the setup steps.
```text
install velt
```
--------------------------------
### Complete React/Next.js Setup Example
Source: https://velt.dev/docs/in-app-user-feedback/setup
A full example demonstrating the import and placement of the VeltUserRequestTool component within a React functional component.
```javascript
import { VeltUserRequestTool } from '@veltdev/react';
function YourComponent() {
return (
)
}
```
--------------------------------
### Complete React/Next.js Setup Example
Source: https://velt.dev/docs/async-collaboration/view-analytics/setup
A full example demonstrating the import and usage of the VeltViewAnalytics component within a React functional component. Ensure you have the necessary imports.
```jsx
import { VeltViewAnalytics } from '@veltdev/react';
function YourComponent() {
return (
)
}
```
--------------------------------
### Full Velt Setup with Page Mode (HTML)
Source: https://velt.dev/docs/async-collaboration/comments/setup/page
This example demonstrates the complete HTML setup for Velt, including script loading, initialization, and the necessary custom elements for Page Mode.
```html
Collaboration App
```
--------------------------------
### Get Users Response Example
Source: https://velt.dev/docs/backend-sdks/node
An example of the response structure when fetching user data.
```json
{
success: true,
statusCode: 200,
data: [{ userId: 'user-1', name: 'John Doe', email: 'john@example.com' }]
}
```
--------------------------------
### Complete React/Next.js Inline Reactions Setup
Source: https://velt.dev/docs/async-collaboration/reactions/setup
A full example demonstrating the import, container setup, and component integration for Velt Inline Reactions in a React/Next.js application.
```jsx
import { VeltInlineReactionsSection } from '@veltdev/react';
export default function App() {
return (
Your Article
);
}
```
--------------------------------
### Complete Freestyle Setup Example (HTML)
Source: https://velt.dev/docs/async-collaboration/comments/setup/freestyle
A basic HTML structure showing the integration of the and custom elements.
```html
Comment documentation
```
--------------------------------
### Full Velt Setup with Page Mode (React/Next.js)
Source: https://velt.dev/docs/async-collaboration/comments/setup/page
This example shows a complete setup for React/Next.js, including VeltProvider, VeltComments, VeltCommentsSidebar with pageMode enabled, and VeltSidebarButton.
```jsx
import {
VeltProvider,
VeltCommentsSidebar,
VeltSidebarButton,
} from '@veltdev/react';
export default function App() {
return (
{/* Add VeltComments to the root of your app provider */}
{/* Add VeltCommentsSidebar to the root of your app provider */}
{/* Add VeltCommentSideBarButton wherever you want it to appear */}
);
}
```
--------------------------------
### Complete HTML Inline Reactions Setup
Source: https://velt.dev/docs/async-collaboration/reactions/setup
A complete HTML example showing the structure for integrating Velt Inline Reactions, including the container and the custom element.
```html
Your Article
```
--------------------------------
### Complete HTML Setup with Velt SDK
Source: https://velt.dev/docs/async-collaboration/comments-sidebar/v1/setup
An example of integrating Velt components in a plain HTML file, including SDK initialization.
```html
Collaboration App
```
--------------------------------
### Response Example - Get Users V2
Source: https://velt.dev/docs/api-reference/rest-apis/v2/users/get-users-v2
An example of a successful response from the Get Users V2 API, showcasing the structure of returned user data.
```javascript
{
"result": {
"status": "success",
"message": "User(s) retrieved successfully.",
"data": [
{
"email": "userEmail@domain.com",
"name": "userName",
"userId": "yourUserId"
}
],
"pageToken": "pageToken"
}
}
```
--------------------------------
### Start Velt MCP Installer via stdio
Source: https://velt.dev/docs/get-started/mcp-installer
Runs the Velt MCP installer directly using npx, suitable for editors that support stdio communication. This command can also be integrated into other editor configurations.
```bash
npx -y @velt-js/mcp-installer
```
--------------------------------
### Complete React/Next.js Setup with VeltProvider
Source: https://velt.dev/docs/async-collaboration/comments-sidebar/v1/setup
A full example demonstrating the integration of Velt components within a VeltProvider for a React/Next.js application.
```jsx
import {
VeltProvider,
VeltCommentsSidebar,
VeltSidebarButton,
VeltCommentTool
} from '@veltdev/react';
export default function App() {
return (
{/* Add VeltComments to the root of your app provider */}
{/* Add VeltCommentsSidebar to the root of your app provider */}
{/* Add VeltCommentTool wherever you want it to appear */}
{/* Add VeltCommentSideBarButton wherever you want it to appear */}
);
}
```
--------------------------------
### Complete HTML Setup for Velt User Invite Tool
Source: https://velt.dev/docs/permission-management/share-and-invite/setup
This example demonstrates the full HTML structure required to initialize Velt and display the user invite tool. Ensure you replace 'YOUR_VELT_API_KEY' with your actual API key.
```html
Collaboration App
```
--------------------------------
### Complete HTML Huddle Setup
Source: https://velt.dev/docs/realtime-collaboration/huddle/setup
An example showing the basic HTML structure for integrating Velt Huddle components in non-React frameworks.
```html
```
--------------------------------
### Complete React/Next.js Setup for Velt User Invite Tool
Source: https://velt.dev/docs/permission-management/share-and-invite/setup
This example shows the complete integration of the VeltUserInviteTool within a React component, including the necessary import statement.
```javascript
import { VeltUserInviteTool } from '@veltdev/react';
function YourComponent() {
return (
//
//
)
}
```
--------------------------------
### Complete React/Next.js Huddle Setup
Source: https://velt.dev/docs/realtime-collaboration/huddle/setup
A full example demonstrating the integration of VeltHuddle and VeltHuddleTool components within a React/Next.js application structure.
```javascript
import { VeltHuddle, VeltHuddleTool} from '@veltdev/react';
export default function App() {
return (
{/* Add VeltHuddle at the root of your app */}
{/* Add VeltHuddleTool where you want the huddle button to appear */}
);
}
```
--------------------------------
### Fetch Users from DB (Other Frameworks)
Source: https://velt.dev/docs/self-host-data/users
Implement the `get` method to fetch user data from your API. This example shows how to integrate it with Velt's global configuration for other JavaScript frameworks.
```js
const fetchUsersFromDB = async (userIds) => {
const response = await fetch('/api/velt/users/get', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ userIds })
});
return await response.json();
};
const userDataProvider = {
get: fetchUsersFromDB,
};
Velt.setDataProviders({ user: userDataProvider });
```
--------------------------------
### Basic HTML Structure with
Source: https://velt.dev/docs/realtime-collaboration/cursors/setup
An example of a basic HTML file structure including the tag. This setup is for frameworks other than React/Next.js.
```html
Cursors documentation
```
--------------------------------
### Velt Recorder Tool and Control Panel Setup (HTML)
Source: https://velt.dev/docs/async-collaboration/recorder/setup
Set up Velt Recorder tools and control panel using plain HTML. This example demonstrates the usage of custom elements for the recorder tool, control panel, and player.
```html
```
--------------------------------
### Manual VeltProvider Setup in React
Source: https://velt.dev/docs/get-started/cli
This example demonstrates how to set up the `VeltProvider` in your React application for collaboration features. Ensure it's placed in the specific page component where collaboration occurs, not in the layout file.
```tsx
// app/dashboard/[docId]/page.tsx (or your collaboration page)
"use client";
import { VeltProvider } from '@veltdev/react';
import { useVeltAuthProvider } from '@/components/velt/VeltInitializeUser';
import { VeltCollaboration } from '@/components/velt/VeltCollaboration';
export default function DocumentPage() {
const { authProvider } = useVeltAuthProvider();
return (
{/* Your page content */}
);
}
```
--------------------------------
### Complete SDK Configuration Example
Source: https://velt.dev/docs/backend-sdks/node
A full example demonstrating initialization with database connection string and API credentials, including graceful shutdown handling for SIGTERM signals.
```typescript
import { VeltSDK } from '@veltdev/node';
const sdk = VeltSDK.initialize({
database: {
connection_string: 'mongodb+srv://user:pass@cluster.mongodb.net/velt-db',
},
apiKey: 'YOUR_VELT_API_KEY',
authToken: 'YOUR_VELT_AUTH_TOKEN'
});
// Graceful shutdown
process.on('SIGTERM', async () => {
await sdk.close();
process.exit(0);
});
```
--------------------------------
### Main Application Setup (main.ts)
Source: https://velt.dev/docs/realtime-collaboration/crdt/setup/core-stores/text
This snippet sets up the main application by importing necessary styles and modules, and then initializing the notepad form handlers. Ensure the CSS and Velt modules are correctly imported.
```typescript
import './style.css';
import './velt';
import { setupNotepadForm } from './notepad';
// Attach form handlers once the DOM is ready
setupNotepadForm();
```
--------------------------------
### Complete Collaborative Key-Value Editor with useStore
Source: https://velt.dev/docs/realtime-collaboration/crdt/setup/core-stores/map
This example demonstrates a full implementation of a collaborative key-value store using the `useStore` hook. It includes functionality for adding, updating, deleting entries, and managing version history. Ensure `@veltdev/crdt-react` is installed.
```tsx
import React, { useState, useEffect, useCallback } from 'react';
import { useStore, Version } from '@veltdev/crdt-react';
type KVMap = Record;
const defaultEntries: KVMap = {
greeting: 'Hello World',
language: 'TypeScript',
framework: 'React',
};
export const KeyValueStore = () => {
const [newKey, setNewKey] = useState('');
const [newValue, setNewValue] = useState('');
const [versionName, setVersionName] = useState('');
const [versions, setVersions] = useState([]);
// Use the useStore hook — handles initialization and subscriptions automatically
const {
value: entries,
update: updateEntries,
store,
saveVersion: storeSaveVersion,
getVersions: storeGetVersions,
restoreVersion: storeRestoreVersion,
getVersionById,
setStateFromVersion,
} = useStore({
storeId: 'my-kvstore',
type: 'map',
initialValue: defaultEntries,
});
// Fetch saved versions when store is ready
const refreshVersions = useCallback(async () => {
const v = await storeGetVersions();
setVersions(v);
}, [storeGetVersions]);
useEffect(() => {
if (store) refreshVersions();
}, [refreshVersions, store]);
const entriesMap = (entries && typeof entries === 'object' && !Array.isArray(entries)) ? entries : {};
// Add a new entry
const handleAddEntry = (e: React.FormEvent) => {
e.preventDefault();
if (newKey.trim() && newValue.trim() && store) {
const current = store.getValue() || {};
updateEntries({ ...current, [newKey.trim()]: newValue.trim() });
setNewKey('');
setNewValue('');
}
};
// Update an existing entry
const handleUpdateEntry = (key: string, value: string) => {
if (!store) return;
const current = store.getValue() || {};
updateEntries({ ...current, [key]: value });
};
// Delete an entry
const handleDeleteEntry = (key: string) => {
if (!store) return;
const current = store.getValue() || {};
const updated = { ...current };
delete updated[key];
updateEntries(updated);
};
// Handle saving a new version
const handleSaveVersion = async (e: React.FormEvent) => {
e.preventDefault();
if (versionName.trim()) {
await storeSaveVersion(versionName.trim());
setVersionName('');
await refreshVersions();
}
};
// Handle restoring a version
const handleRestoreVersion = async (versionId: string) => {
await storeRestoreVersion(versionId);
const version = await getVersionById(versionId);
if (version) {
await setStateFromVersion(version);
}
await refreshVersions();
};
const entryKeys = Object.keys(entriesMap);
return (
);
};
```
--------------------------------
### Main Application Setup
Source: https://velt.dev/docs/realtime-collaboration/crdt/setup/core-stores/map
Imports necessary modules and calls the setup function for the key-value store form once the DOM is ready. This is the entry point for the application's interactive components.
```typescript
import './style.css';
import './velt';
import { setupKVStoreForm } from './kvstore';
// Attach form handlers once the DOM is ready
setupKVStoreForm();
```
--------------------------------
### Main Application Setup
Source: https://velt.dev/docs/realtime-collaboration/crdt/setup/core-stores/xml
Imports necessary CSS and local modules, then calls `setupOutlineForm` to initialize form event handlers once the DOM is ready.
```typescript
import './style.css';
import './velt';
import { setupOutlineForm } from './outline';
// Attach form handlers once the DOM is ready
setupOutlineForm();
```
--------------------------------
### Get API Key Config Success Response Example
Source: https://velt.dev/docs/api-reference/rest-apis/v2/workspace/apikeyconfig-get
This is an example of a successful response from the Get API Key Config endpoint. It includes owner email, plan info, default document access type, private comments flag, JWT/auto-org-user toggles, and masked AI model keys.
```json
{
"result": {
"status": "success",
"message": "API key metadata retrieved successfully.",
"data": {
"ownerEmail": "owner@example.com",
"planInfo": {
"type": "sdk test"
},
"defaultDocumentAccessType": "public",
"isPrivateCommentsEnabled": false,
"requireJwtToken": false,
"requireAutoOrgUser": false,
"aiModelsConfig": {
"openai": {
"displayText": "sk-...XyZ"
}
}
}
}
}
```
--------------------------------
### Get User Permissions Request and Response Payloads (Other Frameworks)
Source: https://velt.dev/docs/release-notes/version-4/sdk-changelog
Defines the request and response structures for the Get User Permissions API in other frameworks. Includes usage example.
```typescript
// Request Payload
interface GetUserPermissionsRequest {
organizationId?: string;
folderIds?: string[];
documentIds?: string[];
}
// Response Payload
interface GetUserPermissionsResponse {
[userId: string]: {
folders?: {
[folderId: string]: {
accessRole?: UserPermissionAccessRole;
expiresAt?: number;
error?: string;
errorCode?: UserPermissionAccessRoleResult;
}
}
organization?: {
[organizationId: string]: {
accessRole?: UserPermissionAccessRole;
expiresAt?: number;
error?: string;
errorCode?: UserPermissionAccessRoleResult;
}
}
documents?: {
[documentId: string]: {
accessRole?: UserPermissionAccessRole;
expiresAt?: number;
error?: string;
errorCode?: UserPermissionAccessRoleResult;
}
}
}
}
enum UserPermissionAccessRoleResult {
DOES_NOT_EXIST = 'does_not_exist',
PERMISSION_DENIED = 'permission_denied',
SOMETHING_WENT_WRONG = 'something_went_wrong',
}
enum UserPermissionAccessRole {
EDITOR = 'editor',
VIEWER = 'viewer',
}
// Using API
await Velt.getUserPermissions(request as GetUserPermissionsRequest);
```
--------------------------------
### Get User Permissions Request and Response Payloads (React/Next.js)
Source: https://velt.dev/docs/release-notes/version-4/sdk-changelog
Defines the request and response structures for the Get User Permissions API in React/Next.js. Includes usage example.
```typescript
// Request Payload
interface GetUserPermissionsRequest {
organizationId?: string;
folderIds?: string[];
documentIds?: string[];
}
// Response Payload
interface GetUserPermissionsResponse {
[userId: string]: {
folders?: {
[folderId: string]: {
accessRole?: UserPermissionAccessRole;
expiresAt?: number;
error?: string;
errorCode?: UserPermissionAccessRoleResult;
}
}
organization?: {
[organizationId: string]: {
accessRole?: UserPermissionAccessRole;
expiresAt?: number;
error?: string;
errorCode?: UserPermissionAccessRoleResult;
}
}
documents?: {
[documentId: string]: {
accessRole?: UserPermissionAccessRole;
expiresAt?: number;
error?: string;
errorCode?: UserPermissionAccessRoleResult;
}
}
}
}
enum UserPermissionAccessRoleResult {
DOES_NOT_EXIST = 'does_not_exist',
PERMISSION_DENIED = 'permission_denied',
SOMETHING_WENT_WRONG = 'something_went_wrong',
}
enum UserPermissionAccessRole {
EDITOR = 'editor',
VIEWER = 'viewer',
}
// Using API
await client.getUserPermissions(request as GetUserPermissionsRequest);
```
--------------------------------
### Main Application Setup - TypeScript
Source: https://velt.dev/docs/realtime-collaboration/crdt/setup/core-stores/array
Imports necessary modules and sets up the application by calling the form setup function. This is the entry point for the client-side application.
```typescript
import './style.css';
import './velt';
import { setupTodoForm } from './todos';
// Attach form handlers once the DOM is ready
setupTodoForm();
```
--------------------------------
### Get Comments API Response Example
Source: https://velt.dev/docs/api-reference/rest-apis/v2/comments-feature/comments/get-comments
This example shows the structure of a successful response when retrieving comments. It includes comment details, author information, and reaction annotations.
```json
{
"result": {
"status": "success",
"message": "Comments retrieved successfully.",
"data": [
{
"commentId": 123456,
"type": "text",
"status": "updated",
"isDraft": false,
"isCommentTextAvailable": true,
"commentText": "This is a sample comment text.",
"commentHtml": "
",
"commentId": 153783,
"commentText": "Sample Comment Text",
"from": {
"email": "user@example.com",
"name": "User Name",
"userId": "yourUserId"
},
"lastUpdated": "2024-06-20T09:53:42.258Z",
"status": "added",
"type": "text"
}
]
}
}
```
--------------------------------
### Complete Velt Comments Integration Example (React/Next.js)
Source: https://velt.dev/docs/async-collaboration/comments/setup/stream
A full example demonstrating the setup of Velt Comments in stream mode within a React/Next.js application, including the VeltProvider.
```jsx
import { VeltProvider, VeltComments, VeltCommentTool } from '@veltdev/react';
export default function App() {
return (
//This element is scrollable
//This element contains the content that you want to be commented.
);
}
```
--------------------------------
### Initialize SDK for Self-hosting
Source: https://velt.dev/docs/backend-sdks/node
Use this for self-hosting setups that require a database connection. Ensure MongoDB is running and accessible.
```typescript
import { VeltSDK } from '@veltdev/node';
const sdk = VeltSDK.initialize({
database: {
host: 'localhost:27017',
username: 'your-username',
password: 'your-password',
auth_database: 'admin',
database_name: 'velt-integration',
},
apiKey: 'YOUR_VELT_API_KEY',
authToken: 'YOUR_VELT_AUTH_TOKEN'
});
```
--------------------------------
### HTML: Include SDK and Initialize Velt
Source: https://velt.dev/docs/get-started/quickstart
Include the Velt SDK script and call the init function with your API key to bootstrap the client.
```html
```
--------------------------------
### Success Response for Get Reviewer Profile
Source: https://velt.dev/docs/api-reference/rest-apis/v2/memory/profiles/get
This is an example of a successful response containing a reviewer's behavioral profile data.
```JSON
{
"result": {
"userId": "u_sarah",
"name": "Sarah Lee",
"email": "sarah@acme.com",
"totalJudgments": 214,
"approvalRate": 0.62,
"avgReviewTimeSeconds": 87,
"topFlags": [ { "issue": "missing-citation", "count": 31 } ],
"contentTypes": ["marketing-copy"],
"peakHours": [9, 10, 14],
"orgBreakdown": {
"org_eu": {
"organizationId": "org_eu",
"clientOrganizationId": null,
"judgments": 120,
"approvals": 70,
"approvalRate": 0.58
}
},
"lastActive": 1731432000000
}
}
```
--------------------------------
### Full Example: User Invite Tool Customization (HTML)
Source: https://velt.dev/docs/permission-management/share-and-invite/customize-ui/slots
A complete HTML example showing the structure for customizing the User Invite Tool with a custom button. This includes basic HTML boilerplate.
```html
User Invite documentation
```
--------------------------------
### Example Directory Structure
Source: https://velt.dev/docs/WIREFRAME_VARIABLES_TEMPLATE
Illustrates the filename conventions for wireframe variable documentation pages based on sibling file naming.
```bash
ui-customization/features/async/comment-dialog/
├── wireframes.mdx
├── primitives.mdx
└── wireframe-variables.mdx ← bare convention
ui-customization/features/async/activity-logs/
├── activity-logs-wireframes.mdx
├── activity-logs-primitives.mdx
└── activity-logs-wireframe-variables.mdx ← prefixed convention
```
--------------------------------
### Initialize Documents in HTML
Source: https://velt.dev/docs/get-started/quickstart
Load the Velt SDK and initialize it with your API key. Then, use `Velt.setDocuments` to set up the collaborative document. The complete HTML example includes the necessary script tags and a placeholder for Velt comments.
```js
// In your script tag
async function loadVelt() {
await Velt.init("YOUR_VELT_API_KEY");
// Set document for current organization
Velt.setDocuments([
{ id: 'unique-document-id', metadata: { documentName: 'Document Name' } }
]);
}
```
```html
My Document
My Document
```
--------------------------------
### Success Response for Get Documents
Source: https://velt.dev/docs/api-reference/rest-apis/v1/documents/get-documents
This is an example of a successful response when documents are retrieved. It includes status, message, and the retrieved document data.
```JSON
{
"result": {
"status": "success",
"message": "Document(s) retrieved successfully.",
"data": [
{
"documentName": "yourDocumentName",
"disabled": false,
"accessType": "public",
"id": "yourDocumentId"
}
]
}
}
```
--------------------------------
### Full Example: User Invite Tool Customization (React/Next.js)
Source: https://velt.dev/docs/permission-management/share-and-invite/customize-ui/slots
A complete React/Next.js example demonstrating how to import and use the VeltUserInviteTool with a custom button template targeting the 'button' slot.
```javascript
import {
VeltUserInviteTool
} from '@veltdev/react';
export default function App() {
return (
<>
>
);
}
```
--------------------------------
### Configuring createLiveStateMiddleware
Source: https://velt.dev/docs/realtime-collaboration/live-state-sync/redux-middleware
Example of initializing `createLiveStateMiddleware` with specific action types, a custom allow action callback, and a custom live state data ID.
```jsx
const { middleware, updateLiveStateDataId } = createLiveStateMiddleware({
allowedActionTypes: new Set(['action1', 'action2']),
disabledActionTypes: new Set(['disabledAction1', 'disabledAction2']),
allowAction: (action) => {
// return true to allow this action, false to restrict this action from syncing
},
liveStateDataId: 'custom-live-state-data-id'
});
```
--------------------------------
### Complete CRDT Text Store Example (notepad.ts)
Source: https://velt.dev/docs/realtime-collaboration/crdt/setup/core-stores/text
This comprehensive example demonstrates initializing a CRDT text store, handling real-time updates, managing document versions, and rendering the UI. It requires Velt SDK initialization and DOM elements for the notepad and version list.
```typescript
import { Store, Version, createVeltStore } from '@veltdev/crdt';
import type { Velt } from '@veltdev/types';
import { subscribeToVeltInit } from './velt';
let store: Store | null = null;
let text = '';
let versions: Version[] = [];
// Initialize the store when the SDK is ready
async function initStore(veltClient: Velt) {
// Create the CRDT text store with initial seed content
const textStore = await createVeltStore({
id: 'my-notepad-store',
type: 'text',
initialValue: 'Welcome to the Collaborative Notepad! Start typing here...',
veltClient: veltClient,
});
if (!textStore) return;
store = textStore;
// Seed UI with the current CRDT value
text = textStore.getValue() || '';
renderNotepad();
// Subscribe to all future changes (local and remote)
textStore.subscribe((newText) => {
text = typeof newText === 'string' ? newText : '';
renderNotepad();
});
// Load saved versions
await refreshVersions();
}
// Wait for the SDK to be ready, then initialize the store
subscribeToVeltInit('notepad', (velt) => {
initStore(velt);
});
// Replace the entire text content
function updateText(newText: string) {
if (!store) return;
store.update(newText);
}
// Save a named snapshot of the current state
async function saveVersionHandler(name: string) {
if (!store) return;
await store.saveVersion(name);
await refreshVersions();
}
// Restore the store to a previously saved version
async function restoreVersionHandler(versionId: string) {
if (!store) return;
await store.restoreVersion(versionId);
const version = await store.getVersionById(versionId);
if (version) {
await store.setStateFromVersion(version);
}
await refreshVersions();
}
// Fetch the latest version list from the backend
async function refreshVersions() {
if (!store) return;
versions = await store.getVersions();
renderVersions();
}
// Render the notepad textarea and character count into the DOM
function renderNotepad() {
const textarea = document.querySelector('.notepad-textarea') as HTMLTextAreaElement;
if (textarea && textarea !== document.activeElement) {
textarea.value = text;
}
const charCount = document.querySelector('.char-count');
if (charCount) {
charCount.textContent = `${text.length} character${text.length !== 1 ? 's' : ''}`;
}
}
// Render the version list into the DOM
function renderVersions() {
const versionList = document.querySelector('.version-list');
if (!versionList) return;
versionList.innerHTML = '';
for (const version of versions) {
const li = document.createElement('li');
const nameSpan = document.createElement('span');
nameSpan.textContent = version.versionName;
const restoreBtn = document.createElement('button');
restoreBtn.textContent = 'Restore';
restoreBtn.addEventListener('click', () => restoreVersionHandler(version.versionId));
li.appendChild(nameSpan);
li.appendChild(restoreBtn);
versionList.appendChild(li);
}
}
// Attach form and textarea event handlers to the DOM
export function setupNotepadForm() {
// Handle textarea input events
const textarea = document.querySelector('.notepad-textarea') as HTMLTextAreaElement;
if (textarea) {
textarea.addEventListener('input', () => {
text = textarea.value;
updateText(text);
const charCount = document.querySelector('.char-count');
if (charCount) {
charCount.textContent = `${text.length} character${text.length !== 1 ? 's' : ''}`;
}
});
}
// Handle version form submission
const versionForm = document.getElementById('version-form');
if (versionForm) {
versionForm.addEventListener('submit', (event) => {
event.preventDefault();
const input = versionForm.querySelector('.version-input') as HTMLInputElement;
if (input && input.value.trim()) {
saveVersionHandler(input.value.trim());
input.value = '';
}
});
}
}
```
--------------------------------
### Install Baseline Velt SDK
Source: https://velt.dev/docs/get-started/cli
Run this command in your Next.js project directory to install the core Velt SDK and generate essential components.
```bash
npx @velt-js/add-velt
```
--------------------------------
### HTML: Complete Integration with Velt Initialization State
Source: https://velt.dev/docs/get-started/advanced
A full HTML example demonstrating Velt initialization using a CDN and monitoring the initialization state. It includes a basic structure for a collaborative web application.
```html
My App
My Collaborative App
```
--------------------------------
### Reconcile after a webhook outage
Source: https://velt.dev/docs/api-reference/rest-apis/v2/approval-engine/executions/get-execution-events
Use this example to fetch events for a specific execution, starting from a sequence number, to reconcile after a webhook outage.
```JSON
{
"data": {
"executionId": "exec_1777374504255_xzy43k9q",
"sinceSeq": 5
}
}
```
--------------------------------
### Get Workspace Response Payload
Source: https://velt.dev/docs/api-reference/sdk/models/data-models
Example of the response payload when retrieving workspace details. It includes status, messages, and detailed workspace information.
```python
{
'result': {
'status': 'success',
'message': 'Workspace retrieved successfully.',
'data': {
'id': 'workspace_abc123',
'name': 'My Workspace',
'owner': {
'email': 'owner@example.com',
'id': 'owner_id_123',
'name': 'John Doe',
'avatar': ''
},
'authToken': 'eyJhbGciOiJSUzI1NiIs...',
'apiKeyList': {
'velt_api_key_1': {
'apiKeyName': 'John Doe Test API Key',
'id': 'velt_api_key_1',
'type': 'testing'
}
}
}
}
}
```
--------------------------------
### Initialize Velt SDK with Full Configuration
Source: https://velt.dev/docs/backend-sdks/python
Initialize the Velt SDK with a complete configuration object that includes database, AWS, collections, user schema, and API credentials. This example demonstrates setting up all available configuration options.
```python
from velt_py import VeltSDK
config = {
'database': {
'connection_string': 'mongodb+srv://user:pass@cluster.mongodb.net/velt-db',
},
'aws': {
'bucket_name': 'your-bucket-name',
'region': 'us-east-1',
'access_key_id': 'YOUR_AWS_ACCESS_KEY',
'secret_access_key': 'YOUR_AWS_SECRET_KEY'
},
'collections': {
'comments': 'comment_annotations',
'reactions': 'reaction_annotations',
'attachments': 'attachments',
'users': 'users'
},
'user_schema': {
'userId': 'userId',
'name': 'name',
'photoUrl': 'photoUrl',
'email': 'email',
'color': 'color',
'textColor': 'textColor',
'isAdmin': 'isAdmin',
'initial': 'initial'
},
'apiKey': 'YOUR_VELT_API_KEY',
'authToken': 'YOUR_VELT_AUTH_TOKEN'
}
sdk = VeltSDK.initialize(config)
```
--------------------------------
### Get Workspace Email Configuration
Source: https://velt.dev/docs/backend-sdks/python
Retrieves the current email service configuration for the workspace. No specific setup is required beyond initializing the SDK.
```python
from velt_py.models.workspace import GetEmailConfigRequest
result = sdk.api.workspace.getEmailConfig(GetEmailConfigRequest())
```
--------------------------------
### Vue.js: Component Setup and Initialization
Source: https://velt.dev/docs/get-started/quickstart
Initialize Velt in the `mounted` hook of your Vue component. This example shows how to initialize the client and authenticate the user.
```javascript
import { initVelt } from '@veltdev/client';
export default {
name: 'App',
data() {
return {
client: null
}
},
async mounted() {
this.client = await initVelt('YOUR_VELT_API_KEY');
```