UNPKG

ocular-widget-sdk

Version:

Ocular's widget SDK

100 lines (77 loc) 2.41 kB
declare global { interface Window { onOcularWidgetReady: () => void; ocularWidget: any; ocularWidgetIsReady: boolean; } } window.onOcularWidgetReady = () => { // @ts-ignore window.ocularWidget = window.ocularWidget || ocularWidget; window.ocularWidgetIsReady = true; }; export const initOcularWidget = ({ code }: any) => { const ocularSolutionScript = document.createElement('script'); ocularSolutionScript.setAttribute('name', 'ocular-solution-widget') ocularSolutionScript.setAttribute('data-modules', 'call'); ocularSolutionScript.setAttribute('code', code) ocularSolutionScript.type = 'text/javascript'; ocularSolutionScript.src = 'https://widget.ocularsolution.com/service/ocular/js/ocular-widget.js?v=1.1.1'; ocularSolutionScript.defer = true; document.body.appendChild(ocularSolutionScript); }; const waitForReady = async () => { return await new Promise<void>((resolve, reject) => { const timeout = 10000; const interval = 1000; let elapsedTime = 0; const checkReady = () => { if (window.ocularWidgetIsReady) { resolve(); } else if (elapsedTime >= timeout) { reject(new Error('Timeout waiting for ocularWidget to be ready')); } else { elapsedTime += interval; setTimeout(checkReady, interval); } }; checkReady(); }); }; class OcularWidget { async show(show: boolean = false) { await waitForReady(); window.ocularWidget.show(show); return 'success'; } async hide() { await waitForReady(); window.ocularWidget.hide(); return 'success'; } async toggle() { await waitForReady(); window.ocularWidget.toggle(); return 'success'; } async setCustomer(customer: any) { await waitForReady(); window.ocularWidget.setCustomer(customer); return 'success'; } async align(align: string) { // 'left' | 'right' | 'center' await waitForReady(); window.ocularWidget.align(align); return 'success'; } async setLocale(locale: string) { await waitForReady(); window.ocularWidget.setLocale(locale); return 'success'; } async getCustomer() { await waitForReady(); return window.ocularWidget.getCustomer() ?? null; } } export const ocularWidgetInstance = new OcularWidget();