Compare commits

..
Author SHA1 Message Date
zooqueenandgithub-actions[bot] a7f14d69c4 chore: bump auth version to patch 2026-02-18 05:03:45 +00:00
9100 changed files with 385652 additions and 201220 deletions
+11
View File
@@ -0,0 +1,11 @@
{
"$schema": "https://unpkg.com/@changesets/config@2.3.0/schema.json",
"changelog": ["@changesets/changelog-github", { "repo": "shadcn-ui/ui" }],
"commit": false,
"fixed": [],
"linked": [],
"access": "public",
"baseBranch": "main",
"updateInternalDependencies": "patch",
"ignore": ["v4", "tests"]
}
+17
View File
@@ -0,0 +1,17 @@
{
"permissions": {
"allow": [
"Bash(git add:*)",
"Bash(git commit:*)",
"Bash(git push:*)",
"Bash(pnpm registry:build:*)",
"Bash(pnpm build:*)",
"Bash(pnpm add:*)",
"Bash(pnpm dev)",
"Bash(jq:*)",
"Bash(curl:*)"
],
"deny": [],
"ask": []
}
}
-3
View File
@@ -1,3 +0,0 @@
{
"extends": ["@commitlint/config-conventional"]
}
+12
View File
@@ -0,0 +1,12 @@
// ORIGINALLY FROM CLOUDFLARE WRANGLER:
// https://github.com/cloudflare/wrangler2/blob/main/.github/changeset-version.js
import { execSync } from "child_process"
// This script is used by the `release.yml` workflow to update the version of the packages being released.
// The standard step is only to run `changeset version` but this does not update the pnpm-lock.yaml file.
// So we also run `pnpm install`, which does this update.
// This is a workaround until this is handled automatically by `changeset version`.
// See https://github.com/changesets/changesets/issues/421.
execSync("npx changeset version", { stdio: "inherit" })
execSync("pnpm install --lockfile-only", { stdio: "inherit" })
-40
View File
@@ -4,43 +4,3 @@ updates:
directory: "/"
schedule:
interval: "weekly"
- package-ecosystem: "npm"
directory: "/templates/astro-app"
schedule:
interval: "weekly"
- package-ecosystem: "npm"
directory: "/templates/astro-monorepo"
schedule:
interval: "weekly"
- package-ecosystem: "npm"
directory: "/templates/next-app"
schedule:
interval: "weekly"
- package-ecosystem: "npm"
directory: "/templates/next-monorepo"
schedule:
interval: "weekly"
- package-ecosystem: "npm"
directory: "/templates/react-router-app"
schedule:
interval: "weekly"
- package-ecosystem: "npm"
directory: "/templates/react-router-monorepo"
schedule:
interval: "weekly"
- package-ecosystem: "npm"
directory: "/templates/start-app"
schedule:
interval: "weekly"
- package-ecosystem: "npm"
directory: "/templates/start-monorepo"
schedule:
interval: "weekly"
- package-ecosystem: "npm"
directory: "/templates/vite-app"
schedule:
interval: "weekly"
- package-ecosystem: "npm"
directory: "/templates/vite-monorepo"
schedule:
interval: "weekly"
-9
View File
@@ -1,9 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1280" height="640" viewBox="0 0 1280 640" role="img" aria-label="ui">
<rect width="1280" height="640" fill="#0A0A0A"/>
<svg x="96" y="215" width="210" height="210" viewBox="0 0 67 67"><path d="M22.21 67V44.6369H0V67H22.21Z" fill="#fff"/><path d="M66.7038 22.3184H22.2534L0.0878906 44.6367H44.4634L66.7038 22.3184Z" fill="#fff"/><path d="M22.21 0H0V22.3184H22.21V0Z" fill="#fff"/><path d="M66.7198 0H44.5098V22.3184H66.7198V0Z" fill="#fff"/><path d="M66.7198 67V44.6369H44.5098V67H66.7198Z" fill="#fff"/></svg>
<text x="378" y="276" font-family="Inter,system-ui,-apple-system,sans-serif" font-size="78" font-weight="800" letter-spacing="-2" fill="#ffffff">ui</text>
<text x="378" y="322" font-family="Inter,system-ui,sans-serif" font-size="30" fill="#ffffff" opacity=".66">React component library for AI applications</text>
<rect x="378" y="338" width="806" height="3" rx="1.5" fill="#ffffff" opacity=".9"/>
<text x="378" y="390" font-family="Inter,system-ui,sans-serif" font-size="24" font-weight="600" fill="#ffffff" opacity=".5">github.com/hanzoai</text>
<text x="1184" y="390" text-anchor="end" font-family="Inter,system-ui,sans-serif" font-size="24" font-weight="600" fill="#ffffff" opacity=".5">hanzo.ai</text>
</svg>

Before

Width:  |  Height:  |  Size: 1.2 KiB

+1 -1
View File
@@ -4,7 +4,7 @@
import { exec } from "child_process"
import fs from "fs"
const pkgJsonPath = "pkgs/shadcn/package.json"
const pkgJsonPath = "pkg/cli/package.json"
try {
const pkg = JSON.parse(fs.readFileSync(pkgJsonPath))
exec("git rev-parse --short HEAD", (err, stdout) => {
+1 -1
View File
@@ -4,7 +4,7 @@
import { exec } from "child_process"
import fs from "fs"
const pkgJsonPath = "pkgs/shadcn/package.json"
const pkgJsonPath = "pkg/cli/package.json"
try {
const pkg = JSON.parse(fs.readFileSync(pkgJsonPath))
exec("git rev-parse --short HEAD", (err, stdout) => {
+261
View File
@@ -0,0 +1,261 @@
name: CI
on:
push:
branches:
- main
- develop
pull_request:
branches:
- main
- develop
workflow_dispatch:
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
lint:
name: Lint
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: 20
- name: Setup pnpm
uses: pnpm/action-setup@v3
with:
version: 9
- name: Get pnpm store directory
shell: bash
run: |
echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV
- name: Setup pnpm cache
uses: actions/cache@v4
with:
path: ${{ env.STORE_PATH }}
key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}
restore-keys: |
${{ runner.os }}-pnpm-store-
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Run linting
run: pnpm run lint
typecheck:
name: Type Check
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: 20
- name: Setup pnpm
uses: pnpm/action-setup@v3
with:
version: 9
- name: Get pnpm store directory
shell: bash
run: |
echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV
- name: Setup pnpm cache
uses: actions/cache@v4
with:
path: ${{ env.STORE_PATH }}
key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}
restore-keys: |
${{ runner.os }}-pnpm-store-
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Build UI package
run: cd pkg/ui && pnpm run build
- name: Run type checking
run: |
cd app && pnpm run typecheck
cd ../pkg/ui && pnpm run tc --noEmit
build:
name: Build
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: 20
- name: Setup pnpm
uses: pnpm/action-setup@v3
with:
version: 9
- name: Get pnpm store directory
shell: bash
run: |
echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV
- name: Setup pnpm cache
uses: actions/cache@v4
with:
path: ${{ env.STORE_PATH }}
key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}
restore-keys: |
${{ runner.os }}-pnpm-store-
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Build UI package
run: cd pkg/ui && pnpm run build:full
- name: Build app
run: cd app && pnpm run build
env:
NEXT_PUBLIC_APP_URL: https://ui.hanzo.ai
- name: Upload build artifacts
uses: actions/upload-artifact@v4
with:
name: build-artifacts
path: |
app/.next
pkg/ui/dist
test:
name: Test
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: 20
- name: Setup pnpm
uses: pnpm/action-setup@v3
with:
version: 9
- name: Get pnpm store directory
shell: bash
run: |
echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV
- name: Setup pnpm cache
uses: actions/cache@v4
with:
path: ${{ env.STORE_PATH }}
key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}
restore-keys: |
${{ runner.os }}-pnpm-store-
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Run pkg/ui tests
run: cd pkg/ui && pnpm test -- --run
- name: Run app tests
run: |
if [ -f "app/package.json" ] && grep -q '"test"' app/package.json 2>/dev/null; then
cd app && pnpm test || echo "No tests configured"
else
echo "No test script found"
fi
- name: Upload coverage
if: always()
uses: codecov/codecov-action@v3
with:
files: ./pkg/ui/coverage/lcov.info
flags: unit
deploy-preview:
name: Deploy Preview
runs-on: ubuntu-latest
needs: [lint, typecheck, build]
if: github.event_name == 'pull_request'
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: 20
- name: Setup pnpm
uses: pnpm/action-setup@v3
with:
version: 9
- name: Install Vercel CLI
run: npm install --global vercel@latest
- name: Pull Vercel Environment Information
run: vercel pull --yes --environment=preview --token=${{ secrets.VERCEL_TOKEN }}
env:
VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }}
VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }}
- name: Build Project Artifacts
run: vercel build --token=${{ secrets.VERCEL_TOKEN }}
- name: Deploy Project Artifacts to Vercel
id: deploy
run: |
url=$(vercel deploy --prebuilt --token=${{ secrets.VERCEL_TOKEN }})
echo "preview_url=$url" >> $GITHUB_OUTPUT
- name: Comment PR with preview URL
if: github.event_name == 'pull_request'
uses: actions/github-script@v7
with:
script: |
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: '🚀 Preview deployed to: ${{ steps.deploy.outputs.preview_url }}'
})
status:
name: CI Status
runs-on: ubuntu-latest
needs: [lint, typecheck, build, test]
if: always()
steps:
- name: Check status
run: |
if [ "${{ needs.lint.result }}" != "success" ] || \
[ "${{ needs.typecheck.result }}" != "success" ] || \
[ "${{ needs.build.result }}" != "success" ] || \
[ "${{ needs.test.result }}" != "success" ]; then
echo "CI checks failed"
exit 1
else
echo "All CI checks passed!"
fi
-9
View File
@@ -1,9 +0,0 @@
name: CI/CD
on:
push: { branches: [main], tags: ["v*"] }
pull_request:
workflow_dispatch:
jobs:
cicd:
uses: hanzoai/ci/.github/workflows/build.yml@v1
secrets: inherit
+116
View File
@@ -0,0 +1,116 @@
name: Code check
on:
pull_request:
branches: ["*"]
jobs:
lint:
runs-on: ubuntu-latest
name: pnpm lint
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Install Node.js
uses: actions/setup-node@v3
with:
node-version: 20
- uses: pnpm/action-setup@v2.2.4
name: Install pnpm
id: pnpm-install
with:
version: 8.6.1
run_install: false
- name: Get pnpm store directory
id: pnpm-cache
run: |
echo "pnpm_cache_dir=$(pnpm store path)" >> $GITHUB_OUTPUT
- uses: actions/cache@v3
name: Setup pnpm cache
with:
path: ${{ steps.pnpm-cache.outputs.pnpm_cache_dir }}
key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}
restore-keys: |
${{ runner.os }}-pnpm-store-
- name: Install dependencies
run: pnpm install
#- run: pnpm lint
format:
runs-on: ubuntu-latest
name: pnpm format:check
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Install Node.js
uses: actions/setup-node@v3
with:
node-version: 20
- uses: pnpm/action-setup@v2.2.4
name: Install pnpm
id: pnpm-install
with:
version: 8.6.1
run_install: false
- name: Get pnpm store directory
id: pnpm-cache
run: |
echo "pnpm_cache_dir=$(pnpm store path)" >> $GITHUB_OUTPUT
- uses: actions/cache@v3
name: Setup pnpm cache
with:
path: ${{ steps.pnpm-cache.outputs.pnpm_cache_dir }}
key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}
restore-keys: |
${{ runner.os }}-pnpm-store-
- name: Install dependencies
run: pnpm install
- run: pnpm format:check
tsc:
runs-on: ubuntu-latest
name: pnpm typecheck
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Install Node.js
uses: actions/setup-node@v3
with:
node-version: 20
- uses: pnpm/action-setup@v2.2.4
name: Install pnpm
id: pnpm-install
with:
version: 8.6.1
run_install: false
- name: Get pnpm store directory
id: pnpm-cache
run: |
echo "pnpm_cache_dir=$(pnpm store path)" >> $GITHUB_OUTPUT
- uses: actions/cache@v3
name: Setup pnpm cache
with:
path: ${{ steps.pnpm-cache.outputs.pnpm_cache_dir }}
key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}
restore-keys: |
${{ runner.os }}-pnpm-store-
- name: Install dependencies
run: pnpm install
- run: pnpm typecheck
+60
View File
@@ -0,0 +1,60 @@
name: Test Coverage
on:
push:
branches: [main, develop]
pull_request:
branches: [main, develop]
jobs:
coverage:
name: Test Coverage
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: 20
- name: Setup pnpm
uses: pnpm/action-setup@v3
with:
version: 9
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Run tests with coverage
run: cd pkg/ui && pnpm test:coverage
- name: Upload coverage to Codecov
uses: codecov/codecov-action@v3
with:
files: ./pkg/ui/coverage/lcov.info
flags: unit
name: hanzo-ui-coverage
- name: Comment PR with coverage
if: github.event_name == 'pull_request'
uses: actions/github-script@v7
with:
script: |
const fs = require('fs');
const coverage = JSON.parse(fs.readFileSync('./pkg/ui/coverage/coverage-summary.json', 'utf8'));
const total = coverage.total;
const comment = `## Test Coverage Report\n\n` +
`Lines: ${total.lines.pct}%\n` +
`Statements: ${total.statements.pct}%\n` +
`Functions: ${total.functions.pct}%\n` +
`Branches: ${total.branches.pct}%`;
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: comment
});
+96
View File
@@ -0,0 +1,96 @@
name: Deploy to GitHub Pages
on:
push:
branches: [main]
workflow_dispatch:
inputs:
capture_screenshots:
description: 'Capture component screenshots (slow, optional)'
required: false
type: boolean
default: false
permissions:
contents: read
pages: write
id-token: write
concurrency:
group: "pages"
cancel-in-progress: false
jobs:
build:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: "20"
- name: Setup pnpm
uses: pnpm/action-setup@v3
with:
version: 9
- name: Get pnpm store directory
shell: bash
run: |
echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV
- name: Setup pnpm cache
uses: actions/cache@v4
with:
path: ${{ env.STORE_PATH }}
key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}
restore-keys: |
${{ runner.os }}-pnpm-store-
- name: Install dependencies
run: |
pnpm install --frozen-lockfile
- name: Build @hanzo/ui package
run: |
cd pkg/ui && pnpm build
- name: Capture screenshots (optional)
if: github.event.inputs.capture_screenshots == 'true'
working-directory: ./app
run: pnpm capture:registry
timeout-minutes: 5
- name: Build documentation
working-directory: ./app
run: |
pnpm build
touch out/.nojekyll
env:
NODE_ENV: production
GITHUB_ACTIONS: true
NEXT_PUBLIC_APP_URL: https://ui.hanzo.ai
SKIP_SCREENSHOTS: true
- name: Setup Pages
uses: actions/configure-pages@v4
- name: Upload artifact
uses: actions/upload-pages-artifact@v3
with:
path: ./app/out
deploy:
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
runs-on: ubuntu-latest
needs: build
steps:
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v4
+78
View File
@@ -0,0 +1,78 @@
name: Deprecated
on:
pull_request_target:
types: [opened, synchronize]
permissions:
issues: write
contents: read
pull-requests: write
jobs:
deprecated:
runs-on: ubuntu-latest
steps:
- name: Checkout PR
uses: actions/checkout@v4
with:
ref: ${{ github.event.pull_request.head.sha }}
fetch-depth: 0
- name: Get changed files
id: changed-files
uses: tj-actions/changed-files@v46
with:
files: |
apps/www/**
files_ignore: |
apps/www/public/r/**
base_sha: ${{ github.event.pull_request.base.sha }}
sha: ${{ github.event.pull_request.head.sha }}
- name: Comment on PR if www files changed
if: steps.changed-files.outputs.any_changed == 'true'
uses: actions/github-script@v7
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
const changedFiles = `${{ steps.changed-files.outputs.all_changed_files }}`.split(' ');
const wwwFiles = changedFiles.filter(file =>
file.startsWith('apps/www/') &&
!file.startsWith('apps/www/public/r/') &&
file !== 'apps/www/package.json'
);
if (wwwFiles.length > 0) {
const comment = `Looks like this PR modifies files in \`apps/www\`, which is deprecated.
Consider applying the change to \`apps/v4\` if relevant.`;
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body: comment
});
// Add deprecated label
await github.rest.issues.addLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
labels: ['deprecated']
});
} else {
// Remove deprecated label if no www files are changed
try {
await github.rest.issues.removeLabel({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
name: 'deprecated'
});
} catch (error) {
// Label doesn't exist, which is fine
console.log('Deprecated label not found, skipping removal');
}
}
+45
View File
@@ -0,0 +1,45 @@
# Adapted from vercel/next.js
name: "Stale issue handler"
on:
workflow_dispatch:
schedule:
# This runs every day 20 minutes before midnight: https://crontab.guru/#40_23_*_*_*
- cron: "40 23 * * *"
jobs:
stale:
runs-on: ubuntu-latest
if: github.repository_owner == 'shadcn-ui'
steps:
- uses: actions/stale@v9
id: issue-stale
name: "Mark stale issues, close stale issues"
with:
repo-token: ${{ secrets.STALE_TOKEN }}
ascending: true
days-before-issue-close: 7
days-before-issue-stale: 365
days-before-pr-stale: -1
days-before-pr-close: -1
remove-issue-stale-when-updated: true
stale-issue-label: "stale?"
exempt-issue-labels: "roadmap,next"
stale-issue-message: "This issue has been automatically marked as stale due to one year of inactivity. It will be closed in 7 days unless theres further input. If you believe this issue is still relevant, please leave a comment or provide updated details. Thank you. (This is an automated message)"
close-issue-message: "This issue has been automatically closed due to one year of inactivity. If youre still experiencing a similar problem or have additional details to share, please open a new issue following our current issue template. Your updated report helps us investigate and address concerns more efficiently. Thank you for your understanding! (This is an automated message)"
operations-per-run: 300
- uses: actions/stale@v9
id: pr-state
name: "Mark stale PRs, close stale PRs"
with:
repo-token: ${{ secrets.STALE_TOKEN }}
ascending: true
days-before-issue-close: -1
days-before-issue-stale: -1
days-before-pr-close: 7
days-before-pr-stale: 365
remove-pr-stale-when-updated: true
exempt-pr-labels: "roadmap,next,bug"
stale-pr-label: "stale?"
stale-pr-message: "This PR has been automatically marked as stale due to one year of inactivity. It will be closed in 7 days unless theres further input. If you believe this PR is still relevant, please leave a comment or provide updated details. Thank you. (This is an automated message)"
close-pr-message: "This PR has been automatically closed due to one year of inactivity. Thank you for your understanding! (This is an automated message)"
operations-per-run: 300
+186
View File
@@ -0,0 +1,186 @@
name: NPM Publish
permissions:
contents: write
id-token: write
on:
workflow_dispatch:
inputs:
package:
description: 'Package to publish'
required: true
type: choice
options:
- ui
- ui-mcp
- auth
- commerce
- checkout
- brand
- react
- all
version_bump:
description: 'Version bump type'
required: true
type: choice
options:
- patch
- minor
- major
jobs:
publish:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v3
with:
version: 8
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'pnpm'
registry-url: 'https://registry.npmjs.org'
- name: Install dependencies
run: pnpm install
- name: Build packages
run: |
if [ "${{ github.event.inputs.package }}" = "all" ] || [ "${{ github.event.inputs.package }}" = "ui" ]; then
cd pkg/ui && pnpm build
cd ../..
fi
if [ "${{ github.event.inputs.package }}" = "all" ] || [ "${{ github.event.inputs.package }}" = "ui-mcp" ]; then
cd pkg/ui-mcp && pnpm build
cd ../..
fi
if [ "${{ github.event.inputs.package }}" = "all" ] || [ "${{ github.event.inputs.package }}" = "auth" ]; then
cd pkg/auth && pnpm build
cd ../..
fi
if [ "${{ github.event.inputs.package }}" = "all" ] || [ "${{ github.event.inputs.package }}" = "commerce" ]; then
cd pkg/commerce && pnpm build
cd ../..
fi
if [ "${{ github.event.inputs.package }}" = "all" ] || [ "${{ github.event.inputs.package }}" = "checkout" ]; then
cd pkg/checkout && pnpm build
cd ../..
fi
if [ "${{ github.event.inputs.package }}" = "all" ] || [ "${{ github.event.inputs.package }}" = "brand" ]; then
cd pkg/brand && pnpm build
cd ../..
fi
if [ "${{ github.event.inputs.package }}" = "all" ] || [ "${{ github.event.inputs.package }}" = "react" ]; then
cd pkg/react && pnpm build
cd ../..
fi
- name: Bump version and publish
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
NPM_CONFIG_PROVENANCE: true
run: |
# Set up npm and pnpm auth
npm config set //registry.npmjs.org/:_authToken $NODE_AUTH_TOKEN
echo "//registry.npmjs.org/:_authToken=${NODE_AUTH_TOKEN}" >> ~/.npmrc
publish_package() {
local pkg_dir=$1
local pkg_name=$(cd $pkg_dir && node -p "require('./package.json').name")
local pkg_version=$(cd $pkg_dir && node -p "require('./package.json').version")
echo "=== Publishing $pkg_name@$pkg_version from $pkg_dir ==="
# Change to package directory
pushd "$pkg_dir"
# Bump version manually using node to avoid any pnpm/npm hooks
echo "Bumping version (${{ github.event.inputs.version_bump }})..."
node -e "
const fs = require('fs');
const pkg = JSON.parse(fs.readFileSync('package.json', 'utf8'));
const [major, minor, patch] = pkg.version.split('.').map(Number);
const bump = '${{ github.event.inputs.version_bump }}';
if (bump === 'major') pkg.version = (major + 1) + '.0.0';
else if (bump === 'minor') pkg.version = major + '.' + (minor + 1) + '.0';
else pkg.version = major + '.' + minor + '.' + (patch + 1);
fs.writeFileSync('package.json', JSON.stringify(pkg, null, 2) + '\n');
console.log('New version:', pkg.version);
"
local new_version=$(node -p "require('./package.json').version")
echo "Version is now: $new_version"
# Pack the tarball
echo "Running pnpm pack..."
pnpm pack --pack-gzip-level 9
local tarball=$(ls -t *.tgz | head -1)
echo "Created tarball: $tarball"
# Verify tarball contents
echo "Tarball package.json:"
tar -xzf "$tarball" -O package/package.json
# Copy to temp dir and publish
local temp_dir="/tmp/publish-$$"
mkdir -p "$temp_dir"
cp "$tarball" "$temp_dir/"
echo "Publishing from $temp_dir..."
cd "$temp_dir"
npm publish "$tarball" --access public
cd -
# Cleanup
rm -rf "$temp_dir"
rm -f "$tarball"
popd
}
case "${{ github.event.inputs.package }}" in
ui)
publish_package "pkg/ui"
;;
ui-mcp)
publish_package "pkg/ui-mcp"
;;
auth)
publish_package "pkg/auth"
;;
commerce)
publish_package "pkg/commerce"
;;
checkout)
publish_package "pkg/checkout"
;;
brand)
publish_package "pkg/brand"
;;
react)
publish_package "pkg/react"
;;
all)
publish_package "pkg/ui"
publish_package "pkg/ui-mcp"
publish_package "pkg/auth"
publish_package "pkg/commerce"
publish_package "pkg/checkout"
publish_package "pkg/brand"
publish_package "pkg/react"
;;
esac
- name: Create Pull Request
uses: peter-evans/create-pull-request@v6
with:
token: ${{ secrets.GITHUB_TOKEN }}
commit-message: 'chore: bump ${{ github.event.inputs.package }} version to ${{ github.event.inputs.version_bump }}'
title: 'chore: bump ${{ github.event.inputs.package }} version'
body: |
Automated version bump for ${{ github.event.inputs.package }} package(s).
Version bump type: ${{ github.event.inputs.version_bump }}
branch: version-bump-${{ github.event.inputs.package }}-${{ github.run_number }}
+65
View File
@@ -0,0 +1,65 @@
# Adapted from create-t3-app.
name: Write Beta Release comment
on:
workflow_run:
workflows: ["Release - Beta"]
types:
- completed
jobs:
comment:
if: |
github.repository_owner == 'hanzoai-ui' &&
${{ github.event.workflow_run.conclusion == 'success' }}
runs-on: ubuntu-latest
name: Write comment to the PR
steps:
- name: "Comment on PR"
uses: actions/github-script@v6
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
const allArtifacts = await github.rest.actions.listWorkflowRunArtifacts({
owner: context.repo.owner,
repo: context.repo.repo,
run_id: context.payload.workflow_run.id,
});
for (const artifact of allArtifacts.data.artifacts) {
// Extract the PR number and package version from the artifact name
const match = /^npm-package-hanzoai-ui@(.*?)-pr-(\d+)/.exec(artifact.name);
if (match) {
require("fs").appendFileSync(
process.env.GITHUB_ENV,
`\nBETA_PACKAGE_VERSION=${match[1]}` +
`\nWORKFLOW_RUN_PR=${match[2]}` +
`\nWORKFLOW_RUN_ID=${context.payload.workflow_run.id}`
);
break;
}
}
- name: "Comment on PR with Link"
uses: marocchino/sticky-pull-request-comment@v2
with:
number: ${{ env.WORKFLOW_RUN_PR }}
message: |
A new prerelease is available for testing:
```sh
npx hanzoai-ui@${{ env.BETA_PACKAGE_VERSION }}
```
- name: "Remove the autorelease label once published"
uses: actions/github-script@v6
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
github.rest.issues.removeLabel({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: '${{ env.WORKFLOW_RUN_PR }}',
name: '🚀 autorelease',
});
+60
View File
@@ -0,0 +1,60 @@
# Adapted from create-t3-app.
name: Release - Beta
on:
pull_request:
types: [labeled]
branches:
- main
jobs:
prerelease:
if: |
github.repository_owner == 'hanzoai' &&
contains(github.event.pull_request.labels.*.name, '🚀 autorelease')
name: Build & Publish a beta release to NPM
runs-on: ubuntu-latest
environment: Preview
steps:
- name: Checkout Repo
uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Use PNPM
uses: pnpm/action-setup@v2.2.4
with:
version: 8.6.1
- name: Use Node.js 18
uses: actions/setup-node@v3
with:
node-version: 18
cache: "pnpm"
- name: Install NPM Dependencies
run: pnpm install
- name: Modify package.json version
run: node .github/version-script-beta.js
- name: Authenticate to NPM
run: echo "//registry.npmjs.org/:_authToken=$NPM_ACCESS_TOKEN" >> pkg/cli/.npmrc
env:
NPM_ACCESS_TOKEN: ${{ secrets.NPM_ACCESS_TOKEN }}
- name: Publish Beta to NPM
run: pnpm pub:beta
- name: get-npm-version
id: package-version
uses: martinbeentjes/npm-get-version-action@main
with:
path: pkg/cli
- name: Upload packaged artifact
uses: actions/upload-artifact@v2
with:
name: npm-package-hanzoai-ui@${{ steps.package-version.outputs.current-version }}-pr-${{ github.event.number }} # encode the PR number into the artifact name
path: pkg/cli/dist/index.js
+154
View File
@@ -0,0 +1,154 @@
name: Publish on Tag
on:
push:
tags:
- 'v*' # Match @hanzo/ui version (e.g., v5.1.1)
jobs:
test:
name: Run Tests
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v3
with:
version: 9
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'pnpm'
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Build packages
run: |
cd pkg/ui && pnpm build && cd ../..
cd pkg/auth && pnpm build && cd ../..
cd pkg/commerce && pnpm build && cd ../..
cd pkg/brand && pnpm build && cd ../..
cd pkg/react && pnpm build && cd ../..
- name: Run tests
run: |
cd pkg/ui && pnpm test
cd ../react && pnpm test
cd ../..
publish:
name: Publish to NPM
needs: test
runs-on: ubuntu-latest
permissions:
contents: write
id-token: write
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v3
with:
version: 9
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'pnpm'
registry-url: 'https://registry.npmjs.org'
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Build all packages
run: |
cd pkg/ui && pnpm build && cd ../..
cd pkg/auth && pnpm build && cd ../..
cd pkg/commerce && pnpm build && cd ../..
cd pkg/brand && pnpm build && cd ../..
cd pkg/react && pnpm build && cd ../..
- name: Configure npm authentication
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_AUTH_TOKEN }}
run: |
npm config set //registry.npmjs.org/:_authToken $NODE_AUTH_TOKEN
npm whoami
- name: Check and publish packages
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_AUTH_TOKEN }}
run: |
echo "Checking all packages for unpublished versions..."
PUBLISHED_COUNT=0
SKIPPED_COUNT=0
PUBLISHED_PACKAGES=""
for package in ui auth commerce brand react; do
cd "pkg/$package"
CURRENT_VERSION=$(node -p "require('./package.json').version")
PACKAGE_NAME=$(node -p "require('./package.json').name")
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "📦 Checking $PACKAGE_NAME@$CURRENT_VERSION"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
# Check if this version already exists on npm
if npm view "$PACKAGE_NAME@$CURRENT_VERSION" version 2>/dev/null; then
echo "⏭️ Already published - skipping"
SKIPPED_COUNT=$((SKIPPED_COUNT + 1))
else
echo "🚀 Publishing to npm..."
npm publish --access public
echo "✅ Successfully published $PACKAGE_NAME@$CURRENT_VERSION"
PUBLISHED_COUNT=$((PUBLISHED_COUNT + 1))
PUBLISHED_PACKAGES="$PUBLISHED_PACKAGES\n- $PACKAGE_NAME@$CURRENT_VERSION"
fi
cd ../..
done
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "📊 Publishing Summary"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "✅ Published: $PUBLISHED_COUNT package(s)"
echo "⏭️ Skipped: $SKIPPED_COUNT package(s)"
if [ $PUBLISHED_COUNT -gt 0 ]; then
echo ""
echo -e "Published packages:$PUBLISHED_PACKAGES"
fi
# Save for GitHub release notes
echo "PUBLISHED_COUNT=$PUBLISHED_COUNT" >> $GITHUB_ENV
echo "PUBLISHED_PACKAGES<<EOF" >> $GITHUB_ENV
echo -e "$PUBLISHED_PACKAGES" >> $GITHUB_ENV
echo "EOF" >> $GITHUB_ENV
- name: Create GitHub Release
if: ${{ env.PUBLISHED_COUNT > 0 }}
uses: softprops/action-gh-release@v1
with:
generate_release_notes: true
body: |
## 📦 NPM Packages Published
${{ env.PUBLISHED_PACKAGES }}
### Installation
```bash
# Install latest versions
npm install @hanzo/ui @hanzo/auth @hanzo/commerce @hanzo/brand @hanzo/react
```
files: |
CHANGELOG.md
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+76
View File
@@ -0,0 +1,76 @@
name: Publish Packages
on:
push:
branches: [main]
paths:
- 'pkg/*/package.json'
jobs:
detect-changes:
runs-on: ubuntu-latest
outputs:
packages: ${{ steps.changed.outputs.packages }}
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 2
- name: Detect changed packages
id: changed
run: |
CHANGED_PACKAGES=()
for pkg_json in pkg/*/package.json; do
pkg_dir=$(dirname "$pkg_json")
pkg_name=$(basename "$pkg_dir")
# Check if package.json version changed
if git diff HEAD~1 HEAD --quiet "$pkg_json" 2>/dev/null; then
continue
fi
# Get old and new versions
OLD_VERSION=$(git show HEAD~1:"$pkg_json" 2>/dev/null | jq -r '.version' || echo "0.0.0")
NEW_VERSION=$(jq -r '.version' "$pkg_json")
if [ "$OLD_VERSION" != "$NEW_VERSION" ]; then
echo "Version change detected: $pkg_name ($OLD_VERSION -> $NEW_VERSION)"
CHANGED_PACKAGES+=("$pkg_name")
fi
done
if [ ${#CHANGED_PACKAGES[@]} -eq 0 ]; then
echo "packages=[]" >> $GITHUB_OUTPUT
else
JSON=$(printf '%s\n' "${CHANGED_PACKAGES[@]}" | jq -R . | jq -s -c .)
echo "packages=$JSON" >> $GITHUB_OUTPUT
fi
publish:
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
- uses: actions/setup-node@v4
with:
node-version: 20
registry-url: 'https://registry.npmjs.org'
cache: 'pnpm'
- name: Install dependencies
run: pnpm install
- name: Build package
run: pnpm --filter ${{ matrix.package }} build
- name: Publish package
run: pnpm --filter ${{ matrix.package }} publish --no-git-checks --access public
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
+60
View File
@@ -0,0 +1,60 @@
# Adapted from create-t3-app.
name: Release
on:
push:
branches:
- main
permissions:
id-token: write
contents: write
pull-requests: write
jobs:
release:
if: ${{ github.repository_owner == 'hanzoai-ui' }}
name: Create a PR for release workflow
runs-on: ubuntu-latest
steps:
- name: Checkout Repo
uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Use PNPM
uses: pnpm/action-setup@v4
with:
version: 9.0.6
- name: Use Node.js 20
uses: actions/setup-node@v4
with:
node-version: 20
registry-url: "https://registry.npmjs.org"
cache: "pnpm"
- name: Update npm for OIDC support
run: npm install -g npm@latest
- name: Install NPM Dependencies
run: pnpm install
# - name: Check for errors
# run: pnpm check
- name: Build the package
run: pnpm shadcn:build
- name: Create Version PR or Publish to NPM
id: changesets
uses: changesets/action@v1
with:
commit: "chore(release): version packages"
title: "chore(release): version packages"
version: node .github/changeset-version.js
publish: npx changeset publish
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NODE_ENV: "production"
+100
View File
@@ -0,0 +1,100 @@
name: Sync Forks
on:
push:
branches: [main]
workflow_dispatch:
inputs:
fork:
description: 'Fork to sync (luxfi or zoo or all)'
required: false
default: 'all'
jobs:
sync-luxfi:
if: github.event.inputs.fork == 'luxfi' || github.event.inputs.fork == 'all' || github.event_name == 'push'
runs-on: ubuntu-latest
steps:
- name: Checkout Hanzo UI
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup Git
run: |
git config --global user.name "Hanzo Bot"
git config --global user.email "bot@hanzo.ai"
- name: Clone Luxfi Fork
run: |
git clone https://github.com/luxfi/ui.git luxfi-ui
cd luxfi-ui
git remote add upstream https://github.com/hanzoai/ui.git
git fetch upstream
- name: Sync and Rebrand
run: |
cd luxfi-ui
# Merge upstream changes
git checkout main
git merge upstream/main --no-edit || true
# Run rebrand script
cp ../scripts/rebrand.sh ./
chmod +x rebrand.sh
./rebrand.sh luxfi
# Commit changes
git add -A
git commit -m "sync: Update from hanzoai/ui and rebrand for Luxfi" || true
- name: Push to Luxfi
env:
GITHUB_TOKEN: ${{ secrets.FORK_SYNC_TOKEN }}
run: |
cd luxfi-ui
git push https://$GITHUB_TOKEN@github.com/luxfi/ui.git main || true
sync-zoo:
if: github.event.inputs.fork == 'zoo' || github.event.inputs.fork == 'all' || github.event_name == 'push'
runs-on: ubuntu-latest
steps:
- name: Checkout Hanzo UI
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup Git
run: |
git config --global user.name "Hanzo Bot"
git config --global user.email "bot@hanzo.ai"
- name: Clone Zoo Fork
run: |
git clone https://github.com/zooai/ui.git zoo-ui
cd zoo-ui
git remote add upstream https://github.com/hanzoai/ui.git
git fetch upstream
- name: Sync and Rebrand
run: |
cd zoo-ui
# Merge upstream changes
git checkout main
git merge upstream/main --no-edit || true
# Run rebrand script
cp ../scripts/rebrand.sh ./
chmod +x rebrand.sh
./rebrand.sh zoo
# Commit changes
git add -A
git commit -m "sync: Update from hanzoai/ui and rebrand for Zoo" || true
- name: Push to Zoo
env:
GITHUB_TOKEN: ${{ secrets.FORK_SYNC_TOKEN }}
run: |
cd zoo-ui
git push https://$GITHUB_TOKEN@github.com/zooai/ui.git main || true
+75
View File
@@ -0,0 +1,75 @@
name: E2E and Visual Tests
on:
push:
branches: [main, develop]
pull_request:
branches: [main, develop]
schedule:
# Run tests weekly on Sunday at 2 AM UTC to catch breaking updates
- cron: '0 2 * * 0'
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
env:
NODE_OPTIONS: --max-old-space-size=8192
jobs:
test:
runs-on: ubuntu-latest
timeout-minutes: 60
strategy:
matrix:
node-version: [20.x]
steps:
- uses: actions/checkout@v4
- name: Setup pnpm
uses: pnpm/action-setup@v2
with:
version: 9.0.6
- name: Setup Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
cache: 'pnpm'
- name: Install dependencies
run: pnpm install
- name: Install Playwright browsers
run: pnpm exec playwright install --with-deps
- name: Build the project
run: pnpm build
env:
NODE_OPTIONS: --max-old-space-size=8192
- name: Run component health check
run: pnpm health-check
continue-on-error: true
- name: Run E2E tests
run: pnpm test:e2e
timeout-minutes: 30
env:
CI: true
- name: Run visual regression tests
run: pnpm test:visual
timeout-minutes: 20
continue-on-error: true
env:
CI: true
- name: Upload test results
if: always()
uses: actions/upload-artifact@v4
with:
name: playwright-report
path: tests/reports/playwright-report/
retention-days: 30
+53
View File
@@ -0,0 +1,53 @@
name: Validate Registries
on:
pull_request:
paths:
- "apps/v4/public/r/registries.json"
- "apps/v4/registry/directory.json"
push:
branches:
- main
paths:
- "apps/v4/public/r/registries.json"
- "apps/v4/registry/directory.json"
jobs:
validate:
runs-on: ubuntu-latest
name: pnpm validate:registries
permissions:
contents: read
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Install Node.js
uses: actions/setup-node@v3
with:
node-version: 20
- uses: pnpm/action-setup@v4
name: Install pnpm
id: pnpm-install
with:
version: 9.0.6
run_install: false
- name: Get pnpm store directory
id: pnpm-cache
run: |
echo "pnpm_cache_dir=$(pnpm store path)" >> $GITHUB_OUTPUT
- uses: actions/cache@v3
name: Setup pnpm cache
with:
path: ${{ steps.pnpm-cache.outputs.pnpm_cache_dir }}
key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}
restore-keys: |
${{ runner.os }}-pnpm-store-
- name: Install dependencies
run: pnpm install
- name: Validate registries
run: pnpm --filter=v4 validate:registries
-3
View File
@@ -78,6 +78,3 @@ playwright-report/
.fleet
.notes
.claude/settings.local.json
pkg/ui/dist-test/
app/public/api/
-26
View File
@@ -1,26 +0,0 @@
# The whole caller. Every decision this pipeline makes — what to test, what to
# build, where to roll it — is read from the root hanzo.yml, so this file only
# ever names the triggers and the reusable.
#
# `.hanzo/workflows`, not `.github/workflows`, and that is not a style choice:
# CI for this repo runs on git.hanzo.ai, which resolves ONLY `.hanzo/workflows`.
# github.com has zero self-hosted runners registered for the `hanzo-build-*`
# labels this pipeline asks for, so the same file under `.github/workflows`
# would queue there forever and never report anything at all.
name: CI/CD
on:
push:
branches: [main]
tags: ['v*']
pull_request:
workflow_dispatch:
concurrency:
group: cicd-${{ github.ref }}
cancel-in-progress: true
jobs:
cicd:
uses: hanzoai/ci/.hanzo/workflows/build.yml@v1
secrets: inherit
-70
View File
@@ -1,70 +0,0 @@
name: deploy
# RETIRED as an automatic lane. The image is built by hanzo.yml's `images:` block
# through hanzoai/ci (.hanzo/workflows/cicd.yml), and this job is kept only as a
# manually-dispatched fallback.
#
# The reason is one capability, not tidiness. ui.hanzo.ai is a static export, so
# its ingest key has to be BAKED IN at build; the key lives in KMS as
# `deploy/PUBLISHABLE_KEY`, and hanzoai/ci is the only lane that reads it and
# passes it as `--build-arg PUBLISHABLE_KEY=…`. The `docker build -t "$image" .`
# below cannot — there is no KMS hop in it and nowhere to put the value — so any
# image it produced would ship a client with no key at all, and cloud answers
# `401 ingest_key_required` for an unattributed write. With the Dockerfile now
# failing closed on an empty key, this job fails on every run instead of quietly
# publishing an inert site.
#
# Left in place rather than deleted, and dispatch-only rather than on push:
# deleting a repo's only build lane strands the host with no failing run to show
# it, and two push-triggered builders for one image means one commit yields two
# images under two tag schemes. Dispatching this publishes `<short-sha>` with an
# EMPTY key and the Dockerfile will refuse it — so if you dispatch it, pass the
# key yourself or expect the gate to fire.
on:
workflow_dispatch:
concurrency:
group: deploy-${{ github.ref }}
cancel-in-progress: false
jobs:
image:
# hanzo-build-linux-amd64, not ubuntu-latest. This file lives in
# .hanzo/workflows, which GitHub never reads -- git.hanzo.ai is the only
# thing that can run it, and the fleet deliberately advertises no generic
# ubuntu-* label (~1400 mirrored forks all ask for it; one bad job was
# retried ~520 times across 10 runners). An unmatched label is not an
# error here, it is silence: the job queues until the 24h timeout, so this
# deploy has never produced an image and nothing ever said so.
runs-on: hanzo-build-linux-amd64
timeout-minutes: 60
steps:
- uses: actions/checkout@v4
- name: build and push
# GHCR_TOKEN/GHCR_USER, which are the org secrets that actually exist.
# This job asked for REGISTRY_TOKEN, which was never defined anywhere —
# the org has exactly GHCR_TOKEN, GHCR_USER, GH_PAT, KMS_CLIENT_ID,
# KMS_CLIENT_SECRET, OCI_TOKEN, OCI_USER — so the guard below fired on
# every run and nothing was ever published. Every other image build in
# the org already uses the GHCR_* pair; this file and papers were the
# two that invented a name.
#
# The username comes from the secret too, rather than being hardcoded to
# hanzo-dev, so rotating the publishing identity is one org-level change.
env:
GHCR_TOKEN: ${{ secrets.GHCR_TOKEN }}
GHCR_USER: ${{ secrets.GHCR_USER }}
run: |
set -euo pipefail
if [ -z "${GHCR_TOKEN:-}" ] || [ -z "${GHCR_USER:-}" ]; then
echo "::error::GHCR_TOKEN/GHCR_USER are unset, so nothing was published."
exit 1
fi
tag="$(git rev-parse --short HEAD)"
image="ghcr.io/hanzoai/ui:${tag}"
echo "${GHCR_TOKEN}" | docker login ghcr.io -u "${GHCR_USER}" --password-stdin
docker build -t "${image}" .
docker push "${image}"
echo "published ${image} — set image.tag AND image.digest in universe charts/app/values/hanzo/ui.yaml"
-343
View File
@@ -1,343 +0,0 @@
name: Publish Packages
on:
push:
branches: [main]
paths:
# BOTH package roots, and the singular one is not a typo — `@hanzo/ui` and
# `@hanzo/data` live under pkg/, everything else under pkgs/.
#
# ⚠️ This list and the `for pkg_json in …` loop below are ONE FACT. The loop
# was already fixed to walk both roots, with a comment explaining that a
# `pkgs/*` glob made pkg/ packages invisible — but this gate was left
# matching `pkgs/*` only, so for a pkg/-only change the corrected job could
# never be REACHED. The fix was reasoned about in the body and not applied
# to the thing that decides whether the body runs.
#
# Cost: @hanzo/ui 8.0.29 sat unpublished while npmjs served 8.0.28, so
# every consumer resolving `^8.0.17` silently got a version without the
# `./chat` entrypoint — an import error in the dependent, nothing at all in
# this repo. Add a root here whenever one is added to the loop.
- 'pkg/*/package.json'
- 'pkgs/*/package.json'
# A publish that fails for an infrastructure reason — the runner missing a
# tool, npmjs answering slowly — could only be retried by pushing another
# commit that touches a package.json, i.e. by burning a version number to
# re-run a job that was never wrong about the code. detect-changes reads what
# npmjs SERVES, so a dispatch is idempotent by construction: it publishes
# exactly the packages that are ahead of the registry, and nothing when none
# are.
workflow_dispatch:
jobs:
detect-changes:
runs-on: hanzo-build-linux-amd64
outputs:
packages: ${{ steps.changed.outputs.packages }}
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 2
- name: Detect changed packages
id: changed
run: |
CHANGED=()
# Both package roots. `@hanzo/ui` and `@hanzo/data` live under pkg/ (singular)
# and were invisible to a `pkgs/*` glob, so no version bump of either could
# ever reach npmjs from here.
for pkg_json in pkg/*/package.json pkgs/*/package.json; do
[ ! -f "$pkg_json" ] && continue
# Skip private packages
IS_PRIVATE=$(jq -r '.private // false' "$pkg_json")
[ "$IS_PRIVATE" = "true" ] && continue
# Only publish @hanzo/* packages
PKG_NAME=$(jq -r '.name' "$pkg_json")
case "$PKG_NAME" in
@hanzo/*) ;;
*) continue ;;
esac
# What npm SERVES, not what the previous commit said. HEAD~1 is the
# FIRST PARENT, so a merge whose first parent is the feature branch
# already carries the new version and the diff is empty — the publish
# is skipped and npm keeps serving the old release, silently. Asking
# the registry is independent of merge topology and of how many
# commits the runner fetched.
NEW=$(jq -r '.version' "$pkg_json")
OLD=$(curl -sf "https://registry.npmjs.org/${PKG_NAME}" \
| jq -r '."dist-tags".latest // "0.0.0"' 2>/dev/null || echo "0.0.0")
# FORWARD ONLY. `!=` fires in both directions, and several packages
# sit BEHIND npm (a release cut elsewhere, a revert) — publishing
# those walks the registry backwards. Only a strictly greater local
# version is a release.
NEWEST=$(printf '%s\n%s\n' "$OLD" "$NEW" | sort -V | tail -1)
if [ "$OLD" != "$NEW" ] && [ "$NEWEST" = "$NEW" ]; then
echo "Version change: $PKG_NAME ($OLD -> $NEW)"
# The package NAME, because every downstream step spends this as a
# `pnpm --filter` argument and a directory basename matches nothing.
# An unmatched filter exits 0, so the build silently no-ops and the
# publish ships an unbuilt tarball — how 8.0.17 and 8.0.19 shipped broken.
CHANGED+=("$PKG_NAME")
fi
done
if [ ${#CHANGED[@]} -eq 0 ]; then
echo "packages=[]" >> $GITHUB_OUTPUT
else
JSON=$(printf '%s\n' "${CHANGED[@]}" | jq -R . | jq -s -c .)
echo "packages=$JSON" >> $GITHUB_OUTPUT
fi
publish:
needs: detect-changes
if: needs.detect-changes.outputs.packages != '[]'
runs-on: hanzo-build-linux-amd64
strategy:
# One package's broken build must not withhold every other package's
# release: the matrix legs are independent publishes, not one artifact.
fail-fast: false
matrix:
package: ${{ fromJson(needs.detect-changes.outputs.packages) }}
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
- uses: actions/setup-node@v4
with:
node-version: 20
registry-url: 'https://registry.npmjs.org'
- name: Install dependencies
run: pnpm install
- name: Build package
# The trailing `...` is load-bearing: it builds the package's WORKSPACE
# DEPENDENCIES first, in topological order.
#
# Without it, `pnpm --filter @hanzo/ui build` runs alone against siblings
# that have no `dist/`. Those siblings type themselves through
# `"types": "dist/index.d.ts"`, so tsc reports them as missing modules and
# the errors do not name the real cause:
# src/product/SiteNav.tsx: Cannot find module '@hanzo/products'
# src/core/tokens.ts: Cannot find module '@hanzo/tokens'
# src/gitops.ts: Cannot find module '@hanzo/cd'
# plus a wave of implicit-any errors in the files that imported them,
# which read like a source problem in @hanzo/ui and are not.
run: pnpm --filter ${{ matrix.package }}... build
- name: Provision bun (only for a package whose test script asks for it)
# @hanzo/canvas declares `bun test` and this runner has no bun, so its
# suite has been `spawn ENOENT` on every run — which fails the leg before
# the publish and is why canvas has sat at 0.2.2 here against 0.2.1 on
# npmjs. The step that exists to stop an untested release was itself the
# thing stopping the release.
#
# Read from the package's OWN manifest, not from a list here, so a
# package that adopts or drops bun needs no edit to this file. A package
# that does not ask for bun does not pay for it.
run: |
set -euo pipefail
PKG_DIR=$(pnpm --filter ${{ matrix.package }} exec pwd | tail -1)
if ! jq -r '.scripts.test // ""' "$PKG_DIR/package.json" | grep -qw bun; then
echo "::notice::${{ matrix.package }} does not run bun"
exit 0
fi
if command -v bun >/dev/null 2>&1; then
echo "bun already on PATH: $(bun --version)"
exit 0
fi
# From npmjs, not bun.sh/install: this job already reaches the npm
# registry (it is what the job exists to publish to) and setup-node
# already put the global bin on PATH, so this adds no new host to
# trust and no new failure mode. The shell installer would also want
# unzip, which a minimal runner image need not carry.
npm install -g bun
bun --version
- name: Test package
# A published version is IMMUTABLE, so this is the last point at which a
# defect costs nothing. Nothing else runs a package's own tests before it
# ships: ci.yml's test job runs `cd pkgs/ui && …` — that one directory —
# and this workflow went checkout → build → publish. So @hanzo/event's
# suite, which pins the version the client stamps on every event, ran in
# no workflow that gates a release, and the stale stamp it was written to
# catch could still have reached npmjs.
#
# `--if-present` so a package with no test script is skipped rather than
# failing the release: the set of testable packages is read from each
# package.json, not listed here, so a new package is covered the day it
# adds a `test` script.
#
# This step needs `test` to mean the same thing in every package — the
# package's own suite, no browser, no network. @hanzo/ui briefly chained
# its two CONSUMER suites onto it (pack a tarball, npm-install it into a
# throwaway app, drive it in chromium), which is a real gate and belongs
# exactly where hanzo.yml already runs it: on the push, in its own
# `ui-consumer` job, next to the `playwright install` that gives it a
# browser. Here there is no such step, so a chained `test` could only
# fail — the last gate before an immutable version would have been one
# that cannot pass, which is the failure mode this repo has already paid
# for twice.
run: pnpm --filter ${{ matrix.package }} run --if-present test
- name: Verify the tarball carries what package.json promises
# `types` is a PROMISE to every consumer, and tsup writes dist/*.mjs in a
# separate pass from dist/*.d.ts — so a declaration failure yields a
# package whose JS is fine and whose types are absent. That is invisible
# here and surfaces in dependents as "Could not find a declaration file".
#
# Asserted from the package's OWN manifest, so it holds for every package
# this workflow publishes and needs no per-package list.
run: |
set -euo pipefail
PKG_DIR=$(pnpm --filter ${{ matrix.package }} exec pwd | tail -1)
TYPES=$(jq -r '.types // .typings // empty' "$PKG_DIR/package.json")
if [ -z "$TYPES" ]; then
echo "::notice::${{ matrix.package }} declares no types entrypoint — nothing to verify"
exit 0
fi
if [ ! -f "$PKG_DIR/$TYPES" ]; then
echo "::error::${{ matrix.package }} declares types at $TYPES but the build produced no such file."
echo "::error::Publishing would ship a package that silently has no types. Fix the declaration build."
exit 1
fi
echo "types present: $TYPES"
- name: Fetch the npm token from KMS
id: npmtok
# publish.yml used secrets.NPM_TOKEN, which exists on NEITHER the hanzoai
# org nor this repo on git.hanzo.ai. An absent secret interpolates to the
# empty string rather than failing, so every publish reached npmjs
# unauthenticated and 401'd -- the reason @hanzo/ui has never shipped from
# CI and each release was a hand publish.
#
# KMS is where a secret lives, so the token is read at run time from the
# same org path and with the same machine identity every other workflow
# here already uses. Nothing new to rotate, and no npm credential is
# stored on the forge.
env:
KMS_CLIENT_ID: ${{ secrets.KMS_CLIENT_ID }}
KMS_CLIENT_SECRET: ${{ secrets.KMS_CLIENT_SECRET }}
KMS_ENDPOINT: ${{ vars.KMS_ENDPOINT || 'https://kms.hanzo.ai' }}
KMS_ORG: ${{ vars.KMS_ORG || 'hanzo' }}
KMS_SECRET_ENV: ${{ vars.KMS_SECRET_ENV || 'prod' }}
# Where the token actually lives, MEASURED: NPM_TOKEN sits at the org
# root, not under deploy/ (which holds CLOUDFLARE_*, GIT_TOKEN,
# KUBECONFIG, UNIVERSE_PIN_TOKEN). Empty means root; set the
# KMS_NPM_PATH variable to move it without editing this file.
KMS_NPM_PATH: ${{ vars.KMS_NPM_PATH || '' }}
run: |
token=$(curl -fsS "${KMS_ENDPOINT}/v1/kms/auth/login" \
-H 'Content-Type: application/json' \
-d "{\"clientId\":\"${KMS_CLIENT_ID}\",\"clientSecret\":\"${KMS_CLIENT_SECRET}\"}" \
| jq -r '.accessToken // empty')
if [ -z "${token}" ]; then
echo "::error::KMS login failed at ${KMS_ENDPOINT}/v1/kms/auth/login (check KMS_CLIENT_ID/KMS_CLIENT_SECRET)."
exit 1
fi
# The read is org-scoped by the TOKEN's owner claim, not by a path
# segment: the flat form is the contract cloud's embedded KMS serves,
# and it answers {name, env, value}. The older
# /v1/kms/orgs/<org>/secrets/... form with .secret.value 404s here.
secret_url="${KMS_ENDPOINT}/v1/kms/secrets/${KMS_NPM_PATH:+${KMS_NPM_PATH}/}NPM_TOKEN?env=${KMS_SECRET_ENV}"
# No -f: a 404 must report WHICH path was empty, not just exit 22.
npm_token=$(curl -sS "${secret_url}" -H "Authorization: Bearer ${token}" | jq -r '.value // empty')
if [ -z "${npm_token}" ]; then
echo "::error::No NPM_TOKEN at ${secret_url}."
echo "::error::Put it there, or set the KMS_NPM_PATH variable to the path that has it."
exit 1
fi
# Masked before it is ever an output, so it cannot surface in a log.
echo "::add-mask::${npm_token}"
echo "token=${npm_token}" >> "$GITHUB_OUTPUT"
- name: Publish package
# Idempotent on purpose: the desired state is "npmjs holds this version", and
# a version already there satisfies it. Versions are immutable, so a conflict
# means the release already happened (a re-run, or a hand publish) — that is
# success, not a failure. Every other error still fails the job.
env:
NODE_AUTH_TOKEN: ${{ steps.npmtok.outputs.token }}
run: |
set -o pipefail
OUT=$(pnpm --filter ${{ matrix.package }} publish \
--no-git-checks --access public 2>&1) || true
echo "$OUT"
case "$OUT" in
*EPUBLISHCONFLICT*|*"cannot publish over"*|*"previously published versions"*)
echo "::notice::${{ matrix.package }} is already on npmjs at this version — nothing to do" ;;
*)
# Not a conflict: confirm the version really landed, else fail loudly.
#
# RETRIED, because npmjs is read-after-write eventually consistent
# and this asked it exactly once, about two seconds after the
# write. On run 26906 both @hanzo/og@1.0.0 and @hanzo/shop@1.0.0
# failed here having printed npm's own `+ @hanzo/og@1.0.0` success
# line moments earlier, and both are on the registry now: the
# publishes worked and the check was simply too early.
#
# A false red here is worse than a slow green. It reports that a
# release did not happen when it did, so the next person bumps the
# version to "fix" it and burns a number over a replication lag —
# and the real signal, a publish that genuinely failed, becomes
# indistinguishable from the noise.
PKG_DIR=$(pnpm --filter ${{ matrix.package }} exec pwd | tail -1)
NAME=$(jq -r '.name' "$PKG_DIR/package.json")
WANT=$(jq -r '.version' "$PKG_DIR/package.json")
landed=
for attempt in 1 2 3 4 5 6; do
if npm view "$NAME@$WANT" version >/dev/null 2>&1; then landed=1; break; fi
echo "$NAME@$WANT not visible to npmjs yet (attempt $attempt/6); waiting 10s"
sleep 10
done
[ -n "$landed" ] \
|| { echo "::error::$NAME@$WANT is not on npmjs 60s after publish"; exit 1; }
echo "published $NAME@$WANT" ;;
esac
- name: Publish to the Hanzo registry
# Second home for the same tarball: api.hanzo.ai/v1/packages/hanzo/npm, our
# own registry (hanzoai/git), so an install does not have to reach npmjs.
# Same artifact, same version — this republishes what the step above just
# built, it does not rebuild or re-version.
#
# BEST-EFFORT by construction. No token ⇒ skip with a notice, so this can
# land before the credential exists and starts working the moment it does.
# An already-published version is a success, not a failure: the registry
# holding it is the desired state either way. npmjs is authoritative and is
# never affected by anything here.
env:
# REGISTRY_TOKEN is the fleet-wide name (six other workflows use it and
# the hanzoai org carries it). This asked for HANZO_REGISTRY_TOKEN, which
# is defined nowhere, so it read as empty and the step below took its
# "not set" branch and exited 0 on every run -- the mirror to
# api.hanzo.ai has never happened, and said so only as a notice.
HANZO_REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}
run: |
set -uo pipefail
if [ -z "${HANZO_REGISTRY_TOKEN:-}" ]; then
echo "::notice::HANZO_REGISTRY_TOKEN not set — package published to npmjs only."
echo "::notice::Add it (a Hanzo Git token with package:write) to mirror to api.hanzo.ai."
exit 0
fi
REG=https://api.hanzo.ai/v1/packages/hanzo/npm/
NPMRC="$RUNNER_TEMP/.npmrc-hanzo"
{
echo "@hanzo:registry=${REG}"
echo "//api.hanzo.ai/v1/packages/hanzo/npm/:_authToken=${HANZO_REGISTRY_TOKEN}"
} > "$NPMRC"
out=$(npm_config_userconfig="$NPMRC" \
pnpm --filter ${{ matrix.package }} publish \
--no-git-checks --access public --registry "$REG" 2>&1) || true
echo "$out"
case "$out" in
*EPUBLISHCONFLICT*|*"cannot publish over"*|*"already exists"*)
echo "::notice::already in the Hanzo registry at this version — nothing to do" ;;
*) echo "$out" | grep -qiE 'error|failed' \
&& echo "::warning::mirror to api.hanzo.ai failed (npmjs publish unaffected)" \
|| echo "mirrored to the Hanzo registry" ;;
esac
-91
View File
@@ -1,91 +0,0 @@
name: Validate Registries
on:
pull_request:
paths:
- "apps/v4/public/r/registries.json"
- "apps/v4/registry/directory.json"
push:
branches:
- main
paths:
- "apps/v4/public/r/registries.json"
- "apps/v4/registry/directory.json"
jobs:
validate:
runs-on: hanzo-build-linux-amd64
name: pnpm validate:registries
permissions:
contents: read
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Install Node.js
uses: actions/setup-node@v3
with:
node-version: 20
- name: Block reserved registry namespaces
env:
RESERVED_NAMESPACES: "@shadcn,@ui,@blocks,@components,@block,@component,@util,@utils,@registry,@lib,@hook,@hooks,@theme,@themes,@chart,@charts"
run: |
node <<'EOF'
const fs = require("node:fs")
const files = [
"apps/v4/public/r/registries.json",
"apps/v4/registry/directory.json",
]
const reservedNamespaces = new Set(
process.env.RESERVED_NAMESPACES.split(",").filter(Boolean)
)
function readNames(filePath) {
return JSON.parse(fs.readFileSync(filePath, "utf8")).map(
(entry) => entry.name
)
}
const violations = files.flatMap((filePath) => {
return readNames(filePath)
.filter((name) => reservedNamespaces.has(name))
.map((name) => `${filePath}: ${name}`)
})
if (violations.length > 0) {
console.error("Reserved registry namespaces are not allowed:")
for (const violation of violations) {
console.error(`- ${violation}`)
}
process.exit(1)
}
EOF
- uses: pnpm/action-setup@v4
name: Install pnpm
id: pnpm-install
with:
version: 9.0.6
run_install: false
- name: Get pnpm store directory
id: pnpm-cache
run: |
echo "pnpm_cache_dir=$(pnpm store path)" >> $GITHUB_OUTPUT
- uses: actions/cache@v3
name: Setup pnpm cache
with:
path: ${{ steps.pnpm-cache.outputs.pnpm_cache_dir }}
key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}
restore-keys: |
${{ runner.os }}-pnpm-store-
- name: Install dependencies
run: pnpm install
- name: Validate registries
run: pnpm --filter=v4 validate:registries
-1
View File
@@ -1,3 +1,2 @@
auto-install-peers=true
link-workspace-packages=true
puppeteer_skip_download=true
-14
View File
@@ -1,14 +0,0 @@
dist
node_modules
.next
build
.contentlayer
**/fixtures
deprecated
apps/v4/registry/styles/**/*.css
# Byte-coupled: hz.js carries the marked region of src/anon.js VERBATIM, and
# pkgs/event/src/anon.test.ts compares them byte for byte. Reformatting either
# one alone breaks the build; the same region is also vendored by hanzoai/cloud.
pkgs/event/src/anon.js
pkgs/event/hz.js
+3 -3
View File
@@ -4,8 +4,8 @@
"typescript.preferences.quoteStyle": "single",
"eslint.workingDirectories": [
{ "pattern": "apps/*/" },
{ "pattern": "pkgs/*/" },
{ "pattern": "pkgs/*/" }
{ "pattern": "packages/*/" },
{ "pattern": "pkg/*/" }
],
"tailwindCSS.classFunctions": ["cva", "cn"],
"vitest.debugExclude": [
@@ -19,6 +19,6 @@
"search.exclude": {
"apps/v4/registry/radix-*": true,
"apps/v4/public/r/*": true,
"pkgs/shadcn/test/fixtures/*": true
"packages/shadcn/test/fixtures/*": true
}
}
-190
View File
@@ -1,190 +0,0 @@
# Hanzo UI Consolidation — one library, all polish, no duplication
**Goal.** RIP the fragmentation (`@hanzo/data` vs `@hanzo/ui` vs in-console duplicates) into ONE canonical, cross-platform, presentational, clean-room library: **`@hanzo/ui`, built on `@hanzo/gui`**. Preserve every polished component + token; zero loss; no fork.
**Status.**
- **Step 1 — Audit:** complete (this document; four source trees read file-by-file).
- **Step 2 — Establish `@hanzo/ui` + migrate the stable foundation:** **DONE & GREEN** (`pkg/ui` is now a real package; `tsc --noEmit` = 0 errors, `vitest` = 12/12).
- **Step 3 — Console re-point:** **STAGED, not merged.** Gate is split (backend live, app lanes in-flight) — see [Step 3](#step-3--console-re-point-staged).
**One decision needs CTO sign-off before publish** — see [Naming / version](#naming--version--the-one-decision).
---
## Architecture — three layers, decomplected
```
@hanzo/gui (Tamagui/One) cross-platform primitives: Text, XStack/YStack, Button, Input,
│ Card, Popover, Select, Switch, Slider, Spinner, ScrollView …
@hanzo/data (pkg/data) the metadata-driven RECORD layer: fields → records → views
│ (RecordsView, DataTable, BoardView, RecordDetail, field editors)
@hanzo/ui (pkg/ui) ◄──── THE ONE LIBRARY. Two orthogonal concerns, one package:
• product/app layer → import { … } from '@hanzo/ui'
• record layer → import { … } from '@hanzo/ui/data' (re-exports @hanzo/data)
```
`@hanzo/data` stays the **source of truth** for the record layer; `@hanzo/ui` **composes** it (`export * from '@hanzo/data'` on the `./data` subpath) rather than copying — so the CMS/ERP/Help app lanes that consume `@hanzo/data` today keep working untouched, and there is exactly one home. This mirrors how the gui base wraps `hanzogui`.
Both layers own a `DataTable` (product = generic typed `<T>` list; data = field-driven record grid). Keeping the record layer on the `./data` subpath keeps each name unambiguous — no rename, no collision.
---
## The preserve-and-merge manifest
Legend: **✅ migrated** (in `pkg/ui`, GREEN) · **↪ re-exported** (composed from `@hanzo/data`) · **⏳ staged** (Step 3, after app lanes land) · **🔧 pending prop-injection** (app-coupled; decouple before it can live in a presentational lib) · **🏠 stays in console** (app glue, not a UI component).
### A. Record layer — `@hanzo/data` → `@hanzo/ui/data` ↪
Source: `pkg/data/src/*` (v1.2.0, clean-room, already published). Surfaced through `@hanzo/ui/data` and `@hanzo/ui/primitives/bases/data`. Nothing re-implemented.
| Component / module | Source | New home |
|---|---|---|
| `RecordsView` (flagship: toolbar over table⇆board, filter/sort/search/group, saved views) | `view/RecordsView.tsx`, `view/Toolbar.tsx` | `@hanzo/ui/data` |
| `DataTable` (field-driven record grid: sort headers, drag resize/reorder, row select, inline edit, pagination) | `table/DataTable.tsx` | `@hanzo/ui/data` |
| `BoardView` (kanban, optimistic drag-move) · `RecordCard` | `board/BoardView.tsx`, `table/RecordCard.tsx` | `@hanzo/ui/data` |
| `RecordDetail` / `RecordForm` | `record/RecordDetail.tsx` | `@hanzo/ui/data` |
| Field model + registry (`FieldType` ×24, `FieldDefinition`, `registerField`, routers) | `field/{types,registry,registerDefaults,FieldDisplay,FieldInput}` | `@hanzo/ui/data` |
| Field displays + **editors** (select/currency/date/relation/file/JSON/boolean/fullName/address…) | `field/{displays,inputs}.tsx` | `@hanzo/ui/data` |
| Composable primitives: `Menu`, `CheckBox`, `Toggle`, `Calendar` | `primitives/*` | `@hanzo/ui/data` |
| Pure logic: `applyView`, `sortRecords`, `filterRecords`, `searchRecords`, `paginate`, `boardColumns`, … | `{table,board,view}/logic.ts` | `@hanzo/ui/data` (+ `@hanzo/data/*/logic` subpaths for Node hosts) |
| Tokens: `tokens`, `TAG_TONES`, `tagTone` | `theme.ts` | **also top-level `@hanzo/ui`** (token surface) |
### B. Console `components/ui/*` product primitives → `@hanzo/ui/product` ✅ / 🔧
Source: `console2/src/components/ui/*`. The pure subset was ported **byte-identical** (verified by `diff`) — 100% of the polish preserved (Charts' hover tooltips/axis-ticks/honest-null, DataTable width/flex/hover-gating, Field's 6 variants, SlideOver's focus-trap + scroll-lock, ComboBox's ReDoS-safe filter).
| Component | Source (`console2/src/components/ui/`) | New home | Status |
|---|---|---|---|
| `DataTable<T>` (generic typed list) + `Column` | `DataTable.tsx` | `@hanzo/ui` (`product/DataTable`) | ✅ |
| `PageHeader` | `PageHeader.tsx` | `@hanzo/ui` | ✅ |
| `Field*` (`FieldRow/Text/TextArea/Switch/Select/Slider`) | `Field.tsx` | `@hanzo/ui` | ✅ |
| **Charts** (`Sparkline/LineChart/BarChart/Donut/BarRows`, `CHART_PALETTE`) | `Charts.tsx` | `@hanzo/ui` | ✅ |
| `Donut` (standalone dependency-free ring) | `Donut.tsx` | `@hanzo/ui` as **`DonutRing`** (alias — Charts.Donut is canonical) | ✅ |
| `StatusTag` (health verdict → pill) | `StatusTag.tsx` | `@hanzo/ui` | ✅ |
| `EmptyState` (DO/Vercel-class first-run) | `EmptyState.tsx` | `@hanzo/ui` | ✅ (**decoupled** — see §I) |
| `Metric*` (`MetricCard/MiniBars/UtilBar/LegendDot/Panel/HintButton`, `SERIES`) | `Metric.tsx` | `@hanzo/ui` (its `Sparkline` preserved as **`MetricSparkline`**) | ✅ |
| `ComboBox` + pure `filterOptions`/`isKnownOption` | `ComboBox.tsx`, `combobox/filter.ts` | `@hanzo/ui` | ✅ (+ `filter.test.ts`) |
| `PrimaryButton` · `HanzoMark` · `ProductIcon` · `ProviderLogo` | resp. files | `@hanzo/ui` | ✅ |
| `SlideOver` (a11y drawer) · `SelectMenu` · `Toast` (`useToast`) | resp. files | `@hanzo/ui` | ✅ (SlideOver import decoupled `~/…/color``./color`) |
| `Reorder<T>` (pointer DnD) · `FadeIn` · `ThemeToggle` · `color` (`asColor`/`IconLike`) | resp. files | `@hanzo/ui` | ✅ (+ `Reorder.test.ts`) |
| `DetailPane` (right-side pane over SlideOver) | `components/DetailPane.tsx` | `@hanzo/ui` | ⏳ (liftable; lands with Step 3 — depends only on SlideOver) |
| `ChunkGuard` (stale-deploy chunk-error reload) | `components/ChunkGuard.tsx` | `@hanzo/ui` | ⏳ (fully portable; lands with Step 3) |
### C. Design tokens + motion → `@hanzo/ui` ✅
The brief's premise (`globals.css` `t_dark`/`t_light` token blocks) is **corrected**: `t_dark`/`t_light` are `@hanzo/gui` (Tamagui) theme **class names**; the calm values live in three real places, all preserved:
| Polish | Source | New home |
|---|---|---|
| Calm dark-first tokens (surface, text, accent `#60a5fa`, tag tones) — raw hex, theme-config independent | `pkg/data/src/theme.ts` | `@hanzo/ui` (top-level `tokens`/`TAG_TONES`/`tagTone`) |
| OKLCH shadcn-compatible palette (soft-charcoal `oklch(0.145 0 0)`, `--radius: 0.5rem`, indigo sidebar accent) | `pkgs/ui/style/hanzo-default-colors.css`, `@hanzo/tokens` | unchanged (legacy shadcn line); the gui line uses the hex tokens above |
| **Motion vocabulary**`fade-up` (FadeIn), `collapse`/`slide`/`fade` (shell/drawer), `drag`, `skeleton`/`pulse`/`row-in`; all `prefers-reduced-motion`-guarded | `console2/app/globals.css` (motion section) | **`@hanzo/ui/styles/motion.css`** (verbatim) — `import '@hanzo/ui/styles/motion.css'` once at app root |
### D. Generic DocType renderer → `@hanzo/ui` ⏳ (Step 3, FINAL — active lane)
Source: `console2/src/components/doctype/*`. **Actively edited by the CMS/ERP/Help lanes (untracked).** Dependency-**injected** (`client: FrameworkClient` prop) — not `~/lib/api`-coupled — so the real move-blockers are `~/lib/framework/{types,fields}` + the `ui/*` primitives (now in `@hanzo/ui`) + `@hanzo/data` (now `@hanzo/ui/data`).
| File | Class | Step-3 disposition |
|---|---|---|
| `MediaGrid.tsx` | presentational | → `@hanzo/ui` (cleanest lift; props-only DAM gallery) |
| `DocTypeRecords.tsx` / `DocTypeDetail.tsx` | mixed (data-bound shell over `@hanzo/data` views) | shell **stays in console**; renders `@hanzo/ui/data` views (already true) |
| `CollectionsBrowser.tsx` | mixed (card grid + install/create orchestration) | presentational card-grid → `@hanzo/ui`; orchestration stays |
| `data.ts` | glue (relation loading) | stays in console |
### E. LivingOverview → `@hanzo/ui` ⏳ (Step 3 — active lane)
Source: `console2/src/components/products/overview/living/*` (untracked/modified). Pure/presentational parts portable; app-glue concentrated in `registry.ts` (live API clients).
| Part | Class | Step-3 disposition |
|---|---|---|
| `motion.ts`, `hooks.ts`, `logic.ts`, `config.ts` (types) | pure | → `@hanzo/ui` (unit-tested; count-up, poll clock, unit formatting) |
| `tiles.tsx`, `LivingOverview.tsx` | presentational (reuse `ui/Charts` verbatim) | → `@hanzo/ui` (once `config.ts`'s one `~/lib/products/registry` `ProductIcon` type is swapped for `@hanzo/ui`'s `IconLike`) |
| `adapters.ts`, `registry.ts` | glue (map REAL `/v1` sources → `OverviewData`) | **stay in console** |
### F. Framework / Base-data libs → stay in console 🏠
`src/lib/framework/*` (DocType wire contract + `FrameworkApi` client + pure `fields.ts` mapper to `@hanzo/data`) and `src/lib/base-data/*` (Base REST client + schema→field mapper) are **app data-access glue**, not UI. They stay in the console. Their pure mappers (`docTypeToFields`, `baseCollectionToFields`) could later publish as a small `@hanzo/base-data` adapter, but they are not UI components and are out of scope for `@hanzo/ui`.
### G. App-coupled console components → 🔧 pending prop-injection (NOT yet in the lib)
These import app `~/lib`/session/router/branding and must be made presentational (inject props) before they belong in a host-agnostic lib. Kept in console for now; the injection contract is specified so the eventual lift is mechanical.
| Component | Coupling | Inject to lift |
|---|---|---|
| `BackendStateCard` (`BackendState.tsx`) | `~/lib/api` `ApiError` | accept a numeric `status` (or shared error shape) instead of `ApiError` |
| `BrandLogo` | session + live IAM `organization()` + `~/config` + branding | `orgName`, `logoUrl` (or a `loadOrgLogo` loader), brand mark/name as props |
| `Breadcrumbs` | `next/navigation` + catalog lookups | `crumbs[]` (or `pathname` + resolver) + `onNavigate` |
| `Loader` / `BrandMark` | `~/config` + brand logo pkgs | `brand`/`brandName` + the animated-SVG getter |
| `States` (`ErrorState`, `OperatorAccessRequired`) | `~/lib/api` + session + branding | the error, the account identity, brand strings |
---
## What this pass built (Step 2)
New in **`pkg/ui`** (was a bare `src/` staging dir — no package):
- `package.json``@hanzo/ui` `8.0.0`, source-published (`files: ["src"]`, exports map to `.ts`), peers `@hanzo/gui >=7.2.2`, `@hanzo/data >=1.2.0`, `react >=19`; MIT (repo `LICENSE.md`). Exports: `.`, `./product`, `./data`, `./primitives/bases/data`, `./styles/motion.css`.
- `src/index.ts` — top-level barrel (product layer + tokens).
- `src/product/index.ts` — product barrel; **collision-free** (Charts `Sparkline`/`Donut` canonical; Metric's → `MetricSparkline`; standalone ring → `DonutRing`; `ComboOption` from the one filter module) — **zero loss**.
- `src/data.ts``export * from '@hanzo/data'` (the record layer, one home).
- `src/styles/hanzo-motion.css` — the motion vocabulary, verbatim.
- `tsconfig.json`, `vitest.config.ts`, `gui.config.ts`, `gui.d.ts`, `.npmignore`, `README.md` — mirror the proven `pkg/data` setup.
- **One decouple fix:** `product/EmptyState.tsx` no longer imports `~/lib/products/registry`; it uses the local `IconLike` type — the last host coupling in the product tree is gone.
**Green:** `tsc --noEmit` = 0 errors (strict); `vitest run` = 12/12 (`combobox/filter`, `Reorder`). Every product component is host-agnostic (imports only `react`, `@hanzo/gui`, `@hanzogui/*`, `@hanzo/data`, relative).
## Clean-room guarantee (preserved)
`pkg/data` audited for GPL/Twenty contamination: **none.** No GPL, no copied license headers/SPDX, no Twenty entity/decorator architecture. The field/record model is an independent `FieldType` union + `FieldDefinition` + runtime `Map` registry (records are plain `Record<string, unknown>`). "Twenty" appears **only as benchmark prose** ("Airtable/Twenty-class polish, clean-room"). License: MIT (repo `LICENSE.md`). `@hanzo/ui` inherits the same posture.
---
## Naming / version — DECIDED: `@hanzo/ui@8`, shadcn retired to `@hanzo/ui-shadcn`
**Decision:** the gui-based unified library takes the `@hanzo/ui` name **forward at `8.0.0`** (aligning with the "Hanzo Cloud 8.x" umbrella; major = breaking re-platform). The legacy shadcn/Radix line (`pkgs/ui`, v5.7.0) is **retired by renaming** to `@hanzo/ui-shadcn` (never hard-deleted) — it stays fully alive under the new name, freeing `@hanzo/ui` for v8. Precedent: `pkg/data@1.2.0` already superseded `pkgs/data@1.1.0` under the same name.
This is **DONE (repo-local):** `pkg/ui/package.json` is `@hanzo/ui@8.0.0`, GREEN. The rest is a coordinated, **sequenced** retire — because publishing `@hanzo/ui@8` (a different, gui-based API with no shadcn `Button/Card/Dialog`) under the name ~20 repos consume for shadcn primitives will BREAK any consumer that resolves to `@8`. So order matters:
**Blast radius (measured across `~/work/hanzo`).** Declared deps on `@hanzo/ui` in ~20 repos. Most pin `^5.x` (semver-safe from an `@8` bump): paas, chat, platform, app, hanzo.ai, o11y, docs, mdx, hanzobot, ui-repo `pkgs/checkout` `^5.3`, `pkgs/agent-ui` `^5.0`. **Would break on `@8`:** `hanzoai/identity/app` (`"latest"`), ui-repo `pkgs/commerce` (`>=5.0.0`); `app/` uses `workspace:^`. The `ui.hanzo.ai` docs app + `pkgs/{commerce,checkout,agent-ui}` import the shadcn line internally.
**Publish reality.** `.github/workflows/publish-on-tag.yml` publishes **`pkgs/ui`** (the shadcn line) as `@hanzo/ui` on a `v*` tag — it does not reference `pkg/ui`. So a tag push today publishes shadcn, not v8. Publishing v8 needs the workflow rewired to build/publish `pkg/ui`. `npm` is not authed locally (`npm whoami` empty) — per house rules, publish goes through **CI (self-hosted runners, canonical org `NPM_TOKEN`)**, not a local `npm publish`.
**Safe sequence to fully land v8 (each step reversible until the tag push):**
1.`pkg/ui` = `@hanzo/ui@8.0.0`, GREEN (done, committed to a branch).
2. Rename `pkgs/ui` name → `@hanzo/ui-shadcn`; update the internal ui-repo consumers (`app/`, `pkgs/{commerce,checkout,agent-ui}`) + `check-no-hanzogui`/registry scripts that reference it.
3. Migrate external consumers off `@hanzo/ui``@hanzo/ui-shadcn` (start with the break-risk ones: `identity` `latest`, `commerce` `>=5`; the `^5` pins are safe to migrate at leisure). ~20 repos — do as a tracked sweep or flag per-repo.
4. Rewire `publish-on-tag.yml` (and `release.yml`) to build + publish `pkg/ui` as `@hanzo/ui@8`, and `pkgs/ui-shadcn` as `@hanzo/ui-shadcn`.
5. `npm deprecate '@hanzo/ui@<8' 'moved to @hanzo/ui-shadcn; @hanzo/ui@8+ is the @hanzo/gui-based unified lib'`.
6. Tag `v8.0.0` → CI publishes `@hanzo/ui@8.0.0`. Verify `npm view @hanzo/ui@8.0.0`.
**Gated on the user's direct go-ahead** (irreversible / globally-visible / ecosystem-wide): steps 26 — the `pkgs/ui` rename, the ~20-repo consumer sweep, the CI rewire, `npm deprecate`, and the `v8.0.0` tag push that triggers publish. These were not executed autonomously.
---
## Step 3 — console re-point (STAGED)
**Gate (per the brief):** cloud `/v1/framework/modules` live **AND** console CMS/ERP/Help native.
- ✅ Backend: `/v1/framework/modules[/:module[/install]]` is **implemented + wired** (`cloud/clients/framework/framework.go:71-73`, HIP-0106 order 129, bound in `subsystems.go:130`, real tests).
- ⏳ Console: `CmsModule.tsx`, `ErpModule.tsx`, `HelpModule.tsx`, `components/doctype/` are **untracked/in-flight** on `feat/console-native-cms`.
→ Gate is **split**, so the re-point is **staged, not applied.** I deliberately did **not** touch `console2`'s working tree (it holds the lanes' uncommitted work — editing it would collide and risk loss, the opposite of the goal).
**Ready-to-apply re-point (mechanical, once the lanes land + merge):**
1. `console2` deps: keep `@hanzo/gui`, `@hanzo/data`; add `@hanzo/ui` (`^6.0.0`). (`@hanzo/data` may stay as a direct dep or be dropped in favor of `@hanzo/ui/data` — both resolve to the same source.)
2. Re-point imports (delete the now-duplicated in-console copies — extract, don't copy):
- `~/components/ui/{DataTable,PageHeader,Field,Charts,Donut,StatusTag,EmptyState,Metric,ComboBox,combobox/filter,PrimaryButton,HanzoMark,ProductIcon,ProviderLogo,SlideOver,SelectMenu,Toast,Reorder,FadeIn,ThemeToggle,color}`**`@hanzo/ui`** (or `@hanzo/ui/product`). Two spot-renames: Metric's `Sparkline``MetricSparkline`, standalone `Donut``DonutRing`.
- `@hanzo/data` (in `doctype/*`, `base-data/*`, `products/*Module`) → **`@hanzo/ui/data`** (identical surface).
- `~/components/{DetailPane,ChunkGuard}`**`@hanzo/ui`**.
- `app/globals.css` motion block → `import '@hanzo/ui/styles/motion.css'` (keep base resets local).
- Move the 5 app-coupled components (§G) into the lib only after applying their inject-props contract; until then they stay local.
3. Verify **identical render**: `tsc --noEmit` + `vitest` + `next build` green, then headless-Playwright the live pages pixel-same (the polish is byte-identical, so parity is expected).
**Report:** `@hanzo/ui` is the ONE unified library — product layer + record layer (`@hanzo/data`) + charts + calm tokens + motion, all on `@hanzo/gui`, presentational, cross-platform, clean-room, GREEN. Console re-point is **ready to apply once the CMS/ERP/Help lanes land**; it was not merged to avoid colliding with that in-flight work.
## Follow-ups (semver-minor, with visual e2e)
- Collapse the preserved Sparkline/Donut variants to one each (`MetricSparkline``Sparkline`, `DonutRing``Donut`) once call-sites are proven identical.
- Lift §G's five components after applying their prop-injection contracts.
- Consider publishing the pure `framework`/`base-data` mappers as a small `@hanzo/base-data` adapter (not UI).
+49 -33
View File
@@ -1,10 +1,10 @@
# Contributing
Thanks for your interest in contributing to ui.shadcn.com. We're happy to have you here.
Thanks for your interest in contributing to ui.hanzo.com. We're happy to have you here.
Please take a moment to review this document before submitting your first pull request. We also strongly recommend that you check for open issues and pull requests to see if someone else is working on something similar.
If you need any help, feel free to reach out to [@shadcn](https://twitter.com/shadcn).
If you need any help, feel free to reach out to [@hanzo](https://x.com/hanzoai).
## About this repository
@@ -12,9 +12,7 @@ This repository is a monorepo.
- We use [pnpm](https://pnpm.io) and [`workspaces`](https://pnpm.io/workspaces) for development.
- We use [Turborepo](https://turbo.build/repo) as our build system.
- Releases are semver-driven: bump a package's `version` in its `package.json` and
merge to `main`. CI (`.github/workflows/publish.yml`) detects the version change
and publishes that package to npm. One step, one source of truth.
- We use [changesets](https://github.com/changesets/changesets) for managing releases.
## Structure
@@ -22,25 +20,28 @@ This repository is structured as follows:
```
apps
└── v4
└── www
├── app
├── components
├── content
└── registry
── new-york-v4
── default
│ ├── example
│ └── ui
└── new-york
├── example
└── ui
packages
└── shadcn
└── cli
```
| Path | Description |
| -------------------- | ---------------------------------------- |
| `apps/v4/app` | The Next.js application for the website. |
| `apps/v4/components` | The React components for the website. |
| `apps/v4/content` | The content for the website. |
| `apps/v4/registry` | The registry for the components. |
| `packages/shadcn` | The `shadcn` package. |
| Path | Description |
| --------------------- | ---------------------------------------- |
| `apps/www/app` | The Next.js application for the website. |
| `apps/www/components` | The React components for the website. |
| `apps/www/content` | The content for the website. |
| `apps/www/registry` | The registry for the components. |
| `packages/cli` | The `hanzo-ui` package. |
## Development
@@ -78,61 +79,76 @@ You can use the `pnpm --filter=[WORKSPACE]` command to start the development pro
#### Examples
1. To run the `ui.shadcn.com` website:
1. To run the `ui.hanzo.com` website:
```bash
pnpm --filter=v4 dev
pnpm --filter=www dev
```
2. To run the `shadcn` package:
2. To run the `hanzo-ui` package:
```bash
pnpm --filter=shadcn dev
pnpm --filter=hanzo-ui dev
```
## Running the CLI Locally
To run the CLI locally, you can follow the workflow:
1. Start by running the dev server:
1. Start by running the registry (main site) to make sure the components are up to date:
```bash
pnpm dev
pnpm v4:dev
```
2. In another terminal tab, test the CLI by running:
2. Run the development script for the CLI:
```bash
pnpm shadcn
pnpm hanzo:dev
```
3. In another terminal tab, test the CLI by running:
```bash
pnpm hanzo
```
To test the CLI in a specific app, use a command like:
```bash
pnpm shadcn <init | add | ...> -c ~/Desktop/my-app
pnpm hanzo <init | add | ...> -c ~/Desktop/my-app
```
4. To run the tests for the CLI:
```bash
pnpm --filter=hanzo test
```
This workflow ensures that you are running the most recent version of the registry and testing the CLI properly in your local environment.
## Documentation
The documentation for this project is located in the `v4` workspace. You can run the documentation locally by running the following command:
The documentation for this project is located in the `www` workspace. You can run the documentation locally by running the following command:
```bash
pnpm --filter=v4 dev
pnpm --filter=www dev
```
Documentation is written using [MDX](https://mdxjs.com). You can find the documentation files in the `apps/v4/content/docs` directory.
Documentation is written using [MDX](https://mdxjs.com). You can find the documentation files in the `apps/www/content/docs` directory.
## Components
We use a registry system for developing components. You can find the source code for the components under `apps/v4/registry`. The components are organized by styles.
We use a registry system for developing components. You can find the source code for the components under `apps/www/registry`. The components are organized by styles.
```bash
apps
└── v4
└── www
└── registry
── new-york-v4
── default
│ ├── example
│ └── ui
└── new-york
├── example
└── ui
```
@@ -141,7 +157,7 @@ When adding or modifying components, please ensure that:
1. You make the changes for every style.
2. You update the documentation.
3. You run `pnpm registry:build` to update the registry.
3. You run `pnpm build:registry` to update the registry.
## Commit Convention
@@ -180,9 +196,9 @@ If you have a request for a new component, please open a discussion on GitHub. W
## CLI
The `shadcn` package is a CLI for adding components to your project. You can find the documentation for the CLI [here](https://ui.shadcn.com/docs/cli).
The `hanzo-ui` package is a CLI for adding components to your project. You can find the documentation for the CLI [here](https://ui.hanzo.com/docs/cli).
Any changes to the CLI should be made in the `packages/shadcn` directory. If you can, it would be great if you could add tests for your changes.
Any changes to the CLI should be made in the `packages/cli` directory. If you can, it would be great if you could add tests for your changes.
## Testing
-106
View File
@@ -1,106 +0,0 @@
# Hanzo Design System — Canonical Tokens
`@hanzo/ui` is the single source of truth for the shared Hanzo product look across
the **Tailwind** apps (hanzo.chat, hanzo.app, hanzo console, commerce, hanzo-desktop).
Change a value here; apps converge on it. This file is that source of truth for the
three things that must read as **one product**: typography, the sidebar/panel system,
and the dark-black palette.
> One library: **`@hanzo/ui@8`** (`pkg/ui`, on **`@hanzo/gui`**) IS the component
> library — the cross-platform product/record layer every surface consumes.
> **`@hanzo/ui-shadcn`** (`pkgs/ui`) is the legacy shadcn/Tailwind/Radix kit, kept
> only for existing v5 consumers (pin `@hanzo/ui-shadcn@^5`; no new adoptions).
> This file stays the source of truth for the *token values* (fonts, dark palette,
> the sidebar glyph) both render.
---
## 1. Typography — Basel Grotesk + Geist Mono
| Role | Family | Notes |
|------|--------|-------|
| UI / body / display / heading (`sans`) | **Basel Grotesk** | Self-hosted. Book = weight **400**, Medium = weight **500**. |
| code / data / mono (`mono`) | **Geist Mono** | `next/font/google` (`Geist_Mono`) or the geist CDN. |
| Arabic / Hebrew (`--font-ar` / `--font-he`) | unchanged | i18n only — keep. |
**Dropped as defaults:** Geist Sans, DM Sans, Figtree, Inter, PT Sans, Roboto Mono.
Basel is a **licensed, non-Google** face — **self-host** the woff2/woff, do NOT use
`next/font/google` for it. Canonical files (mirror lux.exchange):
`Basel-Grotesk-Book.woff2/.woff` (400), `Basel-Grotesk-Medium.woff2/.woff` (500).
`@font-face` (weights 400/500, `font-display: swap`, `font-style: normal`):
```css
@font-face {
font-family: 'Basel';
font-style: normal;
font-weight: 400; /* Book; 500 = Medium */
font-display: swap;
src: url('.../Basel-Grotesk-Book.woff2') format('woff2'),
url('.../Basel-Grotesk-Book.woff') format('woff');
}
```
Per-app adoption (converge the value, keep each app's own mechanism):
- **@hanzo/ui / Next apps** → `next/font/local` for Basel (`--font-basel-sans`) +
`next/font/google` `Geist_Mono` (`--font-geist-mono`). See `app/lib/fonts.ts`;
tailwind `sans → var(--font-basel-sans)`, `mono → var(--font-geist-mono)`.
- **Vite + Tailwind apps** (chat, launcher, desktop) → self-host Basel `@font-face`
+ geist-mono CDN import; tailwind `fontFamily.sans = ['Basel', …]`,
`mono = ['Geist Mono', …]`.
- **Tamagui (console)** → Basel `@font-face` in globals + override the Tamagui
`body`/`heading` font `family` to Basel; Geist Mono for `code`/`pre`.
---
## 2. Sidebar toggle icon — lucide `PanelLeft`
One glyph everywhere: lucide **`PanelLeft`** (the shadcn `SidebarTrigger` default).
Where a directional open/close affordance is wanted, use the pair
**`PanelLeftClose`** (expanded) / **`PanelLeft`** (collapsed). Never a hamburger,
a magnifier, a directional arrow, or a bespoke panel SVG for the sidebar toggle.
- Icon: stroke-2, ~1620px, `currentColor`.
- Button: ghost/outline, square (`size-7`/`h-6 w-6`), subtle hover.
---
## 3. Sidebar + panels
| Spec | Value |
|------|-------|
| Sidebar width (expanded) | **16rem / 256px** (`SIDEBAR_WIDTH`) |
| Sidebar width (collapsed / icon rail) | **3rem / 48px** (apps vary 4870px) |
| Sidebar / panel surface | resting **#0a0a0a** over the true-black page |
| Border / separation | `border-border` — subtle white-alpha ~10% in dark (`border-r` / `border-l`) |
| Item hover | subtle `white/5` |
| Item active | monochrome `white/10`**no colored accent** (the house style is monochrome) |
| Right panel rail | `border-l border-border`, same surface, collapsible |
Prefer the `@hanzo/ui` `Sidebar` primitive (`pkgs/ui/primitives/sidebar.tsx`,
`SidebarTrigger``PanelLeft`) where the app can consume it; otherwise match these
classes/tokens.
---
## 4. Dark-black palette (true-black OLED)
The house dark theme is a **true-black** canvas (matches hanzo.ai marketing +
hanzo.chat OLED), with a shallow surface-depth ladder for cards/panels and quiet
hairline borders — never harsh pure-white on pure-black.
| Token | Value | Use |
|-------|-------|-----|
| Page background | **#000000** (`oklch(0 0 0)`) | body / canvas |
| Surface / sidebar / panel (resting) | **#0a0a0a** | sidebars, panels, cards |
| Press | **#050505** | pressed surface |
| Elevated / hover | **#171717** | hover, raised card |
| Border / divider | **rgba(255,255,255,0.10)** (≈ `#171717` opaque on black) | hairlines |
| Foreground (primary text) | near-white **#ededf1** (`oklch(0.985)`) — not pure `#fff` | body text |
| Muted / secondary text | `white/70` (≈ `#a1a1aa`) | secondary |
Keep each app's theme-token engine (CSS vars / Tailwind tokens / Tamagui `$color*`);
converge the **values/usage** to the table above, don't rip the engine.
Reference: `pkgs/ui/style/hanzo-default-colors.css` (`.dark` / `.hanzo-ui-dark-theme`).
-97
View File
@@ -1,97 +0,0 @@
# ui.hanzo.ai — the @hanzo/ui docs + component registry, served by the house
# static server (ghcr.io/hanzoai/static, a Go binary), same as every other Hanzo
# static site. Built on our own runners, never on a laptop and never by a
# third-party builder.
#
# The app is a Next.js static export: `pnpm build` in app/ writes app/out, which
# is the entire site — docs, the registry JSON the CLI reads, and the static
# /api/registry/*.json index.
FROM node:22 AS builder
WORKDIR /src
ENV NEXT_TELEMETRY_DISABLED=1
# Publishable ingest key (pk-…), baked in at build because a static export has no
# server to read config at runtime. Write-only and HMAC-verified to one org, so it
# is safe in a public bundle; the deployment that builds decides which org the
# site reports as.
#
# ONE name, end to end: KMS holds `deploy/PUBLISHABLE_KEY`, hanzo.yml declares it
# as this image's build_secret, and the KMS name IS the build-arg name. NEXT_PUBLIC_
# is added HERE because that prefix is what makes Next inline it — the app reads
# process.env.NEXT_PUBLIC_PUBLISHABLE_KEY.
#
# Do NOT re-declare `ARG NEXT_PUBLIC_PUBLISHABLE_KEY` after the ENV below. A later
# ARG of the same name shadows the ENV with its own (empty) default, and the build
# stays green while the bundle ships blank — which is exactly how hanzo.chat 1.0.58
# shipped a keyless site from a fully green run.
#
# Fail CLOSED, on BOTH ways this goes wrong.
#
# empty — builds, serves and looks correct while cloud answers
# `401 ingest_key_required` for every anonymous pageview. The previous
# `ARG …=""` default made that the normal outcome of an unattended
# build, which is why no automated lane could ever publish a working
# image.
# `pk_…` — the OLDER key format. v5.7.6 shipped one, passed by hand on a local
# `docker build`, and it is now dead: api.hanzo.ai 401s it on both the
# fetch and beacon transports. A hand-passed key goes stale in silence,
# so requiring the current `pk-` shape refuses the stale one outright.
#
# Neither failure is visible from outside the artifact, so refuse the artifact.
ARG PUBLISHABLE_KEY
ENV NEXT_PUBLIC_PUBLISHABLE_KEY=$PUBLISHABLE_KEY
RUN case "$PUBLISHABLE_KEY" in \
pk-*) : ;; \
'') echo "PUBLISHABLE_KEY is empty - pass --build-arg PUBLISHABLE_KEY=<pk-...> (KMS deploy/PUBLISHABLE_KEY, env prod)" >&2; exit 1 ;; \
*) echo "PUBLISHABLE_KEY is not a publishable key (expected a pk- prefix)" >&2; exit 1 ;; \
esac
# 300+ prerendered pages; the default heap is not enough.
ENV NODE_OPTIONS=--max-old-space-size=8192
RUN corepack enable
COPY . .
# The lockfile is committed, so the build resolves exactly what was reviewed.
RUN pnpm install --frozen-lockfile
# Workspace packages the app imports must be built first: their package.json
# exports point at dist/. Only @hanzo/event qualifies -- .npmrc sets
# link-workspace-packages=true and the lockfile resolves it to link:../pkgs/event.
#
# There used to be a `cd pkgs/ui` line here. pkgs/ui was @hanzo/ui-shadcn, deleted
# in 5dbdb2943 when shadcn was consolidated to one home, and that commit did not
# touch this file -- so every build since has run `cd` into a directory that does
# not exist and died with exit code 2 before compiling anything. The app takes
# @hanzo/ui from the registry now (npm:@hanzo/ui-shadcn@^5), not the workspace.
RUN cd pkgs/event && pnpm build
# Builds the component registry, then the site (app/package.json build script).
#
# ...and then PROVES the key reached the client bundle. The gate above proves a
# key was PASSED; only this proves it was INLINED. Those are different failures:
# a rename on either side of `process.env.NEXT_PUBLIC_PUBLISHABLE_KEY` leaves the
# build-arg intact and the bundle keyless, and a static export cannot report that
# at runtime because there is no runtime.
#
# `&&`, never `;` — a `;` chain returns the LAST command's status, so a failed
# build followed by a passing grep exits 0 and the image is published.
RUN cd app && pnpm build && \
if [ -z "${NEXT_PUBLIC_PUBLISHABLE_KEY}" ]; then \
echo "ERROR: NEXT_PUBLIC_PUBLISHABLE_KEY is empty after a successful build." >&2; exit 1; \
elif grep -rqF "${NEXT_PUBLIC_PUBLISHABLE_KEY}" out; then \
echo "Build OK - ingest key inlined into app/out, verified"; \
else \
echo "ERROR: key supplied but NOT present in app/out - ui would ship unattributed" >&2; exit 1; \
fi
# 0.5.1 serves a directory's index.html in place. On 0.4.1 every page 301'd to
# an explicit /index.html, which leaks that filename into the address bar and
# into the URLs Next builds for its route prefetches.
FROM ghcr.io/hanzoai/static:0.5.2-amd64
COPY --from=builder /src/app/out /public
EXPOSE 3000
# No -spa: the export writes a real index.html per route (trailingSlash), so a
# missing path must 404 rather than silently render the home page.
ENTRYPOINT ["/static", "-port", "3000", "-root", "/public"]
+26 -495
View File
@@ -1,313 +1,16 @@
# @hanzo/ui — LLM context
# Hanzo UI - LLM Context
**What this is.** The React component library for AI applications: 161+
components, 24+ blocks, two themes, and a single typed import surface, all on ONE
substrate (`@hanzo/gui`) so the same import runs on web, native and desktop.
Published as `@hanzo/ui` (v8) on npm. Docs at https://ui.hanzo.ai. Dev port: 3003.
## Overview
**Canonical role.** This is the canonical impl repo for Hanzo's web UI kit —
frontend components, not an SDK. It sits alongside the two SDK lines (full cloud
SDK generated from OpenAPI in `hanzo-<lang>/sdk` + wrapper in `hanzoai/<lang>-sdk`;
AI/agents lib `hanzo` in `hanzoai/python-sdk` flagship, `@hanzo/ai` in `hanzo-js/ai`).
`@hanzo/event` (telemetry, `POST /v1/event`) lives here in `pkgs/event`. DRY: one
impl, one place — link out, never duplicate.
React component library (shadcn/ui fork). 161 components, 24+ blocks, two themes, multi-framework. Published as `@hanzo/ui` on npm.
**Brand rules (hard).**
- Never call Hanzo an "LLM gateway" or position it against LiteLLM — it is a full
AI SDK / AI cloud, not a proxy. Purge that framing on sight.
- Paths are `/v1/…` only — never an `/api/` prefix.
- Zen models are our own family — never name upstream models.
- Voice: "Hanzo — the Open AI Cloud." Developer-first, crisp, no emoji-spam.
**Install / run.**
```bash
pnpm add @hanzo/ui # consume
# dev:
pnpm install && pnpm build:registry && pnpm dev # registry MUST build before app
```
**Key entry points.** `pkg/ui/` (core lib + v8 subpaths: /product /data /canvas
/dashboard /usage /gitops) · `app/registry/{default,new-york}/`
(component SOURCE OF TRUTH) · `pkgs/*` (auto-published `@hanzo/*` packages) ·
`packages/shadcn/` (CLI) · `app/content/docs/` (MDX docs). Publish = bump a
package `version` + merge to main (`.github/workflows/publish.yml`).
**Spec / more context.** Canonical SDK + docs model: `~/work/hanzo/SDK-ARCHITECTURE.md`.
Detailed engineering notes (build order, import surface, telemetry, upstream sync,
gotchas) follow below.
---
## v8 — the canonical `@hanzo/ui` (`pkg/ui`)
`@hanzo/ui@8` (`pkg/ui`) is THE Hanzo component library, and there is ONE
substrate: every component renders through `@hanzo/gui` (Tamagui) primitives on
the `@hanzo/tokens` scale, so one import works on web, native (expo) and desktop
(Tauri). The Radix + Tailwind surface it used to ship alongside is gone — it
lives on as its own package, `@hanzo/shadcn`, and `@hanzo/ui` no longer depends
on it, on any `@radix-ui/*` package, on cva, cmdk or sonner.
`@hanzo/ui-shadcn` (`pkgs/ui`, v5.x) is the legacy standalone package —
superseded, being retired.
### Layout
```
pkg/ui/src/
core/ design core: cn.ts (clsx+tailwind-merge),
tokens.ts (re-export of @hanzo/tokens), fonts.ts (Geist vars)
root.tsx <Hanzo> — the root. Carries the gui config AND the stylesheet.
gallery.tsx EVERY component, once, in every variant. The one list.
theme.css SELF-CONTAINED token CSS vars + Geist Sans/Mono — the identity
backends/gui/ THE component surface on @hanzo/gui. index.ts is its manifest.
product/ the product/app layer (charts, PageHeader, ComboBox, …)
models/ the unified ModelSelector + catalog helpers
primitives/ GENERATED per-member entrypoints (scripts/gen-primitives.mjs)
index.ts root barrel = the component surface + cn
```
### Out of the box — the package carries its own config and its own CSS
```tsx
import { Hanzo, Button } from '@hanzo/ui'
<Hanzo><Button>Ship</Button></Hanzo>
```
That is the entire setup. No `gui.config.ts`, no CSS import, no generator script.
Three things used to be each app's job:
1. **The stylesheet.** gui compiles a style prop to an atomic class the first
time something RENDERS it, so the sheet does not exist until a render has
happened — which is why every app ran a `gen-gui-css.mjs` of its own. hanzo.app
never did: it shipped 103 `_bg-` classes and 26 `_dsp-` classes against a
stylesheet containing ZERO of either, every gui-styled element unstyled in
production, green build throughout. The render happens at OUR publish time now
(`scripts/gen-css.mjs` renders `src/gallery.tsx` in both themes and writes
`dist/styles.css` — 381 KB, 35 KB gzipped, 340 atomic selectors), and
`<Hanzo>` imports it. Styles gui generates at RUNTIME for props we could not
know at publish time still reach the document through `insertStyleRules`;
the shipped sheet is what makes the FIRST paint and every SSR/static render
correct.
2. **The config.** `<Hanzo>` passes `config` from `gui-config.ts` to
`GuiProvider` — as a VALUE, never a bare `import './gui-config'`. Vite 8
(rolldown) ignores package.json `sideEffects` ARRAYS outright: with any array
the registration is dropped and the first render dies on "Missing hanzogui
config"; only `sideEffects: true` keeps it, and that costs +63% bundle
(404 KB → 661 KB measured). Correctness does not live in bundler metadata.
3. **The theme.** gui throws `Missing theme.` for any component with no root
theme context, so a root is structurally required — there is no version of
this with no root at all. Forgetting `<Hanzo>` is therefore a hard crash on
first paint, never a silently unstyled page.
`theme.css` is dark-first at `:root` (it used to claim dark-first while shipping
LIGHT at `:root`, so an app that mounted the dark default and read `--background`
got white). `.light` retunes, and both answer to gui's own `.t_light`/`.t_dark`
that `<Hanzo>` stamps on the body — one theme, named the same by the CSS custom
properties and the component tokens.
### Three tests, one list of components
`src/gallery.tsx` is the specification of "what this package has to style", and
all three layers render THAT — a second copy of the list is how a component gets
styled by one and missed by another.
| Layer | Command | What it catches |
|---|---|---|
| `src/styles.test.tsx` | `pnpm test:unit` | every atomic class the gallery renders vs every class `dist/styles.css` defines a rule for. Not "the intersection is large" — TOTAL. Catches a stale sheet. |
| `src/backends/gui/render.test.tsx` | `pnpm test:unit` | the surface mounts under the real provider; a component that throws on first paint fails. |
| `test/consumer.spec.ts` | `pnpm test:consumer` | packs the tarball, installs it into a temp app OUTSIDE the repo (never a workspace link — that hides `files`/`exports`/`workspace:*` defects), builds, serves, and asserts COMPUTED styles + screenshots at 390 and 1280 in both themes. |
The consumer spec also fails on a solid-white border (the `@hanzo/design`
`border-card: var(--white…)` defect — borders are low-alpha hairlines) and on any
element that has a text child and a zero-height box.
### House rules for a component
- Style through gui props and theme tokens (`$background`, `$color12`,
`$borderColor`) — never a utility class string, never a hard-coded font.
- Touch targets meet the 44px floor via `hitSlop`, never via padding.
- Behaviour (focus, portalling, keyboard, a11y) comes from the matching
`@hanzogui/*` primitive; nothing reimplements it.
- Free-form text children go through `ink()`; `data-slot` markers through
`slot()`. One helper each, one place.
- Module scope stays side-effect free — `forwardRef`/`createContext` calls carry
`/* @__PURE__ */` and nothing assigns `displayName`, so importing one symbol
never drags a neighbour in. A one-symbol import bundles ~4.7KB against ~29KB
for the whole barrel.
- Utility classes carry `hz-`. This sheet used to claim `.row`, `.skeleton`,
`.fade`, `.mono`, `.drag` and `.tnum` at the document level, in a package an
app imports once at its root; an app with its own `.row` got no warning, it got
whichever rule the cascade preferred. The unprefixed selectors survive as
aliases on the same rules for one minor version and are **REMOVED IN 8.1.0**.
Nothing here emits them — `styles.test.tsx` scans every `className=` literal in
`src/` and fails on an unprefixed one. `glass`/`elevation-N` are the one family
still bare: they are an API VALUE (`glass(3).className`), not a typed literal,
so they move on their own change.
- A prop must actually arrive. gui is not the DOM, and two measured cases prove
it in both directions: **`name` is gui's OWN prop** (it names a styled component
and a theme) and is consumed before it reaches the element, so a `name` on a
field type-checks and renders nothing; and gui **drops `secureTextEntry` on
web**, which is why masking needs BOTH spellings via `masked()` in
`backends/gui/mask.ts` and why `<Input type="password">` rendered passwords in
PLAIN TEXT until 8.0.61 (the wrapper destructured `type` out and never
forwarded it, next to an eye offering to reveal what was already visible).
Render it and read the markup before you believe a prop works.
### Subpaths
| Subpath | What |
|---|---|
| `@hanzo/ui` | the component API: Button, Badge, Card*, Checkbox, Dialog*, DropdownMenu*, Input, Toaster, Avatar*, Tabs*, Select*, Tooltip*, Popover*, Command*, Collapsible*, Resizable*, ScrollArea, Slider, Switch, Progress, Separator, Label, Textarea, AspectRatio — + `cn` (the product layer is kept off root, at `/product`) |
| `@hanzo/ui/components` | alias of the root surface, for hosts that shim the package through a `declare module` |
| `@hanzo/ui/product` | the product/app layer: charts, metrics, PageHeader, StatusTag, EmptyState, ComboBox, SlideOver, Toast, Reorder, Field |
| `@hanzo/ui/models` | ModelSelector + fetchModelCatalog + catalog helpers |
| `@hanzo/ui/core` · `/tokens` | cn, Geist font vars, the @hanzo/tokens color/theme/radii/spacing scale |
| `@hanzo/ui/theme.css` | the design tokens alone (custom properties + Geist + touch/elevation) |
| `@hanzo/ui/styles.css` | the COMPLETE sheet — tokens + motion + the generated gui atomic/theme CSS. `<Hanzo>` imports it, so an app never has to |
| `@hanzo/ui/gallery` | every component, once — what the generator, the unit test and the consumer test all render |
| `@hanzo/ui/primitives/<Member>` | per-member entrypoints (for hosts that modularize `@hanzo/ui` imports) |
| `@hanzo/ui/data` | `@hanzo/data`: RecordsView, DataTable, typed field editors |
| `@hanzo/ui/{canvas,dashboard,usage,gitops}` | the optional-peer kits (each re-exports its home package) |
| `@hanzo/ui/product/*` · `/primitives/*` | deep imports — one module without its barrel |
| `@hanzo/ui/product/pure` | the product layer's RULES with none of the layer (below) |
| `@hanzo/ui/product/theme-toggle-next` | the `@hanzogui/next-theme` binding, off the barrel on purpose (below) |
| `@hanzo/ui/css` | `substitute()` — resolve a `var()` chain, for tests jsdom cannot answer (below) |
Everything ships COMPILED from `dist` — every `exports` target is a real file in
the tarball, including `theme.css` and all 90 `primitives/*` entrypoints.
`src/dist.test.ts` asserts that against the built output, wildcards included; a
subpath pointing at a file tsc never emitted is invisible from source.
### Three doors that exist because the barrel is not one
`@hanzo/ui/product` mounts the whole gui runtime to give you one component, and
for three kinds of caller that is not a cost — it is a wall.
**`@hanzo/ui/product/pure` — the rules, without the layer.** `pages()`,
`masked()`, `displayName()`, `tone()`, `orgScope`, `filterOptions`,
`resolveBrand` and the wordmark geometry. Every module it re-exports imports
NOTHING (`src/dist.test.ts` asserts the closure is empty) and is on
`postbuild.mjs`'s `DATA` list, so none is stamped `'use client'` — a stamped
module is a client REFERENCE on React's server layer, and calling `pages()`
through one in a server component throws instead of paging. It loads under a
bare `require()` with no transform and no DOM; the test proves it in a child
node process rather than under vitest, which has vite's transform already
installed and would prove nothing.
The components import these same modules, so there is one definition and not a
testable copy of a shipped one.
**`@hanzo/ui/product/theme-toggle-next` — Next, quarantined.**
`@hanzogui/next-theme`'s provider imports `next/script`, so the product barrel's
one `export { ThemeToggleNext }` line put Next in the graph of every Vite,
Express and Tauri host — the hosts this layer promises to run on. A barrel
re-export is a static edge no bundler can split. It is off the barrel; `<ThemeToggle />`
with no props still reaches it by dynamic import and degrades when next-theme is
absent, and `dist.test.ts` asserts BOTH — no static edge, and the dynamic one
still there, because a test that only asserted the absence would pass on a
deleted feature. `next` is now an OPTIONAL peer here: next-theme requires it and
nothing in this package admitted that.
**`@hanzo/ui/css``substitute(value, vars?)`.** jsdom does not resolve
`var()`; it hands a test the text verbatim. The theme rungs are
`var(--border, rgb(255 255 255 / .10))` on purpose (follow the live cascade
where design's sheet is mounted, keep the audited literal where it is not), so
every consumer trying to assert a border's contrast compared a colour to a
function call. With no `vars` map the answer is exact rather than approximate:
jsdom mounts no design sheet, so the fallback IS what a browser computes. It is
NOT part of `@hanzo/ui/core` — that subpath is ESM-only because @hanzo/design
publishes no `require` condition, and a jest consumer is the caller that needs
this. Importing nothing is what lets it ship both formats.
### One DropdownMenu
There is one `DropdownMenu`, with one API. It is the compound surface (Trigger,
Content, Item, CheckboxItem, RadioItem, Label, Separator, Shortcut, Group,
Portal, Sub*, RadioGroup) AND it accepts the declarative `trigger` + `items`
spec, which it renders through those very same parts. `@hanzo/ui` and
`@hanzo/ui/product` export the same component; there is no second shape.
### modularizeImports support
`scripts/gen-primitives.mjs` reads the gui backend barrel and emits one
`src/primitives/<Member>.tsx` per exported value (re-export from the backend).
This makes `@hanzo/ui/primitives/Button` etc. resolve, so a host whose
`next.config` rewrites `@hanzo/ui``@hanzo/ui/primitives/{{member}}` works
unchanged. Re-run `pnpm gen:primitives` after changing the surface.
### Build — plain `tsc`, one file in, one file out
There is no bundler. `pnpm build` is two `tsc` passes, `scripts/postbuild.mjs`,
then `scripts/gen-css.mjs` (which renders the gallery through vite's SSR pipeline
to harvest `config.getCSS()` into `dist/styles.css` — the slow step, ~2 min):
| Pass | Config | Emits |
|---|---|---|
| ESM + types | `tsconfig.build.json` | `dist/**/*.js`, `.d.ts`, `.js.map`, `.d.ts.map` |
| CJS | `tsconfig.cjs.json` (`--noCheck`) | `dist-cjs/**/*.js`, folded into `dist/**/*.cjs` |
`postbuild.mjs` does the only two things `tsc` will not: it resolves every
relative specifier to a fully-specified path (`./button``./button.js`,
`./x``./x/index.js`; `.cjs` on the CJS half) so Node ESM and strict bundlers
resolve, and it prepends `'use client'` to every emitted module — the whole
library is client-side @hanzo/gui UI and Next's flight-client loader wants the
directive first. It is prepended without a newline so source-map lines hold.
**`@hanzo/data` runs this same script**, with its package root and its own data
modules as arguments (`node ../ui/scripts/postbuild.mjs . theme,table/logic,…`).
It has the same two formats and the same two problems, and a second copy of the
file would be a second place to get the barrel rule wrong. That package used to
point its `exports` at `src/index.ts` and ship raw TSX — every consumer had to
transpile it, and `require('@hanzo/data')` could not load at all, which is one of
the two edges that broke `require('@hanzo/ui')`. It emits `dist/` now, both
formats, from 1.2.2.
The output is UNBUNDLED and mirrors `src/` one-for-one, so a consumer importing
one symbol pulls one module. A bundler here would be actively harmful: tsup's
code splitting emitted 11 shared `chunk-*.js`, and importing `Button` alone
dragged in `chunk-RCMDRI6V.js` (48K of source). Measured with esbuild, `import
{ Button } from '@hanzo/ui'` costs 4717 bytes bundled from tsup output vs 2021
from `tsc` output. Dropping `rollup-plugin-dts` (tsup's `dts` worker) is also
what makes the package build on TypeScript 7, which it cannot do otherwise.
Everything under `src/` is emitted, so every `exports` subpath resolves by
construction — no hand-maintained entry list to drift.
NOTE: `pkg/ui` (singular) sits OUTSIDE the `pkgs/*` pnpm workspace, installs
standalone, and publishes via the maintainer flow, not `publish.yml`. Because the
optional-peer kits (canvas/dashboard/gitops/usage) are not on the public
registry, a standalone install must skip auto-installing peers. `.npmrc` and
`pnpm-lock.yaml` are gitignored here, so create the `.npmrc` once:
```bash
cd pkg/ui
printf 'auto-install-peers=false\nstrict-peer-dependencies=false\n' > .npmrc
pnpm install --ignore-workspace # component-surface deps (radix, cmdk, sonner, …) + @hanzo/tokens
pnpm gen:primitives # refresh the per-member entrypoints
pnpm typecheck:ui # scoped typecheck of the component surface (green)
```
`@hanzo/tokens` (`pkgs/tokens`) must be built first (`pnpm --filter @hanzo/tokens build`)
so the `file:` link resolves. The scoped `typecheck:ui` excludes the optional-peer
subpaths, whose homes aren't installed standalone.
The **kits** = canvas, wallet, network, billing, dashboard, usage, gitops, data.
Add one by mirroring `src/gitops.ts` (a one-line `export *`) + a `./name` export
+ an optional peer/devDep. `pkg/*` is a pnpm workspace member (for `workspace:*`
dev links), but `pkg/ui` publishes via the maintainer flow, not `publish.yml`
(which auto-publishes only `pkgs/*` on a version bump — see PUBLISH_GUIDE.md). The
shared shell lives here too: `AppHeader` + `BrandMark` (@hanzo/logo) +
`OrgSwitcher` + `orgScope` (the console org-scope contract, hoisted per #36). Lux
surfaces use `@luxfi/web3` for wallet/login; `@hanzo/ui/wallet`+`/network` are the
Hanzo-branded equivalents.
**Docs**: https://ui.hanzo.ai | **Dev port**: 3003
## Repository Structure
```
ui/
app/ Hanzo documentation site (Next.js 15.3.1, React 19)
app/ Documentation site (Next.js 15.3.1, React 19)
registry/ Component registry (SOURCE OF TRUTH)
default/ui/ 150+ components
default/example/ Usage demos
@@ -315,25 +18,13 @@ ui/
new-york/ Alternative theme
content/docs/ MDX documentation
scripts/ Build scripts
apps/
v4/ Upstream shadcn v4 docs/registry app (port 4000)
packages/
shadcn/ shadcn CLI v4.1.0 (font system, chart colors, scaffold)
tests/ Integration tests for shadcn CLI
og/ OG image generation (Hanzo-only)
pkg/
ui/ Core library (npm)
react/ React primitives
brand/ Branding system
auth/ Auth components (Firebase optional since v2.6.0)
auth-firebase/ Firebase auth (opt-in package)
commerce/ E-commerce components
checkout/ Checkout flow
shop/ Shop components
agent-ui/ AI agent UI components
tokens/ Design tokens
skills/
shadcn/ AI skill definitions for shadcn CLI
templates/ Project templates (next, vite, astro, react-router, start + monorepo variants)
template/next/ Hanzo-customized Next.js template
brand/ Branding system
brands/ White-label configs (Zoo, Lux)
```
## Critical: Build Order
@@ -355,173 +46,14 @@ pnpm lint # Lint all workspaces
pnpm typecheck # Type checking
pnpm test # Unit tests
pnpm test:e2e # Playwright E2E
pnpm changeset # Create changeset for publishing
```
## How this ships
One way, and it runs on our own stack:
push -> github.com/hanzoai/ui (a mirror)
.github/workflows/sync.yml carries refs onward
-> git.hanzo.ai/hanzoai/ui CANONICAL
.hanzo/workflows/ci.yml lint, typecheck, build, test
.hanzo/workflows/registries.yml the v4 registry check
.hanzo/workflows/publish.yml publishes every pkgs/* package
.hanzo/workflows/deploy.yml builds ghcr.io/hanzoai/ui
-> hanzoai/universe crs/ui.yaml names the tag that is live
-> hanzoai/operator reconciles the App
-> hanzoai/static behind hanzoai/ingress serves ui.hanzo.ai
**git.hanzo.ai is canonical; GitHub is a mirror.** `.github/workflows/` holds
exactly one file, `sync.yml`, and its only job is getting refs to the forge. Every
build, check, publish and deploy is a workflow under `.hanzo/workflows/`, which the
forge reads. `.hanzo/workflows` uses GitHub Actions syntax, so a workflow moves
between the two by changing directory and nothing else.
No Vercel. `ci.yml` used to end in a `deploy-preview` job that ran `vercel deploy`
on every PR; previews come from our own stack or not at all, so that job is gone.
Its `status` job never depended on it.
## Publishing
One way: bump a package's `version` in its `package.json` and merge to `main`.
`.hanzo/workflows/publish.yml` detects the changed `@hanzo/*` package and publishes
it to npm (needs `NPM_TOKEN` as a forge secret). No changesets, no version-PR bot
— the semver bump is the trigger.
It is the SOLE publisher of every non-private `@hanzo/*` in `pkgs/*`, and it
mirrors the same tarball to `api.hanzo.ai/v1/packages/hanzo/npm` when
`HANZO_REGISTRY_TOKEN` is present. That mirror is best-effort by construction: no
token means a notice, not a failure, and npmjs stays authoritative either way.
## Deploying the site
`app/` is a Next.js static export (`output: "export"`, `trailingSlash: true`);
`pnpm build` there writes `app/out`, which `Dockerfile` copies into
`ghcr.io/hanzoai/static`. ui.hanzo.ai has been served that way since 2026-07-25 —
no Cloudflare, no GitHub Pages.
What was missing until now is the build. `crs/ui.yaml` is live and promoted, but no
workflow ever produced the image it pins: every tag up to `v5.7.6` was pushed by
hand. `.hanzo/workflows/deploy.yml` is that step. It publishes
`ghcr.io/hanzoai/ui:<sha>` and stops there — a build never deploys itself. A human
sets `spec.image.tag` in `hanzoai/universe`
`infra/k8s/operator/crs/ui.yaml`, which is the one live thing that says which build
serves.
Coverage lives in `ci.yml`'s `test` job, which runs `pnpm test:coverage` so the
lcov it uploads to Codecov actually exists. A separate `coverage.yml` used to run
the same suite a second time for the same upload plus a PR comment through the
GitHub API; one workflow does it now.
`registries.yml` keeps the `apps/v4` registry honest: reserved namespaces are
rejected and `pnpm --filter=v4 validate:registries` must pass. Its other job
labelled and commented on pull requests with the `gh` CLI against the GitHub API,
which does not exist on the forge, so that job did not come along.
## Telemetry — `@hanzo/event` is the ONE client (`pkgs/event`)
`@hanzo/event` is the single canonical telemetry client for every Hanzo surface.
ONE API surface over **TWO** planes — the client never sends the org; the server
resolves the tenant.
1. **Event stream** — pageview/event/identify/group (and an error breadcrumb),
batched to `POST {host}/v1/event` with `{ batch: [Event, …] }`
`-> { accepted, dropped }`. Tenant from the session or a publishable `pk_` key.
2. **Error plane** — every captured exception is ALSO framed as a real **Sentry
envelope** and POSTed to `POST {dsn.origin}/v1/sentry/{projectId}/envelope/?sentry_key=…`.
This is the ONLY thing that reaches the Sentry error dashboard.
> **There is NO server-side fan-out from `/v1/event` into Sentry.** Versions
> ≤ 0.3.1 claimed there was ("lensed server-side into … error tracking"). There
> is not: cloud's handler folds the exception into `properties.$exception`,
> writes one row to the event warehouse (readable via `GET /v1/errors`), and
> stops. Because every property believed that claim, the whole fleet reported
> **zero** errors to Sentry until 0.3.2 added the envelope. Do not re-collapse
> these planes.
Configure the error plane with `dsn` (or `NEXT_PUBLIC_HANZO_EVENT_DSN`), minted
per property via `POST /v1/sentry/projects`. The DSN key is publishable and
write-only — safe in a bundle, same trust class as `pk_`. **No DSN => the error
plane is inert** (fail-safe: nothing sent, nothing thrown, event stream
unaffected); assert `client.errorPlaneEnabled` if you need to know.
There is NO third plane. Web analytics used to be one — `analytics.hanzo.ai/hz.js`
posting a bare JSON array of `{site, ts, type, …}` to a second collector behind an
identical path spelling — and 0.3.7 deleted both. `hz.js` now lives in this package
as the script-tag DISTRIBUTION of this client: same `WireEvent`, same
`{ batch: [ … ] }`, same `POST {host}/v1/event`. Point everything at the API host.
It could not authenticate until 0.3.12: it sent no `Authorization` and no
`?ingest_key=`, so a keyed static surface's writes were unattributed, the door
refused them (`401`), and nothing in the page said so. `data-ingest-key="pk-…"`.
Entries: `.` (framework-agnostic: `createAnalytics`, `EVENTS`, `GOALS`,
attribution + DSN/scrub helpers) and `./react` (`AnalyticsProvider`,
`useAnalytics`, `usePageview`, `ErrorBoundary`). Auto error capture
(window.onerror / unhandledrejection / React boundary) makes it the drop-in
error-tracking replacement. Secrets and PII are scrubbed client-side before an
error leaves the device. SSR-safe, fail-soft, beacon-on-unload.
Build is a tsup dual bundle: **CJS → `.cjs`, ESM → `.mjs`** (required under
`"type": "module"` — a CJS `.js` is parsed as ESM and crashes `require()` with
"exports is not defined"). Each `exports` condition carries its own types.
### Interaction analytics — `<Hanzo analytics>` is the one wiring
An app instruments nothing. `<Hanzo analytics>` (`pkg/ui/src/root.tsx`) is the
whole setup, and every click / change / submit / route change inside the tree
reaches `POST /v1/event` named by the component it happened on:
```tsx
<Hanzo analytics={{ product: 'console', ingestKey: process.env.NEXT_PUBLIC_PUBLISHABLE_KEY }}>
```
Four packages, one of each concern, no duplication:
| Concern | Where | Note |
|---|---|---|
| client + wire | `@hanzo/event` (`pkgs/event`) | one endpoint, one key |
| capture engine | `@hanzo/observe` (`pkgs/observe`) | delegated listeners, semantic annotation, redaction |
| provider + consent | `@hanzogui/telemetry` (`~/work/hanzo/gui`) | `<TelemetryProvider/>`; owns DNT/GPC + stored choice |
| curated events | `@hanzo/ui/product` `instrument.ts` | `emit({component, action})` — what autocapture cannot know |
**`analytics` is a prop, not a default.** Mounting a component library must not
start a network conversation the app did not ask for. Off, no provider renders.
**Component names are real in production.** Every primitive already carries a
`data-slot` (via `slot()`); `componentName()` in `pkgs/observe/src/annotate.ts`
reads it, ranked ABOVE the React fiber owner deliberately — the fiber name is
dev-only, so grouping on it silently empties the dashboard at deploy. Labels keep
the qualifier: `card/button[Save]`.
**It cannot double-count.** The engine installs *delegated* listeners on a root,
so two engines on one root report everything twice — which is what an app got by
mounting a library provider AND `<ObserveProvider/>`, both correct instructions.
Since observe 0.1.7 the first engine claims its root under a `Symbol.for`
registry (page-wide, so duplicate copies of the package still see each other) and
any later one stays inert (`engine.capturing === false`). Verified in Chromium,
not only in jsdom.
**Consent is decided in ONE layer.** The engine takes `enabled` as a value; the
provider resolves policy (GPC, DNT, stored `hz_consent`, build kill switch) and
passes the answer down. Do not add a second, partial copy to the engine — the two
then disagree about an explicit opt-in.
### One way — supersessions (no divergent telemetry client)
| Package | Status | Note |
|---|---|---|
| `@hanzo/event` | **canonical** | `pkgs/event`, posts `/v1/event` only |
| `@hanzo/capture` (npm) | **deprecated → `@hanzo/event`** | the old name of this package; `@hanzo/event` is a superset |
| `pkgs/capture` (`@hanzo/analytics@0.1.0` dup) | **deleted** | stale in-repo duplicate, removed |
| `hanzoai/analytics` `packages/event` (`@hanzo/event@0.2.0`) | **deleted** | An unpublished FORK of this package in another repo. It was the only copy that could actually reach Sentry, while the published one here could not — the fleet's error telemetry died in that gap. Its envelope + scrub implementation was merged here in 0.3.2. Never fork this package again; it publishes from `pkgs/event` only. |
## Three-Layer Architecture
1. **Components** (`registry/{style}/ui/`) — single primitives (Button, Card, Dialog). CLI-installable.
2. **Examples** (`registry/{style}/example/`) — usage demos for docs via `<ComponentPreview />`.
3. **Blocks** (`registry/{style}/blocks/`) — full-page sections (Dashboard, Login). NOT CLI-installable, docs only.
1. **Components** (`registry/{style}/ui/`) -- Single primitives (Button, Card, Dialog). CLI-installable.
2. **Examples** (`registry/{style}/example/`) -- Usage demos for docs via `<ComponentPreview />`.
3. **Blocks** (`registry/{style}/blocks/`) -- Full-page sections (Dashboard, Login). NOT CLI-installable, docs only.
## Import Path Transformation
@@ -546,29 +78,28 @@ import { cn } from '@hanzo/ui/lib/utils'
## Tech Stack
React 19, Next.js 15.3+, Tailwind CSS 4 (OKLCH colors), Radix UI, Turborepo + pnpm, Fumadocs (MDX), class-variance-authority.
## Upstream Sync
Remote `shadcn` points to a local clone of shadcn-ui/ui.
hanzoai/ui is NOT a GitHub fork — no shared object store, so large merges can fail on push.
Strategy: file-level checkout from shadcn/main for specific directories (not git merge).
- Take theirs: packages/shadcn/, packages/tests/, apps/, templates/, scripts/, skills/
- Keep ours: app/, pkg/, demo/, docs/, template/next/, pnpm-workspace.yaml, package.json
- Regenerate: pnpm-lock.yaml after sync
React 18.3.1 (19 experimental), Next.js 15.3.1, Tailwind CSS (OKLCH colors), Radix UI, Turborepo + pnpm, Fumadocs (MDX), class-variance-authority.
## Key Features
- **Page Builder** (`/builder`): drag-drop block assembly with @dnd-kit, export to TSX
- **Page Builder** (`/builder`): Drag-drop block assembly with @dnd-kit, export to TSX
- **White-Label**: Zoo/Lux forks via `brands/{BRAND}.brand.ts`
- **External Registries**: 35+ sources in `app/registries.json`, install via `npx @hanzo/ui add @aceternity/spotlight`
## Gotchas
- Registry index is `Index[style][name]`, NOT `Index[name]` caused silent block render failures
- Shiki `getHighlighter` incompatible with static export replaced with basic pre/code
- Registry index is `Index[style][name]`, NOT `Index[name]` -- caused silent block render failures
- Shiki `getHighlighter` incompatible with static export -- replaced with basic pre/code
- Some blocks (login-01, login-02, sidebar-02) have Server Component issues with event handlers
- `@hanzo/auth` v2.6.0 uses a pluggable provider registry: `registerAuthProvider('firebase', FirebaseAuthService)`
- Zod validation removed from `_getAllBlocks()`/`_getBlockCode()` -- we control generation
- Firebase split to optional `@hanzo/auth-firebase` package (Jan 2025)
- `@hanzo/auth` v2.6.0 uses pluggable provider registry: `registerAuthProvider('firebase', FirebaseAuthService)`
## Component Stats (2025-10-18)
- 161 total files, ~127 implemented, ~34 stubs
- Unique: 9 3D components, 12 AI components, 13 animation components, 15 nav variants
- 3x more components than upstream shadcn/ui (161 vs 58)
## Rules
-6
View File
@@ -1,6 +0,0 @@
ui
Copyright (c) 2023 Hanzo AI, Inc.
This product includes software from shadcn/ui (https://github.com/shadcn-ui/ui), licensed under MIT:
Copyright (c) 2023 shadcn
+159 -24
View File
@@ -1,39 +1,174 @@
# Publishing
# NPM Publishing Guide - React 19 Packages
Two lanes, one trigger each. No changesets, no version-PR bot.
## Current Package Versions
## 1. `pkgs/*` — auto-publish on version bump (`publish.yml`)
All packages updated to support **React 19.2.0**:
Bump a package's `version` in `pkgs/<name>/package.json` and merge to `main`.
`.github/workflows/publish.yml` detects the changed public `@hanzo/*` package,
builds it, and publishes to npm (repo secret `NPM_TOKEN`). Patch bumps only
(`x.y.z``x.y.z+1`).
- `@hanzo/ui` - v5.1.1
- `@hanzo/auth` - Latest
- `@hanzo/commerce` - Latest
- `@hanzo/brand` - Latest
- `@hanzo/react` - v1.0.0
## 2. `pkg/ui` — `@hanzo/ui@8`, the v8 lane (maintainer flow)
## Publishing Methods
`pkg/ui` (with `pkg/data`) is the modern cross-platform library on `@hanzo/gui`.
It publishes from the package directory (`prepack` builds the `types/`):
### 1. Automatic Publishing (Tag-based)
When you push a git tag starting with `v` (typically matching @hanzo/ui version), the workflow automatically checks all packages and publishes any with new versions:
```bash
# Tag with @hanzo/ui version (workflow checks all packages)
git tag v5.1.1
git push origin v5.1.1
```
**What happens:**
1. Tests run (pkg/ui and pkg/react)
2. All 5 packages build
3. **Automatic version detection:**
- Checks each package's current version in package.json
- Queries npm to see if that version already exists
- Only publishes packages with new versions not on npm
4. GitHub release created (only if packages were published)
**Example workflow output:**
```
📦 Checking @hanzo/ui@5.1.1
⏭️ Already published - skipping
📦 Checking @hanzo/auth@2.5.5
🚀 Publishing to npm...
✅ Successfully published @hanzo/auth@2.5.5
📊 Publishing Summary
✅ Published: 1 package(s)
⏭️ Skipped: 4 package(s)
```
This approach means you:
- Only need to tag once (with @hanzo/ui version)
- Don't need to track which packages need publishing
- Can bump any package version and it auto-publishes on next tag
- Similar to python-sdk monorepo publishing
**Workflow:** `.github/workflows/publish-on-tag.yml`
### 2. Manual Publishing (Workflow Dispatch)
Use GitHub Actions UI to manually publish specific packages:
1. Go to **Actions****NPM Publish**
2. Click **Run workflow**
3. Select package: `ui`, `auth`, `commerce`, `brand`, `react`, or `all`
4. Select version bump: `patch`, `minor`, or `major`
5. Click **Run workflow**
**What happens:**
- Selected package(s) build
- Version bumped automatically
- Package(s) published to npm
- PR created with version bump
**Workflow:** `.github/workflows/npm-publish.yml`
### 3. Local Publishing (Manual)
For quick patches or testing:
```bash
# Build and test
cd pkg/ui
pnpm typecheck && pnpm test && pnpm build
# bump "version" in package.json (patch), commit to main, then:
pnpm build
pnpm test
# Bump version
npm version patch # or minor/major
# Publish
npm publish --access public
```
`@hanzo/ui-shadcn` (`pkgs/ui`) is the legacy v5 kit — existing consumers pin
`@hanzo/ui-shadcn@^5`; it rides lane 1 like any other `pkgs/*` package.
> The old tag-driven flow (`publish-on-tag.yml`, `npm-publish.yml`, the
> `pkg/commerce|brand|react` paths) is gone — do not tag to publish here.
## Prerequisites
- `NPM_TOKEN` repo secret (lane 1) / npm auth as a maintainer (lane 2)
- Every package carries `"publishConfig": { "access": "public" }`
### NPM Authentication Token
## Checklist
The GitHub secret `NPM_AUTH_TOKEN` must be set:
- [ ] `pnpm typecheck` + `pnpm test` green in the package
- [ ] Patch version bump (check the last published patch first)
- [ ] Commit to `main`; lane 1 publishes on merge, lane 2 via `npm publish`
1. Generate token at https://www.npmjs.com/settings/tokens
2. Add to GitHub: Settings → Secrets → Actions → `NPM_AUTH_TOKEN`
### Package Publish Configuration
All packages already configured with:
```json
{
"publishConfig": {
"access": "public",
"registry": "https://registry.npmjs.org/"
}
}
```
## React 19 Compatibility
### Key Updates Made
1. **Type Declarations**: Added `hanzo-ui.d.ts` files for React 19 compatibility
2. **Peer Dependencies**: Force React 19.2.0 via pnpm overrides
3. **Test Environment**: Switched to happy-dom for better React 19 support
4. **Build Configuration**: All packages build successfully with React 19
### Test Status
- **pkg/ui**: 206/207 tests passing (99.5%)
- **pkg/react**: 10/10 tests passing (100%)
## Publishing Checklist
Before publishing:
- [ ] All packages build successfully: `pnpm build`
- [ ] Tests pass: `pnpm test`
- [ ] Types check: `cd app && pnpm typecheck`
- [ ] Lint passes: `cd app && pnpm lint`
- [ ] Update CHANGELOG.md
- [ ] Update version in package.json (if manual)
- [ ] Commit changes
## Troubleshooting
### Build Failures
```bash
# Clean install
rm -rf node_modules pnpm-lock.yaml
pnpm install
# Rebuild
pnpm build
```
### Test Failures
```bash
# Run specific package tests
cd pkg/ui && pnpm test
cd pkg/react && pnpm test
```
### Publish Failures
- Check NPM_AUTH_TOKEN is valid
- Ensure version is unique (not already published)
- Verify package builds: `cd pkg/<name> && pnpm build`
## Package URLs
- npm: https://www.npmjs.com/org/hanzo
- GitHub: https://github.com/hanzoai/ui
- Docs: https://ui.hanzo.ai
---
**Last Updated:** 2025-10-05
**React Version:** 19.2.0
+28 -93
View File
@@ -1,42 +1,35 @@
<p align="center"><img src=".github/hero.svg" alt="@hanzo/ui" width="880"></p>
# @hanzo/ui
**The React component library for AI applications.** Accessible, customizable primitives for React, Vue, Svelte, and React Native — built on shadcn/ui, extended with AI, 3D, animation, and commerce components, and a single typed import surface.
<p align="center">
<a href="https://www.npmjs.com/package/@hanzo/ui"><img src="https://img.shields.io/npm/v/@hanzo/ui?color=black&label=%40hanzo%2Fui" alt="npm"></a>
<a href="./LICENSE.md"><img src="https://img.shields.io/badge/license-MIT-black" alt="MIT"></a>
<a href="https://ui.hanzo.ai"><img src="https://img.shields.io/badge/docs-ui.hanzo.ai-black" alt="docs"></a>
</p>
Accessible and customizable components for React, Vue, Svelte, and React Native. **Built on shadcn/ui with multi-framework support, 3D components, AI components, and advanced features.**
![hero](app/public/og.jpg)
## Features
- **161+ components** 3x the surface of upstream shadcn/ui
- **Multi-framework** React, Vue, Svelte, React Native
- **Two themes** Default & New York variants
- **AI components** — chat, assistants, agent UI, playground
- **3D components** — interactive 3D elements
- **Animations** — advanced motion components
- **Page builder** — visual drag-and-drop assembly, export to TSX
- **Blocks** — 24+ production-ready full-page templates
- **White-label** — fork and rebrand by domain (Zoo, Lux, …)
- **Accessible** — built on Radix UI primitives
- **Customizable** Tailwind CSS 4 (OKLCH), fully typed TypeScript
- **161+ Components** - 3x more than shadcn/ui
- **Multi-Framework** - React, Vue, Svelte, React Native
- **Two Themes** - Default & New York variants
- **AI Components** - Chat, assistants, playground
- **3D Components** - Interactive 3D elements
- **Animations** - Advanced motion components
- **Page Builder** - Visual drag-drop interface
- **White-Label** - Fork and rebrand easily
- **Blocks** - 24+ production-ready templates
- **Accessible** - Built with Radix UI primitives
- **Customizable** - Tailwind CSS powered
- **TypeScript** - Fully typed
## Quick start
## Quick Start
### Install
### Installation
```bash
pnpm add @hanzo/ui
# or
npm install @hanzo/ui
# or
pnpm add @hanzo/ui
```
### Use
### Usage
```tsx
import { Button, Card, Input } from '@hanzo/ui'
@@ -58,59 +51,23 @@ export function App() {
}
```
## One import surface (v8)
## Documentation
`@hanzo/ui@8` is the single entry point for the whole kit. Each capability is a
thin subpath that re-exports its home package — code lives once, and each home is
an optional peer, pulled only when you use its subpath.
| Import | What you get |
|---|---|
| `@hanzo/ui` · `/product` | charts, metrics, PageHeader, StatusTag, EmptyState, ComboBox, SlideOver, Toast |
| `@hanzo/ui/data` | RecordsView, DataTable, typed field editors |
| `@hanzo/ui/canvas` | ProjectCanvas, ServiceNode, DeployTimeline, EnvSwitcher |
| `@hanzo/ui/dashboard` | landing + deploy-pipeline + overview kit |
| `@hanzo/ui/usage` | UsageMeter, UsageProviderCard, UsageDashboard |
| `@hanzo/ui/gitops` | GitopsAppList, tree, diff, sync/rollback, HealthBadge |
Also available as granular imports:
```ts
import { Button, Card } from '@hanzo/ui/components'
import * as Dialog from '@hanzo/ui/primitives/dialog'
import { cn } from '@hanzo/ui/lib/utils'
```
Visit **[ui.hanzo.ai](https://ui.hanzo.ai)** for full docs.
## CLI
Add components straight into your project — the CLI copies source you own:
```bash
npx @hanzo/ui add button
npx @hanzo/ui add card dialog
```
Install from 35+ external registries too:
```bash
npx @hanzo/ui add @aceternity/spotlight
```
## Packages
The workspace publishes a family of scoped packages under `@hanzo/*`:
| Package | Purpose |
|---|---|
| `@hanzo/ui` | Core library + the v8 import surface (161+ components) |
| `@hanzo/react` | React primitives |
| `@hanzo/data` | Records, data tables, typed field editors |
| `@hanzo/canvas` | Service/deploy canvas components |
| `@hanzo/dashboard` | Dashboard + deploy-pipeline kit |
| `@hanzo/commerce` · `@hanzo/checkout` · `@hanzo/shop` | Commerce components |
| `@hanzo/agent-ui` | AI agent UI components |
| `@hanzo/brand` · `@hanzo/tokens` | Branding system & design tokens |
| `@hanzo/event` | Telemetry client (`POST /v1/event`) |
- `@hanzo/ui` - Main UI library (161 components)
- `@hanzo/auth` - Authentication components
- `@hanzo/commerce` - E-commerce components
- `@hanzo/brand` - Branding system
## Development
@@ -118,39 +75,17 @@ The workspace publishes a family of scoped packages under `@hanzo/*`:
git clone https://github.com/hanzoai/ui.git
cd ui
pnpm install
pnpm build:registry # generate the component registry FIRST
pnpm dev # docs site + registry (http://localhost:3003)
pnpm dev
```
> The registry generates the JSON the CLI reads, so `build:registry` must run
> before `build`. Keep the Default and New York themes in sync when adding
> components. Use pnpm — not npm or yarn.
```bash
pnpm build # build the docs app
pnpm lint # lint all workspaces
pnpm typecheck # type check
pnpm test # unit tests
pnpm test:e2e # Playwright E2E
```
## Documentation
Full docs, live previews, and the component catalog: **[ui.hanzo.ai](https://ui.hanzo.ai)**.
## Contributing
See the [contributing guide](/CONTRIBUTING.md).
Please read the [contributing guide](/CONTRIBUTING.md).
## License
MIT — see [LICENSE.md](./LICENSE.md).
MIT - See [LICENSE.md](./LICENSE.md) for details.
---
## Hanzo — the Open AI Cloud
Open source · every language · on-chain settlement. [hanzo.ai](https://hanzo.ai) · [docs.hanzo.ai](https://docs.hanzo.ai)
**SDKs in every language** — [Python](https://github.com/hanzoai/python-sdk) (flagship) · [TypeScript](https://github.com/hanzo-js/sdk) · [Go](https://github.com/hanzo-go/sdk) · [Rust](https://github.com/hanzo-rs/sdk) · [C++](https://github.com/hanzo-cpp/sdk) · [Swift](https://github.com/hanzo-swift/sdk) · [Kotlin](https://github.com/hanzo-kt/sdk) · [umbrella](https://github.com/hanzoai/sdk)
Built by [Hanzo](https://hanzo.ai)
+1 -1
View File
@@ -6,4 +6,4 @@ We will investigate all legitimate reports and do our best to quickly fix the pr
Our preference is that you make use of GitHub's private vulnerability reporting feature to disclose potential security vulnerabilities in our Open Source Software.
To do this, please visit the security tab of the repository and click the [Report a vulnerability](https://github.com/shadcn-ui/ui/security/advisories/new) button.
To do this, please visit the security tab of the repository and click the "Report a vulnerability" button.
+8 -430
View File
File diff suppressed because one or more lines are too long
+5 -12
View File
@@ -1,15 +1,8 @@
// @ts-nocheck
import { dynamic } from "@hanzo/docs-mdx/runtime/dynamic"
import { dynamic } from '@hanzo/docs-mdx/runtime/dynamic';
import * as Config from '../source.config';
import * as Config from "../source.config"
const create = await dynamic<
typeof Config,
import("@hanzo/docs-mdx/runtime/types").InternalTypeConfig & {
DocData: {}
const create = await dynamic<typeof Config, import("@hanzo/docs-mdx/runtime/types").InternalTypeConfig & {
DocData: {
}
>(
Config,
{ configPath: "source.config.ts", environment: "next", outDir: ".docs" },
{ doc: { passthroughs: ["extractedReferences"] } }
)
}>(Config, {"configPath":"source.config.ts","environment":"next","outDir":".docs"}, {"doc":{"passthroughs":["extractedReferences"]}});
+191 -387
View File
File diff suppressed because one or more lines are too long
+12
View File
@@ -0,0 +1,12 @@
node_modules/
.next/
out/
build/
dist/
next-env.d.ts
__registry__/
.source/
*.config.js
*.config.mjs
.turbo/
coverage/
+40
View File
@@ -0,0 +1,40 @@
{
"env": {
"browser": true,
"es2021": true,
"node": true
},
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": "latest",
"sourceType": "module",
"ecmaFeatures": {
"jsx": true
}
},
"plugins": ["@typescript-eslint", "react"],
"ignorePatterns": [
"__registry__/**",
".source/**",
".next/**",
"out/**",
"build/**",
"dist/**",
".turbo/**",
"node_modules/**"
],
"rules": {
"@typescript-eslint/no-explicit-any": "warn",
"@typescript-eslint/no-empty-object-type": "warn",
"@typescript-eslint/ban-ts-comment": "warn",
"@typescript-eslint/no-unused-vars": "warn",
"@typescript-eslint/no-require-imports": "warn",
"@typescript-eslint/no-this-alias": "warn",
"@typescript-eslint/triple-slash-reference": "warn",
"@typescript-eslint/ban-types": "off",
"react/no-unescaped-entities": "warn",
"react/jsx-no-comment-textnodes": "warn",
"react/no-find-dom-node": "warn",
"prefer-const": "warn"
}
}
+3 -3
View File
@@ -94,7 +94,7 @@ forge script script/DeployIdentitySystem.s.sol:DeployIdentitySystem \
# For Lux Mainnet
forge script script/DeployIdentitySystem.s.sol:DeployIdentitySystem \
--rpc-url https://api.lux.network/v1/bc/C/rpc \
--rpc-url https://api.lux.network/ext/bc/C/rpc \
--broadcast
# For Zoo Mainnet
@@ -131,8 +131,8 @@ Visit `http://localhost:3333/identity` to access the identity registration page.
|---------|----------|---------|----------|
| Hanzo Mainnet | 36963 | https://rpc.hanzo.ai | https://explorer.hanzo.ai |
| Hanzo Testnet | 36962 | https://testnet-rpc.hanzo.ai | https://testnet-explorer.hanzo.ai |
| Lux Mainnet | 96369 | https://api.lux.network/v1/bc/C/rpc | https://explorer.lux.network |
| Lux Testnet | 96368 | https://testnet-api.lux.network/v1/bc/C/rpc | https://testnet-explorer.lux.network |
| Lux Mainnet | 96369 | https://api.lux.network/ext/bc/C/rpc | https://explorer.lux.network |
| Lux Testnet | 96368 | https://testnet-api.lux.network/ext/bc/C/rpc | https://testnet-explorer.lux.network |
| Zoo Mainnet | 200200 | https://rpc.zoo.network | https://explorer.zoo.network |
| Zoo Testnet | 200201 | https://testnet-rpc.zoo.network | https://testnet-explorer.zoo.network |
-11
View File
@@ -203,17 +203,6 @@ export const Index: Record<string, any> = {
subcategory: "undefined",
chunks: []
},
"direction": {
name: "direction",
type: "components:ui",
registryDependencies: undefined,
component: React.lazy(() => import("@/registry/default/ui/direction")),
source: "",
files: ["registry/default/ui/direction.tsx"],
category: "undefined",
subcategory: "undefined",
chunks: []
},
"dialog": {
name: "dialog",
type: "components:ui",
-143
View File
@@ -1,143 +0,0 @@
/**
* docs-no-404.test.ts
*
* Static validation: every URL in docs.ts config has a matching MDX file.
* No server needed runs in CI before deployment.
*
* Run: pnpm test (via vitest)
*/
import { describe, it, expect } from 'vitest'
import fs from 'node:fs'
import path from 'node:path'
const CONTENT_DIR = path.resolve(__dirname, '../content/docs')
const CONFIG_PATH = path.resolve(__dirname, '../config/docs.ts')
/** Extract all href values from docs.ts config */
function extractUrlsFromConfig(): string[] {
const content = fs.readFileSync(CONFIG_PATH, 'utf-8')
const hrefRegex = /href:\s*["'`]([^"'`]+)["'`]/g
const urls: string[] = []
let match
while ((match = hrefRegex.exec(content)) !== null) {
urls.push(match[1])
}
return urls.filter(u => u.startsWith('/docs'))
}
/** Convert a /docs/... URL to its expected MDX file path */
function urlToMdxPath(url: string): string[] {
// /docs -> index.mdx
// /docs/charts/bar -> charts/bar.mdx OR charts/bar/index.mdx
const slug = url.replace(/^\/docs\/?/, '') || ''
if (!slug) {
return [path.join(CONTENT_DIR, 'index.mdx')]
}
return [
path.join(CONTENT_DIR, `${slug}.mdx`),
path.join(CONTENT_DIR, slug, 'index.mdx'),
]
}
/** Recursively find all MDX files in content/docs */
function findAllMdxFiles(dir: string, prefix = ''): string[] {
const results: string[] = []
if (!fs.existsSync(dir)) return results
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const fullPath = path.join(dir, entry.name)
if (entry.isDirectory()) {
results.push(...findAllMdxFiles(fullPath, `${prefix}${entry.name}/`))
} else if (entry.name.endsWith('.mdx')) {
const slug = entry.name === 'index.mdx'
? prefix.replace(/\/$/, '')
: `${prefix}${entry.name.replace('.mdx', '')}`
if (slug) {
results.push(`/docs/${slug}`)
} else {
results.push('/docs')
}
}
}
return results
}
describe('Documentation pages — zero 404s', () => {
const configUrls = extractUrlsFromConfig()
const mdxPages = findAllMdxFiles(CONTENT_DIR)
it('should find docs config with URLs', () => {
expect(configUrls.length).toBeGreaterThan(100)
})
it('should find MDX content files', () => {
expect(mdxPages.length).toBeGreaterThan(100)
})
describe('every config URL has a matching MDX file', () => {
for (const url of configUrls) {
it(`${url}`, () => {
const possiblePaths = urlToMdxPath(url)
const exists = possiblePaths.some(p => fs.existsSync(p))
if (!exists) {
throw new Error(
`Missing MDX file for ${url}. Expected one of:\n` +
possiblePaths.map(p => ` - ${p}`).join('\n')
)
}
})
}
})
describe('every MDX file is reachable from config', () => {
const configSet = new Set(configUrls)
const unreachable: string[] = []
for (const page of mdxPages) {
if (!configSet.has(page)) {
unreachable.push(page)
}
}
it('should have no orphaned MDX files (or document known exceptions)', () => {
// Allow a small number of known orphans (category index pages, etc.)
const KNOWN_ORPHANS = new Set([
'/docs/ai/voice-settings',
'/docs/components/animation-components',
])
const unexpected = unreachable.filter(u => !KNOWN_ORPHANS.has(u))
if (unexpected.length > 0) {
console.warn(`Orphaned MDX files (not in nav config):\n${unexpected.map(u => ` ${u}`).join('\n')}`)
}
// Warn but don't fail for orphans — they just won't be in nav
expect(true).toBe(true)
})
})
it('summary: config URLs vs MDX files', () => {
const configSet = new Set(configUrls)
const mdxSet = new Set(mdxPages)
const missingMdx = configUrls.filter(u => {
const paths = urlToMdxPath(u)
return !paths.some(p => fs.existsSync(p))
})
const orphanedMdx = mdxPages.filter(p => !configSet.has(p))
console.log(`\n📊 Docs coverage report:`)
console.log(` Config URLs: ${configUrls.length}`)
console.log(` MDX files: ${mdxPages.length}`)
console.log(` Missing MDX: ${missingMdx.length}`)
console.log(` Orphaned: ${orphanedMdx.length}`)
if (missingMdx.length > 0) {
console.error(`\n❌ URLs with no MDX file:\n${missingMdx.map(u => ` ${u}`).join('\n')}`)
}
if (orphanedMdx.length > 0) {
console.warn(`\n⚠️ MDX files not in nav:\n${orphanedMdx.map(u => ` ${u}`).join('\n')}`)
}
// This is the hard check — every config URL must have content
expect(missingMdx).toEqual([])
})
})
+2 -2
View File
@@ -42,8 +42,8 @@ describe("@hanzo/ui namespace imports - Type Resolution", () => {
* import { GridPattern } from '@hanzo/ui/pattern/grid'
* ```
*
* The package exports are properly configured in pkgs/ui/package.json.
* Build artifacts exist in pkgs/ui/dist/{code,3d,pattern}/.
* The package exports are properly configured in pkg/ui/package.json.
* Build artifacts exist in pkg/ui/dist/{code,3d,pattern}/.
*
* Vitest runtime resolution fails due to internal cross-package imports
* (e.g., CodeBlock imports from @hanzo/ui/lib/utils), which require
+29 -29
View File
@@ -1,9 +1,8 @@
"use client"
import * as React from "react"
import { Index } from "@/__registry__"
import { AlertCircle, RefreshCw } from "lucide-react"
import { Index } from "@/__registry__"
import { Badge } from "@/registry/default/ui/badge"
import { Button } from "@/registry/default/ui/button"
import { Card } from "@/registry/default/ui/card"
@@ -65,21 +64,24 @@ function BlockPreview({ blockName }: { blockName: string }) {
setState({ loaded: true, error: true, showContent: true })
}, [])
const handleRetry = React.useCallback((e: React.MouseEvent) => {
e.preventDefault()
e.stopPropagation()
setState({ loaded: false, error: false, showContent: false })
if (iframeRef.current) {
// Force reload by resetting src
const src = iframeRef.current.src
iframeRef.current.src = ""
setTimeout(() => {
if (iframeRef.current) {
iframeRef.current.src = src
}
}, 0)
}
}, [])
const handleRetry = React.useCallback(
(e: React.MouseEvent) => {
e.preventDefault()
e.stopPropagation()
setState({ loaded: false, error: false, showContent: false })
if (iframeRef.current) {
// Force reload by resetting src
const src = iframeRef.current.src
iframeRef.current.src = ""
setTimeout(() => {
if (iframeRef.current) {
iframeRef.current.src = src
}
}, 0)
}
},
[]
)
React.useEffect(() => {
return () => {
@@ -90,10 +92,7 @@ function BlockPreview({ blockName }: { blockName: string }) {
}, [])
return (
<div
ref={containerRef}
className="relative aspect-[4/3] min-h-[400px] bg-muted/50"
>
<div ref={containerRef} className="relative aspect-[4/3] min-h-[400px] bg-muted/50">
{/* Loading skeleton */}
{!state.showContent && (
<div className="absolute inset-0 flex items-center justify-center">
@@ -274,14 +273,15 @@ export default function BuilderPage() {
<h3 className="text-base font-semibold leading-tight">
{blockName}
</h3>
{block?.category && block?.category !== "undefined" && (
<Badge
variant="outline"
className="shrink-0 text-xs font-medium"
>
{block.category}
</Badge>
)}
{block?.category &&
block?.category !== "undefined" && (
<Badge
variant="outline"
className="shrink-0 text-xs font-medium"
>
{block.category}
</Badge>
)}
</div>
{block?.subcategory &&
block?.subcategory !== "undefined" && (
File diff suppressed because it is too large Load Diff
+427
View File
@@ -0,0 +1,427 @@
"use client"
import * as React from "react"
import dynamic from "next/dynamic"
import { Index } from "@/__registry__"
import {
closestCenter,
DndContext,
DragEndEvent,
DragOverlay,
DragStartEvent,
} from "@dnd-kit/core"
import {
arrayMove,
SortableContext,
useSortable,
verticalListSortingStrategy,
} from "@dnd-kit/sortable"
import { CSS } from "@dnd-kit/utilities"
import { Download, Eye, GripVertical, Plus, Trash2 } from "lucide-react"
import { Button } from "@/registry/new-york/ui/button"
import { Card } from "@/registry/new-york/ui/card"
import { Input } from "@/registry/new-york/ui/input"
import { ScrollArea } from "@/registry/new-york/ui/scroll-area"
import { Separator } from "@/registry/new-york/ui/separator"
// Dynamic block component loader
const DynamicBlock = ({ blockName, scale = 1 }: { blockName: string; scale?: number }) => {
const [BlockComponent, setBlockComponent] = React.useState<React.ComponentType | null>(null)
const [error, setError] = React.useState(false)
React.useEffect(() => {
import(`@/registry/default/block/${blockName}`)
.then((mod) => {
setBlockComponent(() => mod.default)
setError(false)
})
.catch((err) => {
console.error(`Failed to load block ${blockName}:`, err)
setError(true)
})
}, [blockName])
if (error) {
return (
<div className="flex h-full items-center justify-center bg-muted/50 p-4 text-center">
<p className="text-xs text-muted-foreground">Failed to load {blockName}</p>
</div>
)
}
if (!BlockComponent) {
return (
<div className="flex h-full items-center justify-center bg-muted/50">
<div className="h-4 w-4 animate-spin rounded-full border-2 border-primary border-t-transparent" />
</div>
)
}
return (
<div style={{ transform: `scale(${scale})`, transformOrigin: "top left" }}>
<BlockComponent />
</div>
)
}
interface PageBlock {
id: string
blockName: string
}
export default function PageBuilder() {
const [blocks, setBlocks] = React.useState<string[]>([])
const [availableBlocks, setAvailableBlocks] = React.useState<string[]>([])
const [pageBlocks, setPageBlocks] = React.useState<PageBlock[]>([])
const [activeId, setActiveId] = React.useState<string | null>(null)
const [filter, setFilter] = React.useState("")
const [viewport, setViewport] = React.useState<"desktop" | "tablet" | "mobile">("desktop")
React.useEffect(() => {
// Get block IDs from the registry index
const blockIds = Object.keys(Index.default || {}).filter((key) => {
const item = Index.default[key]
return item?.type === "components:block"
})
setBlocks(blockIds)
setAvailableBlocks(blockIds)
}, [])
const filteredBlocks = availableBlocks.filter((block) =>
block.toLowerCase().includes(filter.toLowerCase())
)
const addBlock = (blockName: string) => {
setPageBlocks([...pageBlocks, { id: crypto.randomUUID(), blockName }])
}
const removeBlock = (id: string) => {
setPageBlocks(pageBlocks.filter((b) => b.id !== id))
}
const handleDragStart = (event: DragStartEvent) => {
setActiveId(event.active.id as string)
}
const handleDragEnd = (event: DragEndEvent) => {
const { active, over } = event
setActiveId(null)
if (!over || active.id === over.id) return
setPageBlocks((items) => {
const oldIndex = items.findIndex((item) => item.id === active.id)
const newIndex = items.findIndex((item) => item.id === over.id)
return arrayMove(items, oldIndex, newIndex)
})
}
const generatePageCode = () => {
const imports = pageBlocks
.map((block) => `import ${toPascalCase(block.blockName)} from "@/registry/default/block/${block.blockName}"`)
.join("\n")
const components = pageBlocks
.map((block) => ` <${toPascalCase(block.blockName)} />`)
.join("\n")
return `"use client"
import * as React from "react"
${imports}
export default function CustomPage() {
return (
<div className="flex min-h-screen flex-col">
${components}
</div>
)
}
`
}
const copyCode = async () => {
const code = generatePageCode()
await navigator.clipboard.writeText(code)
// TODO: Show toast notification
}
const downloadCode = () => {
const code = generatePageCode()
const blob = new Blob([code], { type: "text/typescript" })
const url = URL.createObjectURL(blob)
const a = document.createElement("a")
a.href = url
a.download = "page.tsx"
a.click()
URL.revokeObjectURL(url)
}
const deployWithHanzo = () => {
// TODO: Integrate with Hanzo deployment API
const code = generatePageCode()
console.log("Deploying with Hanzo:", code)
// This would call hanzo deployment service
window.open("https://hanzo.ai/deploy", "_blank")
}
const toPascalCase = (str: string) => {
return str
.split("-")
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
.join("")
}
const viewportWidths = {
desktop: "100%",
tablet: "768px",
mobile: "375px",
}
return (
<div className="flex h-screen max-h-screen gap-4 p-6">
{/* Left Sidebar - Block Library */}
<div className="w-64 space-y-4">
<div>
<h2 className="text-lg font-semibold">Block Library</h2>
<p className="text-sm text-muted-foreground">
Drag blocks to build your page
</p>
</div>
<Input
placeholder="Filter blocks..."
value={filter}
onChange={(e) => setFilter(e.target.value)}
/>
<ScrollArea className="h-[calc(100vh-200px)]">
<div className="space-y-4">
{filteredBlocks.map((block) => (
<Card
key={block}
className="cursor-grab overflow-hidden transition-colors hover:bg-muted"
onClick={() => addBlock(block)}
>
{/* 1/4 Scale Block Preview */}
<div className="relative h-32 overflow-hidden bg-muted/50">
<div className="pointer-events-none">
<DynamicBlock blockName={block} scale={0.25} />
</div>
{/* Overlay with block name and add button */}
<div className="absolute inset-0 flex items-center justify-center bg-background/0 opacity-0 transition-opacity hover:bg-background/80 hover:opacity-100">
<div className="flex items-center gap-2">
<Plus className="h-5 w-5" />
<span className="text-sm font-medium">Add to page</span>
</div>
</div>
</div>
<div className="border-t p-2">
<p className="truncate text-xs font-medium">{block}</p>
</div>
</Card>
))}
</div>
</ScrollArea>
</div>
<Separator orientation="vertical" />
{/* Center - Page Builder Canvas */}
<div className="flex-1 space-y-4">
<div className="flex items-center justify-between">
<div>
<h2 className="text-lg font-semibold">Page Builder</h2>
<p className="text-sm text-muted-foreground">
{pageBlocks.length} blocks in page
</p>
</div>
<div className="flex items-center gap-2">
{/* Viewport Controls */}
<div className="flex rounded-lg border">
<Button
variant={viewport === "mobile" ? "default" : "ghost"}
size="sm"
onClick={() => setViewport("mobile")}
className="rounded-r-none"
>
Mobile
</Button>
<Button
variant={viewport === "tablet" ? "default" : "ghost"}
size="sm"
onClick={() => setViewport("tablet")}
className="rounded-none border-x"
>
Tablet
</Button>
<Button
variant={viewport === "desktop" ? "default" : "ghost"}
size="sm"
onClick={() => setViewport("desktop")}
className="rounded-l-none"
>
Desktop
</Button>
</div>
<Separator orientation="vertical" className="h-8" />
<div className="flex gap-2">
<Button
variant="outline"
size="sm"
onClick={copyCode}
disabled={pageBlocks.length === 0}
>
<svg
className="mr-2 h-4 w-4"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<rect width="13" height="13" x="9" y="9" rx="2" ry="2" />
<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />
</svg>
Copy Code
</Button>
<Button
variant="outline"
size="sm"
onClick={downloadCode}
disabled={pageBlocks.length === 0}
>
<Download className="mr-2 h-4 w-4" />
Download
</Button>
<Button
variant="default"
size="sm"
onClick={deployWithHanzo}
disabled={pageBlocks.length === 0}
>
<svg
className="mr-2 h-4 w-4"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" />
</svg>
Deploy with Hanzo
</Button>
</div>
</div>
</div>
<ScrollArea className="h-[calc(100vh-140px)] rounded-lg border bg-background">
<div className="flex min-h-full items-start justify-center p-4">
<div
style={{
width: viewportWidths[viewport],
maxWidth: "100%",
transition: "width 0.3s ease",
}}
>
<DndContext
collisionDetection={closestCenter}
onDragStart={handleDragStart}
onDragEnd={handleDragEnd}
>
<SortableContext
items={pageBlocks.map((b) => b.id)}
strategy={verticalListSortingStrategy}
>
<div className="min-h-[600px] bg-background">
{pageBlocks.length === 0 ? (
<div className="flex h-96 items-center justify-center rounded-lg border border-dashed text-center">
<div className="space-y-2">
<p className="text-sm text-muted-foreground">
Your page is empty
</p>
<p className="text-xs text-muted-foreground">
Click blocks from the left to add them
</p>
</div>
</div>
) : (
pageBlocks.map((block) => (
<SortableBlock
key={block.id}
id={block.id}
blockName={block.blockName}
onRemove={() => removeBlock(block.id)}
/>
))
)}
</div>
</SortableContext>
<DragOverlay>
{activeId ? (
<div className="rounded-lg border bg-card p-4 shadow-lg">
<p className="text-sm font-medium">
{pageBlocks.find((b) => b.id === activeId)?.blockName}
</p>
</div>
) : null}
</DragOverlay>
</DndContext>
</div>
</div>
</ScrollArea>
</div>
</div>
)
}
function SortableBlock({
id,
blockName,
onRemove,
}: {
id: string
blockName: string
onRemove: () => void
}) {
const {
attributes,
listeners,
setNodeRef,
transform,
transition,
isDragging,
} = useSortable({ id })
const style = {
transform: CSS.Transform.toString(transform),
transition,
opacity: isDragging ? 0.5 : 1,
}
return (
<div ref={setNodeRef} style={style} className="group relative">
<div className="absolute -left-12 top-2 z-10 flex flex-col items-center gap-2">
<button
{...attributes}
{...listeners}
className="cursor-grab rounded bg-card p-1 shadow-sm hover:shadow active:cursor-grabbing"
>
<GripVertical className="h-4 w-4 text-muted-foreground" />
</button>
<Button
variant="ghost"
size="icon"
onClick={onRemove}
className="h-6 w-6 bg-background/80 opacity-0 backdrop-blur transition-opacity group-hover:opacity-100"
>
<Trash2 className="h-3 w-3" />
</Button>
</div>
{/* Block Preview - No gaps between blocks */}
<div className="relative overflow-hidden border-b last:border-b-0">
<DynamicBlock blockName={blockName} scale={1} />
</div>
</div>
)
}
+1 -1
View File
@@ -1,12 +1,12 @@
import Link from "next/link"
import { notFound } from "next/navigation"
import { mdxComponents } from "@/mdx-components"
import { findNeighbour } from "@hanzo/docs-core/page-tree"
import {
IconArrowLeft,
IconArrowRight,
IconArrowUpRight,
} from "@tabler/icons-react"
import { findNeighbour } from "@hanzo/docs-core/page-tree"
import { source } from "@/lib/source"
import { absoluteUrl } from "@/lib/utils"
+2 -2
View File
@@ -1,6 +1,7 @@
"use client"
import { useEffect, useState } from "react"
import { ConnectButton } from "@rainbow-me/rainbowkit"
import { formatEther } from "viem"
import {
useAccount,
@@ -10,7 +11,6 @@ import {
useWriteContract,
} from "wagmi"
import { ConnectWallet } from "@/components/connect-wallet"
import {
AI_TOKEN_ABI,
CONTRACT_ADDRESSES,
@@ -208,7 +208,7 @@ export function IdentityForm() {
</CardDescription>
</CardHeader>
<CardContent>
<ConnectWallet />
<ConnectButton />
{isConnected && aiBalance !== undefined && (
<div className="mt-4">
+1 -1
View File
@@ -304,7 +304,7 @@ export default function MCPPage() {
</p>
<div className="flex gap-4">
<Button asChild>
<Link href="https://discord.gg/CJCyAsm9Vr">Join Discord</Link>
<Link href="https://discord.gg/hanzo">Join Discord</Link>
</Button>
<Button variant="outline" asChild>
<Link href="/docs">Read Documentation</Link>
-18
View File
@@ -1,18 +0,0 @@
/**
* POST /api/chat AI chat about UI components.
*
* Uses Hanzo AI (zen-coder-flash) to answer questions about
* Hanzo UI components, props, patterns, and composition.
* Compatible with Vercel AI SDK useChat hook.
*/
import { NextResponse } from 'next/server'
export const dynamic = "force-static"
export async function GET() {
return NextResponse.json(
{ error: 'AI chat requires a server runtime. Use api.hanzo.ai/v1 directly.' },
{ status: 501 },
)
}
@@ -1,38 +0,0 @@
/**
* GET /api/registry/components/:name Get component with full source.
*
* Returns the component JSON including embedded source code.
*/
import { NextRequest, NextResponse } from "next/server"
import { getComponent, getComponentMap } from "../../lib"
export const dynamic = "force-static"
export const dynamicParams = false
export function generateStaticParams() {
const map = getComponentMap()
return Array.from(map.keys()).map((name) => ({ name }))
}
export async function GET(
_req: NextRequest,
{ params }: { params: Promise<{ name: string }> }
) {
const { name } = await params
const component = getComponent(name)
if (!component) {
return NextResponse.json(
{ error: "Component not found", name },
{ status: 404 }
)
}
return NextResponse.json(component, {
headers: {
"Cache-Control": "public, s-maxage=900, stale-while-revalidate=1800",
"Access-Control-Allow-Origin": "*",
},
})
}
-22
View File
@@ -1,22 +0,0 @@
/**
* GET /api/registry/index Full registry manifest.
*
* Returns ALL components with source in a single payload.
* MCP clients can hydrate their cache with one HTTP call.
*/
import { NextResponse } from "next/server"
import { getFullManifest } from "../lib"
export const dynamic = "force-static"
export async function GET() {
const manifest = getFullManifest()
return NextResponse.json(manifest, {
headers: {
"Cache-Control": "public, s-maxage=900, stale-while-revalidate=1800",
"Access-Control-Allow-Origin": "*",
},
})
}
-117
View File
@@ -1,117 +0,0 @@
/**
* Shared registry data loader for API routes.
*
* Reads from the built registry JSON files in public/registry/.
* These are generated at build time by scripts/build-registry.mts.
*/
import { readFileSync, readdirSync, existsSync } from "fs"
import path from "path"
const REGISTRY_DIR = path.join(process.cwd(), "public/registry")
const STYLES_DIR = path.join(REGISTRY_DIR, "styles/default")
export interface RegistryItem {
name: string
type: string
dependencies?: string[]
devDependencies?: string[]
registryDependencies?: string[]
files: Array<{ name: string; content: string } | string>
description?: string
category?: string
}
// In-memory cache (populated on first access, lives for the server lifetime)
let _index: RegistryItem[] | null = null
let _components: Map<string, RegistryItem> | null = null
function loadIndex(): RegistryItem[] {
if (_index) return _index
const indexPath = path.join(REGISTRY_DIR, "index.json")
if (!existsSync(indexPath)) return []
_index = JSON.parse(readFileSync(indexPath, "utf-8")) as RegistryItem[]
return _index
}
function loadComponents(): Map<string, RegistryItem> {
if (_components) return _components
_components = new Map()
if (!existsSync(STYLES_DIR)) return _components
const files = readdirSync(STYLES_DIR).filter((f) => f.endsWith(".json"))
for (const file of files) {
try {
const data = JSON.parse(
readFileSync(path.join(STYLES_DIR, file), "utf-8")
) as RegistryItem
_components.set(data.name, data)
} catch {
// skip malformed files
}
}
return _components
}
/** Get the full component index (names, types, deps — no source). */
export function getIndex(): RegistryItem[] {
return loadIndex()
}
/** Get all components with full source code. */
export function getComponentMap(): Map<string, RegistryItem> {
return loadComponents()
}
/** Get a single component by name (with source). */
export function getComponent(name: string): RegistryItem | undefined {
const map = loadComponents()
// Try exact match first
let item = map.get(name)
if (item) return item
// Try with -demo suffix stripped
item = map.get(`${name}-demo`)
return item
}
/** Search components by name/type. */
export function searchComponents(query: string): RegistryItem[] {
const q = query.toLowerCase()
const index = loadIndex()
return index.filter(
(item) =>
item.name.toLowerCase().includes(q) ||
item.type?.toLowerCase().includes(q) ||
item.description?.toLowerCase().includes(q) ||
item.category?.toLowerCase().includes(q)
)
}
/** List components filtered by type. */
export function listByType(type?: string): RegistryItem[] {
const index = loadIndex()
if (!type) return index
return index.filter((item) => item.type === type || item.type?.includes(type))
}
/** Get full registry manifest (all components with source — single payload). */
export function getFullManifest() {
const map = loadComponents()
const components: Record<string, any> = {}
for (const [name, item] of map) {
components[name] = item
}
return {
generated_at: Date.now(),
total: map.size,
components,
}
}
/** Invalidate the in-memory cache (call after registry:build). */
export function invalidateCache() {
_index = null
_components = null
}
-30
View File
@@ -1,30 +0,0 @@
/**
* GET /api/registry/search?q=button Search components.
*/
import { NextResponse } from "next/server"
import { getIndex } from "../lib"
export const dynamic = "force-static"
export async function GET() {
// Static export: return full index (client-side filtering)
const items = getIndex()
return NextResponse.json(
{
total: items.length,
results: items.map((item) => ({
name: item.name,
type: item.type,
dependencies: item.dependencies,
})),
},
{
headers: {
"Cache-Control": "public, s-maxage=300, stale-while-revalidate=600",
"Access-Control-Allow-Origin": "*",
},
}
)
}
-17
View File
@@ -1,17 +0,0 @@
/**
* POST /api/search Search UI components via Hanzo Cloud.
*
* Proxies to Hanzo Cloud search-docs API with the publishable key.
* Client-side code hits this route instead of Cloud directly.
*/
import { NextResponse } from 'next/server'
export const dynamic = "force-static"
export async function GET() {
return NextResponse.json(
{ error: 'Search requires a server runtime. Use client-side search.' },
{ status: 501 },
)
}
+5 -5
View File
@@ -2,6 +2,11 @@ import "@/styles/globals.css"
import { Metadata, Viewport } from "next"
const META_THEME_COLORS = {
light: "white",
dark: "black",
}
import { siteConfig } from "@/config/site"
import { fontMono, fontSans } from "@/lib/fonts"
import { cn } from "@/lib/utils"
@@ -18,11 +23,6 @@ import {
Toaster as NewYorkToaster,
} from "@/registry/default/ui/toaster"
const META_THEME_COLORS = {
light: "white",
dark: "black",
}
export const metadata: Metadata = {
title: {
default: siteConfig.name,
+2 -16
View File
@@ -1,21 +1,7 @@
"use client"
import { useEffect, useRef } from "react"
import { usePathname } from "next/navigation"
import { analytics } from "@/lib/analytics"
import { Analytics as VercelAnalytics } from "@vercel/analytics/react"
export function Analytics() {
const pathname = usePathname()
const started = useRef(false)
useEffect(() => {
if (!started.current) {
started.current = true
analytics.init()
}
analytics.pageview(pathname ?? undefined)
}, [pathname])
return null
return <VercelAnalytics />
}
+1 -5
View File
@@ -222,11 +222,7 @@ function BlockViewerToolbar({ styleName }: { styleName: Style["name"] }) {
}}
title="Copy install command"
>
{isCopied ? (
<Check className="!h-3.5 !w-3.5" />
) : (
<Clipboard className="!h-3.5 !w-3.5" />
)}
{isCopied ? <Check className="!h-3.5 !w-3.5" /> : <Clipboard className="!h-3.5 !w-3.5" />}
<span className="sr-only">Copy install command</span>
</Button>
<Separator orientation="vertical" className="mx-1 !h-4" />
+1 -9
View File
@@ -62,15 +62,7 @@ export function CommandMenu({ ...props }: DialogProps) {
const { recentSearches, addRecentSearch, clearRecentSearches } =
useRecentSearches()
// SSR renders without `window`, so the first client (hydration) render MUST
// also produce "Ctrl" — computing the platform-specific glyph during render
// makes the hydrated text ("⌘" on macOS) diverge from the server text
// ("Ctrl") → React #418 (hydration text mismatch). Start from the SSR-stable
// value and upgrade to the platform glyph after mount (client-only effect).
const [modKey, setModKey] = React.useState("Ctrl")
React.useEffect(() => {
if (isMacOS()) setModKey("⌘")
}, [])
const modKey = React.useMemo(() => (isMacOS() ? "⌘" : "Ctrl"), [])
React.useEffect(() => {
const down = (e: KeyboardEvent) => {
-40
View File
@@ -1,40 +0,0 @@
"use client"
import { useAccount, useConnect, useDisconnect } from "wagmi"
import { Button } from "@/registry/default/ui/button"
const short = (address: string) => `${address.slice(0, 6)}${address.slice(-4)}`
/**
* Connect the wallet the browser already has, over EIP-1193. There is no
* third-party modal and no bridge service in the page the extension is the
* only party involved.
*/
export function ConnectWallet() {
const { address, isConnected } = useAccount()
const { connect, connectors, isPending } = useConnect()
const { disconnect } = useDisconnect()
if (isConnected && address) {
return (
<div className="flex items-center gap-3">
<span className="font-mono text-sm">{short(address)}</span>
<Button variant="outline" size="sm" onClick={() => disconnect()}>
Disconnect
</Button>
</div>
)
}
const injected = connectors[0]
return (
<Button
onClick={() => injected && connect({ connector: injected })}
disabled={!injected || isPending}
>
{isPending ? "Connecting…" : "Connect Wallet"}
</Button>
)
}
+22 -6
View File
@@ -1,18 +1,34 @@
"use client"
import { type ReactNode } from "react"
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
import { WagmiProvider } from "wagmi"
import "@rainbow-me/rainbowkit/styles.css"
import { getConfig } from "@/lib/wagmi"
import { useEffect, useState, type ReactNode } from "react"
import { RainbowKitProvider } from "@rainbow-me/rainbowkit"
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
import { WagmiProvider, type Config } from "wagmi"
const queryClient = new QueryClient()
const config = getConfig()
export function Web3Provider({ children }: { children: ReactNode }) {
const [config, setConfig] = useState<Config | null>(null)
useEffect(() => {
// Dynamically import wagmi config only on client side
import("@/lib/wagmi").then((mod) => {
setConfig(mod.getConfig())
})
}, [])
// Don't render until config is loaded
if (!config) {
return <>{children}</>
}
return (
<WagmiProvider config={config}>
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
<QueryClientProvider client={queryClient}>
<RainbowKitProvider modalSize="compact">{children}</RainbowKitProvider>
</QueryClientProvider>
</WagmiProvider>
)
}
-200
View File
@@ -97,82 +97,6 @@ export const docsConfig: DocsConfig = {
href: "/docs/changelog",
items: [],
},
{
title: "MCP Server",
href: "/docs/mcp",
items: [],
label: "New",
},
{
title: "About",
href: "/docs/about",
items: [],
},
],
},
{
title: "Installation",
items: [
{
title: "Next.js",
href: "/docs/installation/next",
items: [],
},
{
title: "Vite",
href: "/docs/installation/vite",
items: [],
},
{
title: "Remix",
href: "/docs/installation/remix",
items: [],
},
{
title: "Astro",
href: "/docs/installation/astro",
items: [],
},
{
title: "Gatsby",
href: "/docs/installation/gatsby",
items: [],
},
{
title: "Laravel",
href: "/docs/installation/laravel",
items: [],
},
{
title: "Manual",
href: "/docs/installation/manual",
items: [],
},
],
},
{
title: "Dark Mode",
items: [
{
title: "Next.js",
href: "/docs/dark-mode/next",
items: [],
},
{
title: "Vite",
href: "/docs/dark-mode/vite",
items: [],
},
{
title: "Remix",
href: "/docs/dark-mode/remix",
items: [],
},
{
title: "Astro",
href: "/docs/dark-mode/astro",
items: [],
},
],
},
{
@@ -219,12 +143,6 @@ export const docsConfig: DocsConfig = {
href: "/docs/components/button",
items: [],
},
{
title: "Button Group",
href: "/docs/components/button-group",
items: [],
label: "New",
},
{
title: "Calendar",
href: "/docs/components/calendar",
@@ -270,30 +188,6 @@ export const docsConfig: DocsConfig = {
href: "/docs/components/data-table",
items: [],
},
{
title: "Desktop",
href: "/docs/components/desktop",
items: [],
label: "New",
},
{
title: "Desktop Hooks",
href: "/docs/components/desktop-hooks",
items: [],
label: "New",
},
{
title: "Desktop Spotlight",
href: "/docs/components/desktop-spotlight",
items: [],
label: "New",
},
{
title: "Desktop Window",
href: "/docs/components/desktop-window",
items: [],
label: "New",
},
{
title: "Date Picker",
href: "/docs/components/date-picker",
@@ -304,12 +198,6 @@ export const docsConfig: DocsConfig = {
href: "/docs/components/dialog",
items: [],
},
{
title: "Direction",
href: "/docs/components/direction",
items: [],
label: "New",
},
{
title: "Drawer",
href: "/docs/components/drawer",
@@ -320,18 +208,6 @@ export const docsConfig: DocsConfig = {
href: "/docs/components/dropdown-menu",
items: [],
},
{
title: "Empty State",
href: "/docs/components/empty",
items: [],
label: "New",
},
{
title: "Field",
href: "/docs/components/field",
items: [],
label: "New",
},
{
title: "Form",
href: "/docs/components/form",
@@ -347,24 +223,12 @@ export const docsConfig: DocsConfig = {
href: "/docs/components/input",
items: [],
},
{
title: "Input Group",
href: "/docs/components/input-group",
items: [],
label: "New",
},
{
title: "Input OTP",
href: "/docs/components/input-otp",
items: [],
label: "New",
},
{
title: "Item",
href: "/docs/components/item",
items: [],
label: "New",
},
{
title: "Label",
href: "/docs/components/label",
@@ -749,24 +613,6 @@ export const docsConfig: DocsConfig = {
items: [],
label: "New",
},
{
title: "Particles Background",
href: "/docs/components/particles-background",
items: [],
label: "New",
},
{
title: "Grid Pattern",
href: "/docs/components/grid-pattern",
items: [],
label: "New",
},
{
title: "Timeline",
href: "/docs/components/timeline",
items: [],
label: "New",
},
{
title: "Pin List",
href: "/docs/components/pin-list",
@@ -1182,18 +1028,6 @@ export const docsConfig: DocsConfig = {
items: [],
label: "New",
},
{
title: "AI Code",
href: "/docs/ai/code",
items: [],
label: "New",
},
{
title: "AI Voice",
href: "/docs/ai/voice",
items: [],
label: "New",
},
],
},
{
@@ -1340,40 +1174,6 @@ export const docsConfig: DocsConfig = {
},
],
},
{
title: "Guides",
items: [
{
title: "Page Builder",
href: "/docs/guides/page-builder",
items: [],
label: "New",
},
{
title: "Visual Workflows",
href: "/docs/guides/visual-workflows",
items: [],
label: "New",
},
],
},
{
title: "Hanzo React",
items: [
{
title: "Getting Started",
href: "/docs/hanzo-react/getting-started",
items: [],
label: "New",
},
{
title: "Hooks",
href: "/docs/hanzo-react/hooks",
items: [],
label: "New",
},
],
},
{
title: "Packages",
items: [
+1 -1
View File
@@ -8,7 +8,7 @@ export const siteConfig = {
links: {
twitter: "https://x.com/hanzoai",
github: "https://github.com/hanzoai/ui",
discord: "https://discord.gg/CJCyAsm9Vr",
discord: "https://discord.gg/hanzo",
},
}
-27
View File
@@ -1,27 +0,0 @@
---
title: Contact Forms
description: Contact form sections with validation, multiple fields, and submission handling.
---
## Overview
Contact form blocks provide complete form layouts for collecting user inquiries. They include input validation, loading states, and success confirmation.
## Features
- **Form Validation**: Built-in HTML5 and custom validation
- **Multiple Fields**: Name, email, subject, and message inputs
- **Loading States**: Visual feedback during form submission
- **Success Message**: Confirmation after successful submission
- **Responsive Design**: Adapts to all screen sizes
- **Accessible**: Semantic form elements with proper labels
## Usage
```tsx
import ContactBlock from "@/registry/default/block/contact"
export default function Page() {
return <ContactBlock />
}
```
-26
View File
@@ -1,26 +0,0 @@
---
title: CTA Sections
description: Call-to-action sections for driving user conversions and signups.
---
## Overview
CTA (Call-to-Action) blocks are designed to drive user engagement and conversions. They feature prominent buttons, compelling copy, and focused layouts that guide users toward a specific action.
## Features
- **Conversion-Focused**: Designed to maximize click-through rates
- **Responsive Design**: Adapts to all screen sizes
- **Multiple Layouts**: Centered, split, and banner variations
- **Button Variants**: Primary, secondary, and ghost CTA styles
- **Background Options**: Solid colors, gradients, and image backgrounds
## Usage
```tsx
import CTABlock from "@/registry/default/block/cta"
export default function Page() {
return <CTABlock />
}
```
-27
View File
@@ -1,27 +0,0 @@
---
title: FAQ Sections
description: Frequently asked questions sections with expandable accordions and search.
---
## Overview
FAQ blocks present commonly asked questions in organized, expandable layouts. They use accordion patterns for progressive disclosure and optional search filtering.
## Features
- **Accordion Layout**: Expandable question/answer pairs
- **Search Filtering**: Optional search to find specific questions
- **Categories**: Group questions by topic
- **Responsive**: Full-width layout that works on all devices
- **Accessible**: Keyboard navigation and screen reader support
- **Animated**: Smooth expand/collapse transitions
## Usage
```tsx
import FAQBlock from "@/registry/default/block/faq"
export default function Page() {
return <FAQBlock />
}
```
-26
View File
@@ -1,26 +0,0 @@
---
title: Feature Sections
description: Feature grid and list sections for highlighting product capabilities.
---
## Overview
Feature blocks display product capabilities in organized grid or list layouts. They combine icons, headings, and descriptions to communicate value propositions clearly.
## Features
- **Grid Layouts**: 2, 3, or 4 column responsive grids
- **Icon Support**: Lucide icons or custom SVGs
- **Responsive**: Stacks to single column on mobile
- **Customizable**: Flexible content and styling options
- **Accessible**: Semantic HTML with proper heading hierarchy
## Usage
```tsx
import FeaturesBlock from "@/registry/default/block/features"
export default function Page() {
return <FeaturesBlock />
}
```
-36
View File
@@ -1,36 +0,0 @@
---
title: Hero Sections
description: Full-width hero sections for landing pages with headlines, CTAs, and imagery.
---
## Overview
Hero blocks are viewport-sized sections designed for the top of landing pages. They feature bold typography, call-to-action buttons, and visual elements to capture user attention.
## Variations
### App UI Showcase
<ComponentPreview name="showcase-app-ui-01" />
A hero section showcasing your app's UI with a centered layout and product screenshot.
### E-commerce Showcase
<ComponentPreview name="showcase-ecommerce-01" />
A hero section designed for e-commerce with product imagery and shopping CTAs.
### Marketing Showcase
<ComponentPreview name="showcase-marketing-01" />
A bold marketing hero section with large typography and conversion-focused design.
## Features
- **Responsive Design**: Adapts to all screen sizes
- **CTA Buttons**: Primary and secondary call-to-action buttons
- **Visual Elements**: Support for images, gradients, and animations
- **Typography**: Large, bold headlines with supporting text
- **Customizable**: Easy to modify colors, text, and layout
-27
View File
@@ -1,27 +0,0 @@
---
title: Stats Sections
description: Statistics and metrics sections with counters, charts, and key figures.
---
## Overview
Stats blocks display key metrics and achievements in visually impactful layouts. They feature animated counters, comparison figures, and trend indicators.
## Features
- **Animated Counters**: Number animations on scroll into view
- **Multiple Layouts**: Grid, inline, and featured stat variations
- **Trend Indicators**: Up/down arrows with percentage changes
- **Responsive**: Adapts from multi-column to single column on mobile
- **Icons**: Support for metric-specific icons
- **Customizable**: Easy to update values and labels
## Usage
```tsx
import StatsBlock from "@/registry/default/block/stats"
export default function Page() {
return <StatsBlock />
}
```
-27
View File
@@ -1,27 +0,0 @@
---
title: Team Sections
description: Team member grid and list sections with photos, roles, and social links.
---
## Overview
Team blocks showcase team members with profile photos, names, roles, and social links. They support multiple layout variations for different page contexts.
## Features
- **Grid Layout**: Responsive grid with team member cards
- **Profile Photos**: Avatar images with fallback initials
- **Role Display**: Job titles and department labels
- **Social Links**: GitHub, Twitter, LinkedIn integration
- **Responsive**: Adapts columns based on screen size
- **Hover Effects**: Interactive card hover states
## Usage
```tsx
import TeamBlock from "@/registry/default/block/team"
export default function Page() {
return <TeamBlock />
}
```
-27
View File
@@ -1,27 +0,0 @@
---
title: Testimonials
description: Testimonial sections with user quotes, ratings, and social proof.
---
## Overview
Testimonial blocks display customer reviews and social proof in visually appealing layouts. They support avatars, star ratings, company logos, and quote formatting.
## Features
- **Multiple Layouts**: Grid, carousel, and featured testimonial styles
- **Avatar Support**: User photos with name and title
- **Star Ratings**: Visual rating display
- **Company Logos**: Brand association for B2B testimonials
- **Responsive**: Adapts from multi-column to single column on mobile
- **Animated**: Optional entrance animations and carousel transitions
## Usage
```tsx
import TestimonialsBlock from "@/registry/default/block/testimonials"
export default function Page() {
return <TestimonialsBlock />
}
```
-64
View File
@@ -1,64 +0,0 @@
---
title: Area Chart
description: Area charts for visualizing trends and cumulative values over time.
---
<ComponentPreview name="chart-demo" description="Area chart example" />
## Overview
Area charts are used to show trends over time or across categories. They combine line charts with filled areas beneath the line to emphasize volume.
## Usage
```tsx
import { ChartContainer, ChartTooltip, ChartTooltipContent } from "@hanzo/ui"
import { Area, AreaChart, CartesianGrid, XAxis } from "recharts"
const data = [
{ month: "Jan", desktop: 186, mobile: 80 },
{ month: "Feb", desktop: 305, mobile: 200 },
{ month: "Mar", desktop: 237, mobile: 120 },
]
const config = {
desktop: { label: "Desktop", color: "hsl(var(--chart-1))" },
mobile: { label: "Mobile", color: "hsl(var(--chart-2))" },
}
export function AreaChartDemo() {
return (
<ChartContainer config={config}>
<AreaChart data={data}>
<CartesianGrid vertical={false} />
<XAxis dataKey="month" />
<ChartTooltip content={<ChartTooltipContent />} />
<Area
dataKey="desktop"
fill="var(--color-desktop)"
stroke="var(--color-desktop)"
/>
<Area
dataKey="mobile"
fill="var(--color-mobile)"
stroke="var(--color-mobile)"
/>
</AreaChart>
</ChartContainer>
)
}
```
## Variants
### Stacked Area
Stack multiple areas to show cumulative totals.
### Gradient Fill
Apply gradient fills for visual depth.
### Step Area
Use `type="step"` for discrete step transitions.
-58
View File
@@ -1,58 +0,0 @@
---
title: Bar Chart
description: Bar charts for comparing categorical data and distributions.
---
<ComponentPreview name="chart-demo" description="Bar chart example" />
## Overview
Bar charts display data with rectangular bars proportional to their values. They are ideal for comparing quantities across categories.
## Usage
```tsx
import { ChartContainer, ChartTooltip, ChartTooltipContent } from "@hanzo/ui"
import { Bar, BarChart, CartesianGrid, XAxis } from "recharts"
const data = [
{ month: "Jan", desktop: 186 },
{ month: "Feb", desktop: 305 },
{ month: "Mar", desktop: 237 },
]
const config = {
desktop: { label: "Desktop", color: "hsl(var(--chart-1))" },
}
export function BarChartDemo() {
return (
<ChartContainer config={config}>
<BarChart data={data}>
<CartesianGrid vertical={false} />
<XAxis dataKey="month" />
<ChartTooltip content={<ChartTooltipContent />} />
<Bar dataKey="desktop" fill="var(--color-desktop)" radius={4} />
</BarChart>
</ChartContainer>
)
}
```
## Variants
### Horizontal Bar
Use `layout="vertical"` for horizontal orientation.
### Stacked Bar
Stack multiple bars to show composition within categories.
### Mixed Bar
Combine different bar styles and data series.
### With Labels
Add data labels directly on bars using custom label components.
-108
View File
@@ -1,108 +0,0 @@
---
title: Charts
description: Beautiful, composable chart components built on Recharts.
---
## Overview
@hanzo/ui provides a set of chart components built on top of [Recharts](https://recharts.org/). The chart components are designed to be composable and work with Tailwind CSS theming.
## Installation
<Tabs defaultValue="cli">
<TabsList>
<TabsTrigger value="cli">CLI</TabsTrigger>
<TabsTrigger value="manual">Manual</TabsTrigger>
</TabsList>
<TabsContent value="cli">
```bash
npx @hanzo/ui@latest add chart
```
</TabsContent>
<TabsContent value="manual">
<Steps>
<Step>Install recharts:</Step>
```bash
pnpm add recharts
```
<Step>Copy the chart components into your project.</Step>
<ComponentSource name="chart" />
</Steps>
</TabsContent>
</Tabs>
## Components
The chart package includes the following components:
- **ChartContainer** - Responsive container that handles theming and sizing
- **ChartTooltip** - Styled tooltip component
- **ChartTooltipContent** - Content renderer for tooltips
- **ChartLegend** - Chart legend component
- **ChartLegendContent** - Content renderer for legends
## Chart Types
- [Area Chart](/docs/charts/area) - For showing trends over time
- [Bar Chart](/docs/charts/bar) - For comparing categorical data
- [Line Chart](/docs/charts/line) - For showing continuous data
- [Pie Chart](/docs/charts/pie) - For showing proportional data
- [Radar Chart](/docs/charts/radar) - For multivariate data comparison
- [Radial Chart](/docs/charts/radial) - For circular data visualization
- [Tooltip](/docs/charts/tooltip) - Shared tooltip component
## Usage
```tsx
import { ChartContainer, ChartTooltip, ChartTooltipContent } from "@hanzo/ui"
import { Bar, BarChart, XAxis } from "recharts"
const data = [
{ month: "Jan", value: 186 },
{ month: "Feb", value: 305 },
{ month: "Mar", value: 237 },
]
const config = {
value: { label: "Value", color: "hsl(var(--chart-1))" },
}
export function MyChart() {
return (
<ChartContainer config={config}>
<BarChart data={data}>
<XAxis dataKey="month" />
<ChartTooltip content={<ChartTooltipContent />} />
<Bar dataKey="value" fill="var(--color-value)" />
</BarChart>
</ChartContainer>
)
}
```
## Theming
Charts use CSS variables for theming. Define chart colors in your CSS:
```css
:root {
--chart-1: 12 76% 61%;
--chart-2: 173 58% 39%;
--chart-3: 197 37% 24%;
--chart-4: 43 74% 66%;
--chart-5: 27 87% 67%;
}
```
-60
View File
@@ -1,60 +0,0 @@
---
title: Line Chart
description: Line charts for showing continuous data trends and comparisons.
---
<ComponentPreview name="chart-demo" description="Line chart example" />
## Overview
Line charts connect data points with straight or curved lines, ideal for showing trends and changes over continuous intervals.
## Usage
```tsx
import { ChartContainer, ChartTooltip, ChartTooltipContent } from "@hanzo/ui"
import { CartesianGrid, Line, LineChart, XAxis } from "recharts"
const data = [
{ month: "Jan", desktop: 186, mobile: 80 },
{ month: "Feb", desktop: 305, mobile: 200 },
{ month: "Mar", desktop: 237, mobile: 120 },
]
const config = {
desktop: { label: "Desktop", color: "hsl(var(--chart-1))" },
mobile: { label: "Mobile", color: "hsl(var(--chart-2))" },
}
export function LineChartDemo() {
return (
<ChartContainer config={config}>
<LineChart data={data}>
<CartesianGrid vertical={false} />
<XAxis dataKey="month" />
<ChartTooltip content={<ChartTooltipContent />} />
<Line dataKey="desktop" stroke="var(--color-desktop)" strokeWidth={2} />
<Line dataKey="mobile" stroke="var(--color-mobile)" strokeWidth={2} />
</LineChart>
</ChartContainer>
)
}
```
## Variants
### With Dots
Show data point markers on the line.
### Custom Dots
Use custom shapes for data point markers.
### Linear vs Curved
Toggle between `type="linear"` and `type="monotone"` interpolation.
### Interactive
Add hover interactions and clickable data points.
-52
View File
@@ -1,52 +0,0 @@
---
title: Pie Chart
description: Pie and donut charts for showing proportional data and distributions.
---
## Overview
Pie charts display data as proportional slices of a circle, ideal for showing parts of a whole.
## Usage
```tsx
import { ChartContainer, ChartTooltip, ChartTooltipContent } from "@hanzo/ui"
import { Pie, PieChart } from "recharts"
const data = [
{ browser: "Chrome", visitors: 275, fill: "var(--color-chrome)" },
{ browser: "Safari", visitors: 200, fill: "var(--color-safari)" },
{ browser: "Firefox", visitors: 187, fill: "var(--color-firefox)" },
]
const config = {
chrome: { label: "Chrome", color: "hsl(var(--chart-1))" },
safari: { label: "Safari", color: "hsl(var(--chart-2))" },
firefox: { label: "Firefox", color: "hsl(var(--chart-3))" },
}
export function PieChartDemo() {
return (
<ChartContainer config={config}>
<PieChart>
<ChartTooltip content={<ChartTooltipContent />} />
<Pie data={data} dataKey="visitors" nameKey="browser" />
</PieChart>
</ChartContainer>
)
}
```
## Variants
### Donut Chart
Use `innerRadius` and `outerRadius` to create donut charts.
### With Labels
Add labels inside or outside slices.
### Interactive
Highlight slices on hover with `activeIndex`.
-53
View File
@@ -1,53 +0,0 @@
---
title: Radar Chart
description: Radar charts for multivariate data comparison and analysis.
---
## Overview
Radar charts display multivariate data on axes starting from the same point, useful for comparing multiple quantitative variables.
## Usage
```tsx
import { ChartContainer, ChartTooltip, ChartTooltipContent } from "@hanzo/ui"
import { PolarAngleAxis, PolarGrid, Radar, RadarChart } from "recharts"
const data = [
{ subject: "Math", A: 120, B: 110 },
{ subject: "Chinese", A: 98, B: 130 },
{ subject: "English", A: 86, B: 130 },
{ subject: "Geography", A: 99, B: 100 },
{ subject: "Physics", A: 85, B: 90 },
{ subject: "History", A: 65, B: 85 },
]
const config = {
A: { label: "Student A", color: "hsl(var(--chart-1))" },
B: { label: "Student B", color: "hsl(var(--chart-2))" },
}
export function RadarChartDemo() {
return (
<ChartContainer config={config}>
<RadarChart data={data}>
<PolarGrid />
<PolarAngleAxis dataKey="subject" />
<ChartTooltip content={<ChartTooltipContent />} />
<Radar dataKey="A" fill="var(--color-A)" fillOpacity={0.6} />
<Radar dataKey="B" fill="var(--color-B)" fillOpacity={0.6} />
</RadarChart>
</ChartContainer>
)
}
```
## Variants
### Filled Radar
Use `fillOpacity` to create filled radar areas.
### Multiple Series
Compare multiple datasets on the same radar.
-52
View File
@@ -1,52 +0,0 @@
---
title: Radial Chart
description: Radial bar charts for circular data visualization and progress indicators.
---
## Overview
Radial charts display data in a circular layout, useful for progress indicators, gauges, and circular comparisons.
## Usage
```tsx
import { ChartContainer, ChartTooltip, ChartTooltipContent } from "@hanzo/ui"
import { RadialBar, RadialBarChart } from "recharts"
const data = [
{ name: "Chrome", visitors: 275, fill: "var(--color-chrome)" },
{ name: "Safari", visitors: 200, fill: "var(--color-safari)" },
{ name: "Firefox", visitors: 187, fill: "var(--color-firefox)" },
]
const config = {
chrome: { label: "Chrome", color: "hsl(var(--chart-1))" },
safari: { label: "Safari", color: "hsl(var(--chart-2))" },
firefox: { label: "Firefox", color: "hsl(var(--chart-3))" },
}
export function RadialChartDemo() {
return (
<ChartContainer config={config}>
<RadialBarChart data={data} innerRadius={30} outerRadius={110}>
<ChartTooltip content={<ChartTooltipContent />} />
<RadialBar dataKey="visitors" />
</RadialBarChart>
</ChartContainer>
)
}
```
## Variants
### Stacked Radial
Stack multiple radial bars concentrically.
### With Labels
Add labels to radial segments for clarity.
### Progress Gauge
Use a single radial bar as a progress or gauge indicator.
-61
View File
@@ -1,61 +0,0 @@
---
title: Chart Tooltip
description: Customizable tooltip component for all chart types.
---
## Overview
The chart tooltip component provides a consistent, themed tooltip across all chart types. It integrates with the chart config system for automatic label and color resolution.
## Usage
```tsx
import { ChartTooltip, ChartTooltipContent } from "@hanzo/ui"
// Inside any chart component:
;<ChartTooltip content={<ChartTooltipContent />} />
```
## Props
### ChartTooltipContent
| Prop | Type | Default | Description |
| ------------- | --------------------------- | ------- | ------------------------- |
| hideLabel | boolean | false | Hide the label in tooltip |
| hideIndicator | boolean | false | Hide the color indicator |
| indicator | "line" \| "dot" \| "dashed" | "dot" | Indicator style |
| nameKey | string | - | Key for item names |
| labelKey | string | - | Key for labels |
## Customization
### Custom Formatter
```tsx
<ChartTooltip
content={
<ChartTooltipContent
formatter={(value, name) => (
<span>
{name}: ${value.toLocaleString()}
</span>
)}
/>
}
/>
```
### Custom Label
```tsx
<ChartTooltip
content={<ChartTooltipContent labelFormatter={(label) => `Date: ${label}`} />}
/>
```
## Indicator Styles
- **dot** - Small colored circle (default)
- **line** - Colored line indicator
- **dashed** - Dashed line indicator
+81 -92
View File
@@ -63,28 +63,18 @@ function Desktop() {
return (
<div>
<button onClick={() => windows.openWindow("Settings")}>
Open Settings
</button>
<button onClick={() => windows.toggleWindow("Terminal")}>
Toggle Terminal
</button>
<button onClick={() => windows.openWindow('Settings')}>Open Settings</button>
<button onClick={() => windows.toggleWindow('Terminal')}>Toggle Terminal</button>
<button onClick={() => windows.closeAllWindows()}>Close All</button>
{windows.isOpen("Settings") && (
<Window
title="Settings"
onClose={() => windows.closeWindow("Settings")}
>
{windows.isOpen('Settings') && (
<Window title="Settings" onClose={() => windows.closeWindow('Settings')}>
...
</Window>
)}
{windows.isOpen("Terminal") && (
<Window
title="Terminal"
onClose={() => windows.closeWindow("Terminal")}
>
{windows.isOpen('Terminal') && (
<Window title="Terminal" onClose={() => windows.closeWindow('Terminal')}>
...
</Window>
)}
@@ -95,17 +85,17 @@ function Desktop() {
#### API
| Method | Type | Description |
| ----------------- | ------------------------- | ---------------------------- |
| `isOpen` | `(id: string) => boolean` | Check if a window is open |
| `openWindow` | `(id: string) => void` | Open a window |
| `closeWindow` | `(id: string) => void` | Close a window |
| `toggleWindow` | `(id: string) => void` | Toggle a window's open state |
| `closeAllWindows` | `() => void` | Close all windows |
| `focusWindow` | `(id: string) => void` | Focus/activate a window |
| `activeWindow` | `string \| null` | Currently active window |
| `openWindows` | `string[]` | List of all open window IDs |
| `windows` | `Record<string, boolean>` | Window state map |
| Method | Type | Description |
|--------|------|-------------|
| `isOpen` | `(id: string) => boolean` | Check if a window is open |
| `openWindow` | `(id: string) => void` | Open a window |
| `closeWindow` | `(id: string) => void` | Close a window |
| `toggleWindow` | `(id: string) => void` | Toggle a window's open state |
| `closeAllWindows` | `() => void` | Close all windows |
| `focusWindow` | `(id: string) => void` | Focus/activate a window |
| `activeWindow` | `string \| null` | Currently active window |
| `openWindows` | `string[]` | List of all open window IDs |
| `windows` | `Record<string, boolean>` | Window state map |
---
@@ -160,23 +150,23 @@ function SettingsPanel() {
#### API
| Property | Type | Description |
| ----------------------- | ------------------------------- | -------------------------- |
| `theme` | `'light' \| 'dark' \| 'system'` | Current theme |
| `setTheme` | `(theme) => void` | Set theme |
| `colorScheme` | `string` | Color scheme name |
| `setColorScheme` | `(scheme) => void` | Set color scheme |
| `showDock` | `boolean` | Whether dock is visible |
| `setShowDock` | `(show) => void` | Toggle dock visibility |
| `dockPosition` | `'bottom' \| 'left' \| 'right'` | Dock position |
| `setDockPosition` | `(position) => void` | Set dock position |
| `dockMagnification` | `boolean` | Dock magnification enabled |
| `setDockMagnification` | `(enabled) => void` | Toggle magnification |
| `fontSize` | `number` | Base font size |
| `setFontSize` | `(size) => void` | Set font size |
| `windowTransparency` | `number` | Window transparency (0-1) |
| `setWindowTransparency` | `(opacity) => void` | Set transparency |
| `resetToDefaults` | `() => void` | Reset all settings |
| Property | Type | Description |
|----------|------|-------------|
| `theme` | `'light' \| 'dark' \| 'system'` | Current theme |
| `setTheme` | `(theme) => void` | Set theme |
| `colorScheme` | `string` | Color scheme name |
| `setColorScheme` | `(scheme) => void` | Set color scheme |
| `showDock` | `boolean` | Whether dock is visible |
| `setShowDock` | `(show) => void` | Toggle dock visibility |
| `dockPosition` | `'bottom' \| 'left' \| 'right'` | Dock position |
| `setDockPosition` | `(position) => void` | Set dock position |
| `dockMagnification` | `boolean` | Dock magnification enabled |
| `setDockMagnification` | `(enabled) => void` | Toggle magnification |
| `fontSize` | `number` | Base font size |
| `setFontSize` | `(size) => void` | Set font size |
| `windowTransparency` | `number` | Window transparency (0-1) |
| `setWindowTransparency` | `(opacity) => void` | Set transparency |
| `resetToDefaults` | `() => void` | Reset all settings |
---
@@ -192,18 +182,20 @@ function Desktop() {
return (
<div>
<button onClick={() => overlays.open("spotlight")}>
<button onClick={() => overlays.open('spotlight')}>
Open Spotlight (⌘+Space)
</button>
<button onClick={() => overlays.open("about")}>About This Mac</button>
<button onClick={() => overlays.open('about')}>
About This Mac
</button>
{overlays.isOpen("spotlight") && (
<Spotlight onClose={() => overlays.close("spotlight")} />
{overlays.isOpen('spotlight') && (
<Spotlight onClose={() => overlays.close('spotlight')} />
)}
{overlays.isOpen("about") && (
<AboutDialog onClose={() => overlays.close("about")} />
{overlays.isOpen('about') && (
<AboutDialog onClose={() => overlays.close('about')} />
)}
</div>
)
@@ -212,14 +204,14 @@ function Desktop() {
#### API
| Property | Type | Description |
| ---------- | ------------------------- | --------------------------- |
| `overlays` | `OverlayState` | Current overlay states |
| `isOpen` | `(id: string) => boolean` | Check if an overlay is open |
| `open` | `(id: string) => void` | Open an overlay by id |
| `close` | `(id: string) => void` | Close an overlay by id |
| `toggle` | `(id: string) => void` | Toggle an overlay |
| `closeAll` | `() => void` | Close all overlays |
| Property | Type | Description |
|----------|------|-------------|
| `overlays` | `OverlayState` | Current overlay states |
| `isOpen` | `(id: string) => boolean` | Check if an overlay is open |
| `open` | `(id: string) => void` | Open an overlay by id |
| `close` | `(id: string) => void` | Close an overlay by id |
| `toggle` | `(id: string) => void` | Toggle an overlay |
| `closeAll` | `() => void` | Close all overlays |
Built-in overlay IDs: `spotlight`, `contextMenu`, `modal`, `drawer`
@@ -267,29 +259,29 @@ function Desktop() {
#### Shortcut Definition
| Property | Type | Description |
| -------- | ------------ | -------------------------------- |
| `key` | `string` | Key to listen for |
| `meta` | `boolean` | Require ⌘ (Mac) / Ctrl (Windows) |
| `alt` | `boolean` | Require Alt/Option |
| `shift` | `boolean` | Require Shift |
| `ctrl` | `boolean` | Require Control |
| `action` | `() => void` | Callback when triggered |
| Property | Type | Description |
|----------|------|-------------|
| `key` | `string` | Key to listen for |
| `meta` | `boolean` | Require ⌘ (Mac) / Ctrl (Windows) |
| `alt` | `boolean` | Require Alt/Option |
| `shift` | `boolean` | Require Shift |
| `ctrl` | `boolean` | Require Control |
| `action` | `() => void` | Callback when triggered |
## Complete Example
```tsx
import {
Spotlight,
useDesktopSettings,
useKeyboardShortcuts,
useOverlayManager,
useWindowManager,
Window,
Spotlight,
useWindowManager,
useDesktopSettings,
useOverlayManager,
useKeyboardShortcuts
} from "@hanzo/ui/desktop"
import { Dock, DockItem } from "@hanzo/ui/dock"
const apps = ["Finder", "Terminal", "Safari", "Mail", "Calendar", "Settings"]
const apps = ['Finder', 'Terminal', 'Safari', 'Mail', 'Calendar', 'Settings']
export function Desktop() {
const windows = useWindowManager()
@@ -298,9 +290,9 @@ export function Desktop() {
// Register keyboard shortcuts
useKeyboardShortcuts([
{ key: " ", meta: true, action: overlays.openSpotlight },
{ key: "q", meta: true, action: () => windows.close(windows.activeWindow) },
{ key: ",", meta: true, action: () => windows.open("Settings") },
{ key: ' ', meta: true, action: overlays.openSpotlight },
{ key: 'q', meta: true, action: () => windows.close(windows.activeWindow) },
{ key: ',', meta: true, action: () => windows.open('Settings') },
])
return (
@@ -308,36 +300,33 @@ export function Desktop() {
className="h-screen w-screen relative"
style={{
opacity: settings.windowTransparency,
fontSize: settings.fontSize,
fontSize: settings.fontSize
}}
>
{/* Desktop Background */}
<div className="absolute inset-0 bg-gradient-to-br from-blue-500 to-purple-600" />
{/* Windows */}
{apps.map(
(app) =>
windows.isOpen(app) && (
<Window
key={app}
title={app}
onClose={() => windows.close(app)}
windowType={settings.theme === "dark" ? "dark" : "default"}
>
<div className="p-4">{app} content</div>
</Window>
)
)}
{apps.map(app => windows.isOpen(app) && (
<Window
key={app}
title={app}
onClose={() => windows.close(app)}
windowType={settings.theme === 'dark' ? 'dark' : 'default'}
>
<div className="p-4">{app} content</div>
</Window>
))}
{/* Spotlight */}
{overlays.spotlight && (
<Spotlight
isOpen={true}
onClose={overlays.closeSpotlight}
items={apps.map((app) => ({
items={apps.map(app => ({
id: app.toLowerCase(),
label: app,
category: "Applications",
category: 'Applications'
}))}
onSelect={(item) => {
windows.open(item.label)
@@ -352,7 +341,7 @@ export function Desktop() {
position={settings.dockPosition}
magnification={settings.dockMagnification ? 60 : 0}
>
{apps.map((app) => (
{apps.map(app => (
<DockItem
key={app}
tooltip={app}
+54 -137
View File
@@ -57,19 +57,9 @@ npm install framer-motion lucide-react
import { Spotlight, SpotlightItem } from "@hanzo/ui/desktop"
const items: SpotlightItem[] = [
{
id: "settings",
title: "Settings",
category: "Applications",
icon: <Settings />,
},
{
id: "documents",
title: "Documents",
category: "Folders",
icon: <Folder />,
},
{ id: "music", title: "Music", category: "Applications", icon: <Music /> },
{ id: 'settings', title: 'Settings', category: 'Applications', icon: <Settings /> },
{ id: 'documents', title: 'Documents', category: 'Folders', icon: <Folder /> },
{ id: 'music', title: 'Music', category: 'Applications', icon: <Music /> },
]
export function SpotlightDemo() {
@@ -84,7 +74,7 @@ export function SpotlightDemo() {
onClose={() => setIsOpen(false)}
items={items}
onSelect={(item) => {
console.log("Selected:", item)
console.log('Selected:', item)
setIsOpen(false)
}}
/>
@@ -97,25 +87,25 @@ export function SpotlightDemo() {
### Spotlight
| Prop | Type | Default | Description |
| ------------- | ------------------------------- | ------------- | ------------------------------------------- |
| `isOpen` | `boolean` | - | Controls visibility of the spotlight dialog |
| `onClose` | `() => void` | - | Callback when spotlight is closed |
| `items` | `SpotlightItem[]` | - | Array of searchable items |
| `onSelect` | `(item: SpotlightItem) => void` | - | Callback when an item is selected |
| `placeholder` | `string` | `'Search...'` | Search input placeholder text |
| Prop | Type | Default | Description |
|------|------|---------|-------------|
| `isOpen` | `boolean` | - | Controls visibility of the spotlight dialog |
| `onClose` | `() => void` | - | Callback when spotlight is closed |
| `items` | `SpotlightItem[]` | - | Array of searchable items |
| `onSelect` | `(item: SpotlightItem) => void` | - | Callback when an item is selected |
| `placeholder` | `string` | `'Search...'` | Search input placeholder text |
### SpotlightItem
| Property | Type | Description |
| ---------- | ------------ | ---------------------------------- |
| `id` | `string` | Unique identifier for the item |
| `title` | `string` | Display title |
| `subtitle` | `string` | Optional subtitle/description text |
| `icon` | `ReactNode` | Optional icon to display |
| `category` | `string` | Category for grouping |
| `keywords` | `string[]` | Optional search keywords |
| `action` | `() => void` | Optional action callback |
| Property | Type | Description |
|----------|------|-------------|
| `id` | `string` | Unique identifier for the item |
| `title` | `string` | Display title |
| `subtitle` | `string` | Optional subtitle/description text |
| `icon` | `ReactNode` | Optional icon to display |
| `category` | `string` | Category for grouping |
| `keywords` | `string[]` | Optional search keywords |
| `action` | `() => void` | Optional action callback |
## Features
@@ -130,70 +120,26 @@ export function SpotlightDemo() {
### Application Launcher
```tsx
import { Spotlight, SpotlightItem, useKeyboardShortcuts } from "@hanzo/ui/desktop"
import {
Spotlight,
SpotlightItem,
useKeyboardShortcuts,
} from "@hanzo/ui/desktop"
import {
Calendar,
Terminal,
Chrome,
Folder,
Mail,
Calendar,
Music,
Settings,
Terminal,
Folder
} from "lucide-react"
const apps: SpotlightItem[] = [
{
id: "terminal",
label: "Terminal",
category: "Applications",
icon: <Terminal className="h-5 w-5" />,
},
{
id: "safari",
label: "Safari",
category: "Applications",
icon: <Chrome className="h-5 w-5" />,
},
{
id: "mail",
label: "Mail",
category: "Applications",
icon: <Mail className="h-5 w-5" />,
},
{
id: "calendar",
label: "Calendar",
category: "Applications",
icon: <Calendar className="h-5 w-5" />,
},
{
id: "music",
label: "Music",
category: "Applications",
icon: <Music className="h-5 w-5" />,
},
{
id: "settings",
label: "System Preferences",
category: "Applications",
icon: <Settings className="h-5 w-5" />,
},
{
id: "documents",
label: "Documents",
category: "Folders",
icon: <Folder className="h-5 w-5" />,
},
{
id: "downloads",
label: "Downloads",
category: "Folders",
icon: <Folder className="h-5 w-5" />,
},
{ id: 'terminal', label: 'Terminal', category: 'Applications', icon: <Terminal className="h-5 w-5" /> },
{ id: 'safari', label: 'Safari', category: 'Applications', icon: <Chrome className="h-5 w-5" /> },
{ id: 'mail', label: 'Mail', category: 'Applications', icon: <Mail className="h-5 w-5" /> },
{ id: 'calendar', label: 'Calendar', category: 'Applications', icon: <Calendar className="h-5 w-5" /> },
{ id: 'music', label: 'Music', category: 'Applications', icon: <Music className="h-5 w-5" /> },
{ id: 'settings', label: 'System Preferences', category: 'Applications', icon: <Settings className="h-5 w-5" /> },
{ id: 'documents', label: 'Documents', category: 'Folders', icon: <Folder className="h-5 w-5" /> },
{ id: 'downloads', label: 'Downloads', category: 'Folders', icon: <Folder className="h-5 w-5" /> },
]
export function AppLauncher() {
@@ -201,7 +147,7 @@ export function AppLauncher() {
// ⌘+Space to open (like macOS)
useKeyboardShortcuts([
{ key: " ", meta: true, action: () => setIsOpen(true) },
{ key: ' ', meta: true, action: () => setIsOpen(true) }
])
return (
@@ -211,7 +157,7 @@ export function AppLauncher() {
items={apps}
placeholder="Search applications..."
onSelect={(item) => {
console.log("Launch:", item.label)
console.log('Launch:', item.label)
setIsOpen(false)
}}
/>
@@ -223,51 +169,22 @@ export function AppLauncher() {
```tsx
import { Spotlight, SpotlightItem } from "@hanzo/ui/desktop"
import { Clipboard, Copy, Redo, Save, Scissors, Undo } from "lucide-react"
import {
Save,
Copy,
Scissors,
Clipboard,
Undo,
Redo
} from "lucide-react"
const commands: SpotlightItem[] = [
{
id: "save",
label: "Save",
category: "File",
icon: <Save />,
shortcut: "⌘S",
},
{
id: "copy",
label: "Copy",
category: "Edit",
icon: <Copy />,
shortcut: "⌘C",
},
{
id: "cut",
label: "Cut",
category: "Edit",
icon: <Scissors />,
shortcut: "⌘X",
},
{
id: "paste",
label: "Paste",
category: "Edit",
icon: <Clipboard />,
shortcut: "⌘V",
},
{
id: "undo",
label: "Undo",
category: "Edit",
icon: <Undo />,
shortcut: "⌘Z",
},
{
id: "redo",
label: "Redo",
category: "Edit",
icon: <Redo />,
shortcut: "⌘⇧Z",
},
{ id: 'save', label: 'Save', category: 'File', icon: <Save />, shortcut: '⌘S' },
{ id: 'copy', label: 'Copy', category: 'Edit', icon: <Copy />, shortcut: '⌘C' },
{ id: 'cut', label: 'Cut', category: 'Edit', icon: <Scissors />, shortcut: '⌘X' },
{ id: 'paste', label: 'Paste', category: 'Edit', icon: <Clipboard />, shortcut: '⌘V' },
{ id: 'undo', label: 'Undo', category: 'Edit', icon: <Undo />, shortcut: '⌘Z' },
{ id: 'redo', label: 'Redo', category: 'Edit', icon: <Redo />, shortcut: '⌘⇧Z' },
]
export function CommandPalette() {
@@ -280,7 +197,7 @@ export function CommandPalette() {
items={commands}
placeholder="Type a command..."
onSelect={(item) => {
console.log("Execute:", item.id)
console.log('Execute:', item.id)
setIsOpen(false)
}}
/>
@@ -290,9 +207,9 @@ export function CommandPalette() {
## Keyboard Shortcuts
| Shortcut | Action |
| --------------- | -------------------------------- |
| `↑` / `↓` | Navigate between items |
| `Enter` | Select highlighted item |
| `Escape` | Close spotlight |
| Shortcut | Action |
|----------|--------|
| `↑` / `↓` | Navigate between items |
| `Enter` | Select highlighted item |
| `Escape` | Close spotlight |
| `⌘K` / `⌘Space` | Open spotlight (when configured) |
+19 -19
View File
@@ -75,17 +75,17 @@ export function WindowDemo() {
## Props
| Prop | Type | Default | Description |
| ----------------- | ------------------------------------------------- | ----------------------------- | ----------------------------------------- |
| `title` | `string` | - | Window title displayed in the title bar |
| `onClose` | `() => void` | - | Callback when the close button is clicked |
| `initialPosition` | `{ x: number, y: number }` | `{ x: 100, y: 100 }` | Initial window position |
| `initialSize` | `{ width: number, height: number }` | `{ width: 800, height: 600 }` | Initial window dimensions |
| `minWidth` | `number` | `200` | Minimum window width |
| `minHeight` | `number` | `150` | Minimum window height |
| `windowType` | `'default' \| 'dark' \| 'light' \| 'transparent'` | `'default'` | Window style variant |
| `className` | `string` | - | Additional CSS classes for the window |
| `children` | `ReactNode` | - | Window content |
| Prop | Type | Default | Description |
|------|------|---------|-------------|
| `title` | `string` | - | Window title displayed in the title bar |
| `onClose` | `() => void` | - | Callback when the close button is clicked |
| `initialPosition` | `{ x: number, y: number }` | `{ x: 100, y: 100 }` | Initial window position |
| `initialSize` | `{ width: number, height: number }` | `{ width: 800, height: 600 }` | Initial window dimensions |
| `minWidth` | `number` | `200` | Minimum window width |
| `minHeight` | `number` | `150` | Minimum window height |
| `windowType` | `'default' \| 'dark' \| 'light' \| 'transparent'` | `'default'` | Window style variant |
| `className` | `string` | - | Additional CSS classes for the window |
| `children` | `ReactNode` | - | Window content |
## Variants
@@ -128,7 +128,7 @@ export function WindowDemo() {
```tsx
import { Window } from "@hanzo/ui/desktop"
import { Bell, Settings, User } from "lucide-react"
import { Settings, User, Bell } from "lucide-react"
export function SettingsWindow() {
const [isOpen, setIsOpen] = useState(true)
@@ -164,35 +164,35 @@ export function SettingsWindow() {
### Multiple Windows
```tsx
import { useWindowManager, Window } from "@hanzo/ui/desktop"
import { Window, useWindowManager } from "@hanzo/ui/desktop"
export function MultiWindowDemo() {
const windows = useWindowManager()
return (
<div className="relative h-screen">
{windows.isOpen("Settings") && (
{windows.isOpen('Settings') && (
<Window
title="Settings"
onClose={() => windows.close("Settings")}
onClose={() => windows.close('Settings')}
initialPosition={{ x: 100, y: 100 }}
>
<div className="p-4">Settings content</div>
</Window>
)}
{windows.isOpen("Editor") && (
{windows.isOpen('Editor') && (
<Window
title="Editor"
onClose={() => windows.close("Editor")}
onClose={() => windows.close('Editor')}
initialPosition={{ x: 200, y: 150 }}
>
<div className="p-4">Editor content</div>
</Window>
)}
<button onClick={() => windows.open("Settings")}>Open Settings</button>
<button onClick={() => windows.open("Editor")}>Open Editor</button>
<button onClick={() => windows.open('Settings')}>Open Settings</button>
<button onClick={() => windows.open('Editor')}>Open Editor</button>
</div>
)
}
+25 -23
View File
@@ -8,19 +8,19 @@ The Desktop namespace provides components and hooks for building macOS-style des
## Components
| Component | Description |
| ----------------------------------------------- | ----------------------------------------------------------------------- |
| [Window](/docs/components/desktop-window) | Draggable, resizable window with minimize, maximize, and close controls |
| [Spotlight](/docs/components/desktop-spotlight) | macOS Spotlight-style search and command palette |
| Component | Description |
|-----------|-------------|
| [Window](/docs/components/desktop-window) | Draggable, resizable window with minimize, maximize, and close controls |
| [Spotlight](/docs/components/desktop-spotlight) | macOS Spotlight-style search and command palette |
## Hooks
| Hook | Description |
| ---------------------- | ----------------------------------------------------- |
| `useWindowManager` | Manage multiple windows with open/close/toggle state |
| `useDesktopSettings` | Persist desktop settings like theme, dock position |
| `useOverlayManager` | Manage overlay states (spotlight, about dialog, etc.) |
| `useKeyboardShortcuts` | Register keyboard shortcuts (⌘+Space, ⌘+Q, etc.) |
| Hook | Description |
|------|-------------|
| `useWindowManager` | Manage multiple windows with open/close/toggle state |
| `useDesktopSettings` | Persist desktop settings like theme, dock position |
| `useOverlayManager` | Manage overlay states (spotlight, about dialog, etc.) |
| `useKeyboardShortcuts` | Register keyboard shortcuts (⌘+Space, ⌘+Q, etc.) |
See [Desktop Hooks](/docs/components/desktop-hooks) for detailed hook documentation.
@@ -51,12 +51,12 @@ Then import from the desktop namespace:
```tsx
import {
Spotlight,
useDesktopSettings,
useKeyboardShortcuts,
useOverlayManager,
useWindowManager,
Window,
Spotlight,
useWindowManager,
useDesktopSettings,
useOverlayManager,
useKeyboardShortcuts
} from "@hanzo/ui/desktop"
```
@@ -68,10 +68,10 @@ import {
```tsx
import {
Spotlight,
useKeyboardShortcuts,
useWindowManager,
Window,
Spotlight,
useWindowManager,
useKeyboardShortcuts
} from "@hanzo/ui/desktop"
import { Dock, DockItem } from "@hanzo/ui/dock"
@@ -80,16 +80,16 @@ export function MyDesktop() {
const [showSpotlight, setShowSpotlight] = useState(false)
useKeyboardShortcuts([
{ key: " ", meta: true, action: () => setShowSpotlight(true) },
{ key: ' ', meta: true, action: () => setShowSpotlight(true) },
])
return (
<div className="h-screen relative">
{/* Windows */}
{windows.isOpen("Settings") && (
{windows.isOpen('Settings') && (
<Window
title="Settings"
onClose={() => windows.closeWindow("Settings")}
onClose={() => windows.closeWindow('Settings')}
>
<div className="p-4">Settings content</div>
</Window>
@@ -99,7 +99,9 @@ export function MyDesktop() {
<Spotlight
isOpen={showSpotlight}
onClose={() => setShowSpotlight(false)}
items={[{ id: "settings", title: "Settings", category: "Apps" }]}
items={[
{ id: 'settings', title: 'Settings', category: 'Apps' },
]}
onSelect={(item) => {
windows.openWindow(item.title)
setShowSpotlight(false)
@@ -110,7 +112,7 @@ export function MyDesktop() {
<Dock position="bottom">
<DockItem
tooltip="Settings"
onClick={() => windows.toggleWindow("Settings")}
onClick={() => windows.toggleWindow('Settings')}
/>
</Dock>
</div>
-45
View File
@@ -1,45 +0,0 @@
---
title: Direction
description: Provider and hook for RTL/LTR text direction support.
---
## Overview
The Direction component provides RTL (right-to-left) and LTR (left-to-right) text direction support through a React context provider and hook. Useful for internationalization and bidirectional text layouts.
## Usage
```tsx
import { DirectionProvider, useDirection } from "@hanzo/ui"
export function App() {
return (
<DirectionProvider direction="rtl">
<MyComponent />
</DirectionProvider>
)
}
function MyComponent() {
const direction = useDirection()
return <div>Current direction: {direction}</div>
}
```
## Props
### DirectionProvider
| Prop | Type | Default | Description |
| --------- | -------------- | ------- | --------------- |
| dir | "ltr" \| "rtl" | - | Text direction |
| direction | "ltr" \| "rtl" | - | Alias for `dir` |
| children | ReactNode | - | Child elements |
### useDirection
Returns the current direction from the nearest `DirectionProvider`.
```tsx
const direction = useDirection() // "ltr" | "rtl"
```

Some files were not shown because too many files have changed in this diff Show More