@daybook/feedback 1.1.1 → 1.2.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/README.md CHANGED
@@ -119,6 +119,13 @@ permits: it cannot grant anyone access to anything.
119
119
  `localhost` is an origin like any other. Put it on the **development** environment and you are
120
120
  working in a minute.
121
121
 
122
+ **Or let your assistant do all of it.** If you have Daybook connected as an MCP server in the
123
+ project you are adding the widget to, `get_feedback_install` returns the package, the snippet for
124
+ your framework, the components you can file against, and — most usefully — a `blockers` list saying
125
+ what is still unconfigured. `allow_feedback_domain` and `create_feedback_key` do the two steps that
126
+ need doing. That path exists because the SDK fails quietly by design: without it an assistant sets
127
+ everything up, sees no error, and has no way to tell a working install from a silent one.
128
+
122
129
  On a domain that is not listed, the handshake returns `403 origin_not_allowed` and the widget quietly
123
130
  does not appear — which is also what it does on a revoked key and on a dead network. A feedback
124
131
  button must never break the page it is on.
@@ -218,8 +225,29 @@ three days later when the reporter has moved on.
218
225
  - **Page and device** — route, title, referrer, locale, timezone, viewport with DPR, and a readable
219
226
  browser and OS rather than a raw user-agent string.
220
227
  - **Breadcrumbs** — the last 40 navigations, clicks, console errors and failed or slow requests.
221
- - **A screenshot**, if you leave `screenshots` on and the reporter consents to the browser's share
222
- prompt.
228
+ - **A screenshot**, if the reporter ticks "Capture the screen" and consents to the browser's share
229
+ prompt. The widget hides itself for the frame, so the picture is of the page underneath rather
230
+ than of the form that was just filled in.
231
+
232
+ `screenshots` decides what the composer offers, and takes three values:
233
+
234
+ | Value | The composer |
235
+ |---|---|
236
+ | `true` (default) | offers the capture, ticked |
237
+ | `'optional'` | offers the capture, not ticked |
238
+ | `false` | does not offer it at all |
239
+
240
+ There is no setting that shows the control and then ignores it. A tick box that does nothing is
241
+ worse than no tick box.
242
+
243
+ ## Moving the panel
244
+
245
+ The composer is dragged by its header and pins to whichever side it is let go near; a double-click
246
+ on the header puts it back. Where it was left is remembered, so the next report opens there.
247
+
248
+ It closes on the cross or on Cancel, and on nothing else — not Escape, not a click on the page
249
+ behind it. Every one of those gestures gets pressed while a report is being written, and each of
250
+ them used to throw the words away.
223
251
 
224
252
  ## Redaction
225
253
 
package/dist/client.d.ts CHANGED
@@ -27,7 +27,7 @@ export declare class IngestClient {
27
27
  private session;
28
28
  constructor(apiUrl: string, ingestKey: string);
29
29
  setSession(token: string | null): void;
30
- send(request: IngestRequest, uploads?: Upload[]): Promise<IngestResponse>;
30
+ send(request: IngestRequest, uploads?: Upload[], onUploadFailed?: (upload: Upload, error: unknown) => void): Promise<IngestResponse>;
31
31
  /**
32
32
  * Sends anything left from a previous visit. Called on start, so a report written offline yesterday
33
33
  * arrives today without the reporter doing anything.
@@ -49,6 +49,19 @@ export declare class IngestClient {
49
49
  /** Held in memory only, and only long enough to reach the next handshake. */
50
50
  private identityToken;
51
51
  private base;
52
+ /**
53
+ * Where the bytes actually go, given where the server said they go.
54
+ *
55
+ * The server builds the ticket URL from the host it was called on, and behind a TLS-terminating
56
+ * proxy it does not know it is being served over https — so the ticket came back as
57
+ * `http://api.daybook.team/...`, which a page on https will not fetch at all. The path is the
58
+ * part the server is authoritative about; the origin is the one WE know, because the host handed
59
+ * it to init(). So a ticket pointing at our own host is re-based onto it, scheme included.
60
+ *
61
+ * A ticket for some other host is left alone — that is a deployment doing something deliberate,
62
+ * and rewriting it would send the bytes somewhere they were not meant to go.
63
+ */
64
+ private resolve;
52
65
  /**
53
66
  * Asks who may report from here, what they may send, and what it should look like.
54
67
  *
package/dist/client.js CHANGED
@@ -27,7 +27,7 @@ export class IngestClient {
27
27
  setSession(token) {
28
28
  this.session = token;
29
29
  }
30
- async send(request, uploads = []) {
30
+ async send(request, uploads = [], onUploadFailed) {
31
31
  const payload = {
32
32
  // Generated here rather than by the caller, so every report is retry-safe whether or not the
33
33
  // host app remembered.
@@ -48,11 +48,31 @@ export class IngestClient {
48
48
  const result = await response.json();
49
49
  // Bytes go through the API, which is what makes this work from a customer's own domain at all:
50
50
  // a presigned storage URL would need that bucket to allow their origin. A failed upload does not
51
- // fail the report — the words are the valuable part and they are already saved. Tickets come
52
- // back in the order the declarations were sent, so they pair up by index.
53
- await Promise.all(uploads.map((upload, index) => {
54
- const ticket = result.attachments[index];
55
- return ticket ? this.upload(ticket, upload).catch(() => { }) : Promise.resolve();
51
+ // fail the report — the words are the valuable part and they are already saved.
52
+ //
53
+ // Paired on the ticket's own index, not on position in this array. The server SKIPS a
54
+ // declaration it will not accept, so the ticket list can be shorter than the upload list — and
55
+ // pairing by position then PUTs the second file's bytes at the first file's ticket, which
56
+ // uploads the wrong image and then fails the type check on it.
57
+ const offset = (request.attachments ?? []).length;
58
+ await Promise.all(uploads.map(async (upload, index) => {
59
+ const ticket = ticketFor(result, offset + index);
60
+ // No ticket means the server refused the declaration outright — an extension it does not
61
+ // know, or bytes over the cap. Reported the same way a failed PUT is, because from the
62
+ // reporter's side both are "my screenshot did not arrive".
63
+ if (!ticket) {
64
+ onUploadFailed?.(upload, new Error('The server would not accept that file.'));
65
+ return;
66
+ }
67
+ try {
68
+ await this.upload(ticket, upload);
69
+ }
70
+ catch (error) {
71
+ // Told, not swallowed. This used to be `.catch(() => {})`, so an upload that failed for
72
+ // every report on the deployment — a mixed-content ticket URL, as it turned out — showed
73
+ // the reporter a cheerful confirmation and left triage with an empty attachment row.
74
+ onUploadFailed?.(upload, error);
75
+ }
56
76
  }));
57
77
  return result;
58
78
  }
@@ -151,6 +171,30 @@ export class IngestClient {
151
171
  base() {
152
172
  return this.apiUrl.replace(/\/$/, '');
153
173
  }
174
+ /**
175
+ * Where the bytes actually go, given where the server said they go.
176
+ *
177
+ * The server builds the ticket URL from the host it was called on, and behind a TLS-terminating
178
+ * proxy it does not know it is being served over https — so the ticket came back as
179
+ * `http://api.daybook.team/...`, which a page on https will not fetch at all. The path is the
180
+ * part the server is authoritative about; the origin is the one WE know, because the host handed
181
+ * it to init(). So a ticket pointing at our own host is re-based onto it, scheme included.
182
+ *
183
+ * A ticket for some other host is left alone — that is a deployment doing something deliberate,
184
+ * and rewriting it would send the bytes somewhere they were not meant to go.
185
+ */
186
+ resolve(url) {
187
+ try {
188
+ const base = new URL(this.base());
189
+ const target = new URL(url, base);
190
+ return target.hostname === base.hostname
191
+ ? new URL(target.pathname + target.search, base).toString()
192
+ : target.toString();
193
+ }
194
+ catch {
195
+ return url;
196
+ }
197
+ }
154
198
  /**
155
199
  * Asks who may report from here, what they may send, and what it should look like.
156
200
  *
@@ -187,7 +231,7 @@ export class IngestClient {
187
231
  });
188
232
  }
189
233
  async upload(ticket, upload) {
190
- const response = await fetch(ticket.uploadUrl, {
234
+ const response = await fetch(this.resolve(ticket.uploadUrl), {
191
235
  method: ticket.method,
192
236
  headers: {
193
237
  'Content-Type': ticket.contentType,
@@ -205,6 +249,18 @@ export class IngestClient {
205
249
  await this.post(`/ingest/v1/attachments/${ticket.id}/confirm`, {});
206
250
  }
207
251
  }
252
+ /**
253
+ * The ticket for one declaration, by the index the server put on it.
254
+ *
255
+ * Falls back to position for a server that predates the field, which is what an SDK talking to an
256
+ * older self-hosted install will find.
257
+ */
258
+ function ticketFor(result, index) {
259
+ const byIndex = result.attachments.find(a => a.index === index);
260
+ return byIndex ?? (result.attachments.some(a => typeof a.index === 'number')
261
+ ? undefined
262
+ : result.attachments[index]);
263
+ }
208
264
  function enqueue(request) {
209
265
  const queue = readQueue();
210
266
  queue.push(request);
package/dist/feedback.js CHANGED
@@ -1,12 +1,19 @@
1
- "use strict";var DaybookFeedback=(()=>{var I=Object.defineProperty;var ae=Object.getOwnPropertyDescriptor;var ce=Object.getOwnPropertyNames;var le=Object.prototype.hasOwnProperty;var de=(n,e)=>{for(var t in e)I(n,t,{get:e[t],enumerable:!0})},pe=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ce(e))!le.call(n,o)&&o!==t&&I(n,o,{get:()=>e[o],enumerable:!(r=ae(e,o))||r.enumerable});return n};var he=n=>pe(I({},"__esModule",{value:!0}),n);var _e={};de(_e,{DEFAULT_API_URL:()=>se,DaybookFeedback:()=>$,captureAnchor:()=>L,init:()=>Le,resolveAnchor:()=>te});function g(n){var e;try{let t=new URL(n,location.href);return t.origin===location.origin?t.pathname:`${t.origin}${t.pathname}`}catch{return(e=n.split("?")[0])!=null?e:n}}function M(n){var r,o,i,a,s,c;let e=n.tagName.toLowerCase();if(!n.getAttribute("aria-label")&&!n.getAttribute("data-testid")&&!((r=n.textContent)!=null?r:"").trim()){let d=n.closest("button, a, [role=button], [data-testid], label");if(d&&d!==n)return M(d)}if(n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement||n instanceof HTMLSelectElement){let d=(i=(o=n.getAttribute("name"))!=null?o:n.id)!=null?i:"",p=n instanceof HTMLInputElement?n.type:e;return`${e}[${p}]${d?` name=${d}`:""}`}let t=(c=(a=n.getAttribute("aria-label"))!=null?a:n.getAttribute("data-testid"))!=null?c:((s=n.textContent)!=null?s:"").replace(/\s+/g," ").trim().slice(0,40);return t?`${e} "${t}"`:e}function X(n){return n.replace(/[\w.+-]+@[\w-]+\.[\w.]+/g,"[email]").replace(/\b[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/g,"[jwt]").replace(/\bBearer\s+[\w.-]+/gi,"Bearer [redacted]").replace(/\b\d{12,19}\b/g,"[number]").slice(0,500)}var W="data-daybook-private";var x=class{constructor(e=40,t=!0){this.limit=e;this.redact=t;this.entries=[];this.detach=[]}list(){return[...this.entries]}add(e,t){for(this.entries.push({at:new Date().toISOString(),type:e,message:this.redact?X(t):t.slice(0,500)});this.entries.length>this.limit;)this.entries.shift()}start(){let e=s=>{let c=s.target;c instanceof Element&&(c.closest("[data-daybook-feedback]")||this.add("click",M(c)))};document.addEventListener("click",e,{capture:!0,passive:!0}),this.detach.push(()=>document.removeEventListener("click",e,{capture:!0}));let t=history.pushState,r=history.replaceState,o=()=>this.add("nav",g(location.href));history.pushState=(...s)=>{t.apply(history,s),o()},history.replaceState=(...s)=>{r.apply(history,s),o()},window.addEventListener("popstate",o),this.detach.push(()=>{history.pushState=t,history.replaceState=r,window.removeEventListener("popstate",o)});for(let s of["error","warn"]){let c=console[s];console[s]=(...d)=>{this.add("console",`${s}: ${d.map(C).join(" ")}`),c.apply(console,d)},this.detach.push(()=>{console[s]=c})}let i=s=>this.add("console",`uncaught: ${s.message}`),a=s=>this.add("console",`unhandled rejection: ${C(s.reason)}`);window.addEventListener("error",i),window.addEventListener("unhandledrejection",a),this.detach.push(()=>{window.removeEventListener("error",i),window.removeEventListener("unhandledrejection",a)}),this.watchFetch()}stop(){for(let e of this.detach.splice(0))e()}watchFetch(){if(typeof window.fetch!="function")return;let e=window.fetch;window.fetch=async(...t)=>{let r=performance.now();try{let o=await e.apply(window,t),i=Math.round(performance.now()-r);return(!o.ok||i>3e3)&&this.add("network",`${o.status} ${g(V(t[0]))} ${i}ms`),o}catch(o){throw this.add("network",`failed ${g(V(t[0]))}: ${C(o)}`),o}},this.detach.push(()=>{window.fetch=e})}};function V(n){return typeof n=="string"?n:n instanceof URL?n.href:n.url}function C(n){var e,t;if(typeof n=="string")return n;if(n instanceof Error)return`${n.name}: ${n.message}`;try{return(t=(e=JSON.stringify(n))==null?void 0:e.slice(0,200))!=null?t:String(n)}catch{return String(n)}}var H="pm.feedback.queue";var E=class{constructor(e,t){this.apiUrl=e;this.ingestKey=t;this.session=null;this.identityToken=null}setSession(e){this.session=e}async send(e,t=[]){var a,s;let r={idempotencyKey:(a=e.idempotencyKey)!=null?a:Y(),...e,attachments:[...(s=e.attachments)!=null?s:[],...t.map(c=>({filename:c.filename,contentType:c.contentType,size:c.blob.size}))]},o=await this.post("/ingest/v1",r);if(!o.ok)throw await k(o);let i=await o.json();return await Promise.all(t.map((c,d)=>{let p=i.attachments[d];return p?this.upload(p,c).catch(()=>{}):Promise.resolve()})),i}async flush(){let e=Q();if(e.length!==0){Z([]);for(let t of e)try{let r=await this.post("/ingest/v1",t);!r.ok&&(r.status===429||r.status>=500)&&F(t)}catch{F(t)}}}queue(e){var t;F({...e,idempotencyKey:(t=e.idempotencyKey)!=null?t:Y(),attachments:void 0})}async signIn(){let e=J(64),t=await ue(e),r=J(16),o=`${this.base()}/ingest/v1/authorize?key=${encodeURIComponent(this.ingestKey)}&origin=${encodeURIComponent(location.origin)}&code_challenge=${encodeURIComponent(t)}&state=${encodeURIComponent(r)}`,i=window.open(o,"daybook-feedback","width=460,height=640");if(!i)throw Object.assign(new Error("Popup blocked"),{code:"popup_blocked"});let a=await new Promise((d,p)=>{let b=setInterval(()=>{i.closed&&(w(),p(Object.assign(new Error("Sign-in cancelled"),{code:"cancelled"})))},400),y=m=>{if(m.origin!==new URL(this.base()).origin)return;let h=m.data;if((h==null?void 0:h.source)==="daybook-feedback"&&h.state===r){if(w(),h.error||!h.code){p(Object.assign(new Error("Sign-in was refused"),{code:h.error||"refused"}));return}d(h.code)}},w=()=>{clearInterval(b),window.removeEventListener("message",y)};window.addEventListener("message",y)}),s=await this.post("/ingest/v1/token",{code:a,codeVerifier:e});if(!s.ok)throw await k(s);let{identityToken:c}=await s.json();return this.identityToken=c,c}base(){return this.apiUrl.replace(/\/$/,"")}async handshake(e){var o,i;let t=await this.post("/ingest/v1/session",{...e,identityToken:(o=this.identityToken)!=null?o:void 0});if(!t.ok)throw await k(t);let r=await t.json();return this.session=(i=r.sessionToken)!=null?i:null,r}post(e,t){let r={"Content-Type":"application/json","X-Ingest-Key":this.ingestKey};return this.session&&(r["X-Feedback-Session"]=this.session),fetch(`${this.base()}${e}`,{method:"POST",headers:r,body:JSON.stringify(t),credentials:"omit"})}async upload(e,t){let r=await fetch(e.uploadUrl,{method:e.method,headers:{"Content-Type":e.contentType,"X-Ingest-Key":this.ingestKey},body:t.blob,credentials:"omit"});if(!r.ok)throw await k(r);await this.post(`/ingest/v1/attachments/${e.id}/confirm`,{})}};function F(n){let e=Q();e.push(n),Z(e.slice(-20))}function Q(){try{let n=localStorage.getItem(H);return n?JSON.parse(n):[]}catch{return[]}}function Z(n){try{n.length===0?localStorage.removeItem(H):localStorage.setItem(H,JSON.stringify(n))}catch{}}async function k(n){let e=`http_${n.status}`;try{let t=await n.json();if(t.code&&(e=t.code),t.message)return Object.assign(new Error(t.message),{code:e})}catch{}return Object.assign(new Error(`Ingest failed (${n.status})`),{code:e})}function Y(){return typeof crypto!="undefined"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function J(n){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",t=new Uint8Array(n);return crypto.getRandomValues(t),Array.from(t,r=>e[r%e.length]).join("")}async function ue(n){let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function U(n){var t;let e={platform:"web",route:location.pathname,title:document.title.slice(0,200),locale:navigator.language,timezone:me(),viewport:{width:window.innerWidth,height:window.innerHeight,dpr:(t=window.devicePixelRatio)!=null?t:1},device:fe()};return document.referrer&&(e.referrer=g(document.referrer)),n.app&&(e.app=n.app),n.anchor&&(e.anchor=n.anchor),n.breadcrumbs&&n.breadcrumbs.length>0&&(e.breadcrumbs=n.breadcrumbs),e}function fe(){var o;let n=navigator.userAgent,e=/Edg\//.test(n)?"Edge":/OPR\//.test(n)?"Opera":/Firefox\//.test(n)?"Firefox":/Chrome\//.test(n)?"Chrome":/Safari\//.test(n)?"Safari":"Unknown",t=/Windows NT/.test(n)?"Windows":/iPhone|iPad|iPod/.test(n)?"iOS":/Mac OS X/.test(n)?"macOS":/Android/.test(n)?"Android":/Linux/.test(n)?"Linux":"Unknown",r=(o=n.match(/(?:Edg|OPR|Firefox|Chrome|Version)\/(\d+)/))==null?void 0:o[1];return{browser:r?`${e} ${r}`:e,os:t,touch:navigator.maxTouchPoints>0,userAgent:n.slice(0,300)}}function me(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return`UTC${-new Date().getTimezoneOffset()/60}`}}async function G(n){var r;if(typeof((r=navigator.mediaDevices)==null?void 0:r.getDisplayMedia)!="function")return null;let e=n?be():()=>{},t=null;try{if(t=await navigator.mediaDevices.getDisplayMedia({video:!0,audio:!1,preferCurrentTab:!0}),!t.getVideoTracks()[0])return null;await new Promise(a=>setTimeout(a,250));let i=await ge(t);return i?{blob:i,filename:"screenshot.png",contentType:"image/png"}:null}catch{return null}finally{t==null||t.getTracks().forEach(o=>o.stop()),e()}}async function ge(n){let e=document.createElement("video");e.srcObject=n,e.muted=!0,await e.play().catch(()=>{});let t=document.createElement("canvas");t.width=e.videoWidth||window.innerWidth,t.height=e.videoHeight||window.innerHeight;let r=t.getContext("2d");return r?(r.drawImage(e,0,0,t.width,t.height),e.pause(),e.srcObject=null,new Promise(o=>t.toBlob(i=>o(i),"image/png"))):null}function be(){let n=[...document.querySelectorAll(`[${W}]`),...document.querySelectorAll('input[type="password"]')],e=n.map(t=>t.style.filter);return n.forEach(t=>{t.style.filter="blur(12px)"}),()=>{n.forEach((t,r)=>{var o;t.style.filter=(o=e[r])!=null?o:""})}}function L(n,e){let t=document.elementFromPoint(n,e);if(!(t instanceof HTMLElement))return{selector:null,offsetX:S(n/window.innerWidth),offsetY:S(e/window.innerHeight),elementText:null};let r=t.getBoundingClientRect();return{selector:ye(t),offsetX:r.width>0?S((n-r.left)/r.width):0,offsetY:r.height>0?S((e-r.top)/r.height):0,elementText:we(t)}}function te(n){if(!n.selector)return{x:n.offsetX*window.innerWidth,y:n.offsetY*window.innerHeight};let e=null;try{e=document.querySelector(n.selector)}catch{return null}if(!e)return null;let t=e.getBoundingClientRect();return{x:t.left+n.offsetX*t.width,y:t.top+n.offsetY*t.height}}function ye(n){if(n===document.body)return"body";for(let o of["data-testid","data-test","data-daybook-id","data-cy"]){let i=n.getAttribute(o);if(i){let a=`[${o}="${P(i)}"]`;if(T(a))return a}}if(n.id&&!ee(n.id)){let o=`#${P(n.id)}`;if(T(o))return o}let e=[],t=n;for(;t&&t!==document.body&&e.length<8;){let o=t.tagName.toLowerCase(),i=Array.from(t.classList).filter(c=>!ee(c)).slice(0,2);i.length>0&&(o+=i.map(c=>`.${P(c)}`).join(""));let a=t.parentElement;if(a){let c=Array.from(a.children).filter(d=>d.tagName===t.tagName);c.length>1&&(o+=`:nth-of-type(${c.indexOf(t)+1})`)}e.unshift(o);let s=e.join(" > ");if(T(s))return s;t=a}let r=e.length>0?`body > ${e.join(" > ")}`:null;return r&&T(r)?r:null}function T(n){try{return document.querySelectorAll(n).length===1}catch{return!1}}function ee(n){return/^[a-z]{1,3}[0-9a-f]{5,}$/i.test(n)||/--[0-9a-f]{5,}$/i.test(n)||/^_[0-9a-z]{5,}/i.test(n)||/^v-[0-9a-f]{6,}$/i.test(n)||/^ng-/.test(n)||/[0-9a-f]{8,}/i.test(n)}function we(n){var r,o,i;let t=((o=(r=n.innerText)!=null?r:n.textContent)!=null?o:"").replace(/\s+/g," ").trim();if(!t){let a=(i=n.getAttribute("aria-label"))!=null?i:n.getAttribute("title");return(a==null?void 0:a.trim())||null}return t.length>80?`${t.slice(0,77)}\u2026`:t}function S(n){return Number.isFinite(n)?Math.max(0,Math.min(1,n)):0}function P(n){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(n):n.replace(/([^\w-])/g,"\\$1")}var ve=/^(image\/(png|jpeg|gif|webp)|video\/(mp4|quicktime|webm))$/;function ne(n,e){let t=[];for(let r of n){if(e+t.length>=5)break;let o=ve.test(r.type)?r.size>26214400?`Too large (${(r.size/1048576).toFixed(1)} MB, max 25).`:null:"Only images and short videos.";t.push({blob:r,filename:r.name||`pasted-${t.length+1}.${xe(r.type)}`,contentType:r.type,preview:o?null:URL.createObjectURL(r),error:o})}return t}function re(n){var r;let e=(r=n.clipboardData)==null?void 0:r.items;if(!e)return[];let t=[];for(let o of e){if(o.kind!=="file")continue;let i=o.getAsFile();i&&t.push(i)}return t}function R(n){for(let e of n)e.preview&&URL.revokeObjectURL(e.preview)}function xe(n){var e,t;return(t=(e=n.split("/")[1])==null?void 0:e.replace("quicktime","mov"))!=null?t:"bin"}function oe(n){var r;let t=(r=(typeof n.composedPath=="function"?n.composedPath():[])[0])!=null?r:n.target;return!t||t.nodeType!==1?!1:/^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName)?!0:typeof t.closest=="function"&&t.closest('[contenteditable=""], [contenteditable="true"]')!==null}var _=class{constructor(e,t){this.options=e;this.onSubmit=t;this.mode="idle";this.anchor=null;this.detach=[];this.state="ready";this.reference=null;this.host=document.createElement("div"),this.host.setAttribute("data-daybook-feedback",""),this.host.style.cssText="position:fixed;inset:0;z-index:2147483000;pointer-events:none",this.root=this.host.attachShadow({mode:"open"}),this.root.innerHTML=`<style>${Se}</style><style id="theme"></style><div id="layer"></div>`}setTheme(e){var a,s;let t=this.root.getElementById("theme");if(!t)return;if(!e){t.textContent="";return}let r=[];Te(e.accent)&&r.push(`--pm-accent: ${e.accent}`);let o={none:"0",sm:"6px",md:"12px",lg:"18px"}[(a=e.cornerRadius)!=null?a:"md"];o&&r.push(`--pm-radius: ${o}`);let i=Ee[(s=e.position)!=null?s:"bottom-right"];i&&r.push(i),t.textContent=r.length>0?`:host { ${r.join("; ")} }`:"",this.launcherLabel=typeof e.launcherLabel=="string"&&e.launcherLabel.length>0?e.launcherLabel.slice(0,24):void 0}setState(e){this.state=e,this.host.isConnected&&this.render()}mount(){var e;if(document.body.appendChild(this.host),this.render(),this.options.hotkey!==null){let t=((e=this.options.hotkey)!=null?e:"f").toLowerCase(),r=o=>{if(o.key==="Escape"){this.mode="idle",this.anchor=null,this.render();return}o.metaKey||o.ctrlKey||o.altKey||oe(o)||this.mode!=="composing"&&o.key.toLowerCase()===t&&(this.mode=this.mode==="picking"?"idle":"picking",this.render())};window.addEventListener("keydown",r),this.detach.push(()=>window.removeEventListener("keydown",r))}}unmount(){for(let e of this.detach.splice(0))e();this.host.remove()}open(){this.mode="picking",this.render()}setReporter(e){this.reporter=e}render(){let e=this.root.getElementById("layer");if(e.innerHTML="",this.mode==="idle"){e.appendChild(this.state==="pending"?this.pending():this.launcher());return}if(this.mode==="sent"){e.appendChild(this.sent());return}if(this.mode==="picking"){e.appendChild(this.picker());return}e.appendChild(this.composer())}pending(){let e=document.createElement("div");return e.className="launcher launcher--pending",e.setAttribute("role","status"),e.textContent="Feedback access pending approval",e}sent(){let e=document.createElement("div");e.className="panel panel--sent",e.setAttribute("role","status"),e.innerHTML=`
1
+ "use strict";var DaybookFeedback=(()=>{var C=Object.defineProperty;var fe=Object.getOwnPropertyDescriptor;var me=Object.getOwnPropertyNames;var ge=Object.prototype.hasOwnProperty;var be=(n,e)=>{for(var t in e)C(n,t,{get:e[t],enumerable:!0})},ye=(n,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of me(e))!ge.call(n,r)&&r!==t&&C(n,r,{get:()=>e[r],enumerable:!(o=fe(e,r))||o.enumerable});return n};var we=n=>ye(C({},"__esModule",{value:!0}),n);var qe={};be(qe,{DEFAULT_API_URL:()=>ue,DaybookFeedback:()=>A,captureAnchor:()=>_,init:()=>Oe,resolveAnchor:()=>se});function v(n){var e;try{let t=new URL(n,location.href);return t.origin===location.origin?t.pathname:`${t.origin}${t.pathname}`}catch{return(e=n.split("?")[0])!=null?e:n}}function P(n){var o,r,i,s,a,c;let e=n.tagName.toLowerCase();if(!n.getAttribute("aria-label")&&!n.getAttribute("data-testid")&&!((o=n.textContent)!=null?o:"").trim()){let d=n.closest("button, a, [role=button], [data-testid], label");if(d&&d!==n)return P(d)}if(n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement||n instanceof HTMLSelectElement){let d=(i=(r=n.getAttribute("name"))!=null?r:n.id)!=null?i:"",u=n instanceof HTMLInputElement?n.type:e;return`${e}[${u}]${d?` name=${d}`:""}`}let t=(c=(s=n.getAttribute("aria-label"))!=null?s:n.getAttribute("data-testid"))!=null?c:((a=n.textContent)!=null?a:"").replace(/\s+/g," ").trim().slice(0,40);return t?`${e} "${t}"`:e}function Q(n){return n.replace(/[\w.+-]+@[\w-]+\.[\w.]+/g,"[email]").replace(/\b[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/g,"[jwt]").replace(/\bBearer\s+[\w.-]+/gi,"Bearer [redacted]").replace(/\b\d{12,19}\b/g,"[number]").slice(0,500)}var Z="data-daybook-private";var k=class{constructor(e=40,t=!0){this.limit=e;this.redact=t;this.entries=[];this.detach=[]}list(){return[...this.entries]}add(e,t){for(this.entries.push({at:new Date().toISOString(),type:e,message:this.redact?Q(t):t.slice(0,500)});this.entries.length>this.limit;)this.entries.shift()}start(){let e=a=>{let c=a.target;c instanceof Element&&(c.closest("[data-daybook-feedback]")||this.add("click",P(c)))};document.addEventListener("click",e,{capture:!0,passive:!0}),this.detach.push(()=>document.removeEventListener("click",e,{capture:!0}));let t=history.pushState,o=history.replaceState,r=()=>this.add("nav",v(location.href));history.pushState=(...a)=>{t.apply(history,a),r()},history.replaceState=(...a)=>{o.apply(history,a),r()},window.addEventListener("popstate",r),this.detach.push(()=>{history.pushState=t,history.replaceState=o,window.removeEventListener("popstate",r)});for(let a of["error","warn"]){let c=console[a];console[a]=(...d)=>{this.add("console",`${a}: ${d.map(F).join(" ")}`),c.apply(console,d)},this.detach.push(()=>{console[a]=c})}let i=a=>this.add("console",`uncaught: ${a.message}`),s=a=>this.add("console",`unhandled rejection: ${F(a.reason)}`);window.addEventListener("error",i),window.addEventListener("unhandledrejection",s),this.detach.push(()=>{window.removeEventListener("error",i),window.removeEventListener("unhandledrejection",s)}),this.watchFetch()}stop(){for(let e of this.detach.splice(0))e()}watchFetch(){if(typeof window.fetch!="function")return;let e=window.fetch;window.fetch=async(...t)=>{let o=performance.now();try{let r=await e.apply(window,t),i=Math.round(performance.now()-o);return(!r.ok||i>3e3)&&this.add("network",`${r.status} ${v(G(t[0]))} ${i}ms`),r}catch(r){throw this.add("network",`failed ${v(G(t[0]))}: ${F(r)}`),r}},this.detach.push(()=>{window.fetch=e})}};function G(n){return typeof n=="string"?n:n instanceof URL?n.href:n.url}function F(n){var e,t;if(typeof n=="string")return n;if(n instanceof Error)return`${n.name}: ${n.message}`;try{return(t=(e=JSON.stringify(n))==null?void 0:e.slice(0,200))!=null?t:String(n)}catch{return String(n)}}var j="pm.feedback.queue";var T=class{constructor(e,t){this.apiUrl=e;this.ingestKey=t;this.session=null;this.identityToken=null}setSession(e){this.session=e}async send(e,t=[],o){var c,d,u;let r={idempotencyKey:(c=e.idempotencyKey)!=null?c:ee(),...e,attachments:[...(d=e.attachments)!=null?d:[],...t.map(p=>({filename:p.filename,contentType:p.contentType,size:p.blob.size}))]},i=await this.post("/ingest/v1",r);if(!i.ok)throw await E(i);let s=await i.json(),a=((u=e.attachments)!=null?u:[]).length;return await Promise.all(t.map(async(p,m)=>{let g=ve(s,a+m);if(!g){o==null||o(p,new Error("The server would not accept that file."));return}try{await this.upload(g,p)}catch(y){o==null||o(p,y)}})),s}async flush(){let e=ne();if(e.length!==0){oe([]);for(let t of e)try{let o=await this.post("/ingest/v1",t);!o.ok&&(o.status===429||o.status>=500)&&O(t)}catch{O(t)}}}queue(e){var t;O({...e,idempotencyKey:(t=e.idempotencyKey)!=null?t:ee(),attachments:void 0})}async signIn(){let e=te(64),t=await xe(e),o=te(16),r=`${this.base()}/ingest/v1/authorize?key=${encodeURIComponent(this.ingestKey)}&origin=${encodeURIComponent(location.origin)}&code_challenge=${encodeURIComponent(t)}&state=${encodeURIComponent(o)}`,i=window.open(r,"daybook-feedback","width=460,height=640");if(!i)throw Object.assign(new Error("Popup blocked"),{code:"popup_blocked"});let s=await new Promise((d,u)=>{let p=setInterval(()=>{i.closed&&(g(),u(Object.assign(new Error("Sign-in cancelled"),{code:"cancelled"})))},400),m=y=>{if(y.origin!==new URL(this.base()).origin)return;let f=y.data;if((f==null?void 0:f.source)==="daybook-feedback"&&f.state===o){if(g(),f.error||!f.code){u(Object.assign(new Error("Sign-in was refused"),{code:f.error||"refused"}));return}d(f.code)}},g=()=>{clearInterval(p),window.removeEventListener("message",m)};window.addEventListener("message",m)}),a=await this.post("/ingest/v1/token",{code:s,codeVerifier:e});if(!a.ok)throw await E(a);let{identityToken:c}=await a.json();return this.identityToken=c,c}base(){return this.apiUrl.replace(/\/$/,"")}resolve(e){try{let t=new URL(this.base()),o=new URL(e,t);return o.hostname===t.hostname?new URL(o.pathname+o.search,t).toString():o.toString()}catch{return e}}async handshake(e){var r,i;let t=await this.post("/ingest/v1/session",{...e,identityToken:(r=this.identityToken)!=null?r:void 0});if(!t.ok)throw await E(t);let o=await t.json();return this.session=(i=o.sessionToken)!=null?i:null,o}post(e,t){let o={"Content-Type":"application/json","X-Ingest-Key":this.ingestKey};return this.session&&(o["X-Feedback-Session"]=this.session),fetch(`${this.base()}${e}`,{method:"POST",headers:o,body:JSON.stringify(t),credentials:"omit"})}async upload(e,t){let o=await fetch(this.resolve(e.uploadUrl),{method:e.method,headers:{"Content-Type":e.contentType,"X-Ingest-Key":this.ingestKey},body:t.blob,credentials:"omit"});if(!o.ok)throw await E(o);await this.post(`/ingest/v1/attachments/${e.id}/confirm`,{})}};function ve(n,e){let t=n.attachments.find(o=>o.index===e);return t!=null?t:n.attachments.some(o=>typeof o.index=="number")?void 0:n.attachments[e]}function O(n){let e=ne();e.push(n),oe(e.slice(-20))}function ne(){try{let n=localStorage.getItem(j);return n?JSON.parse(n):[]}catch{return[]}}function oe(n){try{n.length===0?localStorage.removeItem(j):localStorage.setItem(j,JSON.stringify(n))}catch{}}async function E(n){let e=`http_${n.status}`;try{let t=await n.json();if(t.code&&(e=t.code),t.message)return Object.assign(new Error(t.message),{code:e})}catch{}return Object.assign(new Error(`Ingest failed (${n.status})`),{code:e})}function ee(){return typeof crypto!="undefined"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function te(n){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",t=new Uint8Array(n);return crypto.getRandomValues(t),Array.from(t,o=>e[o%e.length]).join("")}async function xe(n){let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function q(n){var t;let e={platform:"web",route:location.pathname,title:document.title.slice(0,200),locale:navigator.language,timezone:Ee(),viewport:{width:window.innerWidth,height:window.innerHeight,dpr:(t=window.devicePixelRatio)!=null?t:1},device:ke()};return document.referrer&&(e.referrer=v(document.referrer)),n.app&&(e.app=n.app),n.anchor&&(e.anchor=n.anchor),n.breadcrumbs&&n.breadcrumbs.length>0&&(e.breadcrumbs=n.breadcrumbs),e}function ke(){var r;let n=navigator.userAgent,e=/Edg\//.test(n)?"Edge":/OPR\//.test(n)?"Opera":/Firefox\//.test(n)?"Firefox":/Chrome\//.test(n)?"Chrome":/Safari\//.test(n)?"Safari":"Unknown",t=/Windows NT/.test(n)?"Windows":/iPhone|iPad|iPod/.test(n)?"iOS":/Mac OS X/.test(n)?"macOS":/Android/.test(n)?"Android":/Linux/.test(n)?"Linux":"Unknown",o=(r=n.match(/(?:Edg|OPR|Firefox|Chrome|Version)\/(\d+)/))==null?void 0:r[1];return{browser:o?`${e} ${o}`:e,os:t,touch:navigator.maxTouchPoints>0,userAgent:n.slice(0,300)}}function Ee(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return`UTC${-new Date().getTimezoneOffset()/60}`}}async function re(n,e=()=>()=>{}){var i;if(typeof((i=navigator.mediaDevices)==null?void 0:i.getDisplayMedia)!="function")return null;let t=n?Le():()=>{},o=e(),r=null;try{if(r=await navigator.mediaDevices.getDisplayMedia({video:!0,audio:!1,preferCurrentTab:!0,selfBrowserSurface:"include",surfaceSwitching:"exclude",monitorTypeSurfaces:"exclude"}),!r.getVideoTracks()[0])return null;await new Promise(c=>setTimeout(c,250));let a=await Te(r);return a?{blob:a,filename:"screenshot.png",contentType:"image/png"}:null}catch{return null}finally{r==null||r.getTracks().forEach(s=>s.stop()),o(),t()}}async function Te(n){let e=document.createElement("video");e.srcObject=n,e.muted=!0,await e.play().catch(()=>{});let t=document.createElement("canvas");t.width=e.videoWidth||window.innerWidth,t.height=e.videoHeight||window.innerHeight;let o=t.getContext("2d");return o?(o.drawImage(e,0,0,t.width,t.height),e.pause(),e.srcObject=null,new Promise(r=>t.toBlob(i=>r(i),"image/png"))):null}function Le(){let n=[...document.querySelectorAll(`[${Z}]`),...document.querySelectorAll('input[type="password"]')],e=n.map(t=>t.style.filter);return n.forEach(t=>{t.style.filter="blur(12px)"}),()=>{n.forEach((t,o)=>{var r;t.style.filter=(r=e[o])!=null?r:""})}}function _(n,e){let t=document.elementFromPoint(n,e);if(!(t instanceof HTMLElement))return{selector:null,offsetX:S(n/window.innerWidth),offsetY:S(e/window.innerHeight),elementText:null};let o=t.getBoundingClientRect();return{selector:Se(t),offsetX:o.width>0?S((n-o.left)/o.width):0,offsetY:o.height>0?S((e-o.top)/o.height):0,elementText:_e(t)}}function se(n){if(!n.selector)return{x:n.offsetX*window.innerWidth,y:n.offsetY*window.innerHeight};let e=null;try{e=document.querySelector(n.selector)}catch{return null}if(!e)return null;let t=e.getBoundingClientRect();return{x:t.left+n.offsetX*t.width,y:t.top+n.offsetY*t.height}}function Se(n){if(n===document.body)return"body";for(let r of["data-testid","data-test","data-daybook-id","data-cy"]){let i=n.getAttribute(r);if(i){let s=`[${r}="${U(i)}"]`;if(L(s))return s}}if(n.id&&!ie(n.id)){let r=`#${U(n.id)}`;if(L(r))return r}let e=[],t=n;for(;t&&t!==document.body&&e.length<8;){let r=t.tagName.toLowerCase(),i=Array.from(t.classList).filter(c=>!ie(c)).slice(0,2);i.length>0&&(r+=i.map(c=>`.${U(c)}`).join(""));let s=t.parentElement;if(s){let c=Array.from(s.children).filter(d=>d.tagName===t.tagName);c.length>1&&(r+=`:nth-of-type(${c.indexOf(t)+1})`)}e.unshift(r);let a=e.join(" > ");if(L(a))return a;t=s}let o=e.length>0?`body > ${e.join(" > ")}`:null;return o&&L(o)?o:null}function L(n){try{return document.querySelectorAll(n).length===1}catch{return!1}}function ie(n){return/^[a-z]{1,3}[0-9a-f]{5,}$/i.test(n)||/--[0-9a-f]{5,}$/i.test(n)||/^_[0-9a-z]{5,}/i.test(n)||/^v-[0-9a-f]{6,}$/i.test(n)||/^ng-/.test(n)||/[0-9a-f]{8,}/i.test(n)}function _e(n){var o,r,i;let t=((r=(o=n.innerText)!=null?o:n.textContent)!=null?r:"").replace(/\s+/g," ").trim();if(!t){let s=(i=n.getAttribute("aria-label"))!=null?i:n.getAttribute("title");return(s==null?void 0:s.trim())||null}return t.length>80?`${t.slice(0,77)}\u2026`:t}function S(n){return Number.isFinite(n)?Math.max(0,Math.min(1,n)):0}function U(n){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(n):n.replace(/([^\w-])/g,"\\$1")}var Re=/^(image\/(png|jpeg|gif|webp)|video\/(mp4|quicktime|webm))$/;function ae(n,e){let t=[];for(let o of n){if(e+t.length>=5)break;let r=Re.test(o.type)?o.size>26214400?`Too large (${(o.size/1048576).toFixed(1)} MB, max 25).`:null:"Only images and short videos.";t.push({blob:o,filename:o.name||`pasted-${t.length+1}.${$e(o.type)}`,contentType:o.type,preview:r?null:URL.createObjectURL(o),error:r})}return t}function ce(n){var o;let e=(o=n.clipboardData)==null?void 0:o.items;if(!e)return[];let t=[];for(let r of e){if(r.kind!=="file")continue;let i=r.getAsFile();i&&t.push(i)}return t}function R(n){for(let e of n)e.preview&&URL.revokeObjectURL(e.preview)}function $e(n){var e,t;return(t=(e=n.split("/")[1])==null?void 0:e.replace("quicktime","mov"))!=null?t:"bin"}function le(n){var o;let t=(o=(typeof n.composedPath=="function"?n.composedPath():[])[0])!=null?o:n.target;return!t||t.nodeType!==1?!1:/^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName)?!0:typeof t.closest=="function"&&t.closest('[contenteditable=""], [contenteditable="true"]')!==null}var M=class{constructor(e,t){this.options=e;this.onSubmit=t;this.mode="idle";this.anchor=null;this.detach=[];this.state="ready";this.policy=null;this.placement=Ie();this.reference=null;this.uploadsFailed=0;this.host=document.createElement("div"),this.host.setAttribute("data-daybook-feedback",""),this.host.style.cssText="position:fixed;inset:0;z-index:2147483000;pointer-events:none",this.root=this.host.attachShadow({mode:"open"}),this.root.innerHTML=`<style>${Fe}</style><style id="theme"></style><div id="layer"></div>`}setTheme(e){var s,a;let t=this.root.getElementById("theme");if(!t)return;if(!e){t.textContent="";return}let o=[];Pe(e.accent)&&o.push(`--pm-accent: ${e.accent}`);let r={none:"0",sm:"6px",md:"12px",lg:"18px"}[(s=e.cornerRadius)!=null?s:"md"];r&&o.push(`--pm-radius: ${r}`);let i=Ce[(a=e.position)!=null?a:"bottom-right"];i&&o.push(i),t.textContent=o.length>0?`:host { ${o.join("; ")} }`:"",this.launcherLabel=typeof e.launcherLabel=="string"&&e.launcherLabel.length>0?e.launcherLabel.slice(0,24):void 0}setState(e){this.state=e,this.host.isConnected&&this.render()}mount(){var e;if(document.body.appendChild(this.host),this.render(),this.options.hotkey!==null){let t=((e=this.options.hotkey)!=null?e:"f").toLowerCase(),o=r=>{if(r.key==="Escape"){this.mode==="picking"&&(this.mode="idle",this.anchor=null,this.render());return}r.metaKey||r.ctrlKey||r.altKey||le(r)||this.mode!=="composing"&&r.key.toLowerCase()===t&&(this.mode=this.mode==="picking"?"idle":"picking",this.render())};window.addEventListener("keydown",o),this.detach.push(()=>window.removeEventListener("keydown",o))}}unmount(){for(let e of this.detach.splice(0))e();this.host.remove()}open(){this.mode="picking",this.render()}setReporter(e){this.reporter=e}setPolicy(e){this.policy=e}capture(){var t,o;let e=(t=this.options.screenshots)!=null?t:!0;return e===!1||((o=this.policy)==null?void 0:o.screenshots)===!1?{offered:!1,checked:!1}:{offered:!0,checked:e!=="optional"}}conceal(){let e=this.host.style.visibility;return this.host.style.visibility="hidden",()=>{this.host.style.visibility=e}}movable(e,t){this.place(e),t.classList.add("drag"),t.title="Drag to move \xB7 double-click to reset",t.addEventListener("dblclick",()=>{this.placement=null,pe(null),this.place(e)}),t.addEventListener("pointerdown",o=>{if(o.target.closest("button")||o.button!==0)return;o.preventDefault();let r=e.getBoundingClientRect(),i=o.clientX-r.left,s=o.clientY-r.top;t.setPointerCapture(o.pointerId),e.classList.add("panel--dragging");let a=d=>{let u=$(d.clientX-i,w-r.width+z,window.innerWidth-z),p=$(d.clientY-s,0,window.innerHeight-z);e.style.left=`${u}px`,e.style.top=`${p}px`,e.style.right="auto",e.style.bottom="auto"},c=()=>{t.releasePointerCapture(o.pointerId),t.removeEventListener("pointermove",a),t.removeEventListener("pointerup",c),t.removeEventListener("pointercancel",c),e.classList.remove("panel--dragging"),this.placement=He(e.getBoundingClientRect()),pe(this.placement),this.place(e)};t.addEventListener("pointermove",a),t.addEventListener("pointerup",c),t.addEventListener("pointercancel",c)})}place(e){let t=this.placement;if(!t){e.style.left=e.style.right=e.style.top=e.style.bottom="";return}let o=e.offsetWidth||380,r=e.offsetHeight||240,i=$(t.dx,w,Math.max(w,window.innerWidth-o-w)),s=$(t.dy,w,Math.max(w,window.innerHeight-r-w));e.style.left=t.h==="left"?`${i}px`:"auto",e.style.right=t.h==="right"?`${i}px`:"auto",e.style.top=t.v==="top"?`${s}px`:"auto",e.style.bottom=t.v==="bottom"?`${s}px`:"auto"}render(){let e=this.root.getElementById("layer");if(e.innerHTML="",this.mode==="idle"){e.appendChild(this.state==="pending"?this.pending():this.launcher());return}if(this.mode==="sent"){let o=this.sent();e.appendChild(o),this.place(o);return}if(this.mode==="picking"){e.appendChild(this.picker());return}let t=this.composer();e.appendChild(t),this.place(t)}pending(){let e=document.createElement("div");return e.className="launcher launcher--pending",e.setAttribute("role","status"),e.textContent="Feedback access pending approval",e}sent(){var c;let e=document.createElement("div");e.className="panel panel--sent",e.setAttribute("role","status");let t=this.reference,o=this.uploadsFailed;e.innerHTML=`
2
2
  <div class="sent__tick" aria-hidden="true">&check;</div>
3
- <div>
3
+ <div class="sent__body">
4
4
  <div class="panel__title">Thank you \u2014 that is on its way.</div>
5
- ${this.reference?`<div class="panel__anchor">Quote <strong>${ie(this.reference)}</strong> if you follow it up.</div>`:""}
6
- </div>`;let t=window.setTimeout(()=>{this.mode==="sent"&&(this.mode="idle",this.render())},6e3);return this.detach.push(()=>window.clearTimeout(t)),e}launcher(){var t,r;let e=document.createElement("button");return e.className="launcher",e.textContent=(t=this.launcherLabel)!=null?t:"Feedback",e.title=this.options.hotkey===null?"Report a problem":`Report a problem (${((r=this.options.hotkey)!=null?r:"f").toUpperCase()})`,e.onclick=()=>{this.mode="picking",this.render()},e}picker(){let e=document.createElement("div");return e.className="mask",e.innerHTML='<div class="hint">Click the thing that is wrong \xB7 <kbd>Esc</kbd> to cancel</div>',e.onclick=t=>{e.style.pointerEvents="none",this.anchor=L(t.clientX,t.clientY),e.style.pointerEvents="",this.mode="composing",this.render()},e}composer(){var j,z,B,K,N;let e=document.createElement("div");e.className="panel";let t=(j=this.anchor)!=null&&j.elementText?`on \u201C${this.anchor.elementText}\u201D`:(z=this.anchor)!=null&&z.selector?`on ${this.anchor.selector}`:"on this page";e.innerHTML=`
7
- <div class="panel__head">
8
- <div>
9
- <div class="panel__anchor">${ie(t)}</div>
5
+ ${t?`<div class="sent__ref">
6
+ <code class="sent__id">${he(t)}</code>
7
+ <button type="button" class="sent__copy" data-copy>Copy</button>
8
+ </div>
9
+ <div class="panel__anchor">Quote it if you follow it up.</div>`:""}
10
+ ${o>0?`<div class="sent__warn">${o===1?"One attachment could not be uploaded.":`${o} attachments could not be uploaded.`} The report was filed without it.</div>`:""}
11
+ </div>
12
+ ${t?'<button type="button" class="panel__close" data-dismiss aria-label="Dismiss">&times;</button>':""}`;let r=()=>{this.mode==="sent"&&(this.mode="idle",this.render())},i=window.setTimeout(r,o>0?2e4:t?12e3:6e3),s=()=>window.clearTimeout(i);if(this.detach.push(()=>window.clearTimeout(i)),this.contain(e),this.place(e),!t)return e;e.addEventListener("pointerenter",s),e.addEventListener("focusin",s),(c=e.querySelector("[data-dismiss]"))==null||c.addEventListener("click",r);let a=e.querySelector("[data-copy]");return a&&(a.onclick=async()=>{s();let d=await Ae(t);a.textContent=d?"Copied":"Copy failed",a.classList.toggle("sent__copy--done",d)}),e}launcher(){var t,o;let e=document.createElement("button");return e.className="launcher",e.textContent=(t=this.launcherLabel)!=null?t:"Feedback",e.title=this.options.hotkey===null?"Report a problem":`Report a problem (${((o=this.options.hotkey)!=null?o:"f").toUpperCase()})`,e.onclick=()=>{this.mode="picking",this.render()},e}picker(){let e=document.createElement("div");return e.className="mask",e.innerHTML='<div class="hint">Click the thing that is wrong \xB7 <kbd>Esc</kbd> to cancel</div>',e.onclick=t=>{e.style.pointerEvents="none",this.anchor=_(t.clientX,t.clientY),e.style.pointerEvents="",this.mode="composing",this.render()},e}composer(){var K,X,W,Y,V;let e=document.createElement("div");e.className="panel";let t=(K=this.anchor)!=null&&K.elementText?`on \u201C${this.anchor.elementText}\u201D`:(X=this.anchor)!=null&&X.selector?`on ${this.anchor.selector}`:"on this page",o=this.capture();e.innerHTML=`
13
+ <div class="panel__head" id="head">
14
+ <span class="panel__grip" aria-hidden="true">\u283F</span>
15
+ <div class="panel__heading">
16
+ <div class="panel__anchor">${he(t)}</div>
10
17
  <div class="panel__title">Report a problem</div>
11
18
  </div>
12
19
  <button id="close" class="panel__close" aria-label="Close">&times;</button>
@@ -20,16 +27,20 @@
20
27
  what somebody came here to do is type.
21
28
  -->
22
29
  <div class="panel__kinds">
23
- ${["bug","idea","praise","question"].map((l,u)=>`<button class="kind${u===0?" kind--on":""}" data-kind="${l}">${l}</button>`).join("")}
30
+ ${["bug","idea","praise","question"].map((l,h)=>`<button class="kind${h===0?" kind--on":""}" data-kind="${l}">${l}</button>`).join("")}
24
31
  </div>
25
32
 
26
33
  <input id="email" type="email" placeholder="Email (optional, so we can reply)" autocomplete="email" />
27
34
 
28
35
  <!-- One attachment area, not two. A checkbox for the screen and a dropzone for a file were
29
- two ways to do the same thing, stacked, both dim. -->
36
+ two ways to do the same thing, stacked, both dim.
37
+
38
+ The capture control is rendered only when it can actually do something. It used to be
39
+ drawn whatever the host had configured and then ignored downstream, so ticking it was a
40
+ promise nobody kept. -->
30
41
  <div id="drop" class="drop">
31
- <label class="shot"><input id="shot" type="checkbox" ${this.options.screenshots===!1?"":"checked"} /> Capture the screen</label>
32
- <span class="drop__or">or paste, drop, or
42
+ ${o.offered?`<label class="shot"><input id="shot" type="checkbox" ${o.checked?"checked":""} /> Capture the screen</label>
43
+ <span class="drop__or">or paste, drop, or`:'<span class="drop__or">Paste, drop, or'}
33
44
  <input id="file" type="file" multiple accept="image/*,video/mp4,video/quicktime,video/webm" hidden />
34
45
  <button id="browse" class="link">choose a file</button>
35
46
  </span>
@@ -42,7 +53,7 @@
42
53
  <span class="panel__note">Sends the page, your browser, and recent errors.</span>
43
54
  <button id="cancel" class="ghost">Cancel</button>
44
55
  <button id="send" class="primary">Send</button>
45
- </div>`;let r=[],o=e.querySelector("#files"),i=e.querySelector("#drop"),a=e.querySelector("#file"),s=()=>{o.innerHTML="",r.forEach((l,u)=>{var D;let f=document.createElement("div");f.className=l.error?"file file--bad":"file",f.innerHTML=l.preview?`<img src="${l.preview}" alt="" />`:'<span class="file__icon">\u25A6</span>';let A=document.createElement("span");A.className="file__name",A.textContent=(D=l.error)!=null?D:l.filename,f.appendChild(A);let v=document.createElement("button");v.className="link",v.textContent="\xD7",v.onclick=()=>{R([l]),r.splice(u,1),s()},f.appendChild(v),o.appendChild(f)}),i.style.display=r.length>=5?"none":""},c=l=>{r.push(...ne(l,r.length)),s()};a.onchange=()=>{a.files&&c(a.files)},e.querySelector("#browse").onclick=()=>a.click(),e.addEventListener("paste",l=>{let u=re(l);u.length>0&&(l.preventDefault(),c(u))}),i.addEventListener("dragover",l=>{l.preventDefault(),i.classList.add("drop--over")}),i.addEventListener("dragleave",()=>i.classList.remove("drop--over")),i.addEventListener("drop",l=>{var u,f;l.preventDefault(),i.classList.remove("drop--over"),c(Array.from((f=(u=l.dataTransfer)==null?void 0:u.files)!=null?f:[]))});let d="bug";e.querySelectorAll(".kind").forEach(l=>{l.onclick=()=>{var u;d=(u=l.dataset.kind)!=null?u:"bug",e.querySelectorAll(".kind").forEach(f=>f.classList.remove("kind--on")),l.classList.add("kind--on")}});let p=e.querySelector("#message"),b=e.querySelector("#email"),y=(N=(B=this.reporter)==null?void 0:B.email)!=null?N:(K=this.options.reporter)==null?void 0:K.email;y&&!b.value&&(b.value=y);let w=e.querySelector("#shot"),m=e.querySelector("#status"),h=e.querySelector("#send"),O=()=>{R(r),this.mode="idle",this.anchor=null,this.render()};e.querySelector("#cancel").onclick=O,e.querySelector("#close").onclick=O;let q=async()=>{if(!p.value.trim()){m.textContent="Say what happened first.";return}h.disabled=!0,m.textContent="Sending\u2026";try{this.reference=await this.onSubmit({message:p.value.trim(),kind:d,email:b.value.trim()||void 0,anchor:this.anchor,withScreenshot:w.checked,files:r.filter(l=>!l.error)})||null,R(r),this.mode="sent",this.anchor=null,this.render()}catch(l){h.disabled=!1,m.textContent=l instanceof Error?`${l.message} \u2014 saved, will retry.`:"Failed, saved and will retry."}};return h.onclick=q,p.onkeydown=l=>{(l.metaKey||l.ctrlKey)&&l.key==="Enter"&&q()},setTimeout(()=>p.focus(),0),e}};function ie(n){return n.replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}var Ee={"bottom-right":"--pm-left: auto; --pm-right: 16px; --pm-top: auto; --pm-bottom: 16px","bottom-left":"--pm-left: 16px; --pm-right: auto; --pm-top: auto; --pm-bottom: 16px","top-right":"--pm-left: auto; --pm-right: 16px; --pm-top: 16px; --pm-bottom: auto","top-left":"--pm-left: 16px; --pm-right: auto; --pm-top: 16px; --pm-bottom: auto"};function Te(n){return typeof n=="string"&&/^(#[0-9a-f]{3,8}|rgba?\([\d\s.,%/]+\)|hsla?\([\d\s.,%/deg]+\)|[a-z]{3,20})$/i.test(n.trim())}var Se=`
56
+ </div>`;let r=[],i=e.querySelector("#files"),s=e.querySelector("#drop"),a=e.querySelector("#file"),c=()=>{i.innerHTML="",r.forEach((l,h)=>{var J;let b=document.createElement("div");b.className=l.error?"file file--bad":"file",b.innerHTML=l.preview?`<img src="${l.preview}" alt="" />`:'<span class="file__icon">\u25A6</span>';let I=document.createElement("span");I.className="file__name",I.textContent=(J=l.error)!=null?J:l.filename,b.appendChild(I);let x=document.createElement("button");x.className="link",x.textContent="\xD7",x.onclick=()=>{R([l]),r.splice(h,1),c()},b.appendChild(x),i.appendChild(b)}),s.style.display=r.length>=5?"none":""},d=l=>{r.push(...ae(l,r.length)),c()};a.onchange=()=>{a.files&&d(a.files)},e.querySelector("#browse").onclick=()=>a.click(),e.addEventListener("paste",l=>{let h=ce(l);h.length>0&&(l.preventDefault(),d(h))}),s.addEventListener("dragover",l=>{l.preventDefault(),s.classList.add("drop--over")}),s.addEventListener("dragleave",()=>s.classList.remove("drop--over")),s.addEventListener("drop",l=>{var h,b;l.preventDefault(),s.classList.remove("drop--over"),d(Array.from((b=(h=l.dataTransfer)==null?void 0:h.files)!=null?b:[]))});let u="bug";e.querySelectorAll(".kind").forEach(l=>{l.onclick=()=>{var h;u=(h=l.dataset.kind)!=null?h:"bug",e.querySelectorAll(".kind").forEach(b=>b.classList.remove("kind--on")),l.classList.add("kind--on")}});let p=e.querySelector("#message"),m=e.querySelector("#email"),g=(V=(W=this.reporter)==null?void 0:W.email)!=null?V:(Y=this.options.reporter)==null?void 0:Y.email;g&&!m.value&&(m.value=g);let y=e.querySelector("#shot"),f=e.querySelector("#status"),H=e.querySelector("#send"),N=()=>{R(r),this.mode="idle",this.anchor=null,this.render()};e.querySelector("#cancel").onclick=N,e.querySelector("#close").onclick=N;let D=async()=>{var l;if(!p.value.trim()){f.textContent="Say what happened first.";return}H.disabled=!0,f.textContent="Sending\u2026";try{let h=await this.onSubmit({message:p.value.trim(),kind:u,email:m.value.trim()||void 0,anchor:this.anchor,withScreenshot:(l=y==null?void 0:y.checked)!=null?l:!1,files:r.filter(b=>!b.error)});this.reference=h.reference,this.uploadsFailed=h.uploadsFailed,R(r),this.mode="sent",this.anchor=null,this.render()}catch(h){H.disabled=!1,f.textContent=h instanceof Error?`${h.message} \u2014 saved, will retry.`:"Failed, saved and will retry."}};return H.onclick=D,p.onkeydown=l=>{(l.metaKey||l.ctrlKey)&&l.key==="Enter"&&D()},setTimeout(()=>p.focus(),0),this.contain(e),this.movable(e,e.querySelector("#head")),e}contain(e){for(let t of["pointerdown","mousedown","click"])e.addEventListener(t,o=>o.stopPropagation())}};async function Ae(n){var t;try{if((t=navigator.clipboard)!=null&&t.writeText)return await navigator.clipboard.writeText(n),!0}catch{}let e=document.createElement("textarea");e.value=n,e.setAttribute("readonly",""),e.style.cssText="position:fixed;top:0;left:0;width:1px;height:1px;opacity:0",document.body.appendChild(e);try{return e.select(),document.execCommand("copy")}catch{return!1}finally{e.remove()}}var de=72,w=16,z=56,B="pm.feedback.placement";function He(n){let e=n.left+n.width/2<window.innerWidth/2?"left":"right",t=n.top+n.height/2<window.innerHeight/2?"top":"bottom",o=e==="left"?n.left:window.innerWidth-n.right,r=t==="top"?n.top:window.innerHeight-n.bottom;return{h:e,v:t,dx:o<de?w:Math.round(o),dy:r<de?w:Math.round(r)}}function Ie(){try{let n=localStorage.getItem(B);if(!n)return null;let e=JSON.parse(n);return(e.h==="left"||e.h==="right")&&(e.v==="top"||e.v==="bottom")&&Number.isFinite(e.dx)&&Number.isFinite(e.dy)?e:null}catch{return null}}function pe(n){try{n?localStorage.setItem(B,JSON.stringify(n)):localStorage.removeItem(B)}catch{}}function $(n,e,t){return Math.min(Math.max(n,e),t)}function he(n){return n.replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}var Ce={"bottom-right":"--pm-left: auto; --pm-right: 16px; --pm-top: auto; --pm-bottom: 16px","bottom-left":"--pm-left: 16px; --pm-right: auto; --pm-top: auto; --pm-bottom: 16px","top-right":"--pm-left: auto; --pm-right: 16px; --pm-top: 16px; --pm-bottom: auto","top-left":"--pm-left: 16px; --pm-right: auto; --pm-top: 16px; --pm-bottom: auto"};function Pe(n){return typeof n=="string"&&/^(#[0-9a-f]{3,8}|rgba?\([\d\s.,%/]+\)|hsla?\([\d\s.,%/deg]+\)|[a-z]{3,20})$/i.test(n.trim())}var Fe=`
46
57
  :host {
47
58
  all: initial;
48
59
 
@@ -73,8 +84,17 @@
73
84
  position: fixed; inset: 0; pointer-events: auto; cursor: crosshair;
74
85
  background: rgba(23,23,23,.12);
75
86
  }
87
+ /*
88
+ Bottom, not top.
89
+
90
+ At top:16px this landed on whatever the host puts at the top centre of their page \u2014 a logo, a
91
+ nav bar, a search field. We are a guest here and we do not know what is up there; on our own app
92
+ it covered the project switcher. The bottom centre is beside the launcher the reporter just
93
+ clicked, which is space the widget already owns, and it keeps their eyes near the thing they are
94
+ about to point at rather than sending them to the far edge of the screen and back.
95
+ */
76
96
  .hint {
77
- position: fixed; left: 50%; top: 16px; transform: translateX(-50%);
97
+ position: fixed; left: 50%; bottom: 76px; transform: translateX(-50%);
78
98
  padding: 7px 12px; border-radius: 8px; background: #171717; color: #fafafa;
79
99
  font-size: 12px; white-space: nowrap;
80
100
  }
@@ -90,8 +110,25 @@ kbd {
90
110
  box-shadow: 0 8px 32px rgba(0,0,0,.24); font-size: 13px;
91
111
  }
92
112
  .panel__head { display: flex; align-items: flex-start; gap: 8px; margin-bottom: 10px }
113
+ .panel__heading { min-width: 0 }
93
114
  .panel__title { font-weight: 600; font-size: 14px }
94
115
 
116
+ /*
117
+ The header is the handle.
118
+
119
+ A 380px panel sits over the page somebody is reporting a problem with, and reading what is under
120
+ it used to mean closing the widget and losing what had been written. touch-action:none because a
121
+ drag on a touch screen is otherwise claimed by the page's own scrolling before we see it.
122
+ */
123
+ .drag { cursor: grab; touch-action: none; user-select: none }
124
+ .drag:active { cursor: grabbing }
125
+ .panel__grip { flex: none; color: #bdbdbd; font-size: 15px; line-height: 16px; letter-spacing: -1px }
126
+ .drag:hover .panel__grip { color: #a3a3a3 }
127
+ .panel--dragging { box-shadow: 0 16px 48px rgba(0,0,0,.32); opacity: .92 }
128
+
129
+ /* An incomplete report, said plainly. Amber rather than red: the words arrived. */
130
+ .sent__warn { margin-top: 6px; color: #b45309; font-size: 11px; line-height: 1.4 }
131
+
95
132
  /* The anchor leads: it is what the reporter pointed at, and the part they need to recognise. */
96
133
  .panel__anchor {
97
134
  color: #737373; font-size: 11px;
@@ -104,12 +141,27 @@ kbd {
104
141
  .panel__close:hover { color: #171717 }
105
142
 
106
143
  /* A confirmation, not a form. */
107
- .panel--sent { display: flex; align-items: center; gap: 10px }
144
+ .panel--sent { display: flex; align-items: flex-start; gap: 10px }
108
145
  .sent__tick {
109
146
  flex: none; width: 24px; height: 24px; border-radius: 999px;
110
147
  background: #ecfdf5; color: #047857;
111
148
  display: grid; place-items: center; font-size: 14px;
112
149
  }
150
+ .sent__body { min-width: 0 }
151
+
152
+ /* The reference on its own line, at its own weight: it is the one thing here to take away. */
153
+ .sent__ref { display: flex; align-items: center; gap: 6px; margin: 4px 0 2px }
154
+ .sent__id {
155
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px;
156
+ color: #171717; background: #f5f5f5; border-radius: 5px; padding: 2px 6px;
157
+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
158
+ }
159
+ .sent__copy {
160
+ flex: none; border: 1px solid #e5e5e5; border-radius: 6px; background: #fff;
161
+ color: #525252; cursor: pointer; font-size: 11px; padding: 3px 8px;
162
+ }
163
+ .sent__copy:hover { border-color: #a3a3a3; color: #171717 }
164
+ .sent__copy--done { border-color: #a7f3d0; background: #ecfdf5; color: #047857 }
113
165
 
114
166
  .panel__kinds { display: flex; gap: 6px; margin: 8px 0 }
115
167
  .kind {
@@ -159,4 +211,4 @@ textarea:focus, input:focus { outline: 2px solid #171717; outline-offset: -1px }
159
211
  .file__icon { width: 28px; text-align: center }
160
212
  .file__name { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap }
161
213
  .link { border: 0; background: transparent; color: #525252; cursor: pointer; font-size: 11px; text-decoration: underline }
162
- `;var se="https://api.daybook.team",$=class{constructor(e){this.options=e;this.widget=null;this.started=!1;this.inFlight=null;this.epoch=0;this.ready=null;var t;if(!e.ingestKey)throw new Error("ingestKey is required");this.client=new E((t=e.apiUrl)!=null?t:se,e.ingestKey),this.trail=e.breadcrumbs===!1?null:new x(40,e.redact!==!1)}start(){var e;return(e=this.trail)==null||e.start(),this.mount(),this.started||(this.started=!0,this.client.flush()),this.handshake(),this}mount(){this.widget||(this.widget=new _(this.options,e=>this.submit(e)),this.widget.setReporter(this.options.reporter),this.widget.mount())}handshake(){var r,o,i;let e=JSON.stringify([(r=this.options.reporter)!=null?r:null,(o=this.options.signature)!=null?o:null,this.epoch]);if(((i=this.inFlight)==null?void 0:i.key)===e)return this.inFlight.promise;let t=this.runHandshake().finally(()=>{var a;((a=this.inFlight)==null?void 0:a.promise)===t&&(this.inFlight=null)});return this.inFlight={key:e,promise:t},t}async runHandshake(){var e,t,r,o,i,a;try{let s=await this.client.handshake({identity:this.options.reporter,signature:this.options.signature,locale:typeof navigator!="undefined"?navigator.language:void 0});if(this.ready=s,(t=(e=this.options).onReady)==null||t.call(e,s),s.reporterStatus==="Blocked"){(r=this.widget)==null||r.unmount(),this.widget=null;return}this.mount(),this.widget.setTheme(Re(s.theme)),this.widget.setState(s.reporterStatus==="Pending"?"pending":"ready")}catch(s){(i=(o=this.options).onError)==null||i.call(o,s),console.warn("[feedback] handshake failed; the widget will not appear",s),(a=this.widget)==null||a.unmount(),this.widget=null}}identify(e){var t;this.options={...this.options,reporter:e?{...this.options.reporter,...e}:void 0},(t=this.widget)==null||t.setReporter(this.options.reporter),this.widget&&this.handshake()}async signIn(){await this.client.signIn(),this.epoch++,await this.handshake()}authenticate(e){this.options={...this.options,signature:e!=null?e:void 0},this.widget&&this.handshake()}stop(){var e,t;this.started=!1,(e=this.trail)==null||e.stop(),(t=this.widget)==null||t.unmount(),this.widget=null}open(){var e;(e=this.widget)==null||e.open()}async report(e,t={}){var r,o,i;return this.client.send({message:e,surface:this.options.surface,...t,context:{...U({breadcrumbs:(r=this.trail)==null?void 0:r.list(),app:this.options.app}),...(o=t.context)!=null?o:{}},reporter:(i=t.reporter)!=null?i:this.options.reporter})}async submit(e){var i,a,s,c,d;let t=e.withScreenshot&&this.options.screenshots!==!1?await G(this.options.redact!==!1):null,r=[...e.files,...t?[t]:[]],o={message:e.message,kind:e.kind,app:this.options.app,surface:this.options.surface,reporter:e.email?{...this.options.reporter,email:e.email}:this.options.reporter,context:U({anchor:e.anchor,breadcrumbs:(i=this.trail)==null?void 0:i.list(),app:this.options.app})};try{let p=await this.client.send(o,r);return(s=(a=this.options).onSent)==null||s.call(a,p),p.reference}catch(p){throw this.client.queue(o),(d=(c=this.options).onError)==null||d.call(c,p),p}}};function Le(n){return new $(n).start()}function Re(n){if(!n)return null;try{let e=JSON.parse(n);return e&&typeof e=="object"?e:null}catch{return null}}return he(_e);})();
214
+ `;var ue="https://api.daybook.team",A=class{constructor(e){this.options=e;this.widget=null;this.started=!1;this.inFlight=null;this.epoch=0;this.ready=null;this.stopped=!1;var t;if(!e.ingestKey)throw new Error("ingestKey is required");this.client=new T((t=e.apiUrl)!=null?t:ue,e.ingestKey),this.trail=e.breadcrumbs===!1?null:new k(40,e.redact!==!1)}start(){var e;return this.stopped=!1,(e=this.trail)==null||e.start(),this.mount(),this.started||(this.started=!0,this.client.flush()),this.handshake(),this}mount(){this.widget||this.stopped||(this.widget=new M(this.options,e=>this.submit(e)),this.widget.setReporter(this.options.reporter),this.widget.mount())}handshake(){var o,r,i;let e=JSON.stringify([(o=this.options.reporter)!=null?o:null,(r=this.options.signature)!=null?r:null,this.epoch]);if(((i=this.inFlight)==null?void 0:i.key)===e)return this.inFlight.promise;let t=this.runHandshake().finally(()=>{var s;((s=this.inFlight)==null?void 0:s.promise)===t&&(this.inFlight=null)});return this.inFlight={key:e,promise:t},t}async runHandshake(){var e,t,o,r,i,s,a;try{let c=await this.client.handshake({identity:this.options.reporter,signature:this.options.signature,locale:typeof navigator!="undefined"?navigator.language:void 0});if(this.ready=c,(t=(e=this.options).onReady)==null||t.call(e,c),c.reporterStatus==="Blocked"){(o=this.widget)==null||o.unmount(),this.widget=null;return}this.mount(),this.widget.setTheme(je(c.theme)),this.widget.setPolicy((r=c.policy)!=null?r:null),this.widget.setState(c.reporterStatus==="Pending"?"pending":"ready")}catch(c){(s=(i=this.options).onError)==null||s.call(i,c),console.warn("[feedback] handshake failed; the widget will not appear",c),(a=this.widget)==null||a.unmount(),this.widget=null}}identify(e){var t;this.options={...this.options,reporter:e?{...this.options.reporter,...e}:void 0},(t=this.widget)==null||t.setReporter(this.options.reporter),this.widget&&this.handshake()}async signIn(){await this.client.signIn(),this.epoch++,await this.handshake()}authenticate(e){this.options={...this.options,signature:e!=null?e:void 0},this.widget&&this.handshake()}stop(){var e,t;this.started=!1,this.stopped=!0,(e=this.trail)==null||e.stop(),(t=this.widget)==null||t.unmount(),this.widget=null}open(){var e;(e=this.widget)==null||e.open()}async report(e,t={}){var o,r,i;return this.client.send({message:e,surface:this.options.surface,...t,context:{...q({breadcrumbs:(o=this.trail)==null?void 0:o.list(),app:this.options.app}),...(r=t.context)!=null?r:{}},reporter:(i=t.reporter)!=null?i:this.options.reporter})}async submit(e){var s,a,c,d,u;let t=e.withScreenshot?await re(this.options.redact!==!1,()=>{var p,m;return(m=(p=this.widget)==null?void 0:p.conceal())!=null?m:(()=>{})}):null,o=[...e.files,...t?[t]:[]],r={message:e.message,kind:e.kind,app:this.options.app,surface:this.options.surface,reporter:e.email?{...this.options.reporter,email:e.email}:this.options.reporter,context:q({anchor:e.anchor,breadcrumbs:(s=this.trail)==null?void 0:s.list(),app:this.options.app})},i=[];try{let p=await this.client.send(r,o,(m,g)=>{var y,f;i.push(g),console.warn(`[feedback] "${m.filename}" did not upload`,g),(f=(y=this.options).onError)==null||f.call(y,g)});return p.uploadsFailed=i.length,(c=(a=this.options).onSent)==null||c.call(a,p),{reference:p.reference,uploadsFailed:i.length}}catch(p){throw this.client.queue(r),(u=(d=this.options).onError)==null||u.call(d,p),p}}};function Oe(n){return new A(n).start()}function je(n){if(!n)return null;try{let e=JSON.parse(n);return e&&typeof e=="object"?e:null}catch{return null}}return we(qe);})();
package/dist/index.d.ts CHANGED
@@ -107,6 +107,7 @@ export declare class DaybookFeedback {
107
107
  */
108
108
  authenticate(signature: string | null): void;
109
109
  stop(): void;
110
+ private stopped;
110
111
  /** Opens the picker programmatically, for a host app's own "Report a problem" menu item. */
111
112
  open(): void;
112
113
  /**
package/dist/index.js CHANGED
@@ -60,6 +60,7 @@ export class DaybookFeedback {
60
60
  this.epoch = 0;
61
61
  /** The last handshake, for a host app that wants to explain a state in its own words. */
62
62
  this.ready = null;
63
+ this.stopped = false;
63
64
  if (!options.ingestKey)
64
65
  throw new Error('ingestKey is required');
65
66
  this.client = new IngestClient(options.apiUrl ?? DEFAULT_API_URL, options.ingestKey);
@@ -76,6 +77,7 @@ export class DaybookFeedback {
76
77
  * running, not that there are two of them.
77
78
  */
78
79
  start() {
80
+ this.stopped = false;
79
81
  this.trail?.start();
80
82
  this.mount();
81
83
  // Once per session, not once per call. start() is called again by hosts that gate the widget on
@@ -99,7 +101,7 @@ export class DaybookFeedback {
99
101
  * widget on it, which is the one flow that mode exists for.
100
102
  */
101
103
  mount() {
102
- if (this.widget)
104
+ if (this.widget || this.stopped)
103
105
  return;
104
106
  this.widget = new FeedbackWidget(this.options, input => this.submit(input));
105
107
  this.widget.setReporter(this.options.reporter);
@@ -135,6 +137,10 @@ export class DaybookFeedback {
135
137
  }
136
138
  this.mount();
137
139
  this.widget.setTheme(parseTheme(result.theme));
140
+ // What the integration allows, so the composer offers only controls that can act. Served
141
+ // since the handshake existed and never read until now — which is why an integration with
142
+ // screenshots turned off still showed a tick box for them.
143
+ this.widget.setPolicy(result.policy ?? null);
138
144
  this.widget.setState(result.reporterStatus === 'Pending' ? 'pending' : 'ready');
139
145
  }
140
146
  catch (error) {
@@ -199,6 +205,18 @@ export class DaybookFeedback {
199
205
  }
200
206
  stop() {
201
207
  this.started = false;
208
+ // Stopped means stopped, including against a handshake already in flight.
209
+ //
210
+ // A host that hides the widget from signed-out visitors calls init() and stop() within the same
211
+ // tick — init mounts and starts a handshake, the host's auth check then stops it, and the
212
+ // handshake resolved a moment later and called mount() again. The launcher came back on a page
213
+ // the host had deliberately taken it off, which on a public page means showing a stranger a
214
+ // control that was never meant for them.
215
+ //
216
+ // Not the same as the widget being unmounted by a REFUSED handshake: that path leaves this flag
217
+ // alone, so signIn() can still bring the widget back, which is the whole point of the Daybook
218
+ // identity mode.
219
+ this.stopped = true;
202
220
  this.trail?.stop();
203
221
  this.widget?.unmount();
204
222
  this.widget = null;
@@ -224,8 +242,12 @@ export class DaybookFeedback {
224
242
  });
225
243
  }
226
244
  async submit(input) {
227
- const screenshot = input.withScreenshot && this.options.screenshots !== false
228
- ? await captureScreenshot(this.options.redact !== false)
245
+ // The reporter's tick is the answer. It used to be second-guessed here against
246
+ // options.screenshots, so a host that set `screenshots: false` still rendered the checkbox and
247
+ // then quietly ignored it — the widget now simply does not offer the control in that case, and
248
+ // what arrives here is a decision somebody actually made.
249
+ const screenshot = input.withScreenshot
250
+ ? await captureScreenshot(this.options.redact !== false, () => this.widget?.conceal() ?? (() => { }))
229
251
  : null;
230
252
  // Attached files first, so a reporter's own screenshot leads the list — they chose it, and it is
231
253
  // usually more pointed than a whole-viewport capture.
@@ -244,12 +266,21 @@ export class DaybookFeedback {
244
266
  app: this.options.app,
245
267
  }),
246
268
  };
269
+ const failures = [];
247
270
  try {
248
- const response = await this.client.send(request, uploads);
271
+ const response = await this.client.send(request, uploads, (upload, error) => {
272
+ failures.push(error);
273
+ // Surfaced rather than swallowed. A screenshot that never lands is invisible to the
274
+ // reporter and merely absent to the triager, so nobody finds out until somebody goes
275
+ // looking — which is exactly how PM-B-0027 stayed open.
276
+ console.warn(`[feedback] "${upload.filename}" did not upload`, error);
277
+ this.options.onError?.(error);
278
+ });
279
+ response.uploadsFailed = failures.length;
249
280
  this.options.onSent?.(response);
250
- // Handed back so the widget can quote it in the confirmation. The reference is the whole
251
- // point of being able to say "F-0007" to support later.
252
- return response.reference;
281
+ // Handed back so the widget can quote it in the confirmation, and say so if a picture went
282
+ // missing. The reference is the whole point of being able to say "F-0007" to support later.
283
+ return { reference: response.reference, uploadsFailed: failures.length };
253
284
  }
254
285
  catch (error) {
255
286
  // Queued before rethrowing, so the words survive a failed send and the widget can say so
@@ -14,4 +14,12 @@ export interface Screenshot {
14
14
  filename: string;
15
15
  contentType: string;
16
16
  }
17
- export declare function captureScreenshot(redact: boolean): Promise<Screenshot | null>;
17
+ /**
18
+ * Takes the picture.
19
+ *
20
+ * <paramref name="conceal"/> hides the widget's own UI and returns the undo. It matters more than it
21
+ * looks: the composer is a 380px panel sitting over the page, and the reporter ticked "capture the
22
+ * screen" precisely because they want what is UNDER it. Without this the screenshot is a picture of
23
+ * the form they just filled in, covering the thing they were reporting.
24
+ */
25
+ export declare function captureScreenshot(redact: boolean, conceal?: () => () => void): Promise<Screenshot | null>;
@@ -1,17 +1,37 @@
1
1
  import { PRIVATE_ATTRIBUTE } from './redact.js';
2
- export async function captureScreenshot(redact) {
2
+ /**
3
+ * Takes the picture.
4
+ *
5
+ * <paramref name="conceal"/> hides the widget's own UI and returns the undo. It matters more than it
6
+ * looks: the composer is a 380px panel sitting over the page, and the reporter ticked "capture the
7
+ * screen" precisely because they want what is UNDER it. Without this the screenshot is a picture of
8
+ * the form they just filled in, covering the thing they were reporting.
9
+ */
10
+ export async function captureScreenshot(redact, conceal = () => () => { }) {
3
11
  if (typeof navigator.mediaDevices?.getDisplayMedia !== 'function')
4
12
  return null;
5
13
  const restore = redact ? hidePrivate() : () => { };
14
+ // Hidden before the picker opens, not after: on the browsers that skip the picker entirely for a
15
+ // current-tab capture there is no gap between the two, and the frame would still contain us.
16
+ const reveal = conceal();
6
17
  let stream = null;
7
18
  try {
8
- // preferCurrentTab keeps the browser's picker on this tab where supported, so the reporter is
9
- // not one misclick away from sharing a different window entirely.
19
+ // Steered as hard as the platform allows at the tab this widget is running in — that is the
20
+ // "screen it opened in" and it is what the reporter means. The picker cannot be skipped (a page
21
+ // that could silently record the screen would be a browser bug), but it can be pointed at the
22
+ // right thing so the default choice is the correct one.
10
23
  stream = await navigator.mediaDevices.getDisplayMedia({
11
24
  video: true,
12
25
  audio: false,
13
- // @ts-expect-error - Chromium-only hint, harmless elsewhere.
26
+ // @ts-expect-error - Chromium-only hints, harmless elsewhere.
14
27
  preferCurrentTab: true,
28
+ // Without this the current tab is EXCLUDED from the picker on some Chromium versions, which
29
+ // is the opposite of what preferCurrentTab asked for.
30
+ selfBrowserSurface: 'include',
31
+ // No mid-capture "share this tab instead" bar: there is one frame to take and switching
32
+ // surfaces during it only produces a picture of somewhere else.
33
+ surfaceSwitching: 'exclude',
34
+ monitorTypeSurfaces: 'exclude',
15
35
  });
16
36
  const track = stream.getVideoTracks()[0];
17
37
  if (!track)
@@ -30,6 +50,7 @@ export async function captureScreenshot(redact) {
30
50
  }
31
51
  finally {
32
52
  stream?.getTracks().forEach(track => track.stop());
53
+ reveal();
33
54
  restore();
34
55
  }
35
56
  }
package/dist/types.d.ts CHANGED
@@ -38,9 +38,22 @@ export interface IngestResponse {
38
38
  contentType: string;
39
39
  maxBytes: number;
40
40
  expiresAtUtc: string;
41
- /** How many declared attachments did not reach storage. Zero on a clean send. */
42
- uploadsFailed?: number;
41
+ /**
42
+ * Which declaration this ticket belongs to.
43
+ *
44
+ * Additive, and absent from a server older than it. The server skips a declaration it will not
45
+ * accept, so the ticket list can be shorter than the list that was sent — this says which is
46
+ * which, rather than leaving the client to assume the two line up.
47
+ */
48
+ index?: number;
43
49
  }[];
50
+ /**
51
+ * How many declared attachments did not reach storage. Zero on a clean send.
52
+ *
53
+ * Filled in by the SDK after the uploads, not sent by the server — at the moment the server
54
+ * answers, no bytes have been PUT yet.
55
+ */
56
+ uploadsFailed?: number;
44
57
  }
45
58
  export interface Breadcrumb {
46
59
  at: string;
@@ -138,10 +151,20 @@ export interface FeedbackOptions {
138
151
  */
139
152
  signature?: string;
140
153
  /**
141
- * Capture a screenshot of the viewport with each report. On by default because "it looks wrong"
142
- * without a picture is the single most expensive kind of report to triage.
154
+ * Whether the composer offers to capture the screen.
155
+ *
156
+ * true — offered, and ticked. The default, because "it looks wrong" without a picture is
157
+ * the single most expensive kind of report to triage.
158
+ * 'optional' — offered, but not ticked. For an app whose screens routinely show data that
159
+ * should not be collected unless the reporter decides it should be.
160
+ * false — not offered at all.
161
+ *
162
+ * `false` used to leave the checkbox on screen and merely ignore it downstream, so a reporter
163
+ * could tick "Capture the screen", send, and get no screenshot and no explanation. A control that
164
+ * does nothing is worse than no control, hence the third state: the host chooses the DEFAULT, the
165
+ * reporter chooses what actually happens.
143
166
  */
144
- screenshots?: boolean;
167
+ screenshots?: boolean | 'optional';
145
168
  /**
146
169
  * Mask input values, strip query strings, and blur elements marked data-daybook-private before any
147
170
  * capture leaves the device. On by default: a screenshot contains whatever was on screen, and the
package/dist/widget.d.ts CHANGED
@@ -24,7 +24,10 @@ export declare class FeedbackWidget {
24
24
  anchor: Anchor | null;
25
25
  withScreenshot: boolean;
26
26
  files: StagedFile[];
27
- }) => Promise<string | void>);
27
+ }) => Promise<{
28
+ reference: string | null;
29
+ uploadsFailed: number;
30
+ }>);
28
31
  /**
29
32
  * Applies the tokens the handshake served.
30
33
  *
@@ -55,6 +58,42 @@ export declare class FeedbackWidget {
55
58
  */
56
59
  private reporter;
57
60
  setReporter(reporter: FeedbackOptions['reporter']): void;
61
+ /**
62
+ * What the integration allows, from the handshake. Null until it answers.
63
+ *
64
+ * Only screenshots are read today, and only to decide whether to OFFER the control — a policy
65
+ * that says no should mean the reporter is never shown a tick box that cannot do anything.
66
+ */
67
+ private policy;
68
+ setPolicy(policy: import('./types.js').HandshakeResponse['policy'] | null): void;
69
+ /** Whether the composer offers screen capture at all, and whether it starts ticked. */
70
+ private capture;
71
+ /**
72
+ * Takes the widget off the screen and hands back the undo.
73
+ *
74
+ * For the screen capture. Everything here lives in one host element, so hiding is one property —
75
+ * and it is `visibility`, not `display`, because removing the panel from layout would reflow the
76
+ * host page underneath it and the picture would be of a page that never existed.
77
+ */
78
+ conceal(): () => void;
79
+ /**
80
+ * Where the reporter dragged the panel to, if they did.
81
+ *
82
+ * Remembered across reports and across visits, because somebody who moved it off the thing they
83
+ * are documenting will want it there for the next report too — and having to move it every time
84
+ * is the friction that stops the second report being written.
85
+ */
86
+ private placement;
87
+ /**
88
+ * Makes the panel draggable by its header, and snaps it to a side when it is let go near one.
89
+ *
90
+ * The panel covers 380px of somebody else's page, and the reporter frequently needs to SEE what
91
+ * is under it — to read an error, to point at it, to take their own screenshot of it. Fixed to
92
+ * one corner, the only way to do that was to close the widget, which loses what they had written.
93
+ */
94
+ private movable;
95
+ /** Applies the remembered placement, or hands the panel back to the theme's corner. */
96
+ private place;
58
97
  private render;
59
98
  /**
60
99
  * Shown in place of the launcher when this person is waiting on approval.
@@ -66,16 +105,49 @@ export declare class FeedbackWidget {
66
105
  private pending;
67
106
  /** The reference of the last report, so the confirmation can quote it. */
68
107
  private reference;
108
+ /** How many attachments did not land, so the confirmation can be honest about it. */
109
+ private uploadsFailed;
69
110
  /**
70
111
  * What a reporter sees after Send.
71
112
  *
72
113
  * Closing silently answered "did that work?" with nothing, which is the one question everybody has
73
- * — and it threw away the reference the wire contract deliberately makes human-quotable. It clears
74
- * itself after a few seconds rather than needing a click: an acknowledgement that has to be
75
- * dismissed is a second chore for having done somebody a favour.
114
+ * — and it threw away the reference the wire contract deliberately makes human-quotable.
115
+ *
116
+ * The reference is quotable but it was not takeable: reading `PM-F-0033` off a toast and typing it
117
+ * into a chat window is transcription, and the reporter routinely wants to hand it straight to an
118
+ * assistant. So it comes with a copy button — which changes what the panel is. A bare
119
+ * acknowledgement should clear itself, because dismissing it is a chore for having done somebody a
120
+ * favour; a panel with something to press should not vanish while you are reaching for it. So it
121
+ * lingers longer, stops counting down the moment it is touched, and grows a close button so a
122
+ * stopped timer is never a trap.
76
123
  */
77
124
  private sent;
78
125
  private launcher;
79
126
  private picker;
80
127
  private composer;
128
+ /**
129
+ * Keeps the widget's own events inside the widget.
130
+ *
131
+ * We are a guest on somebody else's page, and the host's "close when you click anywhere else"
132
+ * handlers are on the document — which sees a click on our panel, retargeted to our host element,
133
+ * as a click somewhere else. That closed the reporter's own menus under our panel and, on any
134
+ * host that treats an outside click as a dismissal of the thing being reported, moved the ground
135
+ * out from under the report while it was being written.
136
+ *
137
+ * Nothing here dismisses the composer either. It closes by the cross or by Cancel and by nothing
138
+ * else — not Escape, not a click outside, not a focus change — because everything in it was typed
139
+ * by hand and none of those gestures mean "throw that away".
140
+ */
141
+ private contain;
81
142
  }
143
+ /**
144
+ * Copy, on the pages a widget actually runs on.
145
+ *
146
+ * navigator.clipboard is not there on http, in some embedded webviews, and in any context the host
147
+ * page has not marked secure — which is a fair description of where a bug gets reported from. The
148
+ * textarea fallback is the old way and still the only one that works in those places.
149
+ *
150
+ * The scratch textarea goes in the document, not the shadow root: execCommand copies the document's
151
+ * selection, and a selection made inside a shadow root is not the document's.
152
+ */
153
+ export declare function copyText(text: string): Promise<boolean>;
package/dist/widget.js CHANGED
@@ -24,8 +24,25 @@ export class FeedbackWidget {
24
24
  * be told so, not left clicking a button that silently does nothing.
25
25
  */
26
26
  this.state = 'ready';
27
+ /**
28
+ * What the integration allows, from the handshake. Null until it answers.
29
+ *
30
+ * Only screenshots are read today, and only to decide whether to OFFER the control — a policy
31
+ * that says no should mean the reporter is never shown a tick box that cannot do anything.
32
+ */
33
+ this.policy = null;
34
+ /**
35
+ * Where the reporter dragged the panel to, if they did.
36
+ *
37
+ * Remembered across reports and across visits, because somebody who moved it off the thing they
38
+ * are documenting will want it there for the next report too — and having to move it every time
39
+ * is the friction that stops the second report being written.
40
+ */
41
+ this.placement = readPlacement();
27
42
  /** The reference of the last report, so the confirmation can quote it. */
28
43
  this.reference = null;
44
+ /** How many attachments did not land, so the confirmation can be honest about it. */
45
+ this.uploadsFailed = 0;
29
46
  this.host = document.createElement('div');
30
47
  this.host.setAttribute('data-daybook-feedback', '');
31
48
  // Above any host overlay, but not Number.MAX_SAFE_INTEGER — a host app with its own modal should
@@ -78,9 +95,17 @@ export class FeedbackWidget {
78
95
  const hotkey = (this.options.hotkey ?? 'f').toLowerCase();
79
96
  const onKey = (event) => {
80
97
  if (event.key === 'Escape') {
81
- this.mode = 'idle';
82
- this.anchor = null;
83
- this.render();
98
+ // The picker, and only the picker.
99
+ //
100
+ // Escape used to close the composer too, which is the same trapdoor as closing on an
101
+ // outside click: it is pressed to cancel a native screenshot selection, to dismiss the
102
+ // host app's own menu, out of habit — and it threw away everything that had been typed.
103
+ // The composer closes by the cross or by Cancel, deliberately, and by nothing else.
104
+ if (this.mode === 'picking') {
105
+ this.mode = 'idle';
106
+ this.anchor = null;
107
+ this.render();
108
+ }
84
109
  return;
85
110
  }
86
111
  if (event.metaKey || event.ctrlKey || event.altKey)
@@ -114,6 +139,100 @@ export class FeedbackWidget {
114
139
  setReporter(reporter) {
115
140
  this.reporter = reporter;
116
141
  }
142
+ setPolicy(policy) {
143
+ this.policy = policy;
144
+ }
145
+ /** Whether the composer offers screen capture at all, and whether it starts ticked. */
146
+ capture() {
147
+ const asked = this.options.screenshots ?? true;
148
+ if (asked === false || this.policy?.screenshots === false) {
149
+ return { offered: false, checked: false };
150
+ }
151
+ return { offered: true, checked: asked !== 'optional' };
152
+ }
153
+ /**
154
+ * Takes the widget off the screen and hands back the undo.
155
+ *
156
+ * For the screen capture. Everything here lives in one host element, so hiding is one property —
157
+ * and it is `visibility`, not `display`, because removing the panel from layout would reflow the
158
+ * host page underneath it and the picture would be of a page that never existed.
159
+ */
160
+ conceal() {
161
+ const previous = this.host.style.visibility;
162
+ this.host.style.visibility = 'hidden';
163
+ return () => { this.host.style.visibility = previous; };
164
+ }
165
+ /**
166
+ * Makes the panel draggable by its header, and snaps it to a side when it is let go near one.
167
+ *
168
+ * The panel covers 380px of somebody else's page, and the reporter frequently needs to SEE what
169
+ * is under it — to read an error, to point at it, to take their own screenshot of it. Fixed to
170
+ * one corner, the only way to do that was to close the widget, which loses what they had written.
171
+ */
172
+ movable(panel, handle) {
173
+ this.place(panel);
174
+ handle.classList.add('drag');
175
+ handle.title = 'Drag to move · double-click to reset';
176
+ handle.addEventListener('dblclick', () => {
177
+ this.placement = null;
178
+ writePlacement(null);
179
+ this.place(panel);
180
+ });
181
+ handle.addEventListener('pointerdown', (event) => {
182
+ // Not from the close button, which lives in this header and is the one thing in it that is
183
+ // not a handle.
184
+ if (event.target.closest('button'))
185
+ return;
186
+ if (event.button !== 0)
187
+ return;
188
+ event.preventDefault();
189
+ const rect = panel.getBoundingClientRect();
190
+ const grabX = event.clientX - rect.left;
191
+ const grabY = event.clientY - rect.top;
192
+ handle.setPointerCapture(event.pointerId);
193
+ panel.classList.add('panel--dragging');
194
+ const move = (moved) => {
195
+ // Clamped so the header — the only way to move it back — can never leave the viewport.
196
+ const left = clamp(moved.clientX - grabX, EDGE - rect.width + HANDLE, window.innerWidth - HANDLE);
197
+ const top = clamp(moved.clientY - grabY, 0, window.innerHeight - HANDLE);
198
+ panel.style.left = `${left}px`;
199
+ panel.style.top = `${top}px`;
200
+ panel.style.right = 'auto';
201
+ panel.style.bottom = 'auto';
202
+ };
203
+ const drop = () => {
204
+ handle.releasePointerCapture(event.pointerId);
205
+ handle.removeEventListener('pointermove', move);
206
+ handle.removeEventListener('pointerup', drop);
207
+ handle.removeEventListener('pointercancel', drop);
208
+ panel.classList.remove('panel--dragging');
209
+ this.placement = placementOf(panel.getBoundingClientRect());
210
+ writePlacement(this.placement);
211
+ this.place(panel);
212
+ };
213
+ handle.addEventListener('pointermove', move);
214
+ handle.addEventListener('pointerup', drop);
215
+ handle.addEventListener('pointercancel', drop);
216
+ });
217
+ }
218
+ /** Applies the remembered placement, or hands the panel back to the theme's corner. */
219
+ place(panel) {
220
+ const at = this.placement;
221
+ if (!at) {
222
+ panel.style.left = panel.style.right = panel.style.top = panel.style.bottom = '';
223
+ return;
224
+ }
225
+ // Re-clamped on every render rather than only on drop: the window the panel was placed in is
226
+ // not necessarily the window it is being drawn in.
227
+ const width = panel.offsetWidth || 380;
228
+ const height = panel.offsetHeight || 240;
229
+ const dx = clamp(at.dx, EDGE, Math.max(EDGE, window.innerWidth - width - EDGE));
230
+ const dy = clamp(at.dy, EDGE, Math.max(EDGE, window.innerHeight - height - EDGE));
231
+ panel.style.left = at.h === 'left' ? `${dx}px` : 'auto';
232
+ panel.style.right = at.h === 'right' ? `${dx}px` : 'auto';
233
+ panel.style.top = at.v === 'top' ? `${dy}px` : 'auto';
234
+ panel.style.bottom = at.v === 'bottom' ? `${dy}px` : 'auto';
235
+ }
117
236
  render() {
118
237
  const layer = this.root.getElementById('layer');
119
238
  layer.innerHTML = '';
@@ -122,14 +241,20 @@ export class FeedbackWidget {
122
241
  return;
123
242
  }
124
243
  if (this.mode === 'sent') {
125
- layer.appendChild(this.sent());
244
+ const note = this.sent();
245
+ layer.appendChild(note);
246
+ // Again, now that it has a size. Placement clamps against the panel's own width and height,
247
+ // and before it is in the document both are zero.
248
+ this.place(note);
126
249
  return;
127
250
  }
128
251
  if (this.mode === 'picking') {
129
252
  layer.appendChild(this.picker());
130
253
  return;
131
254
  }
132
- layer.appendChild(this.composer());
255
+ const panel = this.composer();
256
+ layer.appendChild(panel);
257
+ this.place(panel);
133
258
  }
134
259
  /**
135
260
  * Shown in place of the launcher when this person is waiting on approval.
@@ -149,29 +274,73 @@ export class FeedbackWidget {
149
274
  * What a reporter sees after Send.
150
275
  *
151
276
  * Closing silently answered "did that work?" with nothing, which is the one question everybody has
152
- * — and it threw away the reference the wire contract deliberately makes human-quotable. It clears
153
- * itself after a few seconds rather than needing a click: an acknowledgement that has to be
154
- * dismissed is a second chore for having done somebody a favour.
277
+ * — and it threw away the reference the wire contract deliberately makes human-quotable.
278
+ *
279
+ * The reference is quotable but it was not takeable: reading `PM-F-0033` off a toast and typing it
280
+ * into a chat window is transcription, and the reporter routinely wants to hand it straight to an
281
+ * assistant. So it comes with a copy button — which changes what the panel is. A bare
282
+ * acknowledgement should clear itself, because dismissing it is a chore for having done somebody a
283
+ * favour; a panel with something to press should not vanish while you are reaching for it. So it
284
+ * lingers longer, stops counting down the moment it is touched, and grows a close button so a
285
+ * stopped timer is never a trap.
155
286
  */
156
287
  sent() {
157
288
  const note = document.createElement('div');
158
289
  note.className = 'panel panel--sent';
159
290
  note.setAttribute('role', 'status');
291
+ const reference = this.reference;
292
+ const failed = this.uploadsFailed;
160
293
  note.innerHTML = `
161
294
  <div class="sent__tick" aria-hidden="true">&check;</div>
162
- <div>
295
+ <div class="sent__body">
163
296
  <div class="panel__title">Thank you — that is on its way.</div>
164
- ${this.reference
165
- ? `<div class="panel__anchor">Quote <strong>${escapeHtml(this.reference)}</strong> if you follow it up.</div>`
297
+ ${reference
298
+ ? `<div class="sent__ref">
299
+ <code class="sent__id">${escapeHtml(reference)}</code>
300
+ <button type="button" class="sent__copy" data-copy>Copy</button>
301
+ </div>
302
+ <div class="panel__anchor">Quote it if you follow it up.</div>`
166
303
  : ''}
167
- </div>`;
168
- const close = window.setTimeout(() => {
304
+ ${failed > 0
305
+ // Said out loud. The report itself is safe, and the reporter is the only person who can
306
+ // tell that the picture they attached is missing from it — so they are told rather than
307
+ // shown a clean tick over an incomplete report.
308
+ ? `<div class="sent__warn">${failed === 1
309
+ ? 'One attachment could not be uploaded.'
310
+ : `${failed} attachments could not be uploaded.`} The report was filed without it.</div>`
311
+ : ''}
312
+ </div>
313
+ ${reference
314
+ ? '<button type="button" class="panel__close" data-dismiss aria-label="Dismiss">&times;</button>'
315
+ : ''}`;
316
+ const dismiss = () => {
169
317
  if (this.mode !== 'sent')
170
318
  return;
171
319
  this.mode = 'idle';
172
320
  this.render();
173
- }, 6000);
321
+ };
322
+ const close = window.setTimeout(dismiss, failed > 0 ? 20000 : reference ? 12000 : 6000);
323
+ const hold = () => window.clearTimeout(close);
174
324
  this.detach.push(() => window.clearTimeout(close));
325
+ this.contain(note);
326
+ this.place(note);
327
+ if (!reference)
328
+ return note;
329
+ note.addEventListener('pointerenter', hold);
330
+ note.addEventListener('focusin', hold);
331
+ note.querySelector('[data-dismiss]')?.addEventListener('click', dismiss);
332
+ const copy = note.querySelector('[data-copy]');
333
+ if (copy) {
334
+ copy.onclick = async () => {
335
+ hold();
336
+ // Said either way. A copy button that reports nothing leaves the reporter pressing it
337
+ // twice to find out, and one that claims success it did not have is worse than one that
338
+ // admits the page would not allow it — the reference is still on screen to read.
339
+ const ok = await copyText(reference);
340
+ copy.textContent = ok ? 'Copied' : 'Copy failed';
341
+ copy.classList.toggle('sent__copy--done', ok);
342
+ };
343
+ }
175
344
  return note;
176
345
  }
177
346
  launcher() {
@@ -210,9 +379,11 @@ export class FeedbackWidget {
210
379
  // The anchor leads, because it is the thing this widget has that a contact form does not: the
211
380
  // reporter pointed at something, and saying what they pointed at is how they know we understood.
212
381
  // "Report a problem" is a heading anybody could have written; the anchor is theirs.
382
+ const capture = this.capture();
213
383
  panel.innerHTML = `
214
- <div class="panel__head">
215
- <div>
384
+ <div class="panel__head" id="head">
385
+ <span class="panel__grip" aria-hidden="true">⠿</span>
386
+ <div class="panel__heading">
216
387
  <div class="panel__anchor">${escapeHtml(anchorLabel)}</div>
217
388
  <div class="panel__title">Report a problem</div>
218
389
  </div>
@@ -233,10 +404,16 @@ export class FeedbackWidget {
233
404
  <input id="email" type="email" placeholder="Email (optional, so we can reply)" autocomplete="email" />
234
405
 
235
406
  <!-- One attachment area, not two. A checkbox for the screen and a dropzone for a file were
236
- two ways to do the same thing, stacked, both dim. -->
407
+ two ways to do the same thing, stacked, both dim.
408
+
409
+ The capture control is rendered only when it can actually do something. It used to be
410
+ drawn whatever the host had configured and then ignored downstream, so ticking it was a
411
+ promise nobody kept. -->
237
412
  <div id="drop" class="drop">
238
- <label class="shot"><input id="shot" type="checkbox" ${this.options.screenshots === false ? '' : 'checked'} /> Capture the screen</label>
239
- <span class="drop__or">or paste, drop, or
413
+ ${capture.offered
414
+ ? `<label class="shot"><input id="shot" type="checkbox" ${capture.checked ? 'checked' : ''} /> Capture the screen</label>
415
+ <span class="drop__or">or paste, drop, or`
416
+ : '<span class="drop__or">Paste, drop, or'}
240
417
  <input id="file" type="file" multiple accept="image/*,video/mp4,video/quicktime,video/webm" hidden />
241
418
  <button id="browse" class="link">choose a file</button>
242
419
  </span>
@@ -347,14 +524,16 @@ export class FeedbackWidget {
347
524
  send.disabled = true;
348
525
  status.textContent = 'Sending…';
349
526
  try {
350
- this.reference = (await this.onSubmit({
527
+ const outcome = await this.onSubmit({
351
528
  message: message.value.trim(),
352
529
  kind,
353
530
  email: email.value.trim() || undefined,
354
531
  anchor: this.anchor,
355
- withScreenshot: shot.checked,
532
+ withScreenshot: shot?.checked ?? false,
356
533
  files: files.filter(f => !f.error),
357
- })) || null;
534
+ });
535
+ this.reference = outcome.reference;
536
+ this.uploadsFailed = outcome.uploadsFailed;
358
537
  revoke(files);
359
538
  // Confirmed, not just closed.
360
539
  //
@@ -381,8 +560,117 @@ export class FeedbackWidget {
381
560
  submit();
382
561
  };
383
562
  setTimeout(() => message.focus(), 0);
563
+ this.contain(panel);
564
+ this.movable(panel, panel.querySelector('#head'));
384
565
  return panel;
385
566
  }
567
+ /**
568
+ * Keeps the widget's own events inside the widget.
569
+ *
570
+ * We are a guest on somebody else's page, and the host's "close when you click anywhere else"
571
+ * handlers are on the document — which sees a click on our panel, retargeted to our host element,
572
+ * as a click somewhere else. That closed the reporter's own menus under our panel and, on any
573
+ * host that treats an outside click as a dismissal of the thing being reported, moved the ground
574
+ * out from under the report while it was being written.
575
+ *
576
+ * Nothing here dismisses the composer either. It closes by the cross or by Cancel and by nothing
577
+ * else — not Escape, not a click outside, not a focus change — because everything in it was typed
578
+ * by hand and none of those gestures mean "throw that away".
579
+ */
580
+ contain(panel) {
581
+ for (const type of ['pointerdown', 'mousedown', 'click']) {
582
+ panel.addEventListener(type, event => event.stopPropagation());
583
+ }
584
+ }
585
+ }
586
+ /**
587
+ * Copy, on the pages a widget actually runs on.
588
+ *
589
+ * navigator.clipboard is not there on http, in some embedded webviews, and in any context the host
590
+ * page has not marked secure — which is a fair description of where a bug gets reported from. The
591
+ * textarea fallback is the old way and still the only one that works in those places.
592
+ *
593
+ * The scratch textarea goes in the document, not the shadow root: execCommand copies the document's
594
+ * selection, and a selection made inside a shadow root is not the document's.
595
+ */
596
+ export async function copyText(text) {
597
+ try {
598
+ if (navigator.clipboard?.writeText) {
599
+ await navigator.clipboard.writeText(text);
600
+ return true;
601
+ }
602
+ }
603
+ catch {
604
+ // Denied by permissions policy or not focused. The fallback below still often works.
605
+ }
606
+ const scratch = document.createElement('textarea');
607
+ scratch.value = text;
608
+ scratch.setAttribute('readonly', '');
609
+ scratch.style.cssText = 'position:fixed;top:0;left:0;width:1px;height:1px;opacity:0';
610
+ document.body.appendChild(scratch);
611
+ try {
612
+ scratch.select();
613
+ return document.execCommand('copy');
614
+ }
615
+ catch {
616
+ return false;
617
+ }
618
+ finally {
619
+ scratch.remove();
620
+ }
621
+ }
622
+ /** How close to an edge counts as "put it against that edge", and the margin it lands on. */
623
+ const SNAP = 72;
624
+ const EDGE = 16;
625
+ /** Enough of the header must stay reachable to drag it back. */
626
+ const HANDLE = 56;
627
+ const PLACEMENT_KEY = 'pm.feedback.placement';
628
+ function placementOf(rect) {
629
+ const h = rect.left + rect.width / 2 < window.innerWidth / 2 ? 'left' : 'right';
630
+ const v = rect.top + rect.height / 2 < window.innerHeight / 2 ? 'top' : 'bottom';
631
+ const dx = h === 'left' ? rect.left : window.innerWidth - rect.right;
632
+ const dy = v === 'top' ? rect.top : window.innerHeight - rect.bottom;
633
+ // Let go near a side and it pins flush to it, at the same margin the launcher uses. Dropping it
634
+ // "roughly against the left edge" should read as against the left edge, not as 9px off it.
635
+ return {
636
+ h,
637
+ v,
638
+ dx: dx < SNAP ? EDGE : Math.round(dx),
639
+ dy: dy < SNAP ? EDGE : Math.round(dy),
640
+ };
641
+ }
642
+ function readPlacement() {
643
+ try {
644
+ const raw = localStorage.getItem(PLACEMENT_KEY);
645
+ if (!raw)
646
+ return null;
647
+ const parsed = JSON.parse(raw);
648
+ // Validated rather than trusted: this is storage the host page can also write to, and the
649
+ // values go straight into a style property.
650
+ return (parsed.h === 'left' || parsed.h === 'right')
651
+ && (parsed.v === 'top' || parsed.v === 'bottom')
652
+ && Number.isFinite(parsed.dx) && Number.isFinite(parsed.dy)
653
+ ? parsed
654
+ : null;
655
+ }
656
+ catch {
657
+ return null;
658
+ }
659
+ }
660
+ function writePlacement(placement) {
661
+ try {
662
+ if (placement)
663
+ localStorage.setItem(PLACEMENT_KEY, JSON.stringify(placement));
664
+ else
665
+ localStorage.removeItem(PLACEMENT_KEY);
666
+ }
667
+ catch {
668
+ // Private mode, or a full quota. Losing where the panel was put is not worth an exception on
669
+ // somebody else's page.
670
+ }
671
+ }
672
+ function clamp(value, min, max) {
673
+ return Math.min(Math.max(value, min), max);
386
674
  }
387
675
  function escapeHtml(value) {
388
676
  return value.replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
@@ -446,8 +734,17 @@ const STYLES = `
446
734
  position: fixed; inset: 0; pointer-events: auto; cursor: crosshair;
447
735
  background: rgba(23,23,23,.12);
448
736
  }
737
+ /*
738
+ Bottom, not top.
739
+
740
+ At top:16px this landed on whatever the host puts at the top centre of their page — a logo, a
741
+ nav bar, a search field. We are a guest here and we do not know what is up there; on our own app
742
+ it covered the project switcher. The bottom centre is beside the launcher the reporter just
743
+ clicked, which is space the widget already owns, and it keeps their eyes near the thing they are
744
+ about to point at rather than sending them to the far edge of the screen and back.
745
+ */
449
746
  .hint {
450
- position: fixed; left: 50%; top: 16px; transform: translateX(-50%);
747
+ position: fixed; left: 50%; bottom: 76px; transform: translateX(-50%);
451
748
  padding: 7px 12px; border-radius: 8px; background: #171717; color: #fafafa;
452
749
  font-size: 12px; white-space: nowrap;
453
750
  }
@@ -463,8 +760,25 @@ kbd {
463
760
  box-shadow: 0 8px 32px rgba(0,0,0,.24); font-size: 13px;
464
761
  }
465
762
  .panel__head { display: flex; align-items: flex-start; gap: 8px; margin-bottom: 10px }
763
+ .panel__heading { min-width: 0 }
466
764
  .panel__title { font-weight: 600; font-size: 14px }
467
765
 
766
+ /*
767
+ The header is the handle.
768
+
769
+ A 380px panel sits over the page somebody is reporting a problem with, and reading what is under
770
+ it used to mean closing the widget and losing what had been written. touch-action:none because a
771
+ drag on a touch screen is otherwise claimed by the page's own scrolling before we see it.
772
+ */
773
+ .drag { cursor: grab; touch-action: none; user-select: none }
774
+ .drag:active { cursor: grabbing }
775
+ .panel__grip { flex: none; color: #bdbdbd; font-size: 15px; line-height: 16px; letter-spacing: -1px }
776
+ .drag:hover .panel__grip { color: #a3a3a3 }
777
+ .panel--dragging { box-shadow: 0 16px 48px rgba(0,0,0,.32); opacity: .92 }
778
+
779
+ /* An incomplete report, said plainly. Amber rather than red: the words arrived. */
780
+ .sent__warn { margin-top: 6px; color: #b45309; font-size: 11px; line-height: 1.4 }
781
+
468
782
  /* The anchor leads: it is what the reporter pointed at, and the part they need to recognise. */
469
783
  .panel__anchor {
470
784
  color: #737373; font-size: 11px;
@@ -477,12 +791,27 @@ kbd {
477
791
  .panel__close:hover { color: #171717 }
478
792
 
479
793
  /* A confirmation, not a form. */
480
- .panel--sent { display: flex; align-items: center; gap: 10px }
794
+ .panel--sent { display: flex; align-items: flex-start; gap: 10px }
481
795
  .sent__tick {
482
796
  flex: none; width: 24px; height: 24px; border-radius: 999px;
483
797
  background: #ecfdf5; color: #047857;
484
798
  display: grid; place-items: center; font-size: 14px;
485
799
  }
800
+ .sent__body { min-width: 0 }
801
+
802
+ /* The reference on its own line, at its own weight: it is the one thing here to take away. */
803
+ .sent__ref { display: flex; align-items: center; gap: 6px; margin: 4px 0 2px }
804
+ .sent__id {
805
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px;
806
+ color: #171717; background: #f5f5f5; border-radius: 5px; padding: 2px 6px;
807
+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
808
+ }
809
+ .sent__copy {
810
+ flex: none; border: 1px solid #e5e5e5; border-radius: 6px; background: #fff;
811
+ color: #525252; cursor: pointer; font-size: 11px; padding: 3px 8px;
812
+ }
813
+ .sent__copy:hover { border-color: #a3a3a3; color: #171717 }
814
+ .sent__copy--done { border-color: #a7f3d0; background: #ecfdf5; color: #047857 }
486
815
 
487
816
  .panel__kinds { display: flex; gap: 6px; margin: 8px 0 }
488
817
  .kind {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@daybook/feedback",
3
- "version": "1.1.1",
3
+ "version": "1.2.0",
4
4
  "description": "In-app feedback for the web: point at what is wrong, and everything a triager needs is captured automatically.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",