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);
Comment thread
thetaPC marked this conversation as resolved.
Resolved
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
Original file line number Diff line number Diff line change
Expand Up @@ -560,3 +560,52 @@ configs({ modes: ['ios'], directions: ['ltr'] }).forEach(({ title, config }) =>
});
});
});

/**
* This behavior does not vary across modes/directions.
*/
configs({ modes: ['ios'], directions: ['ltr'] }).forEach(({ title, config }) => {
test.describe(title('picker-column: haptics'), () => {
test('should emit ionHaptic for each stage of a scroll in order', async ({ page }) => {
/**
* Haptics only play on iOS. Since `setContent` replaces `window.Ionic`
* in the head, we set the platform here, before Ionic loads.
*/
await page.setContent(
`
<script>window.Ionic.platforms = ['ios'];</script>
<ion-picker>
<ion-picker-column value="5">
${Array.from(
{ length: 50 },
(_, i) => `<ion-picker-column-option value="${i}">${i}</ion-picker-column-option>`
).join('')}
</ion-picker-column>
</ion-picker>
`,
config
);

await page.locator('ion-picker-column-option.option-active').waitFor();

const ionHaptic = await page.spyOnEvent('ionHaptic');

await page.evaluate(() => {
const scrollEl = document.querySelector('ion-picker-column')!.shadowRoot!.querySelector('.picker-opts')!;
scrollEl.scrollTo({ top: scrollEl.scrollTop + 200, behavior: 'smooth' });
});

await expect.poll(() => ionHaptic.events.at(-1)?.detail.type).toBe('selectionEnd');
// Gives a late duplicate `selectionEnd` time to show up.
await page.waitForTimeout(COMMIT_WINDOW);

const types = ionHaptic.events.map((ev) => ev.detail.type);
const changedCount = types.length - 2;
const targets = ionHaptic.events.map((ev) => (ev.target as HTMLElement).tagName.toLowerCase());

expect(changedCount).toBeGreaterThan(0);
expect(types).toEqual(['selectionStart', ...Array(changedCount).fill('selectionChanged'), 'selectionEnd']);
expect(new Set(targets)).toEqual(new Set(['ion-picker-column']));
});
});
});
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 @@ -195,11 +195,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 @@ -226,4 +229,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 @@ -310,7 +310,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 @@ -354,7 +354,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-interface';

// 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 @@ -206,6 +206,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
20 changes: 20 additions & 0 deletions core/src/utils/native/haptic-interface.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/**
* These types are public, so they live apart from haptic.ts. Its
* `@capacitor/haptics` import would otherwise end up in the published
* types, and apps without that package would fail to compile.
*/

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