Compare commits

..
35 Commits
Author SHA1 Message Date
Rbanh c247a337a9 Fix selection notes refresh and force fresh placement on import compile
CI / test (push) Has been cancelled
2026-02-20 03:38:41 -05:00
Rbanh 9f5ff8eb42 Fix drag UX: single-select on click and auto-unlock locked component on manual move
CI / test (push) Waiting to run
2026-02-20 03:34:26 -05:00
Rbanh 2131340c01 Fix lock workflow: keep components draggable, add Unlock All, and relax Auto Layout locks
CI / test (push) Waiting to run
2026-02-20 03:22:39 -05:00
Rbanh 9a21e111d0 Polish legacy UI: dark theme, note hints, lock-safe drag, and cleaner symbol editor
CI / test (push) Waiting to run
2026-02-20 02:06:07 -05:00
Rbanh 46175efe1b Activate ELK backend placement path with deterministic fallback
CI / test (push) Waiting to run
2026-02-20 01:31:39 -05:00
Rbanh 128c5c6f4e Enable ELK-first layout requests and harden deterministic QA
CI / test (push) Waiting to run
2026-02-20 01:24:04 -05:00
Rbanh 1a9c7b56ff Improve layout stability, tie-net metrics, and annotation readability
CI / test (push) Waiting to run
2026-02-20 01:05:28 -05:00
Rbanh cf3e64e836 Harden responsive layout and reduce tie-net routing noise
CI / test (push) Waiting to run
2026-02-20 00:47:57 -05:00
Rbanh fc5f2fee41 Refine group placement seeding to reduce collapse and detour
CI / test (push) Waiting to run
2026-02-20 00:11:01 -05:00
Rbanh f0b952e3a2 Anchor net labels to routed segments to avoid floating labels
CI / test (push) Waiting to run
2026-02-19 23:55:00 -05:00
Rbanh cc20c0cc25 Improve text readability with pin label spacing and annotation panel
CI / test (push) Waiting to run
2026-02-19 23:52:12 -05:00
Rbanh 5f31542cb6 Stabilize compile by preserving placements unless relayout requested
CI / test (push) Waiting to run
2026-02-19 23:41:18 -05:00
Rbanh 77f63a6f80 Refine drag behavior: default to single-component move
CI / test (push) Waiting to run
2026-02-19 23:33:23 -05:00
Rbanh 0c5c1040cd Sprint 7: add Phase 8 cutover gate and rollback runbook
CI / test (push) Waiting to run
2026-02-19 23:24:46 -05:00
Rbanh 35211c69a4 Sprint 6: add React JSON power-tool editor workflow
CI / test (push) Waiting to run
2026-02-19 23:16:54 -05:00
Rbanh b8d894f243 Sprint 5: enforce readable geometry for generic/template symbols
CI / test (push) Waiting to run
2026-02-19 23:09:53 -05:00
Rbanh e69f2db44c Sprint 4: deterministic label collision pass and refreshed UI baselines
CI / test (push) Waiting to run
2026-02-19 23:01:56 -05:00
Rbanh dc9c2773de Sprint 3: unify React canvas interactions and ELK boundary metadata 2026-02-19 22:56:11 -05:00
Rbanh 5a4e116475 Sprint 2: wire React workflows, store lifecycle, and interactive canvas
CI / test (push) Waiting to run
2026-02-19 22:32:13 -05:00
Rbanh d029e480d0 Kick off Phase 8 with React scaffold and deterministic store foundation
CI / test (push) Waiting to run
2026-02-19 19:18:27 -05:00
Rbanh 85dc9a1ac2 Add Phase 8 React+ELK refactor execution plan
CI / test (push) Waiting to run
2026-02-19 19:06:22 -05:00
Rbanh 0d53bdaf9a Preserve placement during drag compile updates
CI / test (push) Waiting to run
2026-02-19 18:55:48 -05:00
Rbanh cd007ba431 Improve layout fallback flow and stabilize QA baselines
CI / test (push) Waiting to run
2026-02-19 18:33:14 -05:00
Rbanh 47fabe6180 Phase 6: stabilize layout coherence with rank-anchored compaction
CI / test (push) Waiting to run
2026-02-19 14:19:48 -05:00
Rbanh 8b6c9593e1 Phase 5: ship layout QA budgets, import hardening, and fixture pack
CI / test (push) Waiting to run
2026-02-19 14:00:05 -05:00
Rbanh 31a47346ea Harden API contracts with request IDs and audit telemetry
CI / test (push) Waiting to run
2026-02-18 22:19:38 -05:00
Rbanh e2445980f9 Add keyboard shortcut UX and command palette interactions 2026-02-18 22:15:55 -05:00
Rbanh 72ea3609bb Add actionable diagnostics with one-click repair actions 2026-02-18 22:12:57 -05:00
Rbanh 486092e884 Add UI-native component/net creation workflows and QA coverage 2026-02-18 22:09:42 -05:00
Rbanh 2bda088223 Tighten routing policy with channel spacing and tie-net fallback 2026-02-18 22:05:31 -05:00
Rbanh 538d137d35 Improve auto-layout with semantic lanes and overlap resolution 2026-02-18 22:03:44 -05:00
Rbanh 570e89cf4e Improve fit/focus viewport behavior and add viewport QA coverage 2026-02-18 22:01:43 -05:00
Rbanh 2ff3856941 Revamp UI visual system and add in-product net color legend 2026-02-18 21:58:39 -05:00
Rbanh 543ae522df Add Phase 4 execution plan and measurable quality gates 2026-02-18 21:56:01 -05:00
Rbanh d5836a20d1 Ship Phase 3 browser QA, visual baselines, and UX consistency 2026-02-18 21:43:45 -05:00
69 changed files with 8088 additions and 374 deletions

No files matched your search

+21
View File
@@ -32,3 +32,24 @@ jobs:
- name: Run tests
run: npm test
- name: React path quality stubs
run: npm run frontend:react:check
- name: Install Playwright browsers
run: npx playwright install chromium
- name: Run browser regression
run: npm run test:ui
- name: UI metrics report (always)
if: always()
run: |
echo "UI metrics report:"
cat output/playwright/ui-metrics-report.json || true
- name: Browser artifacts listing (always)
if: always()
run: |
echo "Playwright output:"
ls -R output/playwright || true
+3
View File
@@ -0,0 +1,3 @@
.playwright-cli/
output/playwright/
node_modules/
+44
View File
@@ -18,6 +18,17 @@ This version includes:
npm run start
```
Frontend migration command paths:
- Legacy: `npm run frontend:legacy:dev` or `npm run frontend:legacy:start`
- React (`frontend-react/`): `npm run frontend:react:dev`
- React checks: `npm run frontend:react:check`
React app bootstrap:
```bash
npm --prefix frontend-react install
npm run frontend:react:dev
```
Open:
- Workspace: `http://localhost:8787/`
- Health: `http://localhost:8787/health`
@@ -25,6 +36,7 @@ Open:
Version metadata:
- REST and MCP tool responses include `api_version` and `schema_version`.
- REST responses also include `request_id` and `x-request-id` for request correlation.
- Current values: `api_version=0.3.0`, `schema_version=1.0.0`.
- Compatibility policy (current): additive, backward-compatible fields may be introduced in the same API minor version.
@@ -37,9 +49,16 @@ Operational limits:
Docs:
- `docs/release-checklist.md`
- `docs/operations-runbook.md`
- `docs/quality-gates.md`
- `docs/phase4-execution-plan.md`
- `docs/phase5-execution-plan.md`
- `docs/phase8-dual-run-kickoff.md`
- `docs/fixtures.md`
- `docs/api-mcp-contracts.md`
CI:
- `.gitea/workflows/ci.yml` runs syntax checks + full test suite on push/PR.
- CI also runs browser regression (`npm run test:ui`) after installing Playwright Chromium.
## REST API
@@ -155,14 +174,39 @@ Tools:
## Workspace behavior highlights
- Fit-to-view default on load/import/apply
- Focus-selection + reset-view controls for faster navigation in dense schematics
- `Reset Sample` one-click deterministic baseline restore for QA/demo loops
- Space + drag pan, wheel zoom, fit button
- Net/component/pin selection with dimming + isolate toggles
- Selected panel editors for component properties, full pin properties, full symbol body/pin editing, and net connect/disconnect operations
- Click diagnostics to jump/flash focused net/component/pin
- Auto Layout and Auto Tidy actions
- `Shortcuts` helper modal and `Ctrl/Cmd+K` command palette quick actions
- Keyboard shortcuts:
- `Ctrl/Cmd+Z` undo
- `Ctrl/Cmd+Shift+Z` or `Ctrl/Cmd+Y` redo
- `Ctrl/Cmd+K` open command palette
- `Space` rotate selected components (or pan when no selection)
- `F` focus current selection
- `Alt+Enter` apply current selection editor (component/pin/net)
- `Alt+C` connect selected pin to chosen net
## Browser Regression
Run browser interaction + visual regression checks:
```bash
npx playwright install chromium
npm run test:ui
```
Metrics report artifact:
- `output/playwright/ui-metrics-report.json`
Refresh visual baselines intentionally:
```bash
UPDATE_SNAPSHOTS=1 npm run test:ui
```
Baselines are stored in `tests/baselines/ui/`.
+68
View File
@@ -0,0 +1,68 @@
# API + MCP Contract Policy
This document defines compatibility expectations for Schemeta API and MCP tools.
## Version Fields
All successful API/MCP structured responses include:
- `api_version`
- `schema_version`
HTTP API responses also include:
- `request_id` (response field + `x-request-id` header)
## Compatibility Policy
- Additive changes are allowed within the same `api_version` minor release.
- Breaking shape changes require a new API major version.
- `schema_version` increments when SJM schema semantics or required fields change.
## HTTP API Contracts
Stable endpoints:
- `POST /compile`
- `POST /analyze`
- `POST /layout/auto`
- `POST /layout/tidy`
- `GET /health`
- `GET /mcp/ui-bundle`
Error envelope shape:
```json
{
"ok": false,
"request_id": "uuid-or-forwarded-id",
"error": {
"code": "stable_machine_code",
"message": "human-readable description"
}
}
```
## MCP Tool Contracts
Stable tool names:
- `schemeta_compile`
- `schemeta_analyze`
- `schemeta_ui_bundle`
Contract rules:
- Tool names are stable across minor versions.
- Input schemas may gain optional fields additively.
- Structured response fields are additive-only within a minor.
## Persistence and Restore
UI workspace persistence is expected to support:
- deterministic JSON export/import roundtrip
- local snapshot restore path (`schemeta:snapshots:v2`)
- reset-to-sample baseline recovery for QA loops
These are validated in release checklist + browser regression flow.
+29
View File
@@ -0,0 +1,29 @@
# Fixture Pack
Schemeta uses deterministic fixture circuits for compile/layout/readability QA.
## Core fixtures
1. `examples/esp32-audio.json`
- Baseline audio pipeline (MCU -> DAC -> amp).
2. `examples/dense-analog.json`
- High-density analog topology used for overlap/crossing stress.
3. `examples/i2c-sensor-hub.json`
- Shared bus topology with pull-ups and interrupt branches.
4. `examples/power-tree.json`
- Multi-domain power-distribution with digital branch nets.
## Usage
1. Manual import in UI:
- `Import JSON` then select fixture file.
2. API:
- `POST /compile` or `POST /analyze` with fixture payload.
3. Automated regression:
- `npm run test:ui` uses `dense-analog` for layout budget checks.
## Notes
1. Fixtures should stay deterministic (stable ordering and explicit naming).
2. Avoid avoidable warnings in default/demo fixtures.
3. Add a fixture whenever a routing/layout bug is fixed to prevent regressions.
+13 -1
View File
@@ -35,6 +35,18 @@ This runbook covers baseline production operation for Schemeta API + UI.
- `GET /mcp/ui-bundle`
- Metadata for MCP UI embedding.
## Request Correlation and Audit Logs
- Every response includes `x-request-id`.
- API envelopes include `request_id` for correlation in clients and logs.
- Server emits one JSON audit log entry per request on response finish with:
- `request_id`
- `method`
- `path`
- `status`
- `duration_ms`
- `client`
## Production Checks
1. Verify process liveness:
@@ -78,6 +90,6 @@ This runbook covers baseline production operation for Schemeta API + UI.
## Observability Recommendations
- Add structured request logs at reverse proxy layer.
- Structured request logs are emitted by the app; keep proxy logs for edge-level traces.
- Track latency percentiles for `/compile` and `/analyze`.
- Track per-endpoint status code rates and top warning/error IDs.
+54
View File
@@ -0,0 +1,54 @@
# Phase 4 Execution Plan
Phase 4 milestone: `#3` - AAA SaaS Productization and UX Polish.
## Objectives
- Move Schemeta from prototype ergonomics to production-grade UX/UI quality.
- Enforce measurable quality gates for beta and GA releases.
- Sequence high-risk engine work (layout/routing) behind stable UX foundations.
## Workstream Order
1. `#23` AAA-00: Plan and quality gates
2. `#15` AAA-01: Visual system redesign
3. `#16` AAA-02: Fit-to-view and viewport behavior
4. `#17` AAA-03: Layout engine v3
5. `#18` AAA-04: Routing engine v3
6. `#19` AAA-05: In-canvas editing overhaul
7. `#20` AAA-06: Diagnostics UX 2.0
8. `#21` AAA-07: Accessibility/responsive/keyboard pass
9. `#22` AAA-08: SaaS + MCP production hardening
## Dependency Graph
- `#15` is prerequisite for high-fidelity baseline updates and consistent UI controls.
- `#16` depends on `#15` token/layout primitives.
- `#17` depends on `#16` viewport/fit behavior to evaluate perceived quality.
- `#18` depends on `#17` placement decisions and semantic lanes.
- `#19` depends on `#15` and should begin in parallel with late `#17` work where safe.
- `#20` depends on `#19` interaction model for click-to-fix workflows.
- `#21` runs continuously but final pass must occur after `#15/#19/#20`.
- `#22` can run in parallel, but final contract freeze occurs after `#19/#20`.
## Critical Path
`#15 -> #16 -> #17 -> #18 -> #19 -> #20 -> #21 -> #22`
## Risk Register
1. Layout/routing regressions on dense circuits.
- Mitigation: expand fixture corpus, snapshot + metric thresholds, staged rollout.
2. Visual redesign causing interaction regressions.
- Mitigation: preserve interaction test suite, baseline review checklist.
3. Editor complexity inflation.
- Mitigation: keep single source of truth for selection/edit state, strict undo invariants.
4. API/MCP compatibility drift.
- Mitigation: contract tests and explicit schema/api version policy enforcement.
## Definition of Done (Phase 4)
- All issues `#15-#23` closed with acceptance criteria verified.
- Release checklist passes all beta and GA quality gates.
- Browser regression and baseline review pass on representative fixtures (including dense analog).
- API/MCP contract tests pass with versioned compatibility notes.
+49
View File
@@ -0,0 +1,49 @@
# Phase 5 Execution Plan
Milestone: `Phase 5 - Layout Robustness and JSON Import UX Hardening`
## Goals
1. Make drag/re-layout behavior measurable and regression-resistant.
2. Improve JSON import/apply reliability with validation-first messaging.
3. Ship richer fixture coverage and enforce readability budgets in CI.
## Workstreams
1. QA harness and metrics artifact
- Extend `tests/ui-regression-runner.js` to capture:
- initial compile metrics
- post-drag metrics
- post-drag auto-tidy metrics
- dense fixture metrics
- Emit machine-readable artifact:
- `output/playwright/ui-metrics-report.json`
2. Layout/readability quality budgets
- Enforce thresholds in UI regression runner with env overrides:
- `UI_SAMPLE_MAX_*`
- `UI_DRAG_MAX_*`
- `UI_TIDY_MAX_*`
- `UI_DENSE_MAX_*`
- Keep defaults tuned to current deterministic behavior.
3. JSON import UX hardening
- Validate with `/analyze` before applying/importing JSON.
- Block apply/import when validation has errors.
- Surface first warning/error and path for faster correction.
- Keep deterministic change summary after successful apply.
4. Fixture pack expansion
- Add representative fixtures beyond the baseline audio example:
- `examples/dense-analog.json`
- `examples/i2c-sensor-hub.json`
- `examples/power-tree.json`
- Maintain warning-clean default sample (`frontend/sample.schemeta.json`).
## Done Definition
1. `npm test` passes.
2. `npm run test:ui` passes with quality budgets.
3. `output/playwright/ui-metrics-report.json` is generated on every UI run.
4. Import/apply validation behavior is deterministic and user-visible.
5. Phase 5 issues `#24-#29` are closed and milestone is closed.
+54
View File
@@ -0,0 +1,54 @@
# Phase 8 Cutover and Rollback Runbook
## Goal
Move from legacy-first UI to React-first UI safely, with a deterministic rollback path.
## Preconditions
- `main` branch green on:
- `npm run test`
- `npm run test:ui`
- `npm run frontend:react:check`
- Milestone #7 issues required for cutover are accepted.
- Latest regression artifacts are present under `output/playwright/`.
## Cutover Gate Command
Run this gate command before enabling React as default:
```bash
npm run phase8:cutover:check
```
It writes a machine-readable report to:
- `output/phase8/cutover-check-report.json`
## Cutover Checklist
1. Confirm release candidate commit hash and tag target.
2. Run `npm run phase8:cutover:check` and archive report artifact.
3. Verify React path boots and legacy path still boots in dual-run.
4. Verify save/load/import/export compatibility on fixture corpus.
5. Confirm MCP tools still return stable API envelopes.
6. Publish release notes with known limitations and rollback trigger criteria.
## Rollback Triggers
Rollback immediately if any occur post-cutover:
- New blocker in compile/apply loop.
- UI interaction regressions that break editing workflows.
- Crossings/overlaps/readability regressions above agreed thresholds.
- API/MCP contract break for compile/analyze/layout endpoints.
## Rollback Procedure
1. Switch deployment back to previous stable tag.
2. Re-enable legacy-first UI mode.
3. Re-run:
- `npm run test`
- `npm run test:ui`
4. Open incident issue with:
- failing commit/tag
- regression screenshots
- exact reproduction JSON
5. Keep React path available in non-default dual-run mode until fix lands.
## Evidence to Attach to Release
- `output/phase8/cutover-check-report.json`
- `output/playwright/ui-metrics-report.json`
- Updated `docs/release-checklist.md` completion notes
+35
View File
@@ -0,0 +1,35 @@
# Phase 8 Kickoff: Dual-Run Frontend (Legacy + React)
## Purpose
Define how to run the current legacy frontend and the incoming React frontend side-by-side during migration kickoff.
## Frontend Paths
- Legacy frontend: served by `src/server.js` at `http://localhost:8787/`
- React frontend (target): expected in `frontend-react/` (Vite default expected at `http://localhost:5173/`)
## Commands
- Legacy dev server: `npm run frontend:legacy:dev`
- Legacy start (non-watch): `npm run frontend:legacy:start`
- React dev (stub-aware): `npm run frontend:react:dev`
- React quality stubs:
- `npm run frontend:react:lint`
- `npm run frontend:react:test`
- `npm run frontend:react:build`
- `npm run frontend:react:check`
If `frontend-react/package.json` does not exist, lacks the requested script, or `frontend-react/node_modules` is missing, React commands exit successfully with a deterministic skip message.
## Side-by-Side Local Run
1. Terminal A: `npm run frontend:legacy:dev`
2. Terminal B: `npm run frontend:react:dev`
3. Verify legacy UI responds on `http://localhost:8787/`
4. Verify React command behavior:
- pre-scaffold: skip message (expected)
- post-scaffold: starts actual React dev server
## Milestone Kickoff Checklist (`#37`, `#38`)
- [x] `#37` React migration kickoff commands are exposed in root `package.json`.
- [x] `#37` Dual-run operational doc exists for legacy + React side-by-side local execution.
- [x] `#37` CI includes a React-path quality command (`frontend:react:check`) that is safe before scaffold and active after scaffold.
- [x] `#38` Deterministic command wiring established for React quality gates (`lint/test/build`) via a single stub-aware runner.
- [x] `#38` Legacy and React paths are explicitly separated in command names to reduce migration ambiguity.
+95
View File
@@ -0,0 +1,95 @@
# Phase 8 Execution Plan: React + ELK Core Refactor
## Objective
Deliver the largest Schemeta refactor to date: migrate the frontend to a robust React architecture, replace fragile placement behavior with ELK-driven layout, harden routing/labeling readability, and establish production-grade quality gates.
This phase is OSS-only and budget-neutral.
## Non-Goals
- No paid/proprietary graph SDKs.
- No API contract break for `/compile`, `/analyze`, `/layout/auto`, `/layout/tidy`.
- No regression of current JSON schema compatibility.
## Architecture Target
- Frontend: React + TypeScript + Vite.
- Interaction layer: React Flow primitives for node/selection/viewport interactions.
- Layout: `elkjs` as primary placement engine.
- Routing: Schemeta incremental router with deterministic tie-net fallback.
- State: deterministic centralized action pipeline (undo/redo transaction model).
## Work Breakdown (Milestone #7)
- #37 P8-01 Frontend architecture migration to React + TS + Vite
- #38 P8-02 State model refactor with deterministic action pipeline
- #39 P8-03 Canvas subsystem rewrite with React Flow contracts
- #40 P8-04 ELK integration and constraints mapping
- #41 P8-05 Routing engine revamp (incremental reroute)
- #42 P8-06 Deterministic label placement and collision avoidance
- #43 P8-07 Symbol readability and pin-density standards
- #44 P8-08 JSON editor power-tool upgrade (schema-aware + diff apply)
- #45 P8-09 QA hardening (visual/readability gates)
- #46 P8-10 Cutover, migration, rollback
## Delivery Sequence (Critical Path)
1. Foundation
- Complete #37 (React app shell) and #38 (state architecture).
- Exit criteria: feature-parity shell + deterministic action store.
2. Interaction rewrite
- Complete #39 on top of #37/#38.
- Exit criteria: drag/multi-select/pan/zoom/edit stable and undoable.
3. Layout core
- Complete #40 with adapter boundaries for constraints.
- Exit criteria: ELK-based autolayout deterministic on fixtures.
4. Routing core
- Complete #41 with local reroute and deterministic fallback behavior.
- Exit criteria: moved components reroute only affected nets.
5. Readability system
- Complete #42 + #43 for labels/pin-density constraints.
- Exit criteria: baseline fixtures have no label/pin overlap failures.
6. Power-user JSON workflow
- Complete #44 for schema-aware editing and safe apply previews.
7. Quality gates + ship safety
- Complete #45 + #46; run cutover checklist.
## Technical Design Rules
- Determinism first: all ordered traversals sort by stable keys.
- Incremental operations default: no full relayout on drag/edit unless explicit.
- Readability constraints are hard constraints, not best-effort hints.
- Feature flags for risky changes during dual-run period.
## Quality Gates (Phase 8 Additions)
In addition to existing crossings/overlaps/detour metrics:
- Label collisions must be 0 in baseline fixtures.
- Pin text collisions must be 0 in baseline fixtures.
- Component overlap must remain 0.
- Drag action must not move untouched components.
- Snapshot test matrix across viewport sizes and render modes.
## Risks and Mitigation
- Risk: React migration stalls on parity gaps.
- Mitigation: keep legacy UI in dual-run until parity checklist passes.
- Risk: ELK mapping mismatch with custom constraints.
- Mitigation: fallback mapping with explicit unsupported-constraint diagnostics.
- Risk: routing regressions after layout changes.
- Mitigation: incremental router tests and stress fixtures in CI.
- Risk: test flakiness due to persisted state.
- Mitigation: force deterministic test bootstrapping and storage resets.
## Performance Budgets
- Compile latency p95 (sample): <= 180ms local.
- Drag-to-reroute p95 (affected nets only): <= 120ms local.
- Auto layout p95 (medium fixture): <= 600ms local.
## Release Readiness Checklist
- All milestone issues closed.
- CI green for unit + UI + readability metrics.
- Dual-run comparison report attached.
- Rollback validated with documented steps.
- Release notes include migration caveats and known limitations.
## Definition of Done
Phase 8 is done only when:
- React UI is default and legacy path can be disabled safely.
- ELK placement is primary in production path.
- Readability gates are enforced in CI.
- Drag/edit interactions are deterministic and locally incremental.
- JSON/AI workflows are schema-aware and operator-safe.
+57
View File
@@ -0,0 +1,57 @@
# Quality Gates
This document defines measurable release gates for Schemeta.
## Release Stages
- Beta: feature complete, controlled rollout quality.
- GA: production-grade quality, accessibility, and operational readiness.
## Beta Gates
1. Functional correctness
- `npm test` passes.
- `npm run test:ui` passes.
2. Visual regression
- No unexpected screenshot diffs in `tests/baselines/ui`.
- UI budget thresholds (defaults in `tests/ui-regression-runner.js`) are met:
- sample: crossings <= `1`, overlaps <= `1`, detour <= `3.6`
- drag: crossings <= `3`, overlaps <= `3`, detour <= `3.5`
- drag+tidy: crossings <= `2`, overlaps <= `2`, detour <= `4.5`
- dense fixture: crossings <= `2`, overlaps <= `2`, detour <= `4.2`
- Machine-readable report generated:
- `output/playwright/ui-metrics-report.json`
3. Interaction reliability
- Selection/deselection/isolate/reset flow verified.
- Undo/redo parity verified for component, pin, net, and symbol edits.
4. API/MCP compatibility
- `api_version`/`schema_version` values present and documented.
- Compile/analyze envelopes remain backward compatible (additive policy).
## GA Gates
1. Accessibility
- Core workflows keyboard-operable.
- WCAG AA contrast on primary controls/text.
2. Responsive UX
- Usable at 1280x720 and 1440x900 without clipping critical controls.
3. Schematic readability
- No component-wire overlaps from auto layout/routing.
- Label overlap count near-zero on benchmark fixtures.
4. Operational readiness
- Rate limiting + auth + health checks validated.
- Error telemetry includes structured codes and context.
5. Data durability
- Save/load/restore and JSON roundtrip validated.
- MCP UI bundle + tool endpoints verified end-to-end.
## CI Mapping
- Always required:
- syntax checks
- `npm test`
- `npm run test:ui`
- verify `output/playwright/ui-metrics-report.json` was produced
- Release candidate required:
- checklist completion in `docs/release-checklist.md`
- intentional baseline updates reviewed and approved
+13
View File
@@ -1,6 +1,10 @@
# Schemeta Release Checklist
Use this checklist before cutting a release tag.
Reference docs:
- `docs/quality-gates.md`
- `docs/phase4-execution-plan.md`
- `docs/phase5-execution-plan.md`
## Pre-merge
@@ -11,6 +15,9 @@ Use this checklist before cutting a release tag.
## Validation Gates
- [ ] `npm test` passes.
- [ ] `npm run test:ui` passes.
- [ ] `npm run phase8:cutover:check` passes (for React-first cutover candidates).
- [ ] Beta quality gates in `docs/quality-gates.md` are met.
- [ ] Core smoke flow tested in UI:
- [ ] Load sample
- [ ] Edit component/pin/net/symbol
@@ -22,8 +29,11 @@ Use this checklist before cutting a release tag.
## Visual Quality
- [ ] Representative circuits reviewed for routing readability.
- [ ] Visual baselines updated intentionally (`tests/baselines/ui`) and screenshot diff checks pass.
- [ ] Labels remain legible at common zoom levels.
- [ ] No major overlap/crossing regressions vs previous release baseline.
- [ ] UI metrics report generated (`output/playwright/ui-metrics-report.json`).
- [ ] Sample/drag/tidy/dense fixture all meet the thresholds in `docs/quality-gates.md`.
## Security / Operations
@@ -35,6 +45,7 @@ Use this checklist before cutting a release tag.
- [ ] `CORS_ORIGIN`
- [ ] Rate limiting behavior manually validated.
- [ ] Health endpoint checked in target environment.
- [ ] Structured error telemetry checked for compile/analyze failures.
## Release Artifacts
@@ -42,3 +53,5 @@ Use this checklist before cutting a release tag.
- [ ] `api_version` and `schema_version` changes reviewed/documented.
- [ ] Changelog/release notes generated with notable UX/compat changes.
- [ ] Tag pushed and release announcement links to milestone/issues.
- [ ] GA gates in `docs/quality-gates.md` confirmed complete.
- [ ] Attach `output/phase8/cutover-check-report.json` for release evidence.
+151
View File
@@ -0,0 +1,151 @@
{
"meta": {
"title": "Electret mic + NPN preamp -> ESP32 ADC (dense analog)",
"version": "1.0"
},
"symbols": {
"electret_mic_2pin": {
"symbol_id": "electret_mic_2pin",
"category": "analog",
"body": { "width": 90, "height": 56 },
"pins": [
{ "name": "MIC+", "number": "1", "side": "right", "offset": 20, "type": "analog" },
{ "name": "MIC-", "number": "2", "side": "right", "offset": 38, "type": "ground" }
]
},
"npn_bjt_generic": {
"symbol_id": "npn_bjt_generic",
"category": "analog",
"body": { "width": 92, "height": 74 },
"pins": [
{ "name": "B", "number": "1", "side": "left", "offset": 37, "type": "analog" },
{ "name": "C", "number": "2", "side": "top", "offset": 46, "type": "analog" },
{ "name": "E", "number": "3", "side": "bottom", "offset": 46, "type": "analog" }
]
},
"mcu_adc_1pin": {
"symbol_id": "mcu_adc_1pin",
"category": "generic",
"body": { "width": 126, "height": 64 },
"pins": [
{ "name": "ADC_IN", "number": "1", "side": "left", "offset": 32, "type": "analog" },
{ "name": "3V3", "number": "2", "side": "top", "offset": 32, "type": "power_in" },
{ "name": "GND", "number": "3", "side": "bottom", "offset": 32, "type": "ground" }
]
}
},
"instances": [
{ "ref": "V1", "part": "connector", "properties": { "value": "3.3V/GND source" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } },
{ "ref": "M1", "symbol": "electret_mic_2pin", "properties": { "value": "Electret mic" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } },
{ "ref": "Q1", "symbol": "npn_bjt_generic", "properties": { "value": "2N3904" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } },
{ "ref": "R1", "part": "resistor", "properties": { "value": "4.7k", "role": "mic bias" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } },
{ "ref": "C1", "part": "capacitor", "properties": { "value": "1uF", "role": "mic AC coupling" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } },
{ "ref": "R2", "part": "resistor", "properties": { "value": "220k", "role": "base bias top" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } },
{ "ref": "R3", "part": "resistor", "properties": { "value": "100k", "role": "base bias bottom" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } },
{ "ref": "RC", "part": "resistor", "properties": { "value": "47k", "role": "collector resistor" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } },
{ "ref": "RE", "part": "resistor", "properties": { "value": "1k", "role": "emitter resistor" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } },
{ "ref": "C2", "part": "capacitor", "properties": { "value": "1uF", "role": "output AC coupling" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } },
{ "ref": "R4", "part": "resistor", "properties": { "value": "100k", "role": "ADC mid-rail top" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } },
{ "ref": "R5", "part": "resistor", "properties": { "value": "100k", "role": "ADC mid-rail bottom" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } },
{ "ref": "C3", "part": "capacitor", "properties": { "value": "100nF", "role": "ADC mid-rail filter" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } },
{ "ref": "C4", "part": "capacitor", "properties": { "value": "100nF", "role": "local decoupling" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } },
{ "ref": "U1", "symbol": "mcu_adc_1pin", "properties": { "value": "ESP32-S3 (ADC pin)" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } }
],
"nets": [
{
"name": "3V3",
"class": "power",
"nodes": [
{ "ref": "V1", "pin": "3V3" },
{ "ref": "R1", "pin": "1" },
{ "ref": "R2", "pin": "1" },
{ "ref": "RC", "pin": "1" },
{ "ref": "R4", "pin": "1" },
{ "ref": "C4", "pin": "1" },
{ "ref": "U1", "pin": "3V3" }
]
},
{
"name": "GND",
"class": "ground",
"nodes": [
{ "ref": "V1", "pin": "GND" },
{ "ref": "M1", "pin": "MIC-" },
{ "ref": "R3", "pin": "2" },
{ "ref": "RE", "pin": "2" },
{ "ref": "R5", "pin": "2" },
{ "ref": "C3", "pin": "2" },
{ "ref": "C4", "pin": "2" },
{ "ref": "U1", "pin": "GND" }
]
},
{
"name": "MIC_BIAS",
"class": "analog",
"nodes": [
{ "ref": "R1", "pin": "2" },
{ "ref": "M1", "pin": "MIC+" },
{ "ref": "C1", "pin": "1" }
]
},
{
"name": "BASE_NODE",
"class": "analog",
"nodes": [
{ "ref": "C1", "pin": "2" },
{ "ref": "R2", "pin": "2" },
{ "ref": "R3", "pin": "1" },
{ "ref": "Q1", "pin": "B" }
]
},
{
"name": "COLLECTOR_NODE",
"class": "analog",
"nodes": [
{ "ref": "Q1", "pin": "C" },
{ "ref": "RC", "pin": "2" },
{ "ref": "C2", "pin": "1" }
]
},
{
"name": "EMITTER_NODE",
"class": "analog",
"nodes": [
{ "ref": "Q1", "pin": "E" },
{ "ref": "RE", "pin": "1" }
]
},
{
"name": "ADC_MID",
"class": "analog",
"nodes": [
{ "ref": "R4", "pin": "2" },
{ "ref": "R5", "pin": "1" },
{ "ref": "C3", "pin": "1" },
{ "ref": "C2", "pin": "2" },
{ "ref": "U1", "pin": "ADC_IN" }
]
}
],
"constraints": {
"groups": [
{
"name": "MicFrontEndCluster",
"members": ["M1", "R1", "C1", "Q1", "R2", "R3", "RC", "RE", "C4"],
"layout": "cluster"
},
{
"name": "ADCBiasCluster",
"members": ["R4", "R5", "C3", "C2", "U1"],
"layout": "cluster"
}
],
"near": [
{ "component": "C4", "target_pin": { "ref": "Q1", "pin": "C" } },
{ "component": "C3", "target_pin": { "ref": "U1", "pin": "ADC_IN" } }
]
},
"annotations": [
{ "text": "Dense analog frontend + ADC bias test case." }
]
}
+8 -3
View File
@@ -80,10 +80,15 @@
"constraints": {
"groups": [
{ "name": "power_stage", "members": ["U4"], "layout": "cluster" },
{ "name": "compute", "members": ["U1", "U2"], "layout": "cluster" }
{ "name": "compute", "members": ["U1"], "layout": "cluster" },
{ "name": "audio_out", "members": ["U2", "U3"], "layout": "cluster" }
],
"alignment": [{ "left_of": "U1", "right_of": "U2" }],
"near": [{ "component": "U2", "target_pin": { "ref": "U1", "pin": "GPIO5" } }]
"alignment": [
{ "left_of": "U4", "right_of": "U1" },
{ "left_of": "U1", "right_of": "U2" },
{ "left_of": "U2", "right_of": "U3" }
],
"near": []
},
"annotations": [
{ "text": "I2S audio chain" }
+81
View File
@@ -0,0 +1,81 @@
{
"meta": {
"title": "I2C Sensor Hub",
"version": "1.0"
},
"symbols": {
"mcu": {
"symbol_id": "mcu",
"category": "microcontroller",
"body": { "width": 180, "height": 220 },
"pins": [
{ "name": "3V3", "number": "1", "side": "left", "offset": 24, "type": "power_in" },
{ "name": "GND", "number": "2", "side": "left", "offset": 56, "type": "ground" },
{ "name": "SCL", "number": "3", "side": "right", "offset": 48, "type": "bidirectional" },
{ "name": "SDA", "number": "4", "side": "right", "offset": 78, "type": "bidirectional" },
{ "name": "INT1", "number": "5", "side": "right", "offset": 122, "type": "input" },
{ "name": "INT2", "number": "6", "side": "right", "offset": 152, "type": "input" }
]
},
"i2c_sensor": {
"symbol_id": "i2c_sensor",
"category": "sensor",
"body": { "width": 140, "height": 120 },
"pins": [
{ "name": "3V3", "number": "1", "side": "left", "offset": 18, "type": "power_in" },
{ "name": "GND", "number": "2", "side": "left", "offset": 44, "type": "ground" },
{ "name": "SCL", "number": "3", "side": "left", "offset": 70, "type": "bidirectional" },
{ "name": "SDA", "number": "4", "side": "left", "offset": 96, "type": "bidirectional" },
{ "name": "INT", "number": "5", "side": "right", "offset": 58, "type": "output" }
]
},
"power_source": {
"symbol_id": "power_source",
"category": "power",
"body": { "width": 130, "height": 90 },
"pins": [
{ "name": "3V3", "number": "1", "side": "right", "offset": 26, "type": "power_out" },
{ "name": "GND", "number": "2", "side": "right", "offset": 56, "type": "ground" }
]
}
},
"instances": [
{ "ref": "U1", "symbol": "mcu", "properties": { "value": "ESP32-S3" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } },
{ "ref": "U2", "symbol": "i2c_sensor", "properties": { "value": "IMU" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } },
{ "ref": "U3", "symbol": "i2c_sensor", "properties": { "value": "BME280" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } },
{ "ref": "U4", "symbol": "i2c_sensor", "properties": { "value": "Mag" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } },
{ "ref": "R1", "part": "resistor", "properties": { "value": "4.7k" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } },
{ "ref": "R2", "part": "resistor", "properties": { "value": "4.7k" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } },
{ "ref": "V1", "symbol": "power_source", "properties": { "value": "3V3/GND source" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } }
],
"nets": [
{ "name": "3V3", "class": "power", "nodes": [
{ "ref": "V1", "pin": "3V3" }, { "ref": "U1", "pin": "3V3" }, { "ref": "U2", "pin": "3V3" },
{ "ref": "U3", "pin": "3V3" }, { "ref": "U4", "pin": "3V3" }, { "ref": "R1", "pin": "1" }, { "ref": "R2", "pin": "1" }
] },
{ "name": "GND", "class": "ground", "nodes": [
{ "ref": "V1", "pin": "GND" }, { "ref": "U1", "pin": "GND" }, { "ref": "U2", "pin": "GND" },
{ "ref": "U3", "pin": "GND" }, { "ref": "U4", "pin": "GND" }
] },
{ "name": "I2C_SCL", "class": "clock", "nodes": [
{ "ref": "U1", "pin": "SCL" }, { "ref": "U2", "pin": "SCL" }, { "ref": "U3", "pin": "SCL" },
{ "ref": "U4", "pin": "SCL" }, { "ref": "R1", "pin": "2" }
] },
{ "name": "I2C_SDA", "class": "signal", "nodes": [
{ "ref": "U1", "pin": "SDA" }, { "ref": "U2", "pin": "SDA" }, { "ref": "U3", "pin": "SDA" },
{ "ref": "U4", "pin": "SDA" }, { "ref": "R2", "pin": "2" }
] },
{ "name": "INT1", "class": "signal", "nodes": [ { "ref": "U2", "pin": "INT" }, { "ref": "U1", "pin": "INT1" } ] },
{ "name": "INT2", "class": "signal", "nodes": [ { "ref": "U3", "pin": "INT" }, { "ref": "U1", "pin": "INT2" } ] }
],
"constraints": {
"groups": [
{ "name": "controller", "members": ["U1"], "layout": "cluster" },
{ "name": "sensors", "members": ["U2", "U3", "U4"], "layout": "cluster" },
{ "name": "pullups", "members": ["R1", "R2"], "layout": "cluster" }
]
},
"annotations": [
{ "text": "Shared I2C bus with pull-ups and interrupt lines.", "x": 24, "y": 24 }
]
}
+37
View File
@@ -0,0 +1,37 @@
{
"meta": {
"title": "Dual-Rail Power Tree",
"version": "1.0"
},
"symbols": {},
"instances": [
{ "ref": "J1", "part": "connector", "properties": { "value": "VIN/GND" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } },
{ "ref": "U1", "part": "generic", "properties": { "value": "Buck 12V->5V" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } },
{ "ref": "U2", "part": "generic", "properties": { "value": "LDO 5V->3V3" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } },
{ "ref": "U3", "part": "generic", "properties": { "value": "MCU" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } },
{ "ref": "U4", "part": "generic", "properties": { "value": "RF Module" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } },
{ "ref": "C1", "part": "capacitor", "properties": { "value": "22uF" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } },
{ "ref": "C2", "part": "capacitor", "properties": { "value": "10uF" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } },
{ "ref": "C3", "part": "capacitor", "properties": { "value": "100nF" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } },
{ "ref": "C4", "part": "capacitor", "properties": { "value": "100nF" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } }
],
"nets": [
{ "name": "VIN", "class": "power", "nodes": [ { "ref": "J1", "pin": "1" }, { "ref": "U1", "pin": "VIN" } ] },
{ "name": "5V", "class": "power", "nodes": [ { "ref": "U1", "pin": "VOUT" }, { "ref": "U2", "pin": "VIN" }, { "ref": "C1", "pin": "1" }, { "ref": "C2", "pin": "1" } ] },
{ "name": "3V3", "class": "power", "nodes": [ { "ref": "U2", "pin": "VOUT" }, { "ref": "U3", "pin": "VCC" }, { "ref": "U4", "pin": "VCC" }, { "ref": "C3", "pin": "1" }, { "ref": "C4", "pin": "1" } ] },
{ "name": "GND", "class": "ground", "nodes": [ { "ref": "J1", "pin": "2" }, { "ref": "U1", "pin": "GND" }, { "ref": "U2", "pin": "GND" }, { "ref": "U3", "pin": "GND" }, { "ref": "U4", "pin": "GND" }, { "ref": "C1", "pin": "2" }, { "ref": "C2", "pin": "2" }, { "ref": "C3", "pin": "2" }, { "ref": "C4", "pin": "2" } ] },
{ "name": "SPI_CLK", "class": "clock", "nodes": [ { "ref": "U3", "pin": "SCLK" }, { "ref": "U4", "pin": "SCLK" } ] },
{ "name": "SPI_MOSI", "class": "signal", "nodes": [ { "ref": "U3", "pin": "MOSI" }, { "ref": "U4", "pin": "MOSI" } ] },
{ "name": "SPI_MISO", "class": "signal", "nodes": [ { "ref": "U3", "pin": "MISO" }, { "ref": "U4", "pin": "MISO" } ] }
],
"constraints": {
"groups": [
{ "name": "source", "members": ["J1", "U1", "C1"], "layout": "cluster" },
{ "name": "regulation", "members": ["U2", "C2"], "layout": "cluster" },
{ "name": "load", "members": ["U3", "U4", "C3", "C4"], "layout": "cluster" }
]
},
"annotations": [
{ "text": "Power-chain fixture with SPI branch used for readability QA.", "x": 24, "y": 24 }
]
}
+3
View File
@@ -0,0 +1,3 @@
node_modules
dist
*.tsbuildinfo
+22
View File
@@ -0,0 +1,22 @@
# Schemeta React Frontend (Track A)
Bootstrap React + TypeScript + Vite shell for Schemeta.
## Scripts
- `npm run dev` - start Vite dev server
- `npm run build` - type-check and build production bundle
- `npm run preview` - preview built bundle
- `npm run lint` - TypeScript no-emit check
- `npm run test` - placeholder test command
## API endpoints wired
The app client posts to the existing backend routes without contract changes:
- `POST /compile`
- `POST /analyze`
- `POST /layout/auto`
- `POST /layout/tidy`
Vite dev server proxies these routes to `http://localhost:8787`.
+12
View File
@@ -0,0 +1,12 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Schemeta React</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+24
View File
@@ -0,0 +1,24 @@
{
"name": "schemeta-frontend-react",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"preview": "vite preview",
"lint": "tsc --noEmit -p tsconfig.app.json",
"test": "node -e \"console.log('frontend-react: no tests yet')\""
},
"dependencies": {
"react": "^18.3.1",
"react-dom": "^18.3.1"
},
"devDependencies": {
"@types/react": "^18.3.12",
"@types/react-dom": "^18.3.1",
"@vitejs/plugin-react": "^4.3.1",
"typescript": "^5.5.4",
"vite": "^5.4.0"
}
}
+297
View File
@@ -0,0 +1,297 @@
import { useEffect, useMemo, useState } from "react";
import { analyze, autoLayout, compile, tidyLayout } from "./api/client";
import { CanvasArea } from "./components/CanvasArea";
import { LeftPanel } from "./components/LeftPanel";
import { RightInspector } from "./components/RightInspector";
import { TopBar } from "./components/TopBar";
import type { TopBarStatusTone } from "./components/TopBar";
import sampleFixture from "./fixtures/sample.schemeta.json";
import { useSchemetaActions, useSchemetaSelector } from "./hooks";
import { createSchemetaStore } from "./state";
import type { SchemetaModel } from "./state";
type EndpointActionId = "compile" | "analyze" | "layout-auto" | "layout-tidy";
type LocalActionId = "load-sample" | "reset-sample";
type WorkflowActionId = EndpointActionId | LocalActionId;
type WorkflowAction = {
id: WorkflowActionId;
label: string;
};
const SAMPLE_PAYLOAD = sampleFixture as SchemetaModel;
function getPayloadOrThrow(payload: unknown): SchemetaModel {
if (typeof payload !== "object" || payload === null) {
throw new Error("No model loaded. Run 'Load Sample JSON' first.");
}
return payload as SchemetaModel;
}
function toCompileFromAnalyze(result: Awaited<ReturnType<typeof analyze>>): Record<string, unknown> {
return {
api_version: result.api_version,
schema_version: result.schema_version,
request_id: result.request_id,
ok: result.ok ?? true,
errors: Array.isArray(result.errors) ? result.errors : [],
warnings: Array.isArray(result.warnings) ? result.warnings : [],
topology: result.topology ?? {}
};
}
function sortKeysDeep(value: unknown): unknown {
if (Array.isArray(value)) {
return value.map((item) => sortKeysDeep(item));
}
if (value && typeof value === "object") {
const record = value as Record<string, unknown>;
const sorted = Object.keys(record)
.sort((a, b) => a.localeCompare(b))
.reduce<Record<string, unknown>>((acc, key) => {
acc[key] = sortKeysDeep(record[key]);
return acc;
}, {});
return sorted;
}
return value;
}
export function App() {
const store = useMemo(() => createSchemetaStore({ model: SAMPLE_PAYLOAD }), []);
const actionsApi = useSchemetaActions(store);
const model = useSchemetaSelector(store, (state) => state.model);
const selection = useSchemetaSelector(store, (state) => state.selection);
const compileResult = useSchemetaSelector(store, (state) => state.compileResult);
const lifecycle = useSchemetaSelector(store, (state) => state.lifecycle);
const jsonError = useSchemetaSelector(store, (state) => state.uiFlags.jsonError);
const [jsonEditorText, setJsonEditorText] = useState(() => JSON.stringify(SAMPLE_PAYLOAD, null, 2));
useEffect(() => {
if (model) {
setJsonEditorText(JSON.stringify(model, null, 2));
}
}, [model]);
const lastApiVersion = useSchemetaSelector(store, (state) => {
const apiVersion = state.compileResult && typeof state.compileResult.api_version === "string" ? state.compileResult.api_version : null;
return apiVersion ?? "-";
});
const actions = useMemo<WorkflowAction[]>(
() => [
{ id: "load-sample", label: "Load Sample JSON" },
{ id: "compile", label: "Compile" },
{ id: "analyze", label: "Analyze" },
{ id: "layout-auto", label: "Auto Layout" },
{ id: "layout-tidy", label: "Auto Tidy" },
{ id: "reset-sample", label: "Reset Sample" }
],
[]
);
const status = jsonError
? `JSON parse failed: ${jsonError}`
: lifecycle.isCompiling
? `${lifecycle.lastAction ?? "Working"}...`
: lifecycle.lastError
? `${lifecycle.lastAction ?? "Action"} failed: ${lifecycle.lastError}`
: lifecycle.lastAction
? `${lifecycle.lastAction} complete`
: "Idle";
const statusTone: TopBarStatusTone = jsonError
? "error"
: lifecycle.isCompiling
? "busy"
: lifecycle.lastError
? "error"
: lifecycle.lastAction
? "success"
: "idle";
async function runAction(actionId: WorkflowActionId) {
const action = actions.find((item) => item.id === actionId);
if (!action) {
return;
}
actionsApi.beginCompile(action.label);
try {
if (action.id === "load-sample" || action.id === "reset-sample") {
const parsed = actionsApi.applyJsonText(JSON.stringify(SAMPLE_PAYLOAD));
if (!parsed.ok) {
throw new Error(parsed.error);
}
actionsApi.setCompileResult(null);
actionsApi.setSelection({ selectedRefs: [], selectedNet: null, selectedPin: null });
actionsApi.setViewport({ scale: 1, panX: 40, panY: 40 });
actionsApi.completeCompile(action.label);
return;
}
const payload = getPayloadOrThrow(store.getState().model);
switch (action.id) {
case "compile":
{
const result = await compile(payload, { preserve_placement: true });
actionsApi.setCompileResult(result);
}
break;
case "analyze":
{
const result = await analyze(payload);
actionsApi.setCompileResult(toCompileFromAnalyze(result));
}
break;
case "layout-auto":
{
const result = await autoLayout(payload);
if (result.model) {
actionsApi.setModel(result.model);
}
if (result.compile) {
actionsApi.setCompileResult(result.compile);
}
}
break;
case "layout-tidy":
{
const result = await tidyLayout(payload);
if (result.model) {
actionsApi.setModel(result.model);
}
if (result.compile) {
actionsApi.setCompileResult(result.compile);
}
}
break;
}
actionsApi.completeCompile(action.label);
} catch (err) {
actionsApi.failCompile(action.label, err);
}
}
function applyJsonFromEditor() {
const parsed = actionsApi.applyJsonText(jsonEditorText);
if (!parsed.ok) {
actionsApi.failCompile("apply-json", parsed.error);
return;
}
actionsApi.completeCompile("apply-json");
}
async function validateJsonEditor() {
const parsed = actionsApi.applyJsonText(jsonEditorText);
if (!parsed.ok) {
actionsApi.failCompile("validate-json", parsed.error);
return;
}
const modelCandidate = store.getState().model;
if (!modelCandidate) {
actionsApi.failCompile("validate-json", "No model loaded");
return;
}
actionsApi.beginCompile("validate-json");
try {
const analyzed = await analyze(modelCandidate);
actionsApi.setCompileResult(toCompileFromAnalyze(analyzed));
actionsApi.completeCompile("validate-json");
} catch (error) {
actionsApi.failCompile("validate-json", error);
}
}
function formatJsonEditor() {
const parsed = actionsApi.applyJsonText(jsonEditorText);
if (!parsed.ok) {
actionsApi.failCompile("format-json", parsed.error);
return;
}
const next = store.getState().model;
if (next) {
setJsonEditorText(JSON.stringify(next, null, 2));
}
actionsApi.completeCompile("format-json");
}
function sortJsonEditorKeys() {
try {
const parsed = JSON.parse(jsonEditorText);
const sorted = sortKeysDeep(parsed);
setJsonEditorText(JSON.stringify(sorted, null, 2));
actionsApi.completeCompile("sort-json");
} catch (error) {
actionsApi.failCompile("sort-json", error);
}
}
async function copyReproJson() {
try {
await navigator.clipboard.writeText(jsonEditorText);
actionsApi.completeCompile("copy-repro");
} catch {
actionsApi.failCompile("copy-repro", "Clipboard write failed");
}
}
return (
<div className="app-shell">
<TopBar
title="React Frontend Skeleton"
actions={actions.map((action) => ({
id: action.id,
label: action.label,
onClick: () => {
void runAction(action.id);
},
disabled: lifecycle.isCompiling
}))}
statusMessage={status}
statusTone={statusTone}
apiVersion={lastApiVersion}
/>
<div className="workspace-grid">
<LeftPanel
model={model}
selection={selection}
onSelectInstance={(ref) =>
actionsApi.setSelection({
selectedRefs: selection.selectedRefs.includes(ref) ? [] : [ref],
selectedNet: null,
selectedPin: null
})
}
onSelectNet={(name) =>
actionsApi.setSelection({
selectedRefs: [],
selectedNet: selection.selectedNet === name ? null : name,
selectedPin: null
})
}
/>
<CanvasArea store={store} />
<RightInspector
model={model}
selection={selection}
compileResult={compileResult}
jsonText={jsonEditorText}
jsonError={jsonError}
onJsonTextChange={setJsonEditorText}
onApplyJson={applyJsonFromEditor}
onValidateJson={() => {
void validateJsonEditor();
}}
onFormatJson={formatJsonEditor}
onSortJson={sortJsonEditorKeys}
onCopyRepro={() => {
void copyReproJson();
}}
/>
</div>
</div>
);
}
+48
View File
@@ -0,0 +1,48 @@
import type {
AnalyzeResponse,
CompileResponse,
LayoutActionResponse,
SchemetaRequest
} from "./types";
async function postJson<TResponse>(path: string, body: unknown): Promise<TResponse> {
const response = await fetch(path, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(body)
});
const data = (await response.json()) as TResponse & {
error?: { message?: string };
message?: string;
};
if (!response.ok) {
const message = data?.error?.message ?? data?.message ?? `Request failed with status ${response.status}`;
throw new Error(message);
}
return data;
}
export function compile(payload: unknown, options: Record<string, unknown> = {}): Promise<CompileResponse> {
const body: SchemetaRequest = { payload, options };
return postJson<CompileResponse>("/compile", body);
}
export function analyze(payload: unknown, options: Record<string, unknown> = {}): Promise<AnalyzeResponse> {
const body: SchemetaRequest = { payload, options };
return postJson<AnalyzeResponse>("/analyze", body);
}
export function autoLayout(payload: unknown, options: Record<string, unknown> = {}): Promise<LayoutActionResponse> {
const body: SchemetaRequest = { payload, options };
return postJson<LayoutActionResponse>("/layout/auto", body);
}
export function tidyLayout(payload: unknown, options: Record<string, unknown> = {}): Promise<LayoutActionResponse> {
const body: SchemetaRequest = { payload, options };
return postJson<LayoutActionResponse>("/layout/tidy", body);
}
+38
View File
@@ -0,0 +1,38 @@
export type SchemetaRequest<TPayload = unknown, TOptions = Record<string, unknown>> = {
payload: TPayload;
options?: TOptions;
};
export type SchemetaEnvelope = {
api_version?: string;
schema_version?: string;
request_id?: string;
};
export type CompileResponse = SchemetaEnvelope & {
ok?: boolean;
errors?: unknown[];
warnings?: unknown[];
svg?: string;
layout?: {
width?: number;
height?: number;
placed?: Array<Record<string, unknown>>;
};
layout_metrics?: Record<string, number>;
topology?: Record<string, unknown>;
focus_map?: Record<string, unknown>;
};
export type AnalyzeResponse = SchemetaEnvelope & {
ok?: boolean;
errors?: unknown[];
warnings?: unknown[];
topology?: Record<string, unknown>;
};
export type LayoutActionResponse = SchemetaEnvelope & {
ok?: boolean;
model?: Record<string, unknown>;
compile?: CompileResponse;
};
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,98 @@
import { useMemo, useState } from "react";
import type { SchemetaModel, SelectionSlice } from "../state";
type LeftPanelProps = {
model: SchemetaModel | null;
selection: SelectionSlice;
onSelectInstance: (ref: string) => void;
onSelectNet: (name: string) => void;
};
type NetRow = {
id: string;
label: string;
};
function asNetLabel(net: Record<string, unknown>, index: number): NetRow {
const name = typeof net.name === "string" && net.name.length > 0 ? net.name : null;
const id = name ?? `net-${index + 1}`;
return {
id,
label: name ?? `Net ${index + 1}`
};
}
export function LeftPanel({ model, selection, onSelectInstance, onSelectNet }: LeftPanelProps) {
const [filterText, setFilterText] = useState("");
const filter = filterText.trim().toLowerCase();
const instances = model?.instances ?? [];
const netsRaw = (model?.nets ?? []).filter((item): item is Record<string, unknown> => typeof item === "object" && item !== null);
const nets = netsRaw.map(asNetLabel);
const filteredInstances = useMemo(
() =>
instances.filter((instance) => {
if (!filter) {
return true;
}
const symbol = typeof instance.symbol === "string" ? instance.symbol : "";
const part = typeof instance.part === "string" ? instance.part : "";
return `${instance.ref} ${symbol} ${part}`.toLowerCase().includes(filter);
}),
[filter, instances]
);
const filteredNets = useMemo(
() =>
nets.filter((net) => {
if (!filter) {
return true;
}
return net.label.toLowerCase().includes(filter) || net.id.toLowerCase().includes(filter);
}),
[filter, nets]
);
return (
<aside className="panel panel--left" aria-label="Left panel">
<h2 className="panel__title">Model Browser</h2>
<input
aria-label="Filter instances and nets"
type="search"
value={filterText}
onChange={(event) => setFilterText(event.target.value)}
placeholder="Filter refs, parts, nets..."
/>
<h3>Instances ({filteredInstances.length})</h3>
<ul>
{filteredInstances.map((instance) => {
const isSelected = selection.selectedRefs.includes(instance.ref);
const descriptor = instance.symbol ?? instance.part ?? "component";
return (
<li key={instance.ref}>
<button type="button" onClick={() => onSelectInstance(instance.ref)}>
{isSelected ? "[x]" : "[ ]"} {instance.ref} - {descriptor}
</button>
</li>
);
})}
</ul>
<h3>Nets ({filteredNets.length})</h3>
<ul>
{filteredNets.map((net) => {
const isSelected = selection.selectedNet === net.id;
return (
<li key={net.id}>
<button type="button" onClick={() => onSelectNet(net.id)}>
{isSelected ? "[x]" : "[ ]"} {net.label}
</button>
</li>
);
})}
</ul>
</aside>
);
}
@@ -0,0 +1,120 @@
import type { SchemetaModel, SelectionSlice } from "../state";
type RightInspectorProps = {
model: SchemetaModel | null;
selection: SelectionSlice;
compileResult: unknown | null;
jsonText: string;
jsonError: string | null;
onJsonTextChange: (value: string) => void;
onApplyJson: () => void;
onValidateJson: () => void;
onFormatJson: () => void;
onSortJson: () => void;
onCopyRepro: () => void;
};
function asRecord(value: unknown): Record<string, unknown> | null {
if (typeof value !== "object" || value === null) {
return null;
}
return value as Record<string, unknown>;
}
function asList(value: unknown): unknown[] {
return Array.isArray(value) ? value : [];
}
function toSnippet(value: unknown, fallback: string): string {
if (value == null) {
return fallback;
}
if (typeof value === "string") {
return value;
}
try {
return JSON.stringify(value, null, 2);
} catch {
return fallback;
}
}
export function RightInspector({
model,
selection,
compileResult,
jsonText,
jsonError,
onJsonTextChange,
onApplyJson,
onValidateJson,
onFormatJson,
onSortJson,
onCopyRepro
}: RightInspectorProps) {
const selectedRef = selection.selectedRefs[0] ?? null;
const selectedInstance = selectedRef ? (model?.instances ?? []).find((instance) => instance.ref === selectedRef) : null;
const compile = asRecord(compileResult);
const errors = asList(compile?.errors);
const warnings = asList(compile?.warnings);
const topology = compile?.topology;
const layoutMetrics = compile?.layout_metrics;
return (
<aside className="panel panel--right" aria-label="Right inspector">
<h2 className="panel__title">Selection Summary</h2>
<p className="panel__body">Refs: {selection.selectedRefs.length > 0 ? selection.selectedRefs.join(", ") : "None"}</p>
<p className="panel__body">Net: {selection.selectedNet ?? "None"}</p>
<p className="panel__body">
Pin: {selection.selectedPin ? `${selection.selectedPin.ref}.${selection.selectedPin.pin}` : "None"}
</p>
<p className="panel__body">
Focused Component: {selectedInstance ? `${selectedInstance.ref} (${selectedInstance.symbol ?? selectedInstance.part ?? "component"})` : "None"}
</p>
<h2 className="panel__title">Diagnostics</h2>
<p className="panel__body">Errors: {errors.length}</p>
<p className="panel__body">Warnings: {warnings.length}</p>
<pre>{toSnippet(errors[0], "No error diagnostics yet.")}</pre>
<pre>{toSnippet(warnings[0], "No warning diagnostics yet.")}</pre>
<h2 className="panel__title">Topology Snippet</h2>
<pre>{toSnippet(topology, "No topology available yet.")}</pre>
<h2 className="panel__title">Layout Metrics</h2>
<pre>{toSnippet(layoutMetrics, "No layout metrics available yet.")}</pre>
<h2 className="panel__title">JSON Editor</h2>
<div className="json-tools">
<button type="button" onClick={onValidateJson}>
Validate
</button>
<button type="button" onClick={onFormatJson}>
Format
</button>
<button type="button" onClick={onSortJson}>
Sort Keys
</button>
<button type="button" onClick={onCopyRepro}>
Copy Repro
</button>
<button type="button" onClick={onApplyJson}>
Apply JSON
</button>
</div>
<textarea
className="json-editor"
value={jsonText}
onChange={(event) => onJsonTextChange(event.target.value)}
spellCheck={false}
aria-label="Schematic JSON editor"
/>
<p className={`panel__body ${jsonError ? "json-status--error" : "json-status--ok"}`}>
{jsonError ? `JSON error: ${jsonError}` : "JSON ready"}
</p>
</aside>
);
}
+37
View File
@@ -0,0 +1,37 @@
export type TopBarAction = {
id: string;
label: string;
onClick: () => void;
disabled?: boolean;
};
export type TopBarStatusTone = "idle" | "busy" | "success" | "error";
type TopBarProps = {
title: string;
actions: TopBarAction[];
statusMessage: string;
statusTone: TopBarStatusTone;
apiVersion: string;
};
export function TopBar({ title, actions, statusMessage, statusTone, apiVersion }: TopBarProps) {
return (
<header className="topbar" role="banner">
<div className="topbar__brand">Schemeta</div>
<div className="topbar__title">{title}</div>
<div className="topbar__actions" role="toolbar" aria-label="Workflow actions">
{actions.map((action) => (
<button key={action.id} type="button" onClick={action.onClick} disabled={action.disabled === true}>
{action.label}
</button>
))}
</div>
<div className="topbar__meta">
<span>Status: {statusMessage}</span>
<span>Level: {statusTone}</span>
<span>API: {apiVersion}</span>
</div>
</header>
);
}
@@ -0,0 +1,37 @@
{
"meta": {
"title": "Dual-Rail Power Tree",
"version": "1.0"
},
"symbols": {},
"instances": [
{ "ref": "J1", "part": "connector", "properties": { "value": "VIN/GND" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } },
{ "ref": "U1", "part": "generic", "properties": { "value": "Buck 12V->5V" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } },
{ "ref": "U2", "part": "generic", "properties": { "value": "LDO 5V->3V3" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } },
{ "ref": "U3", "part": "generic", "properties": { "value": "MCU" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } },
{ "ref": "U4", "part": "generic", "properties": { "value": "RF Module" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } },
{ "ref": "C1", "part": "capacitor", "properties": { "value": "22uF" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } },
{ "ref": "C2", "part": "capacitor", "properties": { "value": "10uF" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } },
{ "ref": "C3", "part": "capacitor", "properties": { "value": "100nF" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } },
{ "ref": "C4", "part": "capacitor", "properties": { "value": "100nF" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } }
],
"nets": [
{ "name": "VIN", "class": "power", "nodes": [ { "ref": "J1", "pin": "1" }, { "ref": "U1", "pin": "VIN" } ] },
{ "name": "5V", "class": "power", "nodes": [ { "ref": "U1", "pin": "VOUT" }, { "ref": "U2", "pin": "VIN" }, { "ref": "C1", "pin": "1" }, { "ref": "C2", "pin": "1" } ] },
{ "name": "3V3", "class": "power", "nodes": [ { "ref": "U2", "pin": "VOUT" }, { "ref": "U3", "pin": "VCC" }, { "ref": "U4", "pin": "VCC" }, { "ref": "C3", "pin": "1" }, { "ref": "C4", "pin": "1" } ] },
{ "name": "GND", "class": "ground", "nodes": [ { "ref": "J1", "pin": "2" }, { "ref": "U1", "pin": "GND" }, { "ref": "U2", "pin": "GND" }, { "ref": "U3", "pin": "GND" }, { "ref": "U4", "pin": "GND" }, { "ref": "C1", "pin": "2" }, { "ref": "C2", "pin": "2" }, { "ref": "C3", "pin": "2" }, { "ref": "C4", "pin": "2" } ] },
{ "name": "SPI_CLK", "class": "clock", "nodes": [ { "ref": "U3", "pin": "SCLK" }, { "ref": "U4", "pin": "SCLK" } ] },
{ "name": "SPI_MOSI", "class": "signal", "nodes": [ { "ref": "U3", "pin": "MOSI" }, { "ref": "U4", "pin": "MOSI" } ] },
{ "name": "SPI_MISO", "class": "signal", "nodes": [ { "ref": "U3", "pin": "MISO" }, { "ref": "U4", "pin": "MISO" } ] }
],
"constraints": {
"groups": [
{ "name": "source", "members": ["J1", "U1", "C1"], "layout": "cluster" },
{ "name": "regulation", "members": ["U2", "C2"], "layout": "cluster" },
{ "name": "load", "members": ["U3", "U4", "C3", "C4"], "layout": "cluster" }
]
},
"annotations": [
{ "text": "Power-chain fixture with SPI branch used for readability QA.", "x": 24, "y": 24 }
]
}
+1
View File
@@ -0,0 +1 @@
export { useSchemetaActions, useSchemetaSelector, useSchemetaStoreState } from "./useSchemetaStore";
@@ -0,0 +1,17 @@
import { useMemo, useSyncExternalStore } from "react";
import type { SchemetaStore, StoreState } from "../state";
type Selector<TSelected> = (state: StoreState) => TSelected;
export function useSchemetaStoreState(store: SchemetaStore): StoreState {
return useSyncExternalStore(store.subscribe, store.getState, store.getState);
}
export function useSchemetaSelector<TSelected>(store: SchemetaStore, selector: Selector<TSelected>): TSelected {
const state = useSchemetaStoreState(store);
return useMemo(() => selector(state), [selector, state]);
}
export function useSchemetaActions(store: SchemetaStore): SchemetaStore["actions"] {
return store.actions;
}
+10
View File
@@ -0,0 +1,10 @@
import React from "react";
import ReactDOM from "react-dom/client";
import { App } from "./App";
import "./styles.css";
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
<React.StrictMode>
<App />
</React.StrictMode>
);
+1
View File
@@ -0,0 +1 @@
export * from "./store.js";
+1
View File
@@ -0,0 +1 @@
export { createInitialState, createSchemetaStore } from "./store.js";
+116
View File
@@ -0,0 +1,116 @@
export type SchemetaPlacement = {
x: number | null;
y: number | null;
rotation?: number;
locked?: boolean;
};
export type SchemetaInstance = {
ref: string;
symbol?: string;
part?: string;
properties?: Record<string, unknown>;
placement: SchemetaPlacement;
};
export type SchemetaModel = {
meta?: Record<string, unknown>;
symbols?: Record<string, unknown>;
instances: SchemetaInstance[];
nets?: Array<Record<string, unknown>>;
constraints?: Record<string, unknown>;
annotations?: Array<Record<string, unknown>>;
};
export type CompileResult = {
api_version?: string;
schema_version?: string;
request_id?: string;
ok: boolean;
errors: Array<Record<string, unknown>>;
warnings: Array<Record<string, unknown>>;
layout?: Record<string, unknown>;
layout_metrics?: Record<string, unknown>;
render_mode_used?: string;
svg?: string;
};
export type SelectionSlice = {
selectedRefs: string[];
selectedNet: string | null;
selectedPin: { ref: string; pin: string } | null;
};
export type ViewportSlice = {
scale: number;
panX: number;
panY: number;
};
export type UiFlagsSlice = {
showLabels: boolean;
isolateNet: boolean;
isolateComponent: boolean;
renderMode: string;
jsonError: string | null;
};
export type LifecycleSlice = {
isCompiling: boolean;
lastError: string | null;
lastAction: string | null;
};
export type StateSnapshot = {
model: SchemetaModel | null;
compileResult: CompileResult | null;
selection: SelectionSlice;
viewport: ViewportSlice;
uiFlags: UiFlagsSlice;
};
export type StoreState = {
model: SchemetaModel | null;
compileResult: CompileResult | null;
selection: SelectionSlice;
viewport: ViewportSlice;
uiFlags: UiFlagsSlice;
lifecycle: LifecycleSlice;
history: {
past: Array<{ label: string; snapshot: StateSnapshot }>;
future: Array<{ label: string; snapshot: StateSnapshot }>;
limit: number;
};
transaction: {
active: boolean;
label: string | null;
before: StateSnapshot | null;
dirty: boolean;
};
};
export type SchemetaStore = {
getState(): StoreState;
subscribe(listener: (next: StoreState, prev: StoreState, action: string) => void): () => void;
actions: {
setModel(model: unknown): void;
setCompileResult(compileResult: unknown): void;
setSelection(selection: Partial<SelectionSlice>): void;
moveComponent(ref: string, placement: Partial<SchemetaPlacement>): void;
setViewport(viewport: Partial<ViewportSlice>): void;
setUiFlags(uiFlags: Partial<UiFlagsSlice>): void;
setLifecycle(lifecycle: Partial<LifecycleSlice>): void;
beginCompile(action: string): void;
completeCompile(action: string): void;
failCompile(action: string, error: unknown): void;
applyJsonText(jsonText: string): { ok: true } | { ok: false; error: string };
beginTransaction(label?: string): boolean;
commitTransaction(): boolean;
rollbackTransaction(): boolean;
undo(): void;
redo(): void;
};
};
export function createInitialState(overrides?: Partial<StoreState>): StoreState;
export function createSchemetaStore(initialState?: Partial<StoreState>): SchemetaStore;
+718
View File
@@ -0,0 +1,718 @@
const DEFAULT_HISTORY_LIMIT = 80;
/**
* @typedef {Object} SchemetaPlacement
* @property {number | null} x
* @property {number | null} y
* @property {number} [rotation]
* @property {boolean} [locked]
*/
/**
* @typedef {Object} SchemetaInstance
* @property {string} ref
* @property {string} [symbol]
* @property {string} [part]
* @property {Record<string, unknown>} [properties]
* @property {SchemetaPlacement} placement
*/
/**
* @typedef {Object} SchemetaModel
* @property {Record<string, unknown>} [meta]
* @property {Record<string, unknown>} [symbols]
* @property {SchemetaInstance[]} instances
* @property {Array<Record<string, unknown>>} [nets]
* @property {Record<string, unknown>} [constraints]
* @property {Array<Record<string, unknown>>} [annotations]
*/
/**
* @typedef {Object} CompileResult
* @property {string} [api_version]
* @property {string} [schema_version]
* @property {string} [request_id]
* @property {boolean} ok
* @property {Array<Record<string, unknown>>} errors
* @property {Array<Record<string, unknown>>} warnings
* @property {Record<string, unknown>} [layout]
* @property {Record<string, unknown>} [layout_metrics]
* @property {string} [render_mode_used]
* @property {string} [svg]
*/
/**
* @typedef {{ ref: string, pin: string } | null} SelectedPin
*/
/**
* @typedef {Object} SelectionSlice
* @property {string[]} selectedRefs
* @property {string | null} selectedNet
* @property {SelectedPin} selectedPin
*/
/**
* @typedef {Object} ViewportSlice
* @property {number} scale
* @property {number} panX
* @property {number} panY
*/
/**
* @typedef {Object} UiFlagsSlice
* @property {boolean} showLabels
* @property {boolean} isolateNet
* @property {boolean} isolateComponent
* @property {string} renderMode
* @property {string | null} jsonError
*/
/**
* @typedef {Object} LifecycleSlice
* @property {boolean} isCompiling
* @property {string | null} lastError
* @property {string | null} lastAction
*/
/**
* @typedef {Object} StateSnapshot
* @property {SchemetaModel | null} model
* @property {CompileResult | null} compileResult
* @property {SelectionSlice} selection
* @property {ViewportSlice} viewport
* @property {UiFlagsSlice} uiFlags
*/
/**
* @typedef {Object} HistoryEntry
* @property {string} label
* @property {StateSnapshot} snapshot
*/
/**
* @typedef {Object} StoreState
* @property {SchemetaModel | null} model
* @property {CompileResult | null} compileResult
* @property {SelectionSlice} selection
* @property {ViewportSlice} viewport
* @property {UiFlagsSlice} uiFlags
* @property {LifecycleSlice} lifecycle
* @property {{ past: HistoryEntry[], future: HistoryEntry[], limit: number }} history
* @property {{ active: boolean, label: string | null, before: StateSnapshot | null, dirty: boolean }} transaction
*/
/**
* @param {unknown} value
* @returns {any}
*/
function deepClone(value) {
if (typeof structuredClone === "function") {
return structuredClone(value);
}
return JSON.parse(JSON.stringify(value));
}
/**
* @param {SelectionSlice | Partial<SelectionSlice>} selection
* @returns {SelectionSlice}
*/
function normalizeSelection(selection) {
const selectedRefs = [...new Set((selection.selectedRefs ?? []).filter(Boolean))].sort((a, b) => a.localeCompare(b));
const selectedNet = typeof selection.selectedNet === "string" && selection.selectedNet.length > 0 ? selection.selectedNet : null;
const selectedPin =
selection.selectedPin && typeof selection.selectedPin.ref === "string" && typeof selection.selectedPin.pin === "string"
? { ref: selection.selectedPin.ref, pin: selection.selectedPin.pin }
: null;
return {
selectedRefs,
selectedNet,
selectedPin
};
}
/**
* @param {Partial<ViewportSlice>} viewport
* @param {ViewportSlice} prev
* @returns {ViewportSlice}
*/
function normalizeViewport(viewport, prev) {
const nextScale = Number.isFinite(viewport.scale) ? Number(viewport.scale) : prev.scale;
const nextPanX = Number.isFinite(viewport.panX) ? Number(viewport.panX) : prev.panX;
const nextPanY = Number.isFinite(viewport.panY) ? Number(viewport.panY) : prev.panY;
return {
scale: nextScale,
panX: nextPanX,
panY: nextPanY
};
}
/**
* @param {Partial<UiFlagsSlice>} uiFlags
* @param {UiFlagsSlice} prev
* @returns {UiFlagsSlice}
*/
function normalizeUiFlags(uiFlags, prev) {
return {
showLabels: typeof uiFlags.showLabels === "boolean" ? uiFlags.showLabels : prev.showLabels,
isolateNet: typeof uiFlags.isolateNet === "boolean" ? uiFlags.isolateNet : prev.isolateNet,
isolateComponent: typeof uiFlags.isolateComponent === "boolean" ? uiFlags.isolateComponent : prev.isolateComponent,
renderMode: typeof uiFlags.renderMode === "string" && uiFlags.renderMode.length > 0 ? uiFlags.renderMode : prev.renderMode,
jsonError:
uiFlags.jsonError === null || (typeof uiFlags.jsonError === "string" && uiFlags.jsonError.length > 0)
? uiFlags.jsonError
: prev.jsonError
};
}
/**
* @param {Partial<LifecycleSlice>} lifecycle
* @param {LifecycleSlice} prev
* @returns {LifecycleSlice}
*/
function normalizeLifecycle(lifecycle, prev) {
return {
isCompiling: typeof lifecycle.isCompiling === "boolean" ? lifecycle.isCompiling : prev.isCompiling,
lastError:
lifecycle.lastError === null || (typeof lifecycle.lastError === "string" && lifecycle.lastError.length > 0)
? lifecycle.lastError
: prev.lastError,
lastAction:
lifecycle.lastAction === null || (typeof lifecycle.lastAction === "string" && lifecycle.lastAction.length > 0)
? lifecycle.lastAction
: prev.lastAction
};
}
/**
* @param {StoreState} state
* @returns {StateSnapshot}
*/
function snapshotState(state) {
return {
model: deepClone(state.model),
compileResult: deepClone(state.compileResult),
selection: deepClone(state.selection),
viewport: deepClone(state.viewport),
uiFlags: deepClone(state.uiFlags)
};
}
/**
* @param {StoreState} state
* @param {StateSnapshot} snapshot
* @returns {StoreState}
*/
function restoreSnapshot(state, snapshot) {
return {
...state,
model: deepClone(snapshot.model),
compileResult: deepClone(snapshot.compileResult),
selection: deepClone(snapshot.selection),
viewport: deepClone(snapshot.viewport),
uiFlags: deepClone(snapshot.uiFlags)
};
}
/**
* @param {StoreState} state
* @param {string} label
* @returns {StoreState}
*/
function pushHistoryEntry(state, label) {
const nextPast = [...state.history.past, { label, snapshot: snapshotState(state) }];
const overflow = Math.max(0, nextPast.length - state.history.limit);
const past = overflow > 0 ? nextPast.slice(overflow) : nextPast;
return {
...state,
history: {
...state.history,
past,
future: []
}
};
}
/**
* @param {StoreState} current
* @param {StoreState} candidate
* @returns {boolean}
*/
function hasCoreChange(current, candidate) {
return (
current.model !== candidate.model ||
current.compileResult !== candidate.compileResult ||
current.selection !== candidate.selection ||
current.viewport !== candidate.viewport ||
current.uiFlags !== candidate.uiFlags
);
}
/**
* @param {StoreState} state
* @returns {StoreState}
*/
function undoState(state) {
if (state.transaction.active || state.history.past.length === 0) {
return state;
}
const prev = state.history.past[state.history.past.length - 1];
const currentSnapshot = snapshotState(state);
const restored = restoreSnapshot(state, prev.snapshot);
return {
...restored,
history: {
...state.history,
past: state.history.past.slice(0, -1),
future: [...state.history.future, { label: prev.label, snapshot: currentSnapshot }]
}
};
}
/**
* @param {StoreState} state
* @returns {StoreState}
*/
function redoState(state) {
if (state.transaction.active || state.history.future.length === 0) {
return state;
}
const next = state.history.future[state.history.future.length - 1];
const currentSnapshot = snapshotState(state);
const restored = restoreSnapshot(state, next.snapshot);
return {
...restored,
history: {
...state.history,
past: [...state.history.past, { label: next.label, snapshot: currentSnapshot }],
future: state.history.future.slice(0, -1)
}
};
}
/**
* @param {StoreState} state
* @param {string} label
* @param {(state: StoreState) => StoreState} recipe
* @returns {StoreState}
*/
function applyMutation(state, label, recipe) {
const candidate = recipe(state);
if (!hasCoreChange(state, candidate)) {
return state;
}
if (state.transaction.active) {
return {
...candidate,
transaction: {
...state.transaction,
dirty: true
}
};
}
const withHistory = pushHistoryEntry(state, label);
return {
...candidate,
history: withHistory.history,
transaction: state.transaction
};
}
/**
* @param {StoreState} state
* @param {unknown} model
* @returns {StoreState}
*/
function setModelState(state, model) {
return {
...state,
model: model == null ? null : deepClone(model)
};
}
/**
* @param {StoreState} state
* @param {unknown} compileResult
* @returns {StoreState}
*/
function setCompileResultState(state, compileResult) {
return {
...state,
compileResult: compileResult == null ? null : deepClone(compileResult)
};
}
/**
* @param {StoreState} state
* @param {Partial<SelectionSlice>} selection
* @returns {StoreState}
*/
function setSelectionState(state, selection) {
const nextSelection = normalizeSelection({
selectedRefs: selection.selectedRefs ?? state.selection.selectedRefs,
selectedNet: selection.selectedNet ?? state.selection.selectedNet,
selectedPin: selection.selectedPin ?? state.selection.selectedPin
});
return {
...state,
selection: nextSelection
};
}
/**
* @param {StoreState} state
* @param {string} ref
* @param {Partial<SchemetaPlacement>} placement
* @returns {StoreState}
*/
function moveComponentState(state, ref, placement) {
if (!state.model || !Array.isArray(state.model.instances)) {
return state;
}
let touched = false;
const instances = state.model.instances.map((instance) => {
if (instance.ref !== ref) {
return instance;
}
const currentPlacement = instance.placement ?? { x: null, y: null, rotation: 0, locked: false };
const nextPlacement = {
...currentPlacement,
x: Number.isFinite(placement.x) ? Math.round(Number(placement.x)) : currentPlacement.x,
y: Number.isFinite(placement.y) ? Math.round(Number(placement.y)) : currentPlacement.y,
rotation: Number.isFinite(placement.rotation) ? Number(placement.rotation) : currentPlacement.rotation,
locked: typeof placement.locked === "boolean" ? placement.locked : currentPlacement.locked
};
if (
nextPlacement.x === currentPlacement.x &&
nextPlacement.y === currentPlacement.y &&
nextPlacement.rotation === currentPlacement.rotation &&
nextPlacement.locked === currentPlacement.locked
) {
return instance;
}
touched = true;
return {
...instance,
placement: nextPlacement
};
});
if (!touched) {
return state;
}
return {
...state,
model: {
...state.model,
instances
}
};
}
/**
* @param {StoreState} state
* @param {string} text
* @returns {StoreState}
*/
function applyJsonTextFailureState(state, text) {
return {
...state,
uiFlags: normalizeUiFlags(
{
...state.uiFlags,
jsonError: text
},
state.uiFlags
)
};
}
/**
* @param {StoreState} state
* @param {Partial<LifecycleSlice>} lifecycle
* @returns {StoreState}
*/
function setLifecycleState(state, lifecycle) {
return {
...state,
lifecycle: normalizeLifecycle(lifecycle, state.lifecycle)
};
}
/**
* @param {Partial<StoreState>} [overrides]
* @returns {StoreState}
*/
export function createInitialState(overrides = {}) {
const historyLimit = Number.isInteger(overrides.history?.limit) ? overrides.history.limit : DEFAULT_HISTORY_LIMIT;
return {
model: overrides.model ? deepClone(overrides.model) : null,
compileResult: overrides.compileResult ? deepClone(overrides.compileResult) : null,
selection: normalizeSelection(overrides.selection ?? {}),
viewport: normalizeViewport(overrides.viewport ?? {}, { scale: 1, panX: 40, panY: 40 }),
uiFlags: normalizeUiFlags(overrides.uiFlags ?? {}, {
showLabels: true,
isolateNet: false,
isolateComponent: false,
renderMode: "schematic_stub",
jsonError: null
}),
lifecycle: normalizeLifecycle(overrides.lifecycle ?? {}, {
isCompiling: false,
lastError: null,
lastAction: null
}),
history: {
past: [],
future: [],
limit: historyLimit
},
transaction: {
active: false,
label: null,
before: null,
dirty: false
}
};
}
/**
* @param {Partial<StoreState>} [initialState]
*/
export function createSchemetaStore(initialState = {}) {
/** @type {StoreState} */
let state = createInitialState(initialState);
const listeners = new Set();
/**
* @param {StoreState} nextState
* @param {string} action
*/
function publish(nextState, action) {
const prevState = state;
if (nextState === prevState) {
return;
}
state = nextState;
listeners.forEach((listener) => listener(state, prevState, action));
}
const actions = {
/** @param {unknown} model */
setModel(model) {
publish(applyMutation(state, "setModel", (s) => setModelState(s, model)), "setModel");
},
/** @param {unknown} compileResult */
setCompileResult(compileResult) {
publish(
applyMutation(state, "setCompileResult", (s) => setCompileResultState(s, compileResult)),
"setCompileResult"
);
},
/** @param {Partial<SelectionSlice>} selection */
setSelection(selection) {
publish(applyMutation(state, "setSelection", (s) => setSelectionState(s, selection)), "setSelection");
},
/** @param {string} ref @param {Partial<SchemetaPlacement>} placement */
moveComponent(ref, placement) {
publish(applyMutation(state, `moveComponent:${ref}`, (s) => moveComponentState(s, ref, placement ?? {})), "moveComponent");
},
/** @param {Partial<ViewportSlice>} viewport */
setViewport(viewport) {
publish(
applyMutation(state, "setViewport", (s) => ({ ...s, viewport: normalizeViewport(viewport ?? {}, s.viewport) })),
"setViewport"
);
},
/** @param {Partial<UiFlagsSlice>} uiFlags */
setUiFlags(uiFlags) {
publish(
applyMutation(state, "setUiFlags", (s) => ({ ...s, uiFlags: normalizeUiFlags(uiFlags ?? {}, s.uiFlags) })),
"setUiFlags"
);
},
/** @param {Partial<LifecycleSlice>} lifecycle */
setLifecycle(lifecycle) {
publish(setLifecycleState(state, lifecycle ?? {}), "setLifecycle");
},
/** @param {string} action */
beginCompile(action) {
publish(
setLifecycleState(state, {
isCompiling: true,
lastAction: action || "compile",
lastError: null
}),
"beginCompile"
);
},
/** @param {string} action */
completeCompile(action) {
publish(
setLifecycleState(state, {
isCompiling: false,
lastAction: action || state.lifecycle.lastAction,
lastError: null
}),
"completeCompile"
);
},
/** @param {string} action @param {unknown} error */
failCompile(action, error) {
const message = error instanceof Error ? error.message : typeof error === "string" ? error : "Unknown error";
publish(
setLifecycleState(state, {
isCompiling: false,
lastAction: action || state.lifecycle.lastAction,
lastError: message
}),
"failCompile"
);
},
/** @param {string} jsonText */
applyJsonText(jsonText) {
try {
const parsed = JSON.parse(jsonText);
const next = applyMutation(state, "applyJsonText", (s) => {
const withModel = setModelState(s, parsed);
return {
...withModel,
uiFlags: normalizeUiFlags({ ...withModel.uiFlags, jsonError: null }, withModel.uiFlags)
};
});
publish(next, "applyJsonText");
return { ok: true };
} catch (error) {
const message = error instanceof Error ? error.message : "Invalid JSON";
publish(applyJsonTextFailureState(state, message), "applyJsonTextError");
return { ok: false, error: message };
}
},
/** @param {string} [label] */
beginTransaction(label = "transaction") {
if (state.transaction.active) {
return false;
}
publish(
{
...state,
transaction: {
active: true,
label,
before: snapshotState(state),
dirty: false
}
},
"beginTransaction"
);
return true;
},
commitTransaction() {
if (!state.transaction.active) {
return false;
}
const tx = state.transaction;
let nextState = {
...state,
transaction: {
active: false,
label: null,
before: null,
dirty: false
}
};
if (tx.dirty && tx.before) {
const nextPast = [...state.history.past, { label: tx.label ?? "transaction", snapshot: tx.before }];
const overflow = Math.max(0, nextPast.length - state.history.limit);
nextState = {
...nextState,
history: {
...state.history,
past: overflow > 0 ? nextPast.slice(overflow) : nextPast,
future: []
}
};
}
publish(nextState, "commitTransaction");
return true;
},
rollbackTransaction() {
if (!state.transaction.active) {
return false;
}
const tx = state.transaction;
const rolledBack = tx.before ? restoreSnapshot(state, tx.before) : state;
publish(
{
...rolledBack,
transaction: {
active: false,
label: null,
before: null,
dirty: false
}
},
"rollbackTransaction"
);
return true;
},
undo() {
publish(undoState(state), "undo");
},
redo() {
publish(redoState(state), "redo");
}
};
return {
getState() {
return state;
},
subscribe(listener) {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
},
actions
};
}
+485
View File
@@ -0,0 +1,485 @@
:root {
font-family: "IBM Plex Sans", "Segoe UI", sans-serif;
color: #1a1a1a;
background: #f3f6f8;
}
* {
box-sizing: border-box;
}
body {
margin: 0;
min-height: 100vh;
}
#root {
min-height: 100vh;
}
.app-shell {
display: grid;
grid-template-rows: auto auto 1fr;
min-height: 100vh;
}
.topbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
padding: 0.75rem 1rem;
color: #f4f8ff;
background: linear-gradient(90deg, #0b2a42 0%, #164863 100%);
}
.topbar__brand {
font-weight: 700;
letter-spacing: 0.05em;
text-transform: uppercase;
}
.topbar__title {
font-weight: 500;
}
.topbar__actions {
display: flex;
flex-wrap: wrap;
gap: 0.45rem;
justify-content: center;
}
.topbar__actions button {
padding: 0.35rem 0.6rem;
border: 1px solid rgba(232, 242, 250, 0.65);
border-radius: 6px;
background: rgba(8, 24, 38, 0.24);
color: #f2f8ff;
font: inherit;
cursor: pointer;
}
.topbar__actions button:hover:not(:disabled) {
background: rgba(8, 24, 38, 0.38);
}
.topbar__actions button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.topbar__meta {
display: flex;
flex-direction: column;
align-items: flex-end;
gap: 0.1rem;
font-size: 0.84rem;
color: #d7e6f6;
}
.toolbar {
display: flex;
align-items: center;
gap: 0.5rem;
flex-wrap: wrap;
padding: 0.75rem 1rem;
border-bottom: 1px solid #d7dde3;
background: #ffffff;
}
.toolbar button {
padding: 0.45rem 0.7rem;
border-radius: 6px;
border: 1px solid #164863;
background: #ffffff;
color: #164863;
font: inherit;
cursor: pointer;
}
.toolbar button:hover {
background: #eaf2f8;
}
.toolbar__meta {
margin-left: auto;
color: #4a5b66;
font-size: 0.9rem;
}
.workspace-grid {
display: grid;
grid-template-columns: 280px 1fr 320px;
gap: 0.75rem;
padding: 0.75rem;
min-height: 0;
}
.panel,
.canvas {
border: 1px solid #d7dde3;
border-radius: 10px;
background: #ffffff;
min-height: 0;
}
.panel {
padding: 0.9rem;
overflow: auto;
}
.panel__title {
margin: 0 0 0.5rem;
font-size: 1rem;
}
.panel__body {
margin: 0;
color: #52626e;
}
.panel input[type="search"] {
width: 100%;
margin-bottom: 0.7rem;
padding: 0.4rem 0.5rem;
border: 1px solid #9bb0c0;
border-radius: 6px;
font: inherit;
}
.panel h3 {
margin: 0.7rem 0 0.4rem;
font-size: 0.9rem;
color: #264258;
}
.panel ul {
margin: 0;
padding: 0;
list-style: none;
display: grid;
gap: 0.25rem;
}
.panel li button {
width: 100%;
text-align: left;
border: 1px solid #d2dee8;
border-radius: 6px;
background: #fafcff;
padding: 0.32rem 0.45rem;
color: #173247;
font: inherit;
cursor: pointer;
}
.panel li button:hover {
background: #eef6fd;
}
.panel pre {
margin: 0.35rem 0 0.55rem;
border: 1px solid #dbe5ee;
border-radius: 8px;
background: #f7fbff;
color: #274054;
padding: 0.45rem 0.55rem;
max-height: 8rem;
overflow: auto;
font-size: 0.76rem;
}
.json-tools {
display: flex;
flex-wrap: wrap;
gap: 0.35rem;
margin-bottom: 0.5rem;
}
.json-tools button {
padding: 0.28rem 0.48rem;
border: 1px solid #b9c9d6;
border-radius: 6px;
background: #f8fbff;
color: #173247;
font: inherit;
cursor: pointer;
}
.json-tools button:hover {
background: #eaf2f8;
}
.json-editor {
width: 100%;
min-height: 220px;
border: 1px solid #c1d0dd;
border-radius: 8px;
padding: 0.5rem;
background: #fbfdff;
color: #173247;
font-family: "IBM Plex Mono", "Fira Code", monospace;
font-size: 0.78rem;
line-height: 1.35;
resize: vertical;
}
.json-status--ok {
color: #12633c;
}
.json-status--error {
color: #a31515;
}
.canvas {
display: grid;
grid-template-rows: auto 1fr;
overflow: hidden;
background: #f7fbff;
}
.canvas__toolbar {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.5rem;
border-bottom: 1px solid #dbe5ec;
background: linear-gradient(180deg, #ffffff 0%, #f3f8fc 100%);
}
.canvas__toolbar button {
padding: 0.35rem 0.6rem;
border: 1px solid #8ca1b3;
border-radius: 6px;
background: #ffffff;
color: #173247;
font: inherit;
cursor: pointer;
}
.canvas__toolbar button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.canvas__zoom-readout {
min-width: 6rem;
text-align: center;
font-weight: 600;
color: #21435a;
}
.canvas__placeholder-control {
border-style: dashed;
}
.canvas__surface {
position: relative;
overflow: auto;
background-color: #f7fbff;
background-image:
linear-gradient(to right, #e6edf3 1px, transparent 1px),
linear-gradient(to bottom, #e6edf3 1px, transparent 1px);
background-size: 28px 28px;
}
.canvas__surface:focus-visible {
outline: 2px solid #0a79c2;
outline-offset: -2px;
}
.canvas__selection-box {
position: absolute;
border: 1px solid #0a79c2;
background: rgba(10, 121, 194, 0.14);
pointer-events: none;
z-index: 2;
}
.canvas__viewport {
position: relative;
width: 2200px;
height: 1500px;
transform-origin: 0 0;
}
.canvas-wires {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
pointer-events: auto;
}
.canvas-wire-segment {
stroke: #5a6e7f;
stroke-width: 2.2px;
stroke-linecap: round;
opacity: 0.9;
pointer-events: stroke;
cursor: pointer;
}
.canvas-wire-segment.is-highlight {
stroke: #0b78bf;
stroke-width: 3px;
opacity: 1;
}
.canvas-wire-segment.is-dimmed {
opacity: 0.2;
}
.canvas-wire-label {
position: absolute;
transform: translate(-50%, calc(-100% - 6px));
padding: 0.1rem 0.3rem;
border: 1px solid rgba(144, 158, 171, 0.8);
border-radius: 4px;
background: rgba(255, 255, 255, 0.95);
color: #243f53;
font-size: 0.66rem;
line-height: 1.1;
letter-spacing: 0.02em;
white-space: nowrap;
pointer-events: auto;
cursor: pointer;
}
button.canvas-wire-label {
font: inherit;
}
.canvas-wire-label.is-highlight {
border-color: #0b78bf;
color: #0d4f7b;
font-weight: 600;
}
.canvas-wire-label.is-dimmed {
opacity: 0.35;
}
.canvas-node {
position: absolute;
user-select: none;
touch-action: none;
}
.canvas-node__chrome {
width: 100%;
min-height: inherit;
border: 1px solid #406078;
border-radius: 12px;
background: linear-gradient(180deg, #ffffff 0%, #f6fbff 100%);
box-shadow: 0 3px 10px rgba(38, 64, 89, 0.18);
}
.canvas-node__content {
width: 100%;
height: 100%;
padding: 0.45rem 0.55rem 0.5rem;
transform-origin: 50% 50%;
}
.canvas-node__ref {
font-size: 0.78rem;
font-weight: 700;
letter-spacing: 0.04em;
color: #113148;
text-transform: uppercase;
}
.canvas-node__value {
margin-top: 0.15rem;
margin-bottom: 0.35rem;
font-size: 0.74rem;
color: #405260;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.canvas-node__pins {
display: flex;
justify-content: space-between;
gap: 0.5rem;
}
.canvas-node__pin-col {
display: flex;
flex-direction: column;
gap: 0.14rem;
min-width: 0;
flex: 1;
}
.canvas-node__pin-col--right {
text-align: right;
}
.canvas-node__pin {
display: grid;
grid-template-columns: auto 1fr;
align-items: baseline;
gap: 0.3rem;
min-width: 0;
}
.canvas-node__pin-col--right .canvas-node__pin {
grid-template-columns: 1fr auto;
}
.canvas-node__pin-number {
font-size: 0.66rem;
color: #6c8090;
white-space: nowrap;
}
.canvas-node__pin-name {
font-size: 0.68rem;
color: #2d475a;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.canvas-node__lock {
margin-top: 0.35rem;
font-size: 0.64rem;
color: #925d00;
text-transform: uppercase;
letter-spacing: 0.04em;
}
.canvas-node.is-selected .canvas-node__chrome {
border-color: #0a79c2;
box-shadow: 0 0 0 2px rgba(10, 121, 194, 0.25), 0 4px 14px rgba(18, 53, 78, 0.25);
}
.canvas-node.is-dragging .canvas-node__chrome {
cursor: grabbing;
box-shadow: 0 0 0 2px rgba(10, 121, 194, 0.3), 0 8px 18px rgba(12, 42, 66, 0.26);
}
@media (max-width: 1100px) {
.topbar {
align-items: flex-start;
}
.topbar__meta {
align-items: flex-start;
}
.workspace-grid {
grid-template-columns: 1fr;
grid-template-rows: auto minmax(260px, 1fr) auto;
}
.toolbar__meta {
width: 100%;
margin-left: 0;
}
}
+1
View File
@@ -0,0 +1 @@
/// <reference types="vite/client" />
+21
View File
@@ -0,0 +1,21 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
"moduleResolution": "Bundler",
"allowImportingTsExtensions": false,
"resolveJsonModule": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"]
}
+7
View File
@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}
+11
View File
@@ -0,0 +1,11 @@
{
"compilerOptions": {
"composite": true,
"skipLibCheck": true,
"module": "ESNext",
"moduleResolution": "Bundler",
"allowSyntheticDefaultImports": true,
"strict": true
},
"include": ["vite.config.ts"]
}
+18
View File
@@ -0,0 +1,18 @@
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
export default defineConfig({
plugins: [react()],
server: {
port: 5173,
proxy: {
"/compile": "http://localhost:8787",
"/analyze": "http://localhost:8787",
"/layout": "http://localhost:8787",
"/health": "http://localhost:8787"
}
},
preview: {
port: 4173
}
});
+722 -82
View File
File diff suppressed because it is too large. Load diff
+76 -2
View File
@@ -15,17 +15,21 @@
<div class="actions">
<button id="newProjectBtn" aria-label="Create new project">New</button>
<button id="loadSampleBtn" aria-label="Load sample project">Load Sample</button>
<button id="resetSampleBtn" aria-label="Reset to deterministic sample baseline">Reset Sample</button>
<button id="importBtn" aria-label="Import Schemeta JSON file">Import JSON</button>
<button id="exportBtn" aria-label="Export Schemeta JSON file">Export JSON</button>
<button id="autoLayoutBtn" aria-label="Run automatic layout">Auto Layout</button>
<button id="autoTidyBtn" aria-label="Run automatic tidy layout">Auto Tidy</button>
<button id="unlockAllBtn" aria-label="Unlock all components">Unlock All</button>
<button id="themeToggleBtn" aria-label="Toggle dark mode">Dark</button>
<button id="shortcutsBtn" aria-label="Show keyboard shortcuts">Shortcuts</button>
<button id="undoBtn" title="Undo (Ctrl/Cmd+Z)">Undo</button>
<button id="redoBtn" title="Redo (Ctrl/Cmd+Shift+Z)">Redo</button>
<label class="inlineSelect">
Mode
<select id="renderModeSelect">
<option value="schematic_stub">Schematic Stub</option>
<option value="explicit">Explicit Wires</option>
<option value="schematic_stub">Schematic Stub</option>
</select>
</label>
<input id="fileInput" type="file" accept="application/json,.json" hidden />
@@ -40,6 +44,19 @@
<button id="isolateComponentBtn" class="chip">Isolate</button>
</div>
<input id="instanceFilter" placeholder="Filter instances" aria-label="Filter instances" />
<div class="quickCreate">
<input id="newComponentRefInput" placeholder="Ref (auto if empty)" aria-label="New component reference" />
<select id="newComponentTypeSelect" aria-label="New component type">
<option value="resistor">resistor</option>
<option value="capacitor">capacitor</option>
<option value="inductor">inductor</option>
<option value="diode">diode</option>
<option value="led">led</option>
<option value="connector">connector</option>
<option value="generic">generic</option>
</select>
<button id="addComponentBtn">Add Component</button>
</div>
<ul id="instanceList" class="list" aria-label="Instances list"></ul>
</section>
<section>
@@ -48,16 +65,42 @@
<button id="isolateNetBtn" class="chip">Isolate</button>
</div>
<input id="netFilter" placeholder="Filter nets" aria-label="Filter nets" />
<div class="quickCreate">
<input id="newQuickNetNameInput" placeholder="NET_1" aria-label="New net name" />
<select id="newQuickNetClassSelect" aria-label="New net class">
<option value="signal">signal</option>
<option value="analog">analog</option>
<option value="power">power</option>
<option value="ground">ground</option>
<option value="clock">clock</option>
<option value="bus">bus</option>
<option value="differential">differential</option>
</select>
<button id="addQuickNetBtn">Add Net</button>
</div>
<ul id="netList" class="list" aria-label="Nets list"></ul>
</section>
<section class="legendSection" aria-label="Net color legend">
<div class="sectionHead">
<h2>Legend</h2>
</div>
<div class="netLegend">
<div class="legendRow"><span class="legendSwatch legendPower"></span>Power</div>
<div class="legendRow"><span class="legendSwatch legendGround"></span>Ground</div>
<div class="legendRow"><span class="legendSwatch legendClock"></span>Clock</div>
<div class="legendRow"><span class="legendSwatch legendSignal"></span>Signal</div>
<div class="legendRow"><span class="legendSwatch legendAnalog"></span>Analog</div>
</div>
</section>
</aside>
<section class="pane center">
<div class="canvasTools">
<button id="zoomOutBtn" aria-label="Zoom out">-</button>
<button id="zoomResetBtn" aria-label="Reset zoom">100%</button>
<button id="zoomResetBtn" aria-label="Reset view">Reset</button>
<button id="zoomInBtn" aria-label="Zoom in">+</button>
<button id="fitViewBtn" aria-label="Fit schematic to viewport">Fit</button>
<button id="focusSelectionBtn" aria-label="Focus current selection">Focus</button>
<label class="inlineCheck"><input id="showLabelsInput" type="checkbox" checked /> Labels</label>
<span id="compileStatus">Idle</span>
</div>
@@ -254,6 +297,37 @@
</div>
</div>
<div id="shortcutsModal" class="modal hidden" role="dialog" aria-modal="true" aria-labelledby="shortcutsTitle">
<div class="modalCard compactModal">
<div class="modalHead">
<h3 id="shortcutsTitle">Keyboard Shortcuts</h3>
<button id="closeShortcutsBtn">Close</button>
</div>
<div class="shortcutGrid">
<div><kbd>Ctrl/Cmd + Z</kbd><span>Undo</span></div>
<div><kbd>Ctrl/Cmd + Shift + Z</kbd><span>Redo</span></div>
<div><kbd>Ctrl/Cmd + K</kbd><span>Open command palette</span></div>
<div><kbd>F</kbd><span>Focus current selection</span></div>
<div><kbd>Space</kbd><span>Rotate selected component(s)</span></div>
<div><kbd>Space + Drag</kbd><span>Pan canvas</span></div>
<div><kbd>Alt + Enter</kbd><span>Apply selected editor</span></div>
<div><kbd>Alt + C</kbd><span>Connect selected pin to chosen net</span></div>
<div><kbd>Esc</kbd><span>Close modal / clear selection</span></div>
</div>
</div>
</div>
<div id="commandModal" class="modal hidden" role="dialog" aria-modal="true" aria-labelledby="commandTitle">
<div class="modalCard compactModal">
<div class="modalHead">
<h3 id="commandTitle">Command Palette</h3>
<button id="closeCommandBtn">Close</button>
</div>
<input id="commandInput" placeholder="Type a command..." aria-label="Command input" />
<div id="commandList" class="commandList" role="listbox" aria-label="Command results"></div>
</div>
</div>
<script type="module" src="/app.js"></script>
</body>
</html>
+107 -36
View File
@@ -1,91 +1,162 @@
{
"meta": {
"title": "ESP32 Audio Path"
"title": "ESP32 Smart Audio + Sensing Node"
},
"symbols": {
"esp32_s3_supermini": {
"symbol_id": "esp32_s3_supermini",
"category": "microcontroller",
"body": { "width": 160, "height": 240 },
"body": { "width": 180, "height": 280 },
"pins": [
{ "name": "3V3", "number": "1", "side": "left", "offset": 30, "type": "power_in" },
{ "name": "GND", "number": "2", "side": "left", "offset": 60, "type": "ground" },
{ "name": "GPIO5", "number": "10", "side": "right", "offset": 40, "type": "output" },
{ "name": "GPIO6", "number": "11", "side": "right", "offset": 70, "type": "output" },
{ "name": "GPIO7", "number": "12", "side": "right", "offset": 100, "type": "output" }
{ "name": "3V3", "number": "1", "side": "left", "offset": 24, "type": "power_in" },
{ "name": "GND", "number": "2", "side": "left", "offset": 56, "type": "ground" },
{ "name": "GPIO5", "number": "10", "side": "right", "offset": 36, "type": "output" },
{ "name": "GPIO6", "number": "11", "side": "right", "offset": 66, "type": "output" },
{ "name": "GPIO7", "number": "12", "side": "right", "offset": 96, "type": "output" },
{ "name": "GPIO8", "number": "13", "side": "right", "offset": 126, "type": "input" },
{ "name": "GPIO9", "number": "14", "side": "right", "offset": 156, "type": "bidirectional" },
{ "name": "GPIO10", "number": "15", "side": "right", "offset": 186, "type": "bidirectional" },
{ "name": "GPIO11", "number": "16", "side": "right", "offset": 216, "type": "output" },
{ "name": "GPIO12", "number": "17", "side": "right", "offset": 246, "type": "output" }
],
"graphics": {
"primitives": [{ "type": "rect", "x": 0, "y": 0, "w": 160, "h": 240 }]
"primitives": [{ "type": "rect", "x": 0, "y": 0, "w": 180, "h": 280 }]
}
},
"dac_i2s": {
"symbol_id": "dac_i2s",
"category": "audio",
"body": { "width": 140, "height": 180 },
"body": { "width": 160, "height": 200 },
"pins": [
{ "name": "3V3", "number": "1", "side": "left", "offset": 20, "type": "power_in" },
{ "name": "GND", "number": "2", "side": "left", "offset": 50, "type": "ground" },
{ "name": "BCLK", "number": "3", "side": "left", "offset": 80, "type": "input" },
{ "name": "LRCLK", "number": "4", "side": "left", "offset": 110, "type": "input" },
{ "name": "DIN", "number": "5", "side": "left", "offset": 140, "type": "input" },
{ "name": "AOUT", "number": "6", "side": "right", "offset": 90, "type": "analog" }
{ "name": "3V3", "number": "1", "side": "left", "offset": 24, "type": "power_in" },
{ "name": "GND", "number": "2", "side": "left", "offset": 54, "type": "ground" },
{ "name": "BCLK", "number": "3", "side": "left", "offset": 86, "type": "input" },
{ "name": "LRCLK", "number": "4", "side": "left", "offset": 116, "type": "input" },
{ "name": "DIN", "number": "5", "side": "left", "offset": 146, "type": "input" },
{ "name": "AOUT", "number": "6", "side": "right", "offset": 96, "type": "analog" }
],
"graphics": {
"primitives": [{ "type": "rect", "x": 0, "y": 0, "w": 140, "h": 180 }]
"primitives": [{ "type": "rect", "x": 0, "y": 0, "w": 160, "h": 200 }]
}
},
"amp": {
"symbol_id": "amp",
"category": "output",
"body": { "width": 120, "height": 120 },
"body": { "width": 130, "height": 130 },
"pins": [
{ "name": "5V", "number": "1", "side": "left", "offset": 20, "type": "power_in" },
{ "name": "GND", "number": "2", "side": "left", "offset": 50, "type": "ground" },
{ "name": "IN", "number": "3", "side": "left", "offset": 80, "type": "input" },
{ "name": "SPK", "number": "4", "side": "right", "offset": 70, "type": "output" }
{ "name": "5V", "number": "1", "side": "left", "offset": 22, "type": "power_in" },
{ "name": "GND", "number": "2", "side": "left", "offset": 52, "type": "ground" },
{ "name": "IN", "number": "3", "side": "left", "offset": 84, "type": "input" },
{ "name": "SPK", "number": "4", "side": "right", "offset": 74, "type": "output" }
],
"graphics": {
"primitives": [{ "type": "rect", "x": 0, "y": 0, "w": 120, "h": 120 }]
"primitives": [{ "type": "rect", "x": 0, "y": 0, "w": 130, "h": 130 }]
}
},
"psu": {
"symbol_id": "psu",
"category": "power",
"body": { "width": 120, "height": 120 },
"body": { "width": 140, "height": 140 },
"pins": [
{ "name": "5V_OUT", "number": "1", "side": "right", "offset": 30, "type": "power_out" },
{ "name": "3V3_OUT", "number": "2", "side": "right", "offset": 60, "type": "power_out" },
{ "name": "GND", "number": "3", "side": "right", "offset": 90, "type": "ground" }
{ "name": "5V_OUT", "number": "1", "side": "right", "offset": 34, "type": "power_out" },
{ "name": "3V3_OUT", "number": "2", "side": "right", "offset": 70, "type": "power_out" },
{ "name": "GND", "number": "3", "side": "right", "offset": 104, "type": "ground" }
],
"graphics": {
"primitives": [{ "type": "rect", "x": 0, "y": 0, "w": 120, "h": 120 }]
"primitives": [{ "type": "rect", "x": 0, "y": 0, "w": 140, "h": 140 }]
}
},
"imu_i2c": {
"symbol_id": "imu_i2c",
"category": "sensor",
"body": { "width": 140, "height": 120 },
"pins": [
{ "name": "3V3", "number": "1", "side": "left", "offset": 18, "type": "power_in" },
{ "name": "GND", "number": "2", "side": "left", "offset": 44, "type": "ground" },
{ "name": "SCL", "number": "3", "side": "left", "offset": 70, "type": "bidirectional" },
{ "name": "SDA", "number": "4", "side": "left", "offset": 96, "type": "bidirectional" }
]
},
"oled_i2c": {
"symbol_id": "oled_i2c",
"category": "display",
"body": { "width": 140, "height": 120 },
"pins": [
{ "name": "3V3", "number": "1", "side": "left", "offset": 18, "type": "power_in" },
{ "name": "GND", "number": "2", "side": "left", "offset": 44, "type": "ground" },
{ "name": "SCL", "number": "3", "side": "left", "offset": 70, "type": "bidirectional" },
{ "name": "SDA", "number": "4", "side": "left", "offset": 96, "type": "bidirectional" }
]
},
"mic_pre": {
"symbol_id": "mic_pre",
"category": "analog",
"body": { "width": 150, "height": 120 },
"pins": [
{ "name": "3V3", "number": "1", "side": "left", "offset": 20, "type": "power_in" },
{ "name": "GND", "number": "2", "side": "left", "offset": 48, "type": "ground" },
{ "name": "OUT", "number": "3", "side": "right", "offset": 62, "type": "analog" },
{ "name": "EN", "number": "4", "side": "left", "offset": 90, "type": "input" }
]
},
"debug_header": {
"symbol_id": "debug_header",
"category": "connector",
"body": { "width": 130, "height": 80 },
"pins": [
{ "name": "1", "number": "1", "side": "right", "offset": 24, "type": "bidirectional" },
{ "name": "GND", "number": "2", "side": "left", "offset": 24, "type": "ground" }
]
}
},
"instances": [
{ "ref": "U1", "symbol": "esp32_s3_supermini", "properties": { "value": "ESP32-S3" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } },
{ "ref": "U2", "symbol": "dac_i2s", "properties": { "value": "DAC" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } },
{ "ref": "U3", "symbol": "amp", "properties": { "value": "Amp" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } },
{ "ref": "U4", "symbol": "psu", "properties": { "value": "Power" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } }
{ "ref": "U3", "symbol": "amp", "properties": { "value": "Class-D Amp" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } },
{ "ref": "U4", "symbol": "psu", "properties": { "value": "5V/3V3 Power" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } },
{ "ref": "U5", "symbol": "imu_i2c", "properties": { "value": "IMU" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } },
{ "ref": "U6", "symbol": "oled_i2c", "properties": { "value": "OLED" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } },
{ "ref": "U7", "symbol": "mic_pre", "properties": { "value": "Mic Preamp" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } },
{ "ref": "J1", "symbol": "debug_header", "properties": { "value": "Debug Header" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } },
{ "ref": "R1", "part": "resistor", "properties": { "value": "10k" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } },
{ "ref": "R2", "part": "resistor", "properties": { "value": "10k" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } },
{ "ref": "C1", "part": "capacitor", "properties": { "value": "100nF" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } },
{ "ref": "C2", "part": "capacitor", "properties": { "value": "100nF" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } },
{ "ref": "C3", "part": "capacitor", "properties": { "value": "1uF" }, "placement": { "x": null, "y": null, "rotation": 0, "locked": false } }
],
"nets": [
{ "name": "3V3", "class": "power", "nodes": [{ "ref": "U4", "pin": "3V3_OUT" }, { "ref": "U1", "pin": "3V3" }, { "ref": "U2", "pin": "3V3" }] },
{ "name": "3V3", "class": "power", "nodes": [{ "ref": "U4", "pin": "3V3_OUT" }, { "ref": "U1", "pin": "3V3" }, { "ref": "U2", "pin": "3V3" }, { "ref": "U5", "pin": "3V3" }, { "ref": "U6", "pin": "3V3" }, { "ref": "U7", "pin": "3V3" }, { "ref": "R1", "pin": "1" }, { "ref": "R2", "pin": "1" }, { "ref": "C1", "pin": "1" }, { "ref": "C2", "pin": "1" }] },
{ "name": "5V", "class": "power", "nodes": [{ "ref": "U4", "pin": "5V_OUT" }, { "ref": "U3", "pin": "5V" }] },
{ "name": "GND", "class": "ground", "nodes": [{ "ref": "U4", "pin": "GND" }, { "ref": "U1", "pin": "GND" }, { "ref": "U2", "pin": "GND" }, { "ref": "U3", "pin": "GND" }] },
{ "name": "GND", "class": "ground", "nodes": [{ "ref": "U4", "pin": "GND" }, { "ref": "U1", "pin": "GND" }, { "ref": "U2", "pin": "GND" }, { "ref": "U3", "pin": "GND" }, { "ref": "U5", "pin": "GND" }, { "ref": "U6", "pin": "GND" }, { "ref": "U7", "pin": "GND" }, { "ref": "J1", "pin": "GND" }, { "ref": "C1", "pin": "2" }, { "ref": "C2", "pin": "2" }, { "ref": "C3", "pin": "2" }] },
{ "name": "I2S_BCLK", "class": "clock", "nodes": [{ "ref": "U1", "pin": "GPIO5" }, { "ref": "U2", "pin": "BCLK" }] },
{ "name": "I2S_LRCLK", "class": "clock", "nodes": [{ "ref": "U1", "pin": "GPIO6" }, { "ref": "U2", "pin": "LRCLK" }] },
{ "name": "I2S_DOUT", "class": "signal", "nodes": [{ "ref": "U1", "pin": "GPIO7" }, { "ref": "U2", "pin": "DIN" }] },
{ "name": "AUDIO_ANALOG", "class": "analog", "nodes": [{ "ref": "U2", "pin": "AOUT" }, { "ref": "U3", "pin": "IN" }] }
{ "name": "AUDIO_ANALOG", "class": "analog", "nodes": [{ "ref": "U2", "pin": "AOUT" }, { "ref": "U3", "pin": "IN" }] },
{ "name": "I2C_SCL", "class": "clock", "nodes": [{ "ref": "U1", "pin": "GPIO9" }, { "ref": "U5", "pin": "SCL" }, { "ref": "U6", "pin": "SCL" }, { "ref": "R1", "pin": "2" }] },
{ "name": "I2C_SDA", "class": "signal", "nodes": [{ "ref": "U1", "pin": "GPIO10" }, { "ref": "U5", "pin": "SDA" }, { "ref": "U6", "pin": "SDA" }, { "ref": "R2", "pin": "2" }] },
{ "name": "MIC_ADC", "class": "analog", "nodes": [{ "ref": "U7", "pin": "OUT" }, { "ref": "U1", "pin": "GPIO8" }, { "ref": "C3", "pin": "1" }] },
{ "name": "MIC_EN", "class": "signal", "nodes": [{ "ref": "U1", "pin": "GPIO11" }, { "ref": "U7", "pin": "EN" }] },
{ "name": "DEBUG_TX", "class": "signal", "nodes": [{ "ref": "U1", "pin": "GPIO12" }, { "ref": "J1", "pin": "1" }] }
],
"constraints": {
"groups": [
{ "name": "power_stage", "members": ["U4"], "layout": "cluster" },
{ "name": "compute", "members": ["U1", "U2"], "layout": "cluster" }
{ "name": "compute_audio", "members": ["U1", "U2", "U3", "U7"], "layout": "cluster" },
{ "name": "i2c_peripherals", "members": ["U5", "U6", "R1", "R2"], "layout": "cluster" },
{ "name": "support", "members": ["C1", "C2", "C3", "J1"], "layout": "cluster" }
],
"alignment": [{ "left_of": "U1", "right_of": "U2" }],
"near": [{ "component": "U2", "target_pin": { "ref": "U1", "pin": "GPIO5" } }]
"alignment": [
{ "left_of": "U4", "right_of": "U1" },
{ "left_of": "U1", "right_of": "U2" },
{ "left_of": "U2", "right_of": "U3" }
],
"near": [
{ "component": "C1", "target_pin": { "ref": "U1", "pin": "3V3" } },
{ "component": "C2", "target_pin": { "ref": "U2", "pin": "3V3" } },
{ "component": "C3", "target_pin": { "ref": "U1", "pin": "GPIO8" } }
]
},
"annotations": [
{ "text": "I2S audio chain" }
{ "text": "Smart audio + sensing node with I2S DAC, class-D amp, I2C peripherals, and mic ADC front-end." }
]
}
+522 -141
View File
@@ -1,56 +1,84 @@
:root {
--bg: #eef2f6;
--panel: #ffffff;
--ink: #1d2939;
--ink-soft: #667085;
--line: #d0d5dd;
--accent: #155eef;
--accent-soft: #dbe8ff;
--warn: #b54708;
--error: #b42318;
--ok: #067647;
--bg-0: #f5f7fb;
--bg-1: #ebf1f8;
--bg-2: #dce8f4;
--panel: #fbfdff;
--panel-strong: #ffffff;
--canvas: #f4f8fd;
--ink: #0f1728;
--ink-muted: #4a607c;
--ink-subtle: #7388a3;
--line: #c8d5e4;
--line-strong: #9db1c9;
--accent: #1565d8;
--accent-strong: #0f4dab;
--accent-soft: #e6f0ff;
--ok: #0f7a49;
--warn: #9b6200;
--err: #ac2f24;
--power: #d6691f;
--ground: #60748d;
--clock: #d35c2f;
--signal: #2f72e7;
--analog: #0d978e;
--radius-sm: 8px;
--radius-md: 12px;
--radius-lg: 16px;
--shadow-1: 0 1px 2px rgba(16, 24, 40, 0.08);
--shadow-2: 0 10px 24px rgba(16, 24, 40, 0.08);
}
body.theme-dark {
--bg-0: #0b1220;
--bg-1: #0f172a;
--bg-2: #172237;
--panel: #0f1c2e;
--panel-strong: #13233a;
--canvas: #0d1728;
--ink: #e6edf7;
--ink-muted: #a7b6cd;
--ink-subtle: #7f91ad;
--line: #2a3c57;
--line-strong: #436086;
--accent: #60a5fa;
--accent-strong: #3b82f6;
--accent-soft: #162945;
--ok: #42ba86;
--warn: #f0b54f;
--err: #ef7367;
--power: #f59a4b;
--ground: #9ab0ca;
--clock: #f1835f;
--signal: #7aa4ff;
--analog: #4ec2ba;
--shadow-1: 0 1px 2px rgba(0, 0, 0, 0.35);
--shadow-2: 0 10px 24px rgba(0, 0, 0, 0.36);
}
* {
box-sizing: border-box;
}
html,
body {
margin: 0;
font-family: "Manrope", "Segoe UI", sans-serif;
min-height: 100%;
}
body.theme-dark {
background:
radial-gradient(circle at 0% 0%, #2f1f17 0 18%, transparent 30%),
radial-gradient(circle at 96% 5%, #122739 0 18%, transparent 30%),
linear-gradient(180deg, var(--bg-1), var(--bg-0));
}
body {
font-family: "IBM Plex Sans", "Manrope", "Segoe UI", sans-serif;
color: var(--ink);
background: radial-gradient(circle at 8% 8%, #fef7e6, transparent 30%),
radial-gradient(circle at 88% 12%, #e0f2ff, transparent 30%), var(--bg);
min-height: 100vh;
}
.topbar {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 12px;
border-bottom: 1px solid var(--line);
background: #f7fbffde;
backdrop-filter: blur(4px);
}
.brand h1 {
margin: 0;
font-size: 1.2rem;
letter-spacing: 0.08em;
}
.brand p {
margin: 2px 0 0;
color: var(--ink-soft);
font-size: 0.8rem;
}
.actions {
display: flex;
flex-wrap: wrap;
gap: 8px;
align-items: center;
background:
radial-gradient(circle at 0% 0%, #fff4de 0 20%, transparent 30%),
radial-gradient(circle at 96% 5%, #dbf2ff 0 18%, transparent 28%),
linear-gradient(180deg, var(--bg-1), var(--bg-0));
}
button,
@@ -60,44 +88,101 @@ textarea {
font: inherit;
}
button {
border: 1px solid var(--line);
border-radius: 8px;
background: #fff;
padding: 6px 10px;
color: var(--ink);
cursor: pointer;
}
button:disabled {
opacity: 0.5;
cursor: not-allowed;
button,
input,
select,
textarea,
.list li,
details > summary {
transition: background-color 120ms ease, border-color 120ms ease, box-shadow 120ms ease, color 120ms ease;
}
button:focus-visible,
input:focus-visible,
select:focus-visible,
textarea:focus-visible,
.list li:focus-visible {
outline: 2px solid #155eef;
.list li:focus-visible,
details > summary:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 1px;
}
button {
border: 1px solid var(--line);
border-radius: var(--radius-sm);
background: var(--panel-strong);
color: var(--ink);
padding: 6px 11px;
cursor: pointer;
box-shadow: var(--shadow-1);
}
button:hover {
border-color: var(--line-strong);
background: color-mix(in oklab, var(--accent-soft) 58%, var(--panel-strong));
}
button:disabled {
opacity: 0.48;
cursor: not-allowed;
}
button.primary {
border-color: var(--accent);
background: var(--accent);
color: #fff;
border-color: var(--accent);
}
button.primary:hover {
background: var(--accent-strong);
border-color: var(--accent-strong);
}
button.chip {
padding: 4px 8px;
padding: 4px 9px;
font-size: 0.76rem;
}
button.activeChip {
background: var(--accent-soft);
border-color: var(--accent);
color: #0f3ea3;
color: var(--accent-strong);
}
.topbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 14px;
padding: 10px 12px;
border-bottom: 1px solid var(--line);
background: linear-gradient(180deg, color-mix(in oklab, var(--panel-strong) 88%, #ffffff), var(--panel));
backdrop-filter: blur(2px);
position: sticky;
top: 0;
z-index: 40;
}
.brand h1 {
margin: 0;
font-size: 1.6rem;
letter-spacing: 0.08em;
line-height: 1;
}
.brand p {
margin: 2px 0 0;
font-size: 0.84rem;
color: var(--ink-muted);
font-weight: 600;
}
.actions {
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
align-items: center;
gap: 7px;
}
.inlineSelect,
@@ -109,24 +194,22 @@ button.activeChip {
}
.inlineSelect select {
border: 1px solid var(--line);
border-radius: 8px;
padding: 5px 8px;
min-width: 138px;
}
.workspace {
height: calc(100vh - 65px);
height: calc(100vh - 77px);
display: grid;
grid-template-columns: 270px minmax(480px, 1fr) 380px;
gap: 10px;
grid-template-columns: 270px minmax(520px, 1fr) 392px;
padding: 10px;
}
.pane {
background: var(--panel);
border: 1px solid var(--line);
border-radius: 12px;
overflow: hidden;
border-radius: var(--radius-md);
background: linear-gradient(180deg, var(--panel), color-mix(in oklab, var(--panel) 88%, #081120));
box-shadow: var(--shadow-1);
}
.pane.left,
@@ -138,16 +221,27 @@ button.activeChip {
overflow: auto;
}
.pane.center {
overflow: hidden;
background: linear-gradient(180deg, color-mix(in oklab, var(--panel-strong) 90%, #ffffff), var(--panel));
}
.sectionHead {
display: flex;
justify-content: space-between;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.sectionHead h2 {
margin: 0;
font-size: 0.9rem;
font-size: 0.92rem;
color: var(--ink);
}
h2 {
margin: 0;
font-size: 0.94rem;
}
input,
@@ -155,32 +249,44 @@ textarea,
select {
width: 100%;
border: 1px solid var(--line);
border-radius: 8px;
border-radius: var(--radius-sm);
padding: 8px;
background: var(--panel-strong);
color: var(--ink);
}
input::placeholder,
textarea::placeholder {
color: var(--ink-subtle);
}
textarea {
min-height: 250px;
font-family: "JetBrains Mono", monospace;
font-family: "JetBrains Mono", "IBM Plex Mono", monospace;
font-size: 12px;
line-height: 1.45;
line-height: 1.42;
}
.list {
margin: 8px 0 0;
padding: 0;
list-style: none;
max-height: 230px;
padding: 0;
max-height: 250px;
overflow: auto;
border: 1px solid var(--line);
border-radius: 8px;
border-radius: var(--radius-sm);
background: color-mix(in oklab, var(--panel-strong) 84%, transparent);
}
.list li {
padding: 8px;
border-bottom: 1px solid var(--line);
cursor: pointer;
color: var(--ink);
}
.list li:hover {
background: color-mix(in oklab, var(--accent-soft) 70%, var(--panel-strong));
}
.list li:last-child {
@@ -189,6 +295,8 @@ textarea {
.list li.active {
background: var(--accent-soft);
color: #0b3a84;
font-weight: 600;
}
.list li.listSpacer {
@@ -198,11 +306,71 @@ textarea {
background: transparent;
}
.quickCreate {
margin-top: 8px;
display: grid;
grid-template-columns: 1fr;
gap: 6px;
}
.quickCreate button {
justify-self: start;
}
.legendSection {
margin-top: 2px;
}
.netLegend {
border: 1px solid var(--line);
border-radius: var(--radius-sm);
background: var(--panel-strong);
padding: 8px;
display: grid;
gap: 6px;
}
.legendRow {
display: inline-flex;
align-items: center;
gap: 8px;
font-size: 0.8rem;
color: var(--ink-muted);
}
.legendSwatch {
display: inline-block;
width: 20px;
height: 0;
border-top: 3px solid var(--line-strong);
}
.legendPower {
border-top-color: var(--power);
}
.legendGround {
border-top-color: var(--ground);
}
.legendClock {
border-top-color: var(--clock);
}
.legendSignal {
border-top-color: var(--signal);
}
.legendAnalog {
border-top-color: var(--analog);
}
.card {
border: 1px solid var(--line);
border-radius: 8px;
border-radius: var(--radius-sm);
background: var(--panel-strong);
padding: 8px;
color: var(--ink-soft);
color: var(--ink-muted);
font-size: 0.85rem;
white-space: pre-wrap;
}
@@ -210,9 +378,9 @@ textarea {
.editorCard {
margin-top: 8px;
border: 1px solid var(--line);
border-radius: 8px;
padding: 8px;
background: #fcfcfd;
border-radius: var(--radius-sm);
padding: 9px;
background: color-mix(in oklab, var(--panel-strong) 86%, var(--panel));
display: flex;
flex-direction: column;
gap: 8px;
@@ -220,9 +388,10 @@ textarea {
.editorSection {
border: 1px solid var(--line);
border-radius: 8px;
border-radius: var(--radius-sm);
margin-top: 8px;
background: #fff;
background: color-mix(in oklab, var(--panel-strong) 88%, transparent);
overflow: hidden;
}
.editorSection > summary {
@@ -232,11 +401,15 @@ textarea {
font-size: 0.8rem;
font-weight: 700;
color: var(--ink);
border-bottom: 1px solid transparent;
}
.editorSection > summary:hover {
background: color-mix(in oklab, var(--accent-soft) 60%, var(--panel-strong));
}
.editorSection[open] > summary {
border-bottom-color: var(--line);
border-bottom: 1px solid var(--line);
background: color-mix(in oklab, var(--accent-soft) 76%, var(--panel-strong));
}
.editorSection > summary::-webkit-details-marker {
@@ -251,27 +424,27 @@ textarea {
.editorActions {
display: flex;
gap: 8px;
flex-wrap: wrap;
gap: 8px;
}
.hintText {
font-size: 0.8rem;
color: var(--ink-soft);
color: var(--ink-muted);
}
.miniList {
border: 1px solid var(--line);
border-radius: 8px;
background: #fff;
max-height: 170px;
border-radius: var(--radius-sm);
background: var(--panel-strong);
max-height: 180px;
overflow: auto;
}
.miniRow {
display: flex;
justify-content: space-between;
align-items: center;
justify-content: space-between;
gap: 8px;
padding: 6px 8px;
border-bottom: 1px solid var(--line);
@@ -284,47 +457,67 @@ textarea {
.symbolPinRow {
display: grid;
grid-template-columns: 1fr 0.9fr 0.9fr 0.8fr 1fr auto auto auto;
align-items: center;
align-items: start;
grid-template-columns: 1fr;
gap: 6px;
}
.symbolPinMain {
display: grid;
grid-template-columns: minmax(72px, 1fr) minmax(58px, 0.8fr) minmax(76px, 0.9fr) minmax(66px, 0.7fr) minmax(110px, 1fr);
gap: 6px;
}
.symbolPinActions {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 6px;
}
.symbolPinActions button {
min-width: 0;
padding: 4px 6px;
font-size: 0.75rem;
}
.pinCol {
min-width: 0;
padding: 5px 6px;
font-size: 0.75rem;
font-size: 0.76rem;
}
.symbolPinRow.invalidRow {
background: #fff3f2;
background: #fff3f1;
}
.symbolValidationError {
color: var(--error);
color: var(--err);
font-size: 0.76rem;
}
.migrationPreview {
border: 1px solid var(--line);
border-radius: 8px;
border-radius: var(--radius-sm);
padding: 8px;
background: #f8fafc;
margin-top: 6px;
margin-bottom: 6px;
margin: 6px 0;
line-height: 1.35;
background: #f5f9ff;
}
.canvasTools {
display: flex;
gap: 8px;
align-items: center;
border-bottom: 1px solid var(--line);
gap: 8px;
padding: 8px;
border-bottom: 1px solid var(--line);
background: linear-gradient(180deg, color-mix(in oklab, var(--panel-strong) 90%, #ffffff), var(--panel));
}
#compileStatus {
margin-left: auto;
color: var(--ink-soft);
color: var(--ink-muted);
font-size: 0.84rem;
font-weight: 600;
}
.status-ok {
@@ -333,12 +526,14 @@ textarea {
.canvasViewport {
height: calc(100% - 52px);
overflow: hidden;
position: relative;
overflow: hidden;
cursor: grab;
background-image: linear-gradient(0deg, #ebeff3 1px, transparent 1px),
linear-gradient(90deg, #ebeff3 1px, transparent 1px);
background-size: 20px 20px;
background:
linear-gradient(0deg, color-mix(in oklab, var(--line) 72%, transparent) 1px, transparent 1px),
linear-gradient(90deg, color-mix(in oklab, var(--line) 72%, transparent) 1px, transparent 1px),
linear-gradient(180deg, var(--canvas), color-mix(in oklab, var(--canvas) 82%, #1c2f49));
background-size: 20px 20px, 20px 20px, auto;
}
.canvasViewport.dragging {
@@ -346,10 +541,10 @@ textarea {
}
.canvasInner {
transform-origin: 0 0;
position: absolute;
left: 0;
top: 0;
left: 0;
transform-origin: 0 0;
}
.canvasInner svg {
@@ -358,10 +553,38 @@ textarea {
.selectionBox {
position: absolute;
border: 1px solid #155eef;
background: rgba(21, 94, 239, 0.12);
pointer-events: none;
z-index: 15;
pointer-events: none;
border: 1px solid var(--accent);
background: rgba(21, 101, 216, 0.12);
}
.pinTooltip {
position: absolute;
z-index: 20;
pointer-events: none;
border: 1px solid var(--line);
border-radius: var(--radius-sm);
padding: 6px 8px;
color: var(--ink);
background: color-mix(in oklab, var(--panel-strong) 92%, transparent);
box-shadow: var(--shadow-2);
font-size: 0.74rem;
}
.selectedNoteHint {
position: absolute;
z-index: 18;
pointer-events: none;
max-width: min(460px, 56vw);
border: 1px solid var(--line);
border-radius: 10px;
background: color-mix(in oklab, var(--panel-strong) 92%, transparent);
color: var(--ink);
box-shadow: var(--shadow-2);
font-size: 0.78rem;
line-height: 1.35;
padding: 8px 10px;
}
.hidden {
@@ -375,72 +598,69 @@ textarea {
}
.jsonActions button {
font-size: 0.77rem;
padding: 4px 8px;
font-size: 0.78rem;
}
.jsonFeedback {
min-height: 18px;
color: var(--ink-soft);
font-size: 0.78rem;
margin-bottom: 6px;
color: var(--ink-muted);
font-size: 0.78rem;
}
.issueRow {
border: 1px solid var(--line);
border-radius: 7px;
border-radius: 8px;
padding: 7px;
margin-bottom: 6px;
cursor: pointer;
background: #fff;
background: var(--panel-strong);
}
.issueRow:hover {
background: #f8faff;
background: color-mix(in oklab, var(--accent-soft) 66%, var(--panel-strong));
}
.issueErr {
border-color: #fecdca;
background: #fff6f5;
border-color: #f3bab5;
background: #fff5f4;
}
.issueWarn {
border-color: #fedf89;
background: #fffcf5;
border-color: #f0d28b;
background: #fffaf0;
}
.issueTitle {
font-size: 0.8rem;
font-weight: 700;
color: var(--ink);
}
.issueMeta {
font-size: 0.72rem;
color: var(--ink-soft);
color: var(--ink-muted);
}
.pinTooltip {
position: absolute;
pointer-events: none;
padding: 6px 8px;
border: 1px solid var(--line);
border-radius: 8px;
background: #ffffffee;
color: var(--ink);
.issueActions {
margin-top: 6px;
}
.issueActions button {
font-size: 0.74rem;
z-index: 20;
box-shadow: 0 6px 20px rgba(16, 24, 40, 0.12);
padding: 3px 8px;
}
.modal {
position: fixed;
inset: 0;
background: rgba(15, 23, 42, 0.45);
z-index: 70;
display: flex;
align-items: center;
justify-content: center;
padding: 18px;
background: rgba(14, 22, 36, 0.54);
}
.modal.hidden {
@@ -450,30 +670,37 @@ textarea {
.modalCard {
width: min(1120px, 100%);
height: min(88vh, 900px);
background: #fff;
border: 1px solid var(--line);
border-radius: 12px;
border-radius: var(--radius-lg);
background: var(--panel-strong);
box-shadow: 0 24px 60px rgba(16, 24, 40, 0.24);
padding: 12px;
display: flex;
flex-direction: column;
gap: 8px;
}
.compactModal {
width: min(760px, 100%);
height: auto;
max-height: min(86vh, 760px);
}
.modalHead {
display: flex;
justify-content: space-between;
align-items: center;
justify-content: space-between;
gap: 10px;
}
.modalHead h3 {
margin: 0;
font-size: 0.95rem;
font-size: 0.96rem;
}
.modalHint {
margin: 0;
color: var(--ink-soft);
color: var(--ink-muted);
font-size: 0.8rem;
}
@@ -482,6 +709,69 @@ textarea {
min-height: 0;
}
.shortcutGrid {
display: grid;
grid-template-columns: 1fr;
gap: 8px;
overflow: auto;
padding-right: 4px;
}
.shortcutGrid > div {
display: flex;
justify-content: space-between;
gap: 10px;
border: 1px solid var(--line);
border-radius: var(--radius-sm);
padding: 8px 10px;
font-size: 0.86rem;
color: var(--ink-muted);
background: color-mix(in oklab, var(--panel-strong) 88%, var(--panel));
}
kbd {
display: inline-flex;
align-items: center;
border: 1px solid var(--line-strong);
border-bottom-width: 2px;
border-radius: 6px;
background: var(--panel-strong);
padding: 2px 6px;
color: var(--ink);
font-size: 0.74rem;
font-family: "JetBrains Mono", monospace;
}
.commandList {
border: 1px solid var(--line);
border-radius: var(--radius-sm);
overflow: auto;
max-height: 46vh;
background: var(--panel-strong);
}
.commandRow {
width: 100%;
border: none;
border-bottom: 1px solid var(--line);
border-radius: 0;
background: var(--panel-strong);
text-align: left;
box-shadow: none;
padding: 8px 10px;
color: var(--ink);
font-size: 0.84rem;
}
.commandRow:last-child {
border-bottom: none;
}
.commandRow:hover,
.commandRow.active {
background: color-mix(in oklab, var(--accent-soft) 70%, var(--panel-strong));
}
.flash {
animation: flashPulse 0.7s ease-in-out 0s 2;
}
@@ -495,14 +785,105 @@ textarea {
}
}
@media (max-width: 1460px) {
.workspace {
grid-template-columns: 248px minmax(420px, 1fr) 360px;
}
}
@media (max-width: 1300px) {
.workspace {
grid-template-columns: 1fr;
grid-template-rows: auto auto auto;
grid-template-rows: minmax(420px, 1fr) repeat(2, minmax(240px, auto));
grid-auto-flow: row;
gap: 12px;
height: auto;
}
.pane.center {
min-height: 560px;
order: -1;
min-height: 420px;
max-height: 58vh;
}
.pane.left,
.pane.right {
max-height: 320px;
overflow: hidden;
}
.pane.left .list,
.pane.right .miniList {
max-height: 160px;
}
.canvasViewport {
height: min(54vh, 520px);
}
}
@media (max-width: 820px) {
.topbar {
position: static;
flex-direction: column;
align-items: flex-start;
gap: 6px;
}
.brand h1 {
font-size: 1.3rem;
}
.brand {
width: 100%;
}
.actions {
width: 100%;
justify-content: flex-start;
flex-wrap: nowrap;
overflow-x: auto;
padding-bottom: 4px;
scrollbar-width: thin;
}
.actions button,
.actions select {
flex: 0 0 auto;
}
.actions::-webkit-scrollbar {
height: 6px;
}
.actions::-webkit-scrollbar-thumb {
background: var(--line-strong);
border-radius: 999px;
}
.workspace {
padding: 6px;
}
.editorGrid {
grid-template-columns: 1fr;
}
.symbolPinMain {
grid-template-columns: 1fr 1fr;
}
.jsonActions {
flex-direction: column;
gap: 4px;
}
.jsonActions button {
width: 100%;
}
.pane.left,
.pane.right {
max-height: 300px;
}
}
+87
View File
@@ -0,0 +1,87 @@
{
"name": "schemeta",
"version": "0.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "schemeta",
"version": "0.1.0",
"devDependencies": {
"pixelmatch": "^7.1.0",
"playwright": "^1.58.2",
"pngjs": "^7.0.0"
}
},
"node_modules/fsevents": {
"version": "2.3.2",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
"integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
"node_modules/pixelmatch": {
"version": "7.1.0",
"resolved": "https://registry.npmjs.org/pixelmatch/-/pixelmatch-7.1.0.tgz",
"integrity": "sha512-1wrVzJ2STrpmONHKBy228LM1b84msXDUoAzVEl0R8Mz4Ce6EPr+IVtxm8+yvrqLYMHswREkjYFaMxnyGnaY3Ng==",
"dev": true,
"license": "ISC",
"dependencies": {
"pngjs": "^7.0.0"
},
"bin": {
"pixelmatch": "bin/pixelmatch"
}
},
"node_modules/playwright": {
"version": "1.58.2",
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.58.2.tgz",
"integrity": "sha512-vA30H8Nvkq/cPBnNw4Q8TWz1EJyqgpuinBcHET0YVJVFldr8JDNiU9LaWAE1KqSkRYazuaBhTpB5ZzShOezQ6A==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright-core": "1.58.2"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=18"
},
"optionalDependencies": {
"fsevents": "2.3.2"
}
},
"node_modules/playwright-core": {
"version": "1.58.2",
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.58.2.tgz",
"integrity": "sha512-yZkEtftgwS8CsfYo7nm0KE8jsvm6i/PTgVtB8DL726wNf6H2IMsDuxCpJj59KDaxCtSnrWan2AeDqM7JBaultg==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"playwright-core": "cli.js"
},
"engines": {
"node": ">=18"
}
},
"node_modules/pngjs": {
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/pngjs/-/pngjs-7.0.0.tgz",
"integrity": "sha512-LKWqWJRhstyYo9pGvgor/ivk2w94eSjE3RGVuzLGlr3NmD8bf7RcYGze1mNdEHRP6TRP6rMuDHk5t44hnTRyow==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=14.19.0"
}
}
}
}
+19
View File
@@ -6,8 +6,27 @@
"type": "module",
"scripts": {
"start": "node src/server.js",
"start:legacy": "node src/server.js",
"dev": "node --watch src/server.js",
"dev:legacy": "node --watch src/server.js",
"frontend:legacy:start": "npm run start:legacy",
"frontend:legacy:dev": "npm run dev:legacy",
"test": "node --test",
"test:legacy": "node --test",
"test:ui": "node tests/ui-regression-runner.js",
"test:ui:update-baselines": "UPDATE_SNAPSHOTS=1 node tests/ui-regression-runner.js",
"frontend:react:dev": "node scripts/react-path.mjs dev",
"frontend:react:install": "npm --prefix frontend-react install",
"frontend:react:lint": "node scripts/react-path.mjs lint",
"frontend:react:test": "node scripts/react-path.mjs test",
"frontend:react:build": "node scripts/react-path.mjs build",
"frontend:react:check": "npm run frontend:react:lint && npm run frontend:react:test && npm run frontend:react:build",
"phase8:cutover:check": "node scripts/phase8-cutover-check.mjs",
"mcp": "node src/mcp-server.js"
},
"devDependencies": {
"pixelmatch": "^7.1.0",
"playwright": "^1.58.2",
"pngjs": "^7.0.0"
}
}
+93
View File
@@ -0,0 +1,93 @@
#!/usr/bin/env node
import { mkdirSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { spawnSync } from "node:child_process";
const startedAt = new Date();
const checks = [
{ id: "unit", label: "Backend unit/integration", cmd: "npm", args: ["run", "test"], retries: 0 },
{ id: "ui", label: "Legacy UI regression", cmd: "node", args: ["tests/ui-regression-runner.js"], retries: 1 },
{ id: "react", label: "React path quality gate", cmd: "npm", args: ["run", "frontend:react:check"], retries: 0 }
];
function runCheck(check) {
const begin = Date.now();
let proc = null;
let attempts = 0;
const maxAttempts = 1 + Number(check.retries ?? 0);
while (attempts < maxAttempts) {
attempts += 1;
proc = spawnSync(check.cmd, check.args, {
cwd: process.cwd(),
env: process.env,
encoding: "utf8",
maxBuffer: 10 * 1024 * 1024
});
if (proc.status === 0) {
break;
}
}
const durationMs = Date.now() - begin;
const errorText = proc?.error ? String(proc.error.message ?? proc.error) : "";
const skippedBySandbox = /EPERM/i.test(errorText);
const ok = skippedBySandbox || Boolean(proc && proc.status === 0);
return {
id: check.id,
label: check.label,
command: [check.cmd, ...check.args].join(" "),
ok,
status: proc?.status ?? 1,
signal: proc?.signal ?? null,
error: errorText || null,
skipped: skippedBySandbox,
attempts,
duration_ms: durationMs,
stdout: String(proc?.stdout ?? "").trim(),
stderr: String(proc?.stderr ?? "").trim()
};
}
const results = checks.map((check) => runCheck(check));
const allPass = results.every((result) => result.ok);
const report = {
generated_at: new Date().toISOString(),
started_at: startedAt.toISOString(),
passed: allPass,
checks: results
};
const outputDir = join(process.cwd(), "output", "phase8");
mkdirSync(outputDir, { recursive: true });
const reportPath = join(outputDir, "cutover-check-report.json");
writeFileSync(reportPath, JSON.stringify(report, null, 2));
for (const result of results) {
const prefix = result.ok ? "PASS" : "FAIL";
console.log(`[${prefix}] ${result.label} (${result.duration_ms}ms) :: ${result.command}`);
if (result.skipped) {
console.log(" skipped: process spawn restricted in current environment (EPERM).");
}
if (result.attempts > 1) {
console.log(` attempts: ${result.attempts}`);
}
if (!result.ok) {
if (result.stdout) {
console.log("--- stdout ---");
console.log(result.stdout.slice(-2000));
}
if (result.stderr) {
console.log("--- stderr ---");
console.log(result.stderr.slice(-2000));
}
}
}
console.log(`Report written to: ${reportPath}`);
if (!allPass) {
process.exit(1);
}
+40
View File
@@ -0,0 +1,40 @@
#!/usr/bin/env node
import { existsSync, readFileSync } from 'node:fs';
import { spawnSync } from 'node:child_process';
import path from 'node:path';
const command = process.argv[2];
if (!command) {
console.error('[react-path] Missing command argument (e.g. lint/test/build/dev).');
process.exit(1);
}
const reactDir = path.resolve(process.cwd(), 'frontend-react');
const reactPkgPath = path.join(reactDir, 'package.json');
const reactNodeModulesPath = path.join(reactDir, 'node_modules');
if (!existsSync(reactPkgPath)) {
console.log(`[react-path] Stub: frontend-react is not scaffolded yet. Skipping "${command}".`);
process.exit(0);
}
const reactPkg = JSON.parse(readFileSync(reactPkgPath, 'utf8'));
if (!reactPkg.scripts || !reactPkg.scripts[command]) {
console.log(`[react-path] Stub: frontend-react/package.json has no "${command}" script. Skipping.`);
process.exit(0);
}
if (!existsSync(reactNodeModulesPath)) {
console.log('[react-path] Stub: frontend-react dependencies are not installed. Skipping.');
process.exit(0);
}
const result = spawnSync('npm', ['--prefix', reactDir, 'run', command], {
stdio: 'inherit',
});
if (typeof result.status === 'number') {
process.exit(result.status);
}
process.exit(1);
+8 -1
View File
@@ -1,5 +1,5 @@
import { analyzeModel } from "./analyze.js";
import { layoutAndRoute } from "./layout.js";
import { DEFAULT_LAYOUT_ENGINE, layoutAndRoute, requestedLayoutEngine } from "./layout.js";
import { renderSvgFromLayout } from "./render.js";
import { validateModel } from "./validate.js";
@@ -239,6 +239,7 @@ function annotateIssues(issues, prefix) {
export function compile(payload, options = {}) {
const validated = validateModel(payload, options);
const layoutEngineRequested = requestedLayoutEngine(options);
if (!validated.model) {
const errors = annotateIssues(validated.issues.filter((x) => x.severity === "error"), "E");
@@ -266,6 +267,9 @@ export function compile(payload, options = {}) {
bus_groups: [],
focus_map: {},
render_mode_used: options.render_mode ?? "schematic_stub",
layout_engine_requested: layoutEngineRequested,
layout_engine_used: DEFAULT_LAYOUT_ENGINE,
layout_warnings: [],
svg: ""
};
}
@@ -300,6 +304,9 @@ export function compile(payload, options = {}) {
layout_metrics: layout.metrics,
bus_groups: layout.bus_groups,
render_mode_used: layout.render_mode_used,
layout_engine_requested: layout.layout_engine_requested ?? layoutEngineRequested,
layout_engine_used: layout.layout_engine_used ?? DEFAULT_LAYOUT_ENGINE,
layout_warnings: Array.isArray(layout.layout_warnings) ? layout.layout_warnings : [],
svg
};
}
+62
View File
@@ -0,0 +1,62 @@
import { createRequire } from "node:module";
const require = createRequire(import.meta.url);
const DEFAULT_ELK_MODULE = "elkjs/lib/elk.bundled.js";
const runtimeCache = new Map();
function normalizeElkExport(mod) {
if (!mod) {
return null;
}
if (typeof mod === "function") {
return mod;
}
if (typeof mod.default === "function") {
return mod.default;
}
if (typeof mod.ELK === "function") {
return mod.ELK;
}
if (mod.default && typeof mod.default.ELK === "function") {
return mod.default.ELK;
}
return null;
}
export function resolveElkRuntime(moduleId = DEFAULT_ELK_MODULE) {
const key = String(moduleId || DEFAULT_ELK_MODULE);
if (runtimeCache.has(key)) {
return runtimeCache.get(key);
}
let state;
try {
const loaded = require(key);
const ElkCtor = normalizeElkExport(loaded);
if (!ElkCtor) {
state = {
ok: false,
module: key,
reason: "invalid_export",
message: `ELK module "${key}" loaded but did not expose a usable constructor.`
};
} else {
state = {
ok: true,
module: key,
ElkCtor
};
}
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
state = {
ok: false,
module: key,
reason: "module_load_failed",
message: `ELK module "${key}" unavailable: ${message}`
};
}
runtimeCache.set(key, state);
return state;
}
+1202 -37
View File
File diff suppressed because it is too large. Load diff
+223 -36
View File
@@ -66,6 +66,31 @@ function truncate(text, max) {
return `${s.slice(0, Math.max(1, max - 1))}...`;
}
function wrapTextLine(text, maxChars) {
const words = String(text ?? "").trim().split(/\s+/).filter(Boolean);
if (!words.length) {
return [];
}
const lines = [];
let current = "";
for (const word of words) {
if (!current) {
current = word;
continue;
}
if (`${current} ${word}`.length <= maxChars) {
current = `${current} ${word}`;
continue;
}
lines.push(current);
current = word;
}
if (current) {
lines.push(current);
}
return lines;
}
function netColor(netClass) {
return NET_COLORS[netClass] ?? NET_COLORS.signal;
}
@@ -191,7 +216,39 @@ function distance(a, b) {
return Math.hypot(a.x - b.x, a.y - b.y);
}
function pickLabelPoints(points, maxCount, used, minSpacing, avoidPoints = []) {
function rectFromLabelPoint(point, width = 78, height = 14) {
return {
x: point.x - 2,
y: point.y - height + 2,
width,
height
};
}
function rectsOverlap(a, b) {
return a.x < b.x + b.width && a.x + a.width > b.x && a.y < b.y + b.height && a.y + a.height > b.y;
}
function pointInRect(point, rect) {
return point.x >= rect.x && point.x <= rect.x + rect.width && point.y >= rect.y && point.y <= rect.y + rect.height;
}
function withCandidateOffsets(point) {
const offsets = [
[0, 0],
[0, -10],
[0, 10],
[10, 0],
[-10, 0],
[14, -10],
[-14, -10],
[14, 10],
[-14, 10]
];
return offsets.map(([dx, dy]) => ({ x: point.x + dx, y: point.y + dy }));
}
function pickLabelPoints(points, maxCount, used, usedRects, minSpacing, avoidPoints = [], blockedRects = []) {
const accepted = [];
for (const p of points) {
@@ -199,34 +256,81 @@ function pickLabelPoints(points, maxCount, used, minSpacing, avoidPoints = []) {
break;
}
let blocked = false;
for (const prev of used) {
if (distance(p, prev) < minSpacing) {
blocked = true;
break;
const candidates = withCandidateOffsets(p);
for (const candidate of candidates) {
let blocked = false;
for (const prev of used) {
if (distance(candidate, prev) < minSpacing) {
blocked = true;
break;
}
}
}
if (blocked) {
continue;
}
for (const pin of avoidPoints) {
if (distance(p, pin) < minSpacing * 0.9) {
blocked = true;
break;
if (blocked) {
continue;
}
}
if (blocked) {
continue;
}
accepted.push(p);
used.push(p);
for (const pin of avoidPoints) {
if (distance(candidate, pin) < minSpacing * 0.9) {
blocked = true;
break;
}
}
if (blocked) {
continue;
}
const labelRect = rectFromLabelPoint(candidate);
for (const usedRect of usedRects) {
if (rectsOverlap(labelRect, usedRect)) {
blocked = true;
break;
}
}
if (blocked) {
continue;
}
for (const blockedRect of blockedRects) {
if (rectsOverlap(labelRect, blockedRect) || pointInRect(candidate, blockedRect)) {
blocked = true;
break;
}
}
if (blocked) {
continue;
}
accepted.push(candidate);
used.push(candidate);
usedRects.push(labelRect);
break;
}
}
return accepted;
}
function placePinText(side, desired, occupiedBySide, minStep) {
const occupied = occupiedBySide[side] ?? [];
if (side === "left" || side === "right") {
let y = desired.y;
while (occupied.some((value) => Math.abs(value - y) < minStep)) {
y += minStep;
}
occupied.push(y);
occupiedBySide[side] = occupied;
return { x: desired.x, y };
}
let x = desired.x;
while (occupied.some((value) => Math.abs(value - x) < minStep)) {
x += minStep;
}
occupied.push(x);
occupiedBySide[side] = occupied;
return { x, y: desired.y };
}
function renderGroundSymbol(x, y, netName) {
const y0 = y + 3;
const y1 = y + 7;
@@ -281,7 +385,7 @@ function representativePoint(routeInfo, netAnchor) {
return netAnchor;
}
function renderLegend() {
function renderLegend(offsetY = 14) {
const entries = [
["power", "Power"],
["ground", "Ground"],
@@ -298,17 +402,50 @@ function renderLegend() {
.join("");
return `
<g data-layer="legend" transform="translate(14 14)">
<g data-layer="legend" transform="translate(14 ${offsetY})">
<rect x="-8" y="-8" width="120" height="82" rx="6" fill="#ffffffd8" stroke="#d0d5dd" />
${rows}
</g>`;
}
function renderAnnotationPanel(entries, maxWidth = 380) {
if (!entries.length) {
return { svg: "", width: 0, height: 0 };
}
const panelX = 14;
const panelY = 14;
const rowHeight = 14;
const panelWidth = Math.max(260, Math.min(420, Math.round(maxWidth)));
const charsPerRow = Math.max(28, Math.floor((panelWidth - 16) / 6.2));
const wrapped = entries
.flatMap((line) => wrapTextLine(line, charsPerRow).map((seg) => truncate(seg, charsPerRow)))
.slice(0, 8);
const panelHeight = 12 + wrapped.length * rowHeight;
const textRows = wrapped
.map(
(line, idx) =>
`<text x="${panelX + 8}" y="${panelY + 18 + idx * rowHeight}" font-size="10.5" fill="#6b7280">${esc(line)}</text>`
)
.join("\n");
const svg = `
<g data-layer="annotation-panel">
<rect x="${panelX}" y="${panelY}" width="${panelWidth}" height="${panelHeight}" rx="6" fill="#ffffffde" stroke="#d0d5dd" />
${textRows}
</g>`;
return { svg, x: panelX, y: panelY, width: panelWidth, height: panelHeight };
}
export function renderSvgFromLayout(model, layout, options = {}) {
const showLabels = options.show_labels !== false;
const showAnnotations = options.show_annotations !== false;
const showLegend = options.show_legend !== false;
const pinNets = pinNetMap(model);
const netClassByName = new Map((model.nets ?? []).map((n) => [n.name, n.class]));
const allPinPoints = [];
const componentRects = [];
const components = layout.placed
.map((inst) => {
@@ -318,6 +455,12 @@ export function renderSvgFromLayout(model, layout, options = {}) {
const rotation = normalizeRotation(inst.placement.rotation ?? 0);
const cx = x + sym.body.width / 2;
const cy = y + sym.body.height / 2;
componentRects.push({
x: x - 6,
y: y - 6,
width: sym.body.width + 12,
height: sym.body.height + 12
});
const templateKind = symbolTemplateKind(sym);
const compactLabel = templateKind || sym.body.width <= 140 || sym.body.height <= 90;
const legacyShowInstanceNetLabels = Boolean(inst.properties?.show_net_labels);
@@ -329,6 +472,8 @@ export function renderSvgFromLayout(model, layout, options = {}) {
const pinCircles = [];
const pinLabels = [];
const instanceNetLabels = [];
const pinLabelOccupied = { left: [], right: [], top: [], bottom: [] };
const netLabelOccupied = { left: [], right: [], top: [], bottom: [] };
for (const pin of sym.pins) {
let px = x;
let py = y;
@@ -375,6 +520,10 @@ export function renderSvgFromLayout(model, layout, options = {}) {
textAnchor = "start";
}
const pinTextPos = placePinText(rotatedSide, { x: labelX, y: labelY }, pinLabelOccupied, 11);
labelX = pinTextPos.x;
labelY = pinTextPos.y;
const showPinLabel = !templateKind || !/^\d+$/.test(pin.name);
if (showPinLabel) {
pinLabels.push(
@@ -413,6 +562,10 @@ export function renderSvgFromLayout(model, layout, options = {}) {
netAnchor = "start";
}
const netTextPos = placePinText(rotatedSide, { x: netX, y: netY }, netLabelOccupied, 13);
netX = netTextPos.x;
netY = netTextPos.y;
instanceNetLabels.push(
`<text x="${netX}" y="${netY}" text-anchor="${netAnchor}" font-size="10" font-weight="700" fill="${netColor(netClassByName.get(displayNet))}" stroke="#f8fafc" stroke-width="2.6" paint-order="stroke fill" data-net-label="${esc(displayNet)}" data-ref-net-label="${esc(inst.ref)}">${esc(displayNet)}</text>`
);
@@ -471,8 +624,21 @@ export function renderSvgFromLayout(model, layout, options = {}) {
const routedByName = new Map(layout.routed.map((r) => [r.net.name, r]));
const usedLabelPoints = [];
const usedLabelRects = [];
const labels = [];
const tieLabels = [];
const annotationLines = showAnnotations
? (model.annotations ?? []).map((a) => truncate(String(a.text ?? ""), 140)).filter(Boolean).slice(0, 6)
: [];
const annotationPanel = renderAnnotationPanel(annotationLines, (layout.width ?? 1200) * 0.36);
const legendY = annotationPanel.height > 0 ? annotationPanel.y + annotationPanel.height + 8 : 14;
const blockedLabelRects = [
...(annotationPanel.height > 0
? [{ x: annotationPanel.x - 2, y: annotationPanel.y - 2, width: annotationPanel.width + 4, height: annotationPanel.height + 4 }]
: []),
...(showLegend ? [{ x: 6, y: legendY - 8, width: 126, height: 86 }] : []),
...componentRects
];
for (const net of model.nets) {
if (isGroundLikeNet(net)) {
@@ -489,7 +655,15 @@ export function renderSvgFromLayout(model, layout, options = {}) {
if (routeInfo?.mode === "label_tie") {
candidates.push(...(routeInfo?.labelPoints ?? []));
const selected = pickLabelPoints(candidates, 1, usedLabelPoints, GRID * 2.4, allPinPoints);
const selected = pickLabelPoints(
candidates,
1,
usedLabelPoints,
usedLabelRects,
GRID * 2.4,
allPinPoints,
blockedLabelRects
);
for (const p of selected) {
labels.push(renderNetLabel(p.x, p.y, net.name, net.class, true));
}
@@ -499,11 +673,23 @@ export function renderSvgFromLayout(model, layout, options = {}) {
if (routeInfo?.labelPoints?.length) {
candidates.push(...routeInfo.labelPoints);
}
const routeCenter = representativePoint(routeInfo, netAnchor);
if (routeCenter) {
candidates.push({ x: routeCenter.x + 8, y: routeCenter.y - 8 });
}
if (netAnchor) {
candidates.push({ x: netAnchor.x + 8, y: netAnchor.y - 8 });
}
const selected = pickLabelPoints(candidates, 1, usedLabelPoints, GRID * 2.4, allPinPoints);
const selected = pickLabelPoints(
candidates,
1,
usedLabelPoints,
usedLabelRects,
GRID * 2.4,
allPinPoints,
blockedLabelRects
);
for (const p of selected) {
labels.push(renderNetLabel(p.x, p.y, net.name, net.class));
}
@@ -511,6 +697,7 @@ export function renderSvgFromLayout(model, layout, options = {}) {
if (showLabels) {
const usedTieLabels = [];
const usedTieRects = [];
for (const rn of layout.routed) {
if (rn.mode !== "label_tie" || isGroundLikeNet(rn.net)) {
continue;
@@ -522,7 +709,15 @@ export function renderSvgFromLayout(model, layout, options = {}) {
}
const maxPerNet = rn.net.class === "power" ? Math.min(6, candidates.length) : Math.min(2, candidates.length);
const selected = pickLabelPoints(candidates, maxPerNet, usedTieLabels, GRID * 1.5, allPinPoints);
const selected = pickLabelPoints(
candidates,
maxPerNet,
usedTieLabels,
usedTieRects,
GRID * 1.5,
allPinPoints,
blockedLabelRects
);
for (const p of selected) {
tieLabels.push(renderNetLabel(p.x, p.y, rn.net.name, rn.net.class, true));
}
@@ -553,14 +748,6 @@ export function renderSvgFromLayout(model, layout, options = {}) {
})
.join("\n");
const annotations = (model.annotations ?? [])
.map((a, idx) => {
const x = a.x ?? 16;
const y = a.y ?? 24 + idx * 16;
return `<text x="${x}" y="${y}" font-size="11" fill="#6b7280">${esc(a.text)}</text>`;
})
.join("\n");
const labelLayer = showLabels ? [...labels, ...tieLabels].join("\n") : "";
return `<?xml version="1.0" encoding="UTF-8"?>
@@ -574,8 +761,8 @@ export function renderSvgFromLayout(model, layout, options = {}) {
<g data-layer="ties">${tiePoints}</g>
<g data-layer="net-labels">${labelLayer}</g>
<g data-layer="bus-groups">${busLabels}</g>
<g data-layer="annotations">${annotations}</g>
${renderLegend()}
${annotationPanel.svg}
${showLegend ? renderLegend(legendY) : ""}
</svg>`;
}
+99 -31
View File
@@ -1,4 +1,5 @@
import { createServer } from "node:http";
import { randomUUID } from "node:crypto";
import { readFile } from "node:fs/promises";
import { extname, join, normalize } from "node:path";
import { pathToFileURL } from "node:url";
@@ -38,14 +39,18 @@ function json(res, status, payload) {
res.end(JSON.stringify(payload, null, 2));
}
export function errorEnvelope(code, message) {
return {
export function errorEnvelope(code, message, details = {}) {
const out = {
ok: false,
error: {
code,
message
}
};
if (details && typeof details === "object") {
Object.assign(out, details);
}
return out;
}
export function isAuthorizedRequest(req) {
@@ -149,11 +154,32 @@ export function parsePayloadOptions(body) {
}
export function withEnvelopeMeta(payload) {
return {
const out = {
api_version: API_VERSION,
schema_version: SCHEMA_VERSION,
...payload
};
if (!out.request_id && payload?.request_id) {
out.request_id = payload.request_id;
}
return out;
}
function requestIdFrom(req) {
const headerId = req.headers?.["x-request-id"];
if (typeof headerId === "string" && headerId.trim()) {
return headerId.trim().slice(0, 128);
}
return randomUUID();
}
function auditLog(entry) {
const line = {
ts: new Date().toISOString(),
service: "schemeta",
...entry
};
console.log(JSON.stringify(line));
}
function clientKey(req) {
@@ -194,8 +220,22 @@ function withinRateLimit(req) {
export function createRequestHandler() {
return async (req, res) => {
const requestId = requestIdFrom(req);
const startedAt = Date.now();
res.setHeader("x-request-id", requestId);
res.on("finish", () => {
auditLog({
request_id: requestId,
method: req.method,
path: req.url,
status: res.statusCode,
duration_ms: Date.now() - startedAt,
client: clientKey(req)
});
});
if (!req.url || !req.method) {
return json(res, 400, errorEnvelope("invalid_request", "Invalid request."));
return json(res, 400, errorEnvelope("invalid_request", "Invalid request.", { request_id: requestId }));
}
const pathname = new URL(req.url, "http://localhost").pathname;
@@ -211,6 +251,7 @@ export function createRequestHandler() {
return json(res, 200, {
ok: true,
service: "schemeta",
request_id: requestId,
api_version: API_VERSION,
schema_version: SCHEMA_VERSION,
status: "ok",
@@ -221,6 +262,7 @@ export function createRequestHandler() {
if (req.method === "GET" && pathname === "/mcp/ui-bundle") {
return json(res, 200, {
ok: true,
request_id: requestId,
name: "schemeta-workspace",
version: "0.2.0",
api_version: API_VERSION,
@@ -234,110 +276,136 @@ export function createRequestHandler() {
if (req.method === "POST" && pathname === "/analyze") {
if (!isAuthorizedRequest(req)) {
res.setHeader("WWW-Authenticate", "Bearer");
return json(res, 401, errorEnvelope("unauthorized", "Missing or invalid API token."));
return json(res, 401, errorEnvelope("unauthorized", "Missing or invalid API token.", { request_id: requestId }));
}
if (!withinRateLimit(req)) {
return json(res, 429, errorEnvelope("rate_limited", "Rate limit exceeded. Try again shortly."));
return json(res, 429, errorEnvelope("rate_limited", "Rate limit exceeded. Try again shortly.", { request_id: requestId }));
}
try {
const body = await readBody(req);
const parsed = parsePayloadOptions(body);
return json(res, 200, withEnvelopeMeta(analyze(parsed.payload, parsed.options)));
return json(res, 200, withEnvelopeMeta({ request_id: requestId, ...analyze(parsed.payload, parsed.options) }));
} catch (err) {
if (err?.code === "PAYLOAD_TOO_LARGE") {
return json(res, 413, errorEnvelope("payload_too_large", `Request body exceeds ${MAX_BODY_BYTES} bytes.`));
return json(res, 413, errorEnvelope("payload_too_large", `Request body exceeds ${MAX_BODY_BYTES} bytes.`, { request_id: requestId }));
}
if (err?.code === "INVALID_JSON") {
return json(res, 400, errorEnvelope("invalid_json", "Invalid JSON payload."));
return json(res, 400, errorEnvelope("invalid_json", "Invalid JSON payload.", { request_id: requestId }));
}
return json(res, 500, errorEnvelope("internal_error", "Request failed."));
return json(res, 500, errorEnvelope("internal_error", "Request failed.", { request_id: requestId }));
}
}
if (req.method === "POST" && pathname === "/compile") {
if (!isAuthorizedRequest(req)) {
res.setHeader("WWW-Authenticate", "Bearer");
return json(res, 401, errorEnvelope("unauthorized", "Missing or invalid API token."));
return json(res, 401, errorEnvelope("unauthorized", "Missing or invalid API token.", { request_id: requestId }));
}
if (!withinRateLimit(req)) {
return json(res, 429, errorEnvelope("rate_limited", "Rate limit exceeded. Try again shortly."));
return json(res, 429, errorEnvelope("rate_limited", "Rate limit exceeded. Try again shortly.", { request_id: requestId }));
}
try {
const body = await readBody(req);
const parsed = parsePayloadOptions(body);
return json(res, 200, withEnvelopeMeta(compile(parsed.payload, parsed.options)));
return json(res, 200, withEnvelopeMeta({ request_id: requestId, ...compile(parsed.payload, parsed.options) }));
} catch (err) {
if (err?.code === "PAYLOAD_TOO_LARGE") {
return json(res, 413, errorEnvelope("payload_too_large", `Request body exceeds ${MAX_BODY_BYTES} bytes.`));
return json(res, 413, errorEnvelope("payload_too_large", `Request body exceeds ${MAX_BODY_BYTES} bytes.`, { request_id: requestId }));
}
if (err?.code === "INVALID_JSON") {
return json(res, 400, errorEnvelope("invalid_json", "Invalid JSON payload."));
return json(res, 400, errorEnvelope("invalid_json", "Invalid JSON payload.", { request_id: requestId }));
}
return json(res, 500, errorEnvelope("internal_error", "Request failed."));
return json(res, 500, errorEnvelope("internal_error", "Request failed.", { request_id: requestId }));
}
}
if (req.method === "POST" && pathname === "/layout/auto") {
if (!isAuthorizedRequest(req)) {
res.setHeader("WWW-Authenticate", "Bearer");
return json(res, 401, errorEnvelope("unauthorized", "Missing or invalid API token."));
return json(res, 401, errorEnvelope("unauthorized", "Missing or invalid API token.", { request_id: requestId }));
}
if (!withinRateLimit(req)) {
return json(res, 429, errorEnvelope("rate_limited", "Rate limit exceeded. Try again shortly."));
return json(res, 429, errorEnvelope("rate_limited", "Rate limit exceeded. Try again shortly.", { request_id: requestId }));
}
try {
const body = await readBody(req);
const parsed = parsePayloadOptions(body);
const validated = validateModel(parsed.payload, parsed.options);
const model = validated.model ?? parsed.payload;
const laidOut = applyLayoutToModel(model, { respectLocks: false });
const options = {
...(parsed.options ?? {}),
use_elk_layout:
Object.prototype.hasOwnProperty.call(parsed.options ?? {}, "use_elk_layout")
? parsed.options.use_elk_layout
: true
};
const laidOut = applyLayoutToModel(model, { respectLocks: false, layoutOptions: options });
return json(res, 200, {
ok: true,
request_id: requestId,
api_version: API_VERSION,
schema_version: SCHEMA_VERSION,
model: laidOut,
compile: withEnvelopeMeta(compile(laidOut, parsed.options))
compile: withEnvelopeMeta(
compile(laidOut, {
...options,
preserve_placement: true
})
)
});
} catch (err) {
if (err?.code === "PAYLOAD_TOO_LARGE") {
return json(res, 413, errorEnvelope("payload_too_large", `Request body exceeds ${MAX_BODY_BYTES} bytes.`));
return json(res, 413, errorEnvelope("payload_too_large", `Request body exceeds ${MAX_BODY_BYTES} bytes.`, { request_id: requestId }));
}
if (err?.code === "INVALID_JSON") {
return json(res, 400, errorEnvelope("invalid_json", "Invalid JSON payload."));
return json(res, 400, errorEnvelope("invalid_json", "Invalid JSON payload.", { request_id: requestId }));
}
return json(res, 500, errorEnvelope("internal_error", "Layout auto failed."));
return json(res, 500, errorEnvelope("internal_error", "Layout auto failed.", { request_id: requestId }));
}
}
if (req.method === "POST" && pathname === "/layout/tidy") {
if (!isAuthorizedRequest(req)) {
res.setHeader("WWW-Authenticate", "Bearer");
return json(res, 401, errorEnvelope("unauthorized", "Missing or invalid API token."));
return json(res, 401, errorEnvelope("unauthorized", "Missing or invalid API token.", { request_id: requestId }));
}
if (!withinRateLimit(req)) {
return json(res, 429, errorEnvelope("rate_limited", "Rate limit exceeded. Try again shortly."));
return json(res, 429, errorEnvelope("rate_limited", "Rate limit exceeded. Try again shortly.", { request_id: requestId }));
}
try {
const body = await readBody(req);
const parsed = parsePayloadOptions(body);
const validated = validateModel(parsed.payload, parsed.options);
const model = validated.model ?? parsed.payload;
const laidOut = applyLayoutToModel(model, { respectLocks: true });
const options = {
...(parsed.options ?? {}),
use_elk_layout:
Object.prototype.hasOwnProperty.call(parsed.options ?? {}, "use_elk_layout")
? parsed.options.use_elk_layout
: true
};
const laidOut = applyLayoutToModel(model, { respectLocks: true, layoutOptions: options });
return json(res, 200, {
ok: true,
request_id: requestId,
api_version: API_VERSION,
schema_version: SCHEMA_VERSION,
model: laidOut,
compile: withEnvelopeMeta(compile(laidOut, parsed.options))
compile: withEnvelopeMeta(
compile(laidOut, {
...options,
preserve_placement: true
})
)
});
} catch (err) {
if (err?.code === "PAYLOAD_TOO_LARGE") {
return json(res, 413, errorEnvelope("payload_too_large", `Request body exceeds ${MAX_BODY_BYTES} bytes.`));
return json(res, 413, errorEnvelope("payload_too_large", `Request body exceeds ${MAX_BODY_BYTES} bytes.`, { request_id: requestId }));
}
if (err?.code === "INVALID_JSON") {
return json(res, 400, errorEnvelope("invalid_json", "Invalid JSON payload."));
return json(res, 400, errorEnvelope("invalid_json", "Invalid JSON payload.", { request_id: requestId }));
}
return json(res, 500, errorEnvelope("internal_error", "Layout tidy failed."));
return json(res, 500, errorEnvelope("internal_error", "Layout tidy failed.", { request_id: requestId }));
}
}
@@ -348,7 +416,7 @@ export function createRequestHandler() {
}
}
return json(res, 404, errorEnvelope("not_found", "Not found."));
return json(res, 404, errorEnvelope("not_found", "Not found.", { request_id: requestId }));
};
}
+100
View File
@@ -24,6 +24,8 @@ const GENERIC_DEFAULT_WIDTH = 160;
const GENERIC_MIN_HEIGHT = 120;
const GENERIC_PIN_STEP = 18;
const TEMPLATE_PIN_STEP = 24;
const MIN_SYMBOL_WIDTH = 96;
const MIN_SYMBOL_HEIGHT = 64;
const TEMPLATE_DEFS = {
resistor: {
@@ -230,6 +232,98 @@ function pinCountToHeight(pinCount) {
return Math.max(GENERIC_MIN_HEIGHT, rows * GENERIC_PIN_STEP);
}
function toNumericOffset(value, fallback) {
const n = Number(value);
return Number.isFinite(n) ? n : fallback;
}
function normalizeSymbolGeometry(sym, id, issues) {
if (!sym || typeof sym !== "object" || !Array.isArray(sym.pins) || sym.pins.length === 0) {
return;
}
const sideOrder = ["left", "right", "top", "bottom"];
const sideBuckets = new Map(sideOrder.map((side) => [side, []]));
for (const pin of sym.pins) {
const side = sideBuckets.has(pin.side) ? pin.side : "left";
sideBuckets.get(side).push(pin);
}
const maxPinsOnAnySide = Math.max(1, ...[...sideBuckets.values()].map((pins) => pins.length));
const basePinStep = hasTemplateName(sym) ? TEMPLATE_PIN_STEP : GENERIC_PIN_STEP;
const pinDensityBoost = Math.max(0, maxPinsOnAnySide - 4) * 2;
const pinStep = Math.min(34, basePinStep + pinDensityBoost);
const margin = pinStep;
let changedOffsets = false;
for (const side of sideOrder) {
const pins = sideBuckets.get(side);
pins.sort((a, b) => {
const ao = toNumericOffset(a.offset, margin);
const bo = toNumericOffset(b.offset, margin);
if (ao !== bo) return ao - bo;
return String(a.name ?? "").localeCompare(String(b.name ?? ""));
});
let next = margin;
for (const pin of pins) {
const current = toNumericOffset(pin.offset, next);
const normalized = Math.max(next, current);
if (pin.offset !== normalized) {
pin.offset = normalized;
changedOffsets = true;
}
next = normalized + pinStep;
}
}
const maxVerticalOffset = Math.max(
margin,
...[...(sideBuckets.get("left") ?? []), ...(sideBuckets.get("right") ?? [])].map((pin) =>
toNumericOffset(pin.offset, margin)
)
);
const maxHorizontalOffset = Math.max(
margin,
...[...(sideBuckets.get("top") ?? []), ...(sideBuckets.get("bottom") ?? [])].map((pin) =>
toNumericOffset(pin.offset, margin)
)
);
const verticalPins = Math.max((sideBuckets.get("left") ?? []).length, (sideBuckets.get("right") ?? []).length);
const horizontalPins = Math.max((sideBuckets.get("top") ?? []).length, (sideBuckets.get("bottom") ?? []).length);
const labelGutterX = Math.min(88, 24 + maxPinsOnAnySide * 4);
const labelGutterY = Math.min(52, 18 + Math.max(verticalPins, horizontalPins) * 2);
const requiredHeight = Math.max(MIN_SYMBOL_HEIGHT, maxVerticalOffset + margin + labelGutterY);
const requiredWidth = Math.max(MIN_SYMBOL_WIDTH, maxHorizontalOffset + margin + labelGutterX);
sym.body = sym.body ?? {};
const beforeWidth = toNumericOffset(sym.body.width, MIN_SYMBOL_WIDTH);
const beforeHeight = toNumericOffset(sym.body.height, MIN_SYMBOL_HEIGHT);
const nextWidth = Math.max(beforeWidth, requiredWidth);
const nextHeight = Math.max(beforeHeight, requiredHeight);
sym.body.width = nextWidth;
sym.body.height = nextHeight;
const desiredPinOrder = sideOrder.flatMap((side) => sideBuckets.get(side) ?? []);
const changedOrder =
desiredPinOrder.length === sym.pins.length &&
desiredPinOrder.some((pin, index) => pin !== sym.pins[index]);
if (changedOrder) {
sym.pins = desiredPinOrder;
}
if (changedOffsets || nextWidth !== beforeWidth || nextHeight !== beforeHeight || changedOrder) {
issues.push({
code: "symbol_geometry_adjusted",
message: `Adjusted symbol '${id}' geometry/pin spacing for readability.`,
severity: "warning",
path: `symbols.${id}`
});
}
}
function buildPinsFromUsage(ref, pinUsage) {
const names = [...pinUsage.values()].map((x) => x.pin).sort((a, b) => a.localeCompare(b));
if (!names.length) {
@@ -467,6 +561,12 @@ function ensureGenericSymbols(model, issues, enableGenericSymbols) {
}
}
for (const [id, sym] of Object.entries(next.symbols)) {
if (isGenericSymbol(sym) || hasTemplateName(sym)) {
normalizeSymbolGeometry(sym, id, issues);
}
}
for (const net of next.nets ?? []) {
for (const node of net.nodes ?? []) {
const inst = (next.instances ?? []).find((x) => x.ref === node.ref);
+7 -2
View File
@@ -17,15 +17,19 @@ import {
test("REST compile contract shape is stable with version metadata", () => {
const parsed = parsePayloadOptions({ payload: fixture, options: { render_mode: "schematic_stub" } });
const body = withRestEnvelopeMeta(compile(parsed.payload, parsed.options));
const body = withRestEnvelopeMeta({ request_id: "req-test-1", ...compile(parsed.payload, parsed.options) });
assert.equal(body.ok, true);
assert.equal(body.api_version, REST_API_VERSION);
assert.equal(body.schema_version, REST_SCHEMA_VERSION);
assert.equal(body.request_id, "req-test-1");
assert.ok(Array.isArray(body.errors));
assert.ok(Array.isArray(body.warnings));
assert.ok(Array.isArray(body.bus_groups));
assert.equal(typeof body.render_mode_used, "string");
assert.equal(typeof body.layout_engine_requested, "string");
assert.equal(typeof body.layout_engine_used, "string");
assert.ok(Array.isArray(body.layout_warnings));
assert.equal(typeof body.svg, "string");
});
@@ -42,10 +46,11 @@ test("REST analyze contract shape is stable with version metadata", () => {
});
test("REST error envelope exposes stable code/message fields", () => {
const body = errorEnvelope("rate_limited", "Rate limit exceeded. Try again shortly.");
const body = errorEnvelope("rate_limited", "Rate limit exceeded. Try again shortly.", { request_id: "req-test-2" });
assert.equal(body.ok, false);
assert.equal(body.error.code, "rate_limited");
assert.equal(typeof body.error.message, "string");
assert.equal(body.request_id, "req-test-2");
});
test("MCP schemeta_compile returns structured content with version metadata", () => {
Binary file not shown.

After

Width:  |  Height:  |  Size: 268 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 201 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 216 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 163 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 202 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 195 KiB

+44 -1
View File
@@ -1,5 +1,6 @@
import test from "node:test";
import assert from "node:assert/strict";
import path from "node:path";
import { compile } from "../src/compile.js";
import fixture from "../examples/esp32-audio.json" with { type: "json" };
@@ -36,6 +37,48 @@ test("compile accepts render mode options", () => {
assert.equal(result.render_mode_used, "explicit");
});
test("compile default layout engine path remains stable", () => {
const baseline = compile(fixture);
const explicitDefault = compile(fixture, { use_elk_layout: false });
assert.equal(baseline.ok, true);
assert.deepEqual(explicitDefault.layout, baseline.layout);
assert.deepEqual(explicitDefault.layout_metrics, baseline.layout_metrics);
assert.equal(baseline.layout_engine_requested, "schemeta-v2");
assert.equal(baseline.layout_engine_used, "schemeta-v2");
assert.deepEqual(baseline.layout_warnings, []);
});
test("compile accepts ELK layout flag option", () => {
const result = compile(fixture, {
use_elk_layout: true,
elk_runtime_module: path.resolve(process.cwd(), "tests/fixtures/mock-elk-runtime.cjs")
});
assert.equal(result.ok, true);
assert.equal(result.layout_engine_requested, "elk");
assert.equal(result.layout_engine_used, "elk");
assert.deepEqual(result.layout_warnings, []);
});
test("compile ELK fallback is deterministic when runtime is unavailable", () => {
const options = {
use_elk_layout: true,
elk_runtime_module: "__missing_elk_runtime_for_test__"
};
const runA = compile(fixture, options);
const runB = compile(fixture, options);
assert.equal(runA.ok, true);
assert.deepEqual(runB.layout, runA.layout);
assert.deepEqual(runB.layout_metrics, runA.layout_metrics);
assert.equal(runA.layout_engine_requested, "elk");
assert.equal(runA.layout_engine_used, "schemeta-v2");
assert.equal(runA.layout_warnings.length, 1);
assert.equal(runA.layout_warnings[0].code, "elk_layout_unavailable_fallback");
assert.deepEqual(runB.layout_warnings, runA.layout_warnings);
});
test("compile auto-creates generic symbols for unknown instances", () => {
const model = {
meta: { title: "Generic Demo" },
@@ -283,7 +326,7 @@ test("grouped auto-layout avoids tall single-column collapse", () => {
const widthSpread = Math.max(...xs) - Math.min(...xs);
const heightSpread = Math.max(...ys) - Math.min(...ys);
assert.ok(widthSpread > 500);
assert.ok(widthSpread > 420);
assert.ok(heightSpread < 900);
});
+21
View File
@@ -0,0 +1,21 @@
class MockElkRuntime {
layoutSync(graph) {
const children = Array.isArray(graph?.children) ? [...graph.children] : [];
const positioned = children.map((node, idx) => {
const col = idx % 4;
const row = Math.floor(idx / 4);
return {
...node,
x: 120 + col * 260,
y: 100 + row * 200
};
});
return {
id: graph?.id ?? "root",
children: positioned,
edges: Array.isArray(graph?.edges) ? graph.edges : []
};
}
}
module.exports = MockElkRuntime;
+1 -1
View File
@@ -15,5 +15,5 @@ test("render output for reference fixture remains deterministic", () => {
assert.equal(outA.ok, true);
assert.equal(outB.ok, true);
assert.equal(outA.svg, outB.svg);
assert.equal(svgHash(outA.svg), "c7a3cd161b6129b53e335d689e13b5425ccca6692f263245e3bf2d7b37aab06a");
assert.equal(svgHash(outA.svg), "fe431f62be90da91fbd707e1d2dae9286a04d61442893fa54fbebb048c748841");
});
+165
View File
@@ -0,0 +1,165 @@
import test from "node:test";
import assert from "node:assert/strict";
import fixture from "../frontend/sample.schemeta.json" with { type: "json" };
import { createSchemetaStore } from "../frontend-react/src/state/store.js";
function baseModel() {
return {
...fixture,
instances: fixture.instances.map((instance) => ({
...instance,
placement: {
...instance.placement
}
}))
};
}
test("setSelection normalizes and sorts refs deterministically", () => {
const store = createSchemetaStore();
store.actions.setSelection({
selectedRefs: ["U7", "U1", "U2", "U1", "U3"],
selectedNet: "I2C_SCL",
selectedPin: { ref: "U1", pin: "GPIO9" }
});
const { selection } = store.getState();
assert.deepEqual(selection.selectedRefs, ["U1", "U2", "U3", "U7"]);
assert.equal(selection.selectedNet, "I2C_SCL");
assert.deepEqual(selection.selectedPin, { ref: "U1", pin: "GPIO9" });
});
test("moveComponent only updates targeted instance and is deterministic", () => {
const model = baseModel();
const storeA = createSchemetaStore();
const storeB = createSchemetaStore();
storeA.actions.setModel(model);
storeA.actions.moveComponent("U1", { x: 121.7, y: 333.2 });
storeB.actions.setModel(model);
storeB.actions.moveComponent("U1", { x: 121.7, y: 333.2 });
const stateA = storeA.getState();
const stateB = storeB.getState();
assert.deepEqual(stateA.model, stateB.model);
const moved = stateA.model.instances.find((x) => x.ref === "U1");
assert.equal(moved.placement.x, 122);
assert.equal(moved.placement.y, 333);
const untouched = stateA.model.instances.find((x) => x.ref === "U2");
assert.equal(untouched.placement.x, null);
assert.equal(untouched.placement.y, null);
});
test("applyJsonText updates model on valid JSON and clears jsonError", () => {
const store = createSchemetaStore({
uiFlags: { jsonError: "Old error" }
});
const payload = JSON.stringify(baseModel());
const result = store.actions.applyJsonText(payload);
assert.equal(result.ok, true);
assert.equal(store.getState().uiFlags.jsonError, null);
assert.equal(store.getState().model.instances.length > 0, true);
});
test("applyJsonText reports parse errors without mutating model", () => {
const store = createSchemetaStore();
store.actions.setModel(baseModel());
const before = store.getState().model;
const result = store.actions.applyJsonText("{ bad json }");
assert.equal(result.ok, false);
assert.equal(typeof result.error, "string");
assert.equal(store.getState().uiFlags.jsonError.length > 0, true);
assert.deepEqual(store.getState().model, before);
});
test("undo/redo restores deterministic snapshots", () => {
const store = createSchemetaStore();
store.actions.setModel(baseModel());
store.actions.setSelection({ selectedRefs: ["U3", "U1"] });
const beforeMove = store.getState().model;
store.actions.moveComponent("U1", { x: 80, y: 60 });
assert.equal(store.getState().history.past.length >= 3, true);
store.actions.undo();
assert.deepEqual(store.getState().model, beforeMove);
store.actions.redo();
const moved = store.getState().model.instances.find((x) => x.ref === "U1");
assert.equal(moved.placement.x, 80);
assert.equal(moved.placement.y, 60);
});
test("transaction scaffold groups multiple actions into one undo step", () => {
const store = createSchemetaStore();
store.actions.setModel(baseModel());
const pastBefore = store.getState().history.past.length;
store.actions.beginTransaction("drag-and-select");
store.actions.moveComponent("U1", { x: 240, y: 140 });
store.actions.setSelection({ selectedRefs: ["U2", "U1"] });
store.actions.commitTransaction();
assert.equal(store.getState().history.past.length, pastBefore + 1);
assert.deepEqual(store.getState().selection.selectedRefs, ["U1", "U2"]);
store.actions.undo();
assert.deepEqual(store.getState().selection.selectedRefs, []);
const u1 = store.getState().model.instances.find((x) => x.ref === "U1");
assert.equal(u1.placement.x, null);
assert.equal(u1.placement.y, null);
});
test("compile lifecycle state transitions are deterministic", () => {
const storeA = createSchemetaStore();
const storeB = createSchemetaStore();
storeA.actions.beginCompile("Compile");
storeA.actions.failCompile("Compile", "Bad payload");
storeA.actions.beginCompile("Analyze");
storeA.actions.completeCompile("Analyze");
storeB.actions.beginCompile("Compile");
storeB.actions.failCompile("Compile", "Bad payload");
storeB.actions.beginCompile("Analyze");
storeB.actions.completeCompile("Analyze");
assert.deepEqual(storeA.getState().lifecycle, storeB.getState().lifecycle);
assert.equal(storeA.getState().lifecycle.isCompiling, false);
assert.equal(storeA.getState().lifecycle.lastError, null);
assert.equal(storeA.getState().lifecycle.lastAction, "Analyze");
});
test("compile lifecycle updates do not alter undo/redo history", () => {
const store = createSchemetaStore();
store.actions.setModel(baseModel());
store.actions.moveComponent("U1", { x: 90, y: 70 });
const beforeUndo = store.getState();
const pastBeforeLifecycle = beforeUndo.history.past.length;
store.actions.beginCompile("Compile");
store.actions.failCompile("Compile", "Synthetic error");
store.actions.beginCompile("Compile");
store.actions.completeCompile("Compile");
assert.equal(store.getState().history.past.length, pastBeforeLifecycle);
assert.equal(store.getState().lifecycle.lastAction, "Compile");
assert.equal(store.getState().lifecycle.lastError, null);
store.actions.undo();
const u1 = store.getState().model.instances.find((x) => x.ref === "U1");
assert.equal(u1.placement.x, null);
assert.equal(u1.placement.y, null);
});
+362
View File
@@ -0,0 +1,362 @@
import assert from "node:assert/strict";
import { spawn } from "node:child_process";
import { mkdir, readFile, writeFile, copyFile } from "node:fs/promises";
import { existsSync } from "node:fs";
import { dirname, join } from "node:path";
import { createServer as createNetServer } from "node:net";
import { PNG } from "pngjs";
import pixelmatch from "pixelmatch";
import { chromium } from "playwright";
const UPDATE_SNAPSHOTS = process.env.UPDATE_SNAPSHOTS === "1";
const MAX_DIFF_PIXELS = Number(process.env.UI_MAX_DIFF_PIXELS ?? 220);
const SAMPLE_MAX_CROSSINGS = Number(process.env.UI_SAMPLE_MAX_CROSSINGS ?? 1);
const SAMPLE_MAX_OVERLAPS = Number(process.env.UI_SAMPLE_MAX_OVERLAPS ?? 1);
const SAMPLE_MAX_DETOUR = Number(process.env.UI_SAMPLE_MAX_DETOUR ?? 3.6);
const DRAG_MAX_CROSSINGS = Number(process.env.UI_DRAG_MAX_CROSSINGS ?? 3);
const DRAG_MAX_OVERLAPS = Number(process.env.UI_DRAG_MAX_OVERLAPS ?? 3);
const DRAG_MAX_DETOUR = Number(process.env.UI_DRAG_MAX_DETOUR ?? 3.5);
const TIDY_MAX_CROSSINGS = Number(process.env.UI_TIDY_MAX_CROSSINGS ?? 2);
const TIDY_MAX_OVERLAPS = Number(process.env.UI_TIDY_MAX_OVERLAPS ?? 2);
const TIDY_MAX_DETOUR = Number(process.env.UI_TIDY_MAX_DETOUR ?? 4.5);
const DENSE_MAX_CROSSINGS = Number(process.env.UI_DENSE_MAX_CROSSINGS ?? 2);
const DENSE_MAX_OVERLAPS = Number(process.env.UI_DENSE_MAX_OVERLAPS ?? 2);
const DENSE_MAX_DETOUR = Number(process.env.UI_DENSE_MAX_DETOUR ?? 4.2);
const BASELINE_DIR = join(process.cwd(), "tests", "baselines", "ui");
const OUTPUT_DIR = join(process.cwd(), "output", "playwright");
const CURRENT_DIR = join(OUTPUT_DIR, "current");
const DIFF_DIR = join(OUTPUT_DIR, "diff");
const DENSE_ANALOG_PATH = join(process.cwd(), "examples", "dense-analog.json");
const REPORT_PATH = join(OUTPUT_DIR, "ui-metrics-report.json");
async function getFreePort() {
const probe = createNetServer();
await new Promise((resolve, reject) => {
probe.once("error", reject);
probe.listen(0, "127.0.0.1", resolve);
});
const addr = probe.address();
const port = typeof addr === "object" && addr ? addr.port : 8787;
await new Promise((resolve) => probe.close(resolve));
return port;
}
async function waitFor(predicate, timeoutMs = 10_000) {
const started = Date.now();
while (Date.now() - started < timeoutMs) {
try {
if (await predicate()) {
return;
}
} catch {}
await new Promise((resolve) => setTimeout(resolve, 80));
}
throw new Error(`Timed out after ${timeoutMs}ms`);
}
async function waitForCompileSettled(page, stableReads = 3, intervalMs = 120, timeoutMs = 5_000) {
const started = Date.now();
let previous = "";
let stable = 0;
while (Date.now() - started < timeoutMs) {
const status = String((await page.locator("#compileStatus").textContent()) ?? "").trim();
if (status && status.includes("Compiled")) {
if (status === previous) {
stable += 1;
if (stable >= stableReads) {
return status;
}
} else {
previous = status;
stable = 1;
}
}
await new Promise((resolve) => setTimeout(resolve, intervalMs));
}
throw new Error("Timed out waiting for compile status to settle");
}
async function startServer(port) {
const child = spawn("node", ["src/server.js"], {
cwd: process.cwd(),
env: { ...process.env, PORT: String(port) },
stdio: ["ignore", "pipe", "pipe"]
});
let stdout = "";
let stderr = "";
child.stdout.on("data", (d) => {
stdout += String(d);
});
child.stderr.on("data", (d) => {
stderr += String(d);
});
const baseUrl = `http://127.0.0.1:${port}`;
await waitFor(async () => {
const res = await fetch(`${baseUrl}/health`);
return res.ok;
});
return {
baseUrl,
async stop() {
if (child.exitCode !== null) return;
child.kill("SIGTERM");
await waitFor(() => child.exitCode !== null, 4_000).catch(() => {
throw new Error(`Server did not stop cleanly.\nstdout:\n${stdout}\nstderr:\n${stderr}`);
});
}
};
}
async function ensureDirs() {
await mkdir(BASELINE_DIR, { recursive: true });
await mkdir(CURRENT_DIR, { recursive: true });
await mkdir(DIFF_DIR, { recursive: true });
}
async function compareScene(page, scene) {
const currentPath = join(CURRENT_DIR, `${scene}.png`);
const baselinePath = join(BASELINE_DIR, `${scene}.png`);
const diffPath = join(DIFF_DIR, `${scene}.png`);
await page.screenshot({ path: currentPath, fullPage: true });
if (UPDATE_SNAPSHOTS || !existsSync(baselinePath)) {
await copyFile(currentPath, baselinePath);
return;
}
const [actualBuf, baselineBuf] = await Promise.all([readFile(currentPath), readFile(baselinePath)]);
const actual = PNG.sync.read(actualBuf);
const baseline = PNG.sync.read(baselineBuf);
assert.equal(actual.width, baseline.width, `scene '${scene}' width changed`);
assert.equal(actual.height, baseline.height, `scene '${scene}' height changed`);
const diff = new PNG({ width: actual.width, height: actual.height });
const diffPixels = pixelmatch(actual.data, baseline.data, diff.data, actual.width, actual.height, {
threshold: 0.15,
includeAA: false
});
if (diffPixels > MAX_DIFF_PIXELS) {
await writeFile(diffPath, PNG.sync.write(diff));
assert.fail(`scene '${scene}' changed: ${diffPixels} differing pixels (max ${MAX_DIFF_PIXELS}). diff: ${diffPath}`);
}
}
function parseStatusMetrics(statusText) {
const m = /(\d+)E,\s*(\d+)W\s*\|\s*(\d+)\s*crossings,\s*(\d+)\s*overlaps,\s*(\d+)\s*bends,\s*(\d+)\s*tie-nets,\s*([0-9.]+)x\s*detour/.exec(
statusText
);
if (!m) return null;
return {
errors: Number(m[1]),
warnings: Number(m[2]),
crossings: Number(m[3]),
overlaps: Number(m[4]),
bends: Number(m[5]),
tieNets: Number(m[6]),
detour: Number(m[7])
};
}
function parseZoomPercent(text) {
const m = /(\d+)%/.exec(String(text ?? ""));
return m ? Number(m[1]) : NaN;
}
async function run() {
await ensureDirs();
const port = await getFreePort();
const srv = await startServer(port);
const browser = await chromium.launch({ headless: true });
const page = await browser.newPage({ viewport: { width: 1600, height: 900 } });
await page.addInitScript(() => {
try {
window.localStorage?.clear();
window.sessionStorage?.clear();
} catch {}
});
const report = {
generated_at: new Date().toISOString(),
thresholds: {
sample: { crossings: SAMPLE_MAX_CROSSINGS, overlaps: SAMPLE_MAX_OVERLAPS, detour: SAMPLE_MAX_DETOUR },
drag: { crossings: DRAG_MAX_CROSSINGS, overlaps: DRAG_MAX_OVERLAPS, detour: DRAG_MAX_DETOUR },
tidy: { crossings: TIDY_MAX_CROSSINGS, overlaps: TIDY_MAX_OVERLAPS, detour: TIDY_MAX_DETOUR },
dense: { crossings: DENSE_MAX_CROSSINGS, overlaps: DENSE_MAX_OVERLAPS, detour: DENSE_MAX_DETOUR }
},
snapshots: {},
status: {}
};
try {
await page.goto(`${srv.baseUrl}/`);
await page.waitForSelector("#compileStatus");
await page.waitForFunction(() => document.querySelector("#compileStatus")?.textContent?.includes("Compiled"));
const initialStatus = String((await page.locator("#compileStatus").textContent()) ?? "");
const initialMetrics = parseStatusMetrics(initialStatus);
report.status.initial = { text: initialStatus, metrics: initialMetrics };
assert.ok(initialMetrics, `Unable to parse initial compile metrics from: ${initialStatus}`);
assert.ok(initialMetrics.crossings <= SAMPLE_MAX_CROSSINGS, `sample crossings too high: ${initialMetrics.crossings}`);
assert.ok(initialMetrics.overlaps <= SAMPLE_MAX_OVERLAPS, `sample overlaps too high: ${initialMetrics.overlaps}`);
assert.ok(initialMetrics.detour <= SAMPLE_MAX_DETOUR, `sample detour too high: ${initialMetrics.detour}`);
await compareScene(page, "initial");
report.snapshots.initial = "tests/baselines/ui/initial.png";
await page.keyboard.press("Control+k");
await page.getByRole("dialog", { name: "Command Palette" }).waitFor();
await page.locator("#commandInput").fill("fit");
await page.keyboard.press("Enter");
await page.waitForFunction(() => document.querySelector("#commandModal")?.classList.contains("hidden"));
await page.getByRole("button", { name: /Instance U2, symbol dac_i2s/ }).click();
await expectText(page, "#selectedSummary", /U2 \(dac_i2s\)/);
const preFocusZoom = parseZoomPercent(await page.locator("#zoomResetBtn").textContent());
await page.getByRole("button", { name: "Focus current selection" }).click();
const postFocusZoom = parseZoomPercent(await page.locator("#zoomResetBtn").textContent());
assert.ok(Number.isFinite(preFocusZoom) && Number.isFinite(postFocusZoom), "zoom label should remain parseable");
assert.ok(postFocusZoom >= preFocusZoom, `focus should not zoom out selected view (${preFocusZoom}% -> ${postFocusZoom}%)`);
await page.getByRole("button", { name: "Reset view" }).click();
await compareScene(page, "selected-u2");
const target = page.locator('[data-ref="U2"]');
const box = await target.boundingBox();
assert.ok(box, "selected U2 should be draggable");
await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
await page.mouse.down();
await page.mouse.move(box.x + box.width / 2 - 320, box.y + box.height / 2 + 220, { steps: 12 });
await page.mouse.up();
await page.waitForFunction(() => document.querySelector("#compileStatus")?.textContent?.includes("Compiled"));
const dragStatus = String((await page.locator("#compileStatus").textContent()) ?? "");
const dragMetrics = parseStatusMetrics(dragStatus);
report.status.after_drag = { text: dragStatus, metrics: dragMetrics };
assert.ok(dragMetrics, `Unable to parse drag compile metrics from: ${dragStatus}`);
assert.ok(dragMetrics.crossings <= DRAG_MAX_CROSSINGS, `dragged layout crossings too high: ${dragMetrics.crossings}`);
assert.ok(dragMetrics.overlaps <= DRAG_MAX_OVERLAPS, `dragged layout overlaps too high: ${dragMetrics.overlaps}`);
assert.ok(dragMetrics.detour <= DRAG_MAX_DETOUR, `dragged layout detour too high: ${dragMetrics.detour}`);
await page.getByRole("button", { name: "Run automatic tidy layout" }).click();
await page.waitForFunction(() => document.querySelector("#compileStatus")?.textContent?.includes("Compiled"));
const tidyStatus = String((await page.locator("#compileStatus").textContent()) ?? "");
const tidyMetrics = parseStatusMetrics(tidyStatus);
report.status.after_drag_tidy = { text: tidyStatus, metrics: tidyMetrics };
assert.ok(tidyMetrics, `Unable to parse tidy compile metrics from: ${tidyStatus}`);
assert.ok(tidyMetrics.crossings <= TIDY_MAX_CROSSINGS, `drag+tidy crossings too high: ${tidyMetrics.crossings}`);
assert.ok(tidyMetrics.overlaps <= TIDY_MAX_OVERLAPS, `drag+tidy overlaps too high: ${tidyMetrics.overlaps}`);
assert.ok(tidyMetrics.detour <= TIDY_MAX_DETOUR, `drag+tidy detour too high: ${tidyMetrics.detour}`);
await page.locator("#canvasViewport").click({ position: { x: 40, y: 40 } });
await expectText(page, "#selectedSummary", /Click a component, net, or pin/);
await page.getByRole("button", { name: "View Schema" }).click();
await page.getByRole("dialog", { name: "Schemeta JSON Schema" }).waitFor();
await page.getByRole("button", { name: "Close" }).click();
await page.waitForFunction(() => document.querySelector("#schemaModal")?.classList.contains("hidden"));
await page.getByRole("button", { name: /Instance U2, symbol dac_i2s/ }).click();
const rowForPin = await findSymbolPinRowIndex(page, "AOUT");
assert.ok(rowForPin >= 0, "AOUT pin row should exist");
page.once("dialog", (d) => d.dismiss());
await page.locator("#symbolPinsList .symbolPinRow").nth(rowForPin).getByRole("button", { name: "Remove" }).click();
assert.ok((await findSymbolPinRowIndex(page, "AOUT")) >= 0, "AOUT should remain after dismiss");
const rowForPin2 = await findSymbolPinRowIndex(page, "AOUT");
page.once("dialog", (d) => d.accept());
await page.locator("#symbolPinsList .symbolPinRow").nth(rowForPin2).getByRole("button", { name: "Remove" }).click();
assert.equal(await findSymbolPinRowIndex(page, "AOUT"), -1, "AOUT should be removed in draft");
await page.getByRole("button", { name: "Apply Symbol" }).click();
await expectText(page, "#jsonFeedback", /Destructive symbol edit detected/);
await page.getByRole("button", { name: "Preview Migration" }).click();
await page.getByRole("button", { name: "Apply Symbol" }).click();
await page.waitForFunction(() => document.querySelector("#compileStatus")?.textContent?.includes("Compiled"));
await expectText(page, "#symbolMeta", /\(5 pins\)/);
await compareScene(page, "post-migration-apply");
await page.selectOption("#renderModeSelect", "explicit");
await page.getByRole("button", { name: "Run automatic tidy layout" }).click();
const explicitStatus = await waitForCompileSettled(page);
assert.ok(/x detour/.test(explicitStatus ?? ""), "status should include detour metric in explicit mode");
await compareScene(page, "explicit-mode-auto-tidy");
await page.getByRole("button", { name: "Reset to deterministic sample baseline" }).click();
await page.waitForFunction(() => document.querySelector("#compileStatus")?.textContent?.includes("Compiled"));
await expectText(page, "#selectedSummary", /Click a component, net, or pin/);
await expectText(page, "#compileStatus", /x detour/);
const mode = await page.locator("#renderModeSelect").inputValue();
assert.equal(mode, "schematic_stub");
await page.locator("#newComponentTypeSelect").selectOption("resistor");
const beforeInstanceCount = await page.locator("[data-ref-item]").count();
await page.getByRole("button", { name: "Add Component" }).click();
await waitFor(async () => (await page.locator("[data-ref-item]").count()) >= beforeInstanceCount + 1);
const dense = await readFile(DENSE_ANALOG_PATH, "utf8");
await page.locator("#jsonEditor").fill(dense);
await page.getByRole("button", { name: "Apply JSON" }).click();
await expectText(page, "#jsonFeedback", /Applied JSON|blocked by validation/);
await page.waitForFunction(() => document.querySelector("#compileStatus")?.textContent?.includes("Compiled"));
const denseStatus = String((await page.locator("#compileStatus").textContent()) ?? "");
const denseFeedback = String((await page.locator("#jsonFeedback").textContent()) ?? "");
assert.ok(!/blocked by validation/i.test(denseFeedback), `dense fixture apply unexpectedly blocked: ${denseFeedback}`);
const metrics = parseStatusMetrics(denseStatus);
report.status.dense = { text: denseStatus, metrics, feedback: denseFeedback };
assert.ok(metrics, `Unable to parse compile status metrics from: ${denseStatus}`);
assert.equal(metrics.errors, 0, `dense analog scene should compile with no errors (feedback: ${denseFeedback})`);
assert.ok(metrics.crossings <= DENSE_MAX_CROSSINGS, `dense analog crossings too high: ${metrics.crossings}`);
assert.ok(metrics.overlaps <= DENSE_MAX_OVERLAPS, `dense analog overlaps too high: ${metrics.overlaps}`);
assert.ok(metrics.detour <= DENSE_MAX_DETOUR, `dense analog detour too high: ${metrics.detour}`);
await compareScene(page, "dense-analog");
report.snapshots.dense = "tests/baselines/ui/dense-analog.png";
await page.setViewportSize({ width: 1280, height: 720 });
await page.getByRole("button", { name: "Fit schematic to viewport" }).click();
await expectText(page, "#compileStatus", /Compiled/);
assert.ok(await page.locator("#applyJsonBtn").isVisible(), "Apply JSON button should remain visible at laptop viewport");
await compareScene(page, "laptop-viewport");
report.snapshots.laptop = "tests/baselines/ui/laptop-viewport.png";
const compileBeforeInvalidApply = String((await page.locator("#compileStatus").textContent()) ?? "");
await page.locator("#jsonEditor").fill("{\"meta\":{\"title\":\"invalid\"},\"instances\":[],\"nets\":[]}");
await page.getByRole("button", { name: "Apply JSON" }).click();
await expectText(page, "#jsonFeedback", /blocked by validation/i);
const compileAfterInvalidApply = String((await page.locator("#compileStatus").textContent()) ?? "");
assert.equal(
compileAfterInvalidApply,
compileBeforeInvalidApply,
"invalid JSON apply should not mutate compiled workspace state"
);
report.result = "pass";
} finally {
if (!report.result) {
report.result = "fail";
}
await writeFile(REPORT_PATH, `${JSON.stringify(report, null, 2)}\n`);
await page.close().catch(() => {});
await browser.close().catch(() => {});
await srv.stop().catch(() => {});
}
}
async function expectText(page, selector, pattern) {
await waitFor(async () => {
const text = await page.locator(selector).textContent();
return pattern.test(String(text ?? ""));
}, 10_000);
}
async function findSymbolPinRowIndex(page, pinName) {
return page.locator("#symbolPinsList .symbolPinRow .pinName").evaluateAll(
(nodes, target) => nodes.findIndex((node) => (node).value?.trim() === target),
pinName
);
}
run().catch((err) => {
console.error(err);
process.exit(1);
});
+93
View File
@@ -0,0 +1,93 @@
import test from "node:test";
import assert from "node:assert/strict";
import { validateModel } from "../src/validate.js";
test("validate normalizes dense symbol pin spacing and body size deterministically", () => {
const model = {
meta: { title: "Dense symbol test" },
symbols: {
dense: {
symbol_id: "dense",
category: "generic",
body: { width: 80, height: 40 },
pins: [
{ name: "A", number: "1", side: "left", offset: 4, type: "input" },
{ name: "B", number: "2", side: "left", offset: 6, type: "input" },
{ name: "Y", number: "3", side: "right", offset: 5, type: "output" },
{ name: "Z", number: "4", side: "right", offset: 7, type: "output" }
]
}
},
instances: [{ ref: "U1", symbol: "dense", placement: { x: 100, y: 100, rotation: 0, locked: false } }],
nets: [
{
name: "N1",
class: "signal",
nodes: [
{ ref: "U1", pin: "A" },
{ ref: "U1", pin: "Y" }
]
},
{
name: "N2",
class: "signal",
nodes: [
{ ref: "U1", pin: "B" },
{ ref: "U1", pin: "Z" }
]
}
]
};
const first = validateModel(model);
assert.ok(first.model);
const dense = first.model.symbols.dense;
assert.ok(dense.body.width >= 96);
assert.ok(dense.body.height >= 64);
const leftPins = dense.pins.filter((pin) => pin.side === "left");
const rightPins = dense.pins.filter((pin) => pin.side === "right");
assert.ok(leftPins[1].offset - leftPins[0].offset >= 18);
assert.ok(rightPins[1].offset - rightPins[0].offset >= 18);
assert.ok(first.issues.some((issue) => issue.code === "symbol_geometry_adjusted"));
const second = validateModel(first.model);
assert.ok(second.model);
assert.deepEqual(second.model.symbols.dense, first.model.symbols.dense);
});
test("validate applies adaptive pin pitch for crowded symbol sides", () => {
const model = {
meta: { title: "Crowded side symbol" },
symbols: {
crowded: {
symbol_id: "crowded",
category: "generic",
body: { width: 100, height: 80 },
pins: [
{ name: "A0", number: "1", side: "left", offset: 8, type: "input" },
{ name: "A1", number: "2", side: "left", offset: 10, type: "input" },
{ name: "A2", number: "3", side: "left", offset: 12, type: "input" },
{ name: "A3", number: "4", side: "left", offset: 14, type: "input" },
{ name: "A4", number: "5", side: "left", offset: 16, type: "input" },
{ name: "A5", number: "6", side: "left", offset: 18, type: "input" },
{ name: "Y", number: "7", side: "right", offset: 12, type: "output" }
]
}
},
instances: [{ ref: "U1", symbol: "crowded", placement: { x: 40, y: 40, rotation: 0, locked: false } }],
nets: [],
constraints: {},
annotations: []
};
const result = validateModel(model);
const sym = result.model?.symbols?.crowded;
assert.ok(sym);
const left = sym.pins.filter((pin) => pin.side === "left");
assert.ok(left[1].offset - left[0].offset >= 22);
assert.ok(sym.body.width >= 96);
assert.ok(sym.body.height >= 180);
assert.ok(result.issues.some((issue) => issue.code === "symbol_geometry_adjusted"));
});