/** * Delegated listener that binds exactly once. * * modal_footer.php re-loads this file every time an ajax modal opens, which is * why the jQuery originals used a namespaced .off().on() - without it the * handlers stacked up and fired once per modal ever opened. The named flag on * window is the vanilla equivalent. `this` is the matched element, matching * jQuery's delegation contract so the handler bodies are unchanged. */ /** * Run one initialiser in isolation. * * itflowInit() sets up eight independent libraries in sequence. Without this, * a throw in any one of them aborts the whole function and every initialiser * after it silently never runs - which is exactly the kind of failure that * looks like "everything is broken" while the console shows one error from a * library you were not looking at. */ function itflowStep(name, fn) { try { fn(); } catch (e) { console.error('itflow init [' + name + '] failed:', e); } } /** * Typing / in a reply box offers the canned responses of the picker above it * (agent/includes/inc_canned_response_picker.php) - its textarea names the * picker in data-canned-picker. The list narrows as you type after the /; * picking one takes the / and what was typed out again and puts the response * in, as the picker does (agent/js/canned_response_picker.js). Called from the * reply editors' setup, so it is there before the editor is drawn. */ function itflowCannedAutocompleter(editor) { var element = editor.getElement ? editor.getElement() : null; var pickerId = element && element.dataset ? element.dataset.cannedPicker : ''; if (!pickerId) { return; } editor.ui.registry.addAutocompleter('itflowCanned', { trigger: '/', minChars: 0, columns: 1, highlightOn: ['canned_name'], fetch: function (pattern) { var picker = document.getElementById(pickerId); var words = String(pattern || '').toLowerCase().split(/\s+/).filter(Boolean); var items = picker ? Array.prototype.slice.call(picker.querySelectorAll('[data-canned-id]')) : []; var seen = {}; return Promise.resolve(items.filter(function (item) { if (seen[item.dataset.cannedId]) { return false; } seen[item.dataset.cannedId] = true; return words.every(function (word) { return item.dataset.cannedSearchText.indexOf(word) !== -1; }); }).slice(0, 8).map(function (item) { return { type: 'cardmenuitem', value: item.dataset.cannedId, label: item.dataset.cannedName, items: [{ type: 'cardcontainer', direction: 'vertical', items: [ { type: 'cardtext', text: item.dataset.cannedName, name: 'canned_name', classes: ['itflow-canned-ac-name'] }, { type: 'cardtext', text: (item.dataset.cannedPreview || '').slice(0, 90), classes: ['itflow-canned-ac-preview'] } ] }] }; })); }, onAction: function (api, range, value) { api.hide(); editor.selection.setRng(range); editor.insertContent(''); if (window.itflowCannedPick) { window.itflowCannedPick(pickerId, value); } } }); } /** * @ in an internal note offers the agents who can open the ticket - its * textarea carries them in data-mention-agents (ticketMentionAgentsAttr(), * functions/ticket_mention.php). The list narrows as you type a name or role * after the @; picking one puts in a mention the editor treats as one piece, * and saving the note tells them. Only while the note is internal - the form's * reply type says which - and a public reply holding mentions says they are * plain text there. Called from the reply editors' setup. */ function itflowMentionAutocompleter(editor) { var element = editor.getElement ? editor.getElement() : null; var raw = element && element.dataset ? element.dataset.mentionAgents : ''; if (!raw) { return; } var agents = []; try { agents = JSON.parse(raw) || []; } catch (e) { return; } var form = element.form || element.closest('form'); // Internal: the composer's Internal note, or the edit window's Internal - or no choice on the form at all function internal() { var picked = form ? form.querySelector('input[name="public_reply_type"]:checked, input[name="ticket_reply_type"]:checked') : null; return !picked || picked.value === '0' || picked.value === 'Internal'; } // The hint while it is internal; the warning when a public one holds mentions function showState() { if (!form) { return; } var body = editor.getBody ? editor.getBody() : null; var has = !!(body && body.querySelector('.itflow-mention')); var hint = form.querySelector('[data-mention-hint]'); var warn = form.querySelector('[data-mention-public]'); if (hint) { hint.hidden = !internal(); } if (warn) { warn.hidden = internal() || !has; } } editor.ui.registry.addAutocompleter('itflowMention', { trigger: '@', minChars: 0, columns: 1, highlightOn: ['mention_name'], fetch: function (pattern) { if (!internal()) { return Promise.resolve([]); } var words = String(pattern || '').toLowerCase().split(/\s+/).filter(Boolean); return Promise.resolve(agents.filter(function (agent) { var text = (agent.name + ' ' + (agent.role || '')).toLowerCase(); return words.every(function (word) { return text.indexOf(word) !== -1; }); }).slice(0, 8).map(function (agent) { return { type: 'cardmenuitem', value: String(agent.id), label: agent.name, items: [{ type: 'cardcontainer', direction: 'horizontal', align: 'left', valign: 'middle', items: [ agent.avatar ? { type: 'cardimage', src: agent.avatar, alt: '', classes: ['itflow-mention-ac-avatar'] } : { type: 'cardtext', text: agent.initials || '?', classes: ['itflow-mention-ac-initials'] }, { type: 'cardcontainer', direction: 'vertical', items: [ { type: 'cardtext', text: agent.name, name: 'mention_name', classes: ['itflow-mention-ac-name'] }, { type: 'cardtext', text: agent.role || '', classes: ['itflow-mention-ac-role'] } ] } ] }] }; })); }, onAction: function (api, range, value) { api.hide(); var agent = agents.filter(function (a) { return String(a.id) === String(value); })[0]; if (!agent) { return; } editor.selection.setRng(range); editor.insertContent('@' + editor.dom.encode(agent.name) + ' '); showState(); } }); editor.on('init SetContent NodeChange input', showState); if (form && !form.dataset.mentionWatch) { form.dataset.mentionWatch = '1'; form.addEventListener('change', function (e) { if (e.target && (e.target.name === 'public_reply_type' || e.target.name === 'ticket_reply_type')) { showState(); } }); } } /* * Reword with AI - on an editor only when AI is set up for it and the agent's * role may use it: window.itflowAi, printed by includes/footer.php from * aiClientConfig() (functions/ai.php). The ticket editor asks the Tickets * model. The button rewords; its menu has the other tones (shorter, more * formal, friendlier, plain English, organized, just spelling and grammar) * and Translate, which asks which language - the last one picked comes first * next time. The answer replaces the text in one step, so Undo puts it back. * A textarea's data-ai-client-id says the client it is for, for AI Usage. */ function itflowAiOn(ticket) { var ai = window.itflowAi || null; return !!(ai && (ticket ? ai.rewordTicket : ai.reword)); } function itflowAiReword(editor, ticket) { if (!itflowAiOn(ticket)) { return; } var ai = window.itflowAi; var buttonApi = null; var say = function (text, type) { editor.notificationManager.open({ text: text, type: type, timeout: type === 'success' ? 4000 : 8000 }); }; var done = { reword: 'Reworded', shorter: 'Shortened', formal: 'Made more formal', friendly: 'Made friendlier', plain: 'Put in plain English', structure: 'Organized', proofread: 'Spelling and grammar fixed', translate: 'Translated' }; function run(tone, language) { if (editor.getContent({ format: 'text' }).trim() === '') { say('Write something first - Reword works on what is there.', 'info'); return; } var element = editor.getElement(); var clientId = element ? parseInt(element.getAttribute('data-ai-client-id') || '0', 10) : 0; buttonApi.setEnabled(false); editor.setProgressState(true); fetch(ai.endpoint + '?ai_reword' + (ticket ? '&use_case=Tickets' : ''), { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text: editor.getContent(), client_id: clientId || 0, tone: tone, language: language || '' }) }) .then(function (response) { return response.json().catch(function () { throw new Error('HTTP ' + response.status); }); }) .then(function (data) { // Leave the user's text alone if it failed if (data.error || !data.rewordedText) { say(data.error || 'Could not reword the text.', 'error'); return; } editor.undoManager.add(); editor.undoManager.transact(function () { editor.setContent(data.rewordedText); }); say((done[tone] || 'Reworded') + (tone === 'translate' ? ' into ' + language : '') + ' - Undo puts your words back.', 'success'); }) .catch(function () { say('Could not reach ITFlow to reword it - try again.', 'error'); }) .finally(function () { editor.setProgressState(false); buttonApi.setEnabled(true); }); } function translate() { var languages = ai.languages || ['English']; var last = ''; try { last = localStorage.getItem('itflowAiLanguage') || ''; } catch (e) { last = ''; } editor.windowManager.open({ title: 'Translate with AI', body: { type: 'panel', items: [{ type: 'selectbox', name: 'language', label: 'Into', items: languages.map(function (language) { return { text: language, value: language }; }) }] }, initialData: { language: languages.indexOf(last) >= 0 ? last : languages[0] }, buttons: [{ type: 'cancel', text: 'Cancel' }, { type: 'submit', text: 'Translate', primary: true }], onSubmit: function (dialog) { var language = dialog.getData().language; dialog.close(); try { localStorage.setItem('itflowAiLanguage', language); } catch (e) { // Remembering it is only a convenience } run('translate', language); } }); } editor.ui.registry.addSplitButton('reword', { icon: 'ai', tooltip: 'Reword with AI', onAction: function () { run('reword'); }, onItemAction: function (api, value) { if (value === 'translate') { translate(); } else { run(value); } }, fetch: function (callback) { var tones = ai.tones || { reword: 'Reword' }; callback(Object.keys(tones).map(function (tone) { return { type: 'choiceitem', text: tones[tone], value: tone }; })); }, onSetup: function (api) { buttonApi = api; return function () {}; } }); // Draft a reply - on the ticket reply editor, whose textarea says the ticket var element = editor.getElement(); var ticketId = element ? parseInt(element.getAttribute('data-ai-ticket-id') || '0', 10) : 0; if (ticket && ticketId && ai.draft) { itflowAiDraft(editor, ticketId, say); } } /* * Draft with AI - the next reply on the ticket, from what the agent has typed * so far (notes, a line or nothing), for who will read it: the reply type * picked in its form - an internal note, a public note or an email. It * replaces the editor's text in one step, so Undo puts it back. */ function itflowAiDraft(editor, ticketId, say) { var buttonApi = null; var types = { '0': 'internal', '1': 'public', '2': 'email' }; editor.ui.registry.addButton('aidraft', { icon: 'ai-prompt', text: 'Draft', tooltip: 'Draft the reply with AI - from your notes, if you have typed some', onAction: function () { var form = editor.getElement().closest('form'); var picked = form ? form.querySelector('input[name="public_reply_type"]:checked') : null; var notes = editor.getContent({ format: 'text' }).trim() === '' ? '' : editor.getContent(); buttonApi.setEnabled(false); editor.setProgressState(true); fetch(window.itflowAi.endpoint + '?ai_ticket_draft', { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ticket_id: ticketId, notes: notes, type: types[picked ? picked.value : '2'] || 'email' }) }) .then(function (response) { return response.json().catch(function () { throw new Error('HTTP ' + response.status); }); }) .then(function (data) { if (data.error || !data.html) { say(data.error || 'Could not draft it.', 'error'); return; } editor.undoManager.add(); editor.undoManager.transact(function () { editor.setContent(data.html); }); say('Drafted - read it through before it goes. Undo puts back what was there.', 'success'); }) .catch(function () { say('Could not reach ITFlow to draft it - try again.', 'error'); }) .finally(function () { editor.setProgressState(false); buttonApi.setEnabled(true); }); }, onSetup: function (api) { buttonApi = api; return function () {}; } }); } /** * TinyMCE skin options for the current colour mode. * * TinyMCE renders its chrome in its own DOM and its content inside an iframe, * so it inherits nothing from the page - a dark page still got a white editor. * Both the oxide-dark UI skin and the dark content stylesheet are already * vendored under libs/tinymce/skins, so this only has to point at them. */ function itflowTinyMceSkin() { var dark = document.documentElement.getAttribute('data-bs-theme') === 'dark'; var root = getComputedStyle(document.documentElement); var body = getComputedStyle(document.body); function v(name, fallback) { var value = root.getPropertyValue(name).trim(); return value || fallback; } // The editing surface lives in an iframe, so no page CSS reaches it and // custom properties do not cross the boundary either - the values have to // be read here and passed through as literal text. Without this the editor // keeps TinyMCE's own blue-slate dark (#222f3e) next to the app's neutral // grey (#212529), which is close enough to look like a mistake. var contentStyle = 'body{' + 'background-color:' + v('--bs-body-bg', '#fff') + ';' + 'color:' + v('--bs-body-color', '#212529') + ';' + 'font-family:' + body.fontFamily + ';' + 'font-size:' + body.fontSize + ';' + '}' + 'a{color:' + v('--itflow-accent', '#007bff') + ';}' + 'table td,table th{border-color:' + v('--bs-border-color', '#dee2e6') + ';}' + // An @mention (functions/ticket_mention.php) - as it shows on the ticket '.itflow-mention{color:' + v('--itflow-accent', '#007bff') + ';background-color:color-mix(in srgb,' + v('--itflow-accent', '#007bff') + ' 12%,transparent);' + 'border-radius:.25rem;padding:0 .25em;font-weight:500;white-space:nowrap;}'; return { skin: dark ? 'oxide-dark' : 'oxide', content_css: dark ? 'dark' : 'default', content_style: contentStyle }; } /** * Chart.js defaults for the current colour mode. * * Charts are drawn to a , so no CSS reaches them - every colour has to * be handed to Chart.js as a literal. The pages used to hardcode * Chart.defaults.color = '#292b2c', which was fine while the cards were * effectively light but is invisible on a real dark background. * * Returns the axis/grid colour too, since the charts set that per-scale. */ function itflowChartDefaults() { var root = getComputedStyle(document.documentElement); var body = getComputedStyle(document.body); function v(name, fallback) { return (root.getPropertyValue(name) || '').trim() || fallback; } var text = v('--bs-body-color', '#292b2c'); var grid = v('--bs-border-color', 'rgba(0, 0, 0, .125)'); if (window.Chart) { Chart.defaults.font.family = body.fontFamily; Chart.defaults.color = text; Chart.defaults.borderColor = grid; } return { text: text, grid: grid }; } function itflowBindOnce(name, type, selector, handler) { window.itflowBound = window.itflowBound || {}; if (window.itflowBound[name]) { return; } window.itflowBound[name] = true; document.addEventListener(type, function (e) { const match = e.target.closest(selector); if (match) { handler.call(match, e); } }); } /** * Run fn once the DOM is ready, the way jQuery's .ready() did. * * js/ajax_modal.js injects a modal payload's