Skip to content
Merged
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
5 changes: 5 additions & 0 deletions core/src/components/input/input.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -527,6 +527,11 @@ export class Input implements ComponentInterface {

this.clearButtonPressController.destroy();

if (this.clickController) {
this.clickController.destroy();
this.clickController = undefined;
}

if (this.slotMutationController) {
this.slotMutationController.destroy();
this.slotMutationController = undefined;
Expand Down
5 changes: 5 additions & 0 deletions core/src/components/select/select.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -484,6 +484,11 @@ export class Select implements ComponentInterface {
}

disconnectedCallback() {
if (this.clickController) {
this.clickController.destroy();
this.clickController = undefined;
}

if (this.mutationO) {
this.mutationO.disconnect();
this.mutationO = undefined;
Expand Down
127 changes: 123 additions & 4 deletions core/src/components/textarea/test/basic/textarea.e2e.ts
Original file line number Diff line number Diff line change
Expand Up @@ -295,10 +295,6 @@ configs({ modes: ['md'], directions: ['ltr'] }).forEach(({ title, config }) => {
await expect(page.locator('ion-textarea textarea')).not.toBeFocused();
});

/**
* Browsers skip the label forwarding when a click lands on interactive
* content, so activating a slotted control leaves the textarea alone.
*/
['ion-checkbox', 'ion-radio', 'ion-toggle'].forEach((tag) => {
test(`should activate a slotted ${tag} without focusing the textarea`, async ({ page }) => {
const control = page.locator(tag);
Expand Down Expand Up @@ -327,3 +323,126 @@ configs({ modes: ['md'], directions: ['ltr'] }).forEach(({ title, config }) => {
});
});
});

/**
* This behavior does not vary across directions/modes
*/
configs({ modes: ['md'], directions: ['ltr'] }).forEach(({ title, config }) => {
test.describe(title('textarea: slotted control focus'), () => {
test('should focus the textarea after a slotted control stops the click propagating', async ({ page }) => {
await page.setContent(
`
<ion-textarea label="Notes">
<button slot="end" onclick="event.stopPropagation()">Clear</button>
</ion-textarea>
`,
config
);

await page.locator('button[slot="end"]').click();
await page.locator('ion-textarea textarea').click();

await expect(page.locator('ion-textarea textarea')).toBeFocused();
});

test('should navigate when a slotted link is clicked', async ({ page }) => {
await page.setContent(
`
<ion-textarea label="Notes">
<a slot="end" href="#linked">Help</a>
</ion-textarea>
`,
config
);

const clickEvent = await page.spyOnEvent('click');

await page.locator('a[slot="end"]').click();

await expect(page).toHaveURL(/#linked$/);
expect(clickEvent).toHaveReceivedEventTimes(1);
await expect(page.locator('ion-textarea textarea')).not.toBeFocused();
});

test('should toggle a slotted checkbox without focusing the textarea inside an item', async ({ page }) => {
await page.setContent(
`
<ion-item>
<ion-textarea label="Notes">
<ion-checkbox slot="end" aria-label="Remember"></ion-checkbox>
</ion-textarea>
</ion-item>
`,
config
);

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

await checkbox.click();
await page.waitForChanges();

await expect(checkbox).toHaveAttribute('aria-checked', 'true');
expect(clickEvent).toHaveReceivedEventTimes(1);
await expect(page.locator('ion-textarea textarea')).not.toBeFocused();
});

/**
* WebKit forwards the label's click to the textarea even when the click
* started on interactive content, which would pull focus off the control.
*/
test('should leave focus on a slotted control when it is clicked', async ({ page }) => {
await page.setContent(
`
<ion-textarea label="Notes">
<input slot="end" aria-label="Tag" />
</ion-textarea>
`,
config
);

const control = page.locator('input[slot="end"]');

await control.click();

await expect(control).toBeFocused();
});

test('should not focus the textarea when a focused slotted ion-button is clicked', async ({ page }) => {
await page.setContent(
`
<ion-textarea label="Notes">
<ion-button slot="end">Send</ion-button>
</ion-textarea>
`,
config
);

const button = page.locator('ion-button[slot="end"] button');

await button.focus();
await button.click();

await expect(page.locator('ion-textarea textarea')).not.toBeFocused();
});

test('should emit the native click when the textarea is clicked directly', async ({ page }) => {
await page.setContent(
`
<ion-textarea label="Notes"></ion-textarea>
`,
config
);

await page.evaluate(() => {
document.querySelector('ion-textarea')!.addEventListener('click', (ev) => {
(window as any).hostClicks = [...((window as any).hostClicks ?? []), ev.isTrusted];
});
});

await page.locator('ion-textarea textarea').click();

expect(await page.evaluate(() => (window as any).hostClicks)).toEqual([true]);
});
});
});
138 changes: 24 additions & 114 deletions core/src/components/textarea/textarea.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
Element,
Event,
Host,
Listen,
Method,
Prop,
State,
Expand All @@ -14,16 +15,17 @@ import {
h,
writeTask,
} from '@stencil/core';
import type { NotchController, StartEndContainerController } from '@utils/forms';
import type { ClickController, NotchController, StartEndContainerController } from '@utils/forms';
import {
createClickController,
getSlottedClickContent,
createNotchController,
createStartEndContainerController,
checkInvalidState,
reportValidityToElementInternals,
} from '@utils/forms';
import type { Attributes } from '@utils/helpers';
import { inheritAriaAttributes, debounceEvent, inheritAttributes, componentOnReady, raf } from '@utils/helpers';
import { inheritAriaAttributes, debounceEvent, inheritAttributes, componentOnReady } from '@utils/helpers';
import { createSlotMutationController } from '@utils/slot-mutation-controller';
import type { SlotMutationController } from '@utils/slot-mutation-controller';
import { createColorClasses, hostContext } from '@utils/theme';
Expand All @@ -34,13 +36,6 @@ import { getCounterText } from '../input/input.utils';

import type { TextareaChangeEventDetail, TextareaInputEventDetail } from './textarea-interface';

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

/**
* @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 @@ -95,6 +90,7 @@ export class Textarea implements ComponentInterface {
private notchController?: NotchController;
private notchSpacerEl: HTMLElement | undefined;
private startEndContainerController?: StartEndContainerController;
private clickController?: ClickController;
private startContainerEl: HTMLElement | undefined;
private endContainerEl: HTMLElement | undefined;

Expand Down Expand Up @@ -419,6 +415,8 @@ export class Textarea implements ComponentInterface {

this.startEndContainerController.calculateContainerWidths();

this.clickController = createClickController(el, () => this.nativeInput);

// Watch for class changes to update validation state
if (Build.isBrowser && typeof MutationObserver !== 'undefined') {
this.validationObserver = new MutationObserver(() => {
Expand Down Expand Up @@ -450,8 +448,10 @@ export class Textarea implements ComponentInterface {
}

disconnectedCallback() {
this.disarmFocusRejection?.();
this.rejectingFocus = false;
if (this.clickController) {
this.clickController.destroy();
this.clickController = undefined;
}

if (Build.isBrowser) {
document.dispatchEvent(
Expand Down Expand Up @@ -517,7 +517,7 @@ export class Textarea implements ComponentInterface {
@Method()
async setFocus() {
// An explicit focus request is never the focus a gesture delegated here.
this.rejectingFocus = false;
this.clickController?.cancelFocusRejection();

if (this.nativeInput) {
this.nativeInput.focus();
Expand Down Expand Up @@ -678,11 +678,7 @@ export class Textarea implements ComponentInterface {
};

private onFocus = (ev: FocusEvent) => {
// The textarea was not the target of this gesture, so drop the focus without reporting it.

if (this.rejectingFocus) {
this.nativeInput?.blur();

if (this.clickController?.rejectFocus(ev)) {
return;
}

Expand Down Expand Up @@ -772,111 +768,25 @@ export class Textarea implements ComponentInterface {
}

/**
* Stops propagation for clicks on the textarea's own content (label text,
* textarea field) to prevent double-click events. Allows clicks on slotted
* content to propagate so event delegation works for parent handlers.
*
* Only slots belonging directly to this textarea should be considered.
* The textarea itself may have a slot attribute when placed in an item
* or toolbar, which does not make its content slotted content.
* Drops the duplicate click the label forwards to the textarea after a click
* on slotted content.
*/
/**
* Whether the click that began the current gesture already reached the
* consumer. Clicking the label makes the browser forward a second click to
* the native textarea; WebKit forwards it even when the gesture began on
* slotted content, where it would arrive as a duplicate.
*/
private clickReachedConsumer = false;

/** Whether focus delegated to the native textarea belongs to slotted content instead. */
private rejectingFocus = false;
private disarmFocusRejection?: () => void;

/** Whether the click started on slotted content that handles its own click. */
private isInteractiveSlottedContent(ev: MouseEvent) {
const slotted = getSlottedClickContent(ev, this.el);

if (slotted === null) {
return false;
}

/**
* The composed path is used rather than `closest` so that a control which
* keeps its interactive element inside its own shadow root, such as
* `ion-datetime-button`, is still recognized.
*/
const path = ev.composedPath();

return path.slice(0, path.indexOf(slotted) + 1).some((node) => {
const el = node as Node;

return el.nodeType === Node.ELEMENT_NODE && (el as Element).matches(INTERACTIVE_CONTENT);
});
@Listen('click', { capture: true })
onClickCapture(ev: Event) {
this.clickController?.handleClickCapture(ev);
}

private onLabelPointerDown = (ev: MouseEvent) => {
this.clickReachedConsumer = false;

if (ev.button !== 0 || !this.isInteractiveSlottedContent(ev)) {
return;
}

this.armFocusRejection();
private onLabelMouseDown = (ev: MouseEvent) => {
this.clickController?.handleMouseDown(ev);
};

/**
* The gesture ends with the click the browser resolves from it, which can
* land outside the label when the pointer is released off the content, and
* for a drag or a release outside the window never arrives at all.
* Stops clicks on the label text and wrapper padding, since the click the
* label forwards to the textarea already represents them.
*/
private armFocusRejection() {
this.disarmFocusRejection?.();
this.rejectingFocus = true;

const events = ['click', 'dragstart', 'pointercancel'];
const disarm = () => {
this.disarmFocusRejection = undefined;
events.forEach((name) => document.removeEventListener(name, disarm));
raf(() => (this.rejectingFocus = false));
};

this.disarmFocusRejection = disarm;
events.forEach((name) => document.addEventListener(name, disarm));
}

private onLabelClick = (ev: MouseEvent) => {
const target = ev.target as HTMLElement;

if (target === this.nativeInput) {
/**
* Either the click the label forwarded here, or a direct click on the
* textarea. Both should reach the consumer as a single click on the host,
* so only drop it when something else already did.
*/
if (this.clickReachedConsumer) {
ev.stopPropagation();
}

this.clickReachedConsumer = false;

return;
}

/**
* Clicks on slotted content belong to the consumer and have to keep
* propagating. Everything else is internal chrome (the label, the
* start/end containers, the wrapper padding) and is represented by the
* click the label forwards to the native textarea.
*/
const slotted = target.closest('[slot="start"], [slot="end"]');
const isSlotted = slotted !== null && slotted !== this.el && this.el.contains(slotted);

this.clickReachedConsumer = isSlotted;

if (!isSlotted) {
if (ev.target !== this.nativeInput && getSlottedClickContent(ev, this.el) === null) {
ev.stopPropagation();

return;
}
};

Expand Down Expand Up @@ -1089,7 +999,7 @@ export class Textarea implements ComponentInterface {
<label
class="textarea-wrapper"
htmlFor={inputId}
onMouseDown={this.onLabelPointerDown}
onMouseDown={this.onLabelMouseDown}
onClick={this.onLabelClick}
part="wrapper"
>
Expand Down
Loading
Loading