Skip to content

Commit

Permalink
Fix hx-vals/hx-vars encoding along json-enc (bigskysoftware#57)
Browse files Browse the repository at this point in the history
* Fix hx-vals/hx-vars encoding along json-enc #2735

* Collapse value assignment
  • Loading branch information
Telroshan committed Jul 22, 2024
1 parent ee4bbe5 commit 594a21a
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 10 deletions.
36 changes: 26 additions & 10 deletions src/json-enc/json-enc.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,28 @@
htmx.defineExtension('json-enc', {
onEvent: function(name, evt) {
if (name === 'htmx:configRequest') {
evt.detail.headers['Content-Type'] = 'application/json'
(function() {
let api
htmx.defineExtension('json-enc', {
init: function(apiRef) {
api = apiRef
},

onEvent: function(name, evt) {
if (name === 'htmx:configRequest') {
evt.detail.headers['Content-Type'] = 'application/json'
}
},

encodeParameters: function(xhr, parameters, elt) {
xhr.overrideMimeType('text/json')

const vals = api.getExpressionVars(elt)
const object = {}
parameters.forEach(function(value, key) {
// FormData encodes values as strings, restore hx-vals/hx-vars with their initial types
object[key] = Object.hasOwn(vals, key) ? vals[key] : value
})

return (JSON.stringify(object))
}
},
})

encodeParameters: function(xhr, parameters, elt) {
xhr.overrideMimeType('text/json')
return (JSON.stringify(parameters))
}
})
})()
19 changes: 19 additions & 0 deletions src/json-enc/test/ext/json-enc.js
Original file line number Diff line number Diff line change
Expand Up @@ -135,4 +135,23 @@ describe('json-enc extension', function() {
this.server.lastRequest.response.should.equal('{"passwordok":true}')
htmx.config.methodsThatUseUrlParams = defaults
})

it('handles hx-vals properly', function() {
var values = {}
this.server.respondWith('POST', '/test', function(xhr) {
values = JSON.parse(xhr.requestBody)
xhr.respond(200, {}, 'clicked')
})

make(`<form hx-ext="json-enc" hx-post="/test" hx-vals="js:{'obj': {'x': 123}, 'number': 5000, 'numberString': '5000'}">
<button id="btn" type="submit">Submit</button>
</form>`)
var btn = byId('btn')
btn.click()
this.server.respond()

values.number.should.equal(5000)
values.numberString.should.equal('5000')
chai.assert.deepEqual(values.obj, {'x': 123})
})
})

0 comments on commit 594a21a

Please sign in to comment.