shrub/web/lib/js/easy-form.js

48 lines
1.3 KiB
JavaScript
Raw Normal View History

2017-12-19 03:30:45 +03:00
//REVIEW this feels too complicated
let match_url_end = (pattern,out={})=> {
if(!pattern) return out
let here = document.location.pathname.split("/").reverse()
while(!here[0]) here.shift()
for(let segment of pattern.split("/").reverse()){
let val = here.shift()
if(segment[0] != ":") continue //REVIEW check for match?
out[segment.slice(1)] = val
}
return out
}
//
window.easy_form = {
2017-12-19 01:33:20 +03:00
submit: (form)=> {
const param = (key)=> {
var x = form.elements[`easy_form:${key}`]
return x && x.value
}
2017-12-19 03:30:45 +03:00
let mark = param("mark")
2017-12-19 01:33:20 +03:00
if(!mark) throw new TypeError("Need a mark")
2017-12-19 03:30:45 +03:00
let appl = param("appl") || mark.match(/^[^-]*/)[0]
let tag = param("tag")
2017-12-19 01:33:20 +03:00
//
2017-12-19 01:55:49 +03:00
if(param("confirm") != null && !confirm("Are you sure?"))
return false
//
2017-12-19 03:30:45 +03:00
let req = {}
req = match_url_end(param("url_end"),req)
//
for (let [k,v] of new FormData(form)){
2017-12-19 01:33:20 +03:00
if(!/^easy_form:/.test(k)) {
req[k] = v
}
}
if(tag) req = {[tag]:req}
2017-12-19 01:33:20 +03:00
fetch("/~/auth.json", {credentials: "same-origin"})
.then((res)=>res.json())
.then(({oryx})=> fetch(`/~/to/${appl}/${mark}`,{
method: "POST",
body:JSON.stringify({oryx,wire:"/",xyro:req}),
credentials: "same-origin"
}))
return false
}
}