Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 4 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,10 @@ Include `react`, `react-dom`, `@emotion-core`, `@emotion-styled`, `emotion-themi
_React must be at least version 16.8 (must have hooks)_

```html
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script crossorigin src="https://unpkg.com/@emotion/core@10/dist/core.umd.min.js"></script>
<script crossorigin src="https://unpkg.com/@emotion/styled@10/dist/styled.umd.min.js"></script>
<script crossorigin src="https://unpkg.com/emotion-theming@10/dist/emotion-theming.umd.min.js"></script>
<script crossorigin src="https://unpkg.com/react@18.2.0/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18.2.0/umd/react-dom.development.js"></script>:
<script crossorigin src="https://unpkg.com/@emotion/react@11.11.1/dist/emotion-react.umd.min.js"></script>
<script crossorigin src="https://unpkg.com/@emotion/styled@11.0.0/dist/emotion-styled.umd.min.js"></script>
<script
crossorigin
src="https://unpkg.com/tock-react-kit@latest/build/tock-react-kit.umd.js"
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@
"@storybook/testing-library": "^0.2.0",
"@types/node": "^14.0.26",
"@types/react-color": "^3.0.4",
"@types/react-dom": "^16.9.8",
"@types/react-dom": "^18.2.17",
"@types/storybook__react": "^5.2.1",
"@typescript-eslint/eslint-plugin": "^3.9.1",
"@typescript-eslint/parser": "^3.9.1",
Expand Down
1 change: 1 addition & 0 deletions src/TockOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export interface TockOptions extends PartialDeep<TockSettings> {
disableSse?: boolean;
accessibility?: TockAccessibility;
localStorageHistory?: TockLocalStorage;
autoCompletionEndPoint?:String;
}

export default TockOptions;
39 changes: 39 additions & 0 deletions src/components/AutoCompleteList/AutoCompleteList.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import React from 'react';
import { Story, Meta } from '@storybook/react';
import AutoCompleteList, { AutoCompleteListProps } from './AutoCompleteList';

export default {
title: 'Components/AutoCompleteList',
component: AutoCompleteList,
} as Meta;

const Template: Story<AutoCompleteListProps> = (args) => (
<AutoCompleteList {...args} />
);

const suggestions = [
"Semper quis lectus nulla at volutpat diam ut.",
"Lacus sed viverra tellus in hac.",
"Enim sed faucibus turpis in eu mi.",
"Ac auctor augue mauris augue.",
"Odio facilisis mauris sit amet.",
"Rhoncus urna neque viverra justo.",
];

export const Default = Template.bind({});
Default.args = {
suggestions,
onItemClick: (suggestion: string) => {
console.log(`Clicked on suggestion: ${suggestion}`);
},
inputValue: '',
};

export const WithInputValue = Template.bind({});
WithInputValue.args = {
suggestions,
onItemClick: (suggestion: string) => {
console.log(`Clicked on suggestion: ${suggestion}`);
},
inputValue: 'lorem',
};
72 changes: 72 additions & 0 deletions src/components/AutoCompleteList/AutoCompleteList.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import styled, {StyledComponent} from '@emotion/styled';
import React, {DetailedHTMLProps, HTMLAttributes} from 'react';
import {prop} from "styled-tools";

const AutoCompleteListContainer: StyledComponent<
DetailedHTMLProps<HTMLAttributes<HTMLUListElement>, HTMLUListElement>
> = styled.ul`
list-style: none;
width: 100%;
position:absolute;
padding: 0;
margin: 0;
max-height: 100px;
overflow-y: auto;
overflow-x: hidden;
bottom: 2.3rem;
left: 0;
border: 1px solid #ccc;
border-radius: 5px;
background: ${prop<any>('theme.palette.background.input')};
color: ${prop<any>('theme.palette.text.input')};
`;

const AutoCompleteItem: StyledComponent<
DetailedHTMLProps<HTMLAttributes<HTMLLIElement>, HTMLLIElement>
> = styled.li`
border-bottom: 1px solid #ccc;
padding: 0.5em 1em;
cursor: pointer;
width: 100%;
&:hover {
background: #D7D7D7;
}
.bold {
font-weight: bold;
}
`;
export interface AutoCompleteListProps {
suggestions: string[];
onItemClick: (suggestion: string) => void;
inputValue: string;
}

const highlightMatch = (suggestion: string, inputValue: string) => {
const parts = suggestion.split(new RegExp(`(${inputValue})`, 'gi'));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What happens if the input is Hello.........?? Also what happens if the input is 🏳️ and the suggestion contains 🏳️‍🌈?

return parts.map((part, index) =>
part.toLowerCase() === inputValue.toLowerCase() ? (
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should probably use the localeCompare function.

Maybe we could even take the comparison function as a predicate to support custom string comparisons?

<span key={index} className="bold">
{part}
</span>
) : (
<span key={index}>{part}</span>
)
);
};

const AutoCompleteList: React.FC<AutoCompleteListProps> = ({
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In most of the project, we type components as JSX.Element but this does look like a better type definition 👍
We should probably change other type definitions in the project, but that is outside the scope of this PR.

suggestions,
onItemClick,
inputValue
}) => (
<AutoCompleteListContainer>
{suggestions.map((suggestion, index) => (
<AutoCompleteItem key={index} onClick={() => onItemClick(suggestion)}>
{highlightMatch(suggestion, inputValue)}
</AutoCompleteItem>
))}
</AutoCompleteListContainer>
);

export default AutoCompleteList;
4 changes: 4 additions & 0 deletions src/components/AutoCompleteList/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import AutoCompleteList from './AutoCompleteList';

export * from './AutoCompleteList';
export default AutoCompleteList;
3 changes: 2 additions & 1 deletion src/components/Chat/Chat.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ export const DefaultFullScreen: Story = {
<FullscreenContainer>
<Chat
endPoint=""
autoCompletionEndPoint=""
referralParameter=""
widgets={{
ProductWidget,
Expand All @@ -67,7 +68,7 @@ export const DefaultModal: Story = {
render: () => (
<Wrapper>
<ModalContainer>
<Chat endPoint="" referralParameter="" />
<Chat endPoint="" autoCompletionEndPoint="" referralParameter="" />
</ModalContainer>
</Wrapper>
),
Expand Down
5 changes: 5 additions & 0 deletions src/components/Chat/Chat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export interface ChatProps {
disableSse?: boolean;
accessibility?: TockAccessibility;
localStorageHistory?: TockLocalStorage;
autoCompletionEndPoint?: string;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should go in TockSettings rather than in Chat's props (see #152 for an example).

}

const Chat: (props: ChatProps) => JSX.Element = ({
Expand All @@ -37,6 +38,7 @@ const Chat: (props: ChatProps) => JSX.Element = ({
disableSse = false,
accessibility = {},
localStorageHistory = {},
autoCompletionEndPoint,
}: ChatProps) => {
const {
messages,
Expand All @@ -57,6 +59,7 @@ const Chat: (props: ChatProps) => JSX.Element = ({
extraHeadersProvider,
disableSse,
localStorageHistory,
autoCompletionEndPoint
);

useEffect(() => {
Expand Down Expand Up @@ -100,6 +103,8 @@ const Chat: (props: ChatProps) => JSX.Element = ({
onSubmit={sendMessage}
accessibility={accessibility}
clearMessages={clearMessages}
autoCompletionEndPoint={autoCompletionEndPoint as string}
minValueLength={3}
/>
</Container>
);
Expand Down
57 changes: 54 additions & 3 deletions src/components/ChatInput/ChatInput.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import styled, { StyledComponent } from '@emotion/styled';
import styled, {StyledComponent} from '@emotion/styled';
import AutoCompleteList from '../AutoCompleteList';
import React, {
DetailedHTMLProps,
FormEvent,
FormHTMLAttributes,
HTMLAttributes,
InputHTMLAttributes,
useEffect,
useState,
} from 'react';
import { Send, Trash2 } from 'react-feather';
Expand Down Expand Up @@ -120,30 +122,79 @@ export interface ChatInputProps {
onSubmit: (message: string) => void;
accessibility?: TockAccessibility;
clearMessages: () => void;
autoCompletionEndPoint?: string;
minValueLength: number
}

const ChatInput: (props: ChatInputProps) => JSX.Element = ({
disabled,
onSubmit,
accessibility,
clearMessages,
autoCompletionEndPoint,
minValueLength
}: ChatInputProps): JSX.Element => {
const [value, setValue] = useState('');
const submit = (event: FormEvent<HTMLFormElement>) => {
const [suggestions, setSuggestions] = useState<string[]>([]);
const [suggestionSelected, setSuggestionSelected] = useState(false);

const submit = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
if (value) {
onSubmit(value);
setValue('');
setSuggestionSelected(false);
}
};


useEffect(() => {
const fetchData = async () => {
try {
if (value.length >= minValueLength && !suggestionSelected) {
// Fetch data from the autoCompletionEndPoint/autocompletion.json - endpoint
//autoCompletionEndPoint : 'https://example.fr'
const response = await fetch(`${autoCompletionEndPoint}/autocompletion.json`); //
const data = await response.json();
const filteredSuggestions = data.filter((item: string) =>
item.toLowerCase().includes(value.toLowerCase())
);
setSuggestions(filteredSuggestions);
} else {
setSuggestions([]);
}
} catch (error) {
console.error('Error fetching suggestions:', error);
}
};
fetchData();
}, [value, minValueLength, suggestionSelected]);

const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setValue(e.target.value);
setSuggestionSelected(false);
};

const handleSuggestionClick = (suggestion: string) => {
setValue(suggestion);
setSuggestions([]);
setSuggestionSelected(true);
};

return (
<InputOuterContainer onSubmit={submit}>
{suggestions.length > 0 && (
<AutoCompleteList
suggestions={suggestions}
onItemClick={handleSuggestionClick}
inputValue={value}
/>
)}
<Input
disabled={disabled}
className={disabled ? 'disabled-input' : undefined}
value={value}
onChange={({ target: { value } }) => setValue(value)}
onChange={handleInputChange}
/>
<SubmitIcon>
<Send
Expand Down
3 changes: 2 additions & 1 deletion src/renderChat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export const renderChat: (
endPoint: string,
referralParameter?: string,
theme: TockTheme = defaultTheme,
{ localStorage, ...options }: TockOptions = {},
{ localStorage, autoCompletionEndPoint, ...options }: TockOptions = {},
): void => {
if (typeof localStorage === 'boolean') {
throw new Error(
Expand All @@ -31,6 +31,7 @@ export const renderChat: (
<TockContext settings={{ localStorage }}>
<Chat
endPoint={endPoint}
autoCompletionEndPoint={autoCompletionEndPoint}
referralParameter={referralParameter}
{...options}
/>
Expand Down
2 changes: 2 additions & 0 deletions src/useTock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,11 +120,13 @@ const useTock: (
extraHeadersProvider?: () => Promise<Record<string, string>>,
disableSse?: boolean,
localStorageHistory?: TockLocalStorage,
autoCompletionEndPoint?:string,
) => UseTock = (
tockEndPoint: string,
extraHeadersProvider?: () => Promise<Record<string, string>>,
disableSse?: boolean,
localStorageHistory?: TockLocalStorage,
autoCompletionEndPoint?:string,
) => {
const {
localStorage: { prefix: localStoragePrefix },
Expand Down
Loading