@armdesk/connect-sdk 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,5 @@
1
1
  import { getCurrentClient, onCurrentClient } from "./defaults.js";
2
+ import { isView } from "./protocol.js";
2
3
  import { setSafeHtml } from "./sanitize.js";
3
4
  import { themeCss } from "./theme.js";
4
5
  function h(tag, attrs = {}, ...kids) {
@@ -36,12 +37,8 @@ label{display:block;margin:0 0 10px}
36
37
  .agent{border-left:3px solid var(--ad-primary)}
37
38
  .body a{color:var(--ad-primary)}.body pre{white-space:pre-wrap;overflow:auto}
38
39
  .bar{display:flex;gap:8px;justify-content:space-between;align-items:center}
39
- .fab{position:fixed;bottom:20px;z-index:2147483000}
40
- .fab.right{right:20px}.fab.left{left:20px}
41
- .panel{position:fixed;bottom:76px;width:min(400px,calc(100vw - 24px));height:min(640px,calc(100vh - 100px));background:var(--ad-bg);border:1px solid var(--ad-border);border-radius:var(--ad-radius);overflow:hidden;z-index:2147483000;box-shadow:0 8px 30px rgba(0,0,0,.25)}
42
- .panel.right{right:20px}.panel.left{left:20px}
43
40
  `;
44
- export const ELEMENT_TAGS = ["armdesk-tickets", "armdesk-new-ticket", "armdesk-ticket", "armdesk-launcher"];
41
+ export const ELEMENT_TAGS = ["armdesk-tickets", "armdesk-new-ticket", "armdesk-ticket", "armdesk-launcher", "armdesk-messenger"];
45
42
  function readTheme(attr) {
46
43
  if (!attr)
47
44
  return undefined;
@@ -53,7 +50,7 @@ function readTheme(attr) {
53
50
  return undefined;
54
51
  }
55
52
  }
56
- /** Registers the four custom elements (idempotent; a no-op without a browser). */
53
+ /** Registers the custom elements (idempotent; a no-op without a browser). */
57
54
  export function defineElements() {
58
55
  if (typeof customElements === "undefined" || typeof HTMLElement === "undefined")
59
56
  return;
@@ -93,7 +90,7 @@ export function defineElements() {
93
90
  this.bound = null;
94
91
  this.teardown();
95
92
  }
96
- attributeChangedCallback() {
93
+ attributeChangedCallback(_name) {
97
94
  if (!this.isConnected || !this.root)
98
95
  return;
99
96
  this.paintTheme();
@@ -263,36 +260,99 @@ export function defineElements() {
263
260
  this.box.replaceChildren(h("div", { class: "bar" }, h("h3", {}, `${t.number} ${t.subject}`), h("span", { class: "badge" }, t.status.replace(/_/g, " "))), ...threads, ...[t.canReply ? form : null, close].filter((n) => n !== null));
264
261
  }
265
262
  }
266
- class ArmLauncher extends ArmBase {
263
+ /**
264
+ * `<armdesk-messenger position="bottom-left" view="home" open label icon-url offset>`: the messenger bubble + panel.
265
+ * The `open` attribute is two-way (set it to open, it is set while open). Events: `armdesk-messenger-open`,
266
+ * `armdesk-messenger-close`, `armdesk-messenger-unread` (detail: the count).
267
+ */
268
+ class ArmMessenger extends ArmBase {
267
269
  constructor() {
268
270
  super(...arguments);
269
- this.handle = null;
270
- this.open = false;
271
+ this.ctl = null;
272
+ }
273
+ static get observedAttributes() {
274
+ return [...ArmBase.observedAttributes, "open", "icon-url", "offset", "aria-label"];
275
+ }
276
+ defaultView() {
277
+ return "home";
278
+ }
279
+ /** The controller (null until a client is available). */
280
+ get controller() {
281
+ return this.ctl;
282
+ }
283
+ open(view) {
284
+ var _a;
285
+ (_a = this.ctl) === null || _a === void 0 ? void 0 : _a.open(view);
286
+ }
287
+ close() {
288
+ var _a;
289
+ (_a = this.ctl) === null || _a === void 0 ? void 0 : _a.close();
290
+ }
291
+ toggle() {
292
+ var _a;
293
+ (_a = this.ctl) === null || _a === void 0 ? void 0 : _a.toggle();
294
+ }
295
+ attributeChangedCallback(name) {
296
+ var _a, _b;
297
+ if (!this.isConnected || !this.root)
298
+ return;
299
+ if (name === "open") {
300
+ if (this.hasAttribute("open"))
301
+ (_a = this.ctl) === null || _a === void 0 ? void 0 : _a.open();
302
+ else
303
+ (_b = this.ctl) === null || _b === void 0 ? void 0 : _b.close();
304
+ return;
305
+ }
306
+ if (name === "view" && this.ctl) {
307
+ const v = this.getAttribute("view");
308
+ if (isView(v))
309
+ this.ctl.navigate(v);
310
+ return;
311
+ }
312
+ super.attributeChangedCallback(name);
271
313
  }
272
314
  teardown() {
273
315
  var _a;
274
- (_a = this.handle) === null || _a === void 0 ? void 0 : _a.destroy();
275
- this.handle = null;
316
+ (_a = this.ctl) === null || _a === void 0 ? void 0 : _a.destroy();
317
+ this.ctl = null;
276
318
  }
277
319
  async load() {
278
- const side = this.getAttribute("position") === "left" ? "left" : "right";
279
- const panel = h("div", { class: `panel ${side}`, role: "dialog", "aria-label": this.getAttribute("label") || "Support", hidden: true });
280
- const btn = h("button", {
281
- class: `btn fab ${side}`,
282
- "aria-expanded": "false",
283
- onclick: () => {
284
- this.open = !this.open;
285
- panel.hidden = !this.open;
286
- btn.setAttribute("aria-expanded", String(this.open));
287
- const c = this.c;
288
- if (this.open && !this.handle && c) {
289
- const view = (this.getAttribute("view") || "tickets");
290
- this.handle = c.mount(panel, { view, theme: readTheme(this.getAttribute("theme")), height: 640 });
291
- }
292
- },
293
- }, this.getAttribute("label") || "Support");
320
+ const c = this.c;
321
+ if (!c)
322
+ return;
294
323
  this.teardown();
295
- this.box.replaceChildren(btn, panel);
324
+ this.box.replaceChildren();
325
+ const view = this.getAttribute("view");
326
+ const offset = Number(this.getAttribute("offset"));
327
+ const ctl = c.messenger({
328
+ container: this.box,
329
+ position: this.getAttribute("position") === "left" || this.getAttribute("position") === "bottom-left" ? "bottom-left" : "bottom-right",
330
+ label: this.getAttribute("label") || undefined,
331
+ ariaLabel: this.getAttribute("aria-label") || undefined,
332
+ iconUrl: this.getAttribute("icon-url") || undefined,
333
+ offset: this.hasAttribute("offset") && Number.isFinite(offset) ? offset : undefined,
334
+ view: isView(view) ? view : this.defaultView(),
335
+ theme: readTheme(this.getAttribute("theme")),
336
+ open: this.hasAttribute("open"),
337
+ });
338
+ ctl.on("open", (d) => {
339
+ if (!this.hasAttribute("open"))
340
+ this.setAttribute("open", "");
341
+ this.emit("armdesk-messenger-open", d);
342
+ });
343
+ ctl.on("close", () => {
344
+ if (this.hasAttribute("open"))
345
+ this.removeAttribute("open");
346
+ this.emit("armdesk-messenger-close", null);
347
+ });
348
+ ctl.on("unread", (n) => this.emit("armdesk-messenger-unread", n));
349
+ this.ctl = ctl;
350
+ }
351
+ }
352
+ /** 1.0's launcher, now the messenger (it still opens at `tickets` unless `view` says otherwise). */
353
+ class ArmLauncher extends ArmMessenger {
354
+ defaultView() {
355
+ return "tickets";
296
356
  }
297
357
  }
298
358
  const defs = [
@@ -300,6 +360,7 @@ export function defineElements() {
300
360
  ["armdesk-new-ticket", ArmNewTicket],
301
361
  ["armdesk-ticket", ArmTicket],
302
362
  ["armdesk-launcher", ArmLauncher],
363
+ ["armdesk-messenger", ArmMessenger],
303
364
  ];
304
365
  for (const [name, ctor] of defs)
305
366
  if (!customElements.get(name))
@@ -1,18 +1,30 @@
1
- import { createClient, init } from "./client.js";
1
+ import { createClient, init, type ArmDeskClient } from "./client.js";
2
2
  import { mount } from "./mount.js";
3
- import type { ConnectHandle, MountOptions } from "./types.js";
4
- export declare const VERSION = "1.0.0";
3
+ import type { ClientOptions, ConnectHandle, MessengerController, MessengerOptions, MountOptions } from "./types.js";
4
+ export declare const VERSION = "1.1.0";
5
+ /**
6
+ * `ArmDeskConnect.messenger(...)`: the messenger bubble.
7
+ * - `messenger({ orgKey, auth, ...messengerOptions })` signs in (like init) and shows it;
8
+ * - `messenger(messengerOptions)` uses the client from the last `init()`.
9
+ */
10
+ export type MessengerInit = MessengerOptions & Partial<Pick<ClientOptions, "orgKey" | "auth" | "desk" | "apiBase">> & {
11
+ client?: ArmDeskClient;
12
+ };
13
+ export declare function messenger(options?: MessengerInit): MessengerController;
5
14
  /** The IIFE's global: `ArmDeskConnect.init({ orgKey, auth })`. `mount(el, { getToken })` still works (deprecated). */
6
15
  export declare const ArmDeskConnect: {
7
16
  version: string;
8
17
  init: typeof init;
9
18
  createClient: typeof createClient;
19
+ messenger: typeof messenger;
10
20
  /** @deprecated Use `init({ orgKey, auth })` and `client.mount(el)`. */
11
21
  mount: (container: HTMLElement | string, options: MountOptions) => ConnectHandle;
12
22
  };
13
23
  export { init, createClient, mount };
24
+ export { createMessenger } from "./messenger.js";
14
25
  export type { ArmDeskClient } from "./client.js";
15
26
  export { ArmDeskError, type ArmDeskErrorCode } from "./errors.js";
16
27
  export { sanitizeHtml } from "./sanitize.js";
17
28
  export { themeCss, themeVars } from "./theme.js";
29
+ export { VIEW_PATTERN, isView } from "./protocol.js";
18
30
  export type * from "./types.js";
package/dist/esm/index.js CHANGED
@@ -1,15 +1,30 @@
1
1
  import { createClient, init } from "./client.js";
2
+ import { getCurrentClient } from "./defaults.js";
3
+ import { ArmDeskError } from "./errors.js";
2
4
  import { mount } from "./mount.js";
3
- export const VERSION = "1.0.0";
5
+ export const VERSION = "1.1.0";
6
+ export function messenger(options = {}) {
7
+ const { client: given, orgKey, auth, desk, apiBase, ...rest } = options;
8
+ let client = given !== null && given !== void 0 ? given : null;
9
+ if (!client && orgKey && auth)
10
+ client = init({ orgKey, auth, desk, apiBase, theme: rest.theme, features: rest.features, locale: rest.locale });
11
+ client !== null && client !== void 0 ? client : (client = getCurrentClient());
12
+ if (!client)
13
+ throw new ArmDeskError("config", "ArmDeskConnect.messenger: call init({ orgKey, auth }) first, or pass orgKey and auth");
14
+ return client.messenger(rest);
15
+ }
4
16
  /** The IIFE's global: `ArmDeskConnect.init({ orgKey, auth })`. `mount(el, { getToken })` still works (deprecated). */
5
17
  export const ArmDeskConnect = {
6
18
  version: VERSION,
7
19
  init,
8
20
  createClient,
21
+ messenger,
9
22
  /** @deprecated Use `init({ orgKey, auth })` and `client.mount(el)`. */
10
23
  mount: (container, options) => mount(container, options),
11
24
  };
12
25
  export { init, createClient, mount };
26
+ export { createMessenger } from "./messenger.js";
13
27
  export { ArmDeskError } from "./errors.js";
14
28
  export { sanitizeHtml } from "./sanitize.js";
15
29
  export { themeCss, themeVars } from "./theme.js";
30
+ export { VIEW_PATTERN, isView } from "./protocol.js";
@@ -0,0 +1,8 @@
1
+ import type { ClientMountOptions, ConnectHandle, ConnectTheme, MessengerController, MessengerOptions } from "./types.js";
2
+ export interface MessengerDeps {
3
+ mount: (el: HTMLElement, options: ClientMountOptions) => ConnectHandle;
4
+ /** The organisation's theme (colours the bubble). Optional; errors are ignored. */
5
+ loadTheme?: () => Promise<ConnectTheme | undefined>;
6
+ }
7
+ /** Creates the bubble + panel. Use `client.messenger(options)` (or `ArmDeskConnect.messenger(...)`). */
8
+ export declare function createMessenger(deps: MessengerDeps, options?: MessengerOptions): MessengerController;
@@ -0,0 +1,269 @@
1
+ import { isView } from "./protocol.js";
2
+ import { themeCss } from "./theme.js";
3
+ const PANEL_W = 380;
4
+ const PANEL_H = 640;
5
+ const BUBBLE = 56;
6
+ const GAP = 16;
7
+ const MOBILE = 480;
8
+ const CSS = `
9
+ *{box-sizing:border-box}
10
+ .bubble{position:fixed;display:inline-flex;align-items:center;justify-content:center;gap:8px;min-width:${BUBBLE}px;height:${BUBBLE}px;padding:0 16px;border:0;border-radius:999px;background:var(--ad-primary);color:#fff;font:600 15px/1 var(--ad-font);cursor:pointer;box-shadow:0 6px 20px rgba(0,0,0,.22);transition:transform .2s ease,box-shadow .2s ease}
11
+ .bubble.round{width:${BUBBLE}px;padding:0}
12
+ .bubble:hover{transform:scale(1.05);box-shadow:0 8px 26px rgba(0,0,0,.28)}
13
+ .bubble:focus-visible{outline:3px solid var(--ad-primary);outline-offset:3px}
14
+ .bubble svg{width:26px;height:26px;fill:none;stroke:currentColor;stroke-width:2;stroke-linecap:round;stroke-linejoin:round}
15
+ .bubble img{width:28px;height:28px;object-fit:contain}
16
+ .ico{display:inline-flex;transition:transform .2s ease,opacity .2s ease}
17
+ .x{position:absolute;opacity:0;transform:rotate(-90deg)}
18
+ .is-open .ico.main{opacity:0;transform:rotate(90deg)}
19
+ .is-open .x{opacity:1;transform:none}
20
+ .is-open .lbl{display:none}
21
+ .is-open.bubble{width:${BUBBLE}px;padding:0}
22
+ .badge{position:absolute;top:-4px;right:-4px;min-width:20px;height:20px;padding:0 6px;border-radius:999px;background:#dc2626;color:#fff;font:700 11px/20px var(--ad-font);text-align:center;border:2px solid #fff}
23
+ .badge[hidden],.is-open .badge{display:none}
24
+ .panel{position:fixed;width:${PANEL_W}px;height:${PANEL_H}px;max-height:calc(100vh - var(--ad-y) - ${BUBBLE + GAP * 2}px);background:var(--ad-bg);border:1px solid var(--ad-border);border-radius:16px;overflow:hidden;box-shadow:0 12px 48px rgba(0,0,0,.24);visibility:hidden;opacity:0;transform:translateY(12px) scale(.98);pointer-events:none;transition:opacity .2s ease,transform .2s ease,visibility 0s linear .2s}
25
+ .panel.open{visibility:visible;opacity:1;transform:none;pointer-events:auto;transition-delay:0s}
26
+ .right .panel{transform-origin:bottom right}.left .panel{transform-origin:bottom left}
27
+ .panel iframe{width:100%;height:100% !important;border:0;display:block}
28
+ @media (max-width:${MOBILE}px){.panel{inset:0 !important;width:100%;height:100%;max-height:none;border:0;border-radius:0}.wrap.is-open .bubble{display:none}}
29
+ @media (prefers-reduced-motion:reduce){.bubble,.panel,.ico{transition:none !important}.bubble:hover{transform:none}}
30
+ `;
31
+ const SVG_NS = "http://www.w3.org/2000/svg";
32
+ function icon(paths) {
33
+ const svg = document.createElementNS(SVG_NS, "svg");
34
+ svg.setAttribute("viewBox", "0 0 24 24");
35
+ svg.setAttribute("aria-hidden", "true");
36
+ for (const d of paths) {
37
+ const p = document.createElementNS(SVG_NS, "path");
38
+ p.setAttribute("d", d);
39
+ svg.appendChild(p);
40
+ }
41
+ return svg;
42
+ }
43
+ const CHAT = ["M21 12a8 8 0 0 1-11.6 7.1L4 20.5l1.4-4.9A8 8 0 1 1 21 12z"];
44
+ const CLOSE = ["M6 6l12 12", "M18 6L6 18"];
45
+ function span(cls, ...kids) {
46
+ const s = document.createElement("span");
47
+ s.className = cls;
48
+ s.append(...kids);
49
+ return s;
50
+ }
51
+ const isHttpsUrl = (u) => {
52
+ if (typeof u !== "string")
53
+ return false;
54
+ try {
55
+ return new URL(u).protocol === "https:";
56
+ }
57
+ catch (_a) {
58
+ return false;
59
+ }
60
+ };
61
+ let seq = 0;
62
+ /** Creates the bubble + panel. Use `client.messenger(options)` (or `ArmDeskConnect.messenger(...)`). */
63
+ export function createMessenger(deps, options = {}) {
64
+ var _a, _b, _c, _d, _e, _f, _g;
65
+ if (typeof document === "undefined")
66
+ throw new Error("ArmDeskConnect: the messenger needs a browser");
67
+ if (options.view !== undefined && !isView(options.view))
68
+ throw new Error("ArmDeskConnect: invalid view");
69
+ const side = options.position === "bottom-left" || options.position === "left" ? "left" : "right";
70
+ const off = typeof options.offset === "number" ? { x: options.offset, y: options.offset } : (_a = options.offset) !== null && _a !== void 0 ? _a : {};
71
+ const x = Math.max(0, Math.round((_b = off.x) !== null && _b !== void 0 ? _b : 20));
72
+ const y = Math.max(0, Math.round((_c = off.y) !== null && _c !== void 0 ? _c : 20));
73
+ const z = Number.isFinite(options.zIndex) ? Math.round(options.zIndex) : 2147483000;
74
+ const name = options.ariaLabel || options.label || "Support";
75
+ const panelId = `armdesk-messenger-${++seq}`;
76
+ let theme = { ...((_d = options.theme) !== null && _d !== void 0 ? _d : {}) };
77
+ let opened = false;
78
+ let unread = 0;
79
+ let destroyed = false;
80
+ let handle = null;
81
+ let view = (_e = options.view) !== null && _e !== void 0 ? _e : "home";
82
+ const listeners = new Map();
83
+ const emit = (event, payload) => {
84
+ var _a;
85
+ (_a = listeners.get(event)) === null || _a === void 0 ? void 0 : _a.forEach((cb) => {
86
+ try {
87
+ cb(payload);
88
+ }
89
+ catch (_a) {
90
+ // a throwing host listener must not break the messenger
91
+ }
92
+ });
93
+ };
94
+ // ---- DOM -------------------------------------------------------------------
95
+ const host = document.createElement("div");
96
+ host.setAttribute("data-armdesk-messenger", "");
97
+ const root = host.attachShadow({ mode: "open" });
98
+ const style = document.createElement("style");
99
+ const wrap = document.createElement("div");
100
+ wrap.className = `wrap ${side}`;
101
+ wrap.setAttribute("part", "messenger");
102
+ const bubble = document.createElement("button");
103
+ bubble.type = "button";
104
+ bubble.className = `bubble${options.label ? "" : " round"}`;
105
+ bubble.setAttribute("part", "bubble");
106
+ bubble.setAttribute("aria-controls", panelId);
107
+ bubble.setAttribute("aria-expanded", "false");
108
+ bubble.setAttribute("aria-haspopup", "dialog");
109
+ let main = icon(CHAT);
110
+ if (isHttpsUrl(options.iconUrl)) {
111
+ const img = document.createElement("img");
112
+ img.src = options.iconUrl;
113
+ img.alt = "";
114
+ main = img;
115
+ }
116
+ const badge = span("badge");
117
+ badge.hidden = true;
118
+ badge.setAttribute("aria-hidden", "true");
119
+ bubble.append(span("ico main", main), span("ico x", icon(CLOSE)), ...(options.label ? [span("lbl", document.createTextNode(options.label))] : []), badge);
120
+ bubble.style.cssText = `${side}:${x}px;bottom:${y}px;z-index:${z}`;
121
+ const panel = document.createElement("div");
122
+ panel.id = panelId;
123
+ panel.className = "panel";
124
+ panel.setAttribute("part", "panel");
125
+ panel.setAttribute("role", "dialog");
126
+ panel.setAttribute("aria-label", name);
127
+ panel.setAttribute("aria-hidden", "true");
128
+ panel.style.cssText = `${side}:${x}px;bottom:${y + BUBBLE + GAP}px;z-index:${z}`;
129
+ wrap.append(panel, bubble);
130
+ root.append(style, wrap);
131
+ const paint = () => {
132
+ style.textContent = `${themeCss(theme)}:host{display:contents;--ad-y:${y}px}${CSS}`;
133
+ };
134
+ const label = () => {
135
+ const base = opened ? `Close ${name}` : `Open ${name}`;
136
+ bubble.setAttribute("aria-label", unread > 0 && !opened ? `${base}, ${unread} unread` : base);
137
+ };
138
+ paint();
139
+ label();
140
+ // ---- the iframe --------------------------------------------------------------
141
+ const ensureFrame = () => {
142
+ if (handle || destroyed)
143
+ return;
144
+ handle = deps.mount(panel, {
145
+ view,
146
+ theme: options.theme,
147
+ features: options.features,
148
+ locale: options.locale,
149
+ height: PANEL_H,
150
+ host: "messenger",
151
+ title: name,
152
+ onEvent: options.onEvent,
153
+ onError: options.onError,
154
+ onUnread: (n) => setUnread(n),
155
+ onClose: () => close(),
156
+ });
157
+ };
158
+ const setUnread = (n) => {
159
+ if (n === unread)
160
+ return;
161
+ unread = n;
162
+ badge.textContent = n > 99 ? "99+" : String(n);
163
+ badge.hidden = n <= 0;
164
+ label();
165
+ emit("unread", n);
166
+ };
167
+ // ---- open / close ------------------------------------------------------------
168
+ const onKey = (e) => {
169
+ if (e.key === "Escape" && opened) {
170
+ e.stopPropagation();
171
+ close();
172
+ }
173
+ };
174
+ function open(next) {
175
+ if (destroyed)
176
+ return;
177
+ if (next !== undefined && !isView(next))
178
+ throw new Error("ArmDeskConnect: invalid view");
179
+ if (next)
180
+ view = next;
181
+ ensureFrame();
182
+ if (opened) {
183
+ if (next)
184
+ handle === null || handle === void 0 ? void 0 : handle.open(next);
185
+ return;
186
+ }
187
+ opened = true;
188
+ panel.classList.add("open");
189
+ wrap.classList.add("is-open");
190
+ bubble.classList.add("is-open");
191
+ panel.setAttribute("aria-hidden", "false");
192
+ bubble.setAttribute("aria-expanded", "true");
193
+ label();
194
+ handle === null || handle === void 0 ? void 0 : handle.open(next);
195
+ document.addEventListener("keydown", onKey, true);
196
+ // focus moves into the panel (the frame) so keyboard users land in the conversation
197
+ const frame = panel.querySelector("iframe");
198
+ setTimeout(() => opened && (frame === null || frame === void 0 ? void 0 : frame.focus()), 0);
199
+ emit("open", { view: next !== null && next !== void 0 ? next : null });
200
+ }
201
+ function close() {
202
+ if (destroyed || !opened)
203
+ return;
204
+ const focusInPanel = root.activeElement !== null && panel.contains(root.activeElement);
205
+ opened = false;
206
+ panel.classList.remove("open");
207
+ wrap.classList.remove("is-open");
208
+ bubble.classList.remove("is-open");
209
+ panel.setAttribute("aria-hidden", "true");
210
+ bubble.setAttribute("aria-expanded", "false");
211
+ label();
212
+ document.removeEventListener("keydown", onKey, true);
213
+ // focus returns to the bubble when it was inside the panel (WAI-ARIA dialog pattern)
214
+ if (focusInPanel)
215
+ bubble.focus();
216
+ emit("close", undefined);
217
+ }
218
+ bubble.addEventListener("click", () => (opened ? close() : open()));
219
+ panel.addEventListener("keydown", onKey);
220
+ ((_f = options.container) !== null && _f !== void 0 ? _f : document.body).appendChild(host);
221
+ if (!options.lazy)
222
+ ensureFrame();
223
+ if (deps.loadTheme && !((_g = options.theme) === null || _g === void 0 ? void 0 : _g.primaryColor)) {
224
+ deps.loadTheme().then((org) => {
225
+ var _a;
226
+ if (destroyed || !org)
227
+ return;
228
+ theme = { ...org, ...((_a = options.theme) !== null && _a !== void 0 ? _a : {}) };
229
+ paint();
230
+ }, () => undefined);
231
+ }
232
+ if (options.open)
233
+ open();
234
+ return {
235
+ open,
236
+ close,
237
+ toggle: () => (opened ? close() : open()),
238
+ navigate(next) {
239
+ if (!isView(next))
240
+ throw new Error("ArmDeskConnect: invalid view");
241
+ view = next;
242
+ handle === null || handle === void 0 ? void 0 : handle.navigate(next);
243
+ },
244
+ setTheme(next) {
245
+ theme = { ...next };
246
+ paint();
247
+ handle === null || handle === void 0 ? void 0 : handle.setTheme(next);
248
+ },
249
+ isOpen: () => opened,
250
+ unread: () => unread,
251
+ on(event, cb) {
252
+ let set = listeners.get(event);
253
+ if (!set)
254
+ listeners.set(event, (set = new Set()));
255
+ set.add(cb);
256
+ return () => set.delete(cb);
257
+ },
258
+ destroy() {
259
+ if (destroyed)
260
+ return;
261
+ document.removeEventListener("keydown", onKey, true);
262
+ handle === null || handle === void 0 ? void 0 : handle.destroy();
263
+ handle = null;
264
+ destroyed = true;
265
+ listeners.clear();
266
+ host.remove();
267
+ },
268
+ };
269
+ }
package/dist/esm/mount.js CHANGED
@@ -1,4 +1,4 @@
1
- import { deskOrigin, isProtocolMessage, LOCALES, MAX_TOKEN_LENGTH, PROTOCOL_SOURCE, VIEW_PATTERN } from "./protocol.js";
1
+ import { deskOrigin, isProtocolMessage, LOCALES, MAX_TOKEN_LENGTH, PROTOCOL_SOURCE, readUnread, VIEW_PATTERN } from "./protocol.js";
2
2
  const READY_TIMEOUT_MS = 20000;
3
3
  const TOKEN_ATTEMPTS = 4;
4
4
  const TOKEN_BACKOFF_MS = 400;
@@ -32,12 +32,15 @@ export function mount(container, options) {
32
32
  let ready = false;
33
33
  let destroyed = false;
34
34
  let tokenInFlight = null;
35
+ let initSent = false;
36
+ /** An `open` asked for before init went out: sent right after it. */
37
+ let pendingOpen = null;
35
38
  const params = new URLSearchParams({ org: options.orgKey, view });
36
39
  if (options.locale && LOCALES.includes(options.locale))
37
40
  params.set("locale", options.locale);
38
41
  const frame = document.createElement("iframe");
39
42
  frame.src = `${origin}/embed/itsm?${params.toString()}`;
40
- frame.title = "Support tickets";
43
+ frame.title = options.title || "Support tickets";
41
44
  frame.setAttribute("referrerpolicy", "strict-origin");
42
45
  frame.setAttribute("loading", "lazy");
43
46
  frame.setAttribute("data-armdesk-connect", "");
@@ -49,6 +52,14 @@ export function mount(container, options) {
49
52
  return;
50
53
  win.postMessage({ source: PROTOCOL_SOURCE, type, payload }, origin);
51
54
  };
55
+ const safe = (fn) => {
56
+ try {
57
+ fn();
58
+ }
59
+ catch (_a) {
60
+ // host callback errors stay the host's
61
+ }
62
+ };
52
63
  const fail = (code, message) => {
53
64
  var _a;
54
65
  try {
@@ -89,7 +100,19 @@ export function mount(container, options) {
89
100
  const token = await fetchToken();
90
101
  if (!token || destroyed)
91
102
  return;
92
- post(type, type === "init" ? { token, theme, features: (_a = options.features) !== null && _a !== void 0 ? _a : {} } : { token });
103
+ if (type === "token") {
104
+ post("token", { token });
105
+ return;
106
+ }
107
+ const init = { token, theme, features: (_a = options.features) !== null && _a !== void 0 ? _a : {} };
108
+ if (options.host)
109
+ init.host = options.host;
110
+ post("init", init);
111
+ initSent = true;
112
+ if (pendingOpen) {
113
+ post("open", pendingOpen);
114
+ pendingOpen = null;
115
+ }
93
116
  };
94
117
  let readyTimer = setTimeout(() => {
95
118
  if (!ready)
@@ -134,6 +157,15 @@ export function mount(container, options) {
134
157
  }
135
158
  }
136
159
  break;
160
+ case "unread": {
161
+ const n = readUnread(payload);
162
+ if (n !== null)
163
+ safe(() => { var _a; return (_a = options.onUnread) === null || _a === void 0 ? void 0 : _a.call(options, n); });
164
+ break;
165
+ }
166
+ case "close":
167
+ safe(() => { var _a; return (_a = options.onClose) === null || _a === void 0 ? void 0 : _a.call(options); });
168
+ break;
137
169
  case "error":
138
170
  fail(typeof body.code === "string" ? body.code : "error", typeof body.message === "string" ? body.message : "Embed error");
139
171
  break;
@@ -151,6 +183,17 @@ export function mount(container, options) {
151
183
  if (ready)
152
184
  post("navigate", { view });
153
185
  },
186
+ open(next) {
187
+ if (next !== undefined && !VIEW_PATTERN.test(next))
188
+ throw new Error("ArmDeskConnect: invalid view");
189
+ if (next)
190
+ view = next;
191
+ const payload = next ? { view: next } : {};
192
+ if (initSent)
193
+ post("open", payload);
194
+ else
195
+ pendingOpen = payload;
196
+ },
154
197
  setTheme(next) {
155
198
  theme = { ...next };
156
199
  if (ready)
@@ -1,14 +1,33 @@
1
1
  /** The embed protocol shared by the SDK and the embed page (apps/web components/connect-embed). */
2
2
  export declare const PROTOCOL_SOURCE = "armdesk-connect";
3
+ /**
4
+ * Views the embed understands. 1.0: `tickets`, `new`, `ticket:<id>`. 1.1 (messenger): `home`, `messages`, `help`,
5
+ * `chat:<conversationId>`, `article:<id>`. Ids are 1-64 URL-safe characters.
6
+ */
3
7
  export declare const VIEW_PATTERN: RegExp;
4
8
  export declare const LOCALES: readonly ["en", "es", "ar"];
5
9
  export declare const MAX_TOKEN_LENGTH = 8192;
10
+ /** Highest unread count the host accepts from the frame (anything above shows as "99+"). */
11
+ export declare const MAX_UNREAD = 9999;
12
+ /**
13
+ * Message types.
14
+ * host -> frame: `init {token, theme, features, host?}`, `token {token}`, `navigate {view}`, `theme {theme}`,
15
+ * `open {view?}` (the messenger panel became visible; optionally switch view).
16
+ * frame -> host: `ready`, `request-token`, `resize {height}`, `event {name, data}`, `error {code, message}`,
17
+ * `unread {count}` (launcher badge), `close` (the user closed the messenger from inside the frame).
18
+ */
19
+ export declare const HOST_MESSAGES: readonly ["init", "token", "navigate", "theme", "open"];
20
+ export declare const FRAME_MESSAGES: readonly ["ready", "request-token", "resize", "event", "error", "unread", "close"];
6
21
  export interface ProtocolMessage {
7
22
  source: typeof PROTOCOL_SOURCE;
8
23
  type: string;
9
24
  payload?: unknown;
10
25
  }
11
26
  export declare function isProtocolMessage(data: unknown): data is ProtocolMessage;
27
+ /** True for a view string the embed accepts. */
28
+ export declare function isView(v: unknown): boolean;
29
+ /** A sane unread count from an untrusted payload: an integer in 0..MAX_UNREAD, else null. */
30
+ export declare function readUnread(payload: unknown): number | null;
12
31
  /** The origin of a desk URL: https, or http for localhost only. Throws for anything else. */
13
32
  export declare function deskOrigin(baseUrl: string): string;
14
33
  /** Sent by the library to a server-mode session route; a custom header a cross-site form cannot add. */