UNPKG

@cliqdigital/bloomreach-sdk

Version:

React component library for integrating Bloomreach SDK with push notifications support

322 lines (321 loc) 17.1 kB
"use strict"; "use client"; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; Object.defineProperty(exports, "__esModule", { value: true }); exports.NotificationHandler = void 0; var react_1 = __importStar(require("react")); var BloomreachContext_1 = require("../context/BloomreachContext"); var NotificationHandler = /** @class */ (function (_super) { __extends(NotificationHandler, _super); function NotificationHandler(props) { var _this = _super.call(this, props) || this; _this.handleAccept = function () { return __awaiter(_this, void 0, void 0, function () { var permission, error_1, error_2; return __generator(this, function (_a) { switch (_a.label) { case 0: // First set the state to hide the banner immediately this.setState({ isShowingBanner: false, hasShownBanner: true }); _a.label = 1; case 1: _a.trys.push([1, 9, , 10]); return [4 /*yield*/, Notification.requestPermission()]; case 2: permission = _a.sent(); if (!(permission === "granted" && window.exponea)) return [3 /*break*/, 7]; // First track the consent with the correct format window.exponea.track("consent", { category: "browser_notifications", action: "accept", timestamp: new Date().toISOString(), valid_until: "unlimited", source: "public_api", identification_type: "cookie" }); if (!(window.exponea.notifications && typeof window.exponea.notifications.subscribe === 'function')) return [3 /*break*/, 6]; _a.label = 3; case 3: _a.trys.push([3, 5, , 6]); return [4 /*yield*/, window.exponea.notifications.subscribe()]; case 4: _a.sent(); console.log('Successfully subscribed to push notifications'); return [3 /*break*/, 6]; case 5: error_1 = _a.sent(); console.error('Failed to subscribe to push notifications:', error_1); return [3 /*break*/, 6]; case 6: // Track the notification consent event window.exponea.track('push_notification_consent', { status: 'granted', timestamp: new Date().toISOString() }); this.props.onConsentGranted(); return [3 /*break*/, 8]; case 7: this.props.onConsentDenied(); _a.label = 8; case 8: return [3 /*break*/, 10]; case 9: error_2 = _a.sent(); console.error("Error requesting notification permission:", error_2); this.props.onConsentDenied(); return [3 /*break*/, 10]; case 10: return [2 /*return*/]; } }); }); }; _this.handleReject = function () { // First set the state to hide the banner immediately _this.setState({ isShowingBanner: false, hasShownBanner: true }); if (window.exponea) { window.exponea.track("consent", { category: "browser_notifications", action: "reject", timestamp: new Date().toISOString(), source: "public_api", identification_type: "cookie" }); } _this.props.onConsentDenied(); }; _this.state = { isClient: false, hasShownBanner: false, isShowingBanner: false }; return _this; } NotificationHandler.prototype.componentDidMount = function () { this.setState({ isClient: true }); }; NotificationHandler.prototype.componentDidUpdate = function (prevProps, prevState) { var _a, _b, _c; return __awaiter(this, void 0, void 0, function () { var _d, isClient, hasShownBanner, isShowingBanner, _e, isInitialized, config, browserSupported, browserNotificationsSupported, hasExistingPermission, error_3, shouldShowBanner; return __generator(this, function (_f) { switch (_f.label) { case 0: _d = this.state, isClient = _d.isClient, hasShownBanner = _d.hasShownBanner, isShowingBanner = _d.isShowingBanner; _e = this.context, isInitialized = _e.isInitialized, config = _e.config, browserSupported = _e.browserSupported; // If browser doesn't support notifications, don't show banner if (!browserSupported) { return [2 /*return*/]; } browserNotificationsSupported = typeof window !== "undefined" && 'Notification' in window; // If notifications are not supported, don't show the banner if (!browserNotificationsSupported) { return [2 /*return*/]; } hasExistingPermission = browserNotificationsSupported && Notification.permission === "granted"; if (!(hasExistingPermission && !hasShownBanner)) return [3 /*break*/, 5]; this.setState({ hasShownBanner: true }); if (!(((_b = (_a = window.exponea) === null || _a === void 0 ? void 0 : _a.notifications) === null || _b === void 0 ? void 0 : _b.subscribe) && typeof window.exponea.notifications.subscribe === 'function')) return [3 /*break*/, 4]; _f.label = 1; case 1: _f.trys.push([1, 3, , 4]); // Try to subscribe return [4 /*yield*/, window.exponea.notifications.subscribe()]; case 2: // Try to subscribe _f.sent(); console.log('Successfully subscribed with existing permission'); return [3 /*break*/, 4]; case 3: error_3 = _f.sent(); console.error('Failed to subscribe with existing permission:', error_3); return [3 /*break*/, 4]; case 4: return [2 /*return*/]; case 5: shouldShowBanner = isClient && isInitialized && browserSupported && ((_c = config.notifications) === null || _c === void 0 ? void 0 : _c.showConsentBanner) && !hasShownBanner && !isShowingBanner && browserNotificationsSupported && Notification.permission === "default"; if (shouldShowBanner && !prevState.isShowingBanner) { this.setState({ isShowingBanner: true }); } return [2 /*return*/]; } }); }); }; NotificationHandler.prototype.urlBase64ToUint8Array = function (base64String) { var padding = '='.repeat((4 - base64String.length % 4) % 4); var base64 = (base64String + padding) .replace(/\-/g, '+') .replace(/_/g, '/'); var rawData = window.atob(base64); var outputArray = new Uint8Array(rawData.length); for (var i = 0; i < rawData.length; ++i) { outputArray[i] = rawData.charCodeAt(i); } return outputArray; }; NotificationHandler.prototype.renderConsentBanner = function () { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k; var config = this.context.config; var customStyles = ((_b = (_a = config.notifications) === null || _a === void 0 ? void 0 : _a.consentBannerProps) === null || _b === void 0 ? void 0 : _b.styles) || {}; var defaultStyles = { container: { position: 'fixed', bottom: 0, left: 0, right: 0, backgroundColor: 'white', padding: '16px', boxShadow: '0 -2px 10px rgba(0, 0, 0, 0.1)', zIndex: 1000, display: 'flex', flexDirection: 'column', gap: '12px' }, title: { margin: 0, fontSize: '18px' }, description: { margin: 0, fontSize: '14px', color: '#666' }, buttonContainer: { display: 'flex', gap: '8px' }, acceptButton: { padding: '8px 16px', backgroundColor: '#2563eb', color: 'white', border: 'none', borderRadius: '4px', cursor: 'pointer' }, rejectButton: { padding: '8px 16px', backgroundColor: '#e5e7eb', color: '#374151', border: 'none', borderRadius: '4px', cursor: 'pointer' } }; return (react_1.default.createElement("div", { style: __assign(__assign({}, defaultStyles.container), customStyles.container) }, react_1.default.createElement("h3", { style: __assign(__assign({}, defaultStyles.title), customStyles.title) }, ((_d = (_c = config.notifications) === null || _c === void 0 ? void 0 : _c.consentBannerProps) === null || _d === void 0 ? void 0 : _d.title) || 'Enable Push Notifications'), react_1.default.createElement("p", { style: __assign(__assign({}, defaultStyles.description), customStyles.description) }, ((_f = (_e = config.notifications) === null || _e === void 0 ? void 0 : _e.consentBannerProps) === null || _f === void 0 ? void 0 : _f.description) || 'Get updates on new content, offers, and important announcements.'), react_1.default.createElement("div", { style: __assign(__assign({}, defaultStyles.buttonContainer), customStyles.buttonContainer) }, react_1.default.createElement("button", { onClick: this.handleAccept, style: __assign(__assign({}, defaultStyles.acceptButton), customStyles.acceptButton) }, ((_h = (_g = config.notifications) === null || _g === void 0 ? void 0 : _g.consentBannerProps) === null || _h === void 0 ? void 0 : _h.acceptLabel) || 'Allow'), react_1.default.createElement("button", { onClick: this.handleReject, style: __assign(__assign({}, defaultStyles.rejectButton), customStyles.rejectButton) }, ((_k = (_j = config.notifications) === null || _j === void 0 ? void 0 : _j.consentBannerProps) === null || _k === void 0 ? void 0 : _k.rejectLabel) || 'Not Now')))); }; NotificationHandler.prototype.render = function () { var _a = this.state, isClient = _a.isClient, hasShownBanner = _a.hasShownBanner, isShowingBanner = _a.isShowingBanner; var _b = this.context, isInitialized = _b.isInitialized, config = _b.config, browserSupported = _b.browserSupported; if (!isClient || !isInitialized || !browserSupported) { return null; } if (isShowingBanner) { return this.renderConsentBanner(); } return null; }; NotificationHandler.contextType = BloomreachContext_1.BloomreachContext; return NotificationHandler; }(react_1.Component)); exports.NotificationHandler = NotificationHandler;