-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhq.ts
More file actions
279 lines (258 loc) · 8.73 KB
/
Copy pathhq.ts
File metadata and controls
279 lines (258 loc) · 8.73 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
import {
HTMLElement,
Node,
parse,
TextNode,
} from "https://esm.sh/node-html-parser@6.1.4";
import beautify from "https://esm.sh/js-beautify@1.14.0";
export function query_html(
query: string,
html_data: string,
whitespace = true
) {
if (_is_dot(query)) return beautify.html(html_data);
let html: HTMLElement = parse(html_data);
for (const expression of _commands(query)) {
_run(expression, html);
html = parse(html?.toString());
}
return _html(html, whitespace);
}
function _html(html: HTMLElement, whitespace: boolean): string {
return whitespace
? beautify.html(html.removeWhitespace().toString())
: html.removeWhitespace().toString();
}
function _run(expression: string, html: HTMLElement) {
const firstWhiteSpace = expression.indexOf(" ");
const [program, ...params] = [
expression.substring(0, firstWhiteSpace),
expression.substring(firstWhiteSpace + 1),
];
for (const param of params) {
if (program == "value") {
const [selector, valueTemplate, ...valuesOrExpressions] =
param.split(",");
const attributes = valuesOrExpressions
// todo: handle "." in raw strings, f.i. -> "hello . with . dots."
.map((x) => x?.split(".") ?? x)
.map((x) => {
if (x.length == 2) {
return ["attribute", x[1]];
}
return ["value", x[0]];
});
/** 'd' in order to generate indices */
// const regex = /{{%}}/d;
html.querySelectorAll(selector).forEach(function (node) {
let currentTemplate = valueTemplate.slice();
attributes.forEach(function ([type, data]) {
let value = "";
if (type == "attribute" && data == "value") {
value = node.innerHTML;
} else if (type == "attribute") {
value = node.getAttribute(data) ?? "";
} else {
value = data;
}
/** 'String#replace' always the first match */
currentTemplate = currentTemplate.replace("{{%}}", value);
});
// node.innerHTML = 'valueTemplate'
node.set_content(currentTemplate);
});
html.set_content(html?.toString());
} else if (program == "we") {
// console.log(param.split(","));
const [selector, tagToInsert] = param.split(",");
/** @todo: handle undefined tagToInsert, raise some error! */
/**
* [
"parentNode", "childNodes",
"rawAttrs", "voidTag",
"nodeType", "rawTagName",
"id", "_parseOptions",
"classList", "_attrs",
"_rawAttrs"
]
*/
// console.log(html.querySelectorAll(selector)[0])
const elements = html.querySelectorAll(selector);
// for (const e of elements) {
// console.log(e.attributes);
// }
// for (const e of elements) {
// console.log(e.attrs);
// }
// for (const e of elements) {
// console.log(e.classNames);
// }
// for (const e of elements) {
// console.log(e.rawAttributes);
// }
// for (const e of elements) {
// console.log(e.rawAttrs);
// }
// for (const e of elements) {
// console.log(e.rawTagName);
// }
// for (const e of elements) {
// console.log(e.parentNode.rawTagName);
// }
const nodesToReplace = [];
for (const node of elements) {
// console.log(node.parentNode.rawTagName);
nodesToReplace.push(node.attributes);
}
// console.log({ nodesToReplace });
const selectors = [];
for (const node of nodesToReplace) {
let selector = "";
const attributes = Object.entries(node);
attributes.forEach((element) => {
const [attr, val] = element;
selector += `[${attr}="${val}"]`;
});
selectors.push(selector);
// if (id && klass) selectors.push(`[id="${id}"][class="${klass}"]`)
// else if (id) selectors.push(`[id="${id}"]`)
// else if (klass) selectors.push(`[class="${klass}"]`)
}
// console.log({ selectors });
for (const selector of selectors) {
const node = html.querySelector(selector);
if (node) {
const child = node.clone();
const wrapper = new HTMLElement(tagToInsert, {}, "", null, [0, 0]);
wrapper.appendChild(child);
node.replaceWith(wrapper);
html.set_content(beautify.html(html?.toString()));
}
}
// console.log(html.toString())
} else if (program == "itab") {
// console.log("itab")
// console.log(param.split(","))
const [selector, valueTemplate, ...valuesOrExpressions] =
param.split(",");
// console.log({valuesOrExpressions})
const attributes = valuesOrExpressions
// todo: handle "." in raw strings, f.i. -> "hello . with . dots."
.map((x) => x?.split(".") ?? x)
.map((x) => {
if (x.length == 2) {
return ["attribute", x[1]];
}
return ["value", x[0]];
});
// console.log({attributes})
html.querySelectorAll(selector).forEach(function (node) {
let currentTemplate = valueTemplate.slice();
attributes.forEach(function ([type, data]) {
let value = "";
if (type == "attribute" && data == "value") {
value = node.innerHTML;
} else if (type == "attribute") {
value = node.getAttribute(data) ?? "";
} else {
value = data;
}
/** 'String#replace' always the first match */
currentTemplate = currentTemplate.replace("{{%}}", value);
// console.log(currentTemplate)
});
node.insertAdjacentHTML("afterbegin", currentTemplate);
// console.log(node.outerHTML)
});
html.set_content(html?.toString());
} else if (program == "iab") {
const [selector, tagToInsert, nodeValueOrExpression] = param.split(",");
// todo: handle "." in raw strings, f.i. -> "hello . with . dots."
const [_placeholder, attribute] = nodeValueOrExpression?.split(".") ?? [];
html.querySelectorAll(selector).forEach(function (node) {
const elementToInsert = new HTMLElement(
tagToInsert,
{},
"",
null,
[0, 0]
);
const value = attribute
? node.getAttribute(attribute)!
: nodeValueOrExpression;
elementToInsert.appendChild(new TextNode(value, elementToInsert));
node.insertAdjacentHTML("afterbegin", elementToInsert.outerHTML);
});
html.set_content(html?.toString());
} else if (program == "wp") {
_wrap_program(param, html);
} else if (program == "img") {
_img_program(param, html);
} else if (program == "rm") {
_rm_program(html, param);
} else {
_tag_program(html, param, program);
}
}
}
function _tag_program(html: HTMLElement, param: string, program: string) {
// console.log(param.split("+"));
// html.querySelectorAll(param).forEach(function (node) {
// html.querySelectorAll("[id$='main_image'] [class='object']").forEach(function (node) {
// html.querySelectorAll("[class='object'][id$='0']").forEach(function (node) {
html.querySelectorAll(param).forEach(function (node) {
// console.log(node.outerHTML)
node.tagName = program;
});
html.set_content(html?.toString());
}
function _rm_program(html: HTMLElement, param: string) {
// console.log({param})
/** passing el1,el2,el3 wworks! */
html.querySelectorAll(param).forEach(function (node) {
node.remove();
});
html.set_content(html?.toString());
}
function _img_program(param: string, html: HTMLElement) {
let [query, height = "", width = ""] = param.split(",");
height = height !== "" ? height : "auto";
width = width !== "" ? width : "auto";
html.querySelectorAll(query).forEach(function (node) {
const src = node.textContent;
const id = node.id;
node.replaceWith(_img_element(id, height, width, src));
});
}
function _img_element(
id: string,
height: string,
width: string,
src: string
): string | Node {
return new HTMLElement(
"img",
{ id },
`height="${height}" width="${width}" src="${src}" alt="image"`,
null,
[0, 0]
);
}
function _wrap_program(param: string, html: HTMLElement) {
const [tagName, ...attributes] = param.split(",");
const [attrName, attrValue] = attributes;
const rawAttributes =
attributes.length > 0 ? `${attrName}="${attrValue}"` : "";
const wrapper = new HTMLElement(tagName, {}, rawAttributes, null, [0, 0]);
wrapper.appendChild(html);
html.set_content(wrapper.toString());
}
function _is_dot(query: string) {
return query.match(/^.$/g)?.length;
}
function _commands(query: string): string[] {
const [_cat, ...commands] = query
.split("|")
.map((match: string) => match.trim());
return commands;
}