tiny-dices
Version:
Tiny Dices adds a sprinkle of fun and a touch of magic to your dice-rolling adventures — fully customizable with CSS and JavaScript to match your style, theme, or imagination! 🎲✨
420 lines (419 loc) • 17.8 kB
text/typescript
export default TinyDices;
export type PreDiceResult = {
/**
* The sequence of values shown on each face.
*/
sequence: number[];
/**
* Function that re-rolls the dice and returns the new sequence.
*/
reRollDice: () => number[];
/**
* Function that stops the dice rolling.
*/
stop: () => void;
/**
* Reference to the timeout controlling the dice stop, or null if not set.
*/
stopTimeout: NodeJS.Timeout | null;
};
/**
* The final dice result.
*/
export type DiceResult = PreDiceResult & {
result: number;
};
export type DiceElement = {
/**
* - An array of six face elements.
*/
faces: HTMLElement[];
/**
* - The outer wrapper element.
*/
container: HTMLElement | null;
/**
* - The rotating inner cube element.
*/
wrapper: HTMLElement | null;
};
export type CubeResult = {
/**
* - The DOM element representing the cube container.
*/
cube: HTMLDivElement;
/**
* - The final sequence of values shown on each face.
*/
sequence: number[];
/**
* - Function that re-rolls the dice and returns the new sequence.
*/
reRollDice: () => number[];
/**
* - stopTimeout Reference to the timeout controlling the cube stop, or null if not set.
*/
stopTimeout: NodeJS.Timeout | null;
/**
* - Function that stops the cube rolling.
*/
stop: () => void;
};
/**
* @typedef {Object} PreDiceResult
* @property {number[]} sequence The sequence of values shown on each face.
* @property {() => number[]} reRollDice Function that re-rolls the dice and returns the new sequence.
* @property {() => void} stop Function that stops the dice rolling.
* @property {NodeJS.Timeout|null} stopTimeout Reference to the timeout controlling the dice stop, or null if not set.
*/
/**
* The final dice result.
* @typedef {PreDiceResult & { result: number }} DiceResult
*/
/**
* @typedef {Object} DiceElement
* @property {HTMLElement[]} faces - An array of six face elements.
* @property {HTMLElement|null} container - The outer wrapper element.
* @property {HTMLElement|null} wrapper - The rotating inner cube element.
*/
/**
* @typedef {Object} CubeResult
* @property {HTMLDivElement} cube - The DOM element representing the cube container.
* @property {number[]} sequence - The final sequence of values shown on each face.
* @property {() => number[]} reRollDice - Function that re-rolls the dice and returns the new sequence.
* @property {NodeJS.Timeout|null} stopTimeout - stopTimeout Reference to the timeout controlling the cube stop, or null if not set.
* @property {() => void} stop - Function that stops the cube rolling.
*/
/**
* TinyDices - JavaScript class for rendering animated 3D dice with HTML/CSS.
*
* Created by: Yasmin Seidel (JasminDreasond)
* Co-developed with: ChatGPT (OpenAI) as coding assistant
*
* Features:
* - Roll any number of dice
* - Supports custom max values per die
* - Optional spinning animation (infinite or ending)
* - Dynamic cube generation and animation
* - Option to include zero in rolls (canZero)
*
* Usage:
* const container = document.getElementById('myDice');
* const dice = new TinyDices(container);
*
* dice.roll('7,7,7'); // Rolls 3d6
* dice.roll('6,12,20'); // Rolls d6, d12, and d20
* dice.roll([10, 10], false, true); // Rolls 2d10 with infinite spin
* dice.roll([10, 10], true); // Rolls 2d10 starting from 0
* dice.roll([4, 8, 6], true, true); // Rolls d4, d8, and d6 from 0 with infinite spin
*
* Customization:
* dice.setBgSkin('gray'); // Sets background skin to gray
* dice.setTextSkin('red'); // Sets text skin to red
* dice.setBorderSkin('2px solid black'); // Sets border skin to black
*
* dice.getBgSkin(); // Gets current or default background skin
* dice.getTextSkin(); // Gets current or default text skin
* dice.getBorderSkin(); // Gets current or default border skin
*/
declare class TinyDices {
/**
* Creates a new TinyDices instance attached to a specified HTML element.
*
* @param {HTMLElement} diceBase - The HTML container element where the dice will be rendered.
* @param {(result: number, max: number, canZero?: boolean, rollInfinity?: boolean) => CubeResult} [createCubeScript=null]
* - Optional function to override the internal cube creation logic.
* If provided, it will be used instead of the built-in method.
*
* The function should accept the following parameters:
* - result {number} - The main value to appear on the front face of the die.
* - max {number} - The maximum value allowed for a face of the die.
* - canZero {boolean} [optional] - If true, faces can include the number 0.
* - rollInfinity {boolean} [optional] - If true, the die spins infinitely.
*
* And return:
* - {HTMLElement} cube - The DOM element representing the dice cube.
* - {number[]} sequence - An array containing all the face values of the die.
*
*
* When implementing a custom dice creation logic, you can use the following internal methods:
*
* @function tinyDice.addElement
* Adds a structured dice object to the internal list for tracking and future cleanup.
* This method expects an object with `faces`, `container`, and `wrapper` properties.
*
* @function tinyDice.rollNumber(max: number, canZero: boolean): number
* Generates a random number based on the maximum value and zero allowance.
* Useful when assigning values to non-front faces of the die.
*
* @function tinyDice.updateDiceFaceSkin(face: HTMLElement): void
* Applies the dice face style or skin to a given face element.
* This is usually a visual effect or texture that the user can define.
*
* @function tinyDice.addCubeId(): number
* Returns a unique identifier for each die. This value is typically used to set the `z-index`
* of the container, so that new dice appear above older ones.
*
*
*/
constructor(diceBase: HTMLElement, createCubeScript?: (result: number, max: number, canZero?: boolean, rollInfinity?: boolean) => CubeResult);
/** @type {HTMLElement|null} */ diceArea: HTMLElement | null;
/** @type {HTMLElement|null} */ container: HTMLElement | null;
/**
* Checks if the internal HTML structure (dice base container) still exists in the DOM.
*
* Useful to verify if the TinyDices component is still rendered and operational.
*
* @returns {boolean} - Returns `true` if the HTML elements exist, otherwise `false`.
*/
existsHtml(): boolean;
/**
* Increments and returns the current cube ID.
*
* This ID is used to set a unique z-index for each die,
* ensuring that newer dice appear above older ones in the stack.
*
* @returns {number} The current cube ID before incrementing.
*/
addCubeId(): number;
/**
* Adds a new dice element to the internal storage.
*
* This is the public wrapper for the internal method `#addElement`.
* It validates the structure of the dice element before adding.
*
* @param {DiceElement} item
* - The dice element object to add. It must contain:
* - `faces`: an array of six face elements,
* - `container`: the outer wrapper element,
* - `wrapper`: the rotating inner cube element.
*
* @returns {boolean} `true` if the element was valid and added, otherwise `false`.
*/
addElement(item: DiceElement): boolean;
/**
* Sets the random changer amount.
* @param {number} value Stop time value.
* @returns {void}
*/
set rdChangerAmount(value: number);
/**
* Gets the current random changer amount.
* @returns {number} Random changer amountvalue.
*/
get rdChangerAmount(): number;
/**
* Sets the stop time.
* @param {number} value Stop time value.
* @returns {void}
*/
set stopTime(value: number);
/**
* Gets the current stop time.
* @returns {number} Stop time value.
*/
get stopTime(): number;
/**
* Sets the background image using a `data:` URL.
*
* For security reasons, only `data:` URLs are accepted by default to avoid external resource injection.
*
* @param {string|null} value - The background-image URL (must be a `data:` image by default).
*/
set bgImg(value: string | null);
/**
* Returns the currently set background image if valid, or null.
*
* @returns {string|null} - The current background-image value (data:image URL) or null if none is set.
*/
get bgImg(): string | null;
/**
* Sets the background image using a `data:` URL or, optionally, a standard image URL if forced.
*
* For security reasons, only `data:` URLs are accepted by default to avoid external resource injection.
* You can override this restriction using the `forceUnsafe` flag, but this is discouraged unless trusted.
*
* @param {string|null} value - The background-image URL (must be a `data:` image by default).
* @param {boolean} [forceUnsafe=false] - Allows setting non-data URLs if true (use with caution).
*/
setBgImg(value: string | null, forceUnsafe?: boolean): void;
/**
* Sets the background skin style if it's a valid CSS color or linear-gradient.
* Prevents injection of unsafe or malformed styles.
*
* @param {string} skin - A valid CSS color string or gradient.
*/
set bgSkin(skin: string);
/**
* Gets the currently applied background skin.
* @returns {string|null} The current background skin, or the default if not set.
*/
get bgSkin(): string | null;
/**
* Sets the text skin (style) of the dice numbers.
* @param {string|null} skin - The skin name to apply to the text. Pass null or non-string to reset to default.
*/
set textSkin(skin: string | null);
/**
* Gets the currently applied text skin.
* @returns {string|null} The current text skin, or the default if not set.
*/
get textSkin(): string | null;
/**
* Sets the border skin (style) of the dice edges.
* @param {string|null} skin - The skin name to apply to the border. Pass null or non-string to reset to default.
*/
set borderSkin(skin: string | null);
/**
* Gets the currently applied border skin.
* @returns {string|null} The current border skin, or the default if not set.
*/
get borderSkin(): string | null;
/**
* Sets the background skin for selected dice.
* Accepts valid CSS color strings or `linear-gradient(...)`.
* Invalid values reset the skin to `null`.
*
* @param {string} skin - The CSS background to apply when a die is selected.
*/
set selectionBgSkin(skin: string);
/**
* Gets the background skin used for selected dice.
* Returns the custom value if set; otherwise, returns the default.
*
* @returns {string|null} The current background skin for selected dice.
*/
get selectionBgSkin(): string | null;
/**
* Sets the text color for selected dice.
* Only valid CSS color values are accepted.
* Invalid inputs will reset the color to `null`.
*
* @param {string} skin - The text color for selected dice.
*/
set selectionTextSkin(skin: string);
/**
* Gets the text color used for selected dice.
* Returns the custom value if set; otherwise, returns the default.
*
* @returns {string|null} The current text color for selected dice.
*/
get selectionTextSkin(): string | null;
/**
* Updates the visual skin or style of a single dice face element.
*
* This is a public wrapper around the internal method `#updateDiceFaceSkin`,
* allowing external calls to apply the dice face style dynamically.
*
* @param {HTMLElement} face - The DOM element representing a single face of the die.
* @returns {void}
*/
updateDiceFaceSkin(face: HTMLElement): void;
/**
* Updates the visual skin of all dice face elements currently rendered.
* Iterates through each dice in `this.#elements` and applies the active
* background, text color, border, and background image styles using `#updateDiceFaceSkin`.
*
*/
updateDicesSkin(): void;
/**
* Updates the visual skin of a specific die by index.
* Applies current background color, text color, border style, and background image
* to all face elements of the selected die using `#updateDiceFaceSkin`.
*
* @param {number|string} index - The index of the die to update.
* @throws {Error} If the index is not a valid number or string convertible to number.
*
* @returns {boolean} Returns `true` if the die was found and updated; otherwise `false`.
*/
updateDiceSkin(index: number | string): boolean;
/**
* Generates a random integer between a lower bound and a maximum value.
*
* This is a public wrapper for the internal method `#rollNumber`, which handles
* dice-style number generation, optionally allowing zero as a result.
*
* @param {number} [max=0] - The maximum value (inclusive upper bound if `canZero` is true).
* @param {boolean} [canZero=false] - If true, the roll can return 0 (or a range starting from 0).
* @returns {number} A pseudo-random integer within the expected range.
*
* - If `canZero` is false: returns a number from 1 to `max`.
* - If `canZero` is true: returns a number from 0 to `max`.
* - If `max <= 0`: always returns 0.
*/
rollNumber(max?: number, canZero?: boolean): number;
/**
* Parses input parameters to determine the dice configuration.
*
* @param {string|Array<number>} perDieValues - Optional: a comma-separated string or array of individual max values.
* @returns {number[]} - Parsed dice configuration.
*/
parseRollConfig(perDieValues?: string | Array<number>): number[];
/**
* Inserts a single 3D die into the DOM with animation.
*
* @param {number} result - The value displayed on the front face of the die.
* @param {number} max - The maximum value for the die (used to generate other random faces).
* @param {boolean} [canZero=false] - Whether 0 is a valid face value.
* @param {boolean} [rollInfinity=false] - Whether the die should spin indefinitely.
*
* @throws {Error} If `this.diceArea` is not a valid HTMLElement.
* @throws {Error} If `this.#createCube` is not a function.
* @throws {Error} If cube creation fails or returns an invalid sequence.
* @returns {PreDiceResult} - An object with the array representing the values on all six faces of the cube.
*/
insertDiceElement(result: number, max: number, canZero?: boolean, rollInfinity?: boolean): PreDiceResult;
/**
* Clears all dice cubes from the display area.
* Resets internal cube counter to avoid z-index conflicts.
*/
clearDiceArea(): void;
/**
* Inserts a single die cube into the DOM using the specified configuration.
*
* @param {number} max - Default maximum value for dice (if no individual values are given).
* @param {boolean} [canZero=false] - Whether 0 is a valid result.
* @param {boolean} [rollInfinity=false] - Whether all dice should spin infinitely.
* @returns {DiceResult} - Array with results and face sequences for each die.
*/
rollDice(max: number, canZero?: boolean, rollInfinity?: boolean): DiceResult;
/**
* Inserts multiple dice cubes into the DOM using the specified configuration.
*
* @param {number[]} perDieData - Array of individual max values per die.
* @param {boolean} [canZero=false] - Whether 0 is a valid result on any die.
* @param {boolean} [rollInfinity=false] - Whether all dice should spin infinitely.
* @returns {Array<DiceResult>} - Array with results and face sequences for each die.
*/
rollDices(perDieData: number[], canZero?: boolean, rollInfinity?: boolean): Array<DiceResult>;
/**
* Rolls the dice by clearing existing cubes and inserting new ones.
*
* @param {string|Array<number>} perDieInput - Either a comma-separated string or array of max values per die.
* @param {boolean} [canZero=false] - Whether 0 is a valid result.
* @param {boolean} [rollInfinity=false] - Whether dice spin infinitely.
* @returns {Array<DiceResult>} - Array with results and face sequences for each die.
*/
roll(perDieInput: string | Array<number>, canZero?: boolean, rollInfinity?: boolean): Array<DiceResult>;
/**
* Checks whether the TinyDices instance has been destroyed.
*
* @returns {boolean} - Returns `true` if the instance was destroyed, otherwise `false`.
*/
get destroyed(): boolean;
/**
* Completely destroys the TinyDices instance by removing DOM elements and resetting internal state.
*
* This method:
* - Clears all rendered dice.
* - Empties the base DOM elements (container, diceBase, diceArea).
* - Resets all visual skin configurations.
* - Nullifies DOM references.
* - Sets an internal flag to block further usage of the instance.
*
* @example
* dice.destroy(); // 💣 Cleans up everything and makes the instance unusable
*/
destroy(): void;
#private;
}