diff --git a/core/src/components/action-sheet/action-sheet.tsx b/core/src/components/action-sheet/action-sheet.tsx index 8d63b81021d..0bbe4b146c3 100644 --- a/core/src/components/action-sheet/action-sheet.tsx +++ b/core/src/components/action-sheet/action-sheet.tsx @@ -510,7 +510,7 @@ export class ActionSheet implements ComponentInterface, OverlayInterface { if (this.gesture || !this.el.isConnected || groupEl.scrollHeight > groupEl.clientHeight) { return; } - this.gesture = createButtonActiveGesture(wrapperEl, (refEl: HTMLElement) => + this.gesture = createButtonActiveGesture(this.el, wrapperEl, (refEl: HTMLElement) => refEl.classList.contains('action-sheet-button') ); this.gesture.enable(true); diff --git a/core/src/components/action-sheet/test/basic/action-sheet.e2e.ts b/core/src/components/action-sheet/test/basic/action-sheet.e2e.ts index 19368dd652f..7f1bca265fd 100644 --- a/core/src/components/action-sheet/test/basic/action-sheet.e2e.ts +++ b/core/src/components/action-sheet/test/basic/action-sheet.e2e.ts @@ -218,4 +218,28 @@ configs({ modes: ['ios'], directions: ['ltr'] }).forEach(({ config, title }) => await page.mouse.up(); }); }); + + test.describe(title('action sheet: haptics'), () => { + test('should emit ionHaptic from the action sheet when a button is pressed', async ({ page }) => { + await page.goto('/src/components/action-sheet/test/basic', config); + + const ionActionSheetDidPresent = await page.spyOnEvent('ionActionSheetDidPresent'); + const ionHaptic = await page.spyOnEvent('ionHaptic'); + + await page.click('#basic'); + await ionActionSheetDidPresent.next(); + + const button = page.locator('ion-action-sheet .action-sheet-button').first(); + const box = (await button.boundingBox())!; + + await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2); + await page.mouse.down(); + await ionHaptic.next(); + + await expect(ionHaptic).toHaveReceivedEventDetail({ type: 'selectionStart' }); + expect((ionHaptic.events[0].target as HTMLElement).tagName.toLowerCase()).toBe('ion-action-sheet'); + + await page.mouse.up(); + }); + }); }); diff --git a/core/src/components/alert/alert.tsx b/core/src/components/alert/alert.tsx index b8f121e57e0..e2071ed9be7 100644 --- a/core/src/components/alert/alert.tsx +++ b/core/src/components/alert/alert.tsx @@ -401,7 +401,7 @@ export class Alert implements ComponentInterface, OverlayInterface { */ private setupButtonActiveGesture() { if (!this.gesture && getIonMode(this) === 'ios' && this.wrapperEl) { - this.gesture = createButtonActiveGesture(this.wrapperEl, (refEl: HTMLElement) => + this.gesture = createButtonActiveGesture(this.el, this.wrapperEl, (refEl: HTMLElement) => refEl.classList.contains('alert-button') ); this.gesture.enable(true); diff --git a/core/src/components/picker-column/picker-column.tsx b/core/src/components/picker-column/picker-column.tsx index ea56f0711b2..3767c5af337 100644 --- a/core/src/components/picker-column/picker-column.tsx +++ b/core/src/components/picker-column/picker-column.tsx @@ -392,7 +392,7 @@ export class PickerColumn implements ComponentInterface { this.isScrolling = false; this.updateValueTextOnScroll = true; - this.enableHaptics && hapticSelectionEnd(); + this.enableHaptics && hapticSelectionEnd(this.el); /** * Certain tasks (such as those that @@ -503,7 +503,7 @@ export class PickerColumn implements ComponentInterface { this.resetScrollEndTimeout(); if (!this.isScrolling) { - this.enableHaptics && hapticSelectionStart(); + this.enableHaptics && hapticSelectionStart(this.el); this.isScrolling = true; } @@ -600,7 +600,7 @@ export class PickerColumn implements ComponentInterface { * we need to run haptics again. */ if (newActiveElement !== activeEl) { - this.enableHaptics && hapticSelectionChanged(); + this.enableHaptics && hapticSelectionChanged(this.el); if (this.canExitInputMode) { /** diff --git a/core/src/components/refresher/refresher.tsx b/core/src/components/refresher/refresher.tsx index 153f4cc6f76..e0f49bd57b8 100644 --- a/core/src/components/refresher/refresher.tsx +++ b/core/src/components/refresher/refresher.tsx @@ -272,7 +272,7 @@ export class Refresher implements ComponentInterface { if (!this.didRefresh) { this.beginRefresh(); this.didRefresh = true; - hapticImpact({ style: ImpactStyle.Light }); + hapticImpact(this.el, { style: ImpactStyle.Light }); /** * Clear focus from any active element to prevent scroll jumps diff --git a/core/src/components/reorder-group/reorder-group.tsx b/core/src/components/reorder-group/reorder-group.tsx index 918beebd99a..2b1d8cd8e86 100644 --- a/core/src/components/reorder-group/reorder-group.tsx +++ b/core/src/components/reorder-group/reorder-group.tsx @@ -187,7 +187,7 @@ export class ReorderGroup implements ComponentInterface { item.classList.add(ITEM_REORDER_SELECTED); - hapticSelectionStart(); + hapticSelectionStart(this.el); this.ionReorderStart.emit(); } @@ -212,7 +212,7 @@ export class ReorderGroup implements ComponentInterface { const fromIndex = indexForItem(selectedItem); this.lastToIndex = toIndex; - hapticSelectionChanged(); + hapticSelectionChanged(this.el); this.reorderMove(fromIndex, toIndex); } @@ -247,7 +247,7 @@ export class ReorderGroup implements ComponentInterface { }); } - hapticSelectionEnd(); + hapticSelectionEnd(this.el); this.ionReorderEnd.emit({ from: fromIndex, diff --git a/core/src/components/reorder-group/test/reorder-group-events.e2e.ts b/core/src/components/reorder-group/test/reorder-group-events.e2e.ts index d3324e7dbdf..9f38db7089d 100644 --- a/core/src/components/reorder-group/test/reorder-group-events.e2e.ts +++ b/core/src/components/reorder-group/test/reorder-group-events.e2e.ts @@ -285,5 +285,44 @@ configs({ modes: ['ios'], directions: ['ltr'] }).forEach(({ title, config }) => await expect(ionItemReorder).toHaveReceivedEventDetail({ from: 0, to: 2, complete: undefined }); }); }); + + test.describe('ionHaptic', () => { + test('should emit from the reorder group for each haptic during a reorder', async ({ page }) => { + await page.setContent( + ` + + + Item 1 + + + + Item 2 + + + + Item 3 + + + + `, + config + ); + + const reorderGroup = page.locator('ion-reorder-group'); + const ionHaptic = await page.spyOnEvent('ionHaptic'); + + await dragElementBy(reorderGroup.locator('ion-reorder').first(), page, 0, 300); + await page.waitForChanges(); + + const targets = ionHaptic.events.map((ev) => (ev.target as HTMLElement).tagName.toLowerCase()); + const types = ionHaptic.events.map((ev) => ev.detail.type); + + expect(targets.length).toBeGreaterThan(0); + expect(new Set(targets)).toEqual(new Set(['ion-reorder-group'])); + expect(types[0]).toBe('selectionStart'); + expect(types).toContain('selectionChanged'); + expect(types[types.length - 1]).toBe('selectionEnd'); + }); + }); }); }); diff --git a/core/src/components/toggle/test/toggle.spec.ts b/core/src/components/toggle/test/toggle.spec.ts index 47f4717b684..e7717ecb3d6 100644 --- a/core/src/components/toggle/test/toggle.spec.ts +++ b/core/src/components/toggle/test/toggle.spec.ts @@ -119,11 +119,14 @@ describe('ion-toggle: haptics', () => { config.reset({}); }); - const clickToggleOnIOS = async () => { + const clickToggleOnIOS = async (onHaptic?: (ev: CustomEvent) => void) => { const page = await newSpecPage({ components: [Toggle], html: `Toggle`, }); + if (onHaptic) { + page.doc.addEventListener('ionHaptic', onHaptic as EventListener); + } const win = page.win as any; win.Ionic = { ...win.Ionic, platforms: ['ios'] }; // newSpecPage resets the window, so stub Capacitor after it @@ -150,4 +153,14 @@ describe('ion-toggle: haptics', () => { expect(impact).not.toHaveBeenCalled(); }); + + it('should emit ionHaptic from the toggle when clicked', async () => { + const events: CustomEvent[] = []; + + await clickToggleOnIOS((ev) => events.push(ev)); + + expect(events.length).toBe(1); + expect((events[0].target as HTMLElement).tagName.toLowerCase()).toBe('ion-toggle'); + expect(events[0].detail).toEqual({ type: 'selection' }); + }); }); diff --git a/core/src/components/toggle/toggle.tsx b/core/src/components/toggle/toggle.tsx index 041a200bead..27ddbe31c9b 100644 --- a/core/src/components/toggle/toggle.tsx +++ b/core/src/components/toggle/toggle.tsx @@ -294,7 +294,7 @@ export class Toggle implements ComponentInterface { private onMove(detail: GestureDetail) { if (shouldToggle(isRTL(this.el), this.checked, detail.deltaX, -10)) { this.toggleChecked(); - hapticSelection(); + hapticSelection(this.el); } } @@ -338,7 +338,7 @@ export class Toggle implements ComponentInterface { if (this.lastDrag + 300 < Date.now()) { this.toggleChecked(); - enableHaptics && hapticSelection(); + enableHaptics && hapticSelection(this.el); } }; diff --git a/core/src/interface.d.ts b/core/src/interface.d.ts index cfcdb68f828..b50cf412061 100644 --- a/core/src/interface.d.ts +++ b/core/src/interface.d.ts @@ -44,6 +44,7 @@ export { TextareaCustomEvent } from './components/textarea/textarea-interface'; export { ToastOptions } from './components/toast/toast-interface'; export { ToggleCustomEvent } from './components/toggle/toggle-interface'; export { BackButtonEvent, BackButtonEventDetail } from './utils/hardware-back-button'; +export { HapticEvent, HapticEventDetail } from './utils/native/haptic'; // Types from utils export { diff --git a/core/src/utils/config.ts b/core/src/utils/config.ts index 39cd5e2d62e..6d1053e7d16 100644 --- a/core/src/utils/config.ts +++ b/core/src/utils/config.ts @@ -194,6 +194,7 @@ export interface IonicConfig { * Relevant Components: ion-action-sheet, ion-alert, ion-picker-column, ion-refresher, ion-reorder-group, ion-toggle * Haptics are the small vibrations a device plays as touch feedback, such as when a toggle is switched. * If `false`, Ionic components won't trigger haptics. Defaults to `true`. + * Components still dispatch `ionHaptic` wherever they would trigger one, so apps can play their own. */ haptics?: boolean; diff --git a/core/src/utils/gesture/button-active.ts b/core/src/utils/gesture/button-active.ts index 0ee930752dc..000430f1f3a 100644 --- a/core/src/utils/gesture/button-active.ts +++ b/core/src/utils/gesture/button-active.ts @@ -5,11 +5,18 @@ import { hapticSelectionChanged, hapticSelectionEnd, hapticSelectionStart } from import type { Gesture } from './index'; import { createGesture } from './index'; -export const createButtonActiveGesture = (el: HTMLElement, isButton: (refEl: HTMLElement) => boolean): Gesture => { +/** + * @param hostEl The component that owns the buttons. `ionHaptic` is dispatched from it. + */ +export const createButtonActiveGesture = ( + hostEl: HTMLElement, + el: HTMLElement, + isButton: (refEl: HTMLElement) => boolean +): Gesture => { let currentTouchedButton: HTMLElement | undefined; let initialTouchedButton: HTMLElement | undefined; - const activateButtonAtPoint = (x: number, y: number, hapticFeedbackFn: () => void) => { + const activateButtonAtPoint = (x: number, y: number, hapticFeedbackFn: (el: HTMLElement) => void) => { if (typeof (document as any) === 'undefined') { return; } @@ -25,7 +32,7 @@ export const createButtonActiveGesture = (el: HTMLElement, isButton: (refEl: HTM } }; - const setActiveButton = (button: HTMLElement, hapticFeedbackFn: () => void) => { + const setActiveButton = (button: HTMLElement, hapticFeedbackFn: (el: HTMLElement) => void) => { currentTouchedButton = button; if (!initialTouchedButton) { @@ -34,7 +41,7 @@ export const createButtonActiveGesture = (el: HTMLElement, isButton: (refEl: HTM const buttonToModify = currentTouchedButton; writeTask(() => buttonToModify.classList.add('ion-activated')); - hapticFeedbackFn(); + hapticFeedbackFn(hostEl); }; const clearActiveButton = (dispatchClick = false) => { @@ -68,7 +75,7 @@ export const createButtonActiveGesture = (el: HTMLElement, isButton: (refEl: HTM onMove: (ev) => activateButtonAtPoint(ev.currentX, ev.currentY, hapticSelectionChanged), onEnd: () => { clearActiveButton(true); - hapticSelectionEnd(); + hapticSelectionEnd(hostEl); initialTouchedButton = undefined; }, }); diff --git a/core/src/utils/native/haptic.ts b/core/src/utils/native/haptic.ts index 06d2d9fce14..3c2950ecabb 100644 --- a/core/src/utils/native/haptic.ts +++ b/core/src/utils/native/haptic.ts @@ -144,33 +144,68 @@ export const hapticAvailable = (): boolean => { return HapticEngine.available(); }; +/** + * Detail of the `ionHaptic` event. `type` matches the Capacitor Haptics + * method Ionic would call, except `selection`, which Ionic plays as a + * light impact. The haptic engine only plays `selectionChanged` after a + * `selectionStart`, so canceling `selectionStart` also silences the rest + * of that gesture. `selectionEnd` plays nothing and only releases the + * engine, so canceling it has no effect. + */ +export type HapticEventDetail = + | { type: 'selection' | 'selectionStart' | 'selectionChanged' | 'selectionEnd' } + | { type: 'impact'; style: 'HEAVY' | 'MEDIUM' | 'LIGHT' } + | { type: 'notification'; notificationType: 'SUCCESS' | 'WARNING' | 'ERROR' }; + +export type HapticEvent = CustomEvent; + +/** + * Dispatch `ionHaptic` from `el`. + * @returns `true` if the built-in haptic should play. + */ +const emitHaptic = (el: HTMLElement, detail: HapticEventDetail): boolean => { + const ev: HapticEvent = new CustomEvent('ionHaptic', { + bubbles: true, + composed: true, + cancelable: true, + detail, + }); + el.dispatchEvent(ev); + /** + * Read defaultPrevented instead of the dispatchEvent return value: + * Stencil's mock-doc always returns true from dispatchEvent. + */ + return !ev.defaultPrevented && hapticAvailable(); +}; + /** * Trigger a selection changed haptic event. Good for one-time events * (not for gestures) */ -export const hapticSelection = () => { - hapticAvailable() && HapticEngine.selection(); +export const hapticSelection = (el: HTMLElement) => { + emitHaptic(el, { type: 'selection' }) && HapticEngine.selection(); }; /** * Tell the haptic engine that a gesture for a selection change is starting. */ -export const hapticSelectionStart = () => { - hapticAvailable() && HapticEngine.selectionStart(); +export const hapticSelectionStart = (el: HTMLElement) => { + emitHaptic(el, { type: 'selectionStart' }) && HapticEngine.selectionStart(); }; /** * Tell the haptic engine that a selection changed during a gesture. */ -export const hapticSelectionChanged = () => { - hapticAvailable() && HapticEngine.selectionChanged(); +export const hapticSelectionChanged = (el: HTMLElement) => { + emitHaptic(el, { type: 'selectionChanged' }) && HapticEngine.selectionChanged(); }; /** * Tell the haptic engine we are done with a gesture. This needs to be * called lest resources are not properly recycled. */ -export const hapticSelectionEnd = () => { +export const hapticSelectionEnd = (el: HTMLElement) => { + emitHaptic(el, { type: 'selectionEnd' }); hapticAvailable() && HapticEngine.selectionEnd(); }; @@ -178,14 +213,14 @@ export const hapticSelectionEnd = () => { * Use this to indicate success/failure/warning to the user. * options should be of the type `{ type: NotificationType.SUCCESS }` (or `WARNING`/`ERROR`) */ -export const hapticNotification = (options: HapticNotificationOptions) => { - hapticAvailable() && HapticEngine.notification(options); +export const hapticNotification = (el: HTMLElement, options: HapticNotificationOptions) => { + emitHaptic(el, { type: 'notification', notificationType: options.type }) && HapticEngine.notification(options); }; /** * Use this to indicate success/failure/warning to the user. * options should be of the type `{ style: ImpactStyle.LIGHT }` (or `MEDIUM`/`HEAVY`) */ -export const hapticImpact = (options: HapticImpactOptions) => { - hapticAvailable() && HapticEngine.impact(options); +export const hapticImpact = (el: HTMLElement, options: HapticImpactOptions) => { + emitHaptic(el, { type: 'impact', style: options.style }) && HapticEngine.impact(options); }; diff --git a/core/src/utils/native/test/haptic.spec.ts b/core/src/utils/native/test/haptic.spec.ts index a90d0abcb16..62bb0883080 100644 --- a/core/src/utils/native/test/haptic.spec.ts +++ b/core/src/utils/native/test/haptic.spec.ts @@ -13,6 +13,7 @@ import { } from '../haptic'; describe('haptics', () => { + let el: HTMLElement; let haptics: { impact: jest.Mock; notification: jest.Mock; @@ -22,6 +23,8 @@ describe('haptics', () => { }; beforeEach(() => { + el = document.createElement('ion-toggle'); + document.body.appendChild(el); haptics = { impact: jest.fn(), notification: jest.fn(), @@ -38,12 +41,13 @@ describe('haptics', () => { }); afterEach(() => { + el.remove(); delete (window as any).Capacitor; config.reset({}); }); it('should trigger haptics by default', () => { - hapticSelection(); + hapticSelection(el); expect(haptics.impact).toHaveBeenCalledTimes(1); }); @@ -51,12 +55,12 @@ describe('haptics', () => { it('should not trigger haptics when the haptics config is false', () => { config.reset({ haptics: false }); - hapticSelection(); - hapticSelectionStart(); - hapticSelectionChanged(); - hapticSelectionEnd(); - hapticImpact({ style: ImpactStyle.Heavy }); - hapticNotification({ type: NotificationType.Success }); + hapticSelection(el); + hapticSelectionStart(el); + hapticSelectionChanged(el); + hapticSelectionEnd(el); + hapticImpact(el, { style: ImpactStyle.Heavy }); + hapticNotification(el, { type: NotificationType.Success }); Object.values(haptics).forEach((method) => expect(method).not.toHaveBeenCalled()); }); @@ -76,8 +80,98 @@ describe('haptics', () => { it('should trigger haptics when the haptics config is true', () => { config.reset({ haptics: true }); - hapticSelection(); + hapticSelection(el); expect(haptics.impact).toHaveBeenCalledTimes(1); }); + + describe('ionHaptic event', () => { + it('should dispatch ionHaptic when the haptics config is false', () => { + config.reset({ haptics: false }); + const listener = jest.fn(); + el.addEventListener('ionHaptic', listener); + + hapticSelection(el); + + expect(listener).toHaveBeenCalledTimes(1); + expect(haptics.impact).not.toHaveBeenCalled(); + }); + + it('should dispatch ionHaptic when no haptic engine is available', () => { + delete (window as any).Capacitor; + const listener = jest.fn(); + el.addEventListener('ionHaptic', listener); + + hapticSelection(el); + + expect(listener).toHaveBeenCalledTimes(1); + }); + + it('should describe the haptic in the event detail', () => { + const details: unknown[] = []; + el.addEventListener('ionHaptic', (ev) => details.push((ev as CustomEvent).detail)); + + hapticSelectionStart(el); + hapticSelectionChanged(el); + hapticSelectionEnd(el); + hapticImpact(el, { style: ImpactStyle.Heavy }); + hapticNotification(el, { type: NotificationType.Warning }); + + expect(details).toEqual([ + { type: 'selectionStart' }, + { type: 'selectionChanged' }, + { type: 'selectionEnd' }, + { type: 'impact', style: 'HEAVY' }, + { type: 'notification', notificationType: 'WARNING' }, + ]); + }); + + it('should skip the built-in haptic when the event is canceled', () => { + el.addEventListener('ionHaptic', (ev) => ev.preventDefault()); + + hapticSelection(el); + + expect(haptics.impact).not.toHaveBeenCalled(); + }); + + it('should skip only selectionStart when only selectionStart is canceled', () => { + const types: string[] = []; + el.addEventListener('ionHaptic', (ev) => { + const { type } = (ev as CustomEvent).detail; + types.push(type); + if (type === 'selectionStart') { + ev.preventDefault(); + } + }); + + hapticSelectionStart(el); + hapticSelectionChanged(el); + hapticSelectionEnd(el); + + expect(types).toEqual(['selectionStart', 'selectionChanged', 'selectionEnd']); + expect(haptics.selectionStart).not.toHaveBeenCalled(); + expect(haptics.selectionChanged).toHaveBeenCalledTimes(1); + }); + + it('should still release the haptic engine when selectionEnd is canceled', () => { + el.addEventListener('ionHaptic', (ev) => ev.preventDefault()); + + hapticSelectionEnd(el); + + expect(haptics.selectionEnd).toHaveBeenCalledTimes(1); + }); + + it('should dispatch a bubbling ionHaptic event from the source element', () => { + const listener = jest.fn(); + document.addEventListener('ionHaptic', listener); + + hapticSelection(el); + + document.removeEventListener('ionHaptic', listener); + expect(listener).toHaveBeenCalledTimes(1); + const ev = listener.mock.calls[0][0] as CustomEvent; + expect(ev.target).toBe(el); + expect(ev.detail).toEqual({ type: 'selection' }); + }); + }); }); diff --git a/packages/angular/src/lazy/index.ts b/packages/angular/src/lazy/index.ts index 21147495792..6e535b8b395 100644 --- a/packages/angular/src/lazy/index.ts +++ b/packages/angular/src/lazy/index.ts @@ -87,6 +87,8 @@ export { CheckboxChangeEventDetail, DatetimeCustomEvent, DatetimeChangeEventDetail, + HapticEvent, + HapticEventDetail, InfiniteScrollCustomEvent, InputCustomEvent, InputChangeEventDetail, diff --git a/packages/angular/src/standalone/index.ts b/packages/angular/src/standalone/index.ts index c0da0e63345..726afcad9c8 100644 --- a/packages/angular/src/standalone/index.ts +++ b/packages/angular/src/standalone/index.ts @@ -80,6 +80,8 @@ export type { CheckboxChangeEventDetail, DatetimeCustomEvent, DatetimeChangeEventDetail, + HapticEvent, + HapticEventDetail, InfiniteScrollCustomEvent, InputCustomEvent, InputChangeEventDetail, diff --git a/packages/react/src/components/index.ts b/packages/react/src/components/index.ts index 14bea3905f0..9cbbc8ccca1 100644 --- a/packages/react/src/components/index.ts +++ b/packages/react/src/components/index.ts @@ -40,6 +40,8 @@ export { CheckboxChangeEventDetail, DatetimeCustomEvent, DatetimeChangeEventDetail, + HapticEvent, + HapticEventDetail, InfiniteScrollCustomEvent, InputCustomEvent, InputChangeEventDetail, diff --git a/packages/vue/src/index.ts b/packages/vue/src/index.ts index 388a1cbc12f..a693c61c780 100644 --- a/packages/vue/src/index.ts +++ b/packages/vue/src/index.ts @@ -76,6 +76,8 @@ export { CheckboxChangeEventDetail, DatetimeCustomEvent, DatetimeChangeEventDetail, + HapticEvent, + HapticEventDetail, InfiniteScrollCustomEvent, InputCustomEvent, InputChangeEventDetail,