txlemetry-react-native 4.55.1
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.
- package/LICENSE +353 -0
- package/README.md +13 -0
- package/dist/PostHogContext.d.ts +5 -0
- package/dist/PostHogContext.js +1 -0
- package/dist/PostHogErrorBoundary.d.ts +27 -0
- package/dist/PostHogErrorBoundary.js +1 -0
- package/dist/PostHogMaskView.d.ts +39 -0
- package/dist/PostHogMaskView.js +1 -0
- package/dist/PostHogProvider.d.ts +100 -0
- package/dist/PostHogProvider.js +1 -0
- package/dist/autocapture.d.ts +4 -0
- package/dist/autocapture.js +1 -0
- package/dist/error-tracking/index.d.ts +98 -0
- package/dist/error-tracking/index.js +1 -0
- package/dist/error-tracking/utils.d.ts +5 -0
- package/dist/error-tracking/utils.js +1 -0
- package/dist/frameworks/wix-navigation.d.ts +3 -0
- package/dist/frameworks/wix-navigation.js +1 -0
- package/dist/hooks/useFeatureFlag.d.ts +5 -0
- package/dist/hooks/useFeatureFlag.js +1 -0
- package/dist/hooks/useFeatureFlagResult.d.ts +3 -0
- package/dist/hooks/useFeatureFlagResult.js +1 -0
- package/dist/hooks/useFeatureFlags.d.ts +3 -0
- package/dist/hooks/useFeatureFlags.js +1 -0
- package/dist/hooks/useNavigationTracker.d.ts +6 -0
- package/dist/hooks/useNavigationTracker.js +1 -0
- package/dist/hooks/usePostHog.d.ts +2 -0
- package/dist/hooks/usePostHog.js +1 -0
- package/dist/hooks/utils.d.ts +14 -0
- package/dist/hooks/utils.js +1 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.js +1 -0
- package/dist/index.txlemetry.d.ts +36 -0
- package/dist/index.txlemetry.js +21 -0
- package/dist/logs-defaults.d.ts +9 -0
- package/dist/logs-defaults.js +1 -0
- package/dist/native-deps.d.ts +4 -0
- package/dist/native-deps.js +1 -0
- package/dist/optional/OptionalAsyncStorage.d.ts +2 -0
- package/dist/optional/OptionalAsyncStorage.js +1 -0
- package/dist/optional/OptionalExpoApplication.d.ts +2 -0
- package/dist/optional/OptionalExpoApplication.js +1 -0
- package/dist/optional/OptionalExpoDevice.d.ts +2 -0
- package/dist/optional/OptionalExpoDevice.js +1 -0
- package/dist/optional/OptionalExpoFileSystem.d.ts +2 -0
- package/dist/optional/OptionalExpoFileSystem.js +1 -0
- package/dist/optional/OptionalExpoFileSystemLegacy.d.ts +2 -0
- package/dist/optional/OptionalExpoFileSystemLegacy.js +1 -0
- package/dist/optional/OptionalExpoLocalization.d.ts +2 -0
- package/dist/optional/OptionalExpoLocalization.js +1 -0
- package/dist/optional/OptionalPlugin.d.ts +20 -0
- package/dist/optional/OptionalPlugin.js +1 -0
- package/dist/optional/OptionalReactNativeDeviceInfo.d.ts +2 -0
- package/dist/optional/OptionalReactNativeDeviceInfo.js +1 -0
- package/dist/optional/OptionalReactNativeLocalize.d.ts +13 -0
- package/dist/optional/OptionalReactNativeLocalize.js +1 -0
- package/dist/optional/OptionalReactNativeNavigation.d.ts +2 -0
- package/dist/optional/OptionalReactNativeNavigation.js +1 -0
- package/dist/optional/OptionalReactNativeNavigationWix.d.ts +2 -0
- package/dist/optional/OptionalReactNativeNavigationWix.js +1 -0
- package/dist/optional/OptionalReactNativeSafeArea.d.ts +2 -0
- package/dist/optional/OptionalReactNativeSafeArea.js +1 -0
- package/dist/optional/OptionalReactNativeSvg.d.ts +2 -0
- package/dist/optional/OptionalReactNativeSvg.js +1 -0
- package/dist/posthog-rn.d.ts +1096 -0
- package/dist/posthog-rn.js +1 -0
- package/dist/storage.d.ts +41 -0
- package/dist/storage.js +1 -0
- package/dist/surveys/PostHogSurveyProvider.d.ts +23 -0
- package/dist/surveys/PostHogSurveyProvider.js +1 -0
- package/dist/surveys/components/BottomSection.d.ts +9 -0
- package/dist/surveys/components/BottomSection.js +1 -0
- package/dist/surveys/components/Cancel.d.ts +5 -0
- package/dist/surveys/components/Cancel.js +1 -0
- package/dist/surveys/components/ConfirmationMessage.d.ts +12 -0
- package/dist/surveys/components/ConfirmationMessage.js +1 -0
- package/dist/surveys/components/QuestionHeader.d.ts +8 -0
- package/dist/surveys/components/QuestionHeader.js +1 -0
- package/dist/surveys/components/QuestionTypes.d.ts +26 -0
- package/dist/surveys/components/QuestionTypes.js +1 -0
- package/dist/surveys/components/SurveyModal.d.ts +11 -0
- package/dist/surveys/components/SurveyModal.js +1 -0
- package/dist/surveys/components/Surveys.d.ts +16 -0
- package/dist/surveys/components/Surveys.js +1 -0
- package/dist/surveys/getActiveMatchingSurveys.d.ts +2 -0
- package/dist/surveys/getActiveMatchingSurveys.js +1 -0
- package/dist/surveys/icons.d.ts +11 -0
- package/dist/surveys/icons.js +1 -0
- package/dist/surveys/index.d.ts +6 -0
- package/dist/surveys/index.js +1 -0
- package/dist/surveys/safeStyleSheet.d.ts +8 -0
- package/dist/surveys/safeStyleSheet.js +1 -0
- package/dist/surveys/survey-translations.d.ts +7 -0
- package/dist/surveys/survey-translations.js +1 -0
- package/dist/surveys/surveys-utils.d.ts +54 -0
- package/dist/surveys/surveys-utils.js +1 -0
- package/dist/surveys/useActivatedSurveys.d.ts +3 -0
- package/dist/surveys/useActivatedSurveys.js +1 -0
- package/dist/surveys/useSurveyStorage.d.ts +8 -0
- package/dist/surveys/useSurveyStorage.js +1 -0
- package/dist/tooling/expoconfig.d.ts +64 -0
- package/dist/tooling/expoconfig.js +1 -0
- package/dist/tooling/metroconfig.d.ts +21 -0
- package/dist/tooling/metroconfig.js +1 -0
- package/dist/tooling/posthogMetroSerializer.d.ts +17 -0
- package/dist/tooling/posthogMetroSerializer.js +1 -0
- package/dist/tooling/utils.d.ts +58 -0
- package/dist/tooling/utils.js +1 -0
- package/dist/tooling/vendor/expo/expoconfig.d.ts +23 -0
- package/dist/tooling/vendor/expo/expoconfig.js +1 -0
- package/dist/tooling/vendor/metro/countLines.d.ts +2 -0
- package/dist/tooling/vendor/metro/countLines.js +1 -0
- package/dist/tooling/vendor/metro/utils.d.ts +22 -0
- package/dist/tooling/vendor/metro/utils.js +1 -0
- package/dist/types.d.ts +205 -0
- package/dist/types.js +1 -0
- package/dist/utils.d.ts +25 -0
- package/dist/utils.js +1 -0
- package/dist/version.d.ts +1 -0
- package/dist/version.js +1 -0
- package/package.json +149 -0
- package/tooling/txlemetry-xcode.sh +222 -0
- package/tooling/txlemetry.gradle +407 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.PostHog=void 0;Object.defineProperty(exports,"PostHogPersistedProperty",{enumerable:true,get:function get(){return _core.PostHogPersistedProperty;}});var _regenerator=_interopRequireDefault(require("@babel/runtime/regenerator"));var _typeof2=_interopRequireDefault(require("@babel/runtime/helpers/typeof"));var _toConsumableArray2=_interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));var _defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));var _asyncToGenerator2=_interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));var _slicedToArray2=_interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));var _classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));var _createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass"));var _possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));var _getPrototypeOf2=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));var _get2=_interopRequireDefault(require("@babel/runtime/helpers/get"));var _inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits"));var _reactNative=require("react-native");var _core=require("@txlemetry/core");var _storage=require("./storage");var _logsDefaults=require("./logs-defaults");var _version=require("./version");var _nativeDeps=require("./native-deps");var _utils=require("./utils");var _wixNavigation=require("./frameworks/wix-navigation");var _OptionalPlugin=require("./optional/OptionalPlugin");var _errorTracking=require("./error-tracking");function ownKeys(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);r&&(o=o.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable;})),t.push.apply(t,o);}return t;}function _objectSpread(e){for(var r=1;r<arguments.length;r++){var t=null!=arguments[r]?arguments[r]:{};r%2?ownKeys(Object(t),!0).forEach(function(r){(0,_defineProperty2["default"])(e,r,t[r]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):ownKeys(Object(t)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(t,r));});}return e;}function _callSuper(t,o,e){return o=(0,_getPrototypeOf2["default"])(o),(0,_possibleConstructorReturn2["default"])(t,_isNativeReflectConstruct()?Reflect.construct(o,e||[],(0,_getPrototypeOf2["default"])(t).constructor):o.apply(t,e));}function _isNativeReflectConstruct(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}));}catch(t){}return(_isNativeReflectConstruct=function _isNativeReflectConstruct(){return!!t;})();}function _superPropGet(t,o,e,r){var p=(0,_get2["default"])((0,_getPrototypeOf2["default"])(1&r?t.prototype:t),o,e);return 2&r&&"function"==typeof p?function(t){return p.apply(e,t);}:p;}function mapAppStateForLogs(state){if(state==='background'){return'background';}if(!state||state==='unknown'){return undefined;}return'foreground';}var PostHog=exports.PostHog=function(_PostHogCore){function PostHog(apiKey,options){var _this;(0,_classCallCheck2["default"])(this,PostHog);var _a,_b,_c,_d,_e,_f;var normalizedApiKey=typeof apiKey==='string'?apiKey.trim():'';if(!normalizedApiKey){console.error("You must pass your Txlemetry project's api key. The client will be disabled.");}_this=_callSuper(this,PostHog,[normalizedApiKey,options]);_this._appProperties={};_this._sessionReplayNativeInitialized=false;_this._nativeErrorTrackingInitialized=false;_this._sessionReplayEvalChain=Promise.resolve();_this._sessionReplayEventTriggers=[];_this._surveysReadyPromise=null;_this._surveysReady=false;_this._requestHeaders={};_this._surveysReadyResolve=null;_this._isInitialized=false;_this._persistence=(_a=options===null||options===void 0?void 0:options.persistence)!==null&&_a!==void 0?_a:'file';_this._disableSurveys=(_b=options===null||options===void 0?void 0:options.disableSurveys)!==null&&_b!==void 0?_b:false;_this._errorTracking=new _errorTracking.ErrorTracking(_this,options===null||options===void 0?void 0:options.errorTracking,_this._logger);_this._setDefaultPersonProperties=(_c=options===null||options===void 0?void 0:options.setDefaultPersonProperties)!==null&&_c!==void 0?_c:true;_this._overrideDisplayLanguage=((_d=options===null||options===void 0?void 0:options.overrideDisplayLanguage)===null||_d===void 0?void 0:_d.trim())||null;_this._requestHeaders=(_e=options===null||options===void 0?void 0:options.requestHeaders)!==null&&_e!==void 0?_e:{};_this._appProperties=typeof(options===null||options===void 0?void 0:options.customAppProperties)==='function'?options.customAppProperties((0,_nativeDeps.getAppProperties)()):(options===null||options===void 0?void 0:options.customAppProperties)||(0,_nativeDeps.getAppProperties)();var storagePromise;var theStorage;if(_this._persistence==='file'){theStorage=(_f=options===null||options===void 0?void 0:options.customStorage)!==null&&_f!==void 0?_f:(0,_nativeDeps.buildOptimisticAsyncStorage)();}if(theStorage){_this._eventsStorage=(0,_storage.createEventsStorage)(theStorage);_this._logsStorage=(0,_storage.createLogsStorage)(theStorage);var preloads=[];if(_this._eventsStorage.preloadPromise){preloads.push(['events',_this._eventsStorage.preloadPromise]);}if(_this._logsStorage.preloadPromise){preloads.push(['logs',_this._logsStorage.preloadPromise]);}if(preloads.length>0){storagePromise=(0,_core.allSettled)(preloads.map(function(_ref){var _ref2=(0,_slicedToArray2["default"])(_ref,2),p=_ref2[1];return p;})).then(function(results){results.forEach(function(r,i){if(r.status==='rejected'){_this._logger.error("Txlemetry ".concat(preloads[i][0]," storage preload failed:"),r.reason);}});});}}else{_this._eventsStorage=(0,_storage.createEventsMemoryStorage)();_this._logsStorage=(0,_storage.createLogsMemoryStorage)();}_this._currentAppState=mapAppStateForLogs(_reactNative.AppState.currentState);_this._resolvedLogsConfig=(0,_logsDefaults.resolveLogsConfig)(options===null||options===void 0?void 0:options.logs);_this._logs=new _core.PostHogLogs(_this,_this._resolvedLogsConfig,_this._logger,function(){var _a;var flags=_this.getFeatureFlags();var flagKeys=flags?Object.keys(flags):undefined;return{distinctId:_this.getDistinctId()||undefined,sessionId:_this.getSessionId()||undefined,screenName:((_a=_this.sessionProps)===null||_a===void 0?void 0:_a.$screen_name)||undefined,appState:_this._currentAppState,activeFeatureFlags:flagKeys&&flagKeys.length>0?flagKeys:undefined};},function(fn){return _this.wrap(fn);},function(){return _this._logsStorage.waitForPersist();});_reactNative.AppState.addEventListener('change',function(state){if(state==='unknown'){return;}var mapped=mapAppStateForLogs(state);if(mapped){_this._currentAppState=mapped;}void _this.flush()["catch"](function(){var _ref3=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee(err){return _regenerator["default"].wrap(function(_context){while(1)switch(_context.prev=_context.next){case 0:_context.next=1;return(0,_core.logFlushError)(err);case 1:case"end":return _context.stop();}},_callee);}));return function(_x3){return _ref3.apply(this,arguments);};}());var isBackgrounding=mapped==='background';var logsFlushPromise=isBackgrounding?_this._logs.flushWithTimeout(_this._resolvedLogsConfig.backgroundFlushBudgetMs):_this._logs.flush();void logsFlushPromise["catch"](function(){var _ref4=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee2(err){return _regenerator["default"].wrap(function(_context2){while(1)switch(_context2.prev=_context2.next){case 0:_context2.next=1;return(0,_core.logFlushError)(err);case 1:case"end":return _context2.stop();}},_callee2);}));return function(_x4){return _ref4.apply(this,arguments);};}());void _this._eventsStorage.waitForPersist();void _this._logsStorage.waitForPersist();if(state==='active'){_this.getSessionId();}});var initAfterStorage=function initAfterStorage(){var enablePersistSessionIdAcrossRestart=options===null||options===void 0?void 0:options.enablePersistSessionIdAcrossRestart;if(!enablePersistSessionIdAcrossRestart){_this.setPersistedProperty(_core.PostHogPersistedProperty.SessionId,null);_this.setPersistedProperty(_core.PostHogPersistedProperty.SessionLastTimestamp,null);_this.setPersistedProperty(_core.PostHogPersistedProperty.SessionStartTimestamp,null);}_this.setupBootstrap(options);if(!_this.getPersistedProperty(_core.PostHogPersistedProperty.DeviceId)){var anonId=_this.getAnonymousId();if(anonId){_this.setPersistedProperty(_core.PostHogPersistedProperty.DeviceId,anonId);}}if(_this._setDefaultPersonProperties){_this._setDefaultPersonPropertiesForFlags(false);}_this._isInitialized=true;if(_this.isDisabled){return;}var cachedRemoteConfig=_this.getPersistedProperty(_core.PostHogPersistedProperty.RemoteConfig);if(cachedRemoteConfig){_this._errorTracking.onRemoteConfig(cachedRemoteConfig.errorTracking);}_this.reloadRemoteConfigAsync().then(function(response){if(response){_this._handleSurveysFromRemoteConfig(response);}})["catch"](function(error){_this._logger.error('Error loading remote config:',error);})["finally"](function(){_this._notifySurveysReady();});if((options===null||options===void 0?void 0:options.captureAppLifecycleEvents)!==false){void _this.captureAppLifecycleEvents();}void _this.persistAppVersion();void _this.startSessionReplay(options,cachedRemoteConfig!==null&&cachedRemoteConfig!==void 0?cachedRemoteConfig:undefined);if(options===null||options===void 0?void 0:options.enableSessionReplay){_this.onFeatureFlags(function(){void _this._evaluateAndStartSessionReplay();});}if((options===null||options===void 0?void 0:options.addTracingHeaders)&&options.addTracingHeaders.length>0){(0,_core.patchFetchForTracingHeaders)(_this,options.addTracingHeaders);}};if(storagePromise){_this._initPromise=storagePromise.then(initAfterStorage);}else{_this._initPromise=Promise.resolve();initAfterStorage();}return _this;}(0,_inherits2["default"])(PostHog,_PostHogCore);return(0,_createClass2["default"])(PostHog,[{key:"ready",value:(function(){var _ready=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee3(){return _regenerator["default"].wrap(function(_context3){while(1)switch(_context3.prev=_context3.next){case 0:_context3.next=1;return this._initPromise;case 1:case"end":return _context3.stop();}},_callee3,this);}));function ready(){return _ready.apply(this,arguments);}return ready;}())},{key:"onRemoteConfig",value:function onRemoteConfig(response){this._errorTracking.onRemoteConfig(response.errorTracking);}},{key:"_storageForKey",value:function _storageForKey(key){return key===_core.PostHogPersistedProperty.LogsQueue?this._logsStorage:this._eventsStorage;}},{key:"getPersistedProperty",value:function getPersistedProperty(key){return this._storageForKey(key).getItem(key);}},{key:"setPersistedProperty",value:function setPersistedProperty(key,value){var storage=this._storageForKey(key);return value!==null?storage.setItem(key,value):storage.removeItem(key);}},{key:"flushStorage",value:(function(){var _flushStorage=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee4(){return _regenerator["default"].wrap(function(_context4){while(1)switch(_context4.prev=_context4.next){case 0:_context4.next=1;return this._eventsStorage.waitForPersist();case 1:case"end":return _context4.stop();}},_callee4,this);}));function flushStorage(){return _flushStorage.apply(this,arguments);}return flushStorage;}())},{key:"_shutdown",value:(function(){var _shutdown2=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee5(){var shutdownTimeoutMs,start,logsBudgetMs,remainingMs,drain,_args5=arguments;return _regenerator["default"].wrap(function(_context5){while(1)switch(_context5.prev=_context5.next){case 0:shutdownTimeoutMs=_args5.length>0&&_args5[0]!==undefined?_args5[0]:30000;this._errorTracking.clearExceptionSteps();start=Date.now();logsBudgetMs=Math.min(shutdownTimeoutMs,this._resolvedLogsConfig.terminationFlushBudgetMs);_context5.prev=1;_context5.next=2;return Promise.all([this._logs.shutdown(logsBudgetMs),_superPropGet(PostHog,"_shutdown",this,3)([shutdownTimeoutMs])]);case 2:_context5.prev=2;remainingMs=Math.max(0,shutdownTimeoutMs-(Date.now()-start));drain=Promise.all([this._eventsStorage.waitForPersist(),this._logsStorage.waitForPersist()]);_context5.next=3;return Promise.race([drain,new Promise(function(resolve){return(0,_core.safeSetTimeout)(resolve,remainingMs);})]);case 3:return _context5.finish(2);case 4:case"end":return _context5.stop();}},_callee5,this,[[1,,2,4]]);}));function _shutdown(){return _shutdown2.apply(this,arguments);}return _shutdown;}())},{key:"fetch",value:function(_fetch){function fetch(_x,_x2){return _fetch.apply(this,arguments);}fetch.toString=function(){return _fetch.toString();};return fetch;}(function(url,options){return fetch(url,options);})},{key:"getLibraryId",value:function getLibraryId(){return'txlemetry-react-native';}},{key:"getLibraryVersion",value:function getLibraryVersion(){return _version.version;}},{key:"getCustomUserAgent",value:function getCustomUserAgent(){if(_reactNative.Platform.OS==='web'){return'';}return"".concat(this.getLibraryId(),"/").concat(this.getLibraryVersion());}},{key:"getCustomHeaders",value:function getCustomHeaders(){return _objectSpread(_objectSpread({},_superPropGet(PostHog,"getCustomHeaders",this,3)([])),this._requestHeaders);}},{key:"getCommonEventProperties",value:function getCommonEventProperties(){return _objectSpread(_objectSpread(_objectSpread({},_superPropGet(PostHog,"getCommonEventProperties",this,3)([])),this._appProperties),{},{$screen_height:_reactNative.Dimensions.get('screen').height,$screen_width:_reactNative.Dimensions.get('screen').width});}},{key:"getSurveyDisplayLanguageOverride",value:function getSurveyDisplayLanguageOverride(){return this._overrideDisplayLanguage;}},{key:"register",value:function register(properties){return _superPropGet(PostHog,"register",this,3)([properties]);}},{key:"unregister",value:function unregister(property){return _superPropGet(PostHog,"unregister",this,3)([property]);}},{key:"reset",value:function reset(propertiesToKeep){var effectivePropertiesToKeep=propertiesToKeep!==null&&propertiesToKeep!==void 0?propertiesToKeep:[_core.PostHogPersistedProperty.InstalledAppBuild,_core.PostHogPersistedProperty.InstalledAppVersion,_core.PostHogPersistedProperty.DeviceId];_superPropGet(PostHog,"reset",this,3)([[_core.PostHogPersistedProperty.RemoteConfig,_core.PostHogPersistedProperty.SessionReplay,_core.PostHogPersistedProperty.Surveys].concat((0,_toConsumableArray2["default"])(effectivePropertiesToKeep))]);if(this._setDefaultPersonProperties){this._setDefaultPersonPropertiesForFlags(false);}void this._eventsStorage.waitForPersist();}},{key:"_setDefaultPersonPropertiesForFlags",value:function _setDefaultPersonPropertiesForFlags(){var _this2=this;var reloadFeatureFlags=arguments.length>0&&arguments[0]!==undefined?arguments[0]:true;var defaultProps={};var relevantKeys=['$app_version','$app_build','$app_namespace','$os_name','$os_version','$device_type'];relevantKeys.forEach(function(key){var value=_this2._appProperties[key];if(value!==null&&value!==undefined){defaultProps[key]=value;}});var commonProps=this.getCommonEventProperties();if(commonProps.$lib){defaultProps.$lib=commonProps.$lib;}if(commonProps.$lib_version){defaultProps.$lib_version=commonProps.$lib_version;}if(Object.keys(defaultProps).length>0){this.setPersonPropertiesForFlags(defaultProps,reloadFeatureFlags);}}},{key:"flush",value:function flush(){return _superPropGet(PostHog,"flush",this,3)([]);}},{key:"captureLog",value:function captureLog(options){this._logs.captureLog(options);}},{key:"flushLogs",value:function flushLogs(){return this._logs.flush();}},{key:"logger",get:function get(){var _this3=this;if(!this._captureLogger){this._captureLogger={trace:function trace(body,attributes){return _this3.captureLog({body:body,level:'trace',attributes:attributes});},debug:function debug(body,attributes){return _this3.captureLog({body:body,level:'debug',attributes:attributes});},info:function info(body,attributes){return _this3.captureLog({body:body,level:'info',attributes:attributes});},warn:function warn(body,attributes){return _this3.captureLog({body:body,level:'warn',attributes:attributes});},error:function error(body,attributes){return _this3.captureLog({body:body,level:'error',attributes:attributes});},fatal:function fatal(body,attributes){return _this3.captureLog({body:body,level:'fatal',attributes:attributes});}};}return this._captureLogger;}},{key:"optIn",value:function optIn(){var result=_superPropGet(PostHog,"optIn",this,3)([]);void this._eventsStorage.waitForPersist();return result;}},{key:"optOut",value:function optOut(){var result=_superPropGet(PostHog,"optOut",this,3)([]);void this._eventsStorage.waitForPersist();return result;}},{key:"isFeatureEnabled",value:function isFeatureEnabled(key,options){return _superPropGet(PostHog,"isFeatureEnabled",this,3)([key,options]);}},{key:"getFeatureFlag",value:function getFeatureFlag(key,options){return _superPropGet(PostHog,"getFeatureFlag",this,3)([key,options]);}},{key:"getFeatureFlagPayload",value:function getFeatureFlagPayload(key){return _superPropGet(PostHog,"getFeatureFlagPayload",this,3)([key]);}},{key:"reloadFeatureFlags",value:function reloadFeatureFlags(){_superPropGet(PostHog,"reloadFeatureFlags",this,3)([]);}},{key:"reloadFeatureFlagsAsync",value:function reloadFeatureFlagsAsync(){return _superPropGet(PostHog,"reloadFeatureFlagsAsync",this,3)([]);}},{key:"updateFlags",value:function updateFlags(flags,payloads,options){_superPropGet(PostHog,"updateFlags",this,3)([flags,payloads,options]);}},{key:"group",value:function group(groupType,groupKey,properties){_superPropGet(PostHog,"group",this,3)([groupType,groupKey,properties]);if(properties&&Object.keys(properties).length>0){var propsToCache={};Object.keys(properties).forEach(function(key){var value=properties[key];if(value!==null&&value!==undefined){propsToCache[key]=value;}});if(Object.keys(propsToCache).length>0){this.setGroupPropertiesForFlags((0,_defineProperty2["default"])({},groupType,propsToCache));}}}},{key:"alias",value:function alias(_alias){_superPropGet(PostHog,"alias",this,3)([_alias]);}},{key:"getDistinctId",value:function getDistinctId(){return _superPropGet(PostHog,"getDistinctId",this,3)([]);}},{key:"getDeviceId",value:function getDeviceId(){var deviceId=this.getPersistedProperty(_core.PostHogPersistedProperty.DeviceId);if(!deviceId){var anonId=this.getAnonymousId();if(anonId){this.setPersistedProperty(_core.PostHogPersistedProperty.DeviceId,anonId);return anonId;}return'';}return deviceId;}},{key:"setPersonPropertiesForFlags",value:function setPersonPropertiesForFlags(properties){var reloadFeatureFlags=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;_superPropGet(PostHog,"setPersonPropertiesForFlags",this,3)([properties,reloadFeatureFlags]);}},{key:"resetPersonPropertiesForFlags",value:function resetPersonPropertiesForFlags(){var reloadFeatureFlags=arguments.length>0&&arguments[0]!==undefined?arguments[0]:true;_superPropGet(PostHog,"resetPersonPropertiesForFlags",this,3)([]);if(reloadFeatureFlags){this.reloadFeatureFlags();}}},{key:"setGroupPropertiesForFlags",value:function setGroupPropertiesForFlags(properties){var reloadFeatureFlags=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;_superPropGet(PostHog,"setGroupPropertiesForFlags",this,3)([properties]);if(reloadFeatureFlags){this.reloadFeatureFlags();}}},{key:"resetGroupPropertiesForFlags",value:function resetGroupPropertiesForFlags(){var reloadFeatureFlags=arguments.length>0&&arguments[0]!==undefined?arguments[0]:true;_superPropGet(PostHog,"resetGroupPropertiesForFlags",this,3)([]);if(reloadFeatureFlags){this.reloadFeatureFlags();}}},{key:"screen",value:(function(){var _screen=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee6(name,properties,options){return _regenerator["default"].wrap(function(_context6){while(1)switch(_context6.prev=_context6.next){case 0:_context6.next=1;return this._initPromise;case 1:this.registerForSession({$screen_name:name});return _context6.abrupt("return",this.capture('$screen',_objectSpread(_objectSpread({},properties),{},{$screen_name:name}),options));case 2:case"end":return _context6.stop();}},_callee6,this);}));function screen(_x5,_x6,_x7){return _screen.apply(this,arguments);}return screen;}())},{key:"_isEnableSessionReplay",value:function _isEnableSessionReplay(){var _a;return!this.isDisabled&&((_a=this._enableSessionReplay)!==null&&_a!==void 0?_a:false);}},{key:"_resetSessionId",value:function _resetSessionId(reactNativeSessionReplay,sessionId){if(reactNativeSessionReplay){reactNativeSessionReplay.endSession();reactNativeSessionReplay.startSession(sessionId);}}},{key:"getSessionId",value:function getSessionId(){var sessionId=_superPropGet(PostHog,"getSessionId",this,3)([]);if(!this._isEnableSessionReplay()&&!this._isNativePluginInitialized()){return sessionId;}if(sessionId.length>0&&this._currentSessionId&&sessionId!==this._currentSessionId){if(_OptionalPlugin.OptionalReactNativePlugin){try{this._resetSessionId(_OptionalPlugin.OptionalReactNativePlugin,String(sessionId));this._logger.info("sessionId rotated from ".concat(this._currentSessionId," to ").concat(sessionId,"."));}catch(e){this._logger.error("Failed to rotate sessionId: ".concat(e,"."));}}this._currentSessionId=sessionId;if(this._sessionReplayEventTriggers.length>0){void this._evaluateAndStartSessionReplay();}}else{this._logger.info("sessionId not rotated, sessionId ".concat(sessionId," and currentSessionId ").concat(this._currentSessionId,"."));}return sessionId;}},{key:"resetSessionId",value:function resetSessionId(){_superPropGet(PostHog,"resetSessionId",this,3)([]);if((this._isEnableSessionReplay()||this._isNativePluginInitialized())&&_OptionalPlugin.OptionalReactNativePlugin){try{_OptionalPlugin.OptionalReactNativePlugin.endSession();this._logger.info("Native Txlemetry session ended.");}catch(e){this._logger.error("Native Txlemetry session failed to end: ".concat(e,"."));}}}},{key:"startSessionRecording",value:(function(){var _startSessionRecording2=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee7(){var resumeCurrent,_args7=arguments;return _regenerator["default"].wrap(function(_context7){while(1)switch(_context7.prev=_context7.next){case 0:resumeCurrent=_args7.length>0&&_args7[0]!==undefined?_args7[0]:true;_context7.next=1;return this._startSessionRecording(resumeCurrent);case 1:case"end":return _context7.stop();}},_callee7,this);}));function startSessionRecording(){return _startSessionRecording2.apply(this,arguments);}return startSessionRecording;}())},{key:"_startSessionRecording",value:function(){var _startSessionRecording3=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee8(resumeCurrent){var initialized,newSessionId,_t;return _regenerator["default"].wrap(function(_context8){while(1)switch(_context8.prev=_context8.next){case 0:_context8.next=1;return this._initPromise;case 1:if(!this.isDisabled){_context8.next=2;break;}return _context8.abrupt("return",false);case 2:if(_OptionalPlugin.OptionalReactNativePlugin){_context8.next=3;break;}return _context8.abrupt("return",false);case 3:_context8.prev=3;if(_OptionalPlugin.OptionalReactNativePlugin.startRecording){_context8.next=4;break;}this._logger.warn('startRecording is not available. Please update @txlemetry/react-native-plugin or txlemetry-react-native-session-replay.');return _context8.abrupt("return",false);case 4:if(this._sessionReplayNativeInitialized){_context8.next=6;break;}this._logger.info('Native session replay SDK not initialized, initializing now...');_context8.next=5;return this.initializeNativePlugin(this._sessionReplayOptions,undefined,true);case 5:initialized=_context8.sent;if(initialized){_context8.next=6;break;}this._logger.error('Failed to initialize native session replay SDK.');return _context8.abrupt("return",false);case 6:if(!resumeCurrent){_superPropGet(PostHog,"resetSessionId",this,3)([]);newSessionId=_superPropGet(PostHog,"getSessionId",this,3)([]);this._resetSessionId(_OptionalPlugin.OptionalReactNativePlugin,String(newSessionId));this._currentSessionId=newSessionId;}_context8.next=7;return _OptionalPlugin.OptionalReactNativePlugin.startRecording(resumeCurrent);case 7:this._logger.info("Session recording ".concat(resumeCurrent?'resumed':'started',"."));return _context8.abrupt("return",true);case 8:_context8.prev=8;_t=_context8["catch"](3);this._logger.error("Failed to start session recording: ".concat(_t));return _context8.abrupt("return",false);case 9:case"end":return _context8.stop();}},_callee8,this,[[3,8]]);}));function _startSessionRecording(_x8){return _startSessionRecording3.apply(this,arguments);}return _startSessionRecording;}()},{key:"stopSessionRecording",value:(function(){var _stopSessionRecording2=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee9(){return _regenerator["default"].wrap(function(_context9){while(1)switch(_context9.prev=_context9.next){case 0:_context9.next=1;return this._stopSessionRecording();case 1:case"end":return _context9.stop();}},_callee9,this);}));function stopSessionRecording(){return _stopSessionRecording2.apply(this,arguments);}return stopSessionRecording;}())},{key:"_stopSessionRecording",value:function(){var _stopSessionRecording3=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee0(){var _t2;return _regenerator["default"].wrap(function(_context0){while(1)switch(_context0.prev=_context0.next){case 0:_context0.next=1;return this._initPromise;case 1:if(!this.isDisabled){_context0.next=2;break;}return _context0.abrupt("return",false);case 2:if(_OptionalPlugin.OptionalReactNativePlugin){_context0.next=3;break;}return _context0.abrupt("return",false);case 3:_context0.prev=3;if(_OptionalPlugin.OptionalReactNativePlugin.stopRecording){_context0.next=4;break;}this._logger.warn('stopRecording is not available. Please update @txlemetry/react-native-plugin or txlemetry-react-native-session-replay.');return _context0.abrupt("return",false);case 4:_context0.next=5;return _OptionalPlugin.OptionalReactNativePlugin.stopRecording();case 5:this._logger.info('Session recording stopped.');return _context0.abrupt("return",true);case 6:_context0.prev=6;_t2=_context0["catch"](3);this._logger.error("Failed to stop session recording: ".concat(_t2));return _context0.abrupt("return",false);case 7:case"end":return _context0.stop();}},_callee0,this,[[3,6]]);}));function _stopSessionRecording(){return _stopSessionRecording3.apply(this,arguments);}return _stopSessionRecording;}()},{key:"isSessionReplayActive",value:(function(){var _isSessionReplayActive=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee1(){var _t3;return _regenerator["default"].wrap(function(_context1){while(1)switch(_context1.prev=_context1.next){case 0:_context1.next=1;return this._initPromise;case 1:if(!this.isDisabled){_context1.next=2;break;}return _context1.abrupt("return",false);case 2:if(_OptionalPlugin.OptionalReactNativePlugin){_context1.next=3;break;}return _context1.abrupt("return",false);case 3:_context1.prev=3;_context1.next=4;return _OptionalPlugin.OptionalReactNativePlugin.isEnabled();case 4:return _context1.abrupt("return",_context1.sent);case 5:_context1.prev=5;_t3=_context1["catch"](3);this._logger.error("Failed to check session replay status: ".concat(_t3));return _context1.abrupt("return",false);case 6:case"end":return _context1.stop();}},_callee1,this,[[3,5]]);}));function isSessionReplayActive(){return _isSessionReplayActive.apply(this,arguments);}return isSessionReplayActive;}())},{key:"identify",value:function identify(distinctId,properties,options){var previousDistinctId=this.getDistinctId();var userProps=(properties===null||properties===void 0?void 0:properties.$set)||properties;var userPropsOnce=properties===null||properties===void 0?void 0:properties.$set_once;_superPropGet(PostHog,"identify",this,3)([distinctId,properties,options]);var propsToCache={};if(userProps&&(0,_typeof2["default"])(userProps)==='object'&&!Array.isArray(userProps)){Object.entries(userProps).forEach(function(_ref5){var _ref6=(0,_slicedToArray2["default"])(_ref5,2),key=_ref6[0],value=_ref6[1];if(value!==null&&value!==undefined){propsToCache[key]=value;}});}var propsOnceToCache={};if(userPropsOnce&&(0,_typeof2["default"])(userPropsOnce)==='object'&&!Array.isArray(userPropsOnce)){Object.entries(userPropsOnce).forEach(function(_ref7){var _ref8=(0,_slicedToArray2["default"])(_ref7,2),key=_ref8[0],value=_ref8[1];if(value!==null&&value!==undefined){propsOnceToCache[key]=value;}});}if(Object.keys(propsToCache).length>0||Object.keys(propsOnceToCache).length>0){this.setPersonPropertiesForFlags(_objectSpread({$set:propsToCache},Object.keys(propsOnceToCache).length>0?{$set_once:propsOnceToCache}:{}),false);}if((this._isEnableSessionReplay()||this._isNativePluginInitialized())&&_OptionalPlugin.OptionalReactNativePlugin){try{distinctId=distinctId||previousDistinctId;var anonymousId=this.getAnonymousId();_OptionalPlugin.OptionalReactNativePlugin.identify(String(distinctId),String(anonymousId));this._logger.info("Native Txlemetry identified with distinctId ".concat(distinctId," and anonymousId ").concat(anonymousId,"."));}catch(e){this._logger.error("Native Txlemetry failed to identify: ".concat(e,"."));}}void this._eventsStorage.waitForPersist();}},{key:"captureException",value:function captureException(error){var additionalProperties=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var hint=arguments.length>2?arguments[2]:undefined;var resolvedHint=hint!==null&&hint!==void 0?hint:{mechanism:{handled:true,type:'generic'},syntheticException:new Error('Synthetic Error')};additionalProperties=this._errorTracking.attachExceptionSteps(additionalProperties);_superPropGet(PostHog,"captureException",this,3)([error,additionalProperties,resolvedHint]);if((additionalProperties===null||additionalProperties===void 0?void 0:additionalProperties.$exception_level)==='fatal'){void this._eventsStorage.waitForPersist();void this._logsStorage.waitForPersist();}}},{key:"addExceptionStep",value:function addExceptionStep(message,properties){this._errorTracking.addExceptionStep(message,properties);}},{key:"createErrorPropertiesBuilder",value:function createErrorPropertiesBuilder(){return new _core.ErrorTracking.ErrorPropertiesBuilder([new _core.ErrorTracking.PromiseRejectionEventCoercer(),new _core.ErrorTracking.ErrorCoercer(),new _core.ErrorTracking.ErrorEventCoercer(),new _core.ErrorTracking.ObjectCoercer(),new _core.ErrorTracking.StringCoercer(),new _core.ErrorTracking.PrimitiveCoercer()],_core.ErrorTracking.createStackParser((0,_utils.isHermes)()?'hermes':'web:javascript',_core.ErrorTracking.chromeStackLineParser,_core.ErrorTracking.geckoStackLineParser));}},{key:"initReactNativeNavigation",value:function initReactNativeNavigation(options){return(0,_wixNavigation.withReactNativeNavigation)(this,options);}},{key:"createPersonProfile",value:function createPersonProfile(){_superPropGet(PostHog,"createPersonProfile",this,3)([]);}},{key:"setPersonProperties",value:function setPersonProperties(userPropertiesToSet,userPropertiesToSetOnce){var reloadFeatureFlags=arguments.length>2&&arguments[2]!==undefined?arguments[2]:true;_superPropGet(PostHog,"setPersonProperties",this,3)([userPropertiesToSet,userPropertiesToSetOnce,reloadFeatureFlags]);}},{key:"unsetPersonProperties",value:function unsetPersonProperties(propertyNames){var reloadFeatureFlags=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;_superPropGet(PostHog,"unsetPersonProperties",this,3)([propertyNames,reloadFeatureFlags]);}},{key:"getSurveys",value:function(){var _getSurveys=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee10(){var surveys;return _regenerator["default"].wrap(function(_context10){while(1)switch(_context10.prev=_context10.next){case 0:if(!(this._disableSurveys===true)){_context10.next=1;break;}this._logger.info('Loading surveys is disabled.');this._cacheSurveys(null,'disabled in config');return _context10.abrupt("return",[]);case 1:surveys=this.getPersistedProperty(_core.PostHogPersistedProperty.Surveys);if(!(surveys&&surveys.length>0)){_context10.next=2;break;}this._logger.info('Surveys fetched from storage: ',JSON.stringify(surveys));return _context10.abrupt("return",surveys);case 2:this._logger.info('No surveys found in storage');return _context10.abrupt("return",[]);case 3:case"end":return _context10.stop();}},_callee10,this);}));function getSurveys(){return _getSurveys.apply(this,arguments);}return getSurveys;}()},{key:"_onSurveysReady",value:function _onSurveysReady(){var _this4=this;if(this._surveysReady){return Promise.resolve();}if(!this._surveysReadyPromise){this._surveysReadyPromise=new Promise(function(resolve){_this4._surveysReadyResolve=resolve;});}return this._surveysReadyPromise;}},{key:"_cacheSurveys",value:function _cacheSurveys(surveys,source){this.setPersistedProperty(_core.PostHogPersistedProperty.Surveys,surveys);if(surveys&&surveys.length>0){this._logger.info("Surveys cached from ".concat(source,":"),JSON.stringify(surveys));}else if(surveys===null){this._logger.info("Surveys cleared (".concat(source,")"));}else{this._logger.info("No surveys to cache from ".concat(source,")"));}}},{key:"_notifySurveysReady",value:function _notifySurveysReady(){this._surveysReady=true;if(this._surveysReadyResolve){this._surveysReadyResolve();this._surveysReadyResolve=null;this._surveysReadyPromise=null;}}},{key:"_handleSurveysFromRemoteConfig",value:function _handleSurveysFromRemoteConfig(response){if(this._disableSurveys===true){this._logger.info('Loading surveys skipped, disabled.');this._cacheSurveys(null,'remote config (disabled)');return;}var surveys=response.surveys;if(Array.isArray(surveys)&&surveys.length>0){this._cacheSurveys(surveys,'remote config');}else{this._cacheSurveys(null,'remote config');}}},{key:"_isAutocaptureNativeErrors",value:function _isAutocaptureNativeErrors(options){var _a;var autocapture=(_a=options===null||options===void 0?void 0:options.errorTracking)===null||_a===void 0?void 0:_a.autocapture;var nativeCrashes=(0,_typeof2["default"])(autocapture)==='object'&&autocapture.nativeCrashes===true;return!this.isDisabled&&nativeCrashes;}},{key:"_isNativePluginInitialized",value:function _isNativePluginInitialized(){return this._sessionReplayNativeInitialized||this._nativeErrorTrackingInitialized;}},{key:"initializeSessionReplayNative",value:(function(){var _initializeSessionReplayNative=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee11(options,cachedRemoteConfig){return _regenerator["default"].wrap(function(_context11){while(1)switch(_context11.prev=_context11.next){case 0:return _context11.abrupt("return",this.initializeNativePlugin(options,cachedRemoteConfig,true));case 1:case"end":return _context11.stop();}},_callee11,this);}));function initializeSessionReplayNative(_x9,_x0){return _initializeSessionReplayNative.apply(this,arguments);}return initializeSessionReplayNative;}())},{key:"initializeNativePlugin",value:function(){var _initializeNativePlugin=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee12(options,cachedRemoteConfig){var enableSessionReplay,_a,_b,_c,_d,_e,_f,enableNativeErrorTracking,sessionId,defaultThrottleDelayMs,_ref9,_ref9$maskAllTextInpu,maskAllTextInputs,_ref9$maskAllImages,maskAllImages,_ref9$maskAllSandboxe,maskAllSandboxedViews,_ref9$captureLog,localCaptureLog,_ref9$captureNetworkT,localCaptureNetworkTelemetry,_ref9$screenshotModeB,screenshotModeBackgroundCapture,localSampleRate,_ref9$iOSdebouncerDel,iOSdebouncerDelayMs,_ref9$androidDebounce,androidDebouncerDelayMs,throttleDelayMs,remoteConsoleLogEnabled,remoteNetworkTimingEnabled,remoteSampleRateRaw,captureLog,captureNetworkTelemetry,localSampleRateValid,remoteSampleRateValid,sampleRate,source,sdkReplayConfig,sessionReplay,cachedSessionReplayConfig,sdkOptions,loggableSdkOptions,wasSessionReplayEnabled,pluginConfig,_args12=arguments,_t4,_t5;return _regenerator["default"].wrap(function(_context12){while(1)switch(_context12.prev=_context12.next){case 0:enableSessionReplay=_args12.length>2&&_args12[2]!==undefined?_args12[2]:this._isEnableSessionReplay();enableNativeErrorTracking=this._isAutocaptureNativeErrors(options);if(!(!enableSessionReplay&&!enableNativeErrorTracking)){_context12.next=1;break;}return _context12.abrupt("return",true);case 1:if(_OptionalPlugin.OptionalReactNativePlugin){_context12.next=2;break;}this._logger.warn(enableSessionReplay?'Session replay enabled but not installed.':'Native error tracking enabled but not installed.');return _context12.abrupt("return",false);case 2:if(!((!enableSessionReplay||this._sessionReplayNativeInitialized)&&(!enableNativeErrorTracking||this._nativeErrorTrackingInitialized))){_context12.next=3;break;}return _context12.abrupt("return",true);case 3:if(!(this._isNativePluginInitialized()&&enableSessionReplay&&!this._sessionReplayNativeInitialized)){_context12.next=5;break;}this._sessionReplayNativeInitialized=true;_context12.next=4;return(_a=_OptionalPlugin.OptionalReactNativePlugin.startRecording)===null||_a===void 0?void 0:_a.call(_OptionalPlugin.OptionalReactNativePlugin,true);case 4:return _context12.abrupt("return",true);case 5:sessionId=this.getSessionId();if(!(sessionId.length===0)){_context12.next=6;break;}this._logger.warn("Native Txlemetry plugin enabled but no sessionId found.");return _context12.abrupt("return",false);case 6:defaultThrottleDelayMs=1000;_ref9=(_b=options===null||options===void 0?void 0:options.sessionReplayConfig)!==null&&_b!==void 0?_b:{},_ref9$maskAllTextInpu=_ref9.maskAllTextInputs,maskAllTextInputs=_ref9$maskAllTextInpu===void 0?true:_ref9$maskAllTextInpu,_ref9$maskAllImages=_ref9.maskAllImages,maskAllImages=_ref9$maskAllImages===void 0?true:_ref9$maskAllImages,_ref9$maskAllSandboxe=_ref9.maskAllSandboxedViews,maskAllSandboxedViews=_ref9$maskAllSandboxe===void 0?true:_ref9$maskAllSandboxe,_ref9$captureLog=_ref9.captureLog,localCaptureLog=_ref9$captureLog===void 0?true:_ref9$captureLog,_ref9$captureNetworkT=_ref9.captureNetworkTelemetry,localCaptureNetworkTelemetry=_ref9$captureNetworkT===void 0?true:_ref9$captureNetworkT,_ref9$screenshotModeB=_ref9.screenshotModeBackgroundCapture,screenshotModeBackgroundCapture=_ref9$screenshotModeB===void 0?false:_ref9$screenshotModeB,localSampleRate=_ref9.sampleRate,_ref9$iOSdebouncerDel=_ref9.iOSdebouncerDelayMs,iOSdebouncerDelayMs=_ref9$iOSdebouncerDel===void 0?defaultThrottleDelayMs:_ref9$iOSdebouncerDel,_ref9$androidDebounce=_ref9.androidDebouncerDelayMs,androidDebouncerDelayMs=_ref9$androidDebounce===void 0?defaultThrottleDelayMs:_ref9$androidDebounce;throttleDelayMs=(_d=(_c=options===null||options===void 0?void 0:options.sessionReplayConfig)===null||_c===void 0?void 0:_c.throttleDelayMs)!==null&&_d!==void 0?_d:defaultThrottleDelayMs;if(throttleDelayMs===defaultThrottleDelayMs&&(iOSdebouncerDelayMs!==defaultThrottleDelayMs||androidDebouncerDelayMs!==defaultThrottleDelayMs)){throttleDelayMs=Math.max(iOSdebouncerDelayMs,androidDebouncerDelayMs);}remoteConsoleLogEnabled=(0,_utils.getRemoteConfigBool)(cachedRemoteConfig===null||cachedRemoteConfig===void 0?void 0:cachedRemoteConfig.sessionRecording,'consoleLogRecordingEnabled',true);remoteNetworkTimingEnabled=(0,_utils.getRemoteConfigBool)(cachedRemoteConfig===null||cachedRemoteConfig===void 0?void 0:cachedRemoteConfig.capturePerformance,'network_timing',true);remoteSampleRateRaw=(0,_utils.getRemoteConfigNumber)(cachedRemoteConfig===null||cachedRemoteConfig===void 0?void 0:cachedRemoteConfig.sessionRecording,'sampleRate');captureLog=localCaptureLog&&remoteConsoleLogEnabled;captureNetworkTelemetry=localCaptureNetworkTelemetry&&remoteNetworkTimingEnabled;localSampleRateValid=localSampleRate===undefined?undefined:(0,_utils.isValidSampleRate)(localSampleRate)?localSampleRate:undefined;remoteSampleRateValid=remoteSampleRateRaw===undefined?undefined:(0,_utils.isValidSampleRate)(remoteSampleRateRaw)?remoteSampleRateRaw:undefined;sampleRate=localSampleRateValid!==null&&localSampleRateValid!==void 0?localSampleRateValid:remoteSampleRateValid;if(localCaptureLog&&!remoteConsoleLogEnabled){this._logger.info('captureLog disabled by remote config (consoleLogRecordingEnabled=false).');}if(localCaptureNetworkTelemetry&&!remoteNetworkTimingEnabled){this._logger.info('captureNetworkTelemetry disabled by remote config (capturePerformance.network_timing=false).');}if(localSampleRate!==undefined&&localSampleRateValid===undefined){this._logger.warn("Ignoring invalid sessionReplayConfig.sampleRate '".concat(localSampleRate,"'. Expected a number between 0 and 1."));}if(remoteSampleRateRaw!==undefined&&remoteSampleRateValid===undefined){this._logger.warn("Ignoring invalid remote config sessionRecording.sampleRate '".concat(remoteSampleRateRaw,"'. Expected a number between 0 and 1."));}if(typeof sampleRate==='number'){source=localSampleRateValid!==undefined?'local config':'remote config';this._logger.info("sampleRate set from ".concat(source," (").concat(sampleRate,")."));}sdkReplayConfig={maskAllTextInputs:maskAllTextInputs,maskAllImages:maskAllImages,maskAllSandboxedViews:maskAllSandboxedViews,captureLog:captureLog,captureNetworkTelemetry:captureNetworkTelemetry,screenshotModeBackgroundCapture:screenshotModeBackgroundCapture,sampleRate:sampleRate,iOSdebouncerDelayMs:iOSdebouncerDelayMs,androidDebouncerDelayMs:androidDebouncerDelayMs,throttleDelayMs:throttleDelayMs};this._logger.info("Native Txlemetry plugin replay config: ".concat(JSON.stringify(sdkReplayConfig)));sessionReplay=(_e=this.getPersistedProperty(_core.PostHogPersistedProperty.SessionReplay))!==null&&_e!==void 0?_e:{};cachedSessionReplayConfig=(_f=sessionReplay)!==null&&_f!==void 0?_f:{};this._logger.info("Session replay session recording from flags cached config: ".concat(JSON.stringify(cachedSessionReplayConfig)));sdkOptions={apiKey:this.apiKey,host:this.host,debug:this.isDebug,distinctId:this.getDistinctId(),anonymousId:this.getAnonymousId(),sdkVersion:this.getLibraryVersion(),flushAt:this.flushAt,requestHeaders:this._requestHeaders};loggableSdkOptions=_objectSpread(_objectSpread({},sdkOptions),{},{requestHeaders:Object.keys(this._requestHeaders)});this._logger.info("Native Txlemetry plugin sdk options: ".concat(JSON.stringify(loggableSdkOptions)));_context12.prev=7;if(!enableSessionReplay){_context12.next=9;break;}_context12.next=8;return _OptionalPlugin.OptionalReactNativePlugin.isEnabled()["catch"](function(){return false;});case 8:_t4=_context12.sent;_context12.next=10;break;case 9:_t4=false;case 10:wasSessionReplayEnabled=_t4;if(!_OptionalPlugin.OptionalReactNativePlugin.setup){_context12.next=12;break;}pluginConfig={sessionReplay:{enabled:enableSessionReplay,sdkReplayConfig:sdkReplayConfig,decideReplayConfig:cachedSessionReplayConfig},errorTracking:{nativeAutocapture:enableNativeErrorTracking,exceptionSteps:this._errorTracking.getNativePluginExceptionStepsConfig()}};_context12.next=11;return _OptionalPlugin.OptionalReactNativePlugin.setup(String(sessionId),sdkOptions,pluginConfig);case 11:if(wasSessionReplayEnabled){this._resetSessionId(_OptionalPlugin.OptionalReactNativePlugin,String(sessionId));}_context12.next=17;break;case 12:if(enableNativeErrorTracking){this._logger.warn('Native error tracking is not available. Please update @txlemetry/react-native-plugin or txlemetry-react-native-session-replay.');enableNativeErrorTracking=false;}if(enableSessionReplay){_context12.next=13;break;}return _context12.abrupt("return",false);case 13:_context12.next=14;return _OptionalPlugin.OptionalReactNativePlugin.isEnabled();case 14:if(_context12.sent){_context12.next=16;break;}_context12.next=15;return _OptionalPlugin.OptionalReactNativePlugin.start(String(sessionId),sdkOptions,sdkReplayConfig,cachedSessionReplayConfig);case 15:_context12.next=17;break;case 16:this._resetSessionId(_OptionalPlugin.OptionalReactNativePlugin,String(sessionId));case 17:this._currentSessionId=sessionId;if(enableSessionReplay){this._sessionReplayNativeInitialized=true;this._logger.info("Session replay started with sessionId ".concat(sessionId,"."));}if(enableNativeErrorTracking){this._nativeErrorTrackingInitialized=true;this._errorTracking.onNativeErrorTrackingReady();this._logger.info('Native error tracking started.');}return _context12.abrupt("return",true);case 18:_context12.prev=18;_t5=_context12["catch"](7);this._logger.error("Native Txlemetry plugin failed to start: ".concat(_t5,"."));return _context12.abrupt("return",false);case 19:case"end":return _context12.stop();}},_callee12,this,[[7,18]]);}));function initializeNativePlugin(_x1,_x10){return _initializeNativePlugin.apply(this,arguments);}return initializeNativePlugin;}()},{key:"startSessionReplay",value:function(){var _startSessionReplay=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee13(options,cachedRemoteConfig){return _regenerator["default"].wrap(function(_context13){while(1)switch(_context13.prev=_context13.next){case 0:this._enableSessionReplay=options===null||options===void 0?void 0:options.enableSessionReplay;this._sessionReplayOptions=options;_context13.next=1;return this._evaluateAndStartSessionReplay(cachedRemoteConfig);case 1:case"end":return _context13.stop();}},_callee13,this);}));function startSessionReplay(_x11,_x12){return _startSessionReplay.apply(this,arguments);}return startSessionReplay;}()},{key:"_evaluateAndStartSessionReplay",value:function _evaluateAndStartSessionReplay(cachedRemoteConfig){var _this5=this;this._sessionReplayEvalChain=this._sessionReplayEvalChain["catch"](function(){}).then(function(){return _this5._evaluateAndStartSessionReplayInternal(cachedRemoteConfig);});return this._sessionReplayEvalChain;}},{key:"_evaluateAndStartSessionReplayInternal",value:function(){var _evaluateAndStartSessionReplayInternal2=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee14(cachedRemoteConfig){var _a,_b,_c,_d,options,enableNativeErrorTracking,remoteConfig,sessionReplay,featureFlags,cachedFeatureFlags,cachedSessionReplayConfig,recordingActive,linkedFlag,value,flag,variant,_value,eventTriggers,activated,_t6;return _regenerator["default"].wrap(function(_context14){while(1)switch(_context14.prev=_context14.next){case 0:options=this._sessionReplayOptions;enableNativeErrorTracking=this._isAutocaptureNativeErrors(options);remoteConfig=cachedRemoteConfig!==null&&cachedRemoteConfig!==void 0?cachedRemoteConfig:this.getPersistedProperty(_core.PostHogPersistedProperty.RemoteConfig);if(this._isEnableSessionReplay()){_context14.next=2;break;}this._logger.info('Session replay is not enabled.');this._sessionReplayEventTriggers=[];if(!enableNativeErrorTracking){_context14.next=1;break;}_context14.next=1;return this.initializeNativePlugin(options,remoteConfig,false);case 1:return _context14.abrupt("return");case 2:sessionReplay=(_a=this.getPersistedProperty(_core.PostHogPersistedProperty.SessionReplay))!==null&&_a!==void 0?_a:{};featureFlags=(_b=this.getKnownFeatureFlags())!==null&&_b!==void 0?_b:{};cachedFeatureFlags=(_c=featureFlags)!==null&&_c!==void 0?_c:{};cachedSessionReplayConfig=(_d=sessionReplay)!==null&&_d!==void 0?_d:{};this._logger.info('Session replay feature flags from flags cached config:',JSON.stringify(cachedFeatureFlags));recordingActive=true;linkedFlag=cachedSessionReplayConfig['linkedFlag'];if(typeof linkedFlag==='string'){value=cachedFeatureFlags[linkedFlag];if(typeof value==='boolean'){recordingActive=value;}else if(typeof value==='string'){recordingActive=true;}else{recordingActive=false;}this._logger.info("Session replay '".concat(linkedFlag,"' linked flag value: '").concat(value,"'"));}else if(linkedFlag&&(0,_typeof2["default"])(linkedFlag)==='object'){flag=linkedFlag['flag'];variant=linkedFlag['variant'];if(flag&&variant){_value=cachedFeatureFlags[flag];recordingActive=_value===variant;this._logger.info("Session replay '".concat(flag,"' linked flag variant '").concat(variant,"' and value '").concat(_value,"'"));}else{this._logger.info("Session replay '".concat(flag,"' linked flag variant: '").concat(variant,"' does not exist/quota limited."));recordingActive=false;}}else{this._logger.info("Session replay has no cached linkedFlag.");}eventTriggers=this._parseEventTriggers(cachedSessionReplayConfig['eventTriggers']);this._sessionReplayEventTriggers=eventTriggers;if(eventTriggers.length>0){activated=this._isEventTriggerActivatedForSession(_superPropGet(PostHog,"getSessionId",this,3)([]));if(!activated){recordingActive=false;}this._logger.info("Session replay event triggers configured (".concat(eventTriggers.length,"); activated: ").concat(activated,"."));}if(!recordingActive){_context14.next=8;break;}if(!(this._sessionReplayRecordingActive===true)){_context14.next=3;break;}return _context14.abrupt("return");case 3:if(!this._sessionReplayNativeInitialized){_context14.next=5;break;}_context14.next=4;return this._startSessionRecording(true);case 4:_t6=_context14.sent;_context14.next=7;break;case 5:_context14.next=6;return this.initializeNativePlugin(options,remoteConfig,true);case 6:_t6=_context14.sent;case 7:this._sessionReplayRecordingActive=_t6;_context14.next=12;break;case 8:this._logger.info('Session replay disabled.');if(!(this._sessionReplayRecordingActive===true)){_context14.next=10;break;}_context14.next=9;return this._stopSessionRecording();case 9:this._sessionReplayRecordingActive=!_context14.sent;_context14.next=11;break;case 10:this._sessionReplayRecordingActive=false;case 11:if(!enableNativeErrorTracking){_context14.next=12;break;}_context14.next=12;return this.initializeNativePlugin(options,remoteConfig,false);case 12:case"end":return _context14.stop();}},_callee14,this);}));function _evaluateAndStartSessionReplayInternal(_x13){return _evaluateAndStartSessionReplayInternal2.apply(this,arguments);}return _evaluateAndStartSessionReplayInternal;}()},{key:"processBeforeEnqueue",value:function processBeforeEnqueue(message){var processed=_superPropGet(PostHog,"processBeforeEnqueue",this,3)([message]);try{this._maybeActivateEventTrigger(processed===null||processed===void 0?void 0:processed['event']);}catch(e){this._logger.error("Session replay event trigger check failed: ".concat(e,"."));}return processed;}},{key:"_maybeActivateEventTrigger",value:function _maybeActivateEventTrigger(eventName){if(this._sessionReplayEventTriggers.length===0||typeof eventName!=='string'){return;}if(!this._sessionReplayEventTriggers.includes(eventName)){return;}var sessionId=_superPropGet(PostHog,"getSessionId",this,3)([]);if(!sessionId){return;}if(this._isEventTriggerActivatedForSession(sessionId)&&this._sessionReplayRecordingActive===true){return;}if(!this._isEventTriggerActivatedForSession(sessionId)){this.setPersistedProperty(_core.PostHogPersistedProperty.SessionReplayEventTriggerActivatedSession,sessionId);this._logger.info("Session replay event trigger '".concat(eventName,"' activated for session ").concat(sessionId,"."));}void this._evaluateAndStartSessionReplay();}},{key:"_parseEventTriggers",value:function _parseEventTriggers(value){if(!Array.isArray(value)){return[];}return value.filter(function(entry){return typeof entry==='string';});}},{key:"_isEventTriggerActivatedForSession",value:function _isEventTriggerActivatedForSession(sessionId){return this.getPersistedProperty(_core.PostHogPersistedProperty.SessionReplayEventTriggerActivatedSession)===sessionId;}},{key:"captureAppLifecycleEvents",value:function(){var _captureAppLifecycleEvents=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee15(){var _this6=this;var _a,appBuild,appVersion,isMemoryPersistence,properties,prevAppBuild,prevAppVersion,initialUrl,_t7,_t8,_t9;return _regenerator["default"].wrap(function(_context15){while(1)switch(_context15.prev=_context15.next){case 0:appBuild=this._appProperties.$app_build;appVersion=this._appProperties.$app_version;isMemoryPersistence=this._persistence==='memory';properties={};if(!isMemoryPersistence){prevAppBuild=this.getPersistedProperty(_core.PostHogPersistedProperty.InstalledAppBuild);prevAppVersion=this.getPersistedProperty(_core.PostHogPersistedProperty.InstalledAppVersion);if(!appBuild||!appVersion){this._logger.warn('Txlemetry could not track installation/update/open, as the build and version were not set. '+'This can happen if some dependencies are not installed correctly, or if you have provided'+'customAppProperties but not included $app_build or $app_version.');}if(appBuild){if(!prevAppBuild){this.capture('Application Installed',properties);}else if(prevAppBuild!==appBuild){this.capture('Application Updated',_objectSpread(_objectSpread(_objectSpread({},(0,_core.maybeAdd)('previous_version',prevAppVersion)),(0,_core.maybeAdd)('previous_build',prevAppBuild)),properties));}}}else{this._logger.warn('Txlemetry was initialised with persistence set to "memory", capturing native app events (Application Installed and Application Updated) is not supported.');}_context15.next=1;return _reactNative.Linking.getInitialURL();case 1:_t8=_a=_context15.sent;_t7=_t8!==null;if(!_t7){_context15.next=2;break;}_t7=_a!==void 0;case 2:if(!_t7){_context15.next=3;break;}_t9=_a;_context15.next=4;break;case 3:_t9=undefined;case 4:initialUrl=_t9;this.capture('Application Opened',_objectSpread(_objectSpread({},properties),(0,_core.maybeAdd)('url',initialUrl)));_reactNative.AppState.addEventListener('change',function(state){if(state==='active'){_this6.capture('Application Became Active');}else if(state==='background'){_this6.capture('Application Backgrounded');}});case 5:case"end":return _context15.stop();}},_callee15,this);}));function captureAppLifecycleEvents(){return _captureAppLifecycleEvents.apply(this,arguments);}return captureAppLifecycleEvents;}()},{key:"persistAppVersion",value:function(){var _persistAppVersion=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee16(){var appBuild,appVersion;return _regenerator["default"].wrap(function(_context16){while(1)switch(_context16.prev=_context16.next){case 0:appBuild=this._appProperties.$app_build;appVersion=this._appProperties.$app_version;this.setPersistedProperty(_core.PostHogPersistedProperty.InstalledAppBuild,appBuild);this.setPersistedProperty(_core.PostHogPersistedProperty.InstalledAppVersion,appVersion);case 1:case"end":return _context16.stop();}},_callee16,this);}));function persistAppVersion(){return _persistAppVersion.apply(this,arguments);}return persistAppVersion;}()}]);}(_core.PostHogCore);
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { PostHogCustomStorage } from './types';
|
|
2
|
+
type PostHogStorageContents = {
|
|
3
|
+
[key: string]: any;
|
|
4
|
+
};
|
|
5
|
+
export declare class PostHogRNStorage {
|
|
6
|
+
memoryCache: PostHogStorageContents;
|
|
7
|
+
storage: PostHogCustomStorage;
|
|
8
|
+
preloadPromise: Promise<void> | undefined;
|
|
9
|
+
private _storageKey;
|
|
10
|
+
private _pendingPromises;
|
|
11
|
+
private _persistTimer?;
|
|
12
|
+
constructor(storage: PostHogCustomStorage, storageKey: string);
|
|
13
|
+
/**
|
|
14
|
+
* Force any scheduled write to be initiated now and await in-flight async
|
|
15
|
+
* writes. Used by durability-sensitive paths (events flush, AppState
|
|
16
|
+
* background, shutdown, login/logout/opt-in/opt-out, fatal exceptions) so the
|
|
17
|
+
* latest state is on its way to the backend before they continue.
|
|
18
|
+
*
|
|
19
|
+
* Best-effort under crash: backend writes are async, so an immediate
|
|
20
|
+
* termination can interrupt them. Never throws — backend errors are logged
|
|
21
|
+
* inside persist() / _drainScheduledPersist().
|
|
22
|
+
*/
|
|
23
|
+
waitForPersist(): Promise<void>;
|
|
24
|
+
persist(): void;
|
|
25
|
+
private schedulePersist;
|
|
26
|
+
private _drainScheduledPersist;
|
|
27
|
+
getItem(key: string): any | null | undefined;
|
|
28
|
+
setItem(key: string, value: any): void;
|
|
29
|
+
removeItem(key: string): void;
|
|
30
|
+
clear(): void;
|
|
31
|
+
getAllKeys(): readonly string[];
|
|
32
|
+
populateMemoryCache(res: string | null): void;
|
|
33
|
+
}
|
|
34
|
+
export declare class PostHogRNSyncMemoryStorage extends PostHogRNStorage {
|
|
35
|
+
constructor(storageKey: string);
|
|
36
|
+
}
|
|
37
|
+
export declare function createEventsStorage(customStorage: PostHogCustomStorage): PostHogRNStorage;
|
|
38
|
+
export declare function createLogsStorage(customStorage: PostHogCustomStorage): PostHogRNStorage;
|
|
39
|
+
export declare function createEventsMemoryStorage(): PostHogRNStorage;
|
|
40
|
+
export declare function createLogsMemoryStorage(): PostHogRNStorage;
|
|
41
|
+
export {};
|
package/dist/storage.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.PostHogRNSyncMemoryStorage=exports.PostHogRNStorage=void 0;exports.createEventsMemoryStorage=createEventsMemoryStorage;exports.createEventsStorage=createEventsStorage;exports.createLogsMemoryStorage=createLogsMemoryStorage;exports.createLogsStorage=createLogsStorage;var _regenerator=_interopRequireDefault(require("@babel/runtime/regenerator"));var _possibleConstructorReturn2=_interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));var _getPrototypeOf2=_interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));var _inherits2=_interopRequireDefault(require("@babel/runtime/helpers/inherits"));var _asyncToGenerator2=_interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));var _classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));var _createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass"));var _core=require("@txlemetry/core");function _callSuper(t,o,e){return o=(0,_getPrototypeOf2["default"])(o),(0,_possibleConstructorReturn2["default"])(t,_isNativeReflectConstruct()?Reflect.construct(o,e||[],(0,_getPrototypeOf2["default"])(t).constructor):o.apply(t,e));}function _isNativeReflectConstruct(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}));}catch(t){}return(_isNativeReflectConstruct=function _isNativeReflectConstruct(){return!!t;})();}var EVENTS_STORAGE_FILE='.posthog-rn.json';var LOGS_STORAGE_FILE='.posthog-rn-logs.json';var POSTHOG_STORAGE_VERSION='v1';var PERSIST_DEBOUNCE_MS=100;var PostHogRNStorage=exports.PostHogRNStorage=function(){function PostHogRNStorage(storage,storageKey){var _this=this;(0,_classCallCheck2["default"])(this,PostHogRNStorage);var _a;this.memoryCache={};this._pendingPromises=new Set();this.storage=storage;this._storageKey=storageKey;var preloadResult=this.storage.getItem(this._storageKey);if((0,_core.isPromise)(preloadResult)){this.preloadPromise=preloadResult.then(function(res){_this.populateMemoryCache(res);});(_a=this.preloadPromise)===null||_a===void 0?void 0:_a["finally"](function(){_this.preloadPromise=undefined;});}else{this.populateMemoryCache(preloadResult);}}return(0,_createClass2["default"])(PostHogRNStorage,[{key:"waitForPersist",value:(function(){var _waitForPersist=(0,_asyncToGenerator2["default"])(_regenerator["default"].mark(function _callee(){return _regenerator["default"].wrap(function(_context){while(1)switch(_context.prev=_context.next){case 0:this._drainScheduledPersist();if(!(this._pendingPromises.size>0)){_context.next=1;break;}_context.next=1;return Promise.all(this._pendingPromises);case 1:case"end":return _context.stop();}},_callee,this);}));function waitForPersist(){return _waitForPersist.apply(this,arguments);}return waitForPersist;}())},{key:"persist",value:function persist(){var _this2=this;var payload={version:POSTHOG_STORAGE_VERSION,content:this.memoryCache};var result=this.storage.setItem(this._storageKey,JSON.stringify(payload));if((0,_core.isPromise)(result)){var promise=result["catch"](function(err){console.warn('Txlemetry storage persist failed:',err);})["finally"](function(){_this2._pendingPromises["delete"](promise);});this._pendingPromises.add(promise);}}},{key:"schedulePersist",value:function schedulePersist(){var _this3=this;if(this._persistTimer!==undefined){return;}this._persistTimer=(0,_core.safeSetTimeout)(function(){_this3._persistTimer=undefined;try{_this3.persist();}catch(err){console.warn('Txlemetry storage scheduled persist threw:',err);}},PERSIST_DEBOUNCE_MS);}},{key:"_drainScheduledPersist",value:function _drainScheduledPersist(){if(this._persistTimer===undefined){return;}clearTimeout(this._persistTimer);this._persistTimer=undefined;try{this.persist();}catch(err){console.warn('Txlemetry storage drain persist threw:',err);}}},{key:"getItem",value:function getItem(key){return this.memoryCache[key];}},{key:"setItem",value:function setItem(key,value){this.memoryCache[key]=value;this.schedulePersist();}},{key:"removeItem",value:function removeItem(key){delete this.memoryCache[key];this.schedulePersist();}},{key:"clear",value:function clear(){for(var key in this.memoryCache){delete this.memoryCache[key];}this.schedulePersist();}},{key:"getAllKeys",value:function getAllKeys(){return Object.keys(this.memoryCache);}},{key:"populateMemoryCache",value:function populateMemoryCache(res){try{var data=res?JSON.parse(res).content:{};for(var key in data){this.memoryCache[key]=data[key];}}catch(e){console.warn("Txlemetry failed to load persisted data from storage. This is likely because the storage format is. We'll reset the storage.",e);}}}]);}();var PostHogRNSyncMemoryStorage=exports.PostHogRNSyncMemoryStorage=function(_PostHogRNStorage){function PostHogRNSyncMemoryStorage(storageKey){(0,_classCallCheck2["default"])(this,PostHogRNSyncMemoryStorage);var cache={};var storage={getItem:function getItem(key){return cache[key];},setItem:function setItem(key,value){cache[key]=value;}};return _callSuper(this,PostHogRNSyncMemoryStorage,[storage,storageKey]);}(0,_inherits2["default"])(PostHogRNSyncMemoryStorage,_PostHogRNStorage);return(0,_createClass2["default"])(PostHogRNSyncMemoryStorage);}(PostHogRNStorage);function createEventsStorage(customStorage){return new PostHogRNStorage(customStorage,EVENTS_STORAGE_FILE);}function createLogsStorage(customStorage){return new PostHogRNStorage(customStorage,LOGS_STORAGE_FILE);}function createEventsMemoryStorage(){return new PostHogRNSyncMemoryStorage(EVENTS_STORAGE_FILE);}function createLogsMemoryStorage(){return new PostHogRNSyncMemoryStorage(LOGS_STORAGE_FILE);}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import React from 'react';
|
|
2
|
+
import { SurveyAppearance } from '@txlemetry/core';
|
|
3
|
+
import { PostHog } from '../posthog-rn';
|
|
4
|
+
export type PostHogSurveyProviderProps = {
|
|
5
|
+
/**
|
|
6
|
+
* The default appearance for surveys when not specified in PostHog.
|
|
7
|
+
*/
|
|
8
|
+
defaultSurveyAppearance?: SurveyAppearance;
|
|
9
|
+
/**
|
|
10
|
+
* If true, PosHog appearance will be ignored and defaultSurveyAppearance is always used.
|
|
11
|
+
*/
|
|
12
|
+
overrideAppearanceWithDefault?: boolean;
|
|
13
|
+
/**
|
|
14
|
+
* The keyboard avoiding behavior for the survey modal (KeyboardAvoidingView), applied only to Android devices.
|
|
15
|
+
* - 'padding': Adds padding to avoid keyboard (recommended)
|
|
16
|
+
* - 'height': Resizes the view height (default, for legacy - may cause flickering on some Android devices)
|
|
17
|
+
* @default 'height'
|
|
18
|
+
*/
|
|
19
|
+
androidKeyboardBehavior?: 'padding' | 'height';
|
|
20
|
+
client?: PostHog;
|
|
21
|
+
children: React.ReactNode;
|
|
22
|
+
};
|
|
23
|
+
export declare function PostHogSurveyProvider(props: PostHogSurveyProviderProps): JSX.Element;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");var _typeof=require("@babel/runtime/helpers/typeof");Object.defineProperty(exports,"__esModule",{value:true});exports.PostHogSurveyProvider=PostHogSurveyProvider;var _defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));var _slicedToArray2=_interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));var _react=_interopRequireWildcard(require("react"));var _Surveys=require("./components/Surveys");var _getActiveMatchingSurveys=require("./getActiveMatchingSurveys");var _useSurveyStorage2=require("./useSurveyStorage");var _useActivatedSurveys=require("./useActivatedSurveys");var _SurveyModal=require("./components/SurveyModal");var _surveysUtils=require("./surveys-utils");var _core=require("@txlemetry/core");var _usePostHog=require("../hooks/usePostHog");var _useFeatureFlags=require("../hooks/useFeatureFlags");var _surveyTranslations=require("./survey-translations");var _jsxRuntime=require("react/jsx-runtime");var _jsxFileName="/home/runner/work/posthog-js/posthog-js/packages/react-native/dist/surveys/PostHogSurveyProvider.js";function _interopRequireWildcard(e,t){if("function"==typeof WeakMap)var r=new WeakMap(),n=new WeakMap();return(_interopRequireWildcard=function _interopRequireWildcard(e,t){if(!t&&e&&e.__esModule)return e;var o,i,f={__proto__:null,"default":e};if(null===e||"object"!=_typeof(e)&&"function"!=typeof e)return f;if(o=t?n:r){if(o.has(e))return o.get(e);o.set(e,f);}for(var _t2 in e)"default"!==_t2&&{}.hasOwnProperty.call(e,_t2)&&((i=(o=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,_t2))&&(i.get||i.set)?o(f,_t2,i):f[_t2]=e[_t2]);return f;})(e,t);}function ownKeys(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);r&&(o=o.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable;})),t.push.apply(t,o);}return t;}function _objectSpread(e){for(var r=1;r<arguments.length;r++){var t=null!=arguments[r]?arguments[r]:{};r%2?ownKeys(Object(t),!0).forEach(function(r){(0,_defineProperty2["default"])(e,r,t[r]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):ownKeys(Object(t)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(t,r));});}return e;}var ActiveSurveyContext=_react["default"].createContext(undefined);var FeedbackSurveyContext=_react["default"].createContext(undefined);function PostHogSurveyProvider(props){var _a;var posthogFromHook=(0,_usePostHog.usePostHog)();var posthog=(_a=props.client)!==null&&_a!==void 0?_a:posthogFromHook;var _useSurveyStorage=(0,_useSurveyStorage2.useSurveyStorage)(),seenSurveys=_useSurveyStorage.seenSurveys,setSeenSurvey=_useSurveyStorage.setSeenSurvey,setLastSeenSurveyDate=_useSurveyStorage.setLastSeenSurveyDate;var _useState=(0,_react.useState)([]),_useState2=(0,_slicedToArray2["default"])(_useState,2),surveys=_useState2[0],setSurveys=_useState2[1];var _useState3=(0,_react.useState)(undefined),_useState4=(0,_slicedToArray2["default"])(_useState3,2),activeSurvey=_useState4[0],setActiveSurvey=_useState4[1];var activatedSurveys=(0,_useActivatedSurveys.useActivatedSurveys)(posthog,surveys);var flags=(0,_useFeatureFlags.useFeatureFlags)(posthog);(0,_react.useEffect)(function(){posthog.ready().then(function(){return posthog._onSurveysReady();}).then(function(){return posthog.getSurveys();}).then(setSurveys)["catch"](function(){});},[posthog]);(0,_react.useEffect)(function(){if(activeSurvey){return;}var activeSurveys=(0,_getActiveMatchingSurveys.getActiveMatchingSurveys)(surveys,flags!==null&&flags!==void 0?flags:{},seenSurveys,activatedSurveys);var popoverSurveys=activeSurveys.filter(function(survey){return survey.type===_core.SurveyType.Popover;});if(popoverSurveys.length>0){setActiveSurvey(popoverSurveys[0]);}},[activeSurvey,flags,surveys,seenSurveys,activatedSurveys]);var translatedActiveSurvey=(0,_react.useMemo)(function(){return activeSurvey?(0,_surveyTranslations.applySurveyTranslationForUser)(activeSurvey,posthog):undefined;},[activeSurvey,posthog]);var surveyAppearance=(0,_react.useMemo)(function(){var _a,_b,_c,_d,_e;if(props.overrideAppearanceWithDefault||!translatedActiveSurvey){return _objectSpread(_objectSpread({},_surveysUtils.defaultSurveyAppearance),(_a=props.defaultSurveyAppearance)!==null&&_a!==void 0?_a:{});}return _objectSpread(_objectSpread(_objectSpread(_objectSpread({},_surveysUtils.defaultSurveyAppearance),(_b=props.defaultSurveyAppearance)!==null&&_b!==void 0?_b:{}),(_c=translatedActiveSurvey.survey.appearance)!==null&&_c!==void 0?_c:{}),((_d=translatedActiveSurvey.survey.appearance)===null||_d===void 0?void 0:_d.submitButtonColor)?{submitButtonTextColor:(_e=translatedActiveSurvey.survey.appearance.submitButtonTextColor)!==null&&_e!==void 0?_e:(0,_surveysUtils.getContrastingTextColor)(translatedActiveSurvey.survey.appearance.submitButtonColor)}:{});},[translatedActiveSurvey,props.defaultSurveyAppearance,props.overrideAppearanceWithDefault]);var activeContext=(0,_react.useMemo)(function(){if(!activeSurvey||!translatedActiveSurvey){return undefined;}return{survey:translatedActiveSurvey.survey,surveyLanguage:translatedActiveSurvey.language,onShow:function onShow(){(0,_Surveys.sendSurveyShownEvent)(translatedActiveSurvey.survey,posthog,translatedActiveSurvey.language);setLastSeenSurveyDate(new Date());},onClose:function onClose(submitted,responses){setSeenSurvey(activeSurvey.id);setActiveSurvey(undefined);if(!submitted){(0,_Surveys.dismissedSurveyEvent)(translatedActiveSurvey.survey,responses,posthog,translatedActiveSurvey.language);}}};},[activeSurvey,posthog,setLastSeenSurveyDate,setSeenSurvey,translatedActiveSurvey]);var shouldShowModal=activeContext&&activeContext.survey.type===_core.SurveyType.Popover;return(0,_jsxRuntime.jsx)(ActiveSurveyContext.Provider,{value:activeContext,children:(0,_jsxRuntime.jsxs)(FeedbackSurveyContext.Provider,{value:{surveys:surveys,activeSurvey:activeSurvey,setActiveSurvey:setActiveSurvey},children:[props.children,shouldShowModal&&(0,_jsxRuntime.jsx)(_SurveyModal.SurveyModal,_objectSpread({appearance:surveyAppearance,androidKeyboardBehavior:props.androidKeyboardBehavior},activeContext))]})});}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { SurveyAppearanceTheme } from '../surveys-utils';
|
|
2
|
+
export declare function BottomSection({ text, submitDisabled, appearance, onSubmit, link, skipSubmitButton, }: {
|
|
3
|
+
text: string;
|
|
4
|
+
submitDisabled: boolean;
|
|
5
|
+
appearance: SurveyAppearanceTheme;
|
|
6
|
+
onSubmit: () => void;
|
|
7
|
+
link?: string | null;
|
|
8
|
+
skipSubmitButton?: boolean;
|
|
9
|
+
}): JSX.Element;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.BottomSection=BottomSection;var _react=_interopRequireDefault(require("react"));var _reactNative=require("react-native");var _safeStyleSheet=require("../safeStyleSheet");var _jsxRuntime=require("react/jsx-runtime");var _jsxFileName="/home/runner/work/posthog-js/posthog-js/packages/react-native/dist/surveys/components/BottomSection.js";function BottomSection(_ref){var text=_ref.text,submitDisabled=_ref.submitDisabled,appearance=_ref.appearance,onSubmit=_ref.onSubmit,link=_ref.link,skipSubmitButton=_ref.skipSubmitButton;if(skipSubmitButton){return(0,_jsxRuntime.jsx)(_jsxRuntime.Fragment,{});}return(0,_jsxRuntime.jsx)(_reactNative.View,{style:styles.bottomSection,children:(0,_jsxRuntime.jsx)(_reactNative.TouchableOpacity,{style:[styles.button,{backgroundColor:appearance.submitButtonColor},submitDisabled&&styles.buttonDisabled],disabled:submitDisabled,onPress:function onPress(){onSubmit();if(link){_reactNative.Linking.canOpenURL(link).then(function(supported){if(supported){_reactNative.Linking.openURL(link);}});}},children:(0,_jsxRuntime.jsx)(_reactNative.Text,{style:[styles.buttonText,{color:appearance.submitButtonTextColor}],children:text})})});}var styles=(0,_safeStyleSheet.createSafeStyleSheet)({bottomSection:{padding:10},button:{padding:10,borderRadius:5,alignItems:'center'},buttonText:{fontSize:16},buttonDisabled:{opacity:0.5}});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.Cancel=Cancel;var _react=_interopRequireDefault(require("react"));var _reactNative=require("react-native");var _icons=require("../icons");var _safeStyleSheet=require("../safeStyleSheet");var _jsxRuntime=require("react/jsx-runtime");var _jsxFileName="/home/runner/work/posthog-js/posthog-js/packages/react-native/dist/surveys/components/Cancel.js";function Cancel(_ref){var onPress=_ref.onPress,appearance=_ref.appearance;return(0,_jsxRuntime.jsx)(_reactNative.TouchableOpacity,{style:[styles.cancelBtnWrapper,{borderColor:appearance.borderColor}],onPress:onPress,children:(0,_jsxRuntime.jsx)(_icons.CancelSVG,{})});}var styles=(0,_safeStyleSheet.createSafeStyleSheet)({cancelBtnWrapper:{width:40,height:40,borderRadius:20,borderWidth:1,justifyContent:'center',alignItems:'center',backgroundColor:'white'}});
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { ViewStyle } from 'react-native';
|
|
2
|
+
import { SurveyAppearanceTheme } from '../surveys-utils';
|
|
3
|
+
import { SurveyQuestionDescriptionContentType } from '@txlemetry/core';
|
|
4
|
+
export declare function ConfirmationMessage({ appearance, header, description, contentType, onClose, styleOverrides, isModal, }: {
|
|
5
|
+
appearance: SurveyAppearanceTheme;
|
|
6
|
+
header: string;
|
|
7
|
+
description: string;
|
|
8
|
+
contentType?: SurveyQuestionDescriptionContentType;
|
|
9
|
+
onClose: () => void;
|
|
10
|
+
styleOverrides?: ViewStyle;
|
|
11
|
+
isModal: boolean;
|
|
12
|
+
}): JSX.Element;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.ConfirmationMessage=ConfirmationMessage;var _react=_interopRequireDefault(require("react"));var _reactNative=require("react-native");var _safeStyleSheet=require("../safeStyleSheet");var _surveysUtils=require("../surveys-utils");var _BottomSection=require("./BottomSection");var _jsxRuntime=require("react/jsx-runtime");var _jsxFileName="/home/runner/work/posthog-js/posthog-js/packages/react-native/dist/surveys/components/ConfirmationMessage.js";function ConfirmationMessage(_ref){var appearance=_ref.appearance,header=_ref.header,description=_ref.description,contentType=_ref.contentType,onClose=_ref.onClose,styleOverrides=_ref.styleOverrides,isModal=_ref.isModal;var textColor=(0,_surveysUtils.getContrastingTextColor)(appearance.backgroundColor);return(0,_jsxRuntime.jsxs)(_reactNative.View,{style:styleOverrides,children:[(0,_jsxRuntime.jsxs)(_reactNative.View,{style:styles.thankYouMessageContainer,children:[(0,_jsxRuntime.jsx)(_reactNative.Text,{style:[styles.thankYouMessageHeader,{color:textColor}],children:header}),(0,_surveysUtils.shouldRenderDescription)(description,contentType)&&(0,_jsxRuntime.jsx)(_reactNative.Text,{style:{color:textColor,opacity:_surveysUtils.defaultDescriptionOpacity},children:description})]}),isModal&&(0,_jsxRuntime.jsx)(_BottomSection.BottomSection,{text:appearance.thankYouMessageCloseButtonText,submitDisabled:false,appearance:appearance,onSubmit:onClose})]});}var styles=(0,_safeStyleSheet.createSafeStyleSheet)({thankYouMessageContainer:{padding:10},thankYouMessageHeader:{fontSize:18,fontWeight:'bold'}});
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { SurveyQuestionDescriptionContentType } from '@txlemetry/core';
|
|
2
|
+
import { SurveyAppearanceTheme } from '../surveys-utils';
|
|
3
|
+
export declare function QuestionHeader({ question, description, descriptionContentType, appearance, }: {
|
|
4
|
+
question: string;
|
|
5
|
+
description?: string | null;
|
|
6
|
+
descriptionContentType?: SurveyQuestionDescriptionContentType;
|
|
7
|
+
appearance: SurveyAppearanceTheme;
|
|
8
|
+
}): JSX.Element;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.QuestionHeader=QuestionHeader;var _react=_interopRequireDefault(require("react"));var _reactNative=require("react-native");var _safeStyleSheet=require("../safeStyleSheet");var _surveysUtils=require("../surveys-utils");var _jsxRuntime=require("react/jsx-runtime");var _jsxFileName="/home/runner/work/posthog-js/posthog-js/packages/react-native/dist/surveys/components/QuestionHeader.js";function QuestionHeader(_ref){var question=_ref.question,description=_ref.description,descriptionContentType=_ref.descriptionContentType,appearance=_ref.appearance;var _a;var textColor=(_a=appearance.textColor)!==null&&_a!==void 0?_a:(0,_surveysUtils.getContrastingTextColor)(appearance.backgroundColor);return(0,_jsxRuntime.jsxs)(_reactNative.View,{style:styles.container,children:[(0,_jsxRuntime.jsx)(_reactNative.Text,{style:[styles.question,{color:textColor}],children:question}),(0,_surveysUtils.shouldRenderDescription)(description,descriptionContentType)&&(0,_jsxRuntime.jsx)(_reactNative.Text,{style:[styles.description,{color:textColor,opacity:_surveysUtils.defaultDescriptionOpacity}],children:description})]});}var styles=(0,_safeStyleSheet.createSafeStyleSheet)({container:{padding:10},question:{fontSize:18,fontWeight:'bold'},description:{fontSize:14,marginTop:5}});
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { SurveyAppearanceTheme } from '../surveys-utils';
|
|
2
|
+
import { SurveyQuestion } from '@txlemetry/core';
|
|
3
|
+
interface QuestionCommonProps {
|
|
4
|
+
question: SurveyQuestion;
|
|
5
|
+
appearance: SurveyAppearanceTheme;
|
|
6
|
+
}
|
|
7
|
+
export declare function OpenTextQuestion({ question, appearance, onSubmit, }: QuestionCommonProps & {
|
|
8
|
+
onSubmit: (text: string) => void;
|
|
9
|
+
}): JSX.Element;
|
|
10
|
+
export declare function LinkQuestion({ question, appearance, onSubmit, }: QuestionCommonProps & {
|
|
11
|
+
onSubmit: (clicked: string) => void;
|
|
12
|
+
}): JSX.Element;
|
|
13
|
+
export declare function RatingQuestion({ question, appearance, onSubmit, }: QuestionCommonProps & {
|
|
14
|
+
onSubmit: (rating: number | null) => void;
|
|
15
|
+
}): JSX.Element;
|
|
16
|
+
export declare function RatingButton({ index, num, active, appearance, setActiveNumber, }: {
|
|
17
|
+
index: number;
|
|
18
|
+
num: number;
|
|
19
|
+
active: boolean;
|
|
20
|
+
appearance: SurveyAppearanceTheme;
|
|
21
|
+
setActiveNumber: (num: number) => void;
|
|
22
|
+
}): JSX.Element;
|
|
23
|
+
export declare function MultipleChoiceQuestion({ question, appearance, onSubmit, }: QuestionCommonProps & {
|
|
24
|
+
onSubmit: (choices: string | string[] | null) => void;
|
|
25
|
+
}): JSX.Element;
|
|
26
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");var _typeof=require("@babel/runtime/helpers/typeof");Object.defineProperty(exports,"__esModule",{value:true});exports.LinkQuestion=LinkQuestion;exports.MultipleChoiceQuestion=MultipleChoiceQuestion;exports.OpenTextQuestion=OpenTextQuestion;exports.RatingButton=RatingButton;exports.RatingQuestion=RatingQuestion;var _toConsumableArray2=_interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));var _slicedToArray2=_interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));var _react=_interopRequireWildcard(require("react"));var _reactNative=require("react-native");var _safeStyleSheet=require("../safeStyleSheet");var _icons=require("../icons");var _surveysUtils=require("../surveys-utils");var _core=require("@txlemetry/core");var _surveys=require("@txlemetry/core/surveys");var _BottomSection=require("./BottomSection");var _QuestionHeader=require("./QuestionHeader");var _jsxRuntime=require("react/jsx-runtime");var _jsxFileName="/home/runner/work/posthog-js/posthog-js/packages/react-native/dist/surveys/components/QuestionTypes.js";function _interopRequireWildcard(e,t){if("function"==typeof WeakMap)var r=new WeakMap(),n=new WeakMap();return(_interopRequireWildcard=function _interopRequireWildcard(e,t){if(!t&&e&&e.__esModule)return e;var o,i,f={__proto__:null,"default":e};if(null===e||"object"!=_typeof(e)&&"function"!=typeof e)return f;if(o=t?n:r){if(o.has(e))return o.get(e);o.set(e,f);}for(var _t2 in e)"default"!==_t2&&{}.hasOwnProperty.call(e,_t2)&&((i=(o=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,_t2))&&(i.get||i.set)?o(f,_t2,i):f[_t2]=e[_t2]);return f;})(e,t);}function QuestionLayout(_ref){var children=_ref.children,footer=_ref.footer;var _useState=(0,_react.useState)(0),_useState2=(0,_slicedToArray2["default"])(_useState,2),viewportHeight=_useState2[0],setViewportHeight=_useState2[1];var _useState3=(0,_react.useState)(0),_useState4=(0,_slicedToArray2["default"])(_useState3,2),contentHeight=_useState4[0],setContentHeight=_useState4[1];var isOverflowing=contentHeight>viewportHeight+1;return(0,_jsxRuntime.jsxs)(_reactNative.View,{style:questionLayoutStyles.container,children:[(0,_jsxRuntime.jsx)(_reactNative.ScrollView,{style:questionLayoutStyles.scroll,keyboardShouldPersistTaps:"handled",showsVerticalScrollIndicator:false,scrollEnabled:isOverflowing,bounces:isOverflowing,onLayout:function onLayout(e){return setViewportHeight(e.nativeEvent.layout.height);},onContentSizeChange:function onContentSizeChange(_width,height){return setContentHeight(height);},children:children}),footer]});}var questionLayoutStyles=(0,_safeStyleSheet.createSafeStyleSheet)({container:{flexShrink:1},scroll:{flexShrink:1}});function OpenTextQuestion(_ref2){var question=_ref2.question,appearance=_ref2.appearance,onSubmit=_ref2.onSubmit;var _a,_b,_c,_d;var _useState5=(0,_react.useState)(''),_useState6=(0,_slicedToArray2["default"])(_useState5,2),text=_useState6[0],setText=_useState6[1];var validationError=(0,_react.useMemo)(function(){return(0,_surveys.getValidationError)(text,question.validation,question.optional);},[text,question.validation,question.optional]);var minLength=(0,_surveys.getLengthFromRules)(question.validation,_core.SurveyValidationType.MinLength);var maxLength=(0,_surveys.getLengthFromRules)(question.validation,_core.SurveyValidationType.MaxLength);var requirementsHint=(0,_react.useMemo)(function(){return(0,_surveys.getRequirementsHint)(minLength,maxLength);},[minLength,maxLength]);var handleSubmit=function handleSubmit(){if(validationError){return;}onSubmit(text.trim());};return(0,_jsxRuntime.jsxs)(QuestionLayout,{footer:(0,_jsxRuntime.jsx)(_BottomSection.BottomSection,{text:(_a=question.buttonText)!==null&&_a!==void 0?_a:appearance.submitButtonText,submitDisabled:!!validationError,appearance:appearance,onSubmit:handleSubmit}),children:[(0,_jsxRuntime.jsx)(_QuestionHeader.QuestionHeader,{question:question.question,description:question.description,descriptionContentType:question.descriptionContentType,appearance:appearance}),(0,_jsxRuntime.jsxs)(_reactNative.View,{style:styles.textInputContainer,children:[(0,_jsxRuntime.jsx)(_reactNative.TextInput,{style:[styles.textInput,{backgroundColor:appearance.inputBackground,color:(_b=appearance.inputTextColor)!==null&&_b!==void 0?_b:(0,_surveysUtils.getContrastingTextColor)(appearance.inputBackground),borderColor:appearance.borderColor}],multiline:true,numberOfLines:4,placeholder:appearance.placeholder,placeholderTextColor:(0,_surveysUtils.getContrastingTextColor)((_c=appearance.inputTextColor)!==null&&_c!==void 0?_c:(0,_surveysUtils.getContrastingTextColor)(appearance.inputBackground))==='white'?'rgba(0, 0, 0, 0.5)':'rgba(255, 255, 255, 0.5)',onChangeText:setText,value:text}),requirementsHint&&(0,_jsxRuntime.jsx)(_reactNative.Text,{style:[styles.validationHint,{color:(_d=appearance.textColor)!==null&&_d!==void 0?_d:(0,_surveysUtils.getContrastingTextColor)(appearance.backgroundColor)}],children:requirementsHint})]})]});}function LinkQuestion(_ref3){var question=_ref3.question,appearance=_ref3.appearance,_onSubmit=_ref3.onSubmit;var _a,_b;question=question;return(0,_jsxRuntime.jsx)(QuestionLayout,{footer:(0,_jsxRuntime.jsx)(_BottomSection.BottomSection,{text:(_b=(_a=question.buttonText)!==null&&_a!==void 0?_a:appearance.submitButtonText)!==null&&_b!==void 0?_b:'Submit',submitDisabled:false,link:question.link,appearance:appearance,onSubmit:function onSubmit(){return _onSubmit('link clicked');}}),children:(0,_jsxRuntime.jsx)(_QuestionHeader.QuestionHeader,{question:question.question,description:question.description,descriptionContentType:question.descriptionContentType,appearance:appearance})});}function RatingQuestion(_ref4){var _this=this;var question=_ref4.question,appearance=_ref4.appearance,_onSubmit2=_ref4.onSubmit;var _a,_b,_c,_d;var _useState7=(0,_react.useState)(null),_useState8=(0,_slicedToArray2["default"])(_useState7,2),rating=_useState8[0],setRating=_useState8[1];question=question;return(0,_jsxRuntime.jsxs)(QuestionLayout,{footer:(0,_jsxRuntime.jsx)(_BottomSection.BottomSection,{text:(_a=question.buttonText)!==null&&_a!==void 0?_a:appearance.submitButtonText,submitDisabled:rating===null&&!question.optional,appearance:appearance,onSubmit:function onSubmit(){return _onSubmit2(rating);},skipSubmitButton:question.skipSubmitButton}),children:[(0,_jsxRuntime.jsx)(_QuestionHeader.QuestionHeader,{question:question.question,description:question.description,descriptionContentType:question.descriptionContentType,appearance:appearance}),(0,_jsxRuntime.jsxs)(_reactNative.View,{style:styles.ratingSection,children:[(0,_jsxRuntime.jsxs)(_reactNative.View,{style:styles.ratingOptions,children:[question.display===_core.SurveyRatingDisplay.Emoji&&(0,_jsxRuntime.jsx)(_reactNative.View,{style:styles.ratingOptionsEmoji,children:(_b=emojiScaleLists[question.scale])===null||_b===void 0?void 0:_b.map(function(Emoji,idx){var active=idx+1===rating;return(0,_jsxRuntime.jsx)(_reactNative.TouchableOpacity,{style:styles.ratingsEmoji,onPress:function onPress(){var response=idx+1;setRating(response);if(question.skipSubmitButton){_onSubmit2(response);}},children:(0,_jsxRuntime.jsx)(Emoji,{fill:active?appearance.ratingButtonActiveColor:appearance.ratingButtonColor})},idx);})}),question.display===_core.SurveyRatingDisplay.Number&&(0,_jsxRuntime.jsx)(_reactNative.View,{style:[styles.ratingOptionsNumber,{borderColor:appearance.borderColor}],children:getScaleNumbers(question.scale).map(function(number,idx){var active=rating===number;return(0,_jsxRuntime.jsx)(RatingButton,{index:idx,active:active,appearance:appearance,num:number,setActiveNumber:function setActiveNumber(response){setRating(response);if(question.skipSubmitButton){_onSubmit2(response);}}},idx);})})]}),(0,_jsxRuntime.jsxs)(_reactNative.View,{style:styles.ratingText,children:[(0,_jsxRuntime.jsx)(_reactNative.Text,{style:{color:(_c=appearance.textColor)!==null&&_c!==void 0?_c:(0,_surveysUtils.getContrastingTextColor)(appearance.backgroundColor),opacity:_surveysUtils.defaultRatingLabelOpacity},children:question.lowerBoundLabel}),(0,_jsxRuntime.jsx)(_reactNative.Text,{style:{color:(_d=appearance.textColor)!==null&&_d!==void 0?_d:(0,_surveysUtils.getContrastingTextColor)(appearance.backgroundColor),opacity:_surveysUtils.defaultRatingLabelOpacity},children:question.upperBoundLabel})]})]})]});}function RatingButton(_ref5){var index=_ref5.index,num=_ref5.num,active=_ref5.active,appearance=_ref5.appearance,setActiveNumber=_ref5.setActiveNumber;var _a;var backgroundColor=active?appearance.ratingButtonActiveColor:appearance.ratingButtonColor;var textColor=active?(0,_surveysUtils.getContrastingTextColor)(backgroundColor):(_a=appearance.inputTextColor)!==null&&_a!==void 0?_a:(0,_surveysUtils.getContrastingTextColor)(backgroundColor);return(0,_jsxRuntime.jsx)(_reactNative.TouchableOpacity,{style:[styles.ratingsNumber,index===0&&{borderLeftWidth:0},{backgroundColor:backgroundColor,borderColor:appearance.borderColor}],onPress:function onPress(){return setActiveNumber(num);},children:(0,_jsxRuntime.jsx)(_reactNative.Text,{style:{color:textColor},children:num})});}function MultipleChoiceQuestion(_ref6){var _this2=this;var question=_ref6.question,appearance=_ref6.appearance,_onSubmit3=_ref6.onSubmit;var _a;question=question;var isSingleChoice=question.type===_core.SurveyQuestionType.SingleChoice;var allowMultiple=question.type===_core.SurveyQuestionType.MultipleChoice;var openChoice=question.hasOpenChoice?question.choices[question.choices.length-1]:null;var choices=(0,_react.useMemo)(function(){return(0,_surveysUtils.getDisplayOrderChoices)(question);},[question]);var _useState9=(0,_react.useState)([]),_useState0=(0,_slicedToArray2["default"])(_useState9,2),selectedChoices=_useState0[0],setSelectedChoices=_useState0[1];var _useState1=(0,_react.useState)(''),_useState10=(0,_slicedToArray2["default"])(_useState1,2),openEndedInput=_useState10[0],setOpenEndedInput=_useState10[1];var shouldSkipSubmit=question.skipSubmitButton&&isSingleChoice&&!question.hasOpenChoice;return(0,_jsxRuntime.jsxs)(QuestionLayout,{footer:(0,_jsxRuntime.jsx)(_BottomSection.BottomSection,{text:(_a=question.buttonText)!==null&&_a!==void 0?_a:appearance.submitButtonText,submitDisabled:!question.optional&&(selectedChoices.length===0||openChoice!==null&&selectedChoices.includes(openChoice)&&openEndedInput.length===0),appearance:appearance,onSubmit:function onSubmit(){var result=selectedChoices.map(function(c){return c===openChoice?openEndedInput:c;});_onSubmit3(allowMultiple?result:result[0]);},skipSubmitButton:shouldSkipSubmit}),children:[(0,_jsxRuntime.jsx)(_QuestionHeader.QuestionHeader,{question:question.question,description:question.description,descriptionContentType:question.descriptionContentType,appearance:appearance}),(0,_jsxRuntime.jsx)(_reactNative.View,{style:styles.multipleChoiceOptions,children:choices.map(function(choice,idx){var _a;var isOpenChoice=choice===openChoice;var isSelected=selectedChoices.includes(choice);var choiceTextColor=(_a=appearance.inputTextColor)!==null&&_a!==void 0?_a:(0,_surveysUtils.getContrastingTextColor)(appearance.inputBackground);return(0,_jsxRuntime.jsxs)(_reactNative.Pressable,{style:[styles.choiceOption,{backgroundColor:appearance.inputBackground},isSelected?{borderColor:(0,_surveysUtils.getContrastingTextColor)(appearance.backgroundColor)}:{}],onPress:function onPress(){if(allowMultiple){setSelectedChoices(isSelected?selectedChoices.filter(function(c){return c!==choice;}):[].concat((0,_toConsumableArray2["default"])(selectedChoices),[choice]));}else{setSelectedChoices([choice]);if(shouldSkipSubmit&&!isOpenChoice){_onSubmit3(choice);}}},children:[(0,_jsxRuntime.jsxs)(_reactNative.View,{style:styles.choiceText,children:[(0,_jsxRuntime.jsxs)(_reactNative.Text,{style:{flexGrow:1,color:choiceTextColor},children:[choice,isOpenChoice?':':'']}),(0,_jsxRuntime.jsx)(_reactNative.View,{style:styles.rightCheckArea,children:isSelected&&(0,_jsxRuntime.jsx)(_icons.CheckSVG,{})})]}),isOpenChoice&&(0,_jsxRuntime.jsx)(_reactNative.TextInput,{style:styles.openEndedInput,onChangeText:function onChangeText(userValue){setOpenEndedInput(userValue);if(!isSelected){setSelectedChoices(allowMultiple?[].concat((0,_toConsumableArray2["default"])(selectedChoices),[choice]):[choice]);}}})]},idx);})})]});}var emojiScaleLists={2:[_icons.ThumbsUpEmoji,_icons.ThumbsDownEmoji],3:[_icons.DissatisfiedEmoji,_icons.NeutralEmoji,_icons.SatisfiedEmoji],5:[_icons.VeryDissatisfiedEmoji,_icons.DissatisfiedEmoji,_icons.NeutralEmoji,_icons.SatisfiedEmoji,_icons.VerySatisfiedEmoji]};var fiveScaleNumbers=[1,2,3,4,5];var sevenScaleNumbers=[1,2,3,4,5,6,7];var tenScaleNumbers=[0,1,2,3,4,5,6,7,8,9,10];function getScaleNumbers(scale){switch(scale){case 5:return fiveScaleNumbers;case 7:return sevenScaleNumbers;case 10:return tenScaleNumbers;default:return fiveScaleNumbers;}}var styles=(0,_safeStyleSheet.createSafeStyleSheet)({textInputContainer:{padding:10},textInput:{borderColor:'#ccc',borderWidth:1,padding:10,marginVertical:10,fontSize:16,height:80,textAlignVertical:'top'},ratingSection:{marginVertical:10},ratingOptions:{flexDirection:'row',justifyContent:'space-between'},ratingOptionsEmoji:{flexDirection:'row',justifyContent:'space-around',flexWrap:'nowrap',flex:1},ratingsEmoji:{padding:4},ratingOptionsNumber:{margin:10,flexGrow:1,flexDirection:'row',justifyContent:'space-between',borderRadius:5,borderWidth:1,overflow:'hidden'},ratingsNumber:{flex:1,paddingVertical:10,alignItems:'center',borderLeftWidth:1},ratingText:{flexDirection:'row',justifyContent:'space-between',padding:10},multipleChoiceOptions:{padding:10},choiceOption:{flexDirection:'column',marginVertical:5,borderWidth:1,borderColor:'grey',borderRadius:5,padding:10},choiceText:{flexDirection:'row'},rightCheckArea:{flexGrow:0},openEndedInput:{padding:5},validationHint:{fontSize:12,opacity:0.7,marginTop:4}});
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { SurveyAppearanceTheme } from '../surveys-utils';
|
|
2
|
+
import { Survey, type SurveyResponses } from '@txlemetry/core';
|
|
3
|
+
export type SurveyModalProps = {
|
|
4
|
+
survey: Survey;
|
|
5
|
+
surveyLanguage: string | null;
|
|
6
|
+
appearance: SurveyAppearanceTheme;
|
|
7
|
+
onShow: () => void;
|
|
8
|
+
onClose: (submitted: boolean, responses: SurveyResponses) => void;
|
|
9
|
+
androidKeyboardBehavior?: 'padding' | 'height';
|
|
10
|
+
};
|
|
11
|
+
export declare function SurveyModal(props: SurveyModalProps): JSX.Element | null;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");var _typeof=require("@babel/runtime/helpers/typeof");Object.defineProperty(exports,"__esModule",{value:true});exports.SurveyModal=SurveyModal;var _slicedToArray2=_interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));var _react=_interopRequireWildcard(require("react"));var _reactNative=require("react-native");var _Cancel=require("./Cancel");var _ConfirmationMessage=require("./ConfirmationMessage");var _safeStyleSheet=require("../safeStyleSheet");var _surveysUtils=require("../surveys-utils");var _OptionalReactNativeSafeArea=require("../../optional/OptionalReactNativeSafeArea");var _Surveys=require("./Surveys");var _jsxRuntime=require("react/jsx-runtime");var _jsxFileName="/home/runner/work/posthog-js/posthog-js/packages/react-native/dist/surveys/components/SurveyModal.js";function _interopRequireWildcard(e,t){if("function"==typeof WeakMap)var r=new WeakMap(),n=new WeakMap();return(_interopRequireWildcard=function _interopRequireWildcard(e,t){if(!t&&e&&e.__esModule)return e;var o,i,f={__proto__:null,"default":e};if(null===e||"object"!=_typeof(e)&&"function"!=typeof e)return f;if(o=t?n:r){if(o.has(e))return o.get(e);o.set(e,f);}for(var _t2 in e)"default"!==_t2&&{}.hasOwnProperty.call(e,_t2)&&((i=(o=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,_t2))&&(i.get||i.set)?o(f,_t2,i):f[_t2]=e[_t2]);return f;})(e,t);}var VIEWPORT_BUFFER=0;var MODAL_FADE_DURATION_MS=250;var IOS_DISMISS_FALLBACK_MS=1000;function SurveyModal(props){var survey=props.survey,surveyLanguage=props.surveyLanguage,appearance=props.appearance,onShow=props.onShow,onCloseProp=props.onClose,_props$androidKeyboar=props.androidKeyboardBehavior,androidKeyboardBehavior=_props$androidKeyboar===void 0?'height':_props$androidKeyboar;var _useState=(0,_react.useState)(false),_useState2=(0,_slicedToArray2["default"])(_useState,2),isSurveySent=_useState2[0],setIsSurveySent=_useState2[1];var _useState3=(0,_react.useState)({}),_useState4=(0,_slicedToArray2["default"])(_useState3,2),responses=_useState4[0],setResponses=_useState4[1];var _useState5=(0,_react.useState)(true),_useState6=(0,_slicedToArray2["default"])(_useState5,2),isVisible=_useState6[0],setIsVisible=_useState6[1];var _useState7=(0,_react.useState)(true),_useState8=(0,_slicedToArray2["default"])(_useState7,2),contentMounted=_useState8[0],setContentMounted=_useState8[1];var isClosingRef=(0,_react.useRef)(false);var closeNotifiedRef=(0,_react.useRef)(false);var closeTimerRef=(0,_react.useRef)(null);var notifyParentClosed=(0,_react.useCallback)(function(){if(closeNotifiedRef.current)return;closeNotifiedRef.current=true;onCloseProp(isSurveySent,responses);},[isSurveySent,onCloseProp,responses]);var onClose=(0,_react.useCallback)(function(){if(isClosingRef.current)return;isClosingRef.current=true;setContentMounted(false);requestAnimationFrame(function(){setIsVisible(false);var fallbackDelay=_reactNative.Platform.OS==='ios'?IOS_DISMISS_FALLBACK_MS:MODAL_FADE_DURATION_MS;closeTimerRef.current=setTimeout(notifyParentClosed,fallbackDelay);});},[notifyParentClosed]);(0,_react.useEffect)(function(){return function(){if(closeTimerRef.current){clearTimeout(closeTimerRef.current);}};},[]);var insets=(0,_OptionalReactNativeSafeArea.useOptionalSafeAreaInsets)();var _useWindowDimensions=(0,_reactNative.useWindowDimensions)(),windowHeight=_useWindowDimensions.height;var _useState9=(0,_react.useState)(0),_useState0=(0,_slicedToArray2["default"])(_useState9,2),keyboardHeight=_useState0[0],setKeyboardHeight=_useState0[1];var _resolveSurveyAlignme=(0,_surveysUtils.resolveSurveyAlignment)(appearance.position),vertical=_resolveSurveyAlignme.vertical,horizontal=_resolveSurveyAlignme.horizontal;var isBottom=vertical==='flex-end';var shouldShowConfirmation=isSurveySent&&appearance.thankYouMessageHeader;(0,_react.useEffect)(function(){if(isVisible){onShow();}},[isVisible,onShow]);(0,_react.useEffect)(function(){var showEvent=_reactNative.Platform.OS==='ios'?'keyboardWillShow':'keyboardDidShow';var hideEvent=_reactNative.Platform.OS==='ios'?'keyboardWillHide':'keyboardDidHide';var showSub=_reactNative.Keyboard.addListener(showEvent,function(e){return setKeyboardHeight(e.endCoordinates.height);});var hideSub=_reactNative.Keyboard.addListener(hideEvent,function(){return setKeyboardHeight(0);});return function(){showSub.remove();hideSub.remove();};},[]);var maxModalHeight=Math.max(windowHeight-keyboardHeight-insets.top-insets.bottom-VIEWPORT_BUFFER,200);var keyboardBehavior=_reactNative.Platform.OS==='ios'?'padding':androidKeyboardBehavior;return(0,_jsxRuntime.jsx)(_reactNative.Modal,{visible:isVisible,animationType:"fade",transparent:true,onRequestClose:onClose,onDismiss:_reactNative.Platform.OS==='ios'?notifyParentClosed:undefined,statusBarTranslucent:true,children:contentMounted&&(0,_jsxRuntime.jsx)(_reactNative.KeyboardAvoidingView,{behavior:keyboardBehavior,style:styles.fill,children:(0,_jsxRuntime.jsx)(_reactNative.View,{style:[styles.fill,styles.backdrop,{justifyContent:vertical}],onTouchStart:_reactNative.Keyboard.dismiss,children:(0,_jsxRuntime.jsx)(_reactNative.View,{style:[styles.modalRow,{justifyContent:horizontal}],children:(0,_jsxRuntime.jsx)(_reactNative.View,{style:styles.modalContent,pointerEvents:"box-none",children:(0,_jsxRuntime.jsxs)(_reactNative.View,{style:[styles.modalContentInner,{borderColor:appearance.borderColor,backgroundColor:appearance.backgroundColor,marginTop:vertical==='flex-start'?insets.top+10:0,marginBottom:isBottom?keyboardHeight>0?0:insets.bottom+10:0,marginHorizontal:10,maxHeight:maxModalHeight}],children:[(0,_jsxRuntime.jsx)(_reactNative.View,{style:styles.topIconContainer,children:(0,_jsxRuntime.jsx)(_Cancel.Cancel,{onPress:onClose,appearance:appearance})}),isSurveySent?shouldShowConfirmation?(0,_jsxRuntime.jsx)(_ConfirmationMessage.ConfirmationMessage,{appearance:appearance,header:appearance.thankYouMessageHeader,description:appearance.thankYouMessageDescription,contentType:appearance.thankYouMessageDescriptionContentType,onClose:onClose,isModal:true}):null:(0,_jsxRuntime.jsx)(_Surveys.Questions,{survey:survey,surveyLanguage:surveyLanguage,appearance:appearance,responses:responses,onResponsesChange:setResponses,onSubmit:function onSubmit(){return setIsSurveySent(true);}})]})})})})})});}var styles=(0,_safeStyleSheet.createSafeStyleSheet)({fill:{flex:1},backdrop:{backgroundColor:'rgba(0, 0, 0, 0.32)'},modalRow:{flexDirection:'row'},modalContent:{width:'90%',maxWidth:400},modalContentInner:{borderRadius:10,borderWidth:1,padding:20},topIconContainer:{position:'absolute',right:8,top:8,zIndex:1}});
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { StyleProp, ViewStyle } from 'react-native';
|
|
2
|
+
import { SurveyAppearanceTheme } from '../surveys-utils';
|
|
3
|
+
import { Survey, type SurveyResponses } from '@txlemetry/core';
|
|
4
|
+
import { PostHog } from '../../posthog-rn';
|
|
5
|
+
export declare const sendSurveyShownEvent: (survey: Survey, posthog: PostHog, surveyLanguage?: string | null) => void;
|
|
6
|
+
export declare const sendSurveyEvent: (responses: SurveyResponses | undefined, survey: Survey, posthog: PostHog, surveyLanguage?: string | null) => void;
|
|
7
|
+
export declare const dismissedSurveyEvent: (survey: Survey, responses: SurveyResponses | undefined, posthog: PostHog, surveyLanguage?: string | null) => void;
|
|
8
|
+
export declare function Questions({ survey, surveyLanguage, appearance, styleOverrides, responses, onResponsesChange, onSubmit, }: {
|
|
9
|
+
survey: Survey;
|
|
10
|
+
surveyLanguage?: string | null;
|
|
11
|
+
appearance: SurveyAppearanceTheme;
|
|
12
|
+
styleOverrides?: StyleProp<ViewStyle>;
|
|
13
|
+
responses?: SurveyResponses;
|
|
14
|
+
onResponsesChange?: (responses: SurveyResponses) => void;
|
|
15
|
+
onSubmit: () => void;
|
|
16
|
+
}): JSX.Element;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");var _typeof=require("@babel/runtime/helpers/typeof");Object.defineProperty(exports,"__esModule",{value:true});exports.Questions=Questions;exports.sendSurveyShownEvent=exports.sendSurveyEvent=exports.dismissedSurveyEvent=void 0;var _slicedToArray2=_interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));var _defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));var _react=_interopRequireWildcard(require("react"));var _surveysUtils=require("../surveys-utils");var _core=require("@txlemetry/core");var _surveys=require("@txlemetry/core/surveys");var _QuestionTypes=require("./QuestionTypes");var _usePostHog=require("../../hooks/usePostHog");var _jsxRuntime=require("react/jsx-runtime");var _this=void 0,_jsxFileName="/home/runner/work/posthog-js/posthog-js/packages/react-native/dist/surveys/components/Surveys.js";function _interopRequireWildcard(e,t){if("function"==typeof WeakMap)var r=new WeakMap(),n=new WeakMap();return(_interopRequireWildcard=function _interopRequireWildcard(e,t){if(!t&&e&&e.__esModule)return e;var o,i,f={__proto__:null,"default":e};if(null===e||"object"!=_typeof(e)&&"function"!=typeof e)return f;if(o=t?n:r){if(o.has(e))return o.get(e);o.set(e,f);}for(var _t2 in e)"default"!==_t2&&{}.hasOwnProperty.call(e,_t2)&&((i=(o=Object.defineProperty)&&Object.getOwnPropertyDescriptor(e,_t2))&&(i.get||i.set)?o(f,_t2,i):f[_t2]=e[_t2]);return f;})(e,t);}function ownKeys(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);r&&(o=o.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable;})),t.push.apply(t,o);}return t;}function _objectSpread(e){for(var r=1;r<arguments.length;r++){var t=null!=arguments[r]?arguments[r]:{};r%2?ownKeys(Object(t),!0).forEach(function(r){(0,_defineProperty2["default"])(e,r,t[r]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):ownKeys(Object(t)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(t,r));});}return e;}var sendSurveyShownEvent=exports.sendSurveyShownEvent=function sendSurveyShownEvent(survey,posthog,surveyLanguage){posthog.capture('survey shown',_objectSpread(_objectSpread(_objectSpread({$survey_name:survey.name,$survey_id:survey.id},(0,_core.maybeAdd)('$survey_iteration',survey.current_iteration)),(0,_core.maybeAdd)('$survey_iteration_start_date',survey.current_iteration_start_date)),surveyLanguage?(0,_defineProperty2["default"])({},_surveys.SURVEY_LANGUAGE_PROPERTY,surveyLanguage):{}));};var sendSurveyEvent=exports.sendSurveyEvent=function sendSurveyEvent(){var responses=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var survey=arguments.length>1?arguments[1]:undefined;var posthog=arguments.length>2?arguments[2]:undefined;var surveyLanguage=arguments.length>3?arguments[3]:undefined;posthog.capture('survey sent',_objectSpread(_objectSpread(_objectSpread(_objectSpread(_objectSpread({$survey_name:survey.name,$survey_id:survey.id},(0,_core.maybeAdd)('$survey_iteration',survey.current_iteration)),(0,_core.maybeAdd)('$survey_iteration_start_date',survey.current_iteration_start_date)),surveyLanguage?(0,_defineProperty2["default"])({},_surveys.SURVEY_LANGUAGE_PROPERTY,surveyLanguage):{}),(0,_surveys.buildSurveyResponseProperties)(responses,survey)),{},{$set:(0,_defineProperty2["default"])({},(0,_surveys.getSurveyInteractionProperty)(survey,'responded'),true)}));};var dismissedSurveyEvent=exports.dismissedSurveyEvent=function dismissedSurveyEvent(survey){var responses=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var posthog=arguments.length>2?arguments[2]:undefined;var surveyLanguage=arguments.length>3?arguments[3]:undefined;posthog.capture('survey dismissed',_objectSpread(_objectSpread(_objectSpread(_objectSpread(_objectSpread({$survey_name:survey.name,$survey_id:survey.id},(0,_core.maybeAdd)('$survey_iteration',survey.current_iteration)),(0,_core.maybeAdd)('$survey_iteration_start_date',survey.current_iteration_start_date)),surveyLanguage?(0,_defineProperty2["default"])({},_surveys.SURVEY_LANGUAGE_PROPERTY,surveyLanguage):{}),{},{$survey_partially_completed:(0,_surveys.surveyHasResponses)(responses)},(0,_surveys.buildSurveyResponseProperties)(responses,survey)),{},{$set:(0,_defineProperty2["default"])({},(0,_surveys.getSurveyInteractionProperty)(survey,'dismissed'),true)}));};function Questions(_ref4){var survey=_ref4.survey,surveyLanguage=_ref4.surveyLanguage,appearance=_ref4.appearance,styleOverrides=_ref4.styleOverrides,_ref4$responses=_ref4.responses,responses=_ref4$responses===void 0?{}:_ref4$responses,_ref4$onResponsesChan=_ref4.onResponsesChange,onResponsesChange=_ref4$onResponsesChan===void 0?function(){}:_ref4$onResponsesChan,onSubmit=_ref4.onSubmit;var _useState=(0,_react.useState)(0),_useState2=(0,_slicedToArray2["default"])(_useState,2),currentQuestionIndex=_useState2[0],setCurrentQuestionIndex=_useState2[1];var surveyQuestions=(0,_react.useMemo)(function(){return(0,_surveysUtils.getDisplayOrderQuestions)(survey);},[survey]);var posthog=(0,_usePostHog.usePostHog)();var onNextButtonClick=function onNextButtonClick(_ref5){var res=_ref5.res,originalQuestionIndex=_ref5.originalQuestionIndex,questionId=_ref5.questionId;var responseKey=(0,_surveys.getSurveyResponseKey)(questionId);var allResponses=_objectSpread(_objectSpread({},responses),{},(0,_defineProperty2["default"])({},responseKey,res));onResponsesChange(allResponses);var nextStep=(0,_surveysUtils.getNextSurveyStep)(survey,originalQuestionIndex,res);if(nextStep===_core.SurveyQuestionBranchingType.End){sendSurveyEvent(allResponses,survey,posthog,surveyLanguage);onSubmit();}else{setCurrentQuestionIndex(nextStep);}};var question=surveyQuestions[currentQuestionIndex];return getQuestionComponent({question:question,appearance:appearance,styleOverrides:styleOverrides,onSubmit:function onSubmit(res){return onNextButtonClick({res:res,originalQuestionIndex:question.originalQuestionIndex,questionId:question.id});}});}var getQuestionComponent=function getQuestionComponent(props){var questionComponents={open:_QuestionTypes.OpenTextQuestion,link:_QuestionTypes.LinkQuestion,rating:_QuestionTypes.RatingQuestion,multiple_choice:_QuestionTypes.MultipleChoiceQuestion,single_choice:_QuestionTypes.MultipleChoiceQuestion};var Component=questionComponents[props.question.type];return(0,_jsxRuntime.jsx)(Component,_objectSpread({},props),props.question.originalQuestionIndex);};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.getActiveMatchingSurveys=getActiveMatchingSurveys;var _surveysUtils=require("./surveys-utils");var _nativeDeps=require("../native-deps");var _core=require("@txlemetry/core");var ANY_FLAG_VARIANT='any';function defaultMatchType(matchType){return matchType!==null&&matchType!==void 0?matchType:_core.SurveyMatchType.Icontains;}function doesSurveyDeviceTypesMatch(survey){var _a;if(!((_a=survey.conditions)===null||_a===void 0?void 0:_a.deviceTypes)||survey.conditions.deviceTypes.length===0){return true;}return _surveysUtils.surveyValidationMap[defaultMatchType(survey.conditions.deviceTypesMatchType)](survey.conditions.deviceTypes,[_nativeDeps.currentDeviceType]);}function isSurveyFlagEnabled(flagKey,flags){return flagKey?!!flags[flagKey]===true:true;}function getActiveMatchingSurveys(surveys,flags,seenSurveys,activatedSurveys){return surveys.filter(function(survey){var _a,_b,_c,_d,_e;if(!survey.start_date||survey.end_date){return false;}if(!doesSurveyDeviceTypesMatch(survey)){return false;}if(seenSurveys.includes(survey.id)&&!(0,_surveysUtils.canActivateRepeatedly)(survey)){return false;}if(((_a=survey.conditions)===null||_a===void 0?void 0:_a.url)&&survey.conditions.url!==''||((_b=survey.conditions)===null||_b===void 0?void 0:_b.selector)&&survey.conditions.selector!==''){return false;}if(!survey.linked_flag_key&&!survey.targeting_flag_key&&!survey.internal_targeting_flag_key&&!((_c=survey.feature_flag_keys)===null||_c===void 0?void 0:_c.length)){return true;}var linkedFlagCheck=isSurveyFlagEnabled(survey.linked_flag_key,flags);var linkedFlagVariant=(_d=survey.conditions)===null||_d===void 0?void 0:_d.linkedFlagVariant;var linkedFlagVariantCheck=true;if(linkedFlagVariant){linkedFlagVariantCheck=survey.linked_flag_key?flags[survey.linked_flag_key]===linkedFlagVariant||linkedFlagVariant===ANY_FLAG_VARIANT:true;}var targetingFlagCheck=isSurveyFlagEnabled(survey.targeting_flag_key,flags);var eventBasedTargetingFlagCheck=(0,_surveysUtils.hasEvents)(survey)?activatedSurveys.has(survey.id):true;var internalTargetingFlagCheck=survey.internal_targeting_flag_key&&!(0,_surveysUtils.canActivateRepeatedly)(survey)?isSurveyFlagEnabled(survey.internal_targeting_flag_key,flags):true;var flagsCheck=((_e=survey.feature_flag_keys)===null||_e===void 0?void 0:_e.length)?survey.feature_flag_keys.every(function(_ref){var key=_ref.key,value=_ref.value;return!key||!value||isSurveyFlagEnabled(value,flags);}):true;return linkedFlagCheck&&linkedFlagVariantCheck&&targetingFlagCheck&&internalTargetingFlagCheck&&eventBasedTargetingFlagCheck&&flagsCheck;});}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { JSX } from 'react';
|
|
2
|
+
import type { SvgProps } from 'react-native-svg';
|
|
3
|
+
export declare const SatisfiedEmoji: (props: SvgProps) => JSX.Element;
|
|
4
|
+
export declare const NeutralEmoji: (props: SvgProps) => JSX.Element;
|
|
5
|
+
export declare const DissatisfiedEmoji: (props: SvgProps) => JSX.Element;
|
|
6
|
+
export declare const VeryDissatisfiedEmoji: (props: SvgProps) => JSX.Element;
|
|
7
|
+
export declare const VerySatisfiedEmoji: (props: SvgProps) => JSX.Element;
|
|
8
|
+
export declare const ThumbsUpEmoji: (props: SvgProps) => JSX.Element;
|
|
9
|
+
export declare const ThumbsDownEmoji: (props: SvgProps) => JSX.Element;
|
|
10
|
+
export declare const CheckSVG: (props: SvgProps) => JSX.Element;
|
|
11
|
+
export declare const CancelSVG: (props: SvgProps) => JSX.Element;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.VerySatisfiedEmoji=exports.VeryDissatisfiedEmoji=exports.ThumbsUpEmoji=exports.ThumbsDownEmoji=exports.SatisfiedEmoji=exports.NeutralEmoji=exports.DissatisfiedEmoji=exports.CheckSVG=exports.CancelSVG=void 0;var _defineProperty2=_interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));var _react=_interopRequireDefault(require("react"));var _reactNative=require("react-native");var _OptionalReactNativeSvg=require("../optional/OptionalReactNativeSvg");var _safeStyleSheet=require("./safeStyleSheet");var _jsxRuntime=require("react/jsx-runtime");var _this=void 0,_jsxFileName="/home/runner/work/posthog-js/posthog-js/packages/react-native/dist/surveys/icons.js";function ownKeys(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);r&&(o=o.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable;})),t.push.apply(t,o);}return t;}function _objectSpread(e){for(var r=1;r<arguments.length;r++){var t=null!=arguments[r]?arguments[r]:{};r%2?ownKeys(Object(t),!0).forEach(function(r){(0,_defineProperty2["default"])(e,r,t[r]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):ownKeys(Object(t)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(t,r));});}return e;}var Svg=_OptionalReactNativeSvg.OptionalReactNativeSvg===null||_OptionalReactNativeSvg.OptionalReactNativeSvg===void 0?void 0:_OptionalReactNativeSvg.OptionalReactNativeSvg.Svg;var Path=_OptionalReactNativeSvg.OptionalReactNativeSvg===null||_OptionalReactNativeSvg.OptionalReactNativeSvg===void 0?void 0:_OptionalReactNativeSvg.OptionalReactNativeSvg.Path;var getFallbackSize=function getFallbackSize(value,fallback){if(typeof value==='number'){return value;}if(typeof value==='string'){var parsed=Number.parseInt(value,10);return Number.isNaN(parsed)?fallback:parsed;}return fallback;};var getFallbackColor=function getFallbackColor(fill){return typeof fill==='string'&&fill!=='none'?fill:'black';};var getFallbackFontSize=function getFallbackFontSize(label,height){return label.length>1?Math.round(height*0.55):height;};var renderFallbackIcon=function renderFallbackIcon(_ref){var label=_ref.label,fill=_ref.fill,height=_ref.height;return(0,_jsxRuntime.jsx)(_reactNative.Text,{style:[styles.fallbackIcon,{color:getFallbackColor(fill),fontSize:getFallbackFontSize(label,height),height:height,lineHeight:height,width:height}],children:label});};var renderSvgIcon=function renderSvgIcon(_ref2){var props=_ref2.props,height=_ref2.height,width=_ref2.width,viewBox=_ref2.viewBox,pathProps=_ref2.pathProps,fallback=_ref2.fallback;var _a;if(!Svg||!Path){return renderFallbackIcon({label:fallback,fill:props.fill,height:getFallbackSize((_a=props.height)!==null&&_a!==void 0?_a:height,48)});}return(0,_jsxRuntime.jsx)(Svg,_objectSpread(_objectSpread({height:height,viewBox:viewBox,width:width},props),{},{children:(0,_jsxRuntime.jsx)(Path,_objectSpread({},pathProps))}));};var SatisfiedEmoji=exports.SatisfiedEmoji=function SatisfiedEmoji(props){return renderSvgIcon({props:props,height:'48',viewBox:'0 -960 960 960',width:'48',fallback:':)',pathProps:{d:'M626-533q22.5 0 38.25-15.75T680-587q0-22.5-15.75-38.25T626-641q-22.5 0-38.25 15.75T572-587q0 22.5 15.75 38.25T626-533Zm-292 0q22.5 0 38.25-15.75T388-587q0-22.5-15.75-38.25T334-641q-22.5 0-38.25 15.75T280-587q0 22.5 15.75 38.25T334-533Zm146 272q66 0 121.5-35.5T682-393h-52q-23 40-63 61.5T480.5-310q-46.5 0-87-21T331-393h-53q26 61 81 96.5T480-261Zm0 181q-83 0-156-31.5T197-197q-54-54-85.5-127T80-480q0-83 31.5-156T197-763q54-54 127-85.5T480-880q83 0 156 31.5T763-763q54 54 85.5 127T880-480q0 83-31.5 156T763-197q-54 54-127 85.5T480-80Zm0-400Zm0 340q142.375 0 241.188-98.812Q820-337.625 820-480t-98.812-241.188Q622.375-820 480-820t-241.188 98.812Q140-622.375 140-480t98.812 241.188Q337.625-140 480-140Z'}});};var NeutralEmoji=exports.NeutralEmoji=function NeutralEmoji(props){return renderSvgIcon({props:props,height:'48',viewBox:'0 -960 960 960',width:'48',fallback:':|',pathProps:{d:'M626-533q22.5 0 38.25-15.75T680-587q0-22.5-15.75-38.25T626-641q-22.5 0-38.25 15.75T572-587q0 22.5 15.75 38.25T626-533Zm-292 0q22.5 0 38.25-15.75T388-587q0-22.5-15.75-38.25T334-641q-22.5 0-38.25 15.75T280-587q0 22.5 15.75 38.25T334-533Zm20 194h253v-49H354v49ZM480-80q-83 0-156-31.5T197-197q-54-54-85.5-127T80-480q0-83 31.5-156T197-763q54-54 127-85.5T480-880q83 0 156 31.5T763-763q54 54 85.5 127T880-480q0 83-31.5 156T763-197q-54 54-127 85.5T480-80Zm0-400Zm0 340q142.375 0 241.188-98.812Q820-337.625 820-480t-98.812-241.188Q622.375-820 480-820t-241.188 98.812Q140-622.375 140-480t98.812 241.188Q337.625-140 480-140Z'}});};var DissatisfiedEmoji=exports.DissatisfiedEmoji=function DissatisfiedEmoji(props){return renderSvgIcon({props:props,height:'48',viewBox:'0 -960 960 960',width:'48',fallback:':(',pathProps:{d:'M626-533q22.5 0 38.25-15.75T680-587q0-22.5-15.75-38.25T626-641q-22.5 0-38.25 15.75T572-587q0 22.5 15.75 38.25T626-533Zm-292 0q22.5 0 38.25-15.75T388-587q0-22.5-15.75-38.25T334-641q-22.5 0-38.25 15.75T280-587q0 22.5 15.75 38.25T334-533Zm146.174 116Q413-417 358.5-379.5T278-280h53q22-42 62.173-65t87.5-23Q528-368 567.5-344.5T630-280h52q-25-63-79.826-100-54.826-37-122-37ZM480-80q-83 0-156-31.5T197-197q-54-54-85.5-127T80-480q0-83 31.5-156T197-763q54-54 127-85.5T480-880q83 0 156 31.5T763-763q54 54 85.5 127T880-480q0 83-31.5 156T763-197q-54 54-127 85.5T480-80Zm0-400Zm0 340q142.375 0 241.188-98.812Q820-337.625 820-480t-98.812-241.188Q622.375-820 480-820t-241.188 98.812Q140-622.375 140-480t98.812 241.188Q337.625-140 480-140Z'}});};var VeryDissatisfiedEmoji=exports.VeryDissatisfiedEmoji=function VeryDissatisfiedEmoji(props){return renderSvgIcon({props:props,height:'48',viewBox:'0 -960 960 960',width:'48',fallback:'X(',pathProps:{d:'M480-417q-67 0-121.5 37.5T278-280h404q-25-63-80-100t-122-37Zm-183-72 50-45 45 45 31-36-45-45 45-45-31-36-45 45-50-45-31 36 45 45-45 45 31 36Zm272 0 44-45 51 45 31-36-45-45 45-45-31-36-51 45-44-45-31 36 44 45-44 45 31 36ZM480-80q-83 0-156-31.5T197-197q-54-54-85.5-127T80-480q0-83 31.5-156T197-763q54-54 127-85.5T480-880q83 0 156 31.5T763-763q54 54 85.5 127T880-480q0 83-31.5 156T763-197q-54 54-127 85.5T480-80Zm0-400Zm0 340q142 0 241-99t99-241q0-142-99-241t-241-99q-142 0-241 99t-99 241q0 142 99 241t241 99Z'}});};var VerySatisfiedEmoji=exports.VerySatisfiedEmoji=function VerySatisfiedEmoji(props){return renderSvgIcon({props:props,height:'48',viewBox:'0 -960 960 960',width:'48',fallback:':D',pathProps:{d:'M479.504-261Q537-261 585.5-287q48.5-26 78.5-72.4 6-11.6-.75-22.6-6.75-11-20.25-11H316.918Q303-393 296.5-382t-.5 22.6q30 46.4 78.5 72.4 48.5 26 105.004 26ZM347-578l27 27q7.636 8 17.818 8Q402-543 410-551q8-8 8-18t-8-18l-42-42q-8.8-9-20.9-9-12.1 0-21.1 9l-42 42q-8 7.636-8 17.818Q276-559 284-551q8 8 18 8t18-8l27-27Zm267 0 27 27q7.714 8 18 8t18-8q8-7.636 8-17.818Q685-579 677-587l-42-42q-8.8-9-20.9-9-12.1 0-21.1 9l-42 42q-8 7.714-8 18t8 18q7.636 8 17.818 8Q579-543 587-551l27-27ZM480-80q-83 0-156-31.5T197-197q-54-54-85.5-127T80-480q0-83 31.5-156T197-763q54-54 127-85.5T480-880q83 0 156 31.5T763-763q54 54 85.5 127T880-480q0 83-31.5 156T763-197q-54 54-127 85.5T480-80Zm0-400Zm0 340q142.375 0 241.188-98.812Q820-337.625 820-480t-98.812-241.188Q622.375-820 480-820t-241.188 98.812Q140-622.375 140-480t98.812 241.188Q337.625-140 480-140Z'}});};var ThumbsUpEmoji=exports.ThumbsUpEmoji=function ThumbsUpEmoji(props){return renderSvgIcon({props:props,height:'48',viewBox:'0 0 24 24',width:'48',fallback:'+',pathProps:{d:'M2 20h2c.55 0 1-.45 1-1v-9c0-.55-.45-1-1-1H2v11zm19.83-7.12c.11-.25.17-.52.17-.8V11c0-1.1-.9-2-2-2h-5.5l.92-4.65c.05-.22.02-.46-.08-.66-.23-.45-.52-.86-.88-1.22L14 2 7.59 8.41C7.21 8.79 7 9.3 7 9.83v7.84C7 18.95 8.05 20 9.34 20h8.11c.7 0 1.36-.37 1.72-.97l2.66-6.15z'}});};var ThumbsDownEmoji=exports.ThumbsDownEmoji=function ThumbsDownEmoji(props){return renderSvgIcon({props:props,height:'48',viewBox:'0 0 24 24',width:'48',fallback:'-',pathProps:{d:'M22 4h-2c-.55 0-1 .45-1 1v9c0 .55.45 1 1 1h2V4zM2.17 11.12c-.11.25-.17.52-.17.8V13c0 1.1.9 2 2 2h5.5l-.92 4.65c-.05.22-.02.46.08.66.23.45.52.86.88 1.22L10 22l6.41-6.41c.38-.38.59-.89.59-1.42V6.34C17 5.05 15.95 4 14.66 4H6.55c-.7 0-1.36.37-1.72.97l-2.66 6.15z'}});};var CheckSVG=exports.CheckSVG=function CheckSVG(props){return renderSvgIcon({props:props,height:'16',viewBox:'0 0 16 12',width:'16',fallback:'v',pathProps:{d:'M5.30769 10.6923L4.77736 11.2226C4.91801 11.3633 5.10878 11.4423 5.30769 11.4423C5.5066 11.4423 5.69737 11.3633 5.83802 11.2226L5.30769 10.6923ZM15.5303 1.53033C15.8232 1.23744 15.8232 0.762563 15.5303 0.46967C15.2374 0.176777 14.7626 0.176777 14.4697 0.46967L15.5303 1.53033ZM1.53033 5.85429C1.23744 5.56139 0.762563 5.56139 0.46967 5.85429C0.176777 6.14718 0.176777 6.62205 0.46967 6.91495L1.53033 5.85429ZM5.83802 11.2226L15.5303 1.53033L14.4697 0.46967L4.77736 10.162L5.83802 11.2226ZM0.46967 6.91495L4.77736 11.2226L5.83802 10.162L1.53033 5.85429L0.46967 6.91495Z'}});};var CancelSVG=exports.CancelSVG=function CancelSVG(props){var _a;return renderSvgIcon({props:props,height:'12',viewBox:'0 0 12 12',width:'12',fallback:'x',pathProps:{fillRule:'evenodd',clipRule:'evenodd',d:'M0.164752 0.164752C0.384422 -0.0549175 0.740578 -0.0549175 0.960248 0.164752L6 5.20451L11.0398 0.164752C11.2594 -0.0549175 11.6156 -0.0549175 11.8352 0.164752C12.0549 0.384422 12.0549 0.740578 11.8352 0.960248L6.79549 6L11.8352 11.0398C12.0549 11.2594 12.0549 11.6156 11.8352 11.8352C11.6156 12.0549 11.2594 12.0549 11.0398 11.8352L6 6.79549L0.960248 11.8352C0.740578 12.0549 0.384422 12.0549 0.164752 11.8352C-0.0549175 11.6156 -0.0549175 11.2594 0.164752 11.0398L5.20451 6L0.164752 0.960248C-0.0549175 0.740578 -0.0549175 0.384422 0.164752 0.164752Z',fill:(_a=props.fill)!==null&&_a!==void 0?_a:'black'}});};var styles=(0,_safeStyleSheet.createSafeStyleSheet)({fallbackIcon:{textAlign:'center'}});
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { PostHogSurveyProvider } from './PostHogSurveyProvider';
|
|
2
|
+
export type { PostHogSurveyProviderProps } from './PostHogSurveyProvider';
|
|
3
|
+
export { SurveyModal } from './components/SurveyModal';
|
|
4
|
+
export type { SurveyModalProps } from './components/SurveyModal';
|
|
5
|
+
export type { Survey, SurveyAppearance } from '@txlemetry/core';
|
|
6
|
+
export { Questions } from './components/Surveys';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});Object.defineProperty(exports,"PostHogSurveyProvider",{enumerable:true,get:function get(){return _PostHogSurveyProvider.PostHogSurveyProvider;}});Object.defineProperty(exports,"Questions",{enumerable:true,get:function get(){return _Surveys.Questions;}});Object.defineProperty(exports,"SurveyModal",{enumerable:true,get:function get(){return _SurveyModal.SurveyModal;}});var _PostHogSurveyProvider=require("./PostHogSurveyProvider");var _SurveyModal=require("./components/SurveyModal");var _Surveys=require("./components/Surveys");
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { StyleSheet } from 'react-native';
|
|
2
|
+
/**
|
|
3
|
+
* `StyleSheet.create` that returns the raw style map when the React Native
|
|
4
|
+
* `StyleSheet` runtime is unavailable (e.g. Jest `testEnvironment: node` without
|
|
5
|
+
* the RN preset), instead of throwing at import.
|
|
6
|
+
* See https://github.com/PostHog/posthog-js/issues/3740.
|
|
7
|
+
*/
|
|
8
|
+
export declare const createSafeStyleSheet: <T extends StyleSheet.NamedStyles<T>>(styles: T) => T;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.createSafeStyleSheet=void 0;var _reactNative=require("react-native");var createSafeStyleSheet=exports.createSafeStyleSheet=function createSafeStyleSheet(styles){try{return typeof(_reactNative.StyleSheet===null||_reactNative.StyleSheet===void 0?void 0:_reactNative.StyleSheet.create)==='function'?_reactNative.StyleSheet.create(styles):styles;}catch(_a){return styles;}};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { Survey } from '@txlemetry/core';
|
|
2
|
+
import { PostHog } from '../posthog-rn';
|
|
3
|
+
export declare function detectUserLanguage(instance: PostHog): string | null;
|
|
4
|
+
export declare function applySurveyTranslationForUser(survey: Survey, instance: PostHog): {
|
|
5
|
+
survey: Survey;
|
|
6
|
+
language: string | null;
|
|
7
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.applySurveyTranslationForUser=applySurveyTranslationForUser;exports.detectUserLanguage=detectUserLanguage;var _core=require("@txlemetry/core");var _surveys=require("@txlemetry/core/surveys");var logger=(0,_core.createLogger)('[SurveyTranslations]');function getLogger(instance){return instance.isDebug?logger:undefined;}function detectUserLanguage(instance){return(0,_surveys.detectSurveyLanguage)({overrideLanguage:instance.getSurveyDisplayLanguageOverride(),storedPersonProperties:instance.getPersistedProperty(_core.PostHogPersistedProperty.PersonProperties),locale:instance.getCommonEventProperties().$locale},getLogger(instance));}function applySurveyTranslationForUser(survey,instance){var userLanguage=detectUserLanguage(instance);var logger=getLogger(instance);if(!userLanguage){logger===null||logger===void 0?void 0:logger.info('No user language detected');return{survey:survey,language:null};}var result=(0,_surveys.applySurveyTranslation)(survey,userLanguage,logger);return{survey:result.survey,language:result.matchedKey};}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { Survey, SurveyQuestion, SurveyQuestionBranchingType, MultipleSurveyQuestion, SurveyAppearance, SurveyQuestionDescriptionContentType, SurveyMatchType } from '@txlemetry/core';
|
|
2
|
+
export type PropertyOperator = SurveyMatchType | 'gt' | 'lt';
|
|
3
|
+
export type PropertyFilters = {
|
|
4
|
+
[propertyName: string]: {
|
|
5
|
+
values: string[];
|
|
6
|
+
operator: PropertyOperator;
|
|
7
|
+
};
|
|
8
|
+
};
|
|
9
|
+
export interface SurveyEventWithFilters {
|
|
10
|
+
name: string;
|
|
11
|
+
propertyFilters?: PropertyFilters;
|
|
12
|
+
}
|
|
13
|
+
export declare const isMatchingRegex: (value: string, pattern: string) => boolean;
|
|
14
|
+
export declare const surveyValidationMap: Record<PropertyOperator, (targets: string[], values: string[]) => boolean>;
|
|
15
|
+
export declare function matchPropertyFilters(propertyFilters: PropertyFilters | undefined, eventProperties: Record<string, unknown> | undefined): boolean;
|
|
16
|
+
/**
|
|
17
|
+
* Utility function to determine if a description should be rendered based on content type
|
|
18
|
+
* Only renders text content, skips HTML content for React Native compatibility
|
|
19
|
+
* Defaults to Text content type when not specified
|
|
20
|
+
* @param description The description text
|
|
21
|
+
* @param contentType The content type (text or html), defaults to Text if not provided
|
|
22
|
+
* @returns True if the description should be rendered, false otherwise
|
|
23
|
+
*/
|
|
24
|
+
export declare function shouldRenderDescription(description?: string | null, contentType?: SurveyQuestionDescriptionContentType): boolean;
|
|
25
|
+
export declare const defaultBackgroundColor: "#eeeded";
|
|
26
|
+
export declare const defaultDescriptionOpacity = 0.8;
|
|
27
|
+
export declare const defaultRatingLabelOpacity = 0.7;
|
|
28
|
+
export type SurveyAppearanceTheme = Omit<Required<SurveyAppearance>, 'widgetSelector' | 'widgetType' | 'widgetColor' | 'widgetLabel' | 'shuffleQuestions' | 'textColor' | 'inputTextColor'> & {
|
|
29
|
+
textColor?: string;
|
|
30
|
+
inputTextColor?: string;
|
|
31
|
+
};
|
|
32
|
+
export declare const defaultSurveyAppearance: SurveyAppearanceTheme;
|
|
33
|
+
export type SurveyFlexAlign = 'flex-start' | 'center' | 'flex-end';
|
|
34
|
+
export declare function resolveSurveyAlignment(position: string | undefined): {
|
|
35
|
+
vertical: SurveyFlexAlign;
|
|
36
|
+
horizontal: SurveyFlexAlign;
|
|
37
|
+
};
|
|
38
|
+
export declare const getDisplayOrderQuestions: (survey: Survey) => SurveyQuestion[];
|
|
39
|
+
export declare const hasEvents: (survey: Survey) => boolean;
|
|
40
|
+
export declare const canActivateRepeatedly: (survey: Survey) => boolean;
|
|
41
|
+
/**
|
|
42
|
+
* Use the Fisher-yates algorithm to shuffle this array
|
|
43
|
+
* https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
|
|
44
|
+
*/
|
|
45
|
+
export declare const getDisplayOrderChoices: (question: MultipleSurveyQuestion) => string[];
|
|
46
|
+
/**
|
|
47
|
+
* Determines the next question to show based on the survey's branching logic
|
|
48
|
+
* @param survey The survey object
|
|
49
|
+
* @param currentQuestionIndex The current question index
|
|
50
|
+
* @param response The user's response to the current question
|
|
51
|
+
* @returns The index of the next question or SurveyQuestionBranchingType.End if the survey should end
|
|
52
|
+
*/
|
|
53
|
+
export declare function getNextSurveyStep(survey: Survey, currentQuestionIndex: number, response: string | string[] | number | null): number | typeof SurveyQuestionBranchingType.End;
|
|
54
|
+
export declare function getContrastingTextColor(color: string): 'black' | 'white';
|