2
0
mirror of https://github.com/tenrok/maska.git synced 2026-06-11 18:02:27 +03:00

New version code prepare

This commit is contained in:
Alexander Shabunevich
2022-12-04 16:50:18 +03:00
parent fadf78f5bb
commit 31c286bb6b
48 changed files with 15195 additions and 5502 deletions
+499
View File
@@ -0,0 +1,499 @@
# Live Demo
Here are several examples of basic masks that you could create with **Maska**.
This demo is interactive: feel free to edit the examples.
<div id="demo-app"></div>
<script src="dist/demo.js"></script>
# Install
<!-- tabs:start -->
## **Via npm**
```
npm i maska
```
## **From CDN**
To include library from CDN, use UMD format and prefix all classes and directives with `Maska.`
``` html
<script src="https://cdn.jsdelivr.net/npm/maska@latest/dist/maska.umd.js"></script>
<script>
new Maska.MaskInput("[data-maska]") // for masked input
const mask = new Maska.Mask({ mask: "#-#" }) // for programmatic use
</script>
```
<!-- tabs:end -->
# Usage
**Maska** library consists of three main components:
- `Mask` class to mask string values
- `MaskInput` class to apply `Mask` processing to `<input>`
- `vMaska` directive to simplify using of library within Vue components
<!-- tabs:start -->
## **Vanilla JS**
Start with simple input element and `data-maska` attribute:
``` html
<input data-maska="#-#">
```
Then import and init `MaskInput`, passing input element(s) or `querySelector` expression as first argument:
``` js
import { MaskInput } from "maska"
new MaskInput("[data-maska]")
```
Usually you set mask via `data-maska` attribute. But you can pass mask and other [options](#options) via second argument (it will be a default options that can be overriden by `data-maska-` attributes):
``` js
new MaskInput("input", { mask: "#-#" })
```
To destroy mask use `destroy()` method:
``` js
const mask = new MaskInput(...)
mask.destroy()
```
## **Vue**
Import `vMaska` directive and apply it to the input along with `data-maska` attribite:
<!-- tabs:start -->
### **Composition API**
``` html
<script setup>
import { vMaska } from "maska"
</script>
<template>
<input v-maska data-maska="#-#">
</template>
```
### **Options API**
``` html
<script>
import { vMaska } from "maska"
export default {
directives: { maska: vMaska }
}
</script>
<template>
<input v-maska data-maska="#-#">
</template>
```
<!-- tabs:end -->
### Set options with directive
To set default options for the mask you could use directive *argument* (part after `v-maska:`). It can be plain or reactive object and should be wrapped in `[]`:
<!-- tabs:start -->
### **Composition API**
``` html
<script setup>
import { reactive } from "vue"
import { vMaska } from "maska"
const options = reactive({
mask: "#-#",
eager: true
})
</script>
<template>
<input v-maska:[options]>
</template>
```
### **Options API**
``` html
<script>
import { vMaska } from "maska"
export default {
directives: { maska: vMaska },
data: () => ({
options: {
mask: "#-#",
eager: true
}
})
}
</script>
<template>
<input v-maska:[options]>
</template>
```
<!-- tabs:end -->
### Bind to variable
Its very easy to bind mask result to a variable.
This variable should be reactive object and will contains three fields:
- `masked`: string with masked result
- `unmasked`: string with unmasked result
- `completed`: boolean flag indicating that mask is completed
<!-- tabs:start -->
### **Composition API**
``` html
<script setup>
import { reactive } from "vue"
import { vMaska } from "maska"
const binded = reactive({})
</script>
<template>
<input v-maska="binded">
<p v-if="binded.completed">
Masked value: {{ binded.masked }}
Unmasked value: {{ binded.unmasked }}
</p>
</template>
```
### **Options API**
``` html
<script>
import { vMaska } from "maska"
export default {
directives: { maska: vMaska },
data: () => ({
binded: {
masked: "",
unmasked: "",
completed: false
}
})
}
</script>
<template>
<input v-maska="binded">
<p v-if="binded.completed">
Masked value: {{ binded.masked }}
Unmasked value: {{ binded.unmasked }}
</p>
</template>
```
<!-- tabs:end -->
#### Global registration of directive
<!-- tabs:start -->
### **Vue 3**
``` js
import { createApp } from "vue"
import { vMaska } from "maska"
createApp({}).directive("maska", vMaska)
// or in case of CDN load
Vue.createApp({}).directive("maska", Maska.vMaska)
```
### **Vue 2**
``` js
import Vue from "vue"
import { vMaska } from "maska"
Vue.directive("maska", vMaska)
// or in case of CDN load
Vue.directive("maska", Maska.vMaska)
```
<!-- tabs:end -->
<!-- tabs:end -->
# Options
## `Mask` options
Every option of `Mask` class can be set via `data-maska-` attributes or by passing on init.
Options passed on init will be used as defaults and could be overriden by `data-maska-` attributes.
<!-- tabs:start -->
### **Description**
- `mask` / `data-maska` — mask to apply (**string**, **array of strings** or **function**)
- `tokens` / `data-maska-tokens` — custom tokens object
- `tokensReplace` / `data-maska-tokens-replace` — if custom tokens should replace default tokens (if not set they will merge)
- `eager` / `data-maska-eager` — eager mode
- `reversed` / `data-maska-reversed` — reversed mode
### **Types**
``` js
interface MaskOptions {
mask?: MaskType
tokens?: MaskTokens
tokensReplace?: boolean
eager?: boolean
reversed?: boolean
}
```
<!-- tabs:end -->
``` html
<input data-maska="A-A" data-maska-tokens="A:[A-Z]" data-maska-eager>
```
## `MaskInput` options
`MaskInput` options could be set only by passing second argument on init.
Along with `MaskInput` options you could pass any `Mask` options as well (or set them via `data-maska-` attributes).
<!-- tabs:start -->
### **Description**
- `onMaska` — [callback](#events) on every mask processing
- `preProcess` — [hook](#hooks) before mask processing
- `postProcess` — [hook](#hooks) after mask processing
### **Types**
``` js
interface MaskInputOptions extends MaskOptions {
onMaska?: (detail: MaskaDetail) => void
preProcess?: (value: string) => string
postProcess?: (value: string) => string
}
```
<!-- tabs:end -->
``` js
new MaskInput("input", {
mask: "#-#",
reversed: true,
onMaska: (detail) => console.log(detail.completed)
})
```
# Tokens
There are 3 tokens defined by default:
``` js
{
'#': { pattern: /[0-9]/ }, // digits
'@': { pattern: /[a-zA-Z]/ }, // letters
'*': { pattern: /[a-zA-Z0-9]/ }, // letters & digits
}
```
?> Use `!` before token to escape symbol. For example `!#` will render `#` instead of a digit.
## Custom tokens
Add custom tokens via `data-maska-tokens` attribute or by `tokens` option:
<!-- tabs:start -->
### **By data-attr**
When using `data-maska-tokens`, there are two possible formats:
- **Full form** should be a valid JSON-string (but can use both single and double quotes) with pattern in string format without delimiters
- **Simple form** should be a string in format: `T:P:M|T:P:M` where:
- `T` is token
- `P` is pattern in string form
- `M` is optional modifier (see below)
- `|` is separator for multiple tokens
``` html
<input data-maska="Z-Z" data-maska-tokens="{ 'Z': { 'pattern': '[A-Z]' }}">
<input data-maska="Z-Z" data-maska-tokens="Z:[A-Z]">
<input data-maska="Z-z" data-maska-tokens="Z:[A-Z]|z:[a-z]:multiple">
```
?> You cant set `transform` function for token via `data-maska-tokens`.
If you need this, use `tokens` option instead.
### **By option**
When using `tokens` option, pattern should be a valid regular expression object:
``` js
new MaskInput("[data-maska]", {
mask: "A-A",
tokens: {
A: { pattern: /[A-Z]/, transform: (chr) => chr.toUpperCase() }
}
})
```
<!-- tabs:end -->
## Token modifiers
Every token can have a modifier, for example:
``` js
{
0: { pattern: /[0-9]/, optional: true },
9: { pattern: /[0-9]/, repeated: true },
}
```
- `optional` for optional token
- `multiple` for token that can match multiple characters till the next token starts
- `repeated` for tokens that should be repeated. This token will match only one character, but the token itself (or group of such tokens) can be repeated any number of times
| Modifier | Example usage | Mask | Tokens
| --- | --- | --- | ---
| `optional` | IP address | `#00.#00.#00.#00` | `0:[0-9]:optional`
| `multiple` | CARDHOLDER NAME | `A A` | `A:[A-Z]:multiple`
| `repeated` | Money (1 234,56) | `9 99#,##` <small>reversed</small> | `9:[0-9]:repeated`
## Transform tokens
For custom tokens you can define `transform` function, applied to a character before masking.
For example, transforming letters to uppercase on input:
``` js
{
A: { pattern: /[A-Z]/, transform: (chr) => chr.toUpperCase() }
}
```
?> You can also use [hooks](#hooks) for transforming whole value before/after masking.
# Dynamic masks
Pass `mask` as **array** or **function** to make it dynamic:
- With **array** a suitable mask will be chosen by length (smallest first)
- With **function** you can select mask with custom logic using value
``` js
new MaskInput("input", {
mask: (value) => value.startsWith('1') ? '#-#' : '##-##'
})
```
# Hooks
Use hooks for transforming whole value:
- `preProcess` hook called before mask processing
- `postProcess` hook called after mask processing, but before setting input's value
For example, you can use it to check for a maximum length of masked string:
``` js
new MaskInput("input", {
postProcess: (value) => value.slice(0, 5)
})
```
# Events
You can subscribe to `maska` event, fired every time when mask applied:
<!-- tabs:start -->
## **Vanilla JS**
``` js
document.querySelector("input").addEventListener("maska", onMaska)
```
## **Vue**
``` html
<input v-maska data-maska="#-#" @maska="onMaska" />
```
<!-- tabs:end -->
Callback will receive custom event contains `detail` property with given structure:
<!-- tabs:start -->
### **Description**
- `masked`: masked value
- `unmasked`: unmasked value
- `completed`: flag that current mask is completed
### **Types**
``` js
interface MaskaDetail {
masked: string
unmasked: string
completed: boolean
}
```
<!-- tabs:end -->
``` js
const onMaska = (event) => {
console.log({
masked: event.detail.masked,
unmasked: event.detail.unmasked,
completed: event.detail.completed
})
}
```
Alternatively, you can pass callback function directly with `MaskInput` option `onMaska`:
<!-- tabs:start -->
### **Vanilla JS**
``` js
new MaskInput("input", {
onMaska: (detail) => console.log(detail.completed)
})
```
### **Vue**
``` html
<script setup>
const options = {
onMaska: (detail) => console.log(detail.completed)
}
</script>
<template>
<input v-maska:[options]>
</template>
```
<!-- tabs:end -->
# Programmatic use
You can use mask function programmatically by importing `Mask` class.
There are three methods available:
- `masked(value)` returns masked version of given value
- `unmasked(value)` returns unmasked version of given value
- `completed(value)` returns `true` if given value makes mask complete
``` js
import { Mask } from "maska"
const mask = new Mask({ mask: "#-#" })
mask.masked("12") // = 1-2
mask.unmasked("12") // = 12
mask.completed("12") // = true
```
-200
View File
@@ -1,200 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Maska demo</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.5/css/bulma.min.css" integrity="sha256-vK3UTo/8wHbaUn+dTQD0X6dzidqc5l7gczvH+Bnowwk=" crossorigin="anonymous" />
<style>
body { background: #fafafa }
body > section > .container { max-width: 800px }
</style>
</head>
<body>
<section class="section">
<div class="container">
<div class="content">
<div class="is-pulled-right"><a href="https://github.com/beholdr/maska" class="button is-link is-medium">Github</a></div>
<h1 class="is-size-2 is-marginless">Maska demo</h1>
<h2 class="is-size-4">Vue.js examples</h2>
<div class="box">
<form id="vue-form">
<div class="field">
<label class="label">Phone with code: {{ phone }} (raw value: {{ phoneRaw }})</label>
<div class="control">
<input v-maska="['+1 (###) ##-##-##', '+1 (###) ###-##-##']" class="input" type="tel" autocomplete="tel" v-model="phone" @maska="phoneRaw = $event.target.dataset.maskRawValue">
</div>
<p class="help is-family-code">v-maska="['+1 (###) ##-##-##', '+1 (###) ###-##-##']"</p>
</div>
<div class="field">
<label class="label">Reactive mask: <input type="checkbox" v-model="dotFormat"> use dot as date separator?</label>
<div class="control">
<input v-maska="dateMask" class="input">
</div>
<p class="help is-family-code">v-maska="dateMask" — reactive mask by `dateMask` computed property</p>
</div>
<div class="field">
<label class="label">Hex color (custom tokens): {{ color }}</label>
<div class="control">
<input v-maska="{ mask: '!#HHHHHH', tokens: { 'H': { pattern: /[0-9a-fA-F]/, uppercase: true }}}" class="input" v-model="color">
</div>
<p class="help is-family-code">v-maska="{ mask: '!#HHHHHH', tokens: { 'H': { pattern: /[0-9a-fA-F]/, uppercase: true }}}"</p>
</div>
<div class="field">
<div class="field-body">
<div class="field">
<label class="label">Masked input:</label>
<div class="control">
<input v-maska="customMask" class="input">
</div>
</div>
<div class="field">
<label class="label">mask to apply:</label>
<div class="control">
<input class="input" v-model="customMask">
</div>
</div>
</div>
</div>
</form>
</div>
<h2 class="is-size-4">Vanilla JS examples</h2>
<div class="box">
<form id="vanilla-form">
<div class="columns">
<div class="column">
<div class="field">
<label class="label">Phone with code</label>
<div class="control">
<input data-mask="+1 (###) ###-####" class="masked input" type="tel" autocomplete="tel">
</div>
<p class="help is-family-code">data-mask="+1 (###) ###-####"</p>
</div>
<div class="field">
<label class="label">Cardholder name</label>
<div class="control">
<input data-mask="A* A*" class="masked input">
</div>
<p class="help is-family-code">data-mask="A* A*"</p>
</div>
<div class="field">
<label class="label">Leet speak (tokens with transform)</label>
<div class="control">
<input data-mask="T*" class="transform-masked input">
</div>
<p class="help is-family-code">data-mask="T*"</p>
</div>
<div class="field">
<label class="label">All digits</label>
<div class="control">
<input data-mask="#*" class="masked input">
</div>
<p class="help is-family-code">data-mask="#*"</p>
</div>
<div class="field">
<label class="label">Dynamic mask</label>
<div class="control">
<input data-mask='["# cm", "#.# cm", "#.## cm"]' class="masked input">
</div>
<p class="help is-family-code">data-mask='["# cm", "#.# cm", "#.## cm"]'</p>
</div>
</div>
<div class="column">
<div class="field">
<label class="label">Date</label>
<div class="control">
<input data-mask="##/##/####" class="masked input">
</div>
<p class="help is-family-code">data-mask="##/##/####"</p>
</div>
<div class="field">
<label class="label">Credit card</label>
<div class="control">
<input data-mask="#### #### #### ####" class="masked input">
</div>
<p class="help is-family-code">data-mask="#### #### #### ####"</p>
</div>
<div class="field">
<label class="label">Hex color (custom tokens)</label>
<div class="control">
<input data-mask="!#HHHHHH" class="custom-masked input">
</div>
<p class="help is-family-code">data-mask="!#HHHHHH"</p>
</div>
<div class="field">
<label class="label">Without mask (destroyed)</label>
<div class="control">
<input data-mask="###" class="unmasked input">
</div>
<p class="help is-family-code">data-mask="###"</p>
</div>
<div class="field">
<label class="label">CPF/CNPJ</label>
<div class="control">
<input data-mask='["###.###.###-##", "##.###.###/####-##"]' class="masked input">
</div>
<p class="help is-family-code">data-mask='["###.###.###-##", "##.###.###/####-##"]'</p>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</section>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/maska@1.5.1/dist/maska.js"></script>
<script>
// vue
new Vue({
el: '#vue-form',
data: {
phone: '19992345678',
phoneRaw: '',
dotFormat: false,
color: null,
customMask: '#*'
},
computed: {
dateMask: function() {
return this.dotFormat ? '##.##.####' : '##/##/####'
}
}
});
function leetSpeak(char) {
const letters = Object.entries({
'a': '4', 'b': '8', 'e': '3', 'f': 'ph', 'g': '9', 'i': '1', 'o': '0', 's': '5', 't': '7'
}).reduce((acc, [from, to]) => {
acc[from] = to
acc[from.toLocaleUpperCase()] = to
return acc
}, {})
return letters[char] ? letters[char] : char
}
// vanilla default
Maska.create('#vanilla-form .masked');
// vanilla custom tokens
Maska.create('#vanilla-form .custom-masked', {
tokens: { 'H': { pattern: '[0-9a-fA-F]', uppercase: true }}
});
Maska.create('#vanilla-form .transform-masked', {
tokens: { 'T': { pattern: '[ 0-9a-zA-Z]', transform: leetSpeak }}
});
// vanilla destroy
var mask = Maska.create('#vanilla-form .unmasked');
mask.destroy();
</script>
</body>
</html>
+57
View File
@@ -0,0 +1,57 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1.0, shrink-to-fit=no, viewport-fit=cover">
<title>maska docs</title>
<link rel="icon" href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 128 128%22><text y=%220.9em%22 font-size=%22128%22>*️⃣</text></svg>">
<!-- Themes (light + dark) -->
<link rel="stylesheet" media="(prefers-color-scheme: dark)" href="https://cdn.jsdelivr.net/npm/docsify-themeable@0/dist/css/theme-simple-dark.css">
<link rel="stylesheet" media="(prefers-color-scheme: light)" href="https://cdn.jsdelivr.net/npm/docsify-themeable@0/dist/css/theme-simple.css">
<link rel="stylesheet" href="dist/demo.css">
<style>
:root {
--theme-hue: 42;
--heading-h1-font-size: var(--modular-scale-3);
--heading-h2-font-size: var(--modular-scale-2);
--heading-h3-font-size: var(--modular-scale-1);
}
.sidebar > .app-name {
font-weight: 500;
}
@media screen and (max-width: 500px) {
.markdown-section {
padding-left: 16px;
padding-right: 16px;
}
}
</style>
</head>
<body>
<div id="app"></div>
<script>
window.$docsify = {
name: 'maska',
repo: 'beholdr/maska',
maxLevel: 2
}
</script>
<!-- Required -->
<script src="https://cdn.jsdelivr.net/npm/docsify@4/lib/docsify.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/docsify-themeable@0/dist/js/docsify-themeable.min.js"></script>
<!-- Recommended -->
<script src="https://cdn.jsdelivr.net/npm/docsify@4/lib/plugins/search.js"></script>
<script src="https://cdn.jsdelivr.net/npm/docsify-tabs@1"></script>
<script src="https://cdn.jsdelivr.net/npm/docsify-copy-code@2"></script>
<script src="https://cdn.jsdelivr.net/npm/docsify/lib/plugins/external-script.min.js"></script>
</body>
</html>