feat(carousel): add reusable horizontal carousel

This commit is contained in:
2026-09-22 15:17:04 -03:00
parent 0e6c949513
commit 0fffdc5c5a
7 changed files with 509 additions and 39 deletions

View File

@@ -0,0 +1,63 @@
<div
class="carousel"
role="group"
[attr.aria-label]="ariaLabel()"
[class.carousel--looping]="looping()"
>
@if (showArrows()) {
<button
type="button"
class="carousel__arrow"
aria-label="Ver elementos anteriores"
[disabled]="!overflowing()"
(click)="move(-1)"
>
<i class="fa-solid fa-chevron-left" aria-hidden="true"></i>
</button>
}
<div #viewport class="carousel__viewport" (scroll)="onScroll()" (scrollend)="normalize()">
<div class="carousel__track">
@for (block of blocks(); track block) {
@if (block === 0) {
<div #canonical class="carousel__set">
@for (item of items(); track item.value) {
<button
type="button"
class="carousel__item"
(click)="itemSelect.emit(item)"
(focus)="reveal($event)"
>
{{ item.label }}
</button>
}
</div>
} @else {
<div class="carousel__set" aria-hidden="true">
@for (item of items(); track item.value) {
<button
type="button"
class="carousel__item"
tabindex="-1"
(mousedown)="$event.preventDefault()"
(click)="selectCopy(item)"
>
{{ item.label }}
</button>
}
</div>
}
}
</div>
</div>
@if (showArrows()) {
<button
type="button"
class="carousel__arrow"
aria-label="Ver más elementos"
[disabled]="!overflowing()"
(click)="move(1)"
>
<i class="fa-solid fa-chevron-right" aria-hidden="true"></i>
</button>
}
</div>

View File

@@ -0,0 +1,71 @@
:host {
display: block;
min-width: 0;
}
.carousel {
display: flex;
align-items: center;
min-width: 0;
}
.carousel__viewport {
container-type: inline-size;
flex: 1;
min-width: 0;
overflow-x: auto;
scrollbar-width: none;
overflow-anchor: none;
scroll-snap-type: var(--horizontal-carousel-snap, none);
}
.carousel__viewport::-webkit-scrollbar {
display: none;
}
.carousel__track {
display: flex;
width: max-content;
min-width: 100%;
justify-content: center;
}
.carousel__set {
position: relative;
display: flex;
flex: none;
align-items: center;
gap: var(--horizontal-carousel-gap, 1.5rem);
}
.carousel--looping .carousel__set {
padding-right: var(--horizontal-carousel-gap, 1.5rem);
}
.carousel__item,
.carousel__arrow {
flex: none;
min-height: 44px;
border: 0;
padding: 0;
background: transparent;
color: inherit;
font: inherit;
cursor: pointer;
}
.carousel__item {
width: var(--horizontal-carousel-item-width, auto);
white-space: var(--horizontal-carousel-white-space, nowrap);
overflow-wrap: anywhere;
scroll-snap-align: start;
text-transform: var(--horizontal-carousel-text-transform, none);
}
.carousel__arrow {
width: 32px;
font-size: 10px;
}
.carousel__arrow:disabled {
opacity: 0.35;
cursor: default;
}
.carousel__item:hover {
text-decoration: underline;
}
.carousel__item:focus-visible,
.carousel__arrow:focus-visible {
outline: 2px solid currentColor;
outline-offset: -2px;
}

View File

@@ -0,0 +1,180 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { HorizontalCarouselComponent } from './horizontal-carousel.component';
describe('HorizontalCarouselComponent', () => {
let fixture: ComponentFixture<HorizontalCarouselComponent>;
let host: HTMLElement;
let available: number;
let resize: () => void;
const disconnect = vi.fn();
const items = Array.from({ length: 5 }, (_, index) => ({ value: index, label: `Item ${index}` }));
const viewport = () => host.querySelector<HTMLElement>('.carousel__viewport')!;
const period = () =>
host.querySelector<HTMLElement>('.carousel__set')!.getBoundingClientRect().width;
beforeEach(async () => {
available = 320;
vi.stubGlobal(
'ResizeObserver',
class {
constructor(callback: () => void) {
resize = callback;
}
observe() {}
disconnect = disconnect;
},
);
vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockImplementation(function (
this: HTMLElement,
) {
return this.classList.contains('carousel__viewport') ? available - 64 : available;
});
vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function (
this: HTMLElement,
) {
const index = this.parentElement ? Array.from(this.parentElement.children).indexOf(this) : 0;
const left = this.classList.contains('carousel__item') ? index * 124.25 : 0;
const width = this.classList.contains('carousel__set')
? Math.max(
0,
this.children.length * 124.25 - (this.closest('.carousel--looping') ? 0 : 24.25),
)
: 100;
return {
left,
right: left + width,
width,
top: 0,
bottom: 44,
height: 44,
x: left,
y: 0,
toJSON() {},
};
});
vi.stubGlobal(
'matchMedia',
vi.fn(() => ({ matches: true })),
);
// jsdom has no layout or scrolling implementation.
Object.defineProperty(HTMLElement.prototype, 'scrollTo', {
configurable: true,
value: vi.fn(function (this: HTMLElement, options: ScrollToOptions) {
this.scrollLeft = options.left ?? 0;
}),
});
Object.defineProperty(HTMLElement.prototype, 'scrollBy', {
configurable: true,
value: vi.fn(function (this: HTMLElement, options: ScrollToOptions) {
this.scrollLeft += options.left ?? 0;
}),
});
Object.defineProperty(HTMLElement.prototype, 'scrollIntoView', {
configurable: true,
value: vi.fn(),
});
await TestBed.configureTestingModule({
imports: [HorizontalCarouselComponent],
}).compileComponents();
fixture = TestBed.createComponent(HorizontalCarouselComponent);
fixture.componentRef.setInput('items', items);
fixture.componentRef.setInput('ariaLabel', 'Opciones');
host = fixture.nativeElement;
fixture.detectChanges();
await fixture.whenStable();
});
afterEach(() => {
fixture.destroy();
vi.restoreAllMocks();
vi.unstubAllGlobals();
});
it('starts in the middle with only one accessible set', () => {
expect(host.querySelectorAll('.carousel__set')).toHaveLength(3);
expect(host.querySelectorAll('[aria-hidden="true"] .carousel__item')).toHaveLength(10);
expect(host.querySelectorAll('.carousel__item:not([tabindex="-1"])')).toHaveLength(5);
expect(viewport().scrollLeft).toBe(period());
});
it('wraps both directions preserving the exact fractional offset', () => {
const width = period();
viewport().scrollLeft = width - 30.5;
viewport().dispatchEvent(new Event('scrollend'));
expect(viewport().scrollLeft).toBe(2 * width - 30.5);
viewport().scrollLeft = 2 * width + 42.5;
viewport().dispatchEvent(new Event('scrollend'));
expect(viewport().scrollLeft).toBe(width + 42.5);
});
it('uses the idle fallback after a gesture', () => {
vi.useFakeTimers();
viewport().scrollLeft = 12;
viewport().dispatchEvent(new Event('scroll'));
vi.advanceTimersByTime(180);
expect(viewport().scrollLeft).toBe(period() + 12);
vi.useRealTimers();
});
it('arrows respect reduced motion', () => {
host.querySelectorAll<HTMLButtonElement>('.carousel__arrow')[1].click();
expect(viewport().scrollBy).toHaveBeenCalledWith({
left: (available - 64) * 0.8,
behavior: 'instant',
});
});
it('selects the original value when clicking a copy', () => {
const selected = vi.fn();
fixture.componentInstance.itemSelect.subscribe(selected);
host.querySelector<HTMLButtonElement>('[aria-hidden="true"] .carousel__item')!.click();
expect(selected).toHaveBeenCalledWith(items[0]);
});
it('removes copies and arrows when resized to fit, then restores them', async () => {
available = 1000;
resize();
fixture.detectChanges();
await fixture.whenStable();
expect(host.querySelectorAll('.carousel__set')).toHaveLength(1);
expect(host.querySelectorAll('.carousel__arrow')).toHaveLength(0);
available = 320;
resize();
fixture.detectChanges();
await fixture.whenStable();
expect(host.querySelectorAll('.carousel__set')).toHaveLength(3);
expect(viewport().scrollLeft).toBe(period());
});
it('keeps arrows with three visible slots and advances one item', async () => {
host.style.setProperty('--horizontal-carousel-visible-items', '3');
resize();
fixture.detectChanges();
await fixture.whenStable();
host.querySelectorAll<HTMLElement>('.carousel__set').forEach((set) => {
set.style.columnGap = '8px';
});
host.querySelectorAll<HTMLButtonElement>('.carousel__arrow')[1].click();
expect(viewport().scrollBy).toHaveBeenCalledWith({ left: 108, behavior: 'instant' });
fixture.componentRef.setInput('items', items.slice(0, 3));
fixture.detectChanges();
await fixture.whenStable();
expect(host.querySelectorAll('.carousel__set')).toHaveLength(1);
expect(host.querySelectorAll('.carousel__arrow:disabled')).toHaveLength(2);
});
it('supports noncircular overflow and empty lists', async () => {
fixture.componentRef.setInput('circular', false);
fixture.detectChanges();
await fixture.whenStable();
expect(host.querySelectorAll('.carousel__set')).toHaveLength(1);
expect(host.querySelectorAll('.carousel__arrow')).toHaveLength(2);
fixture.componentRef.setInput('items', []);
fixture.detectChanges();
await fixture.whenStable();
expect(host.querySelectorAll('.carousel__arrow')).toHaveLength(0);
expect(host.querySelectorAll('.carousel__item')).toHaveLength(0);
});
});

View File

@@ -0,0 +1,154 @@
import {
afterNextRender,
afterRenderEffect,
ChangeDetectionStrategy,
Component,
computed,
DestroyRef,
ElementRef,
inject,
input,
output,
signal,
viewChild,
} from '@angular/core';
export interface HorizontalCarouselItem {
/** Unique within the carousel. */
value: string | number;
label: string;
}
@Component({
selector: 'app-horizontal-carousel',
templateUrl: './horizontal-carousel.component.html',
styleUrl: './horizontal-carousel.component.scss',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class HorizontalCarouselComponent {
readonly items = input.required<readonly HorizontalCarouselItem[]>();
readonly circular = input(true);
readonly ariaLabel = input.required<string>();
readonly itemSelect = output<HorizontalCarouselItem>();
protected readonly overflowing = signal(false);
protected readonly visibleItems = signal<number | null>(null);
protected readonly showArrows = computed(
() => this.overflowing() || (this.visibleItems() !== null && this.items().length > 0),
);
protected readonly looping = computed(() => this.circular() && this.overflowing());
protected readonly blocks = computed(() => (this.looping() ? [-1, 0, 1] : [0]));
private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);
private readonly viewport = viewChild.required<ElementRef<HTMLElement>>('viewport');
private readonly canonical = viewChild.required<ElementRef<HTMLElement>>('canonical');
private readonly destroyRef = inject(DestroyRef);
private settleTimer?: ReturnType<typeof setTimeout>;
private observer?: ResizeObserver;
private initializedLoop = false;
private transferringFocus = false;
private lastItems?: readonly HorizontalCarouselItem[];
constructor() {
afterRenderEffect(() => {
const items = this.items();
const looping = this.looping();
const set = this.canonical().nativeElement;
this.measure();
if (this.lastItems !== items || this.initializedLoop !== looping) {
this.viewport().nativeElement.scrollLeft = looping ? set.getBoundingClientRect().width : 0;
this.lastItems = items;
this.initializedLoop = looping;
}
});
afterNextRender(() => {
this.observer = new ResizeObserver(() => {
this.measure();
this.normalize();
});
this.observer.observe(this.host.nativeElement);
this.observer.observe(this.canonical().nativeElement);
});
this.destroyRef.onDestroy(() => {
this.observer?.disconnect();
clearTimeout(this.settleTimer);
});
}
private measure(): void {
const slots = Number(
this.host.nativeElement.ownerDocument.defaultView
?.getComputedStyle(this.host.nativeElement)
.getPropertyValue('--horizontal-carousel-visible-items'),
);
this.visibleItems.set(slots > 0 ? slots : null);
if (slots > 0) {
this.overflowing.set(this.items().length > slots);
return;
}
const set = this.canonical().nativeElement;
const children = set.children;
const first = children.item(0) as HTMLElement | null;
const last = children.item(children.length - 1) as HTMLElement | null;
const width =
first && last ? last.getBoundingClientRect().right - first.getBoundingClientRect().left : 0;
const available = this.host.nativeElement.clientWidth;
this.overflowing.set(available > 0 && width > available + 1);
}
protected move(direction: number): void {
const viewport = this.viewport().nativeElement;
const set = this.canonical().nativeElement;
const first = set.children.item(0) as HTMLElement | null;
const gap =
parseFloat(viewport.ownerDocument.defaultView?.getComputedStyle(set).columnGap ?? '0') || 0;
const distance =
this.visibleItems() && first
? first.getBoundingClientRect().width + gap
: viewport.clientWidth * 0.8;
const reduceMotion = viewport.ownerDocument.defaultView?.matchMedia(
'(prefers-reduced-motion: reduce)',
).matches;
viewport.scrollBy({
left: direction * distance,
behavior: reduceMotion ? 'instant' : 'smooth',
});
}
protected onScroll(): void {
clearTimeout(this.settleTimer);
// Fallback for browsers without scrollend; momentum keeps resetting the timer.
this.settleTimer = setTimeout(() => this.normalize(), 180);
}
protected normalize(): void {
clearTimeout(this.settleTimer);
if (!this.looping()) return;
const viewport = this.viewport().nativeElement;
const width = this.canonical().nativeElement.getBoundingClientRect().width;
if (!width) return;
const left = viewport.scrollLeft;
if (left < width || left >= 2 * width) {
viewport.scrollTo({ left: width + (((left % width) + width) % width), behavior: 'instant' });
}
}
protected reveal(event: FocusEvent): void {
// Only the canonical buttons participate in keyboard / screen-reader navigation.
if (this.transferringFocus) return;
(event.target as HTMLElement).scrollIntoView({
block: 'nearest',
inline: 'nearest',
behavior: 'instant',
});
}
protected selectCopy(item: HorizontalCarouselItem): void {
const index = this.items().findIndex((candidate) => candidate.value === item.value);
this.transferringFocus = true;
(this.canonical().nativeElement.children.item(index) as HTMLElement | null)?.focus({
preventScroll: true,
});
this.transferringFocus = false;
this.itemSelect.emit(item);
}
}