### Initial Setup for Snice Framework Development
Source: https://gitlab.com/hedzer/snice/-/blob/main/DEVELOPMENT.md
Commands to clone the Snice repository, navigate into the directory, install dependencies, build the project, and run tests. This is the starting point for setting up a development environment.
```bash
git clone git@gitlab.com:Hedzer/snice.git
cd snice
npm install
npm run build
npm test
```
--------------------------------
### Install and Run Snice Project
Source: https://gitlab.com/hedzer/snice/-/blob/main/bin/templates/pwa/README.md
Commands to install dependencies, start the development server, build for production, preview the production build, and perform type checking for a Snice project.
```bash
# Install dependencies
npm install
# Start dev server
npm run dev
# Build for production
npm run build
# Preview production build
npm run preview
# Type check
npm run type-check
```
--------------------------------
### Install Snice MCP Server
Source: https://gitlab.com/hedzer/snice/-/blob/main/bin/templates/CLAUDE.md
Installs the Snice MCP server, which provides access to component documentation, decorator references, code validation, and component scaffolding. This is a prerequisite for starting any work on the project.
```bash
claude mcp add snice -- npx snice mcp
```
--------------------------------
### Router Setup (TypeScript)
Source: https://gitlab.com/hedzer/snice/-/blob/main/bin/templates/CLAUDE.md
Demonstrates the correct setup for the Snice Router, including initialization with target, type, layout, and context. It also shows how to import the `page` function correctly for defining routes.
```typescript
import { Router } from 'snice';
export const { page, navigate, initialize } = Router({
target: '#app',
type: 'hash', // REQUIRED: 'hash' or 'pushstate'
layout: 'app-shell',
context: { user: null, theme: 'light' }
});
// pages import `page` from './router', NOT from 'snice'
import { page } from '../router';
```
--------------------------------
### Basic Spotlight Tour Setup (HTML & JS)
Source: https://gitlab.com/hedzer/snice/-/blob/main/docs/components/spotlight.md
Demonstrates how to set up a basic spotlight tour by defining steps and starting the tour. It includes HTML elements to target and a script to configure and launch the tour.
```html
Search...
Navigation
Profile
```
--------------------------------
### Basic Snice Flow Setup (TypeScript/HTML)
Source: https://gitlab.com/hedzer/snice/-/blob/main/docs/components/flow.md
Demonstrates the basic setup of the snice-flow component by importing the necessary module and defining initial nodes and edges in HTML and JavaScript. This is useful for getting started with simple flow diagrams.
```typescript
import 'snice/components/flow/snice-flow';
```
```html
```
--------------------------------
### CDN Build Usage Example (HTML)
Source: https://gitlab.com/hedzer/snice/-/blob/main/DEVELOPMENT.md
Demonstrates how to use Snice components bundled for CDN in HTML. Includes examples for direct browser usage with script tags and ES Module usage for dynamic element creation.
```html
Click me
```
--------------------------------
### Basic Router Setup and Navigation
Source: https://gitlab.com/hedzer/snice/-/blob/main/README.md
Provides an example of setting up the Snice router. It shows how to initialize the router with a target element and context, define page components with routes, and perform navigation programmatically.
```typescript
// main.ts
const { page, navigate, initialize } = Router({
target: '#app',
context: new AppContext()
});
// pages/home-page.ts
@page({ tag: 'home-page', routes: ['/'] })
class HomePage extends HTMLElement {
@render()
renderContent() {
return html`
Home
`;
}
}
// pages/user-page.ts
@page({ tag: 'user-page', routes: ['/users/:userId'] })
class UserPage extends HTMLElement {
@property()
userId = ''; // Auto-populated from URL
// ...
}
// main.ts
initialize();
navigate('/users/123');
```
--------------------------------
### Camera Annotate Component Examples
Source: https://gitlab.com/hedzer/snice/-/blob/main/docs/components/camera-annotate.md
Demonstrates various ways to use the Camera Annotate component, including default setup, hiding the labels panel, disabling auto color rotation, and listening to component events.
```html
```
```javascript
```
--------------------------------
### JavaScript: Usage Examples for snice-audio-recorder
Source: https://gitlab.com/hedzer/snice/-/blob/main/docs/ai/components/audio-recorder.md
Provides practical JavaScript examples for using the snice-audio-recorder component, including starting, stopping, pausing, resuming, canceling, and downloading recordings. It also shows how to upload the recorded audio.
```javascript
// Start
await recorder.start();
// Stop and get recording
const recording = await recorder.stop();
// { blob, url, duration, size, format, timestamp }
// Pause/resume
recorder.pause();
recorder.resume();
// Cancel
recorder.cancel();
// Download
recorder.download('recording.webm');
// Upload
const formData = new FormData();
formData.append('audio', recording.blob);
await fetch('/upload', { method: 'POST', body: formData });
```
--------------------------------
### Initialize Snice Spotlight with Steps (JavaScript)
Source: https://gitlab.com/hedzer/snice/-/blob/main/public/showcases/spotlight.html
This snippet demonstrates how to initialize the Snice Spotlight component and define its steps using JavaScript. It targets specific HTML elements and provides titles and descriptions for each step in the tour. The tour is then started programmatically.
```javascript
const spotlight = document.querySelector( 'snice-spotlight'); spotlight.steps = [
{ target: '#search', title: 'Search', description: 'Find anything', position: 'bottom' },
{ target: '#notifs', title: 'Notifications', description: 'Stay updated' },
{ target: '#settings', title: 'Settings', description: 'Customize your experience' }
];
spotlight.start();
```
```javascript
customElements.whenDefined('snice-spotlight').then(() => {
const spotlight = document.getElementById('demo-spotlight');
const btn = document.getElementById('spot-start-btn');
if (spotlight && btn) {
spotlight.steps = [
{ target: '#spot-step1', title: 'Search', description: 'Use the search bar to find components, docs, or examples.', position: 'bottom' },
{ target: '#spot-step2', title: 'Notifications', description: 'Check alerts and updates from your team.', position: 'bottom' },
{ target: '#spot-step3', title: 'Settings', description: 'Customize themes, preferences, and account details.', position: 'bottom' }
];
btn.addEventListener('click', () => spotlight.start());
}
});
```
--------------------------------
### Build Commands (Bash)
Source: https://gitlab.com/hedzer/snice/-/blob/main/bin/templates/CLAUDE.md
Lists the essential npm scripts for managing the Snice project, including commands for starting the development server, building for production, checking TypeScript types, and running tests.
```bash
npm run dev # Dev server
npm run build # Production build
npm run type-check # TypeScript check
npm run test # Run tests (if configured)
```
--------------------------------
### Snice Podcast Player Usage Examples
Source: https://gitlab.com/hedzer/snice/-/blob/main/docs/ai/components/podcast-player.md
Examples demonstrating how to use the snice-podcast-player component in HTML and JavaScript.
```APIDOC
## Snice Podcast Player Usage Examples
### Description
These examples illustrate how to integrate and use the `snice-podcast-player` web component in your projects.
### HTML Usage
#### Direct Source
Use this method when you have a direct URL to an audio file for a single episode.
```html
```
#### From RSS Feed
Use this method to load episodes automatically from a podcast's RSS feed.
```html
```
### JavaScript Usage
#### Programmatic Episode Loading and Control
This example shows how to select the player element, set its episodes programmatically, and control playback.
```javascript
// Get the player element
const player = document.querySelector('snice-podcast-player');
// Define episodes manually
player.episodes = [
{
title: 'Episode 1: The Beginning',
src: '/audio/ep1.mp3',
duration: 1800, // Duration in seconds
artwork: '/images/ep1_art.jpg',
description: 'The first episode of our podcast series.'
},
{
title: 'Episode 2: Deeper Dive',
src: '/audio/ep2.mp3',
duration: 2400,
chapters: [
{ title: 'Introduction', startTime: 0 },
{ title: 'Main Content Part 1', startTime: 120 },
{ title: 'Conclusion', startTime: 1500 }
]
}
];
// Load the first episode (index 0)
player.loadEpisode(0);
// You can also control playback directly
// player.play();
// player.pause();
// player.seekTo(300); // Seek to 5 minutes
// player.setPlaybackRate(1.2);
// Listen for events
player.addEventListener('podcast-play', (event) => {
console.log('Playback started for:', event.detail.episode.title);
});
player.addEventListener('podcast-time-update', (event) => {
// Update a custom progress indicator if needed
// console.log(`Time update: ${event.detail.currentTime} / ${event.detail.duration}`);
});
```
```
--------------------------------
### Setup highlight.js Highlighter for Snice
Source: https://gitlab.com/hedzer/snice/-/blob/main/components/code-block/highlighters/README.md
Integrates highlight.js with Snice by importing the library and a theme, then calling the setup function. Requires highlight.js and its styles to be installed.
```typescript
import hljs from 'highlight.js';
import 'highlight.js/styles/github-dark.css';
import { setupHighlightJs } from 'snice/components/code-block/highlighters/highlight';
setupHighlightJs(hljs);
```
--------------------------------
### Setup Prism.js Highlighter for Snice
Source: https://gitlab.com/hedzer/snice/-/blob/main/components/code-block/highlighters/README.md
Integrates Prism.js with Snice by importing necessary components and themes, then calling the setup function. Requires Prism.js and its components to be installed.
```typescript
import Prism from 'prismjs';
import 'prismjs/components/prism-javascript';
import 'prismjs/components/prism-typescript';
import 'prismjs/themes/prism-tomorrow.css';
import { setupPrismHighlighter } from 'snice/components/code-block/highlighters/prism';
setupPrismHighlighter(Prism);
```
--------------------------------
### Usage Examples
Source: https://gitlab.com/hedzer/snice/-/blob/main/docs/ai/components/nav.md
Examples demonstrating how to use the snice-nav component in HTML and JavaScript.
```APIDOC
## Usage Examples
### Description
Illustrates how to integrate and utilize the `snice-nav` component in your project.
### HTML Usage
```html
```
### JavaScript Usage
```typescript
const nav = document.querySelector('snice-nav');
nav.update([
{ name: 'home', title: 'Home', icon: '🏠', order: 0 },
{ name: 'products', title: 'Products', order: 1 },
], undefined, 'home');
```
```
--------------------------------
### Hash Navigation Example
Source: https://gitlab.com/hedzer/snice/-/blob/main/public/docs.html
Implement navigation using hash-based routing. This involves using anchor tags with `href` attributes starting with `#` (e.g., `# /about`) for declarative navigation, and the `navigate()` function for programmatic navigation. This method is suitable for simpler routing needs.
```html
About
navigate('/about');
navigate('/users/123');
```
--------------------------------
### Snice Paint Usage Examples
Source: https://gitlab.com/hedzer/snice/-/blob/main/docs/ai/components/paint.md
Examples demonstrating how to use the snice-paint web component in HTML and JavaScript.
```APIDOC
## Usage
### Basic Usage
```html
```
### Customization Examples
**Custom Colors:**
```html
```
**Minimal Controls:**
```html
```
**Custom Size Range:**
```html
```
**Custom Color Pickers in Palette:**
```html
```
**Adding Custom Tools:**
```html
```
**Replacing Color Picker:**
```html
```
**Adding a Save Button:**
```html
```
### JavaScript Interaction
```javascript
const paint = document.querySelector('snice-paint');
// Exporting Canvas Content
paint.download('artwork.png');
const url = paint.toDataURL();
// Saving and Loading Strokes
const strokes = paint.getStrokes();
paint.setStrokes(strokes);
```
```
--------------------------------
### Install Prism.js
Source: https://gitlab.com/hedzer/snice/-/blob/main/components/code-block/highlighters/README.md
Installs the Prism.js library using npm. This command is used to add Prism.js as a dependency to your project for syntax highlighting.
```bash
npm install prismjs
```
--------------------------------
### Install highlight.js
Source: https://gitlab.com/hedzer/snice/-/blob/main/components/code-block/highlighters/README.md
Installs the highlight.js library using npm. This command adds highlight.js as a dependency to your project for syntax highlighting.
```bash
npm install highlight.js
```
--------------------------------
### Snice-doc JavaScript Example
Source: https://gitlab.com/hedzer/snice/-/blob/main/docs/ai/components/doc.md
A practical JavaScript example demonstrating how to initialize and use the snice-doc component, including setting content and exporting formats.
```APIDOC
## Example
```javascript
const doc = document.querySelector('snice-doc');
doc.setHTML(`
Title
Content with bold and italic.
`);
// Export formats
const html = doc.getHTML();
const markdown = doc.getMarkdown();
const text = doc.getText();
// Download
doc.downloadAs('markdown', 'my-doc.md');
doc.downloadAs('html');
doc.downloadAs('text');
```
```
--------------------------------
### Snice Timer Stopwatch Example (HTML & JS)
Source: https://gitlab.com/hedzer/snice/-/blob/main/docs/components/timer.md
An example of using the Snice Timer as a stopwatch. It shows how to get a reference to the timer element, start and stop it programmatically, and retrieve the elapsed time.
```html
```
--------------------------------
### JavaScript API for snice-timer Control
Source: https://gitlab.com/hedzer/snice/-/blob/main/docs/ai/components/timer.md
Provides examples of controlling the snice-timer component using its JavaScript API. Shows how to start, stop, reset the timer, get the current time, and listen for timer events.
```javascript
const timer = document.querySelector('snice-timer');
timer.start();
timer.stop();
timer.reset();
console.log(timer.getTime());
timer.addEventListener('timer-complete', () => {
console.log('Countdown finished');
});
```
--------------------------------
### React Usage Example (TypeScript)
Source: https://gitlab.com/hedzer/snice/-/blob/main/DEVELOPMENT.md
Demonstrates how to use the generated React adapters for Snice components like Input and Button. It shows state management with useState and ref handling with useRef. Assumes Snice React components are installed.
```tsx
import { Button, Input } from 'snice/react';
function MyForm() {
const [value, setValue] = useState('');
const buttonRef = useRef();
return (
);
}
```
--------------------------------
### Basic Commands Example (HTML & JavaScript)
Source: https://gitlab.com/hedzer/snice/-/blob/main/docs/components/command-palette.md
An example illustrating how to set up basic commands for the command palette. It focuses on defining the id, label, icon, and category for each command.
```html
```
--------------------------------
### Control Snice Camera Feed (JavaScript)
Source: https://gitlab.com/hedzer/snice/-/blob/main/docs/components/camera.md
Provides JavaScript examples for controlling the Snice camera component, including starting, stopping, capturing, switching cameras, checking activity, getting the media stream, and managing fullscreen mode.
```javascript
// Start camera feed
await camera.start();
```
```javascript
// Stop camera and release resources
camera.stop();
```
```javascript
// Capture current frame as image
const image = await camera.capture();
// Returns: { dataURL, blob, width, height, timestamp }
```
```javascript
// Toggle between front/back camera
await camera.switchCamera();
```
```javascript
// Check if camera is running
if (camera.isActive()) {
// Camera is on
}
```
```javascript
// Get current media stream
const stream = camera.getStream();
```
```javascript
// Enter fullscreen mode
camera.enterFullscreen();
```
```javascript
// Exit fullscreen mode
camera.exitFullscreen();
```
```javascript
// Toggle fullscreen mode
camera.toggleFullscreen();
```
--------------------------------
### Commands with Actions Example (JavaScript)
Source: https://gitlab.com/hedzer/snice/-/blob/main/docs/components/command-palette.md
Shows how to define commands that perform specific actions when executed. This example includes a theme toggle and a logout function, demonstrating asynchronous actions.
```javascript
palette.commands = [
{
id: 'theme-toggle',
label: 'Toggle Theme',
icon: '🌓',
action: () => {
document.body.classList.toggle('dark-mode');
}
},
{
id: 'logout',
label: 'Logout',
icon: '🚪',
action: async () => {
await fetch('/api/logout', { method: 'POST' });
window.location.href = '/login';
}
}
];
```
--------------------------------
### Snice Button Component Examples (HTML)
Source: https://gitlab.com/hedzer/snice/-/blob/main/components/button/demo.html
This snippet showcases practical applications of the Snice Button component in various UI contexts. It includes examples for form actions (Save, Cancel, Delete), toolbar buttons (New, Edit, Copy, Paste, Delete), call-to-action buttons (Get Started, Learn More), icon-only buttons, confirmation dialogs, and button groups.
```html
Are you sure you want to delete this item?
```
--------------------------------
### Clone Project and Install Dependencies
Source: https://gitlab.com/hedzer/snice/-/blob/main/DEVELOPMENT.md
Clones the Snice project from GitLab and installs its npm dependencies. This is a standard first step for contributing to the project.
```bash
git clone git@gitlab.com:Hedzer/snice.git
cd snice
npm install
```
--------------------------------
### Configure Kanban Board for Project Management with JavaScript
Source: https://gitlab.com/hedzer/snice/-/blob/main/docs/components/kanban.md
An example of setting up a Kanban board for project management, including columns for backlog, current sprint, review, and deployed. It demonstrates defining columns with limits, colors, and populating them with cards containing various details like assignee and labels.
```javascript
kanban.columns = [
{
id: 'backlog',
title: 'Backlog',
cards: [
{ id: 1, title: 'Feature A', labels: ['feature'], assignee: 'John' },
{ id: 2, title: 'Bug Fix B', labels: ['bug'], color: '#f44336' }
]
},
{
id: 'sprint',
title: 'Current Sprint',
limit: 5,
color: '#ff9800',
cards: [
{
id: 3,
title: 'Implement Auth',
description: 'JWT-based authentication',
assignee: 'Sarah',
labels: ['backend', 'security']
}
]
},
{
id: 'review',
title: 'Code Review',
color: '#9c27b0',
cards: []
},
{
id: 'deployed',
title: 'Deployed',
color: '#4caf50',
cards: []
}
];
```
--------------------------------
### Start Spotlight Tour
Source: https://gitlab.com/hedzer/snice/-/blob/main/docs/components/spotlight.md
Initiates the spotlight tour from the first step. This method should be called after defining the tour steps.
```typescript
spotlight.start();
```
--------------------------------
### Snice Timer Countdown Example (HTML & JS)
Source: https://gitlab.com/hedzer/snice/-/blob/main/docs/components/timer.md
This example demonstrates the countdown timer functionality of the Snice Timer component. It includes setting the initial time, starting the timer, and listening for the 'timer-complete' event.
```html
```
--------------------------------
### Set up Snice Router for SPA
Source: https://gitlab.com/hedzer/snice/-/blob/main/public/docs.html
Demonstrates the basic setup for initializing the Snice router in a single-page application. It shows how to configure the target element and routing type (hash or pushstate). Dependencies include the 'snice' library.
```typescript
import { Router } from 'snice';
const router = Router({
target: '#app', // Target element selector
type: 'hash' // 'hash' or 'pushstate'
});
// Destructure router methods
const { page, initialize, navigate } = router;
```
--------------------------------
### Time Range Picker Component Examples
Source: https://gitlab.com/hedzer/snice/-/blob/main/public/components.html
Illustrates the snice-time-range-picker component for selecting time ranges. Examples include setting start and end times, granularity, value, and options for 12-hour format, multiple selections, and disabled ranges.
```html
```
--------------------------------
### HTML Examples of Basic Cards
Source: https://gitlab.com/hedzer/snice/-/blob/main/docs/components/card.md
Presents multiple HTML examples showcasing basic card usage. This includes a simple card with default settings and a card with structured text content like a title and paragraph.
```html
This is a basic card with default settings.
Card Title
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
```
--------------------------------
### Router Setup
Source: https://gitlab.com/hedzer/snice/-/blob/main/docs/routing.md
Demonstrates how to set up the Snice router, including options for target element, routing type, and context.
```APIDOC
## Router Setup
### Creating a Router
```typescript
import { Router } from 'snice';
const router = Router({
target: '#app', // Target element selector
type: 'hash' // 'hash' or 'pushstate'
});
// Destructure router methods
const { page, initialize, navigate } = router;
```
### Router Options
```typescript
interface RouterOptions {
target: string; // Target element selector
type: 'hash' | 'pushstate'; // Routing type
window?: Window; // Override window object (for testing)
document?: Document; // Override document object (for testing)
transition?: Transition; // Global transition config
layout?: string; // Default layout for all pages
context?: any; // Router context object (shared state)
fetcher?: Fetcher; // Optional fetch middleware (see docs/fetcher.md)
}
```
### Router Context
The context object provides shared state across all pages and layouts:
```typescript
// app-context.ts
class AppContext {
user: User | null = null;
theme: 'light' | 'dark' = 'light';
setUser(user: User) {
this.user = user;
}
getUser() {
return this.user;
}
}
// main.ts
const { page, initialize } = Router({
target: '#app',
type: 'hash',
context: new AppContext()
});
```
```
--------------------------------
### Gauge Component API
Source: https://gitlab.com/hedzer/snice/-/blob/main/docs/components/gauge.md
This section details the properties and usage of the Snice Gauge component, including basic setup, customization options, and examples.
```APIDOC
## Gauge Component
### Description
The gauge component renders an SVG-based semicircle gauge/meter chart, ideal for dashboards and data visualization. It displays a value within a range using an animated arc fill with optional label text.
### Properties
| Property | Type | Default | Description |
|----------|------|---------|-------------|
| `value` | `number` | `0` | Current value to display |
| `min` | `number` | `0` | Minimum value of the range |
| `max` | `number` | `100` | Maximum value of the range |
| `label` | `string` | `''` | Label text displayed below the gauge |
| `variant` | `'default' | 'primary' | 'success' | 'warning' | 'error' | 'info'` | `'default'` | Color variant |
| `size` | `'small' | 'medium' | 'large'` | `'medium'` | Gauge size |
| `showValue` | `boolean` | `true` | Whether to display the numeric value |
| `thickness` | `number` | `8` | Stroke thickness of the gauge arc |
### Basic Usage
```html
```
```typescript
import 'snice/components/gauge/snice-gauge';
```
### Examples
#### Basic Gauge
```html
```
#### Color Variants
```html
```
#### Different Sizes
```html
```
#### Custom Range
```html
```
#### Custom Thickness
```html
```
#### Without Value Display
```html
```
#### Dashboard Layout
```html
```
#### Dynamic Updates
```html
```
### CSS Parts
Style internal elements from outside the shadow DOM using `::part()`.
| Part | Element | Description |
|------|---------|-------------|
| `base` | `
` | Outer gauge container with `role="meter"` |
| `value` | `` | Numeric value text displayed inside the gauge |
| `label` | `` | Label text displayed below the gauge |
```css
snice-gauge::part(value) {
font-size: 2rem;
font-weight: 800;
}
snice-gauge::part(label) {
color: #64748b;
font-size: 0.875rem;
}
```
```
--------------------------------
### Basic Music Player Setup (HTML and JavaScript)
Source: https://gitlab.com/hedzer/snice/-/blob/main/docs/components/music-player.md
Demonstrates the basic setup of the snice-music-player component in HTML and how to assign a track list using JavaScript. Requires the component to be imported.
```html
```
--------------------------------
### CI/CD Pipeline Configuration (YAML)
Source: https://gitlab.com/hedzer/snice/-/blob/main/tests/react-adapters/README.md
Example CI/CD pipeline script for integrating React adapter tests. This script installs dependencies, builds the React adapters, and runs the tests.
```yaml
# .gitlab-ci.yml or .github/workflows/test.yml
test:
script:
- npm install
- npm run build:react
- npm run test:react-adapters
```
--------------------------------
### Podcast Player Initialization and Episode Loading (JavaScript)
Source: https://gitlab.com/hedzer/snice/-/blob/main/docs/ai/components/podcast-player.md
Provides a JavaScript example for interacting with the snice-podcast-player component. It shows how to select the player element, programmatically set the episode list with chapter data, and load a specific episode.
```javascript
const player = document.querySelector('snice-podcast-player');
player.episodes = [
{ title: 'Ep 1', src: '/audio/ep1.mp3', duration: 1800 },
{ title: 'Ep 2', src: '/audio/ep2.mp3', duration: 2400,
chapters: [
{ title: 'Intro', startTime: 0 },
{ title: 'Main Topic', startTime: 120 }
]
}
];
player.loadEpisode(0);
```
--------------------------------
### Snice Tabs Placement Examples (HTML)
Source: https://gitlab.com/hedzer/snice/-/blob/main/docs/components/tabs.md
Illustrates how to control the positioning of the tab navigation using the 'placement' attribute. Options include 'top' (default), 'bottom', 'start', and 'end'.
```html
```
--------------------------------
### HTML Usage Examples for snice-split-pane
Source: https://gitlab.com/hedzer/snice/-/blob/main/docs/ai/components/split-pane.md
Demonstrates how to use the snice-split-pane component in HTML, including basic setup, setting direction, and configuring sizes. The component utilizes slots for primary and secondary pane content.
```html
Left pane
Right pane
Top
Bottom
30%
70%
```
--------------------------------
### Pushstate Navigation Example (JavaScript)
Source: https://gitlab.com/hedzer/snice/-/blob/main/docs/routing.md
Demonstrates navigation using the pushstate API, which allows for cleaner URLs without hash fragments. This requires initializing the router with the 'pushstate' type.
```html
About
```
```javascript
const { navigate } = Router({
target: '#app',
type: 'pushstate'
});
navigate('/about');
```
--------------------------------
### Native Element Controllers (HTML)
Source: https://gitlab.com/hedzer/snice/-/blob/main/bin/templates/CLAUDE.md
Demonstrates how to attach controllers to any HTML element using the `controller` attribute. This functionality is enabled automatically on load without requiring explicit setup.
```html
...
```
--------------------------------
### Initialize and Control Spotlight Tour (JavaScript)
Source: https://gitlab.com/hedzer/snice/-/blob/main/docs/ai/components/spotlight.md
Demonstrates how to initialize and control the snice-spotlight component using JavaScript. It shows how to set the `steps` property, start the tour, and listen for the `spotlight-end` event.
```javascript
const spotlight = document.querySelector('snice-spotlight');
spotlight.steps = [
{ target: '#step1', title: 'Welcome', description: 'This is the first step', position: 'bottom' },
{ target: '#step2', title: 'Next', description: 'Click here to continue', position: 'right' },
{ target: '#step3', title: 'Done', description: 'All set!', position: 'top' }
];
spotlight.start();
spotlight.addEventListener('spotlight-end', () => {
console.log('Tour completed');
});
```
--------------------------------
### Kanban Usage Example (JavaScript)
Source: https://gitlab.com/hedzer/snice/-/blob/main/docs/ai/components/kanban.md
Demonstrates how to initialize and interact with the snice-kanban component using JavaScript. It covers setting initial data, performing card operations, applying filters, and handling events.
```javascript
kanban.columns = [
{
id: 'todo',
title: 'To Do',
color: '#f44336',
cards: [
{
id: 1,
title: 'Task',
description: 'Details',
assignee: 'Alice',
labels: [
'bug',
{ text: 'urgent', color: '#dc2626', background: '#fee2e2', icon: '🔥', iconPosition: 'left' }
],
color: '#f44336'
}
]
},
{ id: 'done', title: 'Done', cards: [] }
];
// Add/remove/move
kanban.addCard('todo', { id: 2, title: 'New Task' });
kanban.moveCard(1, 'done');
kanban.removeCard(2);
// Filter/search
kanban.filterByLabels(['bug', 'high-priority']);
kanban.search('landing page');
kanban.clearFilters();
// Events
kanban.addEventListener('kanban-card-move', (e) => {
console.log(`Moved ${e.detail.card.title}`);
});
```
--------------------------------
### Router Guards Signature (TypeScript)
Source: https://gitlab.com/hedzer/snice/-/blob/main/bin/templates/CLAUDE.md
Illustrates the correct signature for router guards in Snice, emphasizing the need for two parameters: `context` and `params`. It contrasts this with an incorrect example that misses these parameters.
```typescript
// CORRECT:
const isAuthenticated = (context: any, params: any) => context.principal?.isAuthenticated === true;
// WRONG:
const isAuth = (ctx) => ctx.isAuthenticated; // Missing params, wrong property access
```
--------------------------------
### JavaScript API for Audio Recording Control
Source: https://gitlab.com/hedzer/snice/-/blob/main/docs/components/audio-recorder.md
Provides JavaScript examples for controlling the audio recorder, including starting, stopping, downloading, and uploading recordings. It also shows how to handle the returned AudioRecording object.
```javascript
const recorder = document.querySelector('snice-audio-recorder');
// Start
await recorder.start();
// Stop and get recording
const recording = await recorder.stop();
console.log(recording.url, recording.duration, recording.size);
```
```javascript
const recording = await recorder.stop();
recorder.download('my-recording.webm');
```
```javascript
const recording = await recorder.stop();
const formData = new FormData();
formData.append('audio', recording.blob, 'recording.webm');
await fetch('/upload', { method: 'POST', body: formData });
```
--------------------------------
### Guided Tour Overlay with Steps (HTML, JavaScript)
Source: https://gitlab.com/hedzer/snice/-/blob/main/public/components.html
Provides a guided tour overlay that highlights elements with step-by-step instructions. It accepts an array of step configurations, including target element IDs, titles, descriptions, and positions.
```html
```
```javascript
const spotlight = document.querySelector( 'snice-spotlight');
spotlight.steps = [
{ target: '#search', title: 'Search', description: 'Find anything', position: 'bottom' },
{ target: '#notifs', title: 'Notifications', description: 'Stay updated' },
{ target: '#settings', title: 'Settings', description: 'Customize your experience' }
];
spotlight.start();
```
```javascript
customElements.whenDefined('snice-spotlight').then(() => {
const spotlight = document.getElementById('demo-spotlight');
const btn = document.getElementById('spot-start-btn');
if (spotlight && btn) {
spotlight.steps = [
{ target: '#spot-step1', title: 'Search', description: 'Use the search bar to find components, docs, or examples.', position: 'bottom' },
{ target: '#spot-step2', title: 'Notifications', description: 'Check alerts and updates from your team.', position: 'bottom' },
{ target: '#spot-step3', title: 'Settings', description: 'Customize themes, preferences, and account details.', position: 'bottom' }
];
btn.addEventListener('click', () => spotlight.start());
}
});
```
--------------------------------
### Basic snice-stepper Usage (HTML and JavaScript)
Source: https://gitlab.com/hedzer/snice/-/blob/main/docs/ai/components/stepper.md
Demonstrates the basic setup and initialization of the snice-stepper component. It shows how to define the steps and set the initial current step using JavaScript after the component is rendered in HTML.
```html
```
--------------------------------
### Basic Snice Table Usage (TypeScript & HTML)
Source: https://gitlab.com/hedzer/snice/-/blob/main/docs/components/table.md
Demonstrates the basic setup of a snice-table component by importing the necessary module and configuring columns and data using JavaScript. This is the foundational example for using the table.
```typescript
import 'snice/components/table/snice-table';
```
```html
```
--------------------------------
### Context-Aware Fetcher Setup (JavaScript)
Source: https://gitlab.com/hedzer/snice/-/blob/main/public/docs.html
Demonstrates setting up a `ContextAwareFetcher` with middleware for request and response handling. It shows how to add authentication headers to requests and handle HTTP errors globally. Dependencies: `Router`, `ContextAwareFetcher` from 'snice'.
```javascript
import { Router, ContextAwareFetcher } from 'snice'; // Create a fetcher instance const fetcher = new ContextAwareFetcher(); // Attach JWT to outgoing requests fetcher.use('request', function(request, next) { // \`this\` is bound to the Context instance const jwt = this.application.principal?.token; if (jwt) { request.headers.set('Authorization', `Bearer ${jwt}`); } return next(); }); // Add response middleware (runs after fetch) fetcher.use('response', async function(response, next) { if (!response.ok) { throw new Error(`HTTP ${response.status}: ${response.statusText}`); } return next(); }); // Pass fetcher to Router const router = Router({ target: '#app', context: { auth: null }, fetcher }); router.initialize();
```