Skip to content

Commit

Permalink
Generate HTML4 compliant ids
Browse files Browse the repository at this point in the history
  • Loading branch information
timroes committed Apr 6, 2018
1 parent 37bc86c commit 6a6f4a0
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 2 deletions.
5 changes: 3 additions & 2 deletions src/services/accessibility/html_id_generator.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@ import uuid from 'uuid';
* This function returns a function to generate ids.
* This can be used to generate unique, but predictable ids to pair labels
* with their inputs. It takes an optional prefix as a parameter. If you don't
* specify it, it generates a random id prefix.
* specify it, it generates a random id prefix. If you specify a custom prefix
* it should begin with an letter to be HTML4 compliant.
*/
export function htmlIdGenerator(idPrefix) {
const prefix = idPrefix || uuid.v1();
const prefix = idPrefix || `i${uuid.v1()}`;
return (suffix) => `${prefix}_${suffix || uuid.v1()}`;
}
4 changes: 4 additions & 0 deletions src/services/accessibility/html_id_generator.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@ describe('htmlIdGenerator', () => {
expect(idGenerator1('foo')).not.toBe(idGenerator2('foo'));
});

it('should generate ids beginning with "i" when not passing a prefix', () => {
expect(htmlIdGenerator()()).toMatch(/^i/);
});

it('should generate different ids if no suffix is passed', () => {
const generator = htmlIdGenerator();
expect(generator()).not.toBe(generator());
Expand Down

0 comments on commit 6a6f4a0

Please sign in to comment.