# CE UI Web Components

Reusable Web Components that wrap CE UI behaviors and styling tokens. This package exposes framework-neutral UI pieces built on top of the `@clusterenvision/ui-framework` runtime and `@clusterenvision/ui-scss` design system. Use it to drop matching UI primitives into vanilla apps, micro frontends, or to demo CE UI design tokens outside of React/Vue/Angular wrappers.

> New starter: `projects/products/ce-lms` shows a realistic login/register flow that already wires `ce-ui-scss` and registers CE web components via Vite. Run `npm install && npm run dev` inside `projects/products/ce-lms` to see the LMS-ready auth shell without extra plumbing.

## What lives here?

- **Core components (source of truth)** – `components/` contains the real implementations (Button, ListView, Splitter, ContextMenu, etc.). Edit components here first.
- **Thin entry shims** – `src/` exists only to wire exports/build and re-export from `components/web-components/`. Avoid adding component logic under `src/`.
- **Stories** – `stories/` + `.storybook/` configure Storybook for local development, stacking CE tokens with visual scaffolding.
- **Runtime helpers** – `core/` and `packages/` contain builders for custom elements, theming, and base behaviors that other packages reuse.
- **Design assets** – SCSS skins (`components/*/_*.scss`), demo assets, and docs for contributors.

## Prerequisites

- Node.js 20+
- PNPM 9+

Install once in the monorepo root or within this package:

```sh
pnpm install
```

## Available scripts

Run from `projects/libraries/ui/ce-ui-webcomponents`:

| Script | Purpose |
| --- | --- |
| `pnpm exec storybook build` | build |
| `pnpm storybook` | Start Storybook in dev mode (port 6006). Hot reload for components + stories. |
| `pnpm build-storybook` | Generate static Storybook build into `storybook-static/` for previews or deployment. |
| `pnpm build` | Type-check + emit TypeScript dist output (ES modules) into `dist/`. |
| `pnpm test` | Execute unit tests via Vitest (headless). |
| `pnpm lint` | Run lint rules (if configured). From monorepo root use `pnpm lint --filter ce-ui-webcomponents...`. |
| `pnpm vitest run tests/ComboBox.test.ts tests/MultiSelect.test.ts tests/Dialog.test.ts tests/Dropdown.test.ts tests/TabLayout.test.ts tests/Pagination.test.ts tests/SmartEditor.test.ts tests/RatingElement.test.ts tests/SwitchElement.test.ts tests/ContextMenu.test.ts tests/GridElement.test.ts tests/PivotGridElement.test.ts tests/UploadElement.test.ts` | vite test |
| `pnpm run test:a11y:axe`| ally test |
| `pnpm vitest run` | vitest test |
| `RUN_AXE=1 pnpm vitest run tests/TabLayout.a11y.test.ts.` | axe test |

## Local development

1. Install deps: `pnpm install` (monorepo root or package dir).
2. Start Storybook: `pnpm storybook`
3. Navigate to `http://localhost:6006` to interact with components.

Storybook pulls CE UI tokens, SCSS, and helper layouts to mirror production styling. When running from the monorepo root, prefix with filter: `pnpm --filter @clusterenvision/ui-webcomponents storybook`.

## Newly added components

- **`<ce-switch>`** – Drop-in toggle that mirrors CE spacing tokens, supports helper copy (`hint`, `onLabel`, `offLabel`), and emits `change` events with `{ checked, value }`. Preview it under **Components → Switch** in Storybook to see playground, docs, and theming examples.
- **`<ce-rating>`** – Accessible radiogroup for 1–10 point sentiment capture with custom icons, roving focus, and optional numeric helper text. Explore **Components → Rating** to try different icon sets, densities, and reset behavior.
- **`<ce-upload>`** – Drag-and-drop uploader with queue management, manual/auto start, retry/remove hooks, and progress indicators wired to CE feedback tokens. Open **Components → Upload** in Storybook to try the demo transport adapter and dark-surface styling.
- **`<ce-grid>`** – Data grid custom element with built-in search, sorting, pagination, and density/theme modifiers. Emits deterministic `change` events for host-driven pagination or row selection and ships with Storybook playgrounds.
- **`<ce-pivot-grid>`** – Pivot table element that aggregates data across row/column dimensions, supports totals + search, and broadcasts both `change` and `aggregate` events so hosts can react to derived metrics.
- **`<ce-chart>`** – Lightweight chart primitives (bar, line, area, pie, doughnut) with configurable tooltips, legends, and per-series summaries so you can present small datasets without external charting dependencies.
- **`<ce-editor>` / `<ce-rich-text-editor>` / `<ce-smart-editor>` / `<ce-speech-to-text>`** – Editor family for rich text, chat-style input, and speech capture, with event bridges for change/send/recording updates and sensible SSR placeholders.
- **`<ce-backlog-board>`** – Drag-enabled backlog columns with inline edit hooks, add-column/add-item callbacks, and move/select events for host-driven persistence.
- **`<ce-diagram>`** – Node/link canvas with pan/zoom, toolbox drops, connection mode, inline label editing, and export helpers; emits node and link select events.
- **Icons (Nucleo-ready)** – Point all `<ce-icon>` usages to a shared sprite (e.g., `/assets/icons/latest/nucleo.svg`) with `setIconSpriteUrl()` or per-instance `sprite-url`; fallback `assetBase` can be set globally via `setIconAssetBase()` for `img`-based loading.

Both controls register automatically when you import `@clusterenvision/ui-webcomponents` (or simply load Storybook). Use the global theme toolbar to validate light/dark tokens.

## Icon usage

- Prefer a shared sprite to keep bundles lean. Set it once at app bootstrap and every `<ce-icon>` will render `<svg><use>` references.

```ts
import { setIconAssetBase, setIconSpriteUrl } from '@clusterenvision/ui-webcomponents';

// Point to your hosted Nucleo sprite (e.g., static assets, CDN, or env-specific path)
setIconSpriteUrl('/assets/icons/latest/nucleo.svg');

// Optional: base path for <img> fallback when an inline icon is missing
setIconAssetBase('/assets/icons/latest/nucleo/outline');
```

- Per-icon overrides are supported when you need a different sprite URL:

```html
<ce-icon name="bell" sprite-url="/cdn/icons/nucleo.svg" size="18"></ce-icon>
```

- Render order: sprite `<use>` when `sprite-url` is set (globally or per element) → inline SVG from `@clusterenvision/ui-kit` → `<img>` using `asset-base` (or global `setIconAssetBase`).

## Production builds

- **Package build**: `pnpm build` compiles to `dist/` for publishing or consumption by other packages.
- **Storybook static site**: `pnpm build-storybook` bundles stories into `storybook-static/` which you can host on static hosting (Netlify, Vercel, S3, etc.).

## Testing

- `pnpm test` runs Vitest suites in `tests/`.
- Add `--runInBand` or `--coverage` flags as needed: `pnpm test -- --coverage`.

## Deployment

### Storybook hosting

1. Build: `pnpm build-storybook`
2. Upload `storybook-static/` to your hosting target (e.g., `aws s3 sync storybook-static s3://my-bucket` or `vercel deploy --prebuilt`).

### NPM package release

1. Build the library: `pnpm build`
2. Bump version + publish to private registry or npm: `pnpm publish --access public` (or configure `.npmrc` for private scope).

## Troubleshooting

- Missing styles? Ensure `.storybook/preview.ts` imports `ce-scss-vitepress/dist/ce-ui.css` and `stories/story-layout.css`.
- Stale dist? Clean `dist/` and rerun `pnpm build`.
- Node modules accidentally committed? `.gitignore` ignores `node_modules/` and build outputs.
- Hydration/SSR issues? See `projects/libraries/ui/ce-ui-webcomponents/docs/HYDRATION.md`.

## Contribution workflow

1. Create a branch from the monorepo root.
2. Update component source/tests.
3. Run `pnpm lint` (if available), `pnpm test`, and `pnpm build-storybook` to verify.
4. Submit PR referencing component/story updates.

## Future Plan

Focus areas for upcoming releases:

- **Form**: Compose CE input primitives into a validated form shell (field groups, error summaries, async submission hooks) that mirrors the framework examples.
- **Gauge**: Port the CE gauge visualization with theme-aware gradients, thresholds, and animation controls so dashboards can reuse it outside React.
- **Kanban**: Deliver a drag-enabled board component with swimlanes, card templates, and keyboard support, integrating with existing ListView tokens.
- **Map**: Wrap popular mapping providers (Leaflet/Mapbox) with CE UI overlays for markers, tooltips, and drawing tools.
- **PDF Viewer**: Embed PDF rendering (likely via PDF.js) with CE controls for paging, search, download, and annotations.
- **Pivot Grid**: Provide a data-heavy pivot table with virtualization, aggregations, and column configurators, reusing Grid infrastructure.
- **Scheduler**: Build calendar views (day/week/month) with drag/drop appointments, resource grouping, and timezone-aware rendering.
- **Signature Pad**: Offer a lightweight canvas-based signature capture component with export helpers and validation.

### Component backlog

| Status | Component | Notes |
| --- | --- | --- |
| TODO | Carousel | Responsive slide deck with autoplay, gesture controls, and CE token-aware navigation. |
| TODO | Calendar | Standalone monthly/agenda calendar primitives that the scheduler can reuse. |
| Preview | Backlog Board | Backlog columns with drag/drop, inline edit hooks, and host-driven add/move/select callbacks. |
| Preview | Diagram | Node/link canvas with pan/zoom, snapping, inline label edit, and CE-themed handles. |
| TODO | Gantt | Timeline grid with swimlanes, dependencies, and virtualization tuned for large data sets. |
| TODO | TreeList | Hierarchical grid for large datasets with expand/collapse, sorting, and inline actions. |
| TODO | Tree View | Lightweight tree widget for navigation menus and config panes, with keyboard support. |
| TODO | Timeline | Chronological lanes with milestones, grouping, and zoom controls for programs/roadmaps. |
| TODO | Video Control | Feature-complete player (captions, quality selector, chapters, analytics hooks, PiP/fullscreen) paired with CE-themed controls. |
| TODO | Drag & Drop Layout | Grid/canvas editor for rearranging panels via drag and drop, snapping to CE spacing tokens. |
| Preview | Switch | `<ce-switch>` web component ships with helper text, theming, async states, and Storybook docs/playground coverage. |
| TODO | Spreadsheet | Multi-sheet editor with formulas, selection model, and virtualization leveraging Grid primitives. |
| Preview | Rating | `<ce-rating>` radiogroup delivers keyboard navigation, custom icons, and reset + doc stories for surveys. |
| Preview | Upload | File picker with drag/drop, progress, retry, chunking, and validation hooks tied to CE states. |
| TODO | ce-frame-lms | Build LMS atop `ce-ui-webcomponents`, `ce-ui-scss`, `ce-ui-framework`; lock versions, add regression/a11y tests, perf audits, and publish versioned packages. |

## Production Readiness Notes

- `ce-ui-webcomponents`: feature-rich but pre-production; needs stability pass, unit/DOM regression tests, a11y audit, and versioned API contracts before large-app rollout.
- Icons: configure global sprite once via `setIconSpriteUrl('/assets/icons/latest/nucleo.svg')` (or env-specific CDN path) to keep bundles lean; fallback to `setIconAssetBase()` for `img` loading.
- `ce-ui-scss`: solid token base; ensure version locking, CDN/publish strategy, and visual regression coverage.
- `ce-ui-framework`: treat as pre-production until perf/security audits, routing/data/error-handling policies, and deployment playbooks are in place.
- Next steps before LMS: freeze breaking changes, add comprehensive tests (unit/integration/a11y), run perf checks, document APIs, and publish versioned packages for all three packages.

## Production Readiness Checklist (Webcomponents)

Last updated: 2026-01-26

- [x] Full test suite passes (unit/DOM/a11y/contracts).
- [x] Hydration-safe mounting for preserve-light-dom components (no deferred mount race).
- [x] Theme token fallback injected for text/icon consistency.
- [x] Dialog visibility class compatibility (`ce-dialog--visible` + legacy `open`).
- [x] Canvas stubs in test harness to avoid QR/Chart noise in jsdom.
- [x] Storybook visual regression baseline captured.
- [x] Perf budget tests enabled in CI.
- [x] Versioned release checklist + changelog entry for next release.
  - Verified `vrt:test` on 2026-01-26.

## Cross-platform best practices

To keep webcomponents fast, future-proof, and framework-neutral:

- **Hydration-safe DOM**: SSR HTML must match the client DOM. Avoid rewriting light DOM on connect.
- **Progressive enhancement**: Add behavior/classes instead of rebuilding markup.
- **Event stability**: Emit events on the custom element; avoid nested dispatch loops.
- **Attribute-first state**: Reflect state via attributes so SSR and client stay aligned.
- **Shadow DOM policy**: If using shadow DOM, ship a consistent styling strategy (CSS vars/adopted stylesheets).
- **Performance**: Batch DOM updates and avoid layout thrashing.
- **A11y**: Keyboard support and ARIA roles/labels are required for all interactive elements.

See `projects/libraries/ui/ce-ui-webcomponents/docs/HYDRATION.md` for hydration details and checklists.

- ce-ui-scss
run the following commands
`npm install`
`npx playwright install --with-deps`
`npm run vrt:baseline`
`npm run check:dist`
`npm run build`

Each feature will ship alongside SCSS skins, Storybook demos, and optional data adapters so consumers can test them in isolation before wiring into apps.

That’s a hefty lift for the whole library. Here’s a concrete, staged plan to get ce-ui-webcomponents production‑ready, with specifics you can execute:

Stability/QA hardening

Establish a release branch and adopt semantic versioning; tag the current baseline as 0.9.0, cut issues from there, and target 1.0.0.
Add CI gates: lint (ESLint), format (Prettier), typecheck (tsc), build (Vite), unit + DOM tests (Vitest + @testing-library/dom), and Storybook build.
Add visual/DOM regression: run Storybook with Chromatic or Playwright screenshot diffs on key stories (Buttons, Form controls, Tabs, Dialog, Grid, Upload, RichTextEditor, SmartEditor, Pagination).
Add bundle integrity: run npm run build/pnpm build to ensure tree-shakable, and check size via rollup-plugin-visualizer or bundlewatch.
Unit/DOM test coverage priorities

Core components with logic: Tabs/TabLayout (keyboard, add/close, aria), Dialog/Popup (focus trap, ESC), Dropdown/Combo/MultiSelect (opening, selection, keyboard), Grid (sorting, pagination, empty state), Upload (states), SmartEditor/Editor (toolbar actions toggling contentEditable).
Shared utilities: BaseComponent mounting/destroy lifecycle.
Testing stack: Vitest + @testing-library/dom + jsdom; add helpers to mount/destroy components cleanly.
Add a minimal a11y smoke test per story (axe-core integration) to flag regressions.
A11y audit (WCAG 2.1 AA)

Ensure all controls expose proper roles/aria-*; verify focus order and visible focus rings.
Tabs/TabLayout: correct tablist/tab/tabpanel semantics, arrow key behavior, aria-selected, disabled handling.
Form elements: label/aria-label hookup; error text with aria-live where applicable.
Dialog/Popup: focus trap, aria-modal, label by title, ESC to close.
Buttons/links: no empty labels; icon-only buttons have aria-label.
Color contrast: run automated contrast checks on tokens; adjust any failing tokens.
Keyboard operability: every interactive control reachable via keyboard; no key traps.
Versioning/release process

Set package version to 1.0.0 once above gates pass.
Add CHANGELOG with Keep a Changelog format; note breaking changes and migrations.
Add npm scripts: lint, typecheck, test, test:watch, storybook, storybook:build, a11y (axe against built stories), size (bundlewatch/visualizer).
Configure commit/PR templates to require tests + screenshots for visual components.
What I can do next here

Add foundational test harness (Vitest + @testing-library/dom) and a first wave of tests (e.g., Tabs, Dialog, Dropdown, SmartEditor, Pagination).
Wire axe-core into a Storybook a11y smoke run.
Add bundlewatch/visualizer and set version to 1.0.0 with CHANGELOG.
Add CI workflow config (if you use GitHub Actions) to run the above.

If you’d like, I can start by implementing the test harness, initial component tests, axe smoke test, and update package version/changelog.

Gantt, Scheduler, Spreadsheet, Map, Diagram, ColorPicker family, Wizard/Window/DialogWindow, Splitter, SignaturePad, SpeechToText, Carousel/Chart, AtmCard/BacklogBoard/Cart/Barcode, etc.

RadioRange; TreeList; Wizard/Window/DialogWindow; AtmCard, BacklogBoard, Cart, Barcode
 Smoke test covered.
