Skip to content

Commit

Permalink
Implement UUID v4 with crypto.getRandomValues() (#233)
Browse files Browse the repository at this point in the history
  • Loading branch information
sabljak authored Dec 31, 2024
1 parent 57ee6c9 commit b827048
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 2 deletions.
11 changes: 10 additions & 1 deletion app/assets/javascripts/hotwire_combobox.esm.js
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,15 @@ function nextEventLoopTick() {
return new Promise((resolve) => setTimeout(() => resolve(), 0))
}

function randomUUID() {
const uuidPattern = "10000000-1000-4000-8000-100000000000";

return uuidPattern.replace(/[018]/g, (match) => {
const randomByte = crypto.getRandomValues(new Uint8Array(1))[0];
return (match ^ (randomByte & 15) >> (match / 4)).toString(16)
})
}

Combobox.Autocomplete = Base => class extends Base {
_connectListAutocomplete() {
if (!this._autocompletesList) {
Expand Down Expand Up @@ -213,7 +222,7 @@ Combobox.Callbacks = Base => class extends Base {
}

_enqueueCallback() {
const callbackId = crypto.randomUUID();
const callbackId = randomUUID();
this.callbackQueue.push(callbackId);
return callbackId
}
Expand Down
9 changes: 9 additions & 0 deletions app/assets/javascripts/hw_combobox/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -95,3 +95,12 @@ export function nextAnimationFrame() {
export function nextEventLoopTick() {
return new Promise((resolve) => setTimeout(() => resolve(), 0))
}

export function randomUUID() {
const uuidPattern = "10000000-1000-4000-8000-100000000000"

return uuidPattern.replace(/[018]/g, (match) => {
const randomByte = crypto.getRandomValues(new Uint8Array(1))[0]
return (match ^ (randomByte & 15) >> (match / 4)).toString(16)
})
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import Combobox from "hw_combobox/models/combobox/base"
import { randomUUID } from "hw_combobox/helpers"

const MAX_CALLBACK_ATTEMPTS = 3

Expand All @@ -9,7 +10,7 @@ Combobox.Callbacks = Base => class extends Base {
}

_enqueueCallback() {
const callbackId = crypto.randomUUID()
const callbackId = randomUUID()
this.callbackQueue.push(callbackId)
return callbackId
}
Expand Down

0 comments on commit b827048

Please sign in to comment.