Skip to content

Latest commit

Β 

History

History
463 lines (358 loc) Β· 25.1 KB

CLAUDE.md

File metadata and controls

463 lines (358 loc) Β· 25.1 KB

CLAUDE.md

This file provides guidance to AI coding assistants β€” including Claude Code, GitHub Copilot, and similar tools β€” when working with code in this repository.

Project Overview

Hoist-react is the client-side component of the Hoist web application development toolkit, built by Extremely Heavy Industries (xh.io). It is a library package (not a standalone app) published as @xh/hoist and consumed by Hoist application projects. The server-side counterpart is hoist-core.

  • Language: TypeScript
  • Framework: React with MobX for reactive state management
  • Package manager: pnpm (version pinned via the packageManager field in package.json)

Hoist Developer Tools and Documentation

IMPORTANT: Do not guess at hoist-react APIs, component props, or framework patterns. The package READMEs and concept docs are the authoritative reference for how Hoist works - skipping them risks producing code that conflicts with established patterns or misses built-in functionality.

Hoist Docs MCP server (hoist-docs) - Hoist Docs serves hoist-react and hoist-core documentation and API reference over MCP. .mcp.json runs it locally over stdio (npx @xh/hoist-docs); in this checkout it serves both libraries' develop indexes. Use hoist-search-docs, hoist-list-docs, hoist-read-doc, hoist-search-symbols, hoist-get-symbol, and hoist-get-members, plus hoist://docs/{id} resources. To serve this checkout's current state instead, build indexes in a hoist-docs checkout (pnpm build:react --root ../hoist-react) and set HOIST_DOCS_INDEX_DIR to its indexes directory.

Without the server, read the docs directly: start at docs/README.md, whose "Quick Reference by Task" table maps goals to the right README or concept doc, then read the TypeScript source for exact signatures.

Using the tools: for how-to and concept questions start with hoist-search-docs and read one returned section with hoist-read-doc {id, section}. For exact names and signatures start with hoist-search-symbols - one strong keyword, ideally an API name (GridModel, persistWith, headerName); camelCase names match their parts. Then hoist-get-symbol gives the import line, signature, docs, and a member summary, and hoist-get-members with filter gives member docs. Prefer the package barrel import path when one is shown. impl/ and admin/ code is excluded unless you pass includeInternal: true.

GitHub

Use the GitHub CLI (gh) for GitHub operations: gh pr view, gh issue list, gh pr create, and gh api for anything else. Prefer it over raw curl calls to the GitHub API.

Chrome DevTools MCP Server (chrome-devtools)

Google's chrome-devtools-mcp lets an agent drive and inspect a Chrome window: navigate, click, type, read the console and network requests, and take screenshots. Use it to check a change in a real browser, with Toolbox running against this checkout as described in Running Toolbox against this checkout.

The server connects to a Chrome that you start yourself, with remote debugging on port 9222:

/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome \
  --remote-debugging-port=9222 --user-data-dir="$HOME/.chrome-debug-profile"

The separate --user-data-dir is required. Chrome ignores the debugging flags on its default profile. A fixed folder keeps logins between sessions and keeps the agent out of your everyday profile. To check that the port is open, run curl -s http://127.0.0.1:9222/json/version.

Not enabled by default - add "chrome-devtools" to enabledMcpjsonServers in .claude/settings.local.json to enable it for yourself:

{
  "enabledMcpjsonServers": ["hoist-docs", "chrome-devtools"]
}

hoist-ai plugin (xh@hoist-ai)

The shared .claude/settings.json enables XH's xh@hoist-ai plugin, the same plugin that Hoist applications use. Enabling it does not install it. Each developer should install it once per machine at user scope, which covers every repo and worktree and auto-updates. If no xh: skills appear in your available skills, tell the developer the plugin is missing and give them the command claude plugin install xh@hoist-ai --scope user. Offer to run it for them.

Three of its skills apply in this repo:

  • xh:clear-writing - house style for CHANGELOG entries, PR descriptions, docs, and comments. Prose written here follows its rules. Lint a draft with its script before you commit it.
  • xh:setup-worktree - provisions a runnable worktree. It knows this repo has no client-app/.
  • xh:using-hoist-react-reference - routes Hoist API questions to the MCP tools above. It restates what this file already says, so it adds little here. It is the skill that app developers rely on, so keep it enabled. It still describes the stdio server and CLI tools this repo used to ship, and needs updating for the Hoist Docs service.

The other skills are for Hoist applications and do not apply to this library:

  • xh:onboard-app and xh:hoist-upgrade expect an app with a client-app/ folder. To write upgrade notes for a hoist-react release, use this repo's own xh-upgrade-notes skill instead.
  • xh:using-hoist-core-reference covers Grails and Groovy code, which this repo has none of.

The plugin loads from the marketplace copy, not from a sibling ../hoist-ai checkout. To try a local skill change, install the plugin from that path as hoist-ai's own CLAUDE.md describes.

Build Commands

pnpm install                     # Install dependencies
pnpm lint                        # Lint all code (library JS/TS, SCSS)
pnpm lint:code                   # Lint library JavaScript/TypeScript only
pnpm lint:styles                 # Lint SCSS only
pnpm typecheck                   # Type check library
pnpm test                        # Run library unit tests (Vitest)
pnpm test data/Store             # Run unit tests in spec files whose path contains "data/Store"

Linting and type-checking are separate concerns, and neither subsumes the other β€” run both. ESLint is configured type-aware, but that only powers its own rules; it never reports TypeScript compiler errors, so a genuine type error passes pnpm lint. CI runs the two as distinct steps.

This is a library β€” it has no dev server or standalone build. To run locally, use a wrapper application project (e.g., Toolbox) that includes @xh/hoist as a dependency.

Unit Tests

Before writing or changing a unit test, read docs/unit-testing.md. The essentials:

  • Specs sit next to the code they test, as Foo.spec.ts for Foo.ts. CI runs them on every PR as the "Unit Tests" check.
  • When you change library behavior, add or update the specs that cover it, and run pnpm test.
  • Tests run Hoist's real services against a fake hoist-core server (test-support/hoistCore.ts). Boot it with initTestAppAsync(). Do not mock Hoist modules with vi.mock.
  • Name tests for the behavior they check, so the test list reads as a spec. Test contracts that apps rely on - not trivial getters, rendering, or third-party libraries.
  • When a test exposes a library bug that is not fixed in the same change, mark it it.fails() with a // BUG: comment.

A failing pnpm test run prints each failure with its diff. On a PR, gh pr checks shows the check status, and gh run view <run-id> --log-failed shows the failing output.

Architecture

Core Artifacts

The framework is built around three core artifact types:

  1. Models (HoistModel) - State management and business logic classes. Properties are marked with MobX decorators to make them observable. Models form hierarchies reflecting app structure.

  2. Components (hoistCmp) - Functional React components wrapped with Hoist support including MobX reactivity and model lookup. Created via hoistCmp.factory({}).

  3. Services (HoistService) - Singleton classes for data access and app-wide business logic. Installed via XH.installServicesAsync() and accessed as XH.myCustomService.

See /core/README.md for detailed coverage of all three artifact types.

Key Singleton: XH

XH (in core/XH.ts) is the top-level API entry point. It provides:

  • Access to all Hoist services (e.g., XH.configService, XH.fetchService, XH.myCustomService)
  • App metadata (XH.appCode, XH.appVersion)
  • Common operations (XH.toast(), XH.confirm(), XH.handleException())

See /core/README.md for the full XH API and /svc/README.md for built-in service details.

Element Factories vs JSX

Hoist strongly encourages rendering components via element factories (created at component definition time via the hoistCmp.factory util) over JSX. This minimizes XML-style markup and keeps client side codebases anchored in standard TypeScript/JavaScript syntax:

// Element factory style - strongly preferred
panel({
    title: 'Users',
    children: [grid({model: gridModel})],
    bbar: toolbar(button({text: 'Save'}))
})
// JSX also fully supported - but rarely used by XH
< Panel
    title="Users"
    bbar={<Toolbar><Button text={'Save'}/></Toolbar>}
>
    <Grid model={gridModel}/>
</Panel>

Factories can take a config object for props, using the standard React children key for children. In the shortcut form, factories take children directly as arguments. Use the shortcut form when a call passes only children - toolbar(a, b), p('text') - and the config object form as soon as it passes any other prop. Never pass a factory directly as a callback (rows.map(span)). Factories all support an omit prop for conditional rendering.

item and items are legacy aliases for children. They still work, but do not use them in new code. A container component destructures children from props and passes it on as children to an inner factory. See Authoring a Container Component in the core README for examples and the $items escape hatch for components with their own items prop.

See /core/README.md for full element factory API including conditional rendering with omit and factory creation.

HoistBase for MobX Integration and Lifecycle

All Hoist artifacts extend HoistBase, which provides:

MobX Integration Conventions

  • addAutorun() / addReaction() - Managed MobX subscriptions (auto-disposed on destroy)
  • TC39 decorators - no makeObservable() call is needed. Declare @observable and @bindable fields with the accessor keyword (e.g. @bindable accessor myProp = null).
  • @observable MobX decorator - Marks properties as observable state. Use the MobX 7 named re-exports from @xh/hoist/mobx for variants - e.g. @observableRef for reference-only.
  • @action MobX decorator - Marks methods that modify observable state
  • @bindable Hoist decorator - Marks properties as observable and generates setter methods automatically marked as @action - e.g., setMyProp(value) for property myProp (Hoist custom decorator). @bindableRef is the reference-only variant. Setter convention: If a class defines an explicit public setFoo() method, call it (it likely has additional logic). Otherwise for auto-generated @bindable setters, prefer direct assignment (model.myProp = value) over calling the generated setter (model.setMyProp(value)).
  • @computed MobX decorator - Marks getter properties as derived/computed state

Memory/lifecycle Management Conventions

  • @managed decorator - marks child objects for automatic cleanup - apply to properties holding HoistBase instances or arrays of such instances.
  • destroy() - Lifecycle cleanup method. HoistBase superclass implementation auto-disposes managed subscriptions and child objects.

See /core/README.md for detailed HoistBase API, persistence support, and common pitfalls.

Promise Conventions

  • Methods returning Promises are suffixed with Async (e.g., loadUsersAsync)
  • Use the Runner chain (this.runner({loadSpec}).linkTo(...).track(...).fetchJson(...)) for masking, activity tracking, and spans - see docs/telemetry.md
  • Promise extensions (catchDefault(), track(), timeout(), linkTo()) are the lower-level API the Runner wraps

Prefer Hoist Input Components Over Raw HTML

Always use Hoist's built-in input components (textInput, numberInput, select, picker, checkbox, switchInput, dateInput, textArea, etc.) rather than raw HTML <input>, <select>, or <textarea> elements. Hoist inputs provide consistent styling, model binding, and proper integration with the framework's theming and layout system. Raw HTML elements require manual wrappers and custom SCSS that duplicate what Hoist already provides.

Platform Support

Components in /desktop/ and /mobile/ are platform-specific. Shared code lives in /cmp/, /core/, /data/, and /svc/.

Code Style

For the full conventions reference β€” import organization, class structure, component patterns, null handling, async patterns, error handling, logging, and CSS naming β€” see docs/coding-conventions.md. The principles below are the most important guidelines to internalize:

  • Don't Repeat Yourself β€” Extract shared logic into utilities, base class methods, or helpers. Balance DRY against readability β€” extract when a genuine, stable pattern exists, not prematurely.
  • Clear, descriptive naming β€” Names should convey intent and read naturally. Be descriptive but not verbose (selectedRecord, not r or theCurrentlySelectedRecordFromTheStore).
  • Don't hand-roll collection manipulation - Before writing or approving a loop or inline closure that compares, searches, groups, partitions, dedupes, sorts, merges or reshapes arrays and objects, check lodash and @xh/hoist/utils (including utils/impl for framework code) for an existing helper. Lodash is null-safe, battle-tested, and aids readability. Use native JS only when equally expressive (e.g., array.map(), array.filter()). See Prefer Lodash for Utility Operations.
  • Match the existing pattern - Before special-casing one member of a family (one option, prop, config key or override), check how its siblings are handled and do the same. If the pattern itself seems wrong, raise it rather than changing one case. A drive-by fix to a single member leaves the codebase inconsistent. When consolidating code, keep every condition the old code checked. See Match the Existing Pattern.
  • Keep code concise β€” Favor direct, compact expression over verbose or ceremonial patterns. Use Hoist's own utilities (withDefault, throwIf, element factories) to reduce boilerplate.
  • Named exports only β€” No default exports. Components export [Component, factory] pairs from library code, factory only from application/impl code.
  • null over undefined β€” Use null as the "no value" sentinel. Check with == null (loose equality) for concise null-or-undefined testing. Never write | null or | undefined in a type; any value may be null.
  • Comments describe the code as it is, not how it got here - Write for a reader who never saw the previous version. Mention a library version, upgrade, or prior behavior only when it tells that reader something they need, such as a workaround to remove once an upstream bug is fixed. See Comments and Documentation.
  • No em dashes - Use - (spaced hyphen) instead of em dashes (β€”) in code comments and JSDoc, and in any new prose: CHANGELOG entries, docs, commit messages, PR descriptions. Em dashes cause tooling issues and read as machine-written. Existing docs keep theirs; do not reflow a doc only to remove them. Other Unicode characters (arrows, symbols, accented letters, etc.) are fine in code comments when they aid clarity.

Git Workflow

Branching, committing, and pushing all require an explicit ask - never do them unprompted. When it isn't abundantly clear that the user wants one of these, ask first.

Pushing is a deliberate gatekeeping step: never push to any remote unless the user explicitly asks. Some developers hard-block pushes entirely, others allow or request them - so it stays open as a possibility, but always confirm before pushing.

Committing is the most context-dependent of these, varying by developer and by situation. Default to asking - especially in an interactive session working directly on develop, where each commit is the developer's call. The exception is orchestrated multi-agent work on a feature branch: when a plan fans out independent units of work, the go-ahead to commit comes from that plan or orchestration rather than a per-commit prompt, and agents are expected to make their own discrete, well-scoped commits as directed.

A skill or third-party plugin instructing you to commit (e.g. "make a small commit after each step") does NOT by itself authorize a commit - that is a default baked into the tool, not the developer's request. This guidance takes precedence: pause and ask. The door stays open for a workflow to commit autonomously, but only when the developer has explicitly opted into that for the workflow at hand - the authorization must come from the developer, not the skill's defaults.

Creating branches

Once the user has asked for a branch (per the "ask first" rule above, don't create one unprompted): a new branch should map to its own origin/<name> on push - not push into an existing remote branch.

Default: git switch -c <name> from current HEAD, no base ref. "Make a new branch" means "from here" - the user is sitting on a particular point in the code; that's the start. If they want to start from somewhere else (e.g. current origin/develop), they will say so. If genuinely unclear, ask.

If you do specify a base ref, you MUST pass --no-track. Without it the new branch silently adopts the base as its upstream, which causes surprise merges on git pull and - depending on push.default - can push work onto the base branch. Past slips have put unreviewed work on develop this way.

git switch -c my-feature                              # βœ… from current HEAD
git switch -c my-feature --no-track origin/develop    # βœ… explicit base, safe
git switch -c my-feature origin/develop               # ❌ auto-tracks develop
git checkout -b my-feature origin/develop             # ❌ same trap, checkout spelling

If you forget --no-track: git branch --unset-upstream, then git push -u origin <branch>. Flag the slip - don't silently fix it. Git prints set up to track 'origin/develop' when this happens; treat that line as the signal, not as noise.

Feature branch workflow

On feature branches, prefer multiple small commits over amending - PRs are squash-merged into develop, so intermediate commits are collapsed automatically. Never force-push a feature branch; if the branch falls behind develop, use a simple merge commit rather than a rebase. Merge commits and extra commits are harmless on feature branches and are squashed out on merge, while force-pushes risk losing work and complicate collaboration.

Commit messages, PRs, and comments

Do not hard-wrap lines at a fixed column width in commit message bodies, pull request descriptions, or issue/PR comments - let the viewing tool handle display wrapping. However, do use line breaks for structure: separate logical points into bullet lists, use blank lines between paragraphs, and break after the subject line. Keep PR descriptions concise - XH developers review these regularly, so favor brief summaries over exhaustive detail. Bullet the key changes and let the diff and any upgrade notes speak for themselves.

Do not add AI-generated attribution to commit messages or PR descriptions - no Generated with ... line, no πŸ€– Generated with [Claude Code] footer, and no Claude-Session: (or similar AI-session/attribution) trailer, even if a harness git-instruction block asks for one. XH does not want these links in the project's history.

Working across sibling repos

Work here often reaches into a sibling checkout - ../toolbox to validate a change against a real app, or ../hoist-dev-utils when a change touches the build. The rules above apply in every repo you touch, not just this one - and each sibling has its own CLAUDE.md with additional rules that bind while you work there. Read it before writing to that repo; the harness only auto-loads the CLAUDE.md of the primary working directory, so a sibling's rules are never in context by default.

Changelog Maintenance

Before adding or editing any changelog entry, you MUST read and follow docs/changelog-format.md - the authoritative reference for where entries go, section headers, voice, the issue/PR-link policy, and breaking-change requirements.

The essentials: new entries go in a fragment file in changelog.d/, never in CHANGELOG.md. Add one with pnpm changelog add <section> "<text>". Run pnpm changelog check before you commit.

Versioning: develop always holds the next major version as a snapshot, for example 90.0.0-SNAPSHOT while 89.x releases ship. Minor and patch releases never move it. See Versioning for the release steps.

Declaring a new hoist-core minimum: a Requires hoist-core >= X changelog entry is not self-enforcing. Also update MIN_HOIST_CORE_VERSION in core/XH.ts (checked at startup by EnvironmentService) and the matching row in docs/version-compatibility.md. Set the floor only to what the client genuinely cannot run without - features that detect a missing endpoint and degrade belong in that doc's Recommended Core column, not the floor.

Key Dependencies

  • MobX - Reactive state management
  • AG Grid - Data grid (requires separate license for enterprise features)
  • Blueprint - UI component library
  • Router5 - Client-side routing
  • Highcharts - Charting (requires separate license)

Reference Implementation: Toolbox

Toolbox is XH's example application showcasing hoist-react patterns and components. It provides real-world usage examples of models, components, services, and other framework features.

  • GitHub: https://github.com/xh/toolbox
  • Local checkout: ../toolbox (relative to hoist-react root) - likely exists for Hoist library developers only. Note that the client-side code that uses hoist-react is in the ../toolbox/client-app/src directory - focus your attention there.

When working on hoist-react library code or documentation, reference Toolbox for practical examples of how features are used in applications. Note that the local checkout is specific to the Hoist development environment and would not be available to general application developers who have hoist-react as a dependency.

Running Toolbox against this checkout

To see a hoist-react change in a real browser, run Toolbox with this checkout compiled inline:

  • Client - cd ../toolbox/client-app && pnpm startWithHoist serves http://localhost:3000 and rebuilds when files here change. The page reloads after each rebuild.
  • Server - cd ../toolbox && ./gradlew bootRun serves the Grails API on port 8080, against the developer's MySQL and login by default.

From a worktree of this repo, ../toolbox does not resolve. Run both commands in the Toolbox checkout, and start the client with XH_HOIST_REACT_PATH=<absolute path of this worktree> pnpm startWithHoist. Without it, Toolbox builds the hoist-react checkout next to its own repo, not the worktree. The build banner shows the path and branch in use.

Check first whether both are already running (curl -s -o /dev/null -w '%{http_code}' http://localhost:3000/admin/ and the same for :8080). Leave servers you did not start running when you finish - another session may depend on them.

If you need to log in yourself and have no session to use, never enter the developer's credentials. Start the server on a throwaway in-memory H2 database with a temporary admin instead:

cd ../toolbox
APP_TOOLBOX_USE_H2=true APP_TOOLBOX_OAUTH_PROVIDER=NONE \
APP_TOOLBOX_BOOTSTRAP_ADMIN_USER=agent@xh.io \
APP_TOOLBOX_BOOTSTRAP_ADMIN_PASSWORD=localDevOnly ./gradlew bootRun

Always use exactly agent@xh.io / localDevOnly, never a generated password. Then the developer and other agents can sign in to any throwaway server they find. The user exists only in a local in-memory database, so the password protects nothing.

Startup logs Local admin user available as per instanceConfig. Then log in by POSTing the credentials to /api/xh/login from a page on localhost:3000 (a form fill can be blocked by password-manager overlays) and reload. The database starts empty and is discarded on stop, so features that depend on stored data may not work. Full details, including the login snippet, are in ../toolbox/docs/running-locally.md under "Agent-driven sessions with a throwaway database".