--- url: https://surgijs.github.io/surgijs/guide/getting-started.md --- # Getting started Coming from React? Read [SurgiJS for React developers](./from-react) first. ## Install ```bash npm i @surgijs/core npm i -D @surgijs/compiler ``` `@surgijs/core` is the runtime. `@surgijs/compiler` turns JSX into DOM code at build time. It parses source with [oxc-parser](https://oxc.rs), so it has no TypeScript peer dependency and works with TypeScript 5, 6 and 7. ## Build plugin Vite or Rollup: ```ts // vite.config.ts import surgi from '@surgijs/compiler/vite'; export default { plugins: [surgi()] }; ``` While Vite is serving, the plugin loads React DevTools support. A production build leaves it out. With the extension installed, the component tree shows up; nothing is imported by hand. esbuild: ```ts import { build } from 'esbuild'; import surgi from '@surgijs/compiler/esbuild'; await build({ entryPoints: ['src/main.ts'], bundle: true, plugins: [surgi()] }); ``` Both plugins compile `.jsx` and `.tsx` files outside `node_modules`. The `include` option takes a RegExp or a predicate for other layouts. ## TypeScript ```json { "compilerOptions": { "jsx": "react-jsx", "jsxImportSource": "@surgijs/core", "moduleResolution": "bundler", "strict": true } } ``` `jsxImportSource` gives editors the SurgiJS JSX types. The build plugin replaces JSX before TypeScript or esbuild sees it. ## First component ```tsx import { defineComponent, useEffect, useState, type ReactiveProps } from '@surgijs/core'; export interface CounterProps { step?: number; title?: string; } export const Counter = (props: ReactiveProps) => { const [count, setCount] = useState(0); const { title, step } = props; useEffect(() => { console.log(`Title updated: ${title}`); return () => console.log('Cleanup effect'); }); return (

{title ?? 'Counter'}

Value: {count}

); }; export const MyCounter = defineComponent('my-counter', Counter, { step: Number, title: String }); ``` ```html ``` Props arrive as getters. Inside JSX and template literals the compiler inserts the call, so `{title}` reads the current title and subscribes to it. In plain TypeScript logic call the getter explicitly, as in `step()`. The shadow root renders `

Counter

Value: 0

`. A click updates one text node. ## Working with AI coding agents Point your agent at [`llms.txt`](https://surgijs.github.io/surgijs/llms.txt): a short list of the rules that differ from React and an index of every page as Markdown. [`llms-full.txt`](https://surgijs.github.io/surgijs/llms-full.txt) holds the whole documentation in one file. Every page is also available as Markdown by adding `.md` to its URL, for example [`guide/reactivity.md`](https://surgijs.github.io/surgijs/guide/reactivity.md). ## Development warnings The runtime prints `console.warn` messages prefixed with `[surgijs]` for mistakes that otherwise fail silently: | Warning | Cause | Fix | | --- | --- | --- | | ` is already defined by another copy of @surgijs/core` | Two versions of the library, or a plain `customElements.define`, own the tag. The first definition stays. | Load one copy of `@surgijs/core`. | | `A signal was written inside createMemo or a binding` | A memo or a JSX expression calls a setter. | Write in `createEffect` or an event handler. | | ` keys rows by object identity` | `For` has object items and no `by`. Replacing an object with a copy re-creates its row. | Pass `by={(item) => item.id}`, or `by={(item) => item}` to confirm identity keys. | | `Prop "x" of was read in the component body` | The component function reads a prop outside JSX, `createMemo` and `createEffect`, so the value never updates. | Read the prop where it is used, or wrap the read in `untrack()` when the first value is intended. | | `An effect ran 100 times in one update` | A computation writes a signal it reads, so each run schedules the next. | Read the signal with `untrack()`, or move the write out. | Each warning appears once per signal, `For`, component mount or computation. The warnings live in a separate development build that the `development` export condition selects. Vite and webpack set that condition in development and leave it out of production builds. For esbuild or Rollup, add it yourself in development: `conditions: ['development']` for esbuild, `exportConditions: ['development']` for `@rollup/plugin-node-resolve`. Everything else gets the production build, which has no checks, no messages and no reference to `process`, so it also runs unbundled: from a CDN, an import map, Node or Deno. --- --- url: https://surgijs.github.io/surgijs/guide/from-react.md --- # SurgiJS for React developers SurgiJS keeps the parts of React you write every day (JSX, components as functions, hooks with the same names) and compiles them to web components with fine-grained updates. Most code reads the same. The differences come from one fact: > **A component runs once.** It sets up state and returns the DOM; after that, a change updates only the places that read it. ## Side by side | React | SurgiJS | | --- | --- | | `function Counter({ step })` | `const Counter = (props: ReactiveProps<{ step?: number }>)`, then `const { step } = props` | | `step` is a value | `step` is a getter: `{step}` in JSX, `step()` in code | | `const [count, setCount] = useState(0)` | same; `count` is a getter | | `count * 2` | `count() * 2` (JSX and template literals call it for you) | | `useMemo(() => count * 2, [count])` | `useMemo(() => count() * 2, [count])` | | `useEffect(fn, [count])` | same | | `useEffect(fn, [])` | same: runs once after mount | | `useEffect(fn)` (every render) | `useEffect(fn)` tracks every signal `fn` reads and reruns when one changes | | `useCallback(fn, deps)` | a plain function: components do not re-run, so functions are stable | | `React.memo`, `key` tricks to avoid renders | not needed | | `useRef()` | same, `ref={ref}` on an element | | `useContext(Ctx)` | same, returns a getter | | `{items.map((i) => )}` | ` i.id}>{(i) => }` | | `{cond && }` | `` | | `className` | `class` (or `className`) | | `onChange` on inputs | `onInput` for every keystroke, `onChange` on commit, as in the DOM | | `export default App` + `createRoot(el).render()` | `defineComponent('my-app', App, schema)` and `` in HTML | ## Things that behave differently **The component body is not a render function.** Code at the top of a component runs once, at mount. Reading a getter there takes a snapshot: ```tsx const Price = (props: ReactiveProps<{ amount: number }>) => { const { amount } = props; const label = `$${amount().toFixed(2)}`; // computed once, never updates const live = () => `$${amount().toFixed(2)}`; // a function updates where it is read return {live}; }; ``` Use `useMemo` or a plain arrow for derived values, as in `live` above. **Do not destructure into values.** `const { amount } = props` keeps the getter. `const amount = props.amount()` reads it once. The same holds for objects: `{ count }` in an object literal stores the current value, and the compiler warns about it. **Hooks have no rules of hooks.** Since components run once, hooks can be called in conditions, loops and `For` rows. The order does not matter. **Effects run after mount and on change.** There is no render phase to sync with, so `useEffect` covers what `useLayoutEffect` does in React; DOM refs are attached when it runs. **Props are attributes too.** Each component is a custom element. Props declared in the schema map to attributes (`maxItems` ↔ `max-items`) and properties, so the element works from plain HTML and other frameworks. **Events.** Inside a component, `onClick` and friends work as in React (delegated, `stopPropagation()` honored). To emit events from a component, declare them with `defineEvent`; see [Components](./components#events). ## React hooks you will not need They exist to cope with re-renders, concurrent rendering or React-specific plumbing. A component that runs once has none of those problems. | React | Why | In SurgiJS | | --- | --- | --- | | `useCallback` | keeps a function's identity across renders | a plain function; it is created once | | `useLayoutEffect` | runs after the DOM changes, before paint | `useEffect`: it runs when the element connects, with the DOM attached and before paint | | `useReducer` | state changes through `(state, action) => state` | `useState` and a function that calls the setter | | `useImperativeHandle` | what a parent gets through `ref` | methods and properties live on the custom element itself | | `useSyncExternalStore` | subscribe to an external source | a signal set from a listener in `useEffect`, or `fromStore` from `@surgijs/store/core` | | `useInsertionEffect` | CSS-in-JS before layout | `defineComponent(..., { styles })`, shared through `adoptedStyleSheets` | | `useTransition`, `useDeferredValue` | keep input responsive during heavy renders | updates are fine-grained and batched in a microtask; there is no render to defer | | `useEffectEvent` | read fresh values in an effect without depending on them | list only what should trigger the effect in `deps`, or read with `untrack(fn)` | | `use` + Suspense | read a promise during render | `createResource` with `Show` for loading and error states | | `useActionState`, `useFormStatus`, `useOptimistic` | forms and server actions | form-associated elements (`{ form: true }`); `mutation` in `@surgijs/store` for optimistic updates | | `useDebugValue` | label a custom hook in React DevTools | hook values show up in React DevTools without it | ## Coming from Vue, Svelte or Angular Vue's Composition API, Svelte 5 runes and Angular signals also run component setup once and track dependencies, so most of their concepts map one to one. | Task | React | SurgiJS | Vue 3 | Svelte 5 | Angular | | --- | --- | --- | --- | --- | --- | | State | `useState` | `useState` | `ref()` | `$state` | `signal()` | | Derived value | `useMemo` | `useMemo` | `computed()` | `$derived` | `computed()` | | Effect, tracked automatically | — | `useEffect(fn)` | `watchEffect()` | `$effect` | `effect()` | | Effect on listed dependencies | `useEffect(fn, deps)` | `useEffect(fn, deps)` | `watch(deps, fn)` | `$effect` + `untrack` | `effect()` + `untracked()` | | After mount | `useEffect(fn, [])` | `useEffect(fn, [])` | `onMounted` | `onMount` | `afterNextRender()` | | Cleanup | function returned from `useEffect` | function returned from `useEffect` | `onUnmounted`, `onWatcherCleanup` | function returned from `$effect` | `DestroyRef.onDestroy()` | | DOM reference | `useRef` | `useRef` | `useTemplateRef()` | `bind:this` | `viewChild()` | | Context | `createContext` + `useContext` | same | `provide` / `inject` | `setContext` / `getContext` | providers + `inject()` | | Async data | `use` + Suspense | `createResource` | async `setup` + `Suspense` | `{#await}` | `resource()` | | Read without tracking | — | `untrack` | — | `untrack` | `untracked()` | | List | `items.map` + `key` | `` | `v-for` + `:key` | `{#each items as i (i.id)}` | `@for (i of items; track i.id)` | | Condition | `cond && ` | `` | `v-if` | `{#if}` | `@if` | | Ship as a web component | wrapper library | every component is one | `defineCustomElement` | `customElement: true` | `@angular/elements` | ## Primitives Hooks are thin wrappers over `createSignal`, `createMemo` and `createEffect`. Use those outside components: shared state in a module, stores, utilities. Inside components prefer the hooks; [Reactivity](./reactivity) has the details. --- --- url: https://surgijs.github.io/surgijs/guide/jsx.md --- # JSX to DOM The compiler turns every JSX tree into a static HTML template plus a list of bindings. The runtime clones the template and walks to the dynamic nodes with `firstChild` / `nextSibling`. ```tsx const Row = (props: ReactiveProps<{ label: string; on: boolean }>) => (
{props.label}
); ``` compiles to ```js const _tmpl$1 = /*#__PURE__*/ _$template('
'); const Row = (props) => (() => { const _el$2 = _tmpl$1(), _el$3 = _el$2.firstChild; _$bind(_el$2, () => (props.on() ? 'row on' : 'row'), _$className); _$insert(_el$3, () => props.label()); return _el$2; })(); ``` ## Expressions * An expression without calls is static and runs once. * An expression with calls is dynamic. Reads that happen on every run become a `bind`: the runtime collects the signals during the first run and re-applies the value when one of them changes. * Reads inside conditional branches (`a ? b() : c()`, `a && b()`, `a?.b()`) become a render effect that tracks dependencies on every run. * A reader that calls a single getter is hoisted to module scope, deduplicated, and receives the getter as its argument. * A text signal that is the only child binds `setText` to a placeholder text node. ## Children | Position | Output | | --- | --- | | Only child, text signal | `" "` placeholder and `setText` | | Only child | `insert(el, value)`; the value owns all children | | Last child | `insert(el, value, null)`; appends after static children | | Between static children | `` marker and `insert(el, value, marker)` | `insert` accepts strings, numbers, nodes, fragments, arrays and functions. Arrays reconcile with a keyed DOM diff that reuses existing nodes. ## Attributes and properties ::: v-pre | JSX | DOM | | --- | --- | | `class`, `className` | `className`, removed on `null`/`false` | | `style={{ color, '--gap': x }}` | `style[key]`, dashed keys through `setProperty` | | `style="a: b"` | `style.cssText` | | `htmlFor` | `for` attribute | | `xlink:href`, `xml:lang`, `xmlns:x` | `setAttributeNS` with the right namespace | | `attr:name` | always an attribute | | `prop:name` | always a property | | `ref={el}` / `ref={(el) => ...}` | assigns `el.current` or calls the function | | `{...props}` | `spread`, which applies each key with the same rules | | other names | property when the element has it, attribute otherwise; dashed names always set attributes | ::: `true` renders an empty attribute, `null`, `undefined` and `false` remove it. ## Events `onClick`, `onInput`, `onKeyDown` and the other bubbling UI events use delegation: one listener per event type on `document` (and on closed shadow roots), handlers stored on the element. The dispatcher walks `composedPath()`, sets `currentTarget`, skips disabled elements and honors `stopPropagation()`. `on:name` adds a native listener for any event, including custom events and non-bubbling ones such as `mouseenter`. ## Components A capitalized tag calls the function with a props object. Every prop is a getter, `children` included, so the child decides when to read it. Built-in control components (`For`, `Show`, `Switch`, `Match`, `Portal`, `ErrorBoundary`, context providers) receive their props in the shape they document. --- --- url: https://surgijs.github.io/surgijs/guide/reactivity.md --- # Reactivity and hooks Components use hooks with React names. Code outside components (shared state, stores, utilities) uses the `create*` primitives the hooks are built on. One rule: > Inside a component, `use*`. Outside a component, `create*`. The difference from React: a component function runs **once**. State and props are getters, so the DOM updates where a value is read, not by running the component again. See [SurgiJS for React developers](./from-react). ## Hooks ```tsx import { useEffect, useMemo, useState, type ReactiveProps } from '@surgijs/core'; const Counter = (props: ReactiveProps<{ step?: number }>) => { const { step } = props; const [count, setCount] = useState(0); const double = useMemo(() => count() * 2, [count]); useEffect(() => { document.title = `Clicked ${count()} times`; }, [count]); useEffect(() => { const id = setInterval(() => setCount((c) => c + 1), 1000); return () => clearInterval(id); }, []); return ; }; ``` | Hook | Behavior | | --- | --- | | `useState(init)` | `[get, set]`; `set(v)` or `set(prev => next)` | | `useReducer(reducer, init)` | `[state, dispatch]`; `state` is a getter, `dispatch(action)` stores `reducer(state, action)` and skips the update when the result is the same value | | `useMemo(fn, deps?)` | cached getter; recomputes when a signal it reads changes, or only when a listed dependency does | | `useEffect(fn, deps?)` | runs after mount and when dependencies change; the returned function runs as cleanup before the next run and on unmount | | `useRef()` | `{ current: null }` for `ref={...}` | | `useId(prefix?)` | unique id such as `s-1` | | `useContext(context)` | getter for the nearest provider's value | | `createResource(fetcher)` | accessor with `loading()` and `error()`; tracks signals read by the fetcher and drops stale responses | ### Dependencies `deps` works as in React: * no `deps`: every signal read inside the hook is tracked, so the dependency list writes itself; * `[a, b]`: only `a` and `b` are tracked, and the hook body runs untracked; * `[]`: the effect runs once after mount, the memo computes once. In `.tsx` and `.jsx` files the compiler rewrites `[a, b]` into `() => [a(), b()]`, so the listed getters are read inside the effect. In plain `.ts` (custom hooks outside the compiler) pass that function, or an array of getters: `useEffect(fn, [count])` calls each function in the array. ### Reading values JSX and template literals in components read getters for you: `{count}` and `` `${title}` `` update when the signal changes. In other code call the getter, `count() * 2`, as TypeScript sees a getter there. ## Signals outside components ```ts import { createSignal, createMemo, createEffect, batch } from '@surgijs/core'; const [count, setCount] = createSignal(0); const double = createMemo(() => count() * 2); createEffect(() => console.log(double())); setCount(1); setCount((c) => c + 1); batch(() => { setCount(10); setCount(11); }); ``` * A signal is `{ v, o }`: the value and its observers. * Setters compare with `Object.is` and schedule a flush on a microtask. `batch` and the microtask both coalesce writes. * `flush()` runs queued work immediately: memos first, then render effects, then effects. * Memos are lazy: a read of a stale memo recomputes it. * Dependencies are positional. A computation that reads the same signals in the same order on each run keeps its subscription list untouched. ## Ownership Every computation and root has an owner `{ c, p, k, e }`: cleanups and children, parent, context, error handler. Disposing an owner runs its cleanups in reverse order and disposes its children. ```ts const dispose = createRoot((dispose) => { createEffect(() => console.log(count())); onCleanup(() => console.log('bye')); return dispose; }); ``` `untrack(fn)` reads without subscribing. `getOwner()` and `runWithOwner(owner, fn)` carry ownership into callbacks. ## Bindings `bind(node, read, apply, arg?)` from `@surgijs/core/internal` is the compact form the compiler emits. It runs `read(arg)` once while collecting sources, applies the value, and subscribes a small bound node only when the read touched signals. Updates call `apply(node, value)` when the value changes. A signal with one observer stores it directly, and an owner keeps its bindings in a linked list, so a bound row allocates no arrays. ## Context ```tsx const Theme = createContext('light'); const Label = () => { const theme = useContext(Theme); return label; }; ; ``` `useContext` returns a getter, so a provider value that changes updates the readers. --- --- url: https://surgijs.github.io/surgijs/guide/store.md --- # @surgijs/store Framework-agnostic store (React, Vue, Svelte, Angular, SurgiJS, or plain JS). One object, lazy remotes with **`deps`**, **`staleTime`**, retry, focus/reconnect refetch, **`status()`** for UI, GC with TTL. Not tied to the SurgiJS runtime. ```bash npm i @surgijs/store ``` ## Remote + deps `fetch` runs on first watch and when **`deps`** change — not on every store write. ```ts import { createStore, remote, fromResponse } from '@surgijs/store'; const store = createStore({ windowLocation: '/api/search', windowQueryParams: { q: '' } as Record, noise: 0, results: remote({ deps: (get) => [get.windowLocation, get.windowQueryParams], staleTime: 30_000, // fresh for 30s — skip remount/focus refetch retry: 2, refetchOnFocus: true, refetchOnReconnect: true, fetch: async (get, { signal, report }) => { const path = get('windowLocation') as string; const q = new URLSearchParams(get('windowQueryParams') as Record); const res = await fetch(`${path}?${q}`, { signal }); return fromResponse(res, { report }); }, }), }); store.set('noise', 1); // does not call fetch store.set('windowQueryParams', { q: 'ada' }); // does await store.prefetch('results'); // warm cache without a subscriber ``` ### Defaults `createStore(def, { retry, retryDelay, staleTime, gcTime, refetchOnFocus, refetchOnReconnect })` sets the defaults for every remote. An option on `remote()` wins; an omitted one falls back to the store option, then to the built-in default (`retry: 2`, `staleTime: 0`, `gcTime: 5 min`, refetch on focus and reconnect). ### Data belongs to deps When `deps` change, `data` resets to `placeholderData` (or `undefined`) and `status` is `pending` until the new fetch settles, so the field never shows data fetched for other deps. `status(key).dataDeps` is the deps the current data was fetched for. To keep the old data on screen while the new request runs, set `keepPreviousData: true` on the remote. `status(key).isPreviousData` is then `true` until the new data arrives. ### Debounce `debounce: 300` waits 300 ms after the last `deps` change before calling `fetch`. The first load is not delayed. ```ts results: remote({ deps: (get) => get.query, debounce: 300, fetch: (get, { signal }) => search(get.query, signal), }), ``` ### Typed reads `remote()` cannot know the shape of the store it ends up in, so `get` reads sync fields as `unknown`. `createRemote()` returns a `remote` that knows them, and `ctx.deps` gets the type `deps` returns (a tuple for an array literal): ```ts type State = { cityId: number }; const remote = createRemote(); const store = createStore({ cityId: 1, weather: remote({ deps: (get) => [get.cityId], // get.cityId: number fetch: async (get, { deps: [cityId], signal }) => loadWeather(cityId, signal), }), }); ``` ## Persist and URL ```ts import { persist, syncLocation } from '@surgijs/store'; persist(store, { name: 'app', keys: ['cityId', 'theme'] }); // restores now, saves on change; localStorage by default syncLocation(store, { path: 'path', query: 'query' }); // URL <-> sync fields; back/forward update the store ``` `syncLocation` binds `location.pathname` to a string field and `location.search` to a `Record` field; `history: 'replace'` rewrites the current entry instead of pushing. Route matching stays with your code: read `path` in `deps` or a selector. Both functions return an unsubscribe function. ## SurgiJS signals ```tsx import { fromStatus, fromStore } from '@surgijs/store/core'; function Weather() { const weather = fromStore(store, (s) => s.weather); const status = fromStatus(store, 'weather'); return

{status().isPending ? 'Loading' : weather()?.summary}

; } ``` Both return accessors. The subscription, which keeps remotes loaded, ends with the owner (the component). `@surgijs/core` is an optional peer dependency. ## Vue, Svelte, Angular Each adapter exposes the same two functions, `fromStore(store, selector)` and `fromStatus(store, key)`, returning that framework's native reactive value. The subscription, which keeps remotes loaded, ends with the framework's owner. Peer dependencies are optional and only needed by the adapter you import. ```ts // Vue 3: Readonly>, ends with the current effect scope (component setup, effectScope()) import { fromStore, fromStatus } from '@surgijs/store/vue'; const city = fromStore(store, (s) => s.city); // template:

{{ city?.name }}

``` ```svelte

{$city?.name}

``` ```ts // Angular 16+: Signal, ends with the injection context's DestroyRef import { fromStore, fromStatus } from '@surgijs/store/angular'; @Component({ template: `{{ city()?.name }}` }) class Weather { city = fromStore(store, (s) => s.city); status = fromStatus(store, 'weather'); } ``` Angular accepts `{ destroyRef }` as the third argument when there is no injection context, for example in a function that runs outside a component or service. Pass `{ equals }` to change the comparison. `equals` defaults to deep equality, as in `subscribe`. ## Complex stores (important) **`remote()` is top-level only.** Nested remotes and dotted status paths are **not** supported: ```ts // ❌ does not work — remote buried in a nested object is treated as sync data createStore({ products: { apple: { macbooks: remote({ deps: () => '/…', fetch: … }), }, }, }); // ❌ throws: "products.apple.macbooks" is not remote store.status('products.apple.macbooks'); ``` Shape complex apps as **nested sync UI state** + **flat named remotes** wired through `deps`: ```ts const store = createStore({ // UI / route — nesting is fine route: { catalog: 'apple', product: 'macbooks' } as { catalog: string; product: string; }, filters: { q: '', page: 1 }, selectedId: null as string | null, // server — one top-level remote per query catalogProducts: remote({ deps: (get) => { const r = get('route') as { catalog: string; product: string }; const f = get('filters') as { q: string; page: number }; return ['/api/catalog', r.catalog, r.product, f.q, f.page]; }, fetch: async (_get, { signal, report, deps }) => { const [, catalog, product, q, page] = deps as [string, string, string, string, number]; const res = await fetch(`/api/${catalog}/${product}?q=${q}&page=${page}`, { signal }); return fromResponse(res, { report }); }, }), productDetail: remote({ deps: (get) => get.selectedId, fetch: async (_get, { signal, report, deps }) => { if (deps == null) return null; const res = await fetch(`/api/products/${deps}`, { signal }); return fromResponse(res, { report }); }, }), }); store.set('route', { catalog: 'apple', product: 'macbooks' }); // refetch list store.set('selectedId', 'mbp-14'); // refetch detail store.status('catalogProducts'); // ✅ top-level name only store.status('productDetail'); ``` | In your head | In the store | | --- | --- | | `products.apple.macbooks` | `catalogProducts` + `route` | | `user.profile` | `userProfile` | | `cart.items` (server) | `cartItems` remote | | `cart.items` (local only) | sync nested `cart` | * **One store** — shared UI + related screens (same `deps` graph). * **Several stores** — unrelated features (`authStore` / `shopStore`), each with its own provider or `useStore(shopStore)`. * `status('…')` / `refetch` / `prefetch` / `setData` always take the **top-level remote key**, same as the field you read in `useStore`. ## Status for UI ```ts const st = store.status('results'); st.status; // 'pending' | 'success' | 'empty' | 'err' — one place for UI st.isPending; // first load, no settle yet st.isFetching; // request in flight (incl. background refetch) st.isStale; // past staleTime (or never loaded) st.isSuccess; // last settle ok — including empty `null` / `[]` st.isEmpty; // success with empty payload (not a 404) st.isError; // 404, network, or 200 + `{ ok: false }` / `{ error }` st.httpStatus; // 200 | 404 | … st.code; // app or HTTP code st.error; // RemoteError with `.status`, `.code`, `.body` st.age; // ms since last successful data st.source; // 'network' | 'cache' | 'optimistic' st.staleTime; st.gcTime; st.deps; // deps of the latest load st.dataDeps; // deps the current data was fetched for st.isPreviousData; // keepPreviousData: data still belongs to older deps ``` Watch status in React: ```tsx const list = useStore((s) => s.results); const st = useStore(() => store.status('results')); switch (st.status) { case 'pending': return ; case 'err': return st.httpStatus === 404 ? : ; case 'empty': return ; case 'success': return ; } ``` `fromResponse` distinguishes: | Response | Result | | --- | --- | | `200` / `204` empty body | `data: null`, `isSuccess`, `isEmpty` | | `200` + `[]` | `isSuccess`, `isEmpty` | | `404` | `isError`, `httpStatus: 404` | | `200` + `{ ok: false, code, message }` | `isError`, `httpStatus: 200`, `code` | ## Mutations (create / update / delete) `remote` is for **reads**. For uploads use **`mutation`** — own pending/error status, then `refetch` the list. ```ts import { createStore, mutation, remote, fromResponse } from '@surgijs/store'; type User = { id: string; name: string }; const store = createStore({ users: remote({ deps: () => '/api/users', fetch: async (_get, { signal, report, deps }) => { const res = await fetch(String(deps), { signal }); return fromResponse(res, { report }); }, }), }); const createUser = mutation(async (input: { name: string }, { getData, setData, signal, report, refetch }) => { const prev = getData('users'); setData('users', [...(prev ?? []), { id: 'tmp', ...input }]); // optimistic try { const res = await fetch('/api/users', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(input), signal, }); const user = await fromResponse(res, { report }); await refetch('users'); return user; } catch (e) { setData('users', prev); // rollback throw e; } }); await createUser(store, { name: 'Ada' }); const st = createUser.status(store); // st.status → 'idle' | 'pending' | 'success' | 'err' ``` ## Pagination example ```ts type Page = { items: { id: string; title: string }[]; total: number }; const store = createStore({ page: 1, pageSize: 20, query: '', list: remote({ deps: (get) => [get.page, get.pageSize, get.query], fetch: async (get, { signal, report }) => { const page = get('page') as number; const pageSize = get('pageSize') as number; const query = get('query') as string; const url = `/api/items?page=${page}&limit=${pageSize}&q=${encodeURIComponent(query)}`; const res = await fetch(url, { signal }); return fromResponse(res, { report }); }, gcTime: 5 * 60 * 1000, }), }); // controls store.set('page', 2); // refetch — deps changed store.set('query', 'ada'); // refetch from page identity in deps // UI store.subscribe(() => store.status('list'), (st) => { switch (st.status) { case 'pending': showSpinner(); break; case 'err': showError(st.httpStatus, st.code, st.error); break; case 'empty': showEmpty(); break; case 'success': showPage(st.data!, { refreshing: st.isFetching, age: st.age }); break; } }); store.write((get, set) => { const total = get((s) => s.list)?.total ?? 0; const size = get('pageSize') as number; const pages = Math.max(1, Math.ceil(total / size)); set('page', Math.min((get('page') as number) + 1, pages)); })(); ``` ## Redux DevTools When the Redux DevTools extension is installed, every `createStore` appears on its own: **SurgiJS**, then **SurgiJS 2**, and so on. `set`, `setData` and a settled fetch are actions. Jumping to a state writes those fields back and does not refetch. Nothing is imported or passed to `createStore` for this. ## React snapshot ```tsx import { StoreProvider, useStore } from '@surgijs/store/react'; function Profile() { const { userId, user: details } = useStore(); return
{details?.name}
; } ; ``` More: [package README](https://github.com/SurgiJS/surgijs/tree/main/packages/store), benches via `pnpm bench:store`. --- --- url: https://surgijs.github.io/surgijs/guide/components.md --- # Components ## defineComponent ```ts defineComponent(tag, render, schema?, options?) ``` * `tag`: custom element name. A second call with a defined tag returns the existing class and swaps in the new `render`: connected instances re-render with it. This is how hot module replacement updates a component in place. The schema and options keep their first values, and component state resets on a hot update. A module that calls `defineComponent` accepts its own updates, so modules importing its other exports keep the old values until the page reloads. * `render(props, host, emit)`: a function component. `props` holds a getter per schema key, `emit` dispatches the events declared in `options.events`. * `schema`: `{ name: String | Number | Boolean | Object | Array }`. Keys become observed attributes in kebab case (`maxItems` ↔ `max-items`) and properties on the element. * `options.shadow`: `true` (open shadow root, the default), a `ShadowRootInit`, or `false` for light DOM. * `options.form`: `true` makes the element form-associated. * `options.events`: the events the component emits, built with `defineEvent()`. Pass the props type as a generic when the schema alone would infer constructor types: ```ts defineComponent<{ value?: string }>('ui-field', Field, { value: String }, { form: true }); ``` ## Attributes and properties Attributes coerce by schema type: `Number` uses `+value`, `Boolean` treats presence as `true` and `"false"` as `false`, `Object` and `Array` parse JSON. Setting a `String`, `Number` or `Boolean` property reflects it back to the attribute. Properties set before the element upgrades are picked up on first connect. ## Shadow and light DOM With a shadow root the component renders into it and slots work as usual. A closed root registers its own event delegation, so handlers inside fire exactly once. Use a ref on an inner element when the host needs access to the closed tree. In light DOM the original children move into `props.children` before the first render, and the component places them wherever it inserts `{props.children}`. Disconnecting disposes the render root and clears it in the next microtask. An element moved within the document (removed and inserted again in the same task) keeps its rendered tree and state. Reconnecting after disposal renders again with the current property values. ## Styles `{ styles: css }` (a string or an array of strings) is parsed once per `defineComponent` into a `CSSStyleSheet` and adopted by every instance through `adoptedStyleSheets`, so a hundred elements share one copy of the CSS. Without constructable stylesheets, or when the CSS contains `@import` (which `replaceSync` drops), each root gets a `