-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Copy pathtaipyReducers.ts
935 lines (870 loc) · 30.9 KB
/
taipyReducers.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
/*
* Copyright 2021-2025 Avaiga Private Limited
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
import { PaletteMode } from "@mui/material";
import { createTheme, Theme } from "@mui/material/styles";
import merge from "lodash/merge";
import { Dispatch } from "react";
import { io, Socket } from "socket.io-client";
import { nanoid } from "nanoid";
import { FilterDesc } from "../components/Taipy/tableUtils";
import { stylekitModeThemes, stylekitTheme } from "../themes/stylekit";
import { getBaseURL, TIMEZONE_CLIENT } from "../utils";
import { parseData } from "../utils/dataFormat";
import { MenuProps } from "../utils/lov";
import { changeFavicon, getLocalStorageValue, IdMessage, storeClientId } from "./utils";
import { lightenPayload, sendWsMessage, TAIPY_GUI_ADDR, TAIPY_CLIENT_ID, WsMessage } from "./wsUtils";
export enum Types {
SocketConnected = "SOCKET_CONNECTED",
Update = "UPDATE",
MultipleUpdate = "MULTIPLE_UPDATE",
SendUpdate = "SEND_UPDATE_ACTION",
Action = "SEND_ACTION_ACTION",
RequestDataUpdate = "REQUEST_DATA_UPDATE",
RequestUpdate = "REQUEST_UPDATE",
SetLocations = "SET_LOCATIONS",
SetTheme = "SET_THEME",
SetTimeZone = "SET_TIMEZONE",
SetNotification = "SET_NOTIFICATION",
DeleteNotification = "DELETE_NOTIFICATION",
SetBlock = "SET_BLOCK",
Navigate = "NAVIGATE",
ClientId = "CLIENT_ID",
MultipleMessages = "MULTIPLE_MESSAGES",
SetMenu = "SET_MENU",
DownloadFile = "DOWNLOAD_FILE",
Partial = "PARTIAL",
Acknowledgement = "ACKNOWLEDGEMENT",
Broadcast = "BROADCAST",
LocalStorage = "LOCAL_STORAGE",
}
/**
* The state of the underlying Taipy application.
*/
export interface TaipyState {
socket?: Socket;
isSocketConnected?: boolean;
data: Record<string, unknown>;
theme: Theme;
locations: Record<string, string>;
timeZone?: string;
dateFormat?: string;
dateTimeFormat?: string;
numberFormat?: string;
notifications: NotificationMessage[];
block?: BlockMessage;
navigateTo?: string;
navigateParams?: Record<string, string>;
navigateTab?: string;
navigateForce?: boolean;
id: string;
menu: MenuProps;
download?: FileDownloadProps;
ackList: string[];
}
/**
* Application actions as used by the application reducer.
*/
export interface TaipyBaseAction {
type: Types;
}
export interface NamePayload {
name: string;
payload: Record<string, unknown>;
}
export interface NotificationMessage {
nType: string;
message: string;
system: boolean;
duration: number;
notificationId?: string;
snackbarId: string;
onClose?: string;
reason?: string;
}
interface TaipyAction extends NamePayload, TaipyBaseAction {
propagate?: boolean;
context?: string;
}
interface TaipyMultipleAction extends TaipyBaseAction {
payload: NamePayload[];
}
interface TaipyMultipleMessageAction extends TaipyBaseAction {
actions: TaipyBaseAction[];
}
interface TaipyNotificationAction extends TaipyBaseAction, NotificationMessage {}
interface TaipyDeleteNotificationAction extends TaipyBaseAction {
snackbarId: string;
}
export const BLOCK_CLOSE = { action: "", message: "", close: true, noCancel: false } as BlockMessage;
export interface BlockMessage {
action: string;
noCancel: boolean;
close: boolean;
message: string;
}
interface TaipyBlockAction extends TaipyBaseAction, BlockMessage {}
export interface NavigateMessage {
to?: string;
params?: Record<string, string>;
tab?: string;
force?: boolean;
}
interface TaipyNavigateAction extends TaipyBaseAction, NavigateMessage {}
export interface FileDownloadProps {
content?: string;
name?: string;
onAction?: string;
context?: string;
}
interface TaipyIdAction extends TaipyBaseAction, IdMessage {}
interface TaipyAckAction extends TaipyBaseAction, IdMessage {}
interface TaipyDownloadAction extends TaipyBaseAction, FileDownloadProps {}
interface TaipySetMenuAction extends TaipyBaseAction {
menu: MenuProps;
}
interface TaipyPartialAction extends TaipyBaseAction {
name: string;
create: boolean;
}
export interface FormatConfig {
timeZone: string;
forceTZ: boolean;
date: string;
dateTime: string;
number: string;
}
const getUserTheme = (mode: PaletteMode) => {
const tkTheme = (window.taipyConfig?.stylekit && stylekitTheme) || {};
const tkModeTheme = (window.taipyConfig?.stylekit && stylekitModeThemes[mode]) || {};
const userTheme = window.taipyConfig?.themes?.base || {};
const modeTheme = (window.taipyConfig?.themes && window.taipyConfig.themes[mode]) || {};
return createTheme(
merge(tkTheme, tkModeTheme, userTheme, modeTheme, {
palette: {
mode: mode,
},
components: {
MuiUseMediaQuery: {
defaultProps: {
noSsr: true,
},
},
},
})
);
};
const themes = {
light: getUserTheme("light"),
dark: getUserTheme("dark"),
};
export const INITIAL_STATE: TaipyState = {
data: {},
theme: window.taipyConfig?.darkMode ? themes.dark : themes.light,
locations: {},
timeZone: window.taipyConfig?.timeZone
? window.taipyConfig.timeZone === "client"
? TIMEZONE_CLIENT
: window.taipyConfig.timeZone
: undefined,
id: getLocalStorageValue(TAIPY_CLIENT_ID, ""),
menu: {},
ackList: [],
notifications: [],
};
export const taipyInitialize = (initialState: TaipyState): TaipyState => ({
...initialState,
isSocketConnected: false,
socket: io("/", { autoConnect: false, path: `${getBaseURL()}socket.io` }),
});
export const messageToAction = (message: WsMessage) => {
if (message.type) {
if (message.type === "MU" && Array.isArray(message.payload)) {
return createMultipleUpdateAction(message.payload as NamePayload[]);
} else if (message.type === "U") {
return createUpdateAction(message as unknown as NamePayload);
} else if (message.type === "AL") {
return createNotificationAction(message as unknown as NotificationMessage);
} else if (message.type === "BL") {
return createBlockAction(message as unknown as BlockMessage);
} else if (message.type === "NA") {
return createNavigateAction(
(message as unknown as NavigateMessage).to,
(message as unknown as NavigateMessage).params,
(message as unknown as NavigateMessage).tab,
(message as unknown as NavigateMessage).force
);
} else if (message.type === "ID") {
return createIdAction((message as unknown as IdMessage).id);
} else if (message.type === "DF") {
return createDownloadAction(message as unknown as FileDownloadProps);
} else if (message.type === "PR") {
return createPartialAction((message as unknown as Record<string, string>).name, true);
} else if (message.type === "ACK") {
return createAckAction((message as unknown as IdMessage).id);
} else if (message.type === "FV") {
changeFavicon((message.payload as Record<string, string>)?.value);
} else if (message.type == "BC") {
stackBroadcast((message as NamePayload).name, (message as NamePayload).payload.value);
} else if (message.type == "GA") {
checkGuiAddr((message.payload as Record<string, string>).id);
}
}
return {} as TaipyBaseAction;
};
export const getWsMessageListener = (dispatch: Dispatch<TaipyBaseAction>) => {
const dispatchWsMessage = (message: WsMessage) => {
if (message.type === "MU" && Array.isArray(message.payload)) {
const payloads = message.payload as NamePayload[];
Promise.all(payloads.map((pl) => parseData(pl.payload.value as Record<string, unknown>)))
.then((values) => {
values.forEach((val, idx) => (payloads[idx].payload.value = val));
dispatch(messageToAction(message));
})
.catch(console.warn);
return;
} else if (message.type === "MS" && Array.isArray(message.payload)) {
(message.payload as WsMessage[]).forEach((msg) => dispatchWsMessage(msg));
return;
}
dispatch(messageToAction(message));
};
return dispatchWsMessage;
};
// Broadcast
const __BroadcastRepo: Record<string, Array<unknown>> = {};
const stackBroadcast = (name: string, value: unknown) =>
(__BroadcastRepo[name] = __BroadcastRepo[name] || []).push(value);
const broadcast_timeout = 250;
const initializeBroadcastManagement = (dispatch: Dispatch<TaipyBaseAction>) => {
setInterval(() => {
Object.entries(__BroadcastRepo).forEach(([name, stack]) => {
const broadcastValue = stack.shift();
if (broadcastValue !== undefined) {
dispatch(createUpdateAction({ name, payload: { value: broadcastValue } }));
}
});
}, broadcast_timeout);
};
// Gui Address
const checkGuiAddr = (guiAddr: string) => {
if (!guiAddr) {
return;
}
guiAddr = `${guiAddr}`;
const localGuiAddr = getLocalStorageValue(TAIPY_GUI_ADDR, "");
if (!localGuiAddr || localGuiAddr !== guiAddr) {
localStorage && localStorage.setItem(TAIPY_GUI_ADDR, guiAddr);
if (localGuiAddr) {
console.info("Taipy GUI address changed, reloading the page");
window.location.assign(getBaseURL());
}
}
};
let lastReasonServer = false;
// web socket
export const initializeWebSocket = (socket: Socket | undefined, dispatch: Dispatch<TaipyBaseAction>): void => {
if (socket) {
// Websocket confirm successful initialization
socket.on("connect", () => {
const id = getLocalStorageValue(TAIPY_CLIENT_ID, "");
const payload: Record<string, unknown> = { id };
if (lastReasonServer) {
payload["gui_addr"] = Number(getLocalStorageValue(TAIPY_GUI_ADDR, ""));
}
sendWsMessage(socket, "ID", TAIPY_CLIENT_ID, payload, id, undefined, false, () => {
dispatch({ type: Types.SocketConnected });
});
});
// try to reconnect on connect_error
socket.on("connect_error", (error) => {
if (error && (error as unknown as Record<string, unknown>).type === "TransportError") {
lastReasonServer = true;
}
setTimeout(() => socket.connect(), 500);
});
// try to reconnect on server disconnection
socket.on("disconnect", (reason) => {
if (reason === "io server disconnect") {
lastReasonServer = true;
socket.connect();
}
});
// handle message data from backend
socket.on("message", getWsMessageListener(dispatch));
// only now does the socket tries to open/connect
socket.connect();
// favicon
changeFavicon();
// broadcast
initializeBroadcastManagement(dispatch);
}
};
export const addRows = (previousRows: Record<string, unknown>[], newRows: Record<string, unknown>[], start: number) =>
newRows.reduce((arr, row) => {
arr[start++] = row;
return arr;
}, previousRows.concat([]));
export const storeBlockUi = (block?: BlockMessage) => () => {
if (localStorage) {
if (block) {
document.visibilityState !== "visible" && localStorage.setItem("TaipyBlockUi", JSON.stringify(block));
} else {
localStorage.removeItem("TaipyBlockUi");
}
}
};
export const retrieveBlockUi = (): BlockMessage => {
if (localStorage) {
const val = localStorage.getItem("TaipyBlockUi");
if (val) {
try {
return JSON.parse(val);
} catch {
// too bad
}
}
}
return {} as BlockMessage;
};
export const taipyReducer = (state: TaipyState, baseAction: TaipyBaseAction): TaipyState => {
const action = baseAction as TaipyAction;
let ackId = "";
switch (action.type) {
case Types.SocketConnected:
return !!state.isSocketConnected ? state : { ...state, isSocketConnected: true };
case Types.Update:
const newValue = action.payload.value as Record<string, unknown>;
const oldValue = (state.data[action.name] as Record<string, unknown>) || {};
delete oldValue.__taipy_refresh;
if (typeof action.payload.infinite === "boolean" && action.payload.infinite) {
const start = newValue.start;
if (typeof start === "number") {
const rows = ((oldValue[action.payload.pagekey as string] &&
(oldValue[action.payload.pagekey as string] as Record<string, unknown>).data) ||
[]) as Record<string, unknown>[];
newValue.data = addRows(rows, newValue.data as Record<string, unknown>[], start);
}
}
return {
...state,
data: {
...state.data,
[action.name]: action.payload.pagekey
? { ...oldValue, [action.payload.pagekey as string]: newValue }
: newValue,
},
};
case Types.SetLocations:
return { ...state, locations: action.payload.value as Record<string, string> };
case Types.SetNotification:
const notificationAction = action as unknown as TaipyNotificationAction;
return {
...state,
notifications: [
...state.notifications,
{
nType: notificationAction.nType,
message: notificationAction.message,
system: notificationAction.system,
duration: notificationAction.duration,
notificationId: notificationAction.notificationId,
snackbarId: notificationAction.nType ? nanoid() : notificationAction.nType,
onClose: notificationAction?.onClose,
},
],
};
case Types.DeleteNotification:
const deleteNotificationAction = action as unknown as TaipyNotificationAction;
return {
...state,
notifications: state.notifications.filter(
(notification) => notification.snackbarId !== deleteNotificationAction.snackbarId
),
};
case Types.SetBlock:
const blockAction = action as unknown as TaipyBlockAction;
if (blockAction.close) {
storeBlockUi()();
delete state.block;
return { ...state };
} else {
document.onvisibilitychange = storeBlockUi(blockAction as BlockMessage);
return {
...state,
block: {
noCancel: blockAction.noCancel,
action: blockAction.action,
close: false,
message: blockAction.message,
},
};
}
case Types.Navigate:
return {
...state,
navigateTo: (action as unknown as TaipyNavigateAction).to,
navigateParams: (action as unknown as TaipyNavigateAction).params,
navigateTab: (action as unknown as TaipyNavigateAction).tab,
navigateForce: (action as unknown as TaipyNavigateAction).force,
};
case Types.ClientId:
const id = (action as unknown as TaipyIdAction).id;
storeClientId(id);
return { ...state, id: id };
case Types.Acknowledgement:
const ackList = state.ackList.filter((v) => v !== (action as unknown as TaipyAckAction).id);
return ackList.length < state.ackList.length ? { ...state, ackList } : state;
case Types.SetTheme: {
let mode = action.payload.value as PaletteMode;
if (action.payload.fromBackend) {
mode = getLocalStorageValue("theme", mode, ["light", "dark"]);
}
localStorage && localStorage.setItem("theme", mode);
if (mode !== state.theme.palette.mode) {
return {
...state,
theme: themes[mode],
};
}
return state;
}
case Types.SetTimeZone: {
let timeZone = (action.payload.timeZone as string) || "client";
if (!action.payload.fromBackend) {
timeZone = getLocalStorageValue("timeZone", timeZone);
}
if (!timeZone || timeZone === "client") {
timeZone = TIMEZONE_CLIENT;
}
localStorage && localStorage.setItem("timeZone", timeZone);
if (timeZone !== state.timeZone) {
return {
...state,
timeZone: timeZone,
};
}
return state;
}
case Types.SetMenu: {
const mAction = baseAction as TaipySetMenuAction;
return { ...state, menu: mAction.menu };
}
case Types.DownloadFile: {
const dAction = baseAction as TaipyDownloadAction;
if (dAction.content === undefined) {
delete state.download;
return { ...state };
}
return { ...state, download: { content: dAction.content, name: dAction.name, onAction: dAction.onAction, context: dAction.context } };
}
case Types.Partial: {
const pAction = baseAction as TaipyPartialAction;
const data = { ...state.data };
if (pAction.create) {
data[pAction.name] = true;
} else {
data[pAction.name] !== undefined && delete data[pAction.name];
}
return { ...state, data: data };
}
case Types.MultipleUpdate:
const mAction = baseAction as TaipyMultipleAction;
return mAction.payload.reduce((nState, pl) => taipyReducer(nState, { ...pl, type: Types.Update }), state);
case Types.MultipleMessages:
const msgAction = baseAction as TaipyMultipleMessageAction;
return msgAction.actions.reduce((pState, act) => taipyReducer(pState, act), state);
case Types.SendUpdate:
ackId = sendWsMessage(
state.socket,
"U",
action.name,
action.payload,
state.id,
action.context,
action.propagate
);
break;
case Types.Action:
ackId = sendWsMessage(state.socket, "A", action.name, action.payload, state.id, action.context);
break;
case Types.RequestDataUpdate:
ackId = sendWsMessage(state.socket, "DU", action.name, action.payload, state.id, action.context);
break;
case Types.RequestUpdate:
ackId = sendWsMessage(state.socket, "RU", action.name, action.payload, state.id, action.context);
break;
case Types.LocalStorage:
ackId = sendWsMessage(state.socket, "LS", action.name, action.payload, state.id, action.context);
break;
}
if (ackId) return { ...state, ackList: [...state.ackList, ackId] };
return state;
};
export const createUpdateAction = (payload: NamePayload): TaipyAction => ({
...payload,
type: Types.Update,
});
export const createMultipleUpdateAction = (payload: NamePayload[]): TaipyMultipleAction => ({
type: Types.MultipleUpdate,
payload: payload,
});
/**
* Create a *send update* `Action` that will be used to update `Context`.
*
* This action will update the variable *name* (if *propagate* is true) and trigger the
* invocation of the `on_change` Python function on the backend.
* @param name - The name of the variable holding the requested data
* as received as a property.
* @param value - The new value for the variable named *name*.
* @param context - The execution context.
* @param onChange - The name of the `on_change` Python function to
* invoke on the backend (default is "on_change").
* @param propagate - A flag indicating that the variable should be
* automatically updated on the backend.
* @param relName - The name of the related variable (for
* example the lov when a lov value is updated).
* @returns The action fed to the reducer.
*/
export const createSendUpdateAction = (
name = "",
value: unknown,
context: string | undefined,
onChange?: string,
propagate = true,
relName?: string
): TaipyAction => ({
type: Types.SendUpdate,
name: name,
context: context,
propagate: propagate,
payload: getPayload(value, onChange, relName),
});
export const getPayload = (value: unknown, onChange?: string, relName?: string) => {
const ret: Record<string, unknown> = { value: value };
if (relName) {
ret.relvar = relName;
}
if (onChange) {
ret.on_change = onChange;
}
return ret;
};
/**
* Create an *action* `Action` that will be used to update `Context`.
*
* This action will trigger the invocation of the `on_action` Python function on the backend,
* providing all the parameters as a payload.
* @param name - The name of the action function on the backend.
* @param context - The execution context.
* @param value - The value associated with the action. This can be an object or
* any type of value.
* @param args - Additional information associated to the action.
* @returns The action fed to the reducer.
*/
export const createSendActionNameAction = (
name: string | undefined,
context: string | undefined,
value: unknown,
...args: unknown[]
): TaipyAction => ({
type: Types.Action,
name: name || "",
context: context,
payload:
typeof value === "object" && !Array.isArray(value) && value !== null
? { ...(value as object), args: args }
: { action: value, args: args },
});
export const createRequestChartUpdateAction = (
name: string | undefined,
id: string | undefined,
context: string | undefined,
columns: string[],
pageKey: string,
decimatorPayload: unknown | undefined
): TaipyAction =>
createRequestDataUpdateAction(
name,
id,
context,
columns,
pageKey,
{
decimatorPayload: decimatorPayload,
},
true
);
export const createRequestTableUpdateAction = (
name: string | undefined,
id: string | undefined,
context: string | undefined,
columns: string[],
pageKey: string,
start?: number,
end?: number,
orderBy?: string,
sort?: string,
aggregates?: string[],
applies?: Record<string, unknown>,
styles?: Record<string, string>,
tooltips?: Record<string, string>,
formats?: Record<string, string>,
handleNan?: boolean,
filters?: Array<FilterDesc>,
compare?: string,
compareDatas?: string,
stateContext?: Record<string, unknown>
): TaipyAction =>
createRequestDataUpdateAction(
name,
id,
context,
columns,
pageKey,
lightenPayload({
start,
end,
orderby: orderBy,
sort,
aggregates,
applies,
styles,
tooltips,
formats,
handlenan: handleNan,
filters,
compare,
compare_datas: compareDatas,
state_context: stateContext,
})
);
export const createRequestInfiniteTableUpdateAction = (
name: string | undefined,
id: string | undefined,
context: string | undefined,
columns: string[],
pageKey: string,
start?: number,
end?: number,
orderBy?: string,
sort?: string,
aggregates?: string[],
applies?: Record<string, unknown>,
styles?: Record<string, string>,
tooltips?: Record<string, string>,
formats?: Record<string, string>,
handleNan?: boolean,
filters?: Array<FilterDesc>,
compare?: string,
compareDatas?: string,
stateContext?: Record<string, unknown>,
reverse?: boolean
): TaipyAction =>
createRequestDataUpdateAction(
name,
id,
context,
columns,
pageKey,
lightenPayload({
infinite: true,
start,
end,
orderby: orderBy,
sort,
aggregates,
applies,
styles,
tooltips,
formats,
handlenan: handleNan,
filters,
compare,
compare_datas: compareDatas,
state_context: stateContext,
reverse: !!reverse,
})
);
/**
* Create a *request data update* `Action` that will be used to update the `Context`.
*
* This action will provoke the invocation of the `get_data()` method of the backend
* library. That invocation generates an update of the elements holding the data named
* *name* on the front-end.
* @param name - The name of the variable holding the requested data as received as
* a property.
* @param id - The identifier of the visual element.
* @param context - The execution context.
* @param columns - The list of the columns needed by the element that emitted this
* action.
* @param pageKey - The unique identifier of the data that will be received from
* this action.
* @param payload - The payload (specific to the type of component
* ie table, chart...).
* @param allData - The flag indicating if all the data is requested.
* @param library - The name of the {@link extension} library.
* @returns The action fed to the reducer.
*/
export const createRequestDataUpdateAction = (
name: string | undefined,
id: string | undefined,
context: string | undefined,
columns: string[],
pageKey: string,
payload: Record<string, unknown>,
allData = false,
library?: string
): TaipyAction => {
payload = payload || {};
if (id !== undefined) {
payload.id = id;
}
payload.columns = columns;
payload.pagekey = pageKey;
if (library !== undefined) {
payload.library = library;
}
if (allData) {
payload.alldata = true;
}
return {
type: Types.RequestDataUpdate,
name: name || "",
context: context,
payload: payload,
};
};
/**
* Create a *request update* `Action` that will be used to update the `Context`.
*
* This action will generate an update of the elements holding the variables named
* *names* on the front-end.
* @param id - The identifier of the visual element.
* @param context - The execution context.
* @param names - The names of the requested variables as received in updateVarName and/or updateVars properties.
* @param forceRefresh - Should Taipy re-evaluate the variables or use the current values
* @returns The action fed to the reducer.
*/
export const createRequestUpdateAction = (
id: string | undefined,
context: string | undefined,
names: string[],
forceRefresh = false,
stateContext?: Record<string, unknown>
): TaipyAction => ({
type: Types.RequestUpdate,
name: "",
context: context,
payload: lightenPayload({
id: id,
names: names,
refresh: forceRefresh,
state_context: stateContext,
}),
});
export const createSetLocationsAction = (locations: Record<string, string>): TaipyAction => ({
type: Types.SetLocations,
name: "locations",
payload: { value: locations },
});
export const createThemeAction = (dark: boolean, fromBackend = false): TaipyAction => ({
type: Types.SetTheme,
name: "theme",
payload: { value: dark ? "dark" : "light", fromBackend: fromBackend },
});
export const createTimeZoneAction = (timeZone: string, fromBackend = false): TaipyAction => ({
type: Types.SetTimeZone,
name: "timeZone",
payload: { timeZone: timeZone, fromBackend: fromBackend },
});
const getNotificationType = (nType: string) => {
nType = nType.trim();
if (nType) {
nType = nType.charAt(0).toLowerCase();
switch (nType) {
case "e":
return "error";
case "w":
return "warning";
case "s":
return "success";
default:
return "info";
}
}
return nType;
};
export const createNotificationAction = (notification: NotificationMessage): TaipyNotificationAction => ({
type: Types.SetNotification,
nType: getNotificationType(notification.nType),
message: notification.message,
system: notification.system,
duration: notification.duration,
notificationId: notification.notificationId,
snackbarId: notification.snackbarId,
onClose: notification?.onClose,
});
export const createDeleteNotificationAction = (snackbarId: string): TaipyDeleteNotificationAction => {
return {
type: Types.DeleteNotification,
snackbarId,
}
}
export const createBlockAction = (block: BlockMessage): TaipyBlockAction => ({
type: Types.SetBlock,
noCancel: block.noCancel,
action: block.action || "",
close: !!block.close,
message: block.message,
});
export const createNavigateAction = (
to?: string,
params?: Record<string, string>,
tab?: string,
force?: boolean
): TaipyNavigateAction => ({
type: Types.Navigate,
to,
params,
tab,
force,
});
export const createIdAction = (id: string): TaipyIdAction => ({
type: Types.ClientId,
id,
});
export const createAckAction = (id: string): TaipyAckAction => ({
type: Types.Acknowledgement,
id,
});
export const createDownloadAction = (dMessage?: FileDownloadProps): TaipyDownloadAction => ({
type: Types.DownloadFile,
content: dMessage?.content,
name: dMessage?.name,
onAction: dMessage?.onAction,
context: dMessage?.context,
});
export const createSetMenuAction = (menu: MenuProps): TaipySetMenuAction => ({
type: Types.SetMenu,
menu,
});
export const createPartialAction = (name: string, create: boolean): TaipyPartialAction => ({
type: Types.Partial,
name,
create,
});
export const createLocalStorageAction = (localStorageData: Record<string, string>): TaipyAction => ({
type: Types.LocalStorage,
name: "",
payload: localStorageData,
});