Seitu

Custom primitives

Wrap any value that changes over time in the Seitu contract, and every binding works with it.

Built-in primitives use two public helpers: createSubscription and createReadableSubscription. You can use them too. A handle you build this way works with useSubscription in React, Vue, Solid and Svelte, with createComputed, and with debounce and throttle.

HelperGives you
createSubscription({ onFirstSubscribe })subscribe, notify and size. onFirstSubscribe runs when the first subscriber arrives. The function it returns runs after the last subscriber leaves.
createReadableSubscription(get, subscribe, notify, getServer?)A Readable & Subscribable handle. Subscribers receive get() each time you call notify().

Read-only: listen to the browser

Attach listeners in onFirstSubscribe, so a handle that nothing subscribes to costs nothing. Pass getServer to set the value used during SSR and hydration.

page-visibility.ts
import { ,  } from 'seitu'

export function () {
  const { ,  } = ({
    : () => {
      .('visibilitychange', )
      return () => .('visibilitychange', )
    },
  })

  const  = () =>
    typeof  === 'undefined' || . === 'visible'

  return (, , , () => true)
}

Writable: add set()

Spread the readable handle and add set. Accept a value or an updater, like the built-ins do, and call notify() after the value changes.

search-param.ts
import { ,  } from 'seitu'
import type { , ,  } from 'seitu'

export interface SearchParam
  extends <string | null>, <string | null>, <string | null> {}

export function (: string): SearchParam {
  const { ,  } = ({
    : () => {
      .('popstate', )
      return () => .('popstate', )
    },
  })

  const  = () =>
    typeof  === 'undefined'
      ? null
      : new (.).()

  return {
    ...(, , , () => null),
    : () => {
      const  = typeof  === 'function' ? (()) : 
      const  = new (.)
      if ( === null) ..()
      else ..(, )
      .(., '', )
      ()
    },
  }
}

Rules

  • Call notify() after the value changes, never before. Subscribers read get() when they are notified.
  • Keep get() cheap and pure. Bindings call it on every render. Cache the value if reading it is expensive.
  • Guard browser globals. get() can run on the server. Check typeof window or typeof document and pass getServer so the first client render matches the server HTML.
  • Attach listeners lazily. Put addEventListener, observers and timers in onFirstSubscribe, and return the cleanup.
Edit on GitHub

Last updated on

On this page