Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: mask and separator #125

Merged
merged 4 commits into from
Jan 19, 2022
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
45 changes: 24 additions & 21 deletions packages/library/components/inputter/src/inputter-component.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { html, MuonElement, classMap } from '@muons/library';
import { html, MuonElement, classMap, styleMap, ifDefined } from '@muons/library';
import {
INPUTTER_TYPE
} from '@muons/library/build/tokens/es6/muon-tokens';
import { ValidationMixin } from '@muons/library/mixins/validation-mixin';
import { MaskSeparatorController } from '@muons/library/controllers/mask-separator-controller';
import { maskInput } from '@muons/library/directives/mask-input';
import styles from './styles.css';

/**
Expand Down Expand Up @@ -32,6 +34,15 @@ export class Inputter extends ValidationMixin(MuonElement) {

this.type = INPUTTER_TYPE;
this.isHelperOpen = false;
this.mask = '';
this.separator = '';
}

firstUpdated() {
super.firstUpdated();
if (ifDefined(this.mask)) {
this.addController(new MaskSeparatorController(this, this._slottedInputs[0]));
}
}

get validity() {
Expand All @@ -43,30 +54,22 @@ export class Inputter extends ValidationMixin(MuonElement) {
get standardTemplate() {
const classes = {
'slotted-content': true,
'select-arrow': this._inputType === this._isSelect
'select-arrow': this._isSelect,
'has-mask': this.mask
};

let styles = {};
if (this.mask) {
styles = {
'--maxlength': this.mask.length
};
}
return html`
${this._labelTemplate}
<div class="${classMap(classes)}">
${this._isMultiple ? this._headingTemplate : this._labelTemplate}
<div class="${classMap(classes)}" style="${styleMap(styles)}">
${this._htmlFormElementTemplate}
${this.mask ? maskInput(this.mask, this.separator, this.value) : ``}
</div>
${this._validationMessageTemplate}
`;
}

render() {
// const hasError = this._error && !this.inputType === 'select' ? 'invalid' : ''; // @TODO: it is not an error
const classes = {
'input-holder': true,
'is-pristine': this.pristine,
'is-dirty': !this.pristine
};

return html`
<div class="${classMap(classes)}">
${super.render()}
</div>
`;
${this._validationMessageTemplate}`;
}
}
29 changes: 29 additions & 0 deletions packages/library/components/inputter/src/styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,33 @@

:host {
display: block;

& .has-mask {
position: relative;

& .input-mask,
& ::slotted(input) {
padding: 0.5rem 1rem;
margin: 0.75rem 0;
letter-spacing: 0.5rem;
max-width: calc((var(--maxlength) + 1) * 1rem);
}

& .input-mask {
display: inline-block;
position: absolute;
left: 0;
color: lightslategray;
white-space: pre;
z-index: -1;
text-align: start;
font-size: 1.5rem;
}

& ::slotted(input) {
background-color: transparent;
font-size: 1.25rem;
padding-right: 1.25rem;
}
}
}
14 changes: 11 additions & 3 deletions packages/library/components/inputter/story.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,17 @@ export const Standard = (args) => details.template(args, innerInputText);
Standard.args = { label: 'A label', value: 'this is a test', validation: '[&quot;isRequired&quot;,&quot;minLength(6)&quot;]' };

const choiceInputText = (args) => `
<h4 slot="heading">What is your heating source?</h4>
<p slot="tip-details">more about this</p>
<input type="${args.inputtype}" name="question" value="gas"></input>
<label for="gas">Gas</label>
<input type="${args.inputtype}" name="question" value="electricity"></input>
<label for="electricity">Electricity</label>
`;
export const Radio = (args) => details.template(args, choiceInputText);
Radio.args = { inputtype: 'radio', label: 'A label', value: '', validation: '[&quot;isRequired&quot;]' };
Radio.args = { inputtype: 'radio', label: 'A label', value: '', heading: 'What is your heating source?', validation: '[&quot;isRequired&quot;]' };

export const Checkbox = (args) => details.template(args, choiceInputText);
Checkbox.args = { inputtype: 'checkbox', label: 'A label', value: '', validation: '[&quot;isRequired&quot;]' };
Checkbox.args = { inputtype: 'checkbox', label: 'A label', value: '', heading: 'What is your heating source?', validation: '[&quot;isRequired&quot;]' };

const selectInputText = (args) => `
<label slot="label" for="select-input">${args.label}</label>
Expand All @@ -49,13 +48,22 @@ const textareaInputText = (args) => `
export const Textarea = (args) => details.template(args, textareaInputText);
Textarea.args = { label: 'A label', value: 'gas' };

export const Mask = (args) => details.template(args, innerInputText);
Mask.args = { label: 'A label', value: '', mask: '000000' };

export const Separator = (args) => details.template(args, innerInputText);
Separator.args = { label: 'A label', value: '', separator: '-', mask: ' - - ' };

const innerInputDate = (args) => `
<label slot="label">${args.label}</label>
<input type="text" value="${args.value}" />
`;
export const Date = (args) => details.template(args, innerInputDate);
Date.args = { label: 'A label', value: '', validation: '[&quot;isRequired&quot;,&quot;minDate(\'11/11/2021\')&quot;]' };

export const DateMask = (args) => details.template(args, innerInputDate);
DateMask.args = { label: 'A label', value: '', mask: 'dd/mm/yyyy', separator: '/', validation: '[&quot;isRequired&quot;,&quot;minDate(\'11/11/2021\')&quot;]' };

const innerInputTel = (args) => `
<label slot="label">${args.label}</label>
<input type="tel" value="${args.value}" pattern="[0-9]{3}" title="match the pattern"/>
Expand Down
75 changes: 75 additions & 0 deletions packages/library/controllers/mask-separator-controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import { ifDefined } from '@muons/library';
export class MaskSeparatorController {

constructor(host, input) {
this.host = host;
this.mask = host.mask;
this.separator = host.separator;
this.input = input;
}

hostConnected() {
this.input.addEventListener('input', this.__onInput.bind(this));
this.input.setAttribute('maxlength', this.mask.length);
}

/**
* A method to handle `input` event when `mask` is provided.
* @param {Event} inputEvent - event while 'input.
* @returns {undefined}
*/
__onInput(inputEvent) {
inputEvent.stopPropagation();
inputEvent.preventDefault();
if (ifDefined(this.separator)) {
this.updateValue();
} else {
this.host.value = this.input.value;
}
}

updateValue() {
let value = this.input.value;
let cursor = this.input.selectionStart;
const diff = this.host.value.length - value.length;

if (diff > 0 && this.mask.charAt(cursor) === this.separator) {
value = value.slice(0, cursor - 1) + (cursor < value.length ? value.slice(cursor) : '');
cursor -= 1;
}
const formattedValue = this.formatWithMaskAndSeparator(value);
this.input.value = formattedValue;
this.host.value = formattedValue;

if (this.mask.charAt(cursor) === this.separator) {
cursor += 1;
}
this.host.updateComplete.then(() => {
this.input.setSelectionRange(cursor, cursor);
});
}

formatWithMaskAndSeparator(value) {
const formattedValue = this.__formatInputWithoutSeparator(value);
const parts = this.mask.split(this.separator);
let processedValue = '';
let length = 0;
let partsLength = 0;
for (let i = 0; i < parts.length && length < formattedValue.length; i++) {
partsLength += parts[i].length;
const remainingLength = formattedValue.length - length;
processedValue += formattedValue.substr(
length, remainingLength > parts[i].length ? parts[i].length : remainingLength);
length += parts[i].length;
if (i < (parts.length - 1) && processedValue.length === partsLength) {
processedValue += this.separator;
partsLength += 1;
}
}
return processedValue;
}

__formatInputWithoutSeparator(value) {
return value.split(this.separator).join('');
}
}
22 changes: 22 additions & 0 deletions packages/library/directives/mask-input.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { Directive, directive, html } from '@muons/library';

class MaskInputDirective extends Directive {

constructor(partInfo) {
super(partInfo);
}

render(mask, separator, value) {
let length = value ? value.length : 0;
let updatedMask = new Array(length + 1).join(' ');
if (separator && mask.charAt(length) === separator) {
updatedMask += ' ';
length += 1;
}
updatedMask += mask.slice(length);
return html`<div aria-hidden="true" class="input-mask">${updatedMask}</div>`;
}

}

export const maskInput = directive(MaskInputDirective);
1 change: 1 addition & 0 deletions packages/library/mixins/form-element-mixin.js
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ export const FormElementMixin = (superClass) =>
}

firstUpdated() {
super.firstUpdated();
this._slottedInputs.map((input) => {
input.addEventListener('change', this._onChange.bind(this));
input.addEventListener('blur', this._onBlur.bind(this));
Expand Down
2 changes: 1 addition & 1 deletion packages/library/mixins/validation-mixin.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ export const ValidationMixin = (superClass) =>
this.disableNative = false;
this.showMessage = true;
this._pristine = true;
this._validationState = {};
this._validationState = [];
this._customValidation = {};
}

Expand Down
90 changes: 90 additions & 0 deletions packages/library/tests/components/inputter/inputter.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
/* eslint-disable no-undef */
import { expect, fixture, html, defineCE, unsafeStatic } from '@open-wc/testing';
import { Inputter } from '@muons/library/components/inputter';
import { defaultChecks, fillIn } from '../../helpers';

const tagName = defineCE(Inputter);
const tag = unsafeStatic(tagName);

describe('Inputter', () => {

describe('mask', async () => {
let inputter;
let shadowRoot;
let maskedInput;
let inputElement;
before(async () => {
inputter = await fixture(html`
<${tag} mask="00000">
<label slot="label">input label</label>
<input type="text" value=""/>
</${tag}>`);
shadowRoot = inputter.shadowRoot;
maskedInput = shadowRoot.querySelector('.input-mask');
inputElement = inputter.querySelector('input');
});

it('default checks', async () => {
await defaultChecks(inputter);
});

it('masked input check', async () => {
expect(maskedInput).to.be.not.null; // eslint-disable-line no-unused-expressions
expect(maskedInput.textContent).to.be.equal('00000', '`input-mask` has correct value');
});

it('input value `1`', async () => {
await fillIn(inputElement, '1', 'input');
maskedInput = shadowRoot.querySelector('.input-mask');
expect(inputter.value).to.be.equal('1', 'Inputter has correct value');
expect(maskedInput.textContent).to.be.equal(' 0000', '`input-mask` has correct value');
});

it('input value `12`', async () => {
await fillIn(inputElement, '12', 'input');
maskedInput = shadowRoot.querySelector('.input-mask');
expect(inputter.value).to.be.equal('12', 'Inputter has correct value');
expect(maskedInput.textContent).to.be.equal(' 000', '`input-mask` has correct value');
});
});

describe('mask separator', async () => {
let inputter;
let shadowRoot;
let maskedInput;
let inputElement;
before(async () => {
inputter = await fixture(html`
<${tag} mask="00-00-00" separator="-">
<label slot="label">input label</label>
<input type="text" value=""/>
</${tag}>`);
shadowRoot = inputter.shadowRoot;
maskedInput = shadowRoot.querySelector('.input-mask');
inputElement = inputter.querySelector('input');
});

it('default checks', async () => {
await defaultChecks(inputter);
});

it('masked input check', async () => {
expect(maskedInput).to.be.not.null; // eslint-disable-line no-unused-expressions
expect(maskedInput.textContent).to.be.equal('00-00-00', '`input-mask` has correct value');
});

it('input value `1`', async () => {
await fillIn(inputElement, '1', 'input');
maskedInput = inputter.shadowRoot.querySelector('.input-mask');
expect(inputter.value).to.be.equal('1', 'Inputter has correct value');
expect(maskedInput.textContent).to.be.equal(' 0-00-00', '`input-mask` has correct value');
});

it('input value `12`', async () => {
await fillIn(inputElement, '12', 'input');
maskedInput = inputter.shadowRoot.querySelector('.input-mask');
expect(inputter.value).to.be.equal('12-', 'Inputter has correct value');
expect(maskedInput.textContent).to.be.equal(' 00-00', '`input-mask` has correct value');
});
});
});
33 changes: 33 additions & 0 deletions packages/library/tests/controllers/mask-separator.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/* eslint-disable no-undef */
import { expect } from '@open-wc/testing';
import { MaskSeparatorController } from '@muons/library/controllers/mask-separator-controller';

describe('mask-separator', async () => {
describe('mask ` - - `, separator `-`', async () => {
const host = {
mask: '00-00-00',
separator: '-'
};
const maskController = new MaskSeparatorController(host);

it('controller setup mask', async () => {
expect(maskController.mask).to.be.equal('00-00-00', 'controller has correct mask value');
});

it('controller setup seprator', async () => {
expect(maskController.separator).to.be.equal('-', 'controller has correct separator value');
});

it('update value', async () => {
expect(maskController.formatWithMaskAndSeparator('1')).to.be.equal('1', 'processed value has correct value');
});

it('update value without separator', async () => {
expect(maskController.formatWithMaskAndSeparator('12')).to.be.equal('12-', 'processed value has correct value');
});

it('update value with separator', async () => {
expect(maskController.formatWithMaskAndSeparator('1-23')).to.be.equal('12-3', 'processed value has correct value');
});
});
});
Loading