forked from Goctionni/KinkList
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
1867 lines (1696 loc) · 57.9 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
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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use strict";
function createHTMLElement(cssSelector, inner, attributes) {
/* Separates tag from additional componenets.
* Permitted components, in any order:
* .classname
* #ID
* [attribute] or [attribute=value]
* Must be without any spaces, permitted characters: A-Za-z0-9_-
* Example: button#ExportButton.hidden[disabled]
*/
const regex = /([\w-]+)((?:(?:[#.][\w-]+)|(?:\[[\w-]+(?:=[\w-]*)?\]))+)?/;
const [_, tag, components] = cssSelector.match(regex);
const element = document.createElement(tag);
if (inner != undefined) {
if (Array.isArray(inner))
inner.forEach(e => element.appendChild(e));
else if (typeof inner == "object")
element.appendChild(inner);
else
element.textContent = inner;
}
for (let name in attributes) {
element.setAttribute(name, attributes[name]);
}
if (components) {
const classRegex = /\.[\w-]+/g
const idRegex = /\#[\w-]+/g
const attributeRegex = /\[[\w-]+(?:=[\w-]*)?\]/g
const classes = (components.match(classRegex) || []).map(x => x.slice(1));
const ids = (components.match(idRegex) || []).map(x => x.slice(1));
const attributes =
(components.match(attributeRegex) || []).map(x => x.slice(1, -1));
for (let className of classes) {
element.classList.add(className);
}
for (let id of ids) {
element.id = id;
}
for (let attribute of attributes) {
const [name, value] = attribute.split('=');
element.setAttribute(name, value || '');
}
}
return element;
}
function removeInnerNodes(element) {
while (element.firstChild) {
element.removeChild(element.firstChild);
}
}
function capitalize(str) {
return str[0].toUpperCase() + str.slice(1);
}
function decapitalize(str) {
return str[0].toLowerCase() + str.slice(1);
}
function toCSSClassName(str) {
const className = str
.toLowerCase()
.match(/[a-z]\w*/g)
.map(capitalize)
.join('');
return decapitalize(className);
}
function hide(element) {
const classList = element.classList;
const transitionMap = new Map([
["hidden", "hidden"],
["invisible", "invisible"],
["unhidden", "hidden"],
["visible", "invisible"],
]);
for (let className of transitionMap.keys()) {
if (classList.contains(className)) {
classList.remove(className);
classList.add(transitionMap.get(className));
return;
}
}
classList.add("hidden");
}
function unhide(element) {
const classList = element.classList;
const transitionMap = new Map([
["unhidden", "unhidden"],
["visible", "visible"],
["hidden", "unhidden"],
["invisible", "visible"],
]);
for (let className of transitionMap.keys()) {
if (classList.contains(className)) {
classList.remove(className);
classList.add(transitionMap.get(className));
return;
}
}
classList.add("hidden");
}
function isHidden(element) {
let result = false;
result |= element.classList.contains("hidden")
|| element.classList.contains("invisible");
if (!result) {
const style = window.getComputedStyle(element);
result |= style.display == "none"
|| style.opacity == 0
|| style.visibility == "hidden"
}
return result;
}
function fadeIn(element) {
return new Promise((resolve, reject) => {
if (isHidden(element)) {
element.style.opacity = 0;
unhide(element);
(function fade() {
let opacity = +element.style.opacity;
opacity += 0.1;
if (opacity <= 1){
element.style.opacity = opacity;
requestAnimationFrame(fade);
} else {
resolve();
}
})();
}
});
}
function fadeOut(element) {
return new Promise((resolve, reject) => {
if (!isHidden(element)) {
element.style.opacity = 1;
(function fade() {
let opacity = +element.style.opacity;
opacity -= 0.1;
if (opacity >= 0) {
element.style.opacity = opacity;
requestAnimationFrame(fade);
} else {
hide(element);
resolve();
}
})();
}
});
}
function focus(element) {
window.setTimeout(() => element.focus(), 0);
}
function binarySearch(min, max, searchFunction) {
while (min < max) {
const mid = Math.floor((min + max) / 2);
if (searchFunction(mid)) {
max = mid;
} else {
min = mid + 1;
}
}
return min;
}
function partitionIntoColumns(heights, amount) {
function partitionUnder(heights, maxHeight) {
const columns = [];
let columnHeight = 0;
for (let i = 0; i < heights.length; i++) {
if (columnHeight + heights[i] > maxHeight) {
columnHeight = 0;
columns.push(i);
}
columnHeight += heights[i];
}
columns.push(heights.length);
return columns;
}
function canPartitionUnder(heights, amount, maxHeight) {
return partitionUnder(heights, maxHeight).length <= amount;
}
const maxHeight = heights.reduce((x, y) => Math.max(x, y));
const totalHeight = heights.reduce((x, y) => x + y);
const searchFunction = canPartitionUnder.bind(null, heights, amount);
const target = binarySearch(maxHeight, totalHeight, searchFunction);
return partitionUnder(heights, target);
}
function spreadAcrossColumns(array, partitioning) {
const columns = [];
let start = 0;
for (let end of partitioning) {
columns.push(array.slice(start, end));
start = end;
}
return columns;
}
const cssStylesheet = document.styleSheets[0];
const defaultSettings = {
legend: [
['Not Entered', '#FFFFFF'],
['Favorite' , '#6DB5FE'],
['Like' , '#23FD22'],
['Okay' , '#FDFD6B'],
['Maybe' , '#DB6C00'],
['No' , '#920000'],
],
data: "#Bodies\n(General)\n* Skinny\n* Chubby\n* Small breasts\n* Large breasts\n* Small cocks\n* Large cocks\n\n#Clothing\n(Self, Partner)\n* Clothed sex\n* Lingerie\n* Stockings\n* Heels\n* Leather\n* Latex\n* Uniform / costume\n* Cross-dressing\n\n#Groupings\n(General)\n* You and 1 male\n* You and 1 female\n* You and MtF trans\n* You and FtM trans\n* You and 1 male, 1 female\n* You and 2 males\n* You and 2 females\n* Orgy\n\n#General\n(Giving, Receiving)\n* Romance / Affection\n* Handjob / fingering\n* Blowjob\n* Deep throat\n* Swallowing\n* Facials\n* Cunnilingus\n* Face-sitting\n* Edging\n* Teasing\n* JOI, SI\n\n#Ass play\n(Giving, Receiving)\n* Anal toys\n* Anal sex, pegging\n* Rimming\n* Double penetration\n* Anal fisting\n\n#Restrictive\n(Self, Partner)\n* Gag\n* Collar\n* Leash\n* Chastity\n* Bondage (Light)\n* Bondage (Heavy)\n* Encasement\n\n#Toys\n(Self, Partner)\n* Dildos\n* Plugs\n* Vibrators\n* Sounding\n\n#Domination\n(Dominant, Submissive)\n* Dominant / Submissive\n* Domestic servitude\n* Slavery\n* Pet play\n* DD/lg, MD/lb\n* Discipline\n* Begging\n* Forced orgasm\n* Orgasm control\n* Orgasm denial\n* Power exchange\n\n#No consent\n(Aggressor, Target)\n* Non-con / rape\n* Blackmail / coercion\n* Kidnapping\n* Drugs / alcohol\n* Sleep play\n\n#Taboo\n(General)\n* Incest\n* Ageplay\n* Interracial / Raceplay\n* Bestiality\n* Necrophilia\n* Cheating\n* Exhibitionism\n* Voyeurism\n\n#Surrealism\n(Self, Partner)\n* Futanari\n* Furry\n* Vore\n* Transformation\n* Tentacles\n* Monster or Alien\n\n#Fluids\n(General)\n* Blood\n* Watersports\n* Scat\n* Lactation\n* Diapers\n* Cum play\n\n#Degradation\n(Giving, Receiving)\n* Glory hole\n* Name calling\n* Humiliation\n\n#Touch & Stimulation\n(Actor, Subject)\n* Cock/Pussy worship\n* Ass worship\n* Foot play\n* Tickling\n* Sensation play\n* Electro stimulation\n\n#Misc. Fetish\n(Giving, Receiving)\n* Fisting\n* Gangbang\n* Breath play\n* Impregnation\n* Pregnancy\n* Feminization\n* Cuckold / Cuckquean\n\n#Pain\n(Giving, Receiving)\n* Light pain\n* Heavy pain\n* Nipple clamps\n* Clothes pins\n* Caning\n* Flogging\n* Beating\n* Spanking\n* Cock/Pussy slapping\n* Cock/Pussy torture\n* Hot Wax\n* Scratching\n* Biting\n* Cutting",
state: '',
username: "Anonymous",
}
class KinklistError extends Error {
constructor(message) {
super(message);
this.name = "KinklistError";
if (Error.captureStackTrace) {
Error.captureStackTrace(this, KinklistError);
}
}
}
class Interface {
constructor(object) {
this.object = object;
this.prefix = '';
}
get element() {
if (!this._element) {
this._element = this.createElement();
}
return this._element;
}
set element(element) {
this._element = element;
}
get cssClassName() {
return this.prefix + toCSSClassName(this.object.name);
}
createElement() {return null} // Inherited classes need to define this method.
refresh() {
if (this._element) {
const newElement = this.createElement();
if (this.element.parentNode) {
this.element.parentNode.replaceChild(newElement, this.element);
}
this.element = newElement;
}
}
}
class SelectionOptionInterface extends Interface {
constructor(selectionOption) {
super(selectionOption);
this.prefix = "option-";
}
get cssRule() {
return `.${this.cssClassName} {background-color: ${this.object.color};}`;
}
createElement() {
const tag = `button.circle.${this.cssClassName}` +
`[title=${this.object.name}]`
const element = createHTMLElement(tag);
return element;
}
}
class SelectionInterface extends Interface {
constructor(selection) {
super(selection);
this.prefix = "selection";
}
createElement() {
const selection = this.object;
for (let selectionOption of selection.options) {
selectionOption.interface.element.addEventListener('mousedown', () => {
if (selection.value == selectionOption) {
selection.deselect();
} else {
selection.updateSelection(selectionOption);
}
});
}
const selectionOptionElements =
selection.options.map(selectionOption =>
selectionOption.interface.element);
const element = createHTMLElement("div.selection", selectionOptionElements);
return element;
}
update() {
this.object.options
.map(selectionOption => selectionOption.interface.element)
.forEach((element) => {
element.classList.remove("selected");
});
if (this.object.value) {
this.object.value.interface.element.classList.add("selected");
}
}
}
class KinkInterface extends Interface {
constructor(kink) {
super(kink);
this.prefix = "kink-"
}
createElement() {
const cellElements = [];
const selections = this.object.selections;
for (let selection of selections) {
cellElements.push(createHTMLElement("td", selection.interface.element));
}
cellElements.push(createHTMLElement("td", this.object.name));
const element = createHTMLElement(`tr.kinkrow.${this.cssClassName}`,
cellElements);
return element;
}
}
class CategoryInterface extends Interface {
constructor(category) {
super(category);
this.prefix = "cat-";
this.element = this.createElement();
}
get height() {
return this.calculateHeight();
}
createTableElement() {
const classedTh = (name) => name ? "th.selection-column" : "th";
const headerCellElements = [...this.object.columnNames, '']
.map(name => createHTMLElement(classedTh(name), name));
const theadElement = createHTMLElement("thead", headerCellElements);
const tbodyElement = createHTMLElement("tbody",
this.object.kinks.map(kink => kink.interface.element));
const tableElement = createHTMLElement("table.kinkGroup",
[theadElement, tbodyElement]);
return tableElement;
}
createElement() {
const tableElement = this.createTableElement();
const titleElement = createHTMLElement("h2", this.object.name);
const divElement =
createHTMLElement(`div.kinkCategory.${this.cssClassName}}`,
[titleElement, tableElement]);
return divElement;
}
calculateHeight(force) {
let height;
if (this.element.clientHeight) {
height = this.element.clientHeight;
} else if (force) {
const clone = this.element.cloneNode(true);
clone.style.visibility = "hidden";
document.body.append(clone);
height = clone.clientHeight;
clone.remove();
} else {
const margins = 20;
const h2 = 27;
const tableRow = 25;
height = margins + h2 + tableRow * (this.object.kinks.length + 1);
}
return height;
}
refresh() {
super.refresh();
this.calculateHeight();
}
}
class KinklistInterface extends Interface {
constructor(kinklist) {
super(kinklist);
this.hasCategoriesChanged = false;
this.element = document.querySelector(".kinklist");
}
createElement() {
const columnAmount =
Math.min(4, Math.floor((document.body.scrollWidth - 20) / 400) || 1);
const categories = this.object.categories;
const columns = [];
if (categories.length) {
const categoryHeights =
categories.map(category => category.interface.height);
const partitioning = partitionIntoColumns(categoryHeights, columnAmount);
columns.push(...spreadAcrossColumns(categories, partitioning));
}
const categoryElements = columns.map(column => {
return column.map(category => category.interface.element);
});
const columnElements =
categoryElements.map(column => createHTMLElement("div", column));
const element = createHTMLElement("div.kinklist", columnElements);
return element;
}
appendCSSRuleToStylesheet(rule) {
cssStylesheet.insertRule(rule, 0);
}
updateColors() {
const legend = this.object.legend
.map(([name, color]) => new SelectionOption(name, color));
legend
.map(option => option.interface.cssRule)
.forEach(this.appendCSSRuleToStylesheet);
}
updateLegend() {
const selectionOptions = this.object.legend
.map(option => new SelectionOption(...option));
const legendOptionElements = selectionOptions.map(option => {
const legendText = createHTMLElement("span.selection-name", option.name);
const legendMarker =
createHTMLElement(`span.circle.${option.interface.cssClassName}`);
const optionDiv = createHTMLElement("div.selection",
[legendMarker, legendText]);
return optionDiv;
});
const legendElement = document.querySelector(".legend");
removeInnerNodes(legendElement);
legendElement.append(...legendOptionElements);
}
}
class SelectionOption {
constructor(name, color, selection) {
this.selection = selection;
this.name = name;
this.color = color;
this.interface = new SelectionOptionInterface(this);
}
equals(selectionOption) {
return (this.name == selectionOption.name) &&
(this.color == selectionOption.color);
}
}
class Selection {
constructor(legend, kink) {
this.kink = kink;
this.options = legend
.map(option => new SelectionOption(...option, this));
this._value = null;
this.defaultValue = new SelectionOption("Not selected", "#FFFFFF", this);
this.interface = new SelectionInterface(this);
}
get value() {return this._value};
set value(value) {
if (!(this.options.includes(value) || value == null)) {
throw new KinklistError("Illegal value.");
}
this._value = value;
this.interface.update();
const event = new CustomEvent("kinklist-stateUpdate", {bubbles: true});
this.interface.element.dispatchEvent(event);
}
get apparentValue() {
return this._value || this.defaultValue;
}
get columnName() {
const kink = this.kink;
const columnNames = kink.category.columnNames;
let columnName = '';
if (columnNames.length > 1) {
columnName = columnNames[kink.selections.findIndex(x => x == this)];
}
return columnName;
}
updateSelection(value) {
if (value == null) {
this.value = null;
return;
}
if (!value instanceof SelectionOption) {
throw new KinklistError("Value is not SelectionOption.");
}
if (!this.options.includes(value)) {
throw new KinklistError(`Selection value "${value.name}" out of bounds.`);
}
this.value = value;
}
deselect() {
this.value = null;
}
equals(selection) {
return (this.options.length == selection.options.length) &&
(this.options.every((option, index) =>
option.equals(selection.options[index])));
}
}
class Kink {
constructor(name, category) {
this.category = category;
this.name = name;
//this.description = description;
this.selections = [];
this.interface = new KinkInterface(this);
}
get columnAmount() {
if (this.category) {
return this.category.columnNames.length;
} else return 0;
}
get category() {return this._category};
set category(value) {
if (this._category == value) return;
if (!value) return;
this._category = value;
this.update();
}
update() {
const newSelections = [];
const legend = this.category.kinklist.legend;
for (let i = 0; i < this.columnAmount; i++) {
newSelections.push(new Selection(legend, this));
}
this.selections = newSelections;
this.interface.refresh();
}
}
class Category {
constructor(name, columnNames, kinks, kinklist) {
this.kinklist = kinklist;
this.name = name;
this.columnNames = columnNames;
this.kinks = kinks || [];
this.interface = new CategoryInterface(this);
}
get kinks() {return this._kinks};
set kinks(kinkObjects) {
this._kinks = kinkObjects;
this.linkKinks();
}
addKink(kink) {
kink.category = this;
this.kinks.push(kink);
this.interface.refresh();
}
updateKinks(kinkObjects) {
this.kinks = kinkObjects;
this.interface.refresh();
}
linkKinks() {
for (let kink of this.kinks) {
kink.category = this;
}
}
}
class Kinklist {
constructor(preset) {
this.categories = [];
this.interface = new KinklistInterface(this);
this.preset = preset;
}
get preset() {return this._preset};
get data() {return this._data};
get legend() {return this._legend};
set preset(value) {
this._preset = value;
this.legend = value.legend;
this.data = value.data;
this.state = value.state;
}
set data(value) {
value = this.sanitizeKinklistSettingsInput(value);
this._data = value;
this.parseKinklistSettings(value);
}
set legend(value) {
this._legend = value;
this.interface.updateColors();
this.interface.updateLegend();
}
get kinks() {
const kinks = this.categories.map(category => category.kinks)
.reduce((pv, array) => pv.concat(...array), []); // Same as .flat();
return kinks;
}
get state() {
const encodedSelections = [];
for (let kink of this.kinks) {
for (let selection of kink.selections) {
const index = selection.options.indexOf(selection.value) + 1;
encodedSelections.push(index);
}
}
return (encodedSelections.join('').match(/\d*[1-9]/) || [""])[0];
}
set state(stateString) {
const encodedSelections = stateString.split('');
for (let kink of this.kinks) {
for (let selection of kink.selections) {
const index = encodedSelections.shift() || 0;
const value = index ? selection.options[index - 1] : null;
selection.updateSelection(value);
}
}
this.preset.state = stateString;
}
appendCategory(...categories) {
for (let category of categories) {
this.categories.push(category);
}
}
removeCategory(...categoriesToRemove) {
this.categories = this.categories
.filter(category => !categoriesToRemove.includes(category));
}
flush() {
for (let kink of this.kinks) {
for (let selection of kink.selections) {
selection.deselect();
}
}
}
parseKinklistSettings(inputString) {
if (!inputString) {
throw new KinklistError("Input string empty.");
}
const regexp = new RegExp(/#(.+)\n\((.+)\)\n((?:\*.+\n?)+)/g);
let match;
let categories = [];
while ((match = regexp.exec(this.data))) {
const category = {};
category.name = match[1];
category.columns = match[2].split(/,\s+/);
category.kinks = match[3]
.trim()
.split('\n')
.map(kinkString => kinkString.replace(/\*\s*/, ''));
categories.push(category);
}
const newCategories = [];
const extraCategories = new Set(this.categories);
const categoryNames = [];
categories.forEach(categoryData => {
let {name, columns, kinks} = categoryData;
categoryNames.push(name);
kinks = kinks.map(kinkName =>
this.kinks.find(kinkObject =>
kinkObject.name == kinkName)
|| new Kink(kinkName)
);
let existingCategory = this.categories
.find(category => category.name == name);
if (existingCategory) {
existingCategory.updateKinks(kinks);
extraCategories.delete(existingCategory);
}
else
newCategories.push(new Category(name, columns, kinks, this));
});
if (extraCategories) this.removeCategory(...extraCategories);
if (newCategories) this.appendCategory(...newCategories);
// Sort categories in order they were specified in the list.
this.categories =
categoryNames.map(name => this.categories
.find(category => category.name == name));
this.interface.refresh();
}
sanitizeKinklistSettingsInput(kinklistSettings) {
let sanitized = kinklistSettings;
sanitized = sanitized.replace(/ ?\/ ?/g, "/"); // Zero-width spaces.
return sanitized;
}
}
class Font {
constructor(fontString) {
const match = /(?:(\w+)\s+)?(\d+)px\s+(\w+)/.exec(fontString);
[this.value, this.style, this.size, this.font] = match;
this.size = +this.size;
}
}
class Drawcall {
constructor(x, y, data) {
this.x = x;
this.y = y;
for (const key in data) {
if (key != 'x' && key != 'y') this[key] = data[key];
}
}
}
class KinklistCanvasDrawerCircleSettings {
constructor(circleObject) {
for (const key in circleObject) {
this[key] = circleObject[key];
}
}
get size() {
return this.radius + this.margin + this.border.width;
}
}
class KinklistCanvasDrawer {
constructor(kinklistObject, username) {
this.kinklist = kinklistObject;
this.username = username;
this.settings = {
margins: {
// Global.
top: 10,
bottom: 10,
left: 10,
right: 10,
// Vertical spacing between:
// Kinklist title and categories
title: 10,
// Category title and subtitle
subtitle: 3,
// Kinks
kink: 2,
// Category title and first kink
categoryTitle: 10,
// Categories
category: 10,
// Horizontal spacing between:
// Legend elements
legend: 3,
// Selection circle and kink name
kinkText: 5,
},
column: {
amount: 6,
width: 250,
},
legend: {
width: 120,
},
canvas: {
width: 1520,
//height: 1200,
backgroundColor: "#FFFFFF",
},
circle: new KinklistCanvasDrawerCircleSettings({
radius: 8,
color: "#FFFFFF",
margin: 1,
border: {
width: 1,
color: "#0000007F",
},
}),
text: {
legend: new Font("bold 13px Arial"),
title: new Font("bold 24px Arial"),
categoryTitle: new Font("bold 12px Arial"),
categorySubtitle: new Font("italic 12px Arial"),
kinkTitle: new Font("12px Arial"),
color: "#000000",
align: "start",
baseline: "middle",
},
}
this.canvas = this.createCanvas();
this.context = this.createContext(this.canvas);
}
get filename() {
return `Kinklist (${this.username}).png`;
}
createCanvas(height = this.settings.canvas.height,
width = this.settings.canvas.width) {
const canvas = createHTMLElement("canvas.kinklist-canvas", null,
{width: width, height: height});
canvas.height = height;
canvas.width = width;
canvas.addEventListener("click", () => {
let anchor = document.createElement("a");
anchor.href = canvas.toDataURL();
anchor.download = this.filename;
anchor.click();
});
return canvas;
}
createContext(canvas = this.canvas) {
const context = canvas.getContext('2d');
context.fillStyle = this.settings.canvas.backgroundColor;
context.fillRect(0, 0, canvas.width, canvas.height);
return context;
}
drawDebug(drawcall, context = this.context) {
const debugDrawcall =
new Drawcall(drawcall.x, drawcall.y,
{color:"#FF0000", radius:2, border:{width:0}});
this.drawCircle(debugDrawcall, context);
}
drawText(drawcall, context = this.context) {
//{text, font / color, align, baseline, debug}
const text = this.settings.text;
context.fillStyle = drawcall.color || text.color;
context.textAlign = drawcall.align || text.align;
context.textBaseline = drawcall.baseline || text.baseline;
context.font = drawcall.font.value;
context.fillText(drawcall.text, drawcall.x, drawcall.y);
if (drawcall.debug) {
this.drawDebug(drawcall, this.context);
context.beginPath();
context.moveTo(drawcall.x, drawcall.y);
context.lineTo(drawcall.x + context.measureText(text).width, drawcall.y);
context.strokeStyle = "#FF0000";
context.borderWidth = 1;
context.stroke();
console.log(context.measureText(text));
}
}
drawCircle(drawcall, context = this.context) {
// {color / radius, border: {width, color}, debug}
context.beginPath();
const x = drawcall.x;
const y = drawcall.y;
const circle = this.settings.circle;
const border = drawcall.border || circle.border;
const borderWidth = border.width;
const borderColor = border.color;
// By default border is drawn in the middle of a circumference,
// so we need to extend the radius to make the border face outwards.
const radius = (drawcall.radius || circle.radius) + borderWidth / 2;
const color = drawcall.color || circle.color;
context.arc(x, y, radius, 0, 2 * Math.PI, false);
context.fillStyle = color;
context.fill();
context.strokeStyle = borderColor;
context.lineWidth = borderWidth;
context.stroke();
if (drawcall.debug) this.drawDebug(drawcall, this.context);
}
drawKink(drawcall, context = this.context) {
// {kinkObject: {selections[]: {apparentValue: {color}}, name} / margin}
const circle = this.settings.circle;
for (const selection of drawcall.kinkObject.selections) {
const circleDrawcall =
new Drawcall(drawcall.x, drawcall.y,
{color: selection.apparentValue.color});
this.drawCircle(circleDrawcall, context);
drawcall.x += circle.size * 2;
}
drawcall.x -= circle.size;
// Avoiding nullish coalescing (??) for backwards compatibility with iOS.
drawcall.x += Number.isFinite(drawcall.margin)
? drawcall.margin : this.settings.margins.kinkText;
drawcall.y -= this.settings.text.kinkTitle.size / 2;
const textDrawcall =
new Drawcall(drawcall.x, drawcall.y,
{text: drawcall.kinkObject.name,
font: drawcall.font || this.settings.text.kinkTitle,
baseline: "top"});
this.drawText(textDrawcall, context);
}
drawCategory(drawcall, context = this.context) {
// {categoryObject}
const font = this.settings.text;
const circle = this.settings.circle;
const kinkHeight = Math.max(2 * circle.size, font.kinkTitle.size);
const categoryTitleDrawcall =
new Drawcall(drawcall.x, drawcall.y,
{text: drawcall.categoryObject.name,
font: font.categoryTitle});
this.drawText(categoryTitleDrawcall, context);
const subtitleExists = drawcall.categoryObject.columnNames.length > 1;
if (subtitleExists) {
drawcall.y += font.categoryTitle.size / 2;
drawcall.y += font.categorySubtitle.size / 2;
drawcall.y += this.settings.margins.subtitle;
const categorySubtitleDrawcall =
new Drawcall(drawcall.x, drawcall.y,
{text: drawcall.categoryObject.columnNames.join(', '),
font: font.categorySubtitle});
this.drawText(categorySubtitleDrawcall, context);
}
drawcall.x += circle.size;
drawcall.y += (font.categoryTitle.size + font.kinkTitle.size) / 2;
drawcall.y += this.settings.margins.categoryTitle;
for (const kinkObject of drawcall.categoryObject.kinks) {
const kinkDrawcall =
new Drawcall(drawcall.x, drawcall.y, {kinkObject: kinkObject});
this.drawKink(kinkDrawcall, context);
drawcall.y += kinkHeight + this.settings.margins.kink;
}
}
drawKinklist(kinklistObject = this.kinklist, context = this.context) {
const margins = this.settings.margins;
const font = this.settings.text;
const columns =
this.spreadCategoriesAcrossColumns(kinklistObject.categories);
const columnHeights =
columns.map(column => column.map(category =>
this.calculateCategoryHeight
.bind(this)(category))
.reduce((x, y) => (x + y + margins.category)));
const canvasHeight = Math.max(...columnHeights)
+ margins.top
+ margins.bottom
+ margins.title
+ font.title.size;
context.canvas.height = canvasHeight;
context.fillStyle = "white";
context.fillRect(0, 0, context.canvas.width, context.canvas.height);
let x = margins.left;
let y = margins.top;
let titleDrawcall =
new Drawcall(x, y, {text: `Kinklist (${this.username})`,
font: font.title,
baseline: "top"});
this.drawText(titleDrawcall, context);
let legendX = this.settings.canvas.width
- margins.right
- this.settings.legend.width
* kinklistObject.legend.length
+ this.settings.circle.size;
let legendY = y + this.settings.circle.size;
for (let [name, color] of kinklistObject.legend) {
let legendDrawcall =
new Drawcall(legendX, legendY,
{kinkObject: {
selections: [{apparentValue: {color: color}}],
name: name,
},
font: font.legend,
margin: margins.legend,