diff --git a/.agents/skills/eventa/SKILL.md b/.agents/skills/eventa/SKILL.md new file mode 100644 index 000000000..b41488f61 --- /dev/null +++ b/.agents/skills/eventa/SKILL.md @@ -0,0 +1,233 @@ +--- +name: eventa +description: >- + Guide for using @moeru/eventa — a transport-aware event library powering ergonomic RPC + and streaming flows. Use this skill whenever the user imports from '@moeru/eventa', + mentions eventa, needs cross-process/cross-thread event communication (Electron IPC, + Web Workers, WebSocket, BroadcastChannel, EventEmitter, EventTarget, Worker Threads), + wants to define type-safe events with RPC invoke patterns, needs streaming RPC + (server-streaming, client-streaming, or bidirectional), or asks about transport-agnostic + event abstractions. Also use when the user discusses alternatives to birpc or async-call-rpc. +license: MIT +metadata: + author: moeru-ai + version: "1.0.0" +--- + +# @moeru/eventa + +Transport-aware events powering ergonomic RPC and streaming flows. + +## Core Concepts + +Eventa is built around three ideas: + +1. **Events are first-class** — define typed events once, use them everywhere +2. **Transports are swappable** — the same event definitions work across Electron IPC, WebSocket, Web Workers, BroadcastChannel, EventEmitter, EventTarget, and Worker Threads +3. **RPC is just events** — invoke/stream patterns are composed from the same event primitives + +## API Quick Reference + +### Event Definition & Context + +```ts +import { createContext, defineEventa } from '@moeru/eventa' + +// Define a typed event (the generic is the payload type) +const move = defineEventa<{ x: number, y: number }>() + +// Create a base context (in-memory, useful for same-process communication) +const ctx = createContext() + +// Emit and listen +ctx.emit(move, { x: 100, y: 200 }) +ctx.on(move, ({ body }) => console.log(body.x, body.y)) +``` + +### Unary RPC (Invoke) + +```ts +import { createContext, defineInvoke, defineInvokeEventa, defineInvokeHandler } from '@moeru/eventa' + +const ctx = createContext() + +// defineInvokeEventa(optionalName) +const echo = defineInvokeEventa<{ output: string }, { input: string }>('rpc:echo') + +// Register handler (server side) +defineInvokeHandler(ctx, echo, ({ input }) => ({ output: input.toUpperCase() })) + +// Create invoke function (client side) +const invokeEcho = defineInvoke(ctx, echo) +const result = await invokeEcho({ input: 'hello' }) // { output: 'HELLO' } +``` + +### Streaming RPC (Server-Streaming) + +```ts +import { createContext, defineInvokeEventa, defineStreamInvoke, defineStreamInvokeHandler, toStreamHandler } from '@moeru/eventa' + +const ctx = createContext() +const sync = defineInvokeEventa< + { type: 'progress' | 'result', value: number }, + { jobId: string } +>('rpc:sync') + +// Generator-style handler +defineStreamInvokeHandler(ctx, sync, async function* ({ jobId }) { + for (let i = 1; i <= 5; i++) { + yield { type: 'progress' as const, value: i * 20 } + } + yield { type: 'result' as const, value: 100 } +}) + +// Or imperative style with toStreamHandler +defineStreamInvokeHandler(ctx, sync, toStreamHandler(async ({ payload, emit }) => { + emit({ type: 'progress', value: 0 }) + emit({ type: 'result', value: 100 }) +})) + +// Consume as async iterator +const stream = defineStreamInvoke(ctx, sync) +for await (const update of stream({ jobId: 'import' })) { + console.log(update.type, update.value) +} +``` + +### Client-Streaming (Stream Input, Unary Output) + +```ts +const recordRoute = defineInvokeEventa< + { distance: number, points: number }, + ReadableStream<{ lat: number, lng: number }> +>('rpc:record-route') + +defineInvokeHandler(ctx, recordRoute, async (stream) => { + let points = 0 + for await (const _ of stream) points += 1 + return { distance: points * 10, points } +}) + +const invoke = defineInvoke(ctx, recordRoute) +const input = new ReadableStream({ + start(c) { c.enqueue({ lat: 0, lng: 0 }); c.enqueue({ lat: 1, lng: 1 }); c.close() }, +}) +await invoke(input) +``` + +### Bidirectional Streaming + +```ts +const routeChat = defineInvokeEventa< + { message: string }, + ReadableStream<{ message: string }> +>('rpc:route-chat') + +defineStreamInvokeHandler(ctx, routeChat, async function* (incoming) { + for await (const note of incoming) { + yield { message: `echo: ${note.message}` } + } +}) + +const stream = defineStreamInvoke(ctx, routeChat) +for await (const note of stream(outgoing)) { + console.log(note.message) +} +``` + +### Abort/Cancel + +```ts +// Client-side cancellation +const controller = new AbortController() +const promise = invokeMethod({ input: 'work' }, { signal: controller.signal }) +controller.abort('user cancelled') + +// Server-side abort awareness +defineInvokeHandler(ctx, event, async ({ input }, options) => { + const signal = options?.abortController?.signal + if (signal?.aborted) + return { output: 'aborted' } + signal?.addEventListener('abort', () => { /* cleanup */ }, { once: true }) + return { output: `done: ${input}` } +}) +``` + +### Bulk Registration (Shorthands) + +```ts +const events = { + double: defineInvokeEventa(), + append: defineInvokeEventa(), +} + +defineInvokeHandlers(ctx, events, { + double: input => input * 2, + append: input => `${input}!`, +}) + +const { double, append } = defineInvokes(ctx, events) +``` + +## Adapters + +Each adapter wraps a specific transport into an eventa context. The pattern is always: + +```ts +import { createContext } from '@moeru/eventa/adapters/' + +const { context } = createContext(transportInstance) +``` + +### Available Adapters + +| Adapter | Import Path | Transport | +|---------|-------------|-----------| +| Electron Main | `@moeru/eventa/adapters/electron/main` | `ipcMain` + `webContents` | +| Electron Renderer | `@moeru/eventa/adapters/electron/renderer` | `ipcRenderer` | +| Web Worker (main) | `@moeru/eventa/adapters/webworkers` | `Worker` instance | +| Web Worker (worker) | `@moeru/eventa/adapters/webworkers/worker` | `self` (worker global) | +| Worker Threads (main) | `@moeru/eventa/adapters/worker-threads` | Node.js `Worker` | +| Worker Threads (worker) | `@moeru/eventa/adapters/worker-threads/worker` | `parentPort` | +| WebSocket Client | `@moeru/eventa/adapters/websocket/native` | `WebSocket` | +| WebSocket Server (H3) | `@moeru/eventa/adapters/websocket/h3` | H3 WebSocket hooks | +| BroadcastChannel | `@moeru/eventa/adapters/broadcast-channel` | `BroadcastChannel` | +| EventTarget | `@moeru/eventa/adapters/event-target` | `EventTarget` | +| EventEmitter | `@moeru/eventa/adapters/event-emitter` | Node.js `EventEmitter` | + +### Adapter Usage Pattern (Electron Example) + +```ts +// shared/events.ts — define events once +import { defineInvokeEventa } from '@moeru/eventa' +// main.ts — register handler +import { createContext } from '@moeru/eventa/adapters/electron/main' +// renderer.ts (preload) — call it +import { createContext } from '@moeru/eventa/adapters/electron/renderer' + +export const readdir = defineInvokeEventa<{ dirs: string[] }, { path: string }>('fs:readdir') +const { context } = createContext(ipcMain, mainWindow.webContents) +defineInvokeHandler(context, readdir, async ({ path }) => ({ dirs: await fs.readdir(path) })) + +const { context } = createContext(ipcRenderer) +const invokeReaddir = defineInvoke(context, readdir) +const result = await invokeReaddir({ path: '/usr' }) +``` + +## Advanced Features + +- **Directional events**: `defineInboundEventa()` and `defineOutboundEventa()` for flow control +- **Match expressions**: `matchBy(glob)`, `matchBy(regex)`, `and(...)`, `or(...)` for event filtering +- **WebSocket lifecycle**: `wsConnectedEvent` and `wsDisconnectedEvent` from the native adapter + +## Key Rules + +1. Always define events in a shared module — both sides import the same event definition for type safety +2. `defineInvokeEventa()` — Response type comes first, Request type second +3. Handlers can throw errors safely — eventa propagates them to the caller +4. Validate data at the edges — eventa forwards whatever payload you emit +5. Install only the peer dependencies you need (electron, h3, web-worker are all optional) + +## Documentation + +For the latest API reference, use context7 to query `@moeru/eventa` documentation. diff --git a/.agents/skills/pnpm/GENERATION.md b/.agents/skills/pnpm/GENERATION.md new file mode 100644 index 000000000..f650dd7d1 --- /dev/null +++ b/.agents/skills/pnpm/GENERATION.md @@ -0,0 +1,5 @@ +# Generation Info + +- **Source:** `sources/pnpm` +- **Git SHA:** `a1d6d5aef9d5f369fa2f0d8a54f1edbaff8b23b3` +- **Generated:** 2026-01-28 diff --git a/.agents/skills/pnpm/SKILL.md b/.agents/skills/pnpm/SKILL.md new file mode 100644 index 000000000..9b28506b3 --- /dev/null +++ b/.agents/skills/pnpm/SKILL.md @@ -0,0 +1,42 @@ +--- +name: pnpm +description: Node.js package manager with strict dependency resolution. Use when running pnpm specific commands, configuring workspaces, or managing dependencies with catalogs, patches, or overrides. +metadata: + author: Anthony Fu + version: "2026.1.28" + source: Generated from https://github.com/pnpm/pnpm, scripts located at https://github.com/antfu/skills +--- + +pnpm is a fast, disk space efficient package manager. It uses a content-addressable store to deduplicate packages across all projects on a machine, saving significant disk space. pnpm enforces strict dependency resolution by default, preventing phantom dependencies. Configuration should preferably be placed in `pnpm-workspace.yaml` for pnpm-specific settings. + +**Important:** When working with pnpm projects, agents should check for `pnpm-workspace.yaml` and `.npmrc` files to understand workspace structure and configuration. Always use `--frozen-lockfile` in CI environments. + +> The skill is based on pnpm 10.x, generated at 2026-01-28. + +## Core + +| Topic | Description | Reference | +|-------|-------------|-----------| +| CLI Commands | Install, add, remove, update, run, exec, dlx, and workspace commands | [core-cli](references/core-cli.md) | +| Configuration | pnpm-workspace.yaml, .npmrc settings, and package.json fields | [core-config](references/core-config.md) | +| Workspaces | Monorepo support with filtering, workspace protocol, and shared lockfile | [core-workspaces](references/core-workspaces.md) | +| Store | Content-addressable storage, hard links, and disk efficiency | [core-store](references/core-store.md) | + +## Features + +| Topic | Description | Reference | +|-------|-------------|-----------| +| Catalogs | Centralized dependency version management for workspaces | [features-catalogs](references/features-catalogs.md) | +| Overrides | Force specific versions of dependencies including transitive | [features-overrides](references/features-overrides.md) | +| Patches | Modify third-party packages with custom fixes | [features-patches](references/features-patches.md) | +| Aliases | Install packages under custom names using npm: protocol | [features-aliases](references/features-aliases.md) | +| Hooks | Customize resolution with .pnpmfile.cjs hooks | [features-hooks](references/features-hooks.md) | +| Peer Dependencies | Auto-install, strict mode, and dependency rules | [features-peer-deps](references/features-peer-deps.md) | + +## Best Practices + +| Topic | Description | Reference | +|-------|-------------|-----------| +| CI/CD Setup | GitHub Actions, GitLab CI, Docker, and caching strategies | [best-practices-ci](references/best-practices-ci.md) | +| Migration | Migrating from npm/Yarn, handling phantom deps, monorepo migration | [best-practices-migration](references/best-practices-migration.md) | +| Performance | Install optimizations, store caching, workspace parallelization | [best-practices-performance](references/best-practices-performance.md) | diff --git a/.agents/skills/pnpm/references/best-practices-ci.md b/.agents/skills/pnpm/references/best-practices-ci.md new file mode 100644 index 000000000..f2ea972f9 --- /dev/null +++ b/.agents/skills/pnpm/references/best-practices-ci.md @@ -0,0 +1,285 @@ +--- +name: pnpm-ci-cd-setup +description: Optimizing pnpm for continuous integration and deployment workflows +--- + +# pnpm CI/CD Setup + +Best practices for using pnpm in CI/CD environments for fast, reliable builds. + +## GitHub Actions + +### Basic Setup + +```yaml +name: CI + +on: [push, pull_request] + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: pnpm/action-setup@v4 + with: + version: 9 + + - uses: actions/setup-node@v4 + with: + node-version: 20 + cache: 'pnpm' + + - run: pnpm install --frozen-lockfile + - run: pnpm test + - run: pnpm build +``` + +### With Store Caching + +For larger projects, cache the pnpm store: + +```yaml +- uses: pnpm/action-setup@v4 + with: + version: 9 + +- name: Get pnpm store directory + shell: bash + run: | + echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV + +- uses: actions/cache@v4 + name: Setup pnpm cache + with: + path: ${{ env.STORE_PATH }} + key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }} + restore-keys: | + ${{ runner.os }}-pnpm-store- + +- run: pnpm install --frozen-lockfile +``` + +### Matrix Testing + +```yaml +jobs: + test: + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: [ubuntu-latest, windows-latest, macos-latest] + node: [18, 20, 22] + steps: + - uses: actions/checkout@v4 + - uses: pnpm/action-setup@v4 + - uses: actions/setup-node@v4 + with: + node-version: ${{ matrix.node }} + cache: 'pnpm' + - run: pnpm install --frozen-lockfile + - run: pnpm test +``` + +## GitLab CI + +```yaml +image: node:20 + +stages: + - install + - test + - build + +variables: + PNPM_HOME: /root/.local/share/pnpm + PATH: $PNPM_HOME:$PATH + +before_script: + - corepack enable + - corepack prepare pnpm@latest --activate + +cache: + key: ${CI_COMMIT_REF_SLUG} + paths: + - .pnpm-store + +install: + stage: install + script: + - pnpm config set store-dir .pnpm-store + - pnpm install --frozen-lockfile + +test: + stage: test + script: + - pnpm test + +build: + stage: build + script: + - pnpm build +``` + +## Docker + +### Multi-Stage Build + +```dockerfile +# Build stage +FROM node:20-slim AS builder + +# Enable corepack for pnpm +RUN corepack enable + +WORKDIR /app + +# Copy package files first for layer caching +COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./ +COPY packages/*/package.json ./packages/ + +# Install dependencies +RUN pnpm install --frozen-lockfile + +# Copy source and build +COPY . . +RUN pnpm build + +# Production stage +FROM node:20-slim AS runner + +RUN corepack enable +WORKDIR /app + +COPY --from=builder /app/dist ./dist +COPY --from=builder /app/package.json ./ +COPY --from=builder /app/pnpm-lock.yaml ./ + +# Production install +RUN pnpm install --frozen-lockfile --prod + +CMD ["node", "dist/index.js"] +``` + +### Optimized for Monorepos + +```dockerfile +FROM node:20-slim AS builder +RUN corepack enable +WORKDIR /app + +# Copy workspace config +COPY pnpm-lock.yaml pnpm-workspace.yaml ./ + +# Copy all package.json files maintaining structure +COPY packages/core/package.json ./packages/core/ +COPY packages/api/package.json ./packages/api/ + +# Install all dependencies +RUN pnpm install --frozen-lockfile + +# Copy source +COPY . . + +# Build specific package +RUN pnpm --filter @myorg/api build +``` + +## Key CI Flags + +### --frozen-lockfile + +**Always use in CI.** Fails if `pnpm-lock.yaml` needs updates: + +```bash +pnpm install --frozen-lockfile +``` + +### --prefer-offline + +Use cached packages when available: + +```bash +pnpm install --frozen-lockfile --prefer-offline +``` + +### --ignore-scripts + +Skip lifecycle scripts for faster installs (use cautiously): + +```bash +pnpm install --frozen-lockfile --ignore-scripts +``` + +## Corepack Integration + +Use Corepack to manage pnpm version: + +```json +// package.json +{ + "packageManager": "pnpm@9.0.0" +} +``` + +```yaml +# GitHub Actions +- run: corepack enable +- run: pnpm install --frozen-lockfile +``` + +## Monorepo CI Strategies + +### Build Changed Packages Only + +```yaml +- name: Build changed packages + run: | + pnpm --filter "...[origin/main]" build +``` + +### Parallel Jobs per Package + +```yaml +jobs: + detect-changes: + runs-on: ubuntu-latest + outputs: + packages: ${{ steps.changes.outputs.packages }} + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - id: changes + run: | + echo "packages=$(pnpm --filter '...[origin/main]' list --json | jq -c '[.[].name]')" >> $GITHUB_OUTPUT + + test: + needs: detect-changes + if: needs.detect-changes.outputs.packages != '[]' + runs-on: ubuntu-latest + strategy: + matrix: + package: ${{ fromJson(needs.detect-changes.outputs.packages) }} + steps: + - uses: actions/checkout@v4 + - uses: pnpm/action-setup@v4 + - run: pnpm install --frozen-lockfile + - run: pnpm --filter ${{ matrix.package }} test +``` + +## Best Practices Summary + +1. **Always use `--frozen-lockfile`** in CI +2. **Cache the pnpm store** for faster installs +3. **Use Corepack** for consistent pnpm versions +4. **Specify `packageManager`** in package.json +5. **Use `--filter`** in monorepos to build only what changed +6. **Multi-stage Docker builds** for smaller images + + diff --git a/.agents/skills/pnpm/references/best-practices-migration.md b/.agents/skills/pnpm/references/best-practices-migration.md new file mode 100644 index 000000000..cf38b220d --- /dev/null +++ b/.agents/skills/pnpm/references/best-practices-migration.md @@ -0,0 +1,291 @@ +--- +name: migration-to-pnpm +description: Migrating from npm or Yarn to pnpm with minimal friction +--- + +# Migration to pnpm + +Guide for migrating existing projects from npm or Yarn to pnpm. + +## Quick Migration + +### From npm + +```bash +# Remove npm lockfile and node_modules +rm -rf node_modules package-lock.json + +# Install with pnpm +pnpm install +``` + +### From Yarn + +```bash +# Remove yarn lockfile and node_modules +rm -rf node_modules yarn.lock + +# Install with pnpm +pnpm install +``` + +### Import Existing Lockfile + +pnpm can import existing lockfiles: + +```bash +# Import from npm or yarn lockfile +pnpm import + +# This creates pnpm-lock.yaml from: +# - package-lock.json (npm) +# - yarn.lock (yarn) +# - npm-shrinkwrap.json (npm) +``` + +## Handling Common Issues + +### Phantom Dependencies + +pnpm is strict about dependencies. If code imports a package not in `package.json`, it will fail. + +**Problem:** +```js +// Works with npm (hoisted), fails with pnpm +import lodash from 'lodash' // Not in dependencies, installed by another package +``` + +**Solution:** Add missing dependencies explicitly: +```bash +pnpm add lodash +``` + +### Missing Peer Dependencies + +pnpm reports peer dependency issues by default. + +**Option 1:** Let pnpm auto-install: +```ini +# .npmrc (default in pnpm v8+) +auto-install-peers=true +``` + +**Option 2:** Install manually: +```bash +pnpm add react react-dom +``` + +**Option 3:** Suppress warnings if acceptable: +```json +{ + "pnpm": { + "peerDependencyRules": { + "ignoreMissing": ["react"] + } + } +} +``` + +### Symlink Issues + +Some tools don't work with symlinks. Use hoisted mode: + +```ini +# .npmrc +node-linker=hoisted +``` + +Or hoist specific packages: + +```ini +public-hoist-pattern[]=*eslint* +public-hoist-pattern[]=*babel* +``` + +### Native Module Rebuilds + +If native modules fail, try: + +```bash +# Rebuild all native modules +pnpm rebuild + +# Or reinstall +rm -rf node_modules +pnpm install +``` + +## Monorepo Migration + +### From npm Workspaces + +1. Create `pnpm-workspace.yaml`: + ```yaml + packages: + - 'packages/*' + ``` + +2. Update internal dependencies to use workspace protocol: + ```json + { + "dependencies": { + "@myorg/utils": "workspace:^" + } + } + ``` + +3. Install: + ```bash + rm -rf node_modules packages/*/node_modules package-lock.json + pnpm install + ``` + +### From Yarn Workspaces + +1. Remove Yarn-specific files: + ```bash + rm yarn.lock .yarnrc.yml + rm -rf .yarn + ``` + +2. Create `pnpm-workspace.yaml` matching `workspaces` in package.json: + ```yaml + packages: + - 'packages/*' + ``` + +3. Update `package.json` - remove Yarn workspace config if not needed: + ```json + { + // Remove "workspaces" field (optional, pnpm uses pnpm-workspace.yaml) + } + ``` + +4. Convert workspace references: + ```json + // From Yarn + "@myorg/utils": "*" + + // To pnpm + "@myorg/utils": "workspace:*" + ``` + +### From Lerna + +pnpm can replace Lerna for most use cases: + +```bash +# Lerna: run script in all packages +lerna run build + +# pnpm equivalent +pnpm -r run build + +# Lerna: run in specific package +lerna run build --scope=@myorg/app + +# pnpm equivalent +pnpm --filter @myorg/app run build + +# Lerna: publish +lerna publish + +# pnpm: use changesets instead +pnpm add -Dw @changesets/cli +pnpm changeset +pnpm changeset version +pnpm publish -r +``` + +## Configuration Migration + +### .npmrc Settings + +Most npm/Yarn settings work in pnpm's `.npmrc`: + +```ini +# Registry settings (same as npm) +registry=https://registry.npmjs.org/ +@myorg:registry=https://npm.myorg.com/ + +# Auth tokens (same as npm) +//registry.npmjs.org/:_authToken=${NPM_TOKEN} + +# pnpm-specific additions +auto-install-peers=true +strict-peer-dependencies=false +``` + +### Scripts Migration + +Most scripts work unchanged. Update pnpm-specific patterns: + +```json +{ + "scripts": { + // npm: recursive scripts + "build:all": "npm run build --workspaces", + // pnpm: use -r flag + "build:all": "pnpm -r run build", + + // npm: run in specific workspace + "dev:app": "npm run dev -w packages/app", + // pnpm: use --filter + "dev:app": "pnpm --filter @myorg/app run dev" + } +} +``` + +## CI/CD Migration + +Update CI configuration: + +```yaml +# Before (npm) +- run: npm ci + +# After (pnpm) +- uses: pnpm/action-setup@v4 +- run: pnpm install --frozen-lockfile +``` + +Add to `package.json` for Corepack: +```json +{ + "packageManager": "pnpm@9.0.0" +} +``` + +## Gradual Migration + +For large projects, migrate gradually: + +1. **Start with CI**: Use pnpm in CI, keep npm/yarn locally +2. **Add pnpm-lock.yaml**: Run `pnpm import` to create lockfile +3. **Test thoroughly**: Ensure builds work with pnpm +4. **Update documentation**: Update README, CONTRIBUTING +5. **Remove old files**: Delete old lockfiles after team adoption + +## Rollback Plan + +If migration causes issues: + +```bash +# Remove pnpm files +rm -rf node_modules pnpm-lock.yaml pnpm-workspace.yaml + +# Restore npm +npm install + +# Or restore Yarn +yarn install +``` + +Keep old lockfile in git history for easy rollback. + + diff --git a/.agents/skills/pnpm/references/best-practices-performance.md b/.agents/skills/pnpm/references/best-practices-performance.md new file mode 100644 index 000000000..36524bbd1 --- /dev/null +++ b/.agents/skills/pnpm/references/best-practices-performance.md @@ -0,0 +1,284 @@ +--- +name: pnpm-performance-optimization +description: Tips and tricks for faster installs and better performance +--- + +# pnpm Performance Optimization + +pnpm is fast by default, but these optimizations can make it even faster. + +## Install Optimizations + +### Use Frozen Lockfile + +Skip resolution when lockfile exists: + +```bash +pnpm install --frozen-lockfile +``` + +This is faster because pnpm skips the resolution phase entirely. + +### Prefer Offline Mode + +Use cached packages when available: + +```bash +pnpm install --prefer-offline +``` + +Or configure globally: +```ini +# .npmrc +prefer-offline=true +``` + +### Skip Optional Dependencies + +If you don't need optional deps: + +```bash +pnpm install --no-optional +``` + +### Skip Scripts + +For CI or when scripts aren't needed: + +```bash +pnpm install --ignore-scripts +``` + +**Caution:** Some packages require postinstall scripts to work correctly. + +### Only Build Specific Dependencies + +Only run build scripts for specific packages: + +```ini +# .npmrc +onlyBuiltDependencies[]=esbuild +onlyBuiltDependencies[]=sharp +onlyBuiltDependencies[]=@swc/core +``` + +Or skip builds entirely for deps that don't need them: + +```json +{ + "pnpm": { + "neverBuiltDependencies": ["fsevents", "cpu-features"] + } +} +``` + +## Store Optimizations + +### Side Effects Cache + +Cache native module build results: + +```ini +# .npmrc +side-effects-cache=true +``` + +This caches the results of postinstall scripts, speeding up subsequent installs. + +### Shared Store + +Use a single store for all projects (default behavior): + +```ini +# .npmrc +store-dir=~/.pnpm-store +``` + +Benefits: +- Packages downloaded once for all projects +- Hard links save disk space +- Faster installs from cache + +### Store Maintenance + +Periodically clean unused packages: + +```bash +# Remove unreferenced packages +pnpm store prune + +# Check store integrity +pnpm store status +``` + +## Workspace Optimizations + +### Parallel Execution + +Run workspace scripts in parallel: + +```bash +pnpm -r --parallel run build +``` + +Control concurrency: +```ini +# .npmrc +workspace-concurrency=8 +``` + +### Stream Output + +See output in real-time: + +```bash +pnpm -r --stream run build +``` + +### Filter to Changed Packages + +Only build what changed: + +```bash +# Build packages changed since main branch +pnpm --filter "...[origin/main]" run build +``` + +### Topological Order + +Build dependencies before dependents: + +```bash +pnpm -r run build +# Automatically runs in topological order +``` + +For explicit sequential builds: +```bash +pnpm -r --workspace-concurrency=1 run build +``` + +## Network Optimizations + +### Configure Registry + +Use closest/fastest registry: + +```ini +# .npmrc +registry=https://registry.npmmirror.com/ +``` + +### HTTP Settings + +Tune network settings: + +```ini +# .npmrc +fetch-retries=3 +fetch-retry-mintimeout=10000 +fetch-retry-maxtimeout=60000 +network-concurrency=16 +``` + +### Proxy Configuration + +```ini +# .npmrc +proxy=http://proxy.company.com:8080 +https-proxy=http://proxy.company.com:8080 +``` + +## Lockfile Optimization + +### Single Lockfile (Monorepos) + +Use shared lockfile for all packages (default): + +```ini +# .npmrc +shared-workspace-lockfile=true +``` + +Benefits: +- Single source of truth +- Faster resolution +- Consistent versions across workspace + +### Lockfile-only Mode + +Only update lockfile without installing: + +```bash +pnpm install --lockfile-only +``` + +## Benchmarking + +### Compare Install Times + +```bash +# Clean install +rm -rf node_modules pnpm-lock.yaml +time pnpm install + +# Cached install (with lockfile) +rm -rf node_modules +time pnpm install --frozen-lockfile + +# With store cache +time pnpm install --frozen-lockfile --prefer-offline +``` + +### Profile Resolution + +Debug slow installs: + +```bash +# Verbose logging +pnpm install --reporter=append-only + +# Debug mode +DEBUG=pnpm:* pnpm install +``` + +## Configuration Summary + +Optimized `.npmrc` for performance: + +```ini +# Install behavior +prefer-offline=true +auto-install-peers=true + +# Build optimization +side-effects-cache=true +# Only build what's necessary +onlyBuiltDependencies[]=esbuild +onlyBuiltDependencies[]=@swc/core + +# Network +fetch-retries=3 +network-concurrency=16 + +# Workspace +workspace-concurrency=4 +``` + +## Quick Reference + +| Scenario | Command/Setting | +|----------|-----------------| +| CI installs | `pnpm install --frozen-lockfile` | +| Offline development | `--prefer-offline` | +| Skip native builds | `neverBuiltDependencies` | +| Parallel workspace | `pnpm -r --parallel run build` | +| Build changed only | `pnpm --filter "...[origin/main]" build` | +| Clean store | `pnpm store prune` | + + diff --git a/.agents/skills/pnpm/references/core-cli.md b/.agents/skills/pnpm/references/core-cli.md new file mode 100644 index 000000000..0327d309b --- /dev/null +++ b/.agents/skills/pnpm/references/core-cli.md @@ -0,0 +1,229 @@ +--- +name: pnpm-cli-commands +description: Essential pnpm commands for package management, running scripts, and workspace operations +--- + +# pnpm CLI Commands + +pnpm provides a comprehensive CLI for package management with commands similar to npm/yarn but with unique features. + +## Installation Commands + +### Install all dependencies +```bash +pnpm install +# or +pnpm i +``` + +### Add a dependency +```bash +# Production dependency +pnpm add + +# Dev dependency +pnpm add -D +pnpm add --save-dev + +# Optional dependency +pnpm add -O + +# Global package +pnpm add -g + +# Specific version +pnpm add @ +pnpm add @next +pnpm add @^1.0.0 +``` + +### Remove a dependency +```bash +pnpm remove +pnpm rm +pnpm uninstall +pnpm un +``` + +### Update dependencies +```bash +# Update all +pnpm update +pnpm up + +# Update specific package +pnpm update + +# Update to latest (ignore semver) +pnpm update --latest +pnpm up -L + +# Interactive update +pnpm update --interactive +pnpm up -i +``` + +## Script Commands + +### Run scripts +```bash +pnpm run + + + + +``` + +## Common Animation Patterns + +### Pulse on Success + +```vue + + + + + +``` + +### Highlight on Change + +```vue + + + + + +``` + +### Bounce Attention + +```vue + + + + + +``` + +## Using animationend Event + +Instead of `setTimeout`, use the `animationend` event for cleaner code: + +```vue + + + +``` + +## Composable for Reusable Animations + +```javascript +// composables/useAnimation.js +import { ref } from 'vue' + +export function useAnimation(duration = 500) { + const isAnimating = ref(false) + + function trigger() { + isAnimating.value = true + setTimeout(() => { + isAnimating.value = false + }, duration) + } + + return { + isAnimating, + trigger + } +} +``` + +```vue + + + +``` diff --git a/.agents/skills/vue-best-practices/references/animation-state-driven-technique.md b/.agents/skills/vue-best-practices/references/animation-state-driven-technique.md new file mode 100644 index 000000000..fd2b31409 --- /dev/null +++ b/.agents/skills/vue-best-practices/references/animation-state-driven-technique.md @@ -0,0 +1,296 @@ +--- +title: State-driven Animations with CSS Transitions and Style Bindings +impact: LOW +impactDescription: Combining Vue's reactive style bindings with CSS transitions creates smooth, interactive animations +type: best-practice +tags: [vue3, animation, css, transition, style-binding, state, interactive] +--- + +# State-driven Animations with CSS Transitions and Style Bindings + +**Impact: LOW** - For responsive, interactive animations that react to user input or state changes, combine Vue's dynamic style bindings with CSS transitions. This creates smooth animations that interpolate values in real-time based on state. + +## Task List + +- Use `:style` binding for dynamic properties that change frequently +- Add CSS `transition` property to smoothly animate between values +- Consider using `transform` and `opacity` for GPU-accelerated animations +- For complex value interpolation, use watchers with animation libraries + +## Basic Pattern + +```vue + + + + + +``` + +## Common Use Cases + +### Following Mouse Position + +```vue + + + + + +``` + +### Progress Animation + +```vue + + + + + +``` + +### Scroll-based Animation + +```vue + + + + + +``` + +### Color Theme Transition + +```vue + + + + + +``` + +## Advanced: Numerical Tweening with Watchers + +For smooth number animations (counters, stats), use watchers with animation libraries: + +```vue + + + +``` + +## Performance Considerations + +```vue + +``` diff --git a/.agents/skills/vue-best-practices/references/component-async.md b/.agents/skills/vue-best-practices/references/component-async.md new file mode 100644 index 000000000..745a26561 --- /dev/null +++ b/.agents/skills/vue-best-practices/references/component-async.md @@ -0,0 +1,99 @@ +--- +title: Async Component Best Practices +impact: MEDIUM +impactDescription: Poor async component strategy can delay interactivity in SSR apps and create loading UI flicker +type: best-practice +tags: [vue3, async-components, ssr, hydration, performance, ux] +--- + +# Async Component Best Practices + +**Impact: MEDIUM** - Async components should reduce JavaScript cost without degrading perceived performance. Focus on hydration timing in SSR and stable loading UX. + +## Task List + +- Use lazy hydration strategies for non-critical SSR component trees +- Import only the hydration helpers you actually use +- Keep `loadingComponent` delay near the default `200ms` unless real UX data suggests otherwise +- Configure `delay` and `timeout` together for predictable loading behavior + +## Use Lazy Hydration Strategies in SSR + +In Vue 3.5+, async components can delay hydration until idle time, visibility, media query match, or user interaction. + +**BAD:** +```vue + +``` + +**GOOD:** +```vue + +``` + +## Prevent Loading Spinner Flicker + +Avoid showing loading UI immediately for components that usually resolve quickly. + +**BAD:** +```vue + +``` + +**GOOD:** +```vue + +``` + +## Delay Guidelines + +| Scenario | Recommended Delay | +|----------|-------------------| +| Small component, fast network | `200ms` | +| Known heavy component | `100ms` | +| Background or non-critical UI | `300-500ms` | diff --git a/.agents/skills/vue-best-practices/references/component-data-flow.md b/.agents/skills/vue-best-practices/references/component-data-flow.md new file mode 100644 index 000000000..6af56d6fc --- /dev/null +++ b/.agents/skills/vue-best-practices/references/component-data-flow.md @@ -0,0 +1,314 @@ +--- +title: Component Data Flow Best Practices +impact: HIGH +impactDescription: Clear data flow between components prevents state bugs, stale UI, and brittle coupling +type: best-practice +tags: [vue3, props, emits, v-model, provide-inject, data-flow, typescript] +--- + +# Component Data Flow Best Practices + +**Impact: HIGH** - Vue components stay reliable when data flow is explicit: props go down, events go up, `v-model` handles two-way bindings, and provide/inject supports cross-tree dependencies. Blurring these boundaries leads to stale state, hidden coupling, and hard-to-debug UI. + +The main principle of data flow in Vue.js is **Props Down / Events Up**. This is the most maintainable default, and one-way flow scales well. + +## Task List + +- Treat props as read-only inputs +- Use props/emit for component communication; reserve refs for imperative actions +- When refs are required for imperative APIs, type them with template refs +- Emit events instead of mutating parent state directly +- Use `defineModel` for v-model in modern Vue (3.4+) +- Handle v-model modifiers deliberately in child components +- Use symbols for provide/inject keys to avoid props drilling (over ~3 layers) +- Keep mutations in the provider or expose explicit actions +- In TypeScript projects, prefer type-based `defineProps`, `defineEmits`, and `InjectionKey` + +## Props: One-Way Data Down + +Props are inputs. Do not mutate them in the child. + +**BAD:** +```vue + +``` + +**GOOD:** + +If state needs to change, emit an event, use `v-model` or create a local copy. + +## Prefer props/emit over component refs + +**BAD:** +```vue + + + +``` + +**GOOD:** +```vue + + + +``` + +## Type component refs when imperative access is required + +Prefer props/emits by default. When a parent must call an exposed child method, type the ref explicitly and expose only the intended API from the child with `defineExpose`. + +**BAD:** +```vue + + + +``` + +**GOOD:** +```vue + + +``` + +```vue + + + + +``` + +## Emits: Explicit Events Up + +Component events do not bubble. If a parent needs to know about an event, re-emit it explicitly. + +**BAD:** +```vue + + +``` + +**GOOD:** +```vue + + + + +``` + +**Event naming:** use kebab-case in templates and camelCase in script: +```vue + + + +``` + +## `v-model`: Predictable Two-Way Bindings + +Use `defineModel` by default for component bindings and emit updates on input. Only use the `modelValue` + `update:modelValue` pattern if you are on Vue < 3.4. + +**BAD:** +```vue + + + +``` + +**GOOD (Vue 3.4+):** +```vue + + + +``` + +**GOOD (Vue < 3.4):** +```vue + + + +``` + +If you need the updated value immediately after a change, use the input event value or `nextTick` in the parent. + +## Provide/Inject: Shared Context Without Prop Drilling + +Use provide/inject for cross-tree state, but keep mutations centralized in the provider and expose explicit actions. + +**BAD:** +```vue +// Provider.vue +provide('theme', reactive({ dark: false })) + +// Consumer.vue +const theme = inject('theme') +// Mutating shared state from any depth becomes hard to track +theme.dark = true +``` + +**GOOD:** +```vue +// Provider.vue +const theme = reactive({ dark: false }) +const toggleTheme = () => { theme.dark = !theme.dark } + +provide(themeKey, readonly(theme)) +provide(themeActionsKey, { toggleTheme }) + +// Consumer.vue +const theme = inject(themeKey) +const { toggleTheme } = inject(themeActionsKey) +``` + +Use symbols for keys to avoid collisions in large apps: +```ts +export const themeKey = Symbol('theme') +export const themeActionsKey = Symbol('theme-actions') +``` + +## Use TypeScript Contracts for Public Component APIs + +In TypeScript projects, type component boundaries directly with `defineProps`, `defineEmits`, and `InjectionKey` so invalid payloads and mismatched injections fail at compile time. + +**BAD:** +```vue + +``` + +**GOOD:** +```vue + +``` diff --git a/.agents/skills/vue-best-practices/references/component-fallthrough-attrs.md b/.agents/skills/vue-best-practices/references/component-fallthrough-attrs.md new file mode 100644 index 000000000..2bd4953bf --- /dev/null +++ b/.agents/skills/vue-best-practices/references/component-fallthrough-attrs.md @@ -0,0 +1,174 @@ +--- +title: Component Fallthrough Attributes Best Practices +impact: MEDIUM +impactDescription: Incorrect $attrs access and reactivity assumptions can cause undefined values and watchers that never run +type: best-practice +tags: [vue3, attrs, fallthrough-attributes, composition-api, reactivity] +--- + +# Component Fallthrough Attributes Best Practices + +**Impact: MEDIUM** - Fallthrough attributes are straightforward once you follow Vue's conventions: hyphenated names use bracket notation, listener keys are camelCase `onX`, and `useAttrs()` is current-but-not-reactive. + +## Task List + +- Access hyphenated attribute names with bracket notation (for example `attrs['data-testid']`) +- Access event listeners with camelCase `onX` keys (for example `attrs.onClick`) +- Do not `watch()` values returned from `useAttrs()`; those watchers do not trigger on attr changes +- Use `onUpdated()` for attr-driven side effects +- Promote frequently observed attrs to props when reactive observation is required + +## Access Attribute and Listener Keys Correctly + +Hyphenated attribute names preserve their original casing in JavaScript, so dot notation does not work for keys that include `-`. + +**BAD:** +```vue + +``` + +**GOOD:** +```vue + +``` + +### Naming Reference + +| Parent Usage | Access in `attrs` | +|--------------|-------------------| +| `class="foo"` | `attrs.class` | +| `data-id="123"` | `attrs['data-id']` | +| `aria-label="..."` | `attrs['aria-label']` | +| `foo-bar="baz"` | `attrs['foo-bar']` | +| `@click="fn"` | `attrs.onClick` | +| `@custom-event="fn"` | `attrs.onCustomEvent` | +| `@update:modelValue="fn"` | `attrs['onUpdate:modelValue']` | + +## `useAttrs()` Is Not Reactive + +`useAttrs()` always reflects the latest values, but it is intentionally not reactive for watcher tracking. + +**BAD:** +```vue + +``` + +**GOOD:** +```vue + +``` + +**GOOD:** +```vue + +``` + +## Common Patterns + +### Check for optional attrs safely + +```vue + +``` + +### Forward listeners after internal logic + +```vue + + + +``` + +## TypeScript Notes + +`useAttrs()` is typed as `Record`, so cast individual keys when needed. + +```vue + +``` diff --git a/.agents/skills/vue-best-practices/references/component-keep-alive.md b/.agents/skills/vue-best-practices/references/component-keep-alive.md new file mode 100644 index 000000000..b73db205e --- /dev/null +++ b/.agents/skills/vue-best-practices/references/component-keep-alive.md @@ -0,0 +1,137 @@ +--- +title: KeepAlive Component Best Practices +impact: HIGH +impactDescription: KeepAlive caches component instances; misuse causes stale data, memory growth, or unexpected lifecycle behavior +type: best-practice +tags: [vue3, keepalive, cache, performance, router, dynamic-components] +--- + +# KeepAlive Component Best Practices + +**Impact: HIGH** - `` caches component instances instead of destroying them. Use it to preserve state across switches, but manage cache size and freshness explicitly to avoid memory growth or stale UI. + +## Task List + +- Use KeepAlive only where state preservation improves UX +- Set a reasonable `max` to cap cache size +- Declare component names for include/exclude matching +- Use `onActivated`/`onDeactivated` for cache-aware logic +- Decide how and when cached views refresh their data +- Avoid caching memory-heavy or security-sensitive views + +## When to Use KeepAlive + +Use KeepAlive when switching between views where state should persist (tabs, multi-step forms, dashboards). Avoid it when each visit should start fresh. + +**BAD:** +```vue + +``` + +**GOOD:** +```vue + +``` + +## When NOT to Use KeepAlive + +- Search or filter pages where users expect fresh results +- Memory-heavy components (maps, large tables, media players) +- Sensitive flows where data must be cleared on exit +- Components with heavy background activity you cannot pause + +## Limit and Control the Cache + +Always cap cache size with `max` and restrict caching to specific components when possible. + +```vue + +``` + +## Ensure Component Names Match include/exclude + +`include` and `exclude` match the component `name` option. Explicitly set names for reliable caching. + +```vue + + +``` + +```vue + +``` + +## Cache Invalidation Strategies + +Vue 3 has no direct API to remove a specific cached instance. Use keys or dynamic include/exclude to force refreshes. + +```vue + + + +``` + +## Lifecycle Hooks for Cached Components + +Cached components are not destroyed on switch. Use activation hooks for refresh and cleanup. + +```vue + +``` + +## Router Caching and Freshness + +Decide whether navigation should show cached state or a fresh view. A common pattern is to key by route when params change. + +```vue + +``` + +If you want cache reuse but fresh data, refresh in `onActivated` and compare query/params before fetching. diff --git a/.agents/skills/vue-best-practices/references/component-slots.md b/.agents/skills/vue-best-practices/references/component-slots.md new file mode 100644 index 000000000..61bb159c8 --- /dev/null +++ b/.agents/skills/vue-best-practices/references/component-slots.md @@ -0,0 +1,216 @@ +--- +title: Component Slots Best Practices +impact: MEDIUM +impactDescription: Poor slot API design causes empty DOM wrappers, weak TypeScript safety, brittle defaults, and unnecessary component overhead +type: best-practice +tags: [vue3, slots, components, typescript, composables] +--- + +# Component Slots Best Practices + +**Impact: MEDIUM** - Slots are a core component API surface in Vue. Structure them intentionally so templates stay predictable, typed, and performant. + +## Task List + +- Use shorthand syntax for named slots (`#` instead of `v-slot:`) +- Render optional slot wrapper elements only when slot content exists (`$slots` checks) +- Type scoped slot contracts with `defineSlots` in TypeScript components +- Provide fallback content for optional slots +- Prefer composables over renderless components for pure logic reuse + +## Shorthand syntax for named slots + +**BAD:** +```vue + + + +``` + +**GOOD:** +```vue + + + +``` + +## Conditionally Render Optional Slot Wrappers + +Use `$slots` checks when wrapper elements add spacing, borders, or layout constraints. + +**BAD:** +```vue + + +``` + +**GOOD:** +```vue + + +``` + +## Type Scoped Slot Props with defineSlots + +In ` + + +``` + +**GOOD:** +```vue + + + + +``` + +## Provide Slot Fallback Content + +Fallback content makes components resilient when parents omit optional slots. + +**BAD:** +```vue + + +``` + +**GOOD:** +```vue + + +``` + +## Prefer Composables for Pure Logic Reuse + +Renderless components are still useful for slot-driven composition, but composables are usually cleaner for logic-only reuse. + +**BAD:** +```vue + + + + +``` + +**GOOD:** +```ts +// composables/useMouse.ts +import { onMounted, onUnmounted, ref } from 'vue' + +export function useMouse() { + const x = ref(0) + const y = ref(0) + + function onMove(event: MouseEvent) { + x.value = event.pageX + y.value = event.pageY + } + + onMounted(() => window.addEventListener('mousemove', onMove)) + onUnmounted(() => window.removeEventListener('mousemove', onMove)) + + return { x, y } +} +``` + +```vue + + + + +``` diff --git a/.agents/skills/vue-best-practices/references/component-suspense.md b/.agents/skills/vue-best-practices/references/component-suspense.md new file mode 100644 index 000000000..82fa0dd37 --- /dev/null +++ b/.agents/skills/vue-best-practices/references/component-suspense.md @@ -0,0 +1,238 @@ +--- +title: Suspense Component Best Practices +impact: MEDIUM +impactDescription: Suspense coordinates async dependencies with fallback UI; misconfiguration leads to missing loading states or confusing UX +type: best-practice +tags: [vue3, suspense, async-components, async-setup, loading, fallback, router, transition, keepalive] +--- + +# Suspense Component Best Practices + +**Impact: MEDIUM** - `` coordinates async dependencies (async components or async setup) and renders a fallback while they resolve. Misconfiguration leads to missing loading states, empty renders, or subtle UX bugs. + +## Task List + +- Wrap default and fallback slot content in a single root node +- Use `timeout` when you need the fallback to appear on reverts +- Force root replacement with `:key` when you need Suspense to re-trigger +- Add `suspensible` to nested Suspense boundaries (Vue 3.3+) +- Use `@pending`, `@resolve`, and `@fallback` for programmatic loading state +- Nest `RouterView` -> `Transition` -> `KeepAlive` -> `Suspense` in that order +- Keep Suspense usage centralized and documented in production + +## Single Root in Default and Fallback Slots + +Suspense tracks a single immediate child in both slots. Wrap multiple elements in a single element or component. + +**BAD:** +```vue + +``` + +**GOOD:** +```vue + +``` + +## Fallback Timing on Reverts (`timeout`) + +When Suspense is already resolved and new async work starts, the previous content remains visible until the timeout elapses. Use `timeout="0"` for immediate fallback or a short delay to avoid flicker. + +**BAD:** +```vue + +``` + +**GOOD:** +```vue + +``` + +## Pending State Only Re-triggers on Root Replacement + +Once resolved, Suspense only re-enters pending when the root node of the default slot changes. If async work happens deeper in the tree, no fallback appears. + +**BAD:** +```vue + +``` + +**GOOD:** +```vue + +``` + +## Use `suspensible` for Nested Suspense (Vue 3.3+) + +Nested Suspense boundaries need `suspensible` on the inner boundary so the parent can coordinate loading state. Without it, inner async content may render empty nodes until resolved. + +**BAD:** +```vue + +``` + +**GOOD:** +```vue + +``` + +## Track Loading with Suspense Events + +Use `@pending`, `@resolve`, and `@fallback` for analytics, global loading indicators, or coordinating UI outside the Suspense boundary. + +```vue + + + +``` + +## Recommended Nesting with RouterView, Transition, KeepAlive + +When combining these components, the nesting order should be `RouterView` -> `Transition` -> `KeepAlive` -> `Suspense` so each wrapper works correctly. + +**BAD:** +```vue + +``` + +**GOOD:** +```vue + +``` + +## Treat Suspense Cautiously in Production + +In production code, keep Suspense boundaries minimal, document where they are used, and have a fallback loading strategy if you ever need to replace or refactor them. diff --git a/.agents/skills/vue-best-practices/references/component-teleport.md b/.agents/skills/vue-best-practices/references/component-teleport.md new file mode 100644 index 000000000..8b8167c09 --- /dev/null +++ b/.agents/skills/vue-best-practices/references/component-teleport.md @@ -0,0 +1,118 @@ +--- +title: Teleport Component Best Practices +impact: MEDIUM +impactDescription: Teleport renders content outside the component's DOM position, which is essential for overlays but affects styling and layout +type: best-practice +tags: [vue3, teleport, modal, overlay, positioning, responsive] +--- + +# Teleport Component Best Practices + +**Impact: MEDIUM** - `` renders part of a component's template in a different place in the DOM while preserving the Vue component hierarchy. Use it for overlays (modals, toasts, tooltips) or any UI that must escape stacking contexts, overflow, or fixed positioning constraints. + +## Task List + +- Teleport overlays to `body` or a dedicated container outside the app root +- Keep a shared target for similar UI (`#modals`, `#notifications`) and control layering with order or z-index +- Use `:disabled` for responsive layouts that should render inline on small screens +- Remember props, emits, and provide/inject still work through teleport +- Avoid relying on parent stacking contexts or transforms for teleported UI + +## Teleport Overlays Out of Transformed Containers + +When an ancestor has `transform`, `filter`, or `perspective`, fixed-position overlays can behave like they are locally positioned. Teleport escapes that context. + +**BAD:** +```vue + + + +``` + +**GOOD:** +```vue + +``` + +## Responsive Layouts with `disabled` + +Use `:disabled` to render inline on mobile and teleport on larger screens: + +```vue + + + +``` + +## Logical Hierarchy Is Preserved + +Teleport changes DOM position, not the Vue component tree. Props, emits, slots, and provide/inject still work: + +```vue + +``` + +## Multiple Teleports to the Same Target + +Teleports to the same target append in declaration order: + +```vue + +``` + +Use a shared container to keep stacking predictable, and apply z-index only when you need explicit layering. diff --git a/.agents/skills/vue-best-practices/references/component-transition-group.md b/.agents/skills/vue-best-practices/references/component-transition-group.md new file mode 100644 index 000000000..b6c0cfc4c --- /dev/null +++ b/.agents/skills/vue-best-practices/references/component-transition-group.md @@ -0,0 +1,130 @@ +--- +title: TransitionGroup Component Best Practices +impact: MEDIUM +impactDescription: TransitionGroup animates list items; missing keys or misuse leads to broken list transitions +type: best-practice +tags: [vue3, transition-group, animation, lists, keys] +--- + +# TransitionGroup Component Best Practices + +**Impact: MEDIUM** - `` animates lists of items entering, leaving, and moving. Use it for `v-for` lists or dynamic collections where individual items change over time. + +## Task List + +- Use `` only for lists and repeated items +- Provide unique, stable keys for every direct child +- Use `tag` when you need semantic or layout wrappers +- Avoid the `mode` prop (not supported) +- Use JavaScript hooks for staggered effects + +## Use TransitionGroup for Lists + +`` is designed for list items. Use `tag` to control the wrapper element when needed. + +**BAD:** +```vue + +``` + +**GOOD:** +```vue + +``` + +## Always Provide Stable Keys + +Keys are required. Without stable keys, Vue cannot track item positions and animations break. + +**BAD:** +```vue + +``` + +**GOOD:** +```vue + +``` + +## Do Not Use `mode` on TransitionGroup + +`mode` is only for `` because it swaps a single element. Use `` if you need in/out sequencing. + +**BAD:** +```vue + +``` + +**GOOD:** +```vue + +``` + +## Stagger List Animations with Data Attributes + +For cascading list animations, pass the index to JavaScript hooks and compute delay per item. + +```vue + + + +``` diff --git a/.agents/skills/vue-best-practices/references/component-transition.md b/.agents/skills/vue-best-practices/references/component-transition.md new file mode 100644 index 000000000..b50bcd176 --- /dev/null +++ b/.agents/skills/vue-best-practices/references/component-transition.md @@ -0,0 +1,133 @@ +--- +title: Transition Component Best Practices +impact: MEDIUM +impactDescription: Transition animates a single element or component; incorrect structure or keys prevent animations +type: best-practice +tags: [vue3, transition, animation, performance, keys] +--- + +# Transition Component Best Practices + +**Impact: MEDIUM** - `` animates entering/leaving of a single element or component. It is ideal for toggling UI states, swapping views, or animating one component at a time. + +## Task List + +- Wrap a single element or component inside `` +- Provide a `key` when switching between same element types +- Use `mode="out-in"` when you need sequential swaps +- Prefer `transform` and `opacity` for smooth animations + +## Use Transition for a Single Root Element + +`` only supports one direct child. Wrap multiple nodes in a single element or component. + +**BAD:** +```vue + +``` + +**GOOD:** +```vue + +``` + +## Force Transitions Between Same Element Types + +Vue reuses the same DOM element when the tag type does not change. Add `key` so Vue treats it as a new element and triggers enter/leave. + +**BAD:** +```vue + +``` + +**GOOD:** +```vue + +``` + +## Use `mode` to Avoid Overlap During Swaps + +When swapping components or views, use `mode="out-in"` to prevent both from being visible at the same time. + +**BAD:** +```vue + +``` + +**GOOD:** +```vue + +``` + +## Animate `transform` and `opacity` for Performance + +Avoid layout-triggering properties such as `height`, `margin`, or `top`. Use `transform` and `opacity` for smooth, GPU-friendly transitions. + +**BAD:** +```css +.slide-enter-active, +.slide-leave-active { + transition: height 0.3s ease; +} + +.slide-enter-from, +.slide-leave-to { + height: 0; +} +``` + +**GOOD:** +```css +.slide-enter-active, +.slide-leave-active { + transition: transform 0.3s ease, opacity 0.3s ease; +} + +.slide-enter-from { + transform: translateX(-12px); + opacity: 0; +} + +.slide-leave-to { + transform: translateX(12px); + opacity: 0; +} +``` diff --git a/.agents/skills/vue-best-practices/references/composables.md b/.agents/skills/vue-best-practices/references/composables.md new file mode 100644 index 000000000..b5f10c892 --- /dev/null +++ b/.agents/skills/vue-best-practices/references/composables.md @@ -0,0 +1,296 @@ +--- +title: Composable Organization Patterns +impact: MEDIUM +impactDescription: Well-structured composables improve maintainability, reusability, and update performance +type: best-practice +tags: [vue3, composables, composition-api, code-organization, api-design, readonly, utilities] +--- + +# Composable Organization Patterns + +**Impact: MEDIUM** - Treat composables as reusable, stateful building blocks and keep their code organized by feature concern. This keeps large components maintainable and prevents hard-to-debug mutation and API design issues. + +## Task List + +- Compose complex behavior from small, focused composables +- Use options objects for composables with multiple optional parameters +- Return readonly state when updates must flow through explicit actions +- Keep pure utility functions as plain utilities, not composables +- Organize composable and component code by feature concern, and extract composables when components grow + +## Compose Composables from Smaller Primitives + +**BAD:** +```vue + +``` + +**GOOD:** +```javascript +// composables/useEventListener.js +import { onMounted, onUnmounted, toValue } from 'vue' + +export function useEventListener(target, event, callback) { + onMounted(() => toValue(target).addEventListener(event, callback)) + onUnmounted(() => toValue(target).removeEventListener(event, callback)) +} +``` + +```javascript +// composables/useMouse.js +import { ref } from 'vue' + +import { useEventListener } from './useEventListener' + +export function useMouse() { + const x = ref(0) + const y = ref(0) + + useEventListener(window, 'mousemove', (e) => { + x.value = e.pageX + y.value = e.pageY + }) + + return { x, y } +} +``` + +```javascript +// composables/useMouseInElement.js +import { computed } from 'vue' + +import { useMouse } from './useMouse' + +export function useMouseInElement(elementRef) { + const { x, y } = useMouse() + + const isOutside = computed(() => { + if (!elementRef.value) + return true + const rect = elementRef.value.getBoundingClientRect() + return x.value < rect.left || x.value > rect.right + || y.value < rect.top || y.value > rect.bottom + }) + + return { x, y, isOutside } +} +``` + +## Use Options Object Pattern for Composable Parameters + +**BAD:** +```javascript +export function useFetch(url, method, headers, timeout, retries, immediate) { + // hard to read and easy to misorder +} + +useFetch('/api/users', 'GET', null, 5000, 3, true) +``` + +**GOOD:** +```javascript +export function useFetch(url, options = {}) { + const { + method = 'GET', + headers = {}, + timeout = 30000, + retries = 0, + immediate = true + } = options + + // implementation + return { method, headers, timeout, retries, immediate } +} + +useFetch('/api/users', { + method: 'POST', + timeout: 5000, + retries: 3 +}) +``` + +```typescript +interface UseCounterOptions { + initial?: number + min?: number + max?: number + step?: number +} + +export function useCounter(options: UseCounterOptions = {}) { + const { initial = 0, min = -Infinity, max = Infinity, step = 1 } = options + // implementation +} +``` + +## Return Readonly State with Explicit Actions + +**BAD:** +```javascript +export function useCart() { + const items = ref([]) + const total = computed(() => items.value.reduce((sum, item) => sum + item.price, 0)) + return { items, total } // any consumer can mutate directly +} + +const { items } = useCart() +items.value.push({ id: 1, price: 10 }) +``` + +**GOOD:** +```javascript +import { computed, readonly, ref } from 'vue' + +export function useCart() { + const _items = ref([]) + + const total = computed(() => + _items.value.reduce((sum, item) => sum + item.price * item.quantity, 0) + ) + + function addItem(product, quantity = 1) { + const existing = _items.value.find(item => item.id === product.id) + if (existing) { + existing.quantity += quantity + return + } + _items.value.push({ ...product, quantity }) + } + + function removeItem(productId) { + _items.value = _items.value.filter(item => item.id !== productId) + } + + return { + items: readonly(_items), + total, + addItem, + removeItem + } +} +``` + +## Keep Utilities as Utilities + +**BAD:** +```javascript +export function useFormatters() { + const formatDate = date => new Intl.DateTimeFormat('en-US').format(date) + const formatCurrency = amount => + new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(amount) + return { formatDate, formatCurrency } +} + +const { formatDate } = useFormatters() +``` + +**GOOD:** +```javascript +// utils/formatters.js +export function formatDate(date) { + return new Intl.DateTimeFormat('en-US').format(date) +} + +export function formatCurrency(amount) { + return new Intl.NumberFormat('en-US', { + style: 'currency', + currency: 'USD' + }).format(amount) +} +``` + +```javascript +// composables/useInvoiceSummary.js +import { computed } from 'vue' + +import { formatCurrency } from '@/utils/formatters' + +export function useInvoiceSummary(invoiceRef) { + const totalLabel = computed(() => formatCurrency(invoiceRef.value.total)) + return { totalLabel } +} +``` + +## Organize Composable and Component Code by Feature Concern + +**BAD:** +```vue + +``` + +**GOOD:** +```vue + +``` + +```javascript +// composables/useItems.js +import { onMounted, ref } from 'vue' + +export function useItems() { + const items = ref([]) + const loading = ref(false) + + async function fetchItems() { + loading.value = true + try { + items.value = await api.getItems() + } + finally { + loading.value = false + } + } + + onMounted(fetchItems) + return { items, loading, fetchItems } +} +``` diff --git a/.agents/skills/vue-best-practices/references/directives.md b/.agents/skills/vue-best-practices/references/directives.md new file mode 100644 index 000000000..f11bcc2c2 --- /dev/null +++ b/.agents/skills/vue-best-practices/references/directives.md @@ -0,0 +1,162 @@ +--- +title: Directive Best Practices +impact: MEDIUM +impactDescription: Custom directives are powerful but easy to misuse; following patterns prevents leaks, invalid usage, and unclear abstractions +type: best-practice +tags: [vue3, directives, custom-directives, composition, typescript] +--- + +# Directive Best Practices + +**Impact: MEDIUM** - Directives are for low-level DOM access. Use them sparingly, keep them side-effect safe, and prefer components or composables when you need stateful or reusable UI behavior. + +## Task List + +- Use directives only when you need direct DOM access +- Do not mutate directive arguments or binding objects +- Clean up timers, listeners, and observers in `unmounted` +- Register directives in ` + + +``` + +## Clean Up Side Effects in `unmounted` + +Any timers, listeners, or observers must be removed to avoid leaks. + +```ts +const vResize = { + mounted(el) { + const observer = new ResizeObserver(() => {}) + observer.observe(el) + el._observer = observer + }, + unmounted(el) { + el._observer?.disconnect() + } +} +``` + +## Prefer Function Shorthand for Single-Hook Directives + +If you only need `mounted`/`updated`, use the function form. + +```ts +const vAutofocus = el => el.focus() +``` + +## Use the `v-` Prefix and Script Setup Registration + +```vue + + + +``` + +## Type Custom Directives in TypeScript Projects + +Use `Directive` so `binding.value` is typed, and augment Vue's template types so directives are recognized in SFC templates. + +**BAD:** +```ts +// Untyped directive value and no template type augmentation +export const vHighlight = { + mounted(el, binding) { + el.style.backgroundColor = binding.value + } +} +``` + +**GOOD:** +```ts +import type { Directive } from 'vue' + +type HighlightValue = string + +export const vHighlight = { + mounted(el, binding) { + el.style.backgroundColor = binding.value + } +} satisfies Directive + +declare module 'vue' { + interface ComponentCustomProperties { + vHighlight: typeof vHighlight + } +} +``` + +## Handle SSR with `getSSRProps` + +Directive hooks such as `mounted` and `updated` do not run during SSR. If a directive sets attributes/classes that affect rendered HTML, provide an SSR equivalent via `getSSRProps` to avoid hydration mismatches. + +**BAD:** +```ts +const vTooltip = { + mounted(el, binding) { + el.setAttribute('data-tooltip', binding.value) + el.classList.add('has-tooltip') + } +} +``` + +**GOOD:** +```ts +const vTooltip = { + mounted(el, binding) { + el.setAttribute('data-tooltip', binding.value) + el.classList.add('has-tooltip') + }, + getSSRProps(binding) { + return { + 'data-tooltip': binding.value, + 'class': 'has-tooltip' + } + } +} +``` + +## Prefer Declarative Templates When Possible + +If a standard attribute or binding works, use it instead of a directive. + +## Decide Between Directives and Components + +Use a directive for DOM-level behavior. Use a component when behavior affects structure, state, or rendering. diff --git a/.agents/skills/vue-best-practices/references/perf-avoid-component-abstraction-in-lists.md b/.agents/skills/vue-best-practices/references/perf-avoid-component-abstraction-in-lists.md new file mode 100644 index 000000000..e6d8a891e --- /dev/null +++ b/.agents/skills/vue-best-practices/references/perf-avoid-component-abstraction-in-lists.md @@ -0,0 +1,165 @@ +--- +title: Avoid Excessive Component Abstraction in Large Lists +impact: MEDIUM +impactDescription: Each component instance has memory and render overhead - abstractions multiply this in lists +type: efficiency +tags: [vue3, performance, components, abstraction, lists, optimization] +--- + +# Avoid Excessive Component Abstraction in Large Lists + +**Impact: MEDIUM** - Component instances are more expensive than plain DOM nodes. While abstractions improve code organization, unnecessary nesting creates overhead. In large lists, this overhead multiplies - 100 items with 3 levels of abstraction means 300+ component instances instead of 100. + +Don't avoid abstraction entirely, but be mindful of component depth in frequently-rendered elements like list items. + +## Task List + +- Review list item components for unnecessary wrapper components +- Consider flattening component hierarchies in hot paths +- Use native elements when a component adds no value +- Profile component counts using Vue DevTools +- Focus optimization efforts on the most-rendered components + +**BAD:** +```vue + + + + + + + +``` + +**GOOD:** +```vue + + + + + + + + + +``` + +## When Abstraction Is Still Worth It + +```vue + + + + + + + + + + + + + + + +``` + +## Measuring Component Overhead + +```javascript +// In development, profile component counts +import { getCurrentInstance, onMounted } from 'vue' + +onMounted(() => { + const instance = getCurrentInstance() + let count = 0 + + function countComponents(vnode) { + if (vnode.component) + count++ + if (vnode.children) { + vnode.children.forEach((child) => { + if (child.component || child.children) + countComponents(child) + }) + } + } + + // Use Vue DevTools instead for accurate counts + console.log('Check Vue DevTools Components tab for instance counts') +}) +``` + +## Alternatives to Wrapper Components + +```vue + + + + + +{{ content }} + + + +
+ +
+ + +``` + +## Impact Calculation + +| List Size | Components per Item | Total Instances | Memory Impact | +|-----------|---------------------|-----------------|---------------| +| 100 items | 1 (flat) | 100 | Baseline | +| 100 items | 3 (nested) | 300 | ~3x memory | +| 100 items | 5 (deeply nested) | 500 | ~5x memory | +| 1000 items | 1 (flat) | 1000 | High | +| 1000 items | 5 (deeply nested) | 5000 | Very High | diff --git a/.agents/skills/vue-best-practices/references/perf-v-once-v-memo-directives.md b/.agents/skills/vue-best-practices/references/perf-v-once-v-memo-directives.md new file mode 100644 index 000000000..ae764ab89 --- /dev/null +++ b/.agents/skills/vue-best-practices/references/perf-v-once-v-memo-directives.md @@ -0,0 +1,182 @@ +--- +title: Use v-once and v-memo to Skip Unnecessary Updates +impact: MEDIUM +impactDescription: v-once skips all future updates for static content; v-memo conditionally memoizes subtrees +type: efficiency +tags: [vue3, performance, v-once, v-memo, optimization, directives] +--- + +# Use v-once and v-memo to Skip Unnecessary Updates + +**Impact: MEDIUM** - Vue re-evaluates templates on every reactive change. For content that never changes or changes infrequently, `v-once` and `v-memo` tell Vue to skip updates, reducing render work. + +Use `v-once` for truly static content and `v-memo` for conditionally-static content in lists. + +## Task List + +- Apply `v-once` to elements that use runtime data but never need updating +- Apply `v-memo` to list items that should only update on specific condition changes +- Verify memoized content doesn't need to respond to other state changes +- Profile with Vue DevTools to confirm update skipping + +## v-once: Render Once, Never Update + +**BAD:** +```vue + +``` + +**GOOD:** +```vue + + + +``` + +## v-memo: Conditional Memoization for Lists + +**BAD:** +```vue + +``` + +**GOOD:** +```vue + + + +``` + +## v-memo with Multiple Dependencies + +```vue + + + +``` + +## v-memo with Empty Array = v-once + +```vue + +``` + +## When NOT to Use These Directives + +```vue + +``` + +## Performance Comparison + +| Scenario | Without Directive | With v-once/v-memo | +|----------|-------------------|-------------------| +| Static header, parent re-renders 100x | Re-evaluated 100x | Evaluated 1x | +| 1000 items, selection changes | 1000 items re-render | 2 items re-render | +| Complex child component | Full re-render | Skipped if memoized | + +## Debugging Memoized Components + +```vue + +``` diff --git a/.agents/skills/vue-best-practices/references/perf-virtualize-large-lists.md b/.agents/skills/vue-best-practices/references/perf-virtualize-large-lists.md new file mode 100644 index 000000000..d17422a0b --- /dev/null +++ b/.agents/skills/vue-best-practices/references/perf-virtualize-large-lists.md @@ -0,0 +1,190 @@ +--- +title: Virtualize Large Lists to Avoid DOM Overload +impact: HIGH +impactDescription: Rendering thousands of list items creates excessive DOM nodes, causing slow renders and high memory usage +type: efficiency +tags: [vue3, performance, virtual-list, large-data, dom, optimization] +--- + +# Virtualize Large Lists to Avoid DOM Overload + +**Impact: HIGH** - Rendering all items in a large list (hundreds or thousands) creates massive amounts of DOM nodes. Each node consumes memory, slows down initial render, and makes updates expensive. List virtualization only renders visible items, dramatically improving performance. + +Use a virtualization library when dealing with lists that could exceed 50-100 items, especially if items have complex content. + +## Task List + +- Identify lists that render more than 50-100 items +- Install a virtualization library (vue-virtual-scroller, @tanstack/vue-virtual) +- Replace standard `v-for` with virtualized component +- Ensure list items have consistent or estimable heights +- Test with realistic data volumes during development + +## Recommended Libraries + +| Library | Best For | Notes | +|---------|----------|-------| +| `vue-virtual-scroller` | General use, easy setup | Most popular, good defaults | +| `@tanstack/vue-virtual` | Complex layouts, headless | Framework-agnostic, flexible | +| `vue-virtual-scroll-grid` | Grid layouts | 2D virtualization | +| `vueuc/VVirtualList` | Naive UI projects | Part of Naive UI ecosystem | + +**BAD:** +```vue + + + +``` + +**GOOD:** +```vue + + + + + +``` + +## Using @tanstack/vue-virtual + +```vue + + + + + +``` + +## Dynamic Heights with vue-virtual-scroller + +```vue + + + +``` + +## Performance Comparison + +| Approach | 100 Items | 1,000 Items | 10,000 Items | +|----------|-----------|-------------|--------------| +| Regular v-for | ~100 DOM nodes | ~1,000 DOM nodes | ~10,000 DOM nodes | +| Virtualized | ~20 DOM nodes | ~20 DOM nodes | ~20 DOM nodes | +| Initial render | Fast | Slow | Very slow / crashes | +| Virtualized render | Fast | Fast | Fast | + +## When NOT to Virtualize + +- Lists under 50 items with simple content +- Lists where all items must be accessible to screen readers simultaneously +- Print layouts where all content must render +- SEO-critical content that must be in initial HTML diff --git a/.agents/skills/vue-best-practices/references/plugins.md b/.agents/skills/vue-best-practices/references/plugins.md new file mode 100644 index 000000000..2986b9072 --- /dev/null +++ b/.agents/skills/vue-best-practices/references/plugins.md @@ -0,0 +1,169 @@ +--- +title: Vue Plugin Best Practices +impact: MEDIUM +impactDescription: Incorrect plugin structure or injection key strategy causes install failures, collisions, and unsafe APIs +type: best-practice +tags: [vue3, plugins, provide-inject, typescript, dependency-injection] +--- + +# Vue Plugin Best Practices + +**Impact: MEDIUM** - Vue plugins should follow the `app.use()` contract, expose explicit capabilities, and use collision-safe injection keys. This keeps plugin setup predictable and composable across large apps. + +## Task List + +- Export plugins as an object with `install()` or as an install function +- Use the `app` instance in `install()` to register components/directives/provides +- Type plugin APIs with `Plugin` (and options tuple types when needed) +- Use symbol keys (prefer `InjectionKey`) for `provide/inject` in plugins +- Add a small typed composable wrapper for required injections to fail fast + +## Structure Plugins for `app.use()` + +A Vue plugin must be either: +- An object with `install(app, options?)` +- A function with the same signature + +**BAD:** +```ts +const notAPlugin = { + doSomething() {} +} + +app.use(notAPlugin) +``` + +**GOOD:** +```ts +import type { App } from 'vue' + +interface PluginOptions { + prefix?: string + debug?: boolean +} + +const myPlugin = { + install(app: App, options: PluginOptions = {}) { + const { prefix = 'my', debug = false } = options + + if (debug) { + console.log('Installing myPlugin with prefix:', prefix) + } + + app.provide('myPlugin', { prefix }) + } +} + +app.use(myPlugin, { prefix: 'custom', debug: true }) +``` + +**GOOD:** +```ts +import type { App } from 'vue' + +function simplePlugin(app: App, options?: { message: string }) { + app.config.globalProperties.$greet = () => options?.message ?? 'Hello!' +} + +app.use(simplePlugin, { message: 'Welcome!' }) +``` + +## Register Capabilities Explicitly in `install()` + +Inside `install()`, wire behavior through Vue application APIs: +- `app.component()` for global components +- `app.directive()` for global directives +- `app.provide()` for injectable services and config +- `app.config.globalProperties` for optional global helpers (sparingly) + +**BAD:** +```ts +const uselessPlugin = { + install(app, options) { + const service = createService(options) + } +} +``` + +**GOOD:** +```ts +const usefulPlugin = { + install(app, options) { + const service = createService(options) + app.provide(serviceKey, service) + } +} +``` + +## Type Plugin Contracts + +Use Vue's `Plugin` type to keep install signatures and options type-safe. + +```ts +import type { App, Plugin } from 'vue' + +interface MyOptions { + apiKey: string +} + +const myPlugin: Plugin<[MyOptions]> = { + install(app: App, options: MyOptions) { + app.provide(apiKeyKey, options.apiKey) + } +} +``` + +## Use Symbol Injection Keys in Plugins + +String keys can collide (`'http'`, `'config'`, `'i18n'`). Use symbol keys with `InjectionKey` so injections are unique and typed. + +**BAD:** +```ts +export default { + install(app) { + app.provide('http', axios) + app.provide('config', appConfig) + } +} +``` + +**GOOD:** +```ts +import type { AxiosInstance } from 'axios' +import type { InjectionKey } from 'vue' + +interface AppConfig { + apiUrl: string + timeout: number +} + +export const httpKey: InjectionKey = Symbol('http') +export const configKey: InjectionKey = Symbol('appConfig') + +export default { + install(app) { + app.provide(httpKey, axios) + app.provide(configKey, { apiUrl: '/api', timeout: 5000 }) + } +} +``` + +## Provide Required Injection Helpers + +Wrap required injections in composables that throw clear setup errors. + +```ts +import type { AuthService } from '@/injection-keys' + +import { inject } from 'vue' + +import { authKey } from '@/injection-keys' + +export function useAuth(): AuthService { + const auth = inject(authKey) + if (!auth) { + throw new Error('Auth plugin not installed. Did you forget app.use(authPlugin)?') + } + return auth +} +``` diff --git a/.agents/skills/vue-best-practices/references/reactivity.md b/.agents/skills/vue-best-practices/references/reactivity.md new file mode 100644 index 000000000..374083acd --- /dev/null +++ b/.agents/skills/vue-best-practices/references/reactivity.md @@ -0,0 +1,348 @@ +--- +title: Reactivity Core Patterns (ref, reactive, shallowRef, computed, watch) +impact: MEDIUM +impactDescription: Clear reactivity choices keep state predictable and reduce unnecessary updates in Vue 3 apps +type: efficiency +tags: [vue3, reactivity, ref, reactive, shallowRef, computed, watch, watchEffect, external-state, best-practice] +--- + +# Reactivity Core Patterns (ref, reactive, shallowRef, computed, watch) + +**Impact: MEDIUM** - Choose the right reactive primitive first, derive with `computed`, and use watchers only for side effects. + +This reference covers the core reactivity decisions for local state, external data, derived values, and effects. + +## Task List + +- Declare reactive state correctly + - Always use `shallowRef()` instead of `ref()` for primitive values + - Choose the correct reactive declaration method for objects/arrays/map/set +- Follow best practices for `reactive` + - Avoid destructuring from `reactive()` directly + - Watch correctly for `reactive` +- Follow best practices for `computed` + - Prefer `computed` over watcher-assigned derived refs + - Keep filtered/sorted derivations out of templates + - Use `computed` for reusable class/style logic + - Keep computed getters pure (no side effects) and put side effects in watchers +- Follow best practices for watchers + - Use `immediate: true` instead of duplicate initial calls + - Clean up async effects for watchers + +## Declare reactive state correctly + +### Always use `shallowRef()` instead of `ref()` for primitive values (string, number, boolean, null, etc.) for better performance. + +**Incorrect:** +```ts +import { ref } from 'vue' + +const count = ref(0) +``` + +**Correct:** +```ts +import { shallowRef } from 'vue' + +const count = shallowRef(0) +``` + +### Choose the correct reactive declaration method for objects/arrays/map/set + +Use `ref()` when you often **replace the entire value** (`state.value = newObj`) and still want deep reactivity inside it, usually used for: + +- Frequently reassigned state (replace fetched object/list, reset to defaults, switch presets). +- Composable return values where updates happen mostly via `.value` reassignment. + +Use `reactive()` when you mainly **mutate properties** and full replacement is uncommon, usually used for: + +- “Single state object” patterns (stores/forms): `state.count++`, `state.items.push(...)`, `state.user.name = ...`. +- Situations where you want to avoid `.value` and update nested fields in place. + +```ts +import { reactive } from 'vue' + +const state = reactive({ + count: 0, + user: { name: 'Alice', age: 30 } +}) + +state.count++ // ✅ reactive +state.user.age = 31 // ✅ reactive +// ❌ avoid replacing the reactive object reference: +// state = reactive({ count: 1 }) +``` + +Use `shallowRef()` when the value is **opaque / should not be proxied** (class instances, external library objects, very large nested data) and you only want updates to trigger when you **replace** `state.value` (no deep tracking), usually used for: + +- Storing external instances/handles (SDK clients, class instances) without Vue proxying internals. +- Large data where you update by replacing the root reference (immutable-style updates). + +```ts +import { shallowRef } from 'vue' + +const user = shallowRef({ name: 'Alice', age: 30 }) + +user.value.age = 31 // ❌ not reactive +user.value = { name: 'Bob', age: 25 } // ✅ triggers update +``` + +Use `shallowReactive()` when you want **only top-level properties** reactive; nested objects remain raw, usually used for: + +- Container objects where only top-level keys change and nested payloads should stay unmanaged/unproxied. +- Mixed structures where Vue tracks the wrapper object, but not deeply nested or foreign objects. + +```ts +import { shallowReactive } from 'vue' + +const state = shallowReactive({ + count: 0, + user: { name: 'Alice', age: 30 } +}) + +state.count++ // ✅ reactive +state.user.age = 31 // ❌ not reactive +``` + +## Best practices for `reactive` + +### Avoid destructuring from `reactive()` directly + +**BAD:** + +```ts +import { reactive } from 'vue' + +const state = reactive({ count: 0 }) +const { count } = state // ❌ disconnected from reactivity +``` + +### Watch correctly for reactive + +**BAD:** + +passing a non-getter value into `watch()` + +```ts +import { reactive, watch } from 'vue' + +const state = reactive({ count: 0 }) + +// ❌ watch expects a getter, ref, reactive object, or array of these +watch(state.count, () => { /* ... */ }) +``` + +**GOOD:** + +preserve reactivity with `toRefs()` and use a getter for `watch()` + +```ts +import { reactive, toRefs, watch } from 'vue' + +const state = reactive({ count: 0 }) +const { count } = toRefs(state) // ✅ count is a ref + +watch(count, () => { /* ... */ }) // ✅ +watch(() => state.count, () => { /* ... */ }) // ✅ +``` + +## Best practices for `computed` + +### Prefer `computed` over watcher-assigned derived refs + +**BAD:** +```ts +import { ref, watchEffect } from 'vue' + +const items = ref([{ price: 10 }, { price: 20 }]) +const total = ref(0) + +watchEffect(() => { + total.value = items.value.reduce((sum, item) => sum + item.price, 0) +}) +``` + +**GOOD:** +```ts +import { computed, ref } from 'vue' + +const items = ref([{ price: 10 }, { price: 20 }]) +const total = computed(() => + items.value.reduce((sum, item) => sum + item.price, 0) +) +``` + +### Keep filtered/sorted derivations out of templates + +**BAD:** +```vue + + + +``` + +**GOOD:** +```vue + + + +``` + +### Use `computed` for reusable class/style logic + +**BAD:** +```vue + +``` + +**GOOD:** +```vue + + + +``` + +### Keep computed getters pure (no side effects) and put side effects in watchers instead + +A computed getter should only derive a value. No mutation, no API calls, no storage writes, no event emits. +([Reference](https://vuejs.org/guide/essentials/computed.html#best-practices)) + +**BAD:** + +side effects inside computed + +```ts +const count = ref(0) + +const doubled = computed(() => { + // ❌ side effect + if (count.value > 10) + console.warn('Too big!') + return count.value * 2 +}) +``` + +**GOOD:** + +pure computed + `watch()` for side effects + +```ts +const count = ref(0) +const doubled = computed(() => count.value * 2) + +watch(count, (value) => { + if (value > 10) + console.warn('Too big!') +}) +``` + +## Best practices for watchers + +### Use `immediate: true` instead of duplicate initial calls + +**BAD:** +```ts +import { onMounted, ref, watch } from 'vue' + +const userId = ref(1) + +function loadUser(id) { + // ... +} + +onMounted(() => loadUser(userId.value)) +watch(userId, id => loadUser(id)) +``` + +**GOOD:** +```ts +import { ref, watch } from 'vue' + +const userId = ref(1) + +watch( + userId, + id => loadUser(id), + { immediate: true } +) +``` + +### Clean up async effects for watchers + +When reacting to rapid changes (search boxes, filters), cancel the previous request. + +**GOOD:** + +```ts +const query = ref('') +const results = ref([]) + +watch(query, async (q, _prev, onCleanup) => { + const controller = new AbortController() + onCleanup(() => controller.abort()) + + const res = await fetch(`/api/search?q=${encodeURIComponent(q)}`, { + signal: controller.signal, + }) + + results.value = await res.json() +}) +``` diff --git a/.agents/skills/vue-best-practices/references/render-functions.md b/.agents/skills/vue-best-practices/references/render-functions.md new file mode 100644 index 000000000..d84118731 --- /dev/null +++ b/.agents/skills/vue-best-practices/references/render-functions.md @@ -0,0 +1,199 @@ +--- +title: Render Function Patterns and Performance +impact: MEDIUM +impactDescription: Render functions require explicit patterns for lists, events, v-model, and performance to stay correct and maintainable +type: best-practice +tags: [vue3, render-function, h, v-model, directives, performance, jsx] +--- + +# Render Function Patterns and Performance + +**Impact: MEDIUM** - Render functions are powerful but opt out of template compiler optimizations. Use them intentionally and apply the key patterns below to keep output correct and performant. + +## Task List + +- Prefer templates; use render functions only when templates cannot express the logic +- Always add stable keys when rendering lists with `h()`/JSX +- Use `withModifiers` / `withKeys` for event modifiers +- Implement `v-model` via `modelValue` + `onUpdate:modelValue` +- Apply custom directives with `withDirectives` +- Use functional components for stateless presentational UI + +## Prefer templates over render functions + +**BAD:** +```vue + +``` + +**GOOD:** +```vue + + + +``` + +## Always add keys for list rendering + +**BAD:** +```javascript +import { h, ref } from 'vue' + +export default { + setup() { + const items = ref([{ id: 1, name: 'Apple' }]) + + return () => h('ul', items.value.map(item => h('li', item.name))) + } +} +``` + +**GOOD:** +```javascript +import { h, ref } from 'vue' + +export default { + setup() { + const items = ref([{ id: 1, name: 'Apple' }]) + + return () => h('ul', items.value.map(item => h('li', { key: item.id }, item.name))) + } +} +``` + +## Use `withModifiers` / `withKeys` for event modifiers + +**BAD:** +```javascript +import { h } from 'vue' + +export default { + setup() { + const handleClick = (e) => { + e.stopPropagation() + e.preventDefault() + } + + return () => h('button', { onClick: handleClick }, 'Click') + } +} +``` + +**GOOD:** +```javascript +import { h, withKeys, withModifiers } from 'vue' + +export default { + setup() { + const handleClick = () => {} + const handleEnter = () => {} + + return () => h('div', [ + h('button', { + onClick: withModifiers(handleClick, ['stop', 'prevent']) + }, 'Click'), + h('input', { + onKeyup: withKeys(handleEnter, ['enter']) + }) + ]) + } +} +``` + +## Implement `v-model` explicitly + +**BAD:** +```javascript +import { h, ref } from 'vue' + +import CustomInput from './CustomInput.vue' + +export default { + setup() { + const text = ref('') + return () => h(CustomInput, { modelValue: text.value }) + } +} +``` + +**GOOD:** +```javascript +import { h, ref } from 'vue' + +import CustomInput from './CustomInput.vue' + +export default { + setup() { + const text = ref('') + return () => h(CustomInput, { + 'modelValue': text.value, + 'onUpdate:modelValue': (value) => { text.value = value } + }) + } +} +``` + +## Use `withDirectives` for custom directives + +**BAD:** +```javascript +import { h } from 'vue' + +const vFocus = { mounted: el => el.focus() } + +export default { + setup() { + return () => h('input', { 'v-focus': true }) + } +} +``` + +**GOOD:** +```javascript +import { h, withDirectives } from 'vue' + +const vFocus = { mounted: el => el.focus() } + +export default { + setup() { + return () => withDirectives(h('input'), [[vFocus]]) + } +} +``` + +## Prefer functional components for stateless UI + +**BAD:** +```javascript +import { h } from 'vue' + +export default { + setup() { + return () => h('span', { class: 'badge' }, 'New') + } +} +``` + +**GOOD:** +```javascript +import { h } from 'vue' + +function Badge(props, { slots }) { + return h('span', { class: 'badge' }, slots.default?.()) +} + +Badge.props = ['variant'] + +export default Badge +``` diff --git a/.agents/skills/vue-best-practices/references/sfc.md b/.agents/skills/vue-best-practices/references/sfc.md new file mode 100644 index 000000000..df22e33fb --- /dev/null +++ b/.agents/skills/vue-best-practices/references/sfc.md @@ -0,0 +1,317 @@ +--- +title: Single-File Component Structure, Styling, and Template Patterns +impact: MEDIUM +impactDescription: Consistent SFC structure and styling choices improve maintainability, tooling support, and render performance +type: best-practice +tags: [vue3, sfc, scoped-css, styles, build-tools, performance, template, v-html, v-for, computed, v-if, v-show] +--- + +# Single-File Component Structure, Styling, and Template Patterns + +**Impact: MEDIUM** - Using SFCs with consistent structure and performant styling keeps components easier to maintain and avoids unnecessary render overhead. + +## Task List + +- Use `.vue` SFCs instead of separate `.js`/`.ts` and `.css` files for components +- Colocate template, script, and styles in the same SFC by default +- Use PascalCase for component names in templates and filenames +- Prefer component-scoped styles +- Prefer class selectors (not element selectors) in scoped CSS for performance +- Access DOM / component refs with `useTemplateRef()` in Vue 3.5+ +- Use camelCase keys in `:style` bindings for consistency and IDE support +- Use `v-for` and `v-if` correctly +- Never use `v-html` with untrusted/user-provided content +- Choose `v-if` vs `v-show` based on toggle frequency and initial render cost + +## Colocate template, script, and styles + +**BAD:** +``` +components/ +├── UserCard.vue +├── UserCard.js +└── UserCard.css +``` + +**GOOD:** +```vue + + + + + + +``` + +## Use PascalCase for component names + +**BAD:** +```vue + + + +``` + +**GOOD:** +```vue + + + +``` + +## Best practices for ` +``` + +**GOOD:** + +```vue + +``` + +**GOOD:** + +```css +/* src/assets/main.css */ +/* ✅ resets, tokens, typography, app-wide rules */ +:root { --radius: 999px; } +``` + +### Use class selectors in scoped CSS + +**BAD:** +```vue + + + +``` + +**GOOD:** +```vue + + + +``` + +## Access DOM / component refs with `useTemplateRef()` + +For Vue 3.5+: use `useTemplateRef()` to access template refs. + +```vue + + + +``` + +## Use camelCase in `:style` bindings + +**BAD:** +```vue + +``` + +**GOOD:** +```vue + +``` + +## Use `v-for` and `v-if` correctly + +### Always provide a stable `:key` + +- Prefer primitive keys (`string | number`). +- Avoid using objects as keys. + +**GOOD:** + +```vue +
  • + +
  • +``` + +### Avoid `v-if` and `v-for` on the same element + +It leads to unclear intent and unnecessary work. +([Reference](https://vuejs.org/guide/essentials/list.html#v-for-with-v-if)) + +**To filter items** +**BAD:** + +```vue +
  • + {{ user.name }} +
  • +``` + +**GOOD:** + +```vue + + + +``` + +**To conditionally show/hide the entire list** +**GOOD:** + +```vue +
      +
    • + {{ user.name }} +
    • +
    +``` + +## Never render untrusted HTML with `v-html` + +**BAD:** +```vue + +``` + +**GOOD:** +```vue + + + +``` + +## Choose `v-if` vs `v-show` by toggle behavior + +**BAD:** +```vue + +``` + +**GOOD:** +```vue + +``` diff --git a/.agents/skills/vue-best-practices/references/state-management.md b/.agents/skills/vue-best-practices/references/state-management.md new file mode 100644 index 000000000..e59b63d39 --- /dev/null +++ b/.agents/skills/vue-best-practices/references/state-management.md @@ -0,0 +1,136 @@ +--- +title: State Management Strategy +impact: HIGH +impactDescription: Choosing the wrong store pattern can cause SSR request leaks, brittle mutation flows, and poor scaling +type: best-practice +tags: [vue3, state-management, pinia, composables, ssr, vueuse] +--- + +# State Management Strategy + +**Impact: HIGH** - Use the lightest state solution that fits your app architecture. SPA-only apps can use lightweight global composables, while SSR/Nuxt apps should default to Pinia for request-safe isolation and predictable tooling. + +## Task List + +- Keep state local first, then promote to shared/global only when needed +- Use singleton composables only in non-SSR applications +- Expose global state as readonly and mutate through explicit actions +- Prefer Pinia for SSR/Nuxt, large apps, and advanced debugging/plugin needs +- Avoid exporting mutable module-level reactive state directly + +## Choose the Lightest Store Approach + +- **Feature composable:** Default for reusable logic with local/feature-level state. +- **Singleton composable or VueUse `createGlobalState`:** Small non-SSR apps needing shared app state. +- **Pinia:** SSR/Nuxt apps, medium-to-large apps, and cases requiring DevTools, plugins, or action tracing. + +## Avoid Exporting Mutable Module State + +**BAD:** +```ts +// store/cart.ts +import { reactive } from 'vue' + +export const cart = reactive({ + items: [] as Array<{ id: string, qty: number }> +}) +``` + +**GOOD:** +```ts +// composables/useCartStore.ts +import { reactive, readonly } from 'vue' + +let _store: ReturnType | null = null + +function createCartStore() { + const state = reactive({ + items: [] as Array<{ id: string, qty: number }> + }) + + function addItem(id: string, qty = 1) { + const existing = state.items.find(item => item.id === id) + if (existing) { + existing.qty += qty + return + } + state.items.push({ id, qty }) + } + + return { + state: readonly(state), + addItem + } +} + +export function useCartStore() { + if (!_store) + _store = createCartStore() + return _store +} +``` + +## Do Not Use Runtime Singletons in SSR + +Module singletons live for the runtime lifetime. In SSR this can leak state between requests. + +**BAD:** +```ts +// shared singleton reused across requests +const cartStore = useCartStore() + +export function useServerCart() { + return cartStore +} +``` + +**GOOD:** + +> `pinia` dependency required. + +```ts +// stores/cart.ts +import { defineStore } from 'pinia' + +export const useCartStore = defineStore('cart', { + state: () => ({ + items: [] as Array<{ id: string, qty: number }> + }), + actions: { + addItem(id: string, qty = 1) { + const existing = this.items.find(item => item.id === id) + if (existing) { + existing.qty += qty + return + } + this.items.push({ id, qty }) + } + } +}) +``` + +## Use `createGlobalState` for Small SPA Global State + +> `@vueuse/core` dependency required. + +If the app is non-SSR and already uses VueUse, `createGlobalState` removes singleton boilerplate. + +```ts +import { createGlobalState } from '@vueuse/core' +import { computed, ref } from 'vue' + +export const useAuthState = createGlobalState(() => { + const token = ref(null) + const isAuthenticated = computed(() => token.value !== null) + + function setToken(next: string | null) { + token.value = next + } + + return { + token, + isAuthenticated, + setToken + } +}) +``` diff --git a/.agents/skills/vue-best-practices/references/updated-hook-performance.md b/.agents/skills/vue-best-practices/references/updated-hook-performance.md new file mode 100644 index 000000000..96e21f970 --- /dev/null +++ b/.agents/skills/vue-best-practices/references/updated-hook-performance.md @@ -0,0 +1,187 @@ +--- +title: Avoid Expensive Operations in Updated Hook +impact: MEDIUM +impactDescription: Heavy computations in updated hook cause performance bottlenecks and potential infinite loops +type: capability +tags: [vue3, vue2, lifecycle, updated, performance, optimization, reactivity] +--- + +# Avoid Expensive Operations in Updated Hook + +**Impact: MEDIUM** - The `updated` hook runs after every reactive state change that causes a re-render. Placing expensive operations, API calls, or state mutations here can cause severe performance degradation, infinite loops, and dropped frames below the optimal 60fps threshold. + +Use `updated`/`onUpdated` sparingly for post-DOM-update operations that cannot be handled by watchers or computed properties. For most reactive data handling, prefer watchers (`watch`/`watchEffect`) which provide more control over what triggers the callback. + +## Task List + +- Never perform API calls in updated hook +- Never mutate reactive state inside updated (causes infinite loops) +- Use conditional checks to verify updates are relevant before acting +- Prefer `watch` or `watchEffect` for reacting to specific data changes +- Use throttling/debouncing if updated operations are expensive +- Reserve updated for low-level DOM synchronization tasks + +**BAD:** +```javascript +// BAD: API call in updated - fires on every re-render +export default { + data() { + return { items: [], lastUpdate: null } + }, + updated() { + // This runs after every single state change! + fetch('/api/sync', { + method: 'POST', + body: JSON.stringify(this.items) + }) + } +} +``` + +```javascript +// BAD: State mutation in updated - infinite loop +export default { + data() { + return { renderCount: 0 } + }, + updated() { + // This causes another update, which triggers updated again! + this.renderCount++ // Infinite loop + } +} +``` + +```javascript +// BAD: Heavy computation on every update +export default { + updated() { + // Expensive operation runs on every keystroke, every state change + this.processedData = this.heavyComputation(this.rawData) + this.analytics = this.calculateMetrics(this.allData) + } +} +``` + +**GOOD:** +```javascript +import debounce from 'lodash-es/debounce' + +// GOOD: Use watcher for specific data changes +export default { + data() { + return { items: [] } + }, + watch: { + // Only fires when items actually changes + items: { + handler(newItems) { + this.syncToServer(newItems) + }, + deep: true + } + }, + methods: { + syncToServer: debounce((items) => { + fetch('/api/sync', { + method: 'POST', + body: JSON.stringify(items) + }) + }, 500) + } +} +``` + +```vue + + +``` + +```javascript +// GOOD: Conditional check in updated hook +export default { + data() { + return { + content: '', + lastSyncedContent: '' + } + }, + updated() { + // Only act if specific condition is met + if (this.content !== this.lastSyncedContent) { + this.syncContent() + this.lastSyncedContent = this.content + } + }, + methods: { + syncContent: debounce(() => { + // Sync logic + }, 300) + } +} +``` + +## Valid Use Cases for Updated Hook + +```javascript +// GOOD: Low-level DOM synchronization +export default { + updated() { + // Sync third-party library with Vue's DOM + this.thirdPartyWidget.refresh() + + // Update scroll position after content change + this.$nextTick(() => { + this.maintainScrollPosition() + }) + } +} +``` + +## Prefer Computed Properties for Derived Data + +```javascript +// BAD: Calculating derived data in updated +export default { + data() { + return { numbers: [1, 2, 3, 4, 5] } + }, + updated() { + this.sum = this.numbers.reduce((a, b) => a + b, 0) // Causes another update! + } +} + +// GOOD: Use computed property instead +export default { + data() { + return { numbers: [1, 2, 3, 4, 5] } + }, + computed: { + sum() { + return this.numbers.reduce((a, b) => a + b, 0) + } + } +} +``` diff --git a/.agents/skills/vue/GENERATION.md b/.agents/skills/vue/GENERATION.md new file mode 100644 index 000000000..7d4b4a5db --- /dev/null +++ b/.agents/skills/vue/GENERATION.md @@ -0,0 +1,5 @@ +# Generation Info + +- **Source:** `sources/vue` +- **Git SHA:** `01abf2d03815d9d0ff0b06362a68d5d9542c9e48` +- **Generated:** 2026-01-31 diff --git a/.agents/skills/vue/SKILL.md b/.agents/skills/vue/SKILL.md new file mode 100644 index 000000000..132de88de --- /dev/null +++ b/.agents/skills/vue/SKILL.md @@ -0,0 +1,81 @@ +--- +name: vue +description: Vue 3 Composition API, script setup macros, reactivity system, and built-in components. Use when writing Vue SFCs, defineProps/defineEmits/defineModel, watchers, or using Transition/Teleport/Suspense/KeepAlive. +metadata: + author: Anthony Fu + version: "2026.1.31" + source: Generated from https://github.com/vuejs/docs, scripts at https://github.com/antfu/skills +--- + +# Vue + +> Based on Vue 3.5. Always use Composition API with ` + + +``` + +### Key Imports + +```ts +// Reactivity +import { computed, reactive, readonly, ref, shallowRef, toRef, toRefs, toValue } from 'vue' +// Watchers +import { onWatcherCleanup, watch, watchEffect, watchPostEffect } from 'vue' +// Lifecycle +import { onBeforeMount, onBeforeUnmount, onBeforeUpdate, onMounted, onUnmounted, onUpdated } from 'vue' +// Utilities +import { defineAsyncComponent, defineComponent, nextTick } from 'vue' +``` diff --git a/.agents/skills/vue/references/advanced-patterns.md b/.agents/skills/vue/references/advanced-patterns.md new file mode 100644 index 000000000..9f2a4e27b --- /dev/null +++ b/.agents/skills/vue/references/advanced-patterns.md @@ -0,0 +1,322 @@ +--- +name: advanced-patterns +description: Vue 3 built-in components (Transition, Teleport, Suspense, KeepAlive) and advanced directives +--- + +# Built-in Components & Directives + +## Transition + +Animate enter/leave of a single element or component. + +```vue + + + +``` + +### CSS Classes + +| Class | When | +|-------|------| +| `{name}-enter-from` | Start state for enter | +| `{name}-enter-active` | Active state for enter (add transitions here) | +| `{name}-enter-to` | End state for enter | +| `{name}-leave-from` | Start state for leave | +| `{name}-leave-active` | Active state for leave | +| `{name}-leave-to` | End state for leave | + +### Transition Modes + +```vue + + + + +``` + +### JavaScript Hooks + +```vue + +
    Content
    +
    + + +``` + +### Appear on Initial Render + +```vue + +
    Shows with animation on mount
    +
    +``` + +## TransitionGroup + +Animate list items. Each child must have a unique `key`. + +```vue + + + +``` + +## Teleport + +Render content to a different DOM location. + +```vue + +``` + +### Props + +```vue + + + + + + + + + + + +``` + +## Suspense + +Handle async dependencies with loading states. **Experimental feature.** + +```vue + +``` + +### Async Dependencies + +Suspense waits for: +- Components with `async setup()` +- Components using top-level `await` in ` +``` + +### Events + +```vue + + ... + +``` + +## KeepAlive + +Cache component instances when toggled. + +```vue + +``` + +### Include/Exclude + +```vue + + + + + + + + + + +``` + +### Lifecycle Hooks + +```ts +import { onActivated, onDeactivated } from 'vue' + +onActivated(() => { + // Called when component is inserted from cache + fetchLatestData() +}) + +onDeactivated(() => { + // Called when component is removed to cache + pauseTimers() +}) +``` + +## v-memo + +Skip re-renders when dependencies unchanged. Use for performance optimization. + +```vue + +``` + +Equivalent to `v-once` when empty: +```vue +
    +Never updates +
    +``` + +## v-once + +Render once, skip all future updates. + +```vue + +Static: {{ neverChanges }} + +``` + +## Custom Directives + +Create reusable DOM manipulations. + +```ts +// Directive definition +const vFocus: Directive = { + mounted: el => el.focus() +} + +// Full hooks +const vColor: Directive = { + created(el, binding, vnode, prevVnode) {}, + beforeMount(el, binding) {}, + mounted(el, binding) { + el.style.color = binding.value + }, + beforeUpdate(el, binding) {}, + updated(el, binding) { + el.style.color = binding.value + }, + beforeUnmount(el, binding) {}, + unmounted(el, binding) {} +} +``` + +### Directive Arguments & Modifiers + +```vue +
    + + +``` + +### Global Registration + +```ts +// main.ts +app.directive('focus', { + mounted: el => el.focus() +}) +``` + + diff --git a/.agents/skills/vue/references/core-new-apis.md b/.agents/skills/vue/references/core-new-apis.md new file mode 100644 index 000000000..0ac788bb9 --- /dev/null +++ b/.agents/skills/vue/references/core-new-apis.md @@ -0,0 +1,267 @@ +--- +name: core-new-apis +description: Vue 3 reactivity system, lifecycle hooks, and composable patterns +--- + +# Reactivity, Lifecycle & Composables + +## Reactivity + +### ref vs shallowRef + +```ts +import { ref, shallowRef } from 'vue' + +// ref - deep reactivity (tracks nested changes) +const user = ref({ name: 'John', profile: { age: 30 } }) +user.value.profile.age = 31 // Triggers reactivity + +// shallowRef - only .value assignment triggers reactivity (better performance) +const data = shallowRef({ items: [] }) +data.value.items.push('new') // Does NOT trigger reactivity +data.value = { items: ['new'] } // Triggers reactivity +``` + +**Prefer `shallowRef`** for large data structures or when deep reactivity is unnecessary. + +### computed + +```ts +import { computed, ref } from 'vue' + +const count = ref(0) + +// Read-only computed +const doubled = computed(() => count.value * 2) + +// Writable computed +const plusOne = computed({ + get: () => count.value + 1, + set: (val) => { count.value = val - 1 } +}) +``` + +### reactive & readonly + +```ts +import { reactive, readonly } from 'vue' + +const state = reactive({ count: 0, nested: { value: 1 } }) +state.count++ // Reactive + +const readonlyState = readonly(state) +readonlyState.count++ // Warning, mutation blocked +``` + +Note: `reactive()` loses reactivity on destructuring. Use `ref()` or `toRefs()`. + +## Watchers + +### watch + +```ts +import { ref, watch } from 'vue' + +const count = ref(0) + +// Watch single ref +watch(count, (newVal, oldVal) => { + console.log(`Changed from ${oldVal} to ${newVal}`) +}) + +// Watch getter +watch( + () => props.id, + id => fetchData(id), + { immediate: true } +) + +// Watch multiple sources +watch([firstName, lastName], ([first, last]) => { + fullName.value = `${first} ${last}` +}) + +// Deep watch with depth limit (Vue 3.5+) +watch(state, callback, { deep: 2 }) + +// Once (Vue 3.4+) +watch(source, callback, { once: true }) +``` + +### watchEffect + +Runs immediately and auto-tracks dependencies. + +```ts +import { onWatcherCleanup, ref, watchEffect } from 'vue' + +const id = ref(1) + +watchEffect(async () => { + const controller = new AbortController() + + // Cleanup on re-run or unmount (Vue 3.5+) + onWatcherCleanup(() => controller.abort()) + + const res = await fetch(`/api/${id.value}`, { signal: controller.signal }) + data.value = await res.json() +}) + +// Pause/resume (Vue 3.5+) +const { pause, resume, stop } = watchEffect(() => {}) +pause() +resume() +stop() +``` + +### Flush Timing + +```ts +// 'pre' (default) - before component update +// 'post' - after component update (access updated DOM) +// 'sync' - immediate, use with caution + +watch(source, callback, { flush: 'post' }) +watchPostEffect(() => {}) // Alias for flush: 'post' +``` + +## Lifecycle Hooks + +```ts +import { + onActivated, // KeepAlive + onBeforeMount, + onBeforeUnmount, + onBeforeUpdate, + onDeactivated, // KeepAlive + onErrorCaptured, + onMounted, + onServerPrefetch, // SSR only + onUnmounted, + onUpdated +} from 'vue' + +onMounted(() => { + console.log('DOM is ready') +}) + +onUnmounted(() => { + // Cleanup timers, listeners, etc. +}) + +// Error boundary +onErrorCaptured((err, instance, info) => { + console.error(err) + return false // Stop propagation +}) +``` + +## Effect Scope + +Group reactive effects for batch disposal. + +```ts +import { effectScope, onScopeDispose } from 'vue' + +const scope = effectScope() + +scope.run(() => { + const count = ref(0) + const doubled = computed(() => count.value * 2) + + watch(count, () => console.log(count.value)) + + // Cleanup when scope stops + onScopeDispose(() => { + console.log('Scope disposed') + }) +}) + +// Dispose all effects +scope.stop() +``` + +## Composables + +Composables are functions that encapsulate stateful logic using Composition API. + +### Naming Convention + +- Start with `use`: `useMouse`, `useFetch`, `useCounter` + +### Pattern + +```ts +// composables/useMouse.ts +import { onMounted, onUnmounted, ref } from 'vue' + +export function useMouse() { + const x = ref(0) + const y = ref(0) + + const update = (e: MouseEvent) => { + x.value = e.pageX + y.value = e.pageY + } + + onMounted(() => window.addEventListener('mousemove', update)) + onUnmounted(() => window.removeEventListener('mousemove', update)) + + return { x, y } +} +``` + +### Accept Reactive Input + +Use `toValue()` (Vue 3.3+) to normalize refs, getters, or plain values. + +```ts +import type { MaybeRefOrGetter } from 'vue' + +import { ref, toValue, watchEffect } from 'vue' + +export function useFetch(url: MaybeRefOrGetter) { + const data = ref(null) + const error = ref(null) + + watchEffect(async () => { + data.value = null + error.value = null + + try { + const res = await fetch(toValue(url)) + data.value = await res.json() + } + catch (e) { + error.value = e + } + }) + + return { data, error } +} + +// Usage - all work: +useFetch('/api/users') +useFetch(urlRef) +useFetch(() => `/api/users/${props.id}`) +``` + +### Return Refs (Not Reactive) + +Always return plain object with refs for destructuring compatibility. + +```ts +// Good - preserves reactivity when destructured +return { x, y } + +// Bad - loses reactivity when destructured +return reactive({ x, y }) +``` + + diff --git a/.agents/skills/vue/references/script-setup-macros.md b/.agents/skills/vue/references/script-setup-macros.md new file mode 100644 index 000000000..70939d375 --- /dev/null +++ b/.agents/skills/vue/references/script-setup-macros.md @@ -0,0 +1,210 @@ +--- +name: script-setup-macros +description: Vue 3 script setup syntax and compiler macros for defining props, emits, models, and more +--- + +# Script Setup & Macros + +` + + +``` + +## defineProps + +Declare component props with full TypeScript support. + +```ts +// Type-based declaration (recommended) +const props = defineProps<{ + title: string + count?: number + items: string[] +}>() + +// With defaults (Vue 3.5+) +const { title, count = 0 } = defineProps<{ + title: string + count?: number +}>() + +// With defaults (Vue 3.4 and below) +const props = withDefaults(defineProps<{ + title: string + items?: string[] +}>(), { + items: () => [] // Use factory for arrays/objects +}) +``` + +## defineEmits + +Declare emitted events with typed payloads. + +```ts +// Named tuple syntax (recommended) +const emit = defineEmits<{ + update: [value: string] + change: [id: number, name: string] + close: [] +}>() + +emit('update', 'new value') +emit('change', 1, 'name') +emit('close') +``` + +## defineModel + +Two-way binding prop consumed via `v-model`. Available in Vue 3.4+. + +```ts +// Basic usage - creates "modelValue" prop +const model = defineModel() +model.value = 'hello' // Emits "update:modelValue" + +// Named model - consumed via v-model:name +const count = defineModel('count', { default: 0 }) + +// With modifiers +const [value, modifiers] = defineModel() +if (modifiers.trim) { + // Handle trim modifier +} + +// With transformers +const [value, modifiers] = defineModel({ + get(val) { return val?.toLowerCase() }, + set(val) { return modifiers.trim ? val?.trim() : val } +}) +``` + +Parent usage: +```vue + + + + + +``` + +## defineExpose + +Explicitly expose properties to parent via template refs. Components are closed by default. + +```ts +import { ref } from 'vue' + +const count = ref(0) +function reset() { count.value = 0 } + +defineExpose({ + count, + reset +}) +``` + +Parent access: +```ts +const childRef = ref<{ count: number, reset: () => void }>() +childRef.value?.reset() +``` + +## defineOptions + +Declare component options without a separate ` +``` + +Multiple generics with constraints: +```vue + +``` + +## Local Custom Directives + +Use `vNameOfDirective` naming convention. + +```ts +// Or import and rename +import { myDirective as vMyDirective } from './directives' + +const vFocus = { + mounted: (el: HTMLElement) => el.focus() +} +``` + +```vue + +``` + +## Top-level await + +Use `await` directly in ` +``` + + diff --git a/.agents/skills/vueuse-functions/LICENSE.md b/.agents/skills/vueuse-functions/LICENSE.md new file mode 100644 index 000000000..8a1060dff --- /dev/null +++ b/.agents/skills/vueuse-functions/LICENSE.md @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 SerKo + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/.agents/skills/vueuse-functions/SKILL.md b/.agents/skills/vueuse-functions/SKILL.md new file mode 100644 index 000000000..cb8cdb0ea --- /dev/null +++ b/.agents/skills/vueuse-functions/SKILL.md @@ -0,0 +1,419 @@ +--- +name: vueuse-functions +description: Apply VueUse composables where appropriate to build concise, maintainable Vue.js / Nuxt features. +license: MIT +metadata: + author: SerKo + version: "1.0" +compatibility: Requires Vue 3 (or above) or Nuxt 3 (or above) project +--- + +# VueUse Functions + +This skill is a decision-and-implementation guide for VueUse composables in Vue.js / Nuxt projects. It maps requirements to the most suitable VueUse function, applies the correct usage pattern, and prefers composable-based solutions over bespoke code to keep implementations concise, maintainable, and performant. + +## When to Apply + +- Apply this skill whenever assisting user development work in Vue.js / Nuxt. +- Always check first whether a VueUse function can implement the requirement. +- Prefer VueUse composables over custom code to improve readability, maintainability, and performance. +- Map requirements to the most appropriate VueUse function and follow the function’s invocation rule. +- Please refer to the `Invocation` field in the below functions table. For example: + - `AUTO`: Use automatically when applicable. + - `EXTERNAL`: Use only if the user already installed the required external dependency; otherwise reconsider, and ask to install only if truly needed. + - `EXPLICIT_ONLY`: Use only when explicitly requested by the user. + > *NOTE* User instructions in the prompt or `AGENTS.md` may override a function’s default `Invocation` rule. + +## Functions + +All functions listed below are part of the [VueUse](https://vueuse.org/) library, each section categorizes functions based on their functionality. + +IMPORTANT: Each function entry includes a short `Description` and a detailed `Reference`. When using any function, always consult the corresponding document in `./references` for Usage details and Type Declarations. + +### State + +| Function | Description | Invocation | +|----------|-------------|------------| +| [`createGlobalState`](references/createGlobalState.md) | Keep states in the global scope to be reusable across Vue instances | AUTO | +| [`createInjectionState`](references/createInjectionState.md) | Create global state that can be injected into components | AUTO | +| [`createSharedComposable`](references/createSharedComposable.md) | Make a composable function usable with multiple Vue instances | AUTO | +| [`injectLocal`](references/injectLocal.md) | Extended `inject` with ability to call `provideLocal` to provide the value in the same component | AUTO | +| [`provideLocal`](references/provideLocal.md) | Extended `provide` with ability to call `injectLocal` to obtain the value in the same component | AUTO | +| [`useAsyncState`](references/useAsyncState.md) | Reactive async state | AUTO | +| [`useDebouncedRefHistory`](references/useDebouncedRefHistory.md) | Shorthand for `useRefHistory` with debounced filter | AUTO | +| [`useLastChanged`](references/useLastChanged.md) | Records the timestamp of the last change | AUTO | +| [`useLocalStorage`](references/useLocalStorage.md) | Reactive [LocalStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) | AUTO | +| [`useManualRefHistory`](references/useManualRefHistory.md) | Manually track the change history of a ref when the using calls `commit()` | AUTO | +| [`useRefHistory`](references/useRefHistory.md) | Track the change history of a ref | AUTO | +| [`useSessionStorage`](references/useSessionStorage.md) | Reactive [SessionStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage) | AUTO | +| [`useStorage`](references/useStorage.md) | Create a reactive ref that can be used to access & modify [LocalStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) or [SessionStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage) | AUTO | +| [`useStorageAsync`](references/useStorageAsync.md) | Reactive Storage in with async support | AUTO | +| [`useThrottledRefHistory`](references/useThrottledRefHistory.md) | Shorthand for `useRefHistory` with throttled filter | AUTO | + +### Elements + +| Function | Description | Invocation | +|----------|-------------|------------| +| [`useActiveElement`](references/useActiveElement.md) | Reactive `document.activeElement` | AUTO | +| [`useDocumentVisibility`](references/useDocumentVisibility.md) | Reactively track [`document.visibilityState`](https://developer.mozilla.org/en-US/docs/Web/API/Document/visibilityState) | AUTO | +| [`useDraggable`](references/useDraggable.md) | Make elements draggable | AUTO | +| [`useDropZone`](references/useDropZone.md) | Create a zone where files can be dropped | AUTO | +| [`useElementBounding`](references/useElementBounding.md) | Reactive [bounding box](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect) of an HTML element | AUTO | +| [`useElementSize`](references/useElementSize.md) | Reactive size of an HTML element | AUTO | +| [`useElementVisibility`](references/useElementVisibility.md) | Tracks the visibility of an element within the viewport | AUTO | +| [`useIntersectionObserver`](references/useIntersectionObserver.md) | Detects that a target element's visibility | AUTO | +| [`useMouseInElement`](references/useMouseInElement.md) | Reactive mouse position related to an element | AUTO | +| [`useMutationObserver`](references/useMutationObserver.md) | Watch for changes being made to the DOM tree | AUTO | +| [`useParentElement`](references/useParentElement.md) | Get parent element of the given element | AUTO | +| [`useResizeObserver`](references/useResizeObserver.md) | Reports changes to the dimensions of an Element's content or the border-box | AUTO | +| [`useWindowFocus`](references/useWindowFocus.md) | Reactively track window focus with `window.onfocus` and `window.onblur` events | AUTO | +| [`useWindowScroll`](references/useWindowScroll.md) | Reactive window scroll | AUTO | +| [`useWindowSize`](references/useWindowSize.md) | Reactive window size | AUTO | + +### Browser + +| Function | Description | Invocation | +|----------|-------------|------------| +| [`useBluetooth`](references/useBluetooth.md) | Reactive [Web Bluetooth API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Bluetooth_API) | AUTO | +| [`useBreakpoints`](references/useBreakpoints.md) | Reactive viewport breakpoints | AUTO | +| [`useBroadcastChannel`](references/useBroadcastChannel.md) | Reactive [BroadcastChannel API](https://developer.mozilla.org/en-US/docs/Web/API/BroadcastChannel) | AUTO | +| [`useBrowserLocation`](references/useBrowserLocation.md) | Reactive browser location | AUTO | +| [`useClipboard`](references/useClipboard.md) | Reactive [Clipboard API](https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API) | AUTO | +| [`useClipboardItems`](references/useClipboardItems.md) | Reactive [Clipboard API](https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API) | AUTO | +| [`useColorMode`](references/useColorMode.md) | Reactive color mode (dark / light / customs) with auto data persistence | AUTO | +| [`useCssSupports`](references/useCssSupports.md) | SSR compatible and reactive [`CSS.supports`](https://developer.mozilla.org/docs/Web/API/CSS/supports_static) | AUTO | +| [`useCssVar`](references/useCssVar.md) | Manipulate CSS variables | AUTO | +| [`useDark`](references/useDark.md) | Reactive dark mode with auto data persistence | AUTO | +| [`useEventListener`](references/useEventListener.md) | Use EventListener with ease | AUTO | +| [`useEyeDropper`](references/useEyeDropper.md) | Reactive [EyeDropper API](https://developer.mozilla.org/en-US/docs/Web/API/EyeDropper_API) | AUTO | +| [`useFavicon`](references/useFavicon.md) | Reactive favicon | AUTO | +| [`useFileDialog`](references/useFileDialog.md) | Open file dialog with ease | AUTO | +| [`useFileSystemAccess`](references/useFileSystemAccess.md) | Create and read and write local files with [FileSystemAccessAPI](https://developer.mozilla.org/en-US/docs/Web/API/File_System_Access_API) | AUTO | +| [`useFullscreen`](references/useFullscreen.md) | Reactive [Fullscreen API](https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API) | AUTO | +| [`useGamepad`](references/useGamepad.md) | Provides reactive bindings for the [Gamepad API](https://developer.mozilla.org/en-US/docs/Web/API/Gamepad_API) | AUTO | +| [`useImage`](references/useImage.md) | Reactive load an image in the browser | AUTO | +| [`useMediaControls`](references/useMediaControls.md) | Reactive media controls for both `audio` and `video` elements | AUTO | +| [`useMediaQuery`](references/useMediaQuery.md) | Reactive [Media Query](https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Testing_media_queries) | AUTO | +| [`useMemory`](references/useMemory.md) | Reactive Memory Info | AUTO | +| [`useObjectUrl`](references/useObjectUrl.md) | Reactive URL representing an object | AUTO | +| [`usePerformanceObserver`](references/usePerformanceObserver.md) | Observe performance metrics | AUTO | +| [`usePermission`](references/usePermission.md) | Reactive [Permissions API](https://developer.mozilla.org/en-US/docs/Web/API/Permissions_API) | AUTO | +| [`usePreferredColorScheme`](references/usePreferredColorScheme.md) | Reactive [prefers-color-scheme](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme) media query | AUTO | +| [`usePreferredContrast`](references/usePreferredContrast.md) | Reactive [prefers-contrast](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-contrast) media query | AUTO | +| [`usePreferredDark`](references/usePreferredDark.md) | Reactive dark theme preference | AUTO | +| [`usePreferredLanguages`](references/usePreferredLanguages.md) | Reactive [Navigator Languages](https://developer.mozilla.org/en-US/docs/Web/API/NavigatorLanguage/languages) | AUTO | +| [`usePreferredReducedMotion`](references/usePreferredReducedMotion.md) | Reactive [prefers-reduced-motion](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-reduced-motion) media query | AUTO | +| [`usePreferredReducedTransparency`](references/usePreferredReducedTransparency.md) | Reactive [prefers-reduced-transparency](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-reduced-transparency) media query | AUTO | +| [`useScreenOrientation`](references/useScreenOrientation.md) | Reactive [Screen Orientation API](https://developer.mozilla.org/en-US/docs/Web/API/Screen_Orientation_API) | AUTO | +| [`useScreenSafeArea`](references/useScreenSafeArea.md) | Reactive `env(safe-area-inset-*)` | AUTO | +| [`useScriptTag`](references/useScriptTag.md) | Creates a script tag | AUTO | +| [`useShare`](references/useShare.md) | Reactive [Web Share API](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/share) | AUTO | +| [`useSSRWidth`](references/useSSRWidth.md) | Used to set a global viewport width which will be used when rendering SSR components that rely on the viewport width like [`useMediaQuery`](../useMediaQuery/index.md) or [`useBreakpoints`](../useBreakpoints/index.md) | AUTO | +| [`useStyleTag`](references/useStyleTag.md) | Inject reactive `style` element in head | AUTO | +| [`useTextareaAutosize`](references/useTextareaAutosize.md) | Automatically update the height of a textarea depending on the content | AUTO | +| [`useTextDirection`](references/useTextDirection.md) | Reactive [dir](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/dir) of the element's text | AUTO | +| [`useTitle`](references/useTitle.md) | Reactive document title | AUTO | +| [`useUrlSearchParams`](references/useUrlSearchParams.md) | Reactive [URLSearchParams](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) | AUTO | +| [`useVibrate`](references/useVibrate.md) | Reactive [Vibration API](https://developer.mozilla.org/en-US/docs/Web/API/Vibration_API) | AUTO | +| [`useWakeLock`](references/useWakeLock.md) | Reactive [Screen Wake Lock API](https://developer.mozilla.org/en-US/docs/Web/API/Screen_Wake_Lock_API) | AUTO | +| [`useWebNotification`](references/useWebNotification.md) | Reactive [Notification](https://developer.mozilla.org/en-US/docs/Web/API/notification) | AUTO | +| [`useWebWorker`](references/useWebWorker.md) | Simple [Web Workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers) registration and communication | AUTO | +| [`useWebWorkerFn`](references/useWebWorkerFn.md) | Run expensive functions without blocking the UI | AUTO | + +### Sensors + +| Function | Description | Invocation | +|----------|-------------|------------| +| [`onClickOutside`](references/onClickOutside.md) | Listen for clicks outside of an element | AUTO | +| [`onElementRemoval`](references/onElementRemoval.md) | Fires when the element or any element containing it is removed from the DOM | AUTO | +| [`onKeyStroke`](references/onKeyStroke.md) | Listen for keyboard keystrokes | AUTO | +| [`onLongPress`](references/onLongPress.md) | Listen for a long press on an element | AUTO | +| [`onStartTyping`](references/onStartTyping.md) | Fires when users start typing on non-editable elements | AUTO | +| [`useBattery`](references/useBattery.md) | Reactive [Battery Status API](https://developer.mozilla.org/en-US/docs/Web/API/Battery_Status_API) | AUTO | +| [`useDeviceMotion`](references/useDeviceMotion.md) | Reactive [DeviceMotionEvent](https://developer.mozilla.org/en-US/docs/Web/API/DeviceMotionEvent) | AUTO | +| [`useDeviceOrientation`](references/useDeviceOrientation.md) | Reactive [DeviceOrientationEvent](https://developer.mozilla.org/en-US/docs/Web/API/DeviceOrientationEvent) | AUTO | +| [`useDevicePixelRatio`](references/useDevicePixelRatio.md) | Reactively track [`window.devicePixelRatio`](https://developer.mozilla.org/docs/Web/API/Window/devicePixelRatio) | AUTO | +| [`useDevicesList`](references/useDevicesList.md) | Reactive [enumerateDevices](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/enumerateDevices) listing available input/output devices | AUTO | +| [`useDisplayMedia`](references/useDisplayMedia.md) | Reactive [`mediaDevices.getDisplayMedia`](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getDisplayMedia) streaming | AUTO | +| [`useElementByPoint`](references/useElementByPoint.md) | Reactive element by point | AUTO | +| [`useElementHover`](references/useElementHover.md) | Reactive element's hover state | AUTO | +| [`useFocus`](references/useFocus.md) | Reactive utility to track or set the focus state of a DOM element | AUTO | +| [`useFocusWithin`](references/useFocusWithin.md) | Reactive utility to track if an element or one of its decendants has focus | AUTO | +| [`useFps`](references/useFps.md) | Reactive FPS (frames per second) | AUTO | +| [`useGeolocation`](references/useGeolocation.md) | Reactive [Geolocation API](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API) | AUTO | +| [`useIdle`](references/useIdle.md) | Tracks whether the user is being inactive | AUTO | +| [`useInfiniteScroll`](references/useInfiniteScroll.md) | Infinite scrolling of the element | AUTO | +| [`useKeyModifier`](references/useKeyModifier.md) | Reactive [Modifier State](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/getModifierState) | AUTO | +| [`useMagicKeys`](references/useMagicKeys.md) | Reactive keys pressed state | AUTO | +| [`useMouse`](references/useMouse.md) | Reactive mouse position | AUTO | +| [`useMousePressed`](references/useMousePressed.md) | Reactive mouse pressing state | AUTO | +| [`useNavigatorLanguage`](references/useNavigatorLanguage.md) | Reactive [navigator.language](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/language) | AUTO | +| [`useNetwork`](references/useNetwork.md) | Reactive [Network status](https://developer.mozilla.org/en-US/docs/Web/API/Network_Information_API) | AUTO | +| [`useOnline`](references/useOnline.md) | Reactive online state | AUTO | +| [`usePageLeave`](references/usePageLeave.md) | Reactive state to show whether the mouse leaves the page | AUTO | +| [`useParallax`](references/useParallax.md) | Create parallax effect easily | AUTO | +| [`usePointer`](references/usePointer.md) | Reactive [pointer state](https://developer.mozilla.org/en-US/docs/Web/API/Pointer_events) | AUTO | +| [`usePointerLock`](references/usePointerLock.md) | Reactive [pointer lock](https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API) | AUTO | +| [`usePointerSwipe`](references/usePointerSwipe.md) | Reactive swipe detection based on [PointerEvents](https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent) | AUTO | +| [`useScroll`](references/useScroll.md) | Reactive scroll position and state | AUTO | +| [`useScrollLock`](references/useScrollLock.md) | Lock scrolling of the element | AUTO | +| [`useSpeechRecognition`](references/useSpeechRecognition.md) | Reactive [SpeechRecognition](https://developer.mozilla.org/en-US/docs/Web/API/SpeechRecognition) | AUTO | +| [`useSpeechSynthesis`](references/useSpeechSynthesis.md) | Reactive [SpeechSynthesis](https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesis) | AUTO | +| [`useSwipe`](references/useSwipe.md) | Reactive swipe detection based on [`TouchEvents`](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent) | AUTO | +| [`useTextSelection`](references/useTextSelection.md) | Reactively track user text selection based on [`Window.getSelection`](https://developer.mozilla.org/en-US/docs/Web/API/Window/getSelection) | AUTO | +| [`useUserMedia`](references/useUserMedia.md) | Reactive [`mediaDevices.getUserMedia`](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia) streaming | AUTO | + +### Network + +| Function | Description | Invocation | +|----------|-------------|------------| +| [`useEventSource`](references/useEventSource.md) | An [EventSource](https://developer.mozilla.org/en-US/docs/Web/API/EventSource) or [Server-Sent-Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events) instance opens a persistent connection to an HTTP server | AUTO | +| [`useFetch`](references/useFetch.md) | Reactive [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) provides the ability to abort requests | AUTO | +| [`useWebSocket`](references/useWebSocket.md) | Reactive [WebSocket](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/WebSocket) client | AUTO | + +### Animation + +| Function | Description | Invocation | +|----------|-------------|------------| +| [`useAnimate`](references/useAnimate.md) | Reactive [Web Animations API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API) | AUTO | +| [`useInterval`](references/useInterval.md) | Reactive counter that increases on every interval | AUTO | +| [`useIntervalFn`](references/useIntervalFn.md) | Wrapper for `setInterval` with controls | AUTO | +| [`useNow`](references/useNow.md) | Reactive current Date instance | AUTO | +| [`useRafFn`](references/useRafFn.md) | Call function on every `requestAnimationFrame` | AUTO | +| [`useTimeout`](references/useTimeout.md) | Reactive value that becomes `true` after a given time | AUTO | +| [`useTimeoutFn`](references/useTimeoutFn.md) | Wrapper for `setTimeout` with controls | AUTO | +| [`useTimestamp`](references/useTimestamp.md) | Reactive current timestamp | AUTO | +| [`useTransition`](references/useTransition.md) | Transition between values | AUTO | + +### Component + +| Function | Description | Invocation | +|----------|-------------|------------| +| [`computedInject`](references/computedInject.md) | Combine `computed` and `inject` | AUTO | +| [`createReusableTemplate`](references/createReusableTemplate.md) | Define and reuse template inside the component scope | AUTO | +| [`createTemplatePromise`](references/createTemplatePromise.md) | Template as Promise | AUTO | +| [`templateRef`](references/templateRef.md) | Shorthand for binding ref to template element | AUTO | +| [`tryOnBeforeMount`](references/tryOnBeforeMount.md) | Safe `onBeforeMount` | AUTO | +| [`tryOnBeforeUnmount`](references/tryOnBeforeUnmount.md) | Safe `onBeforeUnmount` | AUTO | +| [`tryOnMounted`](references/tryOnMounted.md) | Safe `onMounted` | AUTO | +| [`tryOnScopeDispose`](references/tryOnScopeDispose.md) | Safe `onScopeDispose` | AUTO | +| [`tryOnUnmounted`](references/tryOnUnmounted.md) | Safe `onUnmounted` | AUTO | +| [`unrefElement`](references/unrefElement.md) | Retrieves the underlying DOM element from a Vue ref or component instance | AUTO | +| [`useCurrentElement`](references/useCurrentElement.md) | Get the DOM element of current component as a ref | AUTO | +| [`useMounted`](references/useMounted.md) | Mounted state in ref | AUTO | +| [`useTemplateRefsList`](references/useTemplateRefsList.md) | Shorthand for binding refs to template elements and components inside `v-for` | AUTO | +| [`useVirtualList`](references/useVirtualList.md) | Create virtual lists with ease | AUTO | +| [`useVModel`](references/useVModel.md) | Shorthand for v-model binding | AUTO | +| [`useVModels`](references/useVModels.md) | Shorthand for props v-model binding | AUTO | + +### Watch + +| Function | Description | Invocation | +|----------|-------------|------------| +| [`until`](references/until.md) | Promised one-time watch for changes | AUTO | +| [`watchArray`](references/watchArray.md) | Watch for an array with additions and removals | AUTO | +| [`watchAtMost`](references/watchAtMost.md) | `watch` with the number of times triggered | AUTO | +| [`watchDebounced`](references/watchDebounced.md) | Debounced watch | AUTO | +| [`watchDeep`](references/watchDeep.md) | Shorthand for watching value with `{deep: true}` | AUTO | +| [`watchIgnorable`](references/watchIgnorable.md) | Ignorable watch | AUTO | +| [`watchImmediate`](references/watchImmediate.md) | Shorthand for watching value with `{immediate: true}` | AUTO | +| [`watchOnce`](references/watchOnce.md) | Shorthand for watching value with `{ once: true }` | AUTO | +| [`watchPausable`](references/watchPausable.md) | Pausable watch | AUTO | +| [`watchThrottled`](references/watchThrottled.md) | Throttled watch | AUTO | +| [`watchTriggerable`](references/watchTriggerable.md) | Watch that can be triggered manually | AUTO | +| [`watchWithFilter`](references/watchWithFilter.md) | `watch` with additional EventFilter control | AUTO | +| [`whenever`](references/whenever.md) | Shorthand for watching value to be truthy | AUTO | + +### Reactivity + +| Function | Description | Invocation | +|----------|-------------|------------| +| [`computedAsync`](references/computedAsync.md) | Computed for async functions | AUTO | +| [`computedEager`](references/computedEager.md) | Eager computed without lazy evaluation | AUTO | +| [`computedWithControl`](references/computedWithControl.md) | Explicitly define the dependencies of computed | AUTO | +| [`createRef`](references/createRef.md) | Returns a `deepRef` or `shallowRef` depending on the `deep` param | AUTO | +| [`extendRef`](references/extendRef.md) | Add extra attributes to Ref | AUTO | +| [`reactify`](references/reactify.md) | Converts plain functions into reactive functions | AUTO | +| [`reactifyObject`](references/reactifyObject.md) | Apply `reactify` to an object | AUTO | +| [`reactiveComputed`](references/reactiveComputed.md) | Computed reactive object | AUTO | +| [`reactiveOmit`](references/reactiveOmit.md) | Reactively omit fields from a reactive object | AUTO | +| [`reactivePick`](references/reactivePick.md) | Reactively pick fields from a reactive object | AUTO | +| [`refAutoReset`](references/refAutoReset.md) | A ref which will be reset to the default value after some time | AUTO | +| [`refDebounced`](references/refDebounced.md) | Debounce execution of a ref value | AUTO | +| [`refDefault`](references/refDefault.md) | Apply default value to a ref | AUTO | +| [`refManualReset`](references/refManualReset.md) | Create a ref with manual reset functionality | AUTO | +| [`refThrottled`](references/refThrottled.md) | Throttle changing of a ref value | AUTO | +| [`refWithControl`](references/refWithControl.md) | Fine-grained controls over ref and its reactivity | AUTO | +| [`syncRef`](references/syncRef.md) | Two-way refs synchronization | AUTO | +| [`syncRefs`](references/syncRefs.md) | Keep target refs in sync with a source ref | AUTO | +| [`toReactive`](references/toReactive.md) | Converts ref to reactive | AUTO | +| [`toRef`](references/toRef.md) | Normalize value/ref/getter to `ref` or `computed` | EXPLICIT_ONLY | +| [`toRefs`](references/toRefs.md) | Extended [`toRefs`](https://vuejs.org/api/reactivity-utilities.html#torefs) that also accepts refs of an object | AUTO | + +### Array + +| Function | Description | Invocation | +|----------|-------------|------------| +| [`useArrayDifference`](references/useArrayDifference.md) | Reactive get array difference of two arrays | AUTO | +| [`useArrayEvery`](references/useArrayEvery.md) | Reactive `Array.every` | AUTO | +| [`useArrayFilter`](references/useArrayFilter.md) | Reactive `Array.filter` | AUTO | +| [`useArrayFind`](references/useArrayFind.md) | Reactive `Array.find` | AUTO | +| [`useArrayFindIndex`](references/useArrayFindIndex.md) | Reactive `Array.findIndex` | AUTO | +| [`useArrayFindLast`](references/useArrayFindLast.md) | Reactive `Array.findLast` | AUTO | +| [`useArrayIncludes`](references/useArrayIncludes.md) | Reactive `Array.includes` | AUTO | +| [`useArrayJoin`](references/useArrayJoin.md) | Reactive `Array.join` | AUTO | +| [`useArrayMap`](references/useArrayMap.md) | Reactive `Array.map` | AUTO | +| [`useArrayReduce`](references/useArrayReduce.md) | Reactive `Array.reduce` | AUTO | +| [`useArraySome`](references/useArraySome.md) | Reactive `Array.some` | AUTO | +| [`useArrayUnique`](references/useArrayUnique.md) | Reactive unique array | AUTO | +| [`useSorted`](references/useSorted.md) | Reactive sort array | AUTO | + +### Time + +| Function | Description | Invocation | +|----------|-------------|------------| +| [`useCountdown`](references/useCountdown.md) | Reactive countdown timer in seconds | AUTO | +| [`useDateFormat`](references/useDateFormat.md) | Get the formatted date according to the string of tokens passed in | AUTO | +| [`useTimeAgo`](references/useTimeAgo.md) | Reactive time ago | AUTO | +| [`useTimeAgoIntl`](references/useTimeAgoIntl.md) | Reactive time ago with i18n supported | AUTO | + +### Utilities + +| Function | Description | Invocation | +|----------|-------------|------------| +| [`createEventHook`](references/createEventHook.md) | Utility for creating event hooks | AUTO | +| [`createUnrefFn`](references/createUnrefFn.md) | Make a plain function accepting ref and raw values as arguments | AUTO | +| [`get`](references/get.md) | Shorthand for accessing `ref.value` | EXPLICIT_ONLY | +| [`isDefined`](references/isDefined.md) | Non-nullish checking type guard for Ref | AUTO | +| [`makeDestructurable`](references/makeDestructurable.md) | Make isomorphic destructurable for object and array at the same time | AUTO | +| [`set`](references/set.md) | Shorthand for `ref.value = x` | EXPLICIT_ONLY | +| [`useAsyncQueue`](references/useAsyncQueue.md) | Executes each asynchronous task sequentially and passes the current task result to the next task | AUTO | +| [`useBase64`](references/useBase64.md) | Reactive base64 transforming | AUTO | +| [`useCached`](references/useCached.md) | Cache a ref with a custom comparator | AUTO | +| [`useCloned`](references/useCloned.md) | Reactive clone of a ref | AUTO | +| [`useConfirmDialog`](references/useConfirmDialog.md) | Creates event hooks to support modals and confirmation dialog chains | AUTO | +| [`useCounter`](references/useCounter.md) | Basic counter with utility functions | AUTO | +| [`useCycleList`](references/useCycleList.md) | Cycle through a list of items | AUTO | +| [`useDebounceFn`](references/useDebounceFn.md) | Debounce execution of a function | AUTO | +| [`useEventBus`](references/useEventBus.md) | A basic event bus | AUTO | +| [`useMemoize`](references/useMemoize.md) | Cache results of functions depending on arguments and keep it reactive | AUTO | +| [`useOffsetPagination`](references/useOffsetPagination.md) | Reactive offset pagination | AUTO | +| [`usePrevious`](references/usePrevious.md) | Holds the previous value of a ref | AUTO | +| [`useStepper`](references/useStepper.md) | Provides helpers for building a multi-step wizard interface | AUTO | +| [`useSupported`](references/useSupported.md) | SSR compatibility `isSupported` | AUTO | +| [`useThrottleFn`](references/useThrottleFn.md) | Throttle execution of a function | AUTO | +| [`useTimeoutPoll`](references/useTimeoutPoll.md) | Use timeout to poll something | AUTO | +| [`useToggle`](references/useToggle.md) | A boolean switcher with utility functions | AUTO | +| [`useToNumber`](references/useToNumber.md) | Reactively convert a string ref to number | AUTO | +| [`useToString`](references/useToString.md) | Reactively convert a ref to string | AUTO | + +### @Electron + +| Function | Description | Invocation | +|----------|-------------|------------| +| [`useIpcRenderer`](references/useIpcRenderer.md) | Provides [ipcRenderer](https://www.electronjs.org/docs/api/ipc-renderer) and all of its APIs with Vue reactivity | EXTERNAL | +| [`useIpcRendererInvoke`](references/useIpcRendererInvoke.md) | Reactive [ipcRenderer.invoke API](https://www.electronjs.org/docs/api/ipc-renderer#ipcrendererinvokechannel-args) result | EXTERNAL | +| [`useIpcRendererOn`](references/useIpcRendererOn.md) | Use [ipcRenderer.on](https://www.electronjs.org/docs/api/ipc-renderer#ipcrendereronchannel-listener) with ease and [ipcRenderer.removeListener](https://www.electronjs.org/docs/api/ipc-renderer#ipcrendererremovelistenerchannel-listener) automatically on unmounted | EXTERNAL | +| [`useZoomFactor`](references/useZoomFactor.md) | Reactive [WebFrame](https://www.electronjs.org/docs/api/web-frame#webframe) zoom factor | EXTERNAL | +| [`useZoomLevel`](references/useZoomLevel.md) | Reactive [WebFrame](https://www.electronjs.org/docs/api/web-frame#webframe) zoom level | EXTERNAL | + +### @Firebase + +| Function | Description | Invocation | +|----------|-------------|------------| +| [`useAuth`](references/useAuth.md) | Reactive [Firebase Auth](https://firebase.google.com/docs/auth) binding | EXTERNAL | +| [`useFirestore`](references/useFirestore.md) | Reactive [Firestore](https://firebase.google.com/docs/firestore) binding | EXTERNAL | +| [`useRTDB`](references/useRTDB.md) | Reactive [Firebase Realtime Database](https://firebase.google.com/docs/database) binding | EXTERNAL | + +### @Head + +| Function | Description | Invocation | +|----------|-------------|------------| +| [`createHead`](https://github.com/vueuse/head#api) | Create the head manager instance. | EXTERNAL | +| [`useHead`](https://github.com/vueuse/head#api) | Update head meta tags reactively. | EXTERNAL | + +### @Integrations + +| Function | Description | Invocation | +|----------|-------------|------------| +| [`useAsyncValidator`](references/useAsyncValidator.md) | Wrapper for [`async-validator`](https://github.com/yiminghe/async-validator) | EXTERNAL | +| [`useAxios`](references/useAxios.md) | Wrapper for [`axios`](https://github.com/axios/axios) | EXTERNAL | +| [`useChangeCase`](references/useChangeCase.md) | Reactive wrapper for [`change-case`](https://github.com/blakeembrey/change-case) | EXTERNAL | +| [`useCookies`](references/useCookies.md) | Wrapper for [`universal-cookie`](https://www.npmjs.com/package/universal-cookie) | EXTERNAL | +| [`useDrauu`](references/useDrauu.md) | Reactive instance for [drauu](https://github.com/antfu/drauu) | EXTERNAL | +| [`useFocusTrap`](references/useFocusTrap.md) | Reactive wrapper for [`focus-trap`](https://github.com/focus-trap/focus-trap) | EXTERNAL | +| [`useFuse`](references/useFuse.md) | Easily implement fuzzy search using a composable with [Fuse.js](https://github.com/krisk/fuse) | EXTERNAL | +| [`useIDBKeyval`](references/useIDBKeyval.md) | Wrapper for [`idb-keyval`](https://www.npmjs.com/package/idb-keyval) | EXTERNAL | +| [`useJwt`](references/useJwt.md) | Wrapper for [`jwt-decode`](https://github.com/auth0/jwt-decode) | EXTERNAL | +| [`useNProgress`](references/useNProgress.md) | Reactive wrapper for [`nprogress`](https://github.com/rstacruz/nprogress) | EXTERNAL | +| [`useQRCode`](references/useQRCode.md) | Wrapper for [`qrcode`](https://github.com/soldair/node-qrcode) | EXTERNAL | +| [`useSortable`](references/useSortable.md) | Wrapper for [`sortable`](https://github.com/SortableJS/Sortable) | EXTERNAL | + +### @Math + +| Function | Description | Invocation | +|----------|-------------|------------| +| [`createGenericProjection`](references/createGenericProjection.md) | Generic version of `createProjection` | EXTERNAL | +| [`createProjection`](references/createProjection.md) | Reactive numeric projection from one domain to another | EXTERNAL | +| [`logicAnd`](references/logicAnd.md) | `AND` condition for refs | EXTERNAL | +| [`logicNot`](references/logicNot.md) | `NOT` condition for ref | EXTERNAL | +| [`logicOr`](references/logicOr.md) | `OR` conditions for refs | EXTERNAL | +| [`useAbs`](references/useAbs.md) | Reactive `Math.abs` | EXTERNAL | +| [`useAverage`](references/useAverage.md) | Get the average of an array reactively | EXTERNAL | +| [`useCeil`](references/useCeil.md) | Reactive `Math.ceil` | EXTERNAL | +| [`useClamp`](references/useClamp.md) | Reactively clamp a value between two other values | EXTERNAL | +| [`useFloor`](references/useFloor.md) | Reactive `Math.floor` | EXTERNAL | +| [`useMath`](references/useMath.md) | Reactive `Math` methods | EXTERNAL | +| [`useMax`](references/useMax.md) | Reactive `Math.max` | EXTERNAL | +| [`useMin`](references/useMin.md) | Reactive `Math.min` | EXTERNAL | +| [`usePrecision`](references/usePrecision.md) | Reactively set the precision of a number | EXTERNAL | +| [`useProjection`](references/useProjection.md) | Reactive numeric projection from one domain to another | EXTERNAL | +| [`useRound`](references/useRound.md) | Reactive `Math.round` | EXTERNAL | +| [`useSum`](references/useSum.md) | Get the sum of an array reactively | EXTERNAL | +| [`useTrunc`](references/useTrunc.md) | Reactive `Math.trunc` | EXTERNAL | + +### @Motion + +| Function | Description | Invocation | +|----------|-------------|------------| +| [`useElementStyle`](https://motion.vueuse.org/api/use-element-style) | Sync a reactive object to a target element CSS styling | EXTERNAL | +| [`useElementTransform`](https://motion.vueuse.org/api/use-element-transform) | Sync a reactive object to a target element CSS transform. | EXTERNAL | +| [`useMotion`](https://motion.vueuse.org/api/use-motion) | Putting your components in motion. | EXTERNAL | +| [`useMotionProperties`](https://motion.vueuse.org/api/use-motion-properties) | Access Motion Properties for a target element. | EXTERNAL | +| [`useMotionVariants`](https://motion.vueuse.org/api/use-motion-variants) | Handle the Variants state and selection. | EXTERNAL | +| [`useSpring`](https://motion.vueuse.org/api/use-spring) | Spring animations. | EXTERNAL | + +### @Router + +| Function | Description | Invocation | +|----------|-------------|------------| +| [`useRouteHash`](references/useRouteHash.md) | Shorthand for a reactive `route.hash` | EXTERNAL | +| [`useRouteParams`](references/useRouteParams.md) | Shorthand for a reactive `route.params` | EXTERNAL | +| [`useRouteQuery`](references/useRouteQuery.md) | Shorthand for a reactive `route.query` | EXTERNAL | + +### @RxJS + +| Function | Description | Invocation | +|----------|-------------|------------| +| [`from`](references/from.md) | Wrappers around RxJS's [`from()`](https://rxjs.dev/api/index/function/from) and [`fromEvent()`](https://rxjs.dev/api/index/function/fromEvent) to allow them to accept `ref`s | EXTERNAL | +| [`toObserver`](references/toObserver.md) | Sugar function to convert a `ref` into an RxJS [Observer](https://rxjs.dev/guide/observer) | EXTERNAL | +| [`useExtractedObservable`](references/useExtractedObservable.md) | Use an RxJS [`Observable`](https://rxjs.dev/guide/observable) as extracted from one or more composables | EXTERNAL | +| [`useObservable`](references/useObservable.md) | Use an RxJS [`Observable`](https://rxjs.dev/guide/observable) | EXTERNAL | +| [`useSubject`](references/useSubject.md) | Bind an RxJS [`Subject`](https://rxjs.dev/guide/subject) to a `ref` and propagate value changes both ways | EXTERNAL | +| [`useSubscription`](references/useSubscription.md) | Use an RxJS [`Subscription`](https://rxjs.dev/guide/subscription) without worrying about unsubscribing from it or creating memory leaks | EXTERNAL | +| [`watchExtractedObservable`](references/watchExtractedObservable.md) | Watch the values of an RxJS [`Observable`](https://rxjs.dev/guide/observable) as extracted from one or more composables | EXTERNAL | + +### @SchemaOrg + +| Function | Description | Invocation | +|----------|-------------|------------| +| [`createSchemaOrg`](https://vue-schema-org.netlify.app/api/core/create-schema-org.html) | Create the schema.org manager instance. | EXTERNAL | +| [`useSchemaOrg`](https://vue-schema-org.netlify.app/api/core/use-schema-org.html) | Update schema.org reactively. | EXTERNAL | + +### @Sound + +| Function | Description | Invocation | +|----------|-------------|------------| +| [`useSound`](https://github.com/vueuse/sound#examples) | Play sound effects reactively. | EXTERNAL | + + diff --git a/.agents/skills/vueuse-functions/SYNC.md b/.agents/skills/vueuse-functions/SYNC.md new file mode 100644 index 000000000..13a4d9371 --- /dev/null +++ b/.agents/skills/vueuse-functions/SYNC.md @@ -0,0 +1,5 @@ +# Sync Info + +- **Source:** `vendor/vueuse/skills/vueuse-functions` +- **Git SHA:** `075b0d6d558cc5ca7d5ffe72a56b5fd92bbef2d1` +- **Synced:** 2026-03-13 diff --git a/.agents/skills/vueuse-functions/references/computedAsync.md b/.agents/skills/vueuse-functions/references/computedAsync.md new file mode 100644 index 000000000..34059d045 --- /dev/null +++ b/.agents/skills/vueuse-functions/references/computedAsync.md @@ -0,0 +1,195 @@ +--- +category: Reactivity +alias: asyncComputed +--- + +# computedAsync + +Computed for async functions. + +## Usage + +```ts +import { computedAsync } from '@vueuse/core' +import { shallowRef } from 'vue' + +const name = shallowRef('jack') + +const userInfo = computedAsync( + async () => { + return await mockLookUp(name.value) + }, + null, // initial state +) +``` + +### Evaluation State + +Pass a ref to track if the async function is currently evaluating. + +```ts +import { computedAsync } from '@vueuse/core' +import { shallowRef } from 'vue' + +const evaluating = shallowRef(false) + +const userInfo = computedAsync( + async () => { /* your logic */ }, + null, + evaluating, // can also be passed via options: { evaluating } +) +``` + +### onCancel + +When the computed source changes before the previous async function resolves, you may want to cancel the previous one. Here is an example showing how to incorporate with the fetch API. + +```ts +import { computedAsync } from '@vueuse/core' +import { shallowRef } from 'vue' + +const packageName = shallowRef('@vueuse/core') + +const downloads = computedAsync(async (onCancel) => { + const abortController = new AbortController() + + onCancel(() => abortController.abort()) + + return await fetch( + `https://api.npmjs.org/downloads/point/last-week/${packageName.value}`, + { signal: abortController.signal }, + ) + .then(response => response.ok ? response.json() : { downloads: '—' }) + .then(result => result.downloads) +}, 0) +``` + +### Lazy + +By default, `computedAsync` will start resolving immediately on creation. Specify `lazy: true` to make it start resolving on the first access. + +```ts +import { computedAsync } from '@vueuse/core' +import { shallowRef } from 'vue' + +const evaluating = shallowRef(false) + +const userInfo = computedAsync( + async () => { /* your logic */ }, + null, + { lazy: true, evaluating }, +) +``` + +### Error Handling + +Use the `onError` callback to handle errors from the async function. + +```ts +import { computedAsync } from '@vueuse/core' +import { shallowRef } from 'vue' + +const name = shallowRef('jack') + +const userInfo = computedAsync( + async () => { + return await mockLookUp(name.value) + }, + null, + { + onError(e) { + console.error('Failed to fetch user info', e) + }, + }, +) +``` + +### Shallow Ref + +By default, `computedAsync` uses `shallowRef` internally. Set `shallow: false` to use a deep ref instead. + +```ts +import { computedAsync } from '@vueuse/core' +import { shallowRef } from 'vue' + +const name = shallowRef('jack') + +const userInfo = computedAsync( + async () => { + return await fetchNestedData(name.value) + }, + null, + { shallow: false }, // enables deep reactivity +) +``` + +## Caveats + +- Just like Vue's built-in `computed` function, `computedAsync` does dependency tracking and is automatically re-evaluated when dependencies change. Note however that only dependencies referenced in the first call stack are considered for this. In other words: **Dependencies that are accessed asynchronously will not trigger re-evaluation of the async computed value.** + +- As opposed to Vue's built-in `computed` function, re-evaluation of the async computed value is triggered whenever dependencies are changing, regardless of whether its result is currently being tracked or not. + +## Type Declarations + +```ts +/** + * Handle overlapping async evaluations. + * + * @param cancelCallback The provided callback is invoked when a re-evaluation of the computed value is triggered before the previous one finished + */ +export type AsyncComputedOnCancel = (cancelCallback: Fn) => void +export interface AsyncComputedOptions< + Lazy = boolean, +> extends ConfigurableFlushSync { + /** + * Should value be evaluated lazily + * + * @default false + */ + lazy?: Lazy + /** + * Ref passed to receive the updated of async evaluation + */ + evaluating?: Ref + /** + * Use shallowRef + * + * @default true + */ + shallow?: boolean + /** + * Callback when error is caught. + */ + onError?: (e: unknown) => void +} +/** + * Create an asynchronous computed dependency. + * + * @see https://vueuse.org/computedAsync + * @param evaluationCallback The promise-returning callback which generates the computed value + * @param initialState The initial state, used until the first evaluation finishes + * @param optionsOrRef Additional options or a ref passed to receive the updates of the async evaluation + */ +export declare function computedAsync( + evaluationCallback: (onCancel: AsyncComputedOnCancel) => T | Promise, + initialState: T, + optionsOrRef: AsyncComputedOptions, +): ComputedRef +export declare function computedAsync( + evaluationCallback: (onCancel: AsyncComputedOnCancel) => T | Promise, + initialState: undefined, + optionsOrRef: AsyncComputedOptions, +): ComputedRef +export declare function computedAsync( + evaluationCallback: (onCancel: AsyncComputedOnCancel) => T | Promise, + initialState: T, + optionsOrRef?: Ref | AsyncComputedOptions, +): Ref +export declare function computedAsync( + evaluationCallback: (onCancel: AsyncComputedOnCancel) => T | Promise, + initialState?: undefined, + optionsOrRef?: Ref | AsyncComputedOptions, +): Ref +/** @deprecated use `computedAsync` instead */ +export declare const asyncComputed: typeof computedAsync +``` diff --git a/.agents/skills/vueuse-functions/references/computedEager.md b/.agents/skills/vueuse-functions/references/computedEager.md new file mode 100644 index 000000000..225dc9a0d --- /dev/null +++ b/.agents/skills/vueuse-functions/references/computedEager.md @@ -0,0 +1,62 @@ +--- +category: Reactivity +alias: eagerComputed +--- + +# computedEager + +Eager computed without lazy evaluation. + +::: info +This function will be removed in future version. +::: + +::: tip +Note💡: If you are using Vue 3.4+, you can use `computed` right away, you no longer need this function. +In Vue 3.4+, if the computed new value does not change, `computed`, `effect`, `watch`, `watchEffect`, `render` dependencies will not be triggered. +See: https://github.com/vuejs/core/pull/5912 +::: + +Learn more at [Vue: When a computed property can be the wrong tool](https://dev.to/linusborg/vue-when-a-computed-property-can-be-the-wrong-tool-195j). + +- Use `computed()` when you have a complex calculation going on, which can actually profit from caching and lazy evaluation and should only be (re-)calculated if really necessary. +- Use `computedEager()` when you have a simple operation, with a rarely changing return value – often a boolean. + +## Usage + +```ts +import { computedEager } from '@vueuse/core' + +const todos = ref([]) +const hasOpenTodos = computedEager(() => !!todos.length) + +console.log(hasOpenTodos.value) // false +toTodos.value.push({ title: 'Learn Vue' }) +console.log(hasOpenTodos.value) // true +``` + +## Type Declarations + +```ts +export type ComputedEagerOptions = WatchOptionsBase +export type ComputedEagerReturn = Readonly> +/** + * + * @deprecated This function will be removed in future version. + * + * Note: If you are using Vue 3.4+, you can straight use computed instead. + * Because in Vue 3.4+, if computed new value does not change, + * computed, effect, watch, watchEffect, render dependencies will not be triggered. + * refer: https://github.com/vuejs/core/pull/5912 + * + * @param fn effect function + * @param options WatchOptionsBase + * @returns readonly shallowRef + */ +export declare function computedEager( + fn: () => T, + options?: ComputedEagerOptions, +): ComputedEagerReturn +/** @deprecated use `computedEager` instead */ +export declare const eagerComputed: typeof computedEager +``` diff --git a/.agents/skills/vueuse-functions/references/computedInject.md b/.agents/skills/vueuse-functions/references/computedInject.md new file mode 100644 index 000000000..7141e331e --- /dev/null +++ b/.agents/skills/vueuse-functions/references/computedInject.md @@ -0,0 +1,138 @@ +--- +category: Component +--- + +# computedInject + +Combine `computed` and `inject`. Useful for creating a computed property based on an injected value. + +## Usage + +In Provider Component + +```ts twoslash include main +import type { InjectionKey, Ref } from 'vue' + +import { provide, ref } from 'vue' + +interface Item { + key: number + value: string +} + +export const ArrayKey: InjectionKey> = Symbol('symbol-key') + +const array = ref([{ key: 1, value: '1' }, { key: 2, value: '2' }, { key: 3, value: '3' }]) + +provide(ArrayKey, array) +``` + +In Receiver Component + +```ts +// @filename: provider.ts +// @include: main +// ---cut--- +import { computedInject } from '@vueuse/core' + +import { ArrayKey } from './provider' + +const computedArray = computedInject(ArrayKey, (source) => { + const arr = [...source.value] + arr.unshift({ key: 0, value: 'all' }) + return arr +}) +``` + +### Default Value + +You can provide a default value that will be used if the injection key is not provided by a parent component. + +```ts +import { computedInject } from '@vueuse/core' + +const computedArray = computedInject( + ArrayKey, + (source) => { + return source.value.map(item => item.value) + }, + ref([]), // default source value +) +``` + +### Factory Default + +Pass `true` as the fourth argument to treat the default value as a factory function. + +```ts +import { computedInject } from '@vueuse/core' + +const computedArray = computedInject( + ArrayKey, + (source) => { + return source.value.map(item => item.value) + }, + () => ref([]), // factory function for default + true, // treat default as factory +) +``` + +### Writable Computed + +You can also create a writable computed property by passing an object with `get` and `set` functions. + +```ts +import { computedInject } from '@vueuse/core' + +const computedArray = computedInject(ArrayKey, { + get(source) { + return source.value.map(item => item.value) + }, + set(value) { + // handle setting the value + console.log('Setting value:', value) + }, +}) +``` + +## Type Declarations + +```ts +export type ComputedInjectGetter = ( + source: T | undefined, + oldValue?: K, +) => K +export type ComputedInjectGetterWithDefault = ( + source: T, + oldValue?: K, +) => K +export type ComputedInjectSetter = (v: T) => void +export interface WritableComputedInjectOptions { + get: ComputedInjectGetter + set: ComputedInjectSetter +} +export interface WritableComputedInjectOptionsWithDefault { + get: ComputedInjectGetterWithDefault + set: ComputedInjectSetter +} +export declare function computedInject( + key: InjectionKey | string, + getter: ComputedInjectGetter, +): ComputedRef +export declare function computedInject( + key: InjectionKey | string, + options: WritableComputedInjectOptions, +): ComputedRef +export declare function computedInject( + key: InjectionKey | string, + getter: ComputedInjectGetterWithDefault, + defaultSource: T, + treatDefaultAsFactory?: false, +): ComputedRef +export declare function computedInject( + key: InjectionKey | string, + options: WritableComputedInjectOptionsWithDefault, + defaultSource: T | (() => T), + treatDefaultAsFactory: true, +): ComputedRef +``` diff --git a/.agents/skills/vueuse-functions/references/computedWithControl.md b/.agents/skills/vueuse-functions/references/computedWithControl.md new file mode 100644 index 000000000..3f4d4bd10 --- /dev/null +++ b/.agents/skills/vueuse-functions/references/computedWithControl.md @@ -0,0 +1,98 @@ +--- +category: Reactivity +alias: controlledComputed +--- + +# computedWithControl + +Explicitly define the dependencies of computed. + +## Usage + +```ts twoslash include main +import { computedWithControl } from '@vueuse/core' + +const source = ref('foo') +const counter = ref(0) + +const computedRef = computedWithControl( + () => source.value, // watch source, same as `watch` + () => counter.value, // computed getter, same as `computed` +) +``` + +With this, the changes of `counter` won't trigger `computedRef` to update but the `source` ref does. + +```ts +// @include: main +// ---cut--- +console.log(computedRef.value) // 0 + +counter.value += 1 + +console.log(computedRef.value) // 0 + +source.value = 'bar' + +console.log(computedRef.value) // 1 +``` + +### Manual Triggering + +You can also manually trigger the update of the computed by: + +```ts +// @include: main +// ---cut--- +const computedRef = computedWithControl( + () => source.value, + () => counter.value, +) + +computedRef.trigger() +``` + +### Deep Watch + +Unlike `computed`, `computedWithControl` is shallow by default. +You can specify the same options as `watch` to control the behavior: + +```ts +const source = ref({ name: 'foo' }) + +const computedRef = computedWithControl( + source, + () => counter.value, + { deep: true }, +) +``` + +## Type Declarations + +```ts +export interface ComputedWithControlRefExtra { + /** + * Force update the computed value. + */ + trigger: () => void +} +export interface ComputedRefWithControl + extends ComputedRef, ComputedWithControlRefExtra {} +export interface WritableComputedRefWithControl + extends WritableComputedRef, ComputedWithControlRefExtra {} +export type ComputedWithControlRef + = | ComputedRefWithControl + | WritableComputedRefWithControl +export declare function computedWithControl( + source: WatchSource | MultiWatchSources, + fn: ComputedGetter, + options?: WatchOptions, +): ComputedRefWithControl +export declare function computedWithControl( + source: WatchSource | MultiWatchSources, + fn: WritableComputedOptions, + options?: WatchOptions, +): WritableComputedRefWithControl +/** @deprecated use `computedWithControl` instead */ +export declare const controlledComputed: typeof computedWithControl +``` diff --git a/.agents/skills/vueuse-functions/references/createEventHook.md b/.agents/skills/vueuse-functions/references/createEventHook.md new file mode 100644 index 000000000..433832dfb --- /dev/null +++ b/.agents/skills/vueuse-functions/references/createEventHook.md @@ -0,0 +1,86 @@ +--- +category: Utilities +--- + +# createEventHook + +Utility for creating event hooks + +## Usage + +Creating a function that uses `createEventHook` + +```ts +import { createEventHook } from '@vueuse/core' + +export function useMyFetch(url) { + const fetchResult = createEventHook() + const fetchError = createEventHook() + + fetch(url) + .then(result => fetchResult.trigger(result)) + .catch(error => fetchError.trigger(error.message)) + + return { + onResult: fetchResult.on, + onError: fetchError.on, + } +} +``` + +Using a function that uses `createEventHook` + +```vue + +``` + +## Type Declarations + +```ts +/** + * The source code for this function was inspired by vue-apollo's `useEventHook` util + * https://github.com/vuejs/vue-apollo/blob/v4/packages/vue-apollo-composable/src/util/useEventHook.ts + */ +type Callback + = IsAny extends true + ? (...param: any) => void + : [T] extends [void] + ? (...param: unknown[]) => void + : [T] extends [any[]] + ? (...param: T) => void + : (...param: [T, ...unknown[]]) => void +export type EventHookOn = (fn: Callback) => { + off: () => void +} +export type EventHookOff = (fn: Callback) => void +export type EventHookTrigger = ( + ...param: Parameters> +) => Promise +export interface EventHook { + on: EventHookOn + off: EventHookOff + trigger: EventHookTrigger + clear: () => void +} +export type EventHookReturn = EventHook +/** + * Utility for creating event hooks + * + * @see https://vueuse.org/createEventHook + * + * @__NO_SIDE_EFFECTS__ + */ +export declare function createEventHook(): EventHookReturn +``` diff --git a/.agents/skills/vueuse-functions/references/createGenericProjection.md b/.agents/skills/vueuse-functions/references/createGenericProjection.md new file mode 100644 index 000000000..c45203151 --- /dev/null +++ b/.agents/skills/vueuse-functions/references/createGenericProjection.md @@ -0,0 +1,25 @@ +--- +category: '@Math' +--- + +# createGenericProjection + +Generic version of `createProjection`. Accepts a custom projector function to map arbitrary type of domains. + +Refer to `createProjection` and `useProjection` + +## Type Declarations + +```ts +export type ProjectorFunction = ( + input: F, + from: readonly [F, F], + to: readonly [T, T], +) => T +export type UseProjection = (input: MaybeRefOrGetter) => ComputedRef +export declare function createGenericProjection( + fromDomain: MaybeRefOrGetter, + toDomain: MaybeRefOrGetter, + projector: ProjectorFunction, +): UseProjection +``` diff --git a/.agents/skills/vueuse-functions/references/createGlobalState.md b/.agents/skills/vueuse-functions/references/createGlobalState.md new file mode 100644 index 000000000..d0909fc69 --- /dev/null +++ b/.agents/skills/vueuse-functions/references/createGlobalState.md @@ -0,0 +1,95 @@ +--- +category: State +related: createSharedComposable +--- + +# createGlobalState + +Keep states in the global scope to be reusable across Vue instances. + +## Usage + +### Without Persistence (Store in Memory) + +```ts +// store.ts +import { createGlobalState } from '@vueuse/core' +import { shallowRef } from 'vue' + +export const useGlobalState = createGlobalState( + () => { + const count = shallowRef(0) + return { count } + } +) +``` + +A bigger example: + +```ts +// store.ts +import { createGlobalState } from '@vueuse/core' +import { computed, shallowRef } from 'vue' + +export const useGlobalState = createGlobalState( + () => { + // state + const count = shallowRef(0) + + // getters + const doubleCount = computed(() => count.value * 2) + + // actions + function increment() { + count.value++ + } + + return { count, doubleCount, increment } + } +) +``` + +### With Persistence + +Store in `localStorage` with `useStorage`: + +```ts twoslash include store +// store.ts +import { createGlobalState, useStorage } from '@vueuse/core' + +export const useGlobalState = createGlobalState( + () => useStorage('vueuse-local-storage', 'initialValue'), +) +``` + +```ts +// @filename: store.ts +// @include: store +// ---cut--- +// component.ts +import { useGlobalState } from './store' + +export default defineComponent({ + setup() { + const state = useGlobalState() + return { state } + }, +}) +``` + +## Type Declarations + +```ts +export type CreateGlobalStateReturn = Fn +/** + * Keep states in the global scope to be reusable across Vue instances. + * + * @see https://vueuse.org/createGlobalState + * @param stateFactory A factory function to create the state + * + * @__NO_SIDE_EFFECTS__ + */ +export declare function createGlobalState( + stateFactory: Fn, +): CreateGlobalStateReturn +``` diff --git a/.agents/skills/vueuse-functions/references/createInjectionState.md b/.agents/skills/vueuse-functions/references/createInjectionState.md new file mode 100644 index 000000000..5aa7331db --- /dev/null +++ b/.agents/skills/vueuse-functions/references/createInjectionState.md @@ -0,0 +1,215 @@ +--- +category: State +--- + +# createInjectionState + +Create global state that can be injected into components. + +## Usage + +```ts twoslash include useCounterStore +// useCounterStore.ts +import { createInjectionState } from '@vueuse/core' +import { computed, shallowRef } from 'vue' + +const [useProvideCounterStore, useCounterStore] = createInjectionState((initialValue: number) => { + // state + const count = shallowRef(initialValue) + + // getters + const double = computed(() => count.value * 2) + + // actions + function increment() { + count.value++ + } + + return { count, double, increment } +}) + +export { useProvideCounterStore } + +// If you want to hide `useCounterStore` and wrap it in default value logic or throw error logic, please don't export `useCounterStore` +export { useCounterStore } + +export function useCounterStoreWithDefaultValue() { + return useCounterStore() ?? { + count: shallowRef(0), + double: shallowRef(0), + increment: () => {}, + } +} + +export function useCounterStoreOrThrow() { + const counterStore = useCounterStore() + if (counterStore == null) + throw new Error('Please call `useProvideCounterStore` on the appropriate parent component') + return counterStore +} +``` + +```vue + + + + +``` + +```vue + + + + +``` + +```vue + + + + +``` + +## Provide a custom InjectionKey + +```ts +// useCounterStore.ts +import { createInjectionState } from '@vueuse/core' +import { computed, shallowRef } from 'vue' + +// custom injectionKey +const CounterStoreKey = 'counter-store' + +const [useProvideCounterStore, useCounterStore] = createInjectionState((initialValue: number) => { + // state + const count = shallowRef(initialValue) + + // getters + const double = computed(() => count.value * 2) + + // actions + function increment() { + count.value++ + } + + return { count, double, increment } +}, { injectionKey: CounterStoreKey }) +``` + +## Provide a custom default value + +```ts +// useCounterStore.ts +import { createInjectionState } from '@vueuse/core' +import { computed, shallowRef } from 'vue' + +const [useProvideCounterStore, useCounterStore] = createInjectionState((initialValue: number) => { + // state + const count = shallowRef(initialValue) + + // getters + const double = computed(() => count.value * 2) + + // actions + function increment() { + count.value++ + } + + return { count, double, increment } +}, { defaultValue: 0 }) +``` + +## Type Declarations + +```ts +export type CreateInjectionStateReturn< + Arguments extends Array, + Return, +> = Readonly< + [ + /** + * Call this function in a provider component to create and provide the state. + * + * @param args Arguments passed to the composable + * @returns The state returned by the composable + */ + useProvidingState: (...args: Arguments) => Return, + /** + * Call this function in a consumer component to inject the state. + * + * @returns The injected state, or `undefined` if not provided and no default value was set. + */ + useInjectedState: () => Return | undefined, + ] +> +export interface CreateInjectionStateOptions { + /** + * Custom injectionKey for InjectionState + */ + injectionKey?: string | InjectionKey + /** + * Default value for the InjectionState + */ + defaultValue?: Return +} +/** + * Create global state that can be injected into components. + * + * @see https://vueuse.org/createInjectionState + * + * @__NO_SIDE_EFFECTS__ + */ +export declare function createInjectionState< + Arguments extends Array, + Return, +>( + composable: (...args: Arguments) => Return, + options?: CreateInjectionStateOptions, +): CreateInjectionStateReturn +``` diff --git a/.agents/skills/vueuse-functions/references/createProjection.md b/.agents/skills/vueuse-functions/references/createProjection.md new file mode 100644 index 000000000..11bfcee2d --- /dev/null +++ b/.agents/skills/vueuse-functions/references/createProjection.md @@ -0,0 +1,31 @@ +--- +category: '@Math' +related: useProjection, createGenericProjection +--- + +# createProjection + +Reactive numeric projection from one domain to another. + +## Usage + +```ts +import { createProjection } from '@vueuse/math' + +const useProjector = createProjection([0, 10], [0, 100]) +const input = ref(0) +const projected = useProjector(input) // projected.value === 0 + +input.value = 5 // projected.value === 50 +input.value = 10 // projected.value === 100 +``` + +## Type Declarations + +```ts +export declare function createProjection( + fromDomain: MaybeRefOrGetter, + toDomain: MaybeRefOrGetter, + projector?: ProjectorFunction, +): UseProjection +``` diff --git a/.agents/skills/vueuse-functions/references/createRef.md b/.agents/skills/vueuse-functions/references/createRef.md new file mode 100644 index 000000000..07f0cac82 --- /dev/null +++ b/.agents/skills/vueuse-functions/references/createRef.md @@ -0,0 +1,54 @@ +--- +category: Reactivity +--- + +# createRef + +Returns a `deepRef` or `shallowRef` depending on the `deep` param. + +## Usage + +```ts +import { createRef } from '@vueuse/core' +import { isShallow, ref } from 'vue' + +const initialData = 1 + +const shallowData = createRef(initialData) +const deepData = createRef(initialData, true) + +isShallow(shallowData) // true +isShallow(deepData) // false +``` + +## Type Declarations + +```ts +export type CreateRefReturn< + T = any, + D extends boolean = false, +> = ShallowOrDeepRef +export type ShallowOrDeepRef< + T = any, + D extends boolean = false, +> = D extends true ? Ref : ShallowRef +/** + * Returns a `deepRef` or `shallowRef` depending on the `deep` param. + * + * @example createRef(1) // ShallowRef + * @example createRef(1, false) // ShallowRef + * @example createRef(1, true) // Ref + * @example createRef("string") // ShallowRef + * @example createRef<"A"|"B">("A", true) // Ref<"A"|"B"> + * + * @param value + * @param deep + * @returns the `deepRef` or `shallowRef` + * + * @__NO_SIDE_EFFECTS__ + */ +export declare function createRef( + value: T, + deep?: D, +): CreateRefReturn +``` diff --git a/.agents/skills/vueuse-functions/references/createReusableTemplate.md b/.agents/skills/vueuse-functions/references/createReusableTemplate.md new file mode 100644 index 000000000..4819471bf --- /dev/null +++ b/.agents/skills/vueuse-functions/references/createReusableTemplate.md @@ -0,0 +1,356 @@ +--- +category: Component +outline: deep +--- + +# createReusableTemplate + +Define and reuse template inside the component scope. + +## Motivation + +It's common to have the need to reuse some part of the template. For example: + +```vue + +``` + +We'd like to reuse our code as much as possible. So normally we might need to extract those duplicated parts into a component. However, in a separated component you lose the ability to access the local bindings. Defining props and emits for them can be tedious sometimes. + +So this function is made to provide a way for defining and reusing templates inside the component scope. + +## Usage + +In the previous example, we could refactor it to: + +```vue + + + +``` + +- `` will register the template and renders nothing. +- `` will render the template provided by ``. +- `` must be used before ``. + +> **Note**: It's recommended to extract as separate components whenever possible. Abusing this function might lead to bad practices for your codebase. + +### Options API + +When using with [Options API](https://vuejs.org/guide/introduction.html#api-styles), you will need to define `createReusableTemplate` outside of the component setup and pass to the `components` option in order to use them in the template. + +```vue + + + +``` + +### Passing Data + +You can also pass data to the template using slots: + +- Use `v-slot="..."` to access the data on `` +- Directly bind the data on `` to pass them to the template + +```vue + + + +``` + +### TypeScript Support + +`createReusableTemplate` accepts a generic type to provide type support for the data passed to the template: + +```vue + + + +``` + +Optionally, if you are not a fan of array destructuring, the following usages are also legal: + +```vue + + + +``` + +```vue + + + +``` + +::: warning +Passing boolean props without `v-bind` is not supported. See the [Caveats](#boolean-props) section for more details. +::: + +### Props and Attributes + +By default, all props and attributes passed to `` will be passed to the template. If you don't want certain props to be passed to the DOM, you need to define the runtime props: + +```ts +import { createReusableTemplate } from '@vueuse/core' + +const [DefineTemplate, ReuseTemplate] = createReusableTemplate({ + props: { + msg: String, + enable: Boolean, + } +}) +``` + +If you don't want to pass any props to the template, you can pass the `inheritAttrs` option: + +```ts +import { createReusableTemplate } from '@vueuse/core' + +const [DefineTemplate, ReuseTemplate] = createReusableTemplate({ + inheritAttrs: false, +}) +``` + +### Passing Slots + +It's also possible to pass slots back from ``. You can access the slots on `` from `$slots`: + +```vue + + + +``` + +## Caveats + +### Boolean props + +As opposed to Vue's behavior, props defined as `boolean` that were passed without `v-bind` or absent will be resolved into an empty string or `undefined` respectively: + +```vue + + + +``` + +## References + +This function is migrated from [vue-reuse-template](https://github.com/antfu/vue-reuse-template). + +Existing Vue discussions/issues about reusing template: + +- [Discussion on Reusing Templates](https://github.com/vuejs/core/discussions/6898) + +Alternative Approaches: + +- [Vue Macros - `namedTemplate`](https://vue-macros.sxzz.moe/features/named-template.html) +- [`unplugin-vue-reuse-template`](https://github.com/liulinboyi/unplugin-vue-reuse-template) + +## Type Declarations + +```ts +type ObjectLiteralWithPotentialObjectLiterals = Record< + string, + Record | undefined +> +type GenerateSlotsFromSlotMap< + T extends ObjectLiteralWithPotentialObjectLiterals, +> = { + [K in keyof T]: Slot +} +export type DefineTemplateComponent< + Bindings extends Record, + MapSlotNameToSlotProps extends ObjectLiteralWithPotentialObjectLiterals, +> = DefineComponent & { + new (): { + $slots: { + default: ( + _: Bindings & { + $slots: GenerateSlotsFromSlotMap + }, + ) => any + } + } +} +export type ReuseTemplateComponent< + Bindings extends Record, + MapSlotNameToSlotProps extends ObjectLiteralWithPotentialObjectLiterals, +> = DefineComponent & { + new (): { + $slots: GenerateSlotsFromSlotMap + } +} +export type ReusableTemplatePair< + Bindings extends Record, + MapSlotNameToSlotProps extends ObjectLiteralWithPotentialObjectLiterals, +> = [ + DefineTemplateComponent, + ReuseTemplateComponent, +] & { + define: DefineTemplateComponent + reuse: ReuseTemplateComponent +} +export interface CreateReusableTemplateOptions< + Props extends Record, +> { + /** + * Inherit attrs from reuse component. + * + * @default true + */ + inheritAttrs?: boolean + /** + * Props definition for reuse component. + */ + props?: ComponentObjectPropsOptions +} +/** + * This function creates `define` and `reuse` components in pair, + * It also allow to pass a generic to bind with type. + * + * @see https://vueuse.org/createReusableTemplate + * + * @__NO_SIDE_EFFECTS__ + */ +export declare function createReusableTemplate< + Bindings extends Record, + MapSlotNameToSlotProps extends ObjectLiteralWithPotentialObjectLiterals = Record<'default', undefined>, +>( + options?: CreateReusableTemplateOptions, +): ReusableTemplatePair +``` diff --git a/.agents/skills/vueuse-functions/references/createSharedComposable.md b/.agents/skills/vueuse-functions/references/createSharedComposable.md new file mode 100644 index 000000000..19e63088c --- /dev/null +++ b/.agents/skills/vueuse-functions/references/createSharedComposable.md @@ -0,0 +1,42 @@ +--- +category: State +related: createGlobalState +--- + +# createSharedComposable + +Make a composable function usable with multiple Vue instances. + +> [!WARNING] +> When used in a **SSR** environment, `createSharedComposable` will **automatically fallback** to a non-shared version. +> This means every call will create a fresh instance in SSR to avoid [cross-request state pollution](https://vuejs.org/guide/scaling-up/ssr.html#cross-request-state-pollution). + +## Usage + +```ts +import { createSharedComposable, useMouse } from '@vueuse/core' + +const useSharedMouse = createSharedComposable(useMouse) + +// CompA.vue +const { x, y } = useSharedMouse() + +// CompB.vue - will reuse the previous state and no new event listeners will be registered +const { x, y } = useSharedMouse() +``` + +## Type Declarations + +```ts +export type SharedComposableReturn = T +/** + * Make a composable function usable with multiple Vue instances. + * + * @see https://vueuse.org/createSharedComposable + * + * @__NO_SIDE_EFFECTS__ + */ +export declare function createSharedComposable( + composable: Fn, +): SharedComposableReturn +``` diff --git a/.agents/skills/vueuse-functions/references/createTemplatePromise.md b/.agents/skills/vueuse-functions/references/createTemplatePromise.md new file mode 100644 index 000000000..c27d6b4ce --- /dev/null +++ b/.agents/skills/vueuse-functions/references/createTemplatePromise.md @@ -0,0 +1,306 @@ +--- +category: Component +outline: deep +--- + +# createTemplatePromise + +Template as Promise. Useful for constructing custom Dialogs, Modals, Toasts, etc. + +## Usage + +```vue + + + +``` + +## Features + +- **Programmatic** - call your UI as a promise +- **Template** - use Vue template to render, not a new DSL +- **TypeScript** - full type safety via generic type +- **Renderless** - you take full control of the UI +- **Transition** - use support Vue transition + +This function is migrated from [vue-template-promise](https://github.com/antfu/vue-template-promise) + +## Usage + +`createTemplatePromise` returns a **Vue Component** that you can directly use in your template with ` + + + + +``` + +Learn more about [Vue Transition](https://vuejs.org/guide/built-ins/transition.html). + +### Slot Props + +The slot provides the following props: + +| Prop | Type | Description | +| ------------- | ---------------------------------------- | --------------------------------------------------------- | +| `promise` | `Promise \| undefined` | The current promise instance | +| `resolve` | `(v: Return \| Promise) => void` | Resolve the promise with a value | +| `reject` | `(v: any) => void` | Reject the promise | +| `args` | `Args` | Arguments passed to `start()` | +| `isResolving` | `boolean` | `true` when resolving another promise passed to `resolve` | +| `key` | `number` | Unique key for list rendering | + +```vue + +``` + +## Motivation + +The common approach to call a dialog or a modal programmatically would be like this: + +```ts +const dialog = useDialog() +const result = await dialog.open({ + title: 'Hello', + content: 'World', +}) +``` + +This would work by sending these information to the top-level component and let it render the dialog. However, it limits the flexibility you could express in the UI. For example, you could want the title to be red, or have extra buttons, etc. You would end up with a lot of options like: + +```ts +const result = await dialog.open({ + title: 'Hello', + titleClass: 'text-red', + content: 'World', + contentClass: 'text-blue text-sm', + buttons: [ + { text: 'OK', class: 'bg-red', onClick: () => {} }, + { text: 'Cancel', class: 'bg-blue', onClick: () => {} }, + ], + // ... +}) +``` + +Even this is not flexible enough. If you want more, you might end up with manual render function. + +```ts +const result = await dialog.open({ + title: 'Hello', + contentSlot: () => h(MyComponent, { content }), +}) +``` + +This is like reinventing a new DSL in the script to express the UI template. + +So this function allows **expressing the UI in templates instead of scripts**, where it is supposed to be, while still being able to be manipulated programmatically. + +## Type Declarations + +```ts +export interface TemplatePromiseProps { + /** + * The promise instance. + */ + promise: Promise | undefined + /** + * Resolve the promise. + */ + resolve: (v: Return | Promise) => void + /** + * Reject the promise. + */ + reject: (v: any) => void + /** + * Arguments passed to TemplatePromise.start() + */ + args: Args + /** + * Indicates if the promise is resolving. + * When passing another promise to `resolve`, this will be set to `true` until the promise is resolved. + */ + isResolving: boolean + /** + * Options passed to createTemplatePromise() + */ + options: TemplatePromiseOptions + /** + * Unique key for list rendering. + */ + key: number +} +export interface TemplatePromiseOptions { + /** + * Determines if the promise can be called only once at a time. + * + * @default false + */ + singleton?: boolean + /** + * Transition props for the promise. + */ + transition?: TransitionGroupProps +} +export type TemplatePromise< + Return, + Args extends any[] = [], +> = DefineComponent & { + new (): { + $slots: { + default: (_: TemplatePromiseProps) => any + } + } +} & { + start: (...args: Args) => Promise +} +/** + * Creates a template promise component. + * + * @see https://vueuse.org/createTemplatePromise + * + * @__NO_SIDE_EFFECTS__ + */ +export declare function createTemplatePromise( + options?: TemplatePromiseOptions, +): TemplatePromise +``` diff --git a/.agents/skills/vueuse-functions/references/createUnrefFn.md b/.agents/skills/vueuse-functions/references/createUnrefFn.md new file mode 100644 index 000000000..0335b8587 --- /dev/null +++ b/.agents/skills/vueuse-functions/references/createUnrefFn.md @@ -0,0 +1,51 @@ +--- +category: Utilities +related: reactify +--- + +# createUnrefFn + +Make a plain function accepting ref and raw values as arguments. +Returns the same value the unconverted function returns, with proper typing. + +::: tip +Make sure you're using the right tool for the job. Using `reactify` +might be more pertinent in some cases where you want to evaluate the function on each changes of it's arguments. +::: + +## Usage + +```ts +import { createUnrefFn } from '@vueuse/core' +import { shallowRef } from 'vue' + +const url = shallowRef('https://httpbin.org/post') +const data = shallowRef({ foo: 'bar' }) + +function post(url, data) { + return fetch(url, { data }) +} +const unrefPost = createUnrefFn(post) + +post(url, data) /* ❌ Will throw an error because the arguments are refs */ +unrefPost(url, data) /* ✔️ Will Work because the arguments will be auto unref */ +``` + +## Type Declarations + +```ts +export type UnrefFn = T extends (...args: infer A) => infer R + ? ( + ...args: { + [K in keyof A]: MaybeRef + } + ) => R + : never +/** + * Make a plain function accepting ref and raw values as arguments. + * Returns the same value the unconverted function returns, with proper typing. + * + * @__NO_SIDE_EFFECTS__ + */ +export declare function createUnrefFn(fn: T): UnrefFn +``` diff --git a/.agents/skills/vueuse-functions/references/extendRef.md b/.agents/skills/vueuse-functions/references/extendRef.md new file mode 100644 index 000000000..478eebb36 --- /dev/null +++ b/.agents/skills/vueuse-functions/references/extendRef.md @@ -0,0 +1,76 @@ +--- +category: Reactivity +--- + +# extendRef + +Add extra attributes to Ref. + +## Usage + +> Please note the extra attribute will not be accessible in Vue's template. + +```ts +import { extendRef } from '@vueuse/core' +import { shallowRef } from 'vue' + +const myRef = shallowRef('content') + +const extended = extendRef(myRef, { foo: 'extra data' }) + +extended.value === 'content' +extended.foo === 'extra data' +``` + +Refs will be unwrapped and be reactive + +```ts +import { extendRef } from '@vueuse/core' +// ---cut--- +const myRef = shallowRef('content') +const extraRef = shallowRef('extra') + +const extended = extendRef(myRef, { extra: extraRef }) + +extended.value === 'content' +extended.extra === 'extra' + +extended.extra = 'new data' // will trigger update +extraRef.value === 'new data' +``` + +## Type Declarations + +```ts +export type ExtendRefReturn = Ref +export interface ExtendRefOptions { + /** + * Is the extends properties enumerable + * + * @default false + */ + enumerable?: boolean + /** + * Unwrap for Ref properties + * + * @default true + */ + unwrap?: Unwrap +} +/** + * Overload 1: Unwrap set to false + */ +export declare function extendRef< + R extends Ref, + Extend extends object, + Options extends ExtendRefOptions, +>(ref: R, extend: Extend, options?: Options): ShallowUnwrapRef & R +/** + * Overload 2: Unwrap unset or set to true + */ +export declare function extendRef< + R extends Ref, + Extend extends object, + Options extends ExtendRefOptions, +>(ref: R, extend: Extend, options?: Options): Extend & R +``` diff --git a/.agents/skills/vueuse-functions/references/from.md b/.agents/skills/vueuse-functions/references/from.md new file mode 100644 index 000000000..81a80c2af --- /dev/null +++ b/.agents/skills/vueuse-functions/references/from.md @@ -0,0 +1,80 @@ +--- +category: '@RxJS' +--- + +# from / fromEvent + +Wrappers around RxJS's [`from()`](https://rxjs.dev/api/index/function/from) and [`fromEvent()`](https://rxjs.dev/api/index/function/fromEvent) to allow them to accept `ref`s. + +## Usage + + + +```ts no-twoslash +import { from, fromEvent, toObserver, useSubscription } from '@vueuse/rxjs' +import { interval } from 'rxjs' +import { map, mapTo, takeUntil, withLatestFrom } from 'rxjs/operators' +import { shallowRef, useTemplateRef } from 'vue' + +const count = shallowRef(0) +const button = useTemplateRef('buttonRef') + +useSubscription( + interval(1000) + .pipe( + mapTo(1), + takeUntil(fromEvent(button, 'click')), + withLatestFrom(from(count, { + immediate: true, + deep: false, + })), + map(([curr, total]) => curr + total), + ) + .subscribe(toObserver(count)), // same as ).subscribe(val => (count.value = val)) +) +``` + +## from + +The `from` function can accept either a standard RxJS `ObservableInput` or a Vue `ref`. When passed a ref, it creates an Observable that emits whenever the ref's value changes. + +### Watch Options + +When using `from` with a ref, you can pass Vue's `WatchOptions`: + +| Option | Type | Description | +| ----------- | --------------------------- | ---------------------------------- | +| `immediate` | `boolean` | Emit the current value immediately | +| `deep` | `boolean` | Deeply watch nested objects | +| `flush` | `'pre' \| 'post' \| 'sync'` | Timing of the callback flush | + +## fromEvent + +The `fromEvent` function extends RxJS's `fromEvent` to accept a ref to an element. When the ref's value changes (e.g., after the component mounts), it automatically subscribes to the new element. + +```ts no-twoslash +import { fromEvent, useSubscription } from '@vueuse/rxjs' +import { useTemplateRef } from 'vue' + +const button = useTemplateRef('buttonRef') + +// Will automatically subscribe when the button element becomes available +useSubscription( + fromEvent(button, 'click').subscribe(() => { + console.log('clicked!') + }) +) +``` + +## Type Declarations + +```ts +export declare function from( + value: ObservableInput | Ref, + watchOptions?: WatchOptions, +): Observable +export declare function fromEvent( + value: MaybeRef, + event: string, +): Observable +``` diff --git a/.agents/skills/vueuse-functions/references/get.md b/.agents/skills/vueuse-functions/references/get.md new file mode 100644 index 000000000..36971f522 --- /dev/null +++ b/.agents/skills/vueuse-functions/references/get.md @@ -0,0 +1,30 @@ +--- +category: Utilities +--- + +# get + +Shorthand for accessing `ref.value` + +## Usage + +```ts +import { get } from '@vueuse/core' + +const a = ref(42) + +console.log(get(a)) // 42 +``` + +## Type Declarations + +```ts +/** + * Shorthand for accessing `ref.value` + */ +export declare function get(ref: MaybeRef): T +export declare function get( + ref: MaybeRef, + key: K, +): T[K] +``` diff --git a/.agents/skills/vueuse-functions/references/injectLocal.md b/.agents/skills/vueuse-functions/references/injectLocal.md new file mode 100644 index 000000000..165acb30f --- /dev/null +++ b/.agents/skills/vueuse-functions/references/injectLocal.md @@ -0,0 +1,35 @@ +--- +category: State +--- + +# injectLocal + +Extended `inject` with ability to call `provideLocal` to provide the value in the same component. + +## Usage + +```vue + +``` + +## Type Declarations + +```ts +/** + * On the basis of `inject`, it is allowed to directly call inject to obtain the value after call provide in the same component. + * + * @example + * ```ts + * injectLocal('MyInjectionKey', 1) + * const injectedValue = injectLocal('MyInjectionKey') // injectedValue === 1 + * ``` + * + * @__NO_SIDE_EFFECTS__ + */ +export declare const injectLocal: typeof inject +``` diff --git a/.agents/skills/vueuse-functions/references/isDefined.md b/.agents/skills/vueuse-functions/references/isDefined.md new file mode 100644 index 000000000..d8a986664 --- /dev/null +++ b/.agents/skills/vueuse-functions/references/isDefined.md @@ -0,0 +1,31 @@ +--- +category: Utilities +--- + +# isDefined + +Non-nullish checking type guard for Ref. + +## Usage + +```ts +import { isDefined } from '@vueuse/core' + +const example = ref(Math.random() ? 'example' : undefined) // Ref + +if (isDefined(example)) + example // Ref +``` + +## Type Declarations + +```ts +export type IsDefinedReturn = boolean +export declare function isDefined( + v: ComputedRef, +): v is ComputedRef> +export declare function isDefined( + v: Ref, +): v is Ref> +export declare function isDefined(v: T): v is Exclude +``` diff --git a/.agents/skills/vueuse-functions/references/logicAnd.md b/.agents/skills/vueuse-functions/references/logicAnd.md new file mode 100644 index 000000000..4b4a6ce93 --- /dev/null +++ b/.agents/skills/vueuse-functions/references/logicAnd.md @@ -0,0 +1,40 @@ +--- +category: '@Math' +alias: and +related: logicNot, logicOr +--- + +# logicAnd + +`AND` condition for refs. + +## Usage + +```ts +import { whenever } from '@vueuse/core' +import { logicAnd } from '@vueuse/math' + +const a = ref(true) +const b = ref(false) + +whenever(logicAnd(a, b), () => { + console.log('both a and b are now truthy!') +}) +``` + +## Type Declarations + +```ts +/** + * `AND` conditions for refs. + * + * @see https://vueuse.org/logicAnd + * + * @__NO_SIDE_EFFECTS__ + */ +export declare function logicAnd( + ...args: MaybeRefOrGetter[] +): ComputedRef +/** @deprecated use `logicAnd` instead */ +export declare const and: typeof logicAnd +``` diff --git a/.agents/skills/vueuse-functions/references/logicNot.md b/.agents/skills/vueuse-functions/references/logicNot.md new file mode 100644 index 000000000..b5b324c9e --- /dev/null +++ b/.agents/skills/vueuse-functions/references/logicNot.md @@ -0,0 +1,36 @@ +--- +category: '@Math' +alias: not +--- + +# logicNot + +`NOT` condition for ref. + +## Usage + +```ts +import { whenever } from '@vueuse/core' +import { logicNot } from '@vueuse/math' + +const a = ref(true) + +whenever(logicNot(a), () => { + console.log('a is now falsy!') +}) +``` + +## Type Declarations + +```ts +/** + * `NOT` conditions for refs. + * + * @see https://vueuse.org/logicNot + * + * @__NO_SIDE_EFFECTS__ + */ +export declare function logicNot(v: MaybeRefOrGetter): ComputedRef +/** @deprecated use `logicNot` instead */ +export declare const not: typeof logicNot +``` diff --git a/.agents/skills/vueuse-functions/references/logicOr.md b/.agents/skills/vueuse-functions/references/logicOr.md new file mode 100644 index 000000000..4fa8bb1cb --- /dev/null +++ b/.agents/skills/vueuse-functions/references/logicOr.md @@ -0,0 +1,40 @@ +--- +category: '@Math' +alias: or +related: logicAnd, logicNot +--- + +# logicOr + +`OR` conditions for refs. + +## Usage + +```ts +import { whenever } from '@vueuse/core' +import { logicOr } from '@vueuse/math' + +const a = ref(true) +const b = ref(false) + +whenever(logicOr(a, b), () => { + console.log('either a or b is truthy!') +}) +``` + +## Type Declarations + +```ts +/** + * `OR` conditions for refs. + * + * @see https://vueuse.org/logicOr + * + * @__NO_SIDE_EFFECTS__ + */ +export declare function logicOr( + ...args: MaybeRefOrGetter[] +): ComputedRef +/** @deprecated use `logicOr` instead */ +export declare const or: typeof logicOr +``` diff --git a/.agents/skills/vueuse-functions/references/makeDestructurable.md b/.agents/skills/vueuse-functions/references/makeDestructurable.md new file mode 100644 index 000000000..261d42357 --- /dev/null +++ b/.agents/skills/vueuse-functions/references/makeDestructurable.md @@ -0,0 +1,41 @@ +--- +category: Utilities +--- + +# makeDestructurable + +Make isomorphic destructurable for object and array at the same time. See [this blog](https://antfu.me/posts/destructuring-with-object-or-array/) for more details. + +## Usage + +TypeScript Example: + +```ts twoslash include main +import { makeDestructurable } from '@vueuse/core' + +const foo = { name: 'foo' } +const bar = 1024 + +const obj = makeDestructurable( + { foo, bar } as const, + [foo, bar] as const, +) +``` + +Usage: + +```ts twoslash +// @include: main +// ---cut--- +let { foo, bar } = obj +let [foo, bar] = obj +``` + +## Type Declarations + +```ts +export declare function makeDestructurable< + T extends Record, + A extends readonly any[], +>(obj: T, arr: A): T & A +``` diff --git a/.agents/skills/vueuse-functions/references/onClickOutside.md b/.agents/skills/vueuse-functions/references/onClickOutside.md new file mode 100644 index 000000000..5ac6ec100 --- /dev/null +++ b/.agents/skills/vueuse-functions/references/onClickOutside.md @@ -0,0 +1,228 @@ +--- +category: Sensors +--- + +# onClickOutside + +Listen for clicks outside of an element. Useful for modals or dropdowns. + +## Usage + +```vue + + + +``` + +### Return Value + +By default, `onClickOutside` returns a `stop` function to remove the event listeners. + +```ts +const stop = onClickOutside(target, handler) + +// Later, stop listening +stop() +``` + +### Controls + +If you need more control over triggering the handler, you can use the `controls` option. This returns an object with `stop`, `cancel`, and `trigger` functions. + +```ts +const { stop, cancel, trigger } = onClickOutside( + modalRef, + (event) => { + modal.value = false + }, + { controls: true }, +) + +// cancel prevents the next click from triggering the handler +cancel() + +// trigger manually fires the handler +trigger(event) + +// stop removes all event listeners +stop() +``` + +### Ignore Elements + +Use the `ignore` option to prevent certain elements from triggering the handler. Provide elements as an array of Refs or CSS selectors. + +```ts +const ignoreElRef = useTemplateRef('ignoreEl') + +onClickOutside( + target, + event => console.log(event), + { ignore: [ignoreElRef, '.ignore-class', '#ignore-id'] }, +) +``` + +### Capture Phase + +By default, the event listener uses the capture phase (`capture: true`). Set `capture: false` to use the bubbling phase instead. + +```ts +onClickOutside(target, handler, { capture: false }) +``` + +### Detect Iframe Clicks + +Clicks inside an iframe are not detected by default. Enable `detectIframe` to also trigger the handler when focus moves to an iframe. + +```ts +onClickOutside(target, handler, { detectIframe: true }) +``` + +## Component Usage + +```vue + +``` + +## Directive Usage + +```vue + + + +``` + +You can also set the handler as an array to set the configuration items of the instruction. + +```vue + + + +``` + +## Type Declarations + +```ts +export interface OnClickOutsideOptions< + Controls extends boolean = false, +> extends ConfigurableWindow { + /** + * List of elements that should not trigger the event, + * provided as Refs or CSS Selectors. + */ + ignore?: MaybeRefOrGetter<(MaybeElementRef | string)[]> + /** + * Use capturing phase for internal event listener. + * @default true + */ + capture?: boolean + /** + * Run handler function if focus moves to an iframe. + * @default false + */ + detectIframe?: boolean + /** + * Use controls to cancel/trigger listener. + * @default false + */ + controls?: Controls +} +export type OnClickOutsideHandler< + T extends OnClickOutsideOptions = OnClickOutsideOptions, +> = ( + event: + | (T['detectIframe'] extends true ? FocusEvent : never) + | (T['controls'] extends true ? Event : never) + | PointerEvent, +) => void +export type OnClickOutsideReturn + = Controls extends false + ? Fn + : { + stop: Fn + cancel: Fn + trigger: (event: Event) => void + } +/** + * Listen for clicks outside of an element. + * + * @see https://vueuse.org/onClickOutside + * @param target + * @param handler + * @param options + */ +export declare function onClickOutside( + target: MaybeComputedElementRef, + handler: OnClickOutsideHandler, + options?: T, +): Fn +export declare function onClickOutside>( + target: MaybeComputedElementRef, + handler: OnClickOutsideHandler, + options: T, +): { + stop: Fn + cancel: Fn + trigger: (event: Event) => void +} +``` diff --git a/.agents/skills/vueuse-functions/references/onElementRemoval.md b/.agents/skills/vueuse-functions/references/onElementRemoval.md new file mode 100644 index 000000000..ec4f523cc --- /dev/null +++ b/.agents/skills/vueuse-functions/references/onElementRemoval.md @@ -0,0 +1,88 @@ +--- +category: Sensors +--- + +# onElementRemoval + +Fires when the element or any element containing it is removed from the DOM. + +## Usage + +```vue {13} + + + +``` + +### Callback with Mutation Records + +The callback receives an array of `MutationRecord` objects that triggered the removal. + +```ts +import { onElementRemoval } from '@vueuse/core' + +onElementRemoval(targetRef, (mutationRecords) => { + console.log('Element removed', mutationRecords) +}) +``` + +### Return Value + +Returns a stop function to stop observing. + +```ts +const stop = onElementRemoval(targetRef, callback) + +// Later, stop observing +stop() +``` + +## Type Declarations + +```ts +export interface OnElementRemovalOptions + extends + ConfigurableWindow, + ConfigurableDocumentOrShadowRoot, + WatchOptionsBase {} +/** + * Fires when the element or any element containing it is removed. + * + * @param target + * @param callback + * @param options + */ +export declare function onElementRemoval( + target: MaybeElementRef, + callback: (mutationRecords: MutationRecord[]) => void, + options?: OnElementRemovalOptions, +): Fn +``` diff --git a/.agents/skills/vueuse-functions/references/onKeyStroke.md b/.agents/skills/vueuse-functions/references/onKeyStroke.md new file mode 100644 index 000000000..f71dcc0d4 --- /dev/null +++ b/.agents/skills/vueuse-functions/references/onKeyStroke.md @@ -0,0 +1,211 @@ +--- +category: Sensors +--- + +# onKeyStroke + +Listen for keyboard keystrokes. By default, listens on `keydown` events on `window`. + +## Usage + +```ts +import { onKeyStroke } from '@vueuse/core' + +onKeyStroke('ArrowDown', (e) => { + e.preventDefault() +}) +``` + +See [this table](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values) for all key codes. + +### Return Value + +Returns a stop function to remove the event listener. + +```ts +const stop = onKeyStroke('Escape', handler) + +// Later, stop listening +stop() +``` + +### Listen To Multiple Keys + +```ts +import { onKeyStroke } from '@vueuse/core' + +onKeyStroke(['s', 'S', 'ArrowDown'], (e) => { + e.preventDefault() +}) + +// listen to all keys by passing `true` or skipping the key parameter +onKeyStroke(true, (e) => { + e.preventDefault() +}) +onKeyStroke((e) => { + e.preventDefault() +}) +``` + +### Custom Key Predicate + +You can pass a custom function to determine which keys should trigger the handler. + +```ts +import { onKeyStroke } from '@vueuse/core' + +onKeyStroke( + e => e.key === 'A' && e.shiftKey, + (e) => { + console.log('Shift+A pressed') + }, +) +``` + +### Custom Event Target + +```ts +import { onKeyStroke } from '@vueuse/core' + +onKeyStroke('A', (e) => { + console.log('Key A pressed on document') +}, { target: document }) +``` + +### Ignore Repeated Events + +The callback will trigger only once when pressing `A` and **holding down**. The `dedupe` option can also be a reactive ref. + +```ts +import { onKeyStroke } from '@vueuse/core' + +onKeyStroke('A', (e) => { + console.log('Key A pressed') +}, { dedupe: true }) +``` + +Reference: [KeyboardEvent.repeat](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/repeat) + +### Passive Mode + +Set `passive: true` to use a passive event listener. + +```ts +import { onKeyStroke } from '@vueuse/core' + +onKeyStroke('A', handler, { passive: true }) +``` + +## Directive Usage + +```vue + + + +``` + +### Custom Keyboard Event + +```ts +import { onKeyStroke } from '@vueuse/core' +// ---cut--- +onKeyStroke('Shift', (e) => { + console.log('Shift key up') +}, { eventName: 'keyup' }) +``` + +Or + +```ts +import { onKeyUp } from '@vueuse/core' +// ---cut--- +onKeyUp('Shift', () => console.log('Shift key up')) +``` + +## Shorthands + +- `onKeyDown` - alias for `onKeyStroke(key, handler, {eventName: 'keydown'})` +- `onKeyPressed` - alias for `onKeyStroke(key, handler, {eventName: 'keypress'})` +- `onKeyUp` - alias for `onKeyStroke(key, handler, {eventName: 'keyup'})` + +## Type Declarations + +```ts +export type KeyPredicate = (event: KeyboardEvent) => boolean +export type KeyFilter = true | string | string[] | KeyPredicate +export type KeyStrokeEventName = 'keydown' | 'keypress' | 'keyup' +export interface OnKeyStrokeOptions { + eventName?: KeyStrokeEventName + target?: MaybeRefOrGetter + passive?: boolean + /** + * Set to `true` to ignore repeated events when the key is being held down. + * + * @default false + */ + dedupe?: MaybeRefOrGetter +} +/** + * Listen for keyboard keystrokes. + * + * @see https://vueuse.org/onKeyStroke + */ +export declare function onKeyStroke( + key: KeyFilter, + handler: (event: KeyboardEvent) => void, + options?: OnKeyStrokeOptions, +): () => void +export declare function onKeyStroke( + handler: (event: KeyboardEvent) => void, + options?: OnKeyStrokeOptions, +): () => void +/** + * Listen to the keydown event of the given key. + * + * @see https://vueuse.org/onKeyStroke + * @param key + * @param handler + * @param options + */ +export declare function onKeyDown( + key: KeyFilter, + handler: (event: KeyboardEvent) => void, + options?: Omit, +): () => void +/** + * Listen to the keypress event of the given key. + * + * @see https://vueuse.org/onKeyStroke + * @param key + * @param handler + * @param options + */ +export declare function onKeyPressed( + key: KeyFilter, + handler: (event: KeyboardEvent) => void, + options?: Omit, +): () => void +/** + * Listen to the keyup event of the given key. + * + * @see https://vueuse.org/onKeyStroke + * @param key + * @param handler + * @param options + */ +export declare function onKeyUp( + key: KeyFilter, + handler: (event: KeyboardEvent) => void, + options?: Omit, +): () => void +``` diff --git a/.agents/skills/vueuse-functions/references/onLongPress.md b/.agents/skills/vueuse-functions/references/onLongPress.md new file mode 100644 index 000000000..93fa8face --- /dev/null +++ b/.agents/skills/vueuse-functions/references/onLongPress.md @@ -0,0 +1,229 @@ +--- +category: Sensors +--- + +# onLongPress + +Listen for a long press on an element. Returns a stop function. + +## Usage + +```vue + + + +``` + +### Custom Delay + +By default, the handler fires after 500ms. You can customize this with the `delay` option. It can be a number or a function that receives the `PointerEvent`. + +```ts +import { onLongPress } from '@vueuse/core' + +// Fixed delay +onLongPress(target, handler, { delay: 1000 }) + +// Dynamic delay based on event +onLongPress(target, handler, { + delay: ev => ev.pointerType === 'touch' ? 800 : 500, +}) +``` + +### Distance Threshold + +The long press will be canceled if the pointer moves more than the threshold (default: 10 pixels). Set to `false` to disable movement detection. + +```ts +import { onLongPress } from '@vueuse/core' + +// Custom threshold +onLongPress(target, handler, { distanceThreshold: 20 }) + +// Disable movement detection +onLongPress(target, handler, { distanceThreshold: false }) +``` + +### On Mouse Up Callback + +You can provide an `onMouseUp` callback to be notified when the pointer is released. + +```ts +import { onLongPress } from '@vueuse/core' + +onLongPress(target, handler, { + onMouseUp(duration, distance, isLongPress) { + console.log(`Held for ${duration}ms, moved ${distance}px, long press: ${isLongPress}`) + }, +}) +``` + +### Modifiers + +The following modifiers are available: + +| Modifier | Description | +| --------- | -------------------------------------------- | +| `stop` | Calls `event.stopPropagation()` | +| `once` | Removes event listener after first trigger | +| `prevent` | Calls `event.preventDefault()` | +| `capture` | Uses capture mode for event listener | +| `self` | Only trigger if target is the element itself | + +```ts +onLongPress(target, handler, { + modifiers: { + prevent: true, + stop: true, + }, +}) +``` + +## Component Usage + +```vue + + + +``` + +## Directive Usage + +```vue + + + +``` + +## Type Declarations + +```ts +export interface OnLongPressOptions { + /** + * Time in ms till `longpress` gets called + * + * @default 500 + */ + delay?: number | ((ev: PointerEvent) => number) + modifiers?: OnLongPressModifiers + /** + * Allowance of moving distance in pixels, + * The action will get canceled When moving too far from the pointerdown position. + * @default 10 + */ + distanceThreshold?: number | false + /** + * Function called when the ref element is released. + * @param duration how long the element was pressed in ms + * @param distance distance from the pointerdown position + * @param isLongPress whether the action was a long press or not + */ + onMouseUp?: (duration: number, distance: number, isLongPress: boolean) => void +} +export interface OnLongPressModifiers { + stop?: boolean + once?: boolean + prevent?: boolean + capture?: boolean + self?: boolean +} +export type OnLongPressReturn = () => void +/** @deprecated use {@link OnLongPressReturn} instead */ +export type UseOnLongPressReturn = OnLongPressReturn +export declare function onLongPress( + target: MaybeElementRef, + handler: (evt: PointerEvent) => void, + options?: OnLongPressOptions, +): OnLongPressReturn +``` diff --git a/.agents/skills/vueuse-functions/references/onStartTyping.md b/.agents/skills/vueuse-functions/references/onStartTyping.md new file mode 100644 index 000000000..d7527b588 --- /dev/null +++ b/.agents/skills/vueuse-functions/references/onStartTyping.md @@ -0,0 +1,53 @@ +--- +category: Sensors +--- + +# onStartTyping + +Fires when users start typing on non-editable elements. Useful for auto-focusing an input field when the user starts typing anywhere on the page. + +## Usage + +```vue + + + +``` + +## How It Works + +The callback only fires when: + +- No editable element (``, `