Skip to content

Commit

Permalink
🐛 Fixes issue with $mask not updating Models
Browse files Browse the repository at this point in the history
  • Loading branch information
ekwoka committed May 14, 2024
1 parent 986479d commit 401987f
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 4 deletions.
14 changes: 11 additions & 3 deletions packages/mask/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,15 @@ export default function (Alpine) {
}

// Override x-model's initial value...
if (el._x_model) el._x_model.set(el.value)
if (el._x_model) {
el._x_model.set(el.value)
const updater = el._x_forceModelUpdate;
el._x_forceModelUpdate = (value) => {
updater(value);
processInputValue(el, false, true);
el._x_model.set(el.value);
};
}
})

const controller = new AbortController()
Expand All @@ -60,7 +68,7 @@ export default function (Alpine) {
// will re-focus the input and cause a focus trap.
el.addEventListener('blur', () => processInputValue(el, false), { signal: controller.signal })

function processInputValue (el, shouldRestoreCursor = true) {
function processInputValue (el, shouldRestoreCursor = true, forceFormat = false) {
let input = el.value

let template = templateFn(input)
Expand All @@ -69,7 +77,7 @@ export default function (Alpine) {
if(!template || template === 'false') return false

// If they hit backspace, don't process input.
if (lastInputValue.length - el.value.length === 1) {
if (lastInputValue.length - el.value.length === 1 && !forceFormat) {
return lastInputValue = el.value
}

Expand Down
16 changes: 15 additions & 1 deletion tests/cypress/integration/plugins/mask.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ test('x-mask with x-model',
)

// This passes locally but fails in CI...
test.skip('x-mask with latently bound x-model',
test('x-mask with latently bound x-model',
[html`
<div x-data="{ value: '' }">
<input x-mask="(999) 999-9999" x-bind="{ 'x-model': 'value' }" id="1">
Expand Down Expand Up @@ -239,3 +239,17 @@ test('$money with custom decimal precision',
get('#3').type('1234.5678').should(haveValue('1,234.567'))
}
)

test('$mask should process the value when updated by x-model',
[html`
<div x-data="{value:55555}">
<input type="text" x-model=value x-mask:dynamic="$money($input)">
<button @click="value = 23420">Change</button>
</div>
`],
({ get }) => {
get('input').should(haveValue('55,555'))
get('button').click()
get('input').should(haveValue('23,420'))
}
)

0 comments on commit 401987f

Please sign in to comment.