-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhalfcab.mjs
More file actions
543 lines (469 loc) · 14.3 KB
/
halfcab.mjs
File metadata and controls
543 lines (469 loc) · 14.3 KB
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
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
import shiftyRouterModule from 'shifty-router'
import hrefModule from 'shifty-router/href.js'
import historyModule from 'shifty-router/history.js'
import createLocation from 'shifty-router/create-location.js'
import { html as litHtml, render } from 'lit'
import { unsafeHTML } from 'lit/directives/unsafe-html.js'
import { render as renderSSR } from '@lit-labs/ssr'
import { hydrate } from '@lit-labs/ssr-client'
import axios from 'axios'
import cssInject from 'csjs-inject'
import merge from 'deepmerge'
import marked from 'marked'
import { decode } from 'html-entities'
import eventEmitter from './eventEmitter/index.mjs'
import qs from 'qs'
let cssTag = cssInject
let componentCSSString = ''
let routesArray = []
let externalRoutes = []
let state = {}
let router
let rootEl
let components
let dataInitial
let el
marked.setOptions({
breaks: true
})
function b64DecodeUnicode (str) {
// Going backwards: from bytestream, to percent-encoding, to original string.
return decodeURIComponent(atob(str).split('').map(function (c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)
}).join(''))
}
if (typeof window !== 'undefined') {
dataInitial = document.querySelector('[data-initial]')
if (!!dataInitial) {
state = (dataInitial && dataInitial.dataset.initial) && Object.assign({}, JSON.parse(b64DecodeUnicode(dataInitial.dataset.initial)))
if (!state.router) {
state.router = {}
}
if (!state.router.pathname) {
Object.assign(state.router, {
pathname: window.location.pathname,
hash: window.location.hash,
query: qs.parse(window.location.search)
})
}
}
} else {
cssTag = (cssStrings, ...values) => {
let output = cssInject(cssStrings, ...values)
componentCSSString += componentCSSString.indexOf(output[' css ']) === -1 ? output[' css '] : ''
return output
}
}
let geb = new eventEmitter({state})
const stringsCache = new WeakMap()
let html = (strings, ...values) => {
// fix for allowing csjs to coexist with lit-html
values = values.map(value => {
if (value && value.hasOwnProperty('toString') && !value.hasOwnProperty('_$litType$')) {
// Check if it's a template result (lit-html object). If not, and has toString (like CSJS object), stringify it.
if (Array.isArray(value)) return value;
if (typeof value === 'object' && value !== null) {
if (value['_$litType$'] !== undefined) return value; // It's a TemplateResult
// CSJS object:
if (value.toString && value.toString !== Object.prototype.toString) {
return value.toString()
}
}
}
return value
})
// Conversion for onEvent=${fn} to @event=${fn}
let newStrings = stringsCache.get(strings)
if (!newStrings) {
const newRaw = strings.raw ? [...strings.raw] : [...strings]
const newVals = [...strings]
const onEventRegex = /on([a-zA-Z]+)=$/
for (let i = 0; i < newVals.length; i++) {
let match = newVals[i].match(onEventRegex)
if (match) {
const eventName = match[1]
const replacement = `@${eventName}=`
newVals[i] = newVals[i].replace(onEventRegex, replacement)
newRaw[i] = newRaw[i].replace(onEventRegex, replacement)
}
}
newStrings = newVals
newStrings.raw = newRaw
stringsCache.set(strings, newStrings)
}
return litHtml(newStrings, ...values)
}
// Detect if a container likely contains Lit SSR markers so hydration is safe
function canHydrateContainer (container) {
try {
if (!container || !container.hasChildNodes()) return false
// Walk comment nodes looking for lit markers inserted by @lit-labs/ssr
const walker = document.createTreeWalker(
container,
NodeFilter.SHOW_COMMENT,
null,
false
)
let n = walker.nextNode()
while (n) {
const data = (n.data || '').toLowerCase()
if (
data.includes('lit-part') ||
data.includes('lit$') ||
data.includes('lit-ssr')
) {
return true
}
n = walker.nextNode()
}
} catch (e) {
// If anything goes wrong, err on the safe side and do not hydrate
return false
}
return false
}
function ssr (rootComponent) {
// Use @lit-labs/ssr render
// It returns an iterable
const resultIterator = renderSSR(rootComponent)
let componentsString = ''
for (const chunk of resultIterator) {
componentsString += chunk
}
return {componentsString, stylesString: componentCSSString}
}
function defineRoute (routeObject) {
if (routeObject.external) {
let foundRoute = externalRoutes.findIndex(route => route.path === routeObject.path)
if(foundRoute !== -1){
externalRoutes[foundRoute] = routeObject
} else {
externalRoutes.push(routeObject.path)
}
return
}
let foundRoute = routesArray.findIndex(route => route.path === routeObject.path)
if(foundRoute !== -1){
routesArray[foundRoute] = routeObject
} else {
routesArray.push(routeObject)
}
}
function formField (ob, prop) {
return e => {
ob[prop] = e.currentTarget.type === 'checkbox' || e.currentTarget.type === 'radio' ? e.currentTarget.checked : e.currentTarget.type === 'number' ? Number(e.currentTarget.value) : e.currentTarget.value
let validOb
let touchedOb
let validFound
if (!ob.valid) {
if (Object.getOwnPropertySymbols(ob).length > 0) {
Object.getOwnPropertySymbols(ob).forEach(symb => {
validFound = validFound || symb.toString().indexOf('Symbol(valid)') === 0
if (symb.toString().indexOf('Symbol(valid)') === 0 && ob[symb] !== undefined) {
validOb = symb
}
})
if(!validFound){
const symb = Symbol('valid')
ob[symb] = {}
validOb = symb
}
} else {
const symb = Symbol('valid')
ob[symb] = {}
validOb = symb
}
} else {
validOb = 'valid'
}
let touchedFound
Object.getOwnPropertySymbols(ob).forEach(symb => {
touchedFound = touchedFound || symb.toString().indexOf('Symbol(touched)') === 0
if (symb.toString().indexOf('Symbol(touched)') === 0 && ob[symb] !== undefined) {
touchedOb = symb
}
})
if(!touchedFound){
const symb = Symbol('touched')
ob[symb] = {}
touchedOb = symb
}
if (touchedOb) {
if (!ob[touchedOb][prop]) {
ob[touchedOb][prop] = true
stateUpdated()
}
}
ob[validOb][prop] = e.currentTarget.validity.valid
console.log('---formField update---')
console.log(prop, ob)
console.log(`Valid? ${ob[validOb][prop]}`)
}
}
function formIsValid (holidingPen) {
let validProp = holidingPen.valid && 'valid'
if (!validProp) {
Object.getOwnPropertySymbols(holidingPen).forEach(symb => {
if (symb.toString().indexOf('Symbol(valid)') === 0 && holidingPen[symb]) {
validProp = symb
}
})
if (!validProp) {
return false
}
}
let validOb = Object.keys(holidingPen[validProp])
for (let i = 0; i < validOb.length; i++) {
if (holidingPen[validProp][validOb[i]] !== true) {
return false
}
}
return true
}
function fieldIsTouched (holidingPen, property) {
let touchedProp
Object.getOwnPropertySymbols(holidingPen).forEach(symb => {
if (symb.toString().indexOf('Symbol(touched)') === 0 && holidingPen[symb]) {
touchedProp = symb
}
})
if (!touchedProp) {
return false
}
return !!holidingPen[touchedProp][property]
}
function resetTouched (holidingPen) {
let touchedProp
Object.getOwnPropertySymbols(holidingPen).forEach(symb => {
if (symb.toString() === 'Symbol(touched)') {
touchedProp = symb
}
})
if (!touchedProp) {
return
}
for (let prop in holidingPen[touchedProp]) {
holidingPen[touchedProp][prop] = false
}
stateUpdated()
}
let waitingAlready = false
function debounce (func) {
if (!waitingAlready) {
waitingAlready = true
nextTick(() => {
func()
waitingAlready = false
})
}
}
function nextTick (func) {
if (typeof window !== 'undefined' && window.requestAnimationFrame) {
window.requestAnimationFrame(func)
} else {
setTimeout(func, 17)
}
}
function stateUpdated () {
if (rootEl) {
let startTime = Date.now()
let newTemplate = components(state)
console.log(`Component render: ${Date.now() - startTime}`)
startTime = Date.now()
// Render into the container (rootEl)
render(newTemplate, rootEl)
console.log(`DOM update: ${Date.now() - startTime}`)
}
}
function updateState (updateObject, options) {
if (updateObject) {
if (options && options.deepMerge === false) {
Object.assign(state, updateObject)
} else {
let deepMergeOptions = {clone: false}
if (options && options.arrayMerge === false) {
deepMergeOptions.arrayMerge = (destinationArray, sourceArray, options) => {
//don't merge arrays, just return the new one
return sourceArray
}
}
Object.assign(state, merge(state, updateObject, deepMergeOptions))
}
}
if (options && options.rerender === false) {
return state
}
debounce(stateUpdated)
// Avoid referencing process in browsers without a bundler (process is undefined)
if (typeof process !== 'undefined' && process.env && process.env.NODE_ENV !== 'production') {
console.log('------STATE UPDATE------')
console.log(updateObject)
console.log(' ')
console.log('------NEW STATE------')
console.log(state)
console.log(' ')
}
return state
}
function emptySSRVideos (c) {
// This was for nanomorph. Lit handles updates differently.
// If we need to manipulate DOM before render, it's harder with Templates.
// Leaving empty or deprecated.
}
function injectHTML (htmlString, options) {
if (options && options.wrapper === false) {
return unsafeHTML(htmlString)
}
return html`<div>${unsafeHTML(htmlString)}</div>`
}
function injectMarkdown (mdString, options) {
return injectHTML(decode(marked(mdString)), options)
}
function gotoRoute (route) {
let {pathname, hash, search, href} = createLocation({}, route)
//if pathname doesn't begin with a /, add one
if (pathname && pathname.indexOf('/') !== 0) {
pathname = `/${pathname}`
}
let component = router(route, {pathname, hash, search, href})
updateState({
router: {
component
}
})
}
function getRouteComponent (pathname) {
let foundRoute = routesArray.find(route => route.key === pathname || route.path === pathname)
return foundRoute && foundRoute.component
}
function getSymbol (ob, symbolName) {
let symbols = Object.getOwnPropertySymbols(ob)
if (symbols.length) {
return symbols.find(symb => symb.toString()
.includes(`Symbol(${symbolName})`))
}
}
function addToHoldingPen (holdingPen, addition) {
let currentValid = holdingPen[getSymbol(holdingPen, 'valid')]
let currentTouched = holdingPen[getSymbol(holdingPen, 'touched')]
let additionValid = addition[getSymbol(addition, 'valid')]
let additionTouched = addition[getSymbol(addition, 'touched')]
let additionWithoutSymbols = {}
Object.keys(addition).forEach(ad => {
additionWithoutSymbols[ad] = addition[ad]
})
Object.assign(currentValid, additionValid)
Object.assign(currentTouched, additionTouched)
Object.assign(holdingPen, additionWithoutSymbols)
}
function removeFromHoldingPen (holdingPen, removal) {
let currentValid = holdingPen[getSymbol(holdingPen, 'valid')]
let currentTouched = holdingPen[getSymbol(holdingPen, 'touched')]
removal.forEach(key => {
if(currentValid){
delete currentValid[key]
}
if(currentTouched){
delete currentTouched[key]
}
if(holdingPen){
delete holdingPen[key]
}
})
}
export default (config, {shiftyRouter = shiftyRouterModule, href = hrefModule, history = historyModule} = {}) => {
//this default function is used for setting up client side and is not run on
// the server
({components, el} = config)
let { hydrationSkipRoutes } = config
return new Promise((resolve, reject) => {
let routesFormatted = routesArray.map(r => [
r.path,
(params, parts) => {
r.callback && r.callback(Object.assign({}, parts, {params}), state)
if (parts && window.location.pathname !== parts.pathname) {
window.history.pushState({href: parts.href}, r.title, parts.href)
}
updateState({
router: {
pathname: parts.pathname,
hash: parts.hash,
query: qs.parse(parts.search),
params,
key: r.key || r.path,
href: location.href,
component: null
}
})
document.title = r.title || ''
return r.component
}
])
router = shiftyRouter({default: '/404'}, routesFormatted)
href(location => {
if (externalRoutes.includes(location.pathname)) {
window.location = location.pathname
return
}
gotoRoute(location.href)
})
history(location => {
gotoRoute(location.href)
})
let c = components(state)// component template
if (el) {
// rootEl is the container
rootEl = document.querySelector(el)
// Initial render. Only hydrate when container has Lit SSR markers.
console.log(`Hydration check. Router Key: ${state.router.key}`)
const shouldSkipHydration = hydrationSkipRoutes && hydrationSkipRoutes.includes(state.router.key)
if (shouldSkipHydration) {
console.log(`Skipping hydration for route: ${state.router.key}`)
rootEl.innerHTML = ''
}
if (canHydrateContainer(rootEl) && !shouldSkipHydration) {
try {
hydrate(c, rootEl)
} catch (e) {
// Fallback to render if hydration fails (or if not SSR'd by Lit)
console.warn('Hydration failed or not applicable, falling back to render', e)
render(c, rootEl)
}
} else {
render(c, rootEl)
}
return resolve({rootEl, state})
}
// If no root element provided?
rootEl = null
// We return 'c' which is now a TemplateResult.
resolve({rootEl: c, state})
})
}
function rerender () {
debounce(stateUpdated)
}
export {
getRouteComponent,
rerender,
formIsValid,
ssr,
injectHTML,
injectMarkdown,
geb,
eventEmitter,
html,
defineRoute,
updateState,
state,
formField,
gotoRoute,
cssTag as css,
axios as http,
fieldIsTouched,
resetTouched,
nextTick,
addToHoldingPen,
removeFromHoldingPen,
unsafeHTML
}