Skip to content

Commit

Permalink
feature: support options object to too
Browse files Browse the repository at this point in the history
  • Loading branch information
koenoe committed Apr 6, 2021
1 parent bf39ff8 commit 1ad6226
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 1 deletion.
41 changes: 41 additions & 0 deletions src/create.test.ts
Expand Up @@ -19,6 +19,47 @@ describe('create', () => {
expect(images).toHaveLength(2);
});

test('should pass data attributes', () => {
const div = document.createElement('div');

div.innerHTML = `
<img src="before.jpg" alt="" />
<img src="after.jpg" alt="" />
`;
div.dataset.start = String(75);

const component = create(div);

expect(component.getAttribute('start')).toEqual(div.dataset.start);
});

test('should pass options', () => {
const div = document.createElement('div');

div.innerHTML = `
<img src="before.jpg" alt="" />
<img src="after.jpg" alt="" />
`;

const component = create(div, { color: 'red' });

expect(component.getAttribute('color')).toEqual('red');
});

test('should prioritise options over data attributes', () => {
const div = document.createElement('div');

div.innerHTML = `
<img src="before.jpg" alt="" />
<img src="after.jpg" alt="" />
`;
div.dataset.start = String(75);

const component = create(div, { start: 25 });

expect(component.getAttribute('start')).toEqual('25');
});

test("should throw error if element doesn't contain two images", () => {
const div = document.createElement('div');

Expand Down
15 changes: 14 additions & 1 deletion src/create.ts
@@ -1,7 +1,12 @@
import type { Cocoen } from './components/cocoen';
import { componentName } from './config';

export const create = (element: HTMLElement): Cocoen => {
type Options = {
start?: number;
color?: string;
};

export const create = (element: HTMLElement, options?: Options): Cocoen => {
const component = document.createElement(componentName) as Cocoen;
const before = element.querySelectorAll('img')[0];
const after = element.querySelectorAll('img')[1];
Expand All @@ -19,6 +24,14 @@ export const create = (element: HTMLElement): Cocoen => {
component.setAttribute(key, String(element.dataset[key])),
);

if (options?.start) {
component.setAttribute('start', String(options.start));
}

if (options?.color) {
component.setAttribute('color', options.color);
}

element.replaceWith(component);

return component;
Expand Down

0 comments on commit 1ad6226

Please sign in to comment.