@tinydialog/sdk-js 0.0.1-rc.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.
@@ -0,0 +1 @@
1
+ "use client";"use strict";(()=>{var t=(()=>{let t=0;return()=>(t+=1,`u${`0000${(Math.random()*36**4|0).toString(36)}`.slice(-4)}${t}`)})();function e(t){const e=[];for(let n=0,o=t.length;n<o;n++)e.push(t[n]);return e}function n(t,e){const n=(t.ownerDocument.defaultView||window).getComputedStyle(t).getPropertyValue(e);return n?parseFloat(n.replace("px","")):0}function o(t,e={}){return{width:e.width||function(t){const e=n(t,"border-left-width"),o=n(t,"border-right-width");return t.clientWidth+e+o}(t),height:e.height||function(t){const e=n(t,"border-top-width"),o=n(t,"border-bottom-width");return t.clientHeight+e+o}(t)}}var r=16384;function i(t){return new Promise(((e,n)=>{const o=new Image;o.onload=()=>{o.decode().then((()=>{requestAnimationFrame((()=>e(o)))}))},o.onerror=n,o.crossOrigin="anonymous",o.decoding="async",o.src=t}))}var a=(t,e)=>{if(t instanceof e)return!0;const n=Object.getPrototypeOf(t);return null!==n&&(n.constructor.name===e.name||a(n,e))};function s(n,o,r){const i=window.getComputedStyle(n,r),a=i.getPropertyValue("content");if(""===a||"none"===a)return;const s=t();try{o.className=`${o.className} ${s}`}catch(t){return}const l=document.createElement("style");l.appendChild(function(t,n,o){const r=`.${t}:${n}`,i=o.cssText?function(t){const e=t.getPropertyValue("content");return`${t.cssText} content: '${e.replace(/'|"/g,"")}';`}(o):function(t){return e(t).map((e=>`${e}: ${t.getPropertyValue(e)}${t.getPropertyPriority(e)?" !important":""};`)).join(" ")}(o);return document.createTextNode(`${r}{${i}}`)}(s,r,i)),o.appendChild(l)}var l="application/font-woff",c="image/jpeg",d={woff:l,woff2:l,ttf:"application/font-truetype",eot:"application/vnd.ms-fontobject",png:"image/png",jpg:c,jpeg:c,gif:"image/gif",tiff:"image/tiff",svg:"image/svg+xml",webp:"image/webp"};function u(t){const e=function(t){const e=/\.([^./]*?)$/g.exec(t);return e?e[1]:""}(t).toLowerCase();return d[e]||""}function h(t){return-1!==t.search(/^(data:)/)}function g(t,e){return`data:${e};base64,${t}`}async function f(t,e,n){const o=await fetch(t,e);if(404===o.status)throw new Error(`Resource "${o.url}" not found`);const r=await o.blob();return new Promise(((t,e)=>{const i=new FileReader;i.onerror=e,i.onloadend=()=>{try{t(n({res:o,result:i.result}))}catch(t){e(t)}},i.readAsDataURL(r)}))}var y={};async function m(t,e,n){const o=function(t,e,n){let o=t.replace(/\?.*/,"");return n&&(o=t),/ttf|otf|eot|woff2?/i.test(o)&&(o=o.replace(/.*\//,"")),e?`[${e}]${o}`:o}(t,e,n.includeQueryParams);if(null!=y[o])return y[o];let r;n.cacheBust&&(t+=(/\?/.test(t)?"&":"?")+(new Date).getTime());try{const o=await f(t,n.fetchRequestInit,(({res:t,result:n})=>(e||(e=t.headers.get("Content-Type")||""),function(t){return t.split(/,/)[1]}(n))));r=g(o,e)}catch(e){r=n.imagePlaceholder||"";let o=`Failed to fetch resource: ${t}`;e&&(o="string"==typeof e?e:e.message),o&&console.warn(o)}return y[o]=r,r}var w=t=>null!=t.tagName&&"SVG"===t.tagName.toUpperCase();async function p(t,n,o){return o||!n.filter||n.filter(t)?Promise.resolve(t).then((t=>async function(t,e){return a(t,HTMLCanvasElement)?async function(t){const e=t.toDataURL();return"data:,"===e?t.cloneNode(!1):i(e)}(t):a(t,HTMLVideoElement)?async function(t,e){if(t.currentSrc){const e=document.createElement("canvas"),n=e.getContext("2d");return e.width=t.clientWidth,e.height=t.clientHeight,null==n||n.drawImage(t,0,0,e.width,e.height),i(e.toDataURL())}const n=t.poster,o=u(n);return i(await m(n,o,e))}(t,e):a(t,HTMLIFrameElement)?async function(t){var e;try{if(null===(e=null==t?void 0:t.contentDocument)||void 0===e?void 0:e.body)return await p(t.contentDocument.body,{},!0)}catch(t){}return t.cloneNode(!1)}(t):t.cloneNode(w(t))}(t,n))).then((o=>async function(t,n,o){var r,i;if(w(n))return n;let s=[];return s=(t=>null!=t.tagName&&"SLOT"===t.tagName.toUpperCase())(t)&&t.assignedNodes?e(t.assignedNodes()):a(t,HTMLIFrameElement)&&(null===(r=t.contentDocument)||void 0===r?void 0:r.body)?e(t.contentDocument.body.childNodes):e((null!==(i=t.shadowRoot)&&void 0!==i?i:t).childNodes),0===s.length||a(t,HTMLVideoElement)||await s.reduce(((t,e)=>t.then((()=>p(e,o))).then((t=>{t&&n.appendChild(t)}))),Promise.resolve()),n}(t,o,n))).then((n=>function(t,n){return a(n,Element)&&(function(t,n){const o=n.style;if(!o)return;const r=window.getComputedStyle(t);r.cssText?(o.cssText=r.cssText,o.transformOrigin=r.transformOrigin):e(r).forEach((e=>{let i=r.getPropertyValue(e);if("font-size"===e&&i.endsWith("px")){const t=Math.floor(parseFloat(i.substring(0,i.length-2)))-.1;i=`${t}px`}a(t,HTMLIFrameElement)&&"display"===e&&"inline"===i&&(i="block"),"d"===e&&n.getAttribute("d")&&(i=`path(${n.getAttribute("d")})`),o.setProperty(e,i,r.getPropertyPriority(e))}))}(t,n),function(t,e){s(t,e,":before"),s(t,e,":after")}(t,n),function(t,e){a(t,HTMLTextAreaElement)&&(e.innerHTML=t.value),a(t,HTMLInputElement)&&e.setAttribute("value",t.value)}(t,n),function(t,e){if(a(t,HTMLSelectElement)){const n=e,o=Array.from(n.children).find((e=>t.value===e.getAttribute("value")));o&&o.setAttribute("selected","")}}(t,n)),n}(t,n))).then((t=>async function(t,e){const n=t.querySelectorAll?t.querySelectorAll("use"):[];if(0===n.length)return t;const o={};for(let r=0;r<n.length;r++){const i=n[r].getAttribute("xlink:href");if(i){const n=t.querySelector(i),r=document.querySelector(i);n||!r||o[i]||(o[i]=await p(r,e,!0))}}const r=Object.values(o);if(r.length){const e="http://www.w3.org/1999/xhtml",n=document.createElementNS(e,"svg");n.setAttribute("xmlns",e),n.style.position="absolute",n.style.width="0",n.style.height="0",n.style.overflow="hidden",n.style.display="none";const o=document.createElementNS(e,"defs");n.appendChild(o);for(let t=0;t<r.length;t++)o.appendChild(r[t]);t.appendChild(n)}return t}(t,n))):null}var b=/url\((['"]?)([^'"]+?)\1\)/g,v=/url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g,E=/src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;function S(t){return-1!==t.search(b)}async function x(t,e,n){if(!S(t))return t;const o=function(t,{preferredFontFormat:e}){return e?t.replace(E,(t=>{for(;;){const[n,,o]=v.exec(t)||[];if(!o)return"";if(o===e)return`src: ${n};`}})):t}(t,n),r=function(t){const e=[];return t.replace(b,((t,n,o)=>(e.push(o),t))),e.filter((t=>!h(t)))}(o);return r.reduce(((t,o)=>t.then((t=>async function(t,e,n,o){try{const r=n?function(t,e){if(t.match(/^[a-z]+:\/\//i))return t;if(t.match(/^\/\//))return window.location.protocol+t;if(t.match(/^[a-z]+:/i))return t;const n=document.implementation.createHTMLDocument(),o=n.createElement("base"),r=n.createElement("a");return n.head.appendChild(o),n.body.appendChild(r),e&&(o.href=e),r.href=t,r.href}(e,n):e,i=u(e);let a;return a=await m(r,i,o),t.replace(function(t){const e=t.replace(/([.*+?^${}()|\[\]\/\\])/g,"\\$1");return new RegExp(`(url\\(['"]?)(${e})(['"]?\\))`,"g")}(e),`$1${a}$3`)}catch(t){}return t}(t,o,e,n)))),Promise.resolve(o))}async function T(t,e,n){var o;const r=null===(o=e.style)||void 0===o?void 0:o.getPropertyValue(t);if(r){const o=await x(r,null,n);return e.style.setProperty(t,o,e.style.getPropertyPriority(t)),!0}return!1}async function $(t,n){a(t,Element)&&(await async function(t,e){await T("background",t,e)||await T("background-image",t,e),await T("mask",t,e)||await T("mask-image",t,e)}(t,n),await async function(t,e){const n=a(t,HTMLImageElement);if((!n||h(t.src))&&(!a(t,SVGImageElement)||h(t.href.baseVal)))return;const o=n?t.src:t.href.baseVal,r=await m(o,u(o),e);await new Promise(((o,i)=>{t.onload=o,t.onerror=e.onImageErrorHandler?(...t)=>{try{o(e.onImageErrorHandler(...t))}catch(t){i(t)}}:i;const a=t;a.decode&&(a.decode=o),"lazy"===a.loading&&(a.loading="eager"),n?(t.srcset="",t.src=r):t.href.baseVal=r}))}(t,n),await async function(t,n){const o=e(t.childNodes).map((t=>$(t,n)));await Promise.all(o).then((()=>t))}(t,n))}var C={};async function P(t){let e=C[t];if(null!=e)return e;const n=await fetch(t);return e={url:t,cssText:await n.text()},C[t]=e,e}async function L(t,e){let n=t.cssText;const o=/url\(["']?([^"')]+)["']?\)/g,r=(n.match(/url\([^)]+\)/g)||[]).map((async r=>{let i=r.replace(o,"$1");return i.startsWith("https://")||(i=new URL(i,t.url).href),f(i,e.fetchRequestInit,(({result:t})=>(n=n.replace(r,`url(${t})`),[r,t])))}));return Promise.all(r).then((()=>n))}function k(t){if(null==t)return[];const e=[];let n=t.replace(/(\/\*[\s\S]*?\*\/)/gi,"");const o=new RegExp("((@.*?keyframes [\\s\\S]*?){([\\s\\S]*?}\\s*?)})","gi");for(;;){const t=o.exec(n);if(null===t)break;e.push(t[0])}n=n.replace(o,"");const r=/@import[\s\S]*?url\([^)]*\)[\s\S]*?;/gi,i=new RegExp("((\\s*?(?:\\/\\*[\\s\\S]*?\\*\\/)?\\s*?@media[\\s\\S]*?){([\\s\\S]*?)}\\s*?})|(([\\s\\S]*?){([\\s\\S]*?)})","gi");for(;;){let t=r.exec(n);if(null===t){if(t=i.exec(n),null===t)break;r.lastIndex=i.lastIndex}else i.lastIndex=r.lastIndex;e.push(t[0])}return e}function R(t){return t.trim().replace(/["']/g,"")}async function H(t,n={}){const{width:r,height:i}=o(t,n),a=await p(t,n,!0);return await async function(t,n){const o=null!=n.fontEmbedCSS?n.fontEmbedCSS:n.skipFonts?null:await async function(t,n){const o=await async function(t,n){if(null==t.ownerDocument)throw new Error("Provided element is not within a Document");const o=e(t.ownerDocument.styleSheets),r=await async function(t,n){const o=[],r=[];return t.forEach((o=>{if("cssRules"in o)try{e(o.cssRules||[]).forEach(((t,e)=>{if(t.type===CSSRule.IMPORT_RULE){let i=e+1;const a=P(t.href).then((t=>L(t,n))).then((t=>k(t).forEach((t=>{try{o.insertRule(t,t.startsWith("@import")?i+=1:o.cssRules.length)}catch(e){console.error("Error inserting rule from remote css",{rule:t,error:e})}})))).catch((t=>{console.error("Error loading remote css",t.toString())}));r.push(a)}}))}catch(e){const i=t.find((t=>null==t.href))||document.styleSheets[0];null!=o.href&&r.push(P(o.href).then((t=>L(t,n))).then((t=>k(t).forEach((t=>{i.insertRule(t,o.cssRules.length)})))).catch((t=>{console.error("Error loading remote stylesheet",t)}))),console.error("Error inlining remote css file",e)}})),Promise.all(r).then((()=>(t.forEach((t=>{if("cssRules"in t)try{e(t.cssRules||[]).forEach((t=>{o.push(t)}))}catch(e){console.error(`Error while reading CSS rules from ${t.href}`,e)}})),o)))}(o,n);return function(t){return t.filter((t=>t.type===CSSRule.FONT_FACE_RULE)).filter((t=>S(t.style.getPropertyValue("src"))))}(r)}(t,n),r=function(t){const e=new Set;return function t(n){(n.style.fontFamily||getComputedStyle(n).fontFamily).split(",").forEach((t=>{e.add(R(t))})),Array.from(n.children).forEach((e=>{e instanceof HTMLElement&&t(e)}))}(t),e}(t);return(await Promise.all(o.filter((t=>r.has(R(t.style.fontFamily)))).map((t=>{const e=t.parentStyleSheet?t.parentStyleSheet.href:null;return x(t.cssText,e,n)})))).join("\n")}(t,n);if(o){const e=document.createElement("style"),n=document.createTextNode(o);e.appendChild(n),t.firstChild?t.insertBefore(e,t.firstChild):t.appendChild(e)}}(a,n),await $(a,n),function(t,e){const{style:n}=t;e.backgroundColor&&(n.backgroundColor=e.backgroundColor),e.width&&(n.width=`${e.width}px`),e.height&&(n.height=`${e.height}px`);const o=e.style;null!=o&&Object.keys(o).forEach((t=>{n[t]=o[t]}))}(a,n),await async function(t,e,n){const o="http://www.w3.org/2000/svg",r=document.createElementNS(o,"svg"),i=document.createElementNS(o,"foreignObject");return r.setAttribute("width",`${e}`),r.setAttribute("height",`${n}`),r.setAttribute("viewBox",`0 0 ${e} ${n}`),i.setAttribute("width","100%"),i.setAttribute("height","100%"),i.setAttribute("x","0"),i.setAttribute("y","0"),i.setAttribute("externalResourcesRequired","true"),r.appendChild(i),i.appendChild(t),async function(t){return Promise.resolve().then((()=>(new XMLSerializer).serializeToString(t))).then(encodeURIComponent).then((t=>`data:image/svg+xml;charset=utf-8,${t}`))}(r)}(a,r,i)}var M={BOTTOM_RIGHT:{right:"0",bottom:"0"},BOTTOM_LEFT:{left:"0",bottom:"0"},TOP_RIGHT:{right:"0",top:"0"},TOP_LEFT:{left:"0",top:"0"}};function I(t,e,n){if(!t||t.length<5)throw new Error(`invalid surveyId! Please copy the correct surveyId from the tinyDialog dashboard. (surveyId=${t})`);if((n??document).querySelector(`#tinydialog-widget__${t}_auto iframe`))return void console.debug(`skipping survey-load for ${t}, already loaded`);let a=n;if(null==a){a=document.createElement("div"),a.className="tinydialog-floating-widget",a.id=`tinydialog-widget__${t}_auto`,a.dataset.tinydialogWidget=t,a.style.position="fixed";for(const[t,n]of Object.entries(M[e?.side??"BOTTOM_RIGHT"]))a.style.setProperty(t,n);a.style.overflow="hidden",a.style.visibility="hidden",a.style.transitionProperty="opacity, transform, height",a.style.transitionDuration="200ms",a.style.transform="scale(0.75)",a.style.opacity="0"}let s=e?.user?.trim();0===s?.length&&(s=void 0);const l=a.querySelector("iframe")??document.createElement("iframe");l.src=`https://app.tinydialog.com/widget/v1/${t}?parent=${encodeURIComponent(window.location.href)}${s?"&user="+s:""}`,l.style.transitionProperty="height",l.style.transitionDuration="150ms",l.style.height="100%",l.style.minWidth="350px",l.ariaLabel="tinyDialog survey widget";const c=async e=>{if(e.data.targetWidget===t)if("tinydialog--updateHeight"===e.data.event&&e.data.data)a.style.height=e.data.data+"px";else if("tinydialog--close"===e.data.event)F(e.data.targetWidget);else if("tinydialog--requestScreenshot"===e.data.event)try{const t=await async function(t,e={}){const{width:n,height:a}=o(t,e),s=await H(t,e),l=await i(s),c=document.createElement("canvas"),d=c.getContext("2d"),u=e.pixelRatio||function(){let t,e;try{e=process}catch(t){}const n=e&&e.env?e.env.devicePixelRatio:null;return n&&(t=parseInt(n,10),Number.isNaN(t)&&(t=1)),t||window.devicePixelRatio||1}(),h=e.canvasWidth||n,g=e.canvasHeight||a;return c.width=h*u,c.height=g*u,e.skipAutoScale||function(t){(t.width>r||t.height>r)&&(t.width>r&&t.height>r?t.width>t.height?(t.height*=r/t.width,t.width=r):(t.width*=r/t.height,t.height=r):t.width>r?(t.height*=r/t.width,t.width=r):(t.width*=r/t.height,t.height=r))}(c),c.style.width=`${h}`,c.style.height=`${g}`,e.backgroundColor&&(d.fillStyle=e.backgroundColor,d.fillRect(0,0,c.width,c.height)),d.drawImage(l,0,0,c.width,c.height),c}(document.body,{skipAutoScale:!0,includeQueryParams:!0,width:window.innerWidth,height:window.innerHeight,canvasWidth:window.innerWidth*Math.min(1,1080/window.innerWidth),canvasHeight:window.innerHeight*Math.min(1,1080/window.innerWidth),backgroundColor:document.body.style.backgroundColor.length>0?window.getComputedStyle(document.body,null).getPropertyValue("background-color"):"rgb(255, 255, 255, 1)",style:{transform:`translate(-${window.scrollX}px, -${window.scrollY}px)`,width:`${window.innerWidth}px`,height:`${window.innerHeight}px`}}),e=await new Promise(((e,n)=>{try{t.toBlob((t=>e(t)),"image/jpeg",.35)}catch(t){n(t)}}));if(!e)return void console.error("could not take screenshot, img null");if(!l.contentWindow)return void console.error("no iframe.contentWindow");l.contentWindow.postMessage({event:"tinydialog--screenshot",data:e},"*")}catch(t){console.error("failed taking screenshot of webpage",t)}};window.removeEventListener("message",c),window.addEventListener("message",c),a.appendChild(l),n||document.body.append(a)}function A(t,e,n=0){document.querySelectorAll('[data-tinydialog-widget-visible="true"]').forEach((t=>{const e=t.dataset.tinydialogWidget;e?F(e):console.warn("visibleWidget to close had no surveyId!",t)}));const o=document.querySelector(`[data-tinydialog-widget='${t}']`);if(o)if(o instanceof HTMLElement)if(!o.style.height&&n<=25)setTimeout((()=>A(t,e,n+1)),30+75*n);else{for(const[t,n]of Object.entries(M[e?.side??"BOTTOM_RIGHT"]))o.style.setProperty(t,n);o.dataset.tinydialogWidgetVisible="true",o.style.visibility="visible",o.style.transform="scale(1.0)",o.style.opacity="1"}else console.warn("tried opening widget, but widgetContainer was not a HTMLElement");else console.warn(`tried opening widget with id ${t} which was not found`)}function F(t){const e=document.querySelector(`[data-tinydialog-widget='${t}']`);e?e instanceof HTMLElement?(e.style.transform="scale(0.75)",e.style.opacity="0",e.style.visibility="hidden",e.removeAttribute("data-tinydialog-widget-visible")):console.warn("tried opening widget, but widgetContainer was not a HTMLElement"):console.debug(`tried closing widget with id ${t} which does not exist on page`)}function O(t){t.currentTarget instanceof HTMLElement&&A(t.currentTarget.dataset.tinydialogOpenwidget,{side:t.currentTarget.dataset.tinydialogWidgetSide?.toUpperCase()})}var N=document.currentScript;onload=()=>{N||(N=document.currentScript)},N?.dataset.tinydialogFloatingButton&&function(t){const e=t.tinydialogFloatingButton;if(!e||e.length<10)return void console.warn('invalid surveyId configured in "data-tinydialog-floating-button"');if(document.querySelector("#tinydialog-floating-button__auto"))return void console.debug("prevented duplicate autoCreateFloatingButton execution, button alreadx exists");const n=document.createElement("button");n.id="tinydialog-floating-button__auto",n.style.position="fixed",n.style.right="20px",n.style.bottom="20px",n.style.width="48px",n.style.height="48px",n.style.background=t.tinydialogFloatingButtonBackground??"black",n.style.color=t.tinydialogFloatingButtonForeground??"white",n.style.borderRadius="100%",n.style.padding="8px",n.style.cursor="pointer",n.style.transitionDuration="300ms",n.style.transitionProperty="all",n.dataset.tinydialogOpenwidget=e,n.addEventListener("mouseenter",(()=>n.style.background=t.tinydialogFloatingButtonBackgroundHover??"#E2187D")),n.addEventListener("mouseleave",(()=>n.style.background=t.tinydialogFloatingButtonBackground??"black"));const o=document.createElement("svg");n.append(o),o.outerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>',document.body.append(n)}(N.dataset),document.querySelectorAll("[data-tinydialog-openwidget]").forEach((t=>{t instanceof HTMLElement&&(I(t.dataset.tinydialogOpenwidget,{side:t.dataset.tinydialogWidgetSide?.toUpperCase(),user:t.dataset.tinydialogUser??N?.dataset.tinydialogUser}),t.removeEventListener("click",O),t.addEventListener("click",O))})),document.querySelectorAll("[data-tinydialog-widgetcontainer]").forEach((t=>{t instanceof HTMLElement&&I(t.dataset.tinydialogWidgetcontainer,{user:t.dataset.tinydialogUser??N?.dataset.tinydialogUser},t)}))})();
package/dist/index.cjs ADDED
@@ -0,0 +1 @@
1
+ "use client";"use strict";var t,e=Object.defineProperty,i=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,a={};((t,i)=>{for(var o in i)e(t,o,{get:i[o],enumerable:!0})})(a,{bindSurveysWithDataAttributes:()=>u,closeWidget:()=>c,loadSurvey:()=>l,showWidget:()=>s}),module.exports=(t=a,((t,a,r,d)=>{if(a&&"object"==typeof a||"function"==typeof a)for(let r of o(a))n.call(t,r)||void 0===r||e(t,r,{get:()=>a[r],enumerable:!(d=i(a,r))||d.enumerable});return t})(e({},"__esModule",{value:!0}),t));var r=require("html-to-image"),d={BOTTOM_RIGHT:{right:"0",bottom:"0"},BOTTOM_LEFT:{left:"0",bottom:"0"},TOP_RIGHT:{right:"0",top:"0"},TOP_LEFT:{left:"0",top:"0"}};function l(t,e,i){if(!t||t.length<5)throw new Error(`invalid surveyId! Please copy the correct surveyId from the tinyDialog dashboard. (surveyId=${t})`);if((i??document).querySelector(`#tinydialog-widget__${t}_auto iframe`))return void console.debug(`skipping survey-load for ${t}, already loaded`);let o=i;if(null==o){o=document.createElement("div"),o.className="tinydialog-floating-widget",o.id=`tinydialog-widget__${t}_auto`,o.dataset.tinydialogWidget=t,o.style.position="fixed";for(const[t,i]of Object.entries(d[e?.side??"BOTTOM_RIGHT"]))o.style.setProperty(t,i);o.style.overflow="hidden",o.style.visibility="hidden",o.style.transitionProperty="opacity, transform, height",o.style.transitionDuration="200ms",o.style.transform="scale(0.75)",o.style.opacity="0"}let n=e?.user?.trim();0===n?.length&&(n=void 0);const a=o.querySelector("iframe")??document.createElement("iframe");a.src=`https://app.tinydialog.com/widget/v1/${t}?parent=${encodeURIComponent(window.location.href)}${n?"&user="+n:""}`,a.style.transitionProperty="height",a.style.transitionDuration="150ms",a.style.height="100%",a.style.minWidth="350px",a.ariaLabel="tinyDialog survey widget";const l=async e=>{if(e.data.targetWidget===t)if("tinydialog--updateHeight"===e.data.event&&e.data.data)o.style.height=e.data.data+"px";else if("tinydialog--close"===e.data.event)c(e.data.targetWidget);else if("tinydialog--requestScreenshot"===e.data.event)try{const t=await(0,r.toCanvas)(document.body,{skipAutoScale:!0,includeQueryParams:!0,width:window.innerWidth,height:window.innerHeight,canvasWidth:window.innerWidth*Math.min(1,1080/window.innerWidth),canvasHeight:window.innerHeight*Math.min(1,1080/window.innerWidth),backgroundColor:document.body.style.backgroundColor.length>0?window.getComputedStyle(document.body,null).getPropertyValue("background-color"):"rgb(255, 255, 255, 1)",style:{transform:`translate(-${window.scrollX}px, -${window.scrollY}px)`,width:`${window.innerWidth}px`,height:`${window.innerHeight}px`}}),e=await new Promise(((e,i)=>{try{t.toBlob((t=>e(t)),"image/jpeg",.35)}catch(t){i(t)}}));if(!e)return void console.error("could not take screenshot, img null");if(!a.contentWindow)return void console.error("no iframe.contentWindow");a.contentWindow.postMessage({event:"tinydialog--screenshot",data:e},"*")}catch(t){console.error("failed taking screenshot of webpage",t)}};window.removeEventListener("message",l),window.addEventListener("message",l),o.appendChild(a),i||document.body.append(o)}function s(t,e,i=0){document.querySelectorAll('[data-tinydialog-widget-visible="true"]').forEach((t=>{const e=t.dataset.tinydialogWidget;e?c(e):console.warn("visibleWidget to close had no surveyId!",t)}));const o=document.querySelector(`[data-tinydialog-widget='${t}']`);if(o)if(o instanceof HTMLElement)if(!o.style.height&&i<=25)setTimeout((()=>s(t,e,i+1)),30+75*i);else{for(const[t,i]of Object.entries(d[e?.side??"BOTTOM_RIGHT"]))o.style.setProperty(t,i);o.dataset.tinydialogWidgetVisible="true",o.style.visibility="visible",o.style.transform="scale(1.0)",o.style.opacity="1"}else console.warn("tried opening widget, but widgetContainer was not a HTMLElement");else console.warn(`tried opening widget with id ${t} which was not found`)}function c(t){const e=document.querySelector(`[data-tinydialog-widget='${t}']`);e?e instanceof HTMLElement?(e.style.transform="scale(0.75)",e.style.opacity="0",e.style.visibility="hidden",e.removeAttribute("data-tinydialog-widget-visible")):console.warn("tried opening widget, but widgetContainer was not a HTMLElement"):console.debug(`tried closing widget with id ${t} which does not exist on page`)}function g(t){t.currentTarget instanceof HTMLElement&&s(t.currentTarget.dataset.tinydialogOpenwidget,{side:t.currentTarget.dataset.tinydialogWidgetSide?.toUpperCase()})}function u(){y?.dataset.tinydialogFloatingButton&&function(t){const e=t.tinydialogFloatingButton;if(!e||e.length<10)return void console.warn('invalid surveyId configured in "data-tinydialog-floating-button"');if(document.querySelector("#tinydialog-floating-button__auto"))return void console.debug("prevented duplicate autoCreateFloatingButton execution, button alreadx exists");const i=document.createElement("button");i.id="tinydialog-floating-button__auto",i.style.position="fixed",i.style.right="20px",i.style.bottom="20px",i.style.width="48px",i.style.height="48px",i.style.background=t.tinydialogFloatingButtonBackground??"black",i.style.color=t.tinydialogFloatingButtonForeground??"white",i.style.borderRadius="100%",i.style.padding="8px",i.style.cursor="pointer",i.style.transitionDuration="300ms",i.style.transitionProperty="all",i.dataset.tinydialogOpenwidget=e,i.addEventListener("mouseenter",(()=>i.style.background=t.tinydialogFloatingButtonBackgroundHover??"#E2187D")),i.addEventListener("mouseleave",(()=>i.style.background=t.tinydialogFloatingButtonBackground??"black"));const o=document.createElement("svg");i.append(o),o.outerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>',document.body.append(i)}(y.dataset),document.querySelectorAll("[data-tinydialog-openwidget]").forEach((t=>{t instanceof HTMLElement&&(l(t.dataset.tinydialogOpenwidget,{side:t.dataset.tinydialogWidgetSide?.toUpperCase(),user:t.dataset.tinydialogUser??y?.dataset.tinydialogUser}),t.removeEventListener("click",g),t.addEventListener("click",g))})),document.querySelectorAll("[data-tinydialog-widgetcontainer]").forEach((t=>{t instanceof HTMLElement&&l(t.dataset.tinydialogWidgetcontainer,{user:t.dataset.tinydialogUser??y?.dataset.tinydialogUser},t)}))}var y=document.currentScript;onload=()=>{y||(y=document.currentScript)},u();
@@ -0,0 +1,10 @@
1
+ interface FloatingWidgetSettings {
2
+ side?: 'BOTTOM_RIGHT' | 'BOTTOM_LEFT' | 'TOP_RIGHT' | 'TOP_LEFT';
3
+ user?: string;
4
+ }
5
+ declare function loadSurvey(surveyId: string, additionalSettings?: FloatingWidgetSettings, targetContainer?: HTMLElement): void;
6
+ declare function showWidget(surveyId: string, additionalSettings?: FloatingWidgetSettings, retryCounter?: number): void;
7
+ declare function closeWidget(surveyId: string): void;
8
+ declare function bindSurveysWithDataAttributes(): void;
9
+
10
+ export { bindSurveysWithDataAttributes, closeWidget, loadSurvey, showWidget };
@@ -0,0 +1,10 @@
1
+ interface FloatingWidgetSettings {
2
+ side?: 'BOTTOM_RIGHT' | 'BOTTOM_LEFT' | 'TOP_RIGHT' | 'TOP_LEFT';
3
+ user?: string;
4
+ }
5
+ declare function loadSurvey(surveyId: string, additionalSettings?: FloatingWidgetSettings, targetContainer?: HTMLElement): void;
6
+ declare function showWidget(surveyId: string, additionalSettings?: FloatingWidgetSettings, retryCounter?: number): void;
7
+ declare function closeWidget(surveyId: string): void;
8
+ declare function bindSurveysWithDataAttributes(): void;
9
+
10
+ export { bindSurveysWithDataAttributes, closeWidget, loadSurvey, showWidget };
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ "use client";import{toCanvas as t}from"html-to-image";var e={BOTTOM_RIGHT:{right:"0",bottom:"0"},BOTTOM_LEFT:{left:"0",bottom:"0"},TOP_RIGHT:{right:"0",top:"0"},TOP_LEFT:{left:"0",top:"0"}};function i(i,n,a){if(!i||i.length<5)throw new Error(`invalid surveyId! Please copy the correct surveyId from the tinyDialog dashboard. (surveyId=${i})`);if((a??document).querySelector(`#tinydialog-widget__${i}_auto iframe`))return void console.debug(`skipping survey-load for ${i}, already loaded`);let d=a;if(null==d){d=document.createElement("div"),d.className="tinydialog-floating-widget",d.id=`tinydialog-widget__${i}_auto`,d.dataset.tinydialogWidget=i,d.style.position="fixed";for(const[t,i]of Object.entries(e[n?.side??"BOTTOM_RIGHT"]))d.style.setProperty(t,i);d.style.overflow="hidden",d.style.visibility="hidden",d.style.transitionProperty="opacity, transform, height",d.style.transitionDuration="200ms",d.style.transform="scale(0.75)",d.style.opacity="0"}let r=n?.user?.trim();0===r?.length&&(r=void 0);const l=d.querySelector("iframe")??document.createElement("iframe");l.src=`https://app.tinydialog.com/widget/v1/${i}?parent=${encodeURIComponent(window.location.href)}${r?"&user="+r:""}`,l.style.transitionProperty="height",l.style.transitionDuration="150ms",l.style.height="100%",l.style.minWidth="350px",l.ariaLabel="tinyDialog survey widget";const s=async e=>{if(e.data.targetWidget===i)if("tinydialog--updateHeight"===e.data.event&&e.data.data)d.style.height=e.data.data+"px";else if("tinydialog--close"===e.data.event)o(e.data.targetWidget);else if("tinydialog--requestScreenshot"===e.data.event)try{const e=await t(document.body,{skipAutoScale:!0,includeQueryParams:!0,width:window.innerWidth,height:window.innerHeight,canvasWidth:window.innerWidth*Math.min(1,1080/window.innerWidth),canvasHeight:window.innerHeight*Math.min(1,1080/window.innerWidth),backgroundColor:document.body.style.backgroundColor.length>0?window.getComputedStyle(document.body,null).getPropertyValue("background-color"):"rgb(255, 255, 255, 1)",style:{transform:`translate(-${window.scrollX}px, -${window.scrollY}px)`,width:`${window.innerWidth}px`,height:`${window.innerHeight}px`}}),i=await new Promise(((t,i)=>{try{e.toBlob((e=>t(e)),"image/jpeg",.35)}catch(t){i(t)}}));if(!i)return void console.error("could not take screenshot, img null");if(!l.contentWindow)return void console.error("no iframe.contentWindow");l.contentWindow.postMessage({event:"tinydialog--screenshot",data:i},"*")}catch(t){console.error("failed taking screenshot of webpage",t)}};window.removeEventListener("message",s),window.addEventListener("message",s),d.appendChild(l),a||document.body.append(d)}function n(t,i,a=0){document.querySelectorAll('[data-tinydialog-widget-visible="true"]').forEach((t=>{const e=t.dataset.tinydialogWidget;e?o(e):console.warn("visibleWidget to close had no surveyId!",t)}));const d=document.querySelector(`[data-tinydialog-widget='${t}']`);if(d)if(d instanceof HTMLElement)if(!d.style.height&&a<=25)setTimeout((()=>n(t,i,a+1)),30+75*a);else{for(const[t,n]of Object.entries(e[i?.side??"BOTTOM_RIGHT"]))d.style.setProperty(t,n);d.dataset.tinydialogWidgetVisible="true",d.style.visibility="visible",d.style.transform="scale(1.0)",d.style.opacity="1"}else console.warn("tried opening widget, but widgetContainer was not a HTMLElement");else console.warn(`tried opening widget with id ${t} which was not found`)}function o(t){const e=document.querySelector(`[data-tinydialog-widget='${t}']`);e?e instanceof HTMLElement?(e.style.transform="scale(0.75)",e.style.opacity="0",e.style.visibility="hidden",e.removeAttribute("data-tinydialog-widget-visible")):console.warn("tried opening widget, but widgetContainer was not a HTMLElement"):console.debug(`tried closing widget with id ${t} which does not exist on page`)}function a(t){t.currentTarget instanceof HTMLElement&&n(t.currentTarget.dataset.tinydialogOpenwidget,{side:t.currentTarget.dataset.tinydialogWidgetSide?.toUpperCase()})}function d(){r?.dataset.tinydialogFloatingButton&&function(t){const e=t.tinydialogFloatingButton;if(!e||e.length<10)return void console.warn('invalid surveyId configured in "data-tinydialog-floating-button"');if(document.querySelector("#tinydialog-floating-button__auto"))return void console.debug("prevented duplicate autoCreateFloatingButton execution, button alreadx exists");const i=document.createElement("button");i.id="tinydialog-floating-button__auto",i.style.position="fixed",i.style.right="20px",i.style.bottom="20px",i.style.width="48px",i.style.height="48px",i.style.background=t.tinydialogFloatingButtonBackground??"black",i.style.color=t.tinydialogFloatingButtonForeground??"white",i.style.borderRadius="100%",i.style.padding="8px",i.style.cursor="pointer",i.style.transitionDuration="300ms",i.style.transitionProperty="all",i.dataset.tinydialogOpenwidget=e,i.addEventListener("mouseenter",(()=>i.style.background=t.tinydialogFloatingButtonBackgroundHover??"#E2187D")),i.addEventListener("mouseleave",(()=>i.style.background=t.tinydialogFloatingButtonBackground??"black"));const n=document.createElement("svg");i.append(n),n.outerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>',document.body.append(i)}(r.dataset),document.querySelectorAll("[data-tinydialog-openwidget]").forEach((t=>{t instanceof HTMLElement&&(i(t.dataset.tinydialogOpenwidget,{side:t.dataset.tinydialogWidgetSide?.toUpperCase(),user:t.dataset.tinydialogUser??r?.dataset.tinydialogUser}),t.removeEventListener("click",a),t.addEventListener("click",a))})),document.querySelectorAll("[data-tinydialog-widgetcontainer]").forEach((t=>{t instanceof HTMLElement&&i(t.dataset.tinydialogWidgetcontainer,{user:t.dataset.tinydialogUser??r?.dataset.tinydialogUser},t)}))}var r=document.currentScript;onload=()=>{r||(r=document.currentScript)},d();export{d as bindSurveysWithDataAttributes,o as closeWidget,i as loadSurvey,n as showWidget};
package/package.json ADDED
@@ -0,0 +1,40 @@
1
+ {
2
+ "name": "@tinydialog/sdk-js",
3
+ "version": "0.0.1-rc.1",
4
+ "description": "JavaScript Client Library for tinyDialog.com",
5
+ "author": "tinydialog.com",
6
+ "homepage": "https://tinydialog.com",
7
+ "license": "MIT",
8
+ "type": "module",
9
+ "main": "dist/index.cjs",
10
+ "module": "dist/index.js",
11
+ "browser": "dist/index.browser.js",
12
+ "types": "dist/index.d.ts",
13
+ "exports": {
14
+ ".": {
15
+ "import": "./dist/index.js",
16
+ "require": "./dist/index.cjs"
17
+ },
18
+ "./package.json": "./package.json"
19
+ },
20
+ "files": [
21
+ "dist"
22
+ ],
23
+ "dependencies": {
24
+ "html-to-image": "^1.11.12"
25
+ },
26
+ "devDependencies": {
27
+ "@eslint/js": "^9.20.0",
28
+ "@stylistic/eslint-plugin": "^3.1.0",
29
+ "@types/eslint": "^9.6.1",
30
+ "eslint": "^9.20.1",
31
+ "eslint-plugin-unused-imports": "^4.1.4",
32
+ "terser": "^5.39.0",
33
+ "tsup": "^8.3.6",
34
+ "typescript": "^5.7.3",
35
+ "typescript-eslint": "^8.24.0"
36
+ },
37
+ "scripts": {
38
+ "build": "tsup"
39
+ }
40
+ }