chat.coffee 70 KB

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