@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.
- package/CHANGELOG.md +25 -0
- package/README.md +109 -2
- package/dist/traitos-ui.global.js +4462 -0
- package/dist/traitos-ui.global.min.js +247 -0
- package/package.json +32 -4
- package/src/browser.js +8 -0
- package/src/core/api.js +24 -0
- package/src/core/callLog.js +27 -0
- package/src/core/dialerPrefs.js +33 -0
- package/src/core/dialpad.js +74 -0
- package/src/core/flowBuilderController.js +115 -0
- package/src/core/flowModel.js +112 -0
- package/src/core/history.js +24 -0
- package/src/core/settingsController.js +95 -0
- package/src/core/settingsSections.js +199 -0
- package/src/core/softphoneController.js +233 -0
- package/src/core/softphoneState.js +44 -0
- package/src/core/sound.js +101 -0
- package/src/core/strings.js +38 -0
- package/src/core/telnyxAdapter.js +38 -0
- package/src/core/tokenManager.js +67 -0
- package/src/core/widgetState.js +53 -0
- package/src/elements/base.js +74 -0
- package/src/elements/dialerWidget.js +139 -0
- package/src/elements/flowBuilder.js +158 -0
- package/src/elements/keypad.js +74 -0
- package/src/elements/phoneBase.js +172 -0
- package/src/elements/settings.js +184 -0
- package/src/elements/softphone.js +101 -0
- package/src/elements/soundOptions.js +39 -0
- package/src/html.js +24 -0
- package/src/index.js +36 -0
- package/src/theme.js +63 -0
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import { TraitElement } from './base.js';
|
|
2
|
+
import { keypadClick, keypadInput, keypadHold } from './keypad.js';
|
|
3
|
+
import { SoftphoneController } from '../core/softphoneController.js';
|
|
4
|
+
import { createDialpad, capsFromLines } from '../core/dialpad.js';
|
|
5
|
+
import { CallLog } from '../core/callLog.js';
|
|
6
|
+
import { stringsFor } from '../core/strings.js';
|
|
7
|
+
import { createSound } from '../core/sound.js';
|
|
8
|
+
import { applySoundEdit } from './soundOptions.js';
|
|
9
|
+
import { listLines, listCalls } from '../core/api.js';
|
|
10
|
+
import { mergeCalls } from '../core/history.js';
|
|
11
|
+
import { storedPrefs, registrationFor, PREFS_EVENT } from '../core/dialerPrefs.js';
|
|
12
|
+
|
|
13
|
+
const localStore = () => { try { return typeof localStorage !== 'undefined' ? localStorage : null; } catch { return null; } };
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* What the softphone and the dialer widget share: the client/adapter/caps/strings properties, a controller that is created once
|
|
17
|
+
* both client and adapter are set, a keypad, a call log, and the `traitos-call` event. Subclasses supply `render()`.
|
|
18
|
+
*
|
|
19
|
+
* Properties: client, adapter, numbers, caps, strings, whatsapp (what a WhatsApp call needs), storage.
|
|
20
|
+
* Events: `traitos-state`, `traitos-error`, and `traitos-call` ({number, channel}; cancelable: call preventDefault() to place the
|
|
21
|
+
* call yourself, otherwise phone calls go through the SDK and the softphone).
|
|
22
|
+
*/
|
|
23
|
+
export class PhoneBase extends TraitElement {
|
|
24
|
+
static get observedAttributes() { return ['allow-dial', 'live-events', 'auto-start', 'theme', 'position', 'inline']; }
|
|
25
|
+
constructor() {
|
|
26
|
+
super();
|
|
27
|
+
this.dp = createDialpad({ clearOnCall: false, onCall: (c) => this._placeCall(c.number, c.channel) });
|
|
28
|
+
this.dp.subscribe(() => this.requestRender());
|
|
29
|
+
this.keypadOpen = false;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
set client(v) { this._client = v; this._lines = null; this._init(); }
|
|
33
|
+
get client() { return this._client; }
|
|
34
|
+
set adapter(v) { this._adapter = v; this._init(); }
|
|
35
|
+
get adapter() { return this._adapter; }
|
|
36
|
+
set numbers(v) { this._numbers = v; if (this.controller) this.controller.numbers = v; }
|
|
37
|
+
set whatsapp(v) { this._whatsapp = v; if (this.controller) this.controller.whatsapp = v; this.requestRender(); }
|
|
38
|
+
get whatsapp() { return this._whatsapp; }
|
|
39
|
+
set strings(v) { this._strings = v; this.requestRender(); }
|
|
40
|
+
get S() { return stringsFor(this._strings); }
|
|
41
|
+
get caps() { return this.dp.caps; }
|
|
42
|
+
set caps(v) { this._caps = v; this.dp.setCaps(v); }
|
|
43
|
+
set storage(v) { this._storage = v; }
|
|
44
|
+
/** The sound engine (key tones, ringtone, spoken digits). Replace it to supply your own. */
|
|
45
|
+
get sound() { if (!this._sound) { this._sound = createSound({ storage: this._store }); this._unsound = this._sound.subscribe(() => this.requestRender()); } return this._sound; }
|
|
46
|
+
set sound(v) { this._sound = v; this.requestRender(); }
|
|
47
|
+
get _store() { return this._storage ?? localStore(); }
|
|
48
|
+
|
|
49
|
+
mounted() {
|
|
50
|
+
this._onPrefs = () => this._applyPrefs();
|
|
51
|
+
this._onVoices = () => this.requestRender();
|
|
52
|
+
globalThis.speechSynthesis?.addEventListener?.('voiceschanged', this._onVoices);
|
|
53
|
+
globalThis.addEventListener?.(PREFS_EVENT, this._onPrefs);
|
|
54
|
+
this._init();
|
|
55
|
+
}
|
|
56
|
+
unmounted() {
|
|
57
|
+
globalThis.removeEventListener?.(PREFS_EVENT, this._onPrefs);
|
|
58
|
+
globalThis.speechSynthesis?.removeEventListener?.('voiceschanged', this._onVoices);
|
|
59
|
+
this._sound?.stopRing(); this._unsound?.(); this._unsound = null;
|
|
60
|
+
clearInterval(this._tick);
|
|
61
|
+
this._unsub?.(); this._unsub = null;
|
|
62
|
+
this._unlog?.(); this._unlog = null;
|
|
63
|
+
this.controller?.stop();
|
|
64
|
+
this.controller = null;
|
|
65
|
+
this._capsLoaded = false;
|
|
66
|
+
}
|
|
67
|
+
attributeChangedCallback() { this.requestRender(); }
|
|
68
|
+
|
|
69
|
+
_init() {
|
|
70
|
+
if (!this._connected) return;
|
|
71
|
+
this._initCaps();
|
|
72
|
+
if (this.controller || !this._client || !this._adapter) { this.requestRender(); return; }
|
|
73
|
+
this.log = new CallLog({ storage: this._store });
|
|
74
|
+
this._unlog = this.log.subscribe(() => this.requestRender());
|
|
75
|
+
this.controller = new SoftphoneController({ client: this._client, adapter: this._adapter, numbers: this._numbers, whatsapp: this._whatsapp, liveEvents: this.hasAttribute('live-events'), log: this.log, strings: this._strings });
|
|
76
|
+
this._applyPrefs();
|
|
77
|
+
this._unsub = this.controller.subscribe((s) => {
|
|
78
|
+
this.emit('traitos-state', s);
|
|
79
|
+
if (s.status === 'error') this.emit('traitos-error', { message: s.error, code: s.errorCode });
|
|
80
|
+
clearInterval(this._tick);
|
|
81
|
+
if (s.status === 'in-call') this._tick = setInterval(() => this.requestRender(), 1000);
|
|
82
|
+
if (s.status !== 'in-call') this.keypadOpen = false;
|
|
83
|
+
this._stateSound(s);
|
|
84
|
+
this.onState?.(s);
|
|
85
|
+
this.requestRender();
|
|
86
|
+
});
|
|
87
|
+
if (this.hasAttribute('auto-start')) this.controller.start();
|
|
88
|
+
this.requestRender();
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Ring while a call is ringing; a short end tone when a call ends. */
|
|
92
|
+
/** Recent calls: this browser's log merged with the server's list when the token may read it. */
|
|
93
|
+
recentCalls() { return mergeCalls(this.log?.list() ?? [], this._serverCalls ?? []); }
|
|
94
|
+
async _loadHistory() {
|
|
95
|
+
if (!this._client || this._historyBusy) return;
|
|
96
|
+
this._historyBusy = true;
|
|
97
|
+
try { this._serverCalls = await listCalls(this._client, 10); this.requestRender(); } catch { /* the token may not read history: the local log still shows */ }
|
|
98
|
+
this._historyBusy = false;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
_stateSound(s) {
|
|
102
|
+
const prev = this._prevStatus; this._prevStatus = s.status;
|
|
103
|
+
if (s.status === 'ringing') this.sound.startRing(); else this.sound.stopRing();
|
|
104
|
+
if (s.status === 'ready' && (prev === 'in-call' || prev === 'ringing')) { this.sound.end(); setTimeout(() => this._loadHistory(), 1500); }
|
|
105
|
+
if (s.status === 'ready' && prev !== 'ready' && !this._serverCalls) this._loadHistory();
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Without `caps`, learn which channels the workspace has from its phone lines. If that fails, phone calling stays on. */
|
|
109
|
+
async _initCaps() {
|
|
110
|
+
if (this._caps || this._capsLoaded || !this._client) return;
|
|
111
|
+
this._capsLoaded = true;
|
|
112
|
+
try { this._lines = await listLines(this._client); if (!this._caps) this.dp.setCaps(capsFromLines(this._lines)); this._applyPrefs(); }
|
|
113
|
+
catch { if (!this._caps) this.dp.setCaps({ phoneCallingEnabled: true }); }
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Ring timeout and ringing channels chosen in <traitos-settings> (kept in this browser). */
|
|
117
|
+
_applyPrefs() {
|
|
118
|
+
const p = storedPrefs(this._store);
|
|
119
|
+
if (!p || !this.controller) return;
|
|
120
|
+
const reg = registrationFor(p, this._lines);
|
|
121
|
+
this.controller.ringTimeoutSeconds = reg.ringTimeoutSeconds || undefined;
|
|
122
|
+
if (!this._numbers && reg.numbers) this.controller.numbers = reg.numbers;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
_placeCall(number, channel) {
|
|
126
|
+
const go = this.emit('traitos-call', { number, channel }, { cancelable: true });
|
|
127
|
+
if (go && this.controller) this.controller.dial(number, channel).then((ok) => { if (ok) this.dp.clear(); this.requestRender(); });
|
|
128
|
+
else if (!this.controller || !go) this.dp.clear();
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Place a call as if the number had been keyed in. Resolves false when it was refused. */
|
|
132
|
+
dial(number, channel = 'phone') {
|
|
133
|
+
if (!this.dp.channels.includes(channel)) return false;
|
|
134
|
+
this.dp.setNumber(String(number));
|
|
135
|
+
return this.dp.call(channel);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** Everything both elements do on a click; returns true when handled. */
|
|
139
|
+
phoneClick(action, node) {
|
|
140
|
+
const c = this.controller;
|
|
141
|
+
// Sounds first, so a press is heard even if the action then refuses (a number that is too short, say).
|
|
142
|
+
if (action === 'kp-key' || action === 'kp-dtmf') this.sound.key(node.dataset.d);
|
|
143
|
+
else if (action === 'snd-test') this.sound.test();
|
|
144
|
+
else if (action !== 'snd-toggle' && action !== 'start' && action !== 'stop') this.sound.click();
|
|
145
|
+
if (action === 'snd-toggle') { this._sndOpen = !this._sndOpen; this.requestRender(); return true; }
|
|
146
|
+
if (action === 'snd-test') return true;
|
|
147
|
+
if (keypadClick(this.dp, action, node, { onDtmf: (d) => c?.dtmf(d) })) return true;
|
|
148
|
+
if (!c) return false;
|
|
149
|
+
if (action === 'start') c.start();
|
|
150
|
+
else if (action === 'stop') c.stop();
|
|
151
|
+
else if (action === 'answer') c.answer();
|
|
152
|
+
else if (action === 'hangup') c.hangup();
|
|
153
|
+
else if (action === 'mute') c.mute();
|
|
154
|
+
else if (action === 'hold') c.hold();
|
|
155
|
+
else if (action === 'toggle-keypad') { this.keypadOpen = !this.keypadOpen; this.requestRender(); }
|
|
156
|
+
else if (action === 'redial') {
|
|
157
|
+
const e = this.recentCalls()[Number(node.dataset.i)];
|
|
158
|
+
if (e?.number) this.dial(e.number.replace(/\D/g, ''), this.dp.channels.includes('phone') ? 'phone' : this.dp.channels[0]);
|
|
159
|
+
} else return false;
|
|
160
|
+
return true;
|
|
161
|
+
}
|
|
162
|
+
onClick(action, node) { this.phoneClick(action, node); }
|
|
163
|
+
onInput(target) { if (target.dataset?.key?.startsWith('snd-')) { if (target.type === 'range') applySoundEdit(this.sound, target); return; } keypadInput(this.dp, target); }
|
|
164
|
+
onChange(target) { applySoundEdit(this.sound, target); }
|
|
165
|
+
onHold(what) { if (keypadHold(this.dp, what)) this.sound.key('+'); }
|
|
166
|
+
|
|
167
|
+
onKey(e) {
|
|
168
|
+
if (e.target?.dataset?.key !== 'dialpad-number') return;
|
|
169
|
+
if (e.key === 'Enter') { e.preventDefault(); this.dp.submit(); }
|
|
170
|
+
else if (e.key.length === 1 && /[0-9*#]/.test(e.key) && !e.ctrlKey && !e.metaKey) this.sound.key(e.key); // typing sounds like pressing
|
|
171
|
+
}
|
|
172
|
+
}
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import { html, raw } from '../html.js';
|
|
2
|
+
import { TraitElement, define } from './base.js';
|
|
3
|
+
import { SettingsController } from '../core/settingsController.js';
|
|
4
|
+
import { SECTIONS, RULE_OPS, RULE_OP_LABEL, RING, MAX_STEPS, OUTBOUND_MODES } from '../core/settingsSections.js';
|
|
5
|
+
import { MAX_RING_SECONDS } from '../core/dialerPrefs.js';
|
|
6
|
+
|
|
7
|
+
const css = `
|
|
8
|
+
section.card { margin-bottom: 14px; } .steps { list-style: none; margin: 0; padding: 0; } .steps > li, .rule { border: 1px solid var(--_line); border-radius: calc(var(--_r) - 4px); padding: 8px 10px; margin: 6px 0; }
|
|
9
|
+
.meter { margin: 8px 0; } .meter .top { display: flex; justify-content: space-between; font-size: 13px; }
|
|
10
|
+
.linkish { background: none; border: 0; color: var(--_accent); padding: 2px 4px; }
|
|
11
|
+
`;
|
|
12
|
+
|
|
13
|
+
const err = (errors, path) => (errors[path] ? html`<p class="err" id="e-${path}" role="alert">${errors[path]}</p>` : '');
|
|
14
|
+
const bad = (errors, path) => (errors[path] ? 'aria-invalid="true"' : '');
|
|
15
|
+
|
|
16
|
+
function field(errors, key, label, value, { type = 'text', hint = '', attrs = '', section, f, i }) {
|
|
17
|
+
const id = `${section}-${key}`;
|
|
18
|
+
return html`<label for="${id}">${label}</label>
|
|
19
|
+
<input id="${id}" data-key="${key}" data-s="${section}" data-f="${f ?? key}" ${i !== undefined ? raw(`data-i="${i}"`) : ''} type="${type}" value="${value ?? ''}" ${raw(attrs)} ${raw(bad(errors, key))} />
|
|
20
|
+
${hint ? html`<p class="hint">${hint}</p>` : ''}${err(errors, key)}`;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function renderHandoff(s) {
|
|
24
|
+
const { draft: d, errors: e } = s;
|
|
25
|
+
return html`
|
|
26
|
+
${field(e, 'transferNumber', 'Transfer number', d.transferNumber, { type: 'tel', hint: 'A phone number to transfer to. Leave empty for none.', section: 'handoff' })}
|
|
27
|
+
<h3>Who to ring, in order</h3>
|
|
28
|
+
${err(e, 'steps')}
|
|
29
|
+
<ol class="steps">${d.steps.map((st, i) => html`<li>
|
|
30
|
+
<div class="row">
|
|
31
|
+
<div><label for="h-kind-${i}">Ring a</label><select id="h-kind-${i}" data-key="steps.${i}.kind" data-s="handoff" data-i="${i}" data-f="kind"><option value="softphone" ${st.kind === 'softphone' ? 'selected' : ''}>Browser softphone</option><option value="phone" ${st.kind === 'phone' ? 'selected' : ''}>Phone number</option></select></div>
|
|
32
|
+
<div><label for="h-target-${i}">${st.kind === 'phone' ? 'Number' : 'Softphone name'}</label><input id="h-target-${i}" data-key="steps.${i}.target" data-s="handoff" data-i="${i}" data-f="target" value="${st.target}" placeholder="${st.kind === 'phone' ? '+18765550100' : 'agent_01'}" ${raw(bad(e, `steps.${i}.target`))} />${err(e, `steps.${i}.target`)}</div>
|
|
33
|
+
<div class="fixed" style="width:96px"><label for="h-ring-${i}">Seconds</label><input id="h-ring-${i}" data-key="steps.${i}.ringSecs" data-s="handoff" data-i="${i}" data-f="ringSecs" type="number" min="${RING.min}" max="${RING.max}" value="${st.ringSecs}" ${raw(bad(e, `steps.${i}.ringSecs`))} />${err(e, `steps.${i}.ringSecs`)}</div>
|
|
34
|
+
<div class="fixed"><button type="button" data-action="step-up" data-s="handoff" data-i="${i}" aria-label="Move step ${i + 1} up" ${i === 0 ? 'disabled' : ''}>↑</button> <button type="button" data-action="step-down" data-s="handoff" data-i="${i}" aria-label="Move step ${i + 1} down" ${i === d.steps.length - 1 ? 'disabled' : ''}>↓</button> <button type="button" class="linkish" data-action="step-remove" data-s="handoff" data-i="${i}" aria-label="Remove step ${i + 1}">Remove</button></div>
|
|
35
|
+
</div></li>`)}</ol>
|
|
36
|
+
<button type="button" data-action="step-add" data-s="handoff" ${d.steps.length >= MAX_STEPS ? 'disabled' : ''}>Add someone to ring</button>
|
|
37
|
+
<label for="h-caller">The person sees</label>
|
|
38
|
+
<select id="h-caller" data-key="callerId" data-s="handoff" data-f="callerId"><option value="customer" ${d.callerId === 'customer' ? 'selected' : ''}>The customer's number</option><option value="platform" ${d.callerId === 'platform' ? 'selected' : ''}>Your company number</option></select>${err(e, 'callerId')}`;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function renderApprovals(s, agentId) {
|
|
42
|
+
const { draft: d, errors: e } = s;
|
|
43
|
+
return html`
|
|
44
|
+
<div class="row">
|
|
45
|
+
<div>${field(e, 'timeoutMinutes', 'Wait for an answer (minutes)', d.timeoutMinutes, { type: 'number', section: 'approvals', attrs: 'min="1" max="20160"' })}</div>
|
|
46
|
+
<div><label for="a-on">If nobody answers</label><select id="a-on" data-key="onTimeout" data-s="approvals" data-f="onTimeout"><option value="escalate" ${d.onTimeout === 'escalate' ? 'selected' : ''}>Escalate to a person</option><option value="deny" ${d.onTimeout === 'deny' ? 'selected' : ''}>Deny the request</option></select>${err(e, 'onTimeout')}</div>
|
|
47
|
+
<div>${field(e, 'liveWaitSeconds', 'Live chat wait (seconds)', d.liveWaitSeconds, { type: 'number', section: 'approvals', attrs: 'min="0" max="600"' })}</div>
|
|
48
|
+
</div>
|
|
49
|
+
<label><input type="checkbox" data-key="notifyEmail" data-s="approvals" data-f="notifyEmail" ${d.notifyEmail ? 'checked' : ''} />Email admins when something needs approval</label>
|
|
50
|
+
<h3>Rules for this agent</h3>
|
|
51
|
+
${agentId ? '' : html`<p class="hint">Choose an agent to edit its rules.</p>`}
|
|
52
|
+
${agentId ? html`${d.rules.map((r, i) => html`<div class="rule">
|
|
53
|
+
<div class="row">
|
|
54
|
+
<div><label for="r-tool-${i}">Tool</label><input id="r-tool-${i}" data-key="rules.${i}.tool" data-s="approvals" data-i="${i}" data-f="tool" value="${r.tool}" placeholder="refund.create or refund.*" ${raw(bad(e, `rules.${i}.tool`))} />${err(e, `rules.${i}.tool`)}</div>
|
|
55
|
+
<div class="fixed"><label for="r-act-${i}">Then</label><select id="r-act-${i}" data-key="rules.${i}.action" data-s="approvals" data-i="${i}" data-f="action">${['ask', 'allow', 'deny'].map((a) => html`<option value="${a}" ${r.action === a ? 'selected' : ''}>${a === 'ask' ? 'Ask a person' : a === 'allow' ? 'Allow' : 'Deny'}</option>`)}</select></div>
|
|
56
|
+
<div class="fixed"><button type="button" class="linkish" data-action="rule-remove" data-s="approvals" data-i="${i}" aria-label="Remove rule ${i + 1}">Remove</button></div>
|
|
57
|
+
</div>
|
|
58
|
+
<label><input type="checkbox" data-key="rules.${i}.cond" data-s="approvals" data-i="${i}" data-f="cond" ${r.when ? 'checked' : ''} />Only when a value matches</label>
|
|
59
|
+
${r.when ? html`<div class="row">
|
|
60
|
+
<div><input aria-label="Field" data-key="rules.${i}.when.field" data-s="approvals" data-i="${i}" data-f="when.field" value="${r.when.field}" placeholder="amount" ${raw(bad(e, `rules.${i}.when.field`))} />${err(e, `rules.${i}.when.field`)}</div>
|
|
61
|
+
<div class="fixed"><select aria-label="Comparison" data-key="rules.${i}.when.op" data-s="approvals" data-i="${i}" data-f="when.op">${RULE_OPS.map((o) => html`<option value="${o}" ${r.when.op === o ? 'selected' : ''}>${RULE_OP_LABEL[o]}</option>`)}</select></div>
|
|
62
|
+
<div><input aria-label="Value" data-key="rules.${i}.when.value" data-s="approvals" data-i="${i}" data-f="when.value" value="${r.when.value}" placeholder="100" ${raw(bad(e, `rules.${i}.when.value`))} />${err(e, `rules.${i}.when.value`)}</div>
|
|
63
|
+
</div>` : ''}</div>`)}
|
|
64
|
+
<button type="button" data-action="rule-add" data-s="approvals">Add a rule</button>` : ''}`;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function renderUsage(s) {
|
|
68
|
+
const { draft: d, errors: e } = s;
|
|
69
|
+
return html`
|
|
70
|
+
<p class="hint">${d.plan ? html`<b>${d.plan}</b> plan, ` : ''}${d.period}${d.status === 'paused' ? ' — conversations are paused (cap reached)' : ''}</p>
|
|
71
|
+
${d.meters.map((m) => html`<div class="meter"><div class="top"><span>${m.label}</span><span>${m.used}${m.included === null ? ' (unlimited)' : ` of ${m.included}`}</span></div>
|
|
72
|
+
<div class="bar" role="progressbar" aria-label="${m.label}" aria-valuemin="0" aria-valuemax="100" aria-valuenow="${m.percent ?? 0}"><i style="width:${Math.min(100, m.percent ?? 0)}%"></i></div></div>`)}
|
|
73
|
+
${field(e, 'spendCap', 'Monthly spend cap (USD)', d.spendCap, { type: 'number', hint: 'Blank means no cap. Past the cap, conversations pause instead of billing overage.', section: 'usage', attrs: 'min="0" step="0.01"' })}
|
|
74
|
+
<label for="u-msg">Message customers see while paused</label>
|
|
75
|
+
<textarea id="u-msg" rows="2" data-key="fallbackMessage" data-s="usage" data-f="fallbackMessage">${d.fallbackMessage}</textarea>${err(e, 'fallbackMessage')}`;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function renderDialer(s) {
|
|
79
|
+
const { draft: d, errors: e } = s;
|
|
80
|
+
const line = (l) => (l.name ? `${l.name} · ${l.number}` : l.number);
|
|
81
|
+
return html`
|
|
82
|
+
<h3>Lines</h3>
|
|
83
|
+
${d.lines.length ? html`<ul class="steps">${d.lines.map((l) => html`<li>${line(l)} <span class="hint">${[l.whatsapp && 'WhatsApp', l.phone && 'Phone'].filter(Boolean).join(' · ')}</span></li>`)}</ul>` : html`<p class="hint">No phone lines yet.</p>`}
|
|
84
|
+
<p class="hint">Enabled for calling: ${[d.whatsappEnabled && 'WhatsApp', d.phoneEnabled && 'Phone'].filter(Boolean).join(', ') || 'none'}</p>
|
|
85
|
+
<h3>How outbound calls are placed</h3>
|
|
86
|
+
${d.mode === null ? html`<p class="hint">Not available to this account.</p>` : html`<fieldset style="border:0;padding:0;margin:0"><legend class="sr">How outbound calls are placed</legend>${OUTBOUND_MODES.map((m) => html`<label><input type="radio" name="d-mode" data-key="mode.${m.id}" data-s="dialer" data-f="mode" value="${m.id}" ${d.mode === m.id ? 'checked' : ''} />${m.label} <span class="hint">${m.hint}</span></label>`)}</fieldset><p class="hint">Changing this needs an organization admin.</p>${err(e, 'mode')}`}
|
|
87
|
+
<h3>This browser</h3>
|
|
88
|
+
<p class="hint">Saved in this browser only; the server does not store these.</p>
|
|
89
|
+
<label for="d-ring">Ring timeout (seconds, 0 for the default)</label>
|
|
90
|
+
<input id="d-ring" type="number" min="0" max="${MAX_RING_SECONDS}" data-key="ringTimeoutSeconds" data-s="dialer" data-f="ringTimeoutSeconds" value="${d.ringTimeoutSeconds}" ${raw(bad(e, 'ringTimeoutSeconds'))} />${err(e, 'ringTimeoutSeconds')}
|
|
91
|
+
<label><input type="checkbox" data-key="ringWhatsapp" data-s="dialer" data-f="ringWhatsapp" ${d.ringWhatsapp ? 'checked' : ''} ${d.whatsappEnabled ? '' : 'disabled'} />Ring this browser for WhatsApp calls${d.whatsappEnabled ? '' : ' (not enabled)'}</label>
|
|
92
|
+
<label><input type="checkbox" data-key="ringPhone" data-s="dialer" data-f="ringPhone" ${d.ringPhone ? 'checked' : ''} ${d.phoneEnabled ? '' : 'disabled'} />Ring this browser for phone calls${d.phoneEnabled ? '' : ' (not enabled)'}</label>
|
|
93
|
+
<label for="d-caller">Caller ID line</label>
|
|
94
|
+
<select id="d-caller" data-key="callerId" data-s="dialer" data-f="callerId"><option value="">Default line</option>${d.lines.map((l) => html`<option value="${l.number}" ${d.callerId === l.number ? 'selected' : ''}>${line(l)}</option>`)}</select>
|
|
95
|
+
<p class="hint">Pass the saved line as <code>from</code> when your page places a call.</p>`;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Pure view of every section. */
|
|
99
|
+
export function renderSettings(snapshot, { agentId, ids = Object.keys(snapshot) } = {}) {
|
|
100
|
+
return html`${ids.map((id) => {
|
|
101
|
+
const s = snapshot[id];
|
|
102
|
+
const def = SECTIONS[id];
|
|
103
|
+
const body = s.status === 'needs-agent' ? html`<p class="hint">Choose an agent to edit this section.</p>`
|
|
104
|
+
: s.status === 'loading' || s.status === 'idle' ? html`<p class="hint" role="status">Loading…</p>`
|
|
105
|
+
: s.status === 'error' ? html`<p class="err" role="alert">${s.message}</p><button data-action="reload" data-s="${id}">Try again</button>`
|
|
106
|
+
: html`<form data-submit="save" data-s="${id}" novalidate>
|
|
107
|
+
${id === 'handoff' ? renderHandoff(s) : id === 'approvals' ? renderApprovals(s, agentId) : id === 'dialer' ? renderDialer(s) : renderUsage(s)}
|
|
108
|
+
${s.message ? html`<p class="${s.status === 'saved' ? 'status ok' : 'status bad'}" role="status">${s.message}</p>` : ''}
|
|
109
|
+
<div class="actions"><button type="button" data-action="reset" data-s="${id}" ${s.dirty ? '' : 'disabled'}>Discard changes</button><button type="submit" class="primary" ${!s.dirty || s.status === 'saving' ? 'disabled' : ''}>${s.status === 'saving' ? 'Saving…' : 'Save'}</button></div></form>`;
|
|
110
|
+
return html`<section class="card" aria-labelledby="t-${id}"><h2 id="t-${id}">${def.label}</h2><p class="hint">${def.description}</p>${body}</section>`;
|
|
111
|
+
})}`.toString();
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* `<traitos-settings agent-id="agent_123" sections="handoff,approvals,usage">` — settings forms that save only what changed.
|
|
116
|
+
* el.client = new TraitOSClient({ baseUrl, token }); // a browser token with the `settings` scope
|
|
117
|
+
* Events: `traitos-saved` ({section}), `traitos-error`.
|
|
118
|
+
*/
|
|
119
|
+
export class TraitOSSettings extends TraitElement {
|
|
120
|
+
static get observedAttributes() { return ['agent-id', 'sections']; }
|
|
121
|
+
get css() { return css; }
|
|
122
|
+
set client(v) { this._client = v; this._init(); }
|
|
123
|
+
get client() { return this._client; }
|
|
124
|
+
set storage(v) { this._storage = v; }
|
|
125
|
+
mounted() { this._init(); }
|
|
126
|
+
unmounted() { this._unsub?.(); this.controller = null; }
|
|
127
|
+
|
|
128
|
+
attributeChangedCallback(name, old, val) {
|
|
129
|
+
if (old === val) return;
|
|
130
|
+
if (name === 'agent-id' && this.controller) this.controller.setAgent(val || undefined);
|
|
131
|
+
if (name === 'sections') { this.controller = null; this._unsub?.(); this._init(); }
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
_init() {
|
|
135
|
+
if (this.controller || !this._connected || !this._client) return;
|
|
136
|
+
const sections = (this.getAttribute('sections') ?? 'handoff,approvals,usage').split(',').map((s) => s.trim()).filter(Boolean);
|
|
137
|
+
this.controller = new SettingsController({ client: this._client, agentId: this.getAttribute('agent-id') || undefined, sections, storage: this._storage ?? (typeof localStorage !== 'undefined' ? localStorage : undefined) });
|
|
138
|
+
this._unsub = this.controller.subscribe(() => this.requestRender());
|
|
139
|
+
this.controller.loadAll();
|
|
140
|
+
this.requestRender();
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
render() {
|
|
144
|
+
if (!this.controller) return html`<div class="card"><p class="hint">Set the <code>client</code> property to load settings.</p></div>`.toString();
|
|
145
|
+
return renderSettings(this.controller.snapshot(), { agentId: this.controller.agentId, ids: this.controller.ids });
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
async onClick(action, node) {
|
|
149
|
+
const c = this.controller;
|
|
150
|
+
const id = node.dataset.s;
|
|
151
|
+
const i = node.dataset.i === undefined ? undefined : Number(node.dataset.i);
|
|
152
|
+
if (!c || !id) return;
|
|
153
|
+
if (action === 'save') { const ok = await c.save(id); if (ok) this.emit('traitos-saved', { section: id }); else if (c.state[id].status !== 'saving' && c.state[id].message) this.emit('traitos-error', { section: id, message: c.state[id].message }); }
|
|
154
|
+
else if (action === 'reset') c.reset(id);
|
|
155
|
+
else if (action === 'reload') c.load(id);
|
|
156
|
+
else if (action === 'step-add') c.edit(id, (d, def) => def.addStep(d));
|
|
157
|
+
else if (action === 'step-remove') c.edit(id, (d, def) => def.removeStep(d, i));
|
|
158
|
+
else if (action === 'step-up') c.edit(id, (d, def) => def.moveStep(d, i, -1));
|
|
159
|
+
else if (action === 'step-down') c.edit(id, (d, def) => def.moveStep(d, i, 1));
|
|
160
|
+
else if (action === 'rule-add') c.edit(id, (d, def) => def.addRule(d));
|
|
161
|
+
else if (action === 'rule-remove') c.edit(id, (d, def) => def.removeRule(d, i));
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
_edit(target) {
|
|
165
|
+
const c = this.controller;
|
|
166
|
+
const id = target.dataset.s, f = target.dataset.f, i = target.dataset.i === undefined ? undefined : Number(target.dataset.i);
|
|
167
|
+
if (!c || !id || !f) return;
|
|
168
|
+
const value = target.type === 'checkbox' ? target.checked : target.value;
|
|
169
|
+
if (id === 'dialer' && target.type === 'radio' && !target.checked) return;
|
|
170
|
+
c.edit(id, (d, def) => {
|
|
171
|
+
if (id === 'handoff' && i !== undefined) def.setStep(d, i, f, value);
|
|
172
|
+
else if (id === 'approvals' && i !== undefined) {
|
|
173
|
+
if (f === 'cond') def.toggleCondition(d, i, value);
|
|
174
|
+
else if (f.startsWith('when.')) def.setCondition(d, i, f.slice(5), value);
|
|
175
|
+
else def.setRule(d, i, f, value);
|
|
176
|
+
} else d[f] = value;
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
onInput(target) { if (target.type !== 'checkbox' && target.type !== 'radio' && target.tagName !== 'SELECT') this._edit(target); }
|
|
181
|
+
onChange(target) { if (target.type === 'checkbox' || target.type === 'radio' || target.tagName === 'SELECT') this._edit(target); }
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
define('traitos-settings', TraitOSSettings);
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { html } 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 { softphoneLabel, formatDuration, cleanDialInput } from '../core/softphoneState.js';
|
|
7
|
+
import { stringsFor, t } from '../core/strings.js';
|
|
8
|
+
import { keypadCss } from '../theme.js';
|
|
9
|
+
|
|
10
|
+
const css = keypadCss + `
|
|
11
|
+
.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; }
|
|
12
|
+
.phone { max-width: 340px; } .head { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
|
|
13
|
+
.dot { width: 9px; height: 9px; border-radius: 50%; background: var(--_line); display: inline-block; margin-right: 6px; }
|
|
14
|
+
.dot.ready { background: var(--_ok); } .dot.ringing { background: var(--_warn); animation: pulse 1s infinite; } .dot.in-call { background: var(--_accent); } .dot.error { background: var(--_bad); }
|
|
15
|
+
.recent { list-style: none; margin: 6px 0 0; padding: 0; font-size: 12.5px; color: var(--_muted); }
|
|
16
|
+
@keyframes pulse { 50% { opacity: .35; } }
|
|
17
|
+
`;
|
|
18
|
+
|
|
19
|
+
const STATUS_KEY = { off: 'off', connecting: 'connecting', ready: 'ready', ringing: 'ringing', 'in-call': 'inCall', error: 'error' };
|
|
20
|
+
|
|
21
|
+
/** Pure "recent calls" list with one-click redial; shared with the widget. `calls` is `CallLog#list()`. */
|
|
22
|
+
export function renderRecentCalls(calls, S, { canRedial = true } = {}) {
|
|
23
|
+
if (!calls?.length) return html`<p class="hint">${S.noRecent}</p>`;
|
|
24
|
+
return html`<ul class="recent-list">${calls.map((c, i) => html`<li><button type="button" data-action="redial" data-i="${i}" ${canRedial && c.number ? '' : 'disabled'} aria-label="${t(S, 'redial', { who: c.who })}">
|
|
25
|
+
<span class="${c.outcome === 'missed' && c.direction === 'in' ? 'miss' : ''}">${c.who}</span> <span class="hint">${c.direction === 'in' ? (c.outcome === 'missed' ? S.missed : S.incoming) : S.outgoing}${c.durationMs ? ` · ${formatDuration(c.durationMs)}` : ''}</span></button></li>`)}</ul>`;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** The live-call controls (name, timer, mute, hold, keypad, hang up) shared by the softphone and the widget bar. */
|
|
29
|
+
export function renderCallControls(s, { S, now, canHold, canDtmf, keypadOpen }) {
|
|
30
|
+
return html`<div class="who">${s.caller ?? S.onACall}</div><div class="timer" aria-hidden="true">${s.startedAt ? formatDuration(now - s.startedAt) : ''}${s.held ? html` · ${S.onHold}` : ''}</div>
|
|
31
|
+
<div class="btns"><button type="button" data-action="mute" aria-pressed="${String(Boolean(s.muted))}">${s.muted ? S.unmute : S.mute}</button>${canHold ? html`<button type="button" data-action="hold" aria-pressed="${String(Boolean(s.held))}">${s.held ? S.resume : S.hold}</button>` : ''}${canDtmf ? html`<button type="button" data-action="toggle-keypad" aria-pressed="${String(Boolean(keypadOpen))}">${keypadOpen ? S.hideKeypad : S.showKeypad}</button>` : ''}<button type="button" class="danger" data-action="hangup">${S.hangUp}</button></div>`;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** The notice after a call: "Call ended · 0:42", or "Missed call". */
|
|
35
|
+
export function renderLastCall(s, S) {
|
|
36
|
+
if (!s.lastCall) return '';
|
|
37
|
+
const l = s.lastCall;
|
|
38
|
+
return html`<p class="status" role="status">${l.outcome === 'missed' ? html`${S.missedCall}: ${l.who}` : t(S, 'callEndedFor', { time: formatDuration(l.durationMs) })}</p>`;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Pure view of the softphone. Pass `dp` (a createDialpad state) to get the keypad; without it `allowDial` shows the plain number field. */
|
|
42
|
+
export function renderSoftphone(s, { allowDial = false, now = Date.now(), dial = '', title, S = stringsFor(), dp, canHold = false, canDtmf = false, keypadOpen = false, calls = [], sound, soundOpen = false, voices = [] } = {}) {
|
|
43
|
+
const heading = title ?? S.softphone;
|
|
44
|
+
const label = S[STATUS_KEY[s.status]] ?? softphoneLabel[s.status] ?? s.status;
|
|
45
|
+
return html`<div class="card phone" role="region" aria-label="${heading}">
|
|
46
|
+
<div class="head"><h2>${heading}</h2><span class="pill"><i class="dot ${s.status}"></i>${label}</span></div>
|
|
47
|
+
<div class="sr" role="status" aria-live="polite">${label}${s.caller ? `: ${s.caller}` : ''}</div>
|
|
48
|
+
${s.error ? html`<p class="err" role="alert">${s.error}</p>` : ''}
|
|
49
|
+
${s.warning ? html`<p class="status bad" role="status">${s.warning}</p>` : ''}
|
|
50
|
+
${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>
|
|
51
|
+
<p class="hint">${S.goOnlineHint}</p>` : ''}
|
|
52
|
+
${s.status === 'connecting' ? html`<p class="hint">${S.connecting}</p>` : ''}
|
|
53
|
+
${s.status === 'ready' ? html`
|
|
54
|
+
${renderLastCall(s, S)}
|
|
55
|
+
<p class="hint">${s.sipUsername ? html`${S.waiting} · <b>${s.sipUsername}</b>` : S.waiting}</p>
|
|
56
|
+
${s.placing ? html`<p class="status" role="status">${t(S, 'placing', { number: s.placing.number })}</p>` : ''}
|
|
57
|
+
${allowDial && dp ? renderKeypad(dp, { S, busy: s.dialing }) : ''}
|
|
58
|
+
${allowDial && !dp ? html`<form data-submit="dial"><label for="dial">${S.numberLabel}</label>
|
|
59
|
+
<div class="row"><input id="dial" data-key="dial" type="tel" inputmode="tel" autocomplete="off" placeholder="+18765550100" value="${dial}" /><button class="primary fixed" type="submit" ${s.dialing ? 'disabled' : ''}>${s.dialing ? '…' : S.phone}</button></div></form>` : ''}
|
|
60
|
+
${calls.length ? html`<h3>${S.recent}</h3>${renderRecentCalls(calls, S)}` : ''}
|
|
61
|
+
${sound ? renderSoundOptions(sound, S, { open: soundOpen, voices, idPrefix: 'sp-snd' }) : ''}
|
|
62
|
+
<div class="btns"><button data-action="stop">${S.goOffline}</button></div>` : ''}
|
|
63
|
+
${s.status === 'ringing' ? html`<div class="who">${s.caller}</div><div class="hint">${S.isCalling}</div>
|
|
64
|
+
<div class="btns"><button class="ok" data-action="answer">${S.answer}</button><button class="danger" data-action="hangup">${S.decline}</button></div>` : ''}
|
|
65
|
+
${s.status === 'in-call' ? html`${renderCallControls(s, { S, now, canHold, canDtmf, keypadOpen })}${keypadOpen && dp ? renderKeypad(dp, { S, mode: 'dtmf' }) : ''}` : ''}
|
|
66
|
+
${s.recent?.length ? html`<h3>${S.recent}</h3><ul class="recent">${s.recent.map((e) => html`<li>${e.type}</li>`)}</ul>` : ''}
|
|
67
|
+
</div>`.toString();
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* `<traitos-softphone>` — take (and place) calls in the browser.
|
|
72
|
+
*
|
|
73
|
+
* el.client = new TraitOSClient({ baseUrl, token }); // a browser token with the `softphone` scope
|
|
74
|
+
* el.adapter = telnyxAdapter(TelnyxRTC, { remoteElement });
|
|
75
|
+
* el.addEventListener('traitos-state', (e) => console.log(e.detail.status));
|
|
76
|
+
*
|
|
77
|
+
* Attributes: `allow-dial` (shows the keypad), `live-events` (needs the `events` scope too), `auto-start`, `theme="dark|light"`.
|
|
78
|
+
* Properties: `numbers` limits which lines ring here; `caps` ({whatsappCallingEnabled, phoneCallingEnabled}; found from the
|
|
79
|
+
* workspace's phone lines when not set); `strings` overrides the wording; `whatsapp` holds what a WhatsApp call needs.
|
|
80
|
+
* Events: `traitos-state` ({status, caller, held, ...}), `traitos-call` ({number, channel}), `traitos-error`.
|
|
81
|
+
*/
|
|
82
|
+
export class TraitOSSoftphone extends PhoneBase {
|
|
83
|
+
get css() { return css; }
|
|
84
|
+
|
|
85
|
+
render() {
|
|
86
|
+
const S = this.S;
|
|
87
|
+
const c = this.controller;
|
|
88
|
+
const s = c?.snapshot() ?? { status: 'off', error: this._client && this._adapter ? null : S.needSetup, recent: [] };
|
|
89
|
+
return renderSoftphone(s, { allowDial: this.hasAttribute('allow-dial'), dial: this._dial ?? '', S, dp: this.dp, now: Date.now(), canHold: !!c?.canHold, canDtmf: !!c?.canDtmf, keypadOpen: this.keypadOpen, calls: this.recentCalls(), sound: this.sound, soundOpen: this._sndOpen, voices: this.sound.voices() });
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
onClick(action, node) {
|
|
93
|
+
if (this.phoneClick(action, node)) return;
|
|
94
|
+
const c = this.controller;
|
|
95
|
+
if (c && action === 'dial') { const v = cleanDialInput(node.querySelector?.('[data-key="dial"]')?.value ?? this._dial); this._dial = v; c.dial(v).then((ok) => { if (ok) this._dial = ''; this.requestRender(); }); }
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
onInput(target) { if (target.dataset.key === 'dial') this._dial = cleanDialInput(target.value); else super.onInput(target); }
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
define('traitos-softphone', TraitOSSoftphone);
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { html } from '../html.js';
|
|
2
|
+
import { KEY_TONES, RINGTONES } from '../core/sound.js';
|
|
3
|
+
|
|
4
|
+
const KEY_LABEL = { dtmf: 'keyToneDtmf', click: 'keyToneClick', off: 'keyToneOff' };
|
|
5
|
+
const RING_LABEL = { classic: 'ringClassic', soft: 'ringSoft', off: 'ringOff' };
|
|
6
|
+
|
|
7
|
+
/** Pure view of the sound options (key sound, volume, ringtone, spoken digits and voice). `voices` is `sound.voices()`. */
|
|
8
|
+
export function renderSoundOptions(sound, S, { open = false, voices = [], idPrefix = 'snd' } = {}) {
|
|
9
|
+
const s = sound.settings;
|
|
10
|
+
const id = (n) => `${idPrefix}-${n}`;
|
|
11
|
+
return html`<div class="snd">
|
|
12
|
+
<button type="button" class="snd-toggle" data-action="snd-toggle" aria-expanded="${String(Boolean(open))}" aria-controls="${id('panel')}">${s.enabled ? '🔊' : '🔇'} ${S.sound}</button>
|
|
13
|
+
${open ? html`<div class="snd-panel" id="${id('panel')}" role="group" aria-label="${S.sound}">
|
|
14
|
+
<label class="snd-check"><input type="checkbox" data-key="snd-enabled" ${s.enabled ? 'checked' : ''} />${S.soundOn}</label>
|
|
15
|
+
<label for="${id('vol')}">${S.volume}</label>
|
|
16
|
+
<input id="${id('vol')}" type="range" min="0" max="1" step="0.05" data-key="snd-volume" value="${s.volume}" aria-valuetext="${Math.round(s.volume * 100)}%" />
|
|
17
|
+
<label for="${id('key')}">${S.keyTone}</label>
|
|
18
|
+
<select id="${id('key')}" data-key="snd-keyTone">${KEY_TONES.map((k) => html`<option value="${k}" ${s.keyTone === k ? 'selected' : ''}>${S[KEY_LABEL[k]]}</option>`)}</select>
|
|
19
|
+
<label for="${id('ring')}">${S.ringtone}</label>
|
|
20
|
+
<select id="${id('ring')}" data-key="snd-ringtone">${Object.keys(RINGTONES).map((k) => html`<option value="${k}" ${s.ringtone === k ? 'selected' : ''}>${S[RING_LABEL[k]]}</option>`)}</select>
|
|
21
|
+
<label class="snd-check"><input type="checkbox" data-key="snd-speak" ${s.speak ? 'checked' : ''} />${S.speakDigits}</label>
|
|
22
|
+
${s.speak ? html`<label for="${id('voice')}">${S.voice}</label>
|
|
23
|
+
<select id="${id('voice')}" data-key="snd-voice"><option value="">${S.voiceDefault}</option>${voices.map((v) => html`<option value="${v.id}" ${s.voice === v.id ? 'selected' : ''}>${v.label}</option>`)}</select>
|
|
24
|
+
<label for="${id('rate')}">${S.voiceRate}</label>
|
|
25
|
+
<input id="${id('rate')}" type="range" min="0.5" max="2" step="0.1" data-key="snd-rate" value="${s.rate}" aria-valuetext="${s.rate}×" />` : ''}
|
|
26
|
+
<div class="btns"><button type="button" data-action="snd-test">${S.soundTest}</button></div>
|
|
27
|
+
</div>` : ''}
|
|
28
|
+
</div>`;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Apply an edit from one of the controls above to a sound object. Returns true when the target was a sound control. */
|
|
32
|
+
export function applySoundEdit(sound, target) {
|
|
33
|
+
const key = target?.dataset?.key;
|
|
34
|
+
if (!key || !key.startsWith('snd-')) return false;
|
|
35
|
+
const name = key.slice(4);
|
|
36
|
+
const value = target.type === 'checkbox' ? !!target.checked : (name === 'volume' || name === 'rate') ? Number(target.value) : target.value;
|
|
37
|
+
sound.update({ [name]: value });
|
|
38
|
+
return true;
|
|
39
|
+
}
|
package/src/html.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tiny HTML templating with escaping by default: every interpolated value is escaped unless it is explicitly marked `raw`
|
|
3
|
+
* (or is itself the result of `html`). Customer data (caller names, flow labels, error text) can never inject markup.
|
|
4
|
+
*/
|
|
5
|
+
const ESC = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' };
|
|
6
|
+
|
|
7
|
+
export const escapeHtml = (value) => String(value ?? '').replace(/[&<>"']/g, (c) => ESC[c]);
|
|
8
|
+
|
|
9
|
+
class SafeHtml {
|
|
10
|
+
constructor(value) { this.value = value; }
|
|
11
|
+
toString() { return this.value; }
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** Mark a string as already-safe markup. Only use on strings you built from `html` or constants. */
|
|
15
|
+
export const raw = (value) => new SafeHtml(String(value));
|
|
16
|
+
|
|
17
|
+
const part = (v) => (v instanceof SafeHtml ? v.value : Array.isArray(v) ? v.map(part).join('') : v === false || v === null || v === undefined ? '' : escapeHtml(v));
|
|
18
|
+
|
|
19
|
+
/** `html\`<b>${userText}</b>\`` -> SafeHtml with `userText` escaped. Arrays are joined; false/null/undefined render nothing. */
|
|
20
|
+
export function html(strings, ...values) {
|
|
21
|
+
let out = strings[0];
|
|
22
|
+
for (let i = 0; i < values.length; i++) out += part(values[i]) + strings[i + 1];
|
|
23
|
+
return new SafeHtml(out);
|
|
24
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @cognitiv-traits/traitos-ui — drop-in TraitOS elements and the pure logic behind them.
|
|
3
|
+
*
|
|
4
|
+
* import '@cognitiv-traits/traitos-ui'; // registers <traitos-softphone>, <traitos-dialer-widget>, <traitos-keypad>, <traitos-settings>, <traitos-flow-builder>
|
|
5
|
+
*
|
|
6
|
+
* The elements are framework-free web components. Everything they do lives in plain controllers (`core/`) that you can use
|
|
7
|
+
* directly to build your own UI in React, Vue or anything else.
|
|
8
|
+
*/
|
|
9
|
+
export { html, raw, escapeHtml } from './html.js';
|
|
10
|
+
export { baseCss } from './theme.js';
|
|
11
|
+
export { TraitElement, define } from './elements/base.js';
|
|
12
|
+
export { TraitOSSoftphone, renderSoftphone, renderRecentCalls, renderCallControls } from './elements/softphone.js';
|
|
13
|
+
export { TraitOSDialerWidget, renderWidget } from './elements/dialerWidget.js';
|
|
14
|
+
export { TraitOSKeypad, renderKeypad } from './elements/keypad.js';
|
|
15
|
+
export { PhoneBase } from './elements/phoneBase.js';
|
|
16
|
+
export { TraitOSSettings, renderSettings } from './elements/settings.js';
|
|
17
|
+
export { TraitOSFlowBuilder, renderFlowBuilder } from './elements/flowBuilder.js';
|
|
18
|
+
|
|
19
|
+
export { SoftphoneController } from './core/softphoneController.js';
|
|
20
|
+
export { SettingsController } from './core/settingsController.js';
|
|
21
|
+
export { FlowBuilderController } from './core/flowBuilderController.js';
|
|
22
|
+
export { createDialpad, sanitizeNumber, digitsOf, canCall, enabledChannels, defaultChannel, capsFromLines, MIN_DIGITS, KEYS } from './core/dialpad.js';
|
|
23
|
+
export { DEFAULT_STRINGS, setDefaultStrings, stringsFor, t } from './core/strings.js';
|
|
24
|
+
export { createSound, normalizeSound, DTMF_FREQ, DEFAULT_SOUND, KEY_TONES, RINGTONES } from './core/sound.js';
|
|
25
|
+
export { renderSoundOptions } from './elements/soundOptions.js';
|
|
26
|
+
export { CallLog } from './core/callLog.js';
|
|
27
|
+
export { placementOf, panelSide, createOpenState, iconLabel, CORNERS } from './core/widgetState.js';
|
|
28
|
+
export { normalizePrefs, registrationFor, loadPrefs, savePrefs, storedPrefs } from './core/dialerPrefs.js';
|
|
29
|
+
export { telnyxAdapter } from './core/telnyxAdapter.js';
|
|
30
|
+
export { TokenManager } from './core/tokenManager.js';
|
|
31
|
+
export * from './core/softphoneState.js';
|
|
32
|
+
export * from './core/flowModel.js';
|
|
33
|
+
export { SECTIONS } from './core/settingsSections.js';
|
|
34
|
+
|
|
35
|
+
/** Register every element (they also register themselves on import). */
|
|
36
|
+
export function defineAll() { /* importing this module already did it */ }
|