Files
blockly/core/utils/idgenerator.ts
Neil Fraser e5dcb766bd chore: Remove radix from parseInt, simplify Blockly.utils.dom methods, use Unicode characters. (#6441)
* chore: remove radix from parseInt

Previously any number starting with '0' would be parsed as octal if the radix was left blank.  But this was changed years ago.  It is no longer needed to specify a radix.

* chore: 'ID' is identification

'id' is a part of Freud's brain.

* Use Unicode characters instead of codes

This is in line with the current style guide.

* Simplify Blockly.utils.dom methods.

classList add/remove/has supports SVG elements in all browsers Blockly supports (i.e. not IE).
2022-09-22 06:59:24 -07:00

78 lines
2.0 KiB
TypeScript

/**
* @license
* Copyright 2019 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
/**
* Generators for unique IDs.
*
* @namespace Blockly.utils.idGenerator
*/
import * as goog from '../../closure/goog/goog.js';
goog.declareModuleId('Blockly.utils.idGenerator');
/**
* Legal characters for the universally unique IDs. Should be all on
* a US keyboard. No characters that conflict with XML or JSON.
* Requests to remove additional 'problematic' characters from this
* soup will be denied. That's your failure to properly escape in
* your own environment. Issues #251, #625, #682, #1304.
*/
const soup = '!#$%()*+,-./:;=?@[]^_`{|}~' +
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
/**
* Namespace object for internal implementations we want to be able to
* stub in tests. Do not use externally.
*
* @internal
*/
const internal = {
/**
* Generate a random unique ID. This should be globally unique.
* 87 characters ^ 20 length is greater than 128 bits (better than a UUID).
*
* @returns A globally unique ID string.
*/
genUid: () => {
const length = 20;
const soupLength = soup.length;
const id = [];
for (let i = 0; i < length; i++) {
id[i] = soup.charAt(Math.random() * soupLength);
}
return id.join('');
},
};
export const TEST_ONLY = internal;
/** Next unique ID to use. */
let nextId = 0;
/**
* Generate the next unique element IDs.
* IDs are compatible with the HTML4 'id' attribute restrictions:
* Use only ASCII letters, digits, '_', '-' and '.'
*
* For UUIDs use genUid (below) instead; this ID generator should
* primarily be used for IDs that end up in the DOM.
*
* @returns The next unique identifier.
* @alias Blockly.utils.idGenerator.getNextUniqueId
*/
export function getNextUniqueId(): string {
return 'blockly-' + (nextId++).toString(36);
}
/**
* Generate a random unique ID.
*
* @see internal.genUid
* @returns A globally unique ID string.
* @alias Blockly.utils.idGenerator.genUid
*/
export function genUid(): string {
return internal.genUid();
}