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
|
import { EvalActions, evalExpr } from './eval'
import {
extractDeclaration,
DeclarationEval,
Declaration,
expressionsToDeclrs,
} from './declarations'
import { parse } from './parser'
import { match } from './utils/adt'
const UNSET_PROPERTY_VALUE = '<unset>'
const EVENT_HANDLERS = {
click: '--cssx-on-click',
load: '--cssx-on-load',
mount: '--cssx-on-mount',
submit: '--cssx-on-submit',
}
const PROPERTIES = [
'--cssx-children',
'--cssx-text',
'--cssx-disgustingly-set-innerhtml',
]
export const injectStyles = () => {
const STYLE_TAG_CLASS = 'cssx-style-root'
if (document.querySelector(`.${STYLE_TAG_CLASS}`)) return
const $style = document.createElement('style')
$style.className = STYLE_TAG_CLASS
const properties = [...PROPERTIES, ...Object.values(EVENT_HANDLERS)]
$style.textContent = `.cssx-layer {
${properties.map(p => `${p}: ${UNSET_PROPERTY_VALUE};`).join(' ')}
}`
document.body.appendChild($style)
}
export const getPropertyValue = ($element: Element, prop: string) => {
const value = `${getComputedStyle($element).getPropertyValue(prop)}`.trim()
return !value || value === UNSET_PROPERTY_VALUE ? '' : value
}
export const getDeclarations = (
$element: Element,
actions: EvalActions,
): Promise<Array<DeclarationEval>> => {
const value = getPropertyValue($element, '--cssx-children')
return extractDeclaration(value, actions)
}
const getEvalActions = ($element: Element, event: any): EvalActions => ({
addClass: async (id, cls) => document.getElementById(id)?.classList.add(cls),
removeClass: async (id, cls) =>
document.getElementById(id)?.classList.remove(cls),
delay: delay => new Promise(res => setTimeout(res, delay)),
jsEval: async js => (0, eval)(js),
loadCssx: async (id, url) =>
new Promise((resolve, reject) => {
const $link = Object.assign(document.createElement('link'), {
href: url,
rel: 'stylesheet',
})
$link.onload = () => {
const $el = document.getElementById(id)
// NOTE: Maybe create and append to body if no root?
if ($el) {
manageElement($el)
resolve(id)
} else {
console.error(`[CSSX] Unable to find root for ${id}`)
reject(`[CSSX] Unable to find root for ${id}`)
}
}
document.body.appendChild($link)
}),
getVariable: async varName => getPropertyValue($element, varName),
updateVariable: async (targetId, varName, value) => {
const $el = document.getElementById(targetId)
if ($el) {
$el.style.setProperty(varName, JSON.stringify(value))
}
},
setAttribute: async (id, name, value) => {
const $el = id ? document.getElementById(id) : $element
if (value) {
$el?.setAttribute(name, value)
} else {
$el?.removeAttribute(name)
}
},
getAttribute: async (id, name) => {
const $el = id ? document.getElementById(id) : $element
return $el?.getAttribute(name) ?? undefined
},
withEvent: async fn => fn(event),
getFormData: async () =>
$element.nodeName === 'FORM'
? new FormData($element as HTMLFormElement)
: undefined,
sendRequest: async ({ url, method, data }) => {
await fetch(url, { method, body: data })
// TODO: Handle response?
},
addChildren: async (id, children) => {
const $el = document.getElementById(id)
const declarations = await expressionsToDeclrs(
children,
getEvalActions($element, event),
)
$el && createLayer(declarations, $el)
},
removeElement: async id => {
const $el = id ? document.getElementById(id) : $element
$el?.parentNode?.removeChild($el)
},
})
export const handleEvents = async (
$element: Element,
isNewElement: boolean = false,
) => {
for (const [eventType, property] of Object.entries(EVENT_HANDLERS)) {
const handlerExpr = getPropertyValue($element, property)
if (handlerExpr) {
const eventHandler = async (event: any) => {
const exprs = parse(handlerExpr)
for (const expr of exprs) {
await evalExpr(expr, getEvalActions($element, event))
}
}
if (eventType === 'mount') {
if (isNewElement) setTimeout(eventHandler)
} else {
;($element as any)[`on${eventType}`] = eventHandler
}
}
}
}
const declarationToElement = (
declaration: DeclarationEval,
$parent?: Element,
) => {
const { tag, id, selectors } = declaration.selector
const tagName = tag || 'div'
let $child = $parent?.querySelector(`:scope > #${id}`)
if (!$child) {
$child = Object.assign(document.createElement(tagName), { id })
}
// Add selectors
for (const selector of selectors) {
match(selector, {
ClassName: cls =>
!$child?.classList.contains(cls) && $child?.classList.add(cls),
Attr: ([key, val]) => $child?.setAttribute(key, val),
})
}
return { node: $child, isNewElement: !$child }
}
const createLayer = async (
declarations: Array<DeclarationEval>,
$parent: Element,
) => {
const LAYER_CLASS = 'cssx-layer'
const $childrenRoot =
$parent?.querySelector(`:scope > .${LAYER_CLASS}`) ??
Object.assign(document.createElement('div'), { className: LAYER_CLASS })
for (const declaration of declarations) {
const { node: $child, isNewElement } = declarationToElement(
declaration,
$childrenRoot,
)
$childrenRoot.appendChild($child)
await manageElement($child, isNewElement)
}
if (!$childrenRoot.parentNode) $parent.appendChild($childrenRoot)
}
export const manageElement = async (
$element: Element,
isNewElement: boolean = false,
) => {
await handleEvents($element, isNewElement)
const text = getPropertyValue($element, '--cssx-text')
if (text) $element.textContent = text
const html = getPropertyValue($element, '--cssx-disgustingly-set-innerhtml')
if (html) $element.innerHTML = html.replace(/(^'|")|('|"$)/g, '')
const declarations = await getDeclarations(
$element,
getEvalActions($element, null),
)
if (declarations.length > 0) {
await createLayer(declarations, $element)
}
}
export interface Options {
root?: HTMLElement
}
export const render = async ({ root = document.body }: Options = {}) => {
injectStyles()
await manageElement(root)
}
|