@posthog/browser-common 0.9.4 → 0.9.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/dist/client.d.ts +6 -0
  2. package/dist/config.js +1 -1
  3. package/dist/config.mjs +1 -1
  4. package/dist/index.d.ts +1 -0
  5. package/dist/index.js +58 -10
  6. package/dist/index.mjs +1 -0
  7. package/dist/survey-action-matcher.d.ts +27 -0
  8. package/dist/survey-action-matcher.js +169 -0
  9. package/dist/survey-action-matcher.mjs +131 -0
  10. package/dist/survey-constants.d.ts +86 -0
  11. package/dist/survey-constants.js +144 -0
  12. package/dist/survey-constants.mjs +76 -0
  13. package/dist/survey-event-host.d.ts +15 -0
  14. package/dist/survey-event-host.js +18 -0
  15. package/dist/survey-event-host.mjs +1 -0
  16. package/dist/survey-event-receiver-base.d.ts +180 -0
  17. package/dist/survey-event-receiver-base.js +354 -0
  18. package/dist/survey-event-receiver-base.mjs +316 -0
  19. package/dist/survey-event-receiver.d.ts +36 -0
  20. package/dist/survey-event-receiver.js +133 -0
  21. package/dist/survey-event-receiver.mjs +95 -0
  22. package/dist/survey-render-context.d.ts +13 -0
  23. package/dist/survey-render-context.js +45 -0
  24. package/dist/survey-render-context.mjs +7 -0
  25. package/dist/surveys/components/BottomSection.d.ts +12 -0
  26. package/dist/surveys/components/BottomSection.js +82 -0
  27. package/dist/surveys/components/BottomSection.mjs +44 -0
  28. package/dist/surveys/components/ConfirmationMessage.d.ts +10 -0
  29. package/dist/surveys/components/ConfirmationMessage.js +92 -0
  30. package/dist/surveys/components/ConfirmationMessage.mjs +54 -0
  31. package/dist/surveys/components/IntroScreen.d.ts +10 -0
  32. package/dist/surveys/components/IntroScreen.js +78 -0
  33. package/dist/surveys/components/IntroScreen.mjs +40 -0
  34. package/dist/surveys/components/PostHogLogo.d.ts +5 -0
  35. package/dist/surveys/components/PostHogLogo.js +54 -0
  36. package/dist/surveys/components/PostHogLogo.mjs +16 -0
  37. package/dist/surveys/components/QuestionHeader.d.ts +10 -0
  38. package/dist/surveys/components/QuestionHeader.js +82 -0
  39. package/dist/surveys/components/QuestionHeader.mjs +41 -0
  40. package/dist/surveys/components/QuestionTypes.d.ts +31 -0
  41. package/dist/surveys/components/QuestionTypes.js +519 -0
  42. package/dist/surveys/components/QuestionTypes.mjs +469 -0
  43. package/dist/surveys/icons.d.ts +12 -0
  44. package/dist/surveys/icons.js +212 -0
  45. package/dist/surveys/icons.mjs +147 -0
  46. package/dist/surveys/survey-branching.d.ts +12 -0
  47. package/dist/surveys/survey-branching.js +101 -0
  48. package/dist/surveys/survey-branching.mjs +60 -0
  49. package/dist/surveys/survey-styles.d.ts +1 -0
  50. package/dist/surveys/survey-styles.js +40 -0
  51. package/dist/surveys/survey-styles.mjs +2 -0
  52. package/dist/surveys/survey-translations.d.ts +22 -0
  53. package/dist/surveys/survey-translations.js +68 -0
  54. package/dist/surveys/survey-translations.mjs +27 -0
  55. package/dist/surveys/survey-url-prefill.d.ts +36 -0
  56. package/dist/surveys/survey-url-prefill.js +162 -0
  57. package/dist/surveys/survey-url-prefill.mjs +118 -0
  58. package/dist/surveys/surveys-extension-utils.d.ts +133 -0
  59. package/dist/surveys/surveys-extension-utils.js +739 -0
  60. package/dist/surveys/surveys-extension-utils.mjs +608 -0
  61. package/dist/surveys-config.d.ts +60 -0
  62. package/dist/surveys-config.js +68 -0
  63. package/dist/surveys-config.mjs +9 -0
  64. package/dist/surveys-renderer.d.ts +248 -0
  65. package/dist/surveys-renderer.js +1299 -0
  66. package/dist/surveys-renderer.mjs +1230 -0
  67. package/dist/surveys.d.ts +117 -0
  68. package/dist/surveys.js +566 -0
  69. package/dist/surveys.mjs +495 -0
  70. package/dist/types/surveys.d.ts +83 -86
  71. package/dist/types/surveys.js +1 -127
  72. package/dist/types/surveys.mjs +1 -76
  73. package/dist/utils/autocapture-utils.js +8 -9
  74. package/dist/utils/autocapture-utils.mjs +8 -9
  75. package/dist/utils/event-utils.js +1 -0
  76. package/dist/utils/event-utils.mjs +1 -0
  77. package/dist/utils/matcher-utils.d.ts +1 -1
  78. package/dist/utils/matcher-utils.js +13 -10
  79. package/dist/utils/matcher-utils.mjs +10 -7
  80. package/dist/utils/survey-utils.d.ts +16 -0
  81. package/dist/utils/survey-utils.js +121 -0
  82. package/dist/utils/survey-utils.mjs +38 -0
  83. package/dist/utils/url-targeting-utils.d.ts +3 -1
  84. package/dist/utils/url-targeting-utils.js +1 -2
  85. package/dist/utils/url-targeting-utils.mjs +1 -2
  86. package/dist/utils/uuidv7.js +4 -4
  87. package/dist/utils/uuidv7.mjs +4 -4
  88. package/package.json +97 -3
@@ -0,0 +1,1299 @@
1
+ "use strict";
2
+ var __webpack_require__ = {};
3
+ (()=>{
4
+ __webpack_require__.d = (exports1, getters, values)=>{
5
+ var define = (defs, kind)=>{
6
+ for(var key in defs)if (__webpack_require__.o(defs, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
7
+ enumerable: true,
8
+ [kind]: defs[key]
9
+ });
10
+ };
11
+ define(getters, "get");
12
+ define(values, "value");
13
+ };
14
+ })();
15
+ (()=>{
16
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
17
+ })();
18
+ (()=>{
19
+ __webpack_require__.r = (exports1)=>{
20
+ if ("u" > typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
21
+ value: 'Module'
22
+ });
23
+ Object.defineProperty(exports1, '__esModule', {
24
+ value: true
25
+ });
26
+ };
27
+ })();
28
+ var __webpack_exports__ = {};
29
+ __webpack_require__.r(__webpack_exports__);
30
+ __webpack_require__.d(__webpack_exports__, {
31
+ FeedbackWidget: ()=>FeedbackWidget,
32
+ INTRO_SCREEN_PREVIEW_INDEX: ()=>INTRO_SCREEN_PREVIEW_INDEX,
33
+ Questions: ()=>Questions,
34
+ SurveyManager: ()=>SurveyManager,
35
+ SurveyPopup: ()=>SurveyPopup,
36
+ generateSurveys: ()=>generateSurveys,
37
+ getNextSurveyStep: ()=>survey_branching_js_namespaceObject.getNextSurveyStep,
38
+ renderFeedbackWidgetPreview: ()=>renderFeedbackWidgetPreview,
39
+ renderSurveysPreview: ()=>renderSurveysPreview,
40
+ useHideSurveyOnURLChange: ()=>useHideSurveyOnURLChange,
41
+ usePopupVisibility: ()=>usePopupVisibility
42
+ });
43
+ const jsx_runtime_namespaceObject = require("preact/jsx-runtime");
44
+ const external_preact_namespaceObject = require("preact");
45
+ const external_surveys_config_js_namespaceObject = require("./surveys-config.js");
46
+ const external_extension_tokens_js_namespaceObject = require("./extension-tokens.js");
47
+ const external_survey_render_context_js_namespaceObject = require("./survey-render-context.js");
48
+ const uuidv7_js_namespaceObject = require("./utils/uuidv7.js");
49
+ const hooks_namespaceObject = require("preact/hooks");
50
+ const external_survey_constants_js_namespaceObject = require("./survey-constants.js");
51
+ const general_utils_js_namespaceObject = require("./utils/general-utils.js");
52
+ const survey_utils_js_namespaceObject = require("./utils/survey-utils.js");
53
+ const core_namespaceObject = require("@posthog/core");
54
+ const surveys_namespaceObject = require("@posthog/core/surveys");
55
+ const ConfirmationMessage_js_namespaceObject = require("./surveys/components/ConfirmationMessage.js");
56
+ const IntroScreen_js_namespaceObject = require("./surveys/components/IntroScreen.js");
57
+ const QuestionHeader_js_namespaceObject = require("./surveys/components/QuestionHeader.js");
58
+ const QuestionTypes_js_namespaceObject = require("./surveys/components/QuestionTypes.js");
59
+ const surveys_extension_utils_js_namespaceObject = require("./surveys/surveys-extension-utils.js");
60
+ const survey_url_prefill_js_namespaceObject = require("./surveys/survey-url-prefill.js");
61
+ const survey_branching_js_namespaceObject = require("./surveys/survey-branching.js");
62
+ const survey_translations_js_namespaceObject = require("./surveys/survey-translations.js");
63
+ const INTRO_SCREEN_PREVIEW_INDEX = -1;
64
+ const DISPATCH_FEEDBACK_WIDGET_EVENT = 'ph:show_survey_widget';
65
+ const WIDGET_LISTENER_ATTRIBUTE = 'PHWidgetSurveyClickListener';
66
+ const SURVEY_NEXT_TO_TRIGGER_PARAMS = {
67
+ ESTIMATED_MIN_HEIGHT: 250,
68
+ HORIZONTAL_PADDING: 20,
69
+ TRIGGER_SPACING: 12
70
+ };
71
+ function getNextToTriggerPosition(target, surveyWidth) {
72
+ try {
73
+ const buttonRect = target.getBoundingClientRect();
74
+ const viewportHeight = window.innerHeight;
75
+ const viewportWidth = window.innerWidth;
76
+ const estimatedMinSurveyHeight = SURVEY_NEXT_TO_TRIGGER_PARAMS.ESTIMATED_MIN_HEIGHT;
77
+ const buttonCenterX = buttonRect.left + buttonRect.width / 2;
78
+ let left = buttonCenterX - surveyWidth / 2;
79
+ const horizontalPadding = SURVEY_NEXT_TO_TRIGGER_PARAMS.HORIZONTAL_PADDING;
80
+ if (left + surveyWidth > viewportWidth - horizontalPadding) left = viewportWidth - surveyWidth - horizontalPadding;
81
+ if (left < horizontalPadding) left = horizontalPadding;
82
+ const spacing = SURVEY_NEXT_TO_TRIGGER_PARAMS.TRIGGER_SPACING;
83
+ const spaceBelow = viewportHeight - buttonRect.bottom;
84
+ const spaceAbove = buttonRect.top;
85
+ const showAbove = spaceBelow < estimatedMinSurveyHeight && spaceAbove > spaceBelow;
86
+ return {
87
+ position: 'fixed',
88
+ top: showAbove ? 'auto' : `${buttonRect.bottom + spacing}px`,
89
+ left: `${left}px`,
90
+ right: 'auto',
91
+ bottom: showAbove ? `${viewportHeight - buttonRect.top + spacing}px` : 'auto',
92
+ zIndex: surveys_extension_utils_js_namespaceObject.defaultSurveyAppearance.zIndex
93
+ };
94
+ } catch (error) {
95
+ survey_utils_js_namespaceObject.SURVEY_LOGGER.warn('Failed to calculate trigger position:', error);
96
+ return null;
97
+ }
98
+ }
99
+ const SURVEY_TARGETING_FLAG_PREFIX = 'survey-targeting-';
100
+ class SurveyManager {
101
+ constructor(posthog){
102
+ this._surveyTimeouts = new Map();
103
+ this._widgetSelectorListeners = new Map();
104
+ this._renderedTabWidgets = new Map();
105
+ this._renderedTargets = new Map();
106
+ this._prefillHandledSurveys = new Set();
107
+ this._disposed = false;
108
+ this._currentLanguage = null;
109
+ this._surveyIsRendered = false;
110
+ this._languageChangeListener = null;
111
+ this._unsubscribeFeatureFlags = null;
112
+ this._surveyPopupProps = null;
113
+ this._loggedFeatureFlagsDisabledWarning = false;
114
+ this.handlePageUnload = ()=>{
115
+ const surveys = this._host.client?.kv.get(external_surveys_config_js_namespaceObject.SURVEYS);
116
+ if (!surveys) return;
117
+ for (const survey of surveys)if ((0, surveys_extension_utils_js_namespaceObject.isSurveyInProgress)(survey)) (0, surveys_extension_utils_js_namespaceObject.sendSurveyAbandonedEvent)(survey, this._host);
118
+ };
119
+ this.handlePopoverSurvey = (surveyParam, options, { resumeDelayFromActivation = false } = {})=>{
120
+ if (!this._host.client?.canCapture) return;
121
+ const { survey: translatedSurvey, language: surveyLanguage } = this._translateSurveyForRendering(surveyParam);
122
+ this._currentLanguage = surveyLanguage;
123
+ this._surveyPopupProps = null;
124
+ this._displayOptions = options;
125
+ const survey = this._applyDisplayOverrides(translatedSurvey, options);
126
+ this._clearSurveyTimeout(survey.id);
127
+ const { properties, initialResponses } = options ?? {};
128
+ const hasPrefillData = initialResponses && Object.keys(initialResponses).length > 0;
129
+ const isSurveyCompleted = hasPrefillData ? this._handleInitialResponses(survey, initialResponses, properties, surveyLanguage) : false;
130
+ if (isSurveyCompleted && !survey.appearance?.displayThankYouMessage) return;
131
+ this._addSurveyToFocus(survey);
132
+ let positionStyle = {};
133
+ if (survey.appearance?.position === external_survey_constants_js_namespaceObject.SurveyPosition.NextToTrigger && survey.appearance?.widgetSelector) {
134
+ const targetElement = document.querySelector(survey.appearance.widgetSelector);
135
+ if (targetElement) positionStyle = getNextToTriggerPosition(targetElement, parseInt(survey.appearance?.maxWidth || surveys_extension_utils_js_namespaceObject.defaultSurveyAppearance.maxWidth)) || {};
136
+ }
137
+ const delaySeconds = survey.appearance?.surveyPopupDelaySeconds || 0;
138
+ const { shadow } = (0, surveys_extension_utils_js_namespaceObject.retrieveSurveyShadow)(survey, this._host);
139
+ this._renderedTargets.set(shadow, shadow.host);
140
+ const surveyPopupProps = {
141
+ posthog: this._host,
142
+ survey: survey,
143
+ removeSurveyFromFocus: this._removeSurveyFromFocus,
144
+ properties: properties,
145
+ style: positionStyle,
146
+ isSurveyCompleted: isSurveyCompleted,
147
+ skipShownEvent: options?.skipShownEvent,
148
+ surveyLanguage
149
+ };
150
+ this._surveyPopupProps = surveyPopupProps;
151
+ if (delaySeconds <= 0) {
152
+ this._surveyIsRendered = true;
153
+ return (0, external_preact_namespaceObject.render)(/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(SurveyPopup, {
154
+ ...surveyPopupProps
155
+ }), shadow);
156
+ }
157
+ const renderAfterDelay = ()=>{
158
+ this._surveyIsRendered = true;
159
+ const { survey: freshlyTranslated, language: freshLanguage } = this._translateSurveyForRendering(surveyParam);
160
+ this._currentLanguage = freshLanguage;
161
+ const freshSurvey = this._applyDisplayOverrides(freshlyTranslated, options);
162
+ const freshPopupProps = {
163
+ ...surveyPopupProps,
164
+ survey: freshSurvey,
165
+ surveyLanguage: freshLanguage
166
+ };
167
+ this._surveyPopupProps = freshPopupProps;
168
+ (0, external_preact_namespaceObject.render)(/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(SurveyPopup, {
169
+ ...freshPopupProps,
170
+ survey: {
171
+ ...freshSurvey,
172
+ appearance: {
173
+ ...freshSurvey.appearance,
174
+ surveyPopupDelaySeconds: 0
175
+ }
176
+ }
177
+ }), shadow);
178
+ };
179
+ const renderIfStillEligible = ()=>{
180
+ if (!this._host.client?.canCapture || !this._shouldDisplaySurvey(survey)) {
181
+ survey_utils_js_namespaceObject.SURVEY_LOGGER.info(`Survey ${survey.id} no longer eligible when its display delay elapsed; not displaying`);
182
+ return this._removeSurveyFromFocus(survey);
183
+ }
184
+ renderAfterDelay();
185
+ };
186
+ const activatedAt = resumeDelayFromActivation ? this._host.surveys?._surveyEventReceiver?.getActivationTimestamp?.(survey.id) : void 0;
187
+ const elapsedMs = (0, core_namespaceObject.isNumber)(activatedAt) ? Math.max(0, Date.now() - activatedAt) : 0;
188
+ const remainingMs = Math.max(0, 1000 * delaySeconds - elapsedMs);
189
+ if (remainingMs <= 0) return renderIfStillEligible();
190
+ const timeoutId = window.setTimeout(()=>{
191
+ this._surveyTimeouts.delete(survey.id);
192
+ renderIfStillEligible();
193
+ }, remainingMs);
194
+ this._surveyTimeouts.set(survey.id, timeoutId);
195
+ };
196
+ this._handleWidget = (survey)=>{
197
+ const { survey: translatedSurvey, language: surveyLanguage } = this._translateSurveyForRendering(survey);
198
+ const { shadow, isNewlyCreated } = (0, surveys_extension_utils_js_namespaceObject.retrieveSurveyShadow)(translatedSurvey, this._host);
199
+ this._renderedTargets.set(shadow, shadow.host);
200
+ if (survey.appearance?.widgetType === external_survey_constants_js_namespaceObject.SurveyWidgetType.Tab) this._renderedTabWidgets.set(survey.id, survey);
201
+ if (!isNewlyCreated) return;
202
+ (0, external_preact_namespaceObject.render)(/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(FeedbackWidget, {
203
+ posthog: this._host,
204
+ survey: translatedSurvey,
205
+ surveyLanguage: surveyLanguage
206
+ }, survey.id), shadow);
207
+ };
208
+ this._detachWidgetSelectorListener = (surveyId)=>{
209
+ const existing = this._widgetSelectorListeners.get(surveyId);
210
+ if (existing) {
211
+ existing.element.removeEventListener('click', existing.listener);
212
+ existing.element.removeAttribute(WIDGET_LISTENER_ATTRIBUTE);
213
+ this._widgetSelectorListeners.delete(surveyId);
214
+ survey_utils_js_namespaceObject.SURVEY_LOGGER.info(`Removed click listener for survey ${surveyId}`);
215
+ }
216
+ };
217
+ this._removeWidgetSelectorListener = (survey)=>{
218
+ if (this._isWidgetSurveyOpen(survey)) return;
219
+ this._removeSurveyFromDom(survey);
220
+ this._detachWidgetSelectorListener(survey.id);
221
+ };
222
+ this._removeTabWidget = (survey)=>{
223
+ if (this._isWidgetSurveyOpen(survey)) return;
224
+ this._removeSurveyFromDom(survey);
225
+ this._renderedTabWidgets.delete(survey.id);
226
+ };
227
+ this._isWidgetSurveyOpen = (survey)=>{
228
+ try {
229
+ const shadowContainer = document.querySelector((0, surveys_extension_utils_js_namespaceObject.getSurveyContainerClass)(survey, true));
230
+ return !!shadowContainer?.shadowRoot?.querySelector('.ph-survey');
231
+ } catch {
232
+ return false;
233
+ }
234
+ };
235
+ this._manageWidgetSelectorListener = (survey, selector)=>{
236
+ const currentElement = document.querySelector(selector);
237
+ const existingListenerData = this._widgetSelectorListeners.get(survey.id);
238
+ if (!currentElement) {
239
+ if (existingListenerData) this._removeWidgetSelectorListener(survey);
240
+ return;
241
+ }
242
+ this._handleWidget(survey);
243
+ if (existingListenerData) if (currentElement === existingListenerData.element) return;
244
+ else {
245
+ survey_utils_js_namespaceObject.SURVEY_LOGGER.info(`Selector element changed for survey ${survey.id}. Re-attaching listener.`);
246
+ this._detachWidgetSelectorListener(survey.id);
247
+ }
248
+ if (!currentElement.hasAttribute(WIDGET_LISTENER_ATTRIBUTE)) {
249
+ const listener = (event)=>{
250
+ event.stopPropagation();
251
+ const positionStyles = survey.appearance?.position === external_survey_constants_js_namespaceObject.SurveyPosition.NextToTrigger ? getNextToTriggerPosition(event.currentTarget, parseInt(survey.appearance?.maxWidth || surveys_extension_utils_js_namespaceObject.defaultSurveyAppearance.maxWidth)) : {};
252
+ window.dispatchEvent(new CustomEvent(DISPATCH_FEEDBACK_WIDGET_EVENT, {
253
+ detail: {
254
+ surveyId: survey.id,
255
+ position: positionStyles
256
+ }
257
+ }));
258
+ };
259
+ (0, general_utils_js_namespaceObject.addEventListener)(currentElement, 'click', listener);
260
+ currentElement.setAttribute(WIDGET_LISTENER_ATTRIBUTE, 'true');
261
+ this._widgetSelectorListeners.set(survey.id, {
262
+ element: currentElement,
263
+ listener,
264
+ survey
265
+ });
266
+ survey_utils_js_namespaceObject.SURVEY_LOGGER.info(`Attached click listener for feedback button survey ${survey.id}`);
267
+ }
268
+ };
269
+ this.renderPopover = (survey)=>{
270
+ if (!this._host.client?.canCapture) return;
271
+ const { survey: translatedSurvey, language: surveyLanguage } = this._translateSurveyForRendering(survey);
272
+ const { shadow } = (0, surveys_extension_utils_js_namespaceObject.retrieveSurveyShadow)(translatedSurvey, this._host);
273
+ this._renderedTargets.set(shadow, shadow.host);
274
+ (0, external_preact_namespaceObject.render)(/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(SurveyPopup, {
275
+ posthog: this._host,
276
+ survey: translatedSurvey,
277
+ removeSurveyFromFocus: this._removeSurveyFromFocus,
278
+ surveyLanguage: surveyLanguage
279
+ }), shadow);
280
+ };
281
+ this.renderSurvey = (survey, selector, properties)=>{
282
+ if (!this._host.client?.canCapture) return;
283
+ const { survey: translatedSurvey, language: surveyLanguage } = this._translateSurveyForRendering(survey);
284
+ let isSurveyCompleted = false;
285
+ if (this._host.config.prefillFromUrl) isSurveyCompleted = this._handleUrlPrefill(translatedSurvey, surveyLanguage, properties);
286
+ (0, external_preact_namespaceObject.render)(/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(SurveyPopup, {
287
+ posthog: this._host,
288
+ survey: translatedSurvey,
289
+ removeSurveyFromFocus: this._removeSurveyFromFocus,
290
+ isPopup: false,
291
+ properties: properties,
292
+ isSurveyCompleted: isSurveyCompleted,
293
+ surveyLanguage: surveyLanguage
294
+ }), selector);
295
+ };
296
+ this.getActiveMatchingSurveys = (callback, forceReload = false)=>{
297
+ this._host.surveys?.getSurveys((surveys)=>{
298
+ const targetingMatchedSurveys = surveys.filter((survey)=>this._shouldDisplaySurvey(survey));
299
+ callback(targetingMatchedSurveys);
300
+ }, forceReload);
301
+ };
302
+ this.callSurveysAndEvaluateDisplayLogic = (forceReload = false)=>{
303
+ this.getActiveMatchingSurveys((surveys)=>{
304
+ const canCaptureResponse = this._host.client?.canCapture;
305
+ const inAppSurveysWithDisplayLogic = surveys.filter((survey)=>canCaptureResponse && (survey.type === external_survey_constants_js_namespaceObject.SurveyType.Popover || survey.type === external_survey_constants_js_namespaceObject.SurveyType.Widget));
306
+ const matchingIds = new Set(inAppSurveysWithDisplayLogic.map((survey)=>survey.id));
307
+ for (const pendingSurveyId of Array.from(this._surveyTimeouts.keys()))if (!matchingIds.has(pendingSurveyId)) this.cancelSurvey(pendingSurveyId);
308
+ const inAppSurveysQueue = this._sortSurveysByAppearanceDelay(inAppSurveysWithDisplayLogic);
309
+ const activeSelectorSurveys = new Set();
310
+ const activeTabWidgetSurveys = new Set();
311
+ inAppSurveysQueue.forEach((survey)=>{
312
+ if (survey.type === external_survey_constants_js_namespaceObject.SurveyType.Widget) {
313
+ if (survey.appearance?.widgetType === external_survey_constants_js_namespaceObject.SurveyWidgetType.Tab) {
314
+ activeTabWidgetSurveys.add(survey.id);
315
+ this._handleWidget(survey);
316
+ return;
317
+ }
318
+ if (survey.appearance?.widgetType === external_survey_constants_js_namespaceObject.SurveyWidgetType.Selector && survey.appearance?.widgetSelector) {
319
+ activeSelectorSurveys.add(survey.id);
320
+ this._manageWidgetSelectorListener(survey, survey.appearance?.widgetSelector);
321
+ }
322
+ }
323
+ if ((0, core_namespaceObject.isNull)(this._surveyInFocus) && survey.type === external_survey_constants_js_namespaceObject.SurveyType.Popover) this.handlePopoverSurvey(survey, void 0, {
324
+ resumeDelayFromActivation: true
325
+ });
326
+ });
327
+ this._widgetSelectorListeners.forEach(({ survey })=>{
328
+ if (!activeSelectorSurveys.has(survey.id)) this._removeWidgetSelectorListener(survey);
329
+ });
330
+ this._renderedTabWidgets.forEach((tabSurvey, surveyId)=>{
331
+ if (!activeTabWidgetSurveys.has(surveyId)) this._removeTabWidget(tabSurvey);
332
+ });
333
+ }, forceReload);
334
+ };
335
+ this._addSurveyToFocus = (survey)=>{
336
+ if (!(0, core_namespaceObject.isNull)(this._surveyInFocus)) survey_utils_js_namespaceObject.SURVEY_LOGGER.error(`Survey ${this._surveyInFocus} already in focus. Cannot add survey ${survey.id}.`);
337
+ this._surveyInFocus = survey.id;
338
+ };
339
+ this._removeSurveyFromFocus = (survey)=>{
340
+ if (this._surveyInFocus !== survey.id) survey_utils_js_namespaceObject.SURVEY_LOGGER.error(`Survey ${survey.id} is not in focus. Cannot remove survey ${survey.id}.`);
341
+ this._clearSurveyTimeout(survey.id);
342
+ this._surveyInFocus = null;
343
+ this._currentLanguage = null;
344
+ this._surveyIsRendered = false;
345
+ this._surveyPopupProps = null;
346
+ this._displayOptions = void 0;
347
+ this._removeSurveyFromDom(survey);
348
+ };
349
+ this._host = posthog;
350
+ this._surveyInFocus = null;
351
+ this._languageChangeListener = ()=>this._onLanguageChange();
352
+ (0, general_utils_js_namespaceObject.addEventListener)(window, 'languagechange', this._languageChangeListener);
353
+ this._unsubscribeFeatureFlags = posthog.client?.getExtension(external_extension_tokens_js_namespaceObject.FeatureFlagsCommonExtension)?.onFeatureFlags(()=>this._onLanguageChange()) ?? null;
354
+ }
355
+ _onLanguageChange() {
356
+ if ((0, core_namespaceObject.isNull)(this._surveyInFocus)) return;
357
+ const surveys = this._host.client?.kv.get(external_surveys_config_js_namespaceObject.SURVEYS);
358
+ const survey = surveys?.find((s)=>s.id === this._surveyInFocus);
359
+ if (!survey) return;
360
+ const { survey: translatedSurvey, language: newLanguage } = this._translateSurveyForRendering(survey);
361
+ if (newLanguage === this._currentLanguage) return;
362
+ this._currentLanguage = newLanguage;
363
+ if (!this._surveyIsRendered) return;
364
+ const overriddenSurvey = this._applyDisplayOverrides(translatedSurvey, this._displayOptions);
365
+ const { shadow } = (0, surveys_extension_utils_js_namespaceObject.retrieveSurveyShadow)(overriddenSurvey, this._host);
366
+ (0, external_preact_namespaceObject.render)(/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(SurveyPopup, {
367
+ ...this._surveyPopupProps,
368
+ posthog: this._host,
369
+ survey: overriddenSurvey,
370
+ removeSurveyFromFocus: this._removeSurveyFromFocus,
371
+ surveyLanguage: newLanguage
372
+ }), shadow);
373
+ }
374
+ _applyDisplayOverrides(survey, options) {
375
+ return options?.position || options?.selector ? {
376
+ ...survey,
377
+ appearance: {
378
+ ...survey.appearance,
379
+ ...options.position && {
380
+ position: options.position
381
+ },
382
+ ...options.selector && {
383
+ widgetSelector: options.selector
384
+ }
385
+ }
386
+ } : survey;
387
+ }
388
+ _clearSurveyTimeout(surveyId) {
389
+ const timeout = this._surveyTimeouts.get(surveyId);
390
+ if (timeout) {
391
+ clearTimeout(timeout);
392
+ this._surveyTimeouts.delete(surveyId);
393
+ }
394
+ }
395
+ cancelSurvey(surveyId) {
396
+ if (!this._surveyTimeouts.has(surveyId)) return;
397
+ survey_utils_js_namespaceObject.SURVEY_LOGGER.info(`Cancelled pending survey ${surveyId}`);
398
+ this._clearSurveyTimeout(surveyId);
399
+ if (this._surveyInFocus === surveyId) {
400
+ this._surveyInFocus = null;
401
+ this._currentLanguage = null;
402
+ this._surveyIsRendered = false;
403
+ this._surveyPopupProps = null;
404
+ this._displayOptions = void 0;
405
+ }
406
+ }
407
+ startAutomaticDisplay() {
408
+ if (this._disposed || this._automaticDisplayDispose || false === this._host.config.automaticDisplay) return;
409
+ this._automaticDisplayDispose = ()=>{};
410
+ const dispose = startAutomaticDisplay(this);
411
+ if (this._disposed) dispose();
412
+ else this._automaticDisplayDispose = dispose;
413
+ }
414
+ clearInMemoryInProgressSurveyState() {
415
+ (0, surveys_extension_utils_js_namespaceObject.clearAllInMemoryInProgressSurveyState)();
416
+ }
417
+ dispose() {
418
+ this._disposed = true;
419
+ this._automaticDisplayDispose?.();
420
+ this._automaticDisplayDispose = void 0;
421
+ if (this._languageChangeListener) {
422
+ window.removeEventListener('languagechange', this._languageChangeListener);
423
+ this._languageChangeListener = null;
424
+ }
425
+ if (this._unsubscribeFeatureFlags) {
426
+ this._unsubscribeFeatureFlags();
427
+ this._unsubscribeFeatureFlags = null;
428
+ }
429
+ this._surveyTimeouts.forEach((_timeout, surveyId)=>this._clearSurveyTimeout(surveyId));
430
+ this._widgetSelectorListeners.forEach((_listener, surveyId)=>this._detachWidgetSelectorListener(surveyId));
431
+ this._renderedTargets.forEach((container, target)=>{
432
+ (0, external_preact_namespaceObject.render)(null, target);
433
+ container?.remove();
434
+ });
435
+ this._renderedTargets.clear();
436
+ this._renderedTabWidgets.clear();
437
+ this._surveyInFocus = null;
438
+ }
439
+ _sortSurveysByAppearanceDelay(surveys) {
440
+ return surveys.sort((a, b)=>{
441
+ const isSurveyInProgressA = (0, surveys_extension_utils_js_namespaceObject.isSurveyInProgress)(a);
442
+ const isSurveyInProgressB = (0, surveys_extension_utils_js_namespaceObject.isSurveyInProgress)(b);
443
+ if (isSurveyInProgressA && !isSurveyInProgressB) return -1;
444
+ if (!isSurveyInProgressA && isSurveyInProgressB) return 1;
445
+ const aIsAlways = a.schedule === external_survey_constants_js_namespaceObject.SurveySchedule.Always;
446
+ const bIsAlways = b.schedule === external_survey_constants_js_namespaceObject.SurveySchedule.Always;
447
+ if (aIsAlways && !bIsAlways) return 1;
448
+ if (!aIsAlways && bIsAlways) return -1;
449
+ return (a.appearance?.surveyPopupDelaySeconds || 0) - (b.appearance?.surveyPopupDelaySeconds || 0);
450
+ });
451
+ }
452
+ _translateSurveyForRendering(survey) {
453
+ return (0, survey_translations_js_namespaceObject.applySurveyTranslationForUser)(survey, this._host);
454
+ }
455
+ _handleUrlPrefill(survey, surveyLanguage, properties) {
456
+ if (this._prefillHandledSurveys.has(survey.id)) return false;
457
+ const { params } = (0, survey_url_prefill_js_namespaceObject.extractPrefillParamsFromUrl)(window.location.search);
458
+ if (0 === Object.keys(params).length) return false;
459
+ survey_utils_js_namespaceObject.SURVEY_LOGGER.info('[Survey Prefill] Detected URL prefill parameters');
460
+ const result = this._processPrefillData(survey, params, surveyLanguage);
461
+ if (!result) return false;
462
+ this._autoSubmitPrefilledResponses(survey, result, properties, surveyLanguage);
463
+ this._prefillHandledSurveys.add(survey.id);
464
+ return result.isSurveyCompleted;
465
+ }
466
+ _autoSubmitPrefilledResponses(survey, result, properties, surveyLanguage) {
467
+ const { responses, submissionId, isSurveyCompleted, skippedResponses } = result;
468
+ const shouldAutoSubmitPrefilled = Object.keys(skippedResponses).length > 0 && survey.enable_partial_responses;
469
+ if (shouldAutoSubmitPrefilled || isSurveyCompleted) (0, surveys_extension_utils_js_namespaceObject.sendSurveyEvent)({
470
+ responses: isSurveyCompleted ? responses : skippedResponses,
471
+ survey,
472
+ surveySubmissionId: submissionId,
473
+ posthog: this._host,
474
+ isSurveyCompleted,
475
+ properties,
476
+ surveyLanguage
477
+ });
478
+ }
479
+ _handleInitialResponses(survey, initialResponses, properties, surveyLanguage) {
480
+ const prefillParams = {};
481
+ for (const [indexStr, value] of Object.entries(initialResponses)){
482
+ const index = parseInt(indexStr);
483
+ prefillParams[index] = (0, core_namespaceObject.isArray)(value) ? value.map(String) : [
484
+ String(value)
485
+ ];
486
+ }
487
+ survey_utils_js_namespaceObject.SURVEY_LOGGER.info('[Survey] Processing initial responses');
488
+ const result = this._processPrefillData(survey, prefillParams, surveyLanguage);
489
+ if (!result) return false;
490
+ this._autoSubmitPrefilledResponses(survey, result, properties, surveyLanguage);
491
+ return result.isSurveyCompleted;
492
+ }
493
+ _processPrefillData(survey, prefillParams, surveyLanguage) {
494
+ try {
495
+ const responses = (0, survey_url_prefill_js_namespaceObject.convertPrefillToResponses)(survey, prefillParams);
496
+ if (0 === Object.keys(responses).length) {
497
+ survey_utils_js_namespaceObject.SURVEY_LOGGER.warn('[Survey Prefill] No valid responses after conversion');
498
+ return null;
499
+ }
500
+ const submissionId = (0, uuidv7_js_namespaceObject.uuidv7)();
501
+ const prefilledIndices = Object.keys(prefillParams).map((k)=>parseInt(k, 10));
502
+ const { startQuestionIndex, skippedResponses, skippedIndices } = (0, survey_url_prefill_js_namespaceObject.calculatePrefillStartIndex)(survey, prefilledIndices, responses);
503
+ const isSurveyCompleted = startQuestionIndex >= survey.questions.length;
504
+ (0, surveys_extension_utils_js_namespaceObject.setInProgressSurveyState)(survey, {
505
+ surveySubmissionId: submissionId,
506
+ responses: responses,
507
+ lastQuestionIndex: startQuestionIndex,
508
+ questionOrder: (0, surveys_extension_utils_js_namespaceObject.getQuestionOrder)(survey.questions),
509
+ visitedIndices: skippedIndices,
510
+ surveyLanguage
511
+ });
512
+ survey_utils_js_namespaceObject.SURVEY_LOGGER.info('[Survey Prefill] Stored prefilled responses in localStorage');
513
+ return {
514
+ responses,
515
+ submissionId,
516
+ startQuestionIndex,
517
+ isSurveyCompleted,
518
+ skippedResponses
519
+ };
520
+ } catch (error) {
521
+ survey_utils_js_namespaceObject.SURVEY_LOGGER.error('[Survey Prefill] Error handling prefill:', error);
522
+ return null;
523
+ }
524
+ }
525
+ _isSurveyFeatureFlagEnabled(flagKey, flagVariant) {
526
+ if (!flagKey) return true;
527
+ const featureFlags = this._host.client?.getExtension(external_extension_tokens_js_namespaceObject.FeatureFlagsCommonExtension);
528
+ const isFeatureEnabled = !!featureFlags?.isFeatureEnabled(flagKey, {
529
+ send_event: !flagKey.startsWith(SURVEY_TARGETING_FLAG_PREFIX)
530
+ });
531
+ let flagVariantCheck = true;
532
+ if (flagVariant) {
533
+ const flagVariantValue = featureFlags?.getFeatureFlag(flagKey, {
534
+ send_event: false
535
+ });
536
+ flagVariantCheck = flagVariantValue === flagVariant || 'any' === flagVariant;
537
+ }
538
+ const enabled = isFeatureEnabled && flagVariantCheck;
539
+ if (!enabled) this._warnIfFeatureFlagsDisabled(flagKey);
540
+ return enabled;
541
+ }
542
+ _warnIfFeatureFlagsDisabled(flagKey) {
543
+ if (this._loggedFeatureFlagsDisabledWarning || false !== this._host.config.featureFlagEvaluation) return;
544
+ this._loggedFeatureFlagsDisabledWarning = true;
545
+ survey_utils_js_namespaceObject.SURVEY_LOGGER.warn(`Survey feature flag "${flagKey}" evaluated to false because advanced_disable_feature_flags is set. PostHog creates an internal targeting flag for almost every survey, so no survey can display while flags are disabled. To keep surveys working, replace advanced_disable_feature_flags with advanced_only_evaluate_survey_feature_flags, which evaluates survey flags only.`);
546
+ }
547
+ _isSurveyConditionMatched(survey) {
548
+ if (!survey.conditions) return true;
549
+ return (0, surveys_extension_utils_js_namespaceObject.doesSurveyUrlMatch)(survey, this._host) && (0, surveys_extension_utils_js_namespaceObject.doesSurveyDeviceTypesMatch)(survey) && (0, surveys_extension_utils_js_namespaceObject.doesSurveyMatchSelector)(survey);
550
+ }
551
+ _internalFlagCheckSatisfied(survey) {
552
+ if ((0, surveys_extension_utils_js_namespaceObject.canActivateRepeatedly)(survey)) return {
553
+ satisfied: true
554
+ };
555
+ if (survey.internal_targeting_flag_key && (0, survey_utils_js_namespaceObject.isSurveyIterationBased)(survey) && !this._host.client?.getExtension(external_extension_tokens_js_namespaceObject.FeatureFlagsCommonExtension)?.hasLoadedFlags) {
556
+ this._warnIfFeatureFlagsDisabled(survey.internal_targeting_flag_key);
557
+ return {
558
+ satisfied: false,
559
+ reason: 'Feature flags have not loaded yet; deferring internal targeting flag check'
560
+ };
561
+ }
562
+ return {
563
+ satisfied: this._isSurveyFeatureFlagEnabled(survey.internal_targeting_flag_key)
564
+ };
565
+ }
566
+ checkSurveyEligibility(survey) {
567
+ const eligibility = {
568
+ eligible: true,
569
+ reason: void 0
570
+ };
571
+ if (!(0, survey_utils_js_namespaceObject.isSurveyRunning)(survey)) {
572
+ eligibility.eligible = false;
573
+ eligibility.reason = `Survey is not running. It was completed on ${survey.end_date}`;
574
+ return eligibility;
575
+ }
576
+ if (!survey_utils_js_namespaceObject.IN_APP_SURVEY_TYPES.includes(survey.type)) {
577
+ eligibility.eligible = false;
578
+ eligibility.reason = `Surveys of type ${survey.type} are never eligible to be shown in the app`;
579
+ return eligibility;
580
+ }
581
+ const linkedFlagVariant = survey.conditions?.linkedFlagVariant;
582
+ if (!this._isSurveyFeatureFlagEnabled(survey.linked_flag_key, linkedFlagVariant)) {
583
+ eligibility.eligible = false;
584
+ if (linkedFlagVariant) eligibility.reason = `Survey linked feature flag is not enabled for variant ${linkedFlagVariant}`;
585
+ else eligibility.reason = "Survey linked feature flag is not enabled";
586
+ return eligibility;
587
+ }
588
+ if (!this._isSurveyFeatureFlagEnabled(survey.targeting_flag_key)) {
589
+ eligibility.eligible = false;
590
+ eligibility.reason = "Survey targeting feature flag is not enabled";
591
+ return eligibility;
592
+ }
593
+ const internalFlagCheck = this._internalFlagCheckSatisfied(survey);
594
+ if (!internalFlagCheck.satisfied) {
595
+ eligibility.eligible = false;
596
+ eligibility.reason = internalFlagCheck.reason ?? 'Survey internal targeting flag is not enabled and survey cannot activate repeatedly and survey is not in progress';
597
+ return eligibility;
598
+ }
599
+ if (!(0, surveys_extension_utils_js_namespaceObject.hasWaitPeriodPassed)(survey.conditions?.seenSurveyWaitPeriodInDays)) {
600
+ eligibility.eligible = false;
601
+ eligibility.reason = "Survey wait period has not passed";
602
+ return eligibility;
603
+ }
604
+ if ((0, surveys_extension_utils_js_namespaceObject.getSurveySeen)(survey)) {
605
+ eligibility.eligible = false;
606
+ eligibility.reason = "Survey has already been seen and it can't be activated again";
607
+ }
608
+ return eligibility;
609
+ }
610
+ checkSurveyCaptureEligibility() {
611
+ if (!this._host.client?.canCapture) return {
612
+ eligible: false,
613
+ reason: survey_utils_js_namespaceObject.SURVEY_CAPTURING_DISABLED
614
+ };
615
+ return {
616
+ eligible: true
617
+ };
618
+ }
619
+ checkSurveyDisplayEligibility(survey) {
620
+ const captureEligibility = this.checkSurveyCaptureEligibility();
621
+ if (!captureEligibility.eligible) return captureEligibility;
622
+ return this.checkSurveyEligibility(survey);
623
+ }
624
+ checkSurveyRenderability(survey) {
625
+ const eligibility = this.checkSurveyDisplayEligibility(survey);
626
+ if (eligibility.eligible && !this._hasActionOrEventTriggeredSurvey(survey)) return {
627
+ eligible: false,
628
+ reason: "Survey event/action trigger has not been fired yet"
629
+ };
630
+ return eligibility;
631
+ }
632
+ _hasActionOrEventTriggeredSurvey(survey) {
633
+ if (!(0, survey_utils_js_namespaceObject.doesSurveyActivateByEvent)(survey) && !(0, survey_utils_js_namespaceObject.doesSurveyActivateByAction)(survey)) return true;
634
+ const surveysActivatedByEventsOrActions = this._host.surveys?._surveyEventReceiver?.getSurveys();
635
+ return !!surveysActivatedByEventsOrActions?.includes(survey.id);
636
+ }
637
+ _checkFlags(survey) {
638
+ if (!survey.feature_flag_keys?.length) return true;
639
+ return survey.feature_flag_keys.every(({ key, value })=>{
640
+ if (!key || !value) return true;
641
+ return this._isSurveyFeatureFlagEnabled(value);
642
+ });
643
+ }
644
+ _shouldDisplaySurvey(survey) {
645
+ return this.checkSurveyEligibility(survey).eligible && this._isSurveyConditionMatched(survey) && this._hasActionOrEventTriggeredSurvey(survey) && this._checkFlags(survey);
646
+ }
647
+ _removeSurveyFromDom(survey) {
648
+ try {
649
+ const shadowContainer = document.querySelector((0, surveys_extension_utils_js_namespaceObject.getSurveyContainerClass)(survey, true));
650
+ if (shadowContainer?.shadowRoot) {
651
+ (0, external_preact_namespaceObject.render)(null, shadowContainer.shadowRoot);
652
+ this._renderedTargets.delete(shadowContainer.shadowRoot);
653
+ }
654
+ shadowContainer?.remove();
655
+ } catch (error) {
656
+ survey_utils_js_namespaceObject.SURVEY_LOGGER.warn(`Failed to remove survey ${survey.id} from DOM:`, error);
657
+ }
658
+ }
659
+ getTestAPI() {
660
+ return {
661
+ addSurveyToFocus: this._addSurveyToFocus,
662
+ removeSurveyFromFocus: this._removeSurveyFromFocus,
663
+ surveyInFocus: this._surveyInFocus,
664
+ surveyTimeouts: this._surveyTimeouts,
665
+ handleWidget: this._handleWidget,
666
+ handlePopoverSurvey: this.handlePopoverSurvey,
667
+ manageWidgetSelectorListener: this._manageWidgetSelectorListener,
668
+ sortSurveysByAppearanceDelay: this._sortSurveysByAppearanceDelay.bind(this),
669
+ checkFlags: this._checkFlags.bind(this),
670
+ isSurveyFeatureFlagEnabled: this._isSurveyFeatureFlagEnabled.bind(this),
671
+ onLanguageChange: this._onLanguageChange.bind(this),
672
+ currentLanguage: this._currentLanguage,
673
+ surveyIsRendered: this._surveyIsRendered
674
+ };
675
+ }
676
+ }
677
+ const DEFAULT_PREVIEW_POSITION_STYLES = {
678
+ position: 'relative',
679
+ left: 'unset',
680
+ right: 'unset',
681
+ top: 'unset',
682
+ bottom: 'unset',
683
+ transform: 'unset'
684
+ };
685
+ const renderSurveysPreview = ({ survey, parentElement, previewPageIndex, forceDisableHtml, onPreviewSubmit, onPreviewBack, posthog, positionStyles = DEFAULT_PREVIEW_POSITION_STYLES })=>{
686
+ const currentStyle = parentElement.querySelector('style[data-ph-survey-style]');
687
+ if (currentStyle) currentStyle.remove();
688
+ const stylesheet = (0, surveys_extension_utils_js_namespaceObject.getSurveyStylesheet)();
689
+ if (stylesheet) {
690
+ parentElement.appendChild(stylesheet);
691
+ (0, surveys_extension_utils_js_namespaceObject.addSurveyCSSVariablesToElement)(parentElement, survey.type, survey.appearance);
692
+ }
693
+ (0, external_preact_namespaceObject.render)(/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(SurveyPopup, {
694
+ survey: survey,
695
+ posthog: posthog,
696
+ forceDisableHtml: forceDisableHtml,
697
+ style: positionStyles,
698
+ onPreviewSubmit: onPreviewSubmit,
699
+ onPreviewBack: onPreviewBack,
700
+ previewPageIndex: previewPageIndex,
701
+ removeSurveyFromFocus: ()=>{}
702
+ }), parentElement);
703
+ };
704
+ const renderFeedbackWidgetPreview = ({ survey, root, forceDisableHtml, posthog })=>{
705
+ const stylesheet = (0, surveys_extension_utils_js_namespaceObject.getSurveyStylesheet)();
706
+ if (stylesheet) {
707
+ root.appendChild(stylesheet);
708
+ (0, surveys_extension_utils_js_namespaceObject.addSurveyCSSVariablesToElement)(root, survey.type, survey.appearance);
709
+ }
710
+ (0, external_preact_namespaceObject.render)(/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(FeedbackWidget, {
711
+ forceDisableHtml: forceDisableHtml,
712
+ survey: survey,
713
+ posthog: posthog,
714
+ readOnly: true
715
+ }), root);
716
+ };
717
+ function generateSurveys(posthog, isSurveysEnabled) {
718
+ if ("u" < typeof document || "u" < typeof window) return;
719
+ const surveyManager = new SurveyManager(posthog);
720
+ if (false === posthog.config.automaticDisplay) {
721
+ survey_utils_js_namespaceObject.SURVEY_LOGGER.info('Surveys automatic display is disabled. Skipping call surveys and evaluate display logic.');
722
+ return surveyManager;
723
+ }
724
+ if (false === isSurveysEnabled) {
725
+ survey_utils_js_namespaceObject.SURVEY_LOGGER.info('There are no surveys to load or Surveys is disabled in the project settings.');
726
+ return surveyManager;
727
+ }
728
+ surveyManager.startAutomaticDisplay();
729
+ return surveyManager;
730
+ }
731
+ function startAutomaticDisplay(surveyManager) {
732
+ surveyManager.callSurveysAndEvaluateDisplayLogic(true);
733
+ let intervalId;
734
+ const startInterval = ()=>{
735
+ if (!(0, core_namespaceObject.isUndefined)(intervalId)) return;
736
+ intervalId = setInterval(()=>{
737
+ surveyManager.callSurveysAndEvaluateDisplayLogic(false);
738
+ }, 1000);
739
+ };
740
+ const stopInterval = ()=>{
741
+ if (!(0, core_namespaceObject.isUndefined)(intervalId)) {
742
+ clearInterval(intervalId);
743
+ intervalId = void 0;
744
+ }
745
+ };
746
+ startInterval();
747
+ const onVisibilityChange = ()=>{
748
+ if (document.hidden) stopInterval();
749
+ else {
750
+ surveyManager.callSurveysAndEvaluateDisplayLogic(false);
751
+ startInterval();
752
+ }
753
+ };
754
+ (0, general_utils_js_namespaceObject.addEventListener)(document, 'visibilitychange', onVisibilityChange);
755
+ return ()=>{
756
+ stopInterval();
757
+ document.removeEventListener('visibilitychange', onVisibilityChange);
758
+ };
759
+ }
760
+ function useHideSurveyOnURLChange({ survey, removeSurveyFromFocus = ()=>{}, setSurveyVisible, isPreviewMode = false, posthog }) {
761
+ (0, hooks_namespaceObject.useEffect)(()=>{
762
+ if (isPreviewMode || !survey.conditions?.url) return;
763
+ const checkUrlMatch = ()=>{
764
+ const isSurveyTypeWidget = survey.type === external_survey_constants_js_namespaceObject.SurveyType.Widget;
765
+ const doesSurveyMatchUrlCondition = (0, surveys_extension_utils_js_namespaceObject.doesSurveyUrlMatch)(survey, posthog);
766
+ const isSurveyWidgetTypeTab = survey.appearance?.widgetType === external_survey_constants_js_namespaceObject.SurveyWidgetType.Tab && isSurveyTypeWidget;
767
+ if (doesSurveyMatchUrlCondition) {
768
+ if (isSurveyWidgetTypeTab) {
769
+ survey_utils_js_namespaceObject.SURVEY_LOGGER.info(`Showing survey ${survey.id} because it is a feedback button tab and URL matches`);
770
+ setSurveyVisible(true);
771
+ }
772
+ return;
773
+ }
774
+ survey_utils_js_namespaceObject.SURVEY_LOGGER.info(`Hiding survey ${survey.id} because URL does not match`);
775
+ setSurveyVisible(false);
776
+ return removeSurveyFromFocus(survey);
777
+ };
778
+ (0, general_utils_js_namespaceObject.addEventListener)(window, 'popstate', checkUrlMatch);
779
+ (0, general_utils_js_namespaceObject.addEventListener)(window, 'hashchange', checkUrlMatch);
780
+ const originalPushState = window.history.pushState;
781
+ const originalReplaceState = window.history.replaceState;
782
+ window.history.pushState = function(...args) {
783
+ originalPushState.apply(this, args);
784
+ checkUrlMatch();
785
+ };
786
+ window.history.replaceState = function(...args) {
787
+ originalReplaceState.apply(this, args);
788
+ checkUrlMatch();
789
+ };
790
+ return ()=>{
791
+ window.removeEventListener('popstate', checkUrlMatch);
792
+ window.removeEventListener('hashchange', checkUrlMatch);
793
+ window.history.pushState = originalPushState;
794
+ window.history.replaceState = originalReplaceState;
795
+ };
796
+ }, [
797
+ isPreviewMode,
798
+ survey,
799
+ removeSurveyFromFocus,
800
+ setSurveyVisible,
801
+ posthog
802
+ ]);
803
+ }
804
+ const CLOSE_ANIMATION_DURATION_MS = 200;
805
+ function usePopupVisibility(survey, posthog, millisecondDelay, isPreviewMode, removeSurveyFromFocus, isPopup, surveyContainerRef, skipShownEvent, surveyLanguage) {
806
+ const [isPopupVisible, setIsPopupVisible] = (0, hooks_namespaceObject.useState)(isPreviewMode || 0 === millisecondDelay || survey.type === external_survey_constants_js_namespaceObject.SurveyType.ExternalSurvey);
807
+ const [isSurveySent, setIsSurveySent] = (0, hooks_namespaceObject.useState)(false);
808
+ const isClosingRef = (0, hooks_namespaceObject.useRef)(false);
809
+ const hidePopupWithAnimation = ()=>{
810
+ const removeDOMAndHidePopup = ()=>{
811
+ if (isPopup) removeSurveyFromFocus(survey);
812
+ setIsPopupVisible(false);
813
+ };
814
+ if (isClosingRef.current) return;
815
+ const container = surveyContainerRef?.current;
816
+ if (!container) return void removeDOMAndHidePopup();
817
+ isClosingRef.current = true;
818
+ container.style.transition = `opacity ${CLOSE_ANIMATION_DURATION_MS}ms ease-out`;
819
+ container.style.opacity = '0';
820
+ setTimeout(()=>{
821
+ isClosingRef.current = false;
822
+ removeDOMAndHidePopup();
823
+ }, CLOSE_ANIMATION_DURATION_MS + 50);
824
+ };
825
+ const handleSurveyClosed = (event)=>{
826
+ if (event.detail.surveyId !== survey.id) return;
827
+ hidePopupWithAnimation();
828
+ };
829
+ (0, hooks_namespaceObject.useEffect)(()=>{
830
+ if (!posthog) return void survey_utils_js_namespaceObject.SURVEY_LOGGER.error('usePopupVisibility hook called without a PostHog instance.');
831
+ if (isPreviewMode) return;
832
+ let autoDisappearTimeout;
833
+ const handleSurveySent = (event)=>{
834
+ if (event.detail.surveyId !== survey.id) return;
835
+ if (!survey.appearance?.displayThankYouMessage) return hidePopupWithAnimation();
836
+ setIsSurveySent(true);
837
+ if (survey.appearance?.autoDisappear) {
838
+ if (autoDisappearTimeout) clearTimeout(autoDisappearTimeout);
839
+ autoDisappearTimeout = setTimeout(hidePopupWithAnimation, 5000);
840
+ }
841
+ };
842
+ const showSurvey = ()=>{
843
+ if (!(0, surveys_extension_utils_js_namespaceObject.doesSurveyUrlMatch)(survey, posthog)) return;
844
+ setIsPopupVisible(true);
845
+ try {
846
+ localStorage.setItem('lastSeenSurveyDate', new Date().toISOString());
847
+ } catch {}
848
+ window.dispatchEvent(new Event('PHSurveyShown'));
849
+ if (!skipShownEvent) posthog.client?.capture(external_survey_constants_js_namespaceObject.SurveyEventName.SHOWN, {
850
+ [external_survey_constants_js_namespaceObject.SurveyEventProperties.SURVEY_NAME]: survey.name,
851
+ [external_survey_constants_js_namespaceObject.SurveyEventProperties.SURVEY_ID]: survey.id,
852
+ [external_survey_constants_js_namespaceObject.SurveyEventProperties.SURVEY_ITERATION]: survey.current_iteration,
853
+ [external_survey_constants_js_namespaceObject.SurveyEventProperties.SURVEY_ITERATION_START_DATE]: survey.current_iteration_start_date,
854
+ ...surveyLanguage && {
855
+ [external_survey_constants_js_namespaceObject.SurveyEventProperties.SURVEY_LANGUAGE]: surveyLanguage
856
+ },
857
+ sessionRecordingUrl: (0, external_survey_render_context_js_namespaceObject.getSurveyReplayUrl)(posthog)
858
+ });
859
+ };
860
+ (0, general_utils_js_namespaceObject.addEventListener)(window, 'PHSurveyClosed', handleSurveyClosed);
861
+ (0, general_utils_js_namespaceObject.addEventListener)(window, 'PHSurveySent', handleSurveySent);
862
+ const showTimeout = millisecondDelay > 0 ? setTimeout(showSurvey, millisecondDelay) : void 0;
863
+ if ((0, core_namespaceObject.isUndefined)(showTimeout)) showSurvey();
864
+ return ()=>{
865
+ if (!(0, core_namespaceObject.isUndefined)(showTimeout)) clearTimeout(showTimeout);
866
+ if (!(0, core_namespaceObject.isUndefined)(autoDisappearTimeout)) clearTimeout(autoDisappearTimeout);
867
+ window.removeEventListener('PHSurveyClosed', handleSurveyClosed);
868
+ window.removeEventListener('PHSurveySent', handleSurveySent);
869
+ };
870
+ }, []);
871
+ useHideSurveyOnURLChange({
872
+ survey,
873
+ removeSurveyFromFocus,
874
+ setSurveyVisible: setIsPopupVisible,
875
+ isPreviewMode,
876
+ posthog
877
+ });
878
+ return {
879
+ isPopupVisible,
880
+ isSurveySent,
881
+ setIsPopupVisible,
882
+ hidePopupWithAnimation
883
+ };
884
+ }
885
+ function getTabPositionStyles(position = external_survey_constants_js_namespaceObject.SurveyTabPosition.Right) {
886
+ switch(position){
887
+ case external_survey_constants_js_namespaceObject.SurveyTabPosition.Top:
888
+ return {
889
+ top: '0',
890
+ left: '50%',
891
+ transform: 'translateX(-50%)'
892
+ };
893
+ case external_survey_constants_js_namespaceObject.SurveyTabPosition.Left:
894
+ return {
895
+ top: '50%',
896
+ left: '0',
897
+ transform: 'rotate(90deg) translateY(-100%)',
898
+ transformOrigin: 'left top'
899
+ };
900
+ case external_survey_constants_js_namespaceObject.SurveyTabPosition.Bottom:
901
+ return {
902
+ bottom: '0',
903
+ left: '50%',
904
+ transform: 'translateX(-50%)'
905
+ };
906
+ default:
907
+ case external_survey_constants_js_namespaceObject.SurveyTabPosition.Right:
908
+ return {
909
+ top: '50%',
910
+ right: '0',
911
+ transform: 'rotate(-90deg) translateY(-100%)',
912
+ transformOrigin: 'right top'
913
+ };
914
+ }
915
+ }
916
+ function SurveyPopup({ survey, forceDisableHtml, posthog, style = {}, previewPageIndex, removeSurveyFromFocus = ()=>{}, isPopup = true, onPreviewSubmit = ()=>{}, onPreviewBack = ()=>{}, onPopupSurveyDismissed = ()=>{}, onCloseConfirmationMessage = ()=>{}, properties, isSurveyCompleted, skipShownEvent, surveyLanguage }) {
917
+ const surveyContainerRef = (0, hooks_namespaceObject.useRef)(null);
918
+ const isPreviewMode = Number.isInteger(previewPageIndex);
919
+ const surveyPopupDelayMilliseconds = survey.appearance?.surveyPopupDelaySeconds ? 1000 * survey.appearance.surveyPopupDelaySeconds : 0;
920
+ const { isPopupVisible, isSurveySent, hidePopupWithAnimation } = usePopupVisibility(survey, posthog, surveyPopupDelayMilliseconds, isPreviewMode, removeSurveyFromFocus, isPopup, surveyContainerRef, skipShownEvent, surveyLanguage);
921
+ const shouldShowConfirmation = isSurveySent || previewPageIndex === survey.questions.length || true === isSurveyCompleted;
922
+ const [introScreenDismissed, setIntroScreenDismissed] = (0, hooks_namespaceObject.useState)(false);
923
+ const hasInProgressState = (0, hooks_namespaceObject.useMemo)(()=>!!(0, surveys_extension_utils_js_namespaceObject.getInProgressSurveyState)(survey), [
924
+ survey
925
+ ]);
926
+ const hasIntroContent = !!(survey.appearance?.introScreenHeader || survey.appearance?.introScreenDescription);
927
+ const shouldShowIntroScreen = isPreviewMode ? previewPageIndex === INTRO_SCREEN_PREVIEW_INDEX : !!survey.appearance?.displayIntroScreen && hasIntroContent && !introScreenDismissed && !hasInProgressState;
928
+ const surveyContextValue = (0, hooks_namespaceObject.useMemo)(()=>{
929
+ const getInProgressSurvey = (0, surveys_extension_utils_js_namespaceObject.getInProgressSurveyState)(survey);
930
+ const surveySubmissionId = getInProgressSurvey?.surveySubmissionId || (0, uuidv7_js_namespaceObject.uuidv7)() || '';
931
+ return {
932
+ isPreviewMode,
933
+ previewPageIndex: previewPageIndex,
934
+ onPopupSurveyDismissed: ()=>{
935
+ if (surveyLanguage) (0, surveys_extension_utils_js_namespaceObject.dismissedSurveyEvent)(survey, posthog, isPreviewMode, surveyLanguage);
936
+ else (0, surveys_extension_utils_js_namespaceObject.dismissedSurveyEvent)(survey, posthog, isPreviewMode);
937
+ onPopupSurveyDismissed();
938
+ },
939
+ isPopup: isPopup || false,
940
+ surveySubmissionId,
941
+ onPreviewSubmit,
942
+ onPreviewBack,
943
+ posthog,
944
+ properties,
945
+ surveyLanguage
946
+ };
947
+ }, [
948
+ isPreviewMode,
949
+ previewPageIndex,
950
+ isPopup,
951
+ posthog,
952
+ survey,
953
+ onPopupSurveyDismissed,
954
+ onPreviewSubmit,
955
+ onPreviewBack,
956
+ properties,
957
+ surveyLanguage
958
+ ]);
959
+ if (!isPopupVisible) return null;
960
+ return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(surveys_extension_utils_js_namespaceObject.SurveyContext.Provider, {
961
+ value: surveyContextValue,
962
+ children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
963
+ className: "ph-survey",
964
+ style: {
965
+ ...(0, surveys_extension_utils_js_namespaceObject.getPopoverPosition)(survey.type, survey.appearance?.position, survey.appearance?.widgetType),
966
+ ...style
967
+ },
968
+ ref: surveyContainerRef,
969
+ children: shouldShowConfirmation ? /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(ConfirmationMessage_js_namespaceObject.ConfirmationMessage, {
970
+ header: survey.appearance?.thankYouMessageHeader || 'Thank you!',
971
+ description: survey.appearance?.thankYouMessageDescription || '',
972
+ forceDisableHtml: !!forceDisableHtml,
973
+ contentType: survey.appearance?.thankYouMessageDescriptionContentType,
974
+ appearance: survey.appearance || surveys_extension_utils_js_namespaceObject.defaultSurveyAppearance,
975
+ onClose: ()=>{
976
+ hidePopupWithAnimation();
977
+ onCloseConfirmationMessage();
978
+ }
979
+ }) : shouldShowIntroScreen ? /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(IntroScreen_js_namespaceObject.IntroScreen, {
980
+ header: survey.appearance?.introScreenHeader || '',
981
+ description: survey.appearance?.introScreenDescription || '',
982
+ forceDisableHtml: !!forceDisableHtml,
983
+ contentType: survey.appearance?.introScreenDescriptionContentType,
984
+ appearance: survey.appearance || surveys_extension_utils_js_namespaceObject.defaultSurveyAppearance,
985
+ onStart: ()=>setIntroScreenDismissed(true)
986
+ }) : /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(Questions, {
987
+ survey: survey,
988
+ forceDisableHtml: !!forceDisableHtml,
989
+ posthog: posthog
990
+ })
991
+ })
992
+ });
993
+ }
994
+ function Questions({ survey, forceDisableHtml, posthog }) {
995
+ const initialInProgressState = (0, hooks_namespaceObject.useMemo)(()=>{
996
+ const state = (0, surveys_extension_utils_js_namespaceObject.getInProgressSurveyState)(survey);
997
+ if (!state) return null;
998
+ const hasIndex = (0, core_namespaceObject.isNumber)(state.lastQuestionIndex);
999
+ const isIndexInRange = hasIndex && state.lastQuestionIndex >= 0 && state.lastQuestionIndex < survey.questions.length;
1000
+ if (hasIndex && !isIndexInRange) {
1001
+ (0, surveys_extension_utils_js_namespaceObject.clearInProgressSurveyState)(survey);
1002
+ return null;
1003
+ }
1004
+ return state;
1005
+ }, [
1006
+ survey
1007
+ ]);
1008
+ const [questionsResponses, setQuestionsResponses] = (0, hooks_namespaceObject.useState)(()=>{
1009
+ if (initialInProgressState?.responses) survey_utils_js_namespaceObject.SURVEY_LOGGER.info('Survey is already in progress, filling in initial responses');
1010
+ return initialInProgressState?.responses || {};
1011
+ });
1012
+ const [submissionBlocked, setSubmissionBlocked] = (0, hooks_namespaceObject.useState)(false);
1013
+ const { previewPageIndex, onPopupSurveyDismissed, isPopup, onPreviewSubmit, onPreviewBack, surveySubmissionId, isPreviewMode, properties, surveyLanguage } = (0, hooks_namespaceObject.useContext)(surveys_extension_utils_js_namespaceObject.SurveyContext);
1014
+ const [currentQuestionIndex, setCurrentQuestionIndex] = (0, hooks_namespaceObject.useState)(()=>{
1015
+ const savedIndex = initialInProgressState?.lastQuestionIndex;
1016
+ const validSavedIndex = (0, core_namespaceObject.isNumber)(savedIndex) && savedIndex >= 0 && savedIndex < survey.questions.length ? savedIndex : 0;
1017
+ return (0, core_namespaceObject.isNumber)(previewPageIndex) && previewPageIndex >= 0 ? previewPageIndex : validSavedIndex;
1018
+ });
1019
+ const [visitedIndices, setVisitedIndices] = (0, hooks_namespaceObject.useState)(()=>(initialInProgressState?.visitedIndices ?? []).filter((index)=>index >= 0 && index < survey.questions.length));
1020
+ const [questionSnapshots, setQuestionSnapshots] = (0, hooks_namespaceObject.useState)(()=>{
1021
+ const inProgressSurveyData = (0, surveys_extension_utils_js_namespaceObject.getInProgressSurveyState)(survey);
1022
+ return inProgressSurveyData?.questionSnapshots ?? {};
1023
+ });
1024
+ const questionOrderIds = (0, hooks_namespaceObject.useMemo)(()=>(0, surveys_extension_utils_js_namespaceObject.getQuestionOrder)((0, surveys_extension_utils_js_namespaceObject.getDisplayOrderQuestions)(survey, initialInProgressState)), [
1025
+ survey.id,
1026
+ initialInProgressState
1027
+ ]);
1028
+ const surveyQuestions = (0, hooks_namespaceObject.useMemo)(()=>{
1029
+ const hasUsableIds = !!questionOrderIds && new Set(questionOrderIds).size === questionOrderIds.length;
1030
+ if (!hasUsableIds) return (0, surveys_extension_utils_js_namespaceObject.getDisplayOrderQuestions)(survey, initialInProgressState);
1031
+ const byId = new Map(survey.questions.map((question)=>[
1032
+ question.id,
1033
+ question
1034
+ ]));
1035
+ const mapped = questionOrderIds.map((id)=>byId.get(id)).filter((question)=>!!question);
1036
+ return mapped.length === questionOrderIds.length ? mapped : survey.questions;
1037
+ }, [
1038
+ questionOrderIds,
1039
+ survey.questions,
1040
+ survey,
1041
+ initialInProgressState
1042
+ ]);
1043
+ (0, hooks_namespaceObject.useEffect)(()=>{
1044
+ if (isPreviewMode && !(0, core_namespaceObject.isUndefined)(previewPageIndex) && previewPageIndex >= 0) setCurrentQuestionIndex(previewPageIndex);
1045
+ }, [
1046
+ previewPageIndex,
1047
+ isPreviewMode
1048
+ ]);
1049
+ const onNextButtonClick = ({ res, displayQuestionIndex, questionId })=>{
1050
+ if (!posthog) return void survey_utils_js_namespaceObject.SURVEY_LOGGER.error('onNextButtonClick called without a PostHog instance.');
1051
+ if (!posthog.client?.canCapture) return void setSubmissionBlocked(true);
1052
+ setSubmissionBlocked(false);
1053
+ if (!questionId) return void survey_utils_js_namespaceObject.SURVEY_LOGGER.error('onNextButtonClick called without a questionId.');
1054
+ const { responses: newResponses, questionSnapshots: newSnapshots } = (0, surveys_namespaceObject.recordSurveyAnswer)({
1055
+ responses: questionsResponses,
1056
+ questionSnapshots
1057
+ }, questionId, res, surveyQuestions[displayQuestionIndex]);
1058
+ setQuestionsResponses(newResponses);
1059
+ setQuestionSnapshots(newSnapshots);
1060
+ const nextStep = (0, survey_branching_js_namespaceObject.getNextSurveyStep)(survey, displayQuestionIndex, res);
1061
+ const isSurveyCompleted = nextStep === external_survey_constants_js_namespaceObject.SurveyQuestionBranchingType.End;
1062
+ const newVisitedIndices = [
1063
+ ...visitedIndices,
1064
+ displayQuestionIndex
1065
+ ];
1066
+ if (!isSurveyCompleted) {
1067
+ setVisitedIndices(newVisitedIndices);
1068
+ setCurrentQuestionIndex(nextStep);
1069
+ (0, surveys_extension_utils_js_namespaceObject.setInProgressSurveyState)(survey, {
1070
+ surveySubmissionId: surveySubmissionId,
1071
+ responses: newResponses,
1072
+ lastQuestionIndex: nextStep,
1073
+ questionOrder: (0, surveys_extension_utils_js_namespaceObject.getQuestionOrder)(surveyQuestions),
1074
+ visitedIndices: newVisitedIndices,
1075
+ surveyLanguage,
1076
+ questionSnapshots: newSnapshots
1077
+ });
1078
+ }
1079
+ if (survey.enable_partial_responses || isSurveyCompleted) {
1080
+ const visitedResponseKeys = new Set(newVisitedIndices.map((i)=>surveyQuestions[i]?.id).filter((id)=>!!id).map((id)=>(0, surveys_extension_utils_js_namespaceObject.getSurveyResponseKey)(id)));
1081
+ const responsesOnPath = Object.fromEntries(Object.entries(newResponses).filter(([key])=>visitedResponseKeys.has(key)));
1082
+ (0, surveys_extension_utils_js_namespaceObject.sendSurveyEvent)({
1083
+ responses: responsesOnPath,
1084
+ survey,
1085
+ surveySubmissionId,
1086
+ isSurveyCompleted,
1087
+ posthog,
1088
+ properties,
1089
+ surveyLanguage,
1090
+ questionSnapshots: newSnapshots
1091
+ });
1092
+ }
1093
+ };
1094
+ const onBackButtonClick = ()=>{
1095
+ if (isPreviewMode) return void onPreviewBack();
1096
+ if (0 === visitedIndices.length) return;
1097
+ const previousIndex = visitedIndices[visitedIndices.length - 1];
1098
+ const newVisitedIndices = visitedIndices.slice(0, -1);
1099
+ setVisitedIndices(newVisitedIndices);
1100
+ setCurrentQuestionIndex(previousIndex);
1101
+ (0, surveys_extension_utils_js_namespaceObject.setInProgressSurveyState)(survey, {
1102
+ surveySubmissionId,
1103
+ responses: questionsResponses,
1104
+ lastQuestionIndex: previousIndex,
1105
+ questionOrder: (0, surveys_extension_utils_js_namespaceObject.getQuestionOrder)(surveyQuestions),
1106
+ visitedIndices: newVisitedIndices,
1107
+ surveyLanguage,
1108
+ questionSnapshots
1109
+ });
1110
+ };
1111
+ const canGoBack = !!survey.appearance?.allowGoBack && (isPreviewMode ? (previewPageIndex ?? 0) > 0 : visitedIndices.length > 0);
1112
+ const currentQuestion = surveyQuestions.at(currentQuestionIndex);
1113
+ if (!currentQuestion) return null;
1114
+ const renderCancelButton = isPopup && survey.appearance?.hideCancelButton !== true;
1115
+ return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("form", {
1116
+ className: "survey-form",
1117
+ name: "surveyForm",
1118
+ children: [
1119
+ renderCancelButton && /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(QuestionHeader_js_namespaceObject.Cancel, {
1120
+ onClick: ()=>{
1121
+ onPopupSurveyDismissed();
1122
+ }
1123
+ }),
1124
+ /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("div", {
1125
+ className: "survey-box",
1126
+ "data-question-index": currentQuestionIndex,
1127
+ children: [
1128
+ submissionBlocked && /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("p", {
1129
+ role: "alert",
1130
+ children: "Your response could not be sent. Please try again later."
1131
+ }),
1132
+ getQuestionComponent({
1133
+ question: currentQuestion,
1134
+ forceDisableHtml,
1135
+ displayQuestionIndex: currentQuestionIndex,
1136
+ appearance: survey.appearance || surveys_extension_utils_js_namespaceObject.defaultSurveyAppearance,
1137
+ onSubmit: (res)=>onNextButtonClick({
1138
+ res,
1139
+ displayQuestionIndex: currentQuestionIndex,
1140
+ questionId: currentQuestion.id
1141
+ }),
1142
+ onPreviewSubmit,
1143
+ initialValue: currentQuestion.id ? questionsResponses[(0, surveys_extension_utils_js_namespaceObject.getSurveyResponseKey)(currentQuestion.id)] : void 0,
1144
+ canGoBack,
1145
+ onBack: onBackButtonClick
1146
+ })
1147
+ ]
1148
+ })
1149
+ ]
1150
+ });
1151
+ }
1152
+ function FeedbackWidget({ survey, forceDisableHtml, posthog, readOnly, surveyLanguage }) {
1153
+ const [isFeedbackButtonVisible, setIsFeedbackButtonVisible] = (0, hooks_namespaceObject.useState)(true);
1154
+ const [showSurvey, setShowSurvey] = (0, hooks_namespaceObject.useState)(false);
1155
+ const [styleOverrides, setStyleOverrides] = (0, hooks_namespaceObject.useState)({});
1156
+ const resetTimeout = (0, hooks_namespaceObject.useRef)(void 0);
1157
+ const toggleSurvey = ()=>{
1158
+ if (!showSurvey && posthog && !readOnly && !posthog.client?.canCapture) return;
1159
+ setShowSurvey(!showSurvey);
1160
+ };
1161
+ (0, hooks_namespaceObject.useEffect)(()=>{
1162
+ if (!posthog) return void survey_utils_js_namespaceObject.SURVEY_LOGGER.error('FeedbackWidget called without a PostHog instance.');
1163
+ if (readOnly) return;
1164
+ if (survey.appearance?.widgetType === 'tab') setStyleOverrides({
1165
+ top: '50%',
1166
+ bottom: 'auto'
1167
+ });
1168
+ const handleShowSurvey = (event)=>{
1169
+ const customEvent = event;
1170
+ if (customEvent.detail?.surveyId === survey.id) {
1171
+ survey_utils_js_namespaceObject.SURVEY_LOGGER.info(`Received show event for feedback button survey ${survey.id}`);
1172
+ setStyleOverrides(customEvent.detail.position || {});
1173
+ toggleSurvey();
1174
+ }
1175
+ };
1176
+ (0, general_utils_js_namespaceObject.addEventListener)(window, DISPATCH_FEEDBACK_WIDGET_EVENT, handleShowSurvey);
1177
+ return ()=>{
1178
+ if (!(0, core_namespaceObject.isUndefined)(resetTimeout.current)) {
1179
+ clearTimeout(resetTimeout.current);
1180
+ resetTimeout.current = void 0;
1181
+ }
1182
+ window.removeEventListener(DISPATCH_FEEDBACK_WIDGET_EVENT, handleShowSurvey);
1183
+ };
1184
+ }, [
1185
+ posthog,
1186
+ readOnly,
1187
+ survey.id,
1188
+ survey.appearance?.widgetType,
1189
+ survey.appearance?.widgetSelector,
1190
+ survey.appearance?.borderColor
1191
+ ]);
1192
+ useHideSurveyOnURLChange({
1193
+ survey,
1194
+ setSurveyVisible: setIsFeedbackButtonVisible,
1195
+ posthog
1196
+ });
1197
+ if (!isFeedbackButtonVisible) return null;
1198
+ const resetShowSurvey = ()=>{
1199
+ if (survey.schedule !== external_survey_constants_js_namespaceObject.SurveySchedule.Always) setIsFeedbackButtonVisible(false);
1200
+ if (!(0, core_namespaceObject.isUndefined)(resetTimeout.current)) clearTimeout(resetTimeout.current);
1201
+ resetTimeout.current = setTimeout(()=>{
1202
+ resetTimeout.current = void 0;
1203
+ setShowSurvey(false);
1204
+ }, 200);
1205
+ };
1206
+ return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)(external_preact_namespaceObject.Fragment, {
1207
+ children: [
1208
+ survey.appearance?.widgetType === 'tab' && /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("button", {
1209
+ className: `ph-survey-widget-tab ${survey.appearance?.tabPosition === external_survey_constants_js_namespaceObject.SurveyTabPosition.Top ? 'widget-tab-top' : ''}`,
1210
+ onClick: toggleSurvey,
1211
+ disabled: readOnly,
1212
+ style: getTabPositionStyles(survey.appearance?.tabPosition),
1213
+ children: survey.appearance?.widgetLabel || ''
1214
+ }),
1215
+ showSurvey && /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(SurveyPopup, {
1216
+ posthog: posthog,
1217
+ survey: survey,
1218
+ forceDisableHtml: forceDisableHtml,
1219
+ style: styleOverrides,
1220
+ onPopupSurveyDismissed: resetShowSurvey,
1221
+ onCloseConfirmationMessage: resetShowSurvey,
1222
+ surveyLanguage: surveyLanguage
1223
+ })
1224
+ ]
1225
+ });
1226
+ }
1227
+ const getQuestionComponent = ({ question, forceDisableHtml, displayQuestionIndex, appearance, onSubmit, onPreviewSubmit, initialValue, canGoBack, onBack })=>{
1228
+ const baseProps = {
1229
+ forceDisableHtml,
1230
+ appearance,
1231
+ onPreviewSubmit: (res)=>{
1232
+ onPreviewSubmit(res);
1233
+ },
1234
+ onSubmit: (res)=>{
1235
+ onSubmit(res);
1236
+ },
1237
+ initialValue,
1238
+ displayQuestionIndex,
1239
+ canGoBack,
1240
+ onBack
1241
+ };
1242
+ switch(question.type){
1243
+ case external_survey_constants_js_namespaceObject.SurveyQuestionType.Open:
1244
+ return /*#__PURE__*/ (0, external_preact_namespaceObject.createElement)(QuestionTypes_js_namespaceObject.OpenTextQuestion, {
1245
+ ...baseProps,
1246
+ question: question,
1247
+ key: question.id
1248
+ });
1249
+ case external_survey_constants_js_namespaceObject.SurveyQuestionType.Link:
1250
+ return /*#__PURE__*/ (0, external_preact_namespaceObject.createElement)(QuestionTypes_js_namespaceObject.LinkQuestion, {
1251
+ ...baseProps,
1252
+ question: question,
1253
+ key: question.id
1254
+ });
1255
+ case external_survey_constants_js_namespaceObject.SurveyQuestionType.Rating:
1256
+ return /*#__PURE__*/ (0, external_preact_namespaceObject.createElement)(QuestionTypes_js_namespaceObject.RatingQuestion, {
1257
+ ...baseProps,
1258
+ question: question,
1259
+ key: question.id
1260
+ });
1261
+ case external_survey_constants_js_namespaceObject.SurveyQuestionType.SingleChoice:
1262
+ case external_survey_constants_js_namespaceObject.SurveyQuestionType.MultipleChoice:
1263
+ return /*#__PURE__*/ (0, external_preact_namespaceObject.createElement)(QuestionTypes_js_namespaceObject.MultipleChoiceQuestion, {
1264
+ ...baseProps,
1265
+ question: question,
1266
+ key: question.id
1267
+ });
1268
+ default:
1269
+ survey_utils_js_namespaceObject.SURVEY_LOGGER.error(`Unsupported question type: ${question.type}`);
1270
+ return null;
1271
+ }
1272
+ };
1273
+ exports.FeedbackWidget = __webpack_exports__.FeedbackWidget;
1274
+ exports.INTRO_SCREEN_PREVIEW_INDEX = __webpack_exports__.INTRO_SCREEN_PREVIEW_INDEX;
1275
+ exports.Questions = __webpack_exports__.Questions;
1276
+ exports.SurveyManager = __webpack_exports__.SurveyManager;
1277
+ exports.SurveyPopup = __webpack_exports__.SurveyPopup;
1278
+ exports.generateSurveys = __webpack_exports__.generateSurveys;
1279
+ exports.getNextSurveyStep = __webpack_exports__.getNextSurveyStep;
1280
+ exports.renderFeedbackWidgetPreview = __webpack_exports__.renderFeedbackWidgetPreview;
1281
+ exports.renderSurveysPreview = __webpack_exports__.renderSurveysPreview;
1282
+ exports.useHideSurveyOnURLChange = __webpack_exports__.useHideSurveyOnURLChange;
1283
+ exports.usePopupVisibility = __webpack_exports__.usePopupVisibility;
1284
+ for(var __rspack_i in __webpack_exports__)if (-1 === [
1285
+ "FeedbackWidget",
1286
+ "INTRO_SCREEN_PREVIEW_INDEX",
1287
+ "Questions",
1288
+ "SurveyManager",
1289
+ "SurveyPopup",
1290
+ "generateSurveys",
1291
+ "getNextSurveyStep",
1292
+ "renderFeedbackWidgetPreview",
1293
+ "renderSurveysPreview",
1294
+ "useHideSurveyOnURLChange",
1295
+ "usePopupVisibility"
1296
+ ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
1297
+ Object.defineProperty(exports, '__esModule', {
1298
+ value: true
1299
+ });