From 131229f02f6319f30a097a4505dba7bace1ccbe4 Mon Sep 17 00:00:00 2001 From: Chenlei Hu Date: Sun, 9 Mar 2025 17:22:18 -0400 Subject: [PATCH] Use uuid for dom widget id (#2947) --- src/scripts/domWidget.ts | 6 +++--- src/utils/formatUtil.ts | 21 ++++++++++++++++++--- 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/src/scripts/domWidget.ts b/src/scripts/domWidget.ts index 77b02e8bc3..a1998f2178 100644 --- a/src/scripts/domWidget.ts +++ b/src/scripts/domWidget.ts @@ -8,7 +8,7 @@ import _ from 'lodash' import { useChainCallback } from '@/composables/functional/useChainCallback' import { app } from '@/scripts/app' import { useDomWidgetStore } from '@/stores/domWidgetStore' -import { generateRandomSuffix } from '@/utils/formatUtil' +import { generateUUID } from '@/utils/formatUtil' export interface DOMWidget extends ICustomWidget { @@ -189,9 +189,9 @@ LGraphNode.prototype.addDOMWidget = function < if (tooltip && !element.title) { element.title = tooltip } - + // Note: Before `LGraphNode.configure` is called, `this.id` is always `-1`. const widget = new DOMWidgetImpl({ - id: `${this.id}:${name}:${generateRandomSuffix()}`, + id: generateUUID(), node: this, name, type, diff --git a/src/utils/formatUtil.ts b/src/utils/formatUtil.ts index 74fc8dc70a..659b96c9ea 100644 --- a/src/utils/formatUtil.ts +++ b/src/utils/formatUtil.ts @@ -316,10 +316,25 @@ export const paramsToCacheKey = (params: unknown): string => { } /** - * Generates a random 4-character string to use as a unique suffix + * Generates a RFC4122 compliant UUID v4 using the native crypto API when available + * @returns A properly formatted UUID string */ -export const generateRandomSuffix = (): string => - Math.random().toString(36).substring(2, 6) +export const generateUUID = (): string => { + // Use native crypto.randomUUID() if available (modern browsers) + if ( + typeof crypto !== 'undefined' && + typeof crypto.randomUUID === 'function' + ) { + return crypto.randomUUID() + } + + // Fallback implementation for older browsers + return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => { + const r = (Math.random() * 16) | 0 + const v = c === 'x' ? r : (r & 0x3) | 0x8 + return v.toString(16) + }) +} /** * Formats a number to a locale-specific string