@webority/support-react 0.128.0 → 0.129.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
@@ -1,6 +1,6 @@
1
1
  # @webority/support-react
2
2
 
3
- Customer support for a React portal: a ticket centre, live chat with an AI assistant and a support agent, a report-an-issue button that
3
+ Customer support for a React portal: a ticket centre, a report-an-issue button that
4
4
  can attach a screenshot of the page when the person asks for one, and support contact details. It talks to the Webority Support API that
5
5
  the product's backend hosts, and it is built on `@webority/ui-react` and `@webority/theme`, so it
6
6
  looks like the rest of the portal with no extra CSS.
@@ -8,13 +8,12 @@ looks like the rest of the portal with no extra CSS.
8
8
  ## Install
9
9
 
10
10
  ```bash
11
- npm install @webority/support-react @webority/chat-react @webority/ui-react react-bootstrap bootstrap@5.3.3
11
+ npm install @webority/support-react @webority/ui-react react-bootstrap bootstrap@5.3.3
12
12
  ```
13
13
 
14
14
  `@webority/ui-react`, `react`, `react-dom`, `react-bootstrap` and `bootstrap` are peer
15
15
  dependencies: the portal already has them. Pin `@webority/support-react` to the same exact
16
- version as `@webority/ui-react`. `@webority/chat-react` is a peer too (the chat screen reuses its
17
- composer and Markdown): pin it to the same exact version. The screenshot uses `html-to-image`, which
16
+ version as `@webority/ui-react`. The screenshot uses `html-to-image`, which
18
17
  installs with the package.
19
18
 
20
19
  ## Set up the provider
@@ -50,28 +49,10 @@ in. It defaults to `Asia/Kolkata`; times read `06-Oct-2026, 1:10 PM`.
50
49
 
51
50
  `createSupportClient(http, basePath = "/api/support")` accepts any axios-like instance with
52
51
  `get(url, config)` and `post(url, data, config)` that resolve to `{ data }`. The second argument
53
- is the base path as a string, or as `{ base }` the way `createChatClient(http, { base })` takes
54
- it: `createSupportClient(userClient, { base: "/api/support" })`. Every method
52
+ is the base path as a string, or as `{ base }`: `createSupportClient(userClient, { base: "/api/support" })`. Every method
55
53
  rejects with a `SupportApiError` carrying `code`, `status` and a `message` written for the
56
54
  person, which the components show as-is.
57
55
 
58
- The chat takes two objects built once, over the same signed-in instance:
59
-
60
- ```jsx
61
- const chatClient = createSupportChatClient({ http: userClient, baseUrl: "/api/support" });
62
- const connection = createSseChatConnection({
63
- http: userClient,
64
- baseUrl: "/api/support",
65
- retryDelaysMs: [1000, 2000, 5000, 10000],
66
- });
67
- ```
68
-
69
- A host on another origin must allow the `Idempotency-Key` request header in its CORS policy, or retried messages fail.
70
-
71
- `createSupportChatClient({ http, baseUrl = "/api/support" })` sends the chat's requests. `createSseChatConnection({ http, baseUrl = "/api/support", retryDelaysMs, stallTimeoutMs = 45000 })`
72
- opens the live stream. `retryDelaysMs` is the wait in milliseconds before each reconnect; the last
73
- entry repeats. `stallTimeoutMs` is how long the stream may go quiet before it is reopened.
74
-
75
56
  `listTickets` returns one page, most recently updated first, in the shape
76
57
  `{ items, page, pageSize, totalCount, totalPages }`. Every query part is optional: `status` is one
77
58
  of `Open`, `NeedsReply`, `Resolved` or `Withdrawn`, `search` matches the subject or the ticket
@@ -95,7 +76,7 @@ the customer side, and its `version` is for support staff only; the components u
95
76
  `confirmAction` is the person's yes to a support action an assistant prepared: raise a ticket,
96
77
  reply on one, or reopen one. Only this call completes the action. It resolves to the ticket it
97
78
  acted on (with `id` and `number`), and an expired or unknown token rejects with the code
98
- `action_expired`. `@webority/chat-react`'s `ActionCard` takes it as its `confirmAction`.
79
+ `action_expired`.
99
80
 
100
81
  ## Components
101
82
 
@@ -160,16 +141,7 @@ such as a chat launcher:
160
141
  <ReportIssue className="ms-auto" />
161
142
  ```
162
143
 
163
- With `compact` and `floating`, the button joins the shared floating stack (`useFloatingStack` from
164
- `@webority/ui-react`): one fixed container in the bottom-end corner that the compact chat launcher
165
- from `@webority/chat-react` also uses. The two stack with a gap, the chat launcher in the corner
166
- and this button above it, so neither needs an offset. `className` and `style` then land on the
167
- item inside the stack, which is not itself fixed.
168
-
169
- ```jsx
170
- <ChatLauncher compact onClick={openChat} />
171
- <ReportIssue floating compact appVersion={version} />
172
- ```
144
+ With compact and floating, the button is an `AppFloatingButton` from `@webority/ui-react` and joins the shared floating stack: one fixed container in the bottom-end corner that other `compact` `floating` buttons, such as the chat library's launcher, also use. They stack with a gap, so neither needs an offset. `className` and `style` then land on the item inside the stack, which is not itself fixed.
173
145
 
174
146
  Nothing on the page is captured unless the person asks. The dialog has an "Add a screenshot"
175
147
  button, with the line "Only what is on your screen now. You can remove it before sending." under
@@ -191,76 +163,6 @@ support config. A field the product has not set is left out, and nothing renders
191
163
  <SupportContact />
192
164
  ```
193
165
 
194
- ### `<SupportChat />`
195
-
196
- A live chat drawer. The AI assistant answers first. "Talk to a person" brings a support agent into
197
- the same conversation, and the whole chat is kept on the customer's support ticket.
198
-
199
- ```jsx
200
- <SupportProvider client={supportClient}>
201
- <SupportChatLauncher onClick={() => setOpen(true)} open={open} />
202
- <SupportChat
203
- chatClient={chatClient}
204
- connection={connection}
205
- open={open}
206
- onClose={() => setOpen(false)}
207
- onOpenTicket={(ticket) => navigate(`/support?ticket=${ticket.id}`)}
208
- />
209
- </SupportProvider>
210
- ```
211
-
212
- Build the two clients once, outside render, as shown under set up, and keep the component inside
213
- `SupportProvider`: the chat reads the support config for the message length and the time zone.
214
-
215
- | Prop | Default | What it does |
216
- |---|---|---|
217
- | `chatClient` | required | The client from `createSupportChatClient`. |
218
- | `connection` | required | The live stream from `createSseChatConnection`. |
219
- | `open` | required | Shows the drawer. The session runs only while it is open. |
220
- | `onClose` | required | Called when the drawer closes. |
221
- | `appVersion` | none | Sent when the chat starts, so support knows which build the customer was on. |
222
- | `start` | none | A hand-over into the chat: `{ chatConversationReference, openingLine, wantsPerson }`. A new object starts the chat again, so keep it in state or `useMemo`. |
223
- | `onOpenTicket({ id, number })` | none | Shows a View ticket button when given. |
224
- | `resolveLink(href)` | none | Decides where a link in a message goes; passed to the Markdown renderer. |
225
- | `linkComponent` | none | The component that draws links in messages; passed to the Markdown renderer. |
226
- | `title` | "Chat with us" | The drawer's heading. |
227
- | `width` | "440px" | The drawer's width. |
228
-
229
- The chat moves through these states:
230
-
231
- - **Assistant answering**: the assistant's reply appears as it is written.
232
- - **Waiting**: "Waiting for a person", with the number of people ahead in the queue.
233
- - **With an agent**: the agent's name shows in the status.
234
- - **Ended**: the reason the chat closed, with the ticket number when one was raised.
235
-
236
- Notes: closing the drawer does not end the chat; reopening it returns the same open chat with every
237
- line. A message that fails shows Try again and keeps its key, so a retry never posts twice. The chat
238
- needs the `/chats` routes of the support API. The live stream is a long-lived GET that needs the
239
- browser's XHR adapter (the axios default); with the fetch adapter the events arrive all at once when the request ends.
240
-
241
- ### `<SupportChatLauncher />`
242
-
243
- The button that opens the chat. It sits in the bottom corner of the page.
244
-
245
- ```jsx
246
- <SupportChatLauncher onClick={() => setOpen(true)} open={open} />
247
- <SupportChatLauncher onClick={() => setOpen(true)} compact position="start" />
248
- ```
249
-
250
- | Prop | Default | What it does |
251
- |---|---|---|
252
- | `onClick` | required | Called when the button is pressed. |
253
- | `open` | `false` | Sets `aria-expanded`, for a launcher whose drawer is open. |
254
- | `label` | "Chat with us" | The button text; with `compact` it is the tooltip and accessible name. |
255
- | `position` | `"end"` | The bottom corner it sits in: `"end"` or `"start"`. |
256
- | `icon` | "message-circle" | The icon's name. |
257
- | `compact` | `false` | Icon only, a circle in the shared floating stack. |
258
- | `className` | none | Added to the button's wrapper, to place it. |
259
- | `style` | none | Merged over the wrapper's own style. |
260
-
261
- Place it with `className` or `style`, as with `<ReportIssue />`. With `compact`, it joins the shared
262
- floating stack beside `<ReportIssue />` and needs no offset.
263
-
264
166
  ## Hooks
265
167
 
266
168
  `useSupportConfig()`, `useSupportTickets(query)`, `useSupportTicketCounts()` and
@@ -2,7 +2,7 @@
2
2
  "format": "webority-guidance/1",
3
3
  "package": {
4
4
  "name": "@webority/support-react",
5
- "version": "0.128.0"
5
+ "version": "0.129.0"
6
6
  },
7
7
  "components": [
8
8
  {
@@ -40,44 +40,6 @@
40
40
  ]
41
41
  }
42
42
  },
43
- {
44
- "name": "SupportChat",
45
- "usage": {
46
- "when": [
47
- "A portal offers live chat: an AI assistant answers first and the customer can ask for a person in the same conversation.",
48
- "The conversation is kept on the customer's support ticket."
49
- ],
50
- "whenNot": [
51
- {
52
- "text": "A one-way report or a long description of a problem.",
53
- "instead": "ReportIssue"
54
- }
55
- ],
56
- "do": [],
57
- "dont": [],
58
- "a11y": [
59
- "The chat opens as a dialog drawer, focuses the message box and closes on Escape.",
60
- "Status changes (waiting, joined, ended) are announced as polite status messages.",
61
- "A failed message says so and offers Try again and Discard."
62
- ]
63
- }
64
- },
65
- {
66
- "name": "SupportChatLauncher",
67
- "usage": {
68
- "when": [
69
- "The floating pill that opens the support chat, pinned to a bottom corner."
70
- ],
71
- "whenNot": [],
72
- "do": [],
73
- "dont": [],
74
- "a11y": [
75
- "The button announces that it opens a dialog (aria-haspopup) and whether it is open (aria-expanded).",
76
- "The default pill shows the label as its button text.",
77
- "The compact circle takes the label as its accessible name and as its tooltip."
78
- ]
79
- }
80
- },
81
43
  {
82
44
  "name": "SupportContact",
83
45
  "usage": {
@@ -1,12 +1 @@
1
- import{createContext as e,useCallback as t,useContext as n,useEffect as r,useId as i,useMemo as a,useRef as o,useState as s}from"react";import{AppActionIcon as c,AppAlert as l,AppAvatar as u,AppBadge as d,AppButton as f,AppCard as p,AppChip as m,AppChipGroup as h,AppConfirmDialog as g,AppCopyButton as _,AppDataTable as v,AppDescriptions as y,AppDrawer as b,AppEmptyState as x,AppFileAttachment as S,AppFormActions as C,AppIcon as w,AppInput as T,AppLink as E,AppModal as D,AppSearch as O,AppSelect as k,AppSkeleton as A,AppSpinner as j,AppStatusBadge as M,AppTabs as N,AppTextarea as P,useFloatingStack as F,warnInvalidValue as I}from"@webority/ui-react";import{toBlob as L}from"html-to-image";import{createPortal as R}from"react-dom";import{IST_TIME_ZONE as z,formatDateTime as B,formatFileSize as V,timeZoneLabel as ee}from"@webority/ui-elements/helpers";import{Fragment as H,jsx as U,jsxs as W}from"react/jsx-runtime";import{ChatComposer as te,ChatMarkdown as ne,DEFAULT_CHAT_LABELS as re}from"@webority/chat-react";var G=`Something went wrong. Please try again.`,K=class extends Error{constructor(e,t,n){super(t),this.name=`SupportApiError`,this.code=e,this.status=n}};async function ie(e){if(e&&typeof Blob<`u`&&e instanceof Blob)try{return JSON.parse(await e.text())}catch{return null}if(typeof e==`string`)try{return JSON.parse(e)}catch{return null}return e??null}async function ae(e){if(e instanceof K)return e;let t=e?.response;if(!t)return new K(`network`,G);let n=await ie(t.data);return new K(typeof n?.code==`string`&&n.code?n.code:`unknown`,typeof n?.detail==`string`&&n.detail.trim()?n.detail:G,t.status)}async function q(e){try{return(await e()).data}catch(e){throw await ae(e)}}function J(e,t,n){n!=null&&String(n).trim()!==``&&e.append(t,String(n))}function oe(e,t,n,r){(n??[]).forEach((n,i)=>{let a=n?.name||`${r}-${i+1}.png`;e.append(t,n,a)})}var se=20;function ce(e,t){return(e??[]).map((e,n)=>e?.name||`${t}-${n+1}.png`).join(`|`)}function le(e){return e instanceof K&&typeof e.status==`number`&&e.status>=400&&e.status<=499&&e.status!==408&&e.status!==429}function ue(e,t=`/api/support`){let n=(typeof t==`string`?t:t?.base??`/api/support`).replace(/\/+$/,``),r=e=>`${n}/tickets/${encodeURIComponent(e)}`,i=/* @__PURE__ */ new Map,a=/* @__PURE__ */ new Map;function o(){for(let e of i.keys()){if(i.size<=se)return;a.has(e)||i.delete(e)}}async function s(e,t){let n=i.get(e)||crypto.randomUUID();i.delete(e),i.set(e,n),a.set(e,(a.get(e)??0)+1),o();try{let r=await t(n);return i.delete(e),r}catch(t){throw le(t)&&i.delete(e),t}finally{let t=a.get(e)-1;t>0?a.set(e,t):a.delete(e)}}return{getConfig:()=>q(()=>e.get(`${n}/settings`)),listTickets:({status:t,search:r,page:i,pageSize:a}={})=>{let o=new URLSearchParams;J(o,`status`,t),J(o,`search`,r?.trim()),J(o,`page`,i),J(o,`pageSize`,a);let s=o.toString();return q(()=>e.get(`${n}/tickets${s?`?${s}`:``}`))},getTicketCounts:()=>q(()=>e.get(`${n}/tickets/counts`)),getTicket:t=>q(()=>e.get(r(t))),createTicket:({category:t,subject:r,body:i,pageUrl:a,userAgent:o,appVersion:c,files:l,screenshots:u})=>{let d=new FormData;return d.append(`category`,t??``),d.append(`subject`,r??``),d.append(`body`,i??``),J(d,`pageUrl`,a),J(d,`userAgent`,o),J(d,`appVersion`,c),oe(d,`files`,l,`file`),oe(d,`screenshots`,u,`screenshot`),s([`ticket`,t,r,i,ce(l,`file`),ce(u,`screenshot`)].join(`\0`),t=>q(()=>e.post(`${n}/tickets`,d,{headers:{"Idempotency-Key":t}})))},getSuggestions:async(t,{signal:r}={})=>{try{return await q(()=>e.get(`${n}/suggestions`,{params:{subject:t},signal:r}))}catch(e){if(e instanceof K&&e.status===404)return[];throw e}},reply:(t,{body:n,files:i,screenshots:a})=>{let o=new FormData;return o.append(`body`,n??``),oe(o,`files`,i,`file`),oe(o,`screenshots`,a,`screenshot`),s([`reply`,t,n,ce(i,`file`),ce(a,`screenshot`)].join(`\0`),n=>q(()=>e.post(`${r(t)}/replies`,o,{headers:{"Idempotency-Key":n}})))},reopen:t=>q(()=>e.post(`${r(t)}/reopen`)),cancel:t=>q(()=>e.post(`${r(t)}/cancel`)),rate:(t,{satisfaction:n,comment:i})=>{let a={satisfaction:n};return i!=null&&i.trim()!==``&&(a.comment=i.trim()),q(()=>e.post(`${r(t)}/rating`,a))},fetchAttachment:t=>q(()=>e.get(`${n}/attachments/${encodeURIComponent(t)}`,{responseType:`blob`})),confirmAction:t=>q(()=>e.post(`${n}/actions/confirm`,{token:t}))}}var de=`Something went wrong. Please try again.`;async function fe(e){if(e&&typeof Blob<`u`&&e instanceof Blob)try{return JSON.parse(await e.text())}catch{return null}if(typeof e==`string`)try{return JSON.parse(e)}catch{return null}return e??null}async function pe(e){if(e instanceof K)return e;let t=e?.response;if(!t)return new K(`network`,de);let n=await fe(t.data);return new K(typeof n?.code==`string`&&n.code?n.code:`unknown`,typeof n?.message==`string`&&n.message?n.message:de,t.status)}async function Y(e){try{return(await e()).data}catch(e){throw await pe(e)}}function me({http:e,baseUrl:t=`/api/support`}){let n=t.replace(/\/+$/,``),r=e=>`${n}/chats/${encodeURIComponent(e)}`;return{start:t=>{let r={};for(let e of[`pageUrl`,`userAgent`,`appVersion`,`chatConversationReference`,`openingLine`]){let n=t?.[e];typeof n==`string`&&n.trim()!==``&&(r[e]=n)}return t?.wantsPerson===!0&&(r.wantsPerson=!0),Y(()=>e.post(`${n}/chats`,r))},current:()=>Y(()=>e.get(`${n}/chats/current`)),get:t=>Y(()=>e.get(r(t))),send:async(t,{body:n,files:i,idempotencyKey:a})=>{if(typeof a!=`string`||a.trim()===``)throw TypeError(`send needs an idempotencyKey from crypto.randomUUID().`);let o=new FormData;return o.append(`body`,n??``),(i??[]).forEach((e,t)=>{o.append(`files`,e,e?.name||`file-${t+1}.png`)}),Y(()=>e.post(`${r(t)}/messages`,o,{headers:{"Idempotency-Key":a}}))},requestAgent:t=>Y(()=>e.post(`${r(t)}/agent`)),typing:async t=>{await Y(()=>e.post(`${r(t)}/typing`))},close:t=>Y(()=>e.post(`${r(t)}/close`))}}var he=e=>{let t=``,n=t=>{let n=`message`,r=[];for(let e of t.split(`
2
- `)){if(e===``||e.startsWith(`:`))continue;let t=e.indexOf(`:`),i=t===-1?e:e.slice(0,t),a=t===-1?``:e.slice(t+1);a.startsWith(` `)&&(a=a.slice(1)),i===`event`?n=a:i===`data`&&r.push(a)}if(r.length===0)return;let i;try{i=JSON.parse(r.join(`
3
- `))}catch{e({name:`error`,data:{code:`invalid-response`,message:null}});return}e({name:n,data:i})};return{push(e){if(!e)return;t=(t+e).replace(/\r\n/g,`
4
- `).replace(/\r(?!$)/g,`
5
- `);let r=t.split(`
6
-
7
- `);t=r.pop()??``;for(let e of r)n(e)},end(){let e=t.replace(/\r$/,``);t=``,e.trim()&&n(e)}}},ge=`Something went wrong. Please try again.`;function _e(e){let t=e?.event?.target;if(t&&typeof t.responseText==`string`&&!(typeof t.status==`number`&&(t.status<200||t.status>=300)))return t.responseText}function ve(e){if(typeof e==`string`)try{return JSON.parse(e)}catch{return null}return e??null}function ye(e){let t=e?.response,n=ve(t?.data),r=typeof n?.code==`string`&&n.code?n.code:`unknown`,i=typeof n?.message==`string`&&n.message?n.message:ge;return{status:t?.status,code:r,message:i}}var be=e=>e===void 0||e===408||e===429||e>=500;function xe(){let e=``,t=null;return{push(n){e=(e+n).replace(/\r\n/g,`
8
- `).replace(/\r(?!$)/g,`
9
- `);let r=e.split(`
10
-
11
- `);e=r.pop();for(let e of r)for(let n of e.split(`
12
- `)){if(!n.startsWith(`id:`))continue;let e=n.slice(3);if(e.startsWith(` `)&&(e=e.slice(1)),!/^\d+$/.test(e))continue;let r=Number(e);t=t===null?r:Math.max(t,r)}},get last(){return t}}}function Se({http:e,baseUrl:t=`/api/support`,retryDelaysMs:n,stallTimeoutMs:r=9e4}){let i=t.replace(/\/+$/,``),a=Array.isArray(n)&&n.length>0?n:[1e3];return{watch(t,n,o){let s=Number.isFinite(n)?n:null,c=!1,l=null,u=null,d=null,f=null,p=!1,m=!1,h=!1,g=null,_=0,v=e=>{Number.isFinite(e)&&(s=Math.max(s??0,e))};function y(e,t){if(!c){m=!0;try{e===`snapshot`?(v(t?.sequence),o.onSnapshot?.(t)):e===`message`?(v(t?.message?.sequence),o.onMessage?.(t)):e===`state`?o.onState?.(t):e===`typing`?o.onTyping?.(t):e===`delta`&&o.onDelta?.(t)}catch{o.onError?.(new K(`handler_failed`,ge))}}}function b(){clearTimeout(u),u=setTimeout(()=>{h=!0,l.abort()},r)}async function x(){l=new AbortController,p=!1,m=!1,h=!1,g=null;let n=0,r=xe(),a=he(({name:e,data:t})=>{c||g||(e===`error`?t?.code===`invalid-response`||t?.code===`stream_ended`?g=`retry`:t?.code===`chat_not_found`?(o.onError?.(t),g=`stop`):(o.onError?.(t),g=`retry`):y(e,t))}),d=e=>{if(c||typeof e!=`string`||e.length<=n)return;let t=e.slice(n);n=e.length,a.push(t),r.push(t),r.last!==null&&(s=Math.max(s??0,r.last)),p=!0,b()},f=`${i}/chats/${encodeURIComponent(t)}/events${s===null?``:`?after=${s}`}`;b();let _;try{_=await e.get(f,{responseType:`text`,headers:{Accept:`text/event-stream`},signal:l.signal,timeout:0,onDownloadProgress:e=>d(_e(e))})}catch(e){if(c)return`stop`;if(h)return`retry`;let t=ye(e);return be(t.status)?`retry`:(o.onError?.({code:t.code,message:t.message}),`stop`)}finally{clearTimeout(u)}return d(_.data),clearTimeout(u),a.end(),g??`retry`}function S(e){return new Promise(t=>{f=t,d=setTimeout(t,e)})}async function C(){let e=0;for(;!c;){let t=await x();if(c||t===`stop`)return;if(p&&(e=0),_=m?0:_+1,_>=10){o.onError?.(new K(`connection_lost`,`We lost the connection to support. Check your internet and try again.`));return}let n=a[Math.min(e,a.length-1)];e+=1,await S(n)}}function w(){c=!0,l?.abort(),clearTimeout(u),clearTimeout(d),f?.()}return C(),w}}}var Ce=3e4,we=e(null);function Te(){let e=n(we);if(!e)throw Error(`Support components and hooks must be used inside <SupportProvider>.`);return e}function X(){return Te().client}function Ee(){return Te().timeZone}function De(){return Te().renderTime??null}function Oe(e,n,i=!0){let[a,c]=s({data:null,loading:i,error:null}),[l,u]=s(0),d=o(e);d.current=e;let f=o(n);r(()=>{let e=f.current!==n;if(f.current=n,!i){c({data:null,loading:!1,error:null});return}let t=!0;return c(t=>({data:e?null:t.data,loading:!0,error:null})),d.current(l>0).then(e=>t&&c({data:e,loading:!1,error:null}),e=>t&&c(t=>({...t,loading:!1,error:e}))),()=>{t=!1}},[n,i,l]);let p=t(()=>u(e=>e+1),[]),m=t(e=>c(t=>({...t,data:typeof e==`function`?e(t.data):e})),[]);return{...a,reload:p,setData:m}}function Z(){let{loadConfig:e}=Te(),{data:t,loading:n,error:r,reload:i}=Oe(e,`config`);return{config:t,loading:n,error:r,reload:i}}function ke(e={}){let t=X(),{status:n,search:r,page:i,pageSize:a}=e,{data:o,loading:s,error:c,reload:l}=Oe(()=>t.listTickets({status:n,search:r,page:i,pageSize:a}),JSON.stringify([`tickets`,n??null,r??null,i??null,a??null]));return{tickets:o?.items??[],totalCount:o?.totalCount??0,totalPages:o?.totalPages??0,loading:s,error:c,reload:l}}function Ae(){let e=X(),{data:t,loading:n,error:r,reload:i}=Oe(()=>e.getTicketCounts(),`ticket-counts`);return{counts:t,loading:n,error:r,reload:i}}function je(e){let n=X(),{data:i,loading:a,error:s,reload:c,setData:l}=Oe(()=>n.getTicket(e),e??``,!!e),u=o(0),d=o(e);d.current=e;let f=t(async e=>{u.current+=1;try{let t=await e();return l(t),t}finally{--u.current}},[l]),p=t(async()=>{if(u.current>0)return;let t=e;try{let e=await n.getTicket(t);if(d.current!==t)return;l(t=>t?Date.parse(e.updatedDateTimeUtc)>=Date.parse(t.updatedDateTimeUtc)?e:t:e)}catch{}},[n,e,l]);return r(()=>{if(!e)return;let t=null,n=()=>{t===null&&(t=setInterval(p,Ce))},r=()=>{t!==null&&clearInterval(t),t=null},i=()=>{document.hidden?r():(p(),n())};return document.addEventListener(`visibilitychange`,i),document.hidden||n(),()=>{r(),document.removeEventListener(`visibilitychange`,i)}},[e,p]),{ticket:i,loading:a,error:s,reload:c,reply:t(t=>f(()=>n.reply(e,t)),[f,n,e]),reopen:t(()=>f(()=>n.reopen(e)),[f,n,e]),cancel:t(()=>f(()=>n.cancel(e)),[f,n,e]),rate:t(t=>f(()=>n.rate(e,t)),[f,n,e])}}var Me=`We could not reach support. Check your connection and try again.`;function Q(e,t){if(e instanceof K){if(e.code===`network`)return Me;if(e.code!==`unknown`)return e.message}return t}function Ne(e){return(e?.allowedContentTypes??[]).join(`,`)}function Pe(e,t){if(t.length===0)return!0;let n=(e||``).toLowerCase();return t.some(e=>{let t=e.toLowerCase();return t.endsWith(`/*`)?n.startsWith(t.slice(0,-1)):n===t})}function Fe(e,t){let n=e??[],r=t?.maxAttachmentsPerMessage??0,i=t?.maxAttachmentBytes??0,a=t?.allowedContentTypes??[];if(r>0&&n.length>r)return r===1?`You can attach one file.`:`You can attach up to ${r} files.`;for(let e of n){let t=e.name||`This file`;if(!Pe(e.type,a))return`${t} is a file type we cannot accept.`;if(i>0&&e.size>i)return`${t} is larger than ${V(i)}.`}return null}var Ie=e=>e===1?`You can attach one file.`:`You can attach up to ${e} files.`;function Le(e){return`${e.name}|${e.size}|${e.lastModified}`}function Re(e,t,n){let r=n?.maxAttachmentsPerMessage??0,i=new Set(e.map(Le)),a=[],o=null;for(let e of t){let t=Le(e);i.has(t)?o??=e.name:(i.add(t),a.push(e))}let s=r>0?Math.max(0,r-e.length):a.length,c=[...e,...a.slice(0,s)];return{files:c,notice:(a.length>s?Ie(r):null)??Fe(c,n)??(o?`${o} is already attached.`:``)}}function ze(e){let t=Array.from(e.clipboardData?.items??[]),n=Date.now();return t.filter(e=>e.kind===`file`&&e.type.startsWith(`image/`)).map(e=>e.getAsFile()).filter(Boolean).map((e,t)=>{let r=(e.type.split(`/`)[1]||`png`).replace(`jpeg`,`jpg`);return new File([e],`pasted-image-${n}-${t+1}.${r}`,{type:e.type})})}var Be=80;function Ve(e,t){let n=Math.min(t,Be),r=(e??``).split(/\r?\n/).find(e=>e.trim()!==``);if(r===void 0)return``;let i=r.replace(/\s+/g,` `).trim();if(i.length<=n)return i;let a=i.slice(0,n+1).lastIndexOf(` `);return(a>0?i.slice(0,a):i.slice(0,n)).replace(/[ ,;:.-]+$/,``)}function He(e,t){let[n,i]=s(e);return r(()=>{let n=setTimeout(()=>i(e),t);return()=>clearTimeout(n)},[e,t]),n}function Ue({id:e,label:t=`Attachments`,files:n,onChange:r,config:i,error:a}){let o=i?.maxAttachmentBytes??0,s=o>0?Math.max(.1,Math.round(o/1048576*10)/10):0;return/* @__PURE__ */ U(S,{id:e,label:t,optional:!0,multiple:!0,value:n,onChange:r,accept:Ne(i),maxSizeMb:s,validate:!1,error:a||void 0})}function We({items:e}){return e.length===0?null:/* @__PURE__ */ U(p,{variant:`muted`,padding:`sm`,title:`These may already answer your question`,children:/* @__PURE__ */ U(`ul`,{className:`list-unstyled mb-0 d-flex flex-column gap-2`,children:e.map(e=>/* @__PURE__ */ W(`li`,{children:[/* @__PURE__ */ U(`div`,{className:`fw-semibold`,children:e.title}),/* @__PURE__ */ U(`div`,{className:`small text-body-secondary`,children:e.summary})]},e.title))})})}var Ge=500,Ke=3,qe=5;function Je(e,t){return t&&e.includes(t)?t:``}function Ye({id:e,config:t,defaultCategory:n,initialValues:i,onValuesChange:a,extraFiles:o=[],onSubmit:c,onBusyChange:u,children:d}){let f=t?.categories??[],p=t?.subjectMaxLength??1/0,[m,h]=s(()=>i?.category??Je(f,n)),[g,_]=s(i?.body??``),[v,y]=s(()=>i?.subject||Ve(i?.body??``,p)),[b,x]=s(()=>{let e=(i?.subject??``).trim();return e!==``&&e!==Ve(i?.body??``,p)}),[S,C]=s(i?.files??[]),[w,E]=s({}),[D,O]=s(``),A=X(),[j,M]=s(``),[N,F]=s([]),I=He(v.trim(),Ge);r(()=>{a?.({category:m,subject:v,body:g,files:S})},[m,v,g,S,a]),r(()=>{M(I)},[I]),r(()=>{if(j.length<Ke){F([]);return}let e=!0,t=new AbortController;return F([]),A.getSuggestions(j,{signal:t.signal}).then(t=>{e&&F(Array.isArray(t)?t.slice(0,qe):[])},()=>{e&&F([])}),()=>{e=!1,t.abort()}},[A,j]);let L=e=>{C(e),E(n=>({...n,files:Fe([...o,...e],t)??void 0}))},R=e=>{let t=ze(e);t.length>0&&L([...S,...t])},z=e=>{let t=e.target.value;_(t),b||y(Ve(t,p)),w.body&&E(e=>({...e,body:t.trim()?void 0:`Enter what happened.`}))},B=e=>{let t=e.target.value;y(t),x(t.trim()!==``)};function V(){let e={};g.trim()||(e.body=`Enter what happened.`);let n=Fe([...o,...S],t);return n&&(e.files=n),E(e),Object.keys(e).length===0}async function ee(e){if(e.preventDefault(),O(``),V()){u?.(!0);try{await c({category:m,subject:v.trim()||Ve(g,p),body:g.trim(),files:S})}catch(e){O(Q(e,`Your ticket did not send. Please try again.`))}finally{u?.(!1)}}}return/* @__PURE__ */ W(`form`,{id:e,onSubmit:ee,noValidate:!0,className:`d-flex flex-column gap-3`,children:[D&&/* @__PURE__ */ U(l,{tone:`danger`,children:D}),/* @__PURE__ */ U(P,{id:`${e}-body`,label:`Message`,required:!0,rows:6,maxLength:t?.bodyMaxLength,showCount:!0,placeholder:`What happened, and what did you expect to happen?`,value:g,onChange:z,onPaste:R,hint:`You can paste an image into the message.`,error:w.body}),/* @__PURE__ */ U(T,{id:`${e}-subject`,label:`Subject`,maxLength:t?.subjectMaxLength,showCount:!0,placeholder:`A short summary`,hint:`Filled in from your message. You can change it.`,value:v,onChange:B,onBlur:()=>M(v.trim())}),/* @__PURE__ */ U(We,{items:N}),/* @__PURE__ */ U(k,{id:`${e}-category`,label:`Category (optional)`,value:m,onChange:h,options:f.map(e=>({value:e,label:e})),placeholder:`Choose a category`,hint:`Not sure? Leave it empty and we will sort it.`,error:w.category}),d,/* @__PURE__ */ U(Ue,{id:`${e}-files`,files:S,onChange:L,config:t,error:w.files})]})}var Xe=`supportCapture`,Ze={zIndex:`var(--wui-z-fixed)`,bottom:0,insetInlineEnd:0},Qe={zIndex:`var(--wui-z-fixed)`},$e={maxWidth:`20rem`},et=e=>e.dataset?.[Xe]===`exclude`||e.matches?.(`.modal-backdrop`)?!1:!(e.matches?.(`.modal`)&&e.querySelector?.(`[data-support-capture="exclude"]`)),tt=()=>new Promise(e=>requestAnimationFrame(()=>e()));async function nt(){let e=await L(document.body,{filter:et,pixelRatio:Math.min(window.devicePixelRatio||1,2),style:{overflow:`visible`,paddingRight:`0px`}});if(!e)throw Error(`The page capture came back empty.`);return new File([e],`screenshot.png`,{type:`image/png`})}function rt({file:e,failed:t,disabled:n,hintId:i,controlRef:a,onAdd:o,onRemove:c}){let[u,d]=s(null);return r(()=>{if(!e)return;let t=URL.createObjectURL(e);return d(t),()=>URL.revokeObjectURL(t)},[e]),/* @__PURE__ */ W(`div`,{className:`d-flex flex-column gap-2`,children:[/* @__PURE__ */ U(`span`,{className:`wui-text-sm fw-semibold`,children:`Screenshot`}),e&&u&&/* @__PURE__ */ U(`img`,{src:u,alt:`Screenshot of the page you were on`,className:`d-block w-100 border rounded`,style:$e}),/* @__PURE__ */ U(`div`,{ref:a,className:`d-flex flex-wrap gap-2`,children:e?/* @__PURE__ */ W(H,{children:[/* @__PURE__ */ U(f,{variant:`outline`,size:`sm`,leftIcon:`refresh-cw`,onClick:o,disabled:n,"aria-describedby":i,children:`Retake`}),/* @__PURE__ */ U(f,{variant:`ghost`,size:`sm`,leftIcon:`x`,onClick:c,disabled:n,children:`Remove screenshot`})]}):/* @__PURE__ */ U(f,{variant:`outline`,size:`sm`,leftIcon:`camera`,onClick:o,disabled:n,"aria-describedby":i,children:`Add a screenshot`})}),/* @__PURE__ */ U(`span`,{id:i,className:`wui-text-sm text-body-secondary`,children:`Only what is on your screen now. You can remove it before sending.`}),t&&/* @__PURE__ */ U(l,{tone:`info`,children:`We could not take a screenshot of this page. You can attach an image instead, or send the report without one.`})]})}function it({label:e=`Report an issue`,floating:t=!1,compact:n=!1,defaultCategory:a=`Bug report`,appVersion:c,getTicketHref:u,onOpenTicket:d,onCreated:p,className:m,style:h}){let g=X(),{config:_,error:v}=Z(),y=`support-report-${i().replace(/[^a-zA-Z0-9-]/g,``)}`,[b,x]=s(!1),[S,C]=s(!1),[T,E]=s(null),[O,k]=s(!1),[A,j]=s(!1),[M,N]=s(null),[P,I]=s(null),L=F(`end`,t&&n),z=o(null),B=o(!1);r(()=>{!S&&B.current&&(B.current=!1,z.current?.querySelector(`button`)?.focus())},[S]);function V(){N(null),E(null),k(!1),I(null),x(!0)}async function ee(){C(!0),k(!1),await tt(),await tt();try{E(await nt())}catch{E(null),k(!0)}finally{B.current=!0,C(!1)}}let te=()=>{A||(x(!1),E(null),k(!1),N(null),I(null))};async function ne(e){let t=await g.createTicket({...e,pageUrl:window.location.href,userAgent:navigator.userAgent,appVersion:c,screenshots:T?[T]:[]});N(t),E(null),p?.(t)}let re=!M&&(!!T||!!P&&(P.subject.trim()!==``||P.body.trim()!==``||P.files.length>0)),G=M&&u?u(M.id):void 0,K=M?/* @__PURE__ */ W(`div`,{className:`d-flex justify-content-end gap-2 w-100`,children:[/* @__PURE__ */ U(f,{variant:`secondary`,onClick:te,children:`Close`}),M&&(G||d)?/* @__PURE__ */ U(f,{href:G,onClick:G?void 0:()=>{x(!1),N(null),d(M)},children:`View ticket`}):null]}):/* @__PURE__ */ W(`div`,{className:`d-flex justify-content-end gap-2 w-100`,children:[/* @__PURE__ */ U(f,{variant:`secondary`,onClick:te,disabled:A,children:`Cancel`}),/* @__PURE__ */ U(f,{type:`submit`,form:y,loading:A,disabled:!_,children:`Submit`})]}),ie=n?/* @__PURE__ */ U(f,{variant:`secondary`,className:`wui-floating-btn wui-floating-btn--secondary`,disabled:S,onClick:V,"aria-haspopup":`dialog`,"aria-label":e,tooltip:e,tooltipPlacement:`start`,children:/* @__PURE__ */ U(w,{name:`bug`,size:22})}):/* @__PURE__ */ U(f,{leftIcon:`bug`,variant:t?`primary`:`outline`,disabled:S,onClick:V,"aria-haspopup":`dialog`,children:e});return/* @__PURE__ */ W(H,{children:[t&&n?L&&R(/* @__PURE__ */ U(`span`,{className:[`wui-floating-stack-item wui-floating-stack-item--secondary`,m].filter(Boolean).join(` `),style:h,children:ie}),L):/* @__PURE__ */ U(`span`,{"data-support-capture":`exclude`,className:[t?`position-fixed m-3`:`d-inline-block`,m].filter(Boolean).join(` `),style:t?{...Ze,...h}:h,children:ie}),S&&/* @__PURE__ */ W(`div`,{"data-support-capture":`exclude`,role:`status`,className:`position-fixed top-0 start-50 translate-middle-x mt-3 d-flex align-items-center gap-2 px-3 py-2 bg-body border rounded-pill shadow-sm wui-text-sm`,style:Qe,children:[/* @__PURE__ */ U(`span`,{className:`spinner-border spinner-border-sm`,"aria-hidden":`true`}),`Taking a screenshot`]}),/* @__PURE__ */ U(D,{open:b,size:`lg`,title:`Report an issue`,subtitle:`Tell us what went wrong. You can add a screenshot of this page if it helps.`,headerIcon:`bug`,confirmDiscard:`Discard this report?`,dirty:re&&!A,onClose:te,footer:K,"data-support-capture":`exclude`,children:M?/* @__PURE__ */ U(l,{tone:`success`,role:`status`,title:`Ticket ${M.number} is with the support team`,children:`We reply by email. You can follow the ticket on your support page.`}):_?/* @__PURE__ */ U(Ye,{id:y,config:_,defaultCategory:a,initialValues:P,onValuesChange:I,extraFiles:T?[T]:[],onSubmit:ne,onBusyChange:j,children:/* @__PURE__ */ U(rt,{file:T,failed:O,disabled:A||S,hintId:`${y}-screenshot-hint`,controlRef:z,onAdd:ee,onRemove:()=>E(null)})}):/* @__PURE__ */ U(l,{tone:v?`danger`:`info`,children:v?Q(v,`We could not load the support settings.`):`Loading the form.`})})]})}function at({open:e,onClose:t,onCreated:n,config:r,defaultCategory:a,appVersion:o}){let c=X(),l=`support-new-${i().replace(/[^a-zA-Z0-9-]/g,``)}`,[u,d]=s(!1),[p,m]=s(null),h=!!p&&(p.subject.trim()!==``||p.body.trim()!==``||p.files.length>0);async function g(e){n(await c.createTicket({...e,userAgent:typeof navigator>`u`?void 0:navigator.userAgent,appVersion:o}))}return/* @__PURE__ */ U(D,{open:e,size:`lg`,title:`New ticket`,subtitle:`Tell us what you need. We reply by email and on this page.`,headerIcon:`message-square`,confirmDiscard:`Discard this ticket?`,dirty:h&&!u,onClose:()=>{u||t()},footer:/* @__PURE__ */ W(`div`,{className:`d-flex justify-content-end gap-2 w-100`,children:[/* @__PURE__ */ U(f,{variant:`secondary`,onClick:t,disabled:u,children:`Cancel`}),/* @__PURE__ */ U(f,{type:`submit`,form:l,loading:u,children:`Send ticket`})]}),children:e&&/* @__PURE__ */ U(Ye,{id:l,config:r,defaultCategory:a,onSubmit:g,onBusyChange:d,onValuesChange:m})})}var ot={Open:`info`,InProgress:`info`,WaitingOnCustomer:`warning`,Resolved:`success`,Closed:`success`,Cancelled:`neutral`};function st(e){return ot[e]??`neutral`}var ct=6e4,lt=[`image/png`,`image/jpeg`,`image/gif`,`image/webp`,`application/pdf`];function ut({attachment:e}){let t=X(),[n,r]=s(!1),[i,a]=s(!1);async function o(){r(!0),a(!1);let n=lt.includes(e.contentType)?window.open(``,`_blank`):null;n&&(n.opener=null);try{let r=await t.fetchAttachment(e.id),i=URL.createObjectURL(r);if(setTimeout(()=>URL.revokeObjectURL(i),ct),n)n.location.href=i;else{let t=document.createElement(`a`);t.href=i,t.download=e.fileName,t.click()}}catch{n?.close(),a(!0)}finally{r(!1)}}let c=Number.isFinite(e.sizeBytes)?V(e.sizeBytes):`-`;return/* @__PURE__ */ W(H,{children:[/* @__PURE__ */ U(m,{leadingIcon:i?`x-circle`:`paperclip`,label:n?/* @__PURE__ */ W(H,{children:[/* @__PURE__ */ U(j,{size:`sm`,label:`Loading ${e.fileName}`}),` `,e.fileName]}):e.fileName,onClick:o,disabled:n,"aria-busy":n||void 0,title:`${e.fileName}, ${c}`}),i&&/* @__PURE__ */ U(`span`,{role:`status`,className:`wui-text-xs text-danger align-self-center`,children:`Could not load this file. Click to try again.`})]})}function $({iso:e,className:t}){let n=De(),r=Ee();return n?n(e):/* @__PURE__ */ U(`time`,{dateTime:e,className:t,children:B(e,{timeZone:r})})}var dt={whiteSpace:`pre-wrap`,overflowWrap:`anywhere`};function ft({messages:e}){return/* @__PURE__ */ U(`ol`,{className:`list-unstyled d-flex flex-column gap-3 mb-0`,"aria-label":`Conversation`,children:e.map(e=>{let t=/* @__PURE__ */ U($,{iso:e.createdDateTimeUtc,className:`wui-text-xs text-body-secondary text-nowrap`});if(e.authorKind===`System`)return/* @__PURE__ */ W(`li`,{className:`text-center wui-text-xs text-body-secondary`,"data-author":`system`,children:[/* @__PURE__ */ U(`span`,{className:`d-block`,children:e.body}),t]},e.id);let n=e.authorKind===`Customer`,r=e.authorName||(n?`You`:`Support team`);return/* @__PURE__ */ W(`li`,{className:`d-flex align-items-start gap-2${n?` flex-row-reverse`:``}`,"data-author":n?`customer`:`agent`,children:[/* @__PURE__ */ U(u,{name:r,size:32,tone:n?`neutral`:`primary`}),/* @__PURE__ */ W(p,{className:`flex-grow-1 border`,padding:`sm`,variant:n?`default`:`accent`,style:{minWidth:0},children:[/* @__PURE__ */ W(`div`,{className:`d-flex flex-wrap align-items-center justify-content-between gap-2 mb-2`,children:[/* @__PURE__ */ W(`span`,{className:`d-inline-flex flex-wrap align-items-center gap-2 fw-semibold wui-text-sm text-break`,children:[r,!n&&/* @__PURE__ */ U(d,{tone:`primary`,children:`Support`})]}),t]}),/* @__PURE__ */ U(`div`,{className:`wui-text-sm`,style:dt,children:e.body}),e.attachments?.length>0&&/* @__PURE__ */ U(`div`,{className:`d-flex flex-wrap gap-2 mt-2`,children:e.attachments.map(e=>/* @__PURE__ */ U(ut,{attachment:e},e.id))})]})]},e.id)})})}function pt({satisfaction:e,comment:t,canRate:n=!1,commentMaxLength:r,onRate:a}){let o=i(),[c,u]=s(``),[d,m]=s(null),[h,g]=s(``);if(e)return/* @__PURE__ */ W(l,{tone:e===`Satisfied`?`success`:`info`,role:`status`,children:[e===`Satisfied`?`You told us this solved your problem.`:`You told us this did not solve your problem.`,t?/* @__PURE__ */ W(`span`,{className:`d-block mt-1`,children:[`Your comment: `,t]}):null]});if(!n)return null;async function _(e){g(``),m(e);try{await a({satisfaction:e,comment:c})}catch(e){g(Q(e,`Your rating did not send. Please try again.`))}finally{m(null)}}return/* @__PURE__ */ U(p,{padding:`sm`,className:`border`,title:`Did this solve your problem?`,children:/* @__PURE__ */ W(`div`,{className:`d-flex flex-column gap-2`,children:[h&&/* @__PURE__ */ U(l,{tone:`danger`,children:h}),/* @__PURE__ */ U(P,{id:`${o}-comment`,label:`Anything to add?`,rows:2,maxLength:r,value:c,onChange:e=>u(e.target.value),hint:`Optional. Your comment goes to the support team.`}),/* @__PURE__ */ W(`div`,{className:`d-flex flex-wrap gap-2`,children:[/* @__PURE__ */ U(f,{variant:`outline`,leftIcon:`check-circle`,loading:d===`Satisfied`,disabled:d!==null,onClick:()=>_(`Satisfied`),children:`Yes, it is solved`}),/* @__PURE__ */ U(f,{variant:`outline`,leftIcon:`x-circle`,loading:d===`Unsatisfied`,disabled:d!==null,onClick:()=>_(`Unsatisfied`),children:`No, it is not`})]})]})})}function mt({onSend:e,config:t,reopens:n=!1}){let r=i(),[a,o]=s(``),[u,d]=s([]),[p,g]=s(``),[_,v]=s(``),[y,b]=s(!1),x=e=>{let n=Re(u,e,t);d(n.files),g(n.notice)},S=e=>{let n=u.filter((t,n)=>n!==e);d(n),g(Fe(n,t)??``)},C=e=>{let t=ze(e);t.length>0&&x(t)};async function w(n){n.preventDefault();let r=a.trim();if(!r){v(`Write a message before you send it.`);return}let i=Fe(u,t);if(i)g(i);else{v(``),b(!0);try{await e({body:r,files:u}),o(``),d([]),g(``)}catch(e){v(Q(e,`Your reply did not send. Please try again.`))}finally{b(!1)}}}let T=_||p;return/* @__PURE__ */ W(`form`,{onSubmit:w,noValidate:!0,className:`d-flex flex-column gap-2 flex-grow-1 min-w-0`,"aria-label":`Reply to this ticket`,children:[T&&/* @__PURE__ */ U(l,{tone:`danger`,children:T}),/* @__PURE__ */ U(P,{id:`${r}-body`,label:`Your reply`,rows:2,autoGrow:!0,maxLength:t?.bodyMaxLength,value:a,onChange:e=>{o(e.target.value),v(``)},onPaste:C,hint:n?`Sending a reply reopens this ticket. You can paste an image into the message.`:`You can paste an image into the message.`,required:!0}),u.length>0&&/* @__PURE__ */ U(h,{label:`Attached files`,children:u.map((e,t)=>/* @__PURE__ */ U(m,{leadingIcon:`paperclip`,label:e.name,removeLabel:`Remove ${e.name}`,onRemove:()=>S(t)},Le(e)))}),/* @__PURE__ */ W(`div`,{className:`d-flex flex-wrap align-items-center justify-content-between gap-2`,children:[/* @__PURE__ */ U(c,{iconVariant:`bulk`,icon:`paperclip`,label:`Attach a file`,multiple:t?.maxAttachmentsPerMessage!==1,accept:Ne(t),onFiles:x}),/* @__PURE__ */ U(f,{type:`submit`,leftIcon:`send`,loading:y,children:`Send reply`})]})]})}function ht({ticketId:e,onBack:t,onChanged:n,onOpenTicket:r}){let{config:i}=Z(),a=Ee(),o=De(),{ticket:c,loading:u,error:d,reload:m,reply:h,reopen:_,cancel:v,rate:b}=je(e),[x,S]=s(!1),[T,E]=s(!1),[D,O]=s(!1),[k,j]=s(``),N=async e=>{let t=await e();return n?.(),t};async function P(){j(``),S(!0);try{await N(_)}catch(e){j(Q(e,`The ticket did not reopen. Please try again.`))}finally{S(!1)}}async function F(){j(``),O(!0);try{await N(v)}catch(e){j(Q(e,`The request was not withdrawn. Please try again.`))}finally{O(!1),E(!1)}}let I=/* @__PURE__ */ U(f,{variant:`ghost`,size:`sm`,leftIcon:`arrow-left`,onClick:t,className:`align-self-start`,children:`Back to tickets`});if(!c)return/* @__PURE__ */ W(`section`,{className:`d-flex flex-column gap-3`,"aria-busy":u||void 0,children:[I,d?/* @__PURE__ */ W(l,{tone:`danger`,children:[Q(d,`We could not load this ticket.`),` `,/* @__PURE__ */ U(f,{variant:`ghost`,size:`sm`,onClick:m,children:`Try again`})]}):/* @__PURE__ */ U(A,{height:160})]});let L=st(c.status),R=[{key:`status`,label:`Status`,value:c.statusLabel?/* @__PURE__ */ U(M,{label:c.statusLabel,tone:L}):`-`},{key:`category`,label:`Category`,value:c.category||`-`},{key:`ticket`,label:`Ticket`,value:c.number},{key:`opened`,label:`Opened`,value:/* @__PURE__ */ U($,{iso:c.createdDateTimeUtc})},{key:`updated`,label:`Last update`,value:/* @__PURE__ */ U($,{iso:c.updatedDateTimeUtc})}];return/* @__PURE__ */ W(`section`,{className:`d-flex flex-column gap-3`,"aria-labelledby":`support-ticket-${c.id}`,children:[I,/* @__PURE__ */ W(`div`,{className:`row g-3`,children:[/* @__PURE__ */ W(`div`,{className:`col-12 col-lg-8 d-flex flex-column gap-3`,children:[/* @__PURE__ */ W(`header`,{className:`d-flex flex-column gap-2`,children:[/* @__PURE__ */ W(`div`,{className:`d-flex flex-wrap align-items-center gap-2`,children:[/* @__PURE__ */ U(`h2`,{id:`support-ticket-${c.id}`,className:`h5 mb-0 text-break`,children:c.subject}),c.statusLabel&&/* @__PURE__ */ U(M,{label:c.statusLabel,tone:L})]}),/* @__PURE__ */ W(`ul`,{className:`list-unstyled d-flex flex-wrap gap-3 mb-0 wui-text-sm text-body-secondary`,"aria-label":`Ticket summary`,children:[c.number&&/* @__PURE__ */ W(`li`,{className:`d-inline-flex align-items-center gap-1`,children:[/* @__PURE__ */ U(w,{variant:`bulk`,name:`receipt-text`,size:16}),c.number]}),c.category&&/* @__PURE__ */ W(`li`,{className:`d-inline-flex align-items-center gap-1`,children:[/* @__PURE__ */ U(w,{variant:`bulk`,name:`folder-2`,size:16}),c.category]}),/* @__PURE__ */ W(`li`,{className:`d-inline-flex align-items-center gap-1`,children:[/* @__PURE__ */ U(w,{variant:`bulk`,name:`calendar-1`,size:16}),`Opened `,/* @__PURE__ */ U($,{iso:c.createdDateTimeUtc})]})]}),o===null&&/* @__PURE__ */ W(`p`,{className:`wui-text-xs text-body-secondary mb-0`,children:[`Times are shown in `,ee(a),`.`]})]}),k&&/* @__PURE__ */ U(l,{tone:`danger`,children:k}),c.mergedInto&&/* @__PURE__ */ W(l,{tone:`info`,role:`status`,children:[`This ticket was merged into `,c.mergedInto.number,`. The conversation carries on there.`,` `,r&&/* @__PURE__ */ W(f,{variant:`ghost`,size:`sm`,onClick:()=>r(c.mergedInto.id),children:[`Open `,c.mergedInto.number]})]}),c.canReopen&&/* @__PURE__ */ U(l,{tone:`success`,role:`status`,children:`If you still need help, reopen the ticket or send a reply.`}),c.status===`WaitingOnCustomer`&&/* @__PURE__ */ U(l,{tone:`warning`,role:`status`,children:`We need your answer to carry on. Reply below and the ticket goes back to our team.`}),!c.canReopen&&/* @__PURE__ */ U(`p`,{className:`wui-text-sm text-body-secondary mb-0`,children:`Our team marks this resolved once your question is answered. Replying reopens it.`}),c.canReopen&&/* @__PURE__ */ U(f,{variant:`secondary`,leftIcon:`history`,loading:x,onClick:P,className:`align-self-start`,children:`Reopen ticket`}),c.canCancel&&/* @__PURE__ */ U(f,{variant:`secondary`,onClick:()=>E(!0),className:`align-self-start`,children:`Withdraw request`}),/* @__PURE__ */ U(g,{open:T,title:`Withdraw this request?`,message:`Our team will stop working on this ticket. You can open a new ticket later if you still need help.`,confirmLabel:`Withdraw request`,cancelLabel:`Keep request`,danger:!0,loading:D,onConfirm:F,onClose:()=>E(!1)}),/* @__PURE__ */ U(pt,{satisfaction:c.satisfaction,comment:c.satisfactionComment,canRate:c.canRate,commentMaxLength:i?.satisfactionCommentMaxLength,onRate:e=>N(()=>b(e))}),/* @__PURE__ */ U(ft,{messages:c.messages??[]}),c.mergedTickets?.length>0&&/* @__PURE__ */ W(`section`,{"aria-labelledby":`support-merged-${c.id}`,className:`d-flex flex-column gap-1`,children:[/* @__PURE__ */ U(`h3`,{id:`support-merged-${c.id}`,className:`h6 mb-0`,children:`Merged into this ticket`}),/* @__PURE__ */ U(`ul`,{className:`list-unstyled d-flex flex-column gap-1 mb-0 wui-text-sm`,children:c.mergedTickets.map(e=>/* @__PURE__ */ U(`li`,{children:r?/* @__PURE__ */ W(f,{variant:`ghost`,size:`sm`,onClick:()=>r(e.id),children:[e.number,`: `,e.subject]}):`${e.number}: ${e.subject}`},e.id))})]}),!c.mergedInto&&/* @__PURE__ */ U(C,{sticky:!0,align:`start`,children:/* @__PURE__ */ U(mt,{config:i,reopens:c.canReopen,onSend:e=>N(()=>h(e))})})]}),/* @__PURE__ */ U(`aside`,{"aria-label":`Ticket details`,className:`col-12 col-lg-4`,children:/* @__PURE__ */ W(p,{padding:`sm`,className:`border`,children:[/* @__PURE__ */ U(`h3`,{className:`h6`,children:`Ticket details`}),/* @__PURE__ */ U(y,{columns:1,items:R})]})})]})]})}var gt=`ticket`;function _t(){return typeof window>`u`?null:new URLSearchParams(window.location.search).get(gt)}function vt(e){if(typeof window>`u`)return e?`?${gt}=${encodeURIComponent(e)}`:`?`;let t=new URL(window.location.href);return e?t.searchParams.set(gt,e):t.searchParams.delete(gt),`${t.pathname}${t.search}${t.hash}`}function yt(e){if(typeof window>`u`)return;let t=vt(e);t!==`${window.location.pathname}${window.location.search}${window.location.hash}`&&window.history.replaceState(window.history.state,``,t)}var bt=[{key:`all`,label:`All`,countKey:`total`},{key:`Open`,label:`Open`,countKey:`open`},{key:`NeedsReply`,label:`Needs your reply`,countKey:`needsReply`},{key:`Resolved`,label:`Resolved`,countKey:`resolved`},{key:`Withdrawn`,label:`Withdrawn`,countKey:`withdrawn`}],xt=[`tabs`,`select`,`none`];function St({tickets:e,loading:t,error:n,onRetry:r,onOpen:i,status:a,onStatusChange:o,statusFilter:s=`tabs`,counts:u,search:d,onSearchChange:p,pagination:m}){I(`SupportCenter`,`statusFilter`,s,xt);let h=bt.map(({key:e,label:t,countKey:n})=>{let r=u?.[n];return{value:e,label:r==null?t:`${t} (${r})`}}),g=(e,t)=>{e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||(e.preventDefault(),i(t))};return/* @__PURE__ */ W(`div`,{className:`d-flex flex-column gap-3`,children:[n&&/* @__PURE__ */ W(l,{tone:`danger`,children:[Q(n,`We could not load your tickets.`),` `,/* @__PURE__ */ U(f,{variant:`ghost`,size:`sm`,onClick:r,children:`Try again`})]}),/* @__PURE__ */ W(`div`,{className:`d-flex flex-column flex-md-row gap-2 align-items-md-center justify-content-between`,children:[s===`none`?null:s===`select`?/* @__PURE__ */ U(k,{label:`Status`,value:a,onChange:o,options:h}):/* @__PURE__ */ U(N,{tabs:bt.map(({key:e,label:t,countKey:n})=>({key:e,label:t,count:u?.[n]})),value:a,onChange:o,ariaLabel:`Filter tickets by status`,className:`flex-grow-1`}),/* @__PURE__ */ U(O,{value:d,onChange:p,placeholder:`Search tickets`,ariaLabel:`Search tickets`})]}),/* @__PURE__ */ U(v,{columns:[{key:`subject`,label:`Subject`,render:e=>/* @__PURE__ */ W(`div`,{className:`d-flex flex-column`,style:{minWidth:0},children:[/* @__PURE__ */ U(E,{href:vt(e.id),animation:`none`,className:`fw-semibold text-break`,onClick:t=>g(t,e.id),children:e.subject}),/* @__PURE__ */ W(`span`,{className:`wui-text-xs text-body-secondary`,children:[e.number,`, `,e.category]})]})},{key:`status`,label:`Status`,render:e=>e.statusLabel?/* @__PURE__ */ U(M,{label:e.statusLabel,tone:st(e.status)}):`-`},{key:`messageCount`,label:`Messages`,cellClassName:`wui-text-sm text-body-secondary`,render:e=>e.messageCount},{key:`updatedDateTimeUtc`,label:`Last update`,cellClassName:`wui-text-sm text-body-secondary text-nowrap`,render:e=>/* @__PURE__ */ U($,{iso:e.updatedDateTimeUtc})}],rows:e,loading:t,skeletonRows:4,ariaLabel:`Support tickets`,rowActionsLabel:`Actions`,rowActions:e=>/* @__PURE__ */ U(c,{icon:`eye`,label:`Open ticket ${e.subject}`,href:vt(e.id),onClick:t=>g(t,e.id)}),stickyActions:!0,stackOnMobile:!0,sourceCount:u?.total??0,pagination:m,empty:/* @__PURE__ */ U(x,{variant:`table`,icon:`message-square`,title:`No tickets yet`,text:`When you raise a ticket, it shows here with its status.`}),emptyFiltered:/* @__PURE__ */ U(x,{variant:`table`,icon:`search`,title:`No tickets match`,text:`Try another search or status.`})})]})}var Ct=300,wt=10;function Tt({initialTicketId:e,defaultCategory:t,appVersion:n,status:i,defaultStatus:a=`all`,onStatusChange:o,statusFilter:c=`tabs`}){let{config:u,error:d,reload:p}=Z(),[m,h]=s(a),g=i!==void 0,_=g?i:m,v=e=>{g||h(e),o?.(e)},[y,b]=s(``),x=He(y.trim(),Ct),[S,C]=s(wt),w=`${_}|${x}|${S}`,[T,E]=s({key:w,page:1}),D=T.key===w?T.page:1,O=e=>E({key:w,page:e}),k=ke({status:_===`all`?void 0:_,search:x||void 0,page:D,pageSize:S}),{counts:A,reload:j}=Ae(),[M,N]=s(()=>e||_t()),[P,F]=s(!1),I=k.totalPages;r(()=>{I>0&&D>I&&E({key:w,page:I})},[I,D,w]);let L=()=>{k.reload(),j()},R=e=>{N(e),yt(e)};if(M)return/* @__PURE__ */ U(ht,{ticketId:M,onBack:()=>R(null),onChanged:L,onOpenTicket:R},M);let z={page:D,totalPages:Math.max(1,k.totalPages),pageSize:S,total:k.totalCount,setPage:O,setPageSize:C};return/* @__PURE__ */ W(`section`,{className:`d-flex flex-column gap-3 min-w-0`,"aria-labelledby":`support-center-title`,children:[/* @__PURE__ */ W(`div`,{className:`d-flex flex-wrap align-items-center justify-content-between gap-2`,children:[/* @__PURE__ */ U(`h2`,{id:`support-center-title`,className:`h5 mb-0`,children:`Your tickets`}),/* @__PURE__ */ U(f,{leftIcon:`plus`,onClick:()=>F(!0),disabled:!u,children:`New ticket`})]}),d&&/* @__PURE__ */ W(l,{tone:`warning`,children:[Q(d,`We could not load the support settings.`),` `,/* @__PURE__ */ U(f,{variant:`ghost`,size:`sm`,onClick:p,children:`Try again`})]}),/* @__PURE__ */ U(St,{tickets:k.tickets,loading:k.loading,error:k.error,onRetry:L,onOpen:R,status:_,onStatusChange:v,statusFilter:c,counts:A,search:y,onSearchChange:b,pagination:z}),u&&/* @__PURE__ */ U(at,{open:P,onClose:()=>F(!1),config:u,defaultCategory:t,appVersion:n,onCreated:e=>{F(!1),L(),R(e.id)}})]})}function Et(e){return e===0?`You are next in the queue.`:e===1?`1 person is ahead of you.`:`${e} people are ahead of you.`}function Dt({position:e}){return/* @__PURE__ */ W(`div`,{className:`d-flex flex-column gap-1`,children:[/* @__PURE__ */ W(`div`,{className:`d-flex align-items-center gap-2`,children:[/* @__PURE__ */ U(j,{size:`sm`,label:`Waiting for a person`}),/* @__PURE__ */ U(`span`,{className:`wui-text-sm`,children:`Waiting for a person to join.`})]}),typeof e==`number`&&/* @__PURE__ */ U(`span`,{className:`wui-text-sm text-body-secondary`,children:Et(e)}),/* @__PURE__ */ U(`span`,{className:`wui-text-sm text-body-secondary`,children:`If no one is free, we will reply here and by email.`})]})}var Ot={CustomerEnded:`You ended this chat.`,AgentEnded:`Our team ended this chat.`,NoAgentAvailable:`No one was free to join. We will reply to you here and by email.`,Idle:`This chat ended because it was quiet for a while.`};function kt({state:e,closeReason:t,agentName:n,ticketNumber:r,ticketId:i,waitingPosition:a,canRequestAgent:o=!1,requesting:s=!1,onRequestAgent:c,onOpenTicket:l,onRestart:u}){return/* @__PURE__ */ W(`div`,{role:`status`,className:`d-flex flex-column gap-2 pb-3 mb-3 border-bottom`,children:[e===`Assistant`&&/* @__PURE__ */ W(H,{children:[/* @__PURE__ */ U(`div`,{children:/* @__PURE__ */ U(d,{tone:`neutral`,children:`AI assistant`})}),/* @__PURE__ */ U(`p`,{className:`wui-text-sm mb-0`,children:`You are chatting with our AI assistant.`}),o&&/* @__PURE__ */ U(`div`,{children:/* @__PURE__ */ U(f,{variant:`outline`,size:`sm`,leftIcon:`user`,loading:s,onClick:c,children:`Talk to a person`})})]}),e===`WaitingForAgent`&&/* @__PURE__ */ W(H,{children:[/* @__PURE__ */ U(`div`,{children:/* @__PURE__ */ U(d,{tone:`info`,children:`In the queue`})}),/* @__PURE__ */ U(Dt,{position:a??null})]}),e===`WithAgent`&&/* @__PURE__ */ W(H,{children:[/* @__PURE__ */ U(`div`,{children:/* @__PURE__ */ U(d,{tone:`success`,children:`Live agent`})}),/* @__PURE__ */ U(`p`,{className:`wui-text-sm mb-0`,children:n?`${n} from our team is chatting with you.`:`A member of our team is chatting with you.`})]}),e===`Closed`&&/* @__PURE__ */ W(H,{children:[/* @__PURE__ */ U(`div`,{children:/* @__PURE__ */ U(d,{tone:`neutral`,children:`Chat ended`})}),/* @__PURE__ */ U(`p`,{className:`wui-text-sm mb-0`,children:Ot[t]??`This chat has ended.`}),r&&/* @__PURE__ */ U(`p`,{className:`wui-text-sm mb-0`,children:`Your ticket number is ${r}.`}),/* @__PURE__ */ W(`div`,{className:`d-flex flex-wrap gap-2`,children:[l&&i&&/* @__PURE__ */ U(f,{variant:`outline`,size:`sm`,onClick:()=>l({id:i,number:r}),children:`View ticket`}),/* @__PURE__ */ U(f,{size:`sm`,leftIcon:`plus`,onClick:u,children:`Start a new chat`})]})]})]})}var At={whiteSpace:`pre-wrap`,overflowWrap:`anywhere`},jt={...At,maxWidth:`85%`};function Mt(e){for(let t=e?.parentElement;t&&t!==document.body;t=t.parentElement){let{overflowY:e}=getComputedStyle(t);if((e===`auto`||e===`scroll`)&&t.scrollHeight>t.clientHeight)return t}return null}function Nt(e){if(!e?.parentElement)return;let t=()=>{let t=Mt(e);t&&(t.scrollTop=t.scrollHeight)};t();let n=new MutationObserver(t);return n.observe(e.parentElement,{childList:!0,subtree:!0,characterData:!0}),()=>n.disconnect()}function Pt({attachments:e}){return e?.length?/* @__PURE__ */ U(`div`,{className:`d-flex flex-wrap gap-2 mt-2`,children:e.map(e=>/* @__PURE__ */ U(ut,{attachment:e},e.id))}):null}function Ft({message:e,resolveLink:t,linkComponent:n}){let r=/* @__PURE__ */ U($,{iso:e.createdDateTimeUtc,className:`wui-text-xs text-body-secondary text-nowrap`});if(e.authorKind===`System`)return/* @__PURE__ */ W(`li`,{className:`text-center wui-text-xs text-body-secondary`,"data-author":`system`,children:[/* @__PURE__ */ U(`span`,{className:`d-block`,children:e.body}),r]});if(e.authorKind===`Customer`)return/* @__PURE__ */ U(`li`,{className:`d-flex justify-content-end`,"data-author":`customer`,children:/* @__PURE__ */ W(p,{padding:`sm`,variant:`muted`,style:jt,children:[/* @__PURE__ */ U(`span`,{className:`visually-hidden`,children:`You: `}),/* @__PURE__ */ U(`div`,{className:`wui-text-sm`,style:At,children:e.body}),/* @__PURE__ */ U(Pt,{attachments:e.attachments}),/* @__PURE__ */ U(`div`,{className:`mt-1`,children:r})]})});if(e.authorKind===`Assistant`)return/* @__PURE__ */ W(`li`,{className:`d-flex align-items-start gap-2`,"data-author":`assistant`,children:[/* @__PURE__ */ U(u,{name:`Assistant`,size:32,tone:`primary`}),/* @__PURE__ */ W(`div`,{className:`flex-grow-1 wui-text-sm min-w-0`,children:[/* @__PURE__ */ W(`div`,{className:`d-flex flex-wrap align-items-center gap-2 mb-1`,children:[/* @__PURE__ */ U(`span`,{className:`fw-semibold`,children:`Assistant`}),/* @__PURE__ */ U(d,{tone:`neutral`,children:`AI`})]}),/* @__PURE__ */ U(`span`,{className:`visually-hidden`,children:`Assistant: `}),/* @__PURE__ */ U(ne,{text:e.body,resolveLink:t,linkComponent:n}),/* @__PURE__ */ U(Pt,{attachments:e.attachments}),/* @__PURE__ */ U(`div`,{className:`mt-1`,children:r})]})]});let i=e.authorName||`Support team`;return/* @__PURE__ */ W(`li`,{className:`d-flex align-items-start gap-2`,"data-author":`agent`,children:[/* @__PURE__ */ U(u,{name:i,size:32,tone:`primary`}),/* @__PURE__ */ W(`div`,{className:`flex-grow-1 wui-text-sm min-w-0`,children:[/* @__PURE__ */ W(`div`,{className:`d-flex flex-wrap align-items-center gap-2 mb-1`,children:[/* @__PURE__ */ U(`span`,{className:`fw-semibold`,children:i}),/* @__PURE__ */ U(d,{tone:`primary`,children:`Support`})]}),/* @__PURE__ */ U(`div`,{style:At,children:e.body}),/* @__PURE__ */ U(Pt,{attachments:e.attachments}),/* @__PURE__ */ U(`div`,{className:`mt-1`,children:r})]})]})}function It({item:e,onRetry:t,onDiscard:n}){return/* @__PURE__ */ W(`li`,{className:`d-flex flex-column align-items-end gap-1`,"data-author":`customer`,children:[/* @__PURE__ */ U(p,{padding:`sm`,variant:`muted`,style:jt,children:/* @__PURE__ */ U(`div`,{className:`wui-text-sm`,style:At,children:e.body})}),e.status===`sending`&&/* @__PURE__ */ U(`span`,{className:`wui-text-xs text-body-secondary`,children:`Sending`}),e.status===`failed`&&/* @__PURE__ */ W(l,{tone:`danger`,size:`sm`,children:[/* @__PURE__ */ U(`div`,{children:e.error}),/* @__PURE__ */ W(`div`,{className:`d-flex gap-2 mt-2`,children:[/* @__PURE__ */ U(f,{size:`sm`,variant:`outline`,onClick:()=>t(e.localId),children:`Try again`}),/* @__PURE__ */ U(f,{size:`sm`,variant:`ghost`,onClick:()=>n(e.localId),children:`Discard`})]})]})]})}function Lt({messages:e,pending:t,assistantText:n,assistantWriting:r,agentName:i,agentTyping:a,onRetry:o,onDiscard:s,resolveLink:c,linkComponent:l}){return e.length===0&&t.length===0&&!n&&!r&&!a?/* @__PURE__ */ U(x,{icon:`sparkles`,size:`sm`,title:`How can we help?`,text:`Ask a question and our AI assistant will answer it. You can ask to talk to a person once you have sent a message.`}):/* @__PURE__ */ W(H,{children:[/* @__PURE__ */ W(`ol`,{className:`list-unstyled d-flex flex-column gap-3 mb-0`,"aria-label":`Conversation`,children:[e.map(e=>/* @__PURE__ */ U(Ft,{message:e,resolveLink:c,linkComponent:l},e.id)),t.map(e=>/* @__PURE__ */ U(It,{item:e,onRetry:o,onDiscard:s},e.localId)),n?/* @__PURE__ */ W(`li`,{className:`d-flex align-items-start gap-2`,"data-author":`assistant`,"aria-busy":`true`,children:[/* @__PURE__ */ U(u,{name:`Assistant`,size:32,tone:`primary`}),/* @__PURE__ */ W(`div`,{className:`flex-grow-1 wui-text-sm min-w-0`,children:[/* @__PURE__ */ U(`span`,{className:`fw-semibold`,children:`Assistant`}),/* @__PURE__ */ U(ne,{text:n,resolveLink:c,linkComponent:l})]})]}):r&&/* @__PURE__ */ W(`li`,{className:`d-flex align-items-start gap-2`,"data-author":`assistant`,children:[/* @__PURE__ */ U(u,{name:`Assistant`,size:32,tone:`primary`}),/* @__PURE__ */ W(`div`,{className:`d-flex align-items-center gap-2 wui-text-sm`,children:[/* @__PURE__ */ U(j,{size:`sm`,label:`The assistant is writing`}),/* @__PURE__ */ U(`span`,{children:`The assistant is writing`})]})]}),a&&/* @__PURE__ */ U(`li`,{className:`wui-text-sm text-body-secondary`,"aria-live":`polite`,children:`${i||`Our team`} is typing`})]}),/* @__PURE__ */ U(`div`,{ref:Nt})]})}var Rt=3e3,zt=`This chat is no longer available.`,Bt=(e,t)=>e.sequence-t.sequence;function Vt(e,t){return e.some(e=>e.id===t.id)?e:[...e,t].sort(Bt)}function Ht(e){let t=/* @__PURE__ */ new Map;for(let n of e)t.has(n.id)||t.set(n.id,n);return[...t.values()].sort(Bt)}function Ut(e,t){if(!e)return;let n=Date.parse(e)-Date.now();if(!(n>0))return;let r=setTimeout(t,n);return()=>clearTimeout(r)}function Wt({chatClient:e,connection:n,open:i,appVersion:a,start:c}){let[l,u]=s(`idle`),[d,f]=s(``),[p,m]=s(null),[h,g]=s([]),[_,v]=s([]),[y,b]=s(``),[x,S]=s(null),[C,w]=s(null),[T,E]=s(``),[D,O]=s(!1),[,k]=s(0),A=o(null),j=o(null),M=o(0),N=t(e=>{let t=j.current;j.current=e.id;let{messages:n,...r}=e;m(r),g(Ht(n??[])),t!==e.id&&v([])},[]);r(()=>Ut(x,()=>k(e=>e+1)),[x]),r(()=>Ut(C,()=>k(e=>e+1)),[C]);let P=t(()=>{let t=!0,r=()=>{},i=e=>({onSnapshot(t){t.id===e&&(N(t),b(``))},onMessage(t){t.chatId===e&&(g(e=>Vt(e,t.message)),t.message.authorKind===`Assistant`&&b(``))},onState(t){t.chatId===e&&(m(e=>e&&{...e,state:t.state,closeReason:t.closeReason,ticketId:t.ticketId,ticketNumber:t.ticketNumber,agentName:t.agentName,waitingPosition:t.state===`WaitingForAgent`?t.waitingPosition:null}),b(``))},onTyping(t){t.chatId===e&&(t.who===`Agent`?S(t.untilDateTimeUtc):t.who===`Assistant`&&w(t.untilDateTimeUtc))},onDelta(t){t.chatId===e&&b(e=>e+t.text)},onError(e){e.code===`chat_not_found`?(m(e=>e&&{...e,state:`Closed`,closeReason:null}),E(zt)):E(typeof e.message==`string`&&e.message?e.message:`The chat connection had a problem. We are reconnecting.`)}});return u(`loading`),e.start({pageUrl:window.location.href,userAgent:navigator.userAgent,appVersion:a,...c}).then(e=>{t&&(N(e),f(``),u(`ready`),r=n.watch(e.id,e.sequence,i(e.id)))}).catch(e=>{t&&(f(Q(e,`We could not start the chat. Please try again.`)),u(`error`))}),()=>{t=!1,r()}},[e,n,N,a,c]);r(()=>{if(!i)return;let e=P();return A.current=()=>{e(),e=P()},()=>{A.current=null,e()}},[i,P]);let F=(t,n)=>e.get(t).then(N).catch(e=>E(Q(e,n)));async function I(t){let n=p.id;try{let r=await e.send(n,{body:t.body,files:t.files,idempotencyKey:t.key});return j.current===n&&(g(e=>{let t=Vt(e,r.message);return r.reply?Vt(t,r.reply):t}),v(e=>e.filter(e=>e.localId!==t.localId)),r.reply&&b(``),!0)}catch(e){return j.current===n?e?.code===`chat_closed`?(v(e=>e.filter(e=>e.localId!==t.localId)),await F(n,zt),!1):(v(n=>n.map(n=>n.localId===t.localId?{...n,status:`failed`,error:Q(e,`Your message did not send. Please try again.`)}:n)),!1):!1}}return{phase:l,startError:d,chat:p,messages:h,pending:_,assistantText:y,agentTypingUntil:x,assistantTypingUntil:C,notice:T,requesting:D,send:(e,t=[])=>{let n={localId:crypto.randomUUID(),key:crypto.randomUUID(),body:e,files:t,status:`sending`,error:``};return v(e=>[...e,n]),I(n)},retry:e=>{let t=_.find(t=>t.localId===e);if(!t)return;let n={...t,status:`sending`,error:``};v(t=>t.map(t=>t.localId===e?n:t)),I(n)},discard:e=>{v(t=>t.filter(t=>t.localId!==e))},requestAgent:async()=>{let t=p.id;O(!0);try{N(await e.requestAgent(t))}catch(e){let n=`We could not reach the team. Please try again.`;e?.code===`chat_not_with_assistant`?await F(t,n):E(Q(e,n))}finally{O(!1)}},end:async()=>{try{N(await e.close(p.id))}catch(e){E(Q(e,`We could not end the chat. Please try again.`))}},restart:()=>{j.current=null,m(null),g([]),v([]),b(``),E(``),S(null),w(null),u(`loading`),A.current?.()},retryStart:()=>{A.current?.()},notifyTyping:()=>{if(l!==`ready`||p?.state!==`WithAgent`)return;let t=Date.now();t-M.current<Rt||(M.current=t,e.typing(p.id).catch(()=>{}))}}}var Gt={composer:`Your message`,placeholder:`Type your message`},Kt=e=>!!e&&Date.now()<Date.parse(e);function qt({chatClient:e,connection:n,open:i,onClose:a,appVersion:u,start:d,onOpenTicket:p,resolveLink:m,linkComponent:h,title:_=`Chat with us`,width:v=`440px`}){let{config:y}=Z(),x=Wt({chatClient:e,connection:n,open:i,appVersion:u,start:d}),[S,C]=s(!1),[T,E]=s([]),[D,O]=s(``),k=o(0),A=o(null),M=o(x.notifyTyping);r(()=>{M.current=x.notifyTyping});let N=e=>{let t=Re(T.map(e=>e.file),e,y);E(t.files.map(e=>T.find(t=>t.file===e)||(k.current+=1,{key:`attachment-${k.current}`,fileName:e.name,contentType:e.type,length:e.size,status:`Ready`,progress:null,error:null,file:e}))),O(t.notice)},P=e=>{E(t=>t.filter(t=>t.key!==e)),O(``)},F=async e=>{let t=T;await x.send(e,t.map(e=>e.file))&&E(e=>e.filter(e=>!t.includes(e)))},I=()=>{E([]),O(``),x.restart()},L=t(()=>M.current(),[]),R=t(e=>{A.current?.removeEventListener(`input`,L),A.current=e,e?.addEventListener(`input`,L)},[L]),z=x.phase===`ready`&&x.chat!==null,B=x.chat?.state,V=z&&B!==`Closed`,ee=Kt(x.assistantTypingUntil)||B===`Assistant`&&x.pending.some(e=>e.status===`sending`),ne=Kt(x.agentTypingUntil),G=x.messages.some(e=>e.authorKind===`Customer`)&&!!x.chat?.assistantAvailable;r(()=>{i&&z&&A.current?.focus()},[i,z]);let K=/* @__PURE__ */ W(`div`,{className:`drawer-header`,children:[/* @__PURE__ */ W(`div`,{className:`drawer-title`,children:[/* @__PURE__ */ U(`span`,{className:`drawer-title-ic`,children:/* @__PURE__ */ U(w,{name:`message-circle`,size:18})}),_]}),/* @__PURE__ */ W(`div`,{className:`d-flex align-items-center gap-1`,children:[V&&/* @__PURE__ */ U(f,{variant:`ghost`,size:`sm`,onClick:()=>C(!0),children:`End chat`}),/* @__PURE__ */ U(c,{icon:`x`,label:`Close`,onClick:a})]})]}),ie;ie=x.phase===`error`?/* @__PURE__ */ W(l,{tone:`danger`,children:[x.startError,/* @__PURE__ */ U(`div`,{className:`mt-2`,children:/* @__PURE__ */ U(f,{size:`sm`,variant:`outline`,onClick:x.retryStart,children:`Try again`})})]}):z?/* @__PURE__ */ W(H,{children:[/* @__PURE__ */ U(kt,{state:B,closeReason:x.chat.closeReason,agentName:x.chat.agentName,ticketNumber:x.chat.ticketNumber,ticketId:x.chat.ticketId,waitingPosition:x.chat.waitingPosition,canRequestAgent:G,requesting:x.requesting,onRequestAgent:x.requestAgent,onOpenTicket:p,onRestart:I}),/* @__PURE__ */ U(Lt,{messages:x.messages,pending:x.pending,assistantText:x.assistantText,assistantWriting:ee,agentName:x.chat.agentName,agentTyping:ne,onRetry:x.retry,onDiscard:x.discard,resolveLink:m,linkComponent:h}),x.notice&&/* @__PURE__ */ U(l,{tone:`danger`,size:`sm`,children:x.notice})]}):/* @__PURE__ */ U(`div`,{className:`d-flex justify-content-center py-4`,children:/* @__PURE__ */ U(j,{label:`Starting your chat`})});let ae=V?/* @__PURE__ */ W(`div`,{className:`d-flex flex-column gap-2`,children:[D&&/* @__PURE__ */ U(l,{tone:`danger`,size:`sm`,children:D}),/* @__PURE__ */ U(te,{onSubmit:F,busy:x.pending.length>0||!!x.assistantText,maxLength:y?.bodyMaxLength??4e3,inputRef:R,attachments:T,onAttach:N,onRemoveAttachment:P,accept:Ne(y),labels:Gt}),B===`Assistant`&&/* @__PURE__ */ U(`p`,{className:`wui-text-xs text-body-secondary mb-0`,children:re.disclaimer})]}):void 0;return/* @__PURE__ */ W(H,{children:[/* @__PURE__ */ U(b,{open:i,onClose:a,sheet:!1,width:v,header:K,footer:ae,ariaLabel:_,onOpened:()=>A.current?.focus(),children:ie}),/* @__PURE__ */ U(g,{open:S,title:`End this chat?`,message:B===`Assistant`?`You can start a new chat whenever you like.`:`Our team can still see this conversation on your ticket.`,confirmLabel:`End chat`,cancelLabel:`Keep chatting`,onConfirm:()=>{C(!1),x.end()},onClose:()=>C(!1)})]})}var Jt={zIndex:`var(--wui-z-fixed)`,bottom:`var(--wui-consent-banner-block, 0px)`},Yt={end:{insetInlineEnd:0},start:{insetInlineStart:0}};function Xt({onClick:e,open:t=!1,label:n=`Chat with us`,position:r=`end`,icon:i=`message-circle`,compact:a=!1,className:o,style:s}){return a?/* @__PURE__ */ U(Zt,{onClick:e,open:t,label:n,position:r,icon:i,className:o,style:s}):/* @__PURE__ */ U(`span`,{"data-support-capture":`exclude`,className:[`position-fixed m-3`,o].filter(Boolean).join(` `),style:{...Jt,...Yt[r],...s},children:/* @__PURE__ */ U(f,{leftIcon:i,className:`rounded-pill`,onClick:e,"aria-haspopup":`dialog`,"aria-expanded":t,children:n})})}function Zt({onClick:e,open:t,label:n,position:r,icon:i,className:a,style:o}){let s=F(r);return s?R(/* @__PURE__ */ U(`span`,{className:[`wui-floating-stack-item wui-floating-stack-item--primary`,a].filter(Boolean).join(` `),style:o,children:/* @__PURE__ */ U(f,{className:`wui-floating-btn`,onClick:e,"aria-label":n,"aria-haspopup":`dialog`,"aria-expanded":t,tooltip:n,tooltipPlacement:r===`start`?`end`:`start`,children:/* @__PURE__ */ U(w,{name:i,size:24})})}),s):null}var Qt=e=>typeof e==`string`&&e.trim()!==``;function $t({className:e}){let{config:t}=Z();if(!t)return null;let n=Qt(t.supportEmail),r=Qt(t.supportPhone),i=Qt(t.supportHours);if(!n&&!r&&!i)return null;let a=[`d-flex flex-wrap align-items-center gap-2 wui-text-sm`,e].filter(Boolean).join(` `);return/* @__PURE__ */ W(`section`,{className:a,"aria-label":Qt(t.supportName)?`Contact ${t.supportName}`:`Contact support`,children:[/* @__PURE__ */ U(`span`,{className:`fw-semibold`,children:Qt(t.supportName)?t.supportName:`Contact support`}),n&&/* @__PURE__ */ W(`span`,{className:`d-inline-flex align-items-center gap-1`,children:[/* @__PURE__ */ U(`a`,{href:`mailto:${t.supportEmail}`,className:`text-break`,children:t.supportEmail}),/* @__PURE__ */ U(_,{text:t.supportEmail,iconOnly:!0,label:`Copy email`,copiedLabel:`Email copied`})]}),r&&/* @__PURE__ */ U(`a`,{href:`tel:${t.supportPhone.replace(/[^\d+]/g,``)}`,children:t.supportPhone}),i&&/* @__PURE__ */ U(`span`,{className:`text-body-secondary`,children:t.supportHours})]})}function en({client:e,timeZone:n=z,renderTime:r,children:i}){let s=o(null),c=t((t=!1)=>{let n=s.current;if(t||!n||n.client!==e){let t=e.getConfig(),n={client:e,pending:t};return s.current=n,t.catch(()=>{s.current===n&&(s.current=null)}),t}return n.pending},[e]),l=a(()=>({client:e,loadConfig:c,timeZone:n,renderTime:r}),[e,c,n,r]);return/* @__PURE__ */ U(we.Provider,{value:l,children:i})}export{it as ReportIssue,K as SupportApiError,Tt as SupportCenter,qt as SupportChat,Xt as SupportChatLauncher,$t as SupportContact,en as SupportProvider,Se as createSseChatConnection,me as createSupportChatClient,ue as createSupportClient,X as useSupportClient,Z as useSupportConfig,je as useSupportTicket,Ae as useSupportTicketCounts,ke as useSupportTickets};
1
+ import{createContext as e,useCallback as t,useContext as n,useEffect as r,useId as i,useMemo as a,useRef as o,useState as s}from"react";import{AppActionIcon as c,AppAlert as l,AppAvatar as u,AppBadge as d,AppButton as f,AppCard as p,AppChip as m,AppChipGroup as h,AppConfirmDialog as g,AppCopyButton as _,AppDataTable as v,AppDescriptions as y,AppEmptyState as b,AppFileAttachment as x,AppFloatingButton as S,AppFormActions as C,AppIcon as w,AppInput as T,AppLink as E,AppModal as D,AppSearch as O,AppSelect as k,AppSkeleton as A,AppSpinner as j,AppStatusBadge as M,AppTabs as N,AppTextarea as P,warnInvalidValue as F}from"@webority/ui-react";import{toBlob as I}from"html-to-image";import{IST_TIME_ZONE as L,formatDateTime as R,formatFileSize as z,timeZoneLabel as B}from"@webority/ui-elements/helpers";import{Fragment as V,jsx as H,jsxs as U}from"react/jsx-runtime";var ee=`Something went wrong. Please try again.`,W=class extends Error{constructor(e,t,n){super(t),this.name=`SupportApiError`,this.code=e,this.status=n}};async function te(e){if(e&&typeof Blob<`u`&&e instanceof Blob)try{return JSON.parse(await e.text())}catch{return null}if(typeof e==`string`)try{return JSON.parse(e)}catch{return null}return e??null}async function ne(e){if(e instanceof W)return e;let t=e?.response;if(!t)return new W(`network`,ee);let n=await te(t.data);return new W(typeof n?.code==`string`&&n.code?n.code:`unknown`,typeof n?.detail==`string`&&n.detail.trim()?n.detail:ee,t.status)}async function G(e){try{return(await e()).data}catch(e){throw await ne(e)}}function K(e,t,n){n!=null&&String(n).trim()!==``&&e.append(t,String(n))}function q(e,t,n,r){(n??[]).forEach((n,i)=>{let a=n?.name||`${r}-${i+1}.png`;e.append(t,n,a)})}var re=20;function ie(e,t){return(e??[]).map((e,n)=>e?.name||`${t}-${n+1}.png`).join(`|`)}function ae(e){return e instanceof W&&typeof e.status==`number`&&e.status>=400&&e.status<=499&&e.status!==408&&e.status!==429}function oe(e,t=`/api/support`){let n=(typeof t==`string`?t:t?.base??`/api/support`).replace(/\/+$/,``),r=e=>`${n}/tickets/${encodeURIComponent(e)}`,i=/* @__PURE__ */ new Map,a=/* @__PURE__ */ new Map;function o(){for(let e of i.keys()){if(i.size<=re)return;a.has(e)||i.delete(e)}}async function s(e,t){let n=i.get(e)||crypto.randomUUID();i.delete(e),i.set(e,n),a.set(e,(a.get(e)??0)+1),o();try{let r=await t(n);return i.delete(e),r}catch(t){throw ae(t)&&i.delete(e),t}finally{let t=a.get(e)-1;t>0?a.set(e,t):a.delete(e)}}return{getConfig:()=>G(()=>e.get(`${n}/settings`)),listTickets:({status:t,search:r,page:i,pageSize:a}={})=>{let o=new URLSearchParams;K(o,`status`,t),K(o,`search`,r?.trim()),K(o,`page`,i),K(o,`pageSize`,a);let s=o.toString();return G(()=>e.get(`${n}/tickets${s?`?${s}`:``}`))},getTicketCounts:()=>G(()=>e.get(`${n}/tickets/counts`)),getTicket:t=>G(()=>e.get(r(t))),createTicket:({category:t,subject:r,body:i,pageUrl:a,userAgent:o,appVersion:c,files:l,screenshots:u})=>{let d=new FormData;return d.append(`category`,t??``),d.append(`subject`,r??``),d.append(`body`,i??``),K(d,`pageUrl`,a),K(d,`userAgent`,o),K(d,`appVersion`,c),q(d,`files`,l,`file`),q(d,`screenshots`,u,`screenshot`),s([`ticket`,t,r,i,ie(l,`file`),ie(u,`screenshot`)].join(`\0`),t=>G(()=>e.post(`${n}/tickets`,d,{headers:{"Idempotency-Key":t}})))},getSuggestions:async(t,{signal:r}={})=>{try{return await G(()=>e.get(`${n}/suggestions`,{params:{subject:t},signal:r}))}catch(e){if(e instanceof W&&e.status===404)return[];throw e}},reply:(t,{body:n,files:i,screenshots:a})=>{let o=new FormData;return o.append(`body`,n??``),q(o,`files`,i,`file`),q(o,`screenshots`,a,`screenshot`),s([`reply`,t,n,ie(i,`file`),ie(a,`screenshot`)].join(`\0`),n=>G(()=>e.post(`${r(t)}/replies`,o,{headers:{"Idempotency-Key":n}})))},reopen:t=>G(()=>e.post(`${r(t)}/reopen`)),cancel:t=>G(()=>e.post(`${r(t)}/cancel`)),rate:(t,{satisfaction:n,comment:i})=>{let a={satisfaction:n};return i!=null&&i.trim()!==``&&(a.comment=i.trim()),G(()=>e.post(`${r(t)}/rating`,a))},fetchAttachment:t=>G(()=>e.get(`${n}/attachments/${encodeURIComponent(t)}`,{responseType:`blob`})),confirmAction:t=>G(()=>e.post(`${n}/actions/confirm`,{token:t}))}}var se=3e4,ce=e(null);function J(){let e=n(ce);if(!e)throw Error(`Support components and hooks must be used inside <SupportProvider>.`);return e}function Y(){return J().client}function le(){return J().timeZone}function ue(){return J().renderTime??null}function X(e,t){let n=J().labels?.[e];return a(()=>n?{...t,...n}:t,[n,t])}function de(e,n,i=!0){let[a,c]=s({data:null,loading:i,error:null}),[l,u]=s(0),d=o(e);d.current=e;let f=o(n);r(()=>{let e=f.current!==n;if(f.current=n,!i){c({data:null,loading:!1,error:null});return}let t=!0;return c(t=>({data:e?null:t.data,loading:!0,error:null})),d.current(l>0).then(e=>t&&c({data:e,loading:!1,error:null}),e=>t&&c(t=>({...t,loading:!1,error:e}))),()=>{t=!1}},[n,i,l]);let p=t(()=>u(e=>e+1),[]),m=t(e=>c(t=>({...t,data:typeof e==`function`?e(t.data):e})),[]);return{...a,reload:p,setData:m}}function fe(){let{loadConfig:e}=J(),{data:t,loading:n,error:r,reload:i}=de(e,`config`);return{config:t,loading:n,error:r,reload:i}}function pe(e={}){let t=Y(),{status:n,search:r,page:i,pageSize:a}=e,{data:o,loading:s,error:c,reload:l}=de(()=>t.listTickets({status:n,search:r,page:i,pageSize:a}),JSON.stringify([`tickets`,n??null,r??null,i??null,a??null]));return{tickets:o?.items??[],totalCount:o?.totalCount??0,totalPages:o?.totalPages??0,loading:s,error:c,reload:l}}function me(){let e=Y(),{data:t,loading:n,error:r,reload:i}=de(()=>e.getTicketCounts(),`ticket-counts`);return{counts:t,loading:n,error:r,reload:i}}function he(e){let n=Y(),{data:i,loading:a,error:s,reload:c,setData:l}=de(()=>n.getTicket(e),e??``,!!e),u=o(0),d=o(e);d.current=e;let f=t(async e=>{u.current+=1;try{let t=await e();return l(t),t}finally{--u.current}},[l]),p=t(async()=>{if(u.current>0)return;let t=e;try{let e=await n.getTicket(t);if(d.current!==t)return;l(t=>t?Date.parse(e.updatedDateTimeUtc)>=Date.parse(t.updatedDateTimeUtc)?e:t:e)}catch{}},[n,e,l]);return r(()=>{if(!e)return;let t=null,n=()=>{t===null&&(t=setInterval(p,se))},r=()=>{t!==null&&clearInterval(t),t=null},i=()=>{document.hidden?r():(p(),n())};return document.addEventListener(`visibilitychange`,i),document.hidden||n(),()=>{r(),document.removeEventListener(`visibilitychange`,i)}},[e,p]),{ticket:i,loading:a,error:s,reload:c,reply:t(t=>f(()=>n.reply(e,t)),[f,n,e]),reopen:t(()=>f(()=>n.reopen(e)),[f,n,e]),cancel:t(()=>f(()=>n.cancel(e)),[f,n,e]),rate:t(t=>f(()=>n.rate(e,t)),[f,n,e])}}function Z(e,t){return String(e).replace(/[{]([A-Za-z0-9_]+)[}]/g,(e,n)=>n in t?String(t[n]):e)}var Q={offline:`We could not reach support. Check your connection and try again.`,attachOne:`You can attach one file.`,attachMany:`You can attach up to {count} files.`,typeNotAccepted:`{name} is a file type we cannot accept.`,tooLarge:`{name} is larger than {size}.`,thisFile:`This file`,alreadyAttached:`{name} is already attached.`};function $(e,t,n=Q.offline){if(e instanceof W){if(e.code===`network`)return n;if(e.code!==`unknown`)return e.message}return t}function ge(e){return(e?.allowedContentTypes??[]).join(`,`)}function _e(e,t){if(t.length===0)return!0;let n=(e||``).toLowerCase();return t.some(e=>{let t=e.toLowerCase();return t.endsWith(`/*`)?n.startsWith(t.slice(0,-1)):n===t})}function ve(e,t,n=Q){let r=e??[],i=t?.maxAttachmentsPerMessage??0,a=t?.maxAttachmentBytes??0,o=t?.allowedContentTypes??[];if(i>0&&r.length>i)return i===1?n.attachOne:Z(n.attachMany,{count:i});for(let e of r){let t=e.name||n.thisFile;if(!_e(e.type,o))return Z(n.typeNotAccepted,{name:t});if(a>0&&e.size>a)return Z(n.tooLarge,{name:t,size:z(a)})}return null}var ye=(e,t)=>e===1?t.attachOne:Z(t.attachMany,{count:e});function be(e){return`${e.name}|${e.size}|${e.lastModified}`}function xe(e,t,n,r=Q){let i=n?.maxAttachmentsPerMessage??0,a=new Set(e.map(be)),o=[],s=null;for(let e of t){let t=be(e);a.has(t)?s??=e.name:(a.add(t),o.push(e))}let c=i>0?Math.max(0,i-e.length):o.length,l=[...e,...o.slice(0,c)];return{files:l,notice:(o.length>c?ye(i,r):null)??ve(l,n,r)??(s?Z(r.alreadyAttached,{name:s}):``)}}function Se(e){let t=Array.from(e.clipboardData?.items??[]),n=Date.now();return t.filter(e=>e.kind===`file`&&e.type.startsWith(`image/`)).map(e=>e.getAsFile()).filter(Boolean).map((e,t)=>{let r=(e.type.split(`/`)[1]||`png`).replace(`jpeg`,`jpg`);return new File([e],`pasted-image-${n}-${t+1}.${r}`,{type:e.type})})}var Ce=80;function we(e,t){let n=Math.min(t,Ce),r=(e??``).split(/\r?\n/).find(e=>e.trim()!==``);if(r===void 0)return``;let i=r.replace(/\s+/g,` `).trim();if(i.length<=n)return i;let a=i.slice(0,n+1).lastIndexOf(` `);return(a>0?i.slice(0,a):i.slice(0,n)).replace(/[ ,;:.-]+$/,``)}function Te(e,t){let[n,i]=s(e);return r(()=>{let n=setTimeout(()=>i(e),t);return()=>clearTimeout(n)},[e,t]),n}function Ee({id:e,label:t=`Attachments`,files:n,onChange:r,config:i,error:a}){let o=i?.maxAttachmentBytes??0,s=o>0?Math.max(.1,Math.round(o/1048576*10)/10):0;return/* @__PURE__ */ H(x,{id:e,label:t,optional:!0,multiple:!0,value:n,onChange:r,accept:ge(i),maxSizeMb:s,validate:!1,error:a||void 0})}var De={title:`These may already answer your question`};function Oe({items:e}){let t=X(`suggestedAnswers`,De);return e.length===0?null:/* @__PURE__ */ H(p,{variant:`muted`,padding:`sm`,title:t.title,children:/* @__PURE__ */ H(`ul`,{className:`list-unstyled mb-0 d-flex flex-column gap-2`,children:e.map(e=>/* @__PURE__ */ U(`li`,{children:[/* @__PURE__ */ H(`div`,{className:`fw-semibold`,children:e.title}),/* @__PURE__ */ H(`div`,{className:`small text-body-secondary`,children:e.summary})]},e.title))})})}var ke={bodyRequired:`Enter what happened.`,sendFailed:`Your ticket did not send. Please try again.`,messageLabel:`Message`,messagePlaceholder:`What happened, and what did you expect to happen?`,messageHint:`You can paste an image into the message.`,subjectLabel:`Subject`,subjectPlaceholder:`A short summary`,subjectHint:`Filled in from your message. You can change it.`,categoryLabel:`Category (optional)`,categoryPlaceholder:`Choose a category`,categoryHint:`Not sure? Leave it empty and we will sort it.`},Ae=500,je=3,Me=5;function Ne(e,t){return t&&e.includes(t)?t:``}function Pe({id:e,config:t,defaultCategory:n,initialValues:i,onValuesChange:a,extraFiles:o=[],onSubmit:c,onBusyChange:u,children:d}){let f=X(`ticketForm`,ke),p=X(`shared`,Q),m=t?.categories??[],h=t?.subjectMaxLength??1/0,[g,_]=s(()=>i?.category??Ne(m,n)),[v,y]=s(i?.body??``),[b,x]=s(()=>i?.subject||we(i?.body??``,h)),[S,C]=s(()=>{let e=(i?.subject??``).trim();return e!==``&&e!==we(i?.body??``,h)}),[w,E]=s(i?.files??[]),[D,O]=s({}),[A,j]=s(``),M=Y(),[N,F]=s(``),[I,L]=s([]),R=Te(b.trim(),Ae);r(()=>{a?.({category:g,subject:b,body:v,files:w})},[g,b,v,w,a]),r(()=>{F(R)},[R]),r(()=>{if(N.length<je){L([]);return}let e=!0,t=new AbortController;return L([]),M.getSuggestions(N,{signal:t.signal}).then(t=>{e&&L(Array.isArray(t)?t.slice(0,Me):[])},()=>{e&&L([])}),()=>{e=!1,t.abort()}},[M,N]);let z=e=>{E(e),O(n=>({...n,files:ve([...o,...e],t,p)??void 0}))},B=e=>{let t=Se(e);t.length>0&&z([...w,...t])},V=e=>{let t=e.target.value;y(t),S||x(we(t,h)),D.body&&O(e=>({...e,body:t.trim()?void 0:f.bodyRequired}))},ee=e=>{let t=e.target.value;x(t),C(t.trim()!==``)};function W(){let e={};v.trim()||(e.body=f.bodyRequired);let n=ve([...o,...w],t,p);return n&&(e.files=n),O(e),Object.keys(e).length===0}async function te(e){if(e.preventDefault(),j(``),W()){u?.(!0);try{await c({category:g,subject:b.trim()||we(v,h),body:v.trim(),files:w})}catch(e){j($(e,f.sendFailed,p.offline))}finally{u?.(!1)}}}return/* @__PURE__ */ U(`form`,{id:e,onSubmit:te,noValidate:!0,className:`d-flex flex-column gap-3`,children:[A&&/* @__PURE__ */ H(l,{tone:`danger`,children:A}),/* @__PURE__ */ H(P,{id:`${e}-body`,label:f.messageLabel,required:!0,rows:6,maxLength:t?.bodyMaxLength,showCount:!0,placeholder:f.messagePlaceholder,value:v,onChange:V,onPaste:B,hint:f.messageHint,error:D.body}),/* @__PURE__ */ H(T,{id:`${e}-subject`,label:f.subjectLabel,maxLength:t?.subjectMaxLength,showCount:!0,placeholder:f.subjectPlaceholder,hint:f.subjectHint,value:b,onChange:ee,onBlur:()=>F(b.trim())}),/* @__PURE__ */ H(Oe,{items:I}),/* @__PURE__ */ H(k,{id:`${e}-category`,label:f.categoryLabel,value:g,onChange:_,options:m.map(e=>({value:e,label:e})),placeholder:f.categoryPlaceholder,hint:f.categoryHint,error:D.category}),d,/* @__PURE__ */ H(Ee,{id:`${e}-files`,files:w,onChange:z,config:t,error:D.files})]})}var Fe={captureEmpty:`The page capture came back empty.`,retake:`Retake`,removeScreenshot:`Remove screenshot`,addScreenshot:`Add a screenshot`,screenshotNote:`Only what is on your screen now. You can remove it before sending.`,screenshotFailed:`We could not take a screenshot of this page. You can attach an image instead, or send the report without one.`,screenshotTitle:`Screenshot`,screenshotLabel:`Screenshot of the page you were on`,viewTicket:`View ticket`,close:`Close`,cancel:`Cancel`,submit:`Submit`,takingScreenshot:`Taking a screenshot`,title:`Report an issue`,subtitle:`Tell us what went wrong. You can add a screenshot of this page if it helps.`,confirmDiscard:`Discard this report?`,createdTitle:`Ticket {number} is with the support team`,createdText:`We reply by email. You can follow the ticket on your support page.`,configError:`We could not load the support settings.`,loading:`Loading the form.`},Ie=`supportCapture`,Le={zIndex:`var(--wui-z-fixed)`,bottom:0,insetInlineEnd:0},Re={zIndex:`var(--wui-z-fixed)`},ze={maxWidth:`20rem`},Be=e=>e.dataset?.[Ie]===`exclude`||e.matches?.(`.modal-backdrop`)?!1:!(e.matches?.(`.modal`)&&e.querySelector?.(`[data-support-capture="exclude"]`)),Ve=()=>new Promise(e=>requestAnimationFrame(()=>e()));async function He(e){let t=await I(document.body,{filter:Be,pixelRatio:Math.min(window.devicePixelRatio||1,2),style:{overflow:`visible`,paddingRight:`0px`}});if(!t)throw Error(e);return new File([t],`screenshot.png`,{type:`image/png`})}function Ue({t:e,file:t,failed:n,disabled:i,hintId:a,controlRef:o,onAdd:c,onRemove:u}){let[d,p]=s(null);return r(()=>{if(!t)return;let e=URL.createObjectURL(t);return p(e),()=>URL.revokeObjectURL(e)},[t]),/* @__PURE__ */ U(`div`,{className:`d-flex flex-column gap-2`,children:[/* @__PURE__ */ H(`span`,{className:`wui-text-sm fw-semibold`,children:e.screenshotTitle}),t&&d&&/* @__PURE__ */ H(`img`,{src:d,alt:e.screenshotLabel,className:`d-block w-100 border rounded`,style:ze}),/* @__PURE__ */ H(`div`,{ref:o,className:`d-flex flex-wrap gap-2`,children:t?/* @__PURE__ */ U(V,{children:[/* @__PURE__ */ H(f,{variant:`outline`,size:`sm`,leftIcon:`refresh-cw`,onClick:c,disabled:i,"aria-describedby":a,children:e.retake}),/* @__PURE__ */ H(f,{variant:`ghost`,size:`sm`,leftIcon:`x`,onClick:u,disabled:i,children:e.removeScreenshot})]}):/* @__PURE__ */ H(f,{variant:`outline`,size:`sm`,leftIcon:`camera`,onClick:c,disabled:i,"aria-describedby":a,children:e.addScreenshot})}),/* @__PURE__ */ H(`span`,{id:a,className:`wui-text-sm text-body-secondary`,children:e.screenshotNote}),n&&/* @__PURE__ */ H(l,{tone:`info`,children:e.screenshotFailed})]})}function We({label:e=`Report an issue`,floating:t=!1,compact:n=!1,defaultCategory:a=`Bug report`,appVersion:c,getTicketHref:u,onOpenTicket:d,onCreated:p,className:m,style:h}){let g=X(`reportIssue`,Fe),_=X(`shared`,Q),v=Y(),{config:y,error:b}=fe(),x=`support-report-${i().replace(/[^a-zA-Z0-9-]/g,``)}`,[C,w]=s(!1),[T,E]=s(!1),[O,k]=s(null),[A,j]=s(!1),[M,N]=s(!1),[P,F]=s(null),[I,L]=s(null),R=o(null),z=o(!1);r(()=>{!T&&z.current&&(z.current=!1,R.current?.querySelector(`button`)?.focus())},[T]);function B(){F(null),k(null),j(!1),L(null),w(!0)}async function ee(){E(!0),j(!1),await Ve(),await Ve();try{k(await He(g.captureEmpty))}catch{k(null),j(!0)}finally{z.current=!0,E(!1)}}let W=()=>{M||(w(!1),k(null),j(!1),F(null),L(null))};async function te(e){let t=await v.createTicket({...e,pageUrl:window.location.href,userAgent:navigator.userAgent,appVersion:c,screenshots:O?[O]:[]});F(t),k(null),p?.(t)}let ne=!P&&(!!O||!!I&&(I.subject.trim()!==``||I.body.trim()!==``||I.files.length>0)),G=P&&u?u(P.id):void 0,K=P&&(G||d)?/* @__PURE__ */ H(f,{href:G,onClick:G?void 0:()=>{w(!1),F(null),d(P)},children:g.viewTicket}):null,q=P?/* @__PURE__ */ U(`div`,{className:`d-flex justify-content-end gap-2 w-100`,children:[/* @__PURE__ */ H(f,{variant:`secondary`,onClick:W,children:g.close}),K]}):/* @__PURE__ */ U(`div`,{className:`d-flex justify-content-end gap-2 w-100`,children:[/* @__PURE__ */ H(f,{variant:`secondary`,onClick:W,disabled:M,children:g.cancel}),/* @__PURE__ */ H(f,{type:`submit`,form:x,loading:M,disabled:!y,children:g.submit})]}),re=n?/* @__PURE__ */ H(S,{icon:`bug`,label:e,order:`secondary`,size:`sm`,variant:`secondary`,stacked:t,className:t?m:void 0,style:t?h:void 0,disabled:T,onClick:B,"aria-haspopup":`dialog`}):/* @__PURE__ */ H(f,{leftIcon:`bug`,variant:t?`primary`:`outline`,disabled:T,onClick:B,"aria-haspopup":`dialog`,children:e});return/* @__PURE__ */ U(V,{children:[t&&n?re:/* @__PURE__ */ H(`span`,{"data-support-capture":`exclude`,className:[t?`position-fixed m-3`:`d-inline-block`,m].filter(Boolean).join(` `),style:t?{...Le,...h}:h,children:re}),T&&/* @__PURE__ */ U(`div`,{"data-support-capture":`exclude`,role:`status`,className:`position-fixed top-0 start-50 translate-middle-x mt-3 d-flex align-items-center gap-2 px-3 py-2 bg-body border rounded-pill shadow-sm wui-text-sm`,style:Re,children:[/* @__PURE__ */ H(`span`,{className:`spinner-border spinner-border-sm`,"aria-hidden":`true`}),g.takingScreenshot]}),/* @__PURE__ */ H(D,{open:C,size:`lg`,title:g.title,subtitle:g.subtitle,headerIcon:`bug`,confirmDiscard:g.confirmDiscard,dirty:ne&&!M,onClose:W,footer:q,"data-support-capture":`exclude`,children:P?/* @__PURE__ */ H(l,{tone:`success`,role:`status`,title:Z(g.createdTitle,{number:P.number}),children:g.createdText}):y?/* @__PURE__ */ H(Pe,{id:x,config:y,defaultCategory:a,initialValues:I,onValuesChange:L,extraFiles:O?[O]:[],onSubmit:te,onBusyChange:N,children:/* @__PURE__ */ H(Ue,{t:g,file:O,failed:A,disabled:M||T,hintId:`${x}-screenshot-hint`,controlRef:R,onAdd:ee,onRemove:()=>k(null)})}):/* @__PURE__ */ H(l,{tone:b?`danger`:`info`,children:b?$(b,g.configError,_.offline):g.loading})})]})}var Ge={title:`New ticket`,subtitle:`Tell us what you need. We reply by email and on this page.`,confirmDiscard:`Discard this ticket?`,cancel:`Cancel`,send:`Send ticket`};function Ke({open:e,onClose:t,onCreated:n,config:r,defaultCategory:a,appVersion:o}){let c=X(`newTicketModal`,Ge),l=Y(),u=`support-new-${i().replace(/[^a-zA-Z0-9-]/g,``)}`,[d,p]=s(!1),[m,h]=s(null),g=!!m&&(m.subject.trim()!==``||m.body.trim()!==``||m.files.length>0);async function _(e){n(await l.createTicket({...e,userAgent:typeof navigator>`u`?void 0:navigator.userAgent,appVersion:o}))}return/* @__PURE__ */ H(D,{open:e,size:`lg`,title:c.title,subtitle:c.subtitle,headerIcon:`message-square`,confirmDiscard:c.confirmDiscard,dirty:g&&!d,onClose:()=>{d||t()},footer:/* @__PURE__ */ U(`div`,{className:`d-flex justify-content-end gap-2 w-100`,children:[/* @__PURE__ */ H(f,{variant:`secondary`,onClick:t,disabled:d,children:c.cancel}),/* @__PURE__ */ H(f,{type:`submit`,form:u,loading:d,children:c.send})]}),children:e&&/* @__PURE__ */ H(Pe,{id:u,config:r,defaultCategory:a,onSubmit:_,onBusyChange:p,onValuesChange:h})})}var qe={Open:`info`,InProgress:`info`,WaitingOnCustomer:`warning`,Resolved:`success`,Closed:`success`,Cancelled:`neutral`};function Je(e){return qe[e]??`neutral`}var Ye={loading:`Loading {name}`,failed:`Could not load this file. Click to try again.`},Xe=6e4,Ze=[`image/png`,`image/jpeg`,`image/gif`,`image/webp`,`application/pdf`];function Qe({attachment:e}){let t=X(`attachmentThumb`,Ye),n=Y(),[r,i]=s(!1),[a,o]=s(!1);async function c(){i(!0),o(!1);let t=Ze.includes(e.contentType)?window.open(``,`_blank`):null;t&&(t.opener=null);try{let r=await n.fetchAttachment(e.id),i=URL.createObjectURL(r);if(setTimeout(()=>URL.revokeObjectURL(i),Xe),t)t.location.href=i;else{let t=document.createElement(`a`);t.href=i,t.download=e.fileName,t.click()}}catch{t?.close(),o(!0)}finally{i(!1)}}let l=Number.isFinite(e.sizeBytes)?z(e.sizeBytes):`-`;return/* @__PURE__ */ U(V,{children:[/* @__PURE__ */ H(m,{leadingIcon:a?`x-circle`:`paperclip`,label:r?/* @__PURE__ */ U(V,{children:[/* @__PURE__ */ H(j,{size:`sm`,label:Z(t.loading,{name:e.fileName})}),` `,e.fileName]}):e.fileName,onClick:c,disabled:r,"aria-busy":r||void 0,title:`${e.fileName}, ${l}`}),a&&/* @__PURE__ */ H(`span`,{role:`status`,className:`wui-text-xs text-danger align-self-center`,children:t.failed})]})}function $e({iso:e,className:t}){let n=ue(),r=le();return n?n(e):/* @__PURE__ */ H(`time`,{dateTime:e,className:t,children:R(e,{timeZone:r})})}var et={conversation:`Conversation`,you:`You`,supportTeam:`Support team`,supportBadge:`Support`},tt={whiteSpace:`pre-wrap`,overflowWrap:`anywhere`};function nt({messages:e}){let t=X(`messageThread`,et);return/* @__PURE__ */ H(`ol`,{className:`list-unstyled d-flex flex-column gap-3 mb-0`,"aria-label":t.conversation,children:e.map(e=>{let n=/* @__PURE__ */ H($e,{iso:e.createdDateTimeUtc,className:`wui-text-xs text-body-secondary text-nowrap`});if(e.authorKind===`System`)return/* @__PURE__ */ U(`li`,{className:`text-center wui-text-xs text-body-secondary`,"data-author":`system`,children:[/* @__PURE__ */ H(`span`,{className:`d-block`,children:e.body}),n]},e.id);let r=e.authorKind===`Customer`,i=e.authorName||(r?t.you:t.supportTeam);return/* @__PURE__ */ U(`li`,{className:`d-flex align-items-start gap-2${r?` flex-row-reverse`:``}`,"data-author":r?`customer`:`agent`,children:[/* @__PURE__ */ H(u,{name:i,size:32,tone:r?`neutral`:`primary`}),/* @__PURE__ */ U(p,{className:`flex-grow-1 border`,padding:`sm`,variant:r?`default`:`accent`,style:{minWidth:0},children:[/* @__PURE__ */ U(`div`,{className:`d-flex flex-wrap align-items-center justify-content-between gap-2 mb-2`,children:[/* @__PURE__ */ U(`span`,{className:`d-inline-flex flex-wrap align-items-center gap-2 fw-semibold wui-text-sm text-break`,children:[i,!r&&/* @__PURE__ */ H(d,{tone:`primary`,children:t.supportBadge})]}),n]}),/* @__PURE__ */ H(`div`,{className:`wui-text-sm`,style:tt,children:e.body}),e.attachments?.length>0&&/* @__PURE__ */ H(`div`,{className:`d-flex flex-wrap gap-2 mt-2`,children:e.attachments.map(e=>/* @__PURE__ */ H(Qe,{attachment:e},e.id))})]})]},e.id)})})}var rt={solved:`You told us this solved your problem.`,notSolved:`You told us this did not solve your problem.`,sendFailed:`Your rating did not send. Please try again.`,commentLabel:`Anything to add?`,commentHint:`Optional. Your comment goes to the support team.`,yes:`Yes, it is solved`,no:`No, it is not`,heading:`Did this solve your problem?`,yourComment:`Your comment:`};function it({satisfaction:e,comment:t,canRate:n=!1,commentMaxLength:r,onRate:a}){let o=X(`ratingPanel`,rt),c=X(`shared`,Q),u=i(),[d,m]=s(``),[h,g]=s(null),[_,v]=s(``);if(e)return/* @__PURE__ */ U(l,{tone:e===`Satisfied`?`success`:`info`,role:`status`,children:[e===`Satisfied`?o.solved:o.notSolved,t?/* @__PURE__ */ U(`span`,{className:`d-block mt-1`,children:[o.yourComment,` `,t]}):null]});if(!n)return null;async function y(e){v(``),g(e);try{await a({satisfaction:e,comment:d})}catch(e){v($(e,o.sendFailed,c.offline))}finally{g(null)}}return/* @__PURE__ */ H(p,{padding:`sm`,className:`border`,title:o.heading,children:/* @__PURE__ */ U(`div`,{className:`d-flex flex-column gap-2`,children:[_&&/* @__PURE__ */ H(l,{tone:`danger`,children:_}),/* @__PURE__ */ H(P,{id:`${u}-comment`,label:o.commentLabel,rows:2,maxLength:r,value:d,onChange:e=>m(e.target.value),hint:o.commentHint}),/* @__PURE__ */ U(`div`,{className:`d-flex flex-wrap gap-2`,children:[/* @__PURE__ */ H(f,{variant:`outline`,leftIcon:`check-circle`,loading:h===`Satisfied`,disabled:h!==null,onClick:()=>y(`Satisfied`),children:o.yes}),/* @__PURE__ */ H(f,{variant:`outline`,leftIcon:`x-circle`,loading:h===`Unsatisfied`,disabled:h!==null,onClick:()=>y(`Unsatisfied`),children:o.no})]})]})})}var at={emptyReply:`Write a message before you send it.`,sendFailed:`Your reply did not send. Please try again.`,replyLabel:`Your reply`,hintReopens:`Sending a reply reopens this ticket. You can paste an image into the message.`,hint:`You can paste an image into the message.`,attachedFiles:`Attached files`,removeFile:`Remove {name}`,attach:`Attach a file`,send:`Send reply`,formLabel:`Reply to this ticket`};function ot({onSend:e,config:t,reopens:n=!1}){let r=X(`replyBox`,at),a=X(`shared`,Q),o=i(),[u,d]=s(``),[p,g]=s([]),[_,v]=s(``),[y,b]=s(``),[x,S]=s(!1),C=e=>{let n=xe(p,e,t,a);g(n.files),v(n.notice)},w=e=>{let n=p.filter((t,n)=>n!==e);g(n),v(ve(n,t,a)??``)},T=e=>{let t=Se(e);t.length>0&&C(t)};async function E(n){n.preventDefault();let i=u.trim();if(!i){b(r.emptyReply);return}let o=ve(p,t,a);if(o)v(o);else{b(``),S(!0);try{await e({body:i,files:p}),d(``),g([]),v(``)}catch(e){b($(e,r.sendFailed,a.offline))}finally{S(!1)}}}let D=y||_;return/* @__PURE__ */ U(`form`,{onSubmit:E,noValidate:!0,className:`d-flex flex-column gap-2 flex-grow-1 min-w-0`,"aria-label":r.formLabel,children:[D&&/* @__PURE__ */ H(l,{tone:`danger`,children:D}),/* @__PURE__ */ H(P,{id:`${o}-body`,label:r.replyLabel,rows:2,autoGrow:!0,maxLength:t?.bodyMaxLength,value:u,onChange:e=>{d(e.target.value),b(``)},onPaste:T,hint:n?r.hintReopens:r.hint,required:!0}),p.length>0&&/* @__PURE__ */ H(h,{label:r.attachedFiles,children:p.map((e,t)=>/* @__PURE__ */ H(m,{leadingIcon:`paperclip`,label:e.name,removeLabel:Z(r.removeFile,{name:e.name}),onRemove:()=>w(t)},be(e)))}),/* @__PURE__ */ U(`div`,{className:`d-flex flex-wrap align-items-center justify-content-between gap-2`,children:[/* @__PURE__ */ H(c,{iconVariant:`bulk`,icon:`paperclip`,label:r.attach,multiple:t?.maxAttachmentsPerMessage!==1,accept:ge(t),onFiles:C}),/* @__PURE__ */ H(f,{type:`submit`,leftIcon:`send`,loading:x,children:r.send})]})]})}var st={reopenFailed:`The ticket did not reopen. Please try again.`,withdrawFailed:`The request was not withdrawn. Please try again.`,back:`Back to tickets`,loadError:`We could not load this ticket.`,retry:`Try again`,fieldStatus:`Status`,fieldCategory:`Category`,fieldTicket:`Ticket`,fieldOpened:`Opened`,fieldUpdated:`Last update`,openedLabel:`Opened`,summaryLabel:`Ticket summary`,detailsLabel:`Ticket details`,detailsTitle:`Ticket details`,timeZoneNote:`Times are shown in {zone}.`,mergedText:`This ticket was merged into {number}. The conversation carries on there.`,openMerged:`Open {number}`,resolvedHint:`If you still need help, reopen the ticket or send a reply.`,waitingHint:`We need your answer to carry on. Reply below and the ticket goes back to our team.`,openHint:`Our team marks this resolved once your question is answered. Replying reopens it.`,reopen:`Reopen ticket`,withdraw:`Withdraw request`,withdrawTitle:`Withdraw this request?`,withdrawMessage:`Our team will stop working on this ticket. You can open a new ticket later if you still need help.`,withdrawConfirm:`Withdraw request`,withdrawCancel:`Keep request`,merged:`Merged into this ticket`};function ct({ticketId:e,onBack:t,onChanged:n,onOpenTicket:r}){let{config:i}=fe(),a=X(`ticketDetail`,st),o=X(`shared`,Q),c=le(),u=ue(),{ticket:d,loading:m,error:h,reload:_,reply:v,reopen:b,cancel:x,rate:S}=he(e),[T,E]=s(!1),[D,O]=s(!1),[k,j]=s(!1),[N,P]=s(``),F=async e=>{let t=await e();return n?.(),t};async function I(){P(``),E(!0);try{await F(b)}catch(e){P($(e,a.reopenFailed,o.offline))}finally{E(!1)}}async function L(){P(``),j(!0);try{await F(x)}catch(e){P($(e,a.withdrawFailed,o.offline))}finally{j(!1),O(!1)}}let R=/* @__PURE__ */ H(f,{variant:`ghost`,size:`sm`,leftIcon:`arrow-left`,onClick:t,className:`align-self-start`,children:a.back});if(!d)return/* @__PURE__ */ U(`section`,{className:`d-flex flex-column gap-3`,"aria-busy":m||void 0,children:[R,h?/* @__PURE__ */ U(l,{tone:`danger`,children:[$(h,a.loadError,o.offline),` `,/* @__PURE__ */ H(f,{variant:`ghost`,size:`sm`,onClick:_,children:a.retry})]}):/* @__PURE__ */ H(A,{height:160})]});let z=Je(d.status),V=[{key:`status`,label:a.fieldStatus,value:d.statusLabel?/* @__PURE__ */ H(M,{label:d.statusLabel,tone:z}):`-`},{key:`category`,label:a.fieldCategory,value:d.category||`-`},{key:`ticket`,label:a.fieldTicket,value:d.number},{key:`opened`,label:a.fieldOpened,value:/* @__PURE__ */ H($e,{iso:d.createdDateTimeUtc})},{key:`updated`,label:a.fieldUpdated,value:/* @__PURE__ */ H($e,{iso:d.updatedDateTimeUtc})}];return/* @__PURE__ */ U(`section`,{className:`d-flex flex-column gap-3`,"aria-labelledby":`support-ticket-${d.id}`,children:[R,/* @__PURE__ */ U(`div`,{className:`row g-3`,children:[/* @__PURE__ */ U(`div`,{className:`col-12 col-lg-8 d-flex flex-column gap-3`,children:[/* @__PURE__ */ U(`header`,{className:`d-flex flex-column gap-2`,children:[/* @__PURE__ */ U(`div`,{className:`d-flex flex-wrap align-items-center gap-2`,children:[/* @__PURE__ */ H(`h2`,{id:`support-ticket-${d.id}`,className:`h5 mb-0 text-break`,children:d.subject}),d.statusLabel&&/* @__PURE__ */ H(M,{label:d.statusLabel,tone:z})]}),/* @__PURE__ */ U(`ul`,{className:`list-unstyled d-flex flex-wrap gap-3 mb-0 wui-text-sm text-body-secondary`,"aria-label":a.summaryLabel,children:[d.number&&/* @__PURE__ */ U(`li`,{className:`d-inline-flex align-items-center gap-1`,children:[/* @__PURE__ */ H(w,{variant:`bulk`,name:`receipt-text`,size:16}),d.number]}),d.category&&/* @__PURE__ */ U(`li`,{className:`d-inline-flex align-items-center gap-1`,children:[/* @__PURE__ */ H(w,{variant:`bulk`,name:`folder-2`,size:16}),d.category]}),/* @__PURE__ */ U(`li`,{className:`d-inline-flex align-items-center gap-1`,children:[/* @__PURE__ */ H(w,{variant:`bulk`,name:`calendar-1`,size:16}),a.openedLabel,` `,/* @__PURE__ */ H($e,{iso:d.createdDateTimeUtc})]})]}),u===null&&/* @__PURE__ */ H(`p`,{className:`wui-text-xs text-body-secondary mb-0`,children:Z(a.timeZoneNote,{zone:B(c)})})]}),N&&/* @__PURE__ */ H(l,{tone:`danger`,children:N}),d.mergedInto&&/* @__PURE__ */ U(l,{tone:`info`,role:`status`,children:[Z(a.mergedText,{number:d.mergedInto.number}),` `,r&&/* @__PURE__ */ H(f,{variant:`ghost`,size:`sm`,onClick:()=>r(d.mergedInto.id),children:Z(a.openMerged,{number:d.mergedInto.number})})]}),d.canReopen&&/* @__PURE__ */ H(l,{tone:`success`,role:`status`,children:a.resolvedHint}),d.status===`WaitingOnCustomer`&&/* @__PURE__ */ H(l,{tone:`warning`,role:`status`,children:a.waitingHint}),!d.canReopen&&/* @__PURE__ */ H(`p`,{className:`wui-text-sm text-body-secondary mb-0`,children:a.openHint}),d.canReopen&&/* @__PURE__ */ H(f,{variant:`secondary`,leftIcon:`history`,loading:T,onClick:I,className:`align-self-start`,children:a.reopen}),d.canCancel&&/* @__PURE__ */ H(f,{variant:`secondary`,onClick:()=>O(!0),className:`align-self-start`,children:a.withdraw}),/* @__PURE__ */ H(g,{open:D,title:a.withdrawTitle,message:a.withdrawMessage,confirmLabel:a.withdrawConfirm,cancelLabel:a.withdrawCancel,danger:!0,loading:k,onConfirm:L,onClose:()=>O(!1)}),/* @__PURE__ */ H(it,{satisfaction:d.satisfaction,comment:d.satisfactionComment,canRate:d.canRate,commentMaxLength:i?.satisfactionCommentMaxLength,onRate:e=>F(()=>S(e))}),/* @__PURE__ */ H(nt,{messages:d.messages??[]}),d.mergedTickets?.length>0&&/* @__PURE__ */ U(`section`,{"aria-labelledby":`support-merged-${d.id}`,className:`d-flex flex-column gap-1`,children:[/* @__PURE__ */ H(`h3`,{id:`support-merged-${d.id}`,className:`h6 mb-0`,children:a.merged}),/* @__PURE__ */ H(`ul`,{className:`list-unstyled d-flex flex-column gap-1 mb-0 wui-text-sm`,children:d.mergedTickets.map(e=>/* @__PURE__ */ H(`li`,{children:r?/* @__PURE__ */ U(f,{variant:`ghost`,size:`sm`,onClick:()=>r(e.id),children:[e.number,`: `,e.subject]}):`${e.number}: ${e.subject}`},e.id))})]}),!d.mergedInto&&/* @__PURE__ */ H(C,{sticky:!0,align:`start`,children:/* @__PURE__ */ H(ot,{config:i,reopens:d.canReopen,onSend:e=>F(()=>v(e))})})]}),/* @__PURE__ */ H(`aside`,{"aria-label":a.detailsLabel,className:`col-12 col-lg-4`,children:/* @__PURE__ */ U(p,{padding:`sm`,className:`border`,children:[/* @__PURE__ */ H(`h3`,{className:`h6`,children:a.detailsTitle}),/* @__PURE__ */ H(y,{columns:1,items:V})]})})]})]})}var lt=`ticket`;function ut(){return typeof window>`u`?null:new URLSearchParams(window.location.search).get(lt)}function dt(e){if(typeof window>`u`)return e?`?${lt}=${encodeURIComponent(e)}`:`?`;let t=new URL(window.location.href);return e?t.searchParams.set(lt,e):t.searchParams.delete(lt),`${t.pathname}${t.search}${t.hash}`}function ft(e){if(typeof window>`u`)return;let t=dt(e);t!==`${window.location.pathname}${window.location.search}${window.location.hash}`&&window.history.replaceState(window.history.state,``,t)}var pt={tabAll:`All`,tabOpen:`Open`,tabNeedsReply:`Needs your reply`,tabResolved:`Resolved`,tabWithdrawn:`Withdrawn`,columnSubject:`Subject`,columnStatus:`Status`,columnMessages:`Messages`,columnLastUpdate:`Last update`,loadError:`We could not load your tickets.`,retry:`Try again`,statusSelect:`Status`,filterByStatus:`Filter tickets by status`,searchPlaceholder:`Search tickets`,searchLabel:`Search tickets`,tableLabel:`Support tickets`,actions:`Actions`,openTicket:`Open ticket {subject}`,emptyTitle:`No tickets yet`,emptyText:`When you raise a ticket, it shows here with its status.`,noMatchTitle:`No tickets match`,noMatchText:`Try another search or status.`},mt=[`tabs`,`select`,`none`];function ht({tickets:e,loading:t,error:n,onRetry:r,onOpen:i,status:a,onStatusChange:o,statusFilter:s=`tabs`,counts:u,search:d,onSearchChange:p,pagination:m}){let h=X(`ticketList`,pt),g=X(`shared`,Q);F(`SupportCenter`,`statusFilter`,s,mt);let _=[{key:`all`,label:h.tabAll,countKey:`total`},{key:`Open`,label:h.tabOpen,countKey:`open`},{key:`NeedsReply`,label:h.tabNeedsReply,countKey:`needsReply`},{key:`Resolved`,label:h.tabResolved,countKey:`resolved`},{key:`Withdrawn`,label:h.tabWithdrawn,countKey:`withdrawn`}],y=_.map(({key:e,label:t,countKey:n})=>{let r=u?.[n];return{value:e,label:r==null?t:`${t} (${r})`}}),x=(e,t)=>{e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||(e.preventDefault(),i(t))},S=[{key:`subject`,label:h.columnSubject,render:e=>/* @__PURE__ */ U(`div`,{className:`d-flex flex-column`,style:{minWidth:0},children:[/* @__PURE__ */ H(E,{href:dt(e.id),animation:`none`,className:`fw-semibold text-break`,onClick:t=>x(t,e.id),children:e.subject}),/* @__PURE__ */ U(`span`,{className:`wui-text-xs text-body-secondary`,children:[e.number,`, `,e.category]})]})},{key:`status`,label:h.columnStatus,render:e=>e.statusLabel?/* @__PURE__ */ H(M,{label:e.statusLabel,tone:Je(e.status)}):`-`},{key:`messageCount`,label:h.columnMessages,cellClassName:`wui-text-sm text-body-secondary`,render:e=>e.messageCount},{key:`updatedDateTimeUtc`,label:h.columnLastUpdate,cellClassName:`wui-text-sm text-body-secondary text-nowrap`,render:e=>/* @__PURE__ */ H($e,{iso:e.updatedDateTimeUtc})}];return/* @__PURE__ */ U(`div`,{className:`d-flex flex-column gap-3`,children:[n&&/* @__PURE__ */ U(l,{tone:`danger`,children:[$(n,h.loadError,g.offline),` `,/* @__PURE__ */ H(f,{variant:`ghost`,size:`sm`,onClick:r,children:h.retry})]}),/* @__PURE__ */ U(`div`,{className:`d-flex flex-column flex-md-row gap-2 align-items-md-center justify-content-between`,children:[s===`none`?null:s===`select`?/* @__PURE__ */ H(k,{label:h.statusSelect,value:a,onChange:o,options:y,fieldClassName:`flex-shrink-0`}):/* @__PURE__ */ H(N,{tabs:_.map(({key:e,label:t,countKey:n})=>({key:e,label:t,count:u?.[n]})),value:a,onChange:o,ariaLabel:h.filterByStatus,className:`flex-grow-1`}),/* @__PURE__ */ H(O,{value:d,onChange:p,placeholder:h.searchPlaceholder,ariaLabel:h.searchLabel})]}),/* @__PURE__ */ H(v,{columns:S,rows:e,loading:t,skeletonRows:4,ariaLabel:h.tableLabel,rowActionsLabel:h.actions,rowActions:e=>/* @__PURE__ */ H(c,{icon:`eye`,label:Z(h.openTicket,{subject:e.subject}),href:dt(e.id),onClick:t=>x(t,e.id)}),stickyActions:!0,stackOnMobile:!0,sourceCount:u?.total??0,pagination:m,empty:/* @__PURE__ */ H(b,{variant:`table`,icon:`message-square`,title:h.emptyTitle,text:h.emptyText}),emptyFiltered:/* @__PURE__ */ H(b,{variant:`table`,icon:`search`,title:h.noMatchTitle,text:h.noMatchText})})]})}var gt=300,_t=10,vt={heading:`Your tickets`,newTicket:`New ticket`,configError:`We could not load the support settings.`,retry:`Try again`};function yt({initialTicketId:e,defaultCategory:t,appVersion:n,status:i,defaultStatus:a=`all`,onStatusChange:o,statusFilter:c=`tabs`}){let u=X(`supportCenter`,vt),d=X(`shared`,Q),{config:p,error:m,reload:h}=fe(),[g,_]=s(a),v=i!==void 0,y=v?i:g,b=e=>{v||_(e),o?.(e)},[x,S]=s(``),C=Te(x.trim(),gt),[w,T]=s(_t),E=`${y}|${C}|${w}`,[D,O]=s({key:E,page:1}),k=D.key===E?D.page:1,A=e=>O({key:E,page:e}),j=pe({status:y===`all`?void 0:y,search:C||void 0,page:k,pageSize:w}),{counts:M,reload:N}=me(),[P,F]=s(()=>e||ut()),[I,L]=s(!1),R=j.totalPages;r(()=>{R>0&&k>R&&O({key:E,page:R})},[R,k,E]);let z=()=>{j.reload(),N()},B=e=>{F(e),ft(e)};if(P)return/* @__PURE__ */ H(ct,{ticketId:P,onBack:()=>B(null),onChanged:z,onOpenTicket:B},P);let V={page:k,totalPages:Math.max(1,j.totalPages),pageSize:w,total:j.totalCount,setPage:A,setPageSize:T};return/* @__PURE__ */ U(`section`,{className:`d-flex flex-column gap-3 min-w-0`,"aria-labelledby":`support-center-title`,children:[/* @__PURE__ */ U(`div`,{className:`d-flex flex-wrap align-items-center justify-content-between gap-2`,children:[/* @__PURE__ */ H(`h2`,{id:`support-center-title`,className:`h5 mb-0`,children:u.heading}),/* @__PURE__ */ H(f,{leftIcon:`plus`,onClick:()=>L(!0),disabled:!p,children:u.newTicket})]}),m&&/* @__PURE__ */ U(l,{tone:`warning`,children:[$(m,u.configError,d.offline),` `,/* @__PURE__ */ H(f,{variant:`ghost`,size:`sm`,onClick:h,children:u.retry})]}),/* @__PURE__ */ H(ht,{tickets:j.tickets,loading:j.loading,error:j.error,onRetry:z,onOpen:B,status:y,onStatusChange:b,statusFilter:c,counts:M,search:x,onSearchChange:S,pagination:V}),p&&/* @__PURE__ */ H(Ke,{open:I,onClose:()=>L(!1),config:p,defaultCategory:t,appVersion:n,onCreated:e=>{L(!1),z(),B(e.id)}})]})}var bt={copyEmail:`Copy email`,emailCopied:`Email copied`,contactNamed:`Contact {name}`,contactSupport:`Contact support`},xt=e=>typeof e==`string`&&e.trim()!==``;function St({className:e}){let t=X(`supportContact`,bt),{config:n}=fe();if(!n)return null;let r=xt(n.supportEmail),i=xt(n.supportPhone),a=xt(n.supportHours);if(!r&&!i&&!a)return null;let o=[`d-flex flex-wrap align-items-center gap-2 wui-text-sm`,e].filter(Boolean).join(` `);return/* @__PURE__ */ U(`section`,{className:o,"aria-label":xt(n.supportName)?Z(t.contactNamed,{name:n.supportName}):t.contactSupport,children:[/* @__PURE__ */ H(`span`,{className:`fw-semibold`,children:xt(n.supportName)?n.supportName:t.contactSupport}),r&&/* @__PURE__ */ U(`span`,{className:`d-inline-flex align-items-center gap-1`,children:[/* @__PURE__ */ H(`a`,{href:`mailto:${n.supportEmail}`,className:`text-break`,children:n.supportEmail}),/* @__PURE__ */ H(_,{text:n.supportEmail,iconOnly:!0,label:t.copyEmail,copiedLabel:t.emailCopied})]}),i&&/* @__PURE__ */ H(`a`,{href:`tel:${n.supportPhone.replace(/[^\d+]/g,``)}`,children:n.supportPhone}),a&&/* @__PURE__ */ H(`span`,{className:`text-body-secondary`,children:n.supportHours})]})}function Ct({client:e,timeZone:n=L,renderTime:r,labels:i,children:s}){let c=o(null),l=t((t=!1)=>{let n=c.current;if(t||!n||n.client!==e){let t=e.getConfig(),n={client:e,pending:t};return c.current=n,t.catch(()=>{c.current===n&&(c.current=null)}),t}return n.pending},[e]),u=a(()=>({client:e,loadConfig:l,timeZone:n,renderTime:r,labels:i}),[e,l,n,r,i]);return/* @__PURE__ */ H(ce.Provider,{value:u,children:s})}export{We as ReportIssue,W as SupportApiError,yt as SupportCenter,St as SupportContact,Ct as SupportProvider,oe as createSupportClient,Y as useSupportClient,fe as useSupportConfig,he as useSupportTicket,me as useSupportTicketCounts,pe as useSupportTickets};
@@ -5,11 +5,13 @@
5
5
  * @param {import('./client.js').SupportClient} props.client From `createSupportClient(http)`.
6
6
  * @param {string} [props.timeZone="Asia/Kolkata"] IANA zone every ticket and message time is shown in.
7
7
  * @param {(iso: string) => import('react').ReactNode} [props.renderTime] Draws every ticket and message time instead of the built-in date and time. When set, the ticket's "Times are shown in" note is left out, because the product's own rendering decides the zone.
8
+ * @param {Record<string, Record<string, string>>} [props.labels] Replaces any built-in English text. Keyed by scope (supportCenter, reportIssue, supportChat, supportContact, ticketList, ticketDetail, ticketForm, newTicketModal, replyBox, ratingPanel, messageThread, suggestedAnswers, attachmentThumb, chatStatusBar, chatTranscript, waitingNotice, chatSession, shared), then by key. Give only the keys you change.
8
9
  * @param {import('react').ReactNode} props.children
9
10
  */
10
- export default function SupportProvider({ client, timeZone, renderTime, children }: {
11
+ export default function SupportProvider({ client, timeZone, renderTime, labels, children }: {
11
12
  client: import('./client.js').SupportClient;
12
13
  timeZone?: string;
13
14
  renderTime?: (iso: string) => import('react').ReactNode;
15
+ labels?: Record<string, Record<string, string>>;
14
16
  children: import('react').ReactNode;
15
17
  }): import("react").JSX.Element;
@@ -197,7 +197,7 @@ export type SupportClient = {
197
197
  *
198
198
  * @param {SupportHttp} http The product's axios-like instance (bearer token and refresh already wired).
199
199
  * @param {string | { base?: string }} [options="/api/support"] The prefix the API maps the support endpoints
200
- * under, as a string or as `{ base }` like `createChatClient`.
200
+ * under, as a string or as `{ base }`.
201
201
  * @returns {SupportClient}
202
202
  */
203
203
  export declare function createSupportClient(http: SupportHttp, options?: string | {
@@ -8,7 +8,7 @@
8
8
  * @param {any} [props.error]
9
9
  * @param {() => void} props.onRetry
10
10
  * @param {(id: string) => void} props.onOpen
11
- * @param {string} props.status A `STATUS_FILTERS` key.
11
+ * @param {string} props.status A status tab key.
12
12
  * @param {(status: string) => void} props.onStatusChange
13
13
  * @param {"tabs"|"select"|"none"} [props.statusFilter="tabs"] Tabs, a Status select, or no control.
14
14
  * @param {import('../client.js').TicketCounts|null} [props.counts] Labels the tabs and the select once loaded.
@@ -1,9 +1,10 @@
1
- /** @type {import('react').Context<{ client: import('./client.js').SupportClient, loadConfig: (fresh?: boolean) => Promise<any>, timeZone: string, renderTime?: (iso: string) => import('react').ReactNode } | null>} */
1
+ /** @type {import('react').Context<{ client: import('./client.js').SupportClient, loadConfig: (fresh?: boolean) => Promise<any>, timeZone: string, renderTime?: (iso: string) => import('react').ReactNode, labels?: Record<string, Record<string, string>> } | null>} */
2
2
  export declare const SupportContext: import('react').Context<{
3
3
  client: import('./client.js').SupportClient;
4
4
  loadConfig: (fresh?: boolean) => Promise<any>;
5
5
  timeZone: string;
6
6
  renderTime?: (iso: string) => import('react').ReactNode;
7
+ labels?: Record<string, Record<string, string>>;
7
8
  } | null>;
8
9
  /**
9
10
  * The support client the nearest SupportProvider holds.
@@ -23,6 +24,7 @@ export declare function useSupportTimeZone(): string;
23
24
  * @returns {((iso: string) => import('react').ReactNode)|null}
24
25
  */
25
26
  export declare function useSupportRenderTime(): ((iso: string) => import('react').ReactNode) | null;
27
+ export declare function useSupportLabels(scope: any, defaults: any): any;
26
28
  /**
27
29
  * What the customer may send and how to reach support. Loaded once per provider and shared.
28
30
  *
@@ -1,10 +1,6 @@
1
- export { createSupportChatClient } from "./chat/client.js";
2
- export { createSseChatConnection } from "./chat/connection.js";
3
1
  export { createSupportClient, SupportApiError } from "./client.js";
4
2
  export { useSupportClient, useSupportConfig, useSupportTicket, useSupportTicketCounts, useSupportTickets } from "./context.js";
5
3
  export { default as ReportIssue } from "./ReportIssue.jsx";
6
4
  export { default as SupportCenter } from "./SupportCenter.jsx";
7
- export { default as SupportChat } from "./SupportChat.jsx";
8
- export { default as SupportChatLauncher } from "./SupportChatLauncher.jsx";
9
5
  export { default as SupportContact } from "./SupportContact.jsx";
10
6
  export { default as SupportProvider } from "./SupportProvider.jsx";
@@ -0,0 +1,11 @@
1
+ export declare function fillLabel(template: any, values: any): string;
2
+ /** Strings several support components share. Scope name: shared. */
3
+ export declare const SHARED_LABELS: {
4
+ offline: string;
5
+ attachOne: string;
6
+ attachMany: string;
7
+ typeNotAccepted: string;
8
+ tooLarge: string;
9
+ thisFile: string;
10
+ alreadyAttached: string;
11
+ };
@@ -5,6 +5,7 @@
5
5
  *
6
6
  * @param {unknown} err
7
7
  * @param {string} fallback
8
+ * @param {string} [offline] The sentence for a network failure.
8
9
  * @returns {string}
9
10
  */
10
- export declare function supportErrorText(err: unknown, fallback: string): string;
11
+ export declare function supportErrorText(err: unknown, fallback: string, offline?: string): string;
@@ -1,3 +1,4 @@
1
+ import { SHARED_LABELS } from "../labels.js";
1
2
  /**
2
3
  * The `accept` attribute for a file input, from the config's allowed content types. An empty
3
4
  * list means any type, so this returns "" rather than undefined: undefined would let the field
@@ -15,13 +16,14 @@ export declare function acceptOf(config: {
15
16
  *
16
17
  * @param {Blob[]} files Every file on the message, screenshots included.
17
18
  * @param {{ maxAttachmentBytes?: number, maxAttachmentsPerMessage?: number, allowedContentTypes?: string[] }|null|undefined} config
19
+ * @param {typeof SHARED_LABELS} [labels]
18
20
  * @returns {string|null}
19
21
  */
20
22
  export declare function validateAttachments(files: Blob[], config: {
21
23
  maxAttachmentBytes?: number;
22
24
  maxAttachmentsPerMessage?: number;
23
25
  allowedContentTypes?: string[];
24
- } | null | undefined): string | null;
26
+ } | null | undefined, labels?: typeof SHARED_LABELS): string | null;
25
27
  /**
26
28
  * The same file picked twice has the same name, size and modified time. A pasted image is a new
27
29
  * File each time, so pasting twice keeps both.
@@ -41,13 +43,14 @@ export declare function fileIdOf(f: Blob & {
41
43
  * @param {File[]} current
42
44
  * @param {File[]} picked
43
45
  * @param {{ maxAttachmentBytes?: number, maxAttachmentsPerMessage?: number, allowedContentTypes?: string[] }|null|undefined} config
46
+ * @param {typeof SHARED_LABELS} [labels]
44
47
  * @returns {{ files: File[], notice: string }}
45
48
  */
46
49
  export declare function mergeAttachments(current: File[], picked: File[], config: {
47
50
  maxAttachmentBytes?: number;
48
51
  maxAttachmentsPerMessage?: number;
49
52
  allowedContentTypes?: string[];
50
- } | null | undefined): {
53
+ } | null | undefined, labels?: typeof SHARED_LABELS): {
51
54
  files: File[];
52
55
  notice: string;
53
56
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webority/support-react",
3
- "version": "0.128.0",
3
+ "version": "0.129.0",
4
4
  "description": "Webority customer support for React portals: ticket centre, report-an-issue with an optional page screenshot, and support contact details, built on @webority/ui-react.",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "type": "module",
@@ -27,9 +27,8 @@
27
27
  },
28
28
  "sideEffects": false,
29
29
  "peerDependencies": {
30
- "@webority/chat-react": "0.128.0",
31
- "@webority/ui-elements": "0.128.0",
32
- "@webority/ui-react": "0.128.0",
30
+ "@webority/ui-elements": "0.129.0",
31
+ "@webority/ui-react": "0.129.0",
33
32
  "bootstrap": "5.3.3",
34
33
  "react": "^19.0.0",
35
34
  "react-bootstrap": "^2.10.0",
@@ -43,10 +42,9 @@
43
42
  "@types/react": "^19.2.17",
44
43
  "@vitejs/plugin-react": "^6.0.1",
45
44
  "@vitest/coverage-v8": "5.0.1",
46
- "@webority/canvas-kit": "0.128.0",
47
- "@webority/chat-react": "0.128.0",
48
- "@webority/ui-elements": "0.128.0",
49
- "@webority/ui-react": "0.128.0",
45
+ "@webority/canvas-kit": "0.129.0",
46
+ "@webority/ui-elements": "0.129.0",
47
+ "@webority/ui-react": "0.129.0",
50
48
  "bootstrap": "5.3.3",
51
49
  "jsdom": "30.1.1",
52
50
  "react": "^19.2.6",
@@ -57,7 +55,6 @@
57
55
  "vitest": "5.0.1"
58
56
  },
59
57
  "dependencies": {
60
- "@webority/markdown-core": "0.128.0",
61
58
  "html-to-image": "^1.11.13"
62
59
  },
63
60
  "scripts": {
@@ -1,39 +0,0 @@
1
- /**
2
- * A live chat with the support team in a drawer. An AI assistant answers first; the customer can ask
3
- * for a person, who joins the same conversation. Closing the drawer leaves the chat open.
4
- *
5
- * @param {object} props
6
- * @param {import('./chat/client.js').SupportChatClient} props.chatClient From `createSupportChatClient`.
7
- * @param {import('./chat/connection.js').SupportChatConnection} props.connection From `createSseChatConnection`.
8
- * @param {boolean} props.open
9
- * @param {() => void} props.onClose
10
- * @param {string} [props.appVersion] The product build, recorded on the chat.
11
- * @param {{ chatConversationReference?: string, openingLine?: string, wantsPerson?: boolean }} [props.start]
12
- * A hand-over: the conversation the customer comes from, their opening words, and whether they want a person now.
13
- * A new object sends it again.
14
- * @param {(ticket: { id: string, number: string }) => void} [props.onOpenTicket] Shows View ticket when a chat has ended with a ticket.
15
- * @param {(href: string) => string|null|undefined} [props.resolveLink] See `ChatMarkdown`.
16
- * @param {import('react').ElementType} [props.linkComponent] A router link (it receives `to`).
17
- * @param {string} [props.title="Chat with us"]
18
- * @param {string} [props.width="440px"]
19
- */
20
- export default function SupportChat({ chatClient, connection, open, onClose, appVersion, start, onOpenTicket, resolveLink, linkComponent, title, width, }: {
21
- chatClient: import('./chat/client.js').SupportChatClient;
22
- connection: import('./chat/connection.js').SupportChatConnection;
23
- open: boolean;
24
- onClose: () => void;
25
- appVersion?: string;
26
- start?: {
27
- chatConversationReference?: string;
28
- openingLine?: string;
29
- wantsPerson?: boolean;
30
- };
31
- onOpenTicket?: (ticket: {
32
- id: string;
33
- number: string;
34
- }) => void;
35
- resolveLink?: (href: string) => string | null | undefined;
36
- linkComponent?: import('react').ElementType;
37
- title?: string;
38
- width?: string;
39
- }): import("react").JSX.Element;
@@ -1,47 +0,0 @@
1
- export declare const meta: {
2
- readonly name: "SupportChat";
3
- readonly marker: null;
4
- readonly platforms: readonly ["web"];
5
- readonly acceptsChildren: false;
6
- readonly props: {
7
- readonly open: {
8
- readonly type: "boolean";
9
- readonly description: "Whether the chat drawer is open. Closing it leaves the chat open for the customer to return to.";
10
- };
11
- readonly title: {
12
- readonly type: "string";
13
- readonly default: "Chat with us";
14
- readonly description: "The drawer heading.";
15
- };
16
- readonly width: {
17
- readonly type: "string";
18
- readonly default: "440px";
19
- readonly description: "The drawer width; the full screen on a phone.";
20
- };
21
- readonly appVersion: {
22
- readonly type: "string";
23
- readonly description: "The product build, recorded on the chat.";
24
- };
25
- readonly start: {
26
- readonly type: "object";
27
- readonly description: "A hand-over into the chat: the conversation the customer comes from, their opening words, and whether they want a person now.";
28
- };
29
- };
30
- readonly examples: readonly [{
31
- readonly id: "SupportChat";
32
- readonly title: "Closed";
33
- readonly props: {
34
- readonly open: false;
35
- };
36
- }];
37
- readonly usage: {
38
- readonly when: readonly ["A portal offers live chat: an AI assistant answers first and the customer can ask for a person in the same conversation.", "The conversation is kept on the customer's support ticket."];
39
- readonly whenNot: readonly [{
40
- readonly text: "A one-way report or a long description of a problem.";
41
- readonly instead: "ReportIssue";
42
- }];
43
- readonly do: readonly [];
44
- readonly dont: readonly [];
45
- readonly a11y: readonly ["The chat opens as a dialog drawer, focuses the message box and closes on Escape.", "Status changes (waiting, joined, ended) are announced as polite status messages.", "A failed message says so and offers Try again and Discard."];
46
- };
47
- };
@@ -1,24 +0,0 @@
1
- /**
2
- * The floating pill that opens the support chat, pinned to a bottom corner. `compact` turns it into a
3
- * 48px icon-only circle in the shared floating stack, with the label as its tooltip and accessible name.
4
- *
5
- * @param {object} props
6
- * @param {() => void} props.onClick Opens the chat.
7
- * @param {boolean} [props.open=false]
8
- * @param {string} [props.label="Chat with us"]
9
- * @param {"end"|"start"} [props.position="end"]
10
- * @param {string} [props.icon="message-circle"]
11
- * @param {boolean} [props.compact=false]
12
- * @param {string} [props.className]
13
- * @param {import('react').CSSProperties} [props.style] Merged over the wrapper's own style.
14
- */
15
- export default function SupportChatLauncher({ onClick, open, label, position, icon, compact, className, style, }: {
16
- onClick: () => void;
17
- open?: boolean;
18
- label?: string;
19
- position?: "end" | "start";
20
- icon?: string;
21
- compact?: boolean;
22
- className?: string;
23
- style?: import('react').CSSProperties;
24
- }): import("react").JSX.Element;
@@ -1,51 +0,0 @@
1
- export declare const meta: {
2
- readonly name: "SupportChatLauncher";
3
- readonly marker: null;
4
- readonly platforms: readonly ["web"];
5
- readonly acceptsChildren: false;
6
- readonly props: {
7
- readonly open: {
8
- readonly type: "boolean";
9
- readonly default: false;
10
- readonly description: "Whether the chat is open. It is announced on the button.";
11
- };
12
- readonly label: {
13
- readonly type: "string";
14
- readonly default: "Chat with us";
15
- readonly description: "The button text; the accessible name and tooltip in compact mode.";
16
- };
17
- readonly position: {
18
- readonly type: "enum";
19
- readonly values: readonly ["end", "start"];
20
- readonly default: "end";
21
- readonly description: "The bottom corner the launcher sits in.";
22
- };
23
- readonly icon: {
24
- readonly type: "string";
25
- readonly default: "message-circle";
26
- readonly description: "A library icon name.";
27
- };
28
- readonly compact: {
29
- readonly type: "boolean";
30
- readonly default: false;
31
- readonly description: "Shows an icon-only circle stacked in the shared floating corner container, with the label as its tooltip.";
32
- };
33
- readonly className: {
34
- readonly type: "string";
35
- readonly description: "Added to the floating wrapper.";
36
- };
37
- };
38
- readonly omit: readonly ["style"];
39
- readonly examples: readonly [{
40
- readonly id: "SupportChatLauncher";
41
- readonly title: "Default";
42
- readonly props: {};
43
- }];
44
- readonly usage: {
45
- readonly when: readonly ["The floating pill that opens the support chat, pinned to a bottom corner."];
46
- readonly whenNot: readonly [];
47
- readonly do: readonly [];
48
- readonly dont: readonly [];
49
- readonly a11y: readonly ["The button announces that it opens a dialog (aria-haspopup) and whether it is open (aria-expanded).", "The default pill shows the label as its button text.", "The compact circle takes the label as its accessible name and as its tooltip."];
50
- };
51
- };
@@ -1,37 +0,0 @@
1
- export type SupportChatClient = {
2
- /**
3
- * Resolves to the customer's chat: a new one (201) or the open one (200). The client does not tell them apart.
4
- * Context keys sent when non-blank: pageUrl, userAgent, appVersion, chatConversationReference, openingLine.
5
- * wantsPerson is sent only when true.
6
- */
7
- start: (context: object) => Promise<import("./types.js").SupportChatView>;
8
- current: () => Promise<import("./types.js").SupportChatView>;
9
- get: (chatId: string) => Promise<import("./types.js").SupportChatView>;
10
- /**
11
- * The idempotency key is created once per composed message and reused on every retry.
12
- */
13
- send: (chatId: string, input: {
14
- body: string;
15
- files?: File[];
16
- idempotencyKey: string;
17
- }) => Promise<import("./types.js").SupportChatPosted>;
18
- /**
19
- * Resolves to the updated view.
20
- */
21
- requestAgent: (chatId: string) => Promise<import("./types.js").SupportChatView>;
22
- typing: (chatId: string) => Promise<void>;
23
- /**
24
- * Resolves to the updated view.
25
- */
26
- close: (chatId: string) => Promise<import("./types.js").SupportChatView>;
27
- };
28
- /**
29
- * Binds the support chat HTTP contract to the product's own authenticated client.
30
- *
31
- * @param {{ http: object, baseUrl?: string }} options
32
- * @returns {SupportChatClient}
33
- */
34
- export declare function createSupportChatClient({ http, baseUrl }: {
35
- http: object;
36
- baseUrl?: string;
37
- }): SupportChatClient;
@@ -1,24 +0,0 @@
1
- export declare const MAX_RECONNECT_ATTEMPTS = 10;
2
- export type SupportChatHandlers = {
3
- onSnapshot: (chat: import("./types.js").SupportChatSnapshotEvent) => void;
4
- onMessage: (event: import("./types.js").SupportChatMessageEvent) => void;
5
- onState: (event: import("./types.js").SupportChatStateEvent) => void;
6
- onTyping: (event: import("./types.js").SupportChatTypingEvent) => void;
7
- onDelta: (event: import("./types.js").SupportChatDeltaEvent) => void;
8
- onError: (event: import("./types.js").SupportChatErrorEvent) => void;
9
- };
10
- export type SupportChatConnection = {
11
- watch: (chatId: string, afterSequence: number | null, handlers: SupportChatHandlers) => () => void;
12
- };
13
- /**
14
- * The shipped connection: the support event stream over the app's signed-in HTTP client, resumed from the last sequence.
15
- *
16
- * @param {{ http: object, baseUrl?: string, retryDelaysMs?: number[], stallTimeoutMs?: number }} options
17
- * @returns {SupportChatConnection}
18
- */
19
- export declare function createSseChatConnection({ http, baseUrl, retryDelaysMs, stallTimeoutMs }: {
20
- http: object;
21
- baseUrl?: string;
22
- retryDelaysMs?: number[];
23
- stallTimeoutMs?: number;
24
- }): SupportChatConnection;
@@ -1,187 +0,0 @@
1
- /**
2
- * Wire shapes of the live support chat. Field names are the camelCase of the backend view records in
3
- * `Webority.Support/SupportChatViews.cs`; enums travel as their member names.
4
- */
5
- export type SupportMessageAuthorKind = "Customer" | "Agent" | "System" | "Assistant";
6
- export type SupportChatState = "Assistant" | "WaitingForAgent" | "WithAgent" | "Closed";
7
- export type SupportChatCloseReason = "CustomerEnded" | "AgentEnded" | "NoAgentAvailable" | "Idle";
8
- export type SupportChatMessageView = {
9
- id: string;
10
- sequence: number;
11
- authorKind: SupportMessageAuthorKind;
12
- authorName: string | null;
13
- body: string;
14
- attachments: {
15
- id: string;
16
- fileName: string;
17
- contentType: string;
18
- sizeBytes: number;
19
- kind: string;
20
- }[];
21
- createdDateTimeUtc: string;
22
- };
23
- export type SupportChatView = {
24
- id: string;
25
- state: SupportChatState;
26
- closeReason: SupportChatCloseReason | null;
27
- sequence: number;
28
- ticketId: string | null;
29
- ticketNumber: string | null;
30
- agentName: string | null;
31
- assistantAvailable: boolean;
32
- assistantAnswering: boolean;
33
- customerTypingUntilDateTimeUtc: string | null;
34
- agentTypingUntilDateTimeUtc: string | null;
35
- waitingSinceDateTimeUtc: string | null;
36
- waitingPosition: number | null;
37
- messages: SupportChatMessageView[];
38
- createdDateTimeUtc: string;
39
- };
40
- export type SupportChatPosted = {
41
- message: SupportChatMessageView;
42
- reply: SupportChatMessageView | null;
43
- /**
44
- * True when the idempotency key had already been used, so nothing new was stored.
45
- */
46
- replayed: boolean;
47
- };
48
- export type SupportChatQueueItem = {
49
- chatId: string;
50
- ticketId: string;
51
- ticketNumber: string;
52
- queue: string;
53
- reporterName: string;
54
- subject: string;
55
- state: SupportChatState;
56
- waitingSinceDateTimeUtc: string | null;
57
- sequence: number;
58
- };
59
- export type SupportChatSnapshotEvent = SupportChatView;
60
- export type SupportChatMessageEvent = {
61
- chatId: string;
62
- message: SupportChatMessageView;
63
- };
64
- export type SupportChatStateEvent = {
65
- chatId: string;
66
- state: SupportChatState;
67
- closeReason: SupportChatCloseReason | null;
68
- ticketId: string | null;
69
- ticketNumber: string | null;
70
- agentName: string | null;
71
- waitingPosition: number | null;
72
- };
73
- export type SupportChatTypingEvent = {
74
- chatId: string;
75
- who: "Customer" | "Agent" | "Assistant";
76
- untilDateTimeUtc: string;
77
- };
78
- export type SupportChatDeltaEvent = {
79
- chatId: string;
80
- text: string;
81
- };
82
- export type SupportChatQueueEvent = {
83
- waiting: SupportChatQueueItem[];
84
- mine: SupportChatQueueItem[];
85
- };
86
- export type SupportChatErrorEvent = {
87
- code: string;
88
- message: string;
89
- };
90
- /** @typedef {"Customer"|"Agent"|"System"|"Assistant"} SupportMessageAuthorKind */
91
- /** @typedef {"Assistant"|"WaitingForAgent"|"WithAgent"|"Closed"} SupportChatState */
92
- /** @typedef {"CustomerEnded"|"AgentEnded"|"NoAgentAvailable"|"Idle"} SupportChatCloseReason */
93
- /**
94
- * @typedef {object} SupportChatMessageView
95
- * @property {string} id
96
- * @property {number} sequence
97
- * @property {SupportMessageAuthorKind} authorKind
98
- * @property {string|null} authorName
99
- * @property {string} body
100
- * @property {{ id: string, fileName: string, contentType: string, sizeBytes: number, kind: string }[]} attachments
101
- * @property {string} createdDateTimeUtc
102
- */
103
- /**
104
- * @typedef {object} SupportChatView
105
- * @property {string} id
106
- * @property {SupportChatState} state
107
- * @property {SupportChatCloseReason|null} closeReason
108
- * @property {number} sequence
109
- * @property {string|null} ticketId
110
- * @property {string|null} ticketNumber
111
- * @property {string|null} agentName
112
- * @property {boolean} assistantAvailable
113
- * @property {boolean} assistantAnswering
114
- * @property {string|null} customerTypingUntilDateTimeUtc
115
- * @property {string|null} agentTypingUntilDateTimeUtc
116
- * @property {string|null} waitingSinceDateTimeUtc
117
- * @property {number|null} waitingPosition
118
- * @property {SupportChatMessageView[]} messages
119
- * @property {string} createdDateTimeUtc
120
- */
121
- /**
122
- * The answer to posting a message: the customer's line, and the assistant's reply when it answered at once.
123
- * @typedef {object} SupportChatPosted
124
- * @property {SupportChatMessageView} message
125
- * @property {SupportChatMessageView|null} reply
126
- * @property {boolean} replayed True when the idempotency key had already been used, so nothing new was stored.
127
- */
128
- /**
129
- * One row of the agent queue.
130
- * @typedef {object} SupportChatQueueItem
131
- * @property {string} chatId
132
- * @property {string} ticketId
133
- * @property {string} ticketNumber
134
- * @property {string} queue
135
- * @property {string} reporterName
136
- * @property {string} subject
137
- * @property {SupportChatState} state
138
- * @property {string|null} waitingSinceDateTimeUtc
139
- * @property {number} sequence
140
- */
141
- /**
142
- * The `snapshot` event: the whole chat, sent first when the client gives no cursor.
143
- * @typedef {SupportChatView} SupportChatSnapshotEvent
144
- */
145
- /**
146
- * The `message` event.
147
- * @typedef {object} SupportChatMessageEvent
148
- * @property {string} chatId
149
- * @property {SupportChatMessageView} message
150
- */
151
- /**
152
- * The `state` event.
153
- * @typedef {object} SupportChatStateEvent
154
- * @property {string} chatId
155
- * @property {SupportChatState} state
156
- * @property {SupportChatCloseReason|null} closeReason
157
- * @property {string|null} ticketId
158
- * @property {string|null} ticketNumber
159
- * @property {string|null} agentName
160
- * @property {number|null} waitingPosition
161
- */
162
- /**
163
- * The `typing` event.
164
- * @typedef {object} SupportChatTypingEvent
165
- * @property {string} chatId
166
- * @property {"Customer"|"Agent"|"Assistant"} who
167
- * @property {string} untilDateTimeUtc
168
- */
169
- /**
170
- * The `delta` event: assistant text to append while it is written. Never stored.
171
- * @typedef {object} SupportChatDeltaEvent
172
- * @property {string} chatId
173
- * @property {string} text
174
- */
175
- /**
176
- * The `queue` event, on the agent stream only: sent when either list changed.
177
- * @typedef {object} SupportChatQueueEvent
178
- * @property {SupportChatQueueItem[]} waiting
179
- * @property {SupportChatQueueItem[]} mine
180
- */
181
- /**
182
- * The `error` event. The server ends the stream after it; the client reconnects.
183
- * @typedef {object} SupportChatErrorEvent
184
- * @property {string} code
185
- * @property {string} message
186
- */
187
- export {};
@@ -1,33 +0,0 @@
1
- /**
2
- * The line above the transcript: who the customer is talking to, what the queue position is, and
3
- * how the chat ended, with the ticket it was kept on.
4
- *
5
- * @param {object} props
6
- * @param {"Assistant"|"WaitingForAgent"|"WithAgent"|"Closed"} props.state
7
- * @param {string|null} [props.closeReason]
8
- * @param {string|null} [props.agentName]
9
- * @param {string|null} [props.ticketNumber]
10
- * @param {string|null} [props.ticketId]
11
- * @param {number|null} [props.waitingPosition]
12
- * @param {boolean} [props.canRequestAgent]
13
- * @param {boolean} [props.requesting]
14
- * @param {() => void} props.onRequestAgent
15
- * @param {((ticket: { id: string, number: string }) => void)} [props.onOpenTicket]
16
- * @param {() => void} props.onRestart
17
- */
18
- export default function ChatStatusBar({ state, closeReason, agentName, ticketNumber, ticketId, waitingPosition, canRequestAgent, requesting, onRequestAgent, onOpenTicket, onRestart, }: {
19
- state: "Assistant" | "WaitingForAgent" | "WithAgent" | "Closed";
20
- closeReason?: string | null;
21
- agentName?: string | null;
22
- ticketNumber?: string | null;
23
- ticketId?: string | null;
24
- waitingPosition?: number | null;
25
- canRequestAgent?: boolean;
26
- requesting?: boolean;
27
- onRequestAgent: () => void;
28
- onOpenTicket?: ((ticket: {
29
- id: string;
30
- number: string;
31
- }) => void);
32
- onRestart: () => void;
33
- }): import("react").JSX.Element;
@@ -1,33 +0,0 @@
1
- /**
2
- * The support chat's conversation, oldest line first: customer, assistant, support team and system
3
- * lines, the customer's messages still sending or failed, and the assistant's answer as it streams.
4
- *
5
- * @param {object} props
6
- * @param {object[]} props.messages
7
- * @param {{ localId: string, body: string, status: "sending"|"failed", error: string }[]} props.pending
8
- * @param {string} props.assistantText
9
- * @param {boolean} props.assistantWriting
10
- * @param {string|null} [props.agentName]
11
- * @param {boolean} props.agentTyping
12
- * @param {(localId: string) => void} props.onRetry
13
- * @param {(localId: string) => void} props.onDiscard
14
- * @param {(href: string) => string|null|undefined} [props.resolveLink]
15
- * @param {import('react').ElementType} [props.linkComponent]
16
- */
17
- export default function ChatTranscript({ messages, pending, assistantText, assistantWriting, agentName, agentTyping, onRetry, onDiscard, resolveLink, linkComponent, }: {
18
- messages: object[];
19
- pending: {
20
- localId: string;
21
- body: string;
22
- status: "sending" | "failed";
23
- error: string;
24
- }[];
25
- assistantText: string;
26
- assistantWriting: boolean;
27
- agentName?: string | null;
28
- agentTyping: boolean;
29
- onRetry: (localId: string) => void;
30
- onDiscard: (localId: string) => void;
31
- resolveLink?: (href: string) => string | null | undefined;
32
- linkComponent?: import('react').ElementType;
33
- }): import("react").JSX.Element;
@@ -1,10 +0,0 @@
1
- /**
2
- * The notice while a customer waits for a person: where they stand in the queue, when the queue
3
- * position is known.
4
- *
5
- * @param {object} props
6
- * @param {number|null} props.position Chats ahead of this one, or null when unknown.
7
- */
8
- export default function WaitingNotice({ position }: {
9
- position: number | null;
10
- }): import("react").JSX.Element;
@@ -1,42 +0,0 @@
1
- /**
2
- * The state of one support chat while its drawer is open: the start, the live event stream, the
3
- * customer's messages that are still sending, and the actions on the chat.
4
- *
5
- * @param {object} options
6
- * @param {import('../../chat/client.js').SupportChatClient} options.chatClient
7
- * @param {import('../../chat/connection.js').SupportChatConnection} options.connection
8
- * @param {boolean} options.open
9
- * @param {string} [options.appVersion]
10
- * @param {{ chatConversationReference?: string, openingLine?: string, wantsPerson?: boolean }} [options.start]
11
- * Sent with the start call. Pass a new object to send a fresh start, for example a hand-over from another assistant.
12
- */
13
- export declare function useSupportChatSession({ chatClient, connection, open, appVersion, start }: {
14
- chatClient: import('../../chat/client.js').SupportChatClient;
15
- connection: import('../../chat/connection.js').SupportChatConnection;
16
- open: boolean;
17
- appVersion?: string;
18
- start?: {
19
- chatConversationReference?: string;
20
- openingLine?: string;
21
- wantsPerson?: boolean;
22
- };
23
- }): {
24
- phase: string;
25
- startError: string;
26
- chat: null;
27
- messages: never[];
28
- pending: never[];
29
- assistantText: string;
30
- agentTypingUntil: null;
31
- assistantTypingUntil: null;
32
- notice: string;
33
- requesting: boolean;
34
- send: (body: any, files?: any[]) => Promise<boolean>;
35
- retry: (localId: any) => void;
36
- discard: (localId: any) => void;
37
- requestAgent: () => Promise<void>;
38
- end: () => Promise<void>;
39
- restart: () => void;
40
- retryStart: () => void;
41
- notifyTyping: () => void;
42
- };