Skip to content

loreanvictor/quel

Repository files navigation

npm package minimized gzipped size) types version GitHub Workflow Status

Reactive Expressions for JavaScript

npm i quel

quel is a tiny library for reactive programming in JavaScript. Use it to write applications that handle user interactions, events, timers, web sockets, etc. using only simple functions.

import { from, observe } from 'quel'


const div$ = document.querySelector('div')

// πŸ‘‡ encapsulate the value of the input
const input = from(document.querySelector('textarea'))

// πŸ‘‡ compute some other values based on that (changing) value
const chars = $ => $(input)?.length ?? 0
const words = $ => $(input)?.split(' ').length ?? 0

// πŸ‘‡ use the calculated value in a side-effect
observe($ => div$.textContent = `${$(chars)} chars, ${$(words)} words`)

quel focuses on simplicity and composability. Even complex scenarios (such as higher-order reactive sources, debouncing events, etc.) are implemented with plain JS functions combined with each other (instead of operators, hooks, or other custom abstractions).

//
// this code creates a timer whose rate changes
// based on the value of an input
//

import { from, observe, Timer } from 'quel'


const div$ = document.querySelector('div')
const input = from(document.querySelector('input'))
const rate = $ => parseInt($(input) ?? 100)

//
// πŸ‘‡ wait a little bit after the input value is changed (debounce),
//    then create a new timer with the new rate.
//
//    `timer` is a "higher-order" source of change, because
//    its rate also changes based on the value of the input.
//
const timer = async $ => {
  await sleep(200)
  return $(rate) && new Timer($(rate))
}

observe($ => {
  //
  // πŸ‘‡ `$(timer)` would yield the latest timer, 
  //     and `$($(timer))` would yield the latest
  //     value of that timer, which is what we want to display.
  //
  const elapsed = $($(timer)) ?? '-'
  div$.textContent = `elapsed: ${elapsed}`
})

Contents


Installation

On node:

npm i quel

On browser (or deno):

import { from, observe } from 'https://esm.sh/quel'

Usage

  1. Encapsulate (or create) sources of change,
const timer = new Timer(1000)
const input = from(document.querySelector('#my-input'))
  1. Process and combine these changing values using simple functions,
const chars = $ => $(input).length
  1. Observe these changing values and react to them (or iterate over them),
const obs = observe($ => console.log($(timer) + ' : ' + $(chars)))
  1. Clean up the sources, releasing resources (e.g. stop a timer, remove an event listener, cloe a socket, etc.).
obs.stop()
timer.stop()

Sources

πŸ“ Create a subject (whose value you can manually set at any time):

import { Subject } from 'quel'

const a = new Subject()
a.set(2)

πŸ•‘ Create a timer:

import { Timer } from 'quel'

const timer = new Timer(1000)

⌨️ Create an event source:

import { from } from 'quel'

const click = from(document.querySelector('button'))
const hover = from(document.querySelector('button'), 'hover')
const input = from(document.querySelector('input'))

πŸ‘€ Read latest value of a source:

src.get()

βœ‹ Stop a source:

src.stop()

πŸ’β€β™‚οΈ Wait for a source to be stopped:

await src.stops()

In runtimes supporting using keyword (see proposal), you can subscribe to a source:

using sub = src.subscribe(value => ...)

Currently TypeScript 5.2 or later supports using keyword.


Expressions

⛓️ Combine two sources using simple expression functions:

const sum = $ => $(a) + $(b)

πŸ” Filter values:

import { SKIP } from 'quel'

const odd = $ => $(a) % 2 === 0 ? SKIP : $(a)

πŸ”ƒ Expressions can be async:

const response = async $ => {
  // a debounce to avoid overwhelming the
  // server with requests.
  await sleep(200)
  
  if ($(query)) {
    try {
      const res = await fetch('https://pokeapi.co/api/v2/pokemon/' + $(query))
      const json = await res.json()

      return JSON.stringify(json, null, 2)
    } catch {
      return 'Could not find Pokemon'
    }
  }
}

🫳 Flatten higher-order sources:

const variableTimer = $ => new Timer($(input))
const message = $ => 'elapsed: ' + $($(timer))

βœ‹ Stop the expression:

import { STOP } from 'quel'

let count = 0
const take5 = $ => {
  if (count++ > 5) return STOP

  return $(src)
}

ℹ️ IMPORTANT

The $ function, passed to expressions, tracks and returns the latest value of a given source. Expressions are then re-run every time a tracked source has a new value. Make sure you track the same sources everytime the expression runs.

DO NOT create sources you want to track inside an expression:

// πŸ‘‡ this is WRONG ❌
const computed = $ => $(new Timer(1000)) * 2
// πŸ‘‡ this is CORRECT βœ…
const timer = new Timer(1000)
const computed = $ => $(timer) * 2

You CAN create new sources inside an expression and return them (without tracking) them, creating a higher-order source:

//
// this is OK βœ…
// `timer` is a source of changing timers, 
// who themselves are a source of changing numbers.
//
const timer = $ => new Timer($(rate))
//
// this is OK βœ…
// `$(timer)` returns the latest timer as long as a new timer
// is not created (in response to a change in `rate`), so this
// expression is re-evaluated only when it needs to.
//
const msg = $ => 'elapsed: ' + $($(timer))

Observation

πŸš€ Run side effects:

import { observe } from 'quel'

observe($ => console.log($(message)))

πŸ’‘ Observations are sources themselves:

const y = observe($ => $(x) * 2)
console.log(y.get())

βœ‹ Don't forget to stop observations:

const obs = observe($ => ...)
obs.stop()

In runtimes supporting using keyword (see proposal), you don't need to manually stop observations:

using obs = observe($ => ...)

Currently TypeScript 5.2 or later supports using keyword.


Async expressions might get aborted mid-execution. You can handle those events by passing a second argument to observe():

let ctrl = new AbortController()

const data = observe(async $ => {
  await sleep(200)
  
  // πŸ‘‡ pass abort controller signal to fetch to cancel mid-flight requests
  const res = await fetch('https://my.api/?q=' + $(input), {
    signal: ctrl.signal
  })

  return await res.json()
}, () => {
  ctrl.abort()
  ctrl = new AbortController()
})

Iteration

Iterate on values of a source using iterate():

import { iterate } from 'quel'

for await (const i of iterate(src)) {
  // do something with it
}

If the source emits values faster than you consume them, you are going to miss out on them:

const timer = new Timer(500)

// πŸ‘‡ loop body is slower than the source. values will be lost!
for await (const i of iterate(timer)) {
  await sleep(1000)
  console.log(i)
}

Cleanup

🧹 You need to manually clean up sources you create:

const timer = new Timer(1000)

// ... whatever ...

timer.stop()

✨ Observations cleanup automatically when all their tracked sources stop. YOU DONT NEED TO CLEANUP OBSERVATIONS.

If you want to stop an observation earlier, call stop() on it:

const obs = observe($ => $(src))

// ... whatever ...

obs.stop()

In runtimes supporting using keyword (see proposal), you can safely create sources without manually cleaning them up:

using timer = new Timer(1000)

Currently TypeScript 5.2 or later supports using keyword.


Typing

TypeScript wouldn't be able to infer proper types for expressions. To resolve this issue, use Track type:

import { Track } from 'quel'

const expr = ($: Track) => $(a) * 2

πŸ‘‰ Check this for more useful types.


Custom Sources

Create your own sources using Source class:

const src = new Source(async emit => {
  await sleep(1000)
  emit('Hellow World!')
})

If cleanup is needed, and your producer is sync, return a cleanup function:

const myTimer = new Source(emit => {
  let i = 0
  const interval = setInterval(() => emit(++i), 1000)
  
  // πŸ‘‡ clear the interval when the source is stopped
  return () => clearInterval(interval)
})

If your producer is async, register the cleanup using finalize callback:

// πŸ‘‡ with async producers, use a callback to specify cleanup code
const asyncTimer = new Source(async (emit, finalize) => {
  let i = 0
  let stopped = false
  
  finalize(() => stopped = true)
  
  while (!stopped) {
    emit(++i)
    await sleep(1000)
  }
})

You can also extend the Source class:

class MyTimer extends Source {
  constructor(rate = 200) {
    super()
    this.rate = rate
    this.count = 0
  }
  
  toggle() {
    if (this.interval) {
      this.interval = clearInterval(this.interval)
    } else {
      this.interval = setInterval(
        // call this.emit() to emit values
        () => this.emit(++this.count),
        this.rate
      )
    }
  }
  
  // override stop() to clean up
  stop() {
    clearInterval(this.interval)
    super.stop()
  }
}

Features

🧩 quel has a minimal API surface (the whole package is ~1.3KB), and relies on composability instead of providng tons of operators / helper methods:

// combine two sources:
$ => $(a) + $(b)
// debounce:
async $ => {
  await sleep(1000)
  return $(src)
}
// flatten (e.g. switchMap):
$ => $($(src))
// filter a source
$ => $(src) % 2 === 0 ? $(src) : SKIP
// take until other source emits a value
$ => !$(notifier) ? $(src) : STOP
// batch emissions
async $ => (await Promise.resolve(), $(src))
// batch with animation frames
async $ => {
  await Promise(resolve => requestAnimationFrame(resolve))
  return $(src)
}
// merge sources
new Source(emit => {
  const obs = sources.map(src => observe($ => emit($(src))))
  return () => obs.forEach(ob => ob.stop())
})
// throttle
let timeout = null
  
$ => {
  const value = $(src)
  if (timeout === null) {
    timeout = setTimeout(() => timeout = null, 1000)
    return value
  } else {
    return SKIP
  }
}

πŸ›‚ quel is imperative (unlike most other general-purpose reactive programming libraries such as RxJS, which are functional), resulting in code that is easier to read, write and debug:

import { interval, map, filter } from 'rxjs'

const a = interval(1000)
const b = interval(500)

combineLatest(a, b).pipe(
  map(([x, y]) => x + y),
  filter(x => x % 2 === 0),
).subscribe(console.log)
import { Timer, observe } from 'quel'

const a = new Timer(1000)
const b = new Timer(500)

observe($ => {
  const sum = $(a) + $(b)
  if (sum % 2 === 0) {
    console.log(sum)
  }
})

⚑ quel is as fast as RxJS. Note that in most cases performance is not the primary concern when programming reactive applications (since you are handling async events). If performance is critical for your use case, I'd recommend using likes of xstream or streamlets, as the imperative style of quel does tax a performance penalty inevitably compared to the fastest possible implementation.


🧠 quel is more memory-intensive than RxJS. Similar to the unavoidable performance tax, tracking sources of an expression will use more memory compared to explicitly tracking and specifying them.


β˜• quel only supports hot listenables. Certain use cases would benefit (for example, in terms of performance) from using cold listenables, or from having hybrid pull-push primitives. However, most common event sources (user events, timers, Web Sockets, etc.) are hot listenables, and quel does indeed use the limited scope for simplification and optimization of its code.


Related Work


Contribution

You need node, NPM to start and git to start.

# clone the code
git clone [email protected]:loreanvictor/quel.git
# install stuff
npm i

Make sure all checks are successful on your PRs. This includes all tests passing, high code coverage, correct typings and abiding all the linting rules. The code is typed with TypeScript, Jest is used for testing and coverage reports, ESLint and TypeScript ESLint are used for linting. Subsequently, IDE integrations for TypeScript and ESLint would make your life much easier (for example, VSCode supports TypeScript out of the box and has this nice ESLint plugin), but you could also use the following commands:

# run tests
npm test
# check code coverage
npm run coverage
# run linter
npm run lint
# run type checker
npm run typecheck

You can also use the following commands to run performance benchmarks:

# run all benchmarks
npm run bench
# run performance benchmarks
npm run bench:perf
# run memory benchmarks
npm run bench:mem