diff --git a/.claude/settings.json b/.claude/settings.json index 8674c2107..08ea08efd 100644 --- a/.claude/settings.json +++ b/.claude/settings.json @@ -15,6 +15,7 @@ "Read(/hyperformula/test-jasmine/**)", "Read(/hyperformula/typedoc/**)", "Read(/hyperformula/storage/**)", + "Read(/hyperformula-ui/packages/core/dist/**)", "Read(/docs/functions/**)", "Read(/docs/.vuepress/dist/**)", "Read(/docs/.vuepress/api-sidebar.json)", diff --git a/.claude/skills/hyperformula-code-review/SKILL.md b/.claude/skills/hyperformula-code-review/SKILL.md index bb5d236f5..ab9046905 100644 --- a/.claude/skills/hyperformula-code-review/SKILL.md +++ b/.claude/skills/hyperformula-code-review/SKILL.md @@ -1,6 +1,6 @@ --- name: hyperformula-code-review -description: Use when reviewing a diff, a branch, or a pull request in the HyperFormula repository. Covers the review order, correctness and Excel compatibility for a calculation engine, performance on the hot paths, the six places a function change must touch, the public API, what the definition of done requires, and how to report findings. +description: Use when reviewing a diff, a branch, or a pull request in the HyperFormula repository, in the engine or in the hyperformula-ui formula editor. Covers the review order, correctness and Excel compatibility for a calculation engine, performance on the hot paths, the six places a function change must touch, the formula editor's invariants, the public API, what the definition of done requires, and how to report findings. --- ## 1. Read the relevant files from `dev-docs/` @@ -10,16 +10,21 @@ Always: | File | Why | |---|---| | [`CODE-REVIEW.md`](../../../dev-docs/CODE-REVIEW.md) | How to review: principles, review order, review-specific checks, reporting | -| [`REVIEWING.md`](../../../hyperformula/dev-docs/REVIEWING.md) | What to look for in each category of an engine change | | [`DEFINITION-OF-DONE.md`](../../../dev-docs/DEFINITION-OF-DONE.md) | What the change was required to contain | -| [`CODE-STYLE.md`](../../../dev-docs/CODE-STYLE.md) | Style, and which paths are hot enough that complexity matters | | [`TESTING.md`](../../../dev-docs/TESTING.md#a-test-must-prove-behaviour) | Whether the tests prove anything, or only execute code | -Then the page covering what the diff touches: [`ARCHITECTURE.md`](../../../hyperformula/dev-docs/ARCHITECTURE.md), [`PARSER.md`](../../../hyperformula/dev-docs/PARSER.md), [`INTERPRETER.md`](../../../hyperformula/dev-docs/INTERPRETER.md), [`DEPENDENCY-GRAPH.md`](../../../hyperformula/dev-docs/DEPENDENCY-GRAPH.md), [`FUNCTION-CATALOGUE.md`](../../../hyperformula/dev-docs/FUNCTION-CATALOGUE.md), [`I18N.md`](../../../hyperformula/dev-docs/I18N.md), [`LICENSING.md`](../../../hyperformula/dev-docs/LICENSING.md), [`EXCEL-COMPATIBILITY.md`](../../../hyperformula/dev-docs/EXCEL-COMPATIBILITY.md), [`PUBLIC-API.md`](../../../hyperformula/dev-docs/PUBLIC-API.md). +Then, for each part of the repository the diff touches: + +| Diff touches | Read | +|---|---| +| `hyperformula/` | [`REVIEWING.md`](../../../hyperformula/dev-docs/REVIEWING.md) for what to look for in each category, and [`CODE-STYLE.md`](../../../dev-docs/CODE-STYLE.md) for style and the hot paths | +| `hyperformula-ui/` | [`REVIEWING.md`](../../../hyperformula-ui/dev-docs/REVIEWING.md) for what to look for in each category, the editor's invariants among them, and [`CODE-STYLE.md`](../../../hyperformula-ui/dev-docs/CODE-STYLE.md) for its own conventions | + +For an engine change, also the page covering what the diff touches: [`ARCHITECTURE.md`](../../../hyperformula/dev-docs/ARCHITECTURE.md), [`PARSER.md`](../../../hyperformula/dev-docs/PARSER.md), [`INTERPRETER.md`](../../../hyperformula/dev-docs/INTERPRETER.md), [`DEPENDENCY-GRAPH.md`](../../../hyperformula/dev-docs/DEPENDENCY-GRAPH.md), [`FUNCTION-CATALOGUE.md`](../../../hyperformula/dev-docs/FUNCTION-CATALOGUE.md), [`I18N.md`](../../../hyperformula/dev-docs/I18N.md), [`LICENSING.md`](../../../hyperformula/dev-docs/LICENSING.md), [`EXCEL-COMPATIBILITY.md`](../../../hyperformula/dev-docs/EXCEL-COMPATIBILITY.md), [`PUBLIC-API.md`](../../../hyperformula/dev-docs/PUBLIC-API.md). ## 2. Work through them in order -1. Review each category in the [review order](../../../dev-docs/CODE-REVIEW.md#review-order), using the checks for it in [`REVIEWING.md`](../../../hyperformula/dev-docs/REVIEWING.md). Stop to report the first serious finding. +1. Review each category in the [review order](../../../dev-docs/CODE-REVIEW.md#review-order), using the checks for it in the `REVIEWING.md` of the part the diff touches. Stop to report the first serious finding. 2. Go through [The change follows our guidelines](../../../dev-docs/CODE-REVIEW.md#the-change-follows-our-guidelines) and the [review-specific checks](../../../dev-docs/CODE-REVIEW.md#review-specific-checks). ## 3. You report; the developer decides diff --git a/.claude/skills/hyperformula-ui-dev/SKILL.md b/.claude/skills/hyperformula-ui-dev/SKILL.md new file mode 100644 index 000000000..73981c50a --- /dev/null +++ b/.claude/skills/hyperformula-ui-dev/SKILL.md @@ -0,0 +1,39 @@ +--- +name: hyperformula-ui-dev +description: > + Use for ANY work in `hyperformula-ui/`: the formula editor package (`hyperformula-ui`, + in `hyperformula-ui/packages/core/`), its demo, its end-to-end suite, its build scripts + and its shared configuration. Covers the editor, the formula bar, the lexer, the kernel, + reference highlighting, autocomplete and function help popups, keyboard shortcuts, + `IGridAdapter`, the generated stylesheet and API docs, and releasing the package. Triggers + on file paths under `hyperformula-ui/`, or when the user describes a symptom in the formula + editor without naming a file. Its code style is not the engine's: load this skill instead + of `hyperformula-dev` for anything in this folder. +--- + +## 1. Read the relevant files from `dev-docs/` + +Always: + +| File | Why | +|---|---| +| [`ARCHITECTURE.md`](../../../hyperformula-ui/dev-docs/ARCHITECTURE.md) | The components, the data flow, and the invariants every change keeps | +| [`CODE-STYLE.md`](../../../hyperformula-ui/dev-docs/CODE-STYLE.md) | The conventions inside `hyperformula-ui/`, which differ from the engine's | +| [`DEFINITION-OF-DONE.md`](../../../dev-docs/DEFINITION-OF-DONE.md) | What the change must contain before review | + +Then the page for what you are changing: + +| File | For | +|---|---| +| [`EDITOR-TASKS.md`](../../../hyperformula-ui/dev-docs/EDITOR-TASKS.md) | Which files implement tokenization, shortcuts, highlights, popups and the overlay | +| [`KEYBOARD-SHORTCUTS.md`](../../../hyperformula-ui/dev-docs/KEYBOARD-SHORTCUTS.md) | Any change to what a key does | +| [`SPEC.md`](../../../hyperformula-ui/dev-docs/SPEC.md) | The public API, the adapter contract, CSS, and the commands | +| [`TESTING.md`](../../../hyperformula-ui/dev-docs/TESTING.md) | Writing the test the change needs | +| [`RELEASE.md`](../../../hyperformula-ui/dev-docs/RELEASE.md) | Publishing the package — only when asked to release | + +## 2. Work through them in order + +1. Find the files with [`EDITOR-TASKS.md`](../../../hyperformula-ui/dev-docs/EDITOR-TASKS.md), and the invariants they must keep with [Key invariants](../../../hyperformula-ui/dev-docs/ARCHITECTURE.md#key-invariants). +2. Write the failing test first — [New behaviour](../../../hyperformula-ui/dev-docs/TESTING.md#new-behaviour) — with skill `test-writing-discipline`. +3. Change the code, then run the checks in [Checks while you work](../../../hyperformula-ui/dev-docs/EDITOR-TASKS.md#checks-while-you-work). Name the workspace by path, as [`SPEC.md`](../../../hyperformula-ui/dev-docs/SPEC.md#12-build--commands) says. Regenerate the stylesheet or the API docs when the change affects them. +4. Add the entry to [`hyperformula-ui/CHANGELOG.md`](../../../hyperformula-ui/CHANGELOG.md) when the change is user-facing, and finish everything in [`DEFINITION-OF-DONE.md`](../../../dev-docs/DEFINITION-OF-DONE.md). diff --git a/.github/workflows/hyperformula-ui.yml b/.github/workflows/hyperformula-ui.yml new file mode 100644 index 000000000..282fd8560 --- /dev/null +++ b/.github/workflows/hyperformula-ui.yml @@ -0,0 +1,95 @@ +name: HyperFormula UI +permissions: + contents: read + +on: + pull_request: + types: + - opened + - reopened + - synchronize # the head branch is updated from the base branch, new commits are pushed to the head branch, or the base branch is changed + push: + branches: + - 'master' + - 'develop' + - 'release/**' + +jobs: + verify: + strategy: + matrix: + node-version: [ '22' ] + os: [ 'ubuntu-latest' ] + name: verify + runs-on: ${{ matrix.os }} + steps: + - name: Setup Node.js ${{ matrix.node-version }} + uses: actions/setup-node@56899e050abffc08c2b3b61f3ec6a79a9dc3223d # https://github.com/actions/setup-node/releases/tag/v1.4.4 + with: + node-version: ${{ matrix.node-version }} + + - name: Checkout main repository + uses: actions/checkout@722adc63f1aa60a57ec37892e133b1d319cae598 # https://github.com/actions/checkout/releases/tag/v2.0.0 + + - name: Install dependencies + run: npm ci + + - name: Build + run: npm run build:ui + + - name: Check the generated stylesheet is committed + run: git diff --exit-code -- 'hyperformula-ui/**/cssText.ts' + + - name: Check the generated API docs are committed + run: | + npm run docs --workspace=hyperformula-ui/packages/core + git diff --exit-code -- hyperformula-ui/packages/core/DOCS.md + + - name: Lint + run: npm run lint --workspace=hyperformula-ui/packages/core + + - name: Typecheck + run: npm run typecheck --workspace=hyperformula-ui/packages/core + + - name: Run unit tests + run: npm run test:ui + + - name: Check the package contents + run: npm pack --dry-run --workspace=hyperformula-ui/packages/core + + - name: Check the published types resolve under every module setting + run: npm run check:types --workspace=hyperformula-ui/packages/core + + e2e: + strategy: + matrix: + node-version: [ '22' ] + os: [ 'ubuntu-latest' ] + name: e2e + runs-on: ${{ matrix.os }} + steps: + - name: Setup Node.js ${{ matrix.node-version }} + uses: actions/setup-node@56899e050abffc08c2b3b61f3ec6a79a9dc3223d # https://github.com/actions/setup-node/releases/tag/v1.4.4 + with: + node-version: ${{ matrix.node-version }} + + - name: Checkout main repository + uses: actions/checkout@722adc63f1aa60a57ec37892e133b1d319cae598 # https://github.com/actions/checkout/releases/tag/v2.0.0 + + - name: Install dependencies + run: npm ci + + # The demo resolves hyperformula from this workspace, so the engine's bundles and typings must exist. + - name: Build the engine + run: npm run bundle-all + + - name: Lint and typecheck the demo and the suite + run: | + npm run lint --workspace=demo-js --workspace=@hfe-demo/shared --workspace=e2e + npm run typecheck --workspace=demo-js --workspace=@hfe-demo/shared --workspace=e2e + + - name: Install Chromium + run: npm exec --workspace=e2e -- playwright install --with-deps chromium + + - name: Run end-to-end tests + run: npm run test:e2e diff --git a/README.md b/README.md index 95bfecf3e..09a3ff6c5 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ This repository holds the engine and everything built around it. | Directory | What it is | Published as | |---|---|---| | [`hyperformula/`](hyperformula/) | The calculation engine. **Start here** — its [README](hyperformula/README.md) is the product documentation. | The [`hyperformula`](https://www.npmjs.com/package/hyperformula) package on npm: ES modules, CommonJS, UMD bundles for the browser (also served by the jsDelivr and unpkg CDNs), and TypeScript typings | -| [`hyperformula-ui/`](hyperformula-ui/) | UI components for working with HyperFormula: a group of packages, with their demos and end-to-end tests. Not imported yet. | Not yet — nothing is published from this directory until the packages are imported | +| [`hyperformula-ui/`](hyperformula-ui/) | UI components for working with HyperFormula: the formula editor package, an editor-only demo, and an end-to-end test. Its [README](hyperformula-ui/README.md) lists what is where. | The `hyperformula-ui` package on npm, once released: ES modules and TypeScript typings | | [`docs/`](docs/) | The documentation portal. Installed separately; not a workspace member. | Not a package. Built and deployed as the documentation site at [handsontable.com/docs/hyperformula](https://handsontable.com/docs/hyperformula/) | The engine's history is [`CHANGELOG.md`](CHANGELOG.md) at the root. The UI packages version and release on their own until they are mature, then join the engine's version — see [`dev-docs/STRUCTURE.md`](dev-docs/STRUCTURE.md#what-the-move-decided). diff --git a/dev-docs/AGENT-TOOLING.md b/dev-docs/AGENT-TOOLING.md index 95e41db9a..30ae6c411 100644 --- a/dev-docs/AGENT-TOOLING.md +++ b/dev-docs/AGENT-TOOLING.md @@ -40,6 +40,7 @@ A skill holds the **steps**: what to do, in what order, and what to check. It do | Skill | For | |---|---| | `hyperformula-dev` | Any work in `hyperformula/src/` — the entry point | +| `hyperformula-ui-dev` | Any work in `hyperformula-ui/` — the entry point for the formula editor | | `hyperformula-function-dev` | Adding or changing a built-in function | | `hyperformula-unit-testing` | Writing or modifying tests | | `test-writing-discipline` | Any red test, and any test that might be going green for the wrong reason | @@ -47,4 +48,4 @@ A skill holds the **steps**: what to do, in what order, and what to check. It do | `writing-docs-pages` | The documentation portal | | `changelog-creation` | The changelog entry | | `pr-creation` | Opening or updating a pull request | -| `hyperformula-code-review` | Reviewing a diff, a branch, or a pull request | +| `hyperformula-code-review` | Reviewing a diff, a branch, or a pull request, in the engine or the UI | diff --git a/dev-docs/BUILD.md b/dev-docs/BUILD.md index 8a72962ed..c1273b71a 100644 --- a/dev-docs/BUILD.md +++ b/dev-docs/BUILD.md @@ -40,13 +40,15 @@ Config is [`docs/wrangler.jsonc`](../docs/wrangler.jsonc); the Worker entry poin ## Release and licences -`npm run release` runs `script/release/release.sh`. Releasing is maintainer-owned — do not invent steps around it, and do not run it as part of another task. +`npm run release` runs `script/release/release.sh`, which releases the engine only. Releasing is maintainer-owned — do not invent steps around it, and do not run it as part of another task. + +The `hyperformula-ui` package is released by hand, on its own version line: [`hyperformula-ui/dev-docs/RELEASE.md`](../hyperformula-ui/dev-docs/RELEASE.md). `npm run check:licenses` asserts that every production dependency carries a permissive licence. ## Scripts and CI -Where each script lives and what calls it is in [`STRUCTURE.md`](STRUCTURE.md#scripts-at-three-levels). The release script keeps its own rules in [`script/release/release-README.md`](../script/release/release-README.md). +Where each script lives and what calls it is in [`STRUCTURE.md`](STRUCTURE.md#scripts-at-each-level). The release script keeps its own rules in [`script/release/release-README.md`](../script/release/release-README.md). - **A step runs in the workflow that needs it.** A step only the tests need belongs to the test workflows, not to `lint`. - **`pre*` and `post*` scripts run the way the scripts are actually called** — by CI, and on a maintainer's machine. npm skips them when `ignore-scripts` is set, which is why `script/release/release.sh` copies the root files itself before `npm publish` instead of trusting `prepack` alone. diff --git a/dev-docs/CODE-REVIEW.md b/dev-docs/CODE-REVIEW.md index c8a471400..d5c824406 100644 --- a/dev-docs/CODE-REVIEW.md +++ b/dev-docs/CODE-REVIEW.md @@ -41,7 +41,7 @@ Review in this order, and report the first serious finding rather than burying i 5. **Scope** — the pull request holds [one change](DEFINITION-OF-DONE.md#one-pull-request-one-change). Say so when unrelated changes have been folded in, rather than approving them through. 6. **Style, last and briefly** — ESLint owns formatting. Comment only on what it cannot check: a misleading name, a function doing two things, duplicated logic an existing helper already covers. -What to look for in each category in an engine change: [`hyperformula/dev-docs/REVIEWING.md`](../hyperformula/dev-docs/REVIEWING.md). +What to look for in each category in an engine change: [`hyperformula/dev-docs/REVIEWING.md`](../hyperformula/dev-docs/REVIEWING.md). In a `hyperformula-ui` change: [`hyperformula-ui/dev-docs/REVIEWING.md`](../hyperformula-ui/dev-docs/REVIEWING.md). ## The change follows our guidelines diff --git a/dev-docs/CODE-STYLE.md b/dev-docs/CODE-STYLE.md index eaadfdfe6..98a8f35c9 100644 --- a/dev-docs/CODE-STYLE.md +++ b/dev-docs/CODE-STYLE.md @@ -2,6 +2,8 @@ ESLint is the source of truth for formatting and code rules — run `npm run lint` before submitting changes (see [the linter section of the building guide](../docs/guide/building.md#run-the-linter)). Some of what follows it enforces, the `jsdoc` rules among them; the rest is what no linter can check for you. +Code in `hyperformula-ui/` follows its own conventions instead — Biome rather than ESLint, among others: [`hyperformula-ui/dev-docs/CODE-STYLE.md`](../hyperformula-ui/dev-docs/CODE-STYLE.md). + ## Style - Prefer a functional approach where possible (`filter`, `map`, `reduce`). diff --git a/dev-docs/DEFINITION-OF-DONE.md b/dev-docs/DEFINITION-OF-DONE.md index 4a699c01c..1692681df 100644 --- a/dev-docs/DEFINITION-OF-DONE.md +++ b/dev-docs/DEFINITION-OF-DONE.md @@ -32,7 +32,9 @@ npm run lint npm run test:jest ``` -Add `npm run test` (which includes the browser run) when the change touches bundling, module format, or anything browser-specific. Add `npm run docs:generate-function-docs` when it touches a function or its catalogue entry — from the repository root, after `npm run docs:install`, because the generator runs in the portal's own install. +Add `npm run test` (which includes the browser run) when the change touches bundling, module format, or anything browser-specific. + +A change in `hyperformula-ui/` runs its own gate instead, from the repository root: `npm run build:ui`, `npm run typecheck` and `npm run test:ui`, plus `npm run test:e2e` when it changes the demo or how the editor mounts in a page. See [`hyperformula-ui/dev-docs/TESTING.md`](../hyperformula-ui/dev-docs/TESTING.md). Add `npm run docs:generate-function-docs` when it touches a function or its catalogue entry — from the repository root, after `npm run docs:install`, because the generator runs in the portal's own install. Read the output. Do not open a pull request on a red run and describe it as ready. A green Jest run without the private suite covers only the smoke tests — see [Fetching the private suite](../hyperformula/dev-docs/TESTING.md#fetching-the-private-suite). A red CI job unrelated to the change is explained in the pull request and reported, not ignored. diff --git a/dev-docs/README.md b/dev-docs/README.md index 436d1d37d..d10e5d422 100644 --- a/dev-docs/README.md +++ b/dev-docs/README.md @@ -18,7 +18,7 @@ In every directory, `CLAUDE.md` is a symlink to its sibling `AGENTS.md`. Edit `A ## Where to look -Repository-wide standards and process live here. Each package documents its own internals: the engine's are in [`hyperformula/dev-docs/`](../hyperformula/dev-docs/README.md). +Repository-wide standards and process live here. Each package documents its own internals: the engine's are in [`hyperformula/dev-docs/`](../hyperformula/dev-docs/README.md), the UI's in [`hyperformula-ui/dev-docs/`](../hyperformula-ui/dev-docs/README.md). | You are working on | Read | |---|---| @@ -42,6 +42,12 @@ Inside the engine — architecture, the parser, the interpreter, the dependency |---|---| | Anything in `hyperformula/src/` | [`hyperformula/dev-docs/README.md`](../hyperformula/dev-docs/README.md) | +Inside the UI — the formula editor's architecture, its code style, its suites and its release: + +| You are working on | Read | +|---|---| +| Anything in `hyperformula-ui/` | [`hyperformula-ui/dev-docs/README.md`](../hyperformula-ui/dev-docs/README.md) | + Outside both: [`README.md`](../README.md) for what the repository holds, [`hyperformula/README.md`](../hyperformula/README.md) for what the engine is and how to install and use it, [`docs/README.md`](../docs/README.md) for running the documentation portal, [`hyperformula/test/README.md`](../hyperformula/test/README.md) for attaching the private test suite, and [`CONTRIBUTING.md`](../CONTRIBUTING.md) for external contributors. ## Conventions diff --git a/dev-docs/STRUCTURE.md b/dev-docs/STRUCTURE.md index e3601ef0b..d4b880d17 100644 --- a/dev-docs/STRUCTURE.md +++ b/dev-docs/STRUCTURE.md @@ -30,12 +30,14 @@ A monorepo. Three top-level directories hold code; the rest is repository-wide. │ ├── package.json README.md │ └── AGENTS.md CLAUDE.md │ -├── hyperformula-ui/ # ── a group of packages: UI components (not imported yet; planned layout below) -│ ├── packages/*/ # one directory per published package -│ ├── demo/*/ # demo applications (private) +├── hyperformula-ui/ # ── a group of packages: UI components +│ ├── packages/core/ # the hyperformula-ui package (published) +│ ├── demo/js/ demo/shared/ # the editor-only demo (private) │ ├── e2e/ # end-to-end suite (private) +│ ├── scripts/ # stylesheet and API docs generators, called by the core's build │ ├── dev-docs/ # the UI's own internals reference -│ └── AGENTS.md CLAUDE.md README.md, and its shared toolchain configuration +│ ├── tsconfig.*.json rspack.base.mjs vitest.base.ts biome.json # shared toolchain configuration +│ └── AGENTS.md CLAUDE.md README.md CHANGELOG.md │ ├── docs/ # ── the documentation portal (NOT a workspace member) │ ├── guide/ # Markdown guides @@ -63,30 +65,35 @@ A monorepo. Three top-level directories hold code; the rest is repository-wide. ## Workspaces -`workspaces` in the root `package.json` lists `hyperformula`. `npm ci` at the root installs it into a shared `node_modules`. `hyperformula-ui/` is a placeholder and is deliberately not listed yet — see [What the move still owes](#what-the-move-still-owes). +`workspaces` in the root `package.json` lists `hyperformula` and the UI's members. `npm ci` at the root installs them into a shared `node_modules`. -`hyperformula-ui/` will be a folder, not a package. npm does not support a workspace that declares workspaces of its own, so the root lists the UI's members directly: `hyperformula-ui/packages/*`, `hyperformula-ui/demo/*` and `hyperformula-ui/e2e`. +`hyperformula-ui/` is a folder, not a package. npm does not support a workspace that declares workspaces of its own, so the root lists the UI's members directly: `hyperformula-ui/packages/*`, `hyperformula-ui/demo/*` and `hyperformula-ui/e2e`. Name a UI workspace by path, `--workspace=hyperformula-ui/packages/core`: a bare `--workspace=hyperformula-ui` also matches workspaces by folder. + +The UI's packages declare their own TypeScript 5 and Biome, because the version npm hoists to the root is the engine's TypeScript 4. The demo and the end-to-end suite depend on `hyperformula` and resolve it from this workspace, so they need the engine built (`npm run bundle-all`) before they typecheck or run. The core package does not import the engine. **`docs/` is deliberately outside the workspace.** The criterion is age, not size. The portal runs on VuePress 1.x, which is end-of-life, builds with webpack 4, and only runs on current Node with `--openssl-legacy-provider`. In a shared install its old packages are hoisted to the root, where anything else can start resolving them by accident — the engine's language build required `fs-extra` without declaring it, and resolved the copy that only the portal's tree supplied. So it has its own `package.json` and installs separately with `npm run docs:install`. The leak runs the other way too: everything the portal imports — `chevrotain` for the grammar diagram, and the engine's ESLint plugins that `examples/eslintrc.examples.js` extends — is declared in `docs/package.json`, rather than resolved from the engine's copies at the root. The one exception is `.vuepress/subtheme/`: it is a typedoc theme that the engine's `typedoc:build-api` loads, so its `typedoc-plugin-markdown` must be the engine's copy, which `hyperformula/package.json` declares. -Size alone does not keep a package out. The UI's dependencies, its frameworks, grid libraries and browser test runner, are larger than the portal's but current, and the UI joins the workspace when it is imported. A root `npm ci` installs them too, so the contributor and CI install grows. What the published `hyperformula` package depends on does not change: those are the UI's own dependencies, not the engine's. +Size alone does not keep a package out. The UI's toolchain, its bundler, test runners and browser test runner, is current, so the UI is in the workspace. A root `npm ci` installs it too, so the contributor and CI install grows. What the published `hyperformula` package depends on does not change: those are the UI's own dependencies, not the engine's. ## Where a command runs | Command | Runs in | |---|---| -| `npm run lint` | Fanned out to every workspace that defines `lint`; each lints itself with its own configuration | +| `npm run lint`, `npm run typecheck` | Fanned out to every workspace that defines the script; each uses its own configuration | | `npm run docs:lint` | The portal's code — `.vuepress/` and `worker/` — with its own configuration, separate because the portal installs separately. Not the Markdown content, and not `examples/`, which `code-examples-generator.sh` formats | | `npm run test:jest`, `bundle-all`, `compile` | Fanned out to `hyperformula` | +| `npm run build:ui`, `test:ui`, `test:e2e`, `dev:ui` | Fanned out to the UI's core package, its end-to-end suite, and its demo | | `npm run docs:*` | Orchestrated from the root across both `hyperformula` and `docs` | Run a package's own scripts from its directory, or with `--workspace=hyperformula`. See [`BUILD.md`](BUILD.md). ## Build outputs -All git-ignored, all under `hyperformula/`: `lib/` (`tsc` output, the input to every bundle), `es/`, `commonjs/`, `dist/`, `languages/`, `typings/`. The portal's output is `docs/.vuepress/dist/`, and `docs/api/` plus `docs/guide/built-in-functions.md` are generated. +All git-ignored. Under `hyperformula/`: `lib/` (`tsc` output, the input to every bundle), `es/`, `commonjs/`, `dist/`, `languages/`, `typings/`. The UI's is `hyperformula-ui/packages/core/dist/`. The portal's output is `docs/.vuepress/dist/`, and `docs/api/` plus `docs/guide/built-in-functions.md` are generated. + +Two generated files in the UI are committed, not ignored: `hyperformula-ui/packages/core/src/theme/cssText.ts` and `hyperformula-ui/packages/core/DOCS.md`. Regenerate them with the change that affects them; CI fails when the stylesheet is stale. -Never edit any of them. Never read the **build artifacts** — `lib/`, `es/`, `commonjs/`, `dist/`, `languages/`, `typings/`, `docs/.vuepress/dist/` — to answer a question about behaviour; read `hyperformula/src/` instead, and the agent deny list in `.claude/settings.json` enforces that. +Never edit any of them. Never read the **build artifacts** — `lib/`, `es/`, `commonjs/`, `dist/`, `languages/`, `typings/`, `docs/.vuepress/dist/` — to answer a question about behaviour; read `hyperformula/src/` or `hyperformula-ui/packages/core/src/` instead, and the agent deny list in `.claude/settings.json` enforces that. `docs/api/` and `docs/guide/built-in-functions.md` are the exception. They are generated, so editing them is pointless, but they *are* the API reference and the function reference and reading them is often exactly right. @@ -96,9 +103,11 @@ This directory holds what applies to the whole repository: the definition of don [`hyperformula/dev-docs/`](../hyperformula/dev-docs/README.md) holds the engine's internals: architecture, the parser, the interpreter, the dependency graph, the function catalogue, translations, performance, its test suites, and its own build steps. -The split is by ownership. A fact lives in exactly one of them, and `hyperformula-ui` gets its own, `hyperformula-ui/dev-docs/`, when it lands. +[`hyperformula-ui/dev-docs/`](../hyperformula-ui/dev-docs/README.md) holds the UI's: its architecture and design, its code style, its suites, and its release procedure. + +The split is by ownership. A fact lives in exactly one of them. -## Scripts at three levels +## Scripts at each level Each script lives with whatever invokes it, and every one has exactly one caller: @@ -107,42 +116,28 @@ Each script lives with whatever invokes it, and every one has exactly one caller | `script/` | `release/` and `check-licenses.mjs` — both span the whole repository | | `hyperformula/script/` | `check-file.js`, `check-publish-package.js`, `if-ne-env.js` — called by the engine's build; `check-license-key-parser-drift.js` — called by `vendored-parser.yml`; `postinstall-skills-message.js` — shipped in the package and run by npm when a user installs it, silent inside this repository | | `docs/script/` | the built-in-functions generator and `prepare-cf-assets.js` — called by the portal | +| `hyperformula-ui/scripts/` | `generateCssText.mjs` and `generateApiDocs.mjs` — called by the UI core's `build:styles` and `docs` | ## Directories with their own `AGENTS.md` -`hyperformula/`, `hyperformula/src/`, `hyperformula/src/parser/`, `hyperformula/src/interpreter/`, `hyperformula/src/interpreter/plugin/`, `hyperformula/src/interpreter/functionMetadata/`, `hyperformula/src/DependencyGraph/`, `hyperformula/src/i18n/`, `hyperformula/test/`, `docs/`, and `script/`. +`hyperformula/`, `hyperformula/src/`, `hyperformula/src/parser/`, `hyperformula/src/interpreter/`, `hyperformula/src/interpreter/plugin/`, `hyperformula/src/interpreter/functionMetadata/`, `hyperformula/src/DependencyGraph/`, `hyperformula/src/i18n/`, `hyperformula/test/`, `hyperformula-ui/`, `hyperformula-ui/packages/core/`, `docs/`, and `script/`. Each is a pointer of a few lines — what the directory is, and which `dev-docs/` page or local `README.md` holds the detail. They load automatically when an agent reads a file in that subtree, so they stay small on purpose. ## What the move still owes -1. **Import `hyperformula-ui`, nested.** The directory is a placeholder. The UI is imported from the formula-builder repository in a separate change, as a whole: its repository moves under `hyperformula-ui/` with its own layout intact (`git filter-repo --to-subdirectory-filter hyperformula-ui`), so its history survives and the relative paths in its shared configuration keep working. Its packages keep the names they have today. - - **Before the import**, in the formula-builder repository itself, convert it from pnpm to npm. The UI adjusts to this repository, not the other way round, and it arrives already working under npm: - - `catalog:` specifications become plain version ranges, and `pnpm-workspace.yaml` goes; - - `workspace:*` specifications, between its own packages and in their `peerDependencies`, become the shared version range, which the release script bumps — npm rejects the `workspace:` protocol outright; - - `pnpm -r`, `pnpm --filter` and `pnpm exec` in its scripts, its CI workflow and its Playwright `webServer` commands become `npm run --workspace=…`, `--workspaces --if-present` and `npm exec`; - - `pnpm-lock.yaml` and the `packageManager` field go, replaced by a `package-lock.json` there. The import drops that lockfile: the root `package-lock.json` covers the UI from then on; - - every package that runs `tsc` declares its own `typescript`: npm hoists one version to the root, which is the engine's 4.x, so a package needing 5.x must declare it to get its own copy. - - **The import change itself** then has to: - - add `hyperformula-ui/packages/*`, `hyperformula-ui/demo/*` and `hyperformula-ui/e2e` to the root `workspaces` array — not before: npm silently ignores an entry with no `package.json`, so listing them early buys nothing, and the lockfile is regenerated when the packages land either way; - - give each UI package a `lint` script running its own linter, so the root `npm run lint` picks it up; - - license each published UI package like the engine: `"license": "GPL-3.0-only"` in its `package.json`, the root `LICENSE.txt` in its tarball through the same `prepack` copy the engine uses, and an entry, by package name, in `WORKSPACES` in `script/check-licenses.mjs`, so its production dependencies pass the same allowlist; - - point the root fan-out scripts, which today target `--workspace=hyperformula` only, at the UI's packages too; - - delete the UI's own `.nvmrc`, if it has one — the root `.nvmrc` covers the whole repository — and add an `AGENTS.md` with a `CLAUDE.md` symlink, and `hyperformula-ui/dev-docs/`; - - keep the UI's own version and history: its packages stay on their `0.x` line, with `hyperformula-ui/CHANGELOG.md` and a release path of their own, tagged with a prefix such as `hyperformula-ui@0.3.0` so the tags cannot collide with the engine's bare `3.5.0`. `script/release/release.sh` keeps releasing the engine only. The UI's `peerDependencies` on `hyperformula` say which engine versions it works with. -2. **Path-filter CI.** Each package's jobs should run only when its own paths change, with full runs on `develop`, `master`, and release branches. Not done here on purpose: a naive `paths:` filter on a workflow that branch protection lists as a required check leaves the check permanently pending, and pull requests become unmergeable. Doing it safely needs the required-checks list, which lives in repository settings rather than in the tree, and the `dorny/paths-filter`-plus-single-gate shape that the Handsontable monorepo uses. -3. **Before this merges, switch the Workers Builds deploy commands.** The Cloudflare dashboard still runs `npx wrangler deploy` and `npx wrangler versions upload` at the repository root, which find no configuration and no `wrangler` there now that `wrangler.jsonc` lives in `docs/`. Set the deploy command to `npm run docs:deploy:cf` and the non-production branch deploy command to `npm run docs:preview:cf`, as [`docs/README.md`](../docs/README.md#deployment) describes. Do it first: every branch with the old layout already defines both scripts at its root, so the switch breaks nothing. Until it is made, every preview build fails, and production stops updating once the move reaches `master`. +1. **Path-filter CI.** Each package's jobs should run only when its own paths change, with full runs on `develop`, `master`, and release branches. Not done here on purpose: a naive `paths:` filter on a workflow that branch protection lists as a required check leaves the check permanently pending, and pull requests become unmergeable. Doing it safely needs the required-checks list, which lives in repository settings rather than in the tree, and the `dorny/paths-filter`-plus-single-gate shape that the Handsontable monorepo uses. +2. **Before this merges, switch the Workers Builds deploy commands.** The Cloudflare dashboard still runs `npx wrangler deploy` and `npx wrangler versions upload` at the repository root, which find no configuration and no `wrangler` there now that `wrangler.jsonc` lives in `docs/`. Set the deploy command to `npm run docs:deploy:cf` and the non-production branch deploy command to `npm run docs:preview:cf`, as [`docs/README.md`](../docs/README.md#deployment) describes. Do it first: every branch with the old layout already defines both scripts at its root, so the switch breaks nothing. Until it is made, every preview build fails, and production stops updating once the move reaches `master`. ## What the move decided -- **npm workspaces, not pnpm.** A package-manager migration is a risk the move did not need to carry at the same time. The same holds for the UI, which uses pnpm today: it converts to npm in its own repository before it is imported, so this repository runs one package manager. +- **npm workspaces, not pnpm.** A package-manager migration is a risk the move did not need to carry at the same time. The UI, which used pnpm, was converted to npm when it was imported, so this repository runs one package manager. - **`docs/` is not a workspace member, because its toolchain is legacy, not because it is large.** VuePress 1.x, webpack 4 and `--openssl-legacy-provider` must never be hoisted into the shared install. The UI, larger but current, does join the workspace — see [Workspaces](#workspaces). It installs on its own with `npm run docs:install`, and CI installs it before building the portal. -- **`hyperformula-ui/` is nested, not flat.** The UI keeps its own layout under one directory, rather than each of its packages getting a top-level directory of its own. The import is then one move with the history intact, the UI's toolchain stays separable from the engine's, and each package's internals still travel with it. The cost: `hyperformula-ui/` is a folder rather than a package, and the root lists its members by glob. -- **`dev-docs/` at two levels, not one at the root.** One directory at the root was the original plan; it was dropped in favour of splitting by ownership, so that each package's internals travel with the package and `hyperformula-ui` gets its own when it lands. Repository-wide standards stay here, and a fact lives in exactly one level — see [`dev-docs/` at two levels](#dev-docs-at-two-levels). -- **The UI packages are GPL-3.0-only, like the engine** — the working assumption until a licensing decision says otherwise. It sets what the import does with their manifests, their tarballs and the licence gate; see [What the move still owes](#what-the-move-still-owes). -- **The UI versions on its own until it is mature, then joins the engine's version.** While its API is still moving, the UI releases on its own `0.x` line, where every minor release may break, with its own changelog — rather than starting at `3.x` and forcing an engine major, or a break smuggled into a minor, whenever the UI changes incompatibly. Once the team judges the UI ready, the versions join — there is no fixed trigger — and from then on the packages release together, on one version, from one changelog. A release then cuts every published package at the same version, whether or not each one changed, and `CHANGELOG.md` at the repository root is the single history for all of them; the UI's changelog is folded into it. That keeps one number to reason about — the version a user reports a bug against identifies the state of the whole repository — at the cost of publishing a package whose code did not move. This order is the safe one: joining separate versions only needs version numbers to go up, while splitting a shared version after users depend on it is hard. +- **`hyperformula-ui/` is nested, not flat.** The UI keeps its own layout under one directory, rather than each of its packages getting a top-level directory of its own. Its shared configuration keeps working at the same relative paths, its toolchain stays separable from the engine's, and each package's internals still travel with it. The cost: `hyperformula-ui/` is a folder rather than a package, and the root lists its members by glob. +- **Only the formula builder's core was imported, without its history.** It came from the formula-builder repository at commit `e85b52b` as one snapshot, with the shared configuration it needs, the editor-only demo and its end-to-end check, and was renamed from `@hfe/core` to `hyperformula-ui`. Grid adapters are not part of the product: Handsontable ships its own as a built-in plugin, and adapters for other grids are examples maintained outside this repository. The formula-builder repository keeps the full history. +- **`dev-docs/` at two levels, not one at the root.** One directory at the root was the original plan; it was dropped in favour of splitting by ownership, so that each package's internals travel with the package and `hyperformula-ui` has its own. Repository-wide standards stay here, and a fact lives in exactly one level — see [`dev-docs/` at two levels](#dev-docs-at-two-levels). +- **The UI packages are GPL-3.0-only, like the engine.** Each published one declares the licence in its `package.json`, carries the root `LICENSE.txt` in its tarball through the same `prepack` copy the engine uses, and is listed in `WORKSPACES` in `script/check-licenses.mjs`, so its production dependencies pass the same allowlist. +- **The UI versions on its own until it is mature, then joins the engine's version.** While its API is still moving, the UI releases on its own `0.x` line, where every minor release may break, with its own changelog and its own manual release procedure, [`hyperformula-ui/dev-docs/RELEASE.md`](../hyperformula-ui/dev-docs/RELEASE.md), with tags prefixed `hyperformula-ui@` so they cannot collide with the engine's bare `3.5.0` — rather than starting at `3.x` and forcing an engine major, or a break smuggled into a minor, whenever the UI changes incompatibly. Once the team judges the UI ready, the versions join — there is no fixed trigger — and from then on the packages release together, on one version, from one changelog. A release then cuts every published package at the same version, whether or not each one changed, and `CHANGELOG.md` at the repository root is the single history for all of them; the UI's changelog is folded into it. That keeps one number to reason about — the version a user reports a bug against identifies the state of the whole repository — at the cost of publishing a package whose code did not move. This order is the safe one: joining separate versions only needs version numbers to go up, while splitting a shared version after users depend on it is hard. - **The published tarball still carries a changelog and a licence.** `hyperformula`'s `prepack` copies the root `CHANGELOG.md` and `LICENSE.txt` into the package and `postpack` removes them again, so each is one file under version control and npm consumers still get both. The webpack banner reads the root `LICENSE.txt` directly. - **One `.nvmrc`, at the root.** The whole repository runs on one Node version; `nvm` finds the root file from any subdirectory, and Workers Builds, which starts at the root, reads it too. - **Each directory lints itself.** `hyperformula/` and `docs/` each carry their own `.eslintrc.js` and `.eslintignore`, and each package declares the lint tooling it uses. The root `npm run lint` only fans out with `--workspaces --if-present`, so a package with a different linter or TypeScript version — the UI — brings its own, and the engine's rules, licence header included, never reach it. `docs/` is not a workspace, so its lint is `npm run docs:lint`, run by the documentation CI job, which installs the portal anyway. diff --git a/hyperformula-ui/.gitignore b/hyperformula-ui/.gitignore new file mode 100644 index 000000000..0366b92e6 --- /dev/null +++ b/hyperformula-ui/.gitignore @@ -0,0 +1,6 @@ +dist +*.tsbuildinfo +playwright-report +test-results +.vite +packages/core/LICENSE.txt diff --git a/hyperformula-ui/AGENTS.md b/hyperformula-ui/AGENTS.md new file mode 100644 index 000000000..a3bedf1a4 --- /dev/null +++ b/hyperformula-ui/AGENTS.md @@ -0,0 +1,10 @@ +# `hyperformula-ui/` — UI components + +A folder of npm workspaces, not a package: the published `hyperformula-ui` package in `packages/core/`, an editor-only demo in `demo/`, and a Playwright suite in `e2e/`. + +- How the UI works, its own code style, its tests and its release: [`dev-docs/README.md`](dev-docs/README.md) +- Repository-wide standards: [`../dev-docs/README.md`](../dev-docs/README.md) + +The code style here is not the engine's. Read [`dev-docs/CODE-STYLE.md`](dev-docs/CODE-STYLE.md) before editing. + +Skill: `hyperformula-ui-dev`. diff --git a/hyperformula-ui/CHANGELOG.md b/hyperformula-ui/CHANGELOG.md new file mode 100644 index 000000000..09d271049 --- /dev/null +++ b/hyperformula-ui/CHANGELOG.md @@ -0,0 +1,11 @@ +# Changelog + +All notable changes to the `hyperformula-ui` package are documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +### Added +- Added the `hyperformula-ui` package: a formula editor for HyperFormula with syntax and reference highlighting, function autocomplete and help, range picking, and an optional formula bar, connected to any grid through the `IGridAdapter` interface. [#1832](https://github.com/handsontable/hyperformula/pull/1832) diff --git a/hyperformula-ui/CLAUDE.md b/hyperformula-ui/CLAUDE.md new file mode 120000 index 000000000..47dc3e3d8 --- /dev/null +++ b/hyperformula-ui/CLAUDE.md @@ -0,0 +1 @@ +AGENTS.md \ No newline at end of file diff --git a/hyperformula-ui/README.md b/hyperformula-ui/README.md index 7aa5d839e..872f15aa8 100644 --- a/hyperformula-ui/README.md +++ b/hyperformula-ui/README.md @@ -1,7 +1,16 @@ # `hyperformula-ui/` -Reserved for the HyperFormula UI components: reference highlighting, the inline formula editor, and function help. +UI components for HyperFormula. Today that is one published package, [`hyperformula-ui`](packages/core/README.md): a formula editor with syntax and reference highlighting, function autocomplete and help, and a formula bar, for any grid. -The UI is not here yet. It is imported from the formula-builder repository in a separate change, nested: the whole repository moves into this directory with its layout and history intact, so this directory will hold a group of packages rather than a single one. Until then it holds only this file, and nothing from it is listed in the root `workspaces` array. +| Directory | What it is | Published | +|---|---|---| +| [`packages/core/`](packages/core/) | The `hyperformula-ui` package | Yes, to npm | +| [`demo/`](demo/) | An editor-only demo page, run with `npm run dev:ui` | No | +| [`e2e/`](e2e/) | A Playwright smoke test against the demo | No | +| [`dev-docs/`](dev-docs/README.md) | Architecture, code style, tests and the release procedure | No | -The planned layout, and everything the import has to do: [`dev-docs/STRUCTURE.md`](../dev-docs/STRUCTURE.md#what-the-move-still-owes). +Run everything from the repository root after `npm ci`; the commands are in [`dev-docs/SPEC.md`](dev-docs/SPEC.md#12-build--commands). + +The code was imported from the formula-builder repository at commit `e85b52b`, without its history. Grid integrations live outside this repository: Handsontable ships its own, as a built-in plugin. + +The packages version on their own `0.x` line, with their own [`CHANGELOG.md`](CHANGELOG.md), until they join the engine's version. diff --git a/hyperformula-ui/biome.json b/hyperformula-ui/biome.json new file mode 100644 index 000000000..1feca076f --- /dev/null +++ b/hyperformula-ui/biome.json @@ -0,0 +1,111 @@ +{ + "$schema": "https://biomejs.dev/schemas/2.4.16/schema.json", + "vcs": { + "enabled": true, + "clientKind": "git", + "useIgnoreFile": true + }, + "files": { + "includes": [ + "**/*.ts", + "**/*.tsx", + "**/*.js", + "**/*.mjs", + "**/*.cjs", + "**/*.json", + "**/*.jsonc", + "**/*.css", + "!**/dist", + "!**/node_modules", + "!**/playwright-report", + "!**/test-results", + "!**/.vite" + ] + }, + "css": { + "formatter": { + "enabled": true, + "quoteStyle": "double" + }, + "linter": { + "enabled": true + } + }, + "formatter": { + "enabled": true, + "indentStyle": "space", + "indentWidth": 2, + "lineWidth": 100, + "lineEnding": "lf" + }, + "javascript": { + "formatter": { + "quoteStyle": "double", + "trailingCommas": "all", + "semicolons": "always", + "arrowParentheses": "always", + "bracketSpacing": true, + "bracketSameLine": false + } + }, + "linter": { + "enabled": true, + "rules": { + "recommended": true, + "style": { + "useConst": "error", + "useTemplate": "error", + "noNonNullAssertion": "warn", + "noParameterAssign": "error", + "useImportType": "error", + "useExportType": "error", + "useNodejsImportProtocol": "error", + "useBlockStatements": "error", + "noNegationElse": "error", + "useShorthandAssign": "error", + "useNumberNamespace": "error", + "noUselessElse": "error", + "useDefaultParameterLast": "error", + "useShorthandFunctionType": "error", + "useSingleVarDeclarator": "error", + "useConsistentArrayType": { "level": "error", "options": { "syntax": "shorthand" } }, + "useSelfClosingElements": "error", + "useFilenamingConvention": { + "level": "error", + "options": { "filenameCases": ["camelCase", "kebab-case"], "requireAscii": true } + } + }, + "suspicious": { + "noExplicitAny": "warn", + "noConsole": { "level": "warn", "options": { "allow": ["error", "warn"] } }, + "noDoubleEquals": "error", + "noAssignInExpressions": "error", + "noShadowRestrictedNames": "error" + }, + "correctness": { + "noUnusedVariables": "error", + "noUnusedImports": "error", + "noUnusedFunctionParameters": "warn" + }, + "complexity": { + "noBannedTypes": "error", + "useFlatMap": "error", + "noImportantStyles": "off", + "noUselessTernary": "error", + "noUselessCatch": "error", + "noUselessFragments": "error", + "noUselessRename": "error", + "noUselessUndefinedInitialization": "error", + "useOptionalChain": "error", + "useLiteralKeys": "error", + "useRegexLiterals": "error" + }, + "performance": { + "noDelete": "error" + }, + "a11y": { + "useSemanticElements": "off" + } + } + } +} diff --git a/hyperformula-ui/demo/js/basic/README.md b/hyperformula-ui/demo/js/basic/README.md new file mode 100644 index 000000000..9268d3761 --- /dev/null +++ b/hyperformula-ui/demo/js/basic/README.md @@ -0,0 +1,18 @@ +# basic — `hyperformula-ui` only, no grid + +Demonstrates `FormulaBuilder` running without any grid adapter — the lowest +layer of the integration surface. Constructs the builder against a host +element and opens the editor imperatively via `openEditor`. + +**Imports:** `hyperformula-ui` (`FormulaBuilder`) only — no adapter package. + +**Construction** (`basic/main.ts`): + +```ts +const builder = new FormulaBuilder({ rootEl: host, hyperformula: engine }); +const editor = builder.editor; +... +builder.openEditor(host, "=SUM(A1:B5) + 2"); +``` + +`FormulaEditor`/`FormulaBuilder` internals: [`dev-docs/ARCHITECTURE.md`](../../../dev-docs/ARCHITECTURE.md). diff --git a/hyperformula-ui/demo/js/basic/index.html b/hyperformula-ui/demo/js/basic/index.html new file mode 100644 index 000000000..7d546d55c --- /dev/null +++ b/hyperformula-ui/demo/js/basic/index.html @@ -0,0 +1,61 @@ + + + + + + HFE — Basic + + + +
+
+

← Basic

+
+ + +
+
+ +
+
+ Editor sizing +
+ + + +
+
+
+ +
+ +
+ Result + — +
+ +
+
+

Tokens

+
(start typing)
+
+
+

State

+

+        
+
+
+ + + diff --git a/hyperformula-ui/demo/js/basic/main.ts b/hyperformula-ui/demo/js/basic/main.ts new file mode 100644 index 000000000..659bf0a42 --- /dev/null +++ b/hyperformula-ui/demo/js/basic/main.ts @@ -0,0 +1,52 @@ +import { buildHyperFormula, evaluateFormula } from "@hfe-demo/shared"; +import { FormulaBuilder } from "hyperformula-ui"; +import { requireEl } from "../helpers/dom"; +import { bindEditorSizingControls } from "../helpers/editorSizing"; + +const host = requireEl("editor-host"); +const tokensEl = requireEl("tokens"); +const stateEl = requireEl("state"); +const resultEl = requireEl("result"); +const exampleBtn = requireEl("set-example"); +const clearBtn = requireEl("clear"); + +const applyEditorWidthCap = () => { + const hostStyle = getComputedStyle(host); + const paddingHorizontal = + (Number.parseFloat(hostStyle.paddingLeft) || 0) + + (Number.parseFloat(hostStyle.paddingRight) || 0); + + host.style.setProperty("--hfe-editor-max-width", `${host.clientWidth - paddingHorizontal}px`); +}; + +applyEditorWidthCap(); +window.addEventListener("resize", applyEditorWidthCap); + +const engine = buildHyperFormula(); +const builder = new FormulaBuilder({ rootEl: host, hyperformula: engine }); +const editor = builder.editor; + +const onChange = (text: string) => { + resultEl.textContent = evaluateFormula(engine, text) || "—"; +}; + +editor.on("change", ({ state }) => { + tokensEl.textContent = JSON.stringify(state.tokens, null, 2); + stateEl.textContent = JSON.stringify({ text: state.text, cursor: state.cursor }, null, 2); + onChange(editor.getValue()); +}); + +builder.openEditor(host, "=SUM(A1:B5) + 2"); +onChange(editor.getValue()); +(window as unknown as { editor: typeof editor }).editor = editor; + +exampleBtn.addEventListener("click", () => { + editor.setValue('=IF(SUM(A1:B10) > 100, "big", AVERAGE(A1:H5))'); + editor.focus(); +}); +clearBtn.addEventListener("click", () => { + editor.setValue(""); + editor.focus(); +}); + +bindEditorSizingControls(host); diff --git a/hyperformula-ui/demo/js/helpers/dom.ts b/hyperformula-ui/demo/js/helpers/dom.ts new file mode 100644 index 000000000..e5b97c7bc --- /dev/null +++ b/hyperformula-ui/demo/js/helpers/dom.ts @@ -0,0 +1,8 @@ +export function requireEl(id: string): T { + const element = document.getElementById(id); + if (!element) { + throw new Error(`required element #${id} not found`); + } + + return element as T; +} diff --git a/hyperformula-ui/demo/js/helpers/editorSizing.ts b/hyperformula-ui/demo/js/helpers/editorSizing.ts new file mode 100644 index 000000000..f5d757b78 --- /dev/null +++ b/hyperformula-ui/demo/js/helpers/editorSizing.ts @@ -0,0 +1,29 @@ +import { requireEl } from "./dom"; + +export function bindEditorSizingControls(target: HTMLElement): void { + const minLinesEl = requireEl("opt-min-lines"); + const maxLinesEl = requireEl("opt-max-lines"); + const resizeEl = requireEl("opt-resize"); + + const setVar = (name: string, value: string): void => { + if (value === "") { + target.style.removeProperty(name); + } else { + target.style.setProperty(name, value); + } + }; + + const applyVar = (name: string, value: string): void => { + setVar(name, value); + window.dispatchEvent(new Event("resize")); + }; + + setVar("--hfe-editor-min-lines", minLinesEl.value); + setVar("--hfe-editor-max-lines", maxLinesEl.value); + setVar("--hfe-editor-resize", resizeEl.value); + window.dispatchEvent(new Event("resize")); + + minLinesEl.addEventListener("input", () => applyVar("--hfe-editor-min-lines", minLinesEl.value)); + maxLinesEl.addEventListener("input", () => applyVar("--hfe-editor-max-lines", maxLinesEl.value)); + resizeEl.addEventListener("change", () => applyVar("--hfe-editor-resize", resizeEl.value)); +} diff --git a/hyperformula-ui/demo/js/index.html b/hyperformula-ui/demo/js/index.html new file mode 100644 index 000000000..0b5294424 --- /dev/null +++ b/hyperformula-ui/demo/js/index.html @@ -0,0 +1,17 @@ + + + + + + HFE — JS demos + + + +
+

HyperFormula Editor — JS demos

+ +
+ + diff --git a/hyperformula-ui/demo/js/package.json b/hyperformula-ui/demo/js/package.json new file mode 100644 index 000000000..43112a43e --- /dev/null +++ b/hyperformula-ui/demo/js/package.json @@ -0,0 +1,24 @@ +{ + "name": "demo-js", + "version": "0.0.0", + "private": true, + "type": "module", + "scripts": { + "dev": "vite --port 5173", + "build": "vite build", + "preview": "vite preview --port 4173", + "lint": "biome check .", + "lint:fix": "biome check --write .", + "typecheck": "tsc -p tsconfig.json" + }, + "dependencies": { + "@hfe-demo/shared": "0.0.0", + "hyperformula": "^3.4.0", + "hyperformula-ui": "*" + }, + "devDependencies": { + "@biomejs/biome": "2.4.16", + "typescript": "^5.6.3", + "vite": "^5.4.10" + } +} diff --git a/hyperformula-ui/demo/js/public/shared.css b/hyperformula-ui/demo/js/public/shared.css new file mode 120000 index 000000000..89c6a15e5 --- /dev/null +++ b/hyperformula-ui/demo/js/public/shared.css @@ -0,0 +1 @@ +../../shared/shared.css \ No newline at end of file diff --git a/hyperformula-ui/demo/js/tsconfig.json b/hyperformula-ui/demo/js/tsconfig.json new file mode 100644 index 000000000..abff259a2 --- /dev/null +++ b/hyperformula-ui/demo/js/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "noEmit": true, + "types": ["vite/client"] + }, + "include": ["basic/**/*", "helpers/**/*"] +} diff --git a/hyperformula-ui/demo/js/vite.config.ts b/hyperformula-ui/demo/js/vite.config.ts new file mode 100644 index 000000000..3c9ed2330 --- /dev/null +++ b/hyperformula-ui/demo/js/vite.config.ts @@ -0,0 +1,26 @@ +import { resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { defineConfig } from "vite"; + +const dirname = fileURLToPath(new URL(".", import.meta.url)); + +export default defineConfig({ + appType: "mpa", + resolve: { + conditions: ["hyperformula-ui-source", "import", "module", "browser", "default"], + }, + css: { + preprocessorOptions: { + scss: { api: "modern-compiler" }, + }, + }, + server: { port: 5173, open: true }, + build: { + rollupOptions: { + input: { + index: resolve(dirname, "index.html"), + basic: resolve(dirname, "basic/index.html"), + }, + }, + }, +}); diff --git a/hyperformula-ui/demo/shared/datasets.ts b/hyperformula-ui/demo/shared/datasets.ts new file mode 100644 index 000000000..cbf509173 --- /dev/null +++ b/hyperformula-ui/demo/shared/datasets.ts @@ -0,0 +1,85 @@ +import { HyperFormula } from "hyperformula"; + +export const ROWS = 100; +export const COLS = 18; + +export function makeSampleData(): (number | string)[][] { + const data: (number | string)[][] = []; + + for (let row = 0; row < ROWS; row++) { + const rowData: (number | string)[] = []; + + for (let col = 0; col < COLS; col++) { + rowData.push((row + 1) * (col + 1)); + } + data.push(rowData); + } + + const row10 = data[10]; + const row11 = data[11]; + const row12 = data[12]; + const rowLast = data[ROWS - 1]; + + if (row10 && row11 && row12 && rowLast) { + row10[0] = "=SUM(A1:A10)"; + row10[1] = "=AVERAGE(B1:B10)"; + row11[0] = "=MAX(A1:H10)"; + row12[0] = + '=ROUND(B2 * C2 + N("price * qty") - B2 * C2 * D2 + N("less discount") + (B2 * C2 - B2 * C2 * D2) * 0.23 + N("VAT 23%"), 2)'; + rowLast[COLS - 1] = "=SUM(A1:A10) + MAX(A1:H10)"; + } + + return data; +} + +export function seedNamedExpressions(engine: HyperFormula, sheetName = "Sheet1"): void { + engine.addNamedExpression("TaxRate", "=0.23"); + engine.addNamedExpression("Region", '="North"'); + engine.addNamedExpression("FirstCell", `='${sheetName}'!$A$1`); + engine.addNamedExpression("SalesRange", `='${sheetName}'!$A$1:$A$10`); + engine.addNamedExpression("ColumnA", `='${sheetName}'!$A:$A`); +} + +export function buildHyperFormula(): HyperFormula { + const engine = HyperFormula.buildFromArray(makeSampleData(), { + licenseKey: "gpl-v3", + }); + + seedNamedExpressions(engine); + + return engine; +} + +export function formatResult(value: unknown): string { + if (value === null || value === undefined) { + return ""; + } + if (typeof value === "object" && value !== null && "type" in (value as object)) { + const err = value as { value?: string; type?: string; message?: string }; + const label = err.value ?? `#${err.type ?? "ERROR"}`; + + return `${label}${err.message ? ` (${err.message})` : ""}`; + } + if (typeof value === "number") { + return Number.isInteger(value) ? String(value) : value.toFixed(4).replace(/\.?0+$/, ""); + } + return String(value); +} + +export function evaluateFormula(engine: HyperFormula, formula: string, sheetId = 0): string { + const trimmed = formula.trim(); + + if (!trimmed) { + return ""; + } + try { + const value = engine.calculateFormula( + trimmed.startsWith("=") ? trimmed : `=${trimmed}`, + sheetId, + ); + + return formatResult(value); + } catch (error) { + return `#ERR (${(error as Error).message})`; + } +} diff --git a/hyperformula-ui/demo/shared/package.json b/hyperformula-ui/demo/shared/package.json new file mode 100644 index 000000000..6e93b2e21 --- /dev/null +++ b/hyperformula-ui/demo/shared/package.json @@ -0,0 +1,21 @@ +{ + "name": "@hfe-demo/shared", + "version": "0.0.0", + "private": true, + "type": "module", + "scripts": { + "lint": "biome check .", + "lint:fix": "biome check --write .", + "typecheck": "tsc -p tsconfig.json" + }, + "exports": { + ".": "./datasets.ts" + }, + "dependencies": { + "hyperformula": "^3.4.0" + }, + "devDependencies": { + "@biomejs/biome": "2.4.16", + "typescript": "^5.6.3" + } +} diff --git a/hyperformula-ui/demo/shared/shared.css b/hyperformula-ui/demo/shared/shared.css new file mode 100644 index 000000000..c5e707acf --- /dev/null +++ b/hyperformula-ui/demo/shared/shared.css @@ -0,0 +1,277 @@ +:root { + color-scheme: light dark; + --bg: light-dark(#f7f8fa, #15161a); + --fg: light-dark(#1c1d20, #e6e6e6); + --muted: light-dark(#6b7280, #9ca3af); + --panel: light-dark(#ffffff, #1e1f22); + --border: light-dark(#e2e4ea, #2f3137); + --accent: light-dark(#0b66ff, #6aa9ff); +} + +* { + box-sizing: border-box; +} + +html, +body { + margin: 0; + padding: 0; + background: var(--bg); + color: var(--fg); + font-family: ui-sans-serif, system-ui, sans-serif; +} + +a { + color: var(--accent); + text-decoration: none; +} +a:hover { + text-decoration: underline; +} + +.app { + max-width: 1024px; + margin: 0 auto; + padding: 24px; + display: grid; + gap: 16px; +} + +.app__header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; +} +.app__header h1 { + margin: 0; + font-size: 18px; +} +.app__header h1 a { + margin-right: 8px; + font-weight: 400; + color: var(--muted); +} + +.app__hint { + margin: 0; + color: var(--muted); + font-size: 13px; +} +.app__hint kbd { + font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; + font-size: 11px; + padding: 1px 5px; + border: 1px solid var(--border); + border-radius: 4px; + background: var(--panel); + color: var(--fg); +} + +.app__controls { + display: flex; + gap: 8px; + align-items: center; +} +.app__controls button, +.app__controls select { + font: inherit; + padding: 4px 10px; + border-radius: 6px; + border: 1px solid var(--border); + background: var(--panel); + color: var(--fg); + cursor: pointer; +} +.app__controls button.is-active { + background: var(--accent); + color: white; + border-color: var(--accent); +} + +.app__editor { + --hfe-editor-min-width: 160px; + background: var(--panel); + padding: 12px; + border-radius: 12px; + border: 1px solid var(--border); +} + +.app__editor .hfe-editor { + width: 100%; +} + +.app__result { + display: flex; + align-items: baseline; + gap: 12px; + background: var(--panel); + border: 1px solid var(--border); + border-radius: 12px; + padding: 10px 14px; +} +.app__result-label { + font-size: 11px; + text-transform: uppercase; + letter-spacing: 0.06em; + color: var(--muted); +} +.app__result-value { + font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; + font-size: 14px; + color: var(--accent); + font-weight: 500; + word-break: break-word; +} + +.app__inspect { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 16px; +} +.app__inspect h2 { + margin: 0 0 8px; + font-size: 13px; + color: var(--muted); + text-transform: uppercase; + letter-spacing: 0.04em; +} +.app__inspect pre { + background: var(--panel); + border: 1px solid var(--border); + border-radius: 8px; + padding: 12px; + margin: 0; + font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; + font-size: 12px; + line-height: 1.5; + overflow: auto; + max-height: 360px; +} + +/* Landing */ +.demo-list { + list-style: none; + margin: 0; + padding: 0; + display: grid; + gap: 12px; +} +.demo-list a { + display: block; + padding: 16px; + border: 1px solid var(--border); + border-radius: 12px; + background: var(--panel); + color: var(--fg); +} +.demo-list a:hover { + border-color: var(--accent); + text-decoration: none; +} +.demo-list strong { + display: block; + font-size: 16px; +} +.demo-list span { + color: var(--muted); + font-size: 13px; +} + +/* Plain table */ +.grid-wrap { + background: var(--panel); + border: 1px solid var(--border); + border-radius: 12px; + padding: 8px; +} +.grid-wrap .formula-bar-host { + margin-bottom: 8px; +} +.grid-scroll { + overflow: auto; + max-height: 320px; +} +/* Handsontable wrap */ +.hot-wrap { + background: var(--panel); + border: 1px solid var(--border); + border-radius: 12px; + padding: 8px; + overflow: auto; +} +.demo-bars { + display: flex; + flex-direction: column; + gap: 6px; + margin-bottom: 12px; +} + +.demo-bar { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 10px; + padding: 6px 10px; + border: 1px solid var(--border); + border-radius: 8px; + font-size: 13px; +} + +.demo-bar__label { + font-weight: 600; + font-size: 12px; + text-transform: uppercase; + letter-spacing: 0.04em; + opacity: 0.7; + min-width: 56px; +} + +.demo-bar__sublabel { + font-weight: 600; + font-size: 11px; + text-transform: uppercase; + letter-spacing: 0.04em; + opacity: 0.55; +} + +.demo-bar__group { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 10px; +} + +.demo-bar label { + display: inline-flex; + align-items: center; + gap: 4px; +} + +.demo-bar select { + font: inherit; + padding: 4px 8px; + border-radius: 6px; + border: 1px solid var(--border); + background: var(--panel); + color: var(--fg); + cursor: pointer; +} + +.demo-bar input[type="checkbox"] { + width: 15px; + height: 15px; + margin: 0; + accent-color: var(--accent); + cursor: pointer; +} + +.demo-bar input[type="number"] { + width: 64px; + font: inherit; + padding: 4px 8px; + border-radius: 6px; + border: 1px solid var(--border); + background: var(--panel); + color: var(--fg); +} diff --git a/hyperformula-ui/demo/shared/tsconfig.json b/hyperformula-ui/demo/shared/tsconfig.json new file mode 100644 index 000000000..e52f7ec75 --- /dev/null +++ b/hyperformula-ui/demo/shared/tsconfig.json @@ -0,0 +1,7 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "noEmit": true + }, + "include": ["datasets.ts"] +} diff --git a/hyperformula-ui/dev-docs/ARCHITECTURE.md b/hyperformula-ui/dev-docs/ARCHITECTURE.md new file mode 100644 index 000000000..e7cd6337f --- /dev/null +++ b/hyperformula-ui/dev-docs/ARCHITECTURE.md @@ -0,0 +1,887 @@ +# Core package — architecture + +## High-level picture + +`packages/core` is the engine-agnostic formula editor. It has no dependency on any specific +grid host. The host connects via `IGridAdapter`. HyperFormula is an optional peer dependency +used for function validation and named-expression resolution. + +## Single-editor host-switch model + +There is exactly one `FormulaEditor` instance per grid. It is owned by `FormulaBuilder` and +reparents between two locations via `FormulaEditor.attachTo(mount)`: + +- **Inline mode** — the editor lives in the cell overlay mount created by the adapter. +- **Bar mode** — the editor lives inside the formula bar overlay created by + `FormulaBar`. + +`IGridAdapter` brokers the handoff via thirteen bar lifecycle methods: + +- `getActiveCell()` — returns the active cell, or `null` when there is none. Serves both the + formula bar (which cell to mirror) and keyboard point-mode (the anchor + `PointModeController.enter()` starts from). Addresses are HF-space: the external Handsontable + `formulaBuilder` plugin (handsontable repo) maps its tracked visual selection through + `visualToHfRow`/`visualToHfCol` and returns `null` + when the selection is not a formula-capable cell. Of the example adapters maintained outside + this repository, the TanStack one reads its tracked selection directly, and the plain-table one + delegates to its injected `PlainTableHost` when one is provided (its demo's `PlainTableSheet`), + else falls back to its `getActiveCell` constructor option, else `null`. The controller handles the `null` path by calling + `selectFirstCell()`, so new adapters may return `null` safely. +- `onSelectionChange(callback)` — adapter fires `GridSelection | null` (`{ active, range }`) + when the selection changes; the bar mirrors the active cell's value and the address box + shows the range (`A1` for a single cell, `A1:B5` for multi-cell). +- `setSelection(range)` — adapter selects the given `CellRange`; called by the address box + when a typed `A1:B5` range is submitted. Gesture ownership (mouse drag, shift+click, + shift+arrows) is host-owned, not core's: the external Handsontable plugin rides HOT's + native selection, the plain-table example host implements its own + mousedown/mouseover/keydown gestures, and the TanStack example adapter ships default gestures through `getCellProps` and owns the resulting + anchor+focus state. Core and adapters carry the data contract only — no gesture code, no + selection visuals. +- `onInlineEditStart(callback)` — adapter fires when a cell editor opens; the formula-bar + controller calls `attachTo(barMount)` and seeds the value. +- `onInlineEditClose(callback)` — adapter fires when the cell editor closes; the controller + detaches. +- `onSwitchToInline(callback)` — adapter fires when the bar hands editing back to the inline + cell; the controller moves the editor back to the inline mount. +- `getCellFormula(address)` — controller reads this to seed the bar when the selection changes. +- `beginEdit(address, seed?): boolean` — controller calls this when the user clicks the bar + placeholder to open the cell editor. Returns `true` if it initiated an edit (synchronously OR + async-pending), `false` if it bailed (read-only, unmapped or not-rendered cell). + `FormulaBar.activateFromIdle` rolls back its bar session only on `false`, so an adapter whose + editor starts on a later tick (e.g. `ag-grid-react`'s deferred `startEditingCell`) must still + return `true` — otherwise the deferred inline-start lands on the wrong branch. When the + activation was focus-driven (idle cell focused) and the deferred `onInlineEditStart` arrives + after focus has already left the formula-cell region, `handleInlineEditStart` cancels the + session (`adapter.cancel()`) instead of stealing focus back into the bar. +- `selectFirstCell()` — controller calls this when `getActiveCell()` returns `null` (no + selection); adapters that always have a selection may implement this as a no-op. +- `setActiveCell(address)` — selects the given cell via the same selection path as + `selectFirstCell()`, without starting an edit. Called by `FormulaBar.navigateTo` (the + address box), paired with `scrollCellIntoView`, and by `FormulaBuilder` after an + outside-click commit (see the outside-click commit policy below). Addresses are HF-space; + the external Handsontable plugin maps them back to visual indices before selecting. +- `commit(value, direction?)` — controller calls to commit the current value; the optional + `Direction` drives the host's post-commit selection move (Enter → down, Tab → right, …). + `commit(value, direction)` must apply the value to the engine synchronously before + returning — commit-error announcements read the engine and capture `valuesUpdated` + inside the commit call. Applies equally to a host-side commit bridge (such as the plain-table + example's `PlainTableHost.commit`) and any consumer-supplied `onCommit`. A deferred write degrades announcements to silence + (no crash, no wrong message). +- `cancel()` — controller calls to cancel the current edit. +- `setInlineEditorVisible(visible)` — hides or shows the cell overlay mount while the editor + is hosted in the bar (the plain-table and TanStack example adapters toggle the container's CSS display; + the external Handsontable plugin hides HOT's editor container via `_hfeHidden`). + +`FormulaBar` composes two own-root sub-components, each with its own `EventManager` scope: +`FormulaBarAddressBox` (`address-box` scope) — an `A1`-style jump-to-cell/range input that +calls `adapter.setActiveCell` + `scrollCellIntoView` for a single cell or `adapter.setSelection` +for an `A1:B5` range, and mirrors the current `GridSelection` via `setSelection()` — and `FormulaBarCell` (`formula-cell` scope) — the fx-icon + +formula area, owning both the idle read-only colored-formula view (its own `VisualOverlay` +seeded with `FormulaEditor.knownFunctionNames`, rendered via `renderValue()` through +`nToComments`) and the `overlayMount` the shared editor `attachTo`'s while bar-hosted. + +While the editor is inline, `FormulaBarCell`'s idle view shows a live colored mirror of the +current text. Because the wrap styles are shared, a bar-hosted editor soft-wraps at the bar +container's width the same way the inline editor wraps at the grid edge (the bar-hosted editor +carries `max-width: 100% !important` — formula-bar.scss — so it wraps at the bar body's width +regardless of EditorSizeController's clip-derived inline cap, which stays in charge of the +height cap); the idle view wraps the same way +(`pre-wrap` + `break-all`) but keeps a static one-line height and scrolls vertically +(`overflow-y: auto`) — never a horizontal scrollbar, never a growing bar while inline. The +bar's vertical padding sits on the overlay and the textarea, not on the formula cell, so the +idle view and a bar-hosted editor capped at one line (`--hfe-editor-max-lines: 1`) are the +same height, and the capped editor's scroll port spans the whole cell. When the user clicks the idle formula cell, the bar triggers a host-switch: the +editor reparents to the bar mount (`FormulaBarCell.overlayMount`), the cell overlay is hidden, and focus moves to the bar +input. The bar shows the mount before `attachTo`, so `EditorSizeController` measures a visible +editor and applies its cap before `focus()` can scroll an ancestor to the caret. A +bar-initiated open then calls `FormulaEditor.scrollToStart()`: the caret stays at the end, but +a capped bar shows the formula's first line, as the idle view did. + +Formula bar activation (a11y design decision, 2026-07, revised 2026-07): the idle formula +cell is a focusable `role="textbox"` placeholder (`tabindex="0"`, `aria-label="Formula +input"`, no `aria-readonly`) whose idle overlay is AT-visible, so the current formula reads +as the textbox value. **Focusing the placeholder activates the shared editor** (Tab, +Shift+Tab, or click — `mousedown` calls `preventDefault` and activates directly rather than +relying on the resulting focus). `role="button"` was rejected: the cell is input-like, not +button-like. A role-less named div was rejected: naming `role=generic` is ARIA-prohibited. +While the overlay editor is mounted the placeholder drops to `tabindex="-1"` so Shift+Tab +from the textarea cannot land on it. + +An earlier hybrid design (bare focus inert, Enter/F2/Space/printable-key activation) +rejected focus-activation on the grounds that Shift+Tab from the grid would re-enter editing +and commit straight back — a backward-traversal loop. The fix is the **clean-editor tab +slide**: while the editor is bar-hosted and its value equals the formula captured when the +edit session started (`KeyboardController.isCleanBarHosted()`, backed by +`HostToggleDelegate.isDirty`), Tab/Shift+Tab are not commit gestures. The captured pristine +value is run through `FormulaEditor.normalizeFormula()` — the same `nToComments`/ +`commentsToN` round-trip `setValue`/`getValue` apply — before `FormulaBar` stores it; a raw +`adapter.getCellFormula()` compared directly against `editor.getValue()` would read a cell +carrying an `N("…")` comment as dirty on open (the round-trip re-spaces the call), sliding +never engaging for any commented formula. +`KeyboardController.commit()` checks `isTabTraversalCommit(direction)` — true for +`commitRight`/`commitLeft`, the two commands the Tab bindings produce, never for the Enter +variants (`commitUp`/`commitDown`) — and returns `false` before invoking `onCommit` when +that check and `isCleanBarHosted()` both hold. `ShortcutManager.dispatch` then never calls +`preventDefault`, so the browser's native Tab navigation moves focus off the bar in either +direction. Inline (cell-hosted) editing keeps Tab-commit unconditionally; only the +bar-hosted clean case slides. The abandoned bar editor (now unfocused, still open) is closed +by `FormulaEditor`'s blur handler: when focus leaves and `isCleanBarHosted()` is still true, +it calls the same `onCancel` the Escape key uses, so the session cancels silently — no +commit, idle view restored — instead of leaking an open editor behind the moved focus. +Dirty sessions (including a type-to-edit seed, which already differs from the pristine +value) still commit on Tab as before. + +### Bar-less fallback + +A grid running **without** a `FormulaBar` wired up has no bar-side subscriber to +`onInlineEditStart`. The external Handsontable `formulaBuilder` plugin (handsontable repo) +handles this itself: when `activeEditor` is still null after the listener loop, the +`!activeEditor` branch in its `handleInlineEditStart` calls `builder.openEditor(mount, seed)` — +which calls `FormulaEditor.attachTo(mount)`, sets the seed value, enters ref-selection mode, +and focuses the editor. + +The `FormulaEditor` inside `FormulaBuilder` is **long-lived**: it is created once and reused +across edit sessions. The plugin's cell editor calls +`editor.input.replaceChildren()` on close, which detaches the editor's root element from +the mount but does not delete it. On the next open, `attachTo(mount)` re-appends the same +element — all DOM listeners survive (see the reparent invariant below). The plain-table +example adapter always assumes a `FormulaBar` is present and does not have this fallback; +the TanStack example adapter's bar is dynamically attachable/detachable, so it relies on the same +barless inline-edit subscription when the bar is absent. That barless subscription +(`FormulaBuilder.subscribeInlineEditLifecycle`, scope `inline-edit`) handles both ends of the +session: `onInlineEditStart` → `openEditor(mount, seed)`, and `onInlineEditClose` → reattach +the editor to the builder's detached mount plus `closeEditor()`. The close half exists because +adapters may remove the inline mount on close (the TanStack example adapter deletes its overlay); +without the reattach the live editor DOM would be torn out with the mount. With a bar +attached, `FormulaBar` owns the same reattachment instead. + +## Component map + +``` +formulaBuilder.ts — FormulaBuilder: master class owning PopupContext + ErrorPopup + FormulaEditor + for one grid instance; optionally owns FormulaBar, attached via + attachFormulaBar(container)/detachFormulaBar() (the formulaBarContainer + constructor option is sugar that calls attachFormulaBar during + construction; detaching restores the barless inline-edit + subscription); adapters construct one FormulaBuilder, call + openEditor/closeEditor, and markCell in their renderer hooks. Its className + option is the single theming entry point: it lands on the popup portal, the + formula bar container, the editor root, and — via + adapter.setOverlayClassName — the adapter's highlight overlay elements + (cleared again with null in destroy(), since the adapter outlives the builder). + Host-owned elements stay outside the theme scope by design: whole-row/column + header tinting (HighlightLayer.renderHeaders inline backgroundColor) and the + hfe-cell--error class resolve CSS variables against the host grid's cascade, + not the className +formulaEditor/ (facade + controllers) +├── formulaEditor.ts — FormulaEditor facade: constructs collaborators/controllers, +│ wires DOM events, exposes public API +├── editorContext.ts — isFormula(kernel): the module's only runtime export +├── editorEdit.ts — applyEditorEdit(ctx, highlights, edit): the single programmatic +│ text-mutation primitive (kernel.replaceRange → kernel caret → +│ input.setText → input.setCaret → highlights.afterMutation). +│ Every controller edit (ref insert/clear, suggestion accept, +│ auto-close paren, unbalanced-paren close, newline, F4 cycle) +│ goes through it — never hand-roll the sync ritual, or the +│ kernel and textarea desync silently +├── types.ts — EditorContext record shared by all controllers, plus +│ FormulaEditorOptions/FormulaEditorEvents; CommandId, ContextFlag, +│ KeyContext, Combo, Binding +├── highlightController.ts — HighlightController: overlay rendering + adapter highlights +├── refController.ts — RefController: ref-insertion state machine +├── popupController.ts — PopupController: suggestions popup + fn-help lifecycle + textarea +│ ARIA mirroring (applySuggestionsAria / applyFnHelpAria) +├── keyboardController.ts — KeyboardController: keydown dispatch (delegates to ShortcutManager) +├── shortcutManager.ts — ShortcutManager: declarative keybinding dispatch (ordered binding +│ table + command map; pure, DOM-free) +├── keymap.ts — BINDINGS: the declarative key-combo → command table (data only) +├── pointModeController.ts — PointModeController: arrow-key reference point-mode state machine +├── editorSizeController.ts — EditorSizeController: caps the editor's max-width AND max-height at +│ the nearest clipping ancestor's client edges (overflow ≠ visible walk +│ from the editor root), so a long formula soft-wraps +│ at the grid's right edge and, when it hits the bottom edge, the editor +│ stops growing and scrolls internally (hfe-editor--height-capped — +│ applied only when content actually overflows the cap — sets +│ overflow-y: scroll on BOTH the textarea and the overlay so both +│ reserve an identical scrollbar gutter and wrap at the same width; +│ a gutter on only one layer shifts its wrap points and desyncs the +│ caret from the colored text. ScrollAnchor mirrors textarea scroll +│ onto the overlay). The overlay gets a padding-bottom mirror of the +│ textarea's scrollHeight because Chrome gives the textarea a phantom +│ caret line when text ends exactly at a wrap boundary — without it the +│ two layers' scroll ranges diverge. Recomputes on input, attachTo, +│ ancestor scroll, and window resize; no clipping ancestor → falls +│ back to the viewport (documentElement client box at 0,0) as the +│ clip, so hosts without an overflow wrapper still get both caps. +│ The height cap never exceeds the clip's clientHeight: once an +│ ancestor scrolls the editor's top above the clip, the rect-based +│ distance to the clip bottom grows by the scroll, and the clamp +│ keeps that from growing the editor. +│ A host may tighten the width cap below the clip edge by setting the +│ --hfe-editor-max-width CSS variable on the editor's mount (the +│ external Handsontable formulaBuilder plugin sets it in its +│ formulaCellEditor's refreshDimensions +│ — applyContentEdgeWidth — to the distance from the edited cell to the +│ master scroll holder's content edge (read via +│ hot.view.getOverlayByName("top").holder), so a right-edge cell wraps at the +│ true grid edge instead of HOT's wider outer wrapper; the js basic +│ demo sets it to its panel's content width so the resize grip can't +│ drag the editor past the panel). The width FLOOR is +│ --hfe-editor-min-width (editor.scss min-width, default 100% of the +│ mount — grid cells keep cell-width parity; a standalone host may +│ lower it so the resize grip can shrink the editor below the mount). +│ Height is host-configurable in line units: +│ --hfe-editor-min-lines (opening height + native-resize floor; min IS +│ the default) and --hfe-editor-max-lines (growth + drag ceiling, +│ intersected with the clip cap), both resolved as +│ lines × line-height + the textarea's computed vertical padding — +│ line-height comes from the textarea too (probe-measured when +│ "normal", root fallback), so adapter overrides count; min-height +│ is written as max(100%, Npx), keeping the stylesheet's mount-parity +│ floor so min-lines never shrinks the editor below its host cell; +│ the Npx term is clamped to the available height (clip ∩ max-lines) +│ so min-height can't beat max-height and overflow the clip. +│ Unparseable lines value → off. +│ --hfe-editor-resize: vertical enables the browser-native resize grip +│ on the editor root (resize: var(--hfe-editor-resize, none) + +│ overflow: hidden); a ResizeObserver on the root routes manual drags +│ through update(), where a browser-written inline height drives the +│ overlay cap + height-capped class. attachTo calls resetManualSize() +│ (clears the browser-written inline size), so every reopen renders +│ content-sized within the clamps. +│ Wrap parity relies on textarea wrap="soft" + the shared +│ white-space: pre-wrap / word-break: break-all block in editor.scss +│ applied identically to the input and the overlay +└── scrollAnchor.ts — ScrollAnchor: textarea scroll sync + ancestor-scroll reanchor +FormulaBar (formulaBar/) +├── formulaBar.ts — FormulaBar: bar mount; composes FormulaBarAddressBox + +│ FormulaBarCell; drives the shared FormulaEditor between bar and +│ inline cell via the IGridAdapter bar-lifecycle methods (see +│ host-switch model above) +├── formulaBarAddressBox.ts — FormulaBarAddressBox: own-root jump-to-cell input +│ (AddressBoxTarget {col,row}); Enter commits via onNavigate, +│ Escape/blur reverts to the last-synced address +└── formulaBarCell.ts — FormulaBarCell: own-root fx icon + idle colored-formula view + (own VisualOverlay) + the overlayMount the shared editor + attaches into while bar-hosted +Kernel (kernel/) +├── kernel.ts — tokenizes text, maintains state, emits events +├── stateManager.ts — holds current text + tokens + cursor position +├── eventBus.ts — typed publish/subscribe bus (KernelEventMap) +├── commentTransform.ts — commentsToN / nToComments boundary +└── types.ts — FormulaState, CursorPosition, KernelEventMap +Lexer (lexer/) +├── lexer.ts — hand-written stateless scanner; tokenizes partial/invalid input live; +│ locale-configurable separators (decimal/arg/array) +├── tokens.ts — TokenType + colLettersToIndex/indexToColLetters +├── types.ts — Token + ref/comment/named-expr meta interfaces, LexerOptions +├── matchers.ts — per-token-kind match helpers used by the scanner loop +├── patterns.ts — shared regex fragments +└── additiveContext.ts — marks each COMMENT token contextOk (legal + N(...) slot) for the + comments boundary +EngineBridge (engine/) +├── engineBridge.ts — EngineBridge facade: separators, config reads, sheet-boundary +│ queries (isOwnSheet / expandWholeRange); delegates the function +│ catalog to FunctionCatalog and named-expression resolution to +│ NamedExpressions. The ONLY HyperFormula access point outside +│ src/engine/ (composed across these engine/ files) +├── functionCatalog.ts — FunctionCatalog (internal): catalog build, signatures, filtering; +│ owns the module-level catalog/canonical caches +├── namedExpressions.ts — NamedExpressions (internal): named-expression scope resolution, +│ formatNamedRange, filtering +├── namedExpr.ts — whole-range span math + annotateNamedExprs token annotation +├── namedExprName.ts — validateNamedExprName +├── readCellText.ts — readCellText(engine, addr): formula → serialized → value fallback +│ shared by adapters and demo hosts +└── types.ts — shared engine types: FunctionParam/FunctionSignature/ + FunctionCatalogEntry, HyperFormulaLike, NamedExprResolution, + CellTextSource/EngineCellAddress +IGridAdapter (adapter/) +├── types.ts — the IGridAdapter contract, composed of three required role interfaces +│ plus one optional one, that mirror the core consumers: GridPickSurface +│ (coord lookup, ref formatting, highlights, cell-pick events, +│ onOutsideCellClick, the outsideClickCommitMode capability, +│ setOverlayClassName, ref-selection mode — driven by FormulaEditor + +│ HighlightController), GridNavigation (getGridSize, getDataEdge, +│ stepCell, scrollCellIntoView — driven by PointModeController; +│ move/jump scroll the viewport so the point-mode cursor stays visible — +│ the point-mode anchor comes from the edit-lifecycle getActiveCell), +│ GridEditLifecycle (the bar/edit lifecycle — driven by FormulaBar and +│ the barless inline-edit subscription), GridHeaderPickSurface +│ (onHeaderPick(callback): Unsubscribe, emitting HeaderPick {axis, +│ sheet, start, end, append} with start/end in HF/engine-space indices +│ — driven by header click/drag on the grid's row/column headers). +│ GridHeaderPickSurface is optional: IGridAdapter and EditorGridAdapter +│ both mix it in as Partial, so adapters without +│ headers (NullAdapter included) implement nothing for it — no no-op +│ method needed. FormulaEditor.wireAdapter subscribes defensively via +│ `adapter.onHeaderPick?.(...)`, formatting the pick with +│ formatWholeRef(pick) (adapter/refFormat.ts, A:C / 4:4 shape) before +│ inserting; expandHeaderSpan(pick, size) (adapter/range.ts) turns a +│ HeaderPick into the equivalent CellRange for highlighting. Adapters +│ that do implement it must never intercept a header interaction that +│ is ineligible (outside ref-selection mode, or drag/click not aimed at +│ a real header) — no preventDefault, no synthetic emit; host-native +│ behavior runs unmodified. Implemented by the external Handsontable +│ formulaBuilder plugin, which covers both axes via its +│ CellPickController, and by the four example adapters maintained +│ outside this repository: AG Grid (column-only, dual path — DomRangePicker for +│ bar-hosted editing, plus an inline-edit interceptor feeding an +│ adapter-owned HeaderDragTracker; ineligible/unresolvable header +│ clicks stay swallowed dead, a deliberate exception protecting +│ against mid-edit sorting); MUI (column-only, direct DOM mousedown on +│ the header cell plus an apiRef columnHeaderOver extension — no +│ columnHeaderMouseDown apiRef event exists); plain-table and TanStack +│ (both axes, via DomRangePicker, riding HeaderDragTracker +│ transitively). IGridAdapter extends all four and adds +│ destroy() (host-owned lifecycle, never called by core); +│ EditorGridAdapter = GridPickSurface & GridNavigation & +│ Pick & +│ Partial — the slice FormulaEditorOptions.adapter +│ and EditorContext.adapter are typed against (FormulaBar/FormulaBuilder +│ take the full IGridAdapter); also GridGeometry, RangeRect +├── nullAdapter.ts — no-op implementation FormulaBuilder falls back to when constructed +│ without an adapter; also the base class for basic adapters +│ (the plain-table example's PlainTableAdapter extends it) +├── cell.ts — parseCellInput / formatCellValue / stepCell (single-step clamped move) +│ / findDataEdge (data-aware boundary walk shared by every adapter's +│ getDataEdge; the caller supplies a hasData predicate in its own +│ coordinate space) +├── range.ts — CellRange helpers, expandWholeRange, expandHeaderSpan +├── geometry.ts — coordinate math +├── refFormat.ts — A1-notation formatting, formatWholeRef +├── refAbsolute.ts — cycleRefAbsolute: F4-style $-anchoring cycle on the ref under the caret +├── domRangePicker.ts — DOM-based range selection helper; owns the DOM event wiring +│ (mousedown/mousemove/mouseup/blur) and eligibility gating, delegating +│ the drag state machine to RangeDragTracker (scroll element defaults +│ to the nearest scrollable ancestor of the root, overridable via +│ getScrollElement) +├── rangeDragTracker.ts — RangeDragTracker: shared drag-pick state machine (anchor/last/append +│ state, preview on extend, single-cell vs range drop decision, edge +│ autoscroll integration); input-source agnostic — DomRangePicker feeds +│ it DOM events, adapter-level pickers (AG Grid's in-edit picks, the +│ external Handsontable plugin's CellPickController) feed it their own +│ events; callers render previews and route drops via its callbacks +├── headerDragTracker.ts — HeaderDragTracker: shared header-drag state machine, the +│ RangeDragTracker pattern applied to whole-row/column picking +│ (anchor/last/append, same-axis latch, normalize lo:hi on drop; options +│ sheet/onPreview/onDrop/onDragEnd); input-source agnostic — DomRangePicker +│ consumes it internally (behavior unchanged from before the extraction), +│ the AG Grid adapter's header interceptor and the external Handsontable +│ plugin's CellPickController each feed it their own events +├── trailingClickSwallow.ts — armTrailingClickSwallow(document, shouldSwallow): one-shot +│ document-capture click swallow armed after a routed header pick, so the +│ gesture's trailing click never reaches host sort/filter handlers; +│ self-removes on the next click OR mousedown (a stale arm from a drag +│ whose click never fired dies on the next gesture instead of eating it); +│ consumed by DomRangePicker, MUI RefPickController, and the external +│ Handsontable plugin's CellPickController +├── edgeAutoScroller.ts — EdgeAutoScroller: shared drag-past-edge autoscroll primitive +│ (overshoot → clamped scroll steps on rAF + onStep callback with the +│ pointer clamped to the scroll element's client box); driven by +│ RangeDragTracker +└── pickEmitter.ts — cell/range/header pick event wiring +UI (ui/) — split by concern: popup/, text/, caret/, highlight/, plus shared dom.ts, icons.ts +├── dom.ts — createEl / clear / ensureRelativePosition helpers (shared primitive); +│ createIcon builds a glyph from a host IconsOptions factory or, +│ failing that, from the built-in SVG data via createSvgIcon +│ (createElementNS — no HTML sink) +├── focusTrap.ts — FocusTrap: reusable focus-scope primitive (focusable discovery via +│ generic selector, focusFirst, focusNext with Tab/Shift+Tab wrap, +│ exit-key callback — default exit key is Escape, hosts override via +│ exitKeys (fn-help passes ["F6"] only — Escape inside the popup now +│ closes it instead of just exiting the trap, so it is handled by the +│ popup's own keydown listener, not the trap) — hasFocus); owns no +│ listeners — the host registers +│ keydown and delegates to interceptKeydown (used by +│ FunctionHelpPopup's F6 scope) +├── icons.ts — SVG icon data shared by popups and FormulaBarCell's fx icon, +│ keyed by IconName in BUILT_IN_ICONS +├── types.ts — IconName, IconsOptions (public: the `icons` option) +├── popup/ +│ ├── basePopup.ts — base class for all popup-style overlays; self-appends root to container +│ ├── suggestionsPopup.ts — suggestions dropdown (extends BasePopup) +│ ├── functionHelpPopup.ts — function signature popup, non-modal dialog (extends BasePopup); also exports +│ │ FunctionHelpPopupOptions (single-consumer, inlined here) +│ ├── errorPopup.ts — error tooltip (extends BasePopup); lifecycle owned by FormulaBuilder; +│ │ also exports ErrorPopupOptions (single-consumer, inlined here) +│ ├── cellError.ts — cellErrorMessage / setCellError adapter-facing cell-marking utils +│ ├── popupContext.ts — PopupContext class; owns the shared
portal that all +│ │ popups for one adapter instance are appended to; constructed +│ │ and owned exclusively by FormulaBuilder, not part of the +│ │ package's public surface +│ ├── positionStrategy.ts — BottomViewportAnchoredStrategy / EndViewportAnchoredStrategy; viewport-absolute coords +│ ├── popupsOptions.ts — withSharedClose(): consumer-facing popup options resolution +│ └── types.ts — shared popup types: AnchorRect, Position, Viewport, PositionStrategy, +│ SuggestionItem, SuggestionsHandlers, SuggestionsAriaState, +│ SuggestionsOptions, FunctionHelpOptions, ErrorOptions, PopupsOptions +├── text/ +│ ├── richInput.ts —