-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathotty.js
526 lines (476 loc) · 15.2 KB
/
otty.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
import morphdom from 'morphdom'
export default {
init(isDev, afterDive, csrfSelector, csrfHeader){
return {isDev, afterDive, csrfSelector, csrfHeader, ...this}
},
obj_to_fd(formInfo, formData) {
if(formInfo instanceof FormData) {
return formInfo
} else {
//get good 🦄
let recursed = (formData, key, item) => {
let key2, item2
if(Array.isArray(item)) {
for(key2 in item) {
item2 = item[key2]
recursed(formData, key + "[]", item2)
}
}
else if(typeof item === 'object') {
for(key2 in item) {
item2 = item[key2]
recursed(formData, key + "[" + key2 + "]", item2)
}
} else {
formData.append(key, item)
}
}
if(!formData){
formData = new FormData();
}
let key;
for(key in formInfo){
let item = formInfo[key]
recursed(formData, key, item)
}
return formData
}
},
_sendsXHROnLoad(resolve, reject, xhr, responseType){
if(xhr.status >= 200 && xhr.status <= 302 && xhr.status != 300) {
let rsp = xhr.response
if(responseType == 'json'){
try { rsp = JSON.parse(rsp) } catch {}
}
resolve({response: rsp, xhr: xhr})
// get xhr.json for the json.
} else {
reject({status: xhr.status, statusText: xhr.statusText});
}
},
_sendsXHROnError(resolve, reject, xhr){
reject({
status: xhr.status,
statusText: xhr.statusText
});
},
sendsXHR({url, formInfo, method = "POST", xhrChangeF,
csrfContent, csrfHeader = this.csrfHeader,
csrfSelector = this.csrfSelector,
confirm, withCredentials = true, responseType="json",
onload = this._sendsXHROnLoad, onerror = this._sendsXHROnError}){
if(!csrfContent){
csrfContent = document.querySelector(csrfSelector).content
}
return new Promise(function(resolve, reject) {
var xhr, form_data;
xhr = new XMLHttpRequest();
xhr.withCredentials = withCredentials
xhr.open(method, url)
xhr.responseType=responseType
xhr.onload = onload.bind(this, resolve, reject, xhr, responseType)
xhr.onerror = onerror.bind(this, resolve, reject, xhr)
//get formInfo into the form_data
form_data = this.obj_to_fd(formInfo)
xhr.setRequestHeader(csrfHeader, csrfContent)
//helper so we know where this came from. Super useful when for example, checking
//if someones signed in, and figuring out how to notify them that they are not
//redirect back with a flash? Or just morph a message up?
xhr.setRequestHeader('Otty', 'true')
//add a file or something if you want go nuts
if(xhrChangeF) {
xhr = xhrChangeF(xhr)
}
if(confirm) {
confirm = confirm(confirm)
if(confirm) {
xhr.send(form_data)
} else {
resolve({'returning': 'user rejected confirm prompt'})
}
} else {
xhr.send(form_data)
}
}.bind(this))
},
xss_pass(url){
return this.isLocalUrl(url, -2)
},
dive(opts = {}){
//divewire can be a security risk as its so dynamic, so make sure we are only connecting with ourselves...
let url = opts.url
let baseElement = opts.baseElement
let submitter = opts.submitter
if(opts.e != null) {
if(baseElement == null) {
baseElement = opts.e.currentTarget
}
if(submitter == null) {
submitter = opts.e.submitter
}
}
if(!this.xss_pass(url)){ throw url + " is not a local_url" }
let handle_response = ((actions, resolve, reject) => {
let y, ottys_capabilities, task, data, out, returning, dive_id, action
returning = actions
if(!Array.isArray(actions)) {
actions = [actions]
}
y = 0
ottys_capabilities = this.afterDive.init(baseElement, submitter, resolve, reject, this.isDev)
for(action of actions) {
if(!action){continue}
//make sure we have not already processed this dive (matters with polling)
dive_id = action.dive_id
if(dive_id) {
if( this.previousDives.includes(dive_id) ) {
continue;
}
this.previousDives.push(dive_id)
delete action.dive_id
}
//get ottys task
task = Object.keys(action)[0]
data = action[task]
if(task == 'eval'){task = 'eval2'}
if(this.isDev){ console.log(task, data) }
if(task == 'returning') {
returning = data
} else {
try {
out = ottys_capabilities[task](data)
} catch(err) {
if(this.isDev){
console.log(task, data, err, err.message)
}
}
if(out == "break"){
break
}
}
}
resolve(returning)
}).bind(this)
return new Promise(function(resolve, reject) {
this.sendsXHR(opts).then((obj) => {
handle_response(obj.response, resolve, reject)
}).catch((e) => {
reject(e)
})
}.bind(this))
},
//this will default to replacing body if this css selector naught found.
async stopGoto(href){
if(!this.handlingNavigation){
//handle use case where person does not want spa, which, after headaches, fair enough.
//as linkclickedf was never activated, this should only happen through afterDive
window.location.href = href
return true
}
//Check scroll to hash on same page
let loc = window.location
href = new URL(href, loc)
//hashes
if(loc.origin == href.origin && href.pathname == loc.pathname){
return await this.scrollToLocationHashElement(href)
}
//I wanted my subdomains to be counted too... apparently not possible...
if(loc.origin != href.origin){
window.location.href = href
return true
}
return false
},
isLocalUrl(url, subdomainAccuracy = -2){
//local includes subdomains. So if we are on x.com, x.com will work and y.x.com will work, but y.com wont.
//change the -2 to -3, -4 etc to modify. Times where this may be an issue:
// - if you share domains with untrusted partys.
let d = window.location.hostname
let urld = (new URL(url, window.location)).hostname //url_with_default_host
let opt1 = d.split('.').slice(subdomainAccuracy).join('.')
let opt2 = urld.split('.').slice(subdomainAccuracy).join('.')
return (opt1 == opt2)
},
async linkClickedF(e) {
let href = e.target.closest('[href]')
if(!href){ return }
if(href.dataset.nativeHref != undefined){return}
href = href.getAttribute('href')
if(!this.isLocalUrl(href, -99)){
return
}
//prevent default if we do not handle
//cancel their thing
e.preventDefault()
e.stopPropagation()
await this.goto(href)
return
},
async scrollToLocationHashElement(loc){
if(!loc.hash){ return false }
let e = document.getElementById(decodeURIComponent(loc.hash.slice(1)))
if(!e){ return false }
await this.waitForImages()
e.scrollIntoView()
return true
},
async goto(href, opts = {}){
if(await this.stopGoto(href)){ return -1 }
opts = {reload: false, ...opts}
let loc = window.location
href = new URL(href, loc)
//start getting the new info
let prom = this.sendsXHR({
url: href,
method: "GET",
responseType: "text", //<- dont try to json parse results
xhrChangeF: (xhr) => { xhr.setRequestHeader('Otty-Nav', 'true'); return xhr } //<- header so server knows regular GET vs other otty requests
})
//get and replace page
prom = await prom
let page = prom.response, xhr = prom.xhr
//in case of redirect...
if(xhr.responseURL){
let nhref = new URL(xhr.responseURL)
nhref.hash = href.hash
href = nhref
}
//replace page , starting at the top of the page. Update page state for where we were before the switch.
//Note it is important to store the replacement html after removal to allow for things such as onRemoved
// to run before we store.
await this.pageReplace(page, 0, href, (BefBodyClone, befY) => {
this.replacePageState(loc, BefBodyClone, befY)
if(!(opts.reload)){
//store the new page information.
this.pushPageState(href, undefined)
}
}, loc)
return href
},
createStorageDoc(orienter, head){
if(!Array.isArray(orienter)){ orienter = [orienter]}
orienter = orienter.map( (x) => x.cloneNode(true) )
let storeDoc = (new DOMParser()).parseFromString('<!DOCTYPE HTML> <html></html>', 'text/html')
if(orienter.length == 1 && orienter[0].nodeName == "BODY"){
storeDoc.body = orienter[0]
} else {
for(let o of orienter){storeDoc.body.appendChild(o)}
}
morphdom(storeDoc.head, head.cloneNode(true))
return storeDoc
},
navigationHeadMorph(tempdocHead){
// this is what my custom otty looks like after I hit an edge case where an external
//library was adding to my head but then it would get reset on nav:
//
// morphdom(document.head, tempdocHead, this.afterDive._morphOpts({permanent: '[href*="google"], [src*="google"], [id*="google"]'}))
morphdom(document.head, tempdocHead)
},
navigationBodyChange(orienter, tmpOrienter) {
let x = 0
while(x < orienter.length){
if(orienter[x].nodeName == "BODY"){
orienter[x].innerHTML = tmpOrienter[x].innerHTML
//javascript wise, its useful for the body's attributes to remain the same.
//css wise, its a headache. So pass the class and style, but not the rest.
orienter[x].setAttribute('class', (tmpOrienter[x].getAttribute('class') || ''))
orienter[x].setAttribute('style', (tmpOrienter[x].getAttribute('style') || ''))
} else {
orienter[x].replaceWith(tmpOrienter[x])
}
x += 1
}
},
getOrienters(tempdoc, url, lastUrl, ){
//this method may be overrode for more functionality.
//Orienters can be an array, and they will still store properly.
//This can allow you to fine tune page updates. For example, changing the notifications
//and a post's contents without changing the layout. Or switching in an email without changing the rest of the page.
//This also necessitates changing navigationBodyChange to deal with it.
let newOrienters, orienters, replaceSelector, fail, a, b
for(replaceSelector of this.navigationReplaces){
if(!Array.isArray(replaceSelector)){ replaceSelector = [replaceSelector]}
fail = false; orienters = []; newOrienters = []
for(let s of replaceSelector){
a = document.querySelector(s)
if(!a){fail = true; break}
b = tempdoc.querySelector(s)
if(!b){fail=true; break}
orienters.push(a); newOrienters.push(b)
}
if(!fail){
return [orienters, newOrienters]
}
}
},
async pageReplace(tempdoc, scroll, url, beforeReplace, lastUrl){
let befY = window.scrollY
//standardize tempdoc (accept strings)
if(typeof tempdoc == "string") {
tempdoc = (new DOMParser()).parseFromString(tempdoc, "text/html")
}
let orienters, newOrienters
[orienters, newOrienters] = this.getOrienters(tempdoc, url, lastUrl)
//been having issues with the removed thing triggering as the observer is on the body which we are removing.
// if(orienters[0].nodeName == "BODY"){
// for(let unitEl of this.qsInclusive(orienters[0], '[data-unit]')){
// this.stopError( () => unitEl._unit?.unitRemoved() )
// }
// }
//set stored information for recreating current page
let storeDoc = this.createStorageDoc(orienters, document.head)
//placement of this is important since we need to change the url and state after killing all the previous units
//but before creating all the new units and event handles. For instance, this breaks _parse->dive[{"behavior": "repeat"}] since
//the thing quick cancels since it thinks it left the page lol.
if(beforeReplace){beforeReplace(storeDoc, befY)}
// orienter.replaceChildren(...tmpOrienter.children)
this.navigationBodyChange(orienters, newOrienters)
//morph the head to the new head. Throw into a different function for
//any strangeness that one may encounter and
this.navigationHeadMorph(tempdoc.querySelector('head'))
let shouldScrollToEl = (url && (!scroll))
//handle scrolling
let scrolled = false
if(shouldScrollToEl){
scrolled = await this.scrollToLocationHashElement(url)
}
if(!scrolled){
if(scroll != 0){await this.waitForImages()}
window.scroll(0, scroll)
}
},
async waitForImages(){
let arr = Array.from(document.body.querySelectorAll('img')).map((im)=>{
new Promise((resolve) => {
im.addEventListener('load', resolve)
if(im.complete){resolve()}
})
})
for(let a of arr){await a}
return true
},
stopError(f){
try{
f()
} catch(e) {
otty.log(e)
}
},
_pageState(scroll, doc, url){
this.historyReferences[this.historyReferenceId] = {
doc: doc,
scroll: scroll,
url: url,
tn: (new Date()).getTime()
}
},
replacePageState(url, doc, scroll){
window.history.replaceState({
historyReferenceId: (this.historyReferenceId),
}, "", url);
this._pageState(scroll, doc, url)
},
pushPageState(url, doc){
window.history.pushState({
historyReferenceId: (this.historyReferenceId = Math.random()),
}, "", url)
this._pageState(0, doc, url)
},
qsInclusive(n, pat){
let units = Array.from(n.querySelectorAll(pat))
if(n.matches(pat)){units.push(n)}
return units
},
handleNavigation(opts = {}){
opts = {navigationReplaces: ['body'], ...opts}
this.navigationReplaces = opts.navigationReplaces
this.historyReferenceId = Math.random()
this.historyReferences = {}
this.handlingNavigation = true
history.scrollRestoration = 'manual'
document.addEventListener('click', this.linkClickedF.bind(this))
window.addEventListener('popstate', (async function (e){
if(e.state && ( e.state.historyReferenceId != undefined)){
let lastInf = this.historyReferences[this.historyReferenceId]
let hr = this.historyReferences[( this.historyReferenceId = e.state.historyReferenceId )]
if(hr){
await this.pageReplace(hr.doc, hr.scroll, hr.url, (strDoc, befY) => {
lastInf.scroll = befY
lastInf.doc = strDoc
}, lastInf.url)
} else {
//if they refresh and hit the back button or something it can make things difficult
//especially since we still get the state information (thats where the e.state.match comes forward.)
this.historyReferenceId = Math.random()
this.goto(window.location, {reload: true})
}
}
}).bind(this))
//do not rely on eachother
// this.updatePageState(window.location, {push: false})
this.scrollToLocationHashElement(window.location)
},
previousDives: [],
poll(dat){
if(this.ActivePollId != dat.id) { return }
let maybeResub = ((x)=>{
if(x == 'should_resub') {
this.subscribeToPoll(dat.queues, dat.pollInfo, dat.waitTime, dat.pollPath, dat.subPath)
} else if(x != "no_updates") {
dat.store = x
}
}).bind(this)
let continuePolling = (()=>{
let poll = (()=>{ this.poll(dat) }).bind(this)
setTimeout(poll, dat.waitTime)
}).bind(this)
let fi = {}
if(dat.store){fi = {'otty-store': dat.store}}
this.dive({
url: dat.pollPath,
formInfo: fi
}).then(maybeResub).finally(continuePolling)
},
subscribeToPoll(queues, pollInfo, waitTime, pollPath, subPath){
this.pollPath = pollPath
let id = Math.random()
this.ActivePollId = id
let dat = { queues, pollInfo, waitTime, id, pollPath, subPath }
let poll = ((out) => {
if(out == 'no_queues') {
if(this.isDev){console.log('no_queues', out)}
} else {
dat.store = out
this.poll(dat)
}
}).bind(this)
let err_log = ((x)=>{
if(this.isDev){console.error('sub fail', x)}
}).bind(this)
this.dive({
url: subPath,
formInfo: {
queues: dat.queues,
...dat.pollInfo
}
}).then(poll, err_log)
},
logData: [],
log: (data, isError) => {
let t = 'noTrace'
try {
t = new Error().stack
} catch{ }
if(isError){
console.error(data)
} else {
console.log(data)
}
otty.logData.push(JSON.stringify({
time: (new Date).getTime(),
loc: window.location.href,
stack: t,
data: data,
}))
}
}