chat-no-jquery.coffee 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677
  1. do(window) ->
  2. scripts = document.getElementsByTagName('script')
  3. # search for script to get protocol and hostname for ws connection
  4. myScript = scripts[scripts.length - 1]
  5. scriptProtocol = window.location.protocol.replace(':', '') # set default protocol
  6. if myScript && myScript.src
  7. scriptHost = myScript.src.match('.*://([^:/]*).*')[1]
  8. scriptProtocol = myScript.src.match('(.*)://[^:/]*.*')[1]
  9. # Define the plugin class
  10. class Core
  11. defaults:
  12. debug: false
  13. constructor: (options) ->
  14. @options = {}
  15. for key, value of @defaults
  16. @options[key] = value
  17. for key, value of options
  18. @options[key] = value
  19. class Base extends Core
  20. constructor: (options) ->
  21. super(options)
  22. @log = new Log(debug: @options.debug, logPrefix: @options.logPrefix || @logPrefix)
  23. class Log extends Core
  24. debug: (items...) =>
  25. return if !@options.debug
  26. @log('debug', items)
  27. notice: (items...) =>
  28. @log('notice', items)
  29. error: (items...) =>
  30. @log('error', items)
  31. log: (level, items) =>
  32. items.unshift('||')
  33. items.unshift(level)
  34. items.unshift(@options.logPrefix)
  35. console.log.apply console, items
  36. return if !@options.debug
  37. logString = ''
  38. for item in items
  39. logString += ' '
  40. if typeof item is 'object'
  41. logString += JSON.stringify(item)
  42. else if item && item.toString
  43. logString += item.toString()
  44. else
  45. logString += item
  46. element = document.querySelector('.js-chatLogDisplay')
  47. if element
  48. element.innerHTML = '<div>' + logString + '</div>' + element.innerHTML
  49. class Timeout extends Base
  50. timeoutStartedAt: null
  51. logPrefix: 'timeout'
  52. defaults:
  53. debug: false
  54. timeout: 4
  55. timeoutIntervallCheck: 0.5
  56. start: =>
  57. @stop()
  58. timeoutStartedAt = new Date
  59. check = =>
  60. timeLeft = new Date - new Date(timeoutStartedAt.getTime() + @options.timeout * 1000 * 60)
  61. @log.debug "Timeout check for #{@options.timeout} minutes (left #{timeLeft/1000} sec.)"#, new Date
  62. return if timeLeft < 0
  63. @stop()
  64. @options.callback()
  65. @log.debug "Start timeout in #{@options.timeout} minutes"#, new Date
  66. @intervallId = setInterval(check, @options.timeoutIntervallCheck * 1000 * 60)
  67. stop: =>
  68. return if !@intervallId
  69. @log.debug "Stop timeout of #{@options.timeout} minutes"#, new Date
  70. clearInterval(@intervallId)
  71. class Io extends Base
  72. logPrefix: 'io'
  73. set: (params) =>
  74. for key, value of params
  75. @options[key] = value
  76. connect: =>
  77. @log.debug "Connecting to #{@options.host}"
  78. @ws = new window.WebSocket("#{@options.host}")
  79. @ws.onopen = (e) =>
  80. @log.debug 'onOpen', e
  81. @options.onOpen(e)
  82. @ping()
  83. @ws.onmessage = (e) =>
  84. pipes = JSON.parse(e.data)
  85. @log.debug 'onMessage', e.data
  86. for pipe in pipes
  87. if pipe.event is 'pong'
  88. @ping()
  89. if @options.onMessage
  90. @options.onMessage(pipes)
  91. @ws.onclose = (e) =>
  92. @log.debug 'close websocket connection', e
  93. if @pingDelayId
  94. clearTimeout(@pingDelayId)
  95. if @manualClose
  96. @log.debug 'manual close, onClose callback'
  97. @manualClose = false
  98. if @options.onClose
  99. @options.onClose(e)
  100. else
  101. @log.debug 'error close, onError callback'
  102. if @options.onError
  103. @options.onError('Connection lost...')
  104. @ws.onerror = (e) =>
  105. @log.debug 'onError', e
  106. if @options.onError
  107. @options.onError(e)
  108. close: =>
  109. @log.debug 'close websocket manually'
  110. @manualClose = true
  111. @ws.close()
  112. reconnect: =>
  113. @log.debug 'reconnect'
  114. @close()
  115. @connect()
  116. send: (event, data = {}) =>
  117. @log.debug 'send', event, data
  118. msg = JSON.stringify
  119. event: event
  120. data: data
  121. @ws.send msg
  122. ping: =>
  123. localPing = =>
  124. @send('ping')
  125. @pingDelayId = setTimeout(localPing, 29000)
  126. class ZammadChat extends Base
  127. defaults:
  128. chatId: undefined
  129. show: true
  130. target: document.querySelector('body')
  131. host: ''
  132. debug: false
  133. flat: false
  134. lang: undefined
  135. cssAutoload: true
  136. cssUrl: undefined
  137. fontSize: undefined
  138. buttonClass: 'open-zammad-chat'
  139. inactiveClass: 'is-inactive'
  140. title: '<strong>Chat</strong> with us!'
  141. scrollHint: 'Scroll down to see new messages'
  142. idleTimeout: 6
  143. idleTimeoutIntervallCheck: 0.5
  144. inactiveTimeout: 8
  145. inactiveTimeoutIntervallCheck: 0.5
  146. waitingListTimeout: 4
  147. waitingListTimeoutIntervallCheck: 0.5
  148. # Callbacks
  149. onReady: undefined
  150. onCloseAnimationEnd: undefined
  151. onError: undefined
  152. onOpenAnimationEnd: undefined
  153. onConnectionReestablished: undefined
  154. onSessionClosed: undefined
  155. onConnectionEstablished: undefined
  156. onCssLoaded: undefined
  157. logPrefix: 'chat'
  158. _messageCount: 0
  159. isOpen: false
  160. blinkOnlineInterval: null
  161. stopBlinOnlineStateTimeout: null
  162. showTimeEveryXMinutes: 2
  163. lastTimestamp: null
  164. lastAddedType: null
  165. inputDisabled: false
  166. inputTimeout: null
  167. isTyping: false
  168. state: 'offline'
  169. initialQueueDelay: 10000
  170. translations:
  171. # ZAMMAD_TRANSLATIONS_START
  172. 'cs':
  173. '<strong>Chat</strong> with us!': '<strong>Chatujte</strong> s námi!'
  174. 'All colleagues are busy.': 'Všichni kolegové jsou vytíženi.'
  175. 'Chat closed by %s': '%s ukončil konverzaci'
  176. 'Compose your message…': 'Napište svou zprávu…'
  177. 'Connecting': 'Připojování'
  178. 'Connection lost': 'Připojení ztraceno'
  179. 'Connection re-established': 'Připojení obnoveno'
  180. 'Offline': 'Offline'
  181. 'Online': 'Online'
  182. 'Scroll down to see new messages': 'Srolujte dolů pro zobrazení nových zpráv'
  183. 'Send': 'Odeslat'
  184. 'Since you didn\'t respond in the last %s minutes your conversation was closed.': 'Jelikož jste nereagovali v posledních %s minutách, vaše konverzace byla uzavřena.'
  185. 'Since you didn\'t respond in the last %s minutes your conversation with <strong>%s</strong> was closed.': 'Jelikož jste nereagovali v posledních %s minutách, vaše konverzace s <strong>%s</strong> byla uzavřena.'
  186. 'Start new conversation': 'Zahájit novou konverzaci'
  187. 'Today': 'Dnes'
  188. 'We are sorry, it is taking longer than expected to get a slot. Please try again later or send us an email. Thank you!': 'Omlouváme se, že musíte čekat déle, než je vhodné pro získání slotu. Prosím, zkuste to později, případně nám napište e-mail. Děkujeme!'
  189. 'You are on waiting list position <strong>%s</strong>.': 'Jste <strong>%s</strong>. v pořadí na čekací listině.'
  190. 'da':
  191. '<strong>Chat</strong> with us!': '<strong>Chat</strong> med os!'
  192. 'All colleagues are busy.': 'Alle medarbejdere er optaget.'
  193. 'Chat closed by %s': 'Chat lukket af %s'
  194. 'Compose your message…': 'Skriv din besked…'
  195. 'Connecting': 'Forbinder'
  196. 'Connection lost': 'Forbindelse mistet'
  197. 'Connection re-established': 'Forbindelse genoprettet'
  198. 'Offline': 'Offline'
  199. 'Online': 'Online'
  200. 'Scroll down to see new messages': 'Scroll ned for at se nye beskeder'
  201. 'Send': 'Afsend'
  202. 'Since you didn\'t respond in the last %s minutes your conversation was closed.': ''
  203. 'Since you didn\'t respond in the last %s minutes your conversation with <strong>%s</strong> was closed.': ''
  204. 'Start new conversation': 'Start en ny samtale'
  205. 'Today': 'I dag'
  206. 'We are sorry, it is taking longer than expected to get a slot. Please try again later or send us an email. Thank you!': ''
  207. 'You are on waiting list position <strong>%s</strong>.': 'Du er i kø som nummer <strong>%s</strong>.'
  208. 'de':
  209. '<strong>Chat</strong> with us!': '<strong>Chatte</strong> mit uns!'
  210. 'All colleagues are busy.': 'Alle Kollegen sind beschäftigt.'
  211. 'Chat closed by %s': 'Chat von %s geschlossen'
  212. 'Compose your message…': 'Verfassen Sie Ihre Nachricht…'
  213. 'Connecting': 'Verbinde'
  214. 'Connection lost': 'Verbindung verloren'
  215. 'Connection re-established': 'Verbindung wieder aufgebaut'
  216. 'Offline': 'Offline'
  217. 'Online': 'Online'
  218. 'Scroll down to see new messages': 'Nach unten scrollen um neue Nachrichten zu sehen'
  219. 'Send': 'Senden'
  220. 'Since you didn\'t respond in the last %s minutes your conversation was closed.': 'Da Sie innerhalb der letzten %s Minuten nicht reagiert haben, wurde Ihre Unterhaltung geschlossen.'
  221. 'Since you didn\'t respond in the last %s minutes your conversation with <strong>%s</strong> was closed.': 'Da Sie innerhalb der letzten %s Minuten nicht reagiert haben, wurde Ihre Unterhaltung mit <strong>%s</strong> geschlossen.'
  222. 'Start new conversation': 'Neue Unterhaltung starten'
  223. 'Today': 'Heute'
  224. 'We are sorry, it is taking longer than expected to get a slot. Please try again later or send us an email. Thank you!': 'Entschuldigung, es dauert länger als erwartet einen freien Platz zu bekommen. Versuchen Sie es später erneut oder senden Sie uns eine E-Mail. Vielen Dank!'
  225. 'You are on waiting list position <strong>%s</strong>.': 'Sie sind in der Warteliste auf Position <strong>%s</strong>.'
  226. 'es':
  227. '<strong>Chat</strong> with us!': '<strong>Chatee</strong> con nosotros!'
  228. 'All colleagues are busy.': 'Todos los colegas están ocupados.'
  229. 'Chat closed by %s': 'Chat cerrado por %s'
  230. 'Compose your message…': 'Escribe tu mensaje…'
  231. 'Connecting': 'Conectando'
  232. 'Connection lost': 'Conexión perdida'
  233. 'Connection re-established': 'Conexión reestablecida'
  234. 'Offline': 'Desconectado'
  235. 'Online': 'En línea'
  236. 'Scroll down to see new messages': 'Desplace hacia abajo para ver nuevos mensajes'
  237. 'Send': 'Enviar'
  238. 'Since you didn\'t respond in the last %s minutes your conversation was closed.': 'Debido a que usted no ha respondido en los últimos %s minutos, su conversación se ha cerrado.'
  239. 'Since you didn\'t respond in the last %s minutes your conversation with <strong>%s</strong> was closed.': 'Debido a que usted no ha respondido en los últimos %s minutos, su conversación con <strong>%s</strong> se ha cerrado.'
  240. 'Start new conversation': 'Iniciar nueva conversación'
  241. 'Today': 'Hoy'
  242. 'We are sorry, it is taking longer than expected to get a slot. Please try again later or send us an email. Thank you!': 'Lo sentimos, estamos tardando más de lo esperado para asignar un agente. Inténtelo de nuevo más tarde o envíenos un correo electrónico. ¡Gracias!'
  243. 'You are on waiting list position <strong>%s</strong>.': 'Usted está en la posición <strong>%s</strong> de la lista de espera.'
  244. 'fr':
  245. '<strong>Chat</strong> with us!': '<strong>Chattez</strong> avec nous !'
  246. 'All colleagues are busy.': 'Tous les agents sont occupés.'
  247. 'Chat closed by %s': 'Chat fermé par %s'
  248. 'Compose your message…': 'Écrivez votre message…'
  249. 'Connecting': 'Connexion'
  250. 'Connection lost': 'Connexion perdue'
  251. 'Connection re-established': 'Connexion ré-établie'
  252. 'Offline': 'Hors-ligne'
  253. 'Online': 'En ligne'
  254. 'Scroll down to see new messages': 'Défiler vers le bas pour voir les nouveaux messages'
  255. 'Send': 'Envoyer'
  256. 'Since you didn\'t respond in the last %s minutes your conversation was closed.': 'Sans réponse de votre part depuis %s minutes, votre conservation a été fermée.'
  257. 'Since you didn\'t respond in the last %s minutes your conversation with <strong>%s</strong> was closed.': 'Sans réponse de votre part depuis %s minutes, votre conversation avec <strong>%s</strong> a été fermée.'
  258. 'Start new conversation': 'Démarrer une nouvelle conversation'
  259. 'Today': 'Aujourd\'hui'
  260. 'We are sorry, it is taking longer than expected to get a slot. Please try again later or send us an email. Thank you!': 'Nous sommes désolés, trouver un agent disponible prend plus de temps que prévu. Réessayez plus tard ou envoyez-nous un mail. Merci !'
  261. 'You are on waiting list position <strong>%s</strong>.': 'Vous êtes actuellement en position <strong>%s</strong> dans la file d\'attente.'
  262. 'hr':
  263. '<strong>Chat</strong> with us!': '<strong>Čavrljajte</strong> sa nama!'
  264. 'All colleagues are busy.': 'Svi kolege su zauzeti.'
  265. 'Chat closed by %s': '%s zatvara chat'
  266. 'Compose your message…': 'Sastavite poruku…'
  267. 'Connecting': 'Povezivanje'
  268. 'Connection lost': 'Veza prekinuta'
  269. 'Connection re-established': 'Veza je ponovno uspostavljena'
  270. 'Offline': 'Odsutan'
  271. 'Online': 'Dostupan(a)'
  272. 'Scroll down to see new messages': 'Pomaknite se prema dolje da biste vidjeli nove poruke'
  273. 'Send': 'Šalji'
  274. 'Since you didn\'t respond in the last %s minutes your conversation was closed.': 'Budući da niste odgovorili u posljednjih %s minuta, Vaš je razgovor zatvoren.'
  275. 'Since you didn\'t respond in the last %s minutes your conversation with <strong>%s</strong> was closed.': 'Budući da niste odgovorili u posljednjih %s minuta, Vaš je razgovor s <strong>%</strong>s zatvoren.'
  276. 'Start new conversation': 'Započni novi razgovor'
  277. 'Today': 'Danas'
  278. 'We are sorry, it is taking longer than expected to get a slot. Please try again later or send us an email. Thank you!': 'Oprostite, proces traje duže nego što se očekivalo da biste dobili slobodan termin. Molimo, pokušajte ponovno kasnije ili nam pošaljite e-mail. Hvala!'
  279. 'You are on waiting list position <strong>%s</strong>.': 'Nalazite se u redu čekanja na poziciji <strong>%s</strong>.'
  280. 'hu':
  281. '<strong>Chat</strong> with us!': '<strong>Csevegjen</strong> velünk!'
  282. 'All colleagues are busy.': 'Minden munkatársunk foglalt.'
  283. 'Chat closed by %s': 'A csevegés %s által lezárva'
  284. 'Compose your message…': 'Fogalmazza meg üzenetét…'
  285. 'Connecting': 'Csatlakozás'
  286. 'Connection lost': 'A kapcsolat megszakadt'
  287. 'Connection re-established': 'A kapcsolat helyreállt'
  288. 'Offline': 'Offline'
  289. 'Online': 'Online'
  290. 'Scroll down to see new messages': 'Görgessen lefelé az új üzenetek megtekintéséhez'
  291. 'Send': 'Küldés'
  292. 'Since you didn\'t respond in the last %s minutes your conversation was closed.': 'Mivel az elmúlt %s percben nem válaszolt, a beszélgetése lezárásra került.'
  293. 'Since you didn\'t respond in the last %s minutes your conversation with <strong>%s</strong> was closed.': 'Mivel az elmúlt %s percben nem válaszolt, <strong>%s</strong> munkatársunkkal folytatott beszélgetését lezártuk.'
  294. 'Start new conversation': 'Új beszélgetés indítása'
  295. 'Today': 'Ma'
  296. 'We are sorry, it is taking longer than expected to get a slot. Please try again later or send us an email. Thank you!': 'Sajnáljuk, hogy a vártnál hosszabb ideig tart a helyfoglalás. Kérjük, próbálja meg később újra, vagy küldjön nekünk egy e-mailt. Köszönjük!'
  297. 'You are on waiting list position <strong>%s</strong>.': 'Ön a várólistán a <strong>%s</strong> helyen szerepel.'
  298. 'it':
  299. '<strong>Chat</strong> with us!': '<strong>Chatta</strong> con noi!'
  300. 'All colleagues are busy.': 'Tutti i colleghi sono occupati.'
  301. 'Chat closed by %s': 'Chat chiusa da %s'
  302. 'Compose your message…': 'Scrivi il tuo messaggio…'
  303. 'Connecting': 'Connessione in corso'
  304. 'Connection lost': 'Connessione persa'
  305. 'Connection re-established': 'Connessione ristabilita'
  306. 'Offline': 'Offline'
  307. 'Online': 'Online'
  308. 'Scroll down to see new messages': 'Scorri verso il basso per vedere i nuovi messaggi'
  309. 'Send': 'Invia'
  310. 'Since you didn\'t respond in the last %s minutes your conversation was closed.': 'Dato che non hai risposto negli ultimi %s minuti, la conversazione è stata chiusa.'
  311. 'Since you didn\'t respond in the last %s minutes your conversation with <strong>%s</strong> was closed.': 'Dato che non hai risposto negli ultimi %s minuti, la conversazione con <strong>%s</strong> è stata chiusa.'
  312. 'Start new conversation': 'Avvia una nuova chat'
  313. 'Today': 'Oggi'
  314. 'We are sorry, it is taking longer than expected to get a slot. Please try again later or send us an email. Thank you!': 'Siamo spiacenti, ci vuole più tempo del previsto per ottenere uno spazio libero. Riprova più tardi o inviaci un\'e-mail. Grazie!'
  315. 'You are on waiting list position <strong>%s</strong>.': 'Sei alla posizione <strong>%s</strong> della lista di attesa.'
  316. 'lt':
  317. '<strong>Chat</strong> with us!': '<strong>Kalbėkitės</strong> su mumis!'
  318. 'All colleagues are busy.': 'Visi kolegos užimti.'
  319. 'Chat closed by %s': '%s uždarė pokalbį'
  320. 'Compose your message…': 'Rašykite žinutę…'
  321. 'Connecting': 'Jungiamasi'
  322. 'Connection lost': 'Dingo ryšys'
  323. 'Connection re-established': 'Ryšys atnaujintas'
  324. 'Offline': 'Atsijungęs'
  325. 'Online': 'Prisijungęs'
  326. 'Scroll down to see new messages': 'Naujos žinutės žemiau'
  327. 'Send': 'Siųsti'
  328. 'Since you didn\'t respond in the last %s minutes your conversation was closed.': 'Jūsų pokalbis buvo uždarytas, nes nieko neatsakėte per %s minučių.'
  329. 'Since you didn\'t respond in the last %s minutes your conversation with <strong>%s</strong> was closed.': 'Jūsų pokalbis su <strong>%s</strong> buvo uždarytas, nes nieko neatsakėte per %s minučių.'
  330. 'Start new conversation': 'Pradėti naują pokalbį'
  331. 'Today': 'Šiandien'
  332. 'We are sorry, it is taking longer than expected to get a slot. Please try again later or send us an email. Thank you!': 'Atsiprašome, kad tenka laukti atskymo. Bandykite vėliau arba rašykite el. paštu. Ačiū!'
  333. 'You are on waiting list position <strong>%s</strong>.': 'Esate <strong>%s</strong> eilėje.'
  334. 'nl':
  335. '<strong>Chat</strong> with us!': '<strong>Chat</strong> met ons!'
  336. 'All colleagues are busy.': 'Alle collega\'s zijn bezet.'
  337. 'Chat closed by %s': 'Chat gesloten door %s'
  338. 'Compose your message…': 'Stel je bericht op…'
  339. 'Connecting': 'Verbinden'
  340. 'Connection lost': 'Verbinding verbroken'
  341. 'Connection re-established': 'Verbinding hersteld'
  342. 'Offline': 'Offline'
  343. 'Online': 'Online'
  344. 'Scroll down to see new messages': 'Scroll naar beneden om nieuwe tickets te bekijken'
  345. 'Send': 'Verstuur'
  346. 'Since you didn\'t respond in the last %s minutes your conversation was closed.': 'De chat is afgesloten omdat je de laatste %s minuten niet hebt gereageerd.'
  347. 'Since you didn\'t respond in the last %s minutes your conversation with <strong>%s</strong> was closed.': 'Je chat met <strong>%s</strong> is afgesloten omdat je niet hebt gereageerd in de laatste %s minuten.'
  348. 'Start new conversation': 'Nieuw gesprek starten'
  349. 'Today': 'Vandaag'
  350. 'We are sorry, it is taking longer than expected to get a slot. Please try again later or send us an email. Thank you!': 'Het spijt ons, het duurt langer dan verwacht om een chat te starten. Probeer het later nog eens of stuur ons een e-mail. Bedankt!'
  351. 'You are on waiting list position <strong>%s</strong>.': 'Je bevindt zich op wachtlijstpositie <strong>%s</strong>.'
  352. 'pl':
  353. '<strong>Chat</strong> with us!': '<strong>Czatuj</strong> z nami!'
  354. 'All colleagues are busy.': 'Wszyscy agenci są zajęci.'
  355. 'Chat closed by %s': 'Chat zamknięty przez %s'
  356. 'Compose your message…': 'Skomponuj swoją wiadomość…'
  357. 'Connecting': 'Łączenie'
  358. 'Connection lost': 'Utracono połączenie'
  359. 'Connection re-established': 'Ponowne nawiązanie połączenia'
  360. 'Offline': 'Offline'
  361. 'Online': 'Online'
  362. 'Scroll down to see new messages': 'Skroluj w dół, aby zobaczyć wiadomości'
  363. 'Send': 'Wyślij'
  364. 'Since you didn\'t respond in the last %s minutes your conversation was closed.': 'Ponieważ nie odpowiedziałeś w ciągu ostatnich %s minut, Twoja rozmowa została zamknięta.'
  365. 'Since you didn\'t respond in the last %s minutes your conversation with <strong>%s</strong> was closed.': 'Ponieważ nie odpowiedziałeś w ciągu ostatnich %s minut, Twoja rozmowa z <strong>%s</strong> została zamknięta.'
  366. 'Start new conversation': 'Rozpocznij nową rozmowę'
  367. 'Today': 'Dzisiaj'
  368. 'We are sorry, it is taking longer than expected to get a slot. Please try again later or send us an email. Thank you!': 'Przepraszamy, znalezienie wolnego konsultanta zajmuje więcej czasu niż oczekiwano. Spróbuj ponownie później lub wyślij nam e-mail. Dziękujemy!'
  369. 'You are on waiting list position <strong>%s</strong>.': 'Jesteś na pozycji listy oczekujących <strong>%s</strong>.'
  370. 'pt-br':
  371. '<strong>Chat</strong> with us!': '<strong>Converse</strong> conosco!'
  372. 'All colleagues are busy.': 'Nossos atendentes estão ocupados.'
  373. 'Chat closed by %s': 'Chat encerrado por %s'
  374. 'Compose your message…': 'Escreva sua mensagem…'
  375. 'Connecting': 'Conectando'
  376. 'Connection lost': 'Conexão perdida'
  377. 'Connection re-established': 'Conexão restabelecida'
  378. 'Offline': 'Desconectado'
  379. 'Online': 'Online'
  380. 'Scroll down to see new messages': 'Rolar para baixo para ver novas mensagems'
  381. 'Send': 'Enviar'
  382. 'Since you didn\'t respond in the last %s minutes your conversation was closed.': 'Como você não respondeu nos últimos %s minutos, sua conversa foi encerrada.'
  383. 'Since you didn\'t respond in the last %s minutes your conversation with <strong>%s</strong> was closed.': 'Como você não respondeu nos últimos %s minutos, sua conversa com <strong>%s</strong> foi encerrada.'
  384. 'Start new conversation': 'Iniciar uma nova conversa'
  385. 'Today': 'Hoje'
  386. 'We are sorry, it is taking longer than expected to get a slot. Please try again later or send us an email. Thank you!': 'Lamentamos, está demorando mais do que o esperado para conseguir uma vaga. Tente novamente mais tarde ou envie-nos um e-mail. Obrigado!'
  387. 'You are on waiting list position <strong>%s</strong>.': 'Você está na posição <strong>%s</strong> da lista de espera.'
  388. 'ro':
  389. '<strong>Chat</strong> with us!': '<strong>Comunică</strong> cu noi!'
  390. 'All colleagues are busy.': 'Toți colegii sunt ocupați momentan.'
  391. 'Chat closed by %s': 'Chat închis de către %s'
  392. 'Compose your message…': 'Compune-ți mesajul…'
  393. 'Connecting': 'Se conectează'
  394. 'Connection lost': 'Conexiune pierdută'
  395. 'Connection re-established': 'Conexiune restabilită'
  396. 'Offline': 'Offline'
  397. 'Online': 'Online'
  398. 'Scroll down to see new messages': 'Derulați în jos pentru a vedea mesajele noi'
  399. 'Send': 'Trimite'
  400. 'Since you didn\'t respond in the last %s minutes your conversation was closed.': 'Deoarece nu ai răspuns în ultimele %s minute, conversația ta a fost închisă.'
  401. 'Since you didn\'t respond in the last %s minutes your conversation with <strong>%s</strong> was closed.': 'Deoarece nu ai răspuns în ultimele %s minute, conversația ta cu <strong>%s</strong> a fost închisă.'
  402. 'Start new conversation': 'Începe o conversație nouă'
  403. 'Today': 'Azi'
  404. 'We are sorry, it is taking longer than expected to get a slot. Please try again later or send us an email. Thank you!': 'Ne pare rău, durează mai mult decât ne așteptam să obținem un loc. Te rugăm să încerci din nou mai târziu sau să ne trimiți un email. Mulțumim!'
  405. 'You are on waiting list position <strong>%s</strong>.': 'Aveți poziția <strong>%s</strong> în lista de așteptare.'
  406. 'ru':
  407. '<strong>Chat</strong> with us!': '<strong>Напишите</strong> нам!'
  408. 'All colleagues are busy.': 'Все коллеги заняты.'
  409. 'Chat closed by %s': 'Чат закрыт %s'
  410. 'Compose your message…': 'Составьте сообщение…'
  411. 'Connecting': 'Подключение'
  412. 'Connection lost': 'Подключение потеряно'
  413. 'Connection re-established': 'Подключение восстановлено'
  414. 'Offline': 'Оффлайн'
  415. 'Online': 'В сети'
  416. 'Scroll down to see new messages': 'Прокрутите вниз, чтобы увидеть новые сообщения'
  417. 'Send': 'Отправить'
  418. 'Since you didn\'t respond in the last %s minutes your conversation was closed.': 'Поскольку Вы не ответили в течение последних %s минут, Ваш разговор был закрыт.'
  419. 'Since you didn\'t respond in the last %s minutes your conversation with <strong>%s</strong> was closed.': 'Поскольку Вы не ответили в течение последних %s минут, Ваш разговор с <strong>%s</strong> был закрыт.'
  420. 'Start new conversation': 'Начать новый разговор'
  421. 'Today': 'Сегодня'
  422. 'We are sorry, it is taking longer than expected to get a slot. Please try again later or send us an email. Thank you!': 'Извините, получение свободного слота занимает больше времени, чем ожидалось. Пожалуйста, повторите попытку позже или отправьте нам электронное письмо. Благодарим Вас!'
  423. 'You are on waiting list position <strong>%s</strong>.': 'Вы находитесь в списке ожидания <strong>%s</strong>.'
  424. 'sr':
  425. '<strong>Chat</strong> with us!': '<strong>Ћаскајте</strong> са нама!'
  426. 'All colleagues are busy.': 'Све колеге су заузете.'
  427. 'Chat closed by %s': 'Ћаскање затворено од стране %s'
  428. 'Compose your message…': 'Напишите поруку…'
  429. 'Connecting': 'Повезивање'
  430. 'Connection lost': 'Веза је изгубљена'
  431. 'Connection re-established': 'Веза је поново успостављена'
  432. 'Offline': 'Одсутан(а)'
  433. 'Online': 'Доступан(а)'
  434. 'Scroll down to see new messages': 'Скролујте на доле за нове поруке'
  435. 'Send': 'Пошаљи'
  436. 'Since you didn\'t respond in the last %s minutes your conversation was closed.': 'Пошто нисте одговорили у последњих %s минут(a), ваш разговор је завршен.'
  437. 'Since you didn\'t respond in the last %s minutes your conversation with <strong>%s</strong> was closed.': 'Пошто нисте одговорили у последњих %s минут(a), ваш разговор са <strong>%s</strong> је завршен.'
  438. 'Start new conversation': 'Започни нови разговор'
  439. 'Today': 'Данас'
  440. 'We are sorry, it is taking longer than expected to get a slot. Please try again later or send us an email. Thank you!': 'Жао нам је, добијање празног термина траје дуже од очекиваног. Молимо покушајте поново касније или нам пошаљите имејл поруку. Хвала вам!'
  441. 'You are on waiting list position <strong>%s</strong>.': 'Ви сте тренутно <strong>%s.</strong> у реду за чекање.'
  442. 'sr-latn-rs':
  443. '<strong>Chat</strong> with us!': '<strong>Ćaskajte</strong> sa nama!'
  444. 'All colleagues are busy.': 'Sve kolege su zauzete.'
  445. 'Chat closed by %s': 'Ćaskanje zatvoreno od strane %s'
  446. 'Compose your message…': 'Napišite poruku…'
  447. 'Connecting': 'Povezivanje'
  448. 'Connection lost': 'Veza je izgubljena'
  449. 'Connection re-established': 'Veza je ponovo uspostavljena'
  450. 'Offline': 'Odsutan(a)'
  451. 'Online': 'Dostupan(a)'
  452. 'Scroll down to see new messages': 'Skrolujte na dole za nove poruke'
  453. 'Send': 'Pošalji'
  454. 'Since you didn\'t respond in the last %s minutes your conversation was closed.': 'Pošto niste odgovorili u poslednjih %s minut(a), vaš razgovor je završen.'
  455. 'Since you didn\'t respond in the last %s minutes your conversation with <strong>%s</strong> was closed.': 'Pošto niste odgovorili u poslednjih %s minut(a), vaš razgovor sa <strong>%s</strong> je završen.'
  456. 'Start new conversation': 'Započni novi razgovor'
  457. 'Today': 'Danas'
  458. 'We are sorry, it is taking longer than expected to get a slot. Please try again later or send us an email. Thank you!': 'Žao nam je, dobijanje praznog termina traje duže od očekivanog. Molimo pokušajte ponovo kasnije ili nam pošaljite imejl poruku. Hvala vam!'
  459. 'You are on waiting list position <strong>%s</strong>.': 'Vi ste trenutno <strong>%s.</strong> u redu za čekanje.'
  460. 'sv':
  461. '<strong>Chat</strong> with us!': '<strong>Chatta</strong> med oss!'
  462. 'All colleagues are busy.': 'Alla kollegor är upptagna.'
  463. 'Chat closed by %s': 'Chatt stängd av %s'
  464. 'Compose your message…': 'Skriv ditt meddelande …'
  465. 'Connecting': 'Ansluter'
  466. 'Connection lost': 'Anslutningen försvann'
  467. 'Connection re-established': 'Anslutningen återupprättas'
  468. 'Offline': 'Offline'
  469. 'Online': 'Online'
  470. 'Scroll down to see new messages': 'Bläddra ner för att se nya meddelanden'
  471. 'Send': 'Skicka'
  472. 'Since you didn\'t respond in the last %s minutes your conversation was closed.': 'Din chatt avslutades då du inte svarade inom %s minuter.'
  473. 'Since you didn\'t respond in the last %s minutes your conversation with <strong>%s</strong> was closed.': 'Chatten stängdes eftersom du inte svarat inom %s minuter i din konversation med <strong>%s</strong>.'
  474. 'Start new conversation': 'Starta ny konversation'
  475. 'Today': 'Idag'
  476. 'We are sorry, it is taking longer than expected to get a slot. Please try again later or send us an email. Thank you!': 'Det tar tyvärr längre tid än förväntat att få en ledig plats. Försök igen senare eller skicka ett mejl till oss. Tack!'
  477. 'You are on waiting list position <strong>%s</strong>.': 'Du är på väntelistan som position <strong>%s</strong>.'
  478. 'zh-cn':
  479. '<strong>Chat</strong> with us!': '发起<strong>即时对话</strong>!'
  480. 'All colleagues are busy.': '所有同事都很忙。'
  481. 'Chat closed by %s': '对话已被 %s 关闭'
  482. 'Compose your message…': '编辑您的信息…'
  483. 'Connecting': '连接中'
  484. 'Connection lost': '连接丢失'
  485. 'Connection re-established': '正在重新建立连接'
  486. 'Offline': '离线'
  487. 'Online': '在线'
  488. 'Scroll down to see new messages': '向下滚动以查看新消息'
  489. 'Send': '发送'
  490. 'Since you didn\'t respond in the last %s minutes your conversation was closed.': '"由于您超过 %s 分钟没有任何回复'
  491. 'Since you didn\'t respond in the last %s minutes your conversation with <strong>%s</strong> was closed.': '"由于您超过 %s 分钟没有回复'
  492. 'Start new conversation': '开始新的会话'
  493. 'Today': '今天'
  494. 'We are sorry, it is taking longer than expected to get a slot. Please try again later or send us an email. Thank you!': ''
  495. 'You are on waiting list position <strong>%s</strong>.': '您目前的等候位置是第 <strong>%s</strong> 位.'
  496. # ZAMMAD_TRANSLATIONS_END
  497. sessionId: undefined
  498. scrolledToBottom: true
  499. scrollSnapTolerance: 10
  500. richTextFormatKey:
  501. 66: true # b
  502. 73: true # i
  503. 85: true # u
  504. 83: true # s
  505. T: (string, items...) =>
  506. if @options.lang && @options.lang isnt 'en'
  507. if !@translations[@options.lang]
  508. @log.notice "Translation '#{@options.lang}' needed!"
  509. else
  510. translations = @translations[@options.lang]
  511. if !translations[string]
  512. @log.notice "Translation needed for '#{string}'"
  513. string = translations[string] || string
  514. if items
  515. for item in items
  516. string = string.replace(/%s/, item)
  517. string
  518. view: (name) =>
  519. return (options) =>
  520. if !options
  521. options = {}
  522. options.T = @T
  523. options.background = @options.background
  524. options.flat = @options.flat
  525. options.fontSize = @options.fontSize
  526. return window.zammadChatTemplates[name](options)
  527. constructor: (options) ->
  528. super(options)
  529. # jQuery migration
  530. if typeof jQuery != 'undefined' && @options.target instanceof jQuery
  531. @log.notice 'Chat: target option is a jQuery object. jQuery is not a requirement for the chat any more.'
  532. @options.target = @options.target.get(0)
  533. # fullscreen
  534. @isFullscreen = (window.matchMedia and window.matchMedia('(max-width: 768px)').matches)
  535. @scrollRoot = @getScrollRoot()
  536. # check prerequisites
  537. if !window.WebSocket or !sessionStorage
  538. @state = 'unsupported'
  539. @log.notice 'Chat: Browser not supported!'
  540. return
  541. if !@options.chatId
  542. @state = 'unsupported'
  543. @log.error 'Chat: need chatId as option!'
  544. return
  545. # detect language
  546. if !@options.lang
  547. @options.lang = document.documentElement.getAttribute('lang')
  548. if @options.lang
  549. if !@translations[@options.lang]
  550. @log.debug "lang: No #{@options.lang} found, try first two letters"
  551. @options.lang = @options.lang.replace(/-.+?$/, '') # replace "-xx" of xx-xx
  552. @log.debug "lang: #{@options.lang}"
  553. # detect host
  554. @detectHost() if !@options.host
  555. @loadCss()
  556. @io = new Io(@options)
  557. @io.set(
  558. onOpen: @render
  559. onClose: @onWebSocketClose
  560. onMessage: @onWebSocketMessage
  561. onError: @onError
  562. )
  563. @io.connect()
  564. getScrollRoot: ->
  565. return document.scrollingElement if 'scrollingElement' of document
  566. html = document.documentElement
  567. start = parseInt(html.pageYOffset, 10)
  568. html.pageYOffset = start + 1
  569. end = parseInt(html.pageYOffset, 10)
  570. html.pageYOffset = start
  571. return if end > start then html else document.body
  572. render: =>
  573. if !@el || !document.querySelector('.zammad-chat')
  574. @renderBase()
  575. # disable open button
  576. btn = document.querySelector(".#{ @options.buttonClass }")
  577. if btn
  578. btn.classList.add @options.inactiveClass
  579. @setAgentOnlineState 'online'
  580. @log.debug 'widget rendered'
  581. @startTimeoutObservers()
  582. @idleTimeout.start()
  583. # get current chat status
  584. @sessionId = sessionStorage.getItem('sessionId')
  585. @send 'chat_status_customer',
  586. session_id: @sessionId
  587. url: window.location.href
  588. renderBase: ->
  589. @el.remove() if @el
  590. @options.target.insertAdjacentHTML('beforeend', @view('chat')(
  591. title: @options.title,
  592. scrollHint: @options.scrollHint
  593. ))
  594. @el = @options.target.querySelector('.zammad-chat')
  595. @input = @el.querySelector('.zammad-chat-input')
  596. @body = @el.querySelector('.zammad-chat-body')
  597. # start bindings
  598. @el.querySelector('.js-chat-open').addEventListener('click', @open)
  599. @el.querySelector('.js-chat-toggle').addEventListener('click', @toggle)
  600. @el.querySelector('.js-chat-status').addEventListener('click', @stopPropagation)
  601. @el.querySelector('.zammad-chat-controls').addEventListener('submit', @onSubmit)
  602. @body.addEventListener('scroll', @detectScrolledtoBottom)
  603. @el.querySelector('.zammad-scroll-hint').addEventListener('click', @onScrollHintClick)
  604. @input.addEventListener('keydown', @onKeydown)
  605. @input.addEventListener('input', @onInput)
  606. @input.addEventListener('paste', @onPaste)
  607. @input.addEventListener('drop', @onDrop)
  608. window.addEventListener('beforeunload', @onLeaveTemporary)
  609. window.addEventListener('hashchange', =>
  610. if @isOpen
  611. if @sessionId
  612. @send 'chat_session_notice',
  613. session_id: @sessionId
  614. message: window.location.href
  615. return
  616. @idleTimeout.start()
  617. )
  618. stopPropagation: (event) ->
  619. event.stopPropagation()
  620. onDrop: (e) =>
  621. e.stopPropagation()
  622. e.preventDefault()
  623. if window.dataTransfer # ie
  624. dataTransfer = window.dataTransfer
  625. else if e.dataTransfer # other browsers
  626. dataTransfer = e.dataTransfer
  627. else
  628. throw 'No clipboardData support'
  629. x = e.clientX
  630. y = e.clientY
  631. file = dataTransfer.files[0]
  632. # look for images
  633. if file.type.match('image.*')
  634. reader = new FileReader()
  635. reader.onload = (e) =>
  636. # Insert the image at the carat
  637. insert = (dataUrl, width) =>
  638. # adapt image if we are on retina devices
  639. if @isRetina()
  640. width = width / 2
  641. result = dataUrl
  642. img = new Image()
  643. img.style.width = '100%'
  644. img.style.maxWidth = width + 'px'
  645. img.src = result
  646. if document.caretPositionFromPoint
  647. pos = document.caretPositionFromPoint(x, y)
  648. range = document.createRange()
  649. range.setStart(pos.offsetNode, pos.offset)
  650. range.collapse()
  651. range.insertNode(img)
  652. else if document.caretRangeFromPoint
  653. range = document.caretRangeFromPoint(x, y)
  654. range.insertNode(img)
  655. else
  656. console.log('could not find carat')
  657. # resize if to big
  658. @resizeImage(e.target.result, 460, 'auto', 2, 'image/jpeg', 'auto', insert)
  659. reader.readAsDataURL(file)
  660. onPaste: (e) =>
  661. e.stopPropagation()
  662. e.preventDefault()
  663. if e.clipboardData
  664. clipboardData = e.clipboardData
  665. else if window.clipboardData
  666. clipboardData = window.clipboardData
  667. else if e.clipboardData
  668. clipboardData = e.clipboardData
  669. else
  670. throw 'No clipboardData support'
  671. imageInserted = false
  672. if clipboardData && clipboardData.items && clipboardData.items[0]
  673. item = clipboardData.items[0]
  674. if item.kind == 'file' && (item.type == 'image/png' || item.type == 'image/jpeg')
  675. imageFile = item.getAsFile()
  676. reader = new FileReader()
  677. reader.onload = (e) =>
  678. insert = (dataUrl, width) =>
  679. # adapt image if we are on retina devices
  680. if @isRetina()
  681. width = width / 2
  682. img = new Image()
  683. img.style.width = '100%'
  684. img.style.maxWidth = width + 'px'
  685. img.src = dataUrl
  686. document.execCommand('insertHTML', false, img)
  687. # resize if to big
  688. @resizeImage(e.target.result, 460, 'auto', 2, 'image/jpeg', 'auto', insert)
  689. reader.readAsDataURL(imageFile)
  690. imageInserted = true
  691. return if imageInserted
  692. # check existing + paste text for limit
  693. text = undefined
  694. docType = undefined
  695. try
  696. text = clipboardData.getData('text/html')
  697. docType = 'html'
  698. if !text || text.length is 0
  699. docType = 'text'
  700. text = clipboardData.getData('text/plain')
  701. if !text || text.length is 0
  702. docType = 'text2'
  703. text = clipboardData.getData('text')
  704. catch e
  705. console.log('Sorry, can\'t insert markup because browser is not supporting it.')
  706. docType = 'text3'
  707. text = clipboardData.getData('text')
  708. if docType is 'text' || docType is 'text2' || docType is 'text3'
  709. text = '<div>' + text.replace(/\n/g, '</div><div>') + '</div>'
  710. text = text.replace(/<div><\/div>/g, '<div><br></div>')
  711. console.log('p', docType, text)
  712. if docType is 'html'
  713. html = document.createElement('div')
  714. # can't log because might contain malicious content
  715. # @log.debug 'HTML clipboard', text
  716. sanitized = DOMPurify.sanitize(text)
  717. @log.debug 'sanitized HTML clipboard', sanitized
  718. html.innerHTML = sanitized
  719. match = false
  720. htmlTmp = text
  721. regex = new RegExp('<(/w|w)\:[A-Za-z]')
  722. if htmlTmp.match(regex)
  723. match = true
  724. htmlTmp = htmlTmp.replace(regex, '')
  725. regex = new RegExp('<(/o|o)\:[A-Za-z]')
  726. if htmlTmp.match(regex)
  727. match = true
  728. htmlTmp = htmlTmp.replace(regex, '')
  729. if match
  730. html = @wordFilter(html)
  731. #html
  732. for node in html.childNodes
  733. if node.nodeType == 8
  734. node.remove()
  735. # remove tags, keep content
  736. for node in html.querySelectorAll('a, font, small, time, form, label')
  737. node.outerHTML = node.innerHTML
  738. # replace tags with generic div
  739. # New type of the tag
  740. replacementTag = 'div';
  741. # Replace all x tags with the type of replacementTag
  742. for node in html.querySelectorAll('textarea')
  743. outer = node.outerHTML
  744. # Replace opening tag
  745. regex = new RegExp('<' + node.tagName, 'i')
  746. newTag = outer.replace(regex, '<' + replacementTag)
  747. # Replace closing tag
  748. regex = new RegExp('</' + node.tagName, 'i')
  749. newTag = newTag.replace(regex, '</' + replacementTag)
  750. node.outerHTML = newTag
  751. # remove tags & content
  752. for node in html.querySelectorAll('font, img, svg, input, select, button, style, applet, embed, noframes, canvas, script, frame, iframe, meta, link, title, head, fieldset')
  753. node.remove()
  754. @removeAttributes(html)
  755. text = html.innerHTML
  756. # as fallback, insert html via pasteHtmlAtCaret (for IE 11 and lower)
  757. if docType is 'text3'
  758. @pasteHtmlAtCaret(text)
  759. else
  760. document.execCommand('insertHTML', false, text)
  761. true
  762. onKeydown: (e) =>
  763. # check for enter
  764. if not @inputDisabled and not e.shiftKey and e.keyCode is 13
  765. e.preventDefault()
  766. @sendMessage()
  767. richtTextControl = false
  768. if !e.altKey && !e.ctrlKey && e.metaKey
  769. richtTextControl = true
  770. else if !e.altKey && e.ctrlKey && !e.metaKey
  771. richtTextControl = true
  772. if richtTextControl && @richTextFormatKey[ e.keyCode ]
  773. e.preventDefault()
  774. if e.keyCode is 66
  775. document.execCommand('bold')
  776. return true
  777. if e.keyCode is 73
  778. document.execCommand('italic')
  779. return true
  780. if e.keyCode is 85
  781. document.execCommand('underline')
  782. return true
  783. if e.keyCode is 83
  784. document.execCommand('strikeThrough')
  785. return true
  786. send: (event, data = {}) =>
  787. data.chat_id = @options.chatId
  788. @io.send(event, data)
  789. onWebSocketMessage: (pipes) =>
  790. for pipe in pipes
  791. @log.debug 'ws:onmessage', pipe
  792. switch pipe.event
  793. when 'chat_error'
  794. @log.notice pipe.data
  795. if pipe.data && pipe.data.state is 'chat_disabled'
  796. @destroy(remove: true)
  797. when 'chat_session_message'
  798. return if pipe.data.self_written
  799. @receiveMessage pipe.data
  800. when 'chat_session_typing'
  801. return if pipe.data.self_written
  802. @onAgentTypingStart()
  803. when 'chat_session_start'
  804. @onConnectionEstablished pipe.data
  805. when 'chat_session_queue'
  806. @onQueueScreen pipe.data
  807. when 'chat_session_closed'
  808. @onSessionClosed pipe.data
  809. when 'chat_session_left'
  810. @onSessionClosed pipe.data
  811. when 'chat_status_customer'
  812. switch pipe.data.state
  813. when 'online'
  814. @sessionId = undefined
  815. if !@options.cssAutoload || @cssLoaded
  816. @onReady()
  817. else
  818. @socketReady = true
  819. when 'offline'
  820. @onError 'Zammad Chat: No agent online'
  821. when 'chat_disabled'
  822. @onError 'Zammad Chat: Chat is disabled'
  823. when 'no_seats_available'
  824. @onError "Zammad Chat: Too many clients in queue. Clients in queue: #{pipe.data.queue}"
  825. when 'reconnect'
  826. @onReopenSession pipe.data
  827. onReady: ->
  828. @log.debug 'widget ready for use'
  829. btn = document.querySelector(".#{ @options.buttonClass }")
  830. if btn
  831. btn.addEventListener('click', @open)
  832. btn.classList.remove(@options.inactiveClass)
  833. @options.onReady?()
  834. if @options.show
  835. @show()
  836. onError: (message) =>
  837. @log.debug message
  838. @addStatus(message)
  839. btn = document.querySelector(".#{ @options.buttonClass }")
  840. if btn
  841. btn.classList.add('zammad-chat-is-hidden')
  842. if @isOpen
  843. @disableInput()
  844. @destroy(remove: false)
  845. else
  846. @destroy(remove: true)
  847. @options.onError?(message)
  848. onReopenSession: (data) =>
  849. @log.debug 'old messages', data.session
  850. @inactiveTimeout.start()
  851. unfinishedMessage = sessionStorage.getItem 'unfinished_message'
  852. # rerender chat history
  853. if data.agent
  854. @onConnectionEstablished(data)
  855. for message in data.session
  856. @renderMessage
  857. message: message.content
  858. id: message.id
  859. from: if message.created_by_id then 'agent' else 'customer'
  860. if unfinishedMessage
  861. @input.innerHTML = unfinishedMessage
  862. # show wait list
  863. if data.position
  864. @onQueue data
  865. @show()
  866. @open()
  867. @scrollToBottom()
  868. if unfinishedMessage
  869. @input.focus()
  870. onInput: =>
  871. # remove unread-state from messages
  872. for message in @el.querySelectorAll('.zammad-chat-message--unread')
  873. message.classList.remove 'zammad-chat-message--unread'
  874. sessionStorage.setItem 'unfinished_message', @input.innerHTML
  875. @onTyping()
  876. onTyping: ->
  877. # send typing start event only every 1.5 seconds
  878. return if @isTyping && @isTyping > new Date(new Date().getTime() - 1500)
  879. @isTyping = new Date()
  880. @send 'chat_session_typing',
  881. session_id: @sessionId
  882. @inactiveTimeout.start()
  883. onSubmit: (event) =>
  884. event.preventDefault()
  885. @sendMessage()
  886. sendMessage: ->
  887. message = @input.innerHTML
  888. return if !message
  889. @inactiveTimeout.start()
  890. sessionStorage.removeItem 'unfinished_message'
  891. messageElement = @view('message')
  892. message: message
  893. from: 'customer'
  894. id: @_messageCount++
  895. unreadClass: ''
  896. @maybeAddTimestamp()
  897. # add message before message typing loader
  898. if @el.querySelector('.zammad-chat-message--typing')
  899. @lastAddedType = 'typing-placeholder'
  900. @el.querySelector('.zammad-chat-message--typing').insertAdjacentHTML('beforebegin', messageElement)
  901. else
  902. @lastAddedType = 'message--customer'
  903. @body.insertAdjacentHTML('beforeend', messageElement)
  904. @input.innerHTML = ''
  905. @scrollToBottom()
  906. # send message event
  907. @send 'chat_session_message',
  908. content: message
  909. id: @_messageCount
  910. session_id: @sessionId
  911. receiveMessage: (data) =>
  912. @inactiveTimeout.start()
  913. # hide writing indicator
  914. @onAgentTypingEnd()
  915. @maybeAddTimestamp()
  916. @renderMessage
  917. message: data.message.content
  918. id: data.id
  919. from: 'agent'
  920. @scrollToBottom showHint: true
  921. renderMessage: (data) =>
  922. @lastAddedType = "message--#{ data.from }"
  923. data.unreadClass = if document.hidden then ' zammad-chat-message--unread' else ''
  924. @body.insertAdjacentHTML('beforeend', @view('message')(data))
  925. open: =>
  926. if @isOpen
  927. @log.debug 'widget already open, block'
  928. return
  929. @isOpen = true
  930. @log.debug 'open widget'
  931. @show()
  932. if !@sessionId
  933. @showLoader()
  934. @el.classList.add 'zammad-chat-is-open'
  935. remainerHeight = @el.clientHeight - @el.querySelector('.zammad-chat-header').offsetHeight
  936. @el.style.transform = "translateY(#{remainerHeight}px)"
  937. # force redraw
  938. @el.clientHeight
  939. if !@sessionId
  940. @el.addEventListener 'transitionend', @onOpenAnimationEnd
  941. @el.classList.add 'zammad-chat--animate'
  942. # force redraw
  943. @el.clientHeight
  944. # start animation
  945. @el.style.transform = ''
  946. @send('chat_session_init'
  947. url: window.location.href
  948. )
  949. else
  950. @el.style.transform = ''
  951. @onOpenAnimationEnd()
  952. onOpenAnimationEnd: =>
  953. @el.removeEventListener 'transitionend', @onOpenAnimationEnd
  954. @el.classList.remove 'zammad-chat--animate'
  955. @idleTimeout.stop()
  956. if @isFullscreen
  957. @disableScrollOnRoot()
  958. @options.onOpenAnimationEnd?()
  959. sessionClose: =>
  960. # send close
  961. @send 'chat_session_close',
  962. session_id: @sessionId
  963. # stop timer
  964. @inactiveTimeout.stop()
  965. @waitingListTimeout.stop()
  966. # delete input store
  967. sessionStorage.removeItem 'unfinished_message'
  968. # stop delay of initial queue position
  969. if @onInitialQueueDelayId
  970. clearTimeout(@onInitialQueueDelayId)
  971. @setSessionId undefined
  972. toggle: (event) =>
  973. if @isOpen
  974. @close(event)
  975. else
  976. @open(event)
  977. close: (event) =>
  978. if !@isOpen
  979. @log.debug 'can\'t close widget, it\'s not open'
  980. return
  981. if @initDelayId
  982. clearTimeout(@initDelayId)
  983. if @sessionId
  984. @log.debug 'session close before widget close'
  985. @sessionClose()
  986. @log.debug 'close widget'
  987. event.stopPropagation() if event
  988. if @isFullscreen
  989. @enableScrollOnRoot()
  990. # close window
  991. remainerHeight = @el.clientHeight - @el.querySelector('.zammad-chat-header').offsetHeight
  992. @el.addEventListener 'transitionend', @onCloseAnimationEnd
  993. @el.classList.add 'zammad-chat--animate'
  994. # force redraw
  995. document.offsetHeight
  996. # animate out
  997. @el.style.transform = "translateY(#{remainerHeight}px)"
  998. onCloseAnimationEnd: =>
  999. @el.removeEventListener 'transitionend', @onCloseAnimationEnd
  1000. @el.classList.remove 'zammad-chat-is-open', 'zammad-chat--animate'
  1001. @el.style.transform = ''
  1002. @showLoader()
  1003. @el.querySelector('.zammad-chat-welcome').classList.remove('zammad-chat-is-hidden')
  1004. @el.querySelector('.zammad-chat-agent').classList.add('zammad-chat-is-hidden')
  1005. @el.querySelector('.zammad-chat-agent-status').classList.add('zammad-chat-is-hidden')
  1006. @isOpen = false
  1007. @options.onCloseAnimationEnd?()
  1008. @io.reconnect()
  1009. onWebSocketClose: =>
  1010. return if @isOpen
  1011. if @el
  1012. @el.classList.remove('zammad-chat-is-shown')
  1013. @el.classList.remove('zammad-chat-is-loaded')
  1014. show: ->
  1015. return if @state is 'offline'
  1016. @el.classList.add('zammad-chat-is-loaded')
  1017. @el.classList.add('zammad-chat-is-shown')
  1018. disableInput: ->
  1019. @inputDisabled = true
  1020. @input.setAttribute('contenteditable', false)
  1021. @el.querySelector('.zammad-chat-send').disabled = true
  1022. @io.close()
  1023. enableInput: ->
  1024. @inputDisabled = false
  1025. @input.setAttribute('contenteditable', true)
  1026. @el.querySelector('.zammad-chat-send').disabled = false
  1027. hideModal: ->
  1028. @el.querySelector('.zammad-chat-modal').innerHTML = ''
  1029. onQueueScreen: (data) =>
  1030. @setSessionId data.session_id
  1031. # delay initial queue position, show connecting first
  1032. show = =>
  1033. @onQueue data
  1034. @waitingListTimeout.start()
  1035. if @initialQueueDelay && !@onInitialQueueDelayId
  1036. @onInitialQueueDelayId = setTimeout(show, @initialQueueDelay)
  1037. return
  1038. # stop delay of initial queue position
  1039. if @onInitialQueueDelayId
  1040. clearTimeout(@onInitialQueueDelayId)
  1041. # show queue position
  1042. show()
  1043. onQueue: (data) =>
  1044. @log.notice 'onQueue', data.position
  1045. @inQueue = true
  1046. @el.querySelector('.zammad-chat-modal').innerHTML = @view('waiting')
  1047. position: data.position
  1048. onAgentTypingStart: =>
  1049. if @stopTypingId
  1050. clearTimeout(@stopTypingId)
  1051. @stopTypingId = setTimeout(@onAgentTypingEnd, 3000)
  1052. # never display two typing indicators
  1053. return if @el.querySelector('.zammad-chat-message--typing')
  1054. @maybeAddTimestamp()
  1055. @body.insertAdjacentHTML('beforeend', @view('typingIndicator')())
  1056. # only if typing indicator is shown
  1057. return if !@isVisible(@el.querySelector('.zammad-chat-message--typing'), true)
  1058. @scrollToBottom()
  1059. onAgentTypingEnd: =>
  1060. @el.querySelector('.zammad-chat-message--typing').remove() if @el.querySelector('.zammad-chat-message--typing')
  1061. onLeaveTemporary: =>
  1062. return if !@sessionId
  1063. @send 'chat_session_leave_temporary',
  1064. session_id: @sessionId
  1065. maybeAddTimestamp: ->
  1066. timestamp = Date.now()
  1067. if !@lastTimestamp or (timestamp - @lastTimestamp) > @showTimeEveryXMinutes * 60000
  1068. label = @T('Today')
  1069. time = new Date().toTimeString().substr 0,5
  1070. if @lastAddedType is 'timestamp'
  1071. # update last time
  1072. @updateLastTimestamp label, time
  1073. @lastTimestamp = timestamp
  1074. else
  1075. # add new timestamp
  1076. @body.insertAdjacentHTML 'beforeend', @view('timestamp')
  1077. label: label
  1078. time: time
  1079. @lastTimestamp = timestamp
  1080. @lastAddedType = 'timestamp'
  1081. @scrollToBottom()
  1082. updateLastTimestamp: (label, time) ->
  1083. return if !@el
  1084. timestamps = @el.querySelectorAll('.zammad-chat-body .zammad-chat-timestamp')
  1085. return if !timestamps
  1086. timestamps[timestamps.length - 1].outerHTML = @view('timestamp')
  1087. label: label
  1088. time: time
  1089. addStatus: (status) ->
  1090. return if !@el
  1091. @maybeAddTimestamp()
  1092. @body.insertAdjacentHTML 'beforeend', @view('status')
  1093. status: status
  1094. @scrollToBottom()
  1095. detectScrolledtoBottom: =>
  1096. scrollBottom = @body.scrollTop + @body.offsetHeight
  1097. @scrolledToBottom = Math.abs(scrollBottom - @body.scrollHeight) <= @scrollSnapTolerance
  1098. @el.querySelector('.zammad-scroll-hint').classList.add('is-hidden') if @scrolledToBottom
  1099. showScrollHint: ->
  1100. @el.querySelector('.zammad-scroll-hint').classList.remove('is-hidden')
  1101. # compensate scroll
  1102. @body.scrollTop = @body.scrollTop + @el.querySelector('.zammad-scroll-hint').offsetHeight
  1103. onScrollHintClick: =>
  1104. # animate scroll
  1105. @body.scrollTo
  1106. top: @body.scrollHeight
  1107. behavior: 'smooth'
  1108. scrollToBottom: ({ showHint } = { showHint: false }) ->
  1109. if @scrolledToBottom
  1110. @body.scrollTop = @body.scrollHeight
  1111. else if showHint
  1112. @showScrollHint()
  1113. destroy: (params = {}) =>
  1114. @log.debug 'destroy widget', params
  1115. @setAgentOnlineState 'offline'
  1116. if params.remove && @el
  1117. @el.remove()
  1118. # Remove button, because it can no longer be used.
  1119. btn = document.querySelector(".#{ @options.buttonClass }")
  1120. if btn
  1121. btn.classList.add @options.inactiveClass
  1122. btn.style.display = 'none';
  1123. # stop all timer
  1124. if @waitingListTimeout
  1125. @waitingListTimeout.stop()
  1126. if @inactiveTimeout
  1127. @inactiveTimeout.stop()
  1128. if @idleTimeout
  1129. @idleTimeout.stop()
  1130. # stop ws connection
  1131. @io.close()
  1132. reconnect: =>
  1133. # set status to connecting
  1134. @log.notice 'reconnecting'
  1135. @disableInput()
  1136. @lastAddedType = 'status'
  1137. @setAgentOnlineState 'connecting'
  1138. @addStatus @T('Connection lost')
  1139. onConnectionReestablished: =>
  1140. # set status back to online
  1141. @lastAddedType = 'status'
  1142. @setAgentOnlineState 'online'
  1143. @addStatus @T('Connection re-established')
  1144. @options.onConnectionReestablished?()
  1145. onSessionClosed: (data) ->
  1146. @addStatus @T('Chat closed by %s', data.realname)
  1147. @disableInput()
  1148. @setAgentOnlineState 'offline'
  1149. @inactiveTimeout.stop()
  1150. @options.onSessionClosed?(data)
  1151. setSessionId: (id) =>
  1152. @sessionId = id
  1153. if id is undefined
  1154. sessionStorage.removeItem 'sessionId'
  1155. else
  1156. sessionStorage.setItem 'sessionId', id
  1157. onConnectionEstablished: (data) =>
  1158. # stop delay of initial queue position
  1159. if @onInitialQueueDelayId
  1160. clearTimeout @onInitialQueueDelayId
  1161. @inQueue = false
  1162. if data.agent
  1163. @agent = data.agent
  1164. if data.session_id
  1165. @setSessionId data.session_id
  1166. # empty old messages
  1167. @body.innerHTML = ''
  1168. @el.querySelector('.zammad-chat-agent').innerHTML = @view('agent')
  1169. agent: @agent
  1170. @enableInput()
  1171. @hideModal()
  1172. @el.querySelector('.zammad-chat-welcome').classList.add('zammad-chat-is-hidden')
  1173. @el.querySelector('.zammad-chat-agent').classList.remove('zammad-chat-is-hidden')
  1174. @el.querySelector('.zammad-chat-agent-status').classList.remove('zammad-chat-is-hidden')
  1175. @input.focus() if not @isFullscreen
  1176. @setAgentOnlineState 'online'
  1177. @waitingListTimeout.stop()
  1178. @idleTimeout.stop()
  1179. @inactiveTimeout.start()
  1180. @options.onConnectionEstablished?(data)
  1181. showCustomerTimeout: ->
  1182. @el.querySelector('.zammad-chat-modal').innerHTML = @view('customer_timeout')
  1183. agent: @agent.name
  1184. delay: @options.inactiveTimeout
  1185. @el.querySelector('.js-restart').addEventListener 'click', -> location.reload()
  1186. @sessionClose()
  1187. showWaitingListTimeout: ->
  1188. @el.querySelector('.zammad-chat-modal').innerHTML = @view('waiting_list_timeout')
  1189. delay: @options.watingListTimeout
  1190. @el.querySelector('.js-restart').addEventListener 'click', -> location.reload()
  1191. @sessionClose()
  1192. showLoader: ->
  1193. @el.querySelector('.zammad-chat-modal').innerHTML = @view('loader')()
  1194. setAgentOnlineState: (state) =>
  1195. @state = state
  1196. return if !@el
  1197. capitalizedState = state.charAt(0).toUpperCase() + state.slice(1)
  1198. @el.querySelector('.zammad-chat-agent-status').dataset.status = state
  1199. @el.querySelector('.zammad-chat-agent-status').textContent = @T(capitalizedState)
  1200. detectHost: ->
  1201. protocol = 'ws://'
  1202. if scriptProtocol is 'https'
  1203. protocol = 'wss://'
  1204. @options.host = "#{ protocol }#{ scriptHost }/ws"
  1205. loadCss: ->
  1206. return if !@options.cssAutoload
  1207. url = @options.cssUrl
  1208. if !url
  1209. url = @options.host
  1210. .replace(/^wss/i, 'https')
  1211. .replace(/^ws/i, 'http')
  1212. .replace(/\/ws$/i, '') # WebSocket may run on example.com/ws path
  1213. url += '/assets/chat/chat.css'
  1214. @log.debug "load css from '#{url}'"
  1215. styles = "@import url('#{url}');"
  1216. newSS = document.createElement('link')
  1217. newSS.onload = @onCssLoaded
  1218. newSS.rel = 'stylesheet'
  1219. newSS.href = 'data:text/css,' + escape(styles)
  1220. document.getElementsByTagName('head')[0].appendChild(newSS)
  1221. onCssLoaded: =>
  1222. @cssLoaded = true
  1223. if @socketReady
  1224. @onReady()
  1225. @options.onCssLoaded?()
  1226. startTimeoutObservers: =>
  1227. @idleTimeout = new Timeout(
  1228. logPrefix: 'idleTimeout'
  1229. debug: @options.debug
  1230. timeout: @options.idleTimeout
  1231. timeoutIntervallCheck: @options.idleTimeoutIntervallCheck
  1232. callback: =>
  1233. @log.debug 'Idle timeout reached, hide widget', new Date
  1234. @destroy(remove: true)
  1235. )
  1236. @inactiveTimeout = new Timeout(
  1237. logPrefix: 'inactiveTimeout'
  1238. debug: @options.debug
  1239. timeout: @options.inactiveTimeout
  1240. timeoutIntervallCheck: @options.inactiveTimeoutIntervallCheck
  1241. callback: =>
  1242. @log.debug 'Inactive timeout reached, show timeout screen.', new Date
  1243. @showCustomerTimeout()
  1244. @destroy(remove: false)
  1245. )
  1246. @waitingListTimeout = new Timeout(
  1247. logPrefix: 'waitingListTimeout'
  1248. debug: @options.debug
  1249. timeout: @options.waitingListTimeout
  1250. timeoutIntervallCheck: @options.waitingListTimeoutIntervallCheck
  1251. callback: =>
  1252. @log.debug 'Waiting list timeout reached, show timeout screen.', new Date
  1253. @showWaitingListTimeout()
  1254. @destroy(remove: false)
  1255. )
  1256. disableScrollOnRoot: ->
  1257. @rootScrollOffset = @scrollRoot.scrollTop
  1258. @scrollRoot.style.overflow = 'hidden'
  1259. @scrollRoot.style.position = 'fixed'
  1260. enableScrollOnRoot: ->
  1261. @scrollRoot.scrollTop = @rootScrollOffset
  1262. @scrollRoot.style.overflow = ''
  1263. @scrollRoot.style.position = ''
  1264. # based on https://github.com/customd/jquery-visible/blob/master/jquery.visible.js
  1265. # to have not dependency, port to coffeescript
  1266. isVisible: (el, partial, hidden, direction) ->
  1267. return if el.length < 1
  1268. vpWidth = window.innerWidth
  1269. vpHeight = window.innerHeight
  1270. direction = if direction then direction else 'both'
  1271. clientSize = if hidden is true then t.offsetWidth * t.offsetHeight else true
  1272. rec = el.getBoundingClientRect()
  1273. tViz = rec.top >= 0 && rec.top < vpHeight
  1274. bViz = rec.bottom > 0 && rec.bottom <= vpHeight
  1275. lViz = rec.left >= 0 && rec.left < vpWidth
  1276. rViz = rec.right > 0 && rec.right <= vpWidth
  1277. vVisible = if partial then tViz || bViz else tViz && bViz
  1278. hVisible = if partial then lViz || rViz else lViz && rViz
  1279. if direction is 'both'
  1280. return clientSize && vVisible && hVisible
  1281. else if direction is 'vertical'
  1282. return clientSize && vVisible
  1283. else if direction is 'horizontal'
  1284. return clientSize && hVisible
  1285. isRetina: ->
  1286. if window.matchMedia
  1287. mq = window.matchMedia('only screen and (min--moz-device-pixel-ratio: 1.3), only screen and (-o-min-device-pixel-ratio: 2.6/2), only screen and (-webkit-min-device-pixel-ratio: 1.3), only screen and (min-device-pixel-ratio: 1.3), only screen and (min-resolution: 1.3dppx)')
  1288. return (mq && mq.matches || (window.devicePixelRatio > 1))
  1289. false
  1290. resizeImage: (dataURL, x = 'auto', y = 'auto', sizeFactor = 1, type, quallity, callback, force = true) ->
  1291. # load image from data url
  1292. imageObject = new Image()
  1293. imageObject.onload = ->
  1294. imageWidth = imageObject.width
  1295. imageHeight = imageObject.height
  1296. console.log('ImageService', 'current size', imageWidth, imageHeight)
  1297. if y is 'auto' && x is 'auto'
  1298. x = imageWidth
  1299. y = imageHeight
  1300. # get auto dimensions
  1301. if y is 'auto'
  1302. factor = imageWidth / x
  1303. y = imageHeight / factor
  1304. if x is 'auto'
  1305. factor = imageWidth / y
  1306. x = imageHeight / factor
  1307. # check if resize is needed
  1308. resize = false
  1309. if x < imageWidth || y < imageHeight
  1310. resize = true
  1311. x = x * sizeFactor
  1312. y = y * sizeFactor
  1313. else
  1314. x = imageWidth
  1315. y = imageHeight
  1316. # create canvas and set dimensions
  1317. canvas = document.createElement('canvas')
  1318. canvas.width = x
  1319. canvas.height = y
  1320. # draw image on canvas and set image dimensions
  1321. context = canvas.getContext('2d')
  1322. context.drawImage(imageObject, 0, 0, x, y)
  1323. # set quallity based on image size
  1324. if quallity == 'auto'
  1325. if x < 200 && y < 200
  1326. quallity = 1
  1327. else if x < 400 && y < 400
  1328. quallity = 0.9
  1329. else if x < 600 && y < 600
  1330. quallity = 0.8
  1331. else if x < 900 && y < 900
  1332. quallity = 0.7
  1333. else
  1334. quallity = 0.6
  1335. # execute callback with resized image
  1336. newDataUrl = canvas.toDataURL(type, quallity)
  1337. if resize
  1338. console.log('ImageService', 'resize', x/sizeFactor, y/sizeFactor, quallity, (newDataUrl.length * 0.75)/1024/1024, 'in mb')
  1339. callback(newDataUrl, x/sizeFactor, y/sizeFactor, true)
  1340. return
  1341. console.log('ImageService', 'no resize', x, y, quallity, (newDataUrl.length * 0.75)/1024/1024, 'in mb')
  1342. callback(newDataUrl, x, y, false)
  1343. # load image from data url
  1344. imageObject.src = dataURL
  1345. # taken from https://stackoverflow.com/questions/6690752/insert-html-at-caret-in-a-contenteditable-div/6691294#6691294
  1346. pasteHtmlAtCaret: (html) ->
  1347. sel = undefined
  1348. range = undefined
  1349. if window.getSelection
  1350. sel = window.getSelection()
  1351. if sel.getRangeAt && sel.rangeCount
  1352. range = sel.getRangeAt(0)
  1353. range.deleteContents()
  1354. el = document.createElement('div')
  1355. el.innerHTML = html
  1356. frag = document.createDocumentFragment(node, lastNode)
  1357. while node = el.firstChild
  1358. lastNode = frag.appendChild(node)
  1359. range.insertNode(frag)
  1360. if lastNode
  1361. range = range.cloneRange()
  1362. range.setStartAfter(lastNode)
  1363. range.collapse(true)
  1364. sel.removeAllRanges()
  1365. sel.addRange(range)
  1366. else if document.selection && document.selection.type != 'Control'
  1367. document.selection.createRange().pasteHTML(html)
  1368. # (C) sbrin - https://github.com/sbrin
  1369. # https://gist.github.com/sbrin/6801034
  1370. wordFilter: (editor) ->
  1371. content = editor.html()
  1372. # Word comments like conditional comments etc
  1373. content = content.replace(/<!--[\s\S]+?-->/gi, '')
  1374. # Remove comments, scripts (e.g., msoShowComment), XML tag, VML content,
  1375. # MS Office namespaced tags, and a few other tags
  1376. content = content.replace(/<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|img|meta|link|style|\w:\w+)(?=[\s\/>]))[^>]*>/gi, '')
  1377. # Convert <s> into <strike> for line-though
  1378. content = content.replace(/<(\/?)s>/gi, '<$1strike>')
  1379. # Replace nbsp entites to char since it's easier to handle
  1380. # content = content.replace(/&nbsp;/gi, "\u00a0")
  1381. content = content.replace(/&nbsp;/gi, ' ')
  1382. # Convert <span style="mso-spacerun:yes">___</span> to string of alternating
  1383. # breaking/non-breaking spaces of same length
  1384. #content = content.replace(/<span\s+style\s*=\s*"\s*mso-spacerun\s*:\s*yes\s*;?\s*"\s*>([\s\u00a0]*)<\/span>/gi, (str, spaces) ->
  1385. # return (spaces.length > 0) ? spaces.replace(/./, " ").slice(Math.floor(spaces.length/2)).split("").join("\u00a0") : ''
  1386. #)
  1387. editor.innerHTML = content
  1388. # Parse out list indent level for lists
  1389. for p in editor.querySelectorAll('p')
  1390. str = p.getAttribute('style')
  1391. matches = /mso-list:\w+ \w+([0-9]+)/.exec(str)
  1392. if matches
  1393. p.dataset._listLevel = parseInt(matches[1], 10)
  1394. # Parse Lists
  1395. last_level = 0
  1396. pnt = null
  1397. for p in editor.querySelectorAll('p')
  1398. cur_level = p.dataset._listLevel
  1399. if cur_level != undefined
  1400. txt = p.textContent
  1401. list_tag = '<ul></ul>'
  1402. if (/^\s*\w+\./.test(txt))
  1403. matches = /([0-9])\./.exec(txt)
  1404. if matches
  1405. start = parseInt(matches[1], 10)
  1406. list_tag = start>1 ? '<ol start="' + start + '"></ol>' : '<ol></ol>'
  1407. else
  1408. list_tag = '<ol></ol>'
  1409. if cur_level > last_level
  1410. if last_level == 0
  1411. p.insertAdjacentHTML 'beforebegin', list_tag
  1412. pnt = p.previousElementSibling
  1413. else
  1414. pnt.insertAdjacentHTML 'beforeend', list_tag
  1415. if cur_level < last_level
  1416. for i in [i..last_level-cur_level]
  1417. pnt = pnt.parentNode
  1418. p.querySelector('span:first').remove() if p.querySelector('span:first')
  1419. pnt.insertAdjacentHTML 'beforeend', '<li>' + p.innerHTML + '</li>'
  1420. p.remove()
  1421. last_level = cur_level
  1422. else
  1423. last_level = 0
  1424. el.removeAttribute('style') for el in editor.querySelectorAll('[style]')
  1425. el.removeAttribute('align') for el in editor.querySelectorAll('[align]')
  1426. el.outerHTML = el.innerHTML for el in editor.querySelectorAll('span')
  1427. el.remove() for el in editor.querySelectorAll('span:empty')
  1428. el.removeAttribute('class') for el in editor.querySelectorAll("[class^='Mso']")
  1429. el.remove() for el in editor.querySelectorAll('p:empty')
  1430. editor
  1431. removeAttribute: (element) ->
  1432. return if !element
  1433. for att in element.attributes
  1434. element.removeAttribute(att.name)
  1435. removeAttributes: (html) =>
  1436. for node in html.querySelectorAll('*')
  1437. @removeAttribute node
  1438. html
  1439. window.ZammadChat = ZammadChat