Giter Site home page Giter Site logo

calibreapp / react-live-chat-loader Goto Github PK

View Code? Open in Web Editor NEW
521.0 8.0 55.0 11.14 MB

Implement a live chat beacon in your React application without performance regressions.

Home Page: https://react-live-chat-loader.now.sh

License: MIT License

JavaScript 4.85% TypeScript 95.15%
react-components react reactjs performance web-performance performance-optimization live-chat intercom helpscout drift

react-live-chat-loader's People

Contributors

allcontributors[bot] avatar altaywtf avatar ashkyd avatar benschwarz avatar cbschuld avatar dependabot[bot] avatar drwlrsn avatar elmoeleven avatar fatexrebirth avatar gazpachu avatar iliredis avatar jaska120 avatar javiermartinz avatar jucallej avatar laugutierrezz avatar luisrudge avatar mirshko avatar motiko avatar myleslinder avatar paulirish avatar robmorieson avatar stramel avatar thefoxis avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-live-chat-loader's Issues

[Feature Request] Customize Intercom Background Color?

What problem would this feature solve?

I'd love to be able to customize the Intercom background_color before initialization. Before using react-live-chat-loader I would simply put that in my window.Intercom('boot') call, but no there's nowhere to put it.

Describe the solution you’d like to see

I'd like for either the color prop to also apply to the background, or for a backgroundColor prop to be added to LiveChatLoaderProvider.

Describe alternatives you’ve considered

I currently use the onReady callback to switch the background color after Intercom loads, but it can cause the default blue to flash to my color on the user's screen if they click the button before Intercom lazy loads.

Chat-loader not working for facebook.

When trying to use the facebook provider="messenger" and providerKey="172743013379" (application ID) I get

=> Refused to display 'https://www.facebook.com/' in a frame because it set 'X-Frame-Options' to 'deny'.

I have white listed the domain from which I using the "react-chat-loader" package.

Intercom opens automatically when state is completed

If I understood the code correctly, when Intercom finishes loading

if (state === 'complete') return chatProvider.open()
state will be set to complete and Intercom is opened automatically without user interaction.

Call to setting complete state:

setTimeout(() => setState('complete'), 2000)

This is very bad UX since on mobile Intercom pops up and takes the whole viewport when opened. Therefore, without any notice a new screen pops up for the user on mobile. I think it should be out of scope of this package to automatically open the Intercom window without user interaction involved or people calling window.Intercom('show') on their code manually.

Messenger not working

@michaeldijkstra thanks for adjusting messenger provider and component first!

I used the latest version in my project, but no customer chat dialog pop up, Have you test it?
I know you move fb-customerchat from preload phase to a component called CustomerChat,
it seems not working, we know that fb-customerchat is necessary for Customer Chat SDK, I think the problem is when you finish loading script, then state will become complete, then LiveChatLoaderContext will update which will trigger useProvider update as well, then re-render
CustomerChat, in the same time, Customer Chat SDK is parsed and executed, it tries to find the fb-customerchat, but CustomerChat just render, so it can't find any match, so it won't work.
I try to move fb-customerchat to any place except inside of LiveChatLoaderProvider, it works as expected.

Is not convenient to have to write additional code for using react-live-chat-loader, What if we wrap code which creates fb-customerchat in useEffect of Messenger component? I think this a great way to decouple all code in load script and still work as you want and you did before.

by the way, I would like you to help me delete this PR: #10, that was a mistake. please delete it.

Weird error

We are getting a weird error about memory leak when we browse 2/3 pages of our website, after some seconds we got it telling us:

commons.js:77200 Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
    in LiveChatLoaderProvider (at layout.js:114)
    in ThemeProvider (at layout.js:88)
    in Layout (at print-on-demand.js:23)
    in PoD (created by HotExportedPoD)
    in AppContainer (created by HotExportedPoD)
    in HotExportedPoD (created by PageRenderer)

[Bug] Typing errors conflict with documentation

Using the Messenger component in Typescript results in annoying typing errors. The props field is defined with

providerKey: Provider | undefined; but would be better served as providerKey?: Provider so we are not forced to do <Messenger providerKey={undefined} /> or <Messenger providerKey='messenger' />

This also does not match with the documentation which doesn't indicate any props are necessary. The same is true with the mention of locale property which does not exist.

Using version 2.7.3

Lighthouse aria-* rule violation

Describe the bug

Lighthouse is complaining about an aria-* rule violation: [aria-*] attributes do not match their roles

How To Reproduce

          <LiveChatLoaderProvider providerKey="lksanlsknksal" provider="drift">
             ...
            <Drift />
          </LiveChatLoaderProvider>

Expected behaviour

No accessibility errors should be present

Screenshots

image

[Bug] Button stops working

Button stops to work if you click it, and close the chat window, navigate to new page. And now try to open it again, it doesn't work anymore.

My setup (ChatWoot)
Code_FgM44oQJ7r

Inline style for Drift causing cutoff effects

Describe the bug

When using drift chat on my Gatsby site, the first pop up shows up correctly that greets the user but upon changing routes/url's it cuts off the pop up box due to the inline style setting of "width: 76px !important"

How To Reproduce

the bug can currently bee seen here on my staging site https://dripsstaging.gtsb.io

  1. Click on the X on the pop up box when greeted after it pops up from hovering over button or idle period.
  2. change to any other page on the website
  3. See error

Expected behavior

Second pop up box should not have a set width of 76px

Video

https://youtu.be/hlmPlh60EZE

Problem with SSR: ReferenceError: window is not defined

It seems that this module does not work in a browserless situation (e.g. server-side rendering). To workaround, I can conditionally render the component, but that's a bit of a pain. It would be nice if the module could detect whether the browser is present (and if not, there is no need to do anything).

[Bug] HelpScout doesn't toggle off

Describe the bug

HelpScout's state to see if it's open or closed doesn't seem to work. Once you open it, you can't close it unless you click HelpScout's specific close button.

You can see it happening in the demo docs as well:
https://react-live-chat-loader.vercel.app/helpscout

How To Reproduce

  1. Set up a HelpScout provider chat
  2. Try to open it in your app
  3. Try to close it

Screenshots

CleanShot 2022-07-27 at 15 49 06

Relevant Log Output

No response

Code of Conduct

  • I agree to follow this project’s Code of Conduct

Warning: The final argument passed to useEffect changed size between renders

I get this warning from time to time.

Warning: The final argument passed to useEffect changed size between renders. The order and size of this array must remain constant.

Previous: []
Incoming: [function () {
    // Don't load if idlePeriod is 0, null or undefined
    if (typeof window === 'undefined' || !loadWhenIdle || !idlePeriod) return; // Don't load if 2g connection or save-data is enabled

    if (connection && (connection.saveData || /2g/.test(connection.effectiveType))) return;
    var idleThreshold = parseInt(idlePeriod, 10);
    if (isNaN(idleThreshold)) return; // deadline.timeRemaining() has an upper limit of 50 milliseconds
    // We want to ensure the page has been idle for a significant period of time
    // Therefore we count consecutive maximum timeRemaining counts and load chat when we reach our threshold

    var elapsedIdlePeriod = 0;
    var previousTimeRemaining = 0;

    var scheduleLoadChat = function scheduleLoadChat(deadline) {
      if (elapsedIdlePeriod > idleThreshold) return loadChat({
        open: false
      });
      var timeRemaining = deadline.timeRemaining(); // To ensure browser is idle, only accumalte elapsedIdlePeriod when
      // two consecutive maximum timeRemaining's have been observed

      if (previousTimeRemaining > 49 && timeRemaining > 49) elapsedIdlePeriod += timeRemaining;
      previousTimeRemaining = timeRemaining;
      requestIdleCallback(scheduleLoadChat);
    };

    if (requestIdleCallback) {
      requestIdleCallback(scheduleLoadChat);
    } else {
      setTimeout(function () {
        return loadChat({
          open: false
        });
      }, idleThreshold);
    }
  }]
    in HelpScout (at App.js:908)
    in LiveChatLoaderProvider (at App.js:902)
    in Provider (at App.js:966)
...

Bundle size

All components are being bundled when using Gatsby V3 and Webpack V5, see screenshot.

image

I think it is due to fact that providers are exported as object instead of named exports (https://github.com/calibreapp/react-live-chat-loader/blob/main/src/providers/index.ts).

Changing exports and then using named imports like:
import * as Providers from 'providers' in (https://github.com/calibreapp/react-live-chat-loader/blob/main/src/components/LiveChatLoaderProvider.tsx#L2)

might make them tree-shakeable. Could you look into this?

React error

When trying to implement this with Drift I'm getting the following error:

TypeError: undefined is not a function (near '...(0, _react.memo)...')

> 205 | var CustomerChat = (0, _react.memo)(function (_ref) {

My implementation:

import React, { Component } from "react";
import { LiveChatLoaderProvider, Drift } from 'react-live-chat-loader'

class App extends Component {

  render() {

    return (
	    <LiveChatLoaderProvider provider="drift" providerKey="***" >
	    	<Drift icon="A" color="#0176ff"/>

            </LiveChatLoaderProvider>
    );
  }
}

export default App;

Any thoughts on what could be causing this?

[Bug] No chat is shown when used together with react-facebook FacebookProvider

React-facebook provides variety of FB-related components. I strongly suspect there is a conflict causing the chat to often not show (but not always), possibly depending on the order of initialization of both packages.


Describe the bug

How To Reproduce

Steps to reproduce the behavior:

  1. Setup both providers and messenger button
<FacebookProvider appId="xxxx">
<LiveChatLoaderProvider providerKey="yyyy" appId="xxxxx" provider="messenger" locale="en_US">
...
<Messenger />
</LiveChatLoaderProvider>
</FacebookProvider>

(Tried also without appId in LiveChatLoaderProvider)
2. Load the page
3. Click the messenger button

Actual results:

  • Chat does not show most of the time (but not always)
  • Exception is logged
TypeError: window.FB.CustomerChat is undefined
at .open ( [../../../src/providers/messenger.ts:81] )
at .open ( [../../../src/providers/messenger.ts:81] )
at .check ( [../../../src/utils/waitForLoad.ts:15] )
at .check ( [../../../src/utils/waitForLoad.ts:20] )
at .check ( [../../../src/utils/waitForLoad.ts:20] )
...
  • Digging deeper I found that messenger.ts:loadScript:16 (link) returns false because window.FB is already there, possibly initialized by react-facebook package.

Expected behaviour

Should the check in messenger.ts not relay on window.FB presence, or ensure that customer chat is there?

[Feature Request] Hide button from frontend if ad-blocker is enabled

What problem would this feature solve?

If you're a user with an ad-blocker, the chat button click does nothing.

Describe the solution you’d like to see

Hide the chat button entirely if the user is using an ad-blocker

Describe alternatives you’ve considered

Hosting the embed script on another domain under a different name in-order to avoid the ad-blocker altogether. This was thrown out because of user privacy.

Additional context

In-case you'd like to read the HelpScout section about ad-blocking: https://docs.helpscout.com/article/911-beacon-and-ad-blockers

[Bug] Module does not publish @types for TS usage

Describe the bug

I don't know if this is a bug, feature request or a chore, but if I import this module in a TS file, I get the following error:

 TS7016: Could not find a declaration file for module 'react-live-chat-loader'.   Try `npm i --save-dev @types/react-live-chat-loader` if it exists or add a new declaration (.d.ts) 

Trying to run that npm command yields:

npm ERR! code E404
npm ERR! 404 Not Found - GET https://registry.npmjs.org/@types%2freact-live-chat-loader - Not found
npm ERR! 404 
npm ERR! 404  '@types/react-live-chat-loader@latest' is not in the npm registry.
npm ERR! 404 You should bug the author to publish it (or use the name yourself!)
npm ERR! 404 
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, http url, or git url.

If there is another recommended way to avoid TS7016 with this package, please let me know. Thanks.

[Bug] GatsbyJS. Chatbot only loads if user puts page in background or hovers over icon.

👋🏻 Hi there! Chat only loads if the user puts the window in the background or hovers over the icon on GatsbyJS. I have included a codesandbox below of a Gatsby starter template with react-live-chat-loader installed to demonstrate this issue.


Describe the bug

Not properly detecting idle period while using react-live-chat-loader with Gatsby JS

How To Reproduce

Steps to reproduce the behavior:

  1. Go to 'https://codesandbox.io/s/drift-gatsby-starter-bugtest-v8iys4'
  2. Click the open in new window popup when prompted to view the main page.
  3. Once site is loaded, sit idle for a couple minutes and nothing happens, but if you hover over the icon OR put the page in the background you will eventually hear the chatbot activating.

Expected behavior

Chatbot loads after set idle period(setting idlePeriod has no effect)

[Bug] Doesn't works with React 18

First, I want to thank you so much for this library! I enjoy using this.
Unfortunately, this library does not work with React 18.

Package.json

image

Describe the bug

Please provide a clear and concise description of what the bug is. Include relevant operating system, browser and other environment information.

How To Reproduce

Steps to reproduce the behavior:

  1. Make sure you are on React 18.x.
  2. Make sure you have the latest version of react-live-chat-loader (2.7.3).
  3. npm install
  4. See error bellow

Expected behaviour

A clean npm install

Screenshots

image

[Feature Request] Ability to style components

What problem would this feature solve?

Currently Intercom allows certain positional changes. It is not possible to mirror this, since the <Intercom> component uses hard-coded styling, other than the color

Describe the solution you’d like to see

Ability to pass in a style object to override any defaults

Ability to set user attributes

Using Intercom, you're able to set user data when registering the chat loader. For example:

window.Intercom('boot', {
app_id: 'app_id_here',
...(user && {
  name: `${user.name.first} ${user.name.last}`,
  email: user.email,
  user_id: user.id,
  created_at: user.created_at,
}),

Is there any way to do this with this loader currently?

Remove aria-label attribute causing accessibility issues in lighthouse report

This was observed on the live chat loader using it for Intercom. The div element wrapping the loader has an aria-label attribute causing an accessibility issue on lighthouse. Removing the aria-label by hand fixed the issue for me.

What problem would this feature solve?

The issue on the lighthouse report (accessibility) would be solved.

Describe the solution you’d like to see

Remove the aria-label="Load Chat" attribute.

Describe alternatives you’ve considered

Replace the aria-label attribute by another one not causing a lighthouse error.

Additional context

Here are some screenshots showing the issue

Capture d’écran 2022-01-05 à 14 57 29
Capture d’écran 2022-01-05 à 10 42 07

Bundled type definitions have broken imports

Thanks for this great library!

It seems like the imports in the bundled type definitions are broken.
For example, at https://unpkg.com/browse/[email protected]/dist/components/LiveChatLoaderProvider.d.ts, provider resolves to any because your absolute import settings (baseUrl) aren't used to create relative paths when declarations are created.

I don't know of any solution that wouldn't involve adding another package to your build toolchain. Potentially interesting without adding webpack or a full rollup setup:

Hide chat icon (Userlike) in print mode

I want to hide Userlike when printing a page. Are there any things that I can easily add to do that?
Trying to do something like this
@media print {
....
display: none !important;
....
}
But there is no possibility for now as I understood.

Thanks!

Intercom controls which pages it shows on

I imagine this will be quite difficult to solve but here goes..

Intercom's admin panel can control on which pages to display the chat widget.

As developers by adding the <Intercom /> component to certain pages we lose the flexibility of having our support team manage which pages to display the widget.

[Feature Request] Accept Drift Event Handlers

What problem would this feature solve?

Drift allows you to respond to a number of events (beyond the 'ready' event) but the drift script has to be loaded and ready before you can attach any listeners.

Right now, to attach listeners to drift events you can wrap either the Drift component and orchestrate it yourself based on the state returned from the useChat hook being set to complete. A simple example:

  const [ state ] = useChat();

  useEffect(() => {
    if (state === "complete") {
       window.drift.on('conversationStarted', () => {})
    }
  }, [ state ]);

Describe the solution you’d like to see

This can be introduced, likely without a breaking change, by accepting an optional events prop in the Drift component and registering the provided event handlers with drift once appropriate.

The events prop type could be an object of Drift event names to handlers:

const driftListeners: DriftEventHandlers = {
  startConversation: ({ conversationId }) => {
    // do something here...
  },
};

This type could defined using something like:

I'm new to TypeScript so take this with a grain of salt

type DriftEventPayloads = {
  startConversation: {
    conversationId: number;
    inboxId: number;
  };
  chatOpen: undefined;
  chatClose: undefined;
  // ... all other supported events
};

type DriftEventHandler<P> = (data: P) => void;

export type DriftEventHandlers = {
  [K in keyof DriftEventPayloads]?: DriftEventHandler<DriftEventPayloads[K]>;
};

If this or an alternate solution makes sense I'm happy to submit a PR.

Describe alternatives you’ve considered

It's possible to accept a prop in the LiveChatLoaderProvider, which in theory makes sense because that's where the initialization props are provided and extra props are included in the context. However, it's unclear to me if event listening would be applicable/beneficial with other providers and would require a change to useChat and the provider api.

[Feature Request] Drift.com Left/Right Align

What problem would this feature solve?

Allowing left alignment of Drift widget

Describe the solution you’d like to see

Adding component props for left (right default) for Drift

Alternatively, can you place an ID or Class on the div that contains the button so I can target it via CSS for left alignment?

Are you willing to work on implementing this solution?

No

Describe alternatives you’ve considered

No response

Additional context

No response

Code of Conduct

  • I agree to follow this project’s Code of Conduct

Use with device-based Segment integration?

Right now, I'm using Segment's device-based Intercom integration to load the Intercom script, identify users, and sync analytics events.

Do you have any suggestion for how to use this facade with Segment? Ideally, I'm thinking it'll work like this:

  1. Your facade stubs a global window.Intercom function that enables other scripts (like Segment) to call the Intercom API while the actual Intercom widget is still being fetched.
  2. Segment calls your stubbed Intercom API whenever their analytics methods are called.
  3. Your facade dynamically fetches the Intercom widget and, once fetched, calls the actual Intercom API with the parameters received by your stubbed API (that way, events aren't lost while Intercom's widget is being fetched).

I've also opened a support ticket with Segment, because I'm guessing they'll be able to help more than you guys.

Plans on adding type definitions?

This project is amazing and we are currently adding it to our own website.

I was wondering if you have any plans on adding type definitions?

Cheers

How to use this for a Webflow website

Hello,

I am using Webflow to create my website and google tag manager to make drift works. But I am not sure how to install this inside the google tag manager since npm seems does not work inside the google tag manager.

Thank you ahead for your help!

Unable to use Custom Button

This code from the README.md file...

import { useChat } from 'react-live-chat-loader'

export const LoadChatButton = () => {
  const [state, loadChat] = useChat()

  return <button onClick={loadChat}>Load Chat</button>
}

... throws the following error:

Server Error
TypeError: Cannot destructure property 'loadWhenIdle' of 'undefined' as it is undefined.

Confused About providerKey?

I'd like to use react-live-chat-loader with Help Scout. The RLCL docs call for me to use aproviderKey. Help Scout doesn't seem to supply me with a providerKey. None is required when I load Help Scout on my site without using a facade, which I do like this:

<script async type="text/javascript">
    !function (e, t, n) {
        function a() {
            var e = t.getElementsByTagName("script")[0], n = t.createElement("script");
            n.type = "text/javascript", n.async = !0, n.src = "https://beacon-v2.helpscout.net", e.parentNode.insertBefore(n, e)
        }

        if (e.Beacon = n = function (t, n, a) {
            e.Beacon.readyQueue.push({method: t, options: n, data: a})
        }, n.readyQueue = [], "complete" === t.readyState) return a();
        e.attachEvent ? e.attachEvent("onload", a) : e.addEventListener("load", a, !1)
    }(window, document, window.Beacon || function () {
    });
</script>

I've looked in the RLCL docs and haven't yet found a reference to where I can find the providerKey.

Where can I find the providerKey for Help Scout?

UPDATE: I found it on the HelpScout site.

Provider for crisp.chat?

Hi there, first of all, thanks for the amazing component, this is great! Anything that can help load less JavaScript on the client is awesome! 💯

I wanted to ask whether it would be possible to have a provider for Crisp chat, since Intercom and Drift are supported.

iOS: Intercom chat widget disappears after 6 seconds

I have the latest version installed and using Intercom via the instructions. On iOS Safari and Chrome, the placeholder Intercom chat widget appears but then disappears after about 6 seconds. Any idea why this is happening?

Beacon shown twice on iPhone

Let me preface this by saying I do not know much about this issue, other than I've had multiple users report it. I do not know if it is HelpScout or this package, but it seems it might be more widespread if it was HelpScout and I could not find any sign of it when searching.

I've had some users, all on iPhones, report that the Beacon shows up twice on some page loads. See this image:
Screen Shot 2020-04-24 at 3 22 10 PM

When this happens, they also report some kind of loss of functionality on the page itself. This makes me think there has been some sort of javascript error impeding the app. I know these types of issues are very difficult to track down and I don't have a small repro scenario (nor currently the resources to craft one), but I thought I should post this here in case anyone has an idea what might be going on.

Load chat button remains when HelpScout is maximised and router changes

Describe the bug

I'm using HelpScout and nextjs.

When I maximise HelpScout and then navigate to another route, the placeholder button shows up over the top of the real button, making it impossible to close the live chat.

How To Reproduce

No response

Screenshots

No response

Relevant Log Output

No response

Code of Conduct

  • I agree to follow this project’s Code of Conduct

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.