Skip to content

Commit

Permalink
refine(frontend): only show widget on homepage (#531)
Browse files Browse the repository at this point in the history
  • Loading branch information
634750802 authored Dec 23, 2024
1 parent db1471d commit e636f25
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 28 deletions.
57 changes: 49 additions & 8 deletions frontend/packages/widget-react/src/Widget.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ import { Dialog, DialogClose, DialogDescription, DialogHeader, DialogOverlay, Di
import { ScrollArea } from '@/components/ui/scroll-area';
import { type ExperimentalFeatures, ExperimentalFeaturesProvider } from '@/experimental/experimental-features-provider';
import * as DialogPrimitive from '@radix-ui/react-dialog';
import { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react';
import { XIcon } from 'lucide-react'
import { XIcon } from 'lucide-react';
import { forwardRef, useEffect, useImperativeHandle, useRef, useState, useSyncExternalStore } from 'react';
import './Widget.css';

export interface WidgetProps {
Expand All @@ -25,7 +25,8 @@ export interface WidgetProps {
buttonIcon: string;
icon: string;
disableAutoThemeDetect?: boolean;
chatEngine?: string
chatEngine?: string;
apiBase?: string;
}

export interface WidgetInstance {
Expand All @@ -34,13 +35,14 @@ export interface WidgetInstance {
initialized: true;
}

export const Widget = forwardRef<WidgetInstance, WidgetProps>(({ container, trigger, experimentalFeatures, disableAutoThemeDetect = false, bootstrapStatus, exampleQuestions, icon, buttonIcon, buttonLabel, chatEngine }, ref) => {
export const Widget = forwardRef<WidgetInstance, WidgetProps>(({ container, trigger, experimentalFeatures, disableAutoThemeDetect = false, bootstrapStatus, exampleQuestions, icon, buttonIcon, buttonLabel, chatEngine, apiBase }, ref) => {
const [open, setOpen] = useState(false);
const [dark, setDark] = useState(() => matchMedia('(prefers-color-scheme: dark)').matches);
const openRef = useRef(open);
const darkRef = useRef(dark);
const [scrollTarget, setScrollTarget] = useState<HTMLDivElement | null>(null);
const gtagFn = useGtagFn();
const shouldDisplayTrigger = useShouldDisplayTrigger(apiBase);

useEffect(() => {
openRef.current = open;
Expand Down Expand Up @@ -135,7 +137,7 @@ export const Widget = forwardRef<WidgetInstance, WidgetProps>(({ container, trig
gtagFn('event', 'tidbai.events.close-widget-dialog');
}
}}>
{!trigger && <DialogTrigger asChild>
{!trigger && shouldDisplayTrigger && <DialogTrigger asChild>
<Button id="tidb-ai-widget-trigger" className="hidden sm:flex fixed right-8 bottom-8 gap-2 items-center" onClick={() => {
gtagFn('event', 'tidbai.events.open-widget-dialog');
}}>
Expand All @@ -149,9 +151,9 @@ export const Widget = forwardRef<WidgetInstance, WidgetProps>(({ container, trig
<DialogOverlay />
<DialogPrimitive.Content
className="fixed left-[50%] top-[50%] z-50 grid translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-0 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg w-[calc(100%-32px)] lg:w-[50vw] outline-none">
<DialogHeader className='relative p-8 pb-0'>
<DialogClose className='absolute right-8 top-8 transition-opacity opacity-70 hover:opacity-100'>
<XIcon className='size-4' />
<DialogHeader className="relative p-8 pb-0">
<DialogClose className="absolute right-8 top-8 transition-opacity opacity-70 hover:opacity-100">
<XIcon className="size-4" />
</DialogClose>
<DialogTitle className="flex items-center gap-4">
<img className="h-8" src={icon} alt="logo" height={32} />
Expand Down Expand Up @@ -209,3 +211,42 @@ export const Widget = forwardRef<WidgetInstance, WidgetProps>(({ container, trig
</PortalProvider>
);
});

// Listen the browser state change to determine when to display the default trigger button.
const __pushState = history.pushState;
const __replaceState = history.replaceState;

history.replaceState = (...params) => {
window.dispatchEvent(new CustomEvent('tidbaihistorychange', { detail: { type: 'replaceState', params } }));
__replaceState.call(history, ...params);
};

history.pushState = (...params) => {
window.dispatchEvent(new CustomEvent('tidbaihistorychange', { detail: { type: 'pushState', params } }));
__pushState.call(history, ...params);
};

window.addEventListener('popstate', (e) => {
window.dispatchEvent(new CustomEvent('tidbaihistorychange', { detail: { type: 'popstate', params: [e.state] } }));
});

function useShouldDisplayTrigger (apiBase?: string) {
const pathname = useSyncExternalStore(fire => {
const callback = () => {
setTimeout(() => {
fire();
}, 1);
};

window.addEventListener('tidbaihistorychange', callback);
return () => {
window.removeEventListener('tidbaihistorychange', callback);
};
}, () => window.location.pathname);

if (!apiBase) {
return pathname === '/';
}

return true;
}
2 changes: 2 additions & 0 deletions frontend/packages/widget-react/src/library.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ const controlled = script.dataset.controlled === 'true';
const trigger = controlled ? true : document.getElementById('tidb-ai-trigger');
const chatEngine = script.dataset.chatEngine;
const scriptDataMeasurementId = script.dataset.measurementId;
const apiBase = script.dataset.apiBase;

loadConfig().then(async ({ settings, bootstrapStatus, experimentalFeatures }) => {
const measurementId = scriptDataMeasurementId ?? settings.ga_id;
Expand All @@ -36,6 +37,7 @@ loadConfig().then(async ({ settings, bootstrapStatus, experimentalFeatures }) =>
<GtagProvider configured gtagFn={gtagFn} gtagId={measurementId}>
<Widget
ref={refFn}
apiBase={apiBase}
container={div}
trigger={trigger}
exampleQuestions={settings.custom_js_example_questions}
Expand Down
20 changes: 0 additions & 20 deletions frontend/packages/widget-react/src/main.tsx

This file was deleted.

0 comments on commit e636f25

Please sign in to comment.