-
Notifications
You must be signed in to change notification settings - Fork 9
/
svg.js
229 lines (205 loc) · 6.7 KB
/
svg.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
/**
* Svg loading plugin.
*
* This plugin loads an svg graphic and defines it in the DOM, so you can reference it in a `<use>` tag.
*
* @example:
* To load the svg file `myicons/myicon.svg`:
* ```
* require(["requirejs-dplugins/svg!myicons/myicon.svg"], function (myiconId){
* // myicon was added to the DOM
* });
* ```
* @module requirejs-dplugins/svg
*/
define([
"./has",
"module",
"requirejs-text/text",
"requirejs-domready/domReady"
], function (has, module, textPlugin, domReady) {
"use strict";
var loaded = {}, // paths of loaded svgs
SPRITE_ID = 'requirejs-dplugins-svg',
sprite = null;
var loadSVG = {
id: module.id,
/**
* Loads an svg file.
* @param {string} path - The svg file to load.
* @param {Function} resourceRequire - A require function local to the module calling the svg plugin.
* @param {Function} onload - A function to call when the specified svg file have been loaded.
* @method
*/
load: function (path, resourceRequire, onload) {
if (has("builder")) { // when building
loaded[path] = true;
onload();
} else { // when running
// special case: when running a built version
// Replace graphic by corresponding sprite.
var idInLayer;
var layersMap = module.config().layersMap;
if (layersMap && layersMap[path]) {
idInLayer = layersMap[path].id;
path = layersMap[path].redirectTo;
}
if (!(path in loaded)) {
loaded[path] = new Promise(function (resolve) {
textPlugin.load(path, resourceRequire, function (svgText) {
domReady(function () {
if (!sprite) {
sprite = createSprite(document, SPRITE_ID);
document.body.appendChild(sprite);
}
var symbol = extractGraphicAsSymbol(document, svgText);
sprite.appendChild(symbol);
resolve(symbol.getAttribute("id"));
});
});
});
}
loaded[path].then(function (symbolId) {
onload(idInLayer || symbolId);
});
}
}
};
if (has("builder")) {
// build variables
var writePluginFiles;
var buildFunctions = {
/**
* Writes the layersMap configuration to the corresponding modules layer.
* The configuration will look like this:
* ```js
* require.config({
* config: {
* "requirejs-dplugins/svg": {
* layersMap: {
* "file1.svg": {redirectTo: "path/to/layer.svg", id: "id-inside-file-1"},
* "file2.svg": {redirectTo: "path/to/layer.svg", id: "id-inside-file-2"}
* }
* }
* }
* });
* ```
*
* @param {Function} write - This function takes a string as argument
* and writes it to the modules layer.
* @param {string} mid - Current module id.
* @param {string} dest - Current svg sprite path.
* @param {Array} loaded - Maps the paths of the svg files contained in current sprite to their ids.
*/
writeConfig: function (write, mid, destMid, loaded) {
var svgConf = {
config: {},
paths: {}
};
svgConf.config[mid] = {
layersMap: {}
};
for (var path in loaded) {
svgConf.config[mid].layersMap[path] = {redirectTo: destMid, id: loaded[path]};
}
write("require.config(" + JSON.stringify(svgConf) + ");");
},
/**
* Concatenates all svg files required by a modules layer and write the result.
*
* @param {Function} writePluginFiles - The write function provided by the builder to `writeFile`.
* and writes it to the modules layer.
* @param {string} dest - Current svg sprite path.
* @param {Array} loaded - Maps the paths of the svg files contained in current sprite to their ids.
*/
writeLayer: function (writePluginFiles, dest, loaded) {
function tryRequire(paths) {
var module;
var path = paths.shift();
if (path) {
try {
// This is a node-require so it is synchronous.
module = require.nodeRequire(path);
} catch (e) {
if (e.code === "MODULE_NOT_FOUND") {
return tryRequire(paths);
} else {
throw e;
}
}
}
return module;
}
var fs = require.nodeRequire("fs"),
jsDomPath = require.getNodePath(require.toUrl(module.id).replace(/[^\/]*$/, "node_modules/jsdom")),
jsDomModule = tryRequire([jsDomPath, "jsdom"]);
var path, url, svgText;
if (!jsDomModule) {
console.log(">> WARNING: Node module jsdom not found. Skipping SVG bundling. If you" +
" want SVG bundling run 'npm install jsdom' in your console.");
for (path in loaded) {
url = require.toUrl(path);
svgText = fs.readFileSync(url, "utf8");
writePluginFiles(url, svgText);
}
return false;
} else {
var jsdom = jsDomModule.jsdom,
document = jsdom("<html></html>"),
sprite = createSprite(document);
for (path in loaded) {
url = require.toUrl(path);
svgText = fs.readFileSync(url, "utf8");
var symbol = extractGraphicAsSymbol(document, svgText);
sprite.appendChild(symbol);
loaded[path] = symbol.getAttribute("id");
}
writePluginFiles(dest, sprite.outerHTML);
return true;
}
}
};
loadSVG.writeFile = function (pluginName, resource, require, write) {
writePluginFiles = write;
};
loadSVG.onLayerEnd = function (write, layer) {
if (layer.name && layer.path) {
var dest = layer.path.replace(/^(.*\/)?(.*).js$/, "$1/$2.svg"),
destMid = layer.name + ".svg";
// Write layer file and config
var success = buildFunctions.writeLayer(writePluginFiles, dest, loaded);
success && buildFunctions.writeConfig(write, module.id, destMid, loaded);
// Reset cache
loaded = {};
}
};
}
return loadSVG;
// makes a symbol out of an svg graphic
function extractGraphicAsSymbol(document, svgText) {
var div = document.createElement("div");
div.innerHTML = svgText;
var element = div.querySelector("svg"),
id = element.getAttribute("id"),
viewBox = element.getAttribute("viewbox") || element.getAttribute("viewBox"),
symbol = createSymbol(document, id, element, viewBox);
return symbol;
}
// makes symbol from svg element
function createSymbol(document, id, element, viewBox) {
var symbol = document.createElementNS("http://www.w3.org/2000/svg", "symbol");
while (element.firstChild) {
symbol.appendChild(element.firstChild);
}
typeof id === "string" && symbol.setAttribute("id", id);
typeof viewBox === "string" && symbol.setAttribute("viewBox", viewBox);
return symbol;
}
// creates empty sprite
function createSprite(document, id) {
var sprite = document.createElementNS("http://www.w3.org/2000/svg", "svg");
sprite.setAttribute("style", "display: none");
id && sprite.setAttribute("id", id);
return sprite;
}
});