Skip to content

Conventions

matthew edited this page Aug 29, 2026 · 1 revision

Coding conventions

The rules code is reviewed against. The mechanical ones are enforced by ESLint and Prettier; the rest are enforced in review. The short checklist is at the end of Build, test and tooling.

7. Coding conventions

Three rules are mandatory and mechanically enforced; the rest elaborates on them.

  1. Object-orientation first. Favour OOP; reach for FP only where it expresses the problem better.
  2. Explicit member accessibility. Every class member is explicitly public/protected/private.
  3. Explicit, total type annotations. Annotate every type — members, parameters, return types, and local variables. any is forbidden.

Paradigm — OOP first, FP where it fits

Model the domain with classes, interfaces, and clear responsibilities. Use functional techniques when they read better: pure functions for stateless transforms; array methods (map/filter/reduce) over manual loops where clearer (mind allocation on hot paths — justify a manual loop with // Why:); signals for reactive state. Don't force a paradigm: a stateless single-method class is usually a function; free functions sharing mutable state are usually a class.

Type safety

  • Annotate everything, including locals, even where inferrable — annotations are documentation and a guard against inference drift: const retryLimit: number = 5;.
  • any is forbidden. Use unknown and narrow explicitly.
  • null vs undefined: prefer undefined for "absent"; reserve null for intentionally-empty values and interop. Never silently return null/undefined to signal failure.
  • Immutability by type: readonly, readonly T[], Readonly<T>, as const.
  • Prefer narrow types: union literals and discriminated unions over loose string/number and boolean state flags.

Access modifiers

  • Every member carries an explicit modifier; start at private and widen only for a real consumer.
  • Mark readonly wherever not reassigned after construction.
  • Never prefix private members with an underscore (private name, not private _name) — this. already disambiguates.
  • Template-bound component members are protected, not public — they are the template contract, not public API. private members are not template-accessible.
  • Use #private JS fields only for hard runtime privacy (e.g. secrets in the main process).

Naming

  • Intention-revealing, pronounceable, searchable names. Classes are nouns (WindowManager); methods and functions are verbs (createWindow); booleans read as predicates (isActive, hasChildren).
  • No misleading names (don't call a Map a list). No I-prefix on interfaces. No Hungarian / type-encoding prefixes.
  • Casing: PascalCase (classes, interfaces, type aliases, enums, decorators, enum members); camelCase (methods, functions, properties, variables, parameters); UPPER_SNAKE_CASE (genuine compile-time global constants); kebab-case (file names).

Classes, functions & structure

  • Single Responsibility; stepdown rule (public API first, private helpers below, each one level of abstraction beneath the last); composition over inheritance (inject collaborators); prefer fully-initialised readonly objects over mutable-with-setters.
  • File-level SRP — a file holds one primary responsibility; no file crosses ~500 LOC / ~5 responsibilities without decomposition. Extract pure transforms into free-function modules and stateful collaborators into injected classes (with dispose() only where there is per-instance lifecycle to tear down), keeping the original type a thin orchestrator that forwards to them; reuse shared atoms/wrappers rather than re-implementing.
  • Functions are small and focused (~≤20 lines, one thing, one level of abstraction) with 0–2 parameters (three or more → a parameter/options object).
  • Explicit return types on every function and method, including void/Promise<void>.
  • No unintended side effects — a query must not mutate. Prefer async/await; never leave a floating promise (await it, return it, or mark it handled); surface cancellation via AbortSignal.
  • Ship no dead code — no stub/seed data on production paths, no editable setting without a reader, no unreferenced exports. Add a control/feature only with the code that consumes it. (Commented-out code and untracked TODOs are covered under Comments below.)

Error handling

  • Throw errors, don't return codes. Throw Error or a domain subclass: class CustomerNotFoundError extends Error { … this.name = 'CustomerNotFoundError'; }.
  • Don't silently return null/undefined for failure — throw, or make absence explicit in the type and document it. Scope resources with try/catch/finally. For expected non-exceptional failure a result type ({ ok: true; value } | { ok: false; error }) is acceptable — used deliberately.
  • Catch unknown and narrow (catch (error: unknown) { if (error instanceof DomainError) … }).
  • Log every caught exception as an error — logger.error(source, 'what failed', error) (main) or log.error(...) (renderer), passing the error object so its stack survives. Never swallow an error silently. See Runtime seams › Logging.

Documentation (TSDoc)

Every member is documented — regardless of visibility, in genuine descriptive prose (capitalised, ending with a period, never placeholder). Reference symbols with {@link Symbol}. Opening phrases are conventional and carry meaning:

Member Opening phrase
Class Represents …
Interface / type / function-type Defines …
Enum Specifies …
Constructor Initializes a new instance of the {@link TypeName} class.
Read-only property/accessor Gets …
Write-only accessor Sets …
Read/write property/accessor Gets or sets …
Boolean property Gets a value indicating whether …
Method A verb phrase describing the action

Required tags: @param per parameter; @returns (text begins with "Returns") for every non-void return; @typeParam matching each generic; @throws {@link ErrorType} per throwable. Avoid empty tags and identical summaries across unrelated members.

Comments (non-documentation)

Rare — prefer rewriting unclear code over explaining it. A comment explains why, never what; lead performance/correctness choices with // Why:. No commented-out code (version control is the history). No TODO without a tracked issue (// TODO(#123): …).

Formatting

Line length 100 (printWidth: 100). One statement / declaration per line. Single quotes, semicolons, trailing commas — never hand-format against Prettier. Import order: external packages, then internal modules, then relative; no unused imports. Break long fluent chains one operator per line.

Angular conventions

  • Standalone components only (no NgModules); declare deps in imports.
  • Signals are the default — signal() (state), computed() (derived; synchronous, memoised, glitch-free — do not hand-wire derived values through RxJS), effect() (reactive side effects). The app is zoneless — do not depend on Zone.js. Reach for RxJS only for genuine async streams (debounced input, IPC feeds) and unavoidable Observable interop, bridged back to signals with toSignal(); never leak a manual subscription.
  • ChangeDetectionStrategy.OnPush on every component. DI via inject(), not constructor params. Signal inputs/outputs (input(), input.required(), output(), model(), viewChild()). Built-in control flow (@if/@for/@switch; always @for … track).
  • @Service() (the project's providedIn: 'root' decorator) for singleton services. Component selectors app- + kebab-case. Services hold logic; components orchestrate (keep components thin).
  • Because the app is zoneless, NgZone.run/runOutsideAngular are effectively identity; some ported code still calls zone.run defensively — preserve it on relocation rather than stripping it.

Electron conventions

Security is a first-class quality concern; the process model stays strictly separated.

  • Process separation: src/shared/electron/main.ts (Node) and preload.ts (bridge) are trusted; the Angular renderer is untrusted and sandboxed.
  • Locked-down webPreferences: contextIsolation: true, nodeIntegration: false, sandbox: true — mandatory, never relaxed.
  • Expose a minimal API via contextBridge — the generic window.bridge (invoke/send/on) + window.host. Never expose ipcRenderer or any Node API to the renderer.
  • Validate every IPC payload in main before acting — treat all renderer input as hostile. Prefer ipcMain.handle/invoke (request/response) over fire-and-forget send. Name channels by domain (project:open, window:minimize) in the per-domain *-channels.ts enums.
  • Restrict navigation and window creation (will-navigate, setWindowOpenHandler); set a Content-Security-Policy; never load remote untrusted URLs into a privileged renderer.

Testing (Vitest)

  • TDD by default; F.I.R.S.T. (Fast, Independent, Repeatable, Self-validating, Timely).
  • Arrange / Act / Assert separated by blank lines; one logical assertion per test.
  • Name tests method_condition_expectation (load_whenCustomerMissing_throwsCustomerNotFoundError). Test behaviour through the public API. Async tests await; cover documented contracts including error paths.

Control atoms

A feature template never writes a raw <button>, <input>, <select>, <textarea>, checkbox or radio. It uses the atom from src/shared/angular/components/forms/ (app-button, app-text-field, app-textarea, app-dropdown, app-checkbox, app-radio, app-toggle, app-button-group, …), and the atom owns the styling. A call site may pass a variant; it may never restyle a control locally. Where no atom exists, the atom gets written — the element is not inlined "just this once".

This exists because the same control was hand-rolled repeatedly and drifted: four near-identical confirm buttons once had different padding, radius, hover treatment, and a coral-versus-accent primary. The atoms were measured from one reference pair and every call site was converted (2026-07/08).

Button variants are about shape only — solid (filled accent), outline (transparent, grey border; the default) and none (no fill, no border; tool-strip and ribbon chrome) — with medium and small sizes. Icon-only is derived, not declared: a glyph with no label is square. Meaning (danger, warning, success) is a separate tone axis to be added later, so tones arrive additively.

Every strip control shares one height — --control-height (1.75rem) and --control-height-small (1.25rem) in _variables.scss. A control that fills a strip sets block-size from the token and keeps only its inline padding; that is why a dropdown, a text field and a button line up.

Structural elements are not controls. A tab, a list row, a menu trigger, a welcome card is a <button> for keyboard and screen-reader reasons, but it is not app-button — it reads the shared tokens instead. Repeated structural markup becomes its own component (the six welcome cards are one component). Components whose internal <button> is the implementation (app-dropdown's face, app-menu's items, the ribbon-strip buttons, dock-tool-strip) consume the same tokens as app-button so they cannot drift, but nothing about them moves.

The one sanctioned exception is the welcome screen: its search box, Clear pill and filter pills stay hand-rolled. It is the application's one bespoke surface, drawn to its own palette (--wl-*) and geometry, and the shared controls would either look wrong there or have to be overridden from the call site — the drift the atoms exist to prevent. Reverted knowingly (2026-07-29) and commented at both the markup and the stylesheet. Its confirm-dialog buttons and its pin control do use the atoms; nothing else may follow.

A dockable panel's chrome is ToolPanel. Extra header controls go in its panelActions slot; a body that manages its own padding sets [flush]="true". Neither is a reason for a new title bar.

Still open from the conversion: an app-link atom for inline text links (agent__action-more and kin), an app-slider for the one range input, and the composer's own text area.

Clone this wiki locally