All files / composables useGeneratedId.ts

100% Statements 11/11
100% Branches 16/16
100% Functions 1/1
100% Lines 11/11

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 2913x 13x 13x                             13x 1140x 1140x 1140x 1128x 12x 6x   6x      
import { getCurrentInstance } from 'vue';
import { LibraryPrefix } from '../constants';
let counter = 0;
 
/**
 * Get a unique ID suitable for use in HTML templates.
 *
 * All strings begin with the library prefix "cdx-". If an optional identifier
 * string is provided, that is included as well. Alternatively, if an "id"
 * element is present on the calling component as either a prop or attribute,
 * that will be used if no identifier argument is provided. All strings include
 * a numerical suffix based on an auto-incrementing counter to ensure
 * uniqueness.
 *
 * @param identifier
 * @return generatedId
 */
export default function useGeneratedId( identifier? : string ) : string {
	const vm = getCurrentInstance();
	const externalId = vm?.props.id as string|undefined ?? vm?.attrs.id as string|undefined;
	if ( identifier ) {
		return `${ LibraryPrefix }-${ identifier }-${ counter++ }`;
	} else if ( externalId ) {
		return `${ LibraryPrefix }-${ externalId }-${ counter++ }`;
	} else {
		return `${ LibraryPrefix }-${ counter++ }`;
	}
}