-
-
Notifications
You must be signed in to change notification settings - Fork 75
/
index.html
1620 lines (1620 loc) · 111 KB
/
index.html
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
<!DOCTYPE html>
<html lang="en">
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dotgrid</title>
</head>
<body>
<script>
'use strict'
function Acels (client) {
this.el = document.createElement('ul')
this.el.id = 'acels'
this.order = []
this.all = {}
this.pipe = null
this.install = (host = document.body) => {
window.addEventListener('keydown', this.onKeyDown, false)
window.addEventListener('keyup', this.onKeyUp, false)
host.appendChild(this.el)
}
this.start = () => {
const cats = this.sort()
for (const cat of this.order) {
const main = document.createElement('li')
const head = document.createElement('a')
head.innerText = cat
const subs = document.createElement('ul')
for (const item of cats[cat]) {
const option = document.createElement('li')
option.onclick = item.downfn
option.innerHTML = item.accelerator ? `${item.name} <i>${item.accelerator.replace('CmdOrCtrl+', '^')}</i>` : `${item.name}`
subs.appendChild(option)
}
main.appendChild(head)
main.appendChild(subs)
this.el.appendChild(main)
}
}
this.set = (cat, name, accelerator, downfn, upfn) => {
if (this.all[accelerator]) { console.warn('Acels', `Trying to overwrite ${this.all[accelerator].name}, with ${name}.`) }
if (this.order.indexOf(cat) < 0) { this.order.push(cat) }
this.all[accelerator] = { cat, name, downfn, upfn, accelerator }
}
this.get = (accelerator) => {
return this.all[accelerator]
}
this.sort = () => {
const h = {}
for (const item of Object.values(this.all)) {
if (!h[item.cat]) { h[item.cat] = [] }
h[item.cat].push(item)
}
return h
}
this.convert = (event) => {
const accelerator = event.key === ' ' ? 'Space' : capitalize(event.key.replace('Arrow', ''))
if ((event.ctrlKey || event.metaKey) && event.shiftKey) {
return `CmdOrCtrl+Shift+${accelerator}`
}
if (event.shiftKey && event.key.toUpperCase() !== event.key) {
return `Shift+${accelerator}`
}
if (event.altKey && event.key.length !== 1) {
return `Alt+${accelerator}`
}
if (event.ctrlKey || event.metaKey) {
return `CmdOrCtrl+${accelerator}`
}
return accelerator
}
this.route = (obj) => {
this.pipe = obj
}
this.onKeyDown = (e) => {
const target = this.get(this.convert(e))
if (!target || !target.downfn) { return this.pipe ? this.pipe.onKeyDown(e) : null }
target.downfn()
e.preventDefault()
}
this.onKeyUp = (e) => {
const target = this.get(this.convert(e))
if (!target || !target.upfn) { return this.pipe ? this.pipe.onKeyUp(e) : null }
target.upfn()
e.preventDefault()
}
this.toMarkdown = () => {
const cats = this.sort()
let text = ''
for (const cat in cats) {
text += `\n### ${cat}\n\n`
for (const item of cats[cat]) {
text += item.accelerator ? `- \`${item.accelerator}\`: ${item.name}\n` : ''
}
}
return text.trim()
}
this.toString = () => {
const cats = this.sort()
let text = ''
for (const cat of this.order) {
for (const item of cats[cat]) {
text += item.accelerator ? `${cat.padEnd(8, ' ')} ${item.name.padEnd(16, ' ')} ${item.accelerator.replace('CmdOrCtrl+', '^')}\n` : ''
}
}
return text.trim()
}
this.toggle = () => {
this.el.className = this.el.className === 'hidden' ? '' : 'hidden'
}
function capitalize (s) { return s.substr(0, 1).toUpperCase() + s.substr(1) }
}
'use strict'
function History () {
this.index = 0
this.a = []
this.clear = function () {
this.a = []
this.index = 0
}
this.push = function (data) {
if (this.index < this.a.length - 1) {
this.fork()
}
this.index = this.a.length
this.a = this.a.slice(0, this.index)
this.a.push(copy(data))
if (this.a.length > 20) {
this.a.shift()
}
}
this.fork = function () {
this.a = this.a.slice(0, this.index + 1)
}
this.pop = function () {
return this.a.pop()
}
this.prev = function () {
this.index = clamp(this.index - 1, 0, this.a.length - 1)
return copy(this.a[this.index])
}
this.next = function () {
this.index = clamp(this.index + 1, 0, this.a.length - 1)
return copy(this.a[this.index])
}
function copy (data) { return data ? JSON.parse(JSON.stringify(data)) : [] }
function clamp (v, min, max) { return v < min ? min : v > max ? max : v }
}
'use strict'
function Source (client) {
this.cache = {}
this.install = () => {
}
this.start = () => {
this.new()
}
this.new = () => {
console.log('Source', 'New file..')
this.cache = {}
}
this.open = (ext, callback, store = false) => {
console.log('Source', 'Open file..')
const input = document.createElement('input')
input.type = 'file'
input.onchange = (e) => {
const file = e.target.files[0]
if (file.name.indexOf('.' + ext) < 0) { console.warn('Source', `Skipped ${file.name}`); return }
this.read(file, callback, store)
}
input.click()
}
this.load = (ext, callback) => {
console.log('Source', 'Load files..')
const input = document.createElement('input')
input.type = 'file'
input.setAttribute('multiple', 'multiple')
input.onchange = (e) => {
for (const file of e.target.files) {
if (file.name.indexOf('.' + ext) < 0) { console.warn('Source', `Skipped ${file.name}`); continue }
this.read(file, this.store)
}
}
input.click()
}
this.store = (file, content) => {
console.info('Source', 'Stored ' + file.name)
this.cache[file.name] = content
}
this.save = (name, content, type = 'text/plain', callback) => {
this.saveAs(name, content, type, callback)
}
this.saveAs = (name, ext, content, type = 'text/plain', callback) => {
console.log('Source', 'Save new file..')
this.write(name, ext, content, type, callback)
}
this.read = (file, callback, store = false) => {
const reader = new FileReader()
reader.onload = (event) => {
const res = event.target.result
if (callback) { callback(file, res) }
if (store) { this.store(file, res) }
}
reader.readAsText(file, 'UTF-8')
}
this.write = (name, ext, content, type, settings = 'charset=utf-8') => {
const link = document.createElement('a')
link.setAttribute('download', `${name}-${timestamp()}.${ext}`)
if (type === 'image/png' || type === 'image/jpeg') {
link.setAttribute('href', content)
} else {
link.setAttribute('href', 'data:' + type + ';' + settings + ',' + encodeURIComponent(content))
}
link.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }))
}
function timestamp (d = new Date(), e = new Date(d)) {
return `${arvelie()}-${neralie()}`
}
function arvelie (date = new Date()) {
const start = new Date(date.getFullYear(), 0, 0)
const diff = (date - start) + ((start.getTimezoneOffset() - date.getTimezoneOffset()) * 60 * 1000)
const doty = Math.floor(diff / 86400000) - 1
const y = date.getFullYear().toString().substr(2, 2)
const m = doty === 364 || doty === 365 ? '+' : String.fromCharCode(97 + Math.floor(doty / 14)).toUpperCase()
const d = `${(doty === 365 ? 1 : doty === 366 ? 2 : (doty % 14)) + 1}`.padStart(2, '0')
return `${y}${m}${d}`
}
function neralie (d = new Date(), e = new Date(d)) {
const ms = e - d.setHours(0, 0, 0, 0)
return (ms / 8640 / 10000).toFixed(6).substr(2, 6)
}
}
'use strict'
function Theme (client) {
this.el = document.createElement('style')
this.el.type = 'text/css'
this.active = {}
this.default = {
background: '#eeeeee',
f_high: '#0a0a0a',
f_med: '#4a4a4a',
f_low: '#6a6a6a',
f_inv: '#111111',
b_high: '#a1a1a1',
b_med: '#c1c1c1',
b_low: '#ffffff',
b_inv: '#ffb545'
}
this.onLoad = () => {}
this.install = (host = document.body) => {
window.addEventListener('dragover', this.drag)
window.addEventListener('drop', this.drop)
host.appendChild(this.el)
}
this.start = () => {
console.log('Theme', 'Starting..')
if (isJson(localStorage.theme)) {
const storage = JSON.parse(localStorage.theme)
if (isValid(storage)) {
console.log('Theme', 'Loading theme in localStorage..')
this.load(storage)
return
}
}
this.load(this.default)
}
this.open = () => {
console.log('Theme', 'Open theme..')
const input = document.createElement('input')
input.type = 'file'
input.onchange = (e) => {
this.read(e.target.files[0], this.load)
}
input.click()
}
this.load = (data) => {
const theme = this.parse(data)
if (!isValid(theme)) { console.warn('Theme', 'Invalid format'); return }
console.log('Theme', 'Loaded theme!')
this.el.innerHTML = `:root {
--background: ${theme.background};
--f_high: ${theme.f_high};
--f_med: ${theme.f_med};
--f_low: ${theme.f_low};
--f_inv: ${theme.f_inv};
--b_high: ${theme.b_high};
--b_med: ${theme.b_med};
--b_low: ${theme.b_low};
--b_inv: ${theme.b_inv};
}`
localStorage.setItem('theme', JSON.stringify(theme))
this.active = theme
if (this.onLoad) {
this.onLoad(data)
}
}
this.reset = () => {
this.load(this.default)
}
this.set = (key, val) => {
if (!val) { return }
const hex = (`${val}`.substr(0, 1) !== '#' ? '#' : '') + `${val}`
if (!isColor(hex)) { console.warn('Theme', `${hex} is not a valid color.`); return }
this.active[key] = hex
}
this.get = (key) => {
return this.active[key]
}
this.parse = (any) => {
if (isValid(any)) { return any }
if (isJson(any)) { return JSON.parse(any) }
if (isHtml(any)) { return extract(any) }
}
this.drag = (e) => {
e.stopPropagation()
e.preventDefault()
e.dataTransfer.dropEffect = 'copy'
}
this.drop = (e) => {
e.preventDefault()
const file = e.dataTransfer.files[0]
if (file.name.indexOf('.svg') > -1) {
this.read(file, this.load)
}
e.stopPropagation()
}
this.read = (file, callback) => {
const reader = new FileReader()
reader.onload = (event) => {
callback(event.target.result)
}
reader.readAsText(file, 'UTF-8')
}
function extract (xml) {
const svg = new DOMParser().parseFromString(xml, 'text/xml')
try {
return {
background: svg.getElementById('background').getAttribute('fill'),
f_high: svg.getElementById('f_high').getAttribute('fill'),
f_med: svg.getElementById('f_med').getAttribute('fill'),
f_low: svg.getElementById('f_low').getAttribute('fill'),
f_inv: svg.getElementById('f_inv').getAttribute('fill'),
b_high: svg.getElementById('b_high').getAttribute('fill'),
b_med: svg.getElementById('b_med').getAttribute('fill'),
b_low: svg.getElementById('b_low').getAttribute('fill'),
b_inv: svg.getElementById('b_inv').getAttribute('fill')
}
} catch (err) {
console.warn('Theme', 'Incomplete SVG Theme', err)
}
}
function isValid (json) {
if (!json) { return false }
if (!json.background || !isColor(json.background)) { return false }
if (!json.f_high || !isColor(json.f_high)) { return false }
if (!json.f_med || !isColor(json.f_med)) { return false }
if (!json.f_low || !isColor(json.f_low)) { return false }
if (!json.f_inv || !isColor(json.f_inv)) { return false }
if (!json.b_high || !isColor(json.b_high)) { return false }
if (!json.b_med || !isColor(json.b_med)) { return false }
if (!json.b_low || !isColor(json.b_low)) { return false }
if (!json.b_inv || !isColor(json.b_inv)) { return false }
return true
}
function isColor (hex) {
return /^#([0-9A-F]{3}){1,2}$/i.test(hex)
}
function isJson (text) {
try { JSON.parse(text); return true } catch (error) { return false }
}
function isHtml (text) {
try { new DOMParser().parseFromString(text, 'text/xml'); return true } catch (error) { return false }
}
}
'use strict'
function Client () {
this.install = function (host) {
console.info('Client', 'Installing..')
this.acels = new Acels(this)
this.theme = new Theme(this)
this.history = new History(this)
this.source = new Source(this)
this.manager = new Manager(this)
this.renderer = new Renderer(this)
this.tool = new Tool(this)
this.interface = new Interface(this)
this.picker = new Picker(this)
this.cursor = new Cursor(this)
host.appendChild(this.renderer.el)
document.addEventListener('mousedown', (e) => { this.cursor.down(e) }, false)
document.addEventListener('mousemove', (e) => { this.cursor.move(e) }, false)
document.addEventListener('contextmenu', (e) => { this.cursor.alt(e) }, false)
document.addEventListener('mouseup', (e) => { this.cursor.up(e) }, false)
document.addEventListener('copy', (e) => { this.copy(e) }, false)
document.addEventListener('cut', (e) => { this.cut(e) }, false)
document.addEventListener('paste', (e) => { this.paste(e) }, false)
window.addEventListener('resize', (e) => { this.onResize() }, false)
window.addEventListener('dragover', (e) => { e.stopPropagation(); e.preventDefault(); e.dataTransfer.dropEffect = 'copy' })
window.addEventListener('drop', this.onDrop)
this.acels.set('∷', 'Toggle Menubar', 'Tab', () => { this.acels.toggle() })
this.acels.set('∷', 'Open Theme', 'CmdOrCtrl+Shift+O', () => { this.theme.open() })
this.acels.set('∷', 'Reset Theme', 'CmdOrCtrl+Backspace', () => { this.theme.reset() })
this.acels.set('File', 'New', 'CmdOrCtrl+N', () => { this.tool.erase(); this.update(); this.source.new() })
this.acels.set('File', 'Open', 'CmdOrCtrl+O', () => { this.source.open('grid', this.whenOpen) })
this.acels.set('File', 'Save', 'CmdOrCtrl+S', () => { this.source.write('dotgrid', 'grid', this.tool.export(), 'text/plain') })
this.acels.set('File', 'Export Vector', 'CmdOrCtrl+E', () => { this.source.write('dotgrid', 'svg', this.manager.toString(), 'image/svg+xml') })
this.acels.set('File', 'Export Image', 'CmdOrCtrl+Shift+E', () => { this.manager.toPNG(this.tool.settings.size, (dataUrl) => { this.source.write('dotgrid', 'png', dataUrl, 'image/png') }) })
this.acels.set('Edit', 'Undo', 'CmdOrCtrl+Z', () => { this.tool.undo() })
this.acels.set('Edit', 'Redo', 'CmdOrCtrl+Shift+Z', () => { this.tool.redo() })
this.acels.set('View', 'Color Picker', 'G', () => { this.picker.start() })
this.acels.set('View', 'Toggle Grid', 'H', () => { this.renderer.toggle() })
this.acels.set('View', 'Toggle Tools', 'CmdOrCtrl+H', () => { this.interface.toggle() })
this.acels.set('Layers', 'Foreground', 'CmdOrCtrl+1', () => { this.tool.selectLayer(0) })
this.acels.set('Layers', 'Middleground', 'CmdOrCtrl+2', () => { this.tool.selectLayer(1) })
this.acels.set('Layers', 'Background', 'CmdOrCtrl+3', () => { this.tool.selectLayer(2) })
this.acels.set('Layers', 'Merge Layers', 'CmdOrCtrl+M', () => { this.tool.merge() })
this.acels.set('Stroke', 'Line', 'A', () => { this.tool.cast('line') })
this.acels.set('Stroke', 'Arc', 'S', () => { this.tool.cast('arc_c') })
this.acels.set('Stroke', 'Arc Rev', 'D', () => { this.tool.cast('arc_r') })
this.acels.set('Stroke', 'Bezier', 'F', () => { this.tool.cast('bezier') })
this.acels.set('Stroke', 'Close', 'Z', () => { this.tool.cast('close') })
this.acels.set('Stroke', 'Arc(full)', 'T', () => { this.tool.cast('arc_c_full') })
this.acels.set('Stroke', 'Arc Rev(full)', 'Y', () => { this.tool.cast('arc_r_full') })
this.acels.set('Stroke', 'Clear Selection', 'Escape', () => { this.tool.clear() })
this.acels.set('Stroke', 'Erase Segment', 'Backspace', () => { this.tool.removeSegment() })
this.acels.set('Control', 'Add Point', 'Enter', () => { this.tool.addVertex(this.cursor.pos); this.renderer.update() })
this.acels.set('Control', 'Move Up', 'Up', () => { this.cursor.pos.y -= 15; this.renderer.update() })
this.acels.set('Control', 'Move Right', 'Right', () => { this.cursor.pos.x += 15; this.renderer.update() })
this.acels.set('Control', 'Move Down', 'Down', () => { this.cursor.pos.y += 15; this.renderer.update() })
this.acels.set('Control', 'Move Left', 'Left', () => { this.cursor.pos.x -= 15; this.renderer.update() })
this.acels.set('Control', 'Remove Point', 'X', () => { this.tool.removeSegmentsAt(this.cursor.pos) })
this.acels.set('Style', 'Linecap', 'Q', () => { this.tool.toggle('linecap') })
this.acels.set('Style', 'Linejoin', 'W', () => { this.tool.toggle('linejoin') })
this.acels.set('Style', 'Mirror', 'E', () => { this.tool.toggle('mirror') })
this.acels.set('Style', 'Fill', 'R', () => { this.tool.toggle('fill') })
this.acels.set('Style', 'Thicker', '}', () => { this.tool.toggle('thickness', 1) })
this.acels.set('Style', 'Thinner', '{', () => { this.tool.toggle('thickness', -1) })
this.acels.set('Style', 'Thicker +5', ']', () => { this.tool.toggle('thickness', 5) })
this.acels.set('Style', 'Thinner -5', '[', () => { this.tool.toggle('thickness', -5) })
this.acels.route(this)
this.manager.install()
this.interface.install(host)
this.theme.install(host, () => { this.update() })
this.acels.install(host)
}
this.start = () => {
console.log('Client', 'Starting..')
console.info(`${this.acels}`)
this.theme.start()
this.acels.start()
this.tool.start()
this.renderer.start()
this.interface.start()
this.history.push(this.layers) // initial state
this.source.new()
this.onResize()
this.interface.update(true) // force an update
setTimeout(() => { document.body.className += ' ready' }, 250)
}
this.update = () => {
this.manager.update()
this.interface.update()
this.renderer.update()
}
this.clear = () => {
this.history.clear()
this.tool.reset()
this.reset()
this.renderer.update()
this.interface.update(true)
}
this.reset = () => {
this.tool.clear()
this.update()
}
this.whenOpen = (file, data) => {
this.tool.replace(JSON.parse(data))
this.onResize()
}
this.fitSize = () => {
if (this.requireResize() === false) { return }
console.log('Client', `Will resize to: ${printSize(this.getRequiredSize())}`)
this.update()
}
this.getPadding = () => {
return { x: 60, y: 90 }
}
this.getWindowSize = () => {
return { width: window.innerWidth, height: window.innerHeight }
}
this.getProjectSize = () => {
return this.tool.settings.size
}
this.getPaddedSize = () => {
const rect = this.getWindowSize()
const pad = this.getPadding()
return { width: step(rect.width - pad.x, 15), height: step(rect.height - pad.y, 15) }
}
this.getRequiredSize = () => {
const rect = this.getProjectSize()
const pad = this.getPadding()
return { width: step(rect.width, 15) + pad.x, height: step(rect.height, 15) + pad.y }
}
this.requireResize = () => {
const _window = this.getWindowSize()
const _required = this.getRequiredSize()
const offset = sizeOffset(_window, _required)
if (offset.width !== 0 || offset.height !== 0) {
console.log('Client', `Require ${printSize(_required)}, but window is ${printSize(_window)}(${printSize(offset)})`)
return true
}
return false
}
this.onResize = () => {
const _project = this.getProjectSize()
const _padded = this.getPaddedSize()
const offset = sizeOffset(_padded, _project)
if (offset.width !== 0 || offset.height !== 0) {
console.log('Client', `Resize project to ${printSize(_padded)}`)
this.tool.settings.size = _padded
}
this.update()
}
this.drag = function (e) {
e.preventDefault()
e.stopPropagation()
const file = e.dataTransfer.files[0]
const filename = file.path ? file.path : file.name ? file.name : ''
if (filename.indexOf('.grid') < 0) { console.warn('Client', 'Not a .grid file'); return }
const reader = new FileReader()
reader.onload = function (e) {
const data = e.target && e.target.result ? e.target.result : ''
this.source.load(filename, data)
this.fitSize()
}
reader.readAsText(file)
}
this.onDrop = (e) => {
e.preventDefault()
e.stopPropagation()
const file = e.dataTransfer.files[0]
if (file.name.indexOf('.grid') > -1) {
this.source.read(e.dataTransfer.files[0], this.whenOpen)
}
}
this.copy = function (e) {
this.renderer.update()
if (e.target !== this.picker.input) {
e.clipboardData.setData('text/source', this.tool.export(this.tool.layer()))
e.clipboardData.setData('text/plain', this.tool.path())
e.clipboardData.setData('text/html', this.manager.el.outerHTML)
e.clipboardData.setData('text/svg+xml', this.manager.el.outerHTML)
e.preventDefault()
}
this.renderer.update()
}
this.cut = function (e) {
this.renderer.update()
if (e.target !== this.picker.input) {
e.clipboardData.setData('text/source', this.tool.export(this.tool.layer()))
e.clipboardData.setData('text/plain', this.tool.export(this.tool.layer()))
e.clipboardData.setData('text/html', this.manager.el.outerHTML)
e.clipboardData.setData('text/svg+xml', this.manager.el.outerHTML)
this.tool.layers[this.tool.index] = []
e.preventDefault()
}
this.renderer.update()
}
this.paste = function (e) {
if (e.target !== this.picker.el) {
let data = e.clipboardData.getData('text/source')
if (isJson(data)) {
data = JSON.parse(data.trim())
this.tool.import(data)
}
e.preventDefault()
}
this.renderer.update()
}
this.onKeyDown = (e) => {
}
this.onKeyUp = (e) => {
}
function sizeOffset (a, b) { return { width: a.width - b.width, height: a.height - b.height } }
function printSize (size) { return `${size.width}x${size.height}` }
function isJson (text) { try { JSON.parse(text); return true } catch (error) { return false } }
function step (v, s) { return Math.round(v / s) * s }
}
'use strict'
function Cursor (client) {
this.pos = { x: 0, y: 0 }
this.lastPos = { x: 0, y: 0 }
this.translation = null
this.operation = null
this.translate = function (from = null, to = null, multi = false, copy = false, layer = false) {
if ((from || to) && this.translation === null) { this.translation = { multi: multi, copy: copy, layer: layer } }
if (from) { this.translation.from = from }
if (to) { this.translation.to = to }
if (!from && !to) {
this.translation = null
}
}
this.down = function (e) {
this.pos = this.atEvent(e)
if (client.tool.vertexAt(this.pos)) {
this.translate(this.pos, this.pos, e.shiftKey, e.ctrlKey || e.metaKey, e.altKey)
}
client.renderer.update()
client.interface.update()
e.preventDefault()
}
this.move = function (e) {
this.pos = this.atEvent(e)
if (this.translation) {
this.translate(null, this.pos)
}
if (this.lastPos.x !== this.pos.x || this.lastPos.y !== this.pos.y) {
client.renderer.update()
}
client.interface.update()
this.lastPos = this.pos
e.preventDefault()
}
this.up = function (e) {
this.pos = this.atEvent(e)
if (this.translation && !isEqual(this.translation.from, this.translation.to)) {
if (this.translation.layer === true) { client.tool.translateLayer(this.translation.from, this.translation.to) } else if (this.translation.copy) { client.tool.translateCopy(this.translation.from, this.translation.to) } else if (this.translation.multi) { client.tool.translateMulti(this.translation.from, this.translation.to) } else { client.tool.translate(this.translation.from, this.translation.to) }
} else if (e.target.id === 'guide') {
client.tool.addVertex({ x: this.pos.x, y: this.pos.y })
client.picker.stop()
}
this.translate()
client.interface.update()
client.renderer.update()
e.preventDefault()
}
this.alt = function (e) {
this.pos = this.atEvent(e)
client.tool.removeSegmentsAt(this.pos)
e.preventDefault()
setTimeout(() => {
client.tool.clear()
}, 150)
}
this.atEvent = function (e) {
return this.snapPos(this.relativePos({ x: e.clientX, y: e.clientY }))
}
this.relativePos = function (pos) {
return {
x: pos.x - client.renderer.el.offsetLeft,
y: pos.y - client.renderer.el.offsetTop
}
}
this.snapPos = function (pos) {
return {
x: clamp(step(pos.x, 15), 15, client.tool.settings.size.width - 15),
y: clamp(step(pos.y, 15), 15, client.tool.settings.size.height - 15)
}
}
function isEqual (a, b) { return a.x === b.x && a.y === b.y }
function clamp (v, min, max) { return v < min ? min : v > max ? max : v }
function step (v, s) { return Math.round(v / s) * s }
}
'use strict'
function Generator (layer, style) {
this.layer = layer
this.style = style
function operate (layer, offset, scale, mirror = 0, angle = 0) {
const l = copy(layer)
for (const k1 in l) {
const seg = l[k1]
for (const k2 in seg.vertices) {
if (mirror === 1 || mirror === 3) { seg.vertices[k2].x = (client.tool.settings.size.width) - seg.vertices[k2].x }
if (mirror === 2 || mirror === 3) { seg.vertices[k2].y = (client.tool.settings.size.height) - seg.vertices[k2].y }
seg.vertices[k2].x += offset.x
seg.vertices[k2].y += offset.y
const center = { x: (client.tool.settings.size.width / 2) + offset.x + (7.5), y: (client.tool.settings.size.height / 2) + offset.y + 30 }
seg.vertices[k2] = rotatePoint(seg.vertices[k2], center, angle)
seg.vertices[k2].x *= scale
seg.vertices[k2].y *= scale
}
}
return l
}
this.render = function (prev, segment, mirror = 0) {
const type = segment.type
const vertices = segment.vertices
let html = ''
let skip = 0
for (const id in vertices) {
if (skip > 0) { skip -= 1; continue }
const vertex = vertices[parseInt(id)]
const next = vertices[parseInt(id) + 1]
const afterNext = vertices[parseInt(id) + 2]
if (parseInt(id) === 0 && !prev) {
html += `M${vertex.x},${vertex.y} `
} else if (parseInt(id) === 0 && prev && (prev.x !== vertex.x || prev.y !== vertex.y)) {
html += `M${vertex.x},${vertex.y} `
}
if (type === 'line') {
html += this._line(vertex)
} else if (type === 'arc_c') {
const clock = mirror > 0 && mirror < 3 ? '0,0' : '0,1'
html += this._arc(vertex, next, clock)
} else if (type === 'arc_r') {
const clock = mirror > 0 && mirror < 3 ? '0,1' : '0,0'
html += this._arc(vertex, next, clock)
} else if (type === 'arc_c_full') {
const clock = mirror > 0 ? '1,0' : '1,1'
html += this._arc(vertex, next, clock)
} else if (type === 'arc_r_full') {
const clock = mirror > 0 ? '1,1' : '1,0'
html += this._arc(vertex, next, clock)
} else if (type === 'bezier') {
html += this._bezier(next, afterNext)
skip = 1
}
}
if (segment.type === 'close') {
html += 'Z '
}
return html
}
this._line = function (a) {
return `L${a.x},${a.y} `
}
this._arc = function (a, b, c) {
if (!a || !b || !c) { return '' }
const offset = { x: b.x - a.x, y: b.y - a.y }
if (offset.x === 0 || offset.y === 0) { return this._line(b) }
return `A${Math.abs(b.x - a.x)},${Math.abs(b.y - a.y)} 0 ${c} ${b.x},${b.y} `
}
this._bezier = function (a, b) {
if (!a || !b) { return '' }
return `Q${a.x},${a.y} ${b.x},${b.y} `
}
this.convert = function (layer, mirror, angle) {
let s = ''
let prev = null
for (const id in layer) {
const seg = layer[parseInt(id)]
s += `${this.render(prev, seg, mirror)}`
prev = seg.vertices ? seg.vertices[seg.vertices.length - 1] : null
}
return s
}
this.toString = function (offset = { x: 0, y: 0 }, scale = 1, mirror = this.style && this.style.mirror_style ? this.style.mirror_style : 0) {
let s = this.convert(operate(this.layer, offset, scale))
if (mirror === 1 || mirror === 2 || mirror === 3) {
s += this.convert(operate(this.layer, offset, scale, mirror), mirror)
}
return s
}
function copy (data) { return data ? JSON.parse(JSON.stringify(data)) : [] }
function rotatePoint (point, origin, angle) { angle = angle * Math.PI / 180.0; return { x: (Math.cos(angle) * (point.x - origin.x) - Math.sin(angle) * (point.y - origin.y) + origin.x).toFixed(1), y: (Math.sin(angle) * (point.x - origin.x) + Math.cos(angle) * (point.y - origin.y) + origin.y).toFixed(1) } }
}
'use strict'
function Interface (client) {
this.el = document.createElement('div')
this.el.id = 'interface'
this.el.appendChild(this.menu_el = document.createElement('div'))
this.menu_el.id = 'menu'
this.isVisible = true
this.zoom = false
const options = {
cast: {
line: { key: 'A', icon: 'M60,60 L240,240' },
arc_c: { key: 'S', icon: 'M60,60 A180,180 0 0,1 240,240' },
arc_r: { key: 'D', icon: 'M60,60 A180,180 0 0,0 240,240' },
bezier: { key: 'F', icon: 'M60,60 Q60,150 150,150 Q240,150 240,240' },
close: { key: 'Z', icon: 'M60,60 A180,180 0 0,1 240,240 M60,60 A180,180 0 0,0 240,240' }
},
toggle: {
linecap: { key: 'Q', icon: 'M60,60 L60,60 L180,180 L240,180 L240,240 L180,240 L180,180' },
linejoin: { key: 'W', icon: 'M60,60 L120,120 L180,120 M120,180 L180,180 L240,240' },
thickness: { key: '', icon: 'M120,90 L120,90 L90,120 L180,210 L210,180 Z M105,105 L105,105 L60,60 M195,195 L195,195 L240,240' },
mirror: { key: 'E', icon: 'M60,60 L60,60 L120,120 M180,180 L180,180 L240,240 M210,90 L210,90 L180,120 M120,180 L120,180 L90,210' },
fill: { key: 'R', icon: 'M60,60 L60,150 L150,150 L240,150 L240,240 Z' }
},
misc: {
color: { key: 'G', icon: 'M150,60 A90,90 0 0,1 240,150 A-90,90 0 0,1 150,240 A-90,-90 0 0,1 60,150 A90,-90 0 0,1 150,60' }
},
source: {
open: { key: 'c-O', icon: 'M155,65 A90,90 0 0,1 245,155 A90,90 0 0,1 155,245 A90,90 0 0,1 65,155 A90,90 0 0,1 155,65 M155,95 A60,60 0 0,1 215,155 A60,60 0 0,1 155,215 A60,60 0 0,1 95,155 A60,60 0 0,1 155,95 ' },
render: { key: 'c-R', icon: 'M155,65 A90,90 0 0,1 245,155 A90,90 0 0,1 155,245 A90,90 0 0,1 65,155 A90,90 0 0,1 155,65 M110,155 L110,155 L200,155 ' },
export: { key: 'c-E', icon: 'M155,65 A90,90 0 0,1 245,155 A90,90 0 0,1 155,245 A90,90 0 0,1 65,155 A90,90 0 0,1 155,65 M110,140 L110,140 L200,140 M110,170 L110,170 L200,170' },
save: { key: 'c-S', icon: 'M155,65 A90,90 0 0,1 245,155 A90,90 0 0,1 155,245 A90,90 0 0,1 65,155 A90,90 0 0,1 155,65 M110,155 L110,155 L200,155 M110,185 L110,185 L200,185 M110,125 L110,125 L200,125' },
grid: { key: 'H', icon: 'M65,155 Q155,245 245,155 M65,155 Q155,65 245,155 M155,125 A30,30 0 0,1 185,155 A30,30 0 0,1 155,185 A30,30 0 0,1 125,155 A30,30 0 0,1 155,125 ' }
}
}
const mirrorPaths = [
'M60,60 L60,60 L120,120 M180,180 L180,180 L240,240 M210,90 L210,90 L180,120 M120,180 L120,180 L90,210',
'M60,60 L240,240 M180,120 L210,90 M120,180 L90,210',
'M210,90 L210,90 L90,210 M60,60 L60,60 L120,120 M180,180 L180,180 L240,240',
'M60,60 L60,60 L120,120 L180,120 L210,90 M240,240 L240,240 L180,180 L120,180 L90,210',
'M120,120 L120,120 L120,120 L180,120 M120,150 L120,150 L180,150 M120,180 L120,180 L180,180 L180,180 L180,180 L240,240 M120,210 L120,210 L180,210 M120,90 L120,90 L180,90 M60,60 L60,60 L120,120 '
]
this.install = function (host) {
host.appendChild(this.el)
}
this.start = function (host) {
let html = ''
for (const type in options) {
const tools = options[type]
for (const name in tools) {
const tool = tools[name]
html += `
<svg
id="option_${name}"
title="${capitalize(name)}"
onmouseout="client.interface.out('${type}','${name}')"
onmouseup="client.interface.up('${type}','${name}')"
onmousedown="client.interface.down('${type}','${name}', event)"
onmouseover="client.interface.over('${type}','${name}')"
viewBox="0 0 300 300"
class="icon ${type}">
<path id="${name}_path" class="icon_path" d="${tool.icon}"/>${name === 'depth' ? '<path class="icon_path inactive" d=""/>' : ''}
<rect ar="${name}" width="300" height="300" opacity="0">
<title>${capitalize(name)}${tool.key ? '(' + tool.key + ')' : ''}</title>
</rect>
</svg>`
}
}
this.menu_el.innerHTML = html
for (const type in options) {
const tools = options[type]
for (const name in tools) {
const tool = tools[name]
tool.el = document.getElementById('option_' + name)
}
}
this.menu_el.appendChild(client.picker.el)
}
this.over = function (type, name) {
client.cursor.operation = {}
client.cursor.operation[type] = name
this.update(true)
client.renderer.update(true)
}
this.out = function (type, name) {
client.cursor.operation = ''
client.renderer.update(true)
}
this.up = function (type, name) {
if (!client.tool[type]) { console.warn(`Unknown option(type): ${type}.${name}`, client.tool); return }
this.update(true)
client.renderer.update(true)
}
this.down = function (type, name, event) {
if (!client.tool[type]) { console.warn(`Unknown option(type): ${type}.${name}`, client.tool); return }
const mod = event.button === 2 ? -1 : 1
client.tool[type](name, mod)
this.update(true)
client.renderer.update(true)
}
this.prev_operation = null
this.update = function (force = false, id) {
if (this.prev_operation === client.cursor.operation && force === false) { return }
let multiVertices = null
const segments = client.tool.layer()
const sumSegments = client.tool.length()
for (const i in segments) {
if (segments[i].vertices.length > 2) { multiVertices = true; break }
}
options.cast.line.el.className.baseVal = !client.tool.canCast('line') ? 'icon inactive' : 'icon'
options.cast.arc_c.el.className.baseVal = !client.tool.canCast('arc_c') ? 'icon inactive' : 'icon'
options.cast.arc_r.el.className.baseVal = !client.tool.canCast('arc_r') ? 'icon inactive' : 'icon'
options.cast.bezier.el.className.baseVal = !client.tool.canCast('bezier') ? 'icon inactive' : 'icon'
options.cast.close.el.className.baseVal = !client.tool.canCast('close') ? 'icon inactive' : 'icon'
options.toggle.thickness.el.className.baseVal = client.tool.layer().length < 1 ? 'icon inactive' : 'icon'
options.toggle.linecap.el.className.baseVal = client.tool.layer().length < 1 ? 'icon inactive' : 'icon'
options.toggle.linejoin.el.className.baseVal = client.tool.layer().length < 1 || !multiVertices ? 'icon inactive' : 'icon'
options.toggle.mirror.el.className.baseVal = client.tool.layer().length < 1 ? 'icon inactive' : 'icon'
options.toggle.fill.el.className.baseVal = client.tool.layer().length < 1 ? 'icon inactive' : 'icon'
options.misc.color.el.children[0].style.fill = client.tool.style().color
options.misc.color.el.children[0].style.stroke = client.tool.style().color
options.misc.color.el.className.baseVal = 'icon'
options.source.save.el.className.baseVal = sumSegments < 1 ? 'icon inactive source' : 'icon source'
options.source.export.el.className.baseVal = sumSegments < 1 ? 'icon inactive source' : 'icon source'
options.source.render.el.className.baseVal = sumSegments < 1 ? 'icon inactive source' : 'icon source'
options.source.grid.el.className.baseVal = client.renderer.showExtras ? 'icon inactive source' : 'icon source'
document.getElementById('grid_path').setAttribute('d', client.renderer.showExtras ? 'M65,155 Q155,245 245,155 M65,155 Q155,65 245,155 M155,125 A30,30 0 0,1 185,155 A30,30 0 0,1 155,185 A30,30 0 0,1 125,155 A30,30 0 0,1 155,125 ' : 'M65,155 Q155,245 245,155 M65,155 ')
document.getElementById('mirror_path').setAttribute('d', mirrorPaths[client.tool.style().mirror_style])
this.prev_operation = client.cursor.operation
}
this.toggle = function () {
this.isVisible = !this.isVisible
this.el.className = this.isVisible ? 'visible' : 'hidden'
}
function capitalize (str) {
return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase()
}
}
'use strict'
function Manager (client) {
this.el = document.createElementNS('http://www.w3.org/2000/svg', 'svg')
this.el.setAttribute('xmlns', 'http://www.w3.org/2000/svg')
this.el.setAttribute('baseProfile', 'full')
this.el.setAttribute('version', '1.1')
this.el.style.fill = 'none'
this.layers = []
this.install = function () {
this.el.appendChild(this.layers[2] = document.createElementNS('http://www.w3.org/2000/svg', 'path'))
this.el.appendChild(this.layers[1] = document.createElementNS('http://www.w3.org/2000/svg', 'path'))
this.el.appendChild(this.layers[0] = document.createElementNS('http://www.w3.org/2000/svg', 'path'))
}
this.update = function () {
this.el.setAttribute('width', (client.tool.settings.size.width) + 'px')
this.el.setAttribute('height', (client.tool.settings.size.height) + 'px')
this.el.style.width = (client.tool.settings.size.width)
this.el.style.height = client.tool.settings.size.height
const styles = client.tool.styles
const paths = client.tool.paths()
for (const id in this.layers) {
const style = styles[id]
const path = paths[id]
const layer = this.layers[id]
layer.style.strokeWidth = style.thickness
layer.style.strokeLinecap = style.strokeLinecap
layer.style.strokeLinejoin = style.strokeLinejoin
layer.style.stroke = style.color
layer.style.fill = style.fill
layer.setAttribute('d', path)
}
}
this.svg64 = function () {
const xml = new XMLSerializer().serializeToString(this.el)
const svg64 = btoa(xml)
const b64Start = 'data:image/svg+xml;base64,'
return b64Start + svg64
}
this.toPNG = function (size = client.tool.settings.size, callback) {
this.update()
const image64 = this.svg64()
const img = new Image()
const canvas = document.createElement('canvas')
canvas.width = (size.width) * 2
canvas.height = (size.height) * 2
img.onload = function () {
canvas.getContext('2d').drawImage(img, 0, 0, (size.width) * 2, (size.height) * 2)
callback(canvas.toDataURL('image/png'))
}
img.src = image64
}
this.toSVG = function (callback) {
this.update()
const image64 = this.svg64()
callback(image64, 'export.svg')
}
this.toGRID = function (callback) {
this.update()
const text = client.tool.export()
const file = new Blob([text], { type: 'text/plain' })
callback(URL.createObjectURL(file), 'export.grid')
}
this.toString = () => {
return new XMLSerializer().serializeToString(this.el)
}
}
'use strict'
function Picker (client) {
this.memory = ''
this.el = document.createElement('div')
this.el.id = 'picker'
this.isActive = false
this.input = document.createElement('input')
this.input.id = 'picker_input'
this.el.appendChild(this.input)
this.start = function () {
if (this.isActive) { return }
this.isActive = true
this.input.setAttribute('placeholder', `${client.tool.style().color.replace('#', '').trim()}`)
this.input.setAttribute('maxlength', 6)
this.input.addEventListener('keydown', this.onKeyDown, false)
this.input.addEventListener('keyup', this.onKeyUp, false)
client.interface.el.className = 'picker'
this.input.focus()
this.input.value = ''
try { client.controller.set('picker') } catch (err) { }
}
this.update = function () {
if (!this.isActive) { return }
if (!isColor(this.input.value)) { return }
const hex = `#${this.input.value}`
document.getElementById('option_color').children[0].style.fill = hex
document.getElementById('option_color').children[0].style.stroke = hex
}
this.stop = function () {
if (!this.isActive) { return }
this.isActive = false
client.interface.el.className = ''
this.input.blur()
this.input.value = ''
try { client.controller.set() } catch (err) { console.log('No controller') }
setTimeout(() => { client.interface.update(true); client.renderer.update() }, 250)
}
this.validate = function () {
if (!isColor(this.input.value)) { return }
const hex = `#${this.input.value}`
client.tool.style().color = hex