@thasmo/external-svg-polyfill
Version:
Small and basic polyfill to support referencing external SVG files.
214 lines (206 loc) • 10.2 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.ExternalSvgPolyfill = factory());
}(this, (function () { 'use strict';
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var Polyfill = (function () {
function Polyfill(options) {
this.defaults = {
target: 'svg use',
context: window.document.body || window.document.documentElement,
root: window.document.body || window.document.documentElement,
run: true,
prefix: true,
detect: true,
observe: true,
crossdomain: true,
namespace: 'external-svg-polyfill',
agents: [
/msie|trident/i,
/edge\/12/i,
/ucbrowser\/11/i,
],
};
this.options = __assign(__assign({}, this.defaults), options);
this.cache = {
files: new Map(),
elements: new Map(),
};
this.handler = {
viewportChange: this.onViewportChange.bind(this),
documentChange: this.onDocumentChanged.bind(this),
};
this.observer = new MutationObserver(this.handler.documentChange);
this.parser = window.document.createElement('a');
this.process = !this.options.detect || this.detect();
this.options.run && this.run();
}
Polyfill.prototype.run = function () {
this.updateElements();
this.options.observe && this.observe();
};
Polyfill.prototype.detect = function () {
return this.options.agents.some(function (agent) { return agent.test(window.navigator.userAgent); });
};
Polyfill.prototype.observe = function () {
this.observer.observe(this.options.context, {
childList: true,
subtree: true,
attributes: true,
attributeFilter: ['href', 'xlink:href'],
});
window.addEventListener('resize', this.handler.viewportChange);
window.addEventListener('orientationchange', this.handler.viewportChange);
};
Polyfill.prototype.unobserve = function () {
this.observer.disconnect();
window.removeEventListener('resize', this.handler.viewportChange);
window.removeEventListener('orientationchange', this.handler.viewportChange);
};
Polyfill.prototype.destroy = function () {
var _this = this;
this.unobserve();
this.cache.elements.forEach(function (value, element) {
_this.dispatchEvent(element, 'revoke', { value: value }, function () {
_this.renderFrame(function () {
_this.setLinkAttribute(element, value);
_this.cache.elements.delete(element);
});
});
});
this.cache.files.forEach(function (file, address) {
file && _this.dispatchEvent(file, 'remove', { address: address }, function () {
_this.renderFrame(function () { return _this.options.root.removeChild(file); });
_this.cache.files.delete(address);
});
});
};
Polyfill.prototype.updateElements = function () {
var elements = typeof this.options.target === 'string'
? [].slice.call(this.options.context.querySelectorAll(this.options.target))
: this.options.target;
elements.forEach(this.processElement.bind(this));
};
Polyfill.prototype.processElement = function (element) {
var _this = this;
var value = element.getAttribute('href') || element.getAttribute('xlink:href');
if (value && value.indexOf('#') !== 0 && !this.cache.elements.has(element)) {
this.parser.href = value;
if (this.process || (this.options.crossdomain && window.location.origin !== this.parser.origin)) {
var address_1 = this.parser.href.split('#')[0];
var identifier_1 = this.generateIdentifier(this.parser.hash, this.parser.pathname);
if (address_1 && !this.cache.files.has(address_1)) {
this.dispatchEvent(element, 'load', { address: address_1 }, function () {
_this.cache.files.set(address_1, null);
_this.loadFile(address_1);
});
}
this.dispatchEvent(element, 'apply', { address: address_1, identifier: identifier_1 }, function () {
_this.renderFrame(function () {
_this.setLinkAttribute(element, "#" + identifier_1);
_this.cache.elements.set(element, value);
});
});
}
}
};
Polyfill.prototype.loadFile = function (address) {
var _this = this;
var loader = new XMLHttpRequest();
loader.addEventListener('load', function (event) { return _this.onFileLoaded.call(_this, event, address); });
loader.open('get', address);
loader.responseType = 'document';
loader.send();
};
Polyfill.prototype.generateIdentifier = function (identifier, prefix) {
identifier = identifier.replace('#', '');
prefix = prefix.replace(/^\//, '').replace(/\.svg$/, '').replace(/[^a-zA-Z0-9]/g, '-');
return this.options.prefix
? prefix + "-" + identifier
: identifier;
};
Polyfill.prototype.dispatchEvent = function (element, name, detail, callback) {
var event = window.document.createEvent('CustomEvent');
event.initCustomEvent(this.options.namespace + "." + name, true, true, detail);
element.dispatchEvent(event);
if (!event.defaultPrevented && callback) {
callback();
}
};
Polyfill.prototype.renderFrame = function (callback) {
window.requestAnimationFrame(callback.bind(this));
};
Polyfill.prototype.setLinkAttribute = function (element, value) {
element.hasAttribute('href') && element.setAttribute('href', value);
element.hasAttribute('xlink:href') && element.setAttribute('xlink:href', value);
};
Polyfill.prototype.prefixValues = function (file, prefix) {
var _this = this;
var value = file.getAttribute('id');
if (value) {
var identifier = this.generateIdentifier(value, prefix);
file.setAttribute('id', identifier);
}
[].slice.call(file.querySelectorAll('[id]')).forEach(function (reference) {
var value = reference.getAttribute('id');
if (value) {
var identifier_2 = _this.generateIdentifier(value, prefix);
reference.setAttribute('id', identifier_2);
[].slice.call(file.querySelectorAll("[fill=\"url(#" + value + ")\"]")).forEach(function (referencee) {
referencee.setAttribute('fill', "url(#" + identifier_2 + ")");
});
}
});
};
Polyfill.prototype.onDocumentChanged = function () {
this.updateElements();
};
Polyfill.prototype.onViewportChange = function () {
this.updateElements();
};
Polyfill.prototype.onFileLoaded = function (event, address) {
var _this = this;
var file = event.target.response.documentElement;
file.setAttribute('aria-hidden', 'true');
file.style.position = 'absolute';
file.style.overflow = 'hidden';
file.style.width = 0;
file.style.height = 0;
this.cache.files.set(address, file);
if (this.options.prefix) {
this.parser.href = address;
this.prefixValues(file, this.parser.pathname);
}
this.dispatchEvent(this.options.root, 'insert', { address: address, file: file }, function () {
_this.renderFrame(function () {
_this.options.root.insertAdjacentElement('afterbegin', file);
});
});
};
return Polyfill;
}());
return Polyfill;
})));
//# sourceMappingURL=bundle.js.map