Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[atom & rstream] Asking for advice on good practices #468

Open
arnaudchenyensu opened this issue May 14, 2024 · 0 comments
Open

[atom & rstream] Asking for advice on good practices #468

arnaudchenyensu opened this issue May 14, 2024 · 0 comments

Comments

@arnaudchenyensu
Copy link

Hi @postspectacular

I was wondering if you had any good practices regarding the use of @thi.ng/atom and @thi.ng/rstream together.

As an example (taken from my previous issue – which is taken from 7guis), let's say that we want to be able to draw circles, move them around and undo/redo the different actions (using a single atom):

import { defAtom, defHistory, defTransacted, defCursor } from "@thi.ng/atom";
import { svg } from "@thi.ng/hiccup-svg";
import { $compile, $klist } from "@thi.ng/rdom";
import { fromView } from "@thi.ng/rstream";
import { repeatedly } from "@thi.ng/transducers";
import { random2, type Vec } from "@thi.ng/vectors";

const WIDTH = 600;
const NUM = 4;
const R = 20;

const db = defAtom({
  sel: -1,
  pts: [...repeatedly(() => random2([], R, WIDTH - R), NUM)]
})

// 1. There are a lot of variables just to manage one property of the atom (in this case `pts`).
// IMO, it seems a bit prone to error. For example, one might expect to update the atom using `pts`,
// when actually the update should be done only using `tx`.
// How would you suggest solving this issue? By having a class/wrappers around `pts`?
const pts = defCursor(db, ['pts'])
const ptsHistory = defHistory(pts)
const $pts = fromView(ptsHistory, { path: [] })
const tx = defTransacted(ptsHistory)

const sel = defCursor(db, ['sel'])
// 2. Similar questions as (1), having $sel as a stream means that someone else can possibly emit on this stream
// without knowing that the correct way to update `sel` is actually to reset the value with sel.reset()
// (which will then notifies the change on $sel).
// (For the sake of the argument, I left `sel` inside the atom but this issue doesn't appear 
// if we are using only a stream like `$sel = reactive(-1)`).
const $sel = fromView(sel, { path: [] })

const addPoint = (x: number, y: number) => {
  ptsHistory.swap((pts) => [...pts, [x, y]])
}

$compile([
  'div',
  {},
  svg(
    {
      width: WIDTH,
      height: WIDTH,
      viewBox: `0 0 ${WIDTH} ${WIDTH}`,
      onmousemove: (e: MouseEvent) => {
        sel.deref() !== -1 && tx.resetIn([sel.deref()], [e.clientX, e.clientY])
        // 3. I needed the pts values to be up to date for the drag & drop of a circle
        // and I thought about creating a stream on a transaction,
        // but I realized that a transaction notifies changes only on commit
        // (even though a transation.deref() will always have the latest value).
        // So I decided to emit the intermediate values directly on the $pts stream.
        // Is there a better way to do it?
        $pts.next(tx.deref())
      },
      onmouseup: () => {
        sel.reset(-1)
        tx.isTransaction && tx.commit()
      },
      ondblclick: (e: MouseEvent) => addPoint(e.clientX, e.clientY)
    },
    $klist(
      $pts.map((pts): [number, Vec][] => pts.map((p, i) => [i, p])),
      "g",
      {
        fill: 'white',
        stroke: 'black'
      },
      ([i, p]) => [
        "circle",
        {
          r: R,
          cx: p[0],
          cy: p[1],
          onmousedown: (e: MouseEvent) => {
            sel.reset(i)
            tx.begin()
            tx.resetIn([i], [e.clientX, e.clientY])
          },
          fill: $sel.map((sel) => sel === i ? 'grey' : 'white')
        }
      ],
      ([i, p]) => `${p}-${i}`
    ),
  ),
  [
    'div',
    {},
    ['button', { onclick: () => ptsHistory.undo() }, 'Undo'],
    ['button', { onclick: () => ptsHistory.redo() }, 'Redo'],
  ],
]).mount(document.getElementById("app")!);
  1. There are a lot of variables just to manage one property of the atom (in this case pts). IMO, it seems a bit prone to error. For example, one might expect to update the atom using pts, when actually the update should be done only using tx. How would you suggest solving this issue? By having a class/wrappers around pts?

  2. Similar questions as (1), having $sel as a stream means that someone else can possibly emit on this stream without knowing that the correct way to update sel is actually to reset the value with sel.reset() (which will then notifies the change on $sel). (For the sake of the argument, I left sel inside the atom but this issue doesn't appear if we are using only a stream like $sel = reactive(-1)).

  3. I needed the pts values to be up to date for the drag & drop of a circle and I thought about creating a stream on a transaction, but I realized that a transaction notifies changes only on commit (even though a transation.deref() will always have the latest value). So I decided to emit the intermediate values directly on the $pts stream. Is there a better way to do it?

I hope these questions make sense 😅 . I realized that when using both @thi.ng/atom and @thi.ng/rstream together different issues arise compare to using, for example, only @thi.ng/rstream which seems easier.

@arnaudchenyensu arnaudchenyensu changed the title [atom & rstream] Advice on good practices [atom & rstream] Asking for advice on good practices May 14, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant