-
Notifications
You must be signed in to change notification settings - Fork 0
/
elements.spritecreator.js
437 lines (429 loc) · 15.4 KB
/
elements.spritecreator.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
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
// *********************************************************************************** base class Meister
class MeisterElement extends HTMLElement {
log(label, ...args) {
// console.log(`<${this.localName}> ${label}:green;color=white`, ...args);
}
}
// *********************************************************************************** base class SpriteMeister
class SpriteMeister extends MeisterElement {
constructor() {
super().attachShadow({
mode: "open",
});
}
appendTemplate() {
let template = document.getElementById(this.nodeName);
if (template) {
this.log(`append template`, this.nodeName);
this.shadowRoot.append(template.content.cloneNode(true));
} else {
this.log("No template:red;color=white");
}
}
addElement(
// 1st:
el = "div",
// 2nd:
{ innerHTML = "", classes = [], attrs = {}, children = [], ...props } = {},
// 3rd:
{
root = this.shadowRoot || this, //!! default root is shadowRoot
insertroot = "append", //!! default append (or: prepend)
insertchildren = "append", //!! append (or: prepend) children
} = {}
) {
el = document.createElement(el);
//this.setAttributes(attrs, el);
Object.keys(attrs).map((key) => el.setAttribute(key, attrs[key]));
el.classList.add(...classes);
Object.assign(el, props);
innerHTML && (el.innerHTML = innerHTML);
el[insertchildren](...children);
root && root[insertroot](el);
return el;
}
addHTML({ root = this.shadowRoot || this, where = "beforeend", html = "[HTML]" }) {
try {
if (!root.insertAdjacentElement) {
setTimeout(() => {
root.insertAdjacentHTML(where, html);
});
} else {
root.insertAdjacentHTML(where, html);
}
} catch (e) {
console.error(this.shadowRoot.insertAdjacentHTML);
}
}
dispatch(detail, options = { name: "sprite-meister", bubbles: true, composed: true }) {
let eventName = options.name;
if (Object.keys(detail).length === 0 && detail.constructor === Object)
// empty Object check
options = { bubbles: true, composed: true };
console.log(`dispatch %c ${eventName}:blue;color=white`, "background:green;color:white", { detail, options });
this.dispatchEvent(
new CustomEvent(eventName, {
bubbles: options.bubbles,
composed: options.composed,
detail,
})
);
}
listen(settings) {
let func = settings;
let name = "sprite-meister";
let root = document.body;
if (typeof settings == "object") {
name = settings.name || name;
func = settings.do;
root = settings.root || root;
if (root == document) console.error("use document.body to listen on ", name, func);
}
this.log(`listen to '${name}'`);
if (typeof func == "function") {
root.addEventListener(name, (evt) => {
console.log(
`${this.nodeName} %c responds to event from %c ${evt.target.nodeName} :royalblue;color=white`,
"background:green;color:white",
"background:orange"
);
func(evt);
});
}
}
respond(func) {
this.listen((evt) => {
if (evt.detail.to && evt.detail.to.includes(this.nodeName)) {
func(evt);
} else {
//console.error(`not for me`,evt.detail.to)
}
});
}
shadowSelector(selector) {
return this.shadowRoot.querySelector(selector);
}
query(selector) {
return (this.shadowRoot || this).querySelector(selector);
}
queryAll(selector) {
return [...(this.shadowRoot || this).querySelectorAll(selector)];
}
setProperty(name, value) {
this.style.setProperty("--" + name, value);
}
}
// *********************************************************************************** define sprite-frames
customElements.define(
"sprite-frames",
class extends SpriteMeister {
// ------------------------------------------------------------------- sprite frames - constructor
constructor() {
super().appendTemplate();
this.listen((evt) => {
if (evt.target.nodeName == "SPRITE-MEISTER") {
console.log(`${this.nodeName} reponds to event from ${evt.target.nodeName}`);
this.render(evt.target);
}
});
} // constructor
set_framenr(framenr, svgelement) {
// dispatch SPRITE-MEISTER framenr
this.dispatch({ to: "SPRITE-MEISTER", framenr });
}
render(sprite) {
try {
this.setProperty("steps", sprite.steps - 1);
let svg = (sprite, framenr, frame) => {
let viewBox = `viewBox='0 0 ${sprite.vbwidth} ${sprite.vbheight}'`;
let svghtml = `<svg xmlns='http://www.w3.org/2000/svg' ${viewBox}>${frame}</svg>`;
//! Where did this code come from?
//! validates SVG but produces XML errors in FireFox
// let testSVG = true;
// if (testSVG) {
// var oParser = new DOMParser();
// var doc = oParser.parseFromString(svghtml, "image/svg+xml");
// var failed = doc.documentElement.nodeName.indexOf("parsererror") > -1;
// if (failed) {
// console.error("failed to load the doc : " + doc.documentElement.nodeName);
// }
// }
return (
`<div class='frame'` +
` onmouseenter='this.getRootNode().host.set_framenr(${framenr})'` +
` onmouseleave='this.getRootNode().host.set_framenr(-1)'>${svghtml}</div>`
);
};
console.log(svg.length);
let gap = 2;
let html = sprite.frames
.map((f, framenr) => svg(sprite, framenr, f.svg))
.join("")
.replaceAll('"', "'");
this.shadowSelector("#spriteframes").innerHTML = html;
} catch (e) {
console.error(`render error:`, [this], e);
}
}
}
);
// *********************************************************************************** define sprite-editor
customElements.define(
"sprite-editor",
class extends SpriteMeister {
constructor() {
super({ template: false, shadow: false });
this.shadowRoot.innerHTML = "<slot></slot>";
}
set_duration(duration, svgelement) {
this.dispatch({ to: "SPRITE-MEISTER", duration });
}
}
);
// *********************************************************************************** define sprite-templates
customElements.define(
"sprite-templates",
class extends SpriteMeister {
// ------------------------------------------------------------------- sprite templates - constructor
constructor() {
super().appendTemplate();
}
// ------------------------------------------------------------------- sprite templates - storeTemplates
storeTemplates() {
let store = [...document.querySelectorAll("[usertemplate")].reduce((store, template) => {
store[template.id] = template.innerHTML;
return store;
}, {});
store = JSON.stringify(store);
localStorage.setItem("usertemplates", store);
}
// ------------------------------------------------------------------- sprite templates - restoreTemplates
restoreTemplates() {
let store = localStorage.getItem("usertemplates");
if (store) {
try {
store = JSON.parse(store);
} catch (e) {
console.error(`${this.id} restoreTemplates error:`, e);
}
Object.keys(store).map((id) => this.appendBodySpriteTemplate(id, store[id]));
}
}
// ------------------------------------------------------------------- sprite templates - connectedCallback
connectedCallback() {
let html = "";
if (this.hasAttribute("user")) {
html += "<h3>localStorage templates</h3>";
let usertemplates = localStorage.getItem("usertemplates");
this.restoreTemplates();
this.listen({
name: "store-user-templates",
do: (evt) => this.storeTemplates(),
root: document.body,
});
this.listen({
name: "remove-template",
do: (evt) => this.removeTemplate(evt.detail.templateid),
});
} else {
html += "<h3>standard templates</h3>";
html += [...document.querySelectorAll("template[spritemeister]")].map((tmpl) => this.appendSpriter(tmpl.id));
}
this.listen();
}
// --------------------------------------------------------- sprite templates - appendBodySpriteTemplate
appendBodySpriteTemplate(id, innerHTML) {
this.log(`append user sprite:red;color=white`, id);
let template = this.addElement(
"template",
{
id,
innerHTML,
},
{
root: document.body,
}
);
let spriter = this.appendSpriter(id);
template.setAttribute("usertemplate", id);
spriter.setAttribute("usertemplate", id);
//this.dispatch({ id });
}
// --------------------------------------------------------- sprite templates - appendSpriter
appendSpriter(id) {
return this.addElement("sprite-meister", {
attrs: {
id,
templatename: id,
template: id,
},
});
}
// --------------------------------------------------------- sprite templates - getTemplate
getTemplate(id) {
return document.querySelector(`template[id="${id}"]`);
}
// --------------------------------------------------------- sprite templates - removeTemplate
removeTemplate(id) {
let template = this.getTemplate(id);
if (template) {
template.remove();
this.storeTemplates();
}
}
}
);
// *********************************************************************************** define sprite-filmstrip
customElements.define(
"sprite-filmstrip",
class extends SpriteMeister {
// ------------------------------------------------------------------- sprite filmstrip - constructor
constructor() {
super().appendTemplate();
this.listen((evt) => {
let sprite = evt.detail.sprite;
if (sprite) {
this.shadowSelector("img").src = sprite.escapedSVG();
this.setProperty("duration", evt.detail.sprite.duration);
this.setProperty("steps", evt.detail.sprite.steps - 1);
}
});
} // constructor
}
);
// *********************************************************************************** define sprite-source
customElements.define(
"sprite-source",
class extends SpriteMeister {
// ------------------------------------------------------------------- sprite source - constructor
constructor() {
super();
this.appendTemplate();
}
// ------------------------------------------------------------------- sprite source - dispatchUpdate
dispatchUpdate() {
this.dispatch({ to: "SPRITE-MEISTER", framedefinition: this.value });
}
// ------------------------------------------------------------------- sprite source - connectedCallback
connectedCallback() {
this.textarea = this.shadowSelector("textarea");
if (this.hasAttribute("editor")) {
this.load();
this.listen({
name: "keyup",
do: (evt) => this.processTextarea_setHeight(false), // false = force updates
root: this.textarea,
});
this.listen({
name: "sprite-meister",
do: (evt) => {
this.processTextarea_setHeight(evt);
if (evt.detail.framedefinition) {
this.value = evt.detail.framedefinition;
}
},
});
this.listen({
name: "save-sprite",
do: (evt) => {},
});
} else { // this element is not the editor
this.listen((evt) => {
let sprite = evt.detail.sprite;
if (evt.detail.sprite) {
let svg = sprite.escapedSVG(this.hasAttribute("escapedtags"));
//! don't call this.load here!
this.value = svg;
}
});
}
} // connectedCallback
// ------------------------------------------------------------------- sprite source - processTextarea
processTextarea_setHeight(evt) {
let linecount = this.value.split(/\n/).length;
this.setProperty("editorEditHeight", linecount + 4 + "em");
console.log("linecount:", linecount);
this.save();
//do NOT dispatchUpdate if already triggered by an evt
if (!evt) this.dispatchUpdate();
}
// ------------------------------------------------------------------- sprite source - GET/SET templateid
get templateid() {
return this.getAttribute("templateid");
}
set templateid(v) {
this.setAttribute("templateid", v);
}
// ------------------------------------------------------------------- sprite source - GET/SET value
get value() {
return this.textarea.value;
}
set value(v) {
this.textarea.value = this.undoHTMLformatting(v);
let title = this.querySelector('span[slot="title"]');
if (title) {
title.innerHTML = `${this.getAttribute("title")} - ${v.length} bytes`;
}
if (this.hasAttribute("editor")) {
if (event && event.detail.templateid) {
console.log("save user template value", event.detail.templateid);
this.templateid = event.detail.templateid;
}
// if user template then update that template
// saver will then save all user templates in the page
// that way we can add user templates by default in index.html
}
}
// ------------------------------------------------------------------- sprite source - save
save() {
console.log(`Save sprite:red;color=white`, this.id, this.templateid);
localStorage.setItem(this.id, this.value);
//save all user templates
this.dispatch(
{},
{
name: "store-user-templates",
}
);
}
// ------------------------------------------------------------------- sprite source - load
load(frame = localStorage.getItem(this.id)) {
let spm = new URLSearchParams(location.search).get("sprite");
if (!frame || spm) {
let frame_template = document.getElementById(spm);
if (!frame_template) frame_template = document.getElementById("bounce");
frame = frame_template.innerHTML;
console.log("loaded:red", spm);
location.replace(location.origin + location.pathname);
}
this.value = frame;
this.save();
setTimeout(() => {
this.dispatchUpdate();
}); //quickfix first load
}
// ------------------------------------------------------------------- sprite source - formattemplate
undoHTMLformatting(frame) {
return frame;
if (frame) {
frame = frame.replace(/\>[\t\s ]+\</g, "><"); // remove whitespace between tags
if (frame[0] == "\n") frame = frame.slice(1, Infinity);
frame = frame.trim();
frame = frame.replace(/"/g, "'");
//frame = frame.replace(/ /g, "X");
//frame = frame.replace(/,/g," ");
frame = frame.replace(/=''/g, ""); // remove incorrect empty attribute values set by HTML
frame = frame.replace("/(<!--)[sS]*(-->)/", ""); // remove comments
// remove newline / carriage return
// str.replace(/\n/g, "");
// remove whitespace (space and tabs) before tags
// str.replace(/[\t ]+\</g, "<");
// remove whitespace between tags
// str.replace(/\>[\t ]+\</g, "><");
// remove whitespace after tags
// str.replace(/\>[\t ]+$/g, ">");
}
return frame;
}
} // class
); // define sprite save