From e078efd6954611457c62b91dc763441c0151373b Mon Sep 17 00:00:00 2001 From: Dan Wilson Date: Tue, 18 Apr 2023 14:00:50 -0600 Subject: [PATCH] allow custom escape character --- src/mask.ts | 15 ++++++++++++++- src/parser.ts | 3 ++- src/tokens.ts | 1 + test/mask-input.test.ts | 36 ++++++++++++++++++++++++++++++++++++ 4 files changed, 53 insertions(+), 2 deletions(-) diff --git a/src/mask.ts b/src/mask.ts index 49e1a82..7e2e4ce 100644 --- a/src/mask.ts +++ b/src/mask.ts @@ -96,6 +96,19 @@ export class Mask { ) } + private isEscape (ch: string) { + if (ch === '!' && !this.opts.tokensReplace) { + return true + } else { + for (let tokensKey in this.opts.tokens) { + if (tokensKey === ch && this.opts.tokens[tokensKey].escape) { + return true + } + } + } + return false; + } + private escapeMask (maskRaw: string): { mask: string escaped: number[] @@ -103,7 +116,7 @@ export class Mask { const chars: string[] = [] const escaped: number[] = [] maskRaw.split('').forEach((ch, i) => { - if (ch === '!' && maskRaw[i - 1] !== '!') { + if (this.isEscape(ch) && !this.isEscape(maskRaw[i - 1])) { escaped.push(i - escaped.length) } else { chars.push(ch) diff --git a/src/parser.ts b/src/parser.ts index 76f6e8e..50bff92 100644 --- a/src/parser.ts +++ b/src/parser.ts @@ -46,7 +46,8 @@ const parseTokens = (value: string): MaskTokens => { pattern: new RegExp(parts[1]), optional: parts[2] === 'optional', multiple: parts[2] === 'multiple', - repeated: parts[2] === 'repeated' + repeated: parts[2] === 'repeated', + escape: parts[2] === 'escape' } }) diff --git a/src/tokens.ts b/src/tokens.ts index 5644717..82a1f68 100644 --- a/src/tokens.ts +++ b/src/tokens.ts @@ -3,6 +3,7 @@ interface MaskToken { multiple?: boolean optional?: boolean repeated?: boolean + escape?: boolean transform?: (char: string) => string } diff --git a/test/mask-input.test.ts b/test/mask-input.test.ts index 1971729..27056b5 100644 --- a/test/mask-input.test.ts +++ b/test/mask-input.test.ts @@ -1449,6 +1449,42 @@ describe("Optional with multiple '-9' mask", () => { }) }) +describe("Custom escape with '$#!99' mask", () => { + beforeAll(() => { + input = prepareInput({ + mask: '$#!99', + tokens: { + '$': { pattern: /\$/, escape: true }, + '9': { pattern: /\d/, multiple: true } + }, + }) + }) + + afterEach(async () => { + await user.clear(input) + }) + + test('input { }', async () => { + await user.type(input, '{ }') + expect(input).toHaveValue('#9') + }) + + test('input 1', async () => { + await user.type(input, '1') + expect(input).toHaveValue('#91') + }) + + test('input 91', async () => { + await user.type(input, '91') + expect(input).toHaveValue('#91') + }) + + test('input 1234', async () => { + await user.type(input, '1234') + expect(input).toHaveValue('#91234') + }) +}) + describe('IP mask', () => { beforeAll(() => { input = prepareInput({