Skip to content

Commit 8b70876

Browse files
committed
feat(core uuid): Add utility function to generate a uuid.
1 parent db271ce commit 8b70876

File tree

3 files changed

+45
-13
lines changed

3 files changed

+45
-13
lines changed

src/core/dom.js

Lines changed: 2 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
/* Utilities for DOM traversal or navigation */
22
import logging from "./logging";
3+
import create_uuid from "./uuid";
34

45
const logger = logging.getLogger("core dom");
56

@@ -541,19 +542,7 @@ const escape_css_id = (id) => {
541542
*/
542543
const element_uuid = (el) => {
543544
if (!get_data(el, "uuid", false)) {
544-
let uuid;
545-
if (window.crypto.randomUUID) {
546-
// Create a real UUID
547-
// window.crypto.randomUUID does only exist in browsers with secure
548-
// context.
549-
// See: https://developer.mozilla.org/en-US/docs/Web/API/Crypto/randomUUID
550-
uuid = window.crypto.randomUUID();
551-
} else {
552-
// Create a sufficiently unique ID
553-
const array = new Uint32Array(4);
554-
uuid = window.crypto.getRandomValues(array).join("");
555-
}
556-
set_data(el, "uuid", uuid);
545+
set_data(el, "uuid", create_uuid());
557546
}
558547
return get_data(el, "uuid");
559548
};

src/core/uuid.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/**
2+
* Get a universally unique id (uuid).
3+
*
4+
* @returns {String} - The uuid.
5+
*/
6+
const create_uuid = () => {
7+
let uuid;
8+
if (window.crypto.randomUUID) {
9+
// Create a real UUID
10+
// window.crypto.randomUUID does only exist in browsers with secure
11+
// context.
12+
// See: https://developer.mozilla.org/en-US/docs/Web/API/Crypto/randomUUID
13+
uuid = window.crypto.randomUUID();
14+
} else {
15+
// Create a sufficiently unique ID
16+
const array = new Uint32Array(4);
17+
uuid = window.crypto.getRandomValues(array).join("");
18+
}
19+
return uuid;
20+
};
21+
export default create_uuid;

src/core/uuid.test.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import create_uuid from "./uuid";
2+
3+
describe("uuid", function () {
4+
it("returns a UUIDv4", function () {
5+
const uuid = create_uuid();
6+
expect(uuid).toMatch(
7+
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/
8+
);
9+
});
10+
11+
it("returns a sufficiently unique id", function () {
12+
// Mock window.crypto.randomUUID not existing, like in browser with
13+
// non-secure context.
14+
const orig_randomUUID = window.crypto.randomUUID;
15+
window.crypto.randomUUID = undefined;
16+
17+
const uuid = create_uuid();
18+
expect(uuid).toMatch(/^[0-9]*$/);
19+
20+
window.crypto.randomUUID = orig_randomUUID;
21+
});
22+
});

0 commit comments

Comments
 (0)