-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
181 lines (153 loc) · 5.98 KB
/
index.ts
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
import { createStore, FletchState } from "fletch-state"
type FletchAction = {
path: string,
value: any;
}
type MethodDefinitions = {
[key:string]: (...args: any[]) => FletchAction | Promise<FletchAction>;
}
type Options = {
getDefaultMethods?: (state: FletchState) => MethodDefinitions,
openDelimiter: string,
closeDelimiter: string,
}
type Template = {
view: HTMLElement,
model: HTMLTemplateElement,
}
type Templates = {
[key:string]: Template;
}
type SprinkleDocument = {
store: FletchState,
templates: Templates,
}
const defaultOptions = {
openDelimiter: "{{",
closeDelimiter: "}}",
}
const getDefaultMethods = (state: FletchState): MethodDefinitions => {
return {
get: async (location: string, params: any = {}) => {
const queryString = Object.keys(params).map(k => `${k}=${params[k]}`).join("&")
const response = await fetch(location + queryString, {
method: "GET",
}).then(r => r.json())
return { path: location, value: response };
},
post: async (location: string, params: any = {}) => {
const response = await fetch(location, {
method: "POST",
body: JSON.stringify(params)
}).then(r => r.json())
return { path: location, value: response }
},
put: async (location: string, params: any = {}) => {
const response = await fetch(location, {
method: "PUT",
body: JSON.stringify(params)
}).then(r => r.json())
return { path: location, value: response }
},
set: (path: string, value: any) => {
return { path, value };
},
toggle: (path: string) => {
const value = state.retrieve(path);
return { path, value: !value }
}
}
}
const getTemplate = (methods: MethodDefinitions, regex: RegExp) => {
return (state: any, element: HTMLElement) => {
// Remove anything with IF
const conditionalElements = element.querySelectorAll("[data-sprinkle-if]");
for(const conditionalElement of conditionalElements) {
const isPresent = new Function("$state", `return !!(${conditionalElement.getAttribute("data-sprinkle-if")})`)(state);
if (!isPresent) {
conditionalElement.remove();
}
}
// Iterate over anything with FOR
const repeatedElements = element.querySelectorAll("[data-sprinkle-for]");
for(const repeatedElement of repeatedElements) {
const iterator = new Function("$state", `return ${repeatedElement.getAttribute("data-sprinkle-for")}`)(state);
repeatedElement.removeAttribute("data-sprinkle-for")
const innerHTML = iterator.map((item: any) => {
return repeatedElement.outerHTML.replace(regex, (substring: string) => {
return new Function("$methods", "$state", "$item", `return ${substring.replace(regex, "$1")}`)(methods, state, item);
});
}).join("")
repeatedElement.innerHTML = innerHTML;
}
// Render the inside and the else
return element.innerHTML.replace(/{{(.*?)}}/g, (substring: string) => {
return new Function("$methods", "$state", `return ${substring.replace(regex, "$1")}`)(methods, state);
});
}
}
export const start = (options: Options = defaultOptions): SprinkleDocument => {
// Get the regex for value interpolation
const regex = new RegExp(`^${options.openDelimiter}(.*?)${options.closeDelimiter}`, "gi");
// Define the default state.
const store = createStore({});
// Override the default methods with the given methods.
const methods = options.getDefaultMethods ? { ...getDefaultMethods(store), ...options.getDefaultMethods(store) } : getDefaultMethods(store);
// Find all templates labelled as having as a sprinkle element.
const elements = document.querySelectorAll<HTMLTemplateElement>("template[data-sprinkle-id]");
// Set the default state to point to the values.
for(const element of elements) {
const currentState = element.getAttribute("data-sprinkle-state");
const id = element.getAttribute("data-sprinkle-id");
if (currentState) {
store.commit(id, JSON.parse(currentState))
}
}
const templates: Templates = {};
for(const element of elements) {
const id = element.getAttribute("data-sprinkle-id");
const path = element.getAttribute("data-sprinkle-namespace") || id;
const compiledElement = document.createElement("div")
compiledElement.innerHTML = element.innerHTML;
const getHTML = getTemplate(methods, regex);
compiledElement.innerHTML = getHTML(store.retrieve(path), compiledElement)
element.replaceWith(compiledElement)
store.subscribe(path, () => {
const replacingElement = document.createElement("div")
replacingElement.innerHTML = element.innerHTML;
compiledElement.innerHTML = getHTML(store.retrieve(path), replacingElement)
});
templates[id] = {
view: compiledElement,
model: element
}
}
// Register the actions
const actionElements = document.querySelectorAll("[data-sprinkle-actions]");
for(const element of actionElements) {
const actions = element.getAttribute("data-sprinkle-actions").split(";");
for(const action of actions) {
// The action will be in the format event:action1(params)|action2(params);
const [trigger, event] = action.split(":");
element.addEventListener(trigger, (e) => {
const value = new Function("$methods", "$event", `return $methods.${event}`)(methods, e) as FletchAction;
if (value) {
store.commit(value.path, value.value);
}
})
}
}
// Register the form listeners
const forms = document.querySelectorAll("form[data-sprinkle-namespace]")
for(const form of forms) {
const path = form.getAttribute("data-sprinkle-namespace")
const inputs = form.querySelectorAll<HTMLInputElement>("input[name],select[name],textarea[name]");
for(const input of inputs) {
input.addEventListener("input", (e) => {
const currentValue = store.retrieve(path)
store.commit(path, { ...currentValue, [(e.target as any).name]: (e.target as any).value })
})
}
}
return { store, templates };
}