-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
App.tsx
1797 lines (1608 loc) · 56 KB
/
App.tsx
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
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2024)
*
* 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 React, { PureComponent, ReactNode } from "react"
import moment from "moment"
import { HotKeys, KeyMap } from "react-hotkeys"
import { enableAllPlugins as enableImmerPlugins } from "immer"
import classNames from "classnames"
// Other local imports.
import { AppContext } from "@streamlit/app/src/components/AppContext"
import AppView from "@streamlit/app/src/components/AppView"
import StatusWidget from "@streamlit/app/src/components/StatusWidget"
import MainMenu, { isLocalhost } from "@streamlit/app/src/components/MainMenu"
import ToolbarActions from "@streamlit/app/src/components/ToolbarActions"
import DeployButton from "@streamlit/app/src/components/DeployButton"
import Header from "@streamlit/app/src/components/Header"
import {
DialogProps,
DialogType,
StreamlitDialog,
} from "@streamlit/app/src/components/StreamlitDialog"
import { ConnectionManager } from "@streamlit/app/src/connection/ConnectionManager"
import { ConnectionState } from "@streamlit/app/src/connection/ConnectionState"
import { SessionEventDispatcher } from "@streamlit/app/src/SessionEventDispatcher"
import {
generateUID,
getElementWidgetID,
getEmbeddingIdClassName,
getIFrameEnclosingApp,
hashString,
isColoredLineDisplayed,
isEmbed,
isInChildFrame,
isPaddingDisplayed,
isScrollingHidden,
isToolbarDisplayed,
notUndefined,
setCookie,
extractPageNameFromPathName,
BaseUriParts,
RERUN_PROMPT_MODAL_DIALOG,
SessionInfo,
FileUploadClient,
logError,
logMessage,
AppRoot,
ComponentRegistry,
handleFavicon,
createAutoTheme,
createTheme,
CUSTOM_THEME_NAME,
getCachedTheme,
isPresetTheme,
ThemeConfig,
toExportedTheme,
StreamlitEndpoints,
ensureError,
LibContext,
AppPage,
BackMsg,
Config,
CustomThemeConfig,
Delta,
FileURLsResponse,
ForwardMsg,
ForwardMsgMetadata,
GitInfo,
IAppPage,
IGitInfo,
Initialize,
NewSession,
PageConfig,
PageInfo,
PageNotFound,
PageProfile,
PagesChanged,
ParentMessage,
SessionEvent,
SessionStatus,
WidgetStates,
ScriptRunState,
HostCommunicationManager,
IMenuItem,
IToolbarItem,
DeployedAppMetadata,
PerformanceEvents,
createFormsData,
FormsData,
WidgetStateManager,
IHostConfigResponse,
LibConfig,
AppConfig,
} from "@streamlit/lib"
import without from "lodash/without"
import { UserSettings } from "@streamlit/app/src/components/StreamlitDialog/UserSettings"
import { DefaultStreamlitEndpoints } from "@streamlit/app/src/connection/DefaultStreamlitEndpoints"
import { SegmentMetricsManager } from "@streamlit/app/src/SegmentMetricsManager"
import { StyledApp } from "@streamlit/app/src/styled-components"
import withScreencast, {
ScreenCastHOC,
} from "@streamlit/app/src/hocs/withScreencast/withScreencast"
// Used to import fonts + responsive reboot items
import "@streamlit/app/src/assets/css/theme.scss"
import { preserveEmbedQueryParams } from "@streamlit/lib/src/util/utils"
import { ThemeManager } from "./util/useThemeManager"
export interface Props {
screenCast: ScreenCastHOC
theme: ThemeManager
}
interface State {
connectionState: ConnectionState
elements: AppRoot
isFullScreen: boolean
scriptRunId: string
scriptName: string
appHash: string | null
scriptRunState: ScriptRunState
userSettings: UserSettings
dialog?: DialogProps | null
layout: PageConfig.Layout
initialSidebarState: PageConfig.SidebarState
menuItems?: PageConfig.IMenuItems | null
allowRunOnSave: boolean
scriptFinishedHandlers: (() => void)[]
toolbarMode: Config.ToolbarMode
themeHash: string
gitInfo: IGitInfo | null
formsData: FormsData
hideTopBar: boolean
hideSidebarNav: boolean
appPages: IAppPage[]
currentPageScriptHash: string
latestRunTime: number
// host communication info
isOwner: boolean
hostMenuItems: IMenuItem[]
hostToolbarItems: IToolbarItem[]
hostHideSidebarNav: boolean
sidebarChevronDownshift: number
pageLinkBaseUrl: string
queryParams: string
deployedAppMetadata: DeployedAppMetadata
libConfig: LibConfig
appConfig: AppConfig
inputsDisabled: boolean
}
const ELEMENT_LIST_BUFFER_TIMEOUT_MS = 10
const INITIAL_SCRIPT_RUN_ID = "<null>"
// eslint-disable-next-line
declare global {
interface Window {
streamlitDebug: any
iFrameResizer: any
}
}
export const showDevelopmentOptions = (
hostIsOwner: boolean | undefined,
toolbarMode: Config.ToolbarMode
): boolean => {
if (toolbarMode == Config.ToolbarMode.DEVELOPER) {
return true
}
if (
Config.ToolbarMode.VIEWER == toolbarMode ||
Config.ToolbarMode.MINIMAL == toolbarMode
) {
return false
}
return hostIsOwner || isLocalhost()
}
export class App extends PureComponent<Props, State> {
private readonly endpoints: StreamlitEndpoints
private readonly sessionInfo = new SessionInfo()
private readonly metricsMgr = new SegmentMetricsManager(this.sessionInfo)
private readonly sessionEventDispatcher = new SessionEventDispatcher()
private connectionManager: ConnectionManager | null
private readonly widgetMgr: WidgetStateManager
private readonly hostCommunicationMgr: HostCommunicationManager
private readonly uploadClient: FileUploadClient
/**
* When new Deltas are received, they are applied to `pendingElementsBuffer`
* rather than directly to `this.state.elements`. We assign
* `pendingElementsBuffer` to `this.state` on a timer, in order to
* decouple Delta updates from React re-renders, for performance reasons.
*
* (If `pendingElementsBuffer === this.state.elements` - the default state -
* then we have no pending elements.)
*/
private pendingElementsBuffer: AppRoot
private pendingElementsTimerRunning: boolean
private readonly componentRegistry: ComponentRegistry
private readonly embeddingId: string = generateUID()
public constructor(props: Props) {
super(props)
// Initialize immerjs
enableImmerPlugins()
this.state = {
connectionState: ConnectionState.INITIAL,
elements: AppRoot.empty(true),
isFullScreen: false,
scriptName: "",
scriptRunId: INITIAL_SCRIPT_RUN_ID,
appHash: null,
scriptRunState: ScriptRunState.NOT_RUNNING,
userSettings: {
wideMode: false,
runOnSave: false,
},
layout: PageConfig.Layout.CENTERED,
initialSidebarState: PageConfig.SidebarState.AUTO,
menuItems: undefined,
allowRunOnSave: true,
scriptFinishedHandlers: [],
themeHash: this.createThemeHash(),
gitInfo: null,
formsData: createFormsData(),
appPages: [],
currentPageScriptHash: "",
// We set hideTopBar to true by default because this information isn't
// available on page load (we get it when the script begins to run), so
// the user would see top bar elements for a few ms if this defaulted to
// false. hideSidebarNav doesn't have this issue (app pages and the value
// of the config option are received simultaneously), but we set it to
// true as well for consistency.
hideTopBar: true,
hideSidebarNav: true,
toolbarMode: Config.ToolbarMode.MINIMAL,
latestRunTime: performance.now(),
// Information sent from the host
isOwner: false,
hostMenuItems: [],
hostToolbarItems: [],
hostHideSidebarNav: false,
sidebarChevronDownshift: 0,
pageLinkBaseUrl: "",
queryParams: "",
deployedAppMetadata: {},
libConfig: {},
appConfig: {},
inputsDisabled: false,
}
this.connectionManager = null
this.widgetMgr = new WidgetStateManager({
sendRerunBackMsg: this.sendRerunBackMsg,
formsDataChanged: formsData => this.setState({ formsData }),
})
this.hostCommunicationMgr = new HostCommunicationManager({
sendRerunBackMsg: this.sendRerunBackMsg,
closeModal: this.closeDialog,
stopScript: this.stopScript,
rerunScript: this.rerunScript,
clearCache: this.clearCache,
sendAppHeartbeat: this.sendAppHeartbeat,
setInputsDisabled: inputsDisabled => {
this.setState({ inputsDisabled })
},
themeChanged: this.props.theme.setImportedTheme,
pageChanged: this.onPageChange,
isOwnerChanged: isOwner => this.setState({ isOwner }),
jwtHeaderChanged: ({ jwtHeaderName, jwtHeaderValue }) => {
if (
this.endpoints.setJWTHeader !== undefined &&
this.state.appConfig.useExternalAuthToken
) {
this.endpoints.setJWTHeader({ jwtHeaderName, jwtHeaderValue })
}
},
hostMenuItemsChanged: hostMenuItems => {
this.setState({ hostMenuItems })
},
hostToolbarItemsChanged: hostToolbarItems => {
this.setState({ hostToolbarItems })
},
hostHideSidebarNavChanged: hostHideSidebarNav => {
this.setState({ hostHideSidebarNav })
},
sidebarChevronDownshiftChanged: sidebarChevronDownshift => {
this.setState({ sidebarChevronDownshift })
},
pageLinkBaseUrlChanged: pageLinkBaseUrl => {
this.setState({ pageLinkBaseUrl })
},
queryParamsChanged: queryParams => {
this.setState({ queryParams })
},
deployedAppMetadataChanged: deployedAppMetadata => {
this.setState({ deployedAppMetadata })
},
})
this.endpoints = new DefaultStreamlitEndpoints({
getServerUri: this.getBaseUriParts,
csrfEnabled: true,
})
this.uploadClient = new FileUploadClient({
sessionInfo: this.sessionInfo,
endpoints: this.endpoints,
// A form cannot be submitted if it contains a FileUploader widget
// that's currently uploading. We write that state here, in response
// to a FileUploadClient callback. The FormSubmitButton element
// reads the state.
formsWithPendingRequestsChanged: formIds =>
this.widgetMgr.setFormsWithUploads(formIds),
requestFileURLs: this.requestFileURLs,
})
this.componentRegistry = new ComponentRegistry(this.endpoints)
this.pendingElementsTimerRunning = false
this.pendingElementsBuffer = this.state.elements
window.streamlitDebug = {
clearForwardMsgCache: this.debugClearForwardMsgCache,
disconnectWebsocket: this.debugDisconnectWebsocket,
shutdownRuntime: this.debugShutdownRuntime,
}
}
/**
* Global keyboard shortcuts.
*/
keyMap: KeyMap = {
RERUN: "r",
CLEAR_CACHE: "c",
// We use key up for stop recording to ensure the esc key doesn't trigger
// other actions (like exiting modals)
STOP_RECORDING: { sequence: "esc", action: "keyup" },
}
keyHandlers = {
RERUN: () => {
this.rerunScript()
},
CLEAR_CACHE: () => {
if (showDevelopmentOptions(this.state.isOwner, this.state.toolbarMode)) {
this.openClearCacheDialog()
}
},
STOP_RECORDING: this.props.screenCast.stopRecording,
}
componentDidMount(): void {
// Initialize connection manager here, to avoid
// "Can't call setState on a component that is not yet mounted." error.
this.connectionManager = new ConnectionManager({
sessionInfo: this.sessionInfo,
endpoints: this.endpoints,
onMessage: this.handleMessage,
onConnectionError: this.handleConnectionError,
connectionStateChanged: this.handleConnectionStateChanged,
claimHostAuthToken: this.hostCommunicationMgr.claimAuthToken,
resetHostAuthToken: this.hostCommunicationMgr.resetAuthToken,
onHostConfigResp: (response: IHostConfigResponse) => {
const {
allowedOrigins,
useExternalAuthToken,
disableFullscreenMode,
enableCustomParentMessages,
mapboxToken,
} = response
const appConfig: AppConfig = {
allowedOrigins,
useExternalAuthToken,
enableCustomParentMessages,
}
const libConfig: LibConfig = { mapboxToken, disableFullscreenMode }
// Set the allowed origins configuration for the host communication:
this.hostCommunicationMgr.setAllowedOrigins(appConfig)
// Set the streamlit-app specific config settings in AppContext:
this.setAppConfig(appConfig)
// Set the streamlit-lib specific config settings in LibContext:
this.setLibConfig(libConfig)
},
})
if (isScrollingHidden()) {
document.body.classList.add("embedded")
}
// Iframe resizer allows parent pages to get the height of the iframe
// contents. The parent page can then reset the height to match and
// avoid unnecessary scrollbars or large embeddings
if (isInChildFrame()) {
window.iFrameResizer = {
heightCalculationMethod: () => {
const taggedEls = document.querySelectorAll("[data-iframe-height]")
// Use ceil to avoid fractional pixels creating scrollbars.
const lowestBounds = Array.from(taggedEls).map(el =>
Math.ceil(el.getBoundingClientRect().bottom)
)
// The higher the value, the further down the page it is.
// Use maximum value to get the lowest of all tagged elements.
return Math.max(0, ...lowestBounds)
},
}
// @ts-expect-error
import("iframe-resizer/js/iframeResizer.contentWindow")
}
this.hostCommunicationMgr.sendMessageToHost({
type: "SET_THEME_CONFIG",
themeInfo: toExportedTheme(this.props.theme.activeTheme.emotion),
})
this.hostCommunicationMgr.sendMessageToHost({
type: "SCRIPT_RUN_STATE_CHANGED",
scriptRunState: this.state.scriptRunState,
})
this.metricsMgr.enqueue("viewReport")
window.addEventListener("popstate", this.onHistoryChange, false)
}
componentDidUpdate(
prevProps: Readonly<Props>,
prevState: Readonly<State>
): void {
// @ts-expect-error
if (window.prerenderReady === false && this.isAppInReadyState(prevState)) {
// @ts-expect-error
window.prerenderReady = true
}
if (this.state.scriptRunState !== prevState.scriptRunState) {
this.hostCommunicationMgr.sendMessageToHost({
type: "SCRIPT_RUN_STATE_CHANGED",
scriptRunState: this.state.scriptRunState,
})
}
}
componentWillUnmount(): void {
// Needing to disconnect our connection manager + websocket connection is
// only needed here to handle the case in dev mode where react hot-reloads
// the client as a result of a source code change. In this scenario, the
// previous websocket connection is still connected, and the client and
// server end up in a reconnect loop because the server rejects attempts to
// connect to an already-connected session.
//
// This situation doesn't exist outside of dev mode because the whole App
// unmounting is either a page refresh or the browser tab closing.
//
// The optional chaining on connectionManager is needed to make typescript
// happy since connectionManager's type is `ConnectionManager | null`,
// but at this point it should always be set.
this.connectionManager?.disconnect()
this.hostCommunicationMgr.closeHostCommunication()
window.removeEventListener("popstate", this.onHistoryChange, false)
}
showError(title: string, errorNode: ReactNode): void {
logError(errorNode)
const newDialog: DialogProps = {
type: DialogType.WARNING,
title,
msg: errorNode,
onClose: () => {},
}
this.openDialog(newDialog)
}
showDeployError = (
title: string,
errorNode: ReactNode,
onContinue?: () => void
): void => {
this.openDialog({
type: DialogType.DEPLOY_ERROR,
title,
msg: errorNode,
onContinue,
onClose: () => {},
onTryAgain: this.sendLoadGitInfoBackMsg,
})
}
/**
* Checks if the code version from the backend is different than the frontend
*/
private hasStreamlitVersionChanged(initializeMsg: Initialize): boolean {
if (this.sessionInfo.isSet) {
const currentStreamlitVersion = this.sessionInfo.current.streamlitVersion
const { environmentInfo } = initializeMsg
if (
environmentInfo != null &&
environmentInfo.streamlitVersion != null
) {
return currentStreamlitVersion != environmentInfo.streamlitVersion
}
}
return false
}
/**
* Called by ConnectionManager when our connection state changes
*/
handleConnectionStateChanged = (newState: ConnectionState): void => {
logMessage(
`Connection state changed from ${this.state.connectionState} to ${newState}`
)
this.setState({ connectionState: newState })
if (newState === ConnectionState.CONNECTED) {
logMessage("Reconnected to server; requesting a script run")
this.widgetMgr.sendUpdateWidgetsMessage()
this.setState({ dialog: null })
} else {
setCookie("_streamlit_xsrf", "")
if (this.sessionInfo.isSet) {
this.sessionInfo.clearCurrent()
}
}
}
handleGitInfoChanged = (gitInfo: IGitInfo): void => {
this.setState({
gitInfo,
})
}
handleCustomParentMessage = (parentMessage: ParentMessage): void => {
if (this.state.appConfig.enableCustomParentMessages) {
this.hostCommunicationMgr.sendMessageToHost({
type: "CUSTOM_PARENT_MESSAGE",
message: parentMessage.message,
})
} else {
logError(
"Sending messages to the host is disabled in line with the platform policy."
)
}
}
/**
* Callback when we get a message from the server.
*/
handleMessage = (msgProto: ForwardMsg): void => {
// We don't have an immutableProto here, so we can't use
// the dispatchOneOf helper
const dispatchProto = (obj: any, name: string, funcs: any): any => {
const whichOne = obj[name]
if (whichOne in funcs) {
return funcs[whichOne](obj[whichOne])
}
throw new Error(`Cannot handle ${name} "${whichOne}".`)
}
try {
dispatchProto(msgProto, "type", {
newSession: (newSessionMsg: NewSession) =>
this.handleNewSession(newSessionMsg),
sessionStatusChanged: (msg: SessionStatus) =>
this.handleSessionStatusChanged(msg),
sessionEvent: (evtMsg: SessionEvent) =>
this.handleSessionEvent(evtMsg),
delta: (deltaMsg: Delta) =>
this.handleDeltaMsg(
deltaMsg,
msgProto.metadata as ForwardMsgMetadata
),
pageConfigChanged: (pageConfig: PageConfig) =>
this.handlePageConfigChanged(pageConfig),
pageInfoChanged: (pageInfo: PageInfo) =>
this.handlePageInfoChanged(pageInfo),
pagesChanged: (pagesChangedMsg: PagesChanged) =>
this.handlePagesChanged(pagesChangedMsg),
pageNotFound: (pageNotFound: PageNotFound) =>
this.handlePageNotFound(pageNotFound),
gitInfoChanged: (gitInfo: GitInfo) =>
this.handleGitInfoChanged(gitInfo),
scriptFinished: (status: ForwardMsg.ScriptFinishedStatus) =>
this.handleScriptFinished(status),
pageProfile: (pageProfile: PageProfile) =>
this.handlePageProfileMsg(pageProfile),
fileUrlsResponse: (fileURLsResponse: FileURLsResponse) =>
this.uploadClient.onFileURLsResponse(fileURLsResponse),
parentMessage: (parentMessage: ParentMessage) =>
this.handleCustomParentMessage(parentMessage),
})
} catch (e) {
const err = ensureError(e)
logError(err)
this.showError("Bad message format", err.message)
}
}
handlePageConfigChanged = (pageConfig: PageConfig): void => {
const { title, favicon, layout, initialSidebarState, menuItems } =
pageConfig
if (title) {
this.hostCommunicationMgr.sendMessageToHost({
type: "SET_PAGE_TITLE",
title,
})
document.title = title
}
if (favicon) {
handleFavicon(
favicon,
this.hostCommunicationMgr.sendMessageToHost,
this.endpoints
)
}
// Only change layout/sidebar when the page config has changed.
// This preserves the user's previous choice, and prevents extra re-renders.
if (layout !== this.state.layout) {
this.setState((prevState: State) => ({
layout,
userSettings: {
...prevState.userSettings,
wideMode: layout === PageConfig.Layout.WIDE,
},
}))
}
if (initialSidebarState !== this.state.initialSidebarState) {
this.setState(() => ({
initialSidebarState,
}))
}
this.setState({ menuItems })
}
handlePageInfoChanged = (pageInfo: PageInfo): void => {
const { queryString } = pageInfo
const targetUrl =
document.location.pathname + (queryString ? `?${queryString}` : "")
window.history.pushState({}, "", targetUrl)
this.hostCommunicationMgr.sendMessageToHost({
type: "SET_QUERY_PARAM",
queryParams: queryString ? `?${queryString}` : "",
})
}
handlePageNotFound = (pageNotFound: PageNotFound): void => {
const { pageName } = pageNotFound
const errMsg = pageName
? `You have requested page /${pageName}, but no corresponding file was found in the app's pages/ directory`
: "The page that you have requested does not seem to exist"
this.showError("Page not found", `${errMsg}. Running the app's main page.`)
const currentPageScriptHash = this.state.appPages[0]?.pageScriptHash || ""
this.setState({ currentPageScriptHash }, () => {
this.hostCommunicationMgr.sendMessageToHost({
type: "SET_CURRENT_PAGE_NAME",
currentPageName: "",
currentPageScriptHash,
})
})
}
handlePagesChanged = (pagesChangedMsg: PagesChanged): void => {
const { appPages } = pagesChangedMsg
this.setState({ appPages }, () => {
this.hostCommunicationMgr.sendMessageToHost({
type: "SET_APP_PAGES",
appPages,
})
})
}
handlePageProfileMsg = (pageProfile: PageProfile): void => {
this.metricsMgr.enqueue("pageProfile", {
...PageProfile.toObject(pageProfile),
appId: this.sessionInfo.current.appId,
numPages: this.state.appPages?.length,
sessionId: this.sessionInfo.current.sessionId,
pythonVersion: this.sessionInfo.current.pythonVersion,
pageScriptHash: this.state.currentPageScriptHash,
activeTheme: this.props.theme?.activeTheme?.name,
totalLoadTime: Math.round(
(performance.now() - this.state.latestRunTime) * 1000
),
})
}
/**
* Handler for ForwardMsg.sessionStatusChanged messages
* @param statusChangeProto a SessionStatus protobuf
*/
handleSessionStatusChanged = (statusChangeProto: SessionStatus): void => {
this.setState((prevState: State) => {
// Determine our new ScriptRunState
let { scriptRunState } = prevState
let { dialog } = prevState
if (
statusChangeProto.scriptIsRunning &&
prevState.scriptRunState !== ScriptRunState.STOP_REQUESTED
) {
// If the script is running, we change our ScriptRunState only
// if we don't have a pending stop request
scriptRunState = ScriptRunState.RUNNING
// If the scriptCompileError dialog is open and the script starts
// running, close it.
if (
dialog != null &&
dialog.type === DialogType.SCRIPT_COMPILE_ERROR
) {
dialog = undefined
}
} else if (
!statusChangeProto.scriptIsRunning &&
prevState.scriptRunState !== ScriptRunState.RERUN_REQUESTED &&
prevState.scriptRunState !== ScriptRunState.COMPILATION_ERROR
) {
// If the script is not running, we change our ScriptRunState only
// if we don't have a pending rerun request, and we don't have
// a script compilation failure
scriptRunState = ScriptRunState.NOT_RUNNING
const customComponentCounter =
this.metricsMgr.getAndResetCustomComponentCounter()
Object.entries(customComponentCounter).forEach(([name, count]) => {
this.metricsMgr.enqueue("customComponentStats", {
name,
count,
})
})
}
return {
userSettings: {
...prevState.userSettings,
runOnSave: Boolean(statusChangeProto.runOnSave),
},
dialog,
scriptRunState,
}
})
}
/**
* Handler for ForwardMsg.sessionEvent messages
* @param sessionEvent a SessionEvent protobuf
*/
handleSessionEvent = (sessionEvent: SessionEvent): void => {
this.sessionEventDispatcher.handleSessionEventMsg(sessionEvent)
if (sessionEvent.type === "scriptCompilationException") {
this.setState({ scriptRunState: ScriptRunState.COMPILATION_ERROR })
const newDialog: DialogProps = {
type: DialogType.SCRIPT_COMPILE_ERROR,
exception: sessionEvent.scriptCompilationException,
onClose: () => {},
}
this.openDialog(newDialog)
} else if (
RERUN_PROMPT_MODAL_DIALOG &&
sessionEvent.type === "scriptChangedOnDisk"
) {
const newDialog: DialogProps = {
type: DialogType.SCRIPT_CHANGED,
onRerun: this.rerunScript,
onClose: () => {},
allowRunOnSave: this.state.allowRunOnSave,
}
this.openDialog(newDialog)
}
}
/**
* Handler for ForwardMsg.newSession messages. This runs on each rerun
* @param newSessionProto a NewSession protobuf
*/
handleNewSession = (newSessionProto: NewSession): void => {
const initialize = newSessionProto.initialize as Initialize
if (this.hasStreamlitVersionChanged(initialize)) {
window.location.reload()
return
}
// First, handle initialization logic. Each NewSession message has
// initialization data. If this is the _first_ time we're receiving
// the NewSession message, we perform some one-time initialization.
if (!this.sessionInfo.isSet) {
// We're not initialized. Perform one-time initialization.
this.handleOneTimeInitialization(newSessionProto)
}
const config = newSessionProto.config as Config
const themeInput = newSessionProto.customTheme as CustomThemeConfig
const { currentPageScriptHash: prevPageScriptHash } = this.state
const newPageScriptHash = newSessionProto.pageScriptHash
// mainPage must be a string as we're guaranteed at this point that
// newSessionProto.appPages is nonempty and has a truthy pageName.
// Otherwise, we'd either have no main script or a nameless main script,
// neither of which can happen.
const mainPage = newSessionProto.appPages[0] as AppPage
// We're similarly guaranteed that newPageName will be found / truthy
// here.
const newPageName = newSessionProto.appPages.find(
p => p.pageScriptHash === newPageScriptHash
)?.pageName as string
const viewingMainPage = newPageScriptHash === mainPage.pageScriptHash
const baseUriParts = this.getBaseUriParts()
if (baseUriParts) {
const { basePath } = baseUriParts
const prevPageNameInPath = extractPageNameFromPathName(
document.location.pathname,
basePath
)
const prevPageName =
prevPageNameInPath === "" ? mainPage.pageName : prevPageNameInPath
// It is important to compare `newPageName` with the previous one encoded in the URL
// to handle new session runs triggered by URL changes through the `onHistoryChange()` callback,
// e.g. the case where the user clicks the back button.
// See https://github.com/streamlit/streamlit/pull/6271#issuecomment-1465090690 for the discussion.
if (prevPageName !== newPageName) {
// If embed params need to be changed, make sure to change to other parts of the code that reference preserveEmbedQueryParams
const queryString = preserveEmbedQueryParams()
const qs = queryString ? `?${queryString}` : ""
const basePathPrefix = basePath ? `/${basePath}` : ""
const pagePath = viewingMainPage ? "" : newPageName
const pageUrl = `${basePathPrefix}/${pagePath}${qs}`
window.history.pushState({}, "", pageUrl)
}
}
this.processThemeInput(themeInput)
this.setState(
{
allowRunOnSave: config.allowRunOnSave,
hideTopBar: config.hideTopBar,
hideSidebarNav: config.hideSidebarNav,
toolbarMode: config.toolbarMode,
appPages: newSessionProto.appPages,
currentPageScriptHash: newPageScriptHash,
latestRunTime: performance.now(),
},
() => {
this.hostCommunicationMgr.sendMessageToHost({
type: "SET_APP_PAGES",
appPages: newSessionProto.appPages,
})
this.hostCommunicationMgr.sendMessageToHost({
type: "SET_CURRENT_PAGE_NAME",
currentPageName: viewingMainPage ? "" : newPageName,
currentPageScriptHash: newPageScriptHash,
})
}
)
const { appHash } = this.state
const { scriptRunId, name: scriptName, mainScriptPath } = newSessionProto
const newSessionHash = hashString(
this.sessionInfo.current.installationId + mainScriptPath
)
// Set the title and favicon to their default values
document.title = `${newPageName} · Streamlit`
handleFavicon(
`${process.env.PUBLIC_URL}/favicon.png`,
this.hostCommunicationMgr.sendMessageToHost,
this.endpoints
)
this.metricsMgr.setMetadata(this.state.deployedAppMetadata)
this.metricsMgr.setAppHash(newSessionHash)
this.metricsMgr.enqueue("updateReport", {
numPages: newSessionProto.appPages.length,
isMainPage: viewingMainPage,
})
if (
appHash === newSessionHash &&
prevPageScriptHash === newPageScriptHash
) {
this.setState({
scriptRunId,
})
} else {
this.clearAppState(newSessionHash, scriptRunId, scriptName)
}
}
/**
* Performs one-time initialization. This is called from `handleNewSession`.
*/
handleOneTimeInitialization = (newSessionProto: NewSession): void => {
const initialize = newSessionProto.initialize as Initialize
const config = newSessionProto.config as Config
this.sessionInfo.setCurrent(
SessionInfo.propsFromNewSessionMessage(newSessionProto)
)
this.metricsMgr.initialize({
gatherUsageStats: config.gatherUsageStats,
})
this.handleSessionStatusChanged(initialize.sessionStatus)
}
/**
* Handler called when the history state changes, e.g. `popstate` event.
*/
onHistoryChange = (): void => {
const targetAppPage =
this.state.appPages.find(appPage =>
// The page name is embedded at the end of the URL path, and if not, we are in the main page.
// See https://github.com/streamlit/streamlit/blob/1.19.0/frontend/src/App.tsx#L740
document.location.pathname.endsWith("/" + appPage.pageName)
) ?? this.state.appPages[0]
// do not cause a rerun when an anchor is clicked and we aren't changing pages
const hasAnchor = document.location.toString().includes("#")
const isSamePage =
targetAppPage?.pageScriptHash === this.state.currentPageScriptHash
if (targetAppPage == null || (hasAnchor && isSamePage)) {
return
}
this.onPageChange(targetAppPage.pageScriptHash as string)
}
/**
* Both sets the given theme locally and sends it to the host.
*/
setAndSendTheme = (themeConfig: ThemeConfig): void => {
this.props.theme.setTheme(themeConfig)
this.hostCommunicationMgr.sendMessageToHost({
type: "SET_THEME_CONFIG",
themeInfo: toExportedTheme(themeConfig.emotion),
})
}
createThemeHash = (themeInput?: CustomThemeConfig): string => {
if (!themeInput) {
// If themeInput is null, then we didn't receive a custom theme for this
// app from the server. We use a hardcoded string literal for the