Skip to content

Commit

Permalink
fix: comply with Custom Elements name constraints
Browse files Browse the repository at this point in the history
  • Loading branch information
bashmish committed Apr 23, 2022
1 parent 7cf3131 commit 2881679
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/transform.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ function toDashCase(name) {
return dashCaseLetters.join('');
}

function removeInvalidCharacters(name) {
return name.replace(/^[^a-z]+/, '').replace(/[^a-z0-9-]/g, '');
}

function incrementTagName(tag, counter, start = 1) {
const newName = counter === start ? tag : `${tag}-${counter}`;
const elementRegistered = !!customElements.get(newName);
Expand All @@ -32,7 +36,7 @@ function getClassUniqueTag(klass) {
}

if (Object.prototype.hasOwnProperty.call(klass, 'name') && klass.name) {
tag = toDashCase(klass.name);
tag = removeInvalidCharacters(toDashCase(klass.name));
if (tag.indexOf('-') === -1) {
tag = `c-${tag}`;
}
Expand Down
15 changes: 15 additions & 0 deletions src/transform.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,21 @@ describe('transform', () => {
expect(customElements.get('my-crocus')).to.equal(MyCrocus);
});

it('ignores certain characters to comply with Custom Elements name constraints', () => {
class _MyCampanula extends HTMLElement {}
expect(getNameForCEClass(_MyCampanula)).to.equal('my-campanula');
expect(customElements.get('my-campanula')).to.equal(_MyCampanula);
class $MyLathyrus extends HTMLElement {}
expect(getNameForCEClass($MyLathyrus)).to.equal('my-lathyrus');
expect(customElements.get('my-lathyrus')).to.equal($MyLathyrus);
class $1MyGrandiflora2 extends HTMLElement {}
expect(getNameForCEClass($1MyGrandiflora2)).to.equal('my-grandiflora2');
expect(customElements.get('my-grandiflora2')).to.equal($1MyGrandiflora2);
class _1My$Campanula_Lathyrus2Grandiflora3 extends HTMLElement {} // eslint-disable-line camelcase
expect(getNameForCEClass(_1My$Campanula_Lathyrus2Grandiflora3)).to.equal('my-campanula-lathyrus2-grandiflora3');
expect(customElements.get('my-campanula-lathyrus2-grandiflora3')).to.equal(_1My$Campanula_Lathyrus2Grandiflora3);
});

it('does not register the same class twice', () => {
class MyIris extends HTMLElement {}
expect(getNameForCEClass(MyIris)).to.equal('my-iris');
Expand Down

0 comments on commit 2881679

Please sign in to comment.