@rebirth-wd/pulse-widget 0.0.0-stage → 0.1.0
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/CHANGELOG.md +12 -0
- package/README.md +37 -2
- package/dist/cdn/pulse.js +70 -0
- package/dist/index.d.ts +83 -0
- package/dist/index.js +459 -0
- package/package.json +45 -3
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# @rebirth-wd/pulse-widget
|
|
2
|
+
|
|
3
|
+
## 0.1.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 4aeeefa: First public release of `<pulse-enquiry>`: one-question-per-screen enquiry flow with a ballpark price range, editable answer chips, answers saved between visits, local-only journey tracking, Turnstile support, and the site's own form as fallback. Also served from the API Worker at `/widget/v1/pulse.js`.
|
|
8
|
+
|
|
9
|
+
### Patch Changes
|
|
10
|
+
|
|
11
|
+
- Updated dependencies [4aeeefa]
|
|
12
|
+
- @rebirth-wd/shared@0.1.0
|
package/README.md
CHANGED
|
@@ -1,3 +1,38 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @rebirth-wd/pulse-widget
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
`<pulse-enquiry>`: the Rebirth Pulse enquiry widget (one question per screen, ballpark price range, answers saved between visits).
|
|
4
|
+
|
|
5
|
+
Put your site's own plain HTML form inside the element. It is what visitors see without JavaScript, while the widget loads, and if the Pulse API is unreachable, so an enquiry is never lost.
|
|
6
|
+
|
|
7
|
+
```html
|
|
8
|
+
<pulse-enquiry site-key="pk_yoursite_key">
|
|
9
|
+
<form method="post" action="/api/contact">…your fallback form…</form>
|
|
10
|
+
</pulse-enquiry>
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## With a bundler (Astro, Vite)
|
|
14
|
+
|
|
15
|
+
```js
|
|
16
|
+
import { definePulseEnquiry, trackJourney } from "@rebirth-wd/pulse-widget";
|
|
17
|
+
trackJourney(); // every page: records the visit in localStorage only, no network
|
|
18
|
+
definePulseEnquiry(); // registers <pulse-enquiry>
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Set `api-base` on the element to point at a non-default API.
|
|
22
|
+
|
|
23
|
+
## From the CDN (no build step)
|
|
24
|
+
|
|
25
|
+
```html
|
|
26
|
+
<script type="module" src="https://rebirth-pulse-api.alexharris0079.workers.dev/widget/v1/pulse.js"></script>
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
`/widget/v1/pulse.js` follows the latest v1 release (5-minute cache); `/widget/<version>/pulse.js` is immutable.
|
|
30
|
+
|
|
31
|
+
## Behaviour
|
|
32
|
+
|
|
33
|
+
- Open Shadow DOM. Brand comes from the design-system `--ds-*` variables on the page; Subtropic defaults otherwise.
|
|
34
|
+
- Config loads only when the element nears the viewport. Add `eager` to load at once.
|
|
35
|
+
- Journey (landing page, referrer, UTM, pages, device) stays in the visitor's browser and is sent once, with the enquiry. Say so in your privacy policy.
|
|
36
|
+
- Respects `prefers-reduced-motion`. Keyboard and screen-reader tested with axe (WCAG 2.2 AA).
|
|
37
|
+
- Fires `pulse:submitted` (`detail: { id, estimate }`) on success.
|
|
38
|
+
- Turnstile renders in a light-DOM `slot="turnstile"` when the site has a Turnstile key.
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
var k="v1",h=50,f=class extends Error{constructor(s,t,e){super(`Pulse API ${s}: ${t}`),this.status=s,this.code=t,this.fields=e,this.name="PulseApiError"}status;code;fields};function v(s,t=(...e)=>fetch(...e)){let e=`${s.replace(/\/+$/,"")}/${k}`;async function r(i,n){let o=await t(e+i,{...n,headers:{accept:"application/json",...n.headers??{}}}),c=await o.json().catch(()=>({}));if(!o.ok)throw new f(o.status,c.error??"http_error",c.fields);return c}return{getWidgetConfig:(i,n)=>r(`/widget/config?key=${encodeURIComponent(i)}`,{method:"GET",signal:n?.signal??null}),createEnquiry:(i,n)=>r("/enquiries",{method:"POST",body:JSON.stringify(i),headers:{"content-type":"text/plain;charset=UTF-8"},signal:n?.signal??null})}}var b="pulse:journey",$=720*36e5,M=["utm_source","utm_medium","utm_campaign","utm_term","utm_content","gclid","fbclid"];function y(){try{return window.localStorage}catch{return null}}function E(s=y()){try{let t=s?.getItem(b);if(!t)return;let e=JSON.parse(t);return Date.now()-e.started>$?void 0:{landing:e.landing,referrer:e.referrer,utm:e.utm,device:e.device,pages:e.pages}}catch{return}}var T=()=>{let s=window.innerWidth;return s<640?"mobile":s<1024?"tablet":"desktop"};function S(s=window.location,t=y()){if(t)try{let e=null,r=t.getItem(b);if(r&&(e=JSON.parse(r),Date.now()-e.started>$&&(e=null)),!e){let n=new URLSearchParams(s.search),o={};for(let l of M){let u=n.get(l);u&&(o[l]=u.slice(0,200))}let c=document.referrer&&new URL(document.referrer).origin!==s.origin?document.referrer.slice(0,500):void 0;e={started:Date.now(),landing:s.pathname.slice(0,500),device:T(),pages:[],...c?{referrer:c}:{},...Object.keys(o).length?{utm:o}:{}}}e.pages[e.pages.length-1]?.path!==s.pathname&&e.pages.push({path:s.pathname.slice(0,300),at:Math.round((Date.now()-e.started)/1e3)}),e.pages.length>h&&(e.pages=e.pages.slice(-h)),t.setItem(b,JSON.stringify(e))}catch{}}function A(s=y()){try{s?.removeItem(b)}catch{}}var j=`
|
|
2
|
+
:host { all: initial; display: block; container-type: inline-size;
|
|
3
|
+
--c-bg: var(--ds-color-surface, #fff); --c-alt: var(--ds-color-surface-alt, #EFEAF8);
|
|
4
|
+
--c-text: var(--ds-color-text, #1E1A2B); --c-muted: var(--ds-color-text-muted, #575170);
|
|
5
|
+
--c-border: var(--ds-color-border, #DCD6E8); --c-strong: var(--ds-color-border-strong, #7F7896);
|
|
6
|
+
--c-accent: var(--ds-color-accent, #5E3BA8); --c-on-accent: var(--ds-color-on-accent, #fff);
|
|
7
|
+
--c-cta: var(--ds-color-cta, #B93A26); --c-on-cta: var(--ds-color-on-cta, #fff);
|
|
8
|
+
--c-focus: var(--ds-color-focus, #5E3BA8); --c-link: var(--ds-color-link, #5E3BA8);
|
|
9
|
+
--c-ok-bg: var(--ds-color-success-bg, #D7EFE6); --c-ok: var(--ds-color-success-text, #1A5C48);
|
|
10
|
+
--c-bad-bg: var(--ds-color-danger-bg, #FBE0DA); --c-bad: var(--ds-color-danger-text, #A12A1A);
|
|
11
|
+
--r: var(--ds-radius-lg, 16px); --r-pill: var(--ds-radius-pill, 999px);
|
|
12
|
+
font-family: var(--ds-font-body, system-ui, -apple-system, "Segoe UI", sans-serif);
|
|
13
|
+
font-size: 16px; line-height: var(--ds-leading-body, 1.55); color: var(--c-text);
|
|
14
|
+
}
|
|
15
|
+
:host([hidden]) { display: none; }
|
|
16
|
+
*, *::before, *::after { box-sizing: border-box; }
|
|
17
|
+
[hidden] { display: none !important; }
|
|
18
|
+
.card { background: var(--c-bg); border: 1px solid var(--c-border); border-radius: var(--r); padding: 24px; box-shadow: var(--ds-shadow-1, 0 1px 2px rgb(0 0 0 / .06)); }
|
|
19
|
+
@container (min-width: 560px) { .card { padding: 32px; } }
|
|
20
|
+
.top { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-block-end: 16px; color: var(--c-muted); font-size: 14px; font-weight: 600; }
|
|
21
|
+
.dots { display: flex; gap: 6px; }
|
|
22
|
+
.dot { inline-size: 8px; block-size: 8px; border-radius: 50%; background: var(--c-border); }
|
|
23
|
+
.dot[data-on] { background: var(--c-accent); }
|
|
24
|
+
.chips { display: flex; flex-wrap: wrap; gap: 8px; margin: 0 0 16px; padding: 0; list-style: none; }
|
|
25
|
+
.chip { display: inline-flex; align-items: center; gap: 6px; min-block-size: 32px; padding: 4px 12px; border: 1px solid var(--c-border); border-radius: var(--r-pill); background: var(--c-alt); color: var(--c-text); font: inherit; font-size: 14px; cursor: pointer; }
|
|
26
|
+
.chip::after { content: "Edit"; color: var(--c-link); font-weight: 600; font-size: 13px; }
|
|
27
|
+
h2 { margin: 0 0 16px; font-family: var(--ds-font-display, inherit); font-size: 1.5em; line-height: var(--ds-leading-tight, 1.15); font-weight: 700; outline: none; }
|
|
28
|
+
.options { display: grid; gap: 10px; grid-template-columns: 1fr; margin: 0; padding: 0; list-style: none; }
|
|
29
|
+
@container (min-width: 480px) { .options { grid-template-columns: 1fr 1fr; } }
|
|
30
|
+
.opt { inline-size: 100%; min-block-size: 56px; padding: 12px 16px; text-align: start; border: 2px solid var(--c-strong); border-radius: var(--ds-radius-md, 12px); background: var(--c-bg); color: var(--c-text); font: inherit; font-weight: 600; cursor: pointer; }
|
|
31
|
+
.opt:hover { border-color: var(--c-accent); }
|
|
32
|
+
.opt[aria-pressed="true"] { border-color: var(--c-accent); background: var(--c-accent); color: var(--c-on-accent); }
|
|
33
|
+
.field { display: grid; gap: 6px; margin-block-end: 16px; }
|
|
34
|
+
label, .label { font-weight: 600; }
|
|
35
|
+
.hint { color: var(--c-muted); font-size: 14px; margin: 0; }
|
|
36
|
+
input[type=text], input[type=email], input[type=tel], textarea { inline-size: 100%; min-block-size: 48px; padding: 10px 14px; border: 2px solid var(--c-strong); border-radius: var(--ds-radius-md, 12px); background: var(--c-bg); color: var(--c-text); font: inherit; }
|
|
37
|
+
textarea { min-block-size: 96px; resize: vertical; }
|
|
38
|
+
input[aria-invalid="true"], textarea[aria-invalid="true"] { border-color: var(--c-bad); }
|
|
39
|
+
.check { display: flex; align-items: flex-start; gap: 12px; }
|
|
40
|
+
.check input { flex: none; inline-size: 24px; block-size: 24px; margin: 0; accent-color: var(--c-accent); }
|
|
41
|
+
.check label { font-weight: 400; }
|
|
42
|
+
.error { color: var(--c-bad); font-size: 14px; font-weight: 600; margin: 0; }
|
|
43
|
+
.alert { padding: 14px 18px; border-radius: var(--ds-radius-md, 12px); font-weight: 600; margin: 0 0 16px; }
|
|
44
|
+
.alert.ok { background: var(--c-ok-bg); color: var(--c-ok); }
|
|
45
|
+
.alert.bad { background: var(--c-bad-bg); color: var(--c-bad); }
|
|
46
|
+
.estimate strong { display: block; font-size: 1.4em; }
|
|
47
|
+
.row { display: grid; gap: 0 16px; }
|
|
48
|
+
@container (min-width: 520px) { .row { grid-template-columns: 1fr 1fr; } }
|
|
49
|
+
.actions { display: flex; flex-wrap: wrap; align-items: center; gap: 12px; margin-block-start: 8px; }
|
|
50
|
+
.btn { display: inline-flex; align-items: center; justify-content: center; min-block-size: 48px; padding: 0 24px; border: 0; border-radius: var(--r-pill); background: var(--c-cta); color: var(--c-on-cta); font: inherit; font-weight: 700; cursor: pointer; }
|
|
51
|
+
.btn[disabled] { opacity: .7; cursor: progress; }
|
|
52
|
+
.link { min-block-size: 44px; padding: 0 8px; border: 0; background: none; color: var(--c-link); font: inherit; font-weight: 600; text-decoration: underline; cursor: pointer; }
|
|
53
|
+
a { color: var(--c-link); }
|
|
54
|
+
.hp { position: absolute; inline-size: 1px; block-size: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
|
|
55
|
+
:focus-visible { outline: 3px solid var(--c-focus); outline-offset: 2px; }
|
|
56
|
+
@media (prefers-reduced-motion: no-preference) {
|
|
57
|
+
.step { animation: enter var(--ds-motion-dur-base, 220ms) var(--ds-motion-ease-standard, cubic-bezier(.2,0,0,1)); }
|
|
58
|
+
.opt, .chip, .btn { transition: background-color var(--ds-motion-dur-fast, 120ms), border-color var(--ds-motion-dur-fast, 120ms), transform var(--ds-motion-dur-fast, 120ms); }
|
|
59
|
+
.opt:active, .btn:active { transform: scale(.98); }
|
|
60
|
+
@keyframes enter { from { opacity: 0; transform: translateY(6px); } }
|
|
61
|
+
}
|
|
62
|
+
@media (forced-colors: active) { .opt[aria-pressed="true"] { outline: 3px solid CanvasText; } .dot[data-on] { background: CanvasText; } }
|
|
63
|
+
`;var d="pulse-enquiry",x="https://rebirth-pulse-api.alexharris0079.workers.dev",a=s=>String(s??"").replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t]),g=s=>"$"+Math.round(s).toLocaleString("en-AU"),m={project:"What's the project?",budget:"Roughly what budget do you have in mind?",timing:"When would you like to start?",suburb:"Which suburb is the job in?",contact:"Where should we send your price range?"},p=class extends HTMLElement{static observedAttributes=["site-key"];client;config;mode="loading";root;step="project";answers={};errors={};alert="";sending=!1;consent=!1;turnstileToken;result;started=!1;get siteKey(){return this.getAttribute("site-key")??""}get storeKey(){return`pulse:form:${this.siteKey}`}connectedCallback(){if(this.shadowRoot||(this.root=this.attachShadow({mode:"open"}),this.root.addEventListener("click",t=>this.onClick(t)),this.root.addEventListener("submit",t=>this.onSubmit(t)),this.root.addEventListener("input",t=>this.onInput(t))),this.render(),!this.siteKey)return this.setMode("fallback");if("IntersectionObserver"in window&&!this.hasAttribute("eager")){let t=new IntersectionObserver(e=>{e.some(r=>r.isIntersecting)&&(t.disconnect(),this.start())},{rootMargin:"400px"});t.observe(this)}else queueMicrotask(()=>{this.start()})}async start(){if(this.started)return;this.started=!0;let t=this.client??=v(this.getAttribute("api-base")||x);try{this.config=await t.getWidgetConfig(this.siteKey,{signal:AbortSignal.timeout(8e3)})}catch(r){return console.warn("[pulse] widget config unavailable, using the fallback form",r),this.setMode("fallback")}this.answers=this.restore();let e=new URL(location.href).searchParams.get("project");e&&this.config.form.projects.some(r=>r.value===e)&&(this.answers.project=e),this.step=this.steps().find(r=>!this.isAnswered(r))??"contact",this.setMode("widget")}setMode(t){this.mode=t,this.dataset.state=t,this.render()}steps(){let t=this.config?.form,e=["project"];return t?.budgets.length&&e.push("budget"),t?.timings.length&&e.push("timing"),e.push("suburb","contact"),e}isAnswered(t){return t==="contact"?!1:this.answers[t]!==void 0}restore(){try{return JSON.parse(localStorage.getItem(this.storeKey)??"{}")}catch{return{}}}save(){try{localStorage.setItem(this.storeKey,JSON.stringify(this.answers))}catch{}}go(t,e=!0){this.step=t,this.alert="",this.render(),e&&this.root.querySelector("h2")?.focus()}next(){let t=this.steps(),e=t.indexOf(this.step),r=t.slice(e+1).find(i=>!this.isAnswered(i));this.go(r??"contact")}onClick(t){let e=t.target.closest("[data-action]");if(!e||e.getRootNode()!==this.root)return;let{action:r,value:i,step:n}=e.dataset;r==="choose"&&n?(this.answers[n]=i??"",this.save(),this.next()):r==="edit"&&n?this.go(n):r==="fallback"&&(this.setMode("fallback"),this.querySelector("input, select, textarea")?.focus())}onInput(t){let e=t.target;e.getRootNode()===this.root&&(e.name==="consent"?this.consent=e.checked:["name","email","phone","message","suburb"].includes(e.name)&&(this.answers[e.name]=e.value,this.save()))}onSubmit(t){let e=t.target;if(e.getRootNode()===this.root){if(t.preventDefault(),e.dataset.step==="suburb")return this.answers.suburb=e.elements.namedItem("suburb").value.trim(),this.save(),this.next();e.dataset.step==="contact"&&this.send(e)}}validate(){let t=this.answers,e={};return t.name?.trim()||(e.name="Enter your name."),/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t.email?.trim()??"")||(e.email="Enter an email address like name@example.com."),t.phone?.trim()&&!/^[+\d][\d\s()-]{7,}$/.test(t.phone.trim())&&(e.phone="Enter a phone number, or leave it blank."),this.consent||(e.consent="Tick the box so we can use your details to reply."),this.config?.turnstileSiteKey&&!this.turnstileToken&&(e.turnstile="Please complete the quick check above the button."),e}async send(t){if(this.sending||!this.config)return;if(this.errors=this.validate(),Object.keys(this.errors).length){this.alert=`Please fix ${Object.keys(this.errors).length===1?"1 thing":`${Object.keys(this.errors).length} things`} before sending.`,this.render(),this.focusFirstError();return}let e=this.answers,r={siteKey:this.siteKey,project:e.project??"",budget:e.budget||void 0,timing:e.timing||void 0,suburb:e.suburb||void 0,name:e.name??"",email:e.email??"",phone:e.phone||void 0,message:e.message||void 0,consent:!0,page:location.pathname,journey:E(),turnstileToken:this.turnstileToken,company_website:t.elements.namedItem("company_website")?.value||void 0};this.sending=!0,this.alert="",this.render();try{this.result=await this.client.createEnquiry(r,{signal:AbortSignal.timeout(15e3)});try{localStorage.removeItem(this.storeKey)}catch{}A(),this.sending=!1,this.setMode("done"),this.root.querySelector("h2")?.focus(),this.dispatchEvent(new CustomEvent("pulse:submitted",{detail:this.result,bubbles:!0,composed:!0}))}catch(i){if(this.sending=!1,i instanceof f&&i.status===422&&i.fields){this.errors=i.fields;let n=this.steps().find(o=>o!=="contact"&&i.fields[o]);if(n){delete this.answers[n],this.go(n),this.alert=i.fields[n],this.render();return}this.alert="Please check the highlighted fields."}else this.alert="fail",window.turnstile?.reset(),this.turnstileToken=void 0;this.render(),this.focusFirstError()}}focusFirstError(){let t=Object.keys(this.errors)[0];(t&&this.root.querySelector(`[name="${t}"]`)||this.root.querySelector(".alert"))?.focus()}mountTurnstile(){let t=this.config?.turnstileSiteKey;if(!t||this.querySelector('[slot="turnstile"]'))return;let e=document.createElement("div");e.slot="turnstile",this.append(e);let r=()=>window.turnstile?.render(e,{sitekey:t,callback:n=>this.turnstileToken=n,"expired-callback":()=>this.turnstileToken=void 0});if(window.turnstile)return void r();let i=document.createElement("script");i.src="https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit",i.async=!0,i.onload=r,document.head.append(i)}render(){if(!this.root)return;let t=this.mode==="loading"||this.mode==="fallback",e=this.mode==="widget"?this.renderStep():this.mode==="done"?this.renderDone():"";this.root.innerHTML=`<style>${j}</style>${e}<div ${t?"":"hidden"}><slot></slot></div>`,this.mode==="widget"&&this.step==="contact"&&this.mountTurnstile()}label(t){let e=this.answers[t];return t==="project"?this.config?.form.projects.find(r=>r.value===e)?.label??e:e||"Skipped"}renderStep(){let t=this.steps(),e=t.indexOf(this.step),r=t.filter(l=>l!==this.step&&this.isAnswered(l)),i=r.length?`<ul class="chips" aria-label="Your answers">${r.map(l=>`<li><button type="button" class="chip" data-action="edit" data-step="${l}" aria-label="${a(`${m[l]} ${this.label(l)}. Edit`)}">${a(this.label(l))}</button></li>`).join("")}</ul>`:"",n=t.map((l,u)=>`<span class="dot"${u<=e?" data-on":""}></span>`).join(""),o=`<div class="top"><span aria-live="polite">${e+1} of ${t.length}</span><span class="dots" aria-hidden="true">${n}</span></div>`,c=this.alert&&this.alert!=="fail"?`<p class="alert bad" role="alert" tabindex="-1">${a(this.alert)}</p>`:"";return`<section class="card" aria-label="Get a price range">${o}${i}<div class="step">${c}${this.stepBody(this.step)}</div></section>`}choices(t,e,r){let i=this.answers[t],n=e.map(c=>`<li><button type="button" class="opt" data-action="choose" data-step="${t}" data-value="${a(c.value)}" aria-pressed="${i===c.value}">${a(c.label)}</button></li>`).join(""),o=r?`<div class="actions"><button type="button" class="link" data-action="choose" data-step="${t}" data-value="">Skip this question</button></div>`:"";return`<h2 tabindex="-1" id="q">${a(m[t])}</h2><ul class="options" aria-labelledby="q">${n}</ul>${o}`}stepBody(t){let e=this.config.form;return t==="project"?this.choices("project",e.projects,!1):t==="budget"?this.choices("budget",e.budgets.map(r=>({value:r,label:r})),!0):t==="timing"?this.choices("timing",e.timings.map(r=>({value:r,label:r})),!0):t==="suburb"?`<form data-step="suburb" novalidate><h2 tabindex="-1">${a(m.suburb)}</h2><div class="field"><label for="suburb">Suburb</label><input type="text" id="suburb" name="suburb" autocomplete="address-level2" enterkeyhint="next" value="${a(this.answers.suburb??"")}" aria-describedby="suburb-hint">${e.reassurance?`<p class="hint" id="suburb-hint">${a(e.reassurance)}</p>`:'<p class="hint" id="suburb-hint">Optional.</p>'}</div><div class="actions"><button class="btn" type="submit">Next</button></div></form>`:this.contactBody()}estimateHtml(){let t=this.config.form.projects.find(e=>e.value===this.answers.project);return!t||t.priceMin==null||t.priceMax==null?"":`<p class="alert ok estimate">Ballpark for a ${a(t.label.toLowerCase())}<strong>${g(t.priceMin)} to ${g(t.priceMax)}</strong><span class="hint">Based on recent jobs. We firm it up once we have seen the space.</span></p>`}field(t,e,r,i,n=""){let o=this.errors[t],c=t==="phone"?'<p class="hint" id="phone-hint">Optional. Handy if you would rather we call.</p>':"",l=[t==="phone"?"phone-hint":"",o?`${t}-error`:""].filter(Boolean).join(" ");return`<div class="field"><label for="${t}">${e}${t==="phone"?"":' <span aria-hidden="true">*</span>'}</label><input type="${r}" id="${t}" name="${t}" autocomplete="${i}" ${n} value="${a(this.answers[t]??"")}" ${t==="phone"?"":"required"} ${o?'aria-invalid="true"':""} ${l?`aria-describedby="${l}"`:""}>${c}${o?`<p class="error" id="${t}-error">${a(o)}</p>`:""}</div>`}contactBody(){let t=this.config,e=this.errors;return`<form data-step="contact" novalidate>${this.alert==="fail"?'<div class="alert bad" role="alert" tabindex="-1">Sorry, that did not send. Please try again, or <button type="button" class="link" data-action="fallback">use the simple form</button>.</div>':""}<h2 tabindex="-1">${a(m.contact)}</h2>${this.estimateHtml()}
|
|
64
|
+
<div class="row">${this.field("name","Your name","text","name",'enterkeyhint="next"')}${this.field("email","Email","email","email",'inputmode="email" enterkeyhint="next"')}</div>
|
|
65
|
+
${this.field("phone","Phone","tel","tel",'inputmode="tel" enterkeyhint="next"')}
|
|
66
|
+
<div class="field"><label for="message">Anything else we should know?</label><textarea id="message" name="message" rows="3" aria-describedby="message-hint">${a(this.answers.message??"")}</textarea><p class="hint" id="message-hint">Optional. Size of the room, what you want to change.</p></div>
|
|
67
|
+
<div class="hp" aria-hidden="true"><label for="company_website">Leave this empty</label><input type="text" id="company_website" name="company_website" tabindex="-1" autocomplete="off"></div>
|
|
68
|
+
<div class="field"><div class="check"><input type="checkbox" id="consent" name="consent" ${this.consent?"checked":""} required ${e.consent?'aria-invalid="true"':""} aria-describedby="consent-text${e.consent?" consent-error":""}"><label for="consent" id="consent-text">${a(t.consentText)} <a href="${a(/^https?:\/\//.test(t.privacyUrl)?t.privacyUrl:"#")}">Read our privacy policy</a>.</label></div>${e.consent?`<p class="error" id="consent-error">${a(e.consent)}</p>`:""}</div>
|
|
69
|
+
${t.turnstileSiteKey?`<div class="field"><slot name="turnstile"></slot>${e.turnstile?`<p class="error">${a(e.turnstile)}</p>`:""}</div>`:""}
|
|
70
|
+
<div class="actions"><button class="btn" type="submit" ${this.sending?"disabled":""}>${this.sending?"Sending\u2026":"Send my enquiry"}</button></div></form>`}renderDone(){let t=this.config?.form.thanks,e=this.result?.estimate;return`<section class="card" aria-label="Enquiry sent"><div class="step"><h2 tabindex="-1">${a(t?.title??"Thanks, we have your enquiry")}</h2>${e?`<p class="alert ok estimate">Your ballpark<strong>${g(e.min)} to ${g(e.max)}</strong></p>`:""}<p>${a(t?.body??"We will be in touch within one business day. Check your inbox for a copy.")}</p></div></section>`}};function I(s=customElements){s.get(d)||s.define(d,p)}var _=(()=>{try{return new URL(import.meta.url).origin}catch{return x}})(),w=class extends p{connectedCallback(){this.hasAttribute("api-base")||this.setAttribute("api-base",_),super.connectedCallback()}};S();customElements.get(d)||customElements.define(d,w);export{I as definePulseEnquiry};
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { PulseClient, WidgetConfig, Journey } from '@rebirth-wd/shared/client';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* <pulse-enquiry site-key="pk_..." api-base="https://..."> (D6, D14).
|
|
5
|
+
*
|
|
6
|
+
* Open Shadow DOM. The light-DOM children (the site's own no-JS <form>, posting to its /api/contact) stay
|
|
7
|
+
* visible through the default slot until the Pulse config loads, and come back if the API fails, so a
|
|
8
|
+
* lead is never lost. Flow: one question per screen, answers as editable chips, ballpark range before
|
|
9
|
+
* contact details, saved to localStorage between visits.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
declare const TAG_NAME = "pulse-enquiry";
|
|
13
|
+
declare const DEFAULT_API_BASE = "https://rebirth-pulse-api.alexharris0079.workers.dev";
|
|
14
|
+
type Mode = "loading" | "widget" | "fallback" | "done";
|
|
15
|
+
declare global {
|
|
16
|
+
interface Window {
|
|
17
|
+
turnstile?: {
|
|
18
|
+
render(el: HTMLElement, opts: Record<string, unknown>): string;
|
|
19
|
+
reset(id?: string): void;
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
interface HTMLElementTagNameMap {
|
|
23
|
+
"pulse-enquiry": PulseEnquiry;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
declare class PulseEnquiry extends HTMLElement {
|
|
27
|
+
static observedAttributes: string[];
|
|
28
|
+
/** Injected in tests. */
|
|
29
|
+
client?: PulseClient;
|
|
30
|
+
config?: WidgetConfig;
|
|
31
|
+
mode: Mode;
|
|
32
|
+
private root;
|
|
33
|
+
private step;
|
|
34
|
+
private answers;
|
|
35
|
+
private errors;
|
|
36
|
+
private alert;
|
|
37
|
+
private sending;
|
|
38
|
+
private consent;
|
|
39
|
+
private turnstileToken?;
|
|
40
|
+
private result?;
|
|
41
|
+
private started;
|
|
42
|
+
get siteKey(): string;
|
|
43
|
+
private get storeKey();
|
|
44
|
+
connectedCallback(): void;
|
|
45
|
+
private start;
|
|
46
|
+
private setMode;
|
|
47
|
+
private steps;
|
|
48
|
+
private isAnswered;
|
|
49
|
+
private restore;
|
|
50
|
+
private save;
|
|
51
|
+
private go;
|
|
52
|
+
private next;
|
|
53
|
+
private onClick;
|
|
54
|
+
private onInput;
|
|
55
|
+
private onSubmit;
|
|
56
|
+
private validate;
|
|
57
|
+
private send;
|
|
58
|
+
private focusFirstError;
|
|
59
|
+
private mountTurnstile;
|
|
60
|
+
private render;
|
|
61
|
+
private label;
|
|
62
|
+
private renderStep;
|
|
63
|
+
private choices;
|
|
64
|
+
private stepBody;
|
|
65
|
+
private estimateHtml;
|
|
66
|
+
private field;
|
|
67
|
+
private contactBody;
|
|
68
|
+
private renderDone;
|
|
69
|
+
}
|
|
70
|
+
declare function definePulseEnquiry(registry?: CustomElementRegistry): void;
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* D9: first-party journey kept in the visitor's own browser. Nothing is sent until they submit an enquiry,
|
|
74
|
+
* and then only once, inside the enquiry. No cookies, no third parties, no per-page-view requests.
|
|
75
|
+
*/
|
|
76
|
+
|
|
77
|
+
declare const JOURNEY_KEY = "pulse:journey";
|
|
78
|
+
declare function readJourney(storage?: Storage | null): Journey | undefined;
|
|
79
|
+
/** Records this page view locally. Call once per page load. */
|
|
80
|
+
declare function trackJourney(loc?: Location, storage?: Storage | null): void;
|
|
81
|
+
declare function clearJourney(storage?: Storage | null): void;
|
|
82
|
+
|
|
83
|
+
export { DEFAULT_API_BASE, JOURNEY_KEY, PulseEnquiry, TAG_NAME, clearJourney, definePulseEnquiry, readJourney, trackJourney };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,459 @@
|
|
|
1
|
+
// src/element.ts
|
|
2
|
+
import { createPulseClient, PulseApiError } from "@rebirth-wd/shared/client";
|
|
3
|
+
|
|
4
|
+
// src/journey.ts
|
|
5
|
+
import { JOURNEY_MAX_PAGES } from "@rebirth-wd/shared/client";
|
|
6
|
+
var JOURNEY_KEY = "pulse:journey";
|
|
7
|
+
var MAX_AGE_MS = 30 * 24 * 36e5;
|
|
8
|
+
var UTM = ["utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content", "gclid", "fbclid"];
|
|
9
|
+
function safeStorage() {
|
|
10
|
+
try {
|
|
11
|
+
return window.localStorage;
|
|
12
|
+
} catch {
|
|
13
|
+
return null;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
function readJourney(storage = safeStorage()) {
|
|
17
|
+
try {
|
|
18
|
+
const raw = storage?.getItem(JOURNEY_KEY);
|
|
19
|
+
if (!raw) return void 0;
|
|
20
|
+
const j = JSON.parse(raw);
|
|
21
|
+
if (Date.now() - j.started > MAX_AGE_MS) return void 0;
|
|
22
|
+
return { landing: j.landing, referrer: j.referrer, utm: j.utm, device: j.device, pages: j.pages };
|
|
23
|
+
} catch {
|
|
24
|
+
return void 0;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
var device = () => {
|
|
28
|
+
const w = window.innerWidth;
|
|
29
|
+
return w < 640 ? "mobile" : w < 1024 ? "tablet" : "desktop";
|
|
30
|
+
};
|
|
31
|
+
function trackJourney(loc = window.location, storage = safeStorage()) {
|
|
32
|
+
if (!storage) return;
|
|
33
|
+
try {
|
|
34
|
+
let j = null;
|
|
35
|
+
const raw = storage.getItem(JOURNEY_KEY);
|
|
36
|
+
if (raw) {
|
|
37
|
+
j = JSON.parse(raw);
|
|
38
|
+
if (Date.now() - j.started > MAX_AGE_MS) j = null;
|
|
39
|
+
}
|
|
40
|
+
if (!j) {
|
|
41
|
+
const params = new URLSearchParams(loc.search);
|
|
42
|
+
const utm = {};
|
|
43
|
+
for (const k of UTM) {
|
|
44
|
+
const v = params.get(k);
|
|
45
|
+
if (v) utm[k] = v.slice(0, 200);
|
|
46
|
+
}
|
|
47
|
+
const ref = document.referrer && new URL(document.referrer).origin !== loc.origin ? document.referrer.slice(0, 500) : void 0;
|
|
48
|
+
j = { started: Date.now(), landing: loc.pathname.slice(0, 500), device: device(), pages: [], ...ref ? { referrer: ref } : {}, ...Object.keys(utm).length ? { utm } : {} };
|
|
49
|
+
}
|
|
50
|
+
const last = j.pages[j.pages.length - 1];
|
|
51
|
+
if (last?.path !== loc.pathname) j.pages.push({ path: loc.pathname.slice(0, 300), at: Math.round((Date.now() - j.started) / 1e3) });
|
|
52
|
+
if (j.pages.length > JOURNEY_MAX_PAGES) j.pages = j.pages.slice(-JOURNEY_MAX_PAGES);
|
|
53
|
+
storage.setItem(JOURNEY_KEY, JSON.stringify(j));
|
|
54
|
+
} catch {
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
function clearJourney(storage = safeStorage()) {
|
|
58
|
+
try {
|
|
59
|
+
storage?.removeItem(JOURNEY_KEY);
|
|
60
|
+
} catch {
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// src/styles.ts
|
|
65
|
+
var css = (
|
|
66
|
+
/* css */
|
|
67
|
+
`
|
|
68
|
+
:host { all: initial; display: block; container-type: inline-size;
|
|
69
|
+
--c-bg: var(--ds-color-surface, #fff); --c-alt: var(--ds-color-surface-alt, #EFEAF8);
|
|
70
|
+
--c-text: var(--ds-color-text, #1E1A2B); --c-muted: var(--ds-color-text-muted, #575170);
|
|
71
|
+
--c-border: var(--ds-color-border, #DCD6E8); --c-strong: var(--ds-color-border-strong, #7F7896);
|
|
72
|
+
--c-accent: var(--ds-color-accent, #5E3BA8); --c-on-accent: var(--ds-color-on-accent, #fff);
|
|
73
|
+
--c-cta: var(--ds-color-cta, #B93A26); --c-on-cta: var(--ds-color-on-cta, #fff);
|
|
74
|
+
--c-focus: var(--ds-color-focus, #5E3BA8); --c-link: var(--ds-color-link, #5E3BA8);
|
|
75
|
+
--c-ok-bg: var(--ds-color-success-bg, #D7EFE6); --c-ok: var(--ds-color-success-text, #1A5C48);
|
|
76
|
+
--c-bad-bg: var(--ds-color-danger-bg, #FBE0DA); --c-bad: var(--ds-color-danger-text, #A12A1A);
|
|
77
|
+
--r: var(--ds-radius-lg, 16px); --r-pill: var(--ds-radius-pill, 999px);
|
|
78
|
+
font-family: var(--ds-font-body, system-ui, -apple-system, "Segoe UI", sans-serif);
|
|
79
|
+
font-size: 16px; line-height: var(--ds-leading-body, 1.55); color: var(--c-text);
|
|
80
|
+
}
|
|
81
|
+
:host([hidden]) { display: none; }
|
|
82
|
+
*, *::before, *::after { box-sizing: border-box; }
|
|
83
|
+
[hidden] { display: none !important; }
|
|
84
|
+
.card { background: var(--c-bg); border: 1px solid var(--c-border); border-radius: var(--r); padding: 24px; box-shadow: var(--ds-shadow-1, 0 1px 2px rgb(0 0 0 / .06)); }
|
|
85
|
+
@container (min-width: 560px) { .card { padding: 32px; } }
|
|
86
|
+
.top { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-block-end: 16px; color: var(--c-muted); font-size: 14px; font-weight: 600; }
|
|
87
|
+
.dots { display: flex; gap: 6px; }
|
|
88
|
+
.dot { inline-size: 8px; block-size: 8px; border-radius: 50%; background: var(--c-border); }
|
|
89
|
+
.dot[data-on] { background: var(--c-accent); }
|
|
90
|
+
.chips { display: flex; flex-wrap: wrap; gap: 8px; margin: 0 0 16px; padding: 0; list-style: none; }
|
|
91
|
+
.chip { display: inline-flex; align-items: center; gap: 6px; min-block-size: 32px; padding: 4px 12px; border: 1px solid var(--c-border); border-radius: var(--r-pill); background: var(--c-alt); color: var(--c-text); font: inherit; font-size: 14px; cursor: pointer; }
|
|
92
|
+
.chip::after { content: "Edit"; color: var(--c-link); font-weight: 600; font-size: 13px; }
|
|
93
|
+
h2 { margin: 0 0 16px; font-family: var(--ds-font-display, inherit); font-size: 1.5em; line-height: var(--ds-leading-tight, 1.15); font-weight: 700; outline: none; }
|
|
94
|
+
.options { display: grid; gap: 10px; grid-template-columns: 1fr; margin: 0; padding: 0; list-style: none; }
|
|
95
|
+
@container (min-width: 480px) { .options { grid-template-columns: 1fr 1fr; } }
|
|
96
|
+
.opt { inline-size: 100%; min-block-size: 56px; padding: 12px 16px; text-align: start; border: 2px solid var(--c-strong); border-radius: var(--ds-radius-md, 12px); background: var(--c-bg); color: var(--c-text); font: inherit; font-weight: 600; cursor: pointer; }
|
|
97
|
+
.opt:hover { border-color: var(--c-accent); }
|
|
98
|
+
.opt[aria-pressed="true"] { border-color: var(--c-accent); background: var(--c-accent); color: var(--c-on-accent); }
|
|
99
|
+
.field { display: grid; gap: 6px; margin-block-end: 16px; }
|
|
100
|
+
label, .label { font-weight: 600; }
|
|
101
|
+
.hint { color: var(--c-muted); font-size: 14px; margin: 0; }
|
|
102
|
+
input[type=text], input[type=email], input[type=tel], textarea { inline-size: 100%; min-block-size: 48px; padding: 10px 14px; border: 2px solid var(--c-strong); border-radius: var(--ds-radius-md, 12px); background: var(--c-bg); color: var(--c-text); font: inherit; }
|
|
103
|
+
textarea { min-block-size: 96px; resize: vertical; }
|
|
104
|
+
input[aria-invalid="true"], textarea[aria-invalid="true"] { border-color: var(--c-bad); }
|
|
105
|
+
.check { display: flex; align-items: flex-start; gap: 12px; }
|
|
106
|
+
.check input { flex: none; inline-size: 24px; block-size: 24px; margin: 0; accent-color: var(--c-accent); }
|
|
107
|
+
.check label { font-weight: 400; }
|
|
108
|
+
.error { color: var(--c-bad); font-size: 14px; font-weight: 600; margin: 0; }
|
|
109
|
+
.alert { padding: 14px 18px; border-radius: var(--ds-radius-md, 12px); font-weight: 600; margin: 0 0 16px; }
|
|
110
|
+
.alert.ok { background: var(--c-ok-bg); color: var(--c-ok); }
|
|
111
|
+
.alert.bad { background: var(--c-bad-bg); color: var(--c-bad); }
|
|
112
|
+
.estimate strong { display: block; font-size: 1.4em; }
|
|
113
|
+
.row { display: grid; gap: 0 16px; }
|
|
114
|
+
@container (min-width: 520px) { .row { grid-template-columns: 1fr 1fr; } }
|
|
115
|
+
.actions { display: flex; flex-wrap: wrap; align-items: center; gap: 12px; margin-block-start: 8px; }
|
|
116
|
+
.btn { display: inline-flex; align-items: center; justify-content: center; min-block-size: 48px; padding: 0 24px; border: 0; border-radius: var(--r-pill); background: var(--c-cta); color: var(--c-on-cta); font: inherit; font-weight: 700; cursor: pointer; }
|
|
117
|
+
.btn[disabled] { opacity: .7; cursor: progress; }
|
|
118
|
+
.link { min-block-size: 44px; padding: 0 8px; border: 0; background: none; color: var(--c-link); font: inherit; font-weight: 600; text-decoration: underline; cursor: pointer; }
|
|
119
|
+
a { color: var(--c-link); }
|
|
120
|
+
.hp { position: absolute; inline-size: 1px; block-size: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
|
|
121
|
+
:focus-visible { outline: 3px solid var(--c-focus); outline-offset: 2px; }
|
|
122
|
+
@media (prefers-reduced-motion: no-preference) {
|
|
123
|
+
.step { animation: enter var(--ds-motion-dur-base, 220ms) var(--ds-motion-ease-standard, cubic-bezier(.2,0,0,1)); }
|
|
124
|
+
.opt, .chip, .btn { transition: background-color var(--ds-motion-dur-fast, 120ms), border-color var(--ds-motion-dur-fast, 120ms), transform var(--ds-motion-dur-fast, 120ms); }
|
|
125
|
+
.opt:active, .btn:active { transform: scale(.98); }
|
|
126
|
+
@keyframes enter { from { opacity: 0; transform: translateY(6px); } }
|
|
127
|
+
}
|
|
128
|
+
@media (forced-colors: active) { .opt[aria-pressed="true"] { outline: 3px solid CanvasText; } .dot[data-on] { background: CanvasText; } }
|
|
129
|
+
`
|
|
130
|
+
);
|
|
131
|
+
|
|
132
|
+
// src/element.ts
|
|
133
|
+
var TAG_NAME = "pulse-enquiry";
|
|
134
|
+
var DEFAULT_API_BASE = "https://rebirth-pulse-api.alexharris0079.workers.dev";
|
|
135
|
+
var esc = (v) => String(v ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]);
|
|
136
|
+
var money = (n) => "$" + Math.round(n).toLocaleString("en-AU");
|
|
137
|
+
var QUESTIONS = {
|
|
138
|
+
project: "What's the project?",
|
|
139
|
+
budget: "Roughly what budget do you have in mind?",
|
|
140
|
+
timing: "When would you like to start?",
|
|
141
|
+
suburb: "Which suburb is the job in?",
|
|
142
|
+
contact: "Where should we send your price range?"
|
|
143
|
+
};
|
|
144
|
+
var PulseEnquiry = class extends HTMLElement {
|
|
145
|
+
static observedAttributes = ["site-key"];
|
|
146
|
+
/** Injected in tests. */
|
|
147
|
+
client;
|
|
148
|
+
config;
|
|
149
|
+
mode = "loading";
|
|
150
|
+
root;
|
|
151
|
+
step = "project";
|
|
152
|
+
answers = {};
|
|
153
|
+
errors = {};
|
|
154
|
+
alert = "";
|
|
155
|
+
sending = false;
|
|
156
|
+
consent = false;
|
|
157
|
+
turnstileToken;
|
|
158
|
+
result;
|
|
159
|
+
started = false;
|
|
160
|
+
get siteKey() {
|
|
161
|
+
return this.getAttribute("site-key") ?? "";
|
|
162
|
+
}
|
|
163
|
+
get storeKey() {
|
|
164
|
+
return `pulse:form:${this.siteKey}`;
|
|
165
|
+
}
|
|
166
|
+
connectedCallback() {
|
|
167
|
+
if (!this.shadowRoot) {
|
|
168
|
+
this.root = this.attachShadow({ mode: "open" });
|
|
169
|
+
this.root.addEventListener("click", (e) => this.onClick(e));
|
|
170
|
+
this.root.addEventListener("submit", (e) => this.onSubmit(e));
|
|
171
|
+
this.root.addEventListener("input", (e) => this.onInput(e));
|
|
172
|
+
}
|
|
173
|
+
this.render();
|
|
174
|
+
if (!this.siteKey) return this.setMode("fallback");
|
|
175
|
+
if ("IntersectionObserver" in window && !this.hasAttribute("eager")) {
|
|
176
|
+
const io = new IntersectionObserver(
|
|
177
|
+
(entries) => {
|
|
178
|
+
if (entries.some((e) => e.isIntersecting)) {
|
|
179
|
+
io.disconnect();
|
|
180
|
+
void this.start();
|
|
181
|
+
}
|
|
182
|
+
},
|
|
183
|
+
{ rootMargin: "400px" }
|
|
184
|
+
);
|
|
185
|
+
io.observe(this);
|
|
186
|
+
} else queueMicrotask(() => void this.start());
|
|
187
|
+
}
|
|
188
|
+
async start() {
|
|
189
|
+
if (this.started) return;
|
|
190
|
+
this.started = true;
|
|
191
|
+
const client = this.client ??= createPulseClient(this.getAttribute("api-base") || DEFAULT_API_BASE);
|
|
192
|
+
try {
|
|
193
|
+
this.config = await client.getWidgetConfig(this.siteKey, { signal: AbortSignal.timeout(8e3) });
|
|
194
|
+
} catch (err) {
|
|
195
|
+
console.warn("[pulse] widget config unavailable, using the fallback form", err);
|
|
196
|
+
return this.setMode("fallback");
|
|
197
|
+
}
|
|
198
|
+
this.answers = this.restore();
|
|
199
|
+
const preset = new URL(location.href).searchParams.get("project");
|
|
200
|
+
if (preset && this.config.form.projects.some((p) => p.value === preset)) this.answers.project = preset;
|
|
201
|
+
this.step = this.steps().find((s) => !this.isAnswered(s)) ?? "contact";
|
|
202
|
+
this.setMode("widget");
|
|
203
|
+
}
|
|
204
|
+
setMode(m) {
|
|
205
|
+
this.mode = m;
|
|
206
|
+
this.dataset.state = m;
|
|
207
|
+
this.render();
|
|
208
|
+
}
|
|
209
|
+
// ---------- state ----------
|
|
210
|
+
steps() {
|
|
211
|
+
const f = this.config?.form;
|
|
212
|
+
const out = ["project"];
|
|
213
|
+
if (f?.budgets.length) out.push("budget");
|
|
214
|
+
if (f?.timings.length) out.push("timing");
|
|
215
|
+
out.push("suburb", "contact");
|
|
216
|
+
return out;
|
|
217
|
+
}
|
|
218
|
+
isAnswered(s) {
|
|
219
|
+
if (s === "contact") return false;
|
|
220
|
+
return this.answers[s] !== void 0;
|
|
221
|
+
}
|
|
222
|
+
restore() {
|
|
223
|
+
try {
|
|
224
|
+
return JSON.parse(localStorage.getItem(this.storeKey) ?? "{}");
|
|
225
|
+
} catch {
|
|
226
|
+
return {};
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
save() {
|
|
230
|
+
try {
|
|
231
|
+
localStorage.setItem(this.storeKey, JSON.stringify(this.answers));
|
|
232
|
+
} catch {
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
go(s, focus = true) {
|
|
236
|
+
this.step = s;
|
|
237
|
+
this.alert = "";
|
|
238
|
+
this.render();
|
|
239
|
+
if (focus) this.root.querySelector("h2")?.focus();
|
|
240
|
+
}
|
|
241
|
+
next() {
|
|
242
|
+
const steps = this.steps();
|
|
243
|
+
const i = steps.indexOf(this.step);
|
|
244
|
+
const after = steps.slice(i + 1).find((s) => !this.isAnswered(s));
|
|
245
|
+
this.go(after ?? "contact");
|
|
246
|
+
}
|
|
247
|
+
// ---------- events ----------
|
|
248
|
+
onClick(e) {
|
|
249
|
+
const t = e.target.closest("[data-action]");
|
|
250
|
+
if (!t || t.getRootNode() !== this.root) return;
|
|
251
|
+
const { action, value, step } = t.dataset;
|
|
252
|
+
if (action === "choose" && step) {
|
|
253
|
+
this.answers[step] = value ?? "";
|
|
254
|
+
this.save();
|
|
255
|
+
this.next();
|
|
256
|
+
} else if (action === "edit" && step) {
|
|
257
|
+
this.go(step);
|
|
258
|
+
} else if (action === "fallback") {
|
|
259
|
+
this.setMode("fallback");
|
|
260
|
+
this.querySelector("input, select, textarea")?.focus();
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
onInput(e) {
|
|
264
|
+
const el = e.target;
|
|
265
|
+
if (el.getRootNode() !== this.root) return;
|
|
266
|
+
if (el.name === "consent") this.consent = el.checked;
|
|
267
|
+
else if (["name", "email", "phone", "message", "suburb"].includes(el.name)) {
|
|
268
|
+
this.answers[el.name] = el.value;
|
|
269
|
+
this.save();
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
onSubmit(e) {
|
|
273
|
+
const form = e.target;
|
|
274
|
+
if (form.getRootNode() !== this.root) return;
|
|
275
|
+
e.preventDefault();
|
|
276
|
+
if (form.dataset.step === "suburb") {
|
|
277
|
+
this.answers.suburb = form.elements.namedItem("suburb").value.trim();
|
|
278
|
+
this.save();
|
|
279
|
+
return this.next();
|
|
280
|
+
}
|
|
281
|
+
if (form.dataset.step === "contact") void this.send(form);
|
|
282
|
+
}
|
|
283
|
+
validate() {
|
|
284
|
+
const a = this.answers;
|
|
285
|
+
const errs = {};
|
|
286
|
+
if (!a.name?.trim()) errs.name = "Enter your name.";
|
|
287
|
+
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(a.email?.trim() ?? "")) errs.email = "Enter an email address like name@example.com.";
|
|
288
|
+
if (a.phone?.trim() && !/^[+\d][\d\s()-]{7,}$/.test(a.phone.trim())) errs.phone = "Enter a phone number, or leave it blank.";
|
|
289
|
+
if (!this.consent) errs.consent = "Tick the box so we can use your details to reply.";
|
|
290
|
+
if (this.config?.turnstileSiteKey && !this.turnstileToken) errs.turnstile = "Please complete the quick check above the button.";
|
|
291
|
+
return errs;
|
|
292
|
+
}
|
|
293
|
+
async send(form) {
|
|
294
|
+
if (this.sending || !this.config) return;
|
|
295
|
+
this.errors = this.validate();
|
|
296
|
+
if (Object.keys(this.errors).length) {
|
|
297
|
+
this.alert = `Please fix ${Object.keys(this.errors).length === 1 ? "1 thing" : `${Object.keys(this.errors).length} things`} before sending.`;
|
|
298
|
+
this.render();
|
|
299
|
+
this.focusFirstError();
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
const a = this.answers;
|
|
303
|
+
const body = {
|
|
304
|
+
siteKey: this.siteKey,
|
|
305
|
+
project: a.project ?? "",
|
|
306
|
+
budget: a.budget || void 0,
|
|
307
|
+
timing: a.timing || void 0,
|
|
308
|
+
suburb: a.suburb || void 0,
|
|
309
|
+
name: a.name ?? "",
|
|
310
|
+
email: a.email ?? "",
|
|
311
|
+
phone: a.phone || void 0,
|
|
312
|
+
message: a.message || void 0,
|
|
313
|
+
consent: true,
|
|
314
|
+
page: location.pathname,
|
|
315
|
+
journey: readJourney(),
|
|
316
|
+
turnstileToken: this.turnstileToken,
|
|
317
|
+
company_website: form.elements.namedItem("company_website")?.value || void 0
|
|
318
|
+
};
|
|
319
|
+
this.sending = true;
|
|
320
|
+
this.alert = "";
|
|
321
|
+
this.render();
|
|
322
|
+
try {
|
|
323
|
+
this.result = await this.client.createEnquiry(body, { signal: AbortSignal.timeout(15e3) });
|
|
324
|
+
try {
|
|
325
|
+
localStorage.removeItem(this.storeKey);
|
|
326
|
+
} catch {
|
|
327
|
+
}
|
|
328
|
+
clearJourney();
|
|
329
|
+
this.sending = false;
|
|
330
|
+
this.setMode("done");
|
|
331
|
+
this.root.querySelector("h2")?.focus();
|
|
332
|
+
this.dispatchEvent(new CustomEvent("pulse:submitted", { detail: this.result, bubbles: true, composed: true }));
|
|
333
|
+
} catch (err) {
|
|
334
|
+
this.sending = false;
|
|
335
|
+
if (err instanceof PulseApiError && err.status === 422 && err.fields) {
|
|
336
|
+
this.errors = err.fields;
|
|
337
|
+
const early = this.steps().find((s) => s !== "contact" && err.fields[s]);
|
|
338
|
+
if (early) {
|
|
339
|
+
delete this.answers[early];
|
|
340
|
+
this.go(early);
|
|
341
|
+
this.alert = err.fields[early];
|
|
342
|
+
this.render();
|
|
343
|
+
return;
|
|
344
|
+
}
|
|
345
|
+
this.alert = "Please check the highlighted fields.";
|
|
346
|
+
} else {
|
|
347
|
+
this.alert = "fail";
|
|
348
|
+
window.turnstile?.reset();
|
|
349
|
+
this.turnstileToken = void 0;
|
|
350
|
+
}
|
|
351
|
+
this.render();
|
|
352
|
+
this.focusFirstError();
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
focusFirstError() {
|
|
356
|
+
const first = Object.keys(this.errors)[0];
|
|
357
|
+
const el = first && this.root.querySelector(`[name="${first}"]`);
|
|
358
|
+
(el || this.root.querySelector(".alert"))?.focus();
|
|
359
|
+
}
|
|
360
|
+
// ---------- Turnstile (light-DOM slot: its iframe must not live in our shadow root) ----------
|
|
361
|
+
mountTurnstile() {
|
|
362
|
+
const sitekey = this.config?.turnstileSiteKey;
|
|
363
|
+
if (!sitekey || this.querySelector('[slot="turnstile"]')) return;
|
|
364
|
+
const host = document.createElement("div");
|
|
365
|
+
host.slot = "turnstile";
|
|
366
|
+
this.append(host);
|
|
367
|
+
const render = () => window.turnstile?.render(host, {
|
|
368
|
+
sitekey,
|
|
369
|
+
callback: (t) => this.turnstileToken = t,
|
|
370
|
+
"expired-callback": () => this.turnstileToken = void 0
|
|
371
|
+
});
|
|
372
|
+
if (window.turnstile) return void render();
|
|
373
|
+
const s = document.createElement("script");
|
|
374
|
+
s.src = "https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit";
|
|
375
|
+
s.async = true;
|
|
376
|
+
s.onload = render;
|
|
377
|
+
document.head.append(s);
|
|
378
|
+
}
|
|
379
|
+
// ---------- rendering ----------
|
|
380
|
+
render() {
|
|
381
|
+
if (!this.root) return;
|
|
382
|
+
const showSlot = this.mode === "loading" || this.mode === "fallback";
|
|
383
|
+
const body = this.mode === "widget" ? this.renderStep() : this.mode === "done" ? this.renderDone() : "";
|
|
384
|
+
this.root.innerHTML = `<style>${css}</style>${body}<div ${showSlot ? "" : "hidden"}><slot></slot></div>`;
|
|
385
|
+
if (this.mode === "widget" && this.step === "contact") this.mountTurnstile();
|
|
386
|
+
}
|
|
387
|
+
label(step) {
|
|
388
|
+
const v = this.answers[step];
|
|
389
|
+
if (step === "project") return this.config?.form.projects.find((p) => p.value === v)?.label ?? v;
|
|
390
|
+
return v || "Skipped";
|
|
391
|
+
}
|
|
392
|
+
renderStep() {
|
|
393
|
+
const steps = this.steps();
|
|
394
|
+
const idx = steps.indexOf(this.step);
|
|
395
|
+
const done = steps.filter((s) => s !== this.step && this.isAnswered(s));
|
|
396
|
+
const chips = done.length ? `<ul class="chips" aria-label="Your answers">${done.map((s) => `<li><button type="button" class="chip" data-action="edit" data-step="${s}" aria-label="${esc(`${QUESTIONS[s]} ${this.label(s)}. Edit`)}">${esc(this.label(s))}</button></li>`).join("")}</ul>` : "";
|
|
397
|
+
const dots = steps.map((_, i) => `<span class="dot"${i <= idx ? " data-on" : ""}></span>`).join("");
|
|
398
|
+
const top = `<div class="top"><span aria-live="polite">${idx + 1} of ${steps.length}</span><span class="dots" aria-hidden="true">${dots}</span></div>`;
|
|
399
|
+
const alert = this.alert && this.alert !== "fail" ? `<p class="alert bad" role="alert" tabindex="-1">${esc(this.alert)}</p>` : "";
|
|
400
|
+
return `<section class="card" aria-label="Get a price range">${top}${chips}<div class="step">${alert}${this.stepBody(this.step)}</div></section>`;
|
|
401
|
+
}
|
|
402
|
+
choices(step, items, skip) {
|
|
403
|
+
const cur = this.answers[step];
|
|
404
|
+
const opts = items.map((o) => `<li><button type="button" class="opt" data-action="choose" data-step="${step}" data-value="${esc(o.value)}" aria-pressed="${cur === o.value}">${esc(o.label)}</button></li>`).join("");
|
|
405
|
+
const skipBtn = skip ? `<div class="actions"><button type="button" class="link" data-action="choose" data-step="${step}" data-value="">Skip this question</button></div>` : "";
|
|
406
|
+
return `<h2 tabindex="-1" id="q">${esc(QUESTIONS[step])}</h2><ul class="options" aria-labelledby="q">${opts}</ul>${skipBtn}`;
|
|
407
|
+
}
|
|
408
|
+
stepBody(step) {
|
|
409
|
+
const f = this.config.form;
|
|
410
|
+
if (step === "project") return this.choices("project", f.projects, false);
|
|
411
|
+
if (step === "budget") return this.choices("budget", f.budgets.map((b) => ({ value: b, label: b })), true);
|
|
412
|
+
if (step === "timing") return this.choices("timing", f.timings.map((b) => ({ value: b, label: b })), true);
|
|
413
|
+
if (step === "suburb")
|
|
414
|
+
return `<form data-step="suburb" novalidate><h2 tabindex="-1">${esc(QUESTIONS.suburb)}</h2><div class="field"><label for="suburb">Suburb</label><input type="text" id="suburb" name="suburb" autocomplete="address-level2" enterkeyhint="next" value="${esc(this.answers.suburb ?? "")}" aria-describedby="suburb-hint">${f.reassurance ? `<p class="hint" id="suburb-hint">${esc(f.reassurance)}</p>` : `<p class="hint" id="suburb-hint">Optional.</p>`}</div><div class="actions"><button class="btn" type="submit">Next</button></div></form>`;
|
|
415
|
+
return this.contactBody();
|
|
416
|
+
}
|
|
417
|
+
estimateHtml() {
|
|
418
|
+
const p = this.config.form.projects.find((o) => o.value === this.answers.project);
|
|
419
|
+
if (!p || p.priceMin == null || p.priceMax == null) return "";
|
|
420
|
+
return `<p class="alert ok estimate">Ballpark for a ${esc(p.label.toLowerCase())}<strong>${money(p.priceMin)} to ${money(p.priceMax)}</strong><span class="hint">Based on recent jobs. We firm it up once we have seen the space.</span></p>`;
|
|
421
|
+
}
|
|
422
|
+
field(name, label, type, auto, extra = "") {
|
|
423
|
+
const err = this.errors[name];
|
|
424
|
+
const hint = name === "phone" ? `<p class="hint" id="phone-hint">Optional. Handy if you would rather we call.</p>` : "";
|
|
425
|
+
const desc = [name === "phone" ? "phone-hint" : "", err ? `${name}-error` : ""].filter(Boolean).join(" ");
|
|
426
|
+
return `<div class="field"><label for="${name}">${label}${name === "phone" ? "" : ` <span aria-hidden="true">*</span>`}</label><input type="${type}" id="${name}" name="${name}" autocomplete="${auto}" ${extra} value="${esc(this.answers[name] ?? "")}" ${name === "phone" ? "" : "required"} ${err ? 'aria-invalid="true"' : ""} ${desc ? `aria-describedby="${desc}"` : ""}>${hint}${err ? `<p class="error" id="${name}-error">${esc(err)}</p>` : ""}</div>`;
|
|
427
|
+
}
|
|
428
|
+
contactBody() {
|
|
429
|
+
const c = this.config;
|
|
430
|
+
const err = this.errors;
|
|
431
|
+
const fail = this.alert === "fail" ? `<div class="alert bad" role="alert" tabindex="-1">Sorry, that did not send. Please try again, or <button type="button" class="link" data-action="fallback">use the simple form</button>.</div>` : "";
|
|
432
|
+
return `<form data-step="contact" novalidate>${fail}<h2 tabindex="-1">${esc(QUESTIONS.contact)}</h2>${this.estimateHtml()}
|
|
433
|
+
<div class="row">${this.field("name", "Your name", "text", "name", 'enterkeyhint="next"')}${this.field("email", "Email", "email", "email", 'inputmode="email" enterkeyhint="next"')}</div>
|
|
434
|
+
${this.field("phone", "Phone", "tel", "tel", 'inputmode="tel" enterkeyhint="next"')}
|
|
435
|
+
<div class="field"><label for="message">Anything else we should know?</label><textarea id="message" name="message" rows="3" aria-describedby="message-hint">${esc(this.answers.message ?? "")}</textarea><p class="hint" id="message-hint">Optional. Size of the room, what you want to change.</p></div>
|
|
436
|
+
<div class="hp" aria-hidden="true"><label for="company_website">Leave this empty</label><input type="text" id="company_website" name="company_website" tabindex="-1" autocomplete="off"></div>
|
|
437
|
+
<div class="field"><div class="check"><input type="checkbox" id="consent" name="consent" ${this.consent ? "checked" : ""} required ${err.consent ? 'aria-invalid="true"' : ""} aria-describedby="consent-text${err.consent ? " consent-error" : ""}"><label for="consent" id="consent-text">${esc(c.consentText)} <a href="${esc(/^https?:\/\//.test(c.privacyUrl) ? c.privacyUrl : "#")}">Read our privacy policy</a>.</label></div>${err.consent ? `<p class="error" id="consent-error">${esc(err.consent)}</p>` : ""}</div>
|
|
438
|
+
${c.turnstileSiteKey ? `<div class="field"><slot name="turnstile"></slot>${err.turnstile ? `<p class="error">${esc(err.turnstile)}</p>` : ""}</div>` : ""}
|
|
439
|
+
<div class="actions"><button class="btn" type="submit" ${this.sending ? "disabled" : ""}>${this.sending ? "Sending\u2026" : "Send my enquiry"}</button></div></form>`;
|
|
440
|
+
}
|
|
441
|
+
renderDone() {
|
|
442
|
+
const t = this.config?.form.thanks;
|
|
443
|
+
const est = this.result?.estimate;
|
|
444
|
+
return `<section class="card" aria-label="Enquiry sent"><div class="step"><h2 tabindex="-1">${esc(t?.title ?? "Thanks, we have your enquiry")}</h2>${est ? `<p class="alert ok estimate">Your ballpark<strong>${money(est.min)} to ${money(est.max)}</strong></p>` : ""}<p>${esc(t?.body ?? "We will be in touch within one business day. Check your inbox for a copy.")}</p></div></section>`;
|
|
445
|
+
}
|
|
446
|
+
};
|
|
447
|
+
function definePulseEnquiry(registry = customElements) {
|
|
448
|
+
if (!registry.get(TAG_NAME)) registry.define(TAG_NAME, PulseEnquiry);
|
|
449
|
+
}
|
|
450
|
+
export {
|
|
451
|
+
DEFAULT_API_BASE,
|
|
452
|
+
JOURNEY_KEY,
|
|
453
|
+
PulseEnquiry,
|
|
454
|
+
TAG_NAME,
|
|
455
|
+
clearJourney,
|
|
456
|
+
definePulseEnquiry,
|
|
457
|
+
readJourney,
|
|
458
|
+
trackJourney
|
|
459
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,48 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rebirth-wd/pulse-widget",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "<pulse-enquiry>: the Rebirth Pulse enquiry widget. Custom element with an open Shadow DOM that upgrades a site's own fallback form.",
|
|
5
|
+
"license": "UNLICENSED",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": {
|
|
9
|
+
"types": "./dist/index.d.ts",
|
|
10
|
+
"import": "./dist/index.js"
|
|
11
|
+
},
|
|
12
|
+
"./package.json": "./package.json"
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"dist",
|
|
16
|
+
"README.md",
|
|
17
|
+
"CHANGELOG.md"
|
|
18
|
+
],
|
|
19
|
+
"dependencies": {
|
|
20
|
+
"@rebirth-wd/shared": "^0.1.0"
|
|
21
|
+
},
|
|
22
|
+
"devDependencies": {
|
|
23
|
+
"eslint": "^10.16.0",
|
|
24
|
+
"typescript": "~6.0.3",
|
|
25
|
+
"vitest": "^5.1.2",
|
|
26
|
+
"happy-dom": "^21.0.4",
|
|
27
|
+
"tsup": "^9.0.0",
|
|
28
|
+
"@rebirth-wd/eslint-config": "0.0.0",
|
|
29
|
+
"@rebirth-wd/tsconfig": "0.0.0"
|
|
30
|
+
},
|
|
31
|
+
"repository": {
|
|
32
|
+
"type": "git",
|
|
33
|
+
"url": "git+https://github.com/rebirth-wd/rebirth-pulse.git",
|
|
34
|
+
"directory": "packages/widget"
|
|
35
|
+
},
|
|
36
|
+
"homepage": "https://github.com/rebirth-wd/rebirth-pulse/tree/main/packages/widget#readme",
|
|
37
|
+
"sideEffects": false,
|
|
38
|
+
"publishConfig": {
|
|
39
|
+
"access": "public",
|
|
40
|
+
"provenance": true
|
|
41
|
+
},
|
|
42
|
+
"scripts": {
|
|
43
|
+
"build": "tsup",
|
|
44
|
+
"lint": "eslint .",
|
|
45
|
+
"typecheck": "tsc -p tsconfig.json",
|
|
46
|
+
"test": "vitest run"
|
|
47
|
+
}
|
|
6
48
|
}
|