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

feat(js): change renderer implementation to virtual DOM #381

Merged
merged 16 commits into from
Jan 21, 2021
Merged
Show file tree
Hide file tree
Changes from 8 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
2 changes: 1 addition & 1 deletion bundlesize.config.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
},
{
"path": "packages/autocomplete-js/dist/umd/index.production.js",
"maxSize": "10.1 kB"
"maxSize": "13.25 kB"
},
{
"path": "packages/autocomplete-preset-algolia/dist/umd/index.production.js",
Expand Down
39 changes: 0 additions & 39 deletions examples/js/app.ts

This file was deleted.

96 changes: 96 additions & 0 deletions examples/js/app.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
/** @jsx h */
import {
autocomplete,
getAlgoliaHits,
highlightHit,
} from '@algolia/autocomplete-js';
import { createAlgoliaInsightsPlugin } from '@algolia/autocomplete-plugin-algolia-insights';
import { createQuerySuggestionsPlugin } from '@algolia/autocomplete-plugin-query-suggestions';
import { createLocalStorageRecentSearchesPlugin } from '@algolia/autocomplete-plugin-recent-searches';
import { Hit } from '@algolia/client-search';
import algoliasearch from 'algoliasearch';
import { h } from 'preact';
import insightsClient from 'search-insights';

import '@algolia/autocomplete-theme-classic';

type Product = { name: string; image: string };
type ProductHit = Hit<Product>;

const appId = 'latency';
const apiKey = '6be0576ff61c053d5f9a3225e2a90f76';
const searchClient = algoliasearch(appId, apiKey);
insightsClient('init', { appId, apiKey });

const algoliaInsightsPlugin = createAlgoliaInsightsPlugin({ insightsClient });
const recentSearchesPlugin = createLocalStorageRecentSearchesPlugin({
key: 'search',
limit: 3,
});
const querySuggestionsPlugin = createQuerySuggestionsPlugin({
searchClient,
indexName: 'instant_search_demo_query_suggestions',
getSearchParams({ state }) {
return recentSearchesPlugin.data.getAlgoliaSearchParams({
clickAnalytics: true,
hitsPerPage: state.query ? 5 : 10,
});
},
});

autocomplete({
container: '#autocomplete',
placeholder: 'Search',
debug: true,
openOnFocus: true,
plugins: [
algoliaInsightsPlugin,
recentSearchesPlugin,
querySuggestionsPlugin,
],
getSources({ query }) {
if (!query) {
return [];
}

return [
{
getItems() {
return getAlgoliaHits<Product>({
searchClient,
queries: [{ indexName: 'instant_search', query }],
});
},
templates: {
item({ item }) {
Copy link
Contributor

Choose a reason for hiding this comment

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

what does an example using a provided pragma / createElement look like (without using jsx directly)?

Copy link
Contributor

Choose a reason for hiding this comment

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

I'm not sure whether the main example should be using jsx, since it might confuse people unfamiliar with it (Shopify, magento...)

Copy link
Member Author

Choose a reason for hiding this comment

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

what does an example using a provided pragma / createElement look like (without using jsx directly)?

You can see in the plugins implementations.

Copy link
Member Author

Choose a reason for hiding this comment

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

I'm not sure whether the main example should be using jsx, since it might confuse people unfamiliar with it (Shopify, magento...)

The main example is used as a playground. We'll provide code samples for people relying on HTML.

Copy link
Member Author

Choose a reason for hiding this comment

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

I created this sandbox to demo how you can use Autocomplete with HTML.

return <ProductItem hit={item} />;
},
},
},
];
},
});

type ProductItemProps = {
hit: ProductHit;
};

function ProductItem({ hit }: ProductItemProps) {
return (
<div className="aa-ItemContent">
<div className="aa-ItemSourceIcon">
<img src={hit.image} alt={hit.name} width="20" height="20" />
</div>

<div
className="aa-ItemTitle"
dangerouslySetInnerHTML={{
__html: highlightHit<ProductHit>({
hit,
attribute: 'name',
}),
}}
/>
</div>
);
}
2 changes: 1 addition & 1 deletion examples/js/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,6 @@
</div>

<script src="env.ts"></script>
<script src="app.ts"></script>
<script src="app.tsx"></script>
</body>
</html>
2 changes: 2 additions & 0 deletions examples/js/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@
"@algolia/autocomplete-plugin-recent-searches": "1.0.0-alpha.38",
"@algolia/autocomplete-preset-algolia": "1.0.0-alpha.38",
"@algolia/autocomplete-theme-classic": "1.0.0-alpha.38",
"@algolia/client-search": "4.8.3",
"algoliasearch": "4.8.3",
"preact": "10.5.7",
"search-insights": "1.6.3"
},
"devDependencies": {
Expand Down
2 changes: 1 addition & 1 deletion packages/autocomplete-core/src/getPropGetters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ export function getPropGetters<
function onFocus(event: TEvent) {
// We want to trigger a query when `openOnFocus` is true
// because the panel should open with the current query.
if (props.openOnFocus || store.getState().query) {
if (props.openOnFocus || Boolean(store.getState().query)) {
onInput({
event,
props,
Expand Down
4 changes: 2 additions & 2 deletions packages/autocomplete-core/src/onInput.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ export function onInput<TItem extends BaseItem>({
setQuery(query);
setActiveItemId(props.defaultActiveItemId);

if (query && props.openOnFocus === false) {
if (!query && props.openOnFocus === false) {
setStatus('idle');
setCollections(
store.getState().collections.map((collection) => ({
Expand Down Expand Up @@ -120,7 +120,7 @@ export function onInput<TItem extends BaseItem>({
setCollections(collections as any);
setIsOpen(
nextState.isOpen ??
((query && props.openOnFocus) ||
((!query && props.openOnFocus) ||
props.shouldPanelShow({ state: store.getState() }))
);

Expand Down
2 changes: 1 addition & 1 deletion packages/autocomplete-core/src/stateReducer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ export const stateReducer: Reducer = (state, action) => {
return {
...state,
activeItemId: action.props.defaultActiveItemId,
isOpen: action.props.openOnFocus || state.query,
isOpen: action.props.openOnFocus || Boolean(state.query),
};
}

Expand Down
3 changes: 2 additions & 1 deletion packages/autocomplete-js/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@
"dependencies": {
"@algolia/autocomplete-core": "1.0.0-alpha.38",
"@algolia/autocomplete-preset-algolia": "1.0.0-alpha.38",
"@algolia/autocomplete-shared": "1.0.0-alpha.38"
"@algolia/autocomplete-shared": "1.0.0-alpha.38",
"preact": "^10.0.0"
},
"devDependencies": {
"@algolia/client-search": "4.8.3"
Expand Down
2 changes: 2 additions & 0 deletions packages/autocomplete-js/src/__tests__/autocomplete.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ describe('autocomplete-js', () => {
</label>
<div
class="aa-LoadingIndicator"
hidden=""
Haroenv marked this conversation as resolved.
Show resolved Hide resolved
>
<svg
class="aa-LoadingIcon"
Expand Down Expand Up @@ -130,6 +131,7 @@ describe('autocomplete-js', () => {
>
<button
class="aa-ResetButton"
hidden=""
type="reset"
>
<svg
Expand Down
28 changes: 13 additions & 15 deletions packages/autocomplete-js/src/autocomplete.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ export function autocomplete<TItem extends BaseItem>(
},
})
);
const renderRequestIdRef = createRef<number | null>(null);
const lastStateRef = createRef<AutocompleteState<TItem>>({
collections: [],
completion: null,
Expand Down Expand Up @@ -76,13 +75,13 @@ export function autocomplete<TItem extends BaseItem>(

const dom = reactive(() =>
createAutocompleteDom({
placeholder: props.value.core.placeholder,
isTouch: isTouch.value,
state: lastStateRef.current,
autocomplete: autocomplete.value,
autocompleteScopeApi,
classNames: props.value.renderer.classNames,
isTouch: isTouch.value,
placeholder: props.value.core.placeholder,
propGetters,
autocompleteScopeApi,
state: lastStateRef.current,
})
);

Expand All @@ -101,29 +100,28 @@ export function autocomplete<TItem extends BaseItem>(

function runRender() {
const renderProps = {
isTouch: isTouch.value,
state: lastStateRef.current,
autocomplete: autocomplete.value,
propGetters,
dom: dom.value,
autocompleteScopeApi,
classNames: props.value.renderer.classNames,
container: props.value.renderer.container,
createElement: props.value.renderer.renderer.createElement,
francoischalifour marked this conversation as resolved.
Show resolved Hide resolved
dom: dom.value,
Fragment: props.value.renderer.renderer.Fragment,
isTouch: isTouch.value,
panelContainer: isTouch.value
? dom.value.touchOverlay
: props.value.renderer.panelContainer,
autocompleteScopeApi,
propGetters,
state: lastStateRef.current,
};

renderSearchBox(renderProps);
renderPanel(props.value.renderer.render, renderProps);
}

function scheduleRender(state: AutocompleteState<TItem>) {
if (renderRequestIdRef.current !== null) {
cancelAnimationFrame(renderRequestIdRef.current);
}

lastStateRef.current = state;
renderRequestIdRef.current = requestAnimationFrame(runRender);
runRender();
Haroenv marked this conversation as resolved.
Show resolved Hide resolved
}

runEffect(() => {
Expand Down
20 changes: 0 additions & 20 deletions packages/autocomplete-js/src/components/Element.ts

This file was deleted.

15 changes: 7 additions & 8 deletions packages/autocomplete-js/src/components/Input.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,30 +3,29 @@ import {
AutocompleteScopeApi,
} from '@algolia/autocomplete-core';

import { createDomElement } from '../createDomElement';
import { AutocompletePropGetters, AutocompleteState } from '../types';
import { Component } from '../types/Component';
import { setProperties } from '../utils';

import { Element } from './Element';

type InputProps = {
onTouchEscape?(): void;
state: AutocompleteState<any>;
autocompleteScopeApi: AutocompleteScopeApi<any>;
getInputProps: AutocompletePropGetters<any>['getInputProps'];
getInputPropsCore: AutocompleteCoreApi<any>['getInputProps'];
autocompleteScopeApi: AutocompleteScopeApi<any>;
onTouchEscape?(): void;
state: AutocompleteState<any>;
};

export const Input: Component<InputProps, HTMLInputElement> = ({
autocompleteScopeApi,
classNames,
getInputProps,
getInputPropsCore,
state,
autocompleteScopeApi,
onTouchEscape,
state,
...props
}) => {
const element = Element('input', props);
const element = createDomElement('input', props);
const inputProps = getInputProps({
state,
props: getInputPropsCore({ inputElement: element }),
Expand Down
1 change: 0 additions & 1 deletion packages/autocomplete-js/src/components/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
export * from './Element';
export * from './Input';
export * from './LoadingIcon';
export * from './ResetIcon';
Expand Down
Loading