-
Notifications
You must be signed in to change notification settings - Fork 145
/
Copy pathsurveys.tsx
970 lines (858 loc) · 34.2 KB
/
surveys.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
import { PostHog } from '../posthog-core'
import { doesSurveyUrlMatch } from '../posthog-surveys'
import {
Survey,
SurveyAppearance,
SurveyQuestion,
SurveyQuestionBranchingType,
SurveyQuestionType,
SurveyRenderReason,
SurveyType,
} from '../posthog-surveys-types'
import * as Preact from 'preact'
import { useContext, useEffect, useMemo, useRef, useState } from 'preact/hooks'
import { addEventListener } from '../utils'
import { document as _document, window as _window } from '../utils/globals'
import { createLogger } from '../utils/logger'
import { isNull, isNumber } from '../utils/type-utils'
import { createWidgetShadow, createWidgetStyle } from './surveys-widget'
import { ConfirmationMessage } from './surveys/components/ConfirmationMessage'
import { Cancel } from './surveys/components/QuestionHeader'
import {
LinkQuestion,
MultipleChoiceQuestion,
OpenTextQuestion,
RatingQuestion,
} from './surveys/components/QuestionTypes'
import {
createShadow,
defaultSurveyAppearance,
dismissedSurveyEvent,
getContrastingTextColor,
getDisplayOrderQuestions,
getSurveySeen,
hasWaitPeriodPassed,
sendSurveyEvent,
style,
SurveyContext,
} from './surveys/surveys-utils'
import { prepareStylesheet } from './utils/stylesheet-loader'
const logger = createLogger('[Surveys]')
// We cast the types here which is dangerous but protected by the top level generateSurveys call
const window = _window as Window & typeof globalThis
const document = _document as Document
function getRatingBucketForResponseValue(responseValue: number, scale: number) {
if (scale === 3) {
if (responseValue < 1 || responseValue > 3) {
throw new Error('The response must be in range 1-3')
}
return responseValue === 1 ? 'negative' : responseValue === 2 ? 'neutral' : 'positive'
} else if (scale === 5) {
if (responseValue < 1 || responseValue > 5) {
throw new Error('The response must be in range 1-5')
}
return responseValue <= 2 ? 'negative' : responseValue === 3 ? 'neutral' : 'positive'
} else if (scale === 7) {
if (responseValue < 1 || responseValue > 7) {
throw new Error('The response must be in range 1-7')
}
return responseValue <= 3 ? 'negative' : responseValue === 4 ? 'neutral' : 'positive'
} else if (scale === 10) {
if (responseValue < 0 || responseValue > 10) {
throw new Error('The response must be in range 0-10')
}
return responseValue <= 6 ? 'detractors' : responseValue <= 8 ? 'passives' : 'promoters'
}
throw new Error('The scale must be one of: 3, 5, 7, 10')
}
export function getNextSurveyStep(
survey: Survey,
currentQuestionIndex: number,
response: string | string[] | number | null
) {
const question = survey.questions[currentQuestionIndex]
const nextQuestionIndex = currentQuestionIndex + 1
if (!question.branching?.type) {
if (currentQuestionIndex === survey.questions.length - 1) {
return SurveyQuestionBranchingType.End
}
return nextQuestionIndex
}
if (question.branching.type === SurveyQuestionBranchingType.End) {
return SurveyQuestionBranchingType.End
} else if (question.branching.type === SurveyQuestionBranchingType.SpecificQuestion) {
if (Number.isInteger(question.branching.index)) {
return question.branching.index
}
} else if (question.branching.type === SurveyQuestionBranchingType.ResponseBased) {
// Single choice
if (question.type === SurveyQuestionType.SingleChoice) {
// :KLUDGE: for now, look up the choiceIndex based on the response
// TODO: once QuestionTypes.MultipleChoiceQuestion is refactored, pass the selected choiceIndex into this method
const selectedChoiceIndex = question.choices.indexOf(`${response}`)
if (question.branching?.responseValues?.hasOwnProperty(selectedChoiceIndex)) {
const nextStep = question.branching.responseValues[selectedChoiceIndex]
// Specific question
if (Number.isInteger(nextStep)) {
return nextStep
}
if (nextStep === SurveyQuestionBranchingType.End) {
return SurveyQuestionBranchingType.End
}
return nextQuestionIndex
}
} else if (question.type === SurveyQuestionType.Rating) {
if (typeof response !== 'number' || !Number.isInteger(response)) {
throw new Error('The response type must be an integer')
}
const ratingBucket = getRatingBucketForResponseValue(response, question.scale)
if (question.branching?.responseValues?.hasOwnProperty(ratingBucket)) {
const nextStep = question.branching.responseValues[ratingBucket]
// Specific question
if (Number.isInteger(nextStep)) {
return nextStep
}
if (nextStep === SurveyQuestionBranchingType.End) {
return SurveyQuestionBranchingType.End
}
return nextQuestionIndex
}
}
return nextQuestionIndex
}
logger.warn('Falling back to next question index due to unexpected branching type')
return nextQuestionIndex
}
export class SurveyManager {
private posthog: PostHog
private surveyInFocus: string | null
constructor(posthog: PostHog) {
this.posthog = posthog
// This is used to track the survey that is currently in focus. We only show one survey at a time.
this.surveyInFocus = null
}
private canShowNextEventBasedSurvey = (): boolean => {
// with event based surveys, we need to show the next survey without reloading the page.
// A simple check for div elements with the class name pattern of PostHogSurvey_xyz doesn't work here
// because preact leaves behind the div element for any surveys responded/dismissed with a <style> node.
// To alleviate this, we check the last div in the dom and see if it has any elements other than a Style node.
// if the last PostHogSurvey_xyz div has only one style node, we can show the next survey in the queue
// without reloading the page.
const surveyPopups = document.querySelectorAll(`div[class^=PostHogSurvey]`)
if (surveyPopups.length > 0) {
return surveyPopups[surveyPopups.length - 1].shadowRoot?.childElementCount === 1
}
return true
}
private handlePopoverSurvey = (survey: Survey): void => {
const surveyWaitPeriodInDays = survey.conditions?.seenSurveyWaitPeriodInDays
const lastSeenSurveyDate = localStorage.getItem(`lastSeenSurveyDate`)
if (!hasWaitPeriodPassed(lastSeenSurveyDate, surveyWaitPeriodInDays)) {
return
}
const surveySeen = getSurveySeen(survey)
if (!surveySeen) {
this.addSurveyToFocus(survey.id)
const shadow = createShadow(style(survey?.appearance), survey.id)
Preact.render(
<SurveyPopup
key={'popover-survey'}
posthog={this.posthog}
survey={survey}
removeSurveyFromFocus={this.removeSurveyFromFocus}
isPopup={true}
/>,
shadow
)
}
}
private handleWidget = (survey: Survey): void => {
const shadow = createWidgetShadow(survey)
const stylesheetContent = style(survey.appearance)
const stylesheet = prepareStylesheet(stylesheetContent, this.posthog)
if (stylesheet) {
shadow.appendChild(stylesheet)
}
Preact.render(
<FeedbackWidget
key={'feedback-survey'}
posthog={this.posthog}
survey={survey}
removeSurveyFromFocus={this.removeSurveyFromFocus}
/>,
shadow
)
}
private handleWidgetSelector = (survey: Survey): void => {
const selectorOnPage =
survey.appearance?.widgetSelector && document.querySelector(survey.appearance.widgetSelector)
if (selectorOnPage) {
if (document.querySelectorAll(`.PostHogWidget${survey.id}`).length === 0) {
this.handleWidget(survey)
} else if (document.querySelectorAll(`.PostHogWidget${survey.id}`).length === 1) {
// we have to check if user selector already has a survey listener attached to it because we always have to check if it's on the page or not
if (!selectorOnPage.getAttribute('PHWidgetSurveyClickListener')) {
const surveyPopup = document
.querySelector(`.PostHogWidget${survey.id}`)
?.shadowRoot?.querySelector(`.survey-form`) as HTMLFormElement
addEventListener(selectorOnPage, 'click', () => {
if (surveyPopup) {
surveyPopup.style.display = surveyPopup.style.display === 'none' ? 'block' : 'none'
addEventListener(surveyPopup, 'PHSurveyClosed', () => {
this.removeSurveyFromFocus(survey.id)
surveyPopup.style.display = 'none'
})
}
})
selectorOnPage.setAttribute('PHWidgetSurveyClickListener', 'true')
}
}
}
}
/**
* Sorts surveys by their appearance delay in ascending order. If a survey does not have an appearance delay,
* it is considered to have a delay of 0.
* @param surveys
* @returns The surveys sorted by their appearance delay
*/
private sortSurveysByAppearanceDelay(surveys: Survey[]): Survey[] {
return surveys.sort(
(a, b) => (a.appearance?.surveyPopupDelaySeconds || 0) - (b.appearance?.surveyPopupDelaySeconds || 0)
)
}
/**
* Checks the feature flags associated with this Survey to see if the survey can be rendered.
* @param survey
* @param instance
*/
public canRenderSurvey = (survey: Survey): SurveyRenderReason => {
const renderReason: SurveyRenderReason = {
visible: false,
}
if (survey.end_date) {
renderReason.disabledReason = `survey was completed on ${survey.end_date}`
return renderReason
}
if (survey.type != SurveyType.Popover) {
renderReason.disabledReason = `Only Popover survey types can be rendered`
return renderReason
}
const linkedFlagCheck = survey.linked_flag_key
? this.posthog.featureFlags.isFeatureEnabled(survey.linked_flag_key)
: true
if (!linkedFlagCheck) {
renderReason.disabledReason = `linked feature flag ${survey.linked_flag_key} is false`
return renderReason
}
const targetingFlagCheck = survey.targeting_flag_key
? this.posthog.featureFlags.isFeatureEnabled(survey.targeting_flag_key)
: true
if (!targetingFlagCheck) {
renderReason.disabledReason = `targeting feature flag ${survey.targeting_flag_key} is false`
return renderReason
}
const internalTargetingFlagCheck = survey.internal_targeting_flag_key
? this.posthog.featureFlags.isFeatureEnabled(survey.internal_targeting_flag_key)
: true
if (!internalTargetingFlagCheck) {
renderReason.disabledReason = `internal targeting feature flag ${survey.internal_targeting_flag_key} is false`
return renderReason
}
renderReason.visible = true
return renderReason
}
public renderSurvey = (survey: Survey, selector: Element): void => {
Preact.render(
<SurveyPopup
key={'popover-survey'}
posthog={this.posthog}
survey={survey}
removeSurveyFromFocus={this.removeSurveyFromFocus}
isPopup={false}
/>,
selector
)
}
public callSurveysAndEvaluateDisplayLogic = (forceReload: boolean = false): void => {
this.posthog?.getActiveMatchingSurveys((surveys) => {
const nonAPISurveys = surveys.filter((survey) => survey.type !== 'api')
// Create a queue of surveys sorted by their appearance delay. We will evaluate the display logic
// for each survey in the queue in order, and only display one survey at a time.
const nonAPISurveyQueue = this.sortSurveysByAppearanceDelay(nonAPISurveys)
nonAPISurveyQueue.forEach((survey) => {
// We only evaluate the display logic for one survey at a time
if (!isNull(this.surveyInFocus)) {
return
}
if (survey.type === SurveyType.Widget) {
if (
survey.appearance?.widgetType === 'tab' &&
document.querySelectorAll(`.PostHogWidget${survey.id}`).length === 0
) {
this.handleWidget(survey)
}
if (survey.appearance?.widgetType === 'selector' && survey.appearance?.widgetSelector) {
this.handleWidgetSelector(survey)
}
}
if (survey.type === SurveyType.Popover && this.canShowNextEventBasedSurvey()) {
this.handlePopoverSurvey(survey)
}
})
}, forceReload)
}
private addSurveyToFocus = (id: string): void => {
if (!isNull(this.surveyInFocus)) {
logger.error(`Survey ${[...this.surveyInFocus]} already in focus. Cannot add survey ${id}.`)
}
this.surveyInFocus = id
}
private removeSurveyFromFocus = (id: string): void => {
if (this.surveyInFocus !== id) {
logger.error(`Survey ${id} is not in focus. Cannot remove survey ${id}.`)
}
this.surveyInFocus = null
}
// Expose internal state and methods for testing
public getTestAPI() {
return {
addSurveyToFocus: this.addSurveyToFocus,
removeSurveyFromFocus: this.removeSurveyFromFocus,
surveyInFocus: this.surveyInFocus,
canShowNextEventBasedSurvey: this.canShowNextEventBasedSurvey,
handleWidget: this.handleWidget,
handlePopoverSurvey: this.handlePopoverSurvey,
handleWidgetSelector: this.handleWidgetSelector,
sortSurveysByAppearanceDelay: this.sortSurveysByAppearanceDelay,
}
}
}
export const renderSurveysPreview = ({
survey,
parentElement,
previewPageIndex,
forceDisableHtml,
onPreviewSubmit,
posthog,
}: {
survey: Survey
parentElement: HTMLElement
previewPageIndex: number
forceDisableHtml?: boolean
onPreviewSubmit?: (res: string | string[] | number | null) => void
posthog?: PostHog
}) => {
const stylesheetContent = style(survey.appearance)
const stylesheet = prepareStylesheet(stylesheetContent, posthog)
// Remove previously attached <style>
Array.from(parentElement.children).forEach((child) => {
if (child instanceof HTMLStyleElement) {
parentElement.removeChild(child)
}
})
if (stylesheet) {
parentElement.appendChild(stylesheet)
}
const textColor = getContrastingTextColor(
survey.appearance?.backgroundColor || defaultSurveyAppearance.backgroundColor || 'white'
)
Preact.render(
<SurveyPopup
key="surveys-render-preview"
survey={survey}
forceDisableHtml={forceDisableHtml}
style={{
position: 'relative',
right: 0,
borderBottom: `1px solid ${survey.appearance?.borderColor}`,
borderRadius: 10,
color: textColor,
}}
onPreviewSubmit={onPreviewSubmit}
previewPageIndex={previewPageIndex}
removeSurveyFromFocus={() => {}}
isPopup={true}
/>,
parentElement
)
}
export const renderFeedbackWidgetPreview = ({
survey,
root,
forceDisableHtml,
posthog,
}: {
survey: Survey
root: HTMLElement
forceDisableHtml?: boolean
posthog?: PostHog
}) => {
const stylesheetContent = createWidgetStyle(survey.appearance?.widgetColor)
const stylesheet = prepareStylesheet(stylesheetContent, posthog)
if (stylesheet) {
root.appendChild(stylesheet)
}
Preact.render(
<FeedbackWidget
key={'feedback-render-preview'}
forceDisableHtml={forceDisableHtml}
survey={survey}
readOnly={true}
removeSurveyFromFocus={() => {}}
/>,
root
)
}
// This is the main exported function
export function generateSurveys(posthog: PostHog) {
// NOTE: Important to ensure we never try and run surveys without a window environment
if (!document || !window) {
return
}
const surveyManager = new SurveyManager(posthog)
surveyManager.callSurveysAndEvaluateDisplayLogic(true)
// recalculate surveys every second to check if URL or selectors have changed
setInterval(() => {
surveyManager.callSurveysAndEvaluateDisplayLogic(false)
}, 1000)
return surveyManager
}
type UseHideSurveyOnURLChangeProps = {
survey: Pick<Survey, 'id' | 'conditions'>
removeSurveyFromFocus: (id: string) => void
setSurveyVisible: (visible: boolean) => void
isPreviewMode?: boolean
}
/**
* This hook handles URL-based survey visibility after the initial mount.
* The initial URL check is handled by the `getActiveMatchingSurveys` method in the `PostHogSurveys` class,
* which ensures the URL matches before displaying a survey for the first time.
* That is the method that is called every second to see if there's a matching survey.
*
* This separation of concerns means:
* 1. Initial URL matching is done by `getActiveMatchingSurveys` before displaying the survey
* 2. Subsequent URL changes are handled here to hide/show the survey as the user navigates
*/
export function useToggleSurveyOnURLChange({
survey,
removeSurveyFromFocus,
setSurveyVisible,
isPreviewMode = false,
}: UseHideSurveyOnURLChangeProps) {
useEffect(() => {
if (isPreviewMode || !survey.conditions?.url) {
return
}
const checkUrlMatch = () => {
const urlCheck = doesSurveyUrlMatch(survey)
if (!urlCheck) {
setSurveyVisible(false)
return removeSurveyFromFocus(survey.id)
}
setSurveyVisible(true)
}
// Listen for browser back/forward browser history changes
addEventListener(window, 'popstate', checkUrlMatch)
// Listen for hash changes, for SPA frameworks that use hash-based routing
// The hashchange event is fired when the fragment identifier of the URL has changed (the part of the URL beginning with and following the # symbol).
addEventListener(window, 'hashchange', checkUrlMatch)
// Listen for SPA navigation
const originalPushState = window.history.pushState
const originalReplaceState = window.history.replaceState
window.history.pushState = function (...args) {
originalPushState.apply(this, args)
checkUrlMatch()
}
window.history.replaceState = function (...args) {
originalReplaceState.apply(this, args)
checkUrlMatch()
}
return () => {
window.removeEventListener('popstate', checkUrlMatch)
window.removeEventListener('hashchange', checkUrlMatch)
window.history.pushState = originalPushState
window.history.replaceState = originalReplaceState
}
}, [isPreviewMode, survey, removeSurveyFromFocus, setSurveyVisible])
}
export function usePopupVisibility(
survey: Survey,
posthog: PostHog | undefined,
millisecondDelay: number,
isPreviewMode: boolean,
removeSurveyFromFocus: (id: string) => void
) {
const [isPopupVisible, setIsPopupVisible] = useState(isPreviewMode || millisecondDelay === 0)
const [isSurveySent, setIsSurveySent] = useState(false)
useEffect(() => {
if (!posthog) {
logger.error('usePopupVisibility hook called without a PostHog instance.')
return
}
if (isPreviewMode) {
return
}
const handleSurveyClosed = () => {
removeSurveyFromFocus(survey.id)
setIsPopupVisible(false)
}
const handleSurveySent = () => {
if (!survey.appearance?.displayThankYouMessage) {
removeSurveyFromFocus(survey.id)
setIsPopupVisible(false)
} else {
setIsSurveySent(true)
removeSurveyFromFocus(survey.id)
if (survey.appearance?.autoDisappear) {
setTimeout(() => {
setIsPopupVisible(false)
}, 5000)
}
}
}
const showSurvey = () => {
// check if the url is still matching, necessary for delayed surveys, as the URL may have changed
// since the survey was scheduled to appear
if (!doesSurveyUrlMatch(survey)) {
return
}
setIsPopupVisible(true)
window.dispatchEvent(new Event('PHSurveyShown'))
posthog.capture('survey shown', {
$survey_name: survey.name,
$survey_id: survey.id,
$survey_iteration: survey.current_iteration,
$survey_iteration_start_date: survey.current_iteration_start_date,
sessionRecordingUrl: posthog.get_session_replay_url?.(),
})
localStorage.setItem('lastSeenSurveyDate', new Date().toISOString())
}
const handleShowSurveyWithDelay = () => {
const timeoutId = setTimeout(() => {
showSurvey()
}, millisecondDelay)
return () => {
clearTimeout(timeoutId)
window.removeEventListener('PHSurveyClosed', handleSurveyClosed)
window.removeEventListener('PHSurveySent', handleSurveySent)
}
}
const handleShowSurveyImmediately = () => {
showSurvey()
return () => {
window.removeEventListener('PHSurveyClosed', handleSurveyClosed)
window.removeEventListener('PHSurveySent', handleSurveySent)
}
}
addEventListener(window, 'PHSurveyClosed', handleSurveyClosed)
addEventListener(window, 'PHSurveySent', handleSurveySent)
if (millisecondDelay > 0) {
return handleShowSurveyWithDelay()
} else {
return handleShowSurveyImmediately()
}
}, [])
useToggleSurveyOnURLChange({
survey,
removeSurveyFromFocus,
setSurveyVisible: setIsPopupVisible,
isPreviewMode,
})
return { isPopupVisible, isSurveySent, setIsPopupVisible }
}
interface SurveyPopupProps {
survey: Survey
forceDisableHtml?: boolean
posthog?: PostHog
style?: React.CSSProperties
previewPageIndex?: number | undefined
removeSurveyFromFocus: (id: string) => void
isPopup?: boolean
onPreviewSubmit?: (res: string | string[] | number | null) => void
}
export function SurveyPopup({
survey,
forceDisableHtml,
posthog,
style,
previewPageIndex,
removeSurveyFromFocus,
isPopup,
onPreviewSubmit = () => {},
}: SurveyPopupProps) {
const isPreviewMode = Number.isInteger(previewPageIndex)
// NB: The client-side code passes the millisecondDelay in seconds, but setTimeout expects milliseconds, so we multiply by 1000
const surveyPopupDelayMilliseconds = survey.appearance?.surveyPopupDelaySeconds
? survey.appearance.surveyPopupDelaySeconds * 1000
: 0
const { isPopupVisible, isSurveySent, setIsPopupVisible } = usePopupVisibility(
survey,
posthog,
surveyPopupDelayMilliseconds,
isPreviewMode,
removeSurveyFromFocus
)
const shouldShowConfirmation = isSurveySent || previewPageIndex === survey.questions.length
const confirmationBoxLeftStyle = style?.left && isNumber(style?.left) ? { left: style.left - 40 } : {}
if (isPreviewMode) {
style = style || {}
style.left = 'unset'
style.right = 'unset'
style.transform = 'unset'
}
return isPopupVisible ? (
<SurveyContext.Provider
value={{
isPreviewMode,
previewPageIndex: previewPageIndex,
handleCloseSurveyPopup: () => dismissedSurveyEvent(survey, posthog, isPreviewMode),
isPopup: isPopup || false,
onPreviewSubmit,
}}
>
{!shouldShowConfirmation ? (
<Questions
survey={survey}
forceDisableHtml={!!forceDisableHtml}
posthog={posthog}
styleOverrides={style}
/>
) : (
<ConfirmationMessage
header={survey.appearance?.thankYouMessageHeader || 'Thank you!'}
description={survey.appearance?.thankYouMessageDescription || ''}
forceDisableHtml={!!forceDisableHtml}
contentType={survey.appearance?.thankYouMessageDescriptionContentType}
appearance={survey.appearance || defaultSurveyAppearance}
styleOverrides={{ ...style, ...confirmationBoxLeftStyle }}
onClose={() => setIsPopupVisible(false)}
/>
)}
</SurveyContext.Provider>
) : null
}
export function Questions({
survey,
forceDisableHtml,
posthog,
styleOverrides,
}: {
survey: Survey
forceDisableHtml: boolean
posthog?: PostHog
styleOverrides?: React.CSSProperties
}) {
const textColor = getContrastingTextColor(
survey.appearance?.backgroundColor || defaultSurveyAppearance.backgroundColor
)
const [questionsResponses, setQuestionsResponses] = useState({})
const { isPreviewMode, previewPageIndex, handleCloseSurveyPopup, isPopup, onPreviewSubmit } =
useContext(SurveyContext)
const [currentQuestionIndex, setCurrentQuestionIndex] = useState(previewPageIndex || 0)
const surveyQuestions = useMemo(() => getDisplayOrderQuestions(survey), [survey])
// Sync preview state
useEffect(() => {
setCurrentQuestionIndex(previewPageIndex ?? 0)
}, [previewPageIndex])
const onNextButtonClick = ({
res,
originalQuestionIndex,
displayQuestionIndex,
}: {
res: string | string[] | number | null
originalQuestionIndex: number
displayQuestionIndex: number
}) => {
if (!posthog) {
logger.error('onNextButtonClick called without a PostHog instance.')
return
}
const responseKey =
originalQuestionIndex === 0 ? `$survey_response` : `$survey_response_${originalQuestionIndex}`
setQuestionsResponses({ ...questionsResponses, [responseKey]: res })
const nextStep = getNextSurveyStep(survey, displayQuestionIndex, res)
if (nextStep === SurveyQuestionBranchingType.End) {
sendSurveyEvent({ ...questionsResponses, [responseKey]: res }, survey, posthog)
} else {
setCurrentQuestionIndex(nextStep)
}
}
return (
<form
className="survey-form"
style={
isPopup
? {
color: textColor,
borderColor: survey.appearance?.borderColor,
...styleOverrides,
}
: {}
}
>
{surveyQuestions.map((question, displayQuestionIndex) => {
const { originalQuestionIndex } = question
const isVisible = isPreviewMode
? currentQuestionIndex === originalQuestionIndex
: currentQuestionIndex === displayQuestionIndex
return (
isVisible && (
<div
className="survey-box"
style={
isPopup
? {
backgroundColor:
survey.appearance?.backgroundColor ||
defaultSurveyAppearance.backgroundColor,
}
: {}
}
>
{isPopup && <Cancel onClick={() => handleCloseSurveyPopup()} />}
{getQuestionComponent({
question,
forceDisableHtml,
displayQuestionIndex,
appearance: survey.appearance || defaultSurveyAppearance,
onSubmit: (res) =>
onNextButtonClick({
res,
originalQuestionIndex,
displayQuestionIndex,
}),
onPreviewSubmit,
})}
</div>
)
)
})}
</form>
)
}
export function FeedbackWidget({
survey,
forceDisableHtml,
posthog,
readOnly,
removeSurveyFromFocus,
}: {
survey: Survey
forceDisableHtml?: boolean
posthog?: PostHog
readOnly?: boolean
removeSurveyFromFocus: (id: string) => void
}): JSX.Element | null {
const [isFeedbackButtonVisible, setIsFeedbackButtonVisible] = useState(true)
const [showSurvey, setShowSurvey] = useState(false)
const [styleOverrides, setStyle] = useState({})
const widgetRef = useRef<HTMLDivElement>(null)
useEffect(() => {
if (!posthog) {
logger.error('FeedbackWidget called without a PostHog instance.')
return
}
if (readOnly) {
return
}
if (survey.appearance?.widgetType === 'tab') {
if (widgetRef.current) {
const widgetPos = widgetRef.current.getBoundingClientRect()
const style = {
top: '50%',
left: parseInt(`${widgetPos.right - 360}`),
bottom: 'auto',
borderRadius: 10,
borderBottom: `1.5px solid ${survey.appearance?.borderColor || '#c9c6c6'}`,
}
setStyle(style)
}
}
if (survey.appearance?.widgetType === 'selector') {
const widget = document.querySelector(survey.appearance.widgetSelector || '') ?? undefined
addEventListener(widget, 'click', () => {
setShowSurvey(!showSurvey)
})
widget?.setAttribute('PHWidgetSurveyClickListener', 'true')
}
}, [])
useToggleSurveyOnURLChange({
survey,
removeSurveyFromFocus,
setSurveyVisible: setIsFeedbackButtonVisible,
})
if (!isFeedbackButtonVisible) {
return null
}
return (
<Preact.Fragment>
{survey.appearance?.widgetType === 'tab' && (
<div
className="ph-survey-widget-tab"
ref={widgetRef}
onClick={() => !readOnly && setShowSurvey(!showSurvey)}
style={{ color: getContrastingTextColor(survey.appearance.widgetColor) }}
>
<div className="ph-survey-widget-tab-icon"></div>
{survey.appearance?.widgetLabel || ''}
</div>
)}
{showSurvey && (
<SurveyPopup
key={'feedback-widget-survey'}
posthog={posthog}
survey={survey}
forceDisableHtml={forceDisableHtml}
style={styleOverrides}
removeSurveyFromFocus={removeSurveyFromFocus}
isPopup={true}
/>
)}
</Preact.Fragment>
)
}
interface GetQuestionComponentProps {
question: SurveyQuestion
forceDisableHtml: boolean
displayQuestionIndex: number
appearance: SurveyAppearance
onSubmit: (res: string | string[] | number | null) => void
onPreviewSubmit: (res: string | string[] | number | null) => void
}
const getQuestionComponent = ({
question,
forceDisableHtml,
displayQuestionIndex,
appearance,
onSubmit,
onPreviewSubmit,
}: GetQuestionComponentProps): JSX.Element => {
const questionComponents = {
[SurveyQuestionType.Open]: OpenTextQuestion,
[SurveyQuestionType.Link]: LinkQuestion,
[SurveyQuestionType.Rating]: RatingQuestion,
[SurveyQuestionType.SingleChoice]: MultipleChoiceQuestion,
[SurveyQuestionType.MultipleChoice]: MultipleChoiceQuestion,
}
const commonProps = {
question,
forceDisableHtml,
appearance,
onPreviewSubmit: (res: string | string[] | number | null) => {
onPreviewSubmit(res)
},
onSubmit: (res: string | string[] | number | null) => {
onSubmit(res)
},
}
const additionalProps: Record<SurveyQuestionType, any> = {
[SurveyQuestionType.Open]: {},
[SurveyQuestionType.Link]: {},
[SurveyQuestionType.Rating]: { displayQuestionIndex },
[SurveyQuestionType.SingleChoice]: { displayQuestionIndex },
[SurveyQuestionType.MultipleChoice]: { displayQuestionIndex },
}
const Component = questionComponents[question.type]
const componentProps = { ...commonProps, ...additionalProps[question.type] }
return <Component {...componentProps} />
}