proposal-signals / signal-polyfill

Implementation tracking the current state of https://github.com/tc39/proposal-signals
Apache License 2.0
185 stars 13 forks source link

Rewriting graph implementation, a signal is made live while getting its value #32

Open divdavem opened 1 week ago

divdavem commented 1 week ago

This PR contains a full rewrite of the graph implementation with a bit less code.

I am opening this PR as a possible solution for the following issue I opened: https://github.com/tc39/proposal-signals/issues/227 With this PR, reading a signal outside a reactive context makes it live for the duration of the get. So, calling get on a signal that is not live triggers the watched callback and then the unwatched callback of the signal itself (and all depending signals that were not live).

With this PR, it is possible to do this:

import { Signal } from 'signal-polyfill';

const updateFromStorage = (e: StorageEvent) => {
  if (e.storageArea === localStorage && e.key === "preferences") {
    preferences$.set(e.newValue);
  }
}
const preferences$ = new Signal.State(null as string | null, {
  [Signal.subtle.watched]: () => {
    preferences$.set(localStorage.getItem("preferences"));
    window.addEventListener('storage', updateFromStorage);
  },
  [Signal.subtle.unwatched]: () => {
    window.removeEventListener('storage', updateFromStorage);
  }
})

const parsedPreferences$ = new Signal.Computed(() => JSON.parse(preferences$.get() ?? "null"));

And parsedPreferences$() will always contain the up-to-date value.

This PR also includes the tests and corresponding behavior from #15 and #16. I have disabled 2 tests that I think are invalid.