@cognitiv-traits/traitos-ui 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Adapter from the Telnyx WebRTC client to the controller's adapter interface. You pass the `TelnyxRTC` class in, so this
3
+ * package does not bundle or depend on it:
4
+ *
5
+ * import { TelnyxRTC } from '@telnyx/webrtc';
6
+ * const adapter = telnyxAdapter(TelnyxRTC, { remoteElement: audioEl });
7
+ */
8
+ export function telnyxAdapter(TelnyxRTC, { remoteElement } = {}) {
9
+ let rtc = null;
10
+ const handlers = { ready: [], error: [], close: [], call: [] };
11
+ const emit = (name, arg) => handlers[name].forEach((fn) => fn(arg));
12
+
13
+ const wrap = (call) => ({
14
+ direction: call.direction,
15
+ state: call.state,
16
+ remoteCallerName: call.remoteCallerName,
17
+ remoteCallerNumber: call.remoteCallerNumber,
18
+ answer: () => call.answer(),
19
+ hangup: () => call.hangup(),
20
+ mute: (on) => (on ? call.muteAudio() : call.unmuteAudio()),
21
+ hold: (on) => (on ? call.hold() : call.unhold()),
22
+ dtmf: (digit) => call.dtmf(digit),
23
+ });
24
+
25
+ return {
26
+ on(name, fn) { handlers[name]?.push(fn); },
27
+ async connect({ token }) {
28
+ rtc = new TelnyxRTC({ login_token: token });
29
+ if (remoteElement) rtc.remoteElement = remoteElement;
30
+ rtc.on('telnyx.ready', () => emit('ready'));
31
+ rtc.on('telnyx.error', (e) => emit('error', e instanceof Error ? e : new Error(e?.message || 'Telnyx error')));
32
+ rtc.on('telnyx.socket.close', () => emit('close'));
33
+ rtc.on('telnyx.notification', (n) => { if (n?.type === 'callUpdate' && n.call) emit('call', wrap(n.call)); });
34
+ rtc.connect();
35
+ },
36
+ async disconnect() { rtc?.disconnect(); rtc = null; },
37
+ };
38
+ }
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Keeps a browser token fresh. Your page never holds the API key: it asks YOUR server for a token (which calls
3
+ * `client.auth.createBrowserToken` with the key) and this renews it before it expires.
4
+ *
5
+ * const tokens = new TokenManager(client, () => fetch('/my-backend/traitos-token').then((r) => r.json()));
6
+ * await tokens.start();
7
+ *
8
+ * The provider may return the token string, or `{ token, expiresIn }` as `createBrowserToken` does.
9
+ */
10
+ export class TokenManager {
11
+ /**
12
+ * @param {{setToken: (t: string) => void}} client
13
+ * @param {() => Promise<string | {token: string, expiresIn?: number, expiresAt?: string}>} provider
14
+ * @param {{refreshAt?: number, minDelayMs?: number, retryMs?: number, onError?: (e: Error) => void, now?: () => number, timers?: {set: Function, clear: Function}}} [options]
15
+ * `refreshAt` is the fraction of the lifetime after which to renew (default 0.8)
16
+ */
17
+ constructor(client, provider, { refreshAt = 0.8, minDelayMs = 5000, retryMs = 5000, onError, now = Date.now, timers } = {}) {
18
+ this.client = client;
19
+ this.provider = provider;
20
+ this.refreshAt = refreshAt;
21
+ this.minDelayMs = minDelayMs;
22
+ this.retryMs = retryMs;
23
+ this.onError = onError;
24
+ this.now = now;
25
+ this.timers = timers ?? { set: (fn, ms) => setTimeout(fn, ms), clear: (t) => clearTimeout(t) };
26
+ this._timer = null;
27
+ this._stopped = false;
28
+ this.expiresAt = null;
29
+ }
30
+
31
+ /** Fetch the first token (rejects if it fails: do not show the UI without one), then keep renewing. */
32
+ async start() {
33
+ this._stopped = false;
34
+ await this.refresh();
35
+ }
36
+
37
+ async refresh() {
38
+ const out = await this.provider();
39
+ const token = typeof out === 'string' ? out : out?.token;
40
+ if (!token) throw new Error('The token provider did not return a token.');
41
+ this.client.setToken(token);
42
+ const ttlMs = typeof out === 'object' && out
43
+ ? (Number.isFinite(out.expiresIn) ? out.expiresIn * 1000 : out.expiresAt ? Date.parse(out.expiresAt) - this.now() : null)
44
+ : null;
45
+ this.expiresAt = ttlMs ? this.now() + ttlMs : null;
46
+ if (ttlMs && !this._stopped) this._schedule(Math.max(this.minDelayMs, ttlMs * this.refreshAt));
47
+ return token;
48
+ }
49
+
50
+ _schedule(ms) {
51
+ if (this._timer) this.timers.clear(this._timer);
52
+ this._timer = this.timers.set(async () => {
53
+ this._timer = null;
54
+ if (this._stopped) return;
55
+ try { await this.refresh(); } catch (error) {
56
+ this.onError?.(error);
57
+ if (!this._stopped) this._schedule(this.retryMs);
58
+ }
59
+ }, ms);
60
+ }
61
+
62
+ stop() {
63
+ this._stopped = true;
64
+ if (this._timer) this.timers.clear(this._timer);
65
+ this._timer = null;
66
+ }
67
+ }
@@ -0,0 +1,53 @@
1
+ /** Pure logic for the dialer widget: where it sits, when it opens and closes, which way its panel opens. No DOM. */
2
+ export const CORNERS = Object.freeze(['bottom-right', 'bottom-left', 'top-right', 'top-left']);
3
+
4
+ /**
5
+ * `inline` embeds the panel open in the page; `position="bottom-right"` (etc.) pins a floating bubble to a corner;
6
+ * neither is a header icon whose panel opens below it. An unknown position falls back to a header icon.
7
+ */
8
+ export function placementOf({ position, inline } = {}) {
9
+ if (inline) return { mode: 'inline', corner: null };
10
+ if (position && CORNERS.includes(position)) return { mode: 'floating', corner: position };
11
+ return { mode: 'header', corner: null };
12
+ }
13
+
14
+ /**
15
+ * Which side the panel opens toward, from the icon's box and the viewport, so it never opens off-screen.
16
+ * @param {{left: number, right: number, top: number, bottom: number}} rect the icon
17
+ * @param {{width: number, height: number}} viewport
18
+ * @param {{width?: number, height?: number}} [panel]
19
+ * @returns {{h: 'left'|'right', v: 'up'|'down'}} `h: 'left'` lines the panel's left edge up with the icon's (it extends right); `'right'` lines up the right edges
20
+ */
21
+ export function panelSide(rect, viewport, panel = {}) {
22
+ const w = panel.width ?? 300, h = panel.height ?? 460;
23
+ const roomRight = viewport.width - rect.left; // panel hangs to the right of the icon's left edge
24
+ const roomLeft = rect.right; // panel hangs to the left of the icon's right edge
25
+ const horizontal = roomRight >= w || roomRight >= roomLeft ? 'left' : 'right';
26
+ const below = viewport.height - rect.bottom, above = rect.top;
27
+ const vertical = below >= h || below >= above ? 'down' : 'up';
28
+ return { h: horizontal, v: vertical };
29
+ }
30
+
31
+ /** Open/close state with the rules the widget needs. `inline` is always open. */
32
+ export function createOpenState({ inline = false, onChange } = {}) {
33
+ let open = inline;
34
+ const set = (v) => { const next = inline ? true : Boolean(v); if (next === open) return false; open = next; onChange?.(open); return true; };
35
+ return {
36
+ get open() { return open; },
37
+ openIt: () => set(true),
38
+ close: () => set(false),
39
+ toggle: () => set(!open),
40
+ setInline(v) { inline = Boolean(v); if (inline && !open) { open = true; onChange?.(true); } },
41
+ /** Escape closes (and the caller returns focus to the icon). Returns true when it did. */
42
+ onKey(key) { return key === 'Escape' && open && !inline ? set(false) : false; },
43
+ /** A pointer press: closes unless it landed inside the widget (`path` is `event.composedPath()`). */
44
+ onOutside(path, host) { return open && !inline && !path.includes(host) ? set(false) : false; },
45
+ };
46
+ }
47
+
48
+ /** The icon's accessible name: includes the call state and missed count so a screen reader hears it without opening the panel. */
49
+ export function iconLabel(S, { status, missed, open }) {
50
+ const base = open ? S.closePhone : S.openPhone;
51
+ const extra = status === 'ringing' ? S.ringing : status === 'in-call' ? S.inCall : missed > 0 ? S.missedBadge.replace('{n}', String(missed)) : '';
52
+ return extra ? `${base} — ${extra}` : base;
53
+ }
@@ -0,0 +1,74 @@
1
+ import { baseCss } from '../theme.js';
2
+
3
+ const Base = typeof HTMLElement !== 'undefined' ? HTMLElement : class {};
4
+
5
+ /**
6
+ * Shared shell for the elements: a shadow root, coalesced re-rendering that keeps the focused input and caret, and events that
7
+ * cross the shadow boundary. Subclasses provide `render()` (a SafeHtml), optional `css`, and `onClick/onInput/onChange`.
8
+ */
9
+ export class TraitElement extends Base {
10
+ constructor() {
11
+ super();
12
+ this._painted = false;
13
+ this._queued = false;
14
+ if (this.attachShadow) {
15
+ this.attachShadow({ mode: 'open' });
16
+ this.shadowRoot.addEventListener('click', (e) => {
17
+ if (this._held) { this._held = false; return; }
18
+ const t = e.target.closest?.('[data-action]');
19
+ if (t && !t.disabled) this.onClick?.(t.dataset.action, t, e);
20
+ });
21
+ this.shadowRoot.addEventListener('input', (e) => { if (e.target.dataset?.key) this.onInput?.(e.target, e); });
22
+ this.shadowRoot.addEventListener('change', (e) => { if (e.target.dataset?.key) this.onChange?.(e.target, e); });
23
+ this.shadowRoot.addEventListener('keydown', (e) => this.onKey?.(e));
24
+ // Long-press: an element with data-hold fires onHold after 500ms, and the click that follows is swallowed.
25
+ let holdTimer = null;
26
+ const stopHold = () => { clearTimeout(holdTimer); holdTimer = null; };
27
+ this.shadowRoot.addEventListener('pointerdown', (e) => {
28
+ const t = e.target.closest?.('[data-hold]');
29
+ if (!t) return;
30
+ stopHold();
31
+ this._held = false;
32
+ holdTimer = setTimeout(() => { holdTimer = null; this._held = true; this.onHold?.(t.dataset.hold, t); }, 500);
33
+ });
34
+ for (const ev of ['pointerup', 'pointerleave', 'pointercancel']) this.shadowRoot.addEventListener(ev, stopHold);
35
+ this.shadowRoot.addEventListener('submit', (e) => { e.preventDefault(); const f = e.target.dataset?.submit; if (f) this.onClick?.(f, e.target, e); });
36
+ }
37
+ }
38
+
39
+ connectedCallback() { this._connected = true; this.mounted?.(); this.requestRender(); }
40
+ disconnectedCallback() { this._connected = false; this.unmounted?.(); }
41
+
42
+ /** Repaint on the next microtask, however many times it is asked for. */
43
+ requestRender() {
44
+ if (this._queued || !this.shadowRoot) return;
45
+ this._queued = true;
46
+ queueMicrotask(() => { this._queued = false; if (this._connected !== false) this.paint(); });
47
+ }
48
+
49
+ paint() {
50
+ const root = this.shadowRoot;
51
+ const active = root.activeElement;
52
+ const key = active?.dataset?.key;
53
+ const focusId = !key && active?.id ? active.id : null;
54
+ const caret = active && 'selectionStart' in active ? [active.selectionStart, active.selectionEnd] : null;
55
+ root.innerHTML = `<style>${baseCss}${this.css ?? ''}</style>${this.render()}`;
56
+ if (key) {
57
+ const el = root.querySelector(`[data-key="${CSS.escape(key)}"]`);
58
+ if (el) { el.focus(); if (caret && el.setSelectionRange) { try { el.setSelectionRange(caret[0], caret[1]); } catch { /* not a text field */ } } }
59
+ }
60
+ else if (focusId) root.getElementById?.(focusId)?.focus();
61
+ this._painted = true;
62
+ }
63
+
64
+ /** A bubbling, composed event, so the host page can listen on the element or above it. */
65
+ emit(name, detail, { cancelable = false } = {}) {
66
+ // Returns false when a listener called preventDefault() on a cancelable event.
67
+ return this.dispatchEvent(new CustomEvent(name, { detail, bubbles: true, composed: true, cancelable }));
68
+ }
69
+ }
70
+
71
+ /** Register an element once; safe in Node and when the tag already exists. */
72
+ export function define(tag, ctor) {
73
+ if (typeof customElements !== 'undefined' && !customElements.get(tag)) customElements.define(tag, ctor);
74
+ }
@@ -0,0 +1,139 @@
1
+ import { html, raw } from '../html.js';
2
+ import { define } from './base.js';
3
+ import { PhoneBase } from './phoneBase.js';
4
+ import { renderKeypad } from './keypad.js';
5
+ import { renderSoundOptions } from './soundOptions.js';
6
+ import { renderCallControls, renderRecentCalls, renderLastCall } from './softphone.js';
7
+ import { stringsFor, t } from '../core/strings.js';
8
+ import { placementOf, panelSide, createOpenState, iconLabel } from '../core/widgetState.js';
9
+ import { keypadCss } from '../theme.js';
10
+
11
+ const ICON = '<svg viewBox="0 0 24 24" width="22" height="22" aria-hidden="true" focusable="false"><path fill="currentColor" d="M6.6 10.8a15 15 0 0 0 6.6 6.6l2.2-2.2a1 1 0 0 1 1-.25 11.4 11.4 0 0 0 3.6.57 1 1 0 0 1 1 1V20a1 1 0 0 1-1 1A17 17 0 0 1 3 4a1 1 0 0 1 1-1h3.5a1 1 0 0 1 1 1c0 1.25.2 2.45.57 3.6a1 1 0 0 1-.25 1z"/></svg>';
12
+
13
+ const css = keypadCss + `
14
+ :host { display: inline-block; position: relative; }
15
+ :host([inline]) { display: block; }
16
+ :host([position]) { position: fixed; z-index: var(--traitos-z, 2147483000); }
17
+ :host([position="bottom-right"]) { right: max(16px, env(safe-area-inset-right)); bottom: max(16px, env(safe-area-inset-bottom)); }
18
+ :host([position="bottom-left"]) { left: max(16px, env(safe-area-inset-left)); bottom: max(16px, env(safe-area-inset-bottom)); }
19
+ :host([position="top-right"]) { right: max(16px, env(safe-area-inset-right)); top: max(16px, env(safe-area-inset-top)); }
20
+ :host([position="top-left"]) { left: max(16px, env(safe-area-inset-left)); top: max(16px, env(safe-area-inset-top)); }
21
+ .fab { position: relative; width: 44px; height: 44px; min-width: 44px; padding: 0; border-radius: 50%; display: inline-flex; align-items: center; justify-content: center; background: var(--_bg); color: inherit; border: 1px solid var(--_line); }
22
+ :host([position]) .fab { width: 56px; height: 56px; background: var(--_accent); border-color: var(--_accent); color: #fff; box-shadow: 0 4px 14px rgba(0,0,0,.25); }
23
+ .fab.ringing, .fab.in-call { background: var(--_accent); border-color: var(--_accent); color: #fff; }
24
+ .fab.ringing { animation: ring 1s infinite; } .fab.in-call { box-shadow: 0 0 0 3px color-mix(in srgb, var(--_ok) 55%, transparent); }
25
+ .badge { position: absolute; top: -4px; right: -4px; min-width: 18px; height: 18px; padding: 0 5px; border-radius: 9px; background: var(--_bad); color: #fff; font-size: 11px; line-height: 18px; text-align: center; font-weight: 700; }
26
+ .panel, .mini { position: absolute; z-index: 1; width: min(320px, calc(100vw - 16px)); max-height: calc(100vh - 80px); overflow: auto; background: var(--_bg); border: 1px solid var(--_line); border-radius: var(--_r); padding: 14px; box-shadow: 0 10px 30px rgba(0,0,0,.22); }
27
+ .panel[data-v="down"], .mini[data-v="down"] { top: calc(100% + 8px); } .panel[data-v="up"], .mini[data-v="up"] { bottom: calc(100% + 8px); }
28
+ .panel[data-h="left"], .mini[data-h="left"] { left: 0; } .panel[data-h="right"], .mini[data-h="right"] { right: 0; }
29
+ .panel.inline { position: static; width: 100%; max-height: none; box-shadow: none; } .mini { width: min(300px, calc(100vw - 16px)); }
30
+ .snd { margin-top: 10px; } .snd-panel { display: grid; gap: 4px; margin-top: 6px; } .snd-check { display: flex; align-items: center; gap: 6px; margin: 4px 0; } .snd-toggle { width: 100%; text-align: left; } .snd input[type=range] { padding: 0; }
31
+ .panel h2 { margin-bottom: 6px; } .panel .hint:empty { display: none; }
32
+ @keyframes ring { 0%,100% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--_accent) 60%, transparent); } 50% { box-shadow: 0 0 0 9px transparent; } }
33
+ `;
34
+
35
+ const SIDE = { inline: { h: 'left', v: 'down' } };
36
+
37
+ /** Pure view of the widget. */
38
+ export function renderWidget(s, { S = stringsFor(), dp, open = false, inline = false, side = { h: 'left', v: 'down' }, calls = [], missed = 0, now = Date.now(), canHold = false, canDtmf = false, keypadOpen = false, hasController = false, sound, soundOpen = false, voices = [] } = {}) {
39
+ const active = s.status === 'ringing' || s.status === 'in-call';
40
+ const label = iconLabel(S, { status: s.status, missed, open });
41
+ const live = s.status === 'ringing' ? `${S.ringing}: ${s.caller ?? ''}` : s.status === 'in-call' ? S.inCall : '';
42
+ const callBody = s.status === 'ringing'
43
+ ? html`<div class="who">${s.caller}</div><div class="hint">${S.isCalling}</div><div class="btns"><button class="ok" data-action="answer">${S.answer}</button><button class="danger" data-action="hangup">${S.decline}</button></div>`
44
+ : html`${renderCallControls(s, { S, now, canHold, canDtmf, keypadOpen })}${keypadOpen && dp ? renderKeypad(dp, { S, mode: 'dtmf' }) : ''}`;
45
+ const idle = !hasController || s.status === 'ready';
46
+ const body = active ? callBody : html`
47
+ ${s.error ? html`<p class="err" role="alert">${s.error}</p>` : ''}
48
+ ${s.warning ? html`<p class="status bad" role="status">${s.warning}</p>` : ''}
49
+ ${hasController && (s.status === 'off' || s.status === 'error') ? html`<div class="btns"><button class="primary" data-action="start">${s.status === 'error' ? S.tryAgain : S.goOnline}</button></div><p class="hint">${S.goOnlineHint}</p>` : ''}
50
+ ${hasController && s.status === 'connecting' ? html`<p class="hint" role="status">${S.connecting}</p>` : ''}
51
+ ${hasController && s.status === 'ready' ? renderLastCall(s, S) : ''}
52
+ ${s.placing ? html`<p class="status" role="status">${t(S, 'placing', { number: s.placing.number })}</p>` : ''}
53
+ ${idle && dp ? renderKeypad(dp, { S, busy: s.dialing }) : ''}
54
+ ${hasController && s.status === 'ready' ? html`<h3>${S.recent}</h3>${renderRecentCalls(calls, S)}` : ''}
55
+ ${sound && idle ? renderSoundOptions(sound, S, { open: soundOpen, voices, idPrefix: 'w-snd' }) : ''}`;
56
+ const panel = html`<div class="panel ${inline ? 'inline' : ''}" id="panel" role="dialog" aria-modal="false" aria-label="${S.dialogLabel}" data-h="${side.h}" data-v="${side.v}">${body}</div>`;
57
+ const mini = html`<div class="mini" role="region" aria-label="${S.dialogLabel}" data-h="${side.h}" data-v="${side.v}">${callBody}</div>`;
58
+ return html`<div class="w">
59
+ ${inline ? '' : html`<button type="button" class="fab ${s.status}" id="fab" data-action="toggle" aria-haspopup="dialog" aria-expanded="${String(Boolean(open))}" aria-controls="panel" aria-label="${label}"><slot name="icon">${raw(ICON)}</slot>${missed > 0 && !active ? html`<span class="badge" aria-hidden="true">${missed > 9 ? '9+' : missed}</span>` : ''}</button>`}
60
+ ${open || inline ? panel : active ? mini : ''}
61
+ <div class="sr" role="status" aria-live="polite">${live}</div>
62
+ </div>`.toString();
63
+ }
64
+
65
+ /**
66
+ * `<traitos-dialer-widget>` — a call icon with a dialer popover, for a header bar, a floating bubble or an embedded panel.
67
+ *
68
+ * <traitos-dialer-widget> an icon in a header bar; the panel opens below it
69
+ * <traitos-dialer-widget position="bottom-right"> a floating bubble pinned to a corner
70
+ * <traitos-dialer-widget inline> the panel, always open, inside the page
71
+ * <span slot="icon" class="material-icons">call</span> (optional) your own icon, as a child
72
+ *
73
+ * Set `client` and `adapter` like <traitos-softphone>. Without an adapter it is a plain dialer that only fires `traitos-call`.
74
+ * Methods: open(), close(), toggle(), dial(number, channel). Properties: isOpen, caps, strings, whatsapp, numbers.
75
+ * Events: `traitos-call` ({number, channel}, cancelable), `traitos-state`, `traitos-error`, `traitos-toggle` ({open}).
76
+ * Closes on Escape (focus returns to the icon) and on a click outside; it never blocks the page behind it.
77
+ */
78
+ export class TraitOSDialerWidget extends PhoneBase {
79
+ static get observedAttributes() { return [...super.observedAttributes, 'open']; }
80
+ constructor() {
81
+ super();
82
+ this.pop = createOpenState({ onChange: (o) => this._opened(o) });
83
+ }
84
+ get css() { return css; }
85
+ get isOpen() { return this.pop.open; }
86
+ open() { return this.pop.openIt(); }
87
+ close() { const r = this.pop.close(); return r; }
88
+ toggle() { return this.pop.toggle(); }
89
+
90
+ mounted() {
91
+ super.mounted();
92
+ this.pop.setInline(this.hasAttribute('inline'));
93
+ if (this.hasAttribute('open')) this.pop.openIt();
94
+ this._onDocPointer = (e) => this.pop.onOutside(e.composedPath(), this);
95
+ this._onDocKey = (e) => { if (this.pop.onKey(e.key)) this._focusIcon(); };
96
+ document.addEventListener('pointerdown', this._onDocPointer, true);
97
+ document.addEventListener('keydown', this._onDocKey);
98
+ }
99
+ unmounted() {
100
+ document.removeEventListener('pointerdown', this._onDocPointer, true);
101
+ document.removeEventListener('keydown', this._onDocKey);
102
+ super.unmounted();
103
+ }
104
+ attributeChangedCallback(name) {
105
+ if (name === 'inline') this.pop.setInline(this.hasAttribute('inline'));
106
+ if (name === 'open') this.hasAttribute('open') ? this.pop.openIt() : this.pop.close();
107
+ this.requestRender();
108
+ }
109
+
110
+ _opened(open) {
111
+ if (open) this.log?.markSeen();
112
+ this.emit('traitos-toggle', { open });
113
+ this.requestRender();
114
+ if (open && !this.hasAttribute('inline')) setTimeout(() => this.shadowRoot?.getElementById('kp-number')?.focus(), 0);
115
+ }
116
+ _focusIcon() { setTimeout(() => this.shadowRoot?.getElementById('fab')?.focus(), 0); }
117
+
118
+ _side() {
119
+ const place = placementOf({ position: this.getAttribute('position'), inline: this.hasAttribute('inline') });
120
+ if (place.mode === 'floating') return { h: place.corner.endsWith('right') ? 'right' : 'left', v: place.corner.startsWith('bottom') ? 'up' : 'down' };
121
+ if (place.mode === 'inline') return SIDE.inline;
122
+ const r = this.getBoundingClientRect?.();
123
+ return r ? panelSide(r, { width: window.innerWidth, height: window.innerHeight }) : SIDE.inline;
124
+ }
125
+
126
+ render() {
127
+ const c = this.controller;
128
+ const S = this.S;
129
+ const s = c?.snapshot() ?? { status: 'off', recent: [], error: null };
130
+ return renderWidget(s, { S, dp: this.dp, open: this.pop.open, inline: this.hasAttribute('inline'), side: this._side(), calls: this.recentCalls(), missed: this.log?.missedCount() ?? 0, now: Date.now(), canHold: !!c?.canHold, canDtmf: !!c?.canDtmf, keypadOpen: this.keypadOpen, hasController: !!c, sound: this.sound, soundOpen: this._sndOpen, voices: this.sound.voices() });
131
+ }
132
+
133
+ onClick(action, node) {
134
+ if (action === 'toggle') { this.pop.toggle(); return; }
135
+ this.phoneClick(action, node);
136
+ }
137
+ }
138
+
139
+ define('traitos-dialer-widget', TraitOSDialerWidget);
@@ -0,0 +1,158 @@
1
+ import { html, raw } from '../html.js';
2
+ import { TraitElement, define } from './base.js';
3
+ import { FlowBuilderController } from '../core/flowBuilderController.js';
4
+ import { TARGET_TYPES, TARGET_LABEL, DAYS, setGreeting, setMenu, setSpam, setHours, addRoute, removeRoute, setRoute, toggleDay, describeFlow, DIGITS } from '../core/flowModel.js';
5
+
6
+ const css = `
7
+ .grid { display: grid; grid-template-columns: minmax(0, 3fr) minmax(0, 2fr); gap: 16px; } @media (max-width: 760px) { .grid { grid-template-columns: 1fr; } }
8
+ .route { border: 1px solid var(--_line); border-radius: calc(var(--_r) - 4px); padding: 8px 10px; margin: 8px 0; } .digit { font-weight: 700; font-size: 18px; width: 2ch; }
9
+ .toolbar { display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 10px; } .linkish { background: none; border: 0; color: var(--_accent); padding: 2px 4px; }
10
+ .map { list-style: none; margin: 0; padding: 0; } .map > li { border-left: 3px solid var(--_accent); padding: 4px 10px; margin: 0 0 8px 6px; background: color-mix(in srgb, var(--_accent) 5%, transparent); }
11
+ .map ul { margin: 4px 0 0; padding-left: 16px; } .days label { display: inline-block; margin: 0 8px 0 0; font-weight: 400; }
12
+ `;
13
+
14
+ const err = (errors, path) => (errors[path] ? html`<p class="err" role="alert">${errors[path]}</p>` : '');
15
+ const bad = (errors, path) => raw(errors[path] ? 'aria-invalid="true"' : '');
16
+ const opts = (list, value, blank) => html`${blank ? html`<option value="">${blank}</option>` : ''}${list.map((x) => html`<option value="${x.id}" ${x.id === value ? 'selected' : ''}>${x.name}</option>`)}`;
17
+
18
+ function renderRoute(d, r, e, lookup) {
19
+ const k = `routes.${d}`;
20
+ const target = r.targetType === 'agent' ? html`<select aria-label="AI agent" data-key="${k}.agent" data-d="${d}" data-f="targetAgentId" ${bad(e, `${k}.target`)}>${opts(lookup.agents, r.targetAgentId, 'Choose an agent')}</select>`
21
+ : r.targetType === 'team_member' ? html`<select aria-label="Team member" data-key="${k}.member" data-d="${d}" data-f="teamMemberId" ${bad(e, `${k}.target`)}>${opts(lookup.team, r.teamMemberId, 'Choose a person')}</select>`
22
+ : r.targetType === 'department' ? html`<div role="group" aria-label="People in this department">${lookup.team.map((m) => html`<label style="font-weight:400"><input type="checkbox" data-action="dept-toggle" data-d="${d}" data-id="${m.id}" ${(r.departmentTargets ?? []).includes(m.id) ? 'checked' : ''} />${m.name}</label>`)}</div>`
23
+ : html`<input aria-label="Phone number" type="tel" data-key="${k}.number" data-d="${d}" data-f="externalNumber" value="${r.externalNumber ?? ''}" placeholder="+18765550100" ${bad(e, `${k}.target`)} />`;
24
+ return html`<div class="route"><div class="row">
25
+ <div class="fixed digit" aria-label="Press ${d}">${d}</div>
26
+ <div><label for="l-${d}">Name</label><input id="l-${d}" data-key="${k}.label" data-d="${d}" data-f="label" value="${r.label}" placeholder="Sales" ${bad(e, `${k}.label`)} />${err(e, `${k}.label`)}</div>
27
+ <div><label for="t-${d}">Who answers</label><select id="t-${d}" data-key="${k}.type" data-d="${d}" data-f="targetType">${TARGET_TYPES.map((t) => html`<option value="${t}" ${t === r.targetType ? 'selected' : ''}>${TARGET_LABEL[t]}</option>`)}</select></div>
28
+ <div class="fixed"><button type="button" class="linkish" data-action="route-remove" data-d="${d}" aria-label="Remove choice ${d}">Remove</button></div>
29
+ </div><div style="margin-top:6px">${target}${err(e, `${k}.target`)}</div></div>`;
30
+ }
31
+
32
+ function renderMap(flow, lookup) {
33
+ const m = describeFlow(flow, lookup);
34
+ return html`<ol class="map" aria-label="How a call flows">${m.steps.map((s) => html`<li><b>${s.kind === 'caller' ? '☎' : s.kind === 'hours' ? '🕘' : s.kind === 'greeting' ? '💬' : '🔢'}</b> ${s.text}</li>`)}
35
+ <li>Caller presses a number<ul>${m.routes.length ? m.routes.map((r) => html`<li><b>${r.digit}</b> ${r.label} → ${r.target}</li>`) : html`<li>No choices yet</li>`}${m.fallback ? html`<li>No answer → ${m.fallback}</li>` : ''}</ul></li></ol>`;
36
+ }
37
+
38
+ /** Pure view of the builder. */
39
+ export function renderFlowBuilder(s, lookup = { agents: [], team: [] }, { prompt = '' } = {}) {
40
+ if (s.status === 'loading' || s.status === 'idle') return html`<div class="card"><p class="hint" role="status">Loading…</p></div>`.toString();
41
+ if (s.status === 'error') return html`<div class="card"><p class="err" role="alert">${s.message}</p><button data-action="reload">Try again</button></div>`.toString();
42
+ const f = s.flow, e = s.localErrors, h = f.hours;
43
+ const sim = s.simulation;
44
+ return html`<div class="card">
45
+ <div class="toolbar" role="toolbar" aria-label="Flow actions">
46
+ <button data-action="undo" ${s.canUndo ? '' : 'disabled'}>Undo</button><button data-action="redo" ${s.canRedo ? '' : 'disabled'}>Redo</button>
47
+ <button data-action="check" ${s.busy ? 'disabled' : ''}>Check with server</button><button data-action="simulate" ${s.busy ? 'disabled' : ''}>Try a call</button>
48
+ <button class="primary" data-action="save" ${!s.dirty || s.busy ? 'disabled' : ''}>${s.busy ? 'Working…' : 'Save'}</button>
49
+ </div>
50
+ ${s.message ? html`<p class="status ${s.message.startsWith('Saved') ? 'ok' : 'bad'}" role="status">${s.message}</p>` : ''}
51
+ ${s.serverCheck ? html`<p class="status ${s.serverCheck.valid ? 'ok' : 'bad'}" role="status">${s.serverCheck.valid ? 'The server accepts this flow.' : `The server found a problem: ${s.serverCheck.error ?? 'invalid flow'}`}</p>` : ''}
52
+ <div class="grid"><div>
53
+ <label for="draft">Describe it in words</label><div class="row"><input id="draft" data-key="draft" value="${prompt}" placeholder="Press 1 for sales, 2 for support; closed on Sundays" /><button class="fixed" data-action="generate" ${s.busy ? 'disabled' : ''}>Draft it</button></div>
54
+ <label for="greeting">Greeting</label><textarea id="greeting" rows="2" data-key="greeting" data-f="greeting" ${bad(e, 'greeting')}>${f.greeting}</textarea>${err(e, 'greeting')}
55
+ <label for="prompt">Menu prompt</label><textarea id="prompt" rows="2" data-key="menu.prompt" data-f="menu.prompt" ${bad(e, 'menu.prompt')}>${f.menu.prompt}</textarea>${err(e, 'menu.prompt')}
56
+ <div class="row"><div><label for="timeout">Wait for a key (seconds)</label><input id="timeout" type="number" min="1" max="30" data-key="menu.timeoutSec" data-f="menu.timeoutSec" value="${f.menu.timeoutSec}" ${bad(e, 'menu.timeoutSec')} />${err(e, 'menu.timeoutSec')}</div>
57
+ <div><label for="fallback">If nobody answers</label><select id="fallback" data-key="menu.fallback" data-f="menu.fallbackAgentId">${opts(lookup.agents, f.menu.fallbackAgentId, 'Hang up')}</select></div></div>
58
+ <h3>Choices</h3>
59
+ ${Object.entries(f.menu.routes).sort(([a], [b]) => DIGITS.indexOf(a) - DIGITS.indexOf(b)).map(([d, r]) => renderRoute(d, r, e, lookup))}
60
+ <button data-action="route-add" ${DIGITS.every((d) => d in f.menu.routes) ? 'disabled' : ''}>Add a choice</button>
61
+ <h3>Opening hours</h3>
62
+ <label style="font-weight:400"><input type="checkbox" data-key="hours.enabled" data-f="hours.enabled" ${h.enabled ? 'checked' : ''} />Use opening hours</label>
63
+ ${h.enabled ? html`<div class="row"><div><label for="open">Opens (hour)</label><input id="open" type="number" min="0" max="23" data-key="hours.openHour" data-f="hours.openHour" value="${h.openHour}" ${bad(e, 'hours.openHour')} />${err(e, 'hours.openHour')}</div>
64
+ <div><label for="close">Closes (hour)</label><input id="close" type="number" min="1" max="24" data-key="hours.closeHour" data-f="hours.closeHour" value="${h.closeHour}" ${bad(e, 'hours.closeHour')} />${err(e, 'hours.closeHour')}</div>
65
+ <div><label for="tz">Time zone</label><input id="tz" data-key="hours.timezone" data-f="hours.timezone" value="${h.timezone}" placeholder="America/Jamaica" /></div></div>
66
+ <div class="days" role="group" aria-label="Open days">${DAYS.map((d) => html`<label><input type="checkbox" data-action="day-toggle" data-n="${d.n}" ${h.days.includes(d.n) ? 'checked' : ''} />${d.label}</label>`)}</div>${err(e, 'hours.days')}
67
+ <label for="after">After hours</label><select id="after" data-key="hours.after" data-f="hours.afterHoursAction"><option value="voicemail" ${h.afterHoursAction === 'voicemail' ? 'selected' : ''}>Take a voicemail</option><option value="agent" ${h.afterHoursAction === 'agent' ? 'selected' : ''}>Let an AI agent answer</option></select>
68
+ ${h.afterHoursAction === 'agent' ? html`<select aria-label="After-hours agent" data-key="hours.afterAgent" data-f="hours.afterHoursAgentId" ${bad(e, 'hours.afterHoursAgentId')}>${opts(lookup.agents, h.afterHoursAgentId, 'Choose an agent')}</select>${err(e, 'hours.afterHoursAgentId')}` : ''}` : ''}
69
+ <h3>Spam</h3>
70
+ <div class="row"><div><label for="rate">Calls per number, per 10 minutes</label><input id="rate" type="number" min="1" data-key="spam.rate" data-f="spam.rateLimitPer10Min" value="${f.spam.rateLimitPer10Min}" /></div></div>
71
+ <label style="font-weight:400"><input type="checkbox" data-key="spam.press1" data-f="spam.press1ScreenUnverified" ${f.spam.press1ScreenUnverified ? 'checked' : ''} />Ask unverified callers to press 1 first</label>
72
+ <label style="font-weight:400"><input type="checkbox" data-key="enabled" data-f="enabled" ${s.enabled ? 'checked' : ''} />This flow answers calls</label>
73
+ </div><div><h3>Call map</h3>${renderMap(f, lookup)}
74
+ ${sim ? html`<h3>Test call</h3><pre style="white-space:pre-wrap;font-size:12.5px" aria-label="Simulation result">${JSON.stringify(sim, null, 2)}</pre>` : ''}
75
+ </div></div></div>`.toString();
76
+ }
77
+
78
+ /**
79
+ * `<traitos-flow-builder phone-number-id="pn_123">` — edit what happens when a number is called.
80
+ * el.client = new TraitOSClient({ baseUrl, token }); // a browser token with the `settings` scope
81
+ * el.agents = [{ id, name }]; el.team = [{ id, name }];
82
+ * Events: `traitos-saved`, `traitos-error`.
83
+ */
84
+ export class TraitOSFlowBuilder extends TraitElement {
85
+ static get observedAttributes() { return ['phone-number-id']; }
86
+ get css() { return css; }
87
+ set client(v) { this._client = v; this._init(); }
88
+ get client() { return this._client; }
89
+ set agents(v) { this._agents = v ?? []; this._rebuild(); }
90
+ set team(v) { this._team = v ?? []; this._rebuild(); }
91
+ mounted() { this._init(); }
92
+ unmounted() { this._unsub?.(); this.controller = null; }
93
+ attributeChangedCallback(n, o, v) { if (o !== v && this.controller) { this.controller = null; this._unsub?.(); this._init(); } }
94
+ _rebuild() { if (this.controller) { this.controller.lookup = { agents: this._agents ?? [], team: this._team ?? [] }; this.requestRender(); } }
95
+
96
+ _init() {
97
+ const id = this.getAttribute('phone-number-id');
98
+ if (this.controller || !this._connected || !this._client || !id) return;
99
+ this.controller = new FlowBuilderController({ client: this._client, phoneNumberId: id, agents: this._agents ?? [], team: this._team ?? [] });
100
+ this._unsub = this.controller.subscribe(() => this.requestRender());
101
+ this.controller.load();
102
+ this.requestRender();
103
+ }
104
+
105
+ render() {
106
+ if (!this.controller) return html`<div class="card"><p class="hint">Set the <code>client</code> property and a <code>phone-number-id</code> to edit a flow.</p></div>`.toString();
107
+ return renderFlowBuilder(this.controller.snapshot(), this.controller.lookup, { prompt: this._prompt ?? '' });
108
+ }
109
+
110
+ async onClick(action, node) {
111
+ const c = this.controller;
112
+ if (!c) return;
113
+ const d = node.dataset.d;
114
+ if (action === 'save') { const ok = await c.save(); this.emit(ok ? 'traitos-saved' : 'traitos-error', { phoneNumberId: c.phoneNumberId, message: c.state.message }); }
115
+ else if (action === 'undo') c.undo();
116
+ else if (action === 'redo') c.redo();
117
+ else if (action === 'reload') c.load();
118
+ else if (action === 'check') c.check();
119
+ else if (action === 'simulate') c.simulate();
120
+ else if (action === 'generate') { if (await c.generate(this._prompt)) { this._prompt = ''; } }
121
+ else if (action === 'route-add') c.apply((f) => addRoute(f));
122
+ else if (action === 'route-remove') c.apply((f) => removeRoute(f, d));
123
+ else if (action === 'day-toggle') c.apply((f) => toggleDay(f, Number(node.dataset.n)));
124
+ else if (action === 'dept-toggle') c.apply((f) => { const cur = f.menu.routes[d]?.departmentTargets ?? []; const id = node.dataset.id; return setRoute(f, d, { departmentTargets: cur.includes(id) ? cur.filter((x) => x !== id) : [...cur, id] }); });
125
+ }
126
+
127
+ _edit(t) {
128
+ const c = this.controller;
129
+ const key = t.dataset.key, f = t.dataset.f;
130
+ if (key === 'draft') { this._prompt = t.value; return; }
131
+ if (!c || !f) return;
132
+ const v = t.type === 'checkbox' ? t.checked : t.value;
133
+ if (f === 'enabled') return c.setEnabled(v);
134
+ if (t.dataset.d) return c.apply((flow) => setRoute(flow, t.dataset.d, { [f]: v === '' && f.endsWith('Id') ? null : v }));
135
+ const num = (x) => (x === '' ? x : Number(x));
136
+ const map = {
137
+ greeting: () => setGreeting(c.state.flow, v),
138
+ 'menu.prompt': () => setMenu(c.state.flow, { prompt: v }),
139
+ 'menu.timeoutSec': () => setMenu(c.state.flow, { timeoutSec: num(v) }),
140
+ 'menu.fallbackAgentId': () => setMenu(c.state.flow, { fallbackAgentId: v || null }),
141
+ 'spam.rateLimitPer10Min': () => setSpam(c.state.flow, { rateLimitPer10Min: num(v) }),
142
+ 'spam.press1ScreenUnverified': () => setSpam(c.state.flow, { press1ScreenUnverified: v }),
143
+ 'hours.enabled': () => setHours(c.state.flow, { enabled: v }),
144
+ 'hours.openHour': () => setHours(c.state.flow, { openHour: num(v) }),
145
+ 'hours.closeHour': () => setHours(c.state.flow, { closeHour: num(v) }),
146
+ 'hours.timezone': () => setHours(c.state.flow, { timezone: v }),
147
+ 'hours.afterHoursAction': () => setHours(c.state.flow, { afterHoursAction: v }),
148
+ 'hours.afterHoursAgentId': () => setHours(c.state.flow, { afterHoursAgentId: v || null }),
149
+ };
150
+ if (map[f]) c.apply(() => map[f]());
151
+ }
152
+
153
+ onInput(t) { if (t.type !== 'checkbox' && t.tagName !== 'SELECT') this._edit(t); }
154
+ onChange(t) { if (t.type === 'checkbox' || t.tagName === 'SELECT') this._edit(t); }
155
+ }
156
+
157
+ define('traitos-flow-builder', TraitOSFlowBuilder);
158
+
@@ -0,0 +1,74 @@
1
+ import { html, raw } from '../html.js';
2
+ import { TraitElement, define } from './base.js';
3
+ import { createDialpad, KEYS, CHANNELS } from '../core/dialpad.js';
4
+ import { stringsFor, t } from '../core/strings.js';
5
+ import { keypadCss } from '../theme.js';
6
+ import { createSound } from '../core/sound.js';
7
+
8
+ const keyLabel = (S, d) => (d === '0' ? S.keyZero : d === '*' ? S.keyStar : d === '#' ? S.keyHash : d);
9
+
10
+ /**
11
+ * Pure view of the keypad, shared by <traitos-keypad>, the softphone and the widget.
12
+ * mode "dial": number box, backspace, one call button per enabled channel
13
+ * mode "dtmf": just the keys (send tones on a live call)
14
+ */
15
+ export function renderKeypad(dp, { S = stringsFor(), mode = 'dial', busy = false } = {}) {
16
+ const dtmf = mode === 'dtmf';
17
+ const calls = CHANNELS.filter((c) => dp.channels.includes(c.id));
18
+ const note = dtmf ? html`<p class="kp-note" role="status">${S.sendingDigits}</p>`
19
+ : dp.nothingEnabled ? html`<p class="kp-note warn" role="status">${S.callingOff}</p>`
20
+ : dp.number && !dp.canCall ? html`<p class="kp-note" role="status">${S.needCountryCode}</p>` : '';
21
+ return html`<div class="kp" role="group" aria-label="${S.keypad}" data-at="dial-pad">
22
+ ${dtmf ? '' : html`<div class="kp-row"><input class="kp-num" id="kp-number" data-key="dialpad-number" type="tel" inputmode="tel" autocomplete="off" maxlength="24" placeholder="${S.numberPlaceholder}" aria-label="${S.numberLabel}" value="${dp.number}" data-at="dial-pad-input" />
23
+ <button type="button" class="kp-back" data-action="kp-back" aria-label="${S.backspace}" ${dp.number ? '' : 'disabled'} data-at="dial-pad-backspace">⌫</button></div>`}
24
+ <div class="kp-grid">${KEYS.map((k) => html`<button type="button" class="kp-key" data-action="${dtmf ? 'kp-dtmf' : 'kp-key'}" data-d="${k.d}" ${k.d === '0' && !dtmf ? raw('data-hold="zero"') : ''} aria-label="${keyLabel(S, k.d)}" data-at="dial-pad-key-${k.d}"><b aria-hidden="true">${k.d}</b><i aria-hidden="true">${k.l}</i></button>`)}</div>
25
+ ${dtmf || !calls.length ? '' : html`<div class="kp-calls">${calls.map((c) => html`<button type="button" class="kp-call" data-action="kp-call" data-channel="${c.id}" aria-label="${t(S, 'callOn', { channel: S[c.labelKey] })}" ${dp.canCall && !busy ? '' : 'disabled'} data-at="dial-pad-call-${c.id}">${S[c.labelKey]}</button>`)}</div>`}
26
+ ${note}
27
+ </div>`;
28
+ }
29
+
30
+ /** Route a click from a keypad button. Returns true when it was one of the keypad's. */
31
+ export function keypadClick(dp, action, node, { onDtmf } = {}) {
32
+ if (action === 'kp-key') { dp.press(node.dataset.d); return true; }
33
+ if (action === 'kp-back') { dp.backspace(); return true; }
34
+ if (action === 'kp-call') { dp.call(node.dataset.channel); return true; }
35
+ if (action === 'kp-dtmf') { onDtmf?.(node.dataset.d); return true; }
36
+ return false;
37
+ }
38
+ export function keypadInput(dp, target) { if (target.dataset?.key !== 'dialpad-number') return false; dp.setNumber(target.value); return true; }
39
+ export function keypadKey(dp, e) {
40
+ if (e.key === 'Enter' && e.target?.dataset?.key === 'dialpad-number') { e.preventDefault(); dp.submit(); return true; }
41
+ return false;
42
+ }
43
+ export function keypadHold(dp, what) { if (what === 'zero') { dp.pressZeroLong(); return true; } return false; }
44
+
45
+ /**
46
+ * `<traitos-keypad>` — a standalone dialpad.
47
+ * el.caps = { whatsappCallingEnabled: true, phoneCallingEnabled: true }; (or the attributes whatsapp-calling / phone-calling)
48
+ * el.addEventListener('traitos-call', (e) => e.detail) // { number: '18765550101', channel: 'whatsapp' | 'phone' }
49
+ * Only enabled channels get a button; a call needs 7+ digits; Enter calls on WhatsApp when it is on, otherwise phone.
50
+ */
51
+ export class TraitOSKeypad extends TraitElement {
52
+ static get observedAttributes() { return ['whatsapp-calling', 'phone-calling', 'theme']; }
53
+ constructor() {
54
+ super();
55
+ this.dp = createDialpad({ onCall: (c) => this.emit('traitos-call', c) });
56
+ this.dp.subscribe(() => this.requestRender());
57
+ }
58
+ get css() { return keypadCss + ':host{max-width:280px}'; }
59
+ get caps() { return this._caps ?? this._attrCaps(); }
60
+ set caps(v) { this._caps = v; this.dp.setCaps(v); }
61
+ set strings(v) { this._strings = v; this.requestRender(); }
62
+ _attrCaps() { return { whatsappCallingEnabled: this.hasAttribute('whatsapp-calling'), phoneCallingEnabled: this.hasAttribute('phone-calling') }; }
63
+ mounted() { this.dp.setCaps(this.caps); }
64
+ attributeChangedCallback() { if (!this._caps) this.dp.setCaps(this._attrCaps()); this.requestRender(); }
65
+ render() { return `<div class="card">${renderKeypad(this.dp, { S: stringsFor(this._strings) })}</div>`; }
66
+ /** Key tones for the standalone keypad; replace to supply your own, or set `sound.update({ enabled: false })`. */
67
+ get sound() { return (this._sound ??= createSound({ storage: typeof localStorage !== 'undefined' ? localStorage : undefined })); }
68
+ set sound(v) { this._sound = v; }
69
+ onClick(a, n) { if (a === 'kp-key') this.sound.key(n.dataset.d); else if (a === 'kp-back' || a === 'kp-call') this.sound.click(); keypadClick(this.dp, a, n); }
70
+ onInput(t2) { keypadInput(this.dp, t2); }
71
+ onKey(e) { if (e.target?.dataset?.key === 'dialpad-number' && e.key.length === 1 && /[0-9*#]/.test(e.key) && !e.ctrlKey && !e.metaKey) this.sound.key(e.key); keypadKey(this.dp, e); }
72
+ onHold(w) { if (keypadHold(this.dp, w)) this.sound.key('+'); }
73
+ }
74
+ define('traitos-keypad', TraitOSKeypad);