File tree Expand file tree Collapse file tree 3 files changed +45
-13
lines changed Expand file tree Collapse file tree 3 files changed +45
-13
lines changed Original file line number Diff line number Diff line change 11/* Utilities for DOM traversal or navigation */
22import logging from "./logging" ;
3+ import create_uuid from "./uuid" ;
34
45const logger = logging . getLogger ( "core dom" ) ;
56
@@ -541,19 +542,7 @@ const escape_css_id = (id) => {
541542 */
542543const 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} ;
Original file line number Diff line number Diff line change 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 ;
Original file line number Diff line number Diff line change 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 - 9 a - f ] { 8 } - [ 0 - 9 a - f ] { 4 } - 4 [ 0 - 9 a - f ] { 3 } - [ 8 9 a b ] [ 0 - 9 a - f ] { 3 } - [ 0 - 9 a - 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+ } ) ;
You can’t perform that action at this time.
0 commit comments