import { Comment, Fragment, Text, cloneVNode, computed, inject, isVNode, provide, ref, toValue, useId, type ComputedRef, type InjectionKey, type MaybeRefOrGetter, type Ref, type VNode, type VNodeChild, } from "vue"; import { fieldContextKey, type FieldContext } from "../field/context"; export type IndicatorFormatOptions = Intl.NumberFormatOptions; export interface IndicatorValueProps { value?: number; minValue?: number; maxValue?: number; isIndeterminate?: boolean; valueLabel?: string | number; formatOptions?: IndicatorFormatOptions; } export interface IndicatorValue { clampedValue: ComputedRef; /** 0–100, or undefined when indeterminate. */ percentage: ComputedRef; /** Formatted display text, or undefined when indeterminate without valueLabel. */ valueText: ComputedRef; } export interface IndicatorSlotState { percentage: number | undefined; valueText: string | undefined; isIndeterminate: boolean; } const DEFAULT_FORMAT: IndicatorFormatOptions = { style: "percent" }; function clamp(value: number, min: number, max: number): number { return Math.min(Math.max(value, min), max); } /** * Mirrors React Aria useProgressBar / useMeter value semantics: * clamp to [minValue, maxValue]; percent format uses the 0–1 ratio; * other styles format the raw clamped value. */ export function useIndicatorValue( getProps: MaybeRefOrGetter, ): IndicatorValue { const read = (): IndicatorValueProps => toValue(getProps); const clampedValue = computed(() => { const p = read(); const min = p.minValue ?? 0; const max = p.maxValue ?? 100; return clamp(p.value ?? 0, min, max); }); const percentage = computed(() => { const p = read(); if (p.isIndeterminate) return undefined; const min = p.minValue ?? 0; const max = p.maxValue ?? 100; if (max === min) return 0; return ((clampedValue.value - min) / (max - min)) * 100; }); const valueText = computed(() => { const p = read(); if (p.isIndeterminate) return undefined; if (p.valueLabel != null && p.valueLabel !== "") return String(p.valueLabel); const min = p.minValue ?? 0; const max = p.maxValue ?? 100; const ratio = max === min ? 0 : (clampedValue.value - min) / (max - min); const formatOptions = p.formatOptions ?? DEFAULT_FORMAT; try { const formatter = new Intl.NumberFormat(undefined, formatOptions); return formatter.format( formatOptions.style === "percent" ? ratio : clampedValue.value, ); } catch { return String(clampedValue.value); } }); return { clampedValue, percentage, valueText }; } export interface IndicatorSlotClasses { [key: string]: string; } export interface IndicatorContextValue { slots: ComputedRef; state: ComputedRef; } export const indicatorContextKey: InjectionKey = Symbol("hv-indicator"); export interface IndicatorLabelRegistry { /** Field scope surrounding the indicator; a nested field owns its own labels. */ fieldScope: FieldContext | undefined; /** Register a label id present under the indicator root; returns unregister. */ registerLabel: (id: string) => () => void; } export const indicatorLabelContextKey: InjectionKey = Symbol("hv-indicator-label"); function isLabelVNode(node: VNode): boolean { const type = node.type as { __name?: string; name?: string } | string; if (typeof type === "string") return false; return type?.__name === "Label" || type?.name === "Label"; } function isExplicitId(value: unknown): value is string { return typeof value === "string" && value.length > 0; } export interface AssignedLabelIds { nodes: VNodeChild[]; ids: string[]; } /** * Walk default-slot children, give each Label a stable unique id * (explicit id wins), and return those ids for aria-labelledby. * Runs inside the root render so SSR first paint already has matching ids. */ export function assignIndicatorLabelIds( children: VNodeChild[], baseId: string, ): AssignedLabelIds { const ids: string[] = []; let autoIndex = 0; function mapNodes(nodes: VNodeChild[]): VNodeChild[] { return nodes.map((node) => { if (Array.isArray(node)) return mapNodes(node); if (!isVNode(node)) return node; if (node.type === Comment || node.type === Text) return node; if (node.type === Fragment) { const cloned = cloneVNode(node); cloned.children = mapNodes((node.children ?? []) as VNodeChild[]); return cloned; } if (isLabelVNode(node)) { const explicit = node.props?.id; if (isExplicitId(explicit)) { if (!ids.includes(explicit)) ids.push(explicit); return node; } const autoId = autoIndex === 0 ? baseId : `${baseId}-${autoIndex}`; autoIndex += 1; if (!ids.includes(autoId)) ids.push(autoId); return cloneVNode(node, { id: autoId }); } if (typeof node.type === "string" && Array.isArray(node.children)) { const cloned = cloneVNode(node); cloned.children = mapNodes(node.children as VNodeChild[]); return cloned; } return node; }); } return { nodes: mapNodes(children), ids }; } export interface IndicatorLabelAssociation { baseId: string; registerLabel: (id: string) => () => void; /** Resolve aria-labelledby: explicit wins, then aria-label disables, else real label ids. */ resolveAriaLabelledby: ( attrs: Record, slotIds: string[], ) => string | undefined; } export function useIndicatorLabelAssociation(): IndicatorLabelAssociation { const baseId = useId(); const nestedLabelIds = ref([]); function registerLabel(id: string): () => void { if (!nestedLabelIds.value.includes(id)) { nestedLabelIds.value = [...nestedLabelIds.value, id]; } return () => { nestedLabelIds.value = nestedLabelIds.value.filter((x) => x !== id); }; } provide(indicatorLabelContextKey, { fieldScope: inject(fieldContextKey, undefined), registerLabel, }); function resolveAriaLabelledby( attrs: Record, slotIds: string[], ): string | undefined { // Never drop a caller-supplied reference — return it so callers re-apply it. const explicit = attrs["aria-labelledby"]; if (typeof explicit === "string" && explicit) return explicit; if (typeof attrs["aria-label"] === "string" && attrs["aria-label"]) { return undefined; } const all = [...new Set([...slotIds, ...nestedLabelIds.value])]; return all.length > 0 ? all.join(" ") : undefined; } return { baseId, registerLabel, resolveAriaLabelledby }; } export function injectIndicatorLabel(): IndicatorLabelRegistry | undefined { return inject(indicatorLabelContextKey, undefined); }