-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
65 lines (57 loc) · 1.78 KB
/
index.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
const dialog = require('./lib/dialog')
const popup = require('./lib/popup')
const params = require('./lib/params')
const types = {popup, dialog}
function Dialox(controller, pending) {
this.pending = pending
this.controller = controller[1]
}
Dialox.prototype.close = function() {
return this.controller.close(), this
}
Dialox.prototype.navigate = function(location) {
return this.controller.navigate(location), this
}
Dialox.prototype.then = function then(cb, eb) {
return this.pending.then(cb, eb)
}
Dialox.prototype.catch = function thenCatch(eb) {
return this.then(null, eb)
}
module.exports = function dialox(url='', data={}, options={}) {
if(typeof url === 'object') {
return function configured(curl, options) {
return dialox(curl, options, url)
}
}
var callback = options.callback || location.origin
var open = types[options.type] || ('ontouchstart' in window ? popup : dialog)
var [domain, search] = url.split('?')
var query = params(data) + (search?('&'+params(params(search))):'')
var ctrl = open(domain + '?' + query, options)
var pending = new Promise((resolve, reject) => {
var modal = options.type || ctrl[0]
requestAnimationFrame(function poll() {
if(modal.closed) {
return reject(new Error('Window was closed.'))
}
try {
var href = modal.location.href
if(href && href.indexOf(callback) > -1) {
var data = params(modal.location.search.slice(1))
if(data.error) {
reject(Object.assign(new Error(data.error), data))
} else {
resolve(data)
}
if(!options.type) ctrl[1].close()
}
} catch(error) {
/* noop */
} finally {
requestAnimationFrame(poll)
}
})
})
return new Dialox(ctrl, pending)
}