Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(RelatedPrompt): component logic to be reusable #1696

Merged
merged 17 commits into from
Feb 14, 2025
Merged
Show file tree
Hide file tree
Changes from all 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
79 changes: 79 additions & 0 deletions packages/x-components/src/directives/__tests__/typing.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import { mount } from '@vue/test-utils';
import typingDirective, { TypingOptions } from '../typing';

function render(typingOptions: TypingOptions) {
const wrapper = mount(
{
template: `<div v-typing="{text, speed}"></div>`,
data: () => ({
text: typingOptions.text,
speed: typingOptions.speed
})
},
{
global: {
directives: {
typing: typingDirective
}
}
}
);
return wrapper;
}

describe('typingHtmlDirective', () => {
beforeEach(() => {
jest.useFakeTimers();
});

afterEach(() => {
jest.useRealTimers();
jest.clearAllMocks();
});

it('should write the text character by character', () => {
const mockHtml = 'Hello, World!';
const wrapper = render({ text: mockHtml });
const el = wrapper.find('div').element;

expect(el.innerHTML).toBe(mockHtml[0]);

jest.runAllTimers();

expect(el.innerHTML).toBe(mockHtml);
});

it('should show a console.error if a text is not send', () => {
const consoleSpy = jest.spyOn(console, 'error').mockImplementation(() => jest.fn());

render({ text: '' });

expect(consoleSpy).toHaveBeenCalledWith('v-typing: "text" is required.');

consoleSpy.mockRestore();
});

it('should call clearTimeout when typing finished', () => {
const mockClearTimeout = jest.spyOn(globalThis, 'clearTimeout');
render({ text: 'Hello, World!' });

jest.runAllTimers();

expect(mockClearTimeout).toHaveBeenCalled();
expect(mockClearTimeout.mock.calls.length).toBeGreaterThanOrEqual(1);

mockClearTimeout.mockRestore();
});

it('should call clearTimeout after unmounting directive', () => {
const mockClearTimeout = jest.spyOn(globalThis, 'clearTimeout');
const sut = render({ text: 'Hello, World!' });

sut.unmount();

expect(mockClearTimeout).toHaveBeenCalled();
expect(mockClearTimeout.mock.calls.length).toBeGreaterThanOrEqual(1);

mockClearTimeout.mockRestore();
});
});
1 change: 1 addition & 0 deletions packages/x-components/src/directives/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from './infinite-scroll';
export * from './typing';
87 changes: 87 additions & 0 deletions packages/x-components/src/directives/typing.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import type { Directive } from 'vue';

/**
* TypingOptions interface.
*
* @public
*/
export interface TypingOptions {
/**
* The text (plain or html) that will be typed into the target element.
*/
text: string;
/**
* The typing speed in milliseconds per character.
*
*/
speed?: number;
/**
* The attribute of the HTML element where the typed text will be placed.
* If not specified, the text will be set as content (innerHTML).
*
* @example 'placeholder'
*/
targetAttr?: string;
}

interface TypingHTMLElement extends HTMLElement {
__timeoutId?: number;
}

const typingDirective: Directive<TypingHTMLElement, TypingOptions> = {
mounted(el, binding) {
execute(el, binding.value);
},

updated(el, binding) {
if (binding.value.text !== binding.oldValue?.text) {
clearTimeout(el.__timeoutId);
execute(el, binding.value);
}
},

unmounted(el) {
clearTimeout(el.__timeoutId);
}
};

/**
* Execute a typing animation in an HTML element.
*
* @param el - The HTML element where the typing animation will be displayed.
* @param options - Options for the behavior of the animation.
*/
function execute(el: TypingHTMLElement, options: TypingOptions) {
const { text, speed = 1, targetAttr = '' } = options;

if (!text) {
console.error('v-typing: "text" is required.');
return;
}

let index = 0;

const updateContent = (value: string) => {
if (targetAttr) {
el.setAttribute(targetAttr, value);
} else {
el.innerHTML = value;
}
};

const type = () => {
if (index < text.length) {
updateContent(text.slice(0, index + 1));
index++;
el.__timeoutId = setTimeout(type, speed) as unknown as number;
} else {
updateContent(text);
clearTimeout(el.__timeoutId);
el.__timeoutId = undefined;
}
};

type();
}

export default typingDirective;
5 changes: 5 additions & 0 deletions packages/x-components/src/views/adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,12 @@ const experienceControlsAdapter = platformAdapter.experienceControls.extends({
endpoint: 'https://config-service.internal.test.empathy.co/public/configs'
});

const relatedPromptsAdapter = platformAdapter.relatedPrompts.extends({
endpoint: 'https://api.empathy.co/relatedprompts/mymotivemarketplace?store=Labstore+London'
});

platformAdapter.experienceControls = experienceControlsAdapter;
platformAdapter.relatedPrompts = relatedPromptsAdapter;

export const adapter = new Proxy(platformAdapter, {
get: (obj: PlatformAdapter, prop: keyof PlatformAdapter) =>
Expand Down
25 changes: 20 additions & 5 deletions packages/x-components/src/views/home/Home.vue
Original file line number Diff line number Diff line change
Expand Up @@ -391,8 +391,21 @@
<template #related-prompts-group>
<RelatedPromptsTagList
:button-class="'x-button-lead x-button-circle x-button-ghost x-p-0'"
class="-x-mb-1 x-mt-24 desktop:x-mt-0 x-p-0"
/>
class="-x-mb-1 x-mt-24 desktop:x-mt-0 x-p-0 x-h-[70px]"
tag-class="x-rounded-xl x-gap-8 x-w-[300px]
x-max-w-[400px]"
:tag-colors="['x-bg-amber-300', 'x-bg-amber-400', 'x-bg-amber-500']"
>
<template #default="{ relatedPrompt, isSelected, onSelect }">
<RelatedPrompt
@click="onSelect"
:related-prompt="relatedPrompt"
:selected="isSelected"
data-wysiwyg="related-prompt"
:data-wysiwyg-id="relatedPrompt.suggestionText"
/>
</template>
</RelatedPromptsTagList>
<QueryPreviewList
v-if="selectedPrompt !== ''"
:queries-preview-info="relatedPromptsQueriesPreviewInfo"
Expand Down Expand Up @@ -519,7 +532,7 @@
<script lang="ts">
/* eslint-disable max-len */
import { computed, ComputedRef, defineComponent, provide, ref } from 'vue';
import { RelatedPrompt } from '@empathyco/x-types';
import { RelatedPrompt as RelatedPromptModel } from '@empathyco/x-types';
import { animateClipPath } from '../../components/animations/animate-clip-path/animate-clip-path.factory';
import StaggeredFadeAndSlide from '../../components/animations/staggered-fade-and-slide.vue';
import AutoProgressBar from '../../components/auto-progress-bar.vue';
Expand Down Expand Up @@ -582,6 +595,7 @@
import { QueryPreviewInfo } from '../../x-modules/queries-preview/store/types';
import QueryPreviewButton from '../../x-modules/queries-preview/components/query-preview-button.vue';
import DisplayEmitter from '../../components/display-emitter.vue';
import RelatedPrompt from '../../x-modules/related-prompts/components/related-prompt.vue';
import RelatedPromptsList from '../../x-modules/related-prompts/components/related-prompts-list.vue';
import RelatedPromptsTagList from '../../x-modules/related-prompts/components/related-prompts-tag-list.vue';
import ArrowRightIcon from '../../components/icons/arrow-right.vue';
Expand Down Expand Up @@ -625,6 +639,7 @@
NextQueriesList,
NextQuery,
NextQueryPreview,
RelatedPrompt,
RelatedPromptsList,
RelatedPromptsTagList,
OpenMainModal,
Expand Down Expand Up @@ -715,15 +730,15 @@
const { relatedPrompts } = useState('relatedPrompts', ['relatedPrompts']);

const relatedPromptsProducts = computed(
(): RelatedPrompt[] => relatedPrompts.value[x.query.search]?.relatedPromptsProducts
(): RelatedPromptModel[] => relatedPrompts.value[x.query.search]?.relatedPromptsProducts
);

const selectedPrompt = computed(() => relatedPrompts.value[x.query.search]?.selectedPrompt);

const relatedPromptsQueriesPreviewInfo = computed(() => {
if (relatedPromptsProducts.value) {
const relatedPromptQueries = relatedPromptsProducts.value.find(
(relatedPrompt: RelatedPrompt) => relatedPrompt.id === selectedPrompt.value
(relatedPrompt: RelatedPromptModel) => relatedPrompt.id === selectedPrompt.value
);
const queries = relatedPromptQueries?.nextQueries as string[];
return queries.map(query => ({ query }));
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { ComponentMountingOptions, mount } from '@vue/test-utils';
import RelatedPrompt from '../related-prompt.vue';
import CrossTinyIcon from '../../../../components/icons/cross-tiny.vue';
import PlusIcon from '../../../../components/icons/plus.vue';
import { createRelatedPromptStub } from '../../../../__stubs__';

const relatedPromptStub = createRelatedPromptStub('Related Prompt 1');

const typingMock = jest.fn();

function render(options: ComponentMountingOptions<typeof RelatedPrompt> = {}) {
const wrapper = mount(RelatedPrompt, {
...options,
props: { relatedPrompt: relatedPromptStub, ...options.props },
directives: {
typing: typingMock
}
});

return {
wrapper,
crossIcon: wrapper.findComponent(CrossTinyIcon),
plusIcon: wrapper.findComponent(PlusIcon)
};
}

describe('relatedPrompt component', () => {
it('should render correctly', () => {
const sut = render();

const [el, binding] = typingMock.mock.calls[0];

expect(typingMock).toHaveBeenCalled();
expect(el.tagName).toBe('SPAN');
expect(binding.value).toStrictEqual({ text: 'Related Prompt 1', speed: 50 });

expect(sut.crossIcon.exists()).toBeFalsy();
expect(sut.plusIcon.exists()).toBeTruthy();
});

it('should render cross icon when selected prop is true', () => {
const sut = render({ props: { relatedPrompt: relatedPromptStub, selected: true } });

expect(sut.crossIcon.exists()).toBeTruthy();
expect(sut.plusIcon.exists()).toBeFalsy();
});
});
Loading
Loading