| 1 |
import { useSSRSafeId } from '../useSSRSafeId'; |
| 2 |
|
| 3 |
type OuiaId = number | string; |
| 4 |
|
| 5 |
// https://ouia.readthedocs.io/en/latest/README.html#ouia-component |
| 6 |
export interface OUIAProps { |
| 7 |
// If there is only one instance of the component on the page at once, it is OPTIONAL |
| 8 |
ouiaId?: OuiaId; |
| 9 |
// False if in animation |
| 10 |
ouiaSafe?: boolean; |
| 11 |
} |
| 12 |
|
| 13 |
const ouiaPrefix = 'OUIA-Generated-'; |
| 14 |
|
| 15 |
/** |
| 16 |
* Get props to conform to OUIA spec. |
| 17 |
* For functional components, use the useOUIAProps hook instead. |
| 18 |
* |
| 19 |
* @param {string} componentType OUIA component type |
| 20 |
* @param {number|string} id OUIA component id |
| 21 |
* @param {boolean} ouiaSafe false if in animation |
| 22 |
*/ |
| 23 |
export function getOUIAProps(componentType: string, id: OuiaId, ouiaSafe: boolean = true) { |
| 24 |
return { |
| 25 |
'data-ouia-component-type': `PF6/${componentType}`, |
| 26 |
'data-ouia-safe': ouiaSafe, |
| 27 |
'data-ouia-component-id': id |
| 28 |
}; |
| 29 |
} |
| 30 |
|
| 31 |
/** |
| 32 |
* Hooks version of the getOUIAProps function with SSR-safe ID generation. |
| 33 |
* Can only be used in functional components. |
| 34 |
* |
| 35 |
* @param {string} componentType OUIA component type |
| 36 |
* @param {number|string} id OUIA component id |
| 37 |
* @param {boolean} ouiaSafe false if in animation |
| 38 |
* @param {string} variant Optional variant to add to the generated ID |
| 39 |
*/ |
| 40 |
export const useOUIAProps = (componentType: string, id?: OuiaId, ouiaSafe: boolean = true, variant?: string) => ({ |
| 41 |
'data-ouia-component-type': `PF6/${componentType}`, |
| 42 |
'data-ouia-safe': ouiaSafe, |
| 43 |
'data-ouia-component-id': useOUIAId(componentType, id, variant) |
| 44 |
}); |
| 45 |
|
| 46 |
/** |
| 47 |
* Returns the provided ID or a deterministic SSR-safe generated OUIA ID. |
| 48 |
* Uses React.useId() under the hood for consistent server/client rendering. |
| 49 |
* |
| 50 |
* @param {string} componentType OUIA component type |
| 51 |
* @param {number|string} id OUIA component id |
| 52 |
* @param {string} variant Optional variant to add to the generated ID |
| 53 |
*/ |
| 54 |
export const useOUIAId = (componentType: string, id?: OuiaId, variant?: string) => { |
| 55 |
const generatedId = useSSRSafeId(`${ouiaPrefix}${componentType}-${variant ? `${variant}-` : ''}`); |
| 56 |
return id ?? generatedId; |
| 57 |
}; |
| 58 |
|
| 59 |
let uid = 0; |
| 60 |
|
| 61 |
/** |
| 62 |
* Legacy counter-based OUIA ID generator for class components that cannot use hooks. |
| 63 |
* Prefer useOUIAId or useOUIAProps for functional components. |
| 64 |
* |
| 65 |
* @deprecated Use useOUIAId in functional components instead. |
| 66 |
*/ |
| 67 |
export function getDefaultOUIAId(componentType: string, variant?: string) { |
| 68 |
return `${ouiaPrefix}${componentType}-${variant ? `${variant}-` : ''}${++uid}`; |
| 69 |
} |