1
0
mirror of https://github.com/jaandrle/deka-dom-el synced 2024-11-25 01:39:37 +01:00
deka-dom-el/observables.d.ts

67 lines
2.4 KiB
TypeScript
Raw Normal View History

2023-11-24 20:41:04 +01:00
export type Observable<V, A>= (set?: V)=> V & A;
2023-11-29 18:25:21 +01:00
type Action<V>= (this: { value: V, stopPropagation(): void }, ...a: any[])=> typeof observable._ | void;
//type SymbolObservable= Symbol;
type SymbolOnclear= symbol;
type Actions<V>= Record<string | SymbolOnclear, Action<V>>;
2024-01-31 14:37:57 +01:00
type OnListenerOptions= Pick<AddEventListenerOptions, "signal"> & { first_time?: boolean };
2023-11-24 20:41:04 +01:00
interface observable{
_: Symbol
/**
* Simple example:
* ```js
* const hello= S("Hello Observable");
* ```
* simple todo observable:
* ```js
* const todos= S([], {
* add(v){ this.value.push(S(v)); },
* remove(i){ this.value.splice(i, 1); },
* [S.symbols.onclear](){ S.clear(...this.value); },
* });
* ```
* computed observable:
* ```js
* const name= S("Jan");
* const surname= S("Andrle");
* const fullname= S(()=> name()+" "+surname());
* ```
* @param value Initial observable value. Or function computing value from other observables.
* @param actions Use to define actions on the observable. Such as add item to the array.
* There is also a reserved function `S.symbol.onclear` which is called when the observable is cleared
* by `S.clear`.
* */
<V, A extends Actions<V>>(value: V, actions?: A): Observable<V, A>;
/**
* Computations observable. This creates a observable which is computed from other observables.
* */
<V>(computation: ()=> V): Observable<V, {}>
action<S extends Observable<any, Actions<any>>, A extends (S extends Observable<any, infer A> ? A : never), N extends keyof A>(
observable: S,
name: N,
...params: A[N] extends (...args: infer P)=> any ? P : never
): void;
clear(...observables: Observable<any, any>[]): void;
2024-01-31 14:37:57 +01:00
on<T>(observable: Observable<T, any>, onchange: (a: T)=> void, options?: OnListenerOptions): void;
2023-11-24 20:41:04 +01:00
symbols: {
2023-11-29 18:25:21 +01:00
//observable: SymbolObservable;
2023-11-24 20:41:04 +01:00
onclear: SymbolOnclear;
}
/**
* Reactive element, which is rendered based on the given observable.
* ```js
* S.el(observable, value=> value ? el("b", "True") : el("i", "False"));
* S.el(listS, list=> list.map(li=> el("li", li)));
* ```
* */
2023-11-29 18:25:21 +01:00
el<S extends any>(observable: Observable<S, any>, el: (v: S)=> Element | Element[] | DocumentFragment): DocumentFragment;
2023-11-24 20:41:04 +01:00
observedAttributes(custom_element: HTMLElement): Record<string, Observable<any, any>>;
2023-11-24 20:41:04 +01:00
}
export const observable: observable;
export const O: observable;
declare global {
type ddeObservable<T, A= {}>= Observable<T, A>;
2023-11-29 18:25:21 +01:00
type ddeAction<V>= Action<V>
2023-11-24 20:41:04 +01:00
type ddeActions<V>= Actions<V>
}