Skip to content

Improve string source handling #8

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

Merged
merged 2 commits into from
Oct 21, 2024
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
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## UNPUBLISHED

### Added

- A string `source` can now contain `{{term}}`, to accommodate paths where `?term=XXX` isn't suitable
- This means you could now use `example.com/search/{{term}}/other-stuff`

### Fixed

- The mouse being over the popup when it's rendered no longer selects that value whilst typing
- A string `source` can now contain a query string (`?`)
- It now checks the source and adds either `?` or `&`, whichever is appropriate

### Changes

Expand Down
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ new Autocomplete(
{
// Query this source & expect a JSON response
source: './relative-folder/query.html'
// or './relative-folder/{{term}}/query'
}
)
// Don't forget to start it
Expand Down Expand Up @@ -107,7 +108,10 @@ The source of the autocompelte data
#### `SourceTypes<T>`

- `string`
a URL we will `GET` with a `term` querystring parameter (expects a JSON response)
a URL that we will `GET`, expecting a JSON response.
**Note:** the search term is added to the URL in one of two ways
- if `{{term}}` is in the URL, this will be replaced, else
- a `term` querystring parameter is appended to the URL
- `Record` set
an object with string keys and values, treated as label, value respectively
- `string[]`
Expand Down
15 changes: 12 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -326,9 +326,18 @@ export class Autocomplete<T = { label: string; value: string }> {
typeof this.options.source === 'string'
? await ((
await window.fetch(
this.options.source +
'?term=' +
encodeURIComponent(data.term),
this.options.source.indexOf('{{term}}') > -1
? this.options.source.replace(
'{{term}}',
encodeURIComponent(data.term),
)
: this.options.source +
(this.options.source.indexOf('?') >
-1
? '&'
: '?') +
'term=' +
encodeURIComponent(data.term),
)
).json() as Promise<ListItemType<T>[]>)
: typeof this.options.source === 'function'
Expand Down
2 changes: 2 additions & 0 deletions tests/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
'use strict';

import { Autocomplete, AutocompleteStatus } from '../src/index';

describe('Core Tests', () => {
Expand Down
46 changes: 46 additions & 0 deletions tests/initialiseEnvironment.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/* exported initialiseEnvironment */

'use strict';
import { Autocomplete, AutocompleteStatus } from '../src';
import { SourceTypes } from '../src/Types/SourceTypes';

export function initialiseEnvironment(): {
inputEL: HTMLInputElement;
autocomplete: Autocomplete<{ label: string; value: string }>;
};
export function initialiseEnvironment(newSource: string): {
inputEL: HTMLInputElement;
autocomplete: Autocomplete<{ label: string; value: string }>;
};
export function initialiseEnvironment<T = { label: string; value: string }>(
newSource?: SourceTypes<T>,
): { inputEL: HTMLInputElement; autocomplete: Autocomplete<T> } {
let inputEL = document.createElement('input');

inputEL.classList.add('test');
inputEL = document.body.insertAdjacentElement(
'beforeend',
inputEL,
) as HTMLInputElement;

const autocomplete = new Autocomplete<T>('.test', {
source:
newSource ??
([
{ label: 'First label', value: 'First Value' },
{ label: 'Second label', value: 'Second Value' },
{ label: 'Third label', value: 'Third Value' },
{ label: 'Final label', value: 'Final Value' },
] as SourceTypes<T>),
onOpen: (e, data) => {
data.ul.style.width = `${(e.target as HTMLInputElement).width}px`;
},
});

autocomplete.start();

it('Setup complete with "started" state', () =>
expect(autocomplete.status).toBe(AutocompleteStatus.Started));

return { inputEL, autocomplete };
}
47 changes: 4 additions & 43 deletions tests/mouseover.test.ts
Original file line number Diff line number Diff line change
@@ -1,50 +1,11 @@
import { Autocomplete, AutocompleteStatus } from '../src/index';
'use strict';

import { initialiseEnvironment } from './initialiseEnvironment';

jest.useFakeTimers();

describe('Mouseover Tests', () => {
let inputEL: HTMLInputElement, autocomplete: Autocomplete;

describe('Test environment:-', () => {
it('has added element', () => {
inputEL = document.createElement('input');

inputEL.classList.add('test');
inputEL = document.body.insertAdjacentElement(
'beforeend',
inputEL,
) as HTMLInputElement;

expect(inputEL).not.toBeNull();
});

it('has created autocomplete', () => {
autocomplete = new Autocomplete('.test', {
source: [
{ label: 'First label', value: 'First Value' },
{ label: 'Second label', value: 'Second Value' },
{ label: 'Third label', value: 'Third Value' },
{ label: 'Final label', value: 'Final Value' },
],
onOpen: (e, data) => {
data.ul.style.width = `${
(e.target as HTMLInputElement).width
}px`;
},
});

expect(autocomplete).not.toBeNull();
});

it('has initial state of "stopped"', () =>
expect(autocomplete.status).toBe(AutocompleteStatus.Stopped));

it('"start" should not throw', () =>
expect(autocomplete.start).not.toThrow());

it('now has "started" state', () =>
expect(autocomplete.status).toBe(AutocompleteStatus.Started));
});
const { inputEL, autocomplete } = initialiseEnvironment();

describe('Mouse over', () => {
beforeEach(() => {
Expand Down
53 changes: 53 additions & 0 deletions tests/term.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
'use strict';

import { initialiseEnvironment } from './initialiseEnvironment';

//@ts-ignore
global.fetch = jest.fn(() =>
Promise.resolve({
json: () => Promise.resolve([{ label: 'Test', value: 'Test' }]),
}),
);

describe('Term Tests', () => {
describe('simple string (no QS):-', () => {
const { inputEL } = initialiseEnvironment('https://example.com');

inputEL.value = 'Test';

inputEL.dispatchEvent(new Event('change'));

it('appends "?term="', () =>
expect(fetch).toHaveBeenCalledWith(
'https://example.com?term=Test',
));
});

describe('string with `?`:-', () => {
const { inputEL } = initialiseEnvironment('https://example.com?test=1');

inputEL.value = 'Test';

inputEL.dispatchEvent(new Event('change'));

it('appends "&term="', () =>
expect(fetch).toHaveBeenCalledWith(
'https://example.com?test=1&term=Test',
));
});

describe('string with `{{term}}`:-', () => {
const { inputEL } = initialiseEnvironment(
'https://example.com/search/{{term}}/suffix',
);

inputEL.value = 'Test';

inputEL.dispatchEvent(new Event('change'));

it('embeds the "term"', () =>
expect(fetch).toHaveBeenCalledWith(
'https://example.com/search/Test/suffix',
));
});
});