Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion core/src/components/action-sheet/action-sheet.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
24 changes: 24 additions & 0 deletions core/src/components/action-sheet/test/basic/action-sheet.e2e.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});
});
});
2 changes: 1 addition & 1 deletion core/src/components/alert/alert.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
6 changes: 3 additions & 3 deletions core/src/components/picker-column/picker-column.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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;
}

Expand Down Expand Up @@ -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) {
/**
Expand Down
2 changes: 1 addition & 1 deletion core/src/components/refresher/refresher.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 3 additions & 3 deletions core/src/components/reorder-group/reorder-group.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ export class ReorderGroup implements ComponentInterface {

item.classList.add(ITEM_REORDER_SELECTED);

hapticSelectionStart();
hapticSelectionStart(this.el);

this.ionReorderStart.emit();
}
Expand All @@ -212,7 +212,7 @@ export class ReorderGroup implements ComponentInterface {
const fromIndex = indexForItem(selectedItem);
this.lastToIndex = toIndex;

hapticSelectionChanged();
hapticSelectionChanged(this.el);
this.reorderMove(fromIndex, toIndex);
}

Expand Down Expand Up @@ -247,7 +247,7 @@ export class ReorderGroup implements ComponentInterface {
});
}

hapticSelectionEnd();
hapticSelectionEnd(this.el);

this.ionReorderEnd.emit({
from: fromIndex,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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(
`
<ion-reorder-group disabled="false">
<ion-item>
<ion-label>Item 1</ion-label>
<ion-reorder slot="end"></ion-reorder>
</ion-item>
<ion-item>
<ion-label>Item 2</ion-label>
<ion-reorder slot="end"></ion-reorder>
</ion-item>
<ion-item>
<ion-label>Item 3</ion-label>
<ion-reorder slot="end"></ion-reorder>
</ion-item>
</ion-reorder-group>
`,
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');
});
});
});
});
15 changes: 14 additions & 1 deletion core/src/components/toggle/test/toggle.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: `<ion-toggle>Toggle</ion-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
Expand All @@ -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' });
});
});
4 changes: 2 additions & 2 deletions core/src/components/toggle/toggle.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

Expand Down Expand Up @@ -338,7 +338,7 @@ export class Toggle implements ComponentInterface {

if (this.lastDrag + 300 < Date.now()) {
this.toggleChecked();
enableHaptics && hapticSelection();
enableHaptics && hapticSelection(this.el);
}
};

Expand Down
1 change: 1 addition & 0 deletions core/src/interface.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
1 change: 1 addition & 0 deletions core/src/utils/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
17 changes: 12 additions & 5 deletions core/src/utils/gesture/button-active.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand All @@ -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) {
Expand All @@ -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) => {
Expand Down Expand Up @@ -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;
},
});
Expand Down
57 changes: 46 additions & 11 deletions core/src/utils/native/haptic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,48 +144,83 @@ 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<HapticEventDetail>;

/**
* 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();
};

/**
* 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);
};
Loading
Loading