chatwoot-ai-tools.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. (() => {
  2. 'use strict';
  3. if (window.__EKS_CHATWOOT_AI_TOOLS__) return;
  4. window.__EKS_CHATWOOT_AI_TOOLS__ = true;
  5. const RELAY_ORIGIN = new URL(document.currentScript?.src || 'https://eks-relay.easyklima.com/chatwoot-ai-tools.js').origin;
  6. const STORE_KEY = 'eksAgentUiToken';
  7. const LANG_KEY = 'eksAgentUiTargetLanguage';
  8. const PANEL_ID = 'eks-ai-translate-panel';
  9. const BUTTON_ID = 'eks-ai-translate-toggle';
  10. const state = {
  11. busy: false,
  12. result: '',
  13. error: '',
  14. };
  15. function t(s) { return s; }
  16. function ensureStyles() {
  17. if (document.getElementById('eks-ai-translate-styles')) return;
  18. const style = document.createElement('style');
  19. style.id = 'eks-ai-translate-styles';
  20. style.textContent = `
  21. #${BUTTON_ID} {
  22. position: fixed; right: 18px; bottom: 18px; z-index: 2147483000;
  23. border: 0; border-radius: 999px; padding: 10px 14px;
  24. background: #1f6feb; color: white; font: 600 13px system-ui, sans-serif;
  25. box-shadow: 0 8px 22px rgba(15,23,42,.25); cursor: pointer;
  26. }
  27. #${PANEL_ID} {
  28. position: fixed; right: 18px; bottom: 66px; z-index: 2147483000;
  29. width: min(420px, calc(100vw - 36px)); max-height: min(720px, calc(100vh - 92px));
  30. overflow: auto; background: #fff; color: #0f172a; border: 1px solid #d7dee8;
  31. border-radius: 14px; box-shadow: 0 18px 48px rgba(15,23,42,.28);
  32. padding: 14px; font: 13px system-ui, sans-serif;
  33. }
  34. #${PANEL_ID}[hidden] { display: none; }
  35. #${PANEL_ID} h3 { margin: 0 0 10px; font-size: 15px; }
  36. #${PANEL_ID} label { display: block; margin: 10px 0 4px; font-weight: 600; }
  37. #${PANEL_ID} input, #${PANEL_ID} textarea, #${PANEL_ID} select {
  38. width: 100%; box-sizing: border-box; border: 1px solid #cbd5e1; border-radius: 8px;
  39. padding: 8px; font: 13px system-ui, sans-serif; background: #fff; color: #0f172a;
  40. }
  41. #${PANEL_ID} textarea { min-height: 88px; resize: vertical; }
  42. #${PANEL_ID} .eks-row { display: flex; gap: 8px; align-items: center; }
  43. #${PANEL_ID} .eks-row > * { flex: 1; }
  44. #${PANEL_ID} button {
  45. border: 0; border-radius: 8px; padding: 8px 10px; background: #1f6feb; color: white;
  46. font: 600 13px system-ui, sans-serif; cursor: pointer;
  47. }
  48. #${PANEL_ID} button.secondary { background: #e2e8f0; color: #0f172a; }
  49. #${PANEL_ID} button.danger { background: #b91c1c; }
  50. #${PANEL_ID} button:disabled { opacity: .55; cursor: wait; }
  51. #${PANEL_ID} .eks-muted { color: #64748b; font-size: 12px; }
  52. #${PANEL_ID} .eks-error { color: #b91c1c; white-space: pre-wrap; }
  53. #${PANEL_ID} .eks-result { background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; padding: 10px; white-space: pre-wrap; min-height: 44px; }
  54. .eks-inline-translate {
  55. margin-left: 6px !important; border: 0 !important; border-radius: 999px !important;
  56. padding: 3px 7px !important; background: #e0f2fe !important; color: #075985 !important;
  57. font: 600 11px system-ui, sans-serif !important; cursor: pointer !important;
  58. }
  59. `;
  60. document.head.appendChild(style);
  61. }
  62. function makeUi() {
  63. ensureStyles();
  64. if (!document.getElementById(BUTTON_ID)) {
  65. const toggle = document.createElement('button');
  66. toggle.id = BUTTON_ID;
  67. toggle.type = 'button';
  68. toggle.textContent = 'AI tłumacz';
  69. toggle.addEventListener('click', () => {
  70. const panel = document.getElementById(PANEL_ID);
  71. panel.hidden = !panel.hidden;
  72. if (!panel.hidden) fillSelectedText();
  73. });
  74. document.body.appendChild(toggle);
  75. }
  76. if (document.getElementById(PANEL_ID)) return;
  77. const panel = document.createElement('section');
  78. panel.id = PANEL_ID;
  79. panel.hidden = true;
  80. panel.innerHTML = `
  81. <h3>${t('EKS AI tłumaczenia')}</h3>
  82. <div class="eks-muted">Token operatora jest zapisany tylko w tej przeglądarce. OpenAI/Flowise sekrety zostają po stronie EKSRelay.</div>
  83. <label>Agent UI token</label>
  84. <input data-eks="token" type="password" autocomplete="off" placeholder="Wklej token operatora" />
  85. <div class="eks-row">
  86. <div>
  87. <label>Język docelowy</label>
  88. <input data-eks="target" value="pl" placeholder="pl, en, de, cs..." />
  89. </div>
  90. <div>
  91. <label>Źródłowy</label>
  92. <input data-eks="source" value="auto" placeholder="auto" />
  93. </div>
  94. </div>
  95. <label>Tekst do tłumaczenia</label>
  96. <textarea data-eks="text" placeholder="Zaznacz tekst wiadomości albo wklej go tutaj"></textarea>
  97. <div class="eks-row" style="margin-top:8px">
  98. <button data-eks="selected" type="button">Tłumacz wiadomość</button>
  99. <button data-eks="draft" type="button">Tłumacz draft</button>
  100. </div>
  101. <div class="eks-row" style="margin-top:8px">
  102. <button data-eks="fill-selected" class="secondary" type="button">Wstaw zaznaczenie</button>
  103. <button data-eks="copy" class="secondary" type="button">Kopiuj wynik</button>
  104. <button data-eks="close" class="secondary" type="button">Zamknij</button>
  105. </div>
  106. <label>Wynik</label>
  107. <div data-eks="result" class="eks-result"></div>
  108. <div data-eks="error" class="eks-error"></div>
  109. `;
  110. document.body.appendChild(panel);
  111. const token = panel.querySelector('[data-eks="token"]');
  112. const target = panel.querySelector('[data-eks="target"]');
  113. token.value = localStorage.getItem(STORE_KEY) || '';
  114. target.value = localStorage.getItem(LANG_KEY) || 'pl';
  115. token.addEventListener('change', () => localStorage.setItem(STORE_KEY, token.value.trim()));
  116. target.addEventListener('change', () => localStorage.setItem(LANG_KEY, target.value.trim() || 'pl'));
  117. panel.querySelector('[data-eks="fill-selected"]').addEventListener('click', fillSelectedText);
  118. panel.querySelector('[data-eks="selected"]').addEventListener('click', () => translate('message'));
  119. panel.querySelector('[data-eks="draft"]').addEventListener('click', () => translate('draft'));
  120. panel.querySelector('[data-eks="copy"]').addEventListener('click', copyResult);
  121. panel.querySelector('[data-eks="close"]').addEventListener('click', () => { panel.hidden = true; });
  122. }
  123. function panelField(name) {
  124. return document.querySelector(`#${PANEL_ID} [data-eks="${name}"]`);
  125. }
  126. function fillSelectedText() {
  127. const selected = String(window.getSelection?.() || '').trim();
  128. if (selected) panelField('text').value = selected;
  129. else {
  130. const draft = getDraftText();
  131. if (draft) panelField('text').value = draft;
  132. }
  133. }
  134. function getDraftText() {
  135. const active = document.activeElement;
  136. if (active && (active.tagName === 'TEXTAREA' || active.tagName === 'INPUT')) return active.value || '';
  137. if (active?.isContentEditable) return active.innerText || active.textContent || '';
  138. const candidate = document.querySelector('[contenteditable="true"][role="textbox"], textarea');
  139. return candidate ? (candidate.value || candidate.innerText || candidate.textContent || '') : '';
  140. }
  141. async function translate(mode) {
  142. const token = panelField('token').value.trim();
  143. const targetLanguage = panelField('target').value.trim() || 'pl';
  144. const sourceLanguageRaw = panelField('source').value.trim();
  145. let text = panelField('text').value.trim();
  146. if (mode === 'draft' && !text) text = getDraftText().trim();
  147. if (!token) return showError('Brak Agent UI token.');
  148. if (!text) return showError('Brak tekstu do tłumaczenia.');
  149. localStorage.setItem(STORE_KEY, token);
  150. localStorage.setItem(LANG_KEY, targetLanguage);
  151. setBusy(true);
  152. showError('');
  153. panelField('result').textContent = '';
  154. try {
  155. const endpoint = mode === 'draft' ? '/agent-tools/translate-draft' : '/agent-tools/translate-message';
  156. const payload = {
  157. targetLanguage,
  158. sourceLanguage: sourceLanguageRaw && sourceLanguageRaw !== 'auto' ? sourceLanguageRaw : undefined,
  159. conversationId: detectConversationId(),
  160. ...(mode === 'draft' ? { draftText: text } : { sourceText: text, messageId: detectMessageId() }),
  161. };
  162. const res = await fetch(`${RELAY_ORIGIN}${endpoint}`, {
  163. method: 'POST',
  164. headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
  165. body: JSON.stringify(payload),
  166. });
  167. const json = await res.json().catch(() => null);
  168. if (!res.ok || !json?.ok) throw new Error(json?.message || `HTTP ${res.status}`);
  169. state.result = json.translatedText || '';
  170. panelField('result').textContent = state.result + (json.cached ? '\n\n[cached]' : '');
  171. } catch (err) {
  172. showError(err instanceof Error ? err.message : String(err));
  173. } finally {
  174. setBusy(false);
  175. }
  176. }
  177. function detectConversationId() {
  178. const m = location.pathname.match(/conversations\/(\d+)/) || location.hash.match(/conversations\/(\d+)/);
  179. return m ? Number(m[1]) : undefined;
  180. }
  181. function detectMessageId() {
  182. const el = window.getSelection?.()?.anchorNode?.parentElement?.closest?.('[data-message-id], [data-id]');
  183. return el?.getAttribute('data-message-id') || el?.getAttribute('data-id') || undefined;
  184. }
  185. async function copyResult() {
  186. if (!state.result) return;
  187. await navigator.clipboard.writeText(state.result);
  188. }
  189. function showError(msg) {
  190. state.error = msg;
  191. const el = panelField('error');
  192. if (el) el.textContent = msg;
  193. }
  194. function setBusy(busy) {
  195. state.busy = busy;
  196. document.querySelectorAll(`#${PANEL_ID} button`).forEach((btn) => { btn.disabled = busy; });
  197. }
  198. function addInlineButtons() {
  199. const candidates = document.querySelectorAll('[data-message-id]:not([data-eks-ai-bound]), .message-bubble:not([data-eks-ai-bound]), [class*="message"]:not([data-eks-ai-bound])');
  200. candidates.forEach((el) => {
  201. const text = (el.innerText || '').trim();
  202. if (text.length < 12 || text.length > 5000) return;
  203. el.setAttribute('data-eks-ai-bound', '1');
  204. const btn = document.createElement('button');
  205. btn.type = 'button';
  206. btn.className = 'eks-inline-translate';
  207. btn.textContent = 'AI→PL';
  208. btn.addEventListener('click', (e) => {
  209. e.preventDefault(); e.stopPropagation();
  210. const panel = document.getElementById(PANEL_ID);
  211. panel.hidden = false;
  212. panelField('target').value = localStorage.getItem(LANG_KEY) || 'pl';
  213. panelField('text').value = text;
  214. });
  215. el.appendChild(btn);
  216. });
  217. }
  218. function boot() {
  219. if (!document.body) return setTimeout(boot, 200);
  220. makeUi();
  221. addInlineButtons();
  222. const obs = new MutationObserver(() => addInlineButtons());
  223. obs.observe(document.body, { childList: true, subtree: true });
  224. }
  225. boot();
  226. })();