Skip to content

Commit 2881679

Browse files
committed
fix: comply with Custom Elements name constraints
1 parent 7cf3131 commit 2881679

2 files changed

Lines changed: 20 additions & 1 deletion

File tree

src/transform.js

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,10 @@ function toDashCase(name) {
1515
return dashCaseLetters.join('');
1616
}
1717

18+
function removeInvalidCharacters(name) {
19+
return name.replace(/^[^a-z]+/, '').replace(/[^a-z0-9-]/g, '');
20+
}
21+
1822
function incrementTagName(tag, counter, start = 1) {
1923
const newName = counter === start ? tag : `${tag}-${counter}`;
2024
const elementRegistered = !!customElements.get(newName);
@@ -32,7 +36,7 @@ function getClassUniqueTag(klass) {
3236
}
3337

3438
if (Object.prototype.hasOwnProperty.call(klass, 'name') && klass.name) {
35-
tag = toDashCase(klass.name);
39+
tag = removeInvalidCharacters(toDashCase(klass.name));
3640
if (tag.indexOf('-') === -1) {
3741
tag = `c-${tag}`;
3842
}

src/transform.spec.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,21 @@ describe('transform', () => {
9292
expect(customElements.get('my-crocus')).to.equal(MyCrocus);
9393
});
9494

95+
it('ignores certain characters to comply with Custom Elements name constraints', () => {
96+
class _MyCampanula extends HTMLElement {}
97+
expect(getNameForCEClass(_MyCampanula)).to.equal('my-campanula');
98+
expect(customElements.get('my-campanula')).to.equal(_MyCampanula);
99+
class $MyLathyrus extends HTMLElement {}
100+
expect(getNameForCEClass($MyLathyrus)).to.equal('my-lathyrus');
101+
expect(customElements.get('my-lathyrus')).to.equal($MyLathyrus);
102+
class $1MyGrandiflora2 extends HTMLElement {}
103+
expect(getNameForCEClass($1MyGrandiflora2)).to.equal('my-grandiflora2');
104+
expect(customElements.get('my-grandiflora2')).to.equal($1MyGrandiflora2);
105+
class _1My$Campanula_Lathyrus2Grandiflora3 extends HTMLElement {} // eslint-disable-line camelcase
106+
expect(getNameForCEClass(_1My$Campanula_Lathyrus2Grandiflora3)).to.equal('my-campanula-lathyrus2-grandiflora3');
107+
expect(customElements.get('my-campanula-lathyrus2-grandiflora3')).to.equal(_1My$Campanula_Lathyrus2Grandiflora3);
108+
});
109+
95110
it('does not register the same class twice', () => {
96111
class MyIris extends HTMLElement {}
97112
expect(getNameForCEClass(MyIris)).to.equal('my-iris');

0 commit comments

Comments
 (0)