forked from lorengreenfield/halfcab
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhalfcab.js
More file actions
274 lines (222 loc) · 7.61 KB
/
halfcab.js
File metadata and controls
274 lines (222 loc) · 7.61 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
import sheetRouter from 'sheet-router'
import href from 'sheet-router/href'
import history from 'sheet-router/history'
import createLocation from 'sheet-router/create-location'
import html from 'bel'
import update from 'nanomorph'
import axios, { get } from 'axios'
import cssInject from 'csjs-inject'
import merge from 'deepmerge'
import marked from 'marked'
import { AllHtmlEntities } from 'html-entities'
import geb, { eventEmitter } from './eventEmitter/index.js'
import qs from 'qs'
import deepFreeze from 'deep-freeze'
let componentRegistry
let entities = new AllHtmlEntities()
let cssTag = cssInject
let componentCSSString = ''
let routesArray = []
let state = {}
let frozenState = {}
let router
let rootEl
let components
let postUpdate
let dataInitial
marked.setOptions({
breaks: true
})
if(typeof window !== 'undefined'){
componentRegistry = new Map()
dataInitial = document.querySelector('[data-initial]')
if(!!dataInitial){
state = (dataInitial && dataInitial.dataset.initial) && Object.assign({}, JSON.parse(atob(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)})
}
}
freezeState()
}else{
cssTag = (cssStrings, ...values) => {
let output = cssInject(cssStrings, ...values)
componentCSSString += componentCSSString.indexOf(output[' css ']) === -1 ? output[' css '] : ''
return output
}
}
function ssr(rootComponent){
let componentsString = `${rootComponent}`
return { componentsString, stylesString: componentCSSString }
}
function defineRoute(routeObject){
routesArray.push(routeObject)
}
function emptyBody(){
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild)
}
}
function formField(ob, prop){
return e => {
ob[prop] = e.currentTarget.type === 'checkbox' || e.currentTarget.type === 'radio' ? e.currentTarget.checked : e.currentTarget.value
let validOb
if(!ob.valid){
if(Object.getOwnPropertySymbols(ob).length > 0){
Object.getOwnPropertySymbols(ob).forEach(symb => {
if(symb.toString() === 'Symbol(valid)'){
validOb = symb
}
})
}else{
ob.valid = {}
validOb = 'valid'
}
}else{
validOb = 'valid'
}
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() === 'Symbol(valid)'){
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
}
let waitingAlready = false
function debounce(func) {
if(!waitingAlready){
waitingAlready = true
requestAnimationFrame(() => {
func()
waitingAlready = false
})
}
}
function stateUpdated(){
rootEl && update(rootEl, components(state))
postUpdate && postUpdate()
}
function freezeState(){
frozenState = merge({}, state)//clone
deepFreeze(frozenState)
}
function updateState(updateObject, options){
if(updateObject){
if(options && options.deepMerge === false){
state = Object.assign({}, state, updateObject)
}else{
let deepMergeOptions = {}
if(options && options.arrayMerge === false){
deepMergeOptions.arrayMerge = (destinationArray, sourceArray, options) => {
//don't merge arrays, just return the new one
return sourceArray
}
}
state = merge(Object.assign({}, state), updateObject, deepMergeOptions)
}
freezeState()
}
debounce(stateUpdated)
if(process.env.NODE_ENV !== 'production'){
console.log('------STATE UPDATE------')
console.log(updateObject)
console.log(' ')
console.log('------NEW STATE------')
console.log(state)
console.log(' ')
}
}
function injectHTML(htmlString){
return html([`<div>${htmlString}</div>`])//using html as a regular function instead of a tag function, and prevent double encoding of ampersands while we're at it
}
function injectMarkdown(mdString){
return injectHTML(entities.decode(marked(mdString)))//using html as a regular function instead of a tag function, and prevent double encoding of ampersands while we're at it
}
function cache(c, args){
if(typeof window === 'undefined'){
return c(args)
}
let key = c.toString() + JSON.stringify(args)
if(!componentRegistry.has(key)){
//not already in the registry, add it
let el = c(args)
componentRegistry.set(key, el)
return el
}else{
return componentRegistry.get(key)
}
}
function gotoRoute(route){
let { pathname, hash, search, href } = createLocation({}, route)
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
}
export default function (config){
//this default function is used for setting up client side and is not run on the server
components = config.components
postUpdate = config.postUpdate
return new Promise((resolve, reject) => {
let routesFormatted = routesArray.map(r => [
r.path,
(params, parts) =>{
r.callback && r.callback(Object.assign({}, parts, {params}))
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
}
}, {
deepMerge: false
})
document.title = parts.pathname !== '' && r.title ? `${config.baseName} - ${r.title}`: config.baseName
return r.component
}
])
router = sheetRouter({default: '/404'}, routesFormatted)
href(location =>{
gotoRoute(location.href)
})
history(location => {
gotoRoute(location.href)
})
rootEl = components(state)
resolve(rootEl)//root element generated by components
})
}
let cd = {}//empty object for storing client dependencies (or mocks or them on the server)
export {getRouteComponent, cache, stateUpdated as rerender, formIsValid, ssr, injectHTML, injectMarkdown, frozenState as state, geb, eventEmitter, cd, html, defineRoute, updateState, emptyBody, formField, gotoRoute, cssTag as css, axios as http}