Skip to content

Commit

Permalink
Fix #2741 by changing Id selectors from #{id} to [id="{id}"] (#2742)
Browse files Browse the repository at this point in the history
* init

* Fix build
  • Loading branch information
BryanValverdeU authored Jul 10, 2024
1 parent 05f0ce0 commit f57a68c
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export function ensureUniqueId(element: HTMLElement, idPrefix: string): string {
const doc = element.ownerDocument;
let i = 0;

while (!element.id || doc.querySelectorAll('#' + element.id).length > 1) {
while (!element.id || doc.querySelectorAll(`[id="${element.id}"]`).length > 1) {
element.id = idPrefix + '_' + i++;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -529,7 +529,7 @@ describe('setDOMSelection', () => {
createRangeSpy.and.returnValue(mockedRange);

querySelectorAllSpy.and.callFake(selector => {
return selector == '#image_0' ? ['', ''] : [''];
return selector == '[id="image_0"]' ? ['', ''] : [''];
});
hasFocusSpy.and.returnValue(false);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,52 @@ describe('ensureUniqueId', () => {
id: 'dup',
} as any;
querySelectorAllSpy.and.callFake((selector: string) =>
selector == '#dup' ? [{}, {}] : []
selector == '[id="dup"]' ? [{}, {}] : []
);
const result = ensureUniqueId(element, 'prefix');

expect(result).toBe('dup_0');
});

it('Should not throw when element id starts with number', () => {
const element = {
ownerDocument: doc,
id: '0',
} as any;

let isFirst = true;
querySelectorAllSpy.and.callFake((_selector: string) => {
if (isFirst) {
isFirst = false;
return [{}, {}];
}
return [{}];
});

ensureUniqueId(element, 'prefix');

expect(querySelectorAllSpy).toHaveBeenCalledWith('[id="0"]');
expect(element.id).toEqual('0_0');
});

it('Should not throw when element id starts with hyphen', () => {
const element = {
ownerDocument: doc,
id: '-',
} as any;

let isFirst = true;
querySelectorAllSpy.and.callFake((_selector: string) => {
if (isFirst) {
isFirst = false;
return [{}, {}];
}
return [{}];
});

ensureUniqueId(element, 'prefix');

expect(querySelectorAllSpy).toHaveBeenCalledWith('[id="-"]');
expect(element.id).toEqual('-_0');
});
});

0 comments on commit f57a68c

Please sign in to comment.