-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
svgtiler.coffee
executable file
·2991 lines (2839 loc) · 110 KB
/
svgtiler.coffee
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
unless window?
path = require 'path'
fs = require 'fs'
xmldom = require '@xmldom/xmldom'
DOMParser = xmldom.DOMParser
domImplementation = new xmldom.DOMImplementation()
XMLSerializer = xmldom.XMLSerializer
prettyXML = require 'prettify-xml'
graphemeSplitter = new require('grapheme-splitter')()
metadata = require '../package.json'
try
metadata.modified = (fs.statSync __filename).mtimeMs
else
DOMParser = window.DOMParser # escape CoffeeScript scope
domImplementation = document.implementation
XMLSerializer = window.XMLSerializer # escape CoffeeScript scope
path =
basename: (x) -> /[^/]*$/.exec(x)[0]
extname: (x) -> /\.[^/]+$/.exec(x)[0]
dirname: (x) -> /[^]*\/|/.exec(x)[0]
graphemeSplitter = splitGraphemes: (x) -> x.split ''
metadata = version: '(web)'
## Register `require` hooks of Babel and CoffeeScript,
## so that imported/required modules are similarly processed.
unless window?
###
Babel plugin to add implicit `export default` to last line of program,
to simulate the effect of `eval` but in a module context.
Only added if there isn't already an `export default` or `exports.default`
in the code, and when the last line is an object, array, or function
expression (with the idea that it wouldn't do much by itself).
###
implicitFinalExportDefault = ({types}) ->
visitor:
Program: (path) ->
body = path.get 'body'
return unless body.length # empty program
## Check for existing `export default` or `exports.default` or
## `exports['default']`, in which case definitely don't add one.
exportedDefault = false
path.traverse(
ExportDefaultDeclaration: (path) ->
exportedDefault = true
return
MemberExpression: (path) ->
{node} = path
check = (key, value) ->
types.isIdentifier(node.object) and
node.object.name == key and (
(types.isIdentifier(node.property) and
node.property.name == value) or
(types.isStringLiteral(node.property) and
node.property.value == value)
)
exportedDefault or= check('exports', 'default') or
check('module', 'exports')
return
)
return if exportedDefault
last = body[body.length-1]
lastNode = last.node
if types.isExpressionStatement(last) and (
types.isObjectExpression(lastNode.expression) or
types.isFunctionExpression(lastNode.expression) or
types.isArrowFunctionExpression(lastNode.expression) or
types.isArrayExpression(lastNode.expression)
# not AssignmentExpression or CallExpression
)
exportLast = types.exportDefaultDeclaration lastNode.expression
exportLast.leadingComments = lastNode.leadingComments
exportLast.innerComments = lastNode.innerComments
exportLast.trailingComments = lastNode.trailingComments
last.replaceWith exportLast
return
## Modify `svgtiler.require` calls to add __dirname as third argument,
## so that files can be located relative to the module's directory.
svgtilerRequire = ({types}) ->
visitor:
CallExpression: (path) ->
{node} = path
{callee} = node
return unless types.isMemberExpression callee
return unless types.isIdentifier(callee.object) and
callee.object.name == 'svgtiler'
return unless types.isIdentifier(callee.property) and
callee.property.name == 'require'
while node.arguments.length < 2
node.arguments.push types.identifier 'undefined'
if node.arguments.length == 2
node.arguments.push types.identifier '__dirname'
return
verboseBabel = ({types}) ->
post: (state) ->
return unless getSettings()?.verbose
if state.opts?.filename?
filename = "[#{state.opts.filename}]"
else if state.inputMap?.sourcemap?.sources?.length
filename =
"[converted from #{state.inputMap.sourcemap.sources.join ' & '}]"
else
filename = ''
console.log '# Babel conversion input:', filename
console.log state.code
console.log '# Babel conversion output:', filename
console.log \
require('@babel/generator').default(state.ast, babelConfig).code
console.log '# End of Babel conversion', filename
return
babelConfig =
plugins: [
implicitFinalExportDefault
svgtilerRequire
[require.resolve('babel-plugin-auto-import'),
declarations: [
default: 'preact'
path: 'preact'
,
default: 'svgtiler'
members: ['share']
path: 'svgtiler'
]
]
require.resolve '@babel/plugin-transform-modules-commonjs'
[require.resolve('@babel/plugin-transform-react-jsx'),
useBuiltIns: true
runtime: 'automatic'
importSource: 'preact'
#pragma: 'preact.h'
#pragmaFrag: 'preact.Fragment'
throwIfNamespace: false
]
require.resolve 'babel-plugin-module-deps'
verboseBabel
]
#inputSourceMap: true # CoffeeScript sets this to its own source map
sourceMaps: 'inline'
retainLines: true
## Tell CoffeeScript's register to transpile with our Babel config.
module.options =
bare: true # needed for implicitFinalExportDefault
#inlineMap: true # rely on Babel's source map
transpile: babelConfig
## Prevent Babel from caching its results, for changes to our plugins.
require('@babel/register') {...babelConfig, cache: false}
CoffeeScript = require 'coffeescript'
CoffeeScript.FILE_EXTENSIONS = ['.coffee', '.cjsx']
CoffeeScript.register()
defaultSettings =
## Log otherwise invisible actions to aid with debugging.
## Currently, 0 = none, nonzero = all, but there may be levels in future.
verbose: 0
## Force all tiles to have specified width or height.
forceWidth: null ## default: no size forcing
forceHeight: null ## default: no size forcing
## Inline <image>s into output SVG (replacing URLs to other files).
inlineImages: not window?
## Process hidden sheets within spreadsheet files.
keepHidden: false
## Don't delete blank extreme rows/columns.
keepMargins: false
## Don't make all rows have the same number of columns by padding with
## empty strings.
keepUneven: false
## Array of conversion formats such as 'pdf' or 'pdf'.
formats: null
## Override for output file's stem (basename without extension).
## Can use `*` to refer to input file's stem, to add prefix or suffix.
outputStem: null
## Directories to output all or some files.
## Can also include stem overrides like "prefix_*_suffix".
outputDir: null ## default: same directory as input
outputDirExt: ## by extension; default is to use outputDir
'.svg': null
'.pdf': null
'.png': null
'.svg_tex': null
## Delete output files instead of creating them, like `make clean`.
clean: false
## Path to inkscape. Default searches PATH.
inkscape: 'inkscape'
## Default overflow behavior is 'visible' unless --no-overflow specified;
## use `overflow:hidden` to restore normal SVG behavior of keeping each tile
## within its bounding box.
overflowDefault: 'visible'
## When a mapping refers to an SVG filename, assume this encoding.
svgEncoding: 'utf8'
## Move <text> from SVG to accompanying LaTeX file.tex.
texText: false
## Use `href` instead of `xlink:href` attribute in <use> and <image>.
## `href` behaves better in web browsers, but `xlink:href` is more
## compatible with older SVG drawing programs.
useHref: window?
## Add `data-key`/`data-i`/`data-j`/`data-k` attributes to <use> elements,
## which specify the drawing key and location (row i, column j, layer k).
useData: window?
## Background rectangle fill color.
background: null
## Glob pattern for Maketiles.
maketile: '[mM]aketile.{args,coffee,js}'
## renderDOM-specific
filename: 'drawing.asc' # default filename when not otherwise specified
keepParent: false
keepClass: false
## Major state
mappings: null # should be valid argument to new Mappings
styles: null # should be valid argument to new Styles
cloneSettings = (settings, addArrays) ->
settings = {...settings}
if settings.formats?
settings.formats = [...settings.formats]
else if addArrays
settings.formats = []
if settings.mappings?
settings.mappings = new Mappings settings.mappings
else if addArrays
settings.mappings = new Mappings
if settings.styles?
settings.styles = new Styles settings.styles
else if addArrays
settings.styles = new Styles
settings
getSetting = (settings, key) ->
settings?[key] ? defaultSettings[key]
getOutputDir = (settings, extension) ->
dir = getSetting(settings, 'outputDirExt')?[extension] ?
getSetting settings, 'outputDir'
if dir
try
fs.mkdirSync dir, recursive: true
catch err
console.warn "Failed to make directory '#{dir}': #{err}"
dir
class HasSettings
getSetting: (key) -> getSetting @settings, key
getOutputDir: (extension) -> getOutputDir @settings, extension
globalShare = {} # for shared data between mapping modules
SVGNS = 'http://www.w3.org/2000/svg'
XLINKNS = 'http://www.w3.org/1999/xlink'
splitIntoLines = (data) ->
data
.replace /\r\n/g, '\n'
.replace /\r/g, '\n'
.split '\n'
whitespace = /[\s\uFEFF\xA0]+/ ## based on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim
extensionOf = (filename) -> path.extname(filename).toLowerCase()
class SVGTilerError extends Error
constructor: (message) ->
super message
@name = 'SVGTilerError'
parseNum = (x) ->
parsed = parseFloat x
if isNaN parsed
null
else
parsed
## Allow Infinity, \infty, Inf with optional sign prefix
infinityRegExp = /^\s*([+-]?)\\?infi?n?i?t?y?\s*$/i
parseNumOrInfinity = (x) ->
if (match = infinityRegExp.exec x)?
if match[1] == '-'
-Infinity
else
Infinity
else
parseNum x
## Conversion from arbitrary unit to px (SVG units),
## from https://www.w3.org/TR/css-values-3/#absolute-lengths
units =
cm: 96 / 2.54
mm: 96 / 25.4
Q: 96 / 25.4 / 4
in: 96
pc: 96 / 6
pt: 96 / 72
px: 1
undefined: 1
parseDim = (x) ->
match = /^\s*([0-9.]+)\s*([a-zA-Z]\w+)?\s*$/.exec x
return null unless match?
if units.hasOwnProperty match[2]
parseNum(match[1]) * units[match[2]]
else
console.warn "Unrecognized unit #{match[2]}"
parseNum match[1]
parseBox = (box, allowNull) ->
return null unless box
box = box.split /\s*[\s,]\s*/
.map parseNum
return null if null in box unless allowNull
box
extractBoundingBox = (xml) ->
###
Parse and return root `boundingBox` attribute,
possibly under the old name of `overflowBox`.
Also remove them if present, so output is valid SVG.
###
box = xml.getAttribute('boundingBox') or xml.getAttribute('overflowBox')
xml.removeAttribute 'boundingBox'
xml.removeAttribute 'overflowBox'
if box.toLowerCase().trim() == 'none'
[null, null, null, null]
else
parseBox box, true
svgBBox = (dom) ->
## xxx Many unsupported features!
## - transformations
## - used symbols/defs
## - paths
## - text
## - line widths which extend bounding box
recurse = (node) ->
if node.nodeType != node.ELEMENT_NODE or
node.nodeName in ['defs', 'use']
return null
# Ignore <symbol>s except the root <symbol> that we're bounding
if node.nodeName == 'symbol' and node != dom
return null
switch node.tagName
when 'rect', 'image'
## For <image>, should autodetect image size (#42)
[parseNum(node.getAttribute 'x') ? 0
parseNum(node.getAttribute 'y') ? 0
parseNum(node.getAttribute 'width') ? 0
parseNum(node.getAttribute 'height') ? 0]
when 'circle'
cx = parseNum(node.getAttribute 'cx') ? 0
cy = parseNum(node.getAttribute 'cy') ? 0
r = parseNum(node.getAttribute 'r') ? 0
[cx - r, cy - r, 2*r, 2*r]
when 'ellipse'
cx = parseNum(node.getAttribute 'cx') ? 0
cy = parseNum(node.getAttribute 'cy') ? 0
rx = parseNum(node.getAttribute 'rx') ? 0
ry = parseNum(node.getAttribute 'ry') ? 0
[cx - rx, cy - ry, 2*rx, 2*ry]
when 'line'
x1 = parseNum(node.getAttribute 'x1') ? 0
y1 = parseNum(node.getAttribute 'y1') ? 0
x2 = parseNum(node.getAttribute 'x2') ? 0
y2 = parseNum(node.getAttribute 'y2') ? 0
xMin = Math.min x1, x2
yMin = Math.min y1, y2
[xMin, yMin, Math.max(x1, x2) - xMin, Math.max(y1, y2) - yMin]
when 'polyline', 'polygon'
points = for point in node.getAttribute('points').trim().split /\s+/
for coord in point.split /,/
parseFloat coord
xs = (point[0] for point in points)
ys = (point[1] for point in points)
xMin = Math.min ...xs
yMin = Math.min ...ys
if isNaN(xMin) or isNaN(yMin) # invalid points attribute; don't render
null
else
[xMin, yMin, Math.max(...xs) - xMin, Math.max(...ys) - yMin]
else
viewBoxes = (recurse(child) for child in node.childNodes)
viewBoxes = (viewBox for viewBox in viewBoxes when viewBox?)
xMin = Math.min ...(viewBox[0] for viewBox in viewBoxes)
yMin = Math.min ...(viewBox[1] for viewBox in viewBoxes)
xMax = Math.max ...(viewBox[0]+viewBox[2] for viewBox in viewBoxes)
yMax = Math.max ...(viewBox[1]+viewBox[3] for viewBox in viewBoxes)
[xMin, yMin, xMax - xMin, yMax - yMin]
viewBox = recurse dom
if not viewBox? or Infinity in viewBox or -Infinity in viewBox
null
else
viewBox
isAuto = (value) ->
typeof value == 'string' and /^\s*auto\s*$/i.test value
attributeOrStyle = (node, attr, styleKey = attr) ->
if value = node.getAttribute attr
value.trim()
else
style = node.getAttribute 'style'
if style
match = ///(?:^|;)\s*#{styleKey}\s*:\s*([^;\s][^;]*)///i.exec style
match?[1]
removeAttributeOrStyle = (node, attr, styleKey = attr) ->
node.removeAttribute attr
style = node.getAttribute 'style'
return unless style?
newStyle = style.replace ///(?:^|;)\s*#{styleKey}\s*:\s*([^;\s][^;]*)///i, ''
if style != newStyle
if newStyle.trim()
node.setAttribute 'style', newStyle
else
node.removeAttribute 'style'
getHref = (node) ->
for key in ['xlink:href', 'href']
if href = node.getAttribute key
return
key: key
href: href
key: null
href: null
extractZIndex = (node) ->
## Check whether DOM node has a specified z-index, defaulting to zero.
## Special values of Infinity or -Infinity are allowed.
## Also remove z-index attribute, so output is valid SVG.
## Note that z-index must be an integer.
## 1. https://www.w3.org/Graphics/SVG/WG/wiki/Proposals/z-index suggests
## a z-index="..." attribute. Check for this first.
## 2. Look for style="z-index:..." as in HTML.
z = parseNumOrInfinity attributeOrStyle node, 'z-index'
removeAttributeOrStyle node, 'z-index'
z ? 0
domRecurse = (node, callback) ->
###
Recurse through DOM starting at `node`, calling `callback(node)`
on every recursive node, including `node` itself.
`callback()` should return a true value if you want to recurse into
the specified node's children (typically, when there isn't a match).
Robust against node being replaced.
###
return unless callback node
return unless node.hasChildNodes()
child = node.lastChild
while child?
nextChild = child.previousSibling
domRecurse child, callback
child = nextChild
return
refRegExp = ///
# url() without quotes
\b url \s* \( \s* \# ([^()]*) \)
# url() with quotes, or src() which requires quotes
| \b (?: url | src) \s* \( \s* (['"]) \s* \# ([^'"]*) \2 \s* \)
///g
findRefs = (root) =>
## Returns an array of id-based references to other elements in the SVG.
refs = []
domRecurse root, (node) =>
return unless node.attributes?
for attr in node.attributes
if attr.name in ['href', 'xlink:href'] and
(value = attr.value.trim()).startsWith '#'
refs.push {id: value[1..].trim(), node, attr: attr.name}
else
while (match = refRegExp.exec attr.value)?
refs.push {id: (match[1] or match[3]).trim(), node, attr: attr.name}
true
refs
contentType =
'.png': 'image/png'
'.jpg': 'image/jpeg'
'.jpeg': 'image/jpeg'
'.gif': 'image/gif'
'.svg': 'image/svg+xml'
## Support for `require`/`import`ing images.
## SVG files get parsed into Preact Virtual DOM so you can manipulate them,
## while raster images get converted into <image> Preact Virtual DOM elements.
## In either case, DOM gets `svg` attribute with raw SVG string.
unless window?
pirates = require 'pirates'
pirates.settings = defaultSettings
pirates.addHook (code, filename) ->
if '.svg' == extensionOf filename
code = removeSVGComments code
domCode = require('@babel/core').transform "module.exports = #{code}",
{...babelConfig, filename}
"""
#{domCode.code}
module.exports.svg = #{JSON.stringify code};
"""
else
href = hrefAttr pirates.settings
"""
module.exports = require('preact').h('image', #{JSON.stringify "#{href}": filename});
module.exports.svg = '<image #{href}="'+#{JSON.stringify filename.replace /"/g, '"'}+'"/>';
"""
, exts: Object.keys contentType
isPreact = (data) ->
typeof data == 'object' and data?.type? and data.props?
$static = Symbol 'svgtiler.static'
wrapStatic = (x) -> [$static]: x # exported as `static` but that's reserved
#fileCache = new Map
loadSVG = (filename, settings) ->
#if (found = fileCache.get filename)?
# return found
#data =
fs.readFileSync filename,
encoding: getSetting settings, 'svgEncoding'
## TODO: Handle <?xml encoding="..."?> or BOM to override svgEncoding.
#fileCache.set filename, data
#data
escapeId = (key) ->
###
According to XML spec [https://www.w3.org/TR/xml/#id],
id/href follows the XML name spec: [https://www.w3.org/TR/xml/#NT-Name]
NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF]
NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040]
Name ::= NameStartChar (NameChar)*
In addition, colons in IDs fail when embedding an SVG via <img>.
We use encodeURIComponent which escapes everything except
A-Z a-z 0-9 - _ . ! ~ * ' ( )
[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent]
into %-encoded symbols, plus we encode _ . ! ~ * ' ( ) and - 0-9 (start only).
But % (and %-encoded) symbols are not supported, so we replace '%' with '_',
an allowed character that we escape.
In the special case of a blank key, we use the special _blank which cannot
be generated by the escaping process.
###
(encodeURIComponent key
.replace /[_\.!~*'()]|^[\-0-9]/g,
(c) -> "%#{c.charCodeAt(0).toString(16).toUpperCase()}"
.replace /%/g, '_'
) or '_blank'
zeroSizeReplacement = 1
removeSVGComments = (svg) ->
## Remove SVG/XML comments such as <?xml...?> and <!DOCTYPE>
## (spec: https://www.w3.org/TR/2008/REC-xml-20081126/#NT-prolog)
svg.replace /<\?[^]*?\?>|<![^-][^]*?>|<!--[^]*?-->/g, ''
#currentMapping = null
currentRender = null
currentDriver = null
currentContext = null
#getMapping = ->
# ## Returns current `Mapping` object,
# ## when used at top level of a JS/CS mapping file.
# currentMapping
#runWithMapping = (mapping, fn) ->
# ## Runs the specified function `fn` as if it were called
# ## at the top level of the specified mapping.
# oldMapping = currentMapping
# currentMapping = mapping
# try
# fn()
# finally
# currentMapping = oldMapping
getRender = ->
## Returns current `Render` object, when used within its execution.
currentRender
runWithRender = (render, fn) ->
## Runs the specified function `fn` as if it were called
## from the specified `render`.
oldRender = currentRender
currentRender = render
try
fn()
finally
currentRender = oldRender
getDriver = ->
## Returns current `Driver` object, when used within its execution.
currentDriver
runWithDriver = (driver, fn) ->
## Runs the specified function `fn` as if it were called
## from the specified `driver`.
oldDriver = currentDriver
currentDriver = driver
try
fn()
finally
currentDriver = oldDriver
getContext = ->
## Returns current `Context` object, when used within a mapping function.
currentContext
runWithContext = (context, fn) ->
## Runs the specified function `fn` as if it were called
## within the specified `context`.
oldContext = currentContext
currentContext = context
try
fn()
finally
currentContext = oldContext
getContextString = ->
## Returns string describing the current context
if currentContext?
"tile '#{currentContext.tile}' in row #{currentContext.i+1}, column #{currentContext.j+1} of drawing '#{currentContext.drawing.filename}'"
#else if currentMapping?
# "mapping '#{currentMapping.filename}'"
else if currentRender?
"render of '#{currentRender.drawing.filename}'"
else
'unknown context'
getSettings = ->
###
Returns currently active `Settings` object, if any, from
* the current Render process (which includes the case of an active Context),
* the current Mapping file,
* the current Driver process, or
* `defaultSettings` if none of the above are currently active.
###
#if currentContext?
# currentContext.render.settings
if currentRender?
currentRender.settings
#else if currentMapping?
# currentMapping.settings
else if currentDriver?
currentDriver.settings
else
defaultSettings
## SVG container element tags from
## https://developer.mozilla.org/en-US/docs/Web/SVG/Element#container_elements
## that are useless when empty and have no `id` attribute.
emptyContainers = new Set [
'defs'
'g'
'svg'
'switch'
'symbol'
]
preactRenderToDom = null
class SVGContent extends HasSettings
###
Base helper for parsing SVG as specified in SVG Tiler:
SVG strings, Preact VDOM, or filenames, with special handling of image files.
Automatically determines `width`, `height`, `viewBox`, `boundingBox`,
and `zIndex` properties if specified in the SVG content,
and sets `isEmpty` to indicate whether the SVG is a useless empty tag.
In many cases (symbols and defs), acquires an `id` property via `setId`,
which can be formatted via `url()` and `hash()`.
In some cases, acquires `isStatic` Boolean property to indicate
re-usable content, or `isForced` Boolean property to indicate
a def that should be included by force (even if unused).
###
constructor: (@name, @value, @settings) ->
## `@value` can be a string (SVG or filename) or Preact VDOM.
super()
url: ->
"url(##{@id})"
hash: ->
"##{@id}"
force: (value = true) ->
@isForced = value
@ # allow chaining
makeSVG: ->
return @svg if @svg?
## Set `@svg` to SVG string for duplication detection.
if isPreact @value
## Render Preact virtual dom nodes (e.g. from JSX notation) into strings
## and directly into DOM.
@svg =
(window?.preactRenderToString?.default ?
require('preact-render-to-string')) @value
if preactRenderToDom == null
try
preactRenderToDom = window?.preactRenderToDom?.RenderToDom ?
require 'preact-render-to-dom'
if preactRenderToDom?
if xmldom?
preactRenderToDom = new preactRenderToDom.RenderToXMLDom {xmldom,
svg: true
skipNS: true
}
else
preactRenderToDom = new preactRenderToDom.RenderToDom {svg: true}
if preactRenderToDom?
@dom = preactRenderToDom.render @value
@postprocessDOM()
else if typeof @value == 'string'
if @value.trim() == '' ## Blank SVG mapped to empty <symbol>
@svg = '<symbol/>' ## This will get width/height 0 in SVGSymbol
else unless @value.includes '<' ## No <'s -> interpret as filename
filename = @value
filename = path.join @settings.dirname, filename if @settings?.dirname?
extension = extensionOf filename
## <image> tag documentation: "Conforming SVG viewers need to
## support at least PNG, JPEG and SVG format files."
## [https://svgwg.org/svg2-draft/embedded.html#ImageElement]
switch extension
when '.png', '.jpg', '.jpeg', '.gif'
@svg = """
<image #{hrefAttr @settings}="#{encodeURI @value}"/>
"""
when '.svg'
@filename = filename
@settings = {...@settings, dirname: path.dirname filename}
@svg = loadSVG @filename, @settings
else
throw new SVGTilerError "Unrecognized extension in filename '#{@value}' for #{@name}"
else
@svg = @value
else
throw new SVGTilerError "Invalid value for #{@name}: #{typeof @value}"
## Remove initial SVG/XML comments (for broader duplication detection,
## and the next replace rule).
@svg = removeSVGComments @svg
setId: (@id) ->
## Can be called before or after makeDOM, updating DOM in latter case.
@dom.setAttribute 'id', @id if @dom?
defaultId: (base = 'id') ->
###
Generate a "default" id (typically for use in def) using these rules:
1. If the root element has an `id` attribute, use that (manual spec).
2. Use the root element's tag name, if any
3. Fallback to use first argument `base`, which defaults to `"id"`.
The returned id is not yet escaped; you should pass it to `escapeId`.
###
doc = @makeDOM()
doc.getAttribute('id') or doc.tagName or base
makeDOM: ->
return @dom if @dom?
@makeSVG()
## Force SVG namespace when parsing, so nodes have correct namespaceURI.
## (This is especially important on the browser, so the results can be
## reparented into an HTML Document.)
svg = @svg.replace /^\s*<(?:[^<>'"\/]|'[^']*'|"[^"]*")*\s*(\/?\s*>)/,
(match, end) ->
unless match.includes 'xmlns'
match = match[...match.length-end.length] +
" xmlns='#{SVGNS}'" + match[match.length-end.length..]
match
@dom = new DOMParser
locator: ## needed when specifying errorHandler
line: 1
col: 1
errorHandler: (level, msg, indent = ' ') =>
msg = msg.replace /^\[xmldom [^\[\]]*\]\t/, ''
msg = msg.replace /@#\[line:(\d+),col:(\d+)\]$/, (match, line, col) =>
lines = svg.split '\n'
(if line > 1 then indent + lines[line-2] + '\n' else '') +
indent + lines[line-1] + '\n' +
indent + ' '.repeat(col-1) + '^^^' +
(if line < lines.length then '\n' + indent + lines[line] else '')
console.error "SVG parse #{level} in #{@name}: #{msg}"
.parseFromString svg, 'image/svg+xml'
.documentElement
@postprocessDOM()
@dom
postprocessDOM: ->
## Remove from the symbol any top-level xmlns=SVGNS or xmlns:xlink,
## in the original parsed content or possibly added above,
## to avoid conflict with these attributes in the top-level <svg>.
## `removeAttribute` won't be defined in the case @dom is DocumentFragment.
@dom.removeAttribute? 'xmlns'
unless @getSetting 'useHref'
@dom.removeAttribute? 'xmlns:xlink'
## Wrap in <symbol> if appropriate,
## before we add width/height/etc. attributes.
@wrap?()
## <image> processing (must come before width/height processing).
domRecurse @dom, (node) =>
if node.nodeName == 'image'
###
Fix image-rendering: if unspecified, or if specified as "optimizeSpeed"
or "pixelated", attempt to render pixels as pixels, as needed for
old-school graphics. SVG 1.1 and Inkscape define
image-rendering="optimizeSpeed" for this. Chrome doesn't support this,
but supports a CSS3 (or SVG) specification of
"image-rendering:pixelated". Combining these seems to work everywhere.
###
imageRendering = attributeOrStyle node, 'image-rendering'
if not imageRendering? or
imageRendering in ['optimizeSpeed', 'pixelated']
node.setAttribute 'image-rendering', 'optimizeSpeed'
style = node.getAttribute('style') ? ''
style = style.replace /(^|;)\s*image-rendering\s*:\s*\w+\s*($|;)/,
(m, before, after) -> before or after or ''
style += ';' if style
node.setAttribute 'style', style + 'image-rendering:pixelated'
## Read file for width/height detection and/or inlining
{href, key} = getHref node
filename = href
if @settings?.dirname? and filename
filename = path.join @settings.dirname, filename
if filename? and not /^data:|file:|[a-z]+:\/\//.test filename # skip URLs
filedata = null
try
filedata = fs.readFileSync filename unless window?
catch e
console.warn "Failed to read image '#{filename}': #{e}"
## Fill in width and/or height if missing
width = parseFloat node.getAttribute 'width'
height = parseFloat node.getAttribute 'height'
if (isNaN width) or (isNaN height)
size = null
if filedata? and not window?
try
size = require('image-size') filedata ? filename
catch e
console.warn "Failed to detect size of image '#{filename}': #{e}"
if size?
## If one of width and height is set, scale to match.
if not isNaN width
node.setAttribute 'height', size.height * (width / size.width)
else if not isNaN height
node.setAttribute 'width', size.width * (height / size.height)
else
## If neither width nor height are set, set both.
node.setAttribute 'width', size.width
node.setAttribute 'height', size.height
## Inline
if filedata? and @getSetting 'inlineImages'
type = contentType[extensionOf filename]
if type?
node.setAttribute "data-filename", path.basename filename
if size?
node.setAttribute "data-width", size.width
node.setAttribute "data-height", size.height
node.setAttribute key,
"data:#{type};base64,#{filedata.toString 'base64'}"
false
else
true
## Determine whether the symbol is "empty",
## meaning it has no useful content so can be safely omitted.
recursiveEmpty = (node, allowId) ->
return not node.data if node.nodeType == node.TEXT_NODE
return false unless node.nodeType == node.DOCUMENT_FRAGMENT_NODE or
emptyContainers.has node.tagName
## `hasAttribute` won't be defined in the case node is DocumentFragment
return false unless allowId or not node.hasAttribute? 'id'
for child in node.childNodes
return false unless recursiveEmpty child
true
@isEmpty = recursiveEmpty @dom, @emptyWithId
## Determine `viewBox`, `width`, and `height` attributes.
@viewBox = parseBox @dom.getAttribute 'viewBox'
@width = parseDim @origWidth = @dom.getAttribute 'width'
@height = parseDim @origHeight = @dom.getAttribute 'height'
## Check for default width/height specified by caller.
if not @width? and @defaultWidth?
@dom.setAttribute 'width', @width = @defaultWidth
if not @height? and @defaultHeight?
@dom.setAttribute 'height', @height = @defaultHeight
## Absent viewBox becomes 0 0 <width> <height> if latter are present
## (but only internal to SVG Tiler, DOM remains unchanged).
if @width? and @height? and not @viewBox? and @autoViewBox
@viewBox = [0, 0, @width, @height]
## Absent viewBox set to automatic bounding box if requested
## (e.g. in `SVGSymbol`).
if not @viewBox? and @autoViewBox
## Treat empty content (e.g. empty fragment) as 0x0.
if @isEmpty
@viewBox = [0, 0, 0, 0]
@dom.setAttribute 'viewBox', @viewBox.join ' '
else if (@viewBox = svgBBox @dom)?
@dom.setAttribute 'viewBox', @viewBox.join ' '
## Absent width/height inherited from viewBox if latter is present,
## in `SVGSymbol` which sets `@autoWidthHeight`.
## Including the width/height in the <symbol> lets us skip it in <use>.
if @viewBox? and @autoWidthHeight
unless @width?
@dom.setAttribute 'width', @width = @viewBox[2]
unless @height?
@dom.setAttribute 'height', @height = @viewBox[3]
## Overflow behavior
overflow = attributeOrStyle @dom, 'overflow'
if not overflow? and @defaultOverflow?
@dom.setAttribute 'overflow', overflow = @defaultOverflow
@overflowVisible = (overflow? and /^\s*(visible|scroll)\b/.test overflow)
###
SVG's `viewBox`, `width`, and `height` attributes have a special rule that
"A value of zero disables rendering of the element."
[https://www.w3.org/TR/SVG11/coords.html#ViewBoxAttribute]
[https://www.w3.org/TR/SVG11/struct.html#SVGElementWidthAttribute]
Avoid this if overflow is visible.
###
if @overflowVisible
if @width == 0
@dom.setAttribute 'width', zeroSizeReplacement
if @height == 0
@dom.setAttribute 'height', zeroSizeReplacement
if @viewBox? and (@viewBox[2] == 0 or @viewBox[3] == 0)
@viewBox[2] = zeroSizeReplacement if @viewBox[2] == 0
@viewBox[3] = zeroSizeReplacement if @viewBox[3] == 0
@dom.setAttribute 'viewBox', @viewBox.join ' '
## Special SVG Tiler attributes that get extracted from DOM
@boundingBox = extractBoundingBox @dom
@zIndex = extractZIndex @dom
#@isEmpty = @dom.childNodes.length == 0 and
# (@emptyWithId or not @dom.hasAttribute 'id') and
# emptyContainers.has @dom.tagName
return
useDOM: ->
@makeDOM()
## `@idOverride` sets `id` attribute just in the used DOM,
## without changing the `@id` property of the `SVGContent` object.
@dom.setAttribute 'id', @idOverride if @idOverride?
## Clone if content is static, to enable later re-use
if @isStatic
@dom.cloneNode true
else
@dom
class SVGWrapped extends SVGContent
###
Abstract base class for `SVGSymbol` and `SVGSVG` which automatically wrap
content in a containing element (`<symbol>` or `<svg>` respectively).
Subclass should define `wrapper` of 'symbol' or 'svg'.
Parser will enforce that the content is wrapped in this element.
###
wrap: ->
## Wrap XML in <wrapper>.
symbol = @dom.ownerDocument.createElementNS SVGNS, @wrapper
## Force `id` to be first attribute.
symbol.setAttribute 'id', @id or ''
## Avoid a layer of indirection for <symbol>/<svg> at top level
if @dom.nodeName in ['symbol', 'svg']
for attribute in @dom.attributes
unless attribute.name in ['version', 'id'] or attribute.name.startsWith 'xmlns'
symbol.setAttribute attribute.name, attribute.value
for child in (node for node in @dom.childNodes)
symbol.appendChild child
@dom.parentNode?.replaceChild symbol, @dom
else
## Allow top-level object to specify <symbol> data.
for attribute in ['viewBox', 'boundingBox', 'z-index', 'overflow',
'width', 'height']
## `width` and `height` have another meaning in e.g. <rect>s,
## so just transfer for tags where they are meaningless.
continue if attribute in ['width', 'height'] and
@dom.tagName not in ['g']
## `hasAttribute` won't be defined in the case @dom is DocumentFragment
if @dom.hasAttribute? attribute
symbol.setAttribute attribute, @dom.getAttribute attribute
@dom.removeAttribute attribute
parent = @dom.parentNode
symbol.appendChild @dom
parent?.appendChild symbol
@dom = symbol
#class SVGSVG extends SVGWrapped
# ###
# SVG content wrapped in `<svg>`.
# ###
# wrapper: 'svg'
class SVGSymbol extends SVGWrapped
###
SVG content wrapped in `<symbol>`, with special width/height handling
and text extraction, used for tiles.
Note though that one `SVGSymbol` may be re-used in many different `Tile`s.
###
wrapper: 'symbol'
autoViewBox: true
autoWidthHeight: true
emptyWithId: true # consider empty even if <symbol> has id attribute
postprocessDOM: ->
## Special defaults for loading symbols in `SVGContent`'s `makeDOM`.
@defaultWidth = @getSetting 'forceWidth'
@defaultHeight = @getSetting 'forceHeight'
@defaultOverflow = @getSetting 'overflowDefault'
## `SVGContent` sets `@width` and `@height` according to
## `width`/`height`/`viewBox` attributes or our defaults.
super()
## Detect special `width="auto"` and/or `height="auto"` fields for future
## processing, and remove them to ensure valid SVG.
@autoWidth = isAuto @origWidth
@autoHeight = isAuto @origHeight