-
Notifications
You must be signed in to change notification settings - Fork 95
/
Copy pathscript.js
165 lines (153 loc) · 6.29 KB
/
script.js
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
/* globals hljs, ClipboardJS, showdown */
/* TODO
- URL should match code. e.g. go to biden, change colors, go to ava. Biden's colors are in URL
*/
async function init() {
const response = await fetch("dist/characterlist.json");
const chars = await response.json();
// Current values of character name and parent attributes. If these change, menu should be redrawn
let current = {};
// Return the menu dropdowns given a selection (q).
// Result = {label: [option, option, ...], label: [...]}
const options = function (q) {
let result = { name: Object.keys(chars) };
const char = chars[q.name] || Object.values(chars)[0];
current = { name: char };
// If the character is a template, i.e. uses other characters, index.json/lookup defines
// dropdowns for each parameter. For example:
// "dee_emotion": { "select": "emotion", "from": "dee", "where": { "angle": "side" } }
// ... means that ?dee_emotion= is picked up from the "emotion" dropdown from character "dee".
// TODO: Not yet implemented
_.each(char.lookups, (lookup, key) => {
let filter = { name: lookup.from };
_.each(lookup.where, (filter_val, filter_key) => {
if (filter_val.expr) {
// TODO: Don't hard-code side
let expr = new Function("q", `return q["${filter_val.expr}"] || 'side'`);
filter[filter_key] = expr(q);
} else {
filter[filter_key] = filter_val;
}
});
result[key] = options(filter)[lookup.select];
});
// If the character is a basic character, i.e. its made of files under its own directory,
// index.json/patterns defines dropdowns for each parameter.
char.patterns.forEach((pattern) => {
let node = char.files;
let hierarchy = [];
// Split each pattern by "/" like the directory structure
for (const dir of pattern.split(/\s*\/\s*/)) {
// (Recursively) loop through each directory
if (dir.match(/\{\{/)) {
// If dir is a variable (e.g. "{{face}}" or "{{face}}.svg"), get all matching keys, filter by current/first option
let key = dir.slice(2, -2);
result[key] = Object.keys(node);
hierarchy.push(key);
node = node[q[key]] || Object.values(node)[0];
} else {
// If dir is a value (e.g. "face"), filter all nodes
node = node[dir];
}
}
// When a parent in the dropdown hierarchy changes, redraw the menu.
// e.g. in {{angle}}/pose/{{pose}}.svg, if angle changes, redraw for new poses.
hierarchy.slice(0, -1).forEach((key) => (current[key] = ""));
});
return result;
};
const menu_template = _.template(document.querySelector("#menu-template").innerHTML);
const code_template = _.template(document.querySelector("#codegen").innerHTML);
const $codetemp = document.querySelector("#codetemp");
const $menu = document.querySelector("#menu");
const $character = document.querySelector("#character .target");
// ID of the dropdown that last triggered a change. Useful to re-focus on it if menu is redrawn
let trigger_id = "";
// Current background color. When the menu is redrawn, preserve this color on the page
let state = { bgcolor: "#ffffff" };
const config = {
typeclass: {
color: "form-control-color",
number: "form-control-number",
range: "form-range d-inline-block my-2 border-0",
},
};
function getParams() {
let params = new URLSearchParams();
for (let node of $menu.querySelectorAll("select, input")) params.append(node.name, node.value);
return params;
}
function bg_color(e) {
if (e.target.classList.contains("bg-color"))
// The first rule in the first sheet defines the background color for the target-container
state.bgcolor = document.styleSheets[0].cssRules[0].style.backgroundColor = e.target.value;
}
// Render the document based on query parameters
async function render() {
let q = g1.url.parse(location.hash.replace(/^#/, "?")).searchKey;
// If the name or parent keys have changed, re-render the menu
const menu_change = !current.name || _.some(current, (val, key) => current[key] != q[key]);
// If the menu has changed, re-render the menu
if (menu_change) {
let opt = options(q);
$menu.innerHTML = menu_template({ q, chars, config, options: opt });
for (let key in current) current[key] = q[key];
}
let params = getParams();
const response = await fetch("comic?" + params);
$character.innerHTML = await response.text();
$codetemp.innerHTML = code_template({
url: location.origin + location.pathname + "comic?" + params || "",
state,
code_template,
});
if (trigger_id) document.querySelector(`#${trigger_id}`).focus();
}
// When location hash changes (or initially), re-render
window.addEventListener("hashchange", render, false);
render();
// When inputs change, change location hash -- but no oftener than 200ms
let delay = 200;
let lastUpdated = 0;
let event, timeout;
$menu.addEventListener("input", (e) => {
event = { hash: getParams(), id: e.target.id };
let diff = +new Date() - lastUpdated;
if (diff < delay) {
if (timeout) clearTimeout(timeout);
timeout = setTimeout(updateURL, diff);
return;
}
updateURL();
});
function updateURL() {
location.hash = event.hash;
trigger_id = event.id;
lastUpdated = +new Date();
}
document.body.addEventListener("input", bg_color, false);
document.body.addEventListener("change", bg_color, false);
new ClipboardJS(".copy");
}
init();
// Render part of README.md as Markdown. Sections delimited by <!-- var ... !>...<!-- end -->
$.get("README.md").done(function (text) {
let converter = new showdown.Converter({ ghCodeBlocks: true, tables: true });
text.match(/<!--\s*var\s+\S*\s*-->[\s\S]*?<!--\s*end\s*-->/gim).forEach(function (match) {
let lines = match.split(/\n/);
let name = lines[0].replace(/^<!--\s*var\s+/, "").replace(/\s*-->$/, "");
$('md[data-target="' + name + '"]')
.addClass("d-block my-4")
.html(converter.makeHtml(lines.slice(1, -1).join("\n")))
.find("pre")
.each(function () {
hljs.highlightBlock(this);
});
});
$("md table")
.addClass("table table-sm")
.find("a")
.each(function () {
$(this).attr("target", "_blank");
});
});