@apia/util 0.0.7 → 0.1.0

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.
@@ -0,0 +1,1643 @@
1
+ import * as React$1 from 'react';
2
+ import React__default, { EffectCallback, Dispatch, SetStateAction, MutableRefObject, DependencyList, FC, HTMLAttributes } from 'react';
3
+ import { AxiosResponse } from 'axios';
4
+ import * as theme_ui_jsx_runtime from 'theme-ui/jsx-runtime';
5
+ import { TIconName, TIconType } from '@apia/icons';
6
+ import { TId as TId$1 } from '@apia/util';
7
+
8
+ declare function arrayOrArray<T>(o: T | T[] | undefined): T[];
9
+
10
+ /**
11
+ * This function gets an array of elements of any kind and an array of
12
+ * functions which will be called to test conditions and will return element
13
+ * whose index equals the matching condition's index
14
+ *
15
+ * @param arr An array of elements of any kind
16
+ * @param conditions An array of conditions, which will be tested in order to determine which index of the array will be returned
17
+ * @param defaultIndex The return value in case that no condition matches
18
+ * @returns An element of the array if any of the conditions matches or the defaultIndex otherwise
19
+ */
20
+ declare function getIndex<T = unknown>(arr: T[], conditions: (boolean | (() => boolean))[], defaultIndex?: number): T;
21
+
22
+ declare const decrypt: (salt: string, iv: string, passPhrase: string, cipherText: string, keySize: number, iterationCount: number) => string;
23
+
24
+ declare const encrypt: (salt: string, iv: string, passPhrase: string, plainText: string, keySize: number, iterationCount: number) => string;
25
+
26
+ declare function apiaDateToStandarFormat(date: string): string;
27
+
28
+ declare function dateToApiaFormat(date: string | Date): string;
29
+
30
+ type TDateFormat = 'DD/MM/YYYY' | 'MM/DD/YYYY' | 'YYYY/MM/DD';
31
+
32
+ declare global {
33
+ interface Window {
34
+ DATE_FORMAT: string;
35
+ }
36
+ }
37
+ declare const getDateFormat: () => TDateFormat;
38
+
39
+ /**
40
+ * Indica si el debugDispatcher fue activado, lo que en muchos casos indica que
41
+ * estamos en ambiente de desarrollo
42
+ */
43
+ declare function isDebugDispatcherEnabled(): boolean;
44
+ /**
45
+ * El debug dispatcher solamente debería activarse en modo desarrollo. Este
46
+ * control solamente puede hacerse desde la aplicación principal, por ello, para
47
+ * activar el debugDispatcher se exporta este método que debe llamarse cuando
48
+ * sea correcto.
49
+ */
50
+ declare function enableDebugDispatcher(): void;
51
+ type TWindowDDispatch = (action: string, ...parameters: unknown[]) => void;
52
+ type TDispatchCallback = (parameters: unknown[]) => unknown;
53
+ interface IStoredCallback {
54
+ (parameters: unknown[]): unknown;
55
+ help: () => void;
56
+ }
57
+ declare const debugDispatcher: {
58
+ callbacks: Record<string, IStoredCallback[]>;
59
+ actions: Record<string, () => void>;
60
+ on(action: string, cb: TDispatchCallback, help: string | React__default.ReactNode, onlyDevelop?: boolean): () => void;
61
+ off(action: string, cb: TDispatchCallback): void;
62
+ emit: TWindowDDispatch;
63
+ };
64
+ declare global {
65
+ interface Window {
66
+ adt: typeof debugDispatcher;
67
+ dd: typeof debugDispatcher & Record<string, () => unknown>;
68
+ }
69
+ }
70
+
71
+ type TCallback = (ev: KeyboardEvent) => unknown;
72
+ type TKey = {
73
+ key: string;
74
+ altKey?: boolean;
75
+ ctrlKey?: boolean;
76
+ shiftKey?: boolean;
77
+ };
78
+ type TShortcutBranch = {
79
+ key: TKey;
80
+ children: TShortcutBranch[];
81
+ callbacks: TCallback[];
82
+ fireEvenFromInputs?: boolean;
83
+ };
84
+ declare const shortcutController: {
85
+ history: TKey[];
86
+ candidates: TShortcutBranch[];
87
+ shortcuts: TShortcutBranch;
88
+ shortcutsStrings: string[];
89
+ categories: {
90
+ dev: string[];
91
+ };
92
+ parseKeyToString(key: string | TKey): string;
93
+ parseKey(keyString: string): TKey;
94
+ /**
95
+ * Para setear un shorcut se puede pasar un string representativo con la
96
+ * forma:
97
+ *
98
+ * **alt**?&**ctrl**?&**shift**?&**(\w)**
99
+ *
100
+ * Donde: alt? ctrl? shift? implica que cualquiera de esas palabras pueden o
101
+ * no aparecer y (\w) es una letra, símbolo o número.
102
+ *
103
+ * Puede aparecer cualquier tecla de control o no, pero el símbolo o letra
104
+ * debe aparecer.
105
+ *
106
+ * @param category
107
+ * Agrega un prefijo de teclas que se deben presionar antes del shortcut para
108
+ * que funcione, de forma que por ejemplo, todos los shortcuts de la categoría
109
+ * dev serán ejecutados solamente si antes se presionó shift&D
110
+ *
111
+ * @example
112
+ *
113
+ shortcutController.on(['shift&A', 'b', 'ctrl&c', 'alt&d'], (ev) => {
114
+ ev.preventDefault();
115
+ console.log('Abctrl+cd'),
116
+ }); // Este shortcut se ejecuta en desarrollo y producción
117
+
118
+ shortcutController.on('unshortcut'.split(''), (ev) => {
119
+ ev.preventDefault();
120
+ console.log('Abctrl+cd'),
121
+ }, 'dev'); // Este shortcut solo se ejecuta en desarrollo
122
+ */
123
+ on(keys: (string | TKey)[], callback: TCallback, category?: keyof typeof this$1.categories, fireEvenFromInputs?: boolean): void;
124
+ };
125
+
126
+ interface IAutoDisconnectMutationObserverConf {
127
+ /** Por defecto es true */
128
+ runCallbackOnInit?: boolean;
129
+ /** Por defecto es 100 (ms) */
130
+ timeout?: number;
131
+ }
132
+ /**
133
+ * Crea un observer que va a desconectarse automáticamente luego de que pase
134
+ * una determinada cantidad de tiempo sin actividad en el elemento.
135
+ *
136
+ * Se usa especialmente para esperar que un componente termine de renderizar y
137
+ * aplicar cálculos a nivel de layout sobre él.
138
+ */
139
+ declare function autoDisconnectMutationObserver(element: HTMLElement, callback: () => unknown, conf?: IAutoDisconnectMutationObserverConf): () => void;
140
+
141
+ /**
142
+ * This function gets an URL and a file name and performs a file download.
143
+ *
144
+ * @param url The url to fetch
145
+ * @param getNameFromResponse The name will be given by the 'content-disposition' prop in the headers
146
+ */
147
+ declare function downloadUrl(url: string, getNameFromResponse?: (blob: AxiosResponse) => string): Promise<void>;
148
+ /**
149
+ * This function gets an URL and a file name and performs a file download.
150
+ *
151
+ * @param url The url to fetch
152
+ * @param fileName The name the file will have as default in the save dialog
153
+ */
154
+ declare function downloadUrl(url: string, fileName: string): Promise<void>;
155
+
156
+ /**
157
+ * Esta función calcula el offset que existe entre un elemento y su padre más inmediato que tenga scroll visible
158
+ */
159
+ declare function findOffsetRelativeToScrollParent(element: HTMLElement, which?: 'Left' | 'Top'): number;
160
+
161
+ /**
162
+ * Encuentra el primer elemento padre del elemento provisto que tenga scroll
163
+ * activo.
164
+ */
165
+ declare function findScrollContainer(el: HTMLElement): HTMLElement | null;
166
+
167
+ /**
168
+ * Busca el padre con scroll visible y establece su scrollTop de acuerdo al offset del elemento pasado como argumento, de modo que éste aparezca visible dentro del padre mencionado.
169
+ *
170
+ * @param fixedOffsetTop Establece un mínimo de distancia que debe mantener con el borde superior del contenedor con scroll. Se usa para compensar en las situaciones donde existen cabezales fijos.
171
+ */
172
+ declare function scrollParentIntoElement(element: HTMLElement, fixedOffsetTop?: number, tries?: number, timeout?: number, scrollId?: string | undefined): void;
173
+
174
+ declare function usePanAndZoom<ContainerType extends HTMLElement = HTMLElement, ChildType extends HTMLElement | SVGElement = HTMLElement>(effectiveMargin?: {
175
+ left: number;
176
+ top: number;
177
+ right: number;
178
+ bottom: number;
179
+ }, blockZoom?: boolean): {
180
+ boxRef: React__default.RefObject<ContainerType>;
181
+ elementRef: React__default.RefObject<ChildType>;
182
+ };
183
+
184
+ type TEventMap = Record<string, any>;
185
+ type TEventKey<T extends TEventMap> = string & keyof T;
186
+ type TEventReceiver<T> = (params: T) => unknown;
187
+ type TFun = () => unknown;
188
+ interface IEmitter<T extends TEventMap> {
189
+ on<K extends TEventKey<T>>(eventName: K, fn: TEventReceiver<T[K]>): TFun;
190
+ off<K extends TEventKey<T>>(eventName: K, fn: TEventReceiver<T[K]>): unknown;
191
+ emit<K extends TEventKey<T>>(eventName: K, params?: T[K]): unknown;
192
+ }
193
+ /**
194
+ * EventEmitter muy sencillo.
195
+ *
196
+ * El siguiente ejemplo es un fragmento de una clase
197
+ * perteneciente al grupo de wai-aria helpers. Ver que el método #shout nada
198
+ * tiene que ver con la clase EventEmitter, sino que es un método interno de la
199
+ * clase WaiTypeAhead.
200
+ *
201
+ * Lo que realmente importa en el ejemplo es el tipado (Lo que va luego de
202
+ * extends EventEmitter) y el this.emit en la creación del emitter; por otra
203
+ * parte es importante el (instance).on(...) que se muestra al final del
204
+ * ejemplo, que permite realizar suscripciones al EventEmitter creado.
205
+ *
206
+ * Además, es notable que cuando se realiza una suscripción mediante
207
+ * (instance).on, este método devuelve un método que al ser llamado rompe la
208
+ * suscripción; esto nos da la firma del método on como:
209
+ *
210
+ * on(eventName: string, callback: (ev: eventType) => unknown): Unsuscriptor;
211
+ *
212
+ * @example
213
+ *
214
+ * // Event emitter creation
215
+ *
216
+ * class WaiTypeAhead extends EventEmitter<{
217
+ multipleKeys: string;
218
+ singleKey: string;
219
+ }> {
220
+ // ...
221
+ #shout({ clear } = { clear: true }) {
222
+ if (this.typing.length === 1) {
223
+ this.emit('singleKey', this.typing);
224
+ } else if (this.typing.length > 1) {
225
+ this.emit('multipleKeys', this.typing);
226
+ }
227
+ // ...
228
+ }
229
+ // ...
230
+ }
231
+
232
+ // Usage
233
+
234
+ const wtype = new WaiTypeAhead();
235
+ wtype.on('multipleKeys', (typing) => {
236
+ write(`Multiple: ${typing}`);
237
+ });
238
+ */
239
+ declare class EventEmitter<T extends TEventMap> implements IEmitter<T> {
240
+ #private;
241
+ on<K extends TEventKey<T>>(eventName: K, fn: TEventReceiver<T[K]>): () => void;
242
+ off<K extends TEventKey<T>>(eventName: K, fn: TEventReceiver<T[K]>): void;
243
+ emit<K extends TEventKey<T>>(eventName: K, params?: T[K]): void;
244
+ }
245
+
246
+ type TLiveEvent = {
247
+ message: string;
248
+ type: 'polite' | 'assertive' | 'reset';
249
+ };
250
+ /**
251
+ * Este método se utiliza para emitir mensajes
252
+ * a los usuarios con discapacidades. **IMPORTANTE:
253
+ * El empleo de esta herramienta debe ser analizado
254
+ * a conciencia**.
255
+ *
256
+ * **La forma que considero correcta de analizar el
257
+ * problema es:**
258
+ *
259
+ * Si yo fuera un usuario ciego o discapacitado, qué
260
+ * tipo de mensaje me gustaría recibir para entender
261
+ * el uso de las herramientas en el contexto actual.
262
+ *
263
+ * Si se encuentra que esta forma de analizar el
264
+ * problema tiene fallos o carencias, por favor
265
+ * iniciar la discusión correspondiente ya que la idea
266
+ * es ir mejorando esta herramienta.
267
+ *
268
+ * **El uso es muy sencillo:**
269
+ *
270
+ * Al llamar al método
271
+ * AriaLiveEmitter.emit({ live: 'polite' | 'assertive',
272
+ * message: 'un mensaje' }), se actualiza un div para
273
+ * que contenta estas características, lo que termina
274
+ * leyendo dicho mensaje al usuario.
275
+ */
276
+ declare const AriaLiveEmitter: {
277
+ "__#1@#emitter": IEmitter<{
278
+ live: TLiveEvent;
279
+ }>;
280
+ on<K extends "live">(eventName: K, fn: TEventReceiver<{
281
+ live: TLiveEvent;
282
+ }[K]>): () => void;
283
+ off<K_1 extends "live">(eventName: K_1, fn: TEventReceiver<{
284
+ live: TLiveEvent;
285
+ }[K_1]>): void;
286
+ emit<K_2 extends "live">(eventName: K_2, params?: {
287
+ live: TLiveEvent;
288
+ }[K_2] | undefined): void;
289
+ };
290
+ declare const LiveRegion: () => theme_ui_jsx_runtime.JSX.Element;
291
+
292
+ /**
293
+ * Existen algunos eventos que se disparan en la
294
+ * aplicación con la finalidad de desencadenar
295
+ * un comportamiento específico. Por ello se declaran
296
+ * las siguientes constantes.
297
+ */
298
+ declare const customEvents: {
299
+ /**
300
+ * Indica que un elemento necesita recibir el foco,
301
+ * de esta forma, elementos que no se están mostrando
302
+ * en pantalla (por display:none por ejemplo), pueden
303
+ * indicar a sus ancestros que deben expandirse.
304
+ */
305
+ focus: string;
306
+ /**
307
+ * Indica que debe cambiarse el título del modal
308
+ */
309
+ iframeModalChangeTitle: string;
310
+ /**
311
+ * Indica que un iframe modal debe cerrarse
312
+ */
313
+ iframeModalClose: string;
314
+ /**
315
+ * Indica que un iframe modal debe cerrarse
316
+ */
317
+ iframeModalNotify: string;
318
+ /**
319
+ * Indica que un modal debe cerrarse
320
+ */
321
+ modalClose: string;
322
+ /**
323
+ * Indica que el panel contenedor debe cerrarse porque
324
+ * está vacío
325
+ */
326
+ hidePanel: string;
327
+ showPanel: string;
328
+ };
329
+
330
+ /**
331
+ * Este selector pretende abarcar todos modificadores que en caso de estar
332
+ * presentes hacen que un elemento no sea focusable
333
+ */
334
+ declare const cantFocusSelector: string;
335
+ /**
336
+ * Este selector pretende abarcar todos los elementos que sean focusables
337
+ */
338
+ declare const focusSelector: string;
339
+ /**
340
+ * Genera un selector que permitirá seleccionar
341
+ * todos los elementos candidatos a recibir foco,
342
+ * que no cumplan con la condición not pasada
343
+ * como parámetro.
344
+ *
345
+ * @param not Un selector not css, indicando cuáles
346
+ * condiciones deben evitar el foco en un elemento.
347
+ *
348
+ * @returns Una cadena que representa un selector
349
+ * css.
350
+ */
351
+ declare function getFocusSelector(not?: string): string;
352
+
353
+ /**
354
+ * Searches for a specific parent of a element,
355
+ * using a callback function as the source of
356
+ * truth in order to determine which is the correct
357
+ * parent.
358
+ *
359
+ * @param element The element where the process
360
+ * starts.
361
+ *
362
+ * @param checkParent A callback that will be
363
+ * called for each of the ancestors of the element
364
+ * until the desired parent is found.
365
+ * This function should return **true when found**
366
+ * the desired parend was found, **null to cancel**
367
+ * the search or **false to continue searching**.
368
+ *
369
+ * @returns The specific parent or null in case
370
+ * the root parent element is raised.
371
+ */
372
+ declare function getSpecificParent(element: HTMLElement | null, checkParent: (parent: HTMLElement) => boolean | null): HTMLElement | null;
373
+
374
+ /**
375
+ * Permite iterar desde un elemento hacia arriba en el
376
+ * DOM, utilizando una función de comparación para
377
+ * determinar si el elemento actual es el que estamos
378
+ * buscando.
379
+ *
380
+ * Si la función checkParent devuelve true, isChild
381
+ * devuelve true.
382
+ */
383
+ declare function isChild(element: HTMLElement | null, checkParent: (parent: HTMLElement) => boolean | null): boolean;
384
+
385
+ interface IParameter {
386
+ name: string;
387
+ value: unknown;
388
+ allowMultiple?: boolean;
389
+ }
390
+ declare class Url {
391
+ #private;
392
+ defaultAllowMultiple: boolean;
393
+ base: string;
394
+ constructor(baseUrl: string, defaultAllowMultiple?: boolean);
395
+ addParameter(name: string, value: unknown, allowMultiple?: boolean): void;
396
+ addParameters(parameters: IParameter[]): void;
397
+ getParameter(name: string): string | string[];
398
+ toString(): string;
399
+ }
400
+
401
+ /**
402
+ * Deshabilita la posibilidad de hacer foco en
403
+ * todos los descendientes de parent. Es
404
+ * especialmente útli cuando se ocultan elementos
405
+ * del DOM sin quitarlos, cuando por accesibilidad
406
+ * es importante que el foco no alcance a dichos
407
+ * métodos.
408
+ */
409
+ declare function disableChildrenFocus(parent: HTMLElement): void;
410
+ /**
411
+ * Restaura el foco de los hijos de parent a los
412
+ * que previamente se les había quitado el foco
413
+ * con disableChildrenFocus.
414
+ */
415
+ declare function enableChildrenFocus(parent: HTMLElement): void;
416
+
417
+ /**
418
+ * Esta clase ofrece la posibilidad de crear una variable que al ser
419
+ * actualizada avisa sobre la actualización.
420
+ *
421
+ * @example
422
+ * const name = new WithEventsValue<string>('Alexis Leite');
423
+ *
424
+ * name.on('update', (newName) => console.log(`El nuevo nombre es ${newName}`));
425
+ *
426
+ * name.value = 'Joel'; // logs "El nuevo nombre es Joel"
427
+ */
428
+ declare class WithEventsValue<T> extends EventEmitter<{
429
+ update: T | undefined;
430
+ }> {
431
+ #private;
432
+ constructor(value?: T);
433
+ get value(): T | undefined;
434
+ set value(value: T | undefined);
435
+ }
436
+
437
+ interface TFncParams {
438
+ type: 'V' | 'P' | 'E';
439
+ value?: string;
440
+ attId?: number;
441
+ }
442
+ type TApiaFormButton = {
443
+ onclick: string;
444
+ text: string;
445
+ id: string;
446
+ type: string;
447
+ };
448
+ interface TApiaSelectPossibleValue {
449
+ value: string | number;
450
+ label: string;
451
+ selected?: boolean;
452
+ }
453
+ interface TApiaMultiplePossibleValue {
454
+ value: string | number;
455
+ label: string;
456
+ selected?: boolean;
457
+ }
458
+ interface TApiaRadioPossibleValue {
459
+ value: string | number;
460
+ label: string;
461
+ selected?: boolean;
462
+ }
463
+ type TApiaPossibleValue = TApiaRadioPossibleValue & TApiaMultiplePossibleValue & TApiaSelectPossibleValue;
464
+ type TFieldEvent = 'onLoad' | 'onReload' | 'onSubmit' | 'onChange' | 'onModalReturn' | 'onClick' | 'onPopulate' | 'populate' | 'gridAdd' | 'gridSort' | 'gridSortUp' | 'gridSortDown' | 'gridDelete' | 'gridColumnSelect' | 'JSApiaUpdate' | 'onSubmit';
465
+ interface TFieldScriptEvent {
466
+ fncName: string;
467
+ evtName: Readonly<TFieldEvent>;
468
+ evtId: number | string;
469
+ fncParams: TFncParams[];
470
+ }
471
+ type TFieldScriptEvents = TFieldScriptEvent[];
472
+ interface TFieldServerEvent {
473
+ evtId: number;
474
+ evtName: Readonly<TFieldEvent>;
475
+ isAjax: boolean;
476
+ }
477
+ type TFieldServerEvents = TFieldServerEvent[];
478
+ interface TApiaFieldPropsObj {
479
+ alignment?: string;
480
+ alt?: string;
481
+ bold?: string;
482
+ checked?: boolean;
483
+ colspan?: number;
484
+ cssClass?: string;
485
+ disabled?: boolean;
486
+ docType?: string;
487
+ dontBreakRadio?: boolean;
488
+ fontColor?: string;
489
+ gridHeight?: number;
490
+ gridColTitle?: string;
491
+ gridTitle?: string;
492
+ height?: string;
493
+ hideAddButton?: boolean;
494
+ hideDelButton?: boolean;
495
+ hideDocMetadata?: boolean;
496
+ hideDocPermissions?: boolean;
497
+ hideGridButtons?: boolean;
498
+ hideIncludeButton?: boolean;
499
+ hideOrderButton?: boolean;
500
+ hideSignButtons?: boolean;
501
+ pagedGridSize?: number;
502
+ paged?: boolean;
503
+ includeFirstRow?: boolean;
504
+ imageUrl?: string;
505
+ inputAsText?: boolean;
506
+ isActuallyReadonly?: boolean;
507
+ multiselect?: boolean;
508
+ name?: string;
509
+ noPrint?: boolean;
510
+ readonly?: boolean;
511
+ readOnly?: boolean;
512
+ regExpMessage?: string;
513
+ reqSign?: boolean;
514
+ reqTrad?: boolean;
515
+ required?: boolean;
516
+ rowspan?: number;
517
+ selParent?: boolean;
518
+ size?: string;
519
+ storeMdlQryResult?: boolean;
520
+ tooltip?: string;
521
+ tooltipHelp?: boolean;
522
+ transient?: boolean;
523
+ underlined?: boolean;
524
+ url?: string;
525
+ value?: unknown;
526
+ updateValueWithoutSynchronize?: unknown;
527
+ valueColor?: string;
528
+ visibilityHidden?: boolean;
529
+ possibleValue?: TApiaSelectPossibleValue[] | TApiaSelectPossibleValue | TApiaRadioPossibleValue[] | TApiaMultiplePossibleValue[] | TApiaMultiplePossibleValue;
530
+ leafIcon?: string;
531
+ parentIcon?: string;
532
+ props?: string;
533
+ id?: string;
534
+ noLock?: boolean;
535
+ noErase?: boolean;
536
+ noModify?: boolean;
537
+ noDownload?: boolean;
538
+ allowEdition?: boolean;
539
+ hideDocDownload?: boolean;
540
+ qryId?: string;
541
+ startIndex?: number;
542
+ curPage?: number;
543
+ pages?: number;
544
+ rowCount?: number;
545
+ maxRecords?: number;
546
+ colWidth?: string;
547
+ gridForm?: string;
548
+ documentMonitorCus?: number;
549
+ fileCollapseFldStrc?: boolean;
550
+ fileCollapseMetadata?: boolean;
551
+ fileCollapsePermission?: boolean;
552
+ fileDefFolder?: number;
553
+ fileDntShwDocMdlOnDrop?: boolean;
554
+ fileExpDate?: boolean;
555
+ fileNoAllwDnD?: boolean;
556
+ fileNotShowDocMon?: boolean;
557
+ fileShowDesc?: boolean;
558
+ fileShwFoldTreeBtn?: boolean;
559
+ fileShwFoldTreeStr?: boolean;
560
+ oneClickUpload?: boolean;
561
+ fieldId?: string;
562
+ hasFinishedLoading?: boolean;
563
+ }
564
+ type TApiaFormElementOption = {
565
+ content: string;
566
+ value: string;
567
+ };
568
+ type TApiaFormElement = {
569
+ class: string;
570
+ disabled: boolean;
571
+ html: boolean;
572
+ id: string;
573
+ mandatory: boolean;
574
+ maxlength?: string;
575
+ modalFunction?: string;
576
+ name: string;
577
+ normalWhiteSpace: boolean;
578
+ onChange: string;
579
+ options: {
580
+ option: TApiaFormElementOption | TApiaFormElementOption[];
581
+ };
582
+ readonly: boolean;
583
+ regExp?: string;
584
+ regExpMessage?: string;
585
+ selected: boolean;
586
+ size: string;
587
+ text: string;
588
+ title: string;
589
+ type: string;
590
+ value: string;
591
+ valueAsAttribute: boolean;
592
+ };
593
+ type TApiaLoadForm = {
594
+ form: {
595
+ multiPart: boolean;
596
+ ajaxNewPanel: boolean;
597
+ showErrors: boolean;
598
+ doEscape: boolean;
599
+ action: string;
600
+ onLoad: string;
601
+ ajaxsubmit: boolean;
602
+ closeAll: boolean;
603
+ title: string;
604
+ autoExpand: boolean;
605
+ titleClass: string;
606
+ addClass: string;
607
+ elements?: {
608
+ label: string;
609
+ element: TApiaFormElement | TApiaFormElement[];
610
+ };
611
+ buttons?: {
612
+ button: TApiaFormButton | TApiaFormButton[];
613
+ };
614
+ };
615
+ };
616
+ type TApiaFilterValue = string | number;
617
+ type TApiaFilterOption = {
618
+ label: string;
619
+ value: TApiaFilterValue;
620
+ selected?: boolean;
621
+ id?: string;
622
+ name?: string;
623
+ };
624
+ type TApiaFilter = {
625
+ asAdditional?: boolean;
626
+ column?: string;
627
+ currentValue: TApiaFilterValue;
628
+ deleteFiltersTimestamp?: number;
629
+ error?: string;
630
+ id: string | number;
631
+ isMeta?: boolean;
632
+ placeholder?: string;
633
+ runAutomatically?: boolean;
634
+ title?: string;
635
+ toolTip?: string;
636
+ detectOnChange?: boolean;
637
+ readonly?: boolean;
638
+ required?: boolean;
639
+ sortCombo?: boolean;
640
+ /**
641
+ * Con esta propiedad se permite agupar los filtros para mostrarlos en un
642
+ * panel especifico.
643
+ */
644
+ group?: string;
645
+ options?: TApiaFilterOption[];
646
+ type?: 'date' | 'D' | 'S' | 'number' | 'N' | 'apiaNumber';
647
+ hide?: boolean;
648
+ hideToFilter?: boolean;
649
+ filterToId?: string;
650
+ filterToValue?: TApiaFilterValue;
651
+ isRange?: boolean;
652
+ };
653
+
654
+ interface TApiaAction {
655
+ toDo?: string;
656
+ param: string | string[];
657
+ }
658
+ interface TApiaActions {
659
+ action: TApiaAction | TApiaAction[];
660
+ }
661
+ interface TApiaMessage {
662
+ text: string;
663
+ label?: string;
664
+ }
665
+ type TApiaComplexCell = {
666
+ label: string;
667
+ classToAdd?: string;
668
+ isHTML?: boolean;
669
+ docName?: string;
670
+ forceTitle?: string;
671
+ [key: string]: unknown;
672
+ };
673
+ type TApiaCellDefinition = TApiaComplexCell | string;
674
+ type TApiaRowDefinition = {
675
+ 'data-selected'?: boolean;
676
+ selected?: boolean;
677
+ dblclic: boolean;
678
+ id: string;
679
+ classToAdd?: string;
680
+ rowSeparator?: boolean;
681
+ suspended?: boolean;
682
+ unselectableTR?: boolean;
683
+ headName?: string;
684
+ isLocked?: boolean;
685
+ cell: TApiaCellDefinition | TApiaCellDefinition[];
686
+ boldType?: boolean;
687
+ 'expired-doc': true;
688
+ };
689
+ type TApiaFunctionPageInfo = {
690
+ amount: string;
691
+ currentPage: string;
692
+ hasMore: boolean;
693
+ pageCount: string;
694
+ prefix: string;
695
+ reachedMax: boolean;
696
+ selectOnlyOne: boolean;
697
+ totalRecords: string;
698
+ };
699
+ type TApiaSystemMessageObj<Structure = Record<string, unknown>> = Structure & {
700
+ onClose?: string;
701
+ sysMessages?: {
702
+ message: TApiaMessage | TApiaMessage[];
703
+ };
704
+ sysExceptions?: {
705
+ exception: TApiaMessage | TApiaMessage[];
706
+ };
707
+ exceptions?: {
708
+ exception: TApiaMessage | TApiaMessage[];
709
+ };
710
+ actions?: TApiaActions;
711
+ code?: unknown;
712
+ load?: Structure;
713
+ };
714
+ type TApiaTableFunction = {
715
+ result: {
716
+ pageInfo: TApiaFunctionPageInfo;
717
+ table?: {
718
+ row: TApiaRowDefinition | TApiaRowDefinition[];
719
+ };
720
+ };
721
+ };
722
+ type TApiaFunction<T = TApiaTableFunction, HasMessages = true> = HasMessages extends true ? {
723
+ function: {
724
+ dropLastMessage?: boolean;
725
+ name: string;
726
+ messages: T;
727
+ };
728
+ } : {
729
+ function: {
730
+ name: string;
731
+ } & T;
732
+ };
733
+ type TApiaLoadText = {
734
+ text: {
735
+ closeAll: boolean;
736
+ title: string;
737
+ addClass: string;
738
+ content: string;
739
+ };
740
+ };
741
+ type TApiaLoad<T extends Record<string, unknown> = TApiaLoadForm> = {
742
+ canClose: boolean;
743
+ type: string;
744
+ } & T;
745
+ interface TMessage {
746
+ text: string;
747
+ content?: string;
748
+ title?: string;
749
+ type?: string;
750
+ }
751
+ interface TNotificationMessage {
752
+ onClose?: string;
753
+ sysMessages?: {
754
+ message: TMessage | TMessage[];
755
+ };
756
+ sysExceptions?: {
757
+ exception: TMessage | TMessage[];
758
+ };
759
+ exceptions?: {
760
+ exception: TMessage | TMessage[];
761
+ };
762
+ }
763
+
764
+ type TId = string | number;
765
+ type TModify<T, R> = Omit<T, keyof R> & R;
766
+ type TMap$1<T> = Record<string | number, T>;
767
+ type TRequireOnlyOne<T, Keys extends keyof T = keyof T> = Pick<T, Exclude<keyof T, Keys>> & {
768
+ [K in Keys]-?: Required<Pick<T, K>> & Partial<Record<Exclude<Keys, K>, undefined>>;
769
+ }[Keys];
770
+
771
+ interface IFocusProps {
772
+ modalsContainerRetriever?: () => HTMLElement;
773
+ notificationsContainerRetriever?: () => HTMLElement;
774
+ }
775
+ interface IOnFocusConfiguration {
776
+ /**
777
+ * El controlador emite un evento custom cuando se realiza foco, con la
778
+ * intención de que los elementos colapsables se abran automáticamente. Si
779
+ * este parámetro es pasado con false, se evita ese comportamiento.
780
+ */
781
+ dispatchCustomEvent?: boolean;
782
+ /**
783
+ * Cuando la pantalla está bloqueada con el spinner, el controlador no
784
+ * intentará hacer foco, a menos que este parámetro se pase en true.
785
+ */
786
+ focusEvenWhenScreenLocked?: boolean;
787
+ scrollIntoViewOptions?: ScrollIntoViewOptions;
788
+ }
789
+ declare const notificationsSelector = ".notification";
790
+ /**
791
+ * Al método focus.on se le puede pasar o bien un HTMLElement o bien una
792
+ * función que implemente esta interfaz. Cuando se pasa una función, la misma
793
+ * será invocada cada vez que se vaya a intentar una acción de foco.
794
+ *
795
+ * Si la función devuelve un elemento HTML, se intentará hacer foco sobre éste.
796
+ *
797
+ * Si la función devuelve null, ese intento será tomado como nulo y se volverá
798
+ * a intentar luego del tiempo determinado.
799
+ *
800
+ * Si la función devuelve false, será eliminada de la cola de foco, lo que
801
+ * significa que ya no se intentará hacer foco sobre este elemento. En cambio,
802
+ * se continuará con los demás elementos de la cola o en caso de no haber
803
+ * ninguno, con el último elemento que tuvo foco y aún esté presente en el
804
+ * documento.
805
+ */
806
+ type TFocusRetriever = (isLastTry: boolean) => HTMLElement | null | false;
807
+ interface IFocusQueryElement {
808
+ element: HTMLElement | TFocusRetriever;
809
+ configuration?: IOnFocusConfiguration;
810
+ }
811
+ declare global {
812
+ interface Window {
813
+ focusStatus: Record<string, unknown>;
814
+ }
815
+ }
816
+ interface IFocusCheck {
817
+ currentInstruction: number;
818
+ }
819
+ declare const focus: {
820
+ "__#6@#root": HTMLElement;
821
+ "__#6@#props": IFocusProps | undefined;
822
+ afterNotificationFocus: IFocusQueryElement | undefined;
823
+ "__#6@#actualFocusQuery": IFocusQueryElement[];
824
+ "__#6@#currentInstruction": number;
825
+ "__#6@#focusDelay": number;
826
+ "__#6@#focusRetries": number;
827
+ "__#6@#focusTimeout": number;
828
+ "__#6@#isIntervalRunning": boolean;
829
+ "__#6@#focusQuery": IFocusQueryElement[];
830
+ "__#6@#checkInstruction"(focusCheck: IFocusCheck): boolean;
831
+ "__#6@#doFocus"(HTMLElement: HTMLElement | TFocusRetriever, focusCheck: IFocusCheck, isLastTry: boolean, configuration?: IOnFocusConfiguration): Promise<false | HTMLElement | null>;
832
+ "__#6@#resetInterval"(): void;
833
+ "__#6@#runFocusInterval"(focusElement?: IFocusQueryElement, internalCall?: boolean): Promise<false | HTMLElement>;
834
+ /**
835
+ * Da la instrucción de colocar el foco en el elemento provisto como
836
+ * parámetro una vez que todas las notificaciones se hayan cerrado. En caso
837
+ * de no existir notificaciones abiertas, hace foco en el elemento
838
+ * directamente.
839
+ */
840
+ afterNotifications(element: HTMLElement | TFocusRetriever, configuration?: IOnFocusConfiguration): void;
841
+ /**
842
+ * Da la instrucción de colocar el foco en el elemento provisto como
843
+ * parámetro luego de recargar la página.
844
+ *
845
+ * Los parámetros pasados serán ordenados en orden de importancia priorizando
846
+ * en el siguiente orden:
847
+ * - id
848
+ * - name
849
+ * - className
850
+ * - selector
851
+ */
852
+ afterReload({ className, id, name, selector, }: TRequireOnlyOne<{
853
+ className: string;
854
+ id: string;
855
+ name: string;
856
+ selector: string;
857
+ }, "className" | "id" | "name" | "selector">): void;
858
+ /**
859
+ * Da la instrucción de colocar el foco el elemento pasado como parámetro.
860
+ * Se puede pasar también una función que devuelva HTMLElement | false | null.
861
+ *
862
+ * El segundo parámetro del método on es un objeto de tipo
863
+ * ScrollIntoViewOptions, que permite modificar el comportamiento del scroll
864
+ * a en el elemento.
865
+ *
866
+ * @see TFocusRetriever para más detalles sobre la función como parámetro.
867
+ */
868
+ on(element: HTMLElement | TFocusRetriever, configuration?: IOnFocusConfiguration): Promise<false | HTMLElement>;
869
+ focusOnReload: string | null;
870
+ restore(): void;
871
+ init(): void;
872
+ };
873
+
874
+ /**
875
+ * The GlobalFocus helper keeps a list of the last focused elements and allows
876
+ * to retrieve the last focused element which matches against a query selector.
877
+ */
878
+ declare const globalFocus: {
879
+ focused: (HTMLElement | TFocusRetriever)[];
880
+ "__#4@#onFocusCallbacks": (() => unknown)[];
881
+ offFocus(cb: () => unknown): void;
882
+ onFocus(cb: () => unknown): () => void;
883
+ inDocument(el: HTMLElement | TFocusRetriever): boolean;
884
+ focus: HTMLElement | TFocusRetriever;
885
+ readonly list: (HTMLElement | TFocusRetriever)[];
886
+ /**
887
+ * @param querySelector A query selector against which the element should match
888
+ * @returns The last HTMLElement if no querySelector argument provided or else, the last which matches
889
+ * against that query selector.
890
+ * */
891
+ last(querySelector?: string, omit?: number): HTMLElement | TFocusRetriever | null;
892
+ };
893
+
894
+ /**
895
+ * Permite reasignar múltiples referencias desde un mismo componente.
896
+ *
897
+ * @example
898
+ *
899
+ * const ref1 = useRef(null)
900
+ * const ref2 = useRef(null)
901
+ *
902
+ * const assignRefs = useMultipleRefs(ref1, ref2);
903
+ *
904
+ * return <Box ref={assignRefs} ...
905
+ */
906
+ declare function useCombinedRefs<RefType = HTMLInputElement>(...refs: (React$1.ForwardedRef<unknown> | undefined)[]): React$1.Dispatch<React$1.SetStateAction<RefType | undefined>>;
907
+
908
+ declare const useDebouncedCallback: <Params extends any[]>(callback: (...params: Params) => unknown, { runWhenTriggered, timeout }?: {
909
+ runWhenTriggered: boolean;
910
+ timeout: number;
911
+ }) => (...params: Params) => void;
912
+
913
+ /**
914
+ * Devuelve una referencia que mantiene siempre el último valor del elemento
915
+ * pasado, es especialmente útil para acceder a valores del componente desde
916
+ * dentro de efectos.
917
+ *
918
+ * *Investigar qué es 'react stale state'*
919
+ */
920
+ declare function useLatest<T>(value: T): React$1.MutableRefObject<T>;
921
+
922
+ declare function useMount(effect: EffectCallback): void;
923
+
924
+ declare function useUnmount(unmountCallback: () => void): void;
925
+
926
+ declare function usePrevious<T>(value: T): React$1.MutableRefObject<T | undefined>;
927
+
928
+ declare function useStateRef<T>(initialState?: T): [
929
+ typeof initialState extends undefined ? T | undefined : T,
930
+ Dispatch<SetStateAction<typeof initialState extends undefined ? T | undefined : T>>,
931
+ MutableRefObject<typeof initialState extends undefined ? T | undefined : T>
932
+ ];
933
+
934
+ /**
935
+ * Este hook se comporta igual que useEffect, con la diferencia de que en el
936
+ * primer renderizado no se va a ejecutar.
937
+ */
938
+ declare function useUpdateEffect(effect: EffectCallback, deps?: DependencyList): void;
939
+
940
+ type TMethod<CR> = CR extends (state: any, ...args: infer Action) => any ? (id: TId, ...args: Action) => unknown : () => unknown;
941
+ type TMethods<State extends TMap, K extends any[] = any[]> = Record<string, (setState: TStateManager<State>, ...args: K) => void>;
942
+ type TMethodsMap<OriginalMethods extends TMethods<any>> = {
943
+ [Name in keyof OriginalMethods]: TMethod<OriginalMethods[Name]>;
944
+ };
945
+ type TEventsMap<OriginalEvents extends TMap> = {
946
+ [Name in keyof OriginalEvents]: (args: OriginalEvents[Name]) => unknown;
947
+ };
948
+ type TEventsHandlers<OriginalEvents extends TMap> = Record<TId, {
949
+ [Name in keyof OriginalEvents]?: ((args?: OriginalEvents[Name]) => unknown)[];
950
+ }>;
951
+ type TMap = Record<string, any>;
952
+ type TStateManager<State> = (newState: Partial<State>) => void;
953
+ type TFireEvent<Events extends TMap> = <K extends keyof Events>(id: TId, ev: K, args: Events[K] extends void ? undefined : Events[K]) => void;
954
+
955
+ /**
956
+ * Permite la creación de componentes multi-instancia que ofrecen métodos para
957
+ * trabajar sobre su estado o su comportamiento interno.
958
+ *
959
+ * @example
960
+ * const [methods, events, Imperative] = makeImperativeComponent<
961
+ {
962
+ age: number;
963
+ },
964
+ { blink: number }
965
+ >()(
966
+ {} as {
967
+ name: string;
968
+ },
969
+ {
970
+ setName(setState, name: string) {
971
+ setState({ name });
972
+ },
973
+ },
974
+ ({ age, name, useEvents }) => {
975
+ const [isBlinking, setIsBlinking] = useState(false);
976
+
977
+ useEvents({
978
+ blink() {
979
+ setInterval(() => setIsBlinking((current) => !current), 300);
980
+ },
981
+ });
982
+
983
+ return (
984
+ <Box sx={{ background: isBlinking ? 'red' : undefined }}>
985
+ {age} {name}
986
+ </Box>
987
+ );
988
+ },
989
+ );
990
+
991
+ methods
992
+ */
993
+ declare function makeImperativeComponent<ComponentProps extends TMap, Events extends TMap = TMap>(): <State extends TMap, Methods extends TMethods<State, any[]>>({ Component, initialState, methods, }: {
994
+ initialState?: State | undefined;
995
+ methods?: Methods | undefined;
996
+ Component: FC<Omit<ComponentProps, "id"> & State>;
997
+ }) => [TMethodsMap<Methods>, TFireEvent<Events>, FC<ComponentProps & {
998
+ id: TId;
999
+ }>];
1000
+
1001
+ type TSingleMethodsMap<Methods extends TMethods<any>, MethodsMap extends TMethodsMap<Methods>> = {
1002
+ [Name in keyof MethodsMap]: MethodsMap[Name] extends (id: TId, ...args: infer Action) => unknown ? (...args: Action) => unknown : never;
1003
+ };
1004
+ declare function makeSingleImperativeComponent<ComponentProps extends TMap, Events extends TMap = TMap>(): <State extends TMap, Methods extends TMethods<State, any[]>>({ initialState, methods, Component, }: {
1005
+ initialState?: State | undefined;
1006
+ methods?: Methods | undefined;
1007
+ Component: FC<Omit<ComponentProps, "id"> & State>;
1008
+ }) => [TSingleMethodsMap<Methods, TMethodsMap<Methods>>, <K extends keyof Events>(ev: K, args: Events[K]) => void, FC<ComponentProps>];
1009
+
1010
+ declare const useImperativeComponentEvents: <Events extends TMap = TMap>(handlers: Partial<TEventsMap<Events>>) => void;
1011
+
1012
+ /**
1013
+ * Permite el uso de eventos en herederos directos o no del imperativeComponent
1014
+ * más cercano.
1015
+ */
1016
+ declare function useImperativeComponentContext<Events extends TMap = TMap>(): {
1017
+ id: TId;
1018
+ eventsStore: TEventsHandlers<Events>;
1019
+ };
1020
+
1021
+ declare global {
1022
+ interface Window {
1023
+ labels: {
1024
+ [key: string]: {
1025
+ text: string;
1026
+ tooltip: string;
1027
+ };
1028
+ };
1029
+ }
1030
+ }
1031
+ /**
1032
+ * Dado un nombre de etiqueta, devuelve el texto que esa etiqueta contiene en
1033
+ * el idioma actual. En este momento, lo único que hace realmente esta función
1034
+ * es devolver la variable del window con el mismo nombre que se está pidiendo.
1035
+ *
1036
+ * La idea de implementar esta función, es que en un futuro la fuente de la que
1037
+ * provienen las labels pueda ser más diversa.
1038
+ *
1039
+ * Permite el pasaje de tokens para el reemplazo automático de los mismos.
1040
+ *
1041
+ * @example
1042
+ *
1043
+ * // Suponemos la etiqueta msgUsu = { text: 'Usuario <TOK1>', title: 'Usuario <TOK1>' }
1044
+ *
1045
+ * getLabel('msgUsu' , {
1046
+ * text: {
1047
+ * TOK1: 'admin',
1048
+ * },
1049
+ * title: {
1050
+ * TOK1: 'no disponible',
1051
+ * }
1052
+ * })
1053
+ */
1054
+ declare function getLabel(name: string, replaceTokens?: {
1055
+ text?: Record<string, string>;
1056
+ title?: Record<string, string>;
1057
+ }): {
1058
+ text: string;
1059
+ tooltip: string;
1060
+ };
1061
+
1062
+ /**
1063
+ * Da formato a un mensaje con tokens incrustados.
1064
+ *
1065
+ * @example
1066
+ *
1067
+ * // Dado el siguiente mensaje:
1068
+ * var msg = 'El campo <TOK1> es inválido.';
1069
+ *
1070
+ * console.log(formatMessage(msg, {
1071
+ * TOK1: 'nombre',
1072
+ * }));
1073
+ * // Imprime: El campo nombre es inválido.
1074
+ */
1075
+ declare const formatMessage: (str: string, obj: {
1076
+ [key: string]: string;
1077
+ }) => string;
1078
+
1079
+ type TTabRenderer<AdditionalPropsType extends Record<string, unknown> = Record<string, unknown>> = (props: {
1080
+ tab: TTab<AdditionalPropsType>;
1081
+ }) => React.ReactElement;
1082
+ type TApiaTabProps = {
1083
+ originalUrl: string;
1084
+ url: string;
1085
+ };
1086
+ type TTab<AdditionalPropsType extends Record<string, unknown> = Record<string, unknown>> = {
1087
+ content: React.FunctionComponent<{
1088
+ tab: TTab<AdditionalPropsType>;
1089
+ }>;
1090
+ icon?: TIconName | TIconType;
1091
+ /**
1092
+ * El id es importante ya que se utiliza por temas de accesibilidad. Es
1093
+ * importante asegurarse de que sea único.*/
1094
+ id: TId;
1095
+ isClosable?: boolean;
1096
+ isDisabled?: boolean;
1097
+ /**
1098
+ * Los tabs que estén marcados como fixed aparecerán al inicio del listado.
1099
+ */
1100
+ isFixed?: boolean;
1101
+ isFocused?: boolean;
1102
+ /**
1103
+ * Si se marca como iconTab, se oculta el label y solamente se muestra el
1104
+ * ícono.
1105
+ */
1106
+ isIconTab?: boolean;
1107
+ isLoading?: boolean;
1108
+ isOpen?: boolean;
1109
+ /**
1110
+ * Cuando se cierra un tab que tiene un método onBeforeClose, el mismo será
1111
+ * llamado y deberá devolver un boolean o un string. Si devuelve true, se
1112
+ * cierra. Si devuelve false, se muestra un cartel de confirmación genérico y
1113
+ * si se devuelve un string, se muestra un cartel de confirmación con el
1114
+ * string devuelto. En caso de que el usuario confirme el cuadro de diálogo,
1115
+ * el tab será cerrado de todas formas. Es decir, no hay forma de evitar que
1116
+ * el tab sea cerrado si el usuario decide continuar con la acción. Para
1117
+ * evitar que un tab sea cerrado, debe pasarse isClosable=false
1118
+ */
1119
+ onBeforeClose?: () => boolean | string | Promise<boolean | string>;
1120
+ /**
1121
+ * Este callback será llamado cada vez que el tab sea abierto
1122
+ */
1123
+ onFocus?: (ev: TTab<AdditionalPropsType>) => unknown;
1124
+ /**
1125
+ * Es el texto que se va a mostrar en el tab
1126
+ */
1127
+ label: string;
1128
+ labelRenderer?: TTabRenderer;
1129
+ /**
1130
+ * Se pueden pasar propiedades adicionales que serán recibidas en cada
1131
+ * evento, de forma de poder compartir piezas de información útiles en las
1132
+ * distintas partes de la aplicación.
1133
+ */
1134
+ tabAdditionalProps: AdditionalPropsType;
1135
+ title?: string;
1136
+ };
1137
+ interface IMainTabsController<AdditionalPropsType extends Record<string, unknown> = Record<string, unknown>, TabType extends TTab<AdditionalPropsType> = TTab<AdditionalPropsType>> {
1138
+ activeTabs: TabType[];
1139
+ tabsList: TId[];
1140
+ append(tab: Omit<TabType, 'tabAdditionalProps'> & Partial<Pick<TabType, 'tabAdditionalProps'>>): void;
1141
+ closeAll(closeFixedTabsAsWell?: boolean, force?: boolean): Promise<void>;
1142
+ closeToRight(targetId: TId): Promise<void>;
1143
+ closeToLeft(targetId: TId): Promise<void>;
1144
+ closeOthers(targetId: TId): Promise<void>;
1145
+ closeTab(tabId: TId, force?: boolean): Promise<boolean>;
1146
+ focusNextTab(): TId | null;
1147
+ focusPreviousTab(): TId | null;
1148
+ focusTab(tabId: TId): void;
1149
+ getTabById(tabId: TId): TabType;
1150
+ getTabElement(tabId: TId): Element | null;
1151
+ handleKeyDown(ev: React.KeyboardEvent): void;
1152
+ openNextTab(): TId | null;
1153
+ openPreviousTab(): TId | null;
1154
+ openTab(tabId: TId, justThis?: boolean): void;
1155
+ }
1156
+ interface ITabsController {
1157
+ handler: IMainTabsController<TApiaTabProps>;
1158
+ handlerSet: boolean;
1159
+ closeActiveTab(force?: boolean): void;
1160
+ closeAll(closeFixedTabsAsWell?: boolean, force?: boolean): void;
1161
+ openMainMenu(): void;
1162
+ openTabByUrl(title: string, url: string, options?: IOpenTabOptions): void;
1163
+ setHandler(handler: IMainTabsController<TApiaTabProps>): void;
1164
+ changeTabState(): void;
1165
+ }
1166
+ interface IOpenTabOptions {
1167
+ funcId?: TId;
1168
+ keepMenuOpen?: boolean;
1169
+ parentTabId?: string;
1170
+ }
1171
+
1172
+ interface ISetBoundary {
1173
+ number?: number | string;
1174
+ min?: number;
1175
+ max?: number;
1176
+ loop?: boolean;
1177
+ }
1178
+ /**
1179
+ * Añade límites a un número, impidiendo que sea
1180
+ * inferior o superior a los límites establecidos.
1181
+ *
1182
+ * Si se pasa loop en true, al llegar al valor maximo o minimo regresara al
1183
+ * minimo o maximo respectivamente.
1184
+ */
1185
+ declare function addBoundary(num: number, min: number, max?: number, loop?: boolean): number;
1186
+ declare function addBoundary(definition: ISetBoundary): number;
1187
+ /**
1188
+ * Esta función acepta un número y devuelve la representaciíon
1189
+ * en string de su tamaño en disco. Ej: 1024 => 1kb
1190
+ */
1191
+ declare function parseAsSize(num: number): string;
1192
+ /**
1193
+ * Toma cualquier valor y devuelve siempre un número. En caso de que el valor
1194
+ * casteado con la función Number(value) de NaN, devuelve defaultReturn, que por
1195
+ * defecto es 0
1196
+ */
1197
+ declare function noNaN(number: unknown, defaultReturn?: number): number;
1198
+
1199
+ /**
1200
+ * Este método itera sobre un objeto hasta encontrar la ruta especificada
1201
+ *
1202
+ * @example
1203
+ *
1204
+ const obj = {
1205
+ a: {
1206
+ b: {
1207
+ c: {
1208
+ d: "d"
1209
+ }
1210
+ }
1211
+ }
1212
+ };
1213
+
1214
+ console.log(getValueByPath(obj,'a.b.c')) // { d: 'd' }
1215
+ console.log(getValueByPath(obj,'a.b.c.d')) // 'd'
1216
+ *
1217
+ */
1218
+ declare function getValueByPath(obj: Record<string, unknown>, path: string | string[], separator?: string): unknown;
1219
+
1220
+ /**
1221
+ * Permite escribir una propiedad en un objeto, en una ruta especificada. Si
1222
+ * dicha ruta no existe dentro del objeto la crea, siempre que sea posible. No
1223
+ * será posible en caso de que alguno de los elementos de la ruta contenga una
1224
+ * propiedad que no sea de tipo objeto.
1225
+ *
1226
+ * @param obj El objeto donde se desea escribir la propiedad
1227
+ * @param path La ruta en la que se va a escribir
1228
+ * @param value El valor que se va a escribir en la ruta especificada
1229
+ * @returns Un objeto idéntico del recibido pero co nlos cambios aplicados
1230
+ *
1231
+ * @throws { Error } En caso de que la ruta especificada contenga algún elemento que no puede ser escrito.
1232
+ *
1233
+ * @example
1234
+ *
1235
+ * const a = {
1236
+ * a: {}
1237
+ * };
1238
+ *
1239
+ * setValueByPath(a, 'a.b.c', 'Hello world');
1240
+ * /* Outputs:
1241
+ * {
1242
+ * a: {
1243
+ * b: {
1244
+ * c: 'Hello world'
1245
+ * }
1246
+ * }
1247
+ * }
1248
+ */
1249
+ declare function setValueByPath(obj: Record<string, unknown>, path: string, value: unknown): Record<string, unknown> | null;
1250
+
1251
+ type TProperties = Record<string, unknown>;
1252
+ type TPropsSuscriptor<PropsType extends Record<string, unknown> = TProperties> = (props: PropsType, urgent?: boolean) => unknown;
1253
+ type TPropsSelector<Selected = any, PropsType = TProperties> = (props: PropsType) => Selected;
1254
+ /**
1255
+ * La función comparadora debe devolver true cuando
1256
+ * los elementos son iguales o false cuando son
1257
+ * distintos.
1258
+ */
1259
+ type TPropsComparator<Selected> = (prevProps: Selected | undefined, newProps: Selected | undefined) => boolean;
1260
+ type TPropsConfiguration<Selected, PropsType extends Record<string, unknown> = TProperties> = {
1261
+ selector?: TPropsSelector<Selected, PropsType>;
1262
+ comparator?: TPropsComparator<Selected>;
1263
+ initialValue?: Selected;
1264
+ propsStore?: PropsStore<PropsType>;
1265
+ };
1266
+ type TUpdateFieldConfiguration = Partial<{
1267
+ noEmit: boolean;
1268
+ isUrgent: boolean;
1269
+ }>;
1270
+
1271
+ interface IPropsStoreConf {
1272
+ logCommands: {
1273
+ propsStore?: string;
1274
+ updateProp?: string;
1275
+ propsSuscriptors?: string;
1276
+ propsLog?: string;
1277
+ };
1278
+ }
1279
+ declare class PropsStore<PropsType extends Record<TId$1, unknown> = Record<TId$1, unknown>> {
1280
+ private configuration?;
1281
+ log: unknown;
1282
+ fields: Record<TId$1, PropsType>;
1283
+ suscriptors: Record<TId$1, TPropsSuscriptor<PropsType>[]>;
1284
+ loggers: Record<string, (props: unknown[]) => void>;
1285
+ constructor(configuration?: IPropsStoreConf | undefined);
1286
+ destructor(): void;
1287
+ getAllFields(): Record<TId$1, PropsType>;
1288
+ /**
1289
+ * Devuelve los props actuales de un campo.
1290
+ */
1291
+ getFieldProps<ParsedPropsType = PropsType>(fieldId: TId$1): ParsedPropsType;
1292
+ removeField(fieldId: TId$1): void;
1293
+ /**
1294
+ * Permite establecer un suscriptor que será llamado
1295
+ * cada vez que las props del campo especificado cambien.
1296
+ */
1297
+ suscribe(fieldId: TId$1, callback: TPropsSuscriptor<PropsType>): () => void;
1298
+ /**
1299
+ * Actualiza o crea las props de un campo.
1300
+ *
1301
+ * La tercera prop está relacionada
1302
+ */
1303
+ updateField<NewPropsType extends Record<TId$1, unknown> = Partial<PropsType>>(fieldId: TId$1, props: Partial<NewPropsType>, conf?: TUpdateFieldConfiguration): void;
1304
+ }
1305
+ declare const propsStore: PropsStore<TProperties>;
1306
+
1307
+ declare const PropsSelectorUndefinedObject: {};
1308
+ declare function isPropsConfigurationObject<Selected, PropsType extends Record<string, unknown> = TProperties>(value?: TPropsSelector<Selected, PropsType> | TPropsConfiguration<Selected, PropsType>): value is TPropsConfiguration<Selected, PropsType>;
1309
+ /**
1310
+ *
1311
+ * Este hook permite escuchar los cambios en las propiedades
1312
+ * de un campo en particular.
1313
+ *
1314
+ * @param configuration
1315
+ * Este objeto permite pasar las siguientes propiedades para ser
1316
+ * determinar el comportamiento del hook:
1317
+ *
1318
+ * **selector:** La función selectora es una función equivalente
1319
+ * a la que se utiliza en el useAppSelector de redux. Con ella
1320
+ * se puede seleccionar una porción de las props, evitando
1321
+ * re-renderizados innecesarios. Esto se debe a que el renderizado
1322
+ * solamente ocurrirá cuando la función selectora devuelva un valor
1323
+ * que sea distinto del anterior.
1324
+ *
1325
+ * El concepto de distinto es: si existe una función comparadora,
1326
+ * se determinará mediante la ejecución de dicha función, a la que
1327
+ * se le pasan como parámetros el objeto anterior y el nuevo.
1328
+ *
1329
+ * En caso de que no haya función comparadora, se comparará que
1330
+ * las props seleccionadas y las nuevas sean exactamente las mismas
1331
+ * (la referencia al mismo objeto).
1332
+ *
1333
+ * **comparator:** La función comparadora de la que estamos
1334
+ * hablando.
1335
+ *
1336
+ * **initialValue:** Un valor para setearlo al inicio, el mismo
1337
+ * solamente será seteado en caso de que ya no exista un valor
1338
+ * en el store.
1339
+ * @returns
1340
+ */
1341
+ declare function usePropsSelector<Selected = TProperties, PropsType extends Record<string, unknown> = TProperties>(fieldId: TId$1, configuration?: TPropsConfiguration<Selected, PropsType>): Selected;
1342
+ /**
1343
+ *
1344
+ * Este hook permite escuchar los cambios en las propiedades
1345
+ * de un campo en particular.
1346
+ *
1347
+ * @param selector La función selectora es una función equivalente
1348
+ * a la que se utiliza en el useAppSelector de redux. Con ella
1349
+ * se puede seleccionar una porción de las props, evitando
1350
+ * re-renderizados innecesarios. Esto se debe a que el renderizado
1351
+ * solamente ocurrirá cuando la función selectora devuelva un valor
1352
+ * que sea distinto del anterior.
1353
+ *
1354
+ * El concepto de distinto es: si existe una función comparadora,
1355
+ * se determinará mediante la ejecución de dicha función, a la que
1356
+ * se le pasan como parámetros el objeto anterior y el nuevo.
1357
+ *
1358
+ * En caso de que no haya función comparadora, se comparará que
1359
+ * las props seleccionadas y las nuevas sean exactamente las mismas
1360
+ * (la referencia al mismo objeto).
1361
+ *
1362
+ * @param comparator La función comparadora de la que estamos
1363
+ * hablando.
1364
+ *
1365
+ * @returns
1366
+ */
1367
+ declare function usePropsSelector<Selected = TProperties, PropsType extends Record<string, unknown> = TProperties>(fieldId: TId$1, selector?: TPropsSelector<Selected, PropsType> | TPropsConfiguration<Selected, PropsType>, comparator?: TPropsComparator<Selected>, anotherPropsStore?: PropsStore<PropsType>): Selected;
1368
+
1369
+ /**
1370
+ * El hook useDomState permite aplicar propiedades a un
1371
+ * elemento del DOM de la forma más eficiente posible.
1372
+ *
1373
+ * Este hook no permite el uso de sx ya que por las características
1374
+ * del sx, el re-renderizado es necesario.
1375
+ *
1376
+ * @example
1377
+ *
1378
+ *
1379
+ * const TestComponent = () => {
1380
+ const { domProps, setDomProps } = useDomState<BoxProps>({
1381
+ style: {
1382
+ position: 'fixed',
1383
+ left: 0,
1384
+ top: 0,
1385
+ width: '150px',
1386
+ height: '150px',
1387
+ backgroundColor: '#ccc',
1388
+ },
1389
+ });
1390
+ const initialPosition = React.useRef({ boxX: 0, boxY: 0, x: 0, y: 0 });
1391
+ const isDragging = React.useRef(false);
1392
+ const [state, setState] = React.useState(1);
1393
+
1394
+ React.useEffect(() => {
1395
+ const move = (ev: MouseEvent) => {
1396
+ if (isDragging.current) {
1397
+ const moveX = ev.clientX - initialPosition.current.x;
1398
+ const moveY = ev.clientY - initialPosition.current.y;
1399
+ const newLeft = initialPosition.current.boxX + moveX;
1400
+ const newTop = initialPosition.current.boxY + moveY;
1401
+ setDomProps({
1402
+ style: {
1403
+ left: `${newLeft}px`,
1404
+ top: `${newTop}px`,
1405
+ },
1406
+ });
1407
+ }
1408
+ };
1409
+
1410
+ const removeSuscription = () => {
1411
+ isDragging.current = false;
1412
+ };
1413
+
1414
+ document.addEventListener('mousemove', move);
1415
+ document.addEventListener('mouseup', removeSuscription);
1416
+
1417
+ return () => {
1418
+ document.removeEventListener('mousemove', move);
1419
+ document.removeEventListener('mouseup', removeSuscription);
1420
+ };
1421
+ }, [setDomProps]);
1422
+
1423
+ console.log('RENDER');
1424
+
1425
+ return (
1426
+ <Box
1427
+ {...domProps}
1428
+ onMouseDown={(ev) => {
1429
+ initialPosition.current = {
1430
+ boxX: Number.parseInt(domProps.style?.left as string, 10),
1431
+ boxY: Number.parseInt(domProps.style?.top as string, 10),
1432
+ x: ev.clientX,
1433
+ y: ev.clientY,
1434
+ };
1435
+ isDragging.current = true;
1436
+ }}
1437
+ >
1438
+ Esta caja es arrastrable. Renderizados: {state}
1439
+ <Button onClick={() => setState((current) => current + 1)}>
1440
+ Renderizar
1441
+ </Button>
1442
+ </Box>
1443
+ );
1444
+ };
1445
+ */
1446
+ declare function useDomState<T extends HTMLAttributes<HTMLElement>>(initialDomProps?: T): {
1447
+ domProps: T & {
1448
+ ref: (el: HTMLElement) => void;
1449
+ };
1450
+ setDomProps: ({ style, ...newDomProps }: Partial<T>) => void;
1451
+ };
1452
+
1453
+ /**
1454
+ * Permite manejar un estado que se actualizará únicamente siguiendo el
1455
+ * comportamiento esperado de un debounce
1456
+ */
1457
+ declare function useDebouncedState<T>(timeout: number, initialState?: T): [T | undefined, (state: SetStateAction<T>, immediate?: boolean) => unknown];
1458
+
1459
+ /**
1460
+ * Esta clase no implementa ninguna funcionalidad de bloqueo, sino solamente se
1461
+ * encarga de la lógica y de los eventos.
1462
+ *
1463
+ * El concepto es que hay n niveles de bloqueo y además existe el bloqueo
1464
+ * forzado. Cada uno de los niveles recibe un nombre, por defecto se realizan
1465
+ * operaciones contra el bloque 'common' si no se pasa ninguno, pero
1466
+ * podría utilizarse cualquier otro. Esto es así con el fin de implementar
1467
+ * varios bloqueos en la misma clase, ejemplos: el bloqueo común, el bloqueo
1468
+ * lineal de las tablas, bloque con pantalla blanca en el inicio de formularios,
1469
+ * o cualquier otro que se desee. Para los bloqueos estándar se utilizan los
1470
+ * métodos lock y unlock.
1471
+ *
1472
+ * El bloqueo forzado por otra parte es un estado general que se puede alterar
1473
+ * mediante los métodos force y releaseForced. Cada vez que se bloquee o
1474
+ * desbloquee la pantalla, se lanzará un evento lockStateChange sin lockName y
1475
+ * con forced = true.
1476
+ *
1477
+ * Además, provee un evento para saber cuándo se desbloquea la pantalla
1478
+ * efectivamente por primera vez para cada tipo de bloqueo. Es posible a su vez
1479
+ * resetear la clase para que este evento sea lanzado nuevamente en el próximo
1480
+ * desbloqueo mediante resetRefreshFirstTime.
1481
+ *
1482
+ * El evento releasForFirstTime se dispara únicamente para el bloqueo 'common'.
1483
+ * Esto es así ya que sino podría dar lugar a confusión en situaciones donde no
1484
+ * se controle el nombre del bloqueo.
1485
+ */
1486
+ declare const screenLocker: {
1487
+ "__#5@#hasReleasedFirstTime": boolean;
1488
+ "__#5@#wasReleasedFirstTime": boolean;
1489
+ "__#5@#isForced": boolean;
1490
+ "__#5@#locks": Record<string, boolean>;
1491
+ readonly hasReleasedFirstTime: boolean;
1492
+ readonly isForced: boolean;
1493
+ /**
1494
+ * Permite saber si un bloqueo determinado está activo o si la clase tiene
1495
+ * forceLock activo.
1496
+ */
1497
+ isLocked(lockName?: string): boolean;
1498
+ "__#5@#shoutLockState"(lockName?: string): void;
1499
+ lock(lockName?: string): void;
1500
+ unlock(lockName?: string): void;
1501
+ force(): void;
1502
+ releaseForced(): void;
1503
+ "__#1@#emitter": IEmitter<{
1504
+ forcedStateChange: {
1505
+ hasReleasedFirstTime: boolean;
1506
+ isForced: boolean;
1507
+ };
1508
+ lockStateChange: {
1509
+ hasReleasedFirstTime: boolean;
1510
+ isLocked: boolean;
1511
+ lockName: string;
1512
+ };
1513
+ releaseForFirstTime: void;
1514
+ ready: void;
1515
+ }>;
1516
+ on<K extends TEventKey<{
1517
+ forcedStateChange: {
1518
+ hasReleasedFirstTime: boolean;
1519
+ isForced: boolean;
1520
+ };
1521
+ lockStateChange: {
1522
+ hasReleasedFirstTime: boolean;
1523
+ isLocked: boolean;
1524
+ lockName: string;
1525
+ };
1526
+ releaseForFirstTime: void;
1527
+ ready: void;
1528
+ }>>(eventName: K, fn: TEventReceiver<{
1529
+ forcedStateChange: {
1530
+ hasReleasedFirstTime: boolean;
1531
+ isForced: boolean;
1532
+ };
1533
+ lockStateChange: {
1534
+ hasReleasedFirstTime: boolean;
1535
+ isLocked: boolean;
1536
+ lockName: string;
1537
+ };
1538
+ releaseForFirstTime: void;
1539
+ ready: void;
1540
+ }[K]>): () => void;
1541
+ off<K_1 extends TEventKey<{
1542
+ forcedStateChange: {
1543
+ hasReleasedFirstTime: boolean;
1544
+ isForced: boolean;
1545
+ };
1546
+ lockStateChange: {
1547
+ hasReleasedFirstTime: boolean;
1548
+ isLocked: boolean;
1549
+ lockName: string;
1550
+ };
1551
+ releaseForFirstTime: void;
1552
+ ready: void;
1553
+ }>>(eventName: K_1, fn: TEventReceiver<{
1554
+ forcedStateChange: {
1555
+ hasReleasedFirstTime: boolean;
1556
+ isForced: boolean;
1557
+ };
1558
+ lockStateChange: {
1559
+ hasReleasedFirstTime: boolean;
1560
+ isLocked: boolean;
1561
+ lockName: string;
1562
+ };
1563
+ releaseForFirstTime: void;
1564
+ ready: void;
1565
+ }[K_1]>): void;
1566
+ emit<K_2 extends TEventKey<{
1567
+ forcedStateChange: {
1568
+ hasReleasedFirstTime: boolean;
1569
+ isForced: boolean;
1570
+ };
1571
+ lockStateChange: {
1572
+ hasReleasedFirstTime: boolean;
1573
+ isLocked: boolean;
1574
+ lockName: string;
1575
+ };
1576
+ releaseForFirstTime: void;
1577
+ ready: void;
1578
+ }>>(eventName: K_2, params?: {
1579
+ forcedStateChange: {
1580
+ hasReleasedFirstTime: boolean;
1581
+ isForced: boolean;
1582
+ };
1583
+ lockStateChange: {
1584
+ hasReleasedFirstTime: boolean;
1585
+ isLocked: boolean;
1586
+ lockName: string;
1587
+ };
1588
+ releaseForFirstTime: void;
1589
+ ready: void;
1590
+ }[K_2] | undefined): void;
1591
+ };
1592
+
1593
+ declare const persistentStorage: {
1594
+ [key: string]: unknown;
1595
+ remove(prop: string): unknown;
1596
+ };
1597
+ declare global {
1598
+ interface Window {
1599
+ persistentStorage: typeof persistentStorage;
1600
+ }
1601
+ }
1602
+
1603
+ /**
1604
+ * @param prop este nombre define el nombre del localStorage, las modificaciones a este parametro no van a tener efecto.
1605
+ */
1606
+ declare function useLocalStorage<T>(prop: string, defaultValue?: T): [T, (newValue: T) => void];
1607
+
1608
+ declare function ucfirst(word: string): string;
1609
+
1610
+ /**
1611
+ * Toma un valor y devuelve true o false según las
1612
+ * siguientes condiciones:
1613
+ *
1614
+ * Si es string, ['',
1615
+ * 'false'].includes(value.toLowerCase()) => false, todo lo
1616
+ * demás => true.
1617
+ *
1618
+ * Si es array, [] => false, [...] => true.
1619
+ *
1620
+ * Todo lo demás !!value
1621
+ *
1622
+ * @example
1623
+ *
1624
+ * toBoolean('true') // true
1625
+ * toBoolean('TrUE') // true
1626
+ * toBoolean('FAlSe') // false
1627
+ * toBoolean(0) // false
1628
+ * toBoolean(1) // true
1629
+ * toBoolean([0]) // true
1630
+ * toBoolean([]) // false
1631
+ */
1632
+ declare function toBoolean(value: unknown): boolean;
1633
+
1634
+ declare const parseXmlAsync: <T>(xml: string) => Promise<T>;
1635
+
1636
+ declare global {
1637
+ interface Window {
1638
+ [key: string]: string;
1639
+ }
1640
+ }
1641
+
1642
+ export { AriaLiveEmitter, EventEmitter, IOnFocusConfiguration, IParameter, ISetBoundary, ITabsController, LiveRegion, 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, apiaDateToStandarFormat, arrayOrArray, autoDisconnectMutationObserver, cantFocusSelector, customEvents, dateToApiaFormat, debugDispatcher, decrypt, disableChildrenFocus, downloadUrl, enableChildrenFocus, enableDebugDispatcher, encrypt, 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 };
1643
+ //# sourceMappingURL=index.d.ts.map