# Engineering Standard

> The repository rules for layout, public API, TypeScript, runtime behaviour, performance, accessibility, CSS, testing and workflow.

Every package in this repository follows these rules. `npm run check` enforces the mechanical ones; reviewers enforce the rest.

## 1. Repository layout and boundaries

- `packages/<name>/src` holds source, `packages/<name>/test` holds tests, `packages/<name>/demo` holds an optional manual demo.
- `apps/*` are deployable sites and services, never imported by packages.
- A package imports another package **only by its public name** (`@birchui/core`), never by a relative path into its sources. ESLint blocks this.
- The dependency direction is fixed:
  - `license` → nothing
  - `core` → nothing
  - `excel` → `license`
  - product packages (`grid-pro`, `scheduler`, `calendar`, `charts`, `forms`, `pdf`, `document`) → `core` + `license` (+ `excel` for `grid-pro`)
  - adapters and `element` → `core`, plus optional product peers behind subpath entries
- No cycles.
- Commercial code never moves into an MIT package. MIT packages never import commercial ones.

## 2. Public API

- Named exports only. Default exports are banned in package sources.
- Each package's `src/index.ts` is its complete public API. Anything not exported there is internal and may change at any time.
- Every widget follows the shared contract in `packages/core/src/widget.ts`:
  - `create(container, options)` returns `{ element, update(partial), on(event, fn) → unsubscribe, destroy() }`
  - it is exported through `defineWidget`, with `name`, `tagName` and the full `events` list.
- Options are plain serializable objects wherever possible. Callbacks are allowed for renderers, validators and value accessors.
- `update(partial)` applies only the keys passed and never recreates the widget.
- Events are past-tense or noun-phrase camelCase (`cellValueChanged`, `eventDrop`). Payloads are objects, never positional arguments.
- Breaking changes to anything exported require a major changeset and a migration note in the docs.

## 3. TypeScript

- `strict` everywhere. Use `any` only at true dynamic boundaries (user row data, JSON input). Prefer `unknown` and narrow.
- Use `import type` for type-only imports (enforced; `verbatimModuleSyntax` is on).
- Public types are generic over the user's row or event type (`GridApi<TRow>`) so user code needs no casts.
- No enums. Use string-literal unions.
- No namespaces. No classes in public APIs, except custom elements and errors; internal classes are fine.
- Name things by role, not by type: `visibleRows`, not `arr2`. Booleans read as predicates (`isEditing`, `hasModule`).
- Files are kebab-case. Types and interfaces are PascalCase. Functions and variables are camelCase. Module-level constants that are real constants are UPPER_SNAKE_CASE.

## 4. Runtime rules

- **SSR-safe imports:** importing any package must not touch `window`, `document`, `navigator` or `location`. DOM work starts inside `create…()`.
- **No side effects on import:** keep `sideEffects: false`, except CSS. Style injection happens in `create…()` through `ensureStyles(id, css)` and can be turned off with `injectStyles: false`.
- **No network calls**, ever, from any package. License checks are offline.
- **Never break the host page:** user callbacks run inside try/catch at the widget boundary and errors are reported with `console.error`. Invalid options produce one descriptive `console.warn` and a safe fallback. Throw only for programmer errors at creation time, such as a missing container.
- **Licensing:** the paid features of a product call `checkLicense(product, { key, host })` once per widget and dispose it on destroy. A missing key shows a watermark and one console warning. It never disables a feature.
- **Cleanup:** every listener, observer, timer and animation frame registered by a widget is released in `destroy()`. Tests assert this.

## 5. Performance budgets

- The grid scrolls 1,000,000 rows at 60 fps on a mid-range laptop. A full re-render costs O(visible cells), not O(rows).
- Pipeline stages (filter, sort, group, pivot) run on arrays of indices or rows without per-row allocations in hot loops.
- No layout thrashing: read geometry first, then write, inside `requestAnimationFrame`.
- Each package documents its minified + gzipped size in its README. A size increase above 10% needs a reason in the changeset.

## 6. Accessibility

- Follow the WAI-ARIA Authoring Practices pattern for the widget: grid or treegrid for grids, grid for calendar months, and form semantics for forms.
- Everything works by keyboard. Focus is always visible. Use a roving tabindex inside composite widgets.
- Virtualized content keeps `aria-rowcount` / `aria-rowindex` (and the column equivalents) correct.
- Respect `prefers-reduced-motion` and `prefers-color-scheme`. Meet WCAG 2.2 AA contrast in both bundled themes.

## 7. CSS

- Use one class prefix per product, all prefixed with the brand prefix (`lq-grid`, `lq-sched`, `lq-cal`, `lq-chart`, `lq-form`).
- Theme only through the shared custom properties (`--lq-*`) defined in `packages/core/src/styles.ts`. Products may add tokens of their own under their prefix.
- No Shadow DOM in main builds. Keep selector specificity low (single class wherever possible) so customers can override.
- Each package's CSS lives in `src/styles.ts` as a single exported template literal. The build extracts it to `dist/styles.css`.

## 8. Testing

- Vitest with happy-dom. Run `npm test` for everything, or `npx vitest run packages/<name>` for one package.
- Pure logic (pipelines, layout engines, parsers, recurrence, zip) lives in DOM-free modules with exhaustive unit tests.
- DOM behaviour is tested through the public API and real dispatched events, not by calling internals.
- Every bug fix adds a test that fails without the fix.
- Performance-critical engines include a perf test with a generous time limit, which catches order-of-magnitude regressions.
- Test names describe behaviour ("keeps ancestors of matching rows when filtering tree data").

## 9. Comments and documentation

- Code should read on its own. Do not write comments that restate code, narrate changes, or argue with a reviewer.
- A comment is allowed only for information the code cannot carry: an external spec quirk (with a reference), a browser bug workaround (with a link), or a licence header.
- Public API documentation lives in `apps/docs/content`. API reference pages are generated from the exported types, so name and type them well.
- Each package has a short README: what it is, install, a minimal realistic example, and its licence.

## 10. Tooling and workflow

| Command                | Purpose                                         |
| ---------------------- | ----------------------------------------------- |
| `npm run check`        | format check + lint + typecheck + tests (CI)    |
| `npm run lint:fix`     | ESLint with autofix                             |
| `npm run format`       | Prettier write                                  |
| `npm run build`        | builds every workspace in dependency order      |
| `npx changeset`        | record a user-facing change for release notes   |

- Use conventional commits: `feat:`, `fix:`, `refactor:`, `docs:`, `chore:`, `test:`, `perf:`. Write a one-line subject, scoped where useful (`feat(grid-pro): pivot totals`).
- CI (`.github/workflows/ci.yml`) runs `check` and `build` on Node 20.19 and 22.
- Dependencies: runtime dependencies need a strong reason. The only approved one is `@noble/ed25519` (licence signatures). Dev dependencies are installed at the root.

## 11. Definition of done (per change)

1. `npm run check` passes.
2. New behaviour has tests, and bugs have regression tests.
3. Keyboard and screen-reader behaviour has been considered and tested where it applies.
4. The public API is exported from `src/index.ts`, typed generically, and documented in `apps/docs`.
5. A changeset is added for published packages.
6. No new console noise, no network access, no import-time side effects.
