1.0.0 • Published 2 years ago

bb-chat v1.0.0

Weekly downloads
-
License
ISC
Repository
github
Last release
2 years ago

vue-beautiful-chat

vue-beautiful-chat provides an intercom-like chat window that can be included easily in any project for free. It provides no messaging facilities, only the view component.

vue-beautiful-chat is porting to vue of react-beautiful-chat (which you can find here)

Go to FAQ ⬇️

gif

Features

  • Customizeable
  • Backend agnostic
  • Free

Demo

Table of Contents

Installation

$ yarn add vue-beautiful-chat

Example

import Chat from 'vue-beautiful-chat'
Vue.use(Chat)
<template>
  <div>
    <beautiful-chat
      :participants="participants"
      :titleImageUrl="titleImageUrl"
      :onMessageWasSent="onMessageWasSent"
      :messageList="messageList"
      :newMessagesCount="newMessagesCount"
      :isOpen="isChatOpen"
      :close="closeChat"
      :icons="icons"
      :open="openChat"
      :showEmoji="true"
      :showFile="true"
      :showEdition="true"
      :showDeletion="true"
      :showTypingIndicator="showTypingIndicator"
      :showLauncher="true"
      :showCloseButton="true"
      :colors="colors"
      :alwaysScrollToBottom="alwaysScrollToBottom"
      :disableUserListToggle="false"
      :messageStyling="messageStyling"
      @onType="handleOnType"
      @edit="editMessage" />
  </div>
</template>
export default {
  name: 'app',
  data() {
    return {
      participants: [
        {
          id: 'user1',
          name: 'Matteo',
          imageUrl: 'https://avatars3.githubusercontent.com/u/1915989?s=230&v=4'
        },
        {
          id: 'user2',
          name: 'Support',
          imageUrl: 'https://avatars3.githubusercontent.com/u/37018832?s=200&v=4'
        }
      ], // the list of all the participant of the conversation. `name` is the user name, `id` is used to establish the author of a message, `imageUrl` is supposed to be the user avatar.
      titleImageUrl: 'https://a.slack-edge.com/66f9/img/avatars-teams/ava_0001-34.png',
      messageList: [
          { type: 'text', author: `me`, data: { text: `Say yes!` } },
          { type: 'text', author: `user1`, data: { text: `No.` } }
      ], // the list of the messages to show, can be paginated and adjusted dynamically
      newMessagesCount: 0,
      isChatOpen: false, // to determine whether the chat window should be open or closed
      showTypingIndicator: '', // when set to a value matching the participant.id it shows the typing indicator for the specific user
      colors: {
        header: {
          bg: '#4e8cff',
          text: '#ffffff'
        },
        launcher: {
          bg: '#4e8cff'
        },
        messageList: {
          bg: '#ffffff'
        },
        sentMessage: {
          bg: '#4e8cff',
          text: '#ffffff'
        },
        receivedMessage: {
          bg: '#eaeaea',
          text: '#222222'
        },
        userInput: {
          bg: '#f4f7f9',
          text: '#565867'
        }
      }, // specifies the color scheme for the component
      alwaysScrollToBottom: false, // when set to true always scrolls the chat to the bottom when new events are in (new message, user starts typing...)
      messageStyling: true // enables *bold* /emph/ _underline_ and such (more info at github.com/mattezza/msgdown)
    }
  },
  methods: {
    sendMessage (text) {
      if (text.length > 0) {
        this.newMessagesCount = this.isChatOpen ? this.newMessagesCount : this.newMessagesCount + 1
        this.onMessageWasSent({ author: 'support', type: 'text', data: { text } })
      }
    },
    onMessageWasSent (message) {
      // called when the user sends a message
      this.messageList = [ ...this.messageList, message ]
    },
    openChat () {
      // called when the user clicks on the fab button to open the chat
      this.isChatOpen = true
      this.newMessagesCount = 0
    },
    closeChat () {
      // called when the user clicks on the botton to close the chat
      this.isChatOpen = false
    },
    handleScrollToTop () {
      // called when the user scrolls message list to top
      // leverage pagination for loading another page of messages
    },
    handleOnType () {
      console.log('Emit typing event')
    },
    editMessage(message){
      const m = this.messageList.find(m=>m.id === message.id);
      m.isEdited = true;
      m.data.text = message.data.text;
    }
  }
}

For more detailed examples see the demo folder.

Components

Launcher

Launcher is the only component needed to use vue-beautiful-chat. It will react dynamically to changes in messages. All new messages must be added via a change in props as shown in the example.

Props

proptypedescription
*participantsagentProfileRepresents your product or service's customer service agents. Fields for each agent: id, name, imageUrl
*onMessageWasSentfunction(message)Called when a message is sent with the message object as an argument.
*isOpenBooleanThe bool indicating whether or not the chat window should be open.
*openFunctionThe function passed to the component that mutates the above mentioned bool toggle for opening the chat
*closeFunctionThe function passed to the component that mutates the above mentioned bool toggle for closing the chat
messageListmessageAn array of message objects to be rendered as a conversation.
showEmojiBooleanA bool indicating whether or not to show the emoji button
showFileBooleanA bool indicating whether or not to show the file chooser button
showDeletionBooleanA bool indicating whether or not to show the edit button for a message
showEditionBooleanA bool indicating whether or not to show the delete button for a message
showTypingIndicatorStringA string that can be set to a user's participant.id to show typing indicator for them
showHeaderBooleanA bool indicating whether or not to show the header of chatwindow
disableUserListToggleBooleanA bool indicating whether or not to allow the user to toggle between message list and participants list
colorsObjectAn object containing the specs of the colors used to paint the component. See here
messageStylingBooleanA bool indicating whether or not to enable msgdown support for message formatting in chat. See here

Events

eventparamsdescription
onTypeundefinedFires when user types on the message input
editmessageFires after user edited message

Slots

header

Replacing default header.

<template v-slot:header>
  🤔 Good chat between {{participants.map(m=>m.name).join(' & ')}}
</template>
user-avatar

Replacing user avatar. Params: message, user

<template v-slot:user-avatar="{ message, user }">
  <div style="border-radius:50%; color: pink; font-size: 15px; line-height:25px; text-align:center;background: tomato; width: 25px !important; height: 25px !important; min-width: 30px;min-height: 30px;margin: 5px; font-weight:bold" v-if="message.type === 'text' && user && user.name">
    {{user.name.toUpperCase()[0]}}
  </div>
</template>
text-message-body

Change markdown for text message. Params: message

<template v-slot:text-message-body="{ message }">
  <small style="background:red" v-if="message.meta">
    {{message.meta}}
  </small>
  {{message.text}}
</template>
system-message-body

Change markdown for system message. Params: message

<template v-slot:system-message-body="{ message }">
  [System]: {{message.text}}
</template>

Message Objects

Message objects are rendered differently depending on their type. Currently, only text, emoji and file types are supported. Each message object has an author field which can have the value 'me' or the id of the corresponding agent.

{
  author: 'support',
  type: 'text',
  id: 1, // or text '1'
  isEdited: false,
  data: {
    text: 'some text',
    meta: '06-16-2019 12:43'
  }
}

{
  author: 'me',
  type: 'emoji',
  id: 1, // or text '1'
  isEdited: false,
  data: {
    code: 'someCode'
  }
}

{
  author: 'me',
  type: 'file',
  id: 1, // or text '1'
  isEdited: false,
  data: {
    file: {
      name: 'file.mp3',
      url: 'https:123.rf/file.mp3'
    }
  }
}

Quick replies

When sending a message, you can provide a set of sentences that will be displayed in the user chat as quick replies. Adding in the message object a suggestions field with the value an array of strings will trigger this functionality

{
  author: 'support',
  type: 'text',
  id: 1, // or text '1'
  data: {
    text: 'some text',
    meta: '06-16-2019 12:43'
  },
  suggestions: ['some quick reply', ..., 'another one']
}

FAQ

git clone git@github.com:mattmezza/vue-beautiful-chat.git
cd vue-beautiful-chat
yarn install  # this installs the package dependencies
yarn watch  # this watches files to continuously compile them

Open a new shell in the same folder

cd demo
yarn install # this installs the demo dependencies
yarn dev # this starts the dev server at http://localhost:8080
  • Fork the repository
  • Fix/add your changes
  • yarn build on the root to have the library compiled with your latest changes
  • create a pull request describing what you did
  • discuss the changes with the maintainer
  • boom! your changes are added to the main repo
  • a release is created almost once per week 😉
  • When initializing the component, pass an object specifying the colors used:
let redColors = {
  header: {
    bg: '#D32F2F',
    text: '#fff'
  },
  launcher: {
    bg: '#D32F2F'
  },
  messageList: {
    bg: '#fff'
  },
  sentMessage: {
    bg: '#F44336',
    text: '#fff'
  },
  receivedMessage: {
    bg: '#eaeaea',
    text: '#222222'
  },
  userInput: {
    bg: '#fff',
    text: '#212121'
  }
}
<beautiful-chat
  ...
  :colors="redColors" />

This is the red variant. Please check this file for the list of variants shown in the demo page online.

Please note that you need to pass an Object containing each one of the color properties otherwise the validation will fail.

Good news, message formatting is already added for you. You can enable it by setting messageStyling to true and you will be using the msgdown library. You can enable/disable the formatting support at any time, or you can let users do it whenever they prefer.

Contributors

@a-kriya, @mattmezza

Please contact us if you would like to join as a contributor.

acceptsabbrevacorn-jsxacorn-walkaddressaggregate-errorajvajv-errorsajv-keywordsalphanum-sortacornamdefineansi-colorsansi-escapesansi-regexansi-stylesanymatchansi-htmlany-promisearchare-we-there-yetargparsearr-flattenarr-unionarray-find-indexaprobaarray-flattenarray-includesarr-diffarray-unionarray-uniquearrifyarray.prototype.flatarray-uniqasn1asn1.jsassign-symbolsassertasyncassert-plusastral-regexasync-eachasync-foreachatobautolinkerasynckitasync-limiterautoprefixeraws-sign2aws4babel-loaderbabel-eslintbabel-plugin-dynamic-import-nodebalanced-matchbasebase64-jsbatchbcrypt-pbkdfbfjbluebirdbig.jsblock-streambn.jsbody-parserbinary-extensionsbonjourbrace-expansionboolbasebracesbrowserify-aesbrorandbrowserify-cipherbrowserify-rsabrowserify-desbrowserify-signbrowserify-zlibbrowserslistbufferbuffer-frombuffer-indexofbuffer-jsonbuffer-xorbuiltin-status-codescacachebytescache-basecache-loadercall-me-maybecaller-callsitecallsitescamel-casecamelcasecaller-pathcamelcase-keyscaniuse-apicaniuse-litecase-sensitive-paths-webpack-plugincaselesschokidarchownrchardetchrome-trace-eventcipher-baseci-infoclass-utilsclean-cssclean-stackcli-cursorcli-highlightcli-truncatecli-widthcliuichalkcli-spinnersclipboardyclone-deepcode-point-atclonecheck-typescoacollection-visitcolor-stringcolorcolor-convertcombined-streamcommondircommandercolor-namecompare-versionscompressiblecomponent-emitterconcat-streamconcat-mapconnect-history-api-fallbackconsole-control-stringscompressionconsolidatecontains-pathconsole-browserifycontent-dispositioncontent-typeconvert-source-mapcopy-concurrentlyconstants-browserifycopy-descriptorcookie-signaturecookiecore-jscopy-webpack-plugincore-js-compatcore-util-iscosmiconfigcreate-ecdhcreate-hashcreate-hmaccross-spawncss-color-namescrypto-browserifycss-declaration-sortercss-select-base-adaptercss-loadercss-selectcss-treecssesccss-whatcssnano-preset-defaultcssnanocssnano-util-get-argumentscssnano-util-same-parentcssnano-util-raw-cachecurrent-script-polyfillcssnano-util-get-matchcssocurrently-unhandledcyclistdashdashde-indentdebugdedentdecode-uri-componentdecamelizedeep-equaldeepmergedeep-isdefault-gatewaydefaultsdefine-propertiesdefine-propertydeldelayed-streamdelegatesdepddes.jsdestroydetect-nodediffie-hellmandir-globdns-txtdns-equaldoctrinedns-packetdom-converterdom-serializerdomelementtypedomain-browserdomhandlerdomutilsdot-propdotenvdotenv-expandduplexerecc-jsbnduplexifyeasy-stackee-firstejsellipticelectron-to-chromiumemoji-jsemoji-datasourceemoji-regexencodeurlend-of-streamemojis-listenhanced-resolveentitieserror-exenquireres-abstractes-to-primitiveescape-goatescape-string-regexpescape-htmlerror-stack-parsereslint-import-resolver-nodeeslinteslint-config-prettiereslint-plugin-eseslint-module-utilseslint-loadererrnoeslint-plugin-importeslint-plugin-prettiereslint-plugin-nodeeslint-plugin-standardeslint-plugin-vueeslint-scopeeslint-utilseslint-plugin-promiseesprimaeslint-visitor-keysespreeestraverseesrecurseesutilsesqueryevent-pubsubetageventseventemitter3evp_bytestokeyexecaexpand-bracketsexpresseventsourceextendexternal-editorfast-deep-equalextglobextsprintfextend-shallowfast-difffast-levenshteinfast-globfast-json-stable-stringifyfaye-websocketfiguresfiggy-puddingfile-loaderfile-typefile-entry-cachefilesizefind-cache-dirfinalhandlerfind-upfind-versionsfill-rangeflat-cacheflattedfor-infollow-redirectsforever-agentform-dataflush-write-streamforwardedfreshfs-extrafrom2fs-minipassfs.realpathfstreamfragment-cachefunction-bindfs-write-stream-atomicfunctional-red-black-treegaugegazegensyncget-own-enumerable-property-symbolsget-caller-fileget-valueget-stdinglobgetpassget-streamglob-parentglob-to-regexpglobbyglobuleglobalsgraceful-fshar-schemahandle-thinggzip-sizehas-flaghashar-validatorhas-ansihas-valuehas-symbolshas-valueshash-sumhash-basehas-unicodehash.jshehex-color-regexhoopyhosted-git-infohighlight.jshmac-drbghpack.jshsl-regexhtml-comment-regexhsla-regexhtml-minifierhtml-entitieshtml-tagshtml-webpack-pluginhtmlparser2http-deceiverhttp-proxyhttp-errorshttp-parser-jshttps-browserifyhttp-signaturehttp-proxy-middlewarehuman-signalsiconv-litehuskyieee754iferricss-utilsignoreimageminimport-freshimport-fromimport-cwdimurmurhashimport-localindent-stringinfer-ownerinflightin-publishinheritsinvariantinquireripinternal-ipipaddr.jsis-absolute-urlindexes-ofip-regexis-arrayishis-accessor-descriptoris-argumentsis-binary-pathis-bufferis-callableis-color-stopis-ciis-data-descriptoris-date-objectis-descriptoris-dockeris-directoryis-extendableis-extglobis-finiteis-fullwidth-code-pointis-globis-numberis-objis-path-insideis-plain-objectis-path-cwdis-plain-objis-resolvableis-regexpis-streamis-stringis-svgis-typedarrayis-symbolis-utf8is-windowsis-regexisexeisarrayis-wslisobjectjavascript-stringifyisstreamjest-workerjs-queuejs-base64js-messagejs-tokensjsbnjs-yamljsescjson-parse-better-errorsjson-schemajson-schema-traversejson-stringify-safejson-stable-stringify-without-jsonifyjson5json3jsonfilejsprimkind-oflaunch-editorlevenkillablelaunch-editor-middlewarelevnlevenarylines-and-columnsis-path-in-cwdlint-stagedloader-runnerlistr2loader-fs-cacheload-json-fileloader-utilslocate-pathlodashlodash.defaultsdeeplodash.mapvalueslodash.memoizelodash.uniqlodash.kebabcaselog-symbolslodash.transformlog-updateloglevelloud-rejectionlru-cacheloose-envifylower-casemake-dirmap-cachemap-visitmap-objmd5.jsmdn-datamedia-typermerge-descriptorsmemory-fsmeowmerge-source-mapmerge2merge-streammiller-rabinmimic-fnmicromatchmime-dbmimemime-typesminimalistic-assertmini-css-extract-pluginminimalistic-crypto-utilsminimatchmethodsminimistminipassminipass-collectminipass-flushmississippiminipass-pipelinemixin-deepmove-concurrentlymkdirpmsmulticast-dnsmulticast-dns-service-typesmsgdownmznanmute-streamnanomatchnatural-comparenegotiatornice-tryno-casenode-forgeneo-asyncnode-gypnode-libs-browsernode-releasesnode-sassnode-ipcnormalize-package-datanoptnormalize-rangenpm-run-pathnormalize-pathnth-checknpmlognum2fractionnumber-is-nanoauth-signobject-copyobject-inspectobject-hashobject-keysobject-isobject-assignobject-visitobject.getownpropertydescriptorsobject.pickobject.assignon-finishedobufobject.valueson-headersonetimeopenonceopencollective-postinstallopeneropnoptionatororaoriginalos-browserifyos-homedirosenvp-finallyos-tmpdirp-locatep-mapp-retryp-tryp-limitp-pipeparallel-transformpakoparam-caseparent-moduleparse-asn1parse-jsonparse5pascalcaseparse5-htmlparser2-tree-adapterparseurlpath-dirnamepath-browserifypath-existspath-keypath-is-absolutepath-parsepath-is-insidepbkdf2path-to-regexppath-typenormalize-urlperformance-nowpicomatchpinkiepinkie-promiseplease-upgrade-nodepnp-webpack-pluginpopper.jspkg-dirpifypkg-upportfinderpostcss-convert-valuespostcss-calcpostcss-colorminpostcssposix-character-classespostcss-discard-emptypostcss-discard-commentspostcss-discard-duplicatespostcss-merge-longhandpostcss-loaderpostcss-merge-rulespostcss-minify-font-valuespostcss-minify-paramspostcss-minify-gradientspostcss-modules-extract-importspostcss-discard-overriddenpostcss-minify-selectorspostcss-load-configpostcss-modules-local-by-defaultpostcss-normalize-charsetpostcss-modules-scopepostcss-normalize-display-valuespostcss-normalize-positionspostcss-modules-valuespostcss-normalize-repeat-stylepostcss-normalize-stringpostcss-normalize-timing-functionspostcss-normalize-whitespacepostcss-ordered-valuespostcss-reduce-transformspostcss-reduce-initialpostcss-selector-parserpostcss-svgopostcss-value-parserpostcss-unique-selectorspostcss-normalize-unicodeprepend-httpprelude-lsprettierprettier-linter-helperspretty-errorprivateprocessprocess-nextick-argspromise-inflightproxy-addrprogresspslprrpublic-encryptpumppumpifypunycodeqqsquery-stringquerystring-es3pseudomapquerystringifyrandombytesrandomfillrange-parserraw-bodyread-pkgquerystringread-pkg-upreadable-streamreaddirpregeneratepostcss-normalize-urlredentregenerator-transformregenerate-unicode-propertiesregex-notregexp.prototype.flagsregenerator-runtimeregexppregjsgenregexpu-coreregjsparserremove-trailing-separatorrenderkidrepeat-elementrepeat-stringreplace-extrepeatingrequestrequest-promise-nativerequire-main-filenamerequire-directoryrequest-promise-coreresolve-cwdrequires-portresolverestore-cursorresolve-urlretresolve-fromretryrgb-regexrgba-regexripemd160run-asyncrelateurlrimrafrun-queuesafe-regexrxjssafer-buffersass-loadersass-graphsafe-buffersaxselect-hosescss-tokenizerselfsignedsemversemver-regexschema-utilssemver-compareserve-indexserve-staticsendserialize-javascriptset-valueset-blockingsha.jssetimmediatesetprototypeofshallow-cloneshebang-commandshebang-regexshell-quotesimple-swizzleslice-ansislashsnapdragon-nodesnapdragonsnapdragon-utilsignal-exitsockjs-clientsort-keyssockjssource-mapsource-list-mapsource-map-supportsource-map-resolvespdx-correctspdx-license-idssource-map-urlspdx-expression-parsespdyspdy-transportsplit-stringspdx-exceptionssshpksprintf-jsssristackframestatic-extendstatusesstdout-streamstream-browserifystealthy-requirestream-eachstablestrict-uri-encodestream-shiftstream-httpstring-argvstring-widthstring.prototype.trimendstring.prototype.trimstartstringify-objectstrip-ansistring_decoderstrip-bomstrip-eofstrip-final-newlinestrip-json-commentsstylehacksstrip-indentsvg-tagssupports-colorsvgotabletapabletarterserterser-webpack-plugintext-tablethenify-allthenifythread-loaderthrough2thunkythroughtimers-browserifytimsorttmpto-fast-propertiesto-object-pathto-arraybufferto-regexto-regex-rangetoidentifiertoposorttough-cookietrue-case-pathtryerts-pnptrim-newlinestsconfig-pathstslibtty-browserifytweetnacltunnel-agenttype-checktype-istypedarraytype-festuglify-jsunicode-canonical-property-names-ecmascriptunicode-match-property-value-ecmascriptunicode-match-property-ecmascriptunion-valueunicode-property-aliases-ecmascriptuniqunique-filenameuniqsuniversalifyunique-slugunquoteunpipeunset-valueupathupper-caseuri-jsurixurlurl-loaderuseurl-parseutilutil.promisifyutilautils-mergeutil-deprecateuuidvalidate-npm-package-licensevaryverrorv8-compile-cachevendorsvm-browserifyv-tooltipvue-eslint-parservue-hot-reload-apivue-loadervue-resizevue-template-compilervue-style-loadervue-template-es2015-compilerwatchpackwbufwcwidthwatchpack-chokidar2webpack-bundle-analyzerwebpackwebpack-dev-serverwebpack-logwebpack-chainwebpack-dev-middlewarewebpack-mergewebpack-sourceswebsocket-extensionswhichwebsocket-driverwhich-modulewide-alignwhich-pm-runsword-wrapwrap-ansiworker-farmwritewrappywsxtendy18nyargs-parseryallistyamlyargsyocto-queueyorkie
1.0.0

2 years ago