houdini/client/js/common/form-to-object.js
Bradley M. Kuhn fc77ee76d6 Relicense Javascript code in accordance with project's new license
The primary license of the project is changing to:
  AGPL-3.0-or-later WITH Web-Template-Output-Additional-Permission-3.0-or-later

The Additional Permission is designed to permit publicly distributed
Javascript code to be relicensed under LGPL-3.0-or-later, but not server-side
Javascript code.  As such, we've relicensed here static Javscript files under
LGPL-3.0-or-later, and those that run as part of build and/or server side
under AGPL-3.0-or-later.

Note that in future, Javascript files may be updated to be stronger copyleft
license with the Additional Permission, particularly if they adapted to run
on server side and/or turned into templates.  Of course, we'd seek public
discussion with the contributor community about such changes.

This commit is one of the many steps to relicense the entire codebase.

Documentation granting permission for this relicensing (from all past
contributors who hold copyrights) is on file with Software Freedom
Conservancy, Inc.
2018-03-25 15:10:40 -04:00

44 lines
1.3 KiB
JavaScript

// License: LGPL-3.0-or-later
// Convert a form to an object literal
module.exports = function(form) {
if(form === undefined) throw new Error("form is undefined")
var result = {}
var fields = toArr(form.querySelectorAll('input, textarea, select'))
.filter(function(n) { return n.hasAttribute('name') })
.map(function(n) {
var name = n.getAttribute('name')
var keys = n.getAttribute('name').split('.')
if(n.value && n.value.toString().length) { // won't set empty strings for empty vals
if(n.getAttribute('type') === 'checkbox') {
deepSet(keys, n.checked, result)
} else if(n.getAttribute('type') === 'radio') {
if(n.checked) deepSet(keys, n.value, result)
} else {
deepSet(keys, n.value, result)
}
}
})
return result
}
function toArr(x) { return Array.prototype.slice.call(x) }
// Given an array of nested keys, a value, and a target object:
// Set the value into the object at the last nested key
function deepSet(keys, val, obj, options) {
var exceptLast = keys.slice(0, keys.length-1)
var last = keys[keys.length-1]
var nested = exceptLast.reduce(function(nestedObj, key) {
if(nestedObj[key] === undefined) {
nestedObj[key] = {}
return nestedObj[key]
} else {
return nestedObj[key]
}
}, obj)
// if(nested[last] === undefined) nested[last] = {}
nested[last] = val
return obj
}