feat(core): add dom strategy

pull/3453/head
Arman Ozak 6 years ago
parent 8c917e390e
commit b19519ece2

@ -0,0 +1,28 @@
export class DomStrategy {
constructor(
public target: HTMLElement = document.head,
public position: InsertPosition = 'beforeend',
) {}
insertElement<T extends HTMLElement>(element: T) {
this.target.insertAdjacentElement(this.position, element);
}
}
export const DOM_STRATEGY = {
AfterElement(element: HTMLElement) {
return new DomStrategy(element, 'afterend');
},
AppendToBody() {
return new DomStrategy(document.body, 'beforeend');
},
AppendToHead() {
return new DomStrategy(document.head, 'beforeend');
},
BeforeElement(element: HTMLElement) {
return new DomStrategy(element, 'beforebegin');
},
PrependToHead() {
return new DomStrategy(document.head, 'afterbegin');
},
};

@ -0,0 +1,49 @@
import { DomStrategy, DOM_STRATEGY } from '../strategies';
describe('DomStrategy', () => {
describe('#insertElement', () => {
it('should append element to head by default', () => {
const strategy = new DomStrategy();
const element = document.createElement('script');
strategy.insertElement(element);
expect(document.head.lastChild).toBe(element);
});
it('should append element to body when body is given as target', () => {
const strategy = new DomStrategy(document.body);
const element = document.createElement('script');
strategy.insertElement(element);
expect(document.body.lastChild).toBe(element);
});
it('should prepend to head when position is given as "afterbegin"', () => {
const strategy = new DomStrategy(undefined, 'afterbegin');
const element = document.createElement('script');
strategy.insertElement(element);
expect(document.head.firstChild).toBe(element);
});
});
});
describe('DOM_STRATEGY', () => {
let div = document.createElement('DIV');
beforeEach(() => {
document.body.innerHTML = '';
document.body.appendChild(div);
});
test.each`
name | target | position
${'AfterElement'} | ${div} | ${'afterend'}
${'AppendToBody'} | ${document.body} | ${'beforeend'}
${'AppendToHead'} | ${document.head} | ${'beforeend'}
${'BeforeElement'} | ${div} | ${'beforebegin'}
${'PrependToHead'} | ${document.head} | ${'afterbegin'}
`('should successfully map $name to CrossOriginStrategy', ({ name, target, position }) => {
expect(DOM_STRATEGY[name](target)).toEqual(new DomStrategy(target, position));
});
});
Loading…
Cancel
Save