feat: add ProgressBar ProgressCircle and Meter

This commit is contained in:
maoyingjie
2026-10-22 14:33:15 +08:00
parent e4d817ce55
commit 73bd7da5fa
66 changed files with 4143 additions and 10 deletions
+115
View File
@@ -0,0 +1,115 @@
/* Adapted from HeroUI v3, ce90ea3. Copyright 2025 NextUI Inc.
* See third-party/HEROUI-LICENSE. Modified: hv- class prefix; Vue state adapters. */
/* ==========================================================================
Meter - A quantity indicator within a known range
========================================================================== */
/* Base styles */
.hv-meter {
@apply grid w-full gap-1;
grid-template-areas:
"label output"
"track track";
grid-template-columns: 1fr auto;
/* Default color tokens (accent) */
--meter-fill: var(--accent);
[data-slot="label"] {
@apply w-fit text-sm font-medium;
grid-area: label;
}
.hv-meter__output {
@apply text-sm font-medium tabular-nums;
grid-area: output;
}
.hv-meter__track {
@apply relative overflow-hidden rounded-sm bg-default;
grid-area: track;
/* Default height (matches --md) */
@apply h-2;
}
.hv-meter__fill {
@apply absolute start-0 top-0 h-full rounded-sm;
background-color: var(--meter-fill);
/**
* Transitions
* CRITICAL: motion-reduce must be AFTER transition for correct override specificity
*/
transition: width 300ms var(--ease-out);
@apply motion-reduce:transition-none;
}
/* Disabled state */
&:disabled,
&[data-disabled="true"],
&[aria-disabled="true"] {
@apply status-disabled;
[data-slot="label"] {
@apply opacity-100;
}
}
}
/* ==========================================================================
Size variants
========================================================================== */
.hv-meter--sm {
.hv-meter__track {
@apply h-1 rounded-xs;
}
.hv-meter__fill {
@apply rounded-xs;
}
}
.hv-meter--md {
/* No styles as this is the default size */
}
.hv-meter--lg {
.hv-meter__track {
@apply h-3 rounded-md;
}
.hv-meter__fill {
@apply rounded-md;
}
}
/* ==========================================================================
Color variants
========================================================================== */
.hv-meter--default {
--meter-fill: var(--default-foreground);
}
.hv-meter--accent {
--meter-fill: var(--accent);
}
.hv-meter--success {
--meter-fill: var(--success);
}
.hv-meter--warning {
--meter-fill: var(--warning);
}
.hv-meter--danger {
--meter-fill: var(--danger);
}
+140
View File
@@ -0,0 +1,140 @@
/* Adapted from HeroUI v3, ce90ea3. Copyright 2025 NextUI Inc.
* See third-party/HEROUI-LICENSE. Modified: hv- class prefix; Vue state adapters. */
/* ==========================================================================
ProgressBar - Shows determinate or indeterminate progress
========================================================================== */
/* Base styles */
.hv-progress-bar {
@apply grid w-full gap-1;
grid-template-areas:
"label output"
"track track";
grid-template-columns: 1fr auto;
/* Default color token (accent) */
--progress-bar-fill: var(--accent);
[data-slot="label"] {
@apply w-fit text-sm font-medium;
grid-area: label;
}
.hv-progress-bar__output {
@apply text-sm font-medium tabular-nums;
grid-area: output;
}
.hv-progress-bar__track {
@apply relative overflow-hidden rounded-sm bg-default;
grid-area: track;
/* Default height (matches --md) */
@apply h-2;
}
.hv-progress-bar__fill {
@apply absolute start-0 top-0 h-full rounded-sm;
background-color: var(--progress-bar-fill);
/**
* Transitions
* CRITICAL: motion-reduce must be AFTER transition for correct override specificity
*/
transition: width 300ms var(--ease-out);
@apply motion-reduce:transition-none;
}
/* Indeterminate state - when no aria-valuenow is set */
&:not([aria-valuenow]) {
.hv-progress-bar__fill {
@apply w-2/5;
animation: hv-progress-bar-indeterminate 1.5s
cubic-bezier(0.65, 0, 0.35, 1) infinite;
@apply motion-reduce:animate-none;
}
}
/* Disabled state */
&:disabled,
&[data-disabled="true"],
&[aria-disabled="true"] {
@apply status-disabled;
[data-slot="label"] {
@apply opacity-100;
}
}
}
/* ==========================================================================
Indeterminate animation
========================================================================== */
@keyframes hv-progress-bar-indeterminate {
0% {
transform: translateX(-100%);
}
100% {
transform: translateX(350%);
}
}
/* ==========================================================================
Size variants
========================================================================== */
.hv-progress-bar--sm {
.hv-progress-bar__track {
@apply h-1 rounded-xs;
}
.hv-progress-bar__fill {
@apply rounded-xs;
}
}
.hv-progress-bar--md {
/* No styles as this is the default size */
}
.hv-progress-bar--lg {
.hv-progress-bar__track {
@apply h-3 rounded-md;
}
.hv-progress-bar__fill {
@apply rounded-md;
}
}
/* ==========================================================================
Color variants
========================================================================== */
.hv-progress-bar--default {
--progress-bar-fill: var(--default-foreground);
}
.hv-progress-bar--accent {
--progress-bar-fill: var(--accent);
}
.hv-progress-bar--success {
--progress-bar-fill: var(--success);
}
.hv-progress-bar--warning {
--progress-bar-fill: var(--warning);
}
.hv-progress-bar--danger {
--progress-bar-fill: var(--danger);
}
@@ -0,0 +1,108 @@
/* Adapted from HeroUI v3, ce90ea3. Copyright 2025 NextUI Inc.
* See third-party/HEROUI-LICENSE. Modified: hv- class prefix; Vue state adapters. */
/* ==========================================================================
ProgressCircle - Circular progress indicator
========================================================================== */
/* Base styles */
.hv-progress-circle {
@apply inline-flex items-center justify-center;
/* Default color token (accent) */
--progress-circle-stroke: var(--accent);
--progress-circle-track-stroke: var(--default);
.hv-progress-circle__track {
/* Default size (matches --md) */
@apply size-7;
}
.hv-progress-circle__track-circle {
stroke: var(--progress-circle-track-stroke);
}
.hv-progress-circle__fill-circle {
stroke: var(--progress-circle-stroke);
/**
* Transitions
* CRITICAL: motion-reduce must be AFTER transition for correct override specificity
*/
transition: stroke-dashoffset 300ms var(--ease-out);
@apply motion-reduce:transition-none;
}
/* Indeterminate state - when no aria-valuenow is set */
&:not([aria-valuenow]) {
.hv-progress-circle__track {
animation: hv-progress-circle-spin 1s linear infinite;
@apply motion-reduce:animate-none;
}
}
/* Disabled state */
&:disabled,
&[data-disabled="true"],
&[aria-disabled="true"] {
@apply status-disabled;
}
}
/* ==========================================================================
Indeterminate animation
========================================================================== */
@keyframes hv-progress-circle-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
/* ==========================================================================
Size variants
========================================================================== */
.hv-progress-circle--sm {
.hv-progress-circle__track {
@apply size-5;
}
}
.hv-progress-circle--md {
/* No styles as this is the default size */
}
.hv-progress-circle--lg {
.hv-progress-circle__track {
@apply size-9;
}
}
/* ==========================================================================
Color variants
========================================================================== */
.hv-progress-circle--default {
--progress-circle-stroke: var(--default-foreground);
}
.hv-progress-circle--accent {
--progress-circle-stroke: var(--accent);
}
.hv-progress-circle--success {
--progress-circle-stroke: var(--success);
}
.hv-progress-circle--warning {
--progress-circle-stroke: var(--warning);
}
.hv-progress-circle--danger {
--progress-circle-stroke: var(--danger);
}
+6
View File
@@ -108,3 +108,9 @@
border: 0;
}
}
@import "./components/progress-bar.css" layer(components);
@import "./components/progress-circle.css" layer(components);
@import "./components/meter.css" layer(components);
+137
View File
@@ -703,3 +703,140 @@ export const emptyStateVariants = tv({
});
export type EmptyStateVariants = VariantProps<typeof emptyStateVariants>;
export const progressBarVariants = tv({
defaultVariants: {
color: "accent",
size: "md",
},
slots: {
base: "hv-progress-bar",
fill: "hv-progress-bar__fill",
output: "hv-progress-bar__output",
track: "hv-progress-bar__track",
},
variants: {
color: {
accent: {
base: "hv-progress-bar--accent",
},
danger: {
base: "hv-progress-bar--danger",
},
default: {
base: "hv-progress-bar--default",
},
success: {
base: "hv-progress-bar--success",
},
warning: {
base: "hv-progress-bar--warning",
},
},
size: {
lg: {
base: "hv-progress-bar--lg",
},
md: {
base: "hv-progress-bar--md",
},
sm: {
base: "hv-progress-bar--sm",
},
},
},
});
export type ProgressBarVariants = VariantProps<typeof progressBarVariants>;
export const progressCircleVariants = tv({
defaultVariants: {
color: "accent",
size: "md",
},
slots: {
base: "hv-progress-circle",
fillCircle: "hv-progress-circle__fill-circle",
track: "hv-progress-circle__track",
trackCircle: "hv-progress-circle__track-circle",
},
variants: {
color: {
accent: {
base: "hv-progress-circle--accent",
},
danger: {
base: "hv-progress-circle--danger",
},
default: {
base: "hv-progress-circle--default",
},
success: {
base: "hv-progress-circle--success",
},
warning: {
base: "hv-progress-circle--warning",
},
},
size: {
lg: {
base: "hv-progress-circle--lg",
},
md: {
base: "hv-progress-circle--md",
},
sm: {
base: "hv-progress-circle--sm",
},
},
},
});
export type ProgressCircleVariants = VariantProps<
typeof progressCircleVariants
>;
export const meterVariants = tv({
defaultVariants: {
color: "accent",
size: "md",
},
slots: {
base: "hv-meter",
fill: "hv-meter__fill",
output: "hv-meter__output",
track: "hv-meter__track",
},
variants: {
color: {
accent: {
base: "hv-meter--accent",
},
danger: {
base: "hv-meter--danger",
},
default: {
base: "hv-meter--default",
},
success: {
base: "hv-meter--success",
},
warning: {
base: "hv-meter--warning",
},
},
size: {
lg: {
base: "hv-meter--lg",
},
md: {
base: "hv-meter--md",
},
sm: {
base: "hv-meter--sm",
},
},
},
});
export type MeterVariants = VariantProps<typeof meterVariants>;
+45 -6
View File
@@ -1,10 +1,20 @@
<script setup lang="ts">
import { inject, useAttrs } from "vue";
import { inject, onUnmounted, useAttrs, useId, watch } from "vue";
import { useFieldPart } from "../field/useFieldPart";
import { useInheritedDisabled } from "../field/disabled";
import { fieldContextKey } from "../field/context";
import { injectIndicatorLabel } from "../progress/value";
defineOptions({ inheritAttrs: false });
const field = inject(fieldContextKey, undefined);
const inheritedField = inject(fieldContextKey, undefined);
const indicatorCandidate = injectIndicatorLabel();
// The nearest owner wins: an indicator overrides its surrounding field,
// while a field nested inside that indicator keeps its own labels.
const indicatorLabel =
indicatorCandidate?.fieldScope === inheritedField
? indicatorCandidate
: undefined;
const field = indicatorLabel ? undefined : inheritedField;
const attrs = useAttrs();
const props = defineProps<{
isRequired?: boolean;
@@ -16,16 +26,45 @@ const labelPart =
const disabled = useInheritedDisabled(
() => props.isDisabled || field?.disabled.value,
);
/** Unique fallback so multiple labels under one indicator never share an id. */
const autoId = useId();
function resolveId(): string {
const explicit = attrs.id;
if (typeof explicit === "string" && explicit) return explicit;
return labelPart?.id.value ?? autoId;
}
let unregister: (() => void) | undefined;
watch(
resolveId,
(id, prevId) => {
if (!indicatorLabel || id === prevId) return;
unregister?.();
unregister = indicatorLabel.registerLabel(id);
},
{ immediate: true },
);
onUnmounted(() => {
unregister?.();
unregister = undefined;
});
</script>
<template>
<component
:is="
(field?.kind === 'toggle' || field?.kind === 'group') && !attrs.for
? 'span'
: 'label'
attrs.for
? 'label'
: field?.kind === 'toggle' || field?.kind === 'group'
? 'span'
: indicatorLabel && !field
? 'span'
: 'label'
"
v-bind="attrs"
:id="labelPart?.id.value ?? attrs.id"
:id="resolveId()"
:for="
attrs.for ?? (field?.kind === 'text' ? field.controlId.value : undefined)
"
@@ -0,0 +1,96 @@
<script lang="ts">
import {
computed,
defineComponent,
h,
provide,
useAttrs,
type PropType,
} from "vue";
import { meterVariants, type MeterVariants } from "@heroui-vue/styles";
import {
assignIndicatorLabelIds,
indicatorContextKey,
useIndicatorLabelAssociation,
useIndicatorValue,
type IndicatorFormatOptions,
} from "../progress/value";
export default defineComponent({
name: "Meter",
inheritAttrs: false,
props: {
value: { type: Number, default: 0 },
minValue: { type: Number, default: 0 },
maxValue: { type: Number, default: 100 },
valueLabel: {
type: [String, Number] as PropType<string | number>,
default: undefined,
},
formatOptions: {
type: Object as PropType<IndicatorFormatOptions>,
default: undefined,
},
size: {
type: String as PropType<MeterVariants["size"]>,
default: "md",
},
color: {
type: String as PropType<MeterVariants["color"]>,
default: "accent",
},
},
setup(props, { slots }) {
const attrs = useAttrs();
const { clampedValue, percentage, valueText } = useIndicatorValue(() => ({
...props,
isIndeterminate: false,
}));
const { baseId, resolveAriaLabelledby } = useIndicatorLabelAssociation();
const slotClasses = computed(() => {
const s = meterVariants({ color: props.color, size: props.size });
return {
base: s.base(),
fill: s.fill(),
output: s.output(),
track: s.track(),
};
});
const state = computed(() => ({
percentage: percentage.value,
valueText: valueText.value,
isIndeterminate: false as boolean,
}));
provide(indicatorContextKey, { slots: slotClasses, state });
return () => {
const rawChildren = slots.default?.(state.value) ?? [];
const { nodes, ids } = assignIndicatorLabelIds(
Array.isArray(rawChildren) ? rawChildren : [rawChildren],
baseId,
);
const role =
typeof attrs.role === "string" && attrs.role
? attrs.role
: "meter progressbar";
const rootProps: Record<string, unknown> = {
...attrs,
class: [slotClasses.value.base, attrs.class],
role,
"aria-valuemin": props.minValue,
"aria-valuemax": props.maxValue,
"aria-valuenow": clampedValue.value,
"aria-valuetext": valueText.value,
"data-slot": "meter",
};
const labelledby = resolveAriaLabelledby(attrs, ids);
if (labelledby !== undefined) rootProps["aria-labelledby"] = labelledby;
return h("div", rootProps, nodes);
};
},
});
</script>
@@ -0,0 +1,30 @@
<script setup lang="ts">
import { computed, inject, useAttrs, type StyleValue } from "vue";
import { indicatorContextKey } from "../progress/value";
defineOptions({ inheritAttrs: false });
const attrs = useAttrs();
const ctx = inject(indicatorContextKey, undefined);
const rootClass = computed(() => ctx?.slots.value.fill);
const rootStyle = computed<StyleValue>(() => {
const width =
ctx?.state.value.percentage == null
? undefined
: `${ctx.state.value.percentage}%`;
return [{ width }, attrs.style];
});
</script>
<template>
<div
v-bind="attrs"
:class="rootClass"
:style="rootStyle"
data-slot="meter-fill"
>
<slot />
</div>
</template>
@@ -0,0 +1,17 @@
<script setup lang="ts">
import { computed, inject, useAttrs } from "vue";
import { indicatorContextKey } from "../progress/value";
defineOptions({ inheritAttrs: false });
const attrs = useAttrs();
const ctx = inject(indicatorContextKey, undefined);
const rootClass = computed(() => ctx?.slots.value.output);
</script>
<template>
<span v-bind="attrs" :class="rootClass" data-slot="meter-output">
<slot>{{ ctx?.state.value.valueText }}</slot>
</span>
</template>
@@ -0,0 +1,17 @@
<script setup lang="ts">
import { computed, inject, useAttrs } from "vue";
import { indicatorContextKey } from "../progress/value";
defineOptions({ inheritAttrs: false });
const attrs = useAttrs();
const ctx = inject(indicatorContextKey, undefined);
const rootClass = computed(() => ctx?.slots.value.track);
</script>
<template>
<div v-bind="attrs" :class="rootClass" data-slot="meter-track">
<slot />
</div>
</template>
@@ -0,0 +1,100 @@
<script lang="ts">
import {
computed,
defineComponent,
h,
provide,
useAttrs,
type PropType,
type StyleValue,
} from "vue";
import {
progressBarVariants,
type ProgressBarVariants,
} from "@heroui-vue/styles";
import {
assignIndicatorLabelIds,
indicatorContextKey,
useIndicatorLabelAssociation,
useIndicatorValue,
type IndicatorFormatOptions,
} from "../progress/value";
export default defineComponent({
name: "ProgressBar",
inheritAttrs: false,
props: {
value: { type: Number, default: 0 },
minValue: { type: Number, default: 0 },
maxValue: { type: Number, default: 100 },
isIndeterminate: { type: Boolean, default: false },
valueLabel: {
type: [String, Number] as PropType<string | number>,
default: undefined,
},
formatOptions: {
type: Object as PropType<IndicatorFormatOptions>,
default: undefined,
},
size: {
type: String as PropType<ProgressBarVariants["size"]>,
default: "md",
},
color: {
type: String as PropType<ProgressBarVariants["color"]>,
default: "accent",
},
},
setup(props, { slots }) {
const attrs = useAttrs();
const { clampedValue, percentage, valueText } = useIndicatorValue(
() => props,
);
const { baseId, resolveAriaLabelledby } = useIndicatorLabelAssociation();
const slotClasses = computed(() => {
const s = progressBarVariants({ color: props.color, size: props.size });
return {
base: s.base(),
fill: s.fill(),
output: s.output(),
track: s.track(),
};
});
const state = computed(() => ({
percentage: percentage.value,
valueText: valueText.value,
isIndeterminate: props.isIndeterminate,
}));
provide(indicatorContextKey, { slots: slotClasses, state });
return () => {
const rawChildren = slots.default?.(state.value) ?? [];
const { nodes, ids } = assignIndicatorLabelIds(
Array.isArray(rawChildren) ? rawChildren : [rawChildren],
baseId,
);
const role =
typeof attrs.role === "string" && attrs.role
? attrs.role
: "progressbar";
const rootProps: Record<string, unknown> = {
...attrs,
class: [slotClasses.value.base, attrs.class],
role,
"aria-valuemin": props.minValue,
"aria-valuemax": props.maxValue,
"aria-valuenow": props.isIndeterminate ? undefined : clampedValue.value,
"aria-valuetext": props.isIndeterminate ? undefined : valueText.value,
"data-slot": "progress-bar",
};
const labelledby = resolveAriaLabelledby(attrs, ids);
if (labelledby !== undefined) rootProps["aria-labelledby"] = labelledby;
return h("div", rootProps, nodes);
};
},
});
</script>
@@ -0,0 +1,30 @@
<script setup lang="ts">
import { computed, inject, useAttrs, type StyleValue } from "vue";
import { indicatorContextKey } from "../progress/value";
defineOptions({ inheritAttrs: false });
const attrs = useAttrs();
const ctx = inject(indicatorContextKey, undefined);
const rootClass = computed(() => ctx?.slots.value.fill);
const rootStyle = computed<StyleValue>(() => {
const width =
ctx?.state.value.isIndeterminate || ctx?.state.value.percentage == null
? undefined
: `${ctx.state.value.percentage}%`;
return [{ width }, attrs.style];
});
</script>
<template>
<div
v-bind="attrs"
:class="rootClass"
:style="rootStyle"
data-slot="progress-bar-fill"
>
<slot />
</div>
</template>
@@ -0,0 +1,17 @@
<script setup lang="ts">
import { computed, inject, useAttrs } from "vue";
import { indicatorContextKey } from "../progress/value";
defineOptions({ inheritAttrs: false });
const attrs = useAttrs();
const ctx = inject(indicatorContextKey, undefined);
const rootClass = computed(() => ctx?.slots.value.output);
</script>
<template>
<span v-bind="attrs" :class="rootClass" data-slot="progress-bar-output">
<slot>{{ ctx?.state.value.valueText }}</slot>
</span>
</template>
@@ -0,0 +1,17 @@
<script setup lang="ts">
import { computed, inject, useAttrs } from "vue";
import { indicatorContextKey } from "../progress/value";
defineOptions({ inheritAttrs: false });
const attrs = useAttrs();
const ctx = inject(indicatorContextKey, undefined);
const rootClass = computed(() => ctx?.slots.value.track);
</script>
<template>
<div v-bind="attrs" :class="rootClass" data-slot="progress-bar-track">
<slot />
</div>
</template>
@@ -0,0 +1,108 @@
<script lang="ts">
import {
computed,
defineComponent,
h,
provide,
useAttrs,
type PropType,
} from "vue";
import {
progressCircleVariants,
type ProgressCircleVariants,
} from "@heroui-vue/styles";
import {
assignIndicatorLabelIds,
indicatorContextKey,
useIndicatorLabelAssociation,
useIndicatorValue,
type IndicatorFormatOptions,
} from "../progress/value";
import {
PROGRESS_CIRCLE_CENTER,
PROGRESS_CIRCLE_CIRCUMFERENCE,
PROGRESS_CIRCLE_RADIUS,
PROGRESS_CIRCLE_STROKE_WIDTH,
} from "./constants";
export default defineComponent({
name: "ProgressCircle",
inheritAttrs: false,
props: {
value: { type: Number, default: 0 },
minValue: { type: Number, default: 0 },
maxValue: { type: Number, default: 100 },
isIndeterminate: { type: Boolean, default: false },
valueLabel: {
type: [String, Number] as PropType<string | number>,
default: undefined,
},
formatOptions: {
type: Object as PropType<IndicatorFormatOptions>,
default: undefined,
},
size: {
type: String as PropType<ProgressCircleVariants["size"]>,
default: "md",
},
color: {
type: String as PropType<ProgressCircleVariants["color"]>,
default: "accent",
},
},
setup(props, { slots }) {
const attrs = useAttrs();
const { clampedValue, percentage, valueText } = useIndicatorValue(
() => props,
);
const { baseId, resolveAriaLabelledby } = useIndicatorLabelAssociation();
const slotClasses = computed(() => {
const s = progressCircleVariants({
color: props.color,
size: props.size,
});
return {
base: s.base(),
fillCircle: s.fillCircle(),
track: s.track(),
trackCircle: s.trackCircle(),
};
});
const state = computed(() => ({
percentage: percentage.value,
valueText: valueText.value,
isIndeterminate: props.isIndeterminate,
}));
provide(indicatorContextKey, { slots: slotClasses, state });
return () => {
const rawChildren = slots.default?.(state.value) ?? [];
const { nodes, ids } = assignIndicatorLabelIds(
Array.isArray(rawChildren) ? rawChildren : [rawChildren],
baseId,
);
const role =
typeof attrs.role === "string" && attrs.role
? attrs.role
: "progressbar";
const rootProps: Record<string, unknown> = {
...attrs,
class: [slotClasses.value.base, attrs.class],
role,
"aria-valuemin": props.minValue,
"aria-valuemax": props.maxValue,
"aria-valuenow": props.isIndeterminate ? undefined : clampedValue.value,
"aria-valuetext": props.isIndeterminate ? undefined : valueText.value,
"data-slot": "progress-circle",
};
const labelledby = resolveAriaLabelledby(attrs, ids);
if (labelledby !== undefined) rootProps["aria-labelledby"] = labelledby;
return h("div", rootProps, nodes);
};
},
});
</script>
@@ -0,0 +1,76 @@
<script setup lang="ts">
import { computed, inject, useAttrs } from "vue";
import { indicatorContextKey } from "../progress/value";
import {
PROGRESS_CIRCLE_CENTER,
PROGRESS_CIRCLE_CIRCUMFERENCE,
PROGRESS_CIRCLE_RADIUS,
PROGRESS_CIRCLE_STROKE_WIDTH,
} from "./constants";
defineOptions({ inheritAttrs: false });
const attrs = useAttrs();
const ctx = inject(indicatorContextKey, undefined);
function pick(
camel: string,
kebab: string,
fallback: string | number,
): string | number {
const value = attrs[camel] ?? attrs[kebab];
return value == null || value === "" ? fallback : (value as string | number);
}
const rootClass = computed(() => ctx?.slots.value.fillCircle);
const cx = computed(() => pick("cx", "cx", PROGRESS_CIRCLE_CENTER));
const cy = computed(() => pick("cy", "cy", PROGRESS_CIRCLE_CENTER));
const r = computed(() => pick("r", "r", PROGRESS_CIRCLE_RADIUS));
const strokeWidth = computed(() =>
pick("strokeWidth", "stroke-width", PROGRESS_CIRCLE_STROKE_WIDTH),
);
const strokeDasharray = computed(() =>
pick("strokeDasharray", "stroke-dasharray", PROGRESS_CIRCLE_CIRCUMFERENCE),
);
const strokeDashoffset = computed(() => {
const explicit = attrs.strokeDashoffset ?? attrs["stroke-dashoffset"];
if (explicit != null && explicit !== "") return explicit as string | number;
const state = ctx?.state.value;
if (!state || state.isIndeterminate || state.percentage == null) {
return PROGRESS_CIRCLE_CIRCUMFERENCE * 0.75;
}
return (
PROGRESS_CIRCLE_CIRCUMFERENCE -
(state.percentage / 100) * PROGRESS_CIRCLE_CIRCUMFERENCE
);
});
const linecap = computed(() => {
const value = attrs.strokeLinecap ?? attrs["stroke-linecap"];
return (value ?? "round") as "butt" | "round" | "square" | "inherit";
});
const transform = computed(() => {
const explicit = attrs.transform;
if (explicit != null && explicit !== "") return explicit as string;
return `rotate(-90 ${PROGRESS_CIRCLE_CENTER} ${PROGRESS_CIRCLE_CENTER})`;
});
</script>
<template>
<circle
v-bind="attrs"
:class="rootClass"
:cx="cx"
:cy="cy"
:r="r"
:stroke-width="strokeWidth"
:stroke-dasharray="strokeDasharray"
:stroke-dashoffset="strokeDashoffset"
:stroke-linecap="linecap"
:transform="transform"
data-slot="progress-circle-fill-circle"
/>
</template>
@@ -0,0 +1,30 @@
<script setup lang="ts">
import { computed, inject, useAttrs } from "vue";
import { indicatorContextKey } from "../progress/value";
import { PROGRESS_CIRCLE_CENTER } from "./constants";
defineOptions({ inheritAttrs: false });
const attrs = useAttrs();
const ctx = inject(indicatorContextKey, undefined);
const rootClass = computed(() => ctx?.slots.value.track);
const viewBox = computed(() => {
const explicit = attrs.viewBox;
if (explicit != null && explicit !== "") return explicit as string;
return `0 0 ${PROGRESS_CIRCLE_CENTER * 2} ${PROGRESS_CIRCLE_CENTER * 2}`;
});
</script>
<template>
<svg
v-bind="attrs"
:class="rootClass"
:viewBox="viewBox"
fill="none"
data-slot="progress-circle-track"
>
<slot />
</svg>
</template>
@@ -0,0 +1,43 @@
<script setup lang="ts">
import { computed, inject, useAttrs } from "vue";
import { indicatorContextKey } from "../progress/value";
import {
PROGRESS_CIRCLE_CENTER,
PROGRESS_CIRCLE_RADIUS,
PROGRESS_CIRCLE_STROKE_WIDTH,
} from "./constants";
defineOptions({ inheritAttrs: false });
const attrs = useAttrs();
const ctx = inject(indicatorContextKey, undefined);
function pick(
camel: string,
kebab: string,
fallback: string | number,
): string | number {
const value = attrs[camel] ?? attrs[kebab];
return value == null || value === "" ? fallback : (value as string | number);
}
const rootClass = computed(() => ctx?.slots.value.trackCircle);
const cx = computed(() => pick("cx", "cx", PROGRESS_CIRCLE_CENTER));
const cy = computed(() => pick("cy", "cy", PROGRESS_CIRCLE_CENTER));
const r = computed(() => pick("r", "r", PROGRESS_CIRCLE_RADIUS));
const strokeWidth = computed(() =>
pick("strokeWidth", "stroke-width", PROGRESS_CIRCLE_STROKE_WIDTH),
);
</script>
<template>
<circle
v-bind="attrs"
:class="rootClass"
:cx="cx"
:cy="cy"
:r="r"
:stroke-width="strokeWidth"
data-slot="progress-circle-track-circle"
/>
</template>
@@ -0,0 +1,7 @@
/** Circle geometry matching the fixed HeroUI baseline (viewBox 0 0 36 36). */
export const PROGRESS_CIRCLE_CENTER = 18;
export const PROGRESS_CIRCLE_STROKE_WIDTH = 4;
export const PROGRESS_CIRCLE_RADIUS =
PROGRESS_CIRCLE_CENTER - PROGRESS_CIRCLE_STROKE_WIDTH / 2;
export const PROGRESS_CIRCLE_CIRCUMFERENCE =
2 * Math.PI * PROGRESS_CIRCLE_RADIUS;
@@ -0,0 +1,231 @@
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<number>;
/** 0–100, or undefined when indeterminate. */
percentage: ComputedRef<number | undefined>;
/** Formatted display text, or undefined when indeterminate without valueLabel. */
valueText: ComputedRef<string | undefined>;
}
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<IndicatorValueProps>,
): 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<IndicatorSlotClasses>;
state: ComputedRef<IndicatorSlotState>;
}
export const indicatorContextKey: InjectionKey<IndicatorContextValue> =
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<IndicatorLabelRegistry> =
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<string, unknown>,
slotIds: string[],
) => string | undefined;
}
export function useIndicatorLabelAssociation(): IndicatorLabelAssociation {
const baseId = useId();
const nestedLabelIds = ref<string[]>([]);
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<string, unknown>,
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);
}
+42
View File
@@ -291,3 +291,45 @@ export {
type BreadcrumbsVariants,
type EmptyStateVariants,
} from "@heroui-vue/styles";
export { default as ProgressBar } from "./components/progress-bar/ProgressBar.vue";
export { default as ProgressBarOutput } from "./components/progress-bar/ProgressBarOutput.vue";
export { default as ProgressBarTrack } from "./components/progress-bar/ProgressBarTrack.vue";
export { default as ProgressBarFill } from "./components/progress-bar/ProgressBarFill.vue";
export type {
ProgressBarProps,
ProgressBarOutputProps,
ProgressBarTrackProps,
ProgressBarFillProps,
} from "./types";
export { default as ProgressCircle } from "./components/progress-circle/ProgressCircle.vue";
export { default as ProgressCircleTrack } from "./components/progress-circle/ProgressCircleTrack.vue";
export { default as ProgressCircleTrackCircle } from "./components/progress-circle/ProgressCircleTrackCircle.vue";
export { default as ProgressCircleFillCircle } from "./components/progress-circle/ProgressCircleFillCircle.vue";
export type {
ProgressCircleProps,
ProgressCircleTrackProps,
ProgressCircleTrackCircleProps,
ProgressCircleFillCircleProps,
} from "./types";
export { default as Meter } from "./components/meter/Meter.vue";
export { default as MeterOutput } from "./components/meter/MeterOutput.vue";
export { default as MeterTrack } from "./components/meter/MeterTrack.vue";
export { default as MeterFill } from "./components/meter/MeterFill.vue";
export type {
MeterProps,
MeterOutputProps,
MeterTrackProps,
MeterFillProps,
} from "./types";
export {
progressBarVariants,
progressCircleVariants,
meterVariants,
type ProgressBarVariants,
type ProgressCircleVariants,
type MeterVariants,
} from "@heroui-vue/styles";
+39
View File
@@ -191,3 +191,42 @@ import type RadioControl from "./components/radio/RadioControl.vue";
export type RadioControlProps = InstanceType<typeof RadioControl>["$props"];
import type RadioIndicator from "./components/radio/RadioIndicator.vue";
export type RadioIndicatorProps = InstanceType<typeof RadioIndicator>["$props"];
import type ProgressBar from "./components/progress-bar/ProgressBar.vue";
import type ProgressBarOutput from "./components/progress-bar/ProgressBarOutput.vue";
import type ProgressBarTrack from "./components/progress-bar/ProgressBarTrack.vue";
import type ProgressBarFill from "./components/progress-bar/ProgressBarFill.vue";
export type ProgressBarProps = InstanceType<typeof ProgressBar>["$props"];
export type ProgressBarOutputProps = InstanceType<
typeof ProgressBarOutput
>["$props"];
export type ProgressBarTrackProps = InstanceType<
typeof ProgressBarTrack
>["$props"];
export type ProgressBarFillProps = InstanceType<
typeof ProgressBarFill
>["$props"];
import type ProgressCircle from "./components/progress-circle/ProgressCircle.vue";
import type ProgressCircleTrack from "./components/progress-circle/ProgressCircleTrack.vue";
import type ProgressCircleTrackCircle from "./components/progress-circle/ProgressCircleTrackCircle.vue";
import type ProgressCircleFillCircle from "./components/progress-circle/ProgressCircleFillCircle.vue";
export type ProgressCircleProps = InstanceType<typeof ProgressCircle>["$props"];
export type ProgressCircleTrackProps = InstanceType<
typeof ProgressCircleTrack
>["$props"];
export type ProgressCircleTrackCircleProps = InstanceType<
typeof ProgressCircleTrackCircle
>["$props"];
export type ProgressCircleFillCircleProps = InstanceType<
typeof ProgressCircleFillCircle
>["$props"];
import type Meter from "./components/meter/Meter.vue";
import type MeterOutput from "./components/meter/MeterOutput.vue";
import type MeterTrack from "./components/meter/MeterTrack.vue";
import type MeterFill from "./components/meter/MeterFill.vue";
export type MeterProps = InstanceType<typeof Meter>["$props"];
export type MeterOutputProps = InstanceType<typeof MeterOutput>["$props"];
export type MeterTrackProps = InstanceType<typeof MeterTrack>["$props"];
export type MeterFillProps = InstanceType<typeof MeterFill>["$props"];