Skip to content
Draft
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
80 changes: 78 additions & 2 deletions core/src/components/checkbox/checkbox.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import type { ComponentInterface, EventEmitter } from '@stencil/core';
import { Build, Component, Element, Event, Host, Method, Prop, State, forceUpdate, h } from '@stencil/core';
import { Build, Component, Element, Event, Host, Listen, Method, Prop, State, forceUpdate, h } from '@stencil/core';
import { checkInvalidState, createItemMultipleInputsObserver } from '@utils/forms';
import type { Attributes } from '@utils/helpers';
import { inheritAriaAttributes, renderHiddenInput } from '@utils/helpers';
import { inheritAriaAttributes, raf, renderHiddenInput } from '@utils/helpers';
import { createColorClasses, hostContext } from '@utils/theme';

import { config } from '../../global/config';
Expand All @@ -11,6 +11,13 @@ import type { Color, Theme } from '../../interface';

import type { CheckboxChangeEventDetail } from './checkbox-interface';

/**
* Slotted label content that handles its own click, so clicking it
* should not toggle the checkbox.
*/
const INTERACTIVE_LABEL_CONTENT =
'a[href], button, details, embed, iframe, select, textarea, input:not([type="hidden"]), audio[controls], video[controls], [contenteditable]:not([contenteditable="false"]), .ion-activatable';

/**
* @virtualProp {"ios" | "md"} mode - The mode determines the platform behaviors of the component.
* @virtualProp {"ios" | "md" | "ionic"} theme - The theme determines the visual appearance of the component.
Expand Down Expand Up @@ -42,6 +49,16 @@ export class Checkbox implements ComponentInterface {
private inheritedAttributes: Attributes = {};
private validationObserver?: MutationObserver;
private itemFocusObserver?: MutationObserver;
private nativeInput?: HTMLInputElement;

/**
* Set when a click starts on the slotted label content, and cleared when
* that click reaches the label text wrapper. If it is still set when the
* label forwards its click to the native input, the slotted content either
* handled the click itself or stopped its propagation, so the checkbox
* must not toggle.
*/
private skipLabelActivation = false;

@Element() el!: HTMLIonCheckboxElement;

Expand Down Expand Up @@ -290,12 +307,70 @@ export class Checkbox implements ComponentInterface {
this.toggleChecked(ev);
};

/**
* Prevents toggling the checkbox when slotted label content handles its
* own click: either it is interactive content, such as a button or link,
* or its click handler stops propagation, such as an icon that opens a
* help popover.
*
* Clicking anything inside of the `<label>` causes the browser to forward
* a second click to the native input once the first click finishes
* dispatching. Stopping propagation of the first click does not cancel
* that forwarded click, so it is cancelled here instead.
*/
@Listen('click', { capture: true })
onClickCapture(ev: MouseEvent) {
if (ev.composedPath()[0] === this.nativeInput) {
if (this.skipLabelActivation) {
this.skipLabelActivation = false;
// Prevent the native input from toggling and the host from emitting the click.
ev.preventDefault();
ev.stopPropagation();
}
return;
}

this.skipLabelActivation = false;

/**
* The target is retargeted to the host's tree, so a click inside the
* checkbox's own shadow root targets the host, while a click inside
* the shadow root of slotted content, such as an ion-icon, targets
* that content.
*/
const { el } = this;
const target = ev.target as Element;
if (target !== el && el.contains(target)) {
this.skipLabelActivation = true;

// The flag only needs to survive until the forwarded click, which is
// dispatched synchronously. Clear it in case the browser never forwards.
raf(() => (this.skipLabelActivation = false));
}
}

/**
* Stops propagation when the display label is clicked,
* otherwise, two clicks will be triggered.
*/
private onDivLabelClick = (ev: MouseEvent) => {
ev.stopPropagation();

if (!this.skipLabelActivation) {
return;
}

const interactive = (ev.target as Element).closest(INTERACTIVE_LABEL_CONTENT);

/**
* The click reached the label text without being stopped, so the
* checkbox should toggle unless it started on interactive content.
* Chromium and Firefox already skip label activation for interactive
* content, but WebKit does not.
*/
if (interactive === null || !this.el.contains(interactive)) {
this.skipLabelActivation = false;
}
};

/**
Expand Down Expand Up @@ -430,6 +505,7 @@ export class Checkbox implements ComponentInterface {
disabled={disabled}
id={inputId}
onChange={this.toggleChecked}
ref={(nativeEl) => (this.nativeInput = nativeEl)}
required={required}
{...inheritedAttributes}
/>
Expand Down
53 changes: 53 additions & 0 deletions core/src/components/checkbox/test/basic/checkbox.e2e.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,59 @@ configs({ modes: ['ios'], directions: ['ltr'] }).forEach(({ title, config }) =>
// Verify the click was triggered exactly once
expect(clickCount).toBe(1);
});

test('should not toggle when a button in the label is clicked', async ({ page }) => {
await page.setContent(
`
<ion-checkbox>
Accept the <button type="button" id="terms">terms</button>
</ion-checkbox>
`,
config
);

const ionChange = await page.spyOnEvent('ionChange');
const checkbox = page.locator('ion-checkbox');

await page.locator('#terms').click();
await page.waitForChanges();

expect(ionChange).not.toHaveReceivedEvent();
await expect(checkbox).toHaveJSProperty('checked', false);
});

test('should not toggle when label content that stops click propagation is clicked', async ({ page }) => {
await page.setContent(
`
<ion-checkbox justify="space-between">
<div>
Description
<ion-icon id="help" name="help-circle-outline"></ion-icon>
</div>
</ion-checkbox>
<script>
document.querySelector('#help').addEventListener('click', (ev) => ev.stopPropagation());
</script>
`,
config
);

const ionChange = await page.spyOnEvent('ionChange');
const checkbox = page.locator('ion-checkbox');

await page.locator('#help').click();
await page.waitForChanges();

expect(ionChange).not.toHaveReceivedEvent();
await expect(checkbox).toHaveJSProperty('checked', false);

// Clicking the rest of the label should still toggle the checkbox.
await page.getByText('Description').click({ position: { x: 5, y: 5 } });
await page.waitForChanges();

expect(ionChange).toHaveReceivedEventTimes(1);
await expect(checkbox).toHaveJSProperty('checked', true);
});
});

test.describe(title('checkbox: ionFocus'), () => {
Expand Down
Loading