chat-no-jquery.coffee 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659
  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. 'ru':
  389. '<strong>Chat</strong> with us!': '<strong>Напишите</strong> нам!'
  390. 'All colleagues are busy.': 'Все коллеги заняты.'
  391. 'Chat closed by %s': 'Чат закрыт %s'
  392. 'Compose your message…': 'Составьте сообщение…'
  393. 'Connecting': 'Подключение'
  394. 'Connection lost': 'Подключение потеряно'
  395. 'Connection re-established': 'Подключение восстановлено'
  396. 'Offline': 'Оффлайн'
  397. 'Online': 'В сети'
  398. 'Scroll down to see new messages': 'Прокрутите вниз, чтобы увидеть новые сообщения'
  399. 'Send': 'Отправить'
  400. 'Since you didn\'t respond in the last %s minutes your conversation was closed.': 'Поскольку Вы не ответили в течение последних %s минут, Ваш разговор был закрыт.'
  401. 'Since you didn\'t respond in the last %s minutes your conversation with <strong>%s</strong> was closed.': 'Поскольку Вы не ответили в течение последних %s минут, Ваш разговор с <strong>%s</strong> был закрыт.'
  402. 'Start new conversation': 'Начать новый разговор'
  403. 'Today': 'Сегодня'
  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!': 'Извините, получение свободного слота занимает больше времени, чем ожидалось. Пожалуйста, повторите попытку позже или отправьте нам электронное письмо. Благодарим Вас!'
  405. 'You are on waiting list position <strong>%s</strong>.': 'Вы находитесь в списке ожидания <strong>%s</strong>.'
  406. 'sr':
  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 минут(a), ваш разговор је завршен.'
  419. 'Since you didn\'t respond in the last %s minutes your conversation with <strong>%s</strong> was closed.': 'Пошто нисте одговорили у последњих %s минут(a), ваш разговор са <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-latn-rs':
  425. '<strong>Chat</strong> with us!': '<strong>Ćaskajte</strong> sa nama!'
  426. 'All colleagues are busy.': 'Sve kolege su zauzete.'
  427. 'Chat closed by %s': 'Ćaskanje zatvoreno od strane %s'
  428. 'Compose your message…': 'Napišite poruku…'
  429. 'Connecting': 'Povezivanje'
  430. 'Connection lost': 'Veza je izgubljena'
  431. 'Connection re-established': 'Veza je ponovo uspostavljena'
  432. 'Offline': 'Odsutan(a)'
  433. 'Online': 'Dostupan(a)'
  434. 'Scroll down to see new messages': 'Skrolujte na dole za nove poruke'
  435. 'Send': 'Pošalji'
  436. '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.'
  437. '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.'
  438. 'Start new conversation': 'Započni novi razgovor'
  439. 'Today': 'Danas'
  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!': 'Ž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!'
  441. 'You are on waiting list position <strong>%s</strong>.': 'Vi ste trenutno <strong>%s.</strong> u redu za čekanje.'
  442. 'sv':
  443. '<strong>Chat</strong> with us!': '<strong>Chatta</strong> med oss!'
  444. 'All colleagues are busy.': 'Alla kollegor är upptagna.'
  445. 'Chat closed by %s': 'Chatt stängd av %s'
  446. 'Compose your message…': 'Skriv ditt meddelande …'
  447. 'Connecting': 'Ansluter'
  448. 'Connection lost': 'Anslutningen försvann'
  449. 'Connection re-established': 'Anslutningen återupprättas'
  450. 'Offline': 'Offline'
  451. 'Online': 'Online'
  452. 'Scroll down to see new messages': 'Bläddra ner för att se nya meddelanden'
  453. 'Send': 'Skicka'
  454. 'Since you didn\'t respond in the last %s minutes your conversation was closed.': 'Din chatt avslutades då du inte svarade inom %s minuter.'
  455. '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>.'
  456. 'Start new conversation': 'Starta ny konversation'
  457. 'Today': 'Idag'
  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!': '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!'
  459. 'You are on waiting list position <strong>%s</strong>.': 'Du är på väntelistan som position <strong>%s</strong>.'
  460. 'zh-cn':
  461. '<strong>Chat</strong> with us!': '发起<strong>即时对话</strong>!'
  462. 'All colleagues are busy.': '所有同事都很忙。'
  463. 'Chat closed by %s': '对话已被 %s 关闭'
  464. 'Compose your message…': '编辑您的信息…'
  465. 'Connecting': '连接中'
  466. 'Connection lost': '连接丢失'
  467. 'Connection re-established': '正在重新建立连接'
  468. 'Offline': '离线'
  469. 'Online': '在线'
  470. 'Scroll down to see new messages': '向下滚动以查看新消息'
  471. 'Send': '发送'
  472. 'Since you didn\'t respond in the last %s minutes your conversation was closed.': '"由于您超过 %s 分钟没有任何回复'
  473. 'Since you didn\'t respond in the last %s minutes your conversation with <strong>%s</strong> was closed.': '"由于您超过 %s 分钟没有回复'
  474. 'Start new conversation': '开始新的会话'
  475. 'Today': '今天'
  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!': ''
  477. 'You are on waiting list position <strong>%s</strong>.': '您目前的等候位置是第 <strong>%s</strong> 位.'
  478. # ZAMMAD_TRANSLATIONS_END
  479. sessionId: undefined
  480. scrolledToBottom: true
  481. scrollSnapTolerance: 10
  482. richTextFormatKey:
  483. 66: true # b
  484. 73: true # i
  485. 85: true # u
  486. 83: true # s
  487. T: (string, items...) =>
  488. if @options.lang && @options.lang isnt 'en'
  489. if !@translations[@options.lang]
  490. @log.notice "Translation '#{@options.lang}' needed!"
  491. else
  492. translations = @translations[@options.lang]
  493. if !translations[string]
  494. @log.notice "Translation needed for '#{string}'"
  495. string = translations[string] || string
  496. if items
  497. for item in items
  498. string = string.replace(/%s/, item)
  499. string
  500. view: (name) =>
  501. return (options) =>
  502. if !options
  503. options = {}
  504. options.T = @T
  505. options.background = @options.background
  506. options.flat = @options.flat
  507. options.fontSize = @options.fontSize
  508. return window.zammadChatTemplates[name](options)
  509. constructor: (options) ->
  510. super(options)
  511. # jQuery migration
  512. if typeof jQuery != 'undefined' && @options.target instanceof jQuery
  513. @log.notice 'Chat: target option is a jQuery object. jQuery is not a requirement for the chat any more.'
  514. @options.target = @options.target.get(0)
  515. # fullscreen
  516. @isFullscreen = (window.matchMedia and window.matchMedia('(max-width: 768px)').matches)
  517. @scrollRoot = @getScrollRoot()
  518. # check prerequisites
  519. if !window.WebSocket or !sessionStorage
  520. @state = 'unsupported'
  521. @log.notice 'Chat: Browser not supported!'
  522. return
  523. if !@options.chatId
  524. @state = 'unsupported'
  525. @log.error 'Chat: need chatId as option!'
  526. return
  527. # detect language
  528. if !@options.lang
  529. @options.lang = document.documentElement.getAttribute('lang')
  530. if @options.lang
  531. if !@translations[@options.lang]
  532. @log.debug "lang: No #{@options.lang} found, try first two letters"
  533. @options.lang = @options.lang.replace(/-.+?$/, '') # replace "-xx" of xx-xx
  534. @log.debug "lang: #{@options.lang}"
  535. # detect host
  536. @detectHost() if !@options.host
  537. @loadCss()
  538. @io = new Io(@options)
  539. @io.set(
  540. onOpen: @render
  541. onClose: @onWebSocketClose
  542. onMessage: @onWebSocketMessage
  543. onError: @onError
  544. )
  545. @io.connect()
  546. getScrollRoot: ->
  547. return document.scrollingElement if 'scrollingElement' of document
  548. html = document.documentElement
  549. start = parseInt(html.pageYOffset, 10)
  550. html.pageYOffset = start + 1
  551. end = parseInt(html.pageYOffset, 10)
  552. html.pageYOffset = start
  553. return if end > start then html else document.body
  554. render: =>
  555. if !@el || !document.querySelector('.zammad-chat')
  556. @renderBase()
  557. # disable open button
  558. btn = document.querySelector(".#{ @options.buttonClass }")
  559. if btn
  560. btn.classList.add @options.inactiveClass
  561. @setAgentOnlineState 'online'
  562. @log.debug 'widget rendered'
  563. @startTimeoutObservers()
  564. @idleTimeout.start()
  565. # get current chat status
  566. @sessionId = sessionStorage.getItem('sessionId')
  567. @send 'chat_status_customer',
  568. session_id: @sessionId
  569. url: window.location.href
  570. renderBase: ->
  571. @el.remove() if @el
  572. @options.target.insertAdjacentHTML('beforeend', @view('chat')(
  573. title: @options.title,
  574. scrollHint: @options.scrollHint
  575. ))
  576. @el = @options.target.querySelector('.zammad-chat')
  577. @input = @el.querySelector('.zammad-chat-input')
  578. @body = @el.querySelector('.zammad-chat-body')
  579. # start bindings
  580. @el.querySelector('.js-chat-open').addEventListener('click', @open)
  581. @el.querySelector('.js-chat-toggle').addEventListener('click', @toggle)
  582. @el.querySelector('.js-chat-status').addEventListener('click', @stopPropagation)
  583. @el.querySelector('.zammad-chat-controls').addEventListener('submit', @onSubmit)
  584. @body.addEventListener('scroll', @detectScrolledtoBottom)
  585. @el.querySelector('.zammad-scroll-hint').addEventListener('click', @onScrollHintClick)
  586. @input.addEventListener('keydown', @onKeydown)
  587. @input.addEventListener('input', @onInput)
  588. @input.addEventListener('paste', @onPaste)
  589. @input.addEventListener('drop', @onDrop)
  590. window.addEventListener('beforeunload', @onLeaveTemporary)
  591. window.addEventListener('hashchange', =>
  592. if @isOpen
  593. if @sessionId
  594. @send 'chat_session_notice',
  595. session_id: @sessionId
  596. message: window.location.href
  597. return
  598. @idleTimeout.start()
  599. )
  600. stopPropagation: (event) ->
  601. event.stopPropagation()
  602. onDrop: (e) =>
  603. e.stopPropagation()
  604. e.preventDefault()
  605. if window.dataTransfer # ie
  606. dataTransfer = window.dataTransfer
  607. else if e.dataTransfer # other browsers
  608. dataTransfer = e.dataTransfer
  609. else
  610. throw 'No clipboardData support'
  611. x = e.clientX
  612. y = e.clientY
  613. file = dataTransfer.files[0]
  614. # look for images
  615. if file.type.match('image.*')
  616. reader = new FileReader()
  617. reader.onload = (e) =>
  618. # Insert the image at the carat
  619. insert = (dataUrl, width) =>
  620. # adapt image if we are on retina devices
  621. if @isRetina()
  622. width = width / 2
  623. result = dataUrl
  624. img = new Image()
  625. img.style.width = '100%'
  626. img.style.maxWidth = width + 'px'
  627. img.src = result
  628. if document.caretPositionFromPoint
  629. pos = document.caretPositionFromPoint(x, y)
  630. range = document.createRange()
  631. range.setStart(pos.offsetNode, pos.offset)
  632. range.collapse()
  633. range.insertNode(img)
  634. else if document.caretRangeFromPoint
  635. range = document.caretRangeFromPoint(x, y)
  636. range.insertNode(img)
  637. else
  638. console.log('could not find carat')
  639. # resize if to big
  640. @resizeImage(e.target.result, 460, 'auto', 2, 'image/jpeg', 'auto', insert)
  641. reader.readAsDataURL(file)
  642. onPaste: (e) =>
  643. e.stopPropagation()
  644. e.preventDefault()
  645. if e.clipboardData
  646. clipboardData = e.clipboardData
  647. else if window.clipboardData
  648. clipboardData = window.clipboardData
  649. else if e.clipboardData
  650. clipboardData = e.clipboardData
  651. else
  652. throw 'No clipboardData support'
  653. imageInserted = false
  654. if clipboardData && clipboardData.items && clipboardData.items[0]
  655. item = clipboardData.items[0]
  656. if item.kind == 'file' && (item.type == 'image/png' || item.type == 'image/jpeg')
  657. imageFile = item.getAsFile()
  658. reader = new FileReader()
  659. reader.onload = (e) =>
  660. insert = (dataUrl, width) =>
  661. # adapt image if we are on retina devices
  662. if @isRetina()
  663. width = width / 2
  664. img = new Image()
  665. img.style.width = '100%'
  666. img.style.maxWidth = width + 'px'
  667. img.src = dataUrl
  668. document.execCommand('insertHTML', false, img)
  669. # resize if to big
  670. @resizeImage(e.target.result, 460, 'auto', 2, 'image/jpeg', 'auto', insert)
  671. reader.readAsDataURL(imageFile)
  672. imageInserted = true
  673. return if imageInserted
  674. # check existing + paste text for limit
  675. text = undefined
  676. docType = undefined
  677. try
  678. text = clipboardData.getData('text/html')
  679. docType = 'html'
  680. if !text || text.length is 0
  681. docType = 'text'
  682. text = clipboardData.getData('text/plain')
  683. if !text || text.length is 0
  684. docType = 'text2'
  685. text = clipboardData.getData('text')
  686. catch e
  687. console.log('Sorry, can\'t insert markup because browser is not supporting it.')
  688. docType = 'text3'
  689. text = clipboardData.getData('text')
  690. if docType is 'text' || docType is 'text2' || docType is 'text3'
  691. text = '<div>' + text.replace(/\n/g, '</div><div>') + '</div>'
  692. text = text.replace(/<div><\/div>/g, '<div><br></div>')
  693. console.log('p', docType, text)
  694. if docType is 'html'
  695. html = document.createElement('div')
  696. # can't log because might contain malicious content
  697. # @log.debug 'HTML clipboard', text
  698. sanitized = DOMPurify.sanitize(text)
  699. @log.debug 'sanitized HTML clipboard', sanitized
  700. html.innerHTML = sanitized
  701. match = false
  702. htmlTmp = text
  703. regex = new RegExp('<(/w|w)\:[A-Za-z]')
  704. if htmlTmp.match(regex)
  705. match = true
  706. htmlTmp = htmlTmp.replace(regex, '')
  707. regex = new RegExp('<(/o|o)\:[A-Za-z]')
  708. if htmlTmp.match(regex)
  709. match = true
  710. htmlTmp = htmlTmp.replace(regex, '')
  711. if match
  712. html = @wordFilter(html)
  713. #html
  714. for node in html.childNodes
  715. if node.nodeType == 8
  716. node.remove()
  717. # remove tags, keep content
  718. for node in html.querySelectorAll('a, font, small, time, form, label')
  719. node.outerHTML = node.innerHTML
  720. # replace tags with generic div
  721. # New type of the tag
  722. replacementTag = 'div';
  723. # Replace all x tags with the type of replacementTag
  724. for node in html.querySelectorAll('textarea')
  725. outer = node.outerHTML
  726. # Replace opening tag
  727. regex = new RegExp('<' + node.tagName, 'i')
  728. newTag = outer.replace(regex, '<' + replacementTag)
  729. # Replace closing tag
  730. regex = new RegExp('</' + node.tagName, 'i')
  731. newTag = newTag.replace(regex, '</' + replacementTag)
  732. node.outerHTML = newTag
  733. # remove tags & content
  734. for node in html.querySelectorAll('font, img, svg, input, select, button, style, applet, embed, noframes, canvas, script, frame, iframe, meta, link, title, head, fieldset')
  735. node.remove()
  736. @removeAttributes(html)
  737. text = html.innerHTML
  738. # as fallback, insert html via pasteHtmlAtCaret (for IE 11 and lower)
  739. if docType is 'text3'
  740. @pasteHtmlAtCaret(text)
  741. else
  742. document.execCommand('insertHTML', false, text)
  743. true
  744. onKeydown: (e) =>
  745. # check for enter
  746. if not @inputDisabled and not e.shiftKey and e.keyCode is 13
  747. e.preventDefault()
  748. @sendMessage()
  749. richtTextControl = false
  750. if !e.altKey && !e.ctrlKey && e.metaKey
  751. richtTextControl = true
  752. else if !e.altKey && e.ctrlKey && !e.metaKey
  753. richtTextControl = true
  754. if richtTextControl && @richTextFormatKey[ e.keyCode ]
  755. e.preventDefault()
  756. if e.keyCode is 66
  757. document.execCommand('bold')
  758. return true
  759. if e.keyCode is 73
  760. document.execCommand('italic')
  761. return true
  762. if e.keyCode is 85
  763. document.execCommand('underline')
  764. return true
  765. if e.keyCode is 83
  766. document.execCommand('strikeThrough')
  767. return true
  768. send: (event, data = {}) =>
  769. data.chat_id = @options.chatId
  770. @io.send(event, data)
  771. onWebSocketMessage: (pipes) =>
  772. for pipe in pipes
  773. @log.debug 'ws:onmessage', pipe
  774. switch pipe.event
  775. when 'chat_error'
  776. @log.notice pipe.data
  777. if pipe.data && pipe.data.state is 'chat_disabled'
  778. @destroy(remove: true)
  779. when 'chat_session_message'
  780. return if pipe.data.self_written
  781. @receiveMessage pipe.data
  782. when 'chat_session_typing'
  783. return if pipe.data.self_written
  784. @onAgentTypingStart()
  785. when 'chat_session_start'
  786. @onConnectionEstablished pipe.data
  787. when 'chat_session_queue'
  788. @onQueueScreen pipe.data
  789. when 'chat_session_closed'
  790. @onSessionClosed pipe.data
  791. when 'chat_session_left'
  792. @onSessionClosed pipe.data
  793. when 'chat_status_customer'
  794. switch pipe.data.state
  795. when 'online'
  796. @sessionId = undefined
  797. if !@options.cssAutoload || @cssLoaded
  798. @onReady()
  799. else
  800. @socketReady = true
  801. when 'offline'
  802. @onError 'Zammad Chat: No agent online'
  803. when 'chat_disabled'
  804. @onError 'Zammad Chat: Chat is disabled'
  805. when 'no_seats_available'
  806. @onError "Zammad Chat: Too many clients in queue. Clients in queue: #{pipe.data.queue}"
  807. when 'reconnect'
  808. @onReopenSession pipe.data
  809. onReady: ->
  810. @log.debug 'widget ready for use'
  811. btn = document.querySelector(".#{ @options.buttonClass }")
  812. if btn
  813. btn.addEventListener('click', @open)
  814. btn.classList.remove(@options.inactiveClass)
  815. @options.onReady?()
  816. if @options.show
  817. @show()
  818. onError: (message) =>
  819. @log.debug message
  820. @addStatus(message)
  821. btn = document.querySelector(".#{ @options.buttonClass }")
  822. if btn
  823. btn.classList.add('zammad-chat-is-hidden')
  824. if @isOpen
  825. @disableInput()
  826. @destroy(remove: false)
  827. else
  828. @destroy(remove: true)
  829. @options.onError?(message)
  830. onReopenSession: (data) =>
  831. @log.debug 'old messages', data.session
  832. @inactiveTimeout.start()
  833. unfinishedMessage = sessionStorage.getItem 'unfinished_message'
  834. # rerender chat history
  835. if data.agent
  836. @onConnectionEstablished(data)
  837. for message in data.session
  838. @renderMessage
  839. message: message.content
  840. id: message.id
  841. from: if message.created_by_id then 'agent' else 'customer'
  842. if unfinishedMessage
  843. @input.innerHTML = unfinishedMessage
  844. # show wait list
  845. if data.position
  846. @onQueue data
  847. @show()
  848. @open()
  849. @scrollToBottom()
  850. if unfinishedMessage
  851. @input.focus()
  852. onInput: =>
  853. # remove unread-state from messages
  854. for message in @el.querySelectorAll('.zammad-chat-message--unread')
  855. message.classList.remove 'zammad-chat-message--unread'
  856. sessionStorage.setItem 'unfinished_message', @input.innerHTML
  857. @onTyping()
  858. onTyping: ->
  859. # send typing start event only every 1.5 seconds
  860. return if @isTyping && @isTyping > new Date(new Date().getTime() - 1500)
  861. @isTyping = new Date()
  862. @send 'chat_session_typing',
  863. session_id: @sessionId
  864. @inactiveTimeout.start()
  865. onSubmit: (event) =>
  866. event.preventDefault()
  867. @sendMessage()
  868. sendMessage: ->
  869. message = @input.innerHTML
  870. return if !message
  871. @inactiveTimeout.start()
  872. sessionStorage.removeItem 'unfinished_message'
  873. messageElement = @view('message')
  874. message: message
  875. from: 'customer'
  876. id: @_messageCount++
  877. unreadClass: ''
  878. @maybeAddTimestamp()
  879. # add message before message typing loader
  880. if @el.querySelector('.zammad-chat-message--typing')
  881. @lastAddedType = 'typing-placeholder'
  882. @el.querySelector('.zammad-chat-message--typing').insertAdjacentHTML('beforebegin', messageElement)
  883. else
  884. @lastAddedType = 'message--customer'
  885. @body.insertAdjacentHTML('beforeend', messageElement)
  886. @input.innerHTML = ''
  887. @scrollToBottom()
  888. # send message event
  889. @send 'chat_session_message',
  890. content: message
  891. id: @_messageCount
  892. session_id: @sessionId
  893. receiveMessage: (data) =>
  894. @inactiveTimeout.start()
  895. # hide writing indicator
  896. @onAgentTypingEnd()
  897. @maybeAddTimestamp()
  898. @renderMessage
  899. message: data.message.content
  900. id: data.id
  901. from: 'agent'
  902. @scrollToBottom showHint: true
  903. renderMessage: (data) =>
  904. @lastAddedType = "message--#{ data.from }"
  905. data.unreadClass = if document.hidden then ' zammad-chat-message--unread' else ''
  906. @body.insertAdjacentHTML('beforeend', @view('message')(data))
  907. open: =>
  908. if @isOpen
  909. @log.debug 'widget already open, block'
  910. return
  911. @isOpen = true
  912. @log.debug 'open widget'
  913. @show()
  914. if !@sessionId
  915. @showLoader()
  916. @el.classList.add 'zammad-chat-is-open'
  917. remainerHeight = @el.clientHeight - @el.querySelector('.zammad-chat-header').offsetHeight
  918. @el.style.transform = "translateY(#{remainerHeight}px)"
  919. # force redraw
  920. @el.clientHeight
  921. if !@sessionId
  922. @el.addEventListener 'transitionend', @onOpenAnimationEnd
  923. @el.classList.add 'zammad-chat--animate'
  924. # force redraw
  925. @el.clientHeight
  926. # start animation
  927. @el.style.transform = ''
  928. @send('chat_session_init'
  929. url: window.location.href
  930. )
  931. else
  932. @el.style.transform = ''
  933. @onOpenAnimationEnd()
  934. onOpenAnimationEnd: =>
  935. @el.removeEventListener 'transitionend', @onOpenAnimationEnd
  936. @el.classList.remove 'zammad-chat--animate'
  937. @idleTimeout.stop()
  938. if @isFullscreen
  939. @disableScrollOnRoot()
  940. @options.onOpenAnimationEnd?()
  941. sessionClose: =>
  942. # send close
  943. @send 'chat_session_close',
  944. session_id: @sessionId
  945. # stop timer
  946. @inactiveTimeout.stop()
  947. @waitingListTimeout.stop()
  948. # delete input store
  949. sessionStorage.removeItem 'unfinished_message'
  950. # stop delay of initial queue position
  951. if @onInitialQueueDelayId
  952. clearTimeout(@onInitialQueueDelayId)
  953. @setSessionId undefined
  954. toggle: (event) =>
  955. if @isOpen
  956. @close(event)
  957. else
  958. @open(event)
  959. close: (event) =>
  960. if !@isOpen
  961. @log.debug 'can\'t close widget, it\'s not open'
  962. return
  963. if @initDelayId
  964. clearTimeout(@initDelayId)
  965. if @sessionId
  966. @log.debug 'session close before widget close'
  967. @sessionClose()
  968. @log.debug 'close widget'
  969. event.stopPropagation() if event
  970. if @isFullscreen
  971. @enableScrollOnRoot()
  972. # close window
  973. remainerHeight = @el.clientHeight - @el.querySelector('.zammad-chat-header').offsetHeight
  974. @el.addEventListener 'transitionend', @onCloseAnimationEnd
  975. @el.classList.add 'zammad-chat--animate'
  976. # force redraw
  977. document.offsetHeight
  978. # animate out
  979. @el.style.transform = "translateY(#{remainerHeight}px)"
  980. onCloseAnimationEnd: =>
  981. @el.removeEventListener 'transitionend', @onCloseAnimationEnd
  982. @el.classList.remove 'zammad-chat-is-open', 'zammad-chat--animate'
  983. @el.style.transform = ''
  984. @showLoader()
  985. @el.querySelector('.zammad-chat-welcome').classList.remove('zammad-chat-is-hidden')
  986. @el.querySelector('.zammad-chat-agent').classList.add('zammad-chat-is-hidden')
  987. @el.querySelector('.zammad-chat-agent-status').classList.add('zammad-chat-is-hidden')
  988. @isOpen = false
  989. @options.onCloseAnimationEnd?()
  990. @io.reconnect()
  991. onWebSocketClose: =>
  992. return if @isOpen
  993. if @el
  994. @el.classList.remove('zammad-chat-is-shown')
  995. @el.classList.remove('zammad-chat-is-loaded')
  996. show: ->
  997. return if @state is 'offline'
  998. @el.classList.add('zammad-chat-is-loaded')
  999. @el.classList.add('zammad-chat-is-shown')
  1000. disableInput: ->
  1001. @inputDisabled = true
  1002. @input.setAttribute('contenteditable', false)
  1003. @el.querySelector('.zammad-chat-send').disabled = true
  1004. @io.close()
  1005. enableInput: ->
  1006. @inputDisabled = false
  1007. @input.setAttribute('contenteditable', true)
  1008. @el.querySelector('.zammad-chat-send').disabled = false
  1009. hideModal: ->
  1010. @el.querySelector('.zammad-chat-modal').innerHTML = ''
  1011. onQueueScreen: (data) =>
  1012. @setSessionId data.session_id
  1013. # delay initial queue position, show connecting first
  1014. show = =>
  1015. @onQueue data
  1016. @waitingListTimeout.start()
  1017. if @initialQueueDelay && !@onInitialQueueDelayId
  1018. @onInitialQueueDelayId = setTimeout(show, @initialQueueDelay)
  1019. return
  1020. # stop delay of initial queue position
  1021. if @onInitialQueueDelayId
  1022. clearTimeout(@onInitialQueueDelayId)
  1023. # show queue position
  1024. show()
  1025. onQueue: (data) =>
  1026. @log.notice 'onQueue', data.position
  1027. @inQueue = true
  1028. @el.querySelector('.zammad-chat-modal').innerHTML = @view('waiting')
  1029. position: data.position
  1030. onAgentTypingStart: =>
  1031. if @stopTypingId
  1032. clearTimeout(@stopTypingId)
  1033. @stopTypingId = setTimeout(@onAgentTypingEnd, 3000)
  1034. # never display two typing indicators
  1035. return if @el.querySelector('.zammad-chat-message--typing')
  1036. @maybeAddTimestamp()
  1037. @body.insertAdjacentHTML('beforeend', @view('typingIndicator')())
  1038. # only if typing indicator is shown
  1039. return if !@isVisible(@el.querySelector('.zammad-chat-message--typing'), true)
  1040. @scrollToBottom()
  1041. onAgentTypingEnd: =>
  1042. @el.querySelector('.zammad-chat-message--typing').remove() if @el.querySelector('.zammad-chat-message--typing')
  1043. onLeaveTemporary: =>
  1044. return if !@sessionId
  1045. @send 'chat_session_leave_temporary',
  1046. session_id: @sessionId
  1047. maybeAddTimestamp: ->
  1048. timestamp = Date.now()
  1049. if !@lastTimestamp or (timestamp - @lastTimestamp) > @showTimeEveryXMinutes * 60000
  1050. label = @T('Today')
  1051. time = new Date().toTimeString().substr 0,5
  1052. if @lastAddedType is 'timestamp'
  1053. # update last time
  1054. @updateLastTimestamp label, time
  1055. @lastTimestamp = timestamp
  1056. else
  1057. # add new timestamp
  1058. @body.insertAdjacentHTML 'beforeend', @view('timestamp')
  1059. label: label
  1060. time: time
  1061. @lastTimestamp = timestamp
  1062. @lastAddedType = 'timestamp'
  1063. @scrollToBottom()
  1064. updateLastTimestamp: (label, time) ->
  1065. return if !@el
  1066. timestamps = @el.querySelectorAll('.zammad-chat-body .zammad-chat-timestamp')
  1067. return if !timestamps
  1068. timestamps[timestamps.length - 1].outerHTML = @view('timestamp')
  1069. label: label
  1070. time: time
  1071. addStatus: (status) ->
  1072. return if !@el
  1073. @maybeAddTimestamp()
  1074. @body.insertAdjacentHTML 'beforeend', @view('status')
  1075. status: status
  1076. @scrollToBottom()
  1077. detectScrolledtoBottom: =>
  1078. scrollBottom = @body.scrollTop + @body.offsetHeight
  1079. @scrolledToBottom = Math.abs(scrollBottom - @body.scrollHeight) <= @scrollSnapTolerance
  1080. @el.querySelector('.zammad-scroll-hint').classList.add('is-hidden') if @scrolledToBottom
  1081. showScrollHint: ->
  1082. @el.querySelector('.zammad-scroll-hint').classList.remove('is-hidden')
  1083. # compensate scroll
  1084. @body.scrollTop = @body.scrollTop + @el.querySelector('.zammad-scroll-hint').offsetHeight
  1085. onScrollHintClick: =>
  1086. # animate scroll
  1087. @body.scrollTo
  1088. top: @body.scrollHeight
  1089. behavior: 'smooth'
  1090. scrollToBottom: ({ showHint } = { showHint: false }) ->
  1091. if @scrolledToBottom
  1092. @body.scrollTop = @body.scrollHeight
  1093. else if showHint
  1094. @showScrollHint()
  1095. destroy: (params = {}) =>
  1096. @log.debug 'destroy widget', params
  1097. @setAgentOnlineState 'offline'
  1098. if params.remove && @el
  1099. @el.remove()
  1100. # Remove button, because it can no longer be used.
  1101. btn = document.querySelector(".#{ @options.buttonClass }")
  1102. if btn
  1103. btn.classList.add @options.inactiveClass
  1104. btn.style.display = 'none';
  1105. # stop all timer
  1106. if @waitingListTimeout
  1107. @waitingListTimeout.stop()
  1108. if @inactiveTimeout
  1109. @inactiveTimeout.stop()
  1110. if @idleTimeout
  1111. @idleTimeout.stop()
  1112. # stop ws connection
  1113. @io.close()
  1114. reconnect: =>
  1115. # set status to connecting
  1116. @log.notice 'reconnecting'
  1117. @disableInput()
  1118. @lastAddedType = 'status'
  1119. @setAgentOnlineState 'connecting'
  1120. @addStatus @T('Connection lost')
  1121. onConnectionReestablished: =>
  1122. # set status back to online
  1123. @lastAddedType = 'status'
  1124. @setAgentOnlineState 'online'
  1125. @addStatus @T('Connection re-established')
  1126. @options.onConnectionReestablished?()
  1127. onSessionClosed: (data) ->
  1128. @addStatus @T('Chat closed by %s', data.realname)
  1129. @disableInput()
  1130. @setAgentOnlineState 'offline'
  1131. @inactiveTimeout.stop()
  1132. @options.onSessionClosed?(data)
  1133. setSessionId: (id) =>
  1134. @sessionId = id
  1135. if id is undefined
  1136. sessionStorage.removeItem 'sessionId'
  1137. else
  1138. sessionStorage.setItem 'sessionId', id
  1139. onConnectionEstablished: (data) =>
  1140. # stop delay of initial queue position
  1141. if @onInitialQueueDelayId
  1142. clearTimeout @onInitialQueueDelayId
  1143. @inQueue = false
  1144. if data.agent
  1145. @agent = data.agent
  1146. if data.session_id
  1147. @setSessionId data.session_id
  1148. # empty old messages
  1149. @body.innerHTML = ''
  1150. @el.querySelector('.zammad-chat-agent').innerHTML = @view('agent')
  1151. agent: @agent
  1152. @enableInput()
  1153. @hideModal()
  1154. @el.querySelector('.zammad-chat-welcome').classList.add('zammad-chat-is-hidden')
  1155. @el.querySelector('.zammad-chat-agent').classList.remove('zammad-chat-is-hidden')
  1156. @el.querySelector('.zammad-chat-agent-status').classList.remove('zammad-chat-is-hidden')
  1157. @input.focus() if not @isFullscreen
  1158. @setAgentOnlineState 'online'
  1159. @waitingListTimeout.stop()
  1160. @idleTimeout.stop()
  1161. @inactiveTimeout.start()
  1162. @options.onConnectionEstablished?(data)
  1163. showCustomerTimeout: ->
  1164. @el.querySelector('.zammad-chat-modal').innerHTML = @view('customer_timeout')
  1165. agent: @agent.name
  1166. delay: @options.inactiveTimeout
  1167. @el.querySelector('.js-restart').addEventListener 'click', -> location.reload()
  1168. @sessionClose()
  1169. showWaitingListTimeout: ->
  1170. @el.querySelector('.zammad-chat-modal').innerHTML = @view('waiting_list_timeout')
  1171. delay: @options.watingListTimeout
  1172. @el.querySelector('.js-restart').addEventListener 'click', -> location.reload()
  1173. @sessionClose()
  1174. showLoader: ->
  1175. @el.querySelector('.zammad-chat-modal').innerHTML = @view('loader')()
  1176. setAgentOnlineState: (state) =>
  1177. @state = state
  1178. return if !@el
  1179. capitalizedState = state.charAt(0).toUpperCase() + state.slice(1)
  1180. @el.querySelector('.zammad-chat-agent-status').dataset.status = state
  1181. @el.querySelector('.zammad-chat-agent-status').textContent = @T(capitalizedState)
  1182. detectHost: ->
  1183. protocol = 'ws://'
  1184. if scriptProtocol is 'https'
  1185. protocol = 'wss://'
  1186. @options.host = "#{ protocol }#{ scriptHost }/ws"
  1187. loadCss: ->
  1188. return if !@options.cssAutoload
  1189. url = @options.cssUrl
  1190. if !url
  1191. url = @options.host
  1192. .replace(/^wss/i, 'https')
  1193. .replace(/^ws/i, 'http')
  1194. .replace(/\/ws$/i, '') # WebSocket may run on example.com/ws path
  1195. url += '/assets/chat/chat.css'
  1196. @log.debug "load css from '#{url}'"
  1197. styles = "@import url('#{url}');"
  1198. newSS = document.createElement('link')
  1199. newSS.onload = @onCssLoaded
  1200. newSS.rel = 'stylesheet'
  1201. newSS.href = 'data:text/css,' + escape(styles)
  1202. document.getElementsByTagName('head')[0].appendChild(newSS)
  1203. onCssLoaded: =>
  1204. @cssLoaded = true
  1205. if @socketReady
  1206. @onReady()
  1207. @options.onCssLoaded?()
  1208. startTimeoutObservers: =>
  1209. @idleTimeout = new Timeout(
  1210. logPrefix: 'idleTimeout'
  1211. debug: @options.debug
  1212. timeout: @options.idleTimeout
  1213. timeoutIntervallCheck: @options.idleTimeoutIntervallCheck
  1214. callback: =>
  1215. @log.debug 'Idle timeout reached, hide widget', new Date
  1216. @destroy(remove: true)
  1217. )
  1218. @inactiveTimeout = new Timeout(
  1219. logPrefix: 'inactiveTimeout'
  1220. debug: @options.debug
  1221. timeout: @options.inactiveTimeout
  1222. timeoutIntervallCheck: @options.inactiveTimeoutIntervallCheck
  1223. callback: =>
  1224. @log.debug 'Inactive timeout reached, show timeout screen.', new Date
  1225. @showCustomerTimeout()
  1226. @destroy(remove: false)
  1227. )
  1228. @waitingListTimeout = new Timeout(
  1229. logPrefix: 'waitingListTimeout'
  1230. debug: @options.debug
  1231. timeout: @options.waitingListTimeout
  1232. timeoutIntervallCheck: @options.waitingListTimeoutIntervallCheck
  1233. callback: =>
  1234. @log.debug 'Waiting list timeout reached, show timeout screen.', new Date
  1235. @showWaitingListTimeout()
  1236. @destroy(remove: false)
  1237. )
  1238. disableScrollOnRoot: ->
  1239. @rootScrollOffset = @scrollRoot.scrollTop
  1240. @scrollRoot.style.overflow = 'hidden'
  1241. @scrollRoot.style.position = 'fixed'
  1242. enableScrollOnRoot: ->
  1243. @scrollRoot.scrollTop = @rootScrollOffset
  1244. @scrollRoot.style.overflow = ''
  1245. @scrollRoot.style.position = ''
  1246. # based on https://github.com/customd/jquery-visible/blob/master/jquery.visible.js
  1247. # to have not dependency, port to coffeescript
  1248. isVisible: (el, partial, hidden, direction) ->
  1249. return if el.length < 1
  1250. vpWidth = window.innerWidth
  1251. vpHeight = window.innerHeight
  1252. direction = if direction then direction else 'both'
  1253. clientSize = if hidden is true then t.offsetWidth * t.offsetHeight else true
  1254. rec = el.getBoundingClientRect()
  1255. tViz = rec.top >= 0 && rec.top < vpHeight
  1256. bViz = rec.bottom > 0 && rec.bottom <= vpHeight
  1257. lViz = rec.left >= 0 && rec.left < vpWidth
  1258. rViz = rec.right > 0 && rec.right <= vpWidth
  1259. vVisible = if partial then tViz || bViz else tViz && bViz
  1260. hVisible = if partial then lViz || rViz else lViz && rViz
  1261. if direction is 'both'
  1262. return clientSize && vVisible && hVisible
  1263. else if direction is 'vertical'
  1264. return clientSize && vVisible
  1265. else if direction is 'horizontal'
  1266. return clientSize && hVisible
  1267. isRetina: ->
  1268. if window.matchMedia
  1269. 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)')
  1270. return (mq && mq.matches || (window.devicePixelRatio > 1))
  1271. false
  1272. resizeImage: (dataURL, x = 'auto', y = 'auto', sizeFactor = 1, type, quallity, callback, force = true) ->
  1273. # load image from data url
  1274. imageObject = new Image()
  1275. imageObject.onload = ->
  1276. imageWidth = imageObject.width
  1277. imageHeight = imageObject.height
  1278. console.log('ImageService', 'current size', imageWidth, imageHeight)
  1279. if y is 'auto' && x is 'auto'
  1280. x = imageWidth
  1281. y = imageHeight
  1282. # get auto dimensions
  1283. if y is 'auto'
  1284. factor = imageWidth / x
  1285. y = imageHeight / factor
  1286. if x is 'auto'
  1287. factor = imageWidth / y
  1288. x = imageHeight / factor
  1289. # check if resize is needed
  1290. resize = false
  1291. if x < imageWidth || y < imageHeight
  1292. resize = true
  1293. x = x * sizeFactor
  1294. y = y * sizeFactor
  1295. else
  1296. x = imageWidth
  1297. y = imageHeight
  1298. # create canvas and set dimensions
  1299. canvas = document.createElement('canvas')
  1300. canvas.width = x
  1301. canvas.height = y
  1302. # draw image on canvas and set image dimensions
  1303. context = canvas.getContext('2d')
  1304. context.drawImage(imageObject, 0, 0, x, y)
  1305. # set quallity based on image size
  1306. if quallity == 'auto'
  1307. if x < 200 && y < 200
  1308. quallity = 1
  1309. else if x < 400 && y < 400
  1310. quallity = 0.9
  1311. else if x < 600 && y < 600
  1312. quallity = 0.8
  1313. else if x < 900 && y < 900
  1314. quallity = 0.7
  1315. else
  1316. quallity = 0.6
  1317. # execute callback with resized image
  1318. newDataUrl = canvas.toDataURL(type, quallity)
  1319. if resize
  1320. console.log('ImageService', 'resize', x/sizeFactor, y/sizeFactor, quallity, (newDataUrl.length * 0.75)/1024/1024, 'in mb')
  1321. callback(newDataUrl, x/sizeFactor, y/sizeFactor, true)
  1322. return
  1323. console.log('ImageService', 'no resize', x, y, quallity, (newDataUrl.length * 0.75)/1024/1024, 'in mb')
  1324. callback(newDataUrl, x, y, false)
  1325. # load image from data url
  1326. imageObject.src = dataURL
  1327. # taken from https://stackoverflow.com/questions/6690752/insert-html-at-caret-in-a-contenteditable-div/6691294#6691294
  1328. pasteHtmlAtCaret: (html) ->
  1329. sel = undefined
  1330. range = undefined
  1331. if window.getSelection
  1332. sel = window.getSelection()
  1333. if sel.getRangeAt && sel.rangeCount
  1334. range = sel.getRangeAt(0)
  1335. range.deleteContents()
  1336. el = document.createElement('div')
  1337. el.innerHTML = html
  1338. frag = document.createDocumentFragment(node, lastNode)
  1339. while node = el.firstChild
  1340. lastNode = frag.appendChild(node)
  1341. range.insertNode(frag)
  1342. if lastNode
  1343. range = range.cloneRange()
  1344. range.setStartAfter(lastNode)
  1345. range.collapse(true)
  1346. sel.removeAllRanges()
  1347. sel.addRange(range)
  1348. else if document.selection && document.selection.type != 'Control'
  1349. document.selection.createRange().pasteHTML(html)
  1350. # (C) sbrin - https://github.com/sbrin
  1351. # https://gist.github.com/sbrin/6801034
  1352. wordFilter: (editor) ->
  1353. content = editor.html()
  1354. # Word comments like conditional comments etc
  1355. content = content.replace(/<!--[\s\S]+?-->/gi, '')
  1356. # Remove comments, scripts (e.g., msoShowComment), XML tag, VML content,
  1357. # MS Office namespaced tags, and a few other tags
  1358. content = content.replace(/<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|img|meta|link|style|\w:\w+)(?=[\s\/>]))[^>]*>/gi, '')
  1359. # Convert <s> into <strike> for line-though
  1360. content = content.replace(/<(\/?)s>/gi, '<$1strike>')
  1361. # Replace nbsp entites to char since it's easier to handle
  1362. # content = content.replace(/&nbsp;/gi, "\u00a0")
  1363. content = content.replace(/&nbsp;/gi, ' ')
  1364. # Convert <span style="mso-spacerun:yes">___</span> to string of alternating
  1365. # breaking/non-breaking spaces of same length
  1366. #content = content.replace(/<span\s+style\s*=\s*"\s*mso-spacerun\s*:\s*yes\s*;?\s*"\s*>([\s\u00a0]*)<\/span>/gi, (str, spaces) ->
  1367. # return (spaces.length > 0) ? spaces.replace(/./, " ").slice(Math.floor(spaces.length/2)).split("").join("\u00a0") : ''
  1368. #)
  1369. editor.innerHTML = content
  1370. # Parse out list indent level for lists
  1371. for p in editor.querySelectorAll('p')
  1372. str = p.getAttribute('style')
  1373. matches = /mso-list:\w+ \w+([0-9]+)/.exec(str)
  1374. if matches
  1375. p.dataset._listLevel = parseInt(matches[1], 10)
  1376. # Parse Lists
  1377. last_level = 0
  1378. pnt = null
  1379. for p in editor.querySelectorAll('p')
  1380. cur_level = p.dataset._listLevel
  1381. if cur_level != undefined
  1382. txt = p.textContent
  1383. list_tag = '<ul></ul>'
  1384. if (/^\s*\w+\./.test(txt))
  1385. matches = /([0-9])\./.exec(txt)
  1386. if matches
  1387. start = parseInt(matches[1], 10)
  1388. list_tag = start>1 ? '<ol start="' + start + '"></ol>' : '<ol></ol>'
  1389. else
  1390. list_tag = '<ol></ol>'
  1391. if cur_level > last_level
  1392. if last_level == 0
  1393. p.insertAdjacentHTML 'beforebegin', list_tag
  1394. pnt = p.previousElementSibling
  1395. else
  1396. pnt.insertAdjacentHTML 'beforeend', list_tag
  1397. if cur_level < last_level
  1398. for i in [i..last_level-cur_level]
  1399. pnt = pnt.parentNode
  1400. p.querySelector('span:first').remove() if p.querySelector('span:first')
  1401. pnt.insertAdjacentHTML 'beforeend', '<li>' + p.innerHTML + '</li>'
  1402. p.remove()
  1403. last_level = cur_level
  1404. else
  1405. last_level = 0
  1406. el.removeAttribute('style') for el in editor.querySelectorAll('[style]')
  1407. el.removeAttribute('align') for el in editor.querySelectorAll('[align]')
  1408. el.outerHTML = el.innerHTML for el in editor.querySelectorAll('span')
  1409. el.remove() for el in editor.querySelectorAll('span:empty')
  1410. el.removeAttribute('class') for el in editor.querySelectorAll("[class^='Mso']")
  1411. el.remove() for el in editor.querySelectorAll('p:empty')
  1412. editor
  1413. removeAttribute: (element) ->
  1414. return if !element
  1415. for att in element.attributes
  1416. element.removeAttribute(att.name)
  1417. removeAttributes: (html) =>
  1418. for node in html.querySelectorAll('*')
  1419. @removeAttribute node
  1420. html
  1421. window.ZammadChat = ZammadChat