Skip to content

Commit

Permalink
feat(shared): add invariant util
Browse files Browse the repository at this point in the history
  • Loading branch information
francoischalifour committed Dec 6, 2020
1 parent 00ec22b commit 0e28f55
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 1 deletion.
11 changes: 10 additions & 1 deletion packages/autocomplete-js/src/utils/getHTMLElement.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
import { invariant } from '@algolia/autocomplete-shared';

export function getHTMLElement(value: string | HTMLElement): HTMLElement {
if (typeof value === 'string') {
return document.querySelector<HTMLElement>(value)!;
const element = document.querySelector<HTMLElement>(value)!;

invariant(
element !== null,
`The element ${JSON.stringify(value)} is not in the document.`
);

return element;
}

return value;
Expand Down
1 change: 1 addition & 0 deletions packages/autocomplete-shared/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export * from './createRef';
export * from './debounce';
export * from './invariant';
export * from './isEqual';
export * from './MaybePromise';
export * from './warn';
Expand Down
14 changes: 14 additions & 0 deletions packages/autocomplete-shared/src/invariant.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/**
* Throws an error if the condition is not met in development monde.
* This is used to make development a better experience to provide guidance as
* to where the error comes from.
*/
export function invariant(condition: boolean, message: string) {
if (!__DEV__) {
return;
}

if (!condition) {
throw new Error(`[Autocomplete] ${message}`);
}
}

0 comments on commit 0e28f55

Please sign in to comment.