@apia/util 0.3.6 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cleanDist.json CHANGED
@@ -1,3 +1,3 @@
1
1
  {
2
- "cleanDist": 0.7197744380857216
2
+ "cleanDist": 0.4517589736941394
3
3
  }
package/dist/index.d.ts CHANGED
@@ -380,9 +380,9 @@ declare class HashedEventEmitter<T extends TEventMap, HashData extends TEventMap
380
380
  #private;
381
381
  private hashMethod;
382
382
  constructor(hashMethod: (hash: HashData) => string);
383
- on<K extends TEventKey<T>>(hash: HashData, eventName: K, fn: TEventReceiver<T[K]>): () => void;
384
- off<K extends TEventKey<T>>(hash: HashData, eventName: K, fn: TEventReceiver<T[K]>): void;
385
- emit<K extends TEventKey<T>>(hash: HashData, eventName: K, params?: T[K]): void;
383
+ on<K extends TEventKey<T>>(hash: HashData | '*', eventName: K, fn: TEventReceiver<T[K]>): () => void;
384
+ off<K extends TEventKey<T>>(hash: HashData | '*', eventName: K, fn: TEventReceiver<T[K]>): void;
385
+ emit<K extends TEventKey<T>>(hash: HashData | '*', eventName: K, params?: T[K]): void;
386
386
  }
387
387
 
388
388
  /**
@@ -790,20 +790,20 @@ interface IFocusCheck {
790
790
  currentInstruction: number;
791
791
  }
792
792
  declare const focus: {
793
- "__#7@#root": HTMLElement;
794
- "__#7@#props": IFocusProps | undefined;
793
+ "__#8@#root": HTMLElement;
794
+ "__#8@#props": IFocusProps | undefined;
795
795
  afterNotificationFocus: IFocusQueryElement | undefined;
796
- "__#7@#actualFocusQuery": IFocusQueryElement[];
797
- "__#7@#currentInstruction": number;
798
- "__#7@#focusDelay": number;
799
- "__#7@#focusRetries": number;
800
- "__#7@#focusTimeout": number;
801
- "__#7@#isIntervalRunning": boolean;
802
- "__#7@#focusQuery": IFocusQueryElement[];
803
- "__#7@#checkInstruction"(focusCheck: IFocusCheck): boolean;
804
- "__#7@#doFocus"(HTMLElement: HTMLElement | TFocusRetriever, focusCheck: IFocusCheck, isLastTry: boolean, configuration?: IOnFocusConfiguration): Promise<false | HTMLElement | null>;
805
- "__#7@#resetInterval"(): void;
806
- "__#7@#runFocusInterval"(focusElement?: IFocusQueryElement, internalCall?: boolean): Promise<false | HTMLElement>;
796
+ "__#8@#actualFocusQuery": IFocusQueryElement[];
797
+ "__#8@#currentInstruction": number;
798
+ "__#8@#focusDelay": number;
799
+ "__#8@#focusRetries": number;
800
+ "__#8@#focusTimeout": number;
801
+ "__#8@#isIntervalRunning": boolean;
802
+ "__#8@#focusQuery": IFocusQueryElement[];
803
+ "__#8@#checkInstruction"(focusCheck: IFocusCheck): boolean;
804
+ "__#8@#doFocus"(HTMLElement: HTMLElement | TFocusRetriever, focusCheck: IFocusCheck, isLastTry: boolean, configuration?: IOnFocusConfiguration): Promise<false | HTMLElement | null>;
805
+ "__#8@#resetInterval"(): void;
806
+ "__#8@#runFocusInterval"(focusElement?: IFocusQueryElement, internalCall?: boolean): Promise<false | HTMLElement>;
807
807
  /**
808
808
  * Da la instrucción de colocar el foco en el elemento provisto como
809
809
  * parámetro una vez que todas las notificaciones se hayan cerrado. En caso
@@ -865,6 +865,71 @@ declare const globalFocus: {
865
865
  last(querySelector?: string, omit?: number): HTMLElement | TFocusRetriever | null;
866
866
  };
867
867
 
868
+ type THistoryCount = {
869
+ currentStep: number;
870
+ stepCount: number;
871
+ };
872
+ type THistoryStep<T> = {
873
+ content: T;
874
+ } & THistoryCount;
875
+ type THistoryStepChange<T> = THistoryCount & THistoryStep<T> & {
876
+ fromPush?: boolean;
877
+ hasPrevious: boolean;
878
+ hasNext: boolean;
879
+ };
880
+ type THistoryConfiguration = {
881
+ maxLength: number;
882
+ };
883
+ /**
884
+ * # Cómo usar el historial
885
+ *
886
+ * Es muy sencillo: se instancia con un callback que recibirá un método push
887
+ * cada vez que una ventana se cierre. En esos momentos, el usuario del History
888
+ * puede hacer push al estado.
889
+ *
890
+ * ## La mecánica
891
+ *
892
+ * - Instancio la clase y recibo el método push
893
+ * - Cuando se realizan cambios significativos, llamo al método openWindow
894
+ * - El método openWindow da una ventana de 350ms antes de llamar al callback
895
+ * - Si durante esa ventana se vuelve a llamar a openWindow, la ventana se
896
+ * resetea
897
+ * - Si al llamar al callback, se hace push al estado, ese estado es propagado
898
+ * mediante el hook y mediante el evento on('stepChange')
899
+ *
900
+ * ## Back y forward
901
+ *
902
+ * El back y forward son dos métodos del history que hacen un stepChange y
903
+ * emiten a través de on('stepChange') y el hook
904
+ */
905
+ declare class History<T> extends EventEmitter<{
906
+ stepChange: THistoryStepChange<T>;
907
+ }> {
908
+ private configuration;
909
+ private autocloseTimeout;
910
+ private currentStep;
911
+ private content;
912
+ private enabled;
913
+ private _isOpen;
914
+ private timeoutMs;
915
+ constructor(onCloseWindow: (push: (newState: T) => void) => unknown, configuration?: THistoryConfiguration);
916
+ private closeWindow;
917
+ private getEvent;
918
+ private onCloseWindow;
919
+ private push;
920
+ private shoutStepChange;
921
+ hooks: {
922
+ useCountChange: (onChange: (ev: THistoryStepChange<T>) => unknown) => void;
923
+ };
924
+ back: () => void;
925
+ disable: () => void;
926
+ enable: () => void;
927
+ forward: () => void;
928
+ get isOpen(): boolean;
929
+ openWindow: () => void;
930
+ updateConfig: (newConfiguration: Partial<THistoryConfiguration>) => void;
931
+ }
932
+
868
933
  /**
869
934
  * Permite reasignar múltiples referencias desde un mismo componente.
870
935
  *
@@ -911,6 +976,13 @@ declare function useStateRef<T>(initialState?: T): [
911
976
  */
912
977
  declare function useUpdateEffect(effect: EffectCallback, deps?: DependencyList): void;
913
978
 
979
+ declare function shallowEqual(a: unknown, b: unknown): boolean;
980
+ /**
981
+ * Compara con shallowEqual todos los ítems de dos arrays
982
+ */
983
+ declare function shallowCompareArrays(a: unknown[], b: unknown[]): boolean;
984
+ declare function useShallowMemo<T>(creator: () => T, deps: unknown[]): T;
985
+
914
986
  type TMethod<CR> = CR extends (state: any, ...args: infer Action) => any ? (id: TId, ...args: Action) => unknown : () => unknown;
915
987
  type TMethods<State extends TMap, K extends any[] = any[]> = Record<string, (setState: TStateManager<State>, ...args: K) => void>;
916
988
  type TMethodsMap<OriginalMethods extends TMethods<any>> = {
@@ -1463,6 +1535,202 @@ declare const screenLocker: {
1463
1535
  }[K_2] | undefined): void;
1464
1536
  };
1465
1537
 
1538
+ type StatefulStoreUnsuscriber = () => void;
1539
+ type StatefulStoreUpdater<Props> = (currentProps: Props) => Props;
1540
+ type StatefulStoreUpdateProps<Props> = StatefulStoreUpdater<Props> | Partial<Props>;
1541
+ /**
1542
+ * Clase facilitadora del uso de StatefulStore. Es un pequeño almacen que
1543
+ * permite actualizar sus propiedades y sabe cómo sincronizarse con el store de
1544
+ * modo que los cambios se propaguen según corresponda.
1545
+ */
1546
+ declare abstract class BasicStoredElement<Props extends Record<string, unknown>> {
1547
+ #private;
1548
+ abstract getId(): TId;
1549
+ onUpdate(cb: () => void): StatefulStoreUnsuscriber;
1550
+ props: Props;
1551
+ constructor(props: Props);
1552
+ protected shoutUpdates: () => void;
1553
+ update(newProps: StatefulStoreUpdateProps<Props>): void;
1554
+ useProps: () => Props;
1555
+ }
1556
+ /**
1557
+ * Son las acciones de adición del store.
1558
+ */
1559
+ type AddActions<T extends Record<string, BasicStoredElement<any>>> = {
1560
+ [P in keyof T as `add${Capitalize<string & P>}`]: (el: T[P]) => void;
1561
+ };
1562
+ /**
1563
+ * Acciones de vaciado del store.
1564
+ */
1565
+ type EmptyActions<T extends Record<string, BasicStoredElement<any>>> = {
1566
+ [P in keyof T as `empty${Capitalize<string & P>}`]: () => void;
1567
+ };
1568
+ /**
1569
+ * Acciones de removido del store.
1570
+ */
1571
+ type RemoveActions<T extends Record<string, BasicStoredElement<any>>> = {
1572
+ [P in keyof T as `remove${Capitalize<string & P>}`]: (id: TId) => void;
1573
+ };
1574
+ /**
1575
+ * Conjunto de acciones disponibles del store
1576
+ */
1577
+ type ActionMethods<T extends Record<string, BasicStoredElement<any>>> = {
1578
+ actions: AddActions<T> & EmptyActions<T> & RemoveActions<T>;
1579
+ };
1580
+ /**
1581
+ * Método que permite obtener el listado de elementos de un tipo.
1582
+ */
1583
+ type GetStateActions<T extends Record<string, BasicStoredElement<any>>> = {
1584
+ [P in keyof T as `get${Capitalize<string & P>}State`]: () => T[P][];
1585
+ };
1586
+ /**
1587
+ * Método que permite conocer las propiedades de un elemento.
1588
+ */
1589
+ type GetItemActions<T extends Record<string, BasicStoredElement<any>>> = {
1590
+ [P in keyof T as `get${Capitalize<string & P>}`]: (id: TId) => T[P];
1591
+ };
1592
+ type UpdateItemActions<T extends Record<string, BasicStoredElement<any>>> = {
1593
+ [P in keyof T as `update${Capitalize<string & P>}`]: (id: TId, newProps: StatefulStoreUpdateProps<T[P]['props']>) => void;
1594
+ };
1595
+ /**
1596
+ * Conjunto de métodos que permiten acceder al estado en un momento
1597
+ * determinado.
1598
+ */
1599
+ type StateMethods<T extends Record<string, BasicStoredElement<any>>> = {
1600
+ state: GetStateActions<T> & GetItemActions<T> & UpdateItemActions<T>;
1601
+ };
1602
+ /**
1603
+ * Es el hook encargado de permitir la escucha de listado de elementos y sus
1604
+ * propiedades.
1605
+ */
1606
+ type HookUseState<T extends Record<string, BasicStoredElement<any>>> = {
1607
+ [P in keyof T as `use${Capitalize<string & P>}`]: () => T[P][];
1608
+ };
1609
+ /**
1610
+ * Es el hook encargado de permitir la escucha de listado de elementos
1611
+ */
1612
+ type HookUseList<T extends Record<string, BasicStoredElement<any>>> = {
1613
+ [P in keyof T as `use${Capitalize<string & P>}List`]: () => T[P][];
1614
+ };
1615
+ /**
1616
+ * Es el hook encargado de permitir la escucha de propiedades de un elemento
1617
+ */
1618
+ type HookUseStateById<T extends Record<string, BasicStoredElement<any>>> = {
1619
+ [P in keyof T as `use${Capitalize<string & P>}ById`]: (id: TId) => T[P] | undefined;
1620
+ };
1621
+ /**
1622
+ * Conjunto de hooks del store.
1623
+ */
1624
+ type HooksMethods<T extends Record<string, BasicStoredElement<any>>> = {
1625
+ hooks: HookUseState<T> & HookUseStateById<T> & HookUseList<T>;
1626
+ };
1627
+ /**
1628
+ * Es la suscripción encargada de permitir la escucha de propiedades de un
1629
+ * elemento
1630
+ */
1631
+ type SuscribeById<T extends Record<string, BasicStoredElement<any>>> = {
1632
+ [P in keyof T as `change${Capitalize<string & P>}Element`]: (id: TId, cb: (props: T[P]) => unknown) => StatefulStoreUnsuscriber;
1633
+ };
1634
+ /**
1635
+ * Es la suscripción encaragada de permitir la escucha de cambios en la lista y
1636
+ * las propiedades de sus elementos.
1637
+ */
1638
+ type SuscribeToListChange<T extends Record<string, BasicStoredElement<any>>> = {
1639
+ [P in keyof T as `change${Capitalize<string & P>}`]: (cb: (props: T[P][]) => unknown) => StatefulStoreUnsuscriber;
1640
+ };
1641
+ /**
1642
+ * Es la suscripción encaragada de permitir la escucha de cambios en la
1643
+ * cantidad de elementos de la lista, pero no en las propiedades de los
1644
+ * elementos.
1645
+ */
1646
+ type SuscribeToListCountChange<T extends Record<string, BasicStoredElement<any>>> = {
1647
+ [P in keyof T as `change${Capitalize<string & P>}Ammount`]: (cb: (props: T[P][]) => unknown) => StatefulStoreUnsuscriber;
1648
+ };
1649
+ type SuscribeMethods<T extends Record<string, BasicStoredElement<any>>> = {
1650
+ on: SuscribeById<T> & SuscribeToListChange<T> & SuscribeToListCountChange<T>;
1651
+ };
1652
+ type InitialStates<T extends Record<string, BasicStoredElement<any>>> = {
1653
+ [P in keyof T as `${string & P}State`]: T[P][];
1654
+ };
1655
+ /**
1656
+ * Este store permite mantener `N` listados de objetos y por cada tipo de
1657
+ * objeto ofrece métodos para agregar, eliminar, obtener uno, obtener todos y
1658
+ * un hook para conocer el listado en tiempo real.
1659
+ *
1660
+ * **Métodos disponibles**
1661
+ *
1662
+ * - **action.addXXX**: Agrega un elemento de tipo XXX a la lista.
1663
+ * - **action.emptyXXX**: Vacía el listado de tipo XXX.
1664
+ * - **action.removeXXX**: Elimina un elemento de tipo XXX de la lista.
1665
+ * - **hooks.useXXX**: Permite conocer el listado de elementos y el cambio
1666
+ * en sus propiedades en tiempo real.
1667
+ * - **hooks.useXXXById**: Permite conocer los cambios a un elemento de la
1668
+ * lista en tiempo real.
1669
+ * - **hooks.useXXXList**: Permite conocer el listado de
1670
+ * elementos pero no reacciona a los cambios en las propiedades de los
1671
+ * elementos.
1672
+ * - **on.changeXXX**: Permite suscribirse al listado de elementos y
1673
+ * cambios en sus propiedades.
1674
+ * - **on.changeXXXAmmount**: Permite suscribirse
1675
+ * al listado de elementos, sin tomar en cuenta el cambio en las propiedades
1676
+ * de sus items.
1677
+ * - **on.changeXXXElement**: Permite suscribirse al cambio de
1678
+ * propiedades de un ítem particular
1679
+ * - **state.getXXX**: Permite obtener el
1680
+ * esatdo de un elemento particular de la lista.
1681
+ * - **state.getXXXState**:
1682
+ * Permite obtener el estado del listado completo de un tipo de elementos.
1683
+ * - **state.updateXXX**: Es un atajo para state.getXXX(id).update
1684
+ *
1685
+ * La funcionalidad de actualización se implementa en el objeto almacenado y es
1686
+ * comunicada en forma automática al store, de forma que el store no conoce
1687
+ * solamente cuántos y cuáles elementos hay almacenados, sino que además refleja
1688
+ * en tiempo real el estado de sus propiedades.
1689
+ *
1690
+ * @example
1691
+ *
1692
+ type TPeople = { name: string };
1693
+ class People extends BasicStoredElement<TPeople> {
1694
+ getId(): TId {
1695
+ return this.props.name;
1696
+ }
1697
+ }
1698
+
1699
+ class Schedule extends BasicStoredElement<{ day: string; task: string }>
1700
+ {
1701
+ getId() {
1702
+ return this.props.day;
1703
+ }
1704
+ }
1705
+
1706
+ const r = makeStatefulStore(
1707
+ {
1708
+ people: People.prototype,
1709
+ schedules: Schedule.prototype,
1710
+ },
1711
+ {
1712
+ peopleState: [new People({ name: 'A' }), new People({ name: 'B' })],
1713
+ },
1714
+ );
1715
+
1716
+ const p = r.hooks.usePeople();
1717
+ p[0].props.name;
1718
+
1719
+ r.hooks.usePeople();
1720
+
1721
+ r.actions.removePeople('asdf');
1722
+
1723
+ r.actions.addPeople(new People({ name: 'asdf' }));
1724
+ r.actions.removePeople('asdf');
1725
+
1726
+ r.state.getPeopleState();
1727
+ const pep = r.state.getPeople('asdf')
1728
+
1729
+ const ph = r.hooks.usePeople();
1730
+ const sch = r.hooks.useSchedules();
1731
+ */
1732
+ declare function makeStatefulStore<T extends Record<string, BasicStoredElement<any>>>(entries: T, initialStates?: Partial<InitialStates<T>>): ActionMethods<T> & HooksMethods<T> & StateMethods<T> & SuscribeMethods<T>;
1733
+
1466
1734
  declare const persistentStorage: {
1467
1735
  [key: string]: unknown;
1468
1736
  remove(prop: string): unknown;
@@ -1506,4 +1774,4 @@ declare function toBoolean(value: unknown): boolean;
1506
1774
 
1507
1775
  declare const parseXmlAsync: <T>(xml: string) => Promise<T>;
1508
1776
 
1509
- export { EventEmitter, HashedEventEmitter, IOnFocusConfiguration, IParameter, ISetBoundary, PropsSelectorUndefinedObject, PropsStore, TApiaAction, TApiaActions, TApiaCellDefinition, TApiaComplexCell, TApiaFieldPropsObj, TApiaFilter, TApiaFilterOption, TApiaFilterValue, TApiaFormButton, TApiaFormElement, TApiaFormElementOption, TApiaFunction, TApiaFunctionPageInfo, TApiaLoad, TApiaLoadForm, TApiaLoadText, TApiaMessage, TApiaMultiplePossibleValue, TApiaPossibleValue, TApiaRadioPossibleValue, TApiaRowDefinition, TApiaSelectPossibleValue, TApiaSystemMessageObj, TApiaTableFunction, TCallback, TDateFormat, TDispatchCallback, TFieldEvent, TFieldScriptEvent, TFieldScriptEvents, TFieldServerEvent, TFieldServerEvents, TFncParams, TFocusRetriever, TId, TKey, TMap$1 as TMap, TMessage, TModify, TNotificationMessage, TPropsComparator, TPropsConfiguration, TPropsSelector, TRequireOnlyOne, TShortcutBranch, TUpdateFieldConfiguration, Url, WithEventsValue, addBoundary, animate, apiaDateToStandarFormat, arrayOrArray, autoDisconnectMutationObserver, cantFocusSelector, customEvents, dateToApiaFormat, debugDispatcher, decrypt, disableChildrenFocus, downloadUrl, enableChildrenFocus, enableDebugDispatcher, encrypt, eventEmitterBaseFunction, findOffsetRelativeToScrollParent, findScrollContainer, focus, focusSelector, formatMessage, getDateFormat, getFocusSelector, getIndex, getLabel, getSpecificParent, getValueByPath, globalFocus, isChild, isDebugDispatcherEnabled, isPropsConfigurationObject, makeImperativeComponent, makeSingleImperativeComponent, noNaN, notificationsSelector, parseAsSize, parseXmlAsync, persistentStorage, propsStore, screenLocker, scrollParentIntoElement, setValueByPath, shortcutController, toBoolean, ucfirst, useCombinedRefs, useDebouncedCallback, useDebouncedState, useDomState, useImperativeComponentContext, useImperativeComponentEvents, useLatest, useLocalStorage, useMount, usePanAndZoom, usePrevious, usePropsSelector, useStateRef, useUnmount, useUpdateEffect };
1777
+ export { BasicStoredElement, EventEmitter, HashedEventEmitter, History, IOnFocusConfiguration, IParameter, ISetBoundary, PropsSelectorUndefinedObject, PropsStore, StatefulStoreUpdateProps, StatefulStoreUpdater, TApiaAction, TApiaActions, TApiaCellDefinition, TApiaComplexCell, TApiaFieldPropsObj, TApiaFilter, TApiaFilterOption, TApiaFilterValue, TApiaFormButton, TApiaFormElement, TApiaFormElementOption, TApiaFunction, TApiaFunctionPageInfo, TApiaLoad, TApiaLoadForm, TApiaLoadText, TApiaMessage, TApiaMultiplePossibleValue, TApiaPossibleValue, TApiaRadioPossibleValue, TApiaRowDefinition, TApiaSelectPossibleValue, TApiaSystemMessageObj, TApiaTableFunction, TCallback, TDateFormat, TDispatchCallback, TFieldEvent, TFieldScriptEvent, TFieldScriptEvents, TFieldServerEvent, TFieldServerEvents, TFncParams, TFocusRetriever, THistoryCount, THistoryStep, THistoryStepChange, TId, TKey, TMap$1 as TMap, TMessage, TModify, TNotificationMessage, TPropsComparator, TPropsConfiguration, TPropsSelector, TRequireOnlyOne, TShortcutBranch, TUpdateFieldConfiguration, Url, WithEventsValue, addBoundary, animate, apiaDateToStandarFormat, arrayOrArray, autoDisconnectMutationObserver, cantFocusSelector, customEvents, dateToApiaFormat, debugDispatcher, decrypt, disableChildrenFocus, downloadUrl, enableChildrenFocus, enableDebugDispatcher, encrypt, eventEmitterBaseFunction, findOffsetRelativeToScrollParent, findScrollContainer, focus, focusSelector, formatMessage, getDateFormat, getFocusSelector, getIndex, getLabel, getSpecificParent, getValueByPath, globalFocus, isChild, isDebugDispatcherEnabled, isPropsConfigurationObject, makeImperativeComponent, makeSingleImperativeComponent, makeStatefulStore, noNaN, notificationsSelector, parseAsSize, parseXmlAsync, persistentStorage, propsStore, screenLocker, scrollParentIntoElement, setValueByPath, shallowCompareArrays, shallowEqual, shortcutController, toBoolean, ucfirst, useCombinedRefs, useDebouncedCallback, useDebouncedState, useDomState, useImperativeComponentContext, useImperativeComponentEvents, useLatest, useLocalStorage, useMount, usePanAndZoom, usePrevious, usePropsSelector, useShallowMemo, useStateRef, useUnmount, useUpdateEffect };