-
Notifications
You must be signed in to change notification settings - Fork 0
/
compatability.js
418 lines (389 loc) · 10.3 KB
/
compatability.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
/* Compatability layer to get scripts to work on
* more than just mozilla.
*/
// From: http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html
if(!globalThis.Node) {
globalThis.Node = {
ELEMENT_NODE : 1,
ATTRIBUTE_NODE : 2,
TEXT_NODE : 3,
CDATA_SECTION_NODE : 4,
ENTITY_REFERENCE_NODE : 5,
ENTITY_NODE : 6,
PROCESSING_INSTRUCTION_NODE : 7,
COMMENT_NODE : 8,
DOCUMENT_NODE : 9,
DOCUMENT_TYPE_NODE : 10,
DOCUMENT_FRAGMENT_NODE : 11,
NOTATION_NODE : 12,
}
}
/**
* Returns if event listeners can be added
*/
export function supportsEventListeners(element) {
if(element == null) element = this
return (
typeof(element.addEventListener) != 'undefined'
|| typeof(this.attachEvent) != 'undefined'
)
}
/**
* Returns if elements can be dynamically inserted
*/
export function supportsDynamicInsertion() {
return true
}
/**
* Adds a listener that fires on document loading
*/
export function addLoadListener(listener, onbubble) {
if(supportsEventListeners(this)) {
addListener(this, 'load', listener, onbubble)
} else if(supportsEventListeners(document)) {
addListener(document, 'load', listener, onbubble)
} else {
alert('Could not set up load listener')
}
}
/**
* Adds an event listener to a component
*/
export function addListener(element, event, listener, bubble) {
if(element.addEventListener) {
if(typeof(bubble) == 'undefined') bubble = false
element.addEventListener(event, listener, bubble)
} else if(this.attachEvent) {
element.attachEvent('on' + event, listener)
} else {
console.error(`Could not set up ${event} listener.`)
}
}
/**
* Remove an event listener from a component
*/
export function removeListener(element, event, listener, bubble = false) {
if(element.removeEventListener) {
element.removeEventListener(event, listener, bubble)
} else if(this.detachEvent) {
element.detachEvent(`on${event}`, listener)
} else {
console.error(`Could not remove \`${event}\` listener.`)
}
}
export const stylesheetAlerted = false
/**
* Add a new rule to the last stylesheet
*/
export function addStylesheetRule(selector, declarations, stylesheet) {
if(
stylesheet == null
&& typeof(document.styleSheets) != 'undefined'
) {
stylesheet = (
document.styleSheets[document.styleSheets.length - 1]
)
}
if(stylesheet != null) {
const rules = undefined
if(stylesheet.cssRules != null) {
rules = stylesheet.cssRules
} else if(stylesheet.rules != null) {
rules = stylesheet.rules
}
if(rules != null) {
if(stylesheet.insertRule != null) {
stylesheet.insertRule(
`${selector}{${declarations}}`,
rules.length,
)
} else if(stylesheet.addRule != null) {
stylesheet.addRule(selector, declarations)
}
return rules.at(-1).style
}
}
}
/**
* Add an option to a select
*/
export function addOption(text, parent) {
if(text) {
const option = document.createElement('option')
option.appendChild(document.createTextNode(text))
parent.appendChild(option)
}
}
export function createEvent(type, useBuiltIn = true) {
if(typeof(document.createEvent) != 'undefined' && useBuiltIn) {
return document.createEvent.apply(document, arguments)
} else {
const event = new Object()
event[`init${type.substring(0, type.length - 1)}`] = function() {
for(
let i = 0;
i < arguments.length && i < this.argNames.length;
i++
) {
this[this.argNames[i]] = arguments[i]
}
}
const baseArgs = ['type', 'bubbles', 'cancelable']
switch(type) {
case 'UIEvents': {
event.argNames = baseArgs.concat(['view', 'detail'])
break
}
case 'MouseEvents': {
event.argNames = baseArgs.concat([
'view', 'detail', 'screenX', 'screenY',
'clientX', 'clientY', 'ctrlKey', 'altKey',
'shiftKey', 'metaKey', 'button',
'relatedTarget'
])
break
}
case 'MutationEvents': {
event.argNames = baseArgs.concat([
'relatedNode', 'prevValue', 'newValue',
'attrName', 'attrChange'
])
break
}
default: {
event.argNames = baseArgs
}
}
return event
}
}
/**
* Get the source of an event
*/
export function getSource(event) {
if(event.target) {
return event.target
} else if(event.srcElement) {
return event.srcElement
}
console.error('Could not find event source.')
}
/**
* Keep an event from exhibiting its default behavior
*/
export function killEvent(event) {
if(event.preventDefault) {
event.preventDefault()
} else { // assume it is IE
event.returnValue = false
}
}
/**
* Get the form associated with a component that has received
* a submit event
*/
export function getForm(submission) {
// The event source may be the component that
// caused the submit or the whole form
if(submission.form) {
return submission.form
} else if(submission.tagName.toLowerCase() == 'form') {
return submission
}
console.error('Could not find form element.')
}
/**
* Print in dialogs the properties an object has
*/
export function printProperties(element, skipConstants) {
const lists = []
for(let property in element) {
if(skipConstants && property.match(/^[A-Z_0-9]*$/)) continue
const name = `element.${property}`
const value = element[property]
const type = typeof(value)
if(!lists[type]) lists[type] = `${type}s:`
lists[type] += '\n'
if(type == 'function') {
lists[type] += name
} else {
lists[type] += `${name} => ${value}`
}
}
console.info({ 'Object Properties': lists })
}
/**
* Empty a node
*/
export function clearNode(node) {
while(node.hasChildNodes()) {
node.removeChild(node.firstChild)
}
}
/**
* Append the elements in an array to an element
*/
export function copyTo(holder, contents) {
for(const content of Array.from(contents)) {
holder.appendChild(content)
}
}
/* Randomizes the elements of an array */
Array.prototype.randomize = function performFisherYates() {
let i = this.length
if(i > 0) {
while(--i > 0) {
const j = Math.floor(Math.random() * (i + 1))
const tempi = this[i]
const tempj = this[j]
this[i] = tempj
this[j] = tempi
}
}
}
export function nodeIsInDocument(node) {
return (
node != null
&& node.parentNode != null
&& node.parentNode.nodeType == Node.ELEMENT_NODE
)
}
export function setStyleProperty(element, property, value) {
if(element?.style == null) {
console.error(`Not Stylable: ${typeof(element)}:`, element)
} else {
if(element.style.setProperty) {
element.style.setProperty(property, value, null)
} else if(element.style.setAttribute) {
element.style.setAttribute(property, value)
} else {
element.style[property] = value
}
}
}
export function getCurrentStyle(element) {
if(element.currentStyle) {
return element.currentStyle
} else if(
document.defaultView
&& document.defaultView.getComputedStyle
) {
return document.defaultView.getComputedStyle(element, '')
}
}
export function setOpacity(element, opacity) {
if(element?.style?.opacity != null) {
element.style.opacity = opacity
} else if(element.style.filter) {
}
}
export function getXMLHttpRequest(callback) {
let request
if(typeof(XMLHttpRequest) !== 'undefined') {
request = new XMLHttpRequest()
} else if(window.ActiveXObject) {
const msxmlProgIds = [
'MSXML2.XMLHTTP.5.0',
'MSXML2.XMLHTTP.4.0',
'MSXML2.XMLHTTP.3.0',
'MSXML2.XMLHTTP',
'Microsoft.XMLHTTP',
]
for(const msxmlProgId of msxmlProgIds) {
try {
request = new ActiveXObject(msxmlProgid)
if(request) break
} catch(e) {}
}
}
if(request != null) {
setXMLHttpCallback(request, callback)
}
return request
}
export async function loadXMLDocument(url, callback) {
const res = await fetch(url)
const text = await res.text()
const doc = new DOMParser().parseFromString(text, 'text/xml')
callback?.call(callback, doc)
return doc
}
export function selectNodes(document, xpath, namespaceID, namespace) {
let nodes = null
try {
if(document.evaluate) {
let resolver = null
if(namespace) {
resolver = {
normalResolver: (
document.createNSResolver(document.documentElement)
),
lookupNamespaceURI(prefix) {
switch(prefix) {
case namespaceID: return namespace
default: return (
this.normalResolver.lookupNamespaceURI(prefix)
)
}
}
}
}
nodes = document.evaluate(
xpath, document, resolver,
XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null,
)
nodes.length = () => (nodes.snapshotLength)
nodes.item = (index) => (nodes.snapshotItem(index))
} else if(
document.documentElement
&& document.documentElement.selectNodes != null
) {
if(namespace) {
document.setProperty(
'SelectionNamespaces',
`xmlns:${namespaceID}='${namespace}'`
)
}
document.setProperty('SelectionLanguage', 'XPath')
nodes = document.documentElement.selectNodes(xpath)
} else {
console.error(
`Could not select XPath: ${xpath} on ${document}.`
)
}
} catch(e) {
console.error(`[${xpath}]: ${e.message}`)
}
return nodes
}
export function getCookie() {
const values = []
const cookieParts = document.cookie.split(/ +/g)
for(const part of cookieParts) {
const equalsIndex = part.indexOf('=')
if(equalsIndex > 0) {
const name = part.substring(0, equalsIndex)
values[name] = decodeURIComponent(
part.substring(equalsIndex + 1)
)
}
}
return values
}
export function setCookie(values, expiration) {
if(expiration == null) {
expiration = 1 // one day
}
if(values.expires == null) {
const expirationDate = new Date()
expirationDate.setTime(
expirationDate.getTime() + (expiration * 24 * 60 * 60 * 1000)
)
values.expires = expirationDate.toGMTString()
}
const cookieValue = ''
for(const key in values) {
cookieValue += `${key}=${encodeURIComponent(values[key])};`
}
document.cookie = cookieValue
}