-
Notifications
You must be signed in to change notification settings - Fork 5
/
maker.js
executable file
·557 lines (514 loc) · 22.2 KB
/
maker.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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
//After a page is updated this stores the edit key so we can modify it again
var EDIT_KEY = null;
var HASH_TO_LOAD = null;
var HASH_TYPE = "v1";
//Display error
function mayError(errObj){
if (errObj.error){
$("#error strong").text(errObj.error);
$("#error em").text(errObj.details);
$("#error").show()
return 1;
} else {
return 0;
}
}
//Blanks the cards
function newCard(){
$(".card").attr("class","card pony malefemale unicorn web-grey");
$(".card .name").val("");
$(".card .attrs").val("");
$(".card .effect").val("").change();
$(".card .flavour").val("").change();
$(".card .copyright").val("WEB CARD; TSSSF by Horrible People Games. Art by Unknown.");
EDIT_KEY = null;
document.location.hash = "";
$("#shortUrl,#longUrl,#image").val("").change().addClass("empty")
$("#error").hide();
}
function shorten_url(url, callback){
$.ajax({
url: "http://v.gd/create.php",
type: "POST",
dataType: 'json',
data: {format:"json", url:window.location.href},
success: function(r,s,t)
{
callback(r["shorturl"]);
}
});
}
//Saves a card
function save(){
shorten_url(location.href, function(shorturl){
$("#shortUrl").val(shorturl);
$("#longUrl").val(document.location.href);
$("#shortUrl,#longUrl").removeClass("empty"); //Bodge fix for placeholder overlay
});
}
function doReplace(repl, str) {
var regexStr = Object.keys(repl).map(function(s) {
return s.replace(/([^\w\s])/g, '\\$1');
}).join('|');
return str.replace(new RegExp(regexStr, 'g'), function(m) {
return repl[m];
});
}
function sanitize(str){
var SPECIAL_REPLACE = {
"While this card is in your hand, you may discard a Pony card from the grid and play this card in its place. This power cannot be copied.": "{replace}",
"You may swap 2 Pony cards on the shipping grid.": "{swap}",
"You may swap up to 3 Pony cards on the grid.": "{3swap}",
"You may draw 1 card from the Ship or Pony deck.": "{draw}",
"You may discard 1 active Goal and draw 1 new Goal to replace it.": "{goal}",
"You may search the Ship or Pony discard pile for 1 card of your choice and put it into your hand. If it's still in your hand at the end of your turn, discard it.": "{search}",
"You may copy the power of any Pony card currently on the shipping grid, except for Pony cards with the Changeling keyword.": "{copy}",
"May count as either \u2642 or \u2640 for all Goals, Ships, and powers.": "{hermaphrodite}",
"This card counts as 2 Ponies.": "{double pony}",
"Instead of playing this Ship with a Pony card from your hand, or connecting two Pony cards already on the shipping grid, you may take a Pony card from the grid and reattach it elsewhere with this Ship. That card's power activates.": "{love poison}",
"When you attach this card to the grid, you may choose one Pony card attached to this Ship. Until the end of your turn, that Pony card gains one keyword of your choice, except for Pony names.": "{keyword change}",
"When you attach this card to the grid, you may choose one Pony card attached to this Ship. Until the end of your turn, that Pony card becomes the opposite gender.": "{gender change}",
"When you attach this card to the grid, you may choose one Pony card attached to this Ship. Until the end of your turn, that Pony card becomes the race of your choice. This cannot affect Pony cards with the Changeling keyword.": "{race change}",
"When you attach this card to the grid, you may choose one Pony card attached to this Ship. Until the end of your turn, that Pony card's timeline becomes \uE004.": "{timeline change}",
"You may choose to play the top card of the Pony discard pile with this Ship, rather than play a Pony card from your hand.": "{play from discard}",
"When you attach this card to the grid, you may choose one Pony card attached to this Ship. Until the end of your turn, that Pony card counts as 2 Ponies.": "{clone}",
"\u2642":"{male}",
"\u2640":"{female}",
"\u26A4":"{malefemale}",
"\u2764":"{ship}",
"\uE000":"{earthpony}",
"\uE001":"{unicorn}",
"\uE002":"{pegasus}",
"\uE003":"{alicorn}",
"\uE004":"{postapocalypse}",
"`":""
};
str = doReplace(SPECIAL_REPLACE, str);
str = str.replace(/\r\n/g, "\\n");
return str.replace(/\n/g, "\\n");
}
function search_classes(element, search_array){
var i;
for (i = 0; i < search_array.length; i++) {
if (element.hasClass(search_array[i]))
return search_array[i];
}
return "";
}
function html_to_pycard(){
var html_element = $(".card"),
html_name = $(".card .name").val(),
html_keywords = $(".card .attrs").val(),
html_body = $(".card .effect").val(),
html_flavor = $(".card .flavour").val(),
html_copyright = $(".card .copyright").val(),
html_art = $("#image").val(),
pycard_type, pycard_art, pycard_symbols, pycard_name,
pycard_keywords, pycard_body, pycard_flavor, pycard_copyright,
pycard_expansion, race, gender, points, outstr;
pycard_type = search_classes(html_element,
["pony", "ship", "goal", "start"]);
//Types are case-sensitive and must be capitalized
pycard_type = pycard_type[0].toUpperCase() + pycard_type.slice(1);
pycard_art = sanitize(html_art);
pycard_name = sanitize(html_name);
pycard_keywords = sanitize(html_keywords);
pycard_body = sanitize(html_body);
pycard_flavor = sanitize(html_flavor);
pycard_copyright = sanitize(html_copyright);
pycard_symbols = [];
gender = search_classes(html_element, ["male", "female", "malefemale"]);
if (gender != "")
pycard_symbols.push(gender);
race = search_classes(html_element,
["unicorn", "pegasus", "earthpony", "alicorn"]);
if (race != "") {
if (html_element.hasClass("changeling"))
race = "changeling" + race;
pycard_symbols.push(race)
}
if (html_element.hasClass("time"))
pycard_symbols.push("dystopian");
if (pycard_type === "Ship")
pycard_symbols = ["ship"];
else if (pycard_type === "Goal"){
pycard_symbols = ["goal"];
points = search_classes(html_element,
["s0", "s1", "s2", "s3",
"s4", "s2-3", "s3-4"]);
if (points != "")
pycard_symbols.push(points.slice(1));
else
pycard_symbols.push("0");
}
pycard_expansion = search_classes(html_element,
["web-outline", "web-white", "web-grey"]);
//Last two are "expansion" and "client", which we don't support yet
outstr = pycard_type + "`" + pycard_art + "`" + pycard_symbols.join("!")
+ "`" + pycard_name + "`" + pycard_keywords + "`" + pycard_body
+ "`" + pycard_flavor + "`" + pycard_expansion
+ "`" + pycard_copyright;
return outstr;
}
function generate_hash(hashtype){
var tmphash = '';
switch(hashtype) {
case "raw":
tmphash = html_to_pycard();
break;
case "v1":
tmphash = LZString.compressToBase64(html_to_pycard());
break;
default:
hashtype = "v1";
tmphash = LZString.compressToBase64(html_to_pycard());
}
return "#" + hashtype + ":" + tmphash;
}
function cardChanged(){
var tmphash;
if (typeof(HASH_TO_LOAD) === "string") {
tmphash = HASH_TO_LOAD;
HASH_TO_LOAD = null;
load_with_hash_type(tmphash);
} else {
//We don't want this change to trigger our load
$(window).off('hashchange', hashChanged);
document.location.hash = generate_hash(HASH_TYPE);
$(window).on('hashchange', hashChanged);
}
$("#shortUrl").val("");
$("#longUrl").val("");
}
function hashChanged(){
var hs, i;
hs = document.location.hash.slice(1)
i = hs.indexOf(":");
if (i != -1) {
HASH_TYPE = hs.slice(0,i);
load_with_hash_type(hs.slice(i+1));
}
}
function load_with_hash_type(loadstr){
switch(HASH_TYPE) {
case "rawtov1":
HASH_TYPE = "v1";
//intentionally falling through here
case "raw":
pycard_to_html(loadstr);
break;
case "v1toraw":
HASH_TYPE = "raw";
//intentionally falling through here
case "v1":
pycard_to_html(LZString.decompressFromBase64(loadstr));
break;
default:
HASH_TYPE="v1";
HASH_TO_LOAD = null;
}
cardChanged();
}
function pycard_to_html(pycard_str){
var pycard_arr,
pycard_symbols,
i,
card_element = $('.card');
//If there was a problem decompressing the hash, we may get passed a null
if (typeof(pycard_str) != "string")
return;
//Temporarily disable URL updating
$(".card input[type=text], .card textarea, #image").off("change paste",
cardChanged);
pycard_arr = pycard_str.replace(/\\n/g, "\n").split("`");
if (pycard_arr.length < 7)
return;
//Remove existing non-card classes
card_element.attr({"class": "card"});
// Card type = [0]
card_element.addClass(pycard_arr[0].toLowerCase());
// Card art = [1]
$("#image").val(pycard_arr[1]).change();
// Card symbols = [2]
pycard_symbols = pycard_arr[2].toLowerCase().replace(/ /g, "").split("!");
for (i = 0; i < pycard_symbols.length; i++) {
if (pycard_symbols[i].indexOf("changeling") === 0) {
card_element.addClass("changeling");
card_element.addClass(pycard_symbols[i].substr("changeling".length))
} else if (pycard_symbols[i][0] >= '0' && pycard_symbols[i][0] <= '9') {
// If it starts with a number, it's a goal symbol
card_element.addClass("s" + pycard_symbols[i]);
} else if (pycard_symbols[i] === "dystopian") {
card_element.addClass("time");
} else {
card_element.addClass(pycard_symbols[i]);
}
}
// Add in "empty" symbols
if ($('.card:not(.male,.female,.malefemale)').length > 0)
card_element.addClass("G");
if ($('.card:not(.earthpony,.unicorn,.pegasus,.alicorn)').length > 0)
card_element.addClass("R");
// Card title = [3]
$(".card .name").val(pycard_arr[3]).change();
// Card keywords = [4]
$(".card .attrs").val(pycard_arr[4]).change();
// Card body = [5]
$(".card .effect").val(pycard_arr[5]).change();
// Card flavor = [6]
$(".card .flavour").val(pycard_arr[6]).change();
// Card expansion symbol = [7]
if (["web-outline", "web-grey", "web-white"].indexOf(pycard_arr[7]) != -1)
card_element.addClass(pycard_arr[7]);
// Card copyright string = [8]
$(".card .copyright").val(pycard_arr[8]).change();
//Re-enable URL updating
$(".card input[type=text], .card textarea, #image").on("change paste",
cardChanged);
}
function exportCard(id){
$.ajax({
type: "POST",
contentType: "application/json",
url: "/TSSSF/ponyimage.php",
dataType: "json",
data: JSON.stringify({
pycard:html_to_pycard(),
returntype:"encoded_url",
imagetype: "vassal"
})
}).done(function(r){
console.log(r);
if(mayError(r)) {return;}
$('.preview-lightbox img').attr('src', r["image"]);
$.featherlight($('.preview-lightbox'));
$('.featherlight-content div[data-tabname]').each(function(){
$(this).attr('id', $(this).attr("data-tabname"));
});
});
}
function imgurWrapper(){
if ($('.featherlight-content input[value="linkthis"]').is(":checked")) {
shorten_url(generate_hash("v1"), function(s_url){
saveCardToImgur(s_url);
});
} else {
saveCardToImgur();
}
}
function downloadDataUrl(url, filename){
var tmplink = document.createElement('a'),
clickEvent = new MouseEvent("click", {
"view": window,
"bubbles": true,
"cancelable": false
});
if (!url.match(/^data:/))
console.log("downloadDataUrl is only designed to " +
"download 'data:' URLs, not " + url);
if (filename != "")
tmplink.download = filename + ".png";
else
tmplink.download = "card.png";
tmplink.href = url;
tmplink.dispatchEvent(clickEvent);
}
function saveCardToDownload(){
$.ajax({
type: "POST",
contentType: "application/json",
url: "/TSSSF/ponyimage.php",
dataType: "json",
data: JSON.stringify({
pycard:html_to_pycard(),
returntype:"encoded_url",
imagetype:$('.featherlight-content input[name=exportType]:checked').val()
})
}).done(function(r){
if(mayError(r)) {return;}
downloadDataUrl(r["image"],
$('.card .name').val().replace(/[^a-z0-9]/gi, "_").toLowerCase());
});
}
function saveCardToImgur(my_url){
$.ajax({
type: "POST",
contentType: "application/json",
url: "/TSSSF/ponyimage.php",
dataType: "json",
data: JSON.stringify({
pycard:html_to_pycard(),
returntype:"imgur",
imagetype:$('.featherlight-content input[name=exportType]:checked').val(),
my_url: my_url
})
}).done(function(r){
if(mayError(r)) {return;}
$('.featherlight-content input[type="text"]').removeClass("empty");
$('.featherlight-content input[type="text"]').val(r["image"]);
open(r["image"]);
});
}
function cardSetup(){
//Check the hash to see if we are loading something
if(document.location.hash){
console.log("Document hash is currently " + document.location.hash);
hs = document.location.hash.substr(1)
i = hs.indexOf(":");
if (i != -1) {
HASH_TYPE = hs.slice(0,i);
HASH_TO_LOAD = hs.slice(i+1);
}
}
//On card button clicks, remove other classes and add new ones.
//Unless it is changeling, special case, just toggle.
$(".card button").on("click", function(){
var oldClass = "";
var newClass = $(this).attr("value");
if (newClass == "changeling"){
$(".card").toggleClass($(this).attr("value"));
} else {
$(this).parent().children("button").each(function(){
if ($(this).attr("value") != "changeling"){
if ($(".card").hasClass($(this).attr("value"))) {
oldClass = $(this).attr("value");
}
$(".card").removeClass($(this).attr("value"));
}
});
$(".card").addClass(newClass);
if ((oldClass == "ship" || oldClass == "goal") &&
(newClass == "pony" || newClass == "start")) {
$(".card").addClass("malefemale");
$(".card").addClass("unicorn");
} else if (oldClass != "goal" && newClass == "goal") {
$(".card").addClass("s0");
}
}
});
//On Window resize we use css transformation to scale the card to fix
//Yes it seems horrible but the alternative was somehting even more horrible!
$(window).resize(function(){
var f = ($(".cardwrapper").width())/788;
$(".card").css("transform","scale("+f+")")
$(".cardwrapper").height(1088*f);
});
//Constant infomation for special escape code handling.
var SPECIAL_REPLACE = {
"{male}":"\u2642",
"{female}":"\u2640",
"{malefemale}":"\u26A4",
"{ship}":"\u2764",
"{earth}":"\uE000",
"{earthpony}":"\uE000",
"{unicorn}":"\uE001",
"{pegasus}":"\uE002",
"{alicorn}":"\uE003",
"{postapocalypse}":"\uE004",
"{replace}": "While this card is in your hand, you may discard a Pony card from the grid and play this card in its place. This power cannot be copied.",
"{swap}": "You may swap 2 Pony cards on the shipping grid.",
"{3swap}": "You may swap up to 3 Pony cards on the grid.",
"{draw}": "You may draw 1 card from the Ship or Pony deck.",
"{goal}": "You may discard 1 active Goal and draw 1 new Goal to replace it.",
"{search}": "You may search the Ship or Pony discard pile for 1 card of your choice and put it into your hand. If it's still in your hand at the end of your turn, discard it.",
"{copy}": "You may copy the power of any Pony card currently on the shipping grid, except for Pony cards with the Changeling keyword.",
"{hermaphrodite}": "May count as either \u2642 or \u2640 for all Goals, Ships, and powers.",
"{double pony}": "This card counts as 2 Ponies.",
"{love poison}": "Instead of playing this Ship with a Pony card from your hand, or connecting two Pony cards already on the shipping grid, you may take a Pony card from the grid and reattach it elsewhere with this Ship. That card's power activates.",
"{keyword change}": "When you attach this card to the grid, you may choose one Pony card attached to this Ship. Until the end of your turn, that Pony card gains one keyword of your choice, except for Pony names.",
"{gender change}": "When you attach this card to the grid, you may choose one Pony card attached to this Ship. Until the end of your turn, that Pony card becomes the opposite gender.",
"{race change}": "When you attach this card to the grid, you may choose one Pony card attached to this Ship. Until the end of your turn, that Pony card becomes the race of your choice. This cannot affect Pony cards with the Changeling keyword.",
"{timeline change}": "When you attach this card to the grid, you may choose one Pony card attached to this Ship. Until the end of your turn, that Pony card's timeline becomes \uE004.",
"{play from discard}": "You may choose to play the top card of the Pony discard pile with this Ship, rather than play a Pony card from your hand.",
"{clone}": "When you attach this card to the grid, you may choose one Pony card attached to this Ship. Until the end of your turn, that Pony card counts as 2 Ponies."
};
//Replace special escape codes when an input is updated
$(".card input[type=text], .card textarea").on("change",function(){
var txt = $(this).val();
txt = doReplace(SPECIAL_REPLACE, txt);
$(this).val(txt)
});
//Replace and create tooltip hints
$.each(SPECIAL_REPLACE,function(key,replace){
//console.log([key,replace,"dt[data-original-title='"+key+"']",$("dt[data-original-title='"+key+"']")]);
$("dt[data-original-title='"+key+"']").attr("data-original-title",replace).tooltip();
});
$(".card .name").on("change keyup paste",function(){
var t = $(this),
o = $(".cardHelper .name");
t.toggleClass("small", (t.val().match(/\n/g)||[]).length > 0);
o.toggleClass("small", (t.val().match(/\n/g)||[]).length > 0);
});
//When a text editor is updated resize its helper to clone back the height.
//This is because CSS Really hates working vertically
$(".card textarea").on("change keyup paste",function(){
var t = $(this),
o = $(".cardHelper ." + t.attr("class").replace(/ /g, "."));
o.text(t.val() + " ");
t.height(o.height());
});
//Update image
$("#image").change(function(){
var image_sites = [/^https?:\/\/i\.imgur\.com\//,
/^https?:\/\/img\.booru\.org\/secretshipfic\//,
/^https?:\/\/derpicdn.net\//,
/^https?:\/\/(localhost|127\.[\d.]+|\[[0:]+1\])(:\d+)?\//],
html_sites = [/^https?:\/\/(www\.)?imgur\.com\//,
/^https?:\/\/secretshipfic\.booru\.org\//,
/^https?:\/\/(www\.)?derpiboo\.ru\//],
regex_matched = false,
i;
$("#error").hide();
for (i = 0; i < image_sites.length; i++) {
if (image_sites[i].test($(this).val())) {
regex_matched = true;
break;
}
}
if (regex_matched === true || $(this).val() === "") {
$(".card .image").css("background-image","url('"+$(this).val()+"')");
} else {
$(".card .image").css("background-image","url('')");
for (i = 0; i < html_sites.length; i++) {
if (html_sites[i].test($(this).val())) {
regex_matched = true;
break;
}
}
if (regex_matched === true) {
mayError({error: "Image URL Not Allowed",
details: "Reminder: you have to link the image itself," +
" not the HTML page it comes from."});
} else {
mayError({error: "Image URL Not Allowed",
details: "Reminder: the image must be from one of the" +
" allowed imagehosts"});
}
}
});
//Trigger URL update
$(".card input[type=text], .card textarea, #image").on("change paste",
cardChanged);
$(".card button").on("click", cardChanged);
$(window).on('hashchange', hashChanged);
//Save, New & Export buttons
$("#save").click(save);
$("#new").click(newCard);
$("#export").click(exportCard);
$("#save_imgur").click(imgurWrapper);
$("#save_download").click(saveCardToDownload);
//Log number of ajax events for the spinner
var AJAX_EVENTS = 0;
$( document ).ajaxSend(function(){
AJAX_EVENTS++;
$("#working").show();
$("#error").hide();
}).ajaxComplete(function() {
if ( --AJAX_EVENTS == 0 ) {
$("#working").hide();
}
});
//Inital call setup functions
$(window).resize();
$(".card textarea").change();
}