Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * createSingle is a "sugar" wrapper around the SolidJS function createSignal:
- * const single = createSingle(value, options?);
- * single (and single.s!) return the original setter, augmented with .g, .s, .r, and .w.
- * single.g (and single.g.g!) return the original getter, augmented with .g and .r, for
- * passing read-only access to other places ("segmentation of access").
- * single.r, single.g.r, and single.g() return the read-only value by calling the getter.
- * single.w = value, single(value), and single.s(value) change the value by calling the setter.
- * single.w also works for read-modify-write (++, --, and op=) but you should use .r otherwise.
- * Notes: single is the *setter*, so single() is not a valid call signature.
- */
- import { createSignal, Accessor, Setter } from "solid-js";
- export type SignalOptions<T> = { equals?: false | ((prev: T, next: T) => boolean) };
- type ReaderPrototype<T> = {
- (): T;
- get g (): SingleReader<T>;
- get r (): T;
- };
- export type SingleReader<T> = Accessor<T> & ReaderPrototype<T>;
- type AccessorPrototype<T> = {
- (newv: T): T;
- get g (): SingleReader<T>;
- get r (): T;
- get s (): SingleAccessor<T>;
- get w (): T;
- set w (newv: T);
- };
- export type SingleAccessor<T> = Setter<T> & AccessorPrototype<T>;
- export type CreateSingle<T> = {
- (iv: T, options?: SignalOptions<T>): SingleAccessor<T>;
- accessorPrototype: AccessorPrototype<T>;
- readerPrototype: ReaderPrototype<T>;
- };
- export default function createSingle<T> (iv: T, options?: SignalOptions<T>): SingleAccessor<T> {
- const cs = createSingle as CreateSingle<T>;
- if (!cs.readerPrototype) cs.readerPrototype = Object.setPrototypeOf({
- get g () { return this; },
- get r () { return this(); }
- }, Function.prototype) as ReaderPrototype<T>;
- if (!cs.accessorPrototype) cs.accessorPrototype = Object.setPrototypeOf({
- get r () { return this.g(); },
- get w () { return this.g(); },
- set w (newv: T) { this(newv); }
- }, Function.prototype) as AccessorPrototype<T>;
- const [getter, setter] = createSignal(iv, options);
- // eslint-disable-next-line
- if (!('r' in getter)) Object.setPrototypeOf(getter, cs.readerPrototype);
- if (!('w' in setter)) Object.setPrototypeOf(setter, cs.accessorPrototype);
- if (!('g' in setter)) Object.defineProperty(setter, 'g', { value: getter, writable: false });
- return setter as SingleAccessor<T>;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement