Skip to content

Commit

Permalink
fix(core): add .select()-method support for MaskitoElement (#1268)
Browse files Browse the repository at this point in the history
  • Loading branch information
nsbarsukov authored May 21, 2024
1 parent 50c58ab commit 51f5934
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 1 deletion.
7 changes: 6 additions & 1 deletion projects/core/src/lib/types/maskito-element.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
export type TextfieldLike = Pick<
HTMLInputElement,
'maxLength' | 'selectionEnd' | 'selectionStart' | 'setSelectionRange' | 'value'
| 'maxLength'
| 'select'
| 'selectionEnd'
| 'selectionStart'
| 'setSelectionRange'
| 'value'
>;
export type MaskitoElement = HTMLElement & TextfieldLike;
4 changes: 4 additions & 0 deletions projects/core/src/lib/utils/content-editable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ class ContentEditableAdapter implements TextfieldLike {
public setSelectionRange(from: number | null, to: number | null): void {
setContentEditableSelection(this.element, [from || 0, to || 0]);
}

public select(): void {
this.setSelectionRange(0, this.value.length);
}
}

export function maskitoAdaptContentEditable(element: HTMLElement): MaskitoElement {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import {Component} from '@angular/core';
import {MaskitoDirective} from '@maskito/angular';
import type {MaskitoOptions} from '@maskito/core';
import {maskitoEventHandler} from '@maskito/kit';

@Component({
standalone: true,
imports: [MaskitoDirective],
template: `
<input
value="123"
[maskito]="maskitoOptions"
/>
<textarea [maskito]="maskitoOptions">123</textarea>
<div
contenteditable="true"
[maskito]="maskitoOptions"
[textContent]="'123'"
></div>
`,
})
export class TestComponent {
protected readonly maskitoOptions: MaskitoOptions = {
mask: /^\d+$/,
plugins: [
maskitoEventHandler('focus', element => element.select(), {once: true}),
],
};
}

describe('Native method `.select()` works', () => {
['input', 'textarea'].forEach(selector => {
it(`for <${selector} />`, () => {
cy.mount(TestComponent);
cy.get(selector)
.should('have.value', '123')
.should('have.prop', 'selectionStart', 0)
.should('have.prop', 'selectionEnd', 0)
.should('not.be.focused')
.focus()
.should('have.prop', 'selectionStart', 0)
.should('have.prop', 'selectionEnd', 3);
});
});

it('for [contenteditable]', () => {
cy.mount(TestComponent);
cy.get('[contenteditable]')
.should('have.text', '123')
.should('not.be.focused')
.focus()
.type('0') // all selected value will be overwritten
.should('have.text', '0')
.focus()
.type('2') // no selection (plugin works only for the first focus), just append value
.should('have.text', '02');
});
});

0 comments on commit 51f5934

Please sign in to comment.