UNPKG

@dicebear/avatars

Version:
1,608 lines (1,415 loc) 41.6 kB
import _hexToRgb from 'pure-color/parse/hex'; import _rgbToHsv from 'pure-color/convert/rgb2hsv'; import _rgbToHex from 'pure-color/convert/rgb2hex'; import _hsvToRgb from 'pure-color/convert/hsv2rgb'; import { parseSync, stringify } from 'svgson'; function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread2(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } function _toArray(arr) { return _arrayWithHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableRest(); } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function () {}; return { s: F, n: function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function (e) { throw e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function () { it = it.call(o); }, n: function () { var step = it.next(); normalCompletion = step.done; return step; }, e: function (e) { didErr = true; err = e; }, f: function () { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } var MIN = -2147483648; var MAX = 2147483647; function xorshift(value) { value ^= value << 13; value ^= value >> 17; value ^= value << 5; return value; } function hashSeed(seed) { var hash = 0; for (var i = 0; i < seed.length; i++) { hash = (hash << 5) - hash + seed.charCodeAt(i) | 0; hash = xorshift(hash); } return hash; } function randomSeed() { return MIN + Math.floor((MAX - MIN) * Math.random()).toString(); } function create(seed) { var _seed; seed = (_seed = seed) !== null && _seed !== void 0 ? _seed : randomSeed(); var value = hashSeed(seed) || 1; var next = function next() { return value = xorshift(value); }; var _integer = function integer(min, max) { return Math.floor((next() - MIN) / (MAX - MIN) * (max + 1 - min) + min); }; return { seed: seed, bool: function bool() { var likelihood = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 50; return _integer(0, 100) < likelihood; }, integer: function integer(min, max) { return _integer(min, max); }, pick: function pick(arr) { return arr[_integer(0, arr.length - 1)]; } }; } var prng = /*#__PURE__*/Object.freeze({ __proto__: null, create: create }); /** * @deprecated use `utils.prng` instead. */ var Random = /*#__PURE__*/function () { function Random(seed) { _classCallCheck(this, Random); _defineProperty(this, "prng", void 0); _defineProperty(this, "seed", void 0); this.prng = create(seed); this.seed = this.prng.seed; } _createClass(Random, [{ key: "bool", value: function bool() { var likelihood = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 50; return this.prng.bool(likelihood); } }, { key: "integer", value: function integer(min, max) { return this.prng.integer(min, max); } }, { key: "pickone", value: function pickone(arr) { return this.prng.pick(arr); } }]); return Random; }(); var color$i = { 50: '#FFF8E1', 100: '#FFECB3', 200: '#FFE082', 300: '#FFB74D', 400: '#FFCA28', 500: '#FFC107', 600: '#FFB300', 700: '#FFA000', 800: '#FF8F00', 900: '#FF6F00' }; var color$h = { 50: '#E3F2FD', 100: '#BBDEFB', 200: '#90CAF9', 300: '#64B5F6', 400: '#42A5F5', 500: '#2196F3', 600: '#1E88E5', 700: '#1976D2', 800: '#1565C0', 900: '#0D47A1' }; var color$g = { 50: '#ECEFF1', 100: '#CFD8DC', 200: '#B0BEC5', 300: '#90A4AE', 400: '#78909C', 500: '#607D8B', 600: '#546E7A', 700: '#455A64', 800: '#37474F', 900: '#263238' }; var color$f = { 50: '#EFEBE9', 100: '#D7CCC8', 200: '#BCAAA4', 300: '#A1887F', 400: '#8D6E63', 500: '#795548', 600: '#6D4C41', 700: '#5D4037', 800: '#4E342E', 900: '#3E2723' }; var color$e = { 50: '#E0F7FA', 100: '#B2EBF2', 200: '#80DEEA', 300: '#4DD0E1', 400: '#26C6DA', 500: '#00BCD4', 600: '#00ACC1', 700: '#0097A7', 800: '#00838F', 900: '#006064' }; var color$d = { 50: '#FBE9E7', 100: '#FFCCBC', 200: '#FFAB91', 300: '#A1887F', 400: '#FF7043', 500: '#FF5722', 600: '#F4511E', 700: '#E64A19', 800: '#D84315', 900: '#BF360C' }; var color$c = { 50: '#EDE7F6', 100: '#D1C4E9', 200: '#B39DDB', 300: '#9575CD', 400: '#7E57C2', 500: '#673AB7', 600: '#5E35B1', 700: '#512DA8', 800: '#4527A0', 900: '#311B92' }; var color$b = { 50: '#E8F5E9', 100: '#C8E6C9', 200: '#A5D6A7', 300: '#81C784', 400: '#66BB6A', 500: '#4CAF50', 600: '#43A047', 700: '#388E3C', 800: '#2E7D32', 900: '#1B5E20' }; var color$a = { 50: '#FAFAFA', 100: '#F5F5F5', 200: '#EEEEEE', 300: '#E0E0E0', 400: '#BDBDBD', 500: '#9E9E9E', 600: '#757575', 700: '#616161', 800: '#424242', 900: '#212121' }; var color$9 = { 50: '#E8EAF6', 100: '#C5CAE9', 200: '#9FA8DA', 300: '#7986CB', 400: '#5C6BC0', 500: '#3F51B5', 600: '#3949AB', 700: '#303F9F', 800: '#283593', 900: '#1A237E' }; var color$8 = { 50: '#E1F5FE', 100: '#B3E5FC', 200: '#81D4FA', 300: '#4FC3F7', 400: '#29B6F6', 500: '#03A9F4', 600: '#039BE5', 700: '#0288D1', 800: '#0277BD', 900: '#01579B' }; var color$7 = { 50: '#F1F8E9', 100: '#DCEDC8', 200: '#C5E1A5', 300: '#AED581', 400: '#9CCC65', 500: '#8BC34A', 600: '#7CB342', 700: '#689F38', 800: '#558B2F', 900: '#33691E' }; var color$6 = { 50: '#F9FBE7', 100: '#F0F4C3', 200: '#E6EE9C', 300: '#DCE775', 400: '#D4E157', 500: '#CDDC39', 600: '#C0CA33', 700: '#AFB42B', 800: '#9E9D24', 900: '#827717' }; var color$5 = { 50: '#FFF3E0', 100: '#FFE0B2', 200: '#FFCC80', 300: '#FF8A65', 400: '#FFA726', 500: '#FF9800', 600: '#FB8C00', 700: '#F57C00', 800: '#EF6C00', 900: '#E65100' }; var color$4 = { 50: '#FCE4EC', 100: '#F8BBD0', 200: '#F48FB1', 300: '#F06292', 400: '#EC407A', 500: '#E91E63', 600: '#D81B60', 700: '#C2185B', 800: '#AD1457', 900: '#880E4F' }; var color$3 = { 50: '#F3E5F5', 100: '#E1BEE7', 200: '#CE93D8', 300: '#BA68C8', 400: '#AB47BC', 500: '#9C27B0', 600: '#8E24AA', 700: '#7B1FA2', 800: '#6A1B9A', 900: '#4A148C' }; var color$2 = { 50: '#FFEBEE', 100: '#FFCDD2', 200: '#EF9A9A', 300: '#E57373', 400: '#EF5350', 500: '#F44336', 600: '#E53935', 700: '#D32F2F', 800: '#C62828', 900: '#B71C1C' }; var color$1 = { 50: '#E0F2F1', 100: '#B2DFDB', 200: '#80CBC4', 300: '#4DB6AC', 400: '#26A69A', 500: '#009688', 600: '#00897B', 700: '#00796B', 800: '#00695C', 900: '#004D40' }; var color = { 50: '#FFFDE7', 100: '#FFF9C4', 200: '#FFF59D', 300: '#FFF176', 400: '#FFEE58', 500: '#FFEB3B', 600: '#FDD835', 700: '#FBC02D', 800: '#F9A825', 900: '#F57F17' }; var collection = { amber: color$i, blue: color$h, blueGrey: color$g, brown: color$f, cyan: color$e, deepOrange: color$d, deepPurple: color$c, green: color$b, grey: color$a, indigo: color$9, lightBlue: color$8, lightGreen: color$7, lime: color$6, orange: color$5, pink: color$4, purple: color$3, red: color$2, teal: color$1, yellow: color }; /** @deprecated */ var Color = /*#__PURE__*/function () { function Color() { var color = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '#000'; _classCallCheck(this, Color); _defineProperty(this, "alpha", 1); _defineProperty(this, "color", {}); if (color[0] == '#') { this.hex = color; } else { var match = /^(rgb|rgba|hsv)\(([0-9\%\,\.\s]+)\)$/.exec(color.trim()); if (match) { var values = match[2].split(',').map(function (val) { return parseInt(val.trim()); }); switch (match[1]) { case 'rgb': this.rgb = values; break; case 'rgba': this.rgba = values; break; case 'hsv': this.hsv = values; break; default: throw new Error('Unsupported color format: ' + color); } } else { throw new Error('Unknown color format: ' + color); } } } _createClass(Color, [{ key: "clone", value: function clone() { return new Color('rgb(' + this.rgb.join(',') + ')'); } }, { key: "rgb", get: function get() { return this.color.rgb = this.color.rgb || (this.color.hex ? this.hexToRgb(this.hex) : this.hsvToRgb(this.hsv)); }, set: function set(rgb) { if (rgb.length != 3) { throw new Error('An array with a length of 3 is expected.'); } this.alpha = 1; this.color = { rgb: rgb }; } }, { key: "rgba", get: function get() { return [this.rgb[0], this.rgb[1], this.rgb[2], this.alpha]; }, set: function set(rgba) { if (rgba.length != 4) { throw new Error('An array with a length of 3 is expected.'); } this.rgb = [rgba[0], rgba[1], rgba[2]]; this.alpha = rgba[3]; } }, { key: "hsv", get: function get() { // Slice array to return copy return (this.color.hsv = this.color.hsv || this.rgbToHsv(this.rgb)).slice(0); }, set: function set(hsv) { if (hsv.length != 3) { throw new Error('An array with a length of 3 is expected.'); } this.alpha = 1; this.color = { hsv: hsv }; } }, { key: "hex", get: function get() { // Slice array to return copy return (this.color.hex = this.color.hex || this.rgbToHex(this.rgb)).slice(0); }, set: function set(hex) { this.alpha = 1; this.color = { hex: hex }; } }, { key: "brighterThan", value: function brighterThan(color, difference) { var primaryColorHsv = this.hsv; var secondaryColorHsv = color.hsv; if (primaryColorHsv[2] >= secondaryColorHsv[2] + difference) { return this; } primaryColorHsv[2] = secondaryColorHsv[2] + difference; if (primaryColorHsv[2] > 360) { primaryColorHsv[2] = 360; } this.hsv = primaryColorHsv; return this; } }, { key: "darkerThan", value: function darkerThan(color, difference) { var primaryColorHsv = this.hsv; var secondaryColorHsv = color.hsv; if (primaryColorHsv[2] <= secondaryColorHsv[2] - difference) { return this; } primaryColorHsv[2] = secondaryColorHsv[2] - difference; if (primaryColorHsv[2] < 0) { primaryColorHsv[2] = 0; } this.hsv = primaryColorHsv; return this; } }, { key: "brighterOrDarkerThan", value: function brighterOrDarkerThan(color, difference) { var primaryColorHsv = this.hsv; var secondaryColorHsv = color.hsv; if (primaryColorHsv[2] <= secondaryColorHsv[2]) { return this.darkerThan(color, difference); } else { return this.brighterThan(color, difference); } } }, { key: "rgbToHex", value: function rgbToHex(rgb) { return _rgbToHex(rgb); } }, { key: "hexToRgb", value: function hexToRgb(hex) { return _hexToRgb(hex).map(function (val) { return Math.round(val); }); } }, { key: "rgbToHsv", value: function rgbToHsv(rgb) { return _rgbToHsv(rgb).map(function (val) { return Math.round(val); }); } }, { key: "hsvToRgb", value: function hsvToRgb(hsv) { return _hsvToRgb(hsv).map(function (val) { return Math.round(val); }); } }]); return Color; }(); _defineProperty(Color, "collection", collection); var index$1 = /*#__PURE__*/Object.freeze({ __proto__: null, collection: collection, 'default': Color }); /** * @deprecated */ var Parser = /*#__PURE__*/function () { function Parser() { _classCallCheck(this, Parser); } _createClass(Parser, null, [{ key: "parse", value: function parse(svg) { return typeof svg === 'string' ? parseSync(svg) : svg; } }, { key: "stringify", value: function stringify$1(svg) { return typeof svg === 'string' ? svg : stringify(svg); } }]); return Parser; }(); function xml(attr) { return attr.replace(/&/g, '&amp;').replace(/'/g, '&apos;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); } var escape = /*#__PURE__*/Object.freeze({ __proto__: null, xml: xml }); var schema$1 = { "type": "object", "$schema": "http://json-schema.org/draft-07/schema#", "title": "Options", "properties": { "seed": { "title": "Seed", "type": "string" }, "s": { "title": "Seed", "type": "string" }, "base64": { "title": "Base64", "description": "@deprecated use dataUri instead", "type": "boolean", "default": false }, "dataUri": { "title": "Data URI", "type": "boolean", "default": false }, "userAgent": { "title": "User Agent", "description": "@deprecated", "type": "string" }, "flip": { "title": "Flip", "type": "boolean", "default": false }, "rotate": { "title": "Rotate", "type": "integer", "minimum": 0, "maximum": 360, "default": 0 }, "scale": { "title": "Scale", "type": "integer", "minimum": 0, "maximum": 200, "default": 100 }, "radius": { "title": "Radius", "type": "integer", "minimum": 0, "maximum": 50, "default": 0 }, "r": { "title": "Radius", "type": "integer", "minimum": 0, "maximum": 50, "default": 0 }, "width": { "title": "Width", "description": "@deprecated use size instead", "type": "integer", "minimum": 1 }, "w": { "title": "Width", "description": "@deprecated use size instead", "type": "integer", "minimum": 1 }, "height": { "title": "Height", "description": "@deprecated use size instead", "type": "integer", "minimum": 1 }, "h": { "title": "Height", "description": "@deprecated use size instead", "type": "integer", "minimum": 1 }, "size": { "title": "Size", "type": "integer", "minimum": 1 }, "margin": { "title": "Margin", "description": "@deprecated use scale instead", "type": "integer", "minimum": 0, "maximum": 25, "default": 0 }, "m": { "title": "Margin", "description": "@deprecated use scale instead", "type": "integer", "minimum": 0, "maximum": 25, "default": 0 }, "backgroundColor": { "title": "Background Color", "anyOf": [{ "type": "string", "pattern": "^#([a-fA-F0-9]{3}|[a-fA-F0-9]{4}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$" }, { "type": "string", "pattern": "^[0-9a-zA-Z]+$" }, { "type": "array", "items": { "anyOf": [{ "type": "string", "pattern": "^#([a-fA-F0-9]{3}|[a-fA-F0-9]{4}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$" }, { "type": "string", "pattern": "^[0-9a-zA-Z]+$" }] } }] }, "background": { "title": "Background Color", "anyOf": [{ "type": "string", "pattern": "^#([a-fA-F0-9]{3}|[a-fA-F0-9]{4}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$" }, { "type": "string", "pattern": "^[0-9a-zA-Z]+$" }, { "type": "array", "items": { "anyOf": [{ "type": "string", "pattern": "^#([a-fA-F0-9]{3}|[a-fA-F0-9]{4}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$" }, { "type": "string", "pattern": "^[0-9a-zA-Z]+$" }] } }], "description": "@deprecated use backgroundColor instead" }, "b": { "title": "Background Color", "anyOf": [{ "type": "string", "pattern": "^#([a-fA-F0-9]{3}|[a-fA-F0-9]{4}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$" }, { "type": "string", "pattern": "^[0-9a-zA-Z]+$" }, { "type": "array", "items": { "anyOf": [{ "type": "string", "pattern": "^#([a-fA-F0-9]{3}|[a-fA-F0-9]{4}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$" }, { "type": "string", "pattern": "^[0-9a-zA-Z]+$" }] } }] }, "translateX": { "title": "Translate X%", "type": "integer", "minimum": -100, "maximum": 100, "default": 0 }, "translateY": { "title": "Translate Y%", "type": "integer", "minimum": -100, "maximum": 100, "default": 0 } }, "additionalProperties": false }; function properties(schema) { return schema.properties || {}; } function defaults(schema) { var result = {}; var props = properties(schema); Object.keys(props).forEach(function (key) { var val = props[key]; if (_typeof(val) === 'object' && undefined !== val.default) { if (Array.isArray(val.default)) { result[key] = _toConsumableArray(val.default); } else if (_typeof(val.default) === 'object') { result[key] = _objectSpread2({}, val.default); } else { result[key] = val.default; } } }); return result; } function aliases(schema) { var result = {}; var props = properties(schema); Object.keys(props).forEach(function (key) { var val = props[key]; if (_typeof(val) === 'object') { var title = val.title; if (title) { result[title] = result[title] || []; result[title].push(key); } } }); return Object.values(result).filter(function (keys) { return keys.length > 1; }).map(function (keys) { return keys.sort().sort(function (a, b) { if (a.length === b.length) { return 0; } return a.length > b.length ? 1 : -1; }); }); } function aliasesMap(schema) { var result = new Map(); var _iterator = _createForOfIteratorHelper(aliases(schema)), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var row = _step.value; var _row$reverse = row.reverse(), _row$reverse2 = _toArray(_row$reverse), key = _row$reverse2[0], values = _row$reverse2.slice(1); var _iterator2 = _createForOfIteratorHelper(values), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var val = _step2.value; result.set(val, key); } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } return result; } var schema = /*#__PURE__*/Object.freeze({ __proto__: null, properties: properties, defaults: defaults, aliases: aliases, aliasesMap: aliasesMap }); function omit(obj, key) { obj[key]; var result = _objectWithoutProperties(obj, [key].map(_toPropertyKey)); return result; } var helper = /*#__PURE__*/Object.freeze({ __proto__: null, omit: omit }); function merge(style, options) { var optionSources = [{ seed: Math.random().toString(), /** @ts-ignore @deprecated - will be removed with version 5.0 */ userAgent: typeof window !== 'undefined' && window.navigator && window.navigator.userAgent }, defaults(schema$1), defaults(style.schema), options]; var result = createAliasProxy(style); optionSources.forEach(function (optionSource) { result = Object.assign(result, omit(optionSource, '_aliases')); }); return result; } function createAliasProxy(style) { var aliasMap = new Map([].concat(_toConsumableArray(Array.from(aliasesMap(schema$1))), _toConsumableArray(Array.from(aliasesMap(style.schema))))); return new Proxy({ _aliases: aliasMap }, { get: function get(obj, key) { var _obj$_aliases$get; var originalKey = (_obj$_aliases$get = obj._aliases.get(key)) !== null && _obj$_aliases$get !== void 0 ? _obj$_aliases$get : key; return obj[originalKey]; }, set: function set(obj, key, value) { var _obj$_aliases$get2; var originalKey = (_obj$_aliases$get2 = obj._aliases.get(key)) !== null && _obj$_aliases$get2 !== void 0 ? _obj$_aliases$get2 : key; obj[originalKey] = value; return true; }, deleteProperty: function deleteProperty(obj, key) { var _obj$_aliases$get3; var originalKey = (_obj$_aliases$get3 = obj._aliases.get(key)) !== null && _obj$_aliases$get3 !== void 0 ? _obj$_aliases$get3 : key; delete obj[originalKey]; return true; } }); } var options = /*#__PURE__*/Object.freeze({ __proto__: null, merge: merge, createAliasProxy: createAliasProxy }); var ccLicenses = { by: { permits: ['Reproduction', 'Distribution', 'DerivativeWorks'], requires: ['Notice', 'Attribution'], prohibits: [] }, 'by-sa': { permits: ['Reproduction', 'Distribution', 'DerivativeWorks'], requires: ['Notice', 'Attribution', 'ShareAlike'], prohibits: [] }, 'by-nd': { permits: ['Reproduction', 'Distribution'], requires: ['Notice', 'Attribution'], prohibits: [] }, 'by-nc': { permits: ['Reproduction', 'Distribution', 'DerivativeWorks'], requires: ['Notice', 'Attribution'], prohibits: ['CommercialUse'] }, 'by-nc-sa': { permits: ['Reproduction', 'Distribution', 'DerivativeWorks'], requires: ['Notice', 'Attribution', 'ShareAlike'], prohibits: ['CommercialUse'] }, 'by-nc-nd': { permits: ['Reproduction', 'Distribution'], requires: ['Notice', 'Attribution'], prohibits: ['CommercialUse'] }, zero: { permits: ['Reproduction', 'Distribution', 'DerivativeWorks'], requires: [], prohibits: [] } }; function createGroup(_ref) { var children = _ref.children, x = _ref.x, y = _ref.y; return "<g transform=\"translate(".concat(x, ", ").concat(y, ")\">").concat(children, "</g>"); } function getXmlnsAttributes() { return { 'xmlns:dc': 'http://purl.org/dc/elements/1.1/', 'xmlns:cc': 'http://creativecommons.org/ns#', 'xmlns:rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#', 'xmlns:svg': 'http://www.w3.org/2000/svg', xmlns: 'http://www.w3.org/2000/svg' }; } function getMetadata(style) { return "\n<metadata>\n<rdf:RDF>\n<cc:Work>\n<dc:format>image/svg+xml</dc:format>\n<dc:type rdf:resource=\"http://purl.org/dc/dcmitype/StillImage\" />\n".concat(getMetadataWorkTitle(style), "\n").concat(getMetadataWorkCreator(style), "\n").concat(getMetadataWorkSource(style), "\n").concat(getMetadataWorkLicense(style), "\n").concat(getMetadataWorkContributor(style), "\n</cc:Work>\n").concat(getMetadataLicense(style), "\n</rdf:RDF>\n</metadata>\n"); } function getMetadataWorkTitle(style) { if (style.meta.title) { return "<dc:title>".concat(style.meta.title, "</dc:title>"); } return ''; } function getMetadataWorkCreator(style) { if (style.meta.creator) { var creators = Array.isArray(style.meta.creator) ? style.meta.creator : [style.meta.creator]; return "\n<dc:creator>\n".concat(getMetadataWorkAgents(creators), "\n</dc:creator>\n"); } return ''; } function getMetadataWorkSource(style) { if (style.meta.source) { return "<dc:source>".concat(style.meta.source, "</dc:source>"); } return ''; } function getMetadataWorkLicense(style) { if (style.meta.license) { return "<cc:license rdf:resource=\"".concat(style.meta.license.url, "\" />"); } return ''; } function getMetadataWorkContributor(style) { if (style.meta.contributor) { var contributors = Array.isArray(style.meta.contributor) ? style.meta.contributor : [style.meta.contributor]; return "\n<dc:contributor>\n".concat(getMetadataWorkAgents(contributors), "\n</dc:contributor>\n"); } return ''; } function getMetadataWorkAgents(agents) { return agents.map(function (agent) { return "\n<cc:Agent>\n<dc:title>".concat(agent, "</dc:title>\n</cc:Agent>\n"); }); } function getMetadataLicense(style) { var _style$meta$license; var match = (_style$meta$license = style.meta.license) === null || _style$meta$license === void 0 ? void 0 : _style$meta$license.url.match(/^https?:\/\/creativecommons.org\/(?:licenses|publicdomain)\/([a-z\-]+)\/\d.\d\//); if (match) { var license = ccLicenses[match[1]]; if (license) { var _style$meta$license2; var result = ""; license.permits.forEach(function (permits) { result += "<cc:permits rdf:resource=\"https://creativecommons.org/ns#".concat(permits, "\" />"); }); license.requires.forEach(function (requires) { result += "<cc:requires rdf:resource=\"https://creativecommons.org/ns#".concat(requires, "\" />"); }); license.prohibits.forEach(function (prohibits) { result += "<cc:prohibits rdf:resource=\"https://creativecommons.org/ns#".concat(prohibits, "\" />"); }); return "\n<cc:License rdf:about=\"".concat((_style$meta$license2 = style.meta.license) === null || _style$meta$license2 === void 0 ? void 0 : _style$meta$license2.url, "\">\n").concat(result, "\n</cc:License>\n"); } } return ''; } function getViewBox(result) { var viewBox = result.attributes['viewBox'].split(' '); var x = parseInt(viewBox[0]); var y = parseInt(viewBox[1]); var width = parseInt(viewBox[2]); var height = parseInt(viewBox[3]); return { x: x, y: y, width: width, height: height }; } /** * @deprecated use addScale instead */ function addMargin(result, options) { var _options$margin; var margin = typeof options === 'number' ? options : (_options$margin = options.margin) !== null && _options$margin !== void 0 ? _options$margin : 0; return addScale(result, 100 - margin * 2); } /** * @deprecated use addViewboxMask instead */ function addRadius(result, options) { if (undefined === options.radius) { return result.body; } return addViewboxMask(result, options.radius); } function addBackgroundColor(result, options) { var _options$backgroundCo; var _getViewBox = getViewBox(result), width = _getViewBox.width, height = _getViewBox.height, x = _getViewBox.x, y = _getViewBox.y; var backgroundColor = typeof options === 'string' ? options : (_options$backgroundCo = options.backgroundColor) !== null && _options$backgroundCo !== void 0 ? _options$backgroundCo : 'transparent'; return "\n<rect fill=\"".concat(backgroundColor, "\" width=\"").concat(width, "\" height=\"").concat(height, "\" x=\"").concat(x, "\" y=\"").concat(y, "\" />\n").concat(result.body, "\n"); } function addScale(result, scale) { var _getViewBox2 = getViewBox(result), width = _getViewBox2.width, height = _getViewBox2.height, x = _getViewBox2.x, y = _getViewBox2.y; var percent = scale ? (scale - 100) / 100 : 0; var translateX = (width / 2 + x) * percent * -1; var translateY = (height / 2 + y) * percent * -1; return "\n<g transform=\"translate(".concat(translateX, " ").concat(translateY, ") scale(").concat(scale / 100, ")\">\n").concat(result.body, "\n</g>\n"); } function addTranslate(result, x, y) { var viewBox = getViewBox(result); var translateX = (viewBox.width + viewBox.x * 2) * ((x !== null && x !== void 0 ? x : 0) / 100); var translateY = (viewBox.height + viewBox.y * 2) * ((y !== null && y !== void 0 ? y : 0) / 100); return "\n<g transform=\"translate(".concat(translateX, " ").concat(translateY, ")\">\n").concat(result.body, "\n</g>\n"); } function addRotate(result, rotate) { var _getViewBox3 = getViewBox(result), width = _getViewBox3.width, height = _getViewBox3.height, x = _getViewBox3.x, y = _getViewBox3.y; return "\n<g transform=\"rotate(".concat(rotate, ", ").concat(width / 2 + x, ", ").concat(height / 2 + y, ")\">\n").concat(result.body, "\n</g>\n"); } function addFlip(result) { var _getViewBox4 = getViewBox(result), width = _getViewBox4.width, x = _getViewBox4.x; return "\n<g transform=\"scale(-1 1) translate(".concat(width * -1 - x * 2, " 0)\">\n").concat(result.body, "\n</g>\n"); } function addViewboxMask(result, radius) { var _getViewBox5 = getViewBox(result), width = _getViewBox5.width, height = _getViewBox5.height, x = _getViewBox5.x, y = _getViewBox5.y; var rx = radius ? width * radius / 100 : 0; var ry = radius ? height * radius / 100 : 0; return "\n<mask id=\"avatarsRadiusMask\">\n<rect width=\"".concat(width, "\" height=\"").concat(height, "\" rx=\"").concat(rx, "\" ry=\"").concat(ry, "\" x=\"").concat(x, "\" y=\"").concat(y, "\" fill=\"#fff\" />\n</mask>\n<g mask=\"url(#avatarsRadiusMask)\">").concat(result.body, "</g>\n"); } function createAttrString(attributes) { attributes = _objectSpread2(_objectSpread2({}, getXmlnsAttributes()), attributes); return Object.keys(attributes).map(function (attr) { return "".concat(xml(attr), "=\"").concat(xml(attributes[attr]), "\""); }).join(' '); } function removeWhitespace(svg) { return svg // Remove spaces at both ends of the string .trim() // Remove breaking lines .replace(/\n/g, ' ') // Remove space between tags .replace(/>\s+</g, '><') // Reduce whitespace .replace(/\s{2,}/g, ' ') // Create self closing tags .replace(/<([^\/>]+)><\/[^>]+>/gi, '<$1/>') // Remove whitespace before tag close .replace(/\s(\/?>)/g, '$1'); } var svg = /*#__PURE__*/Object.freeze({ __proto__: null, createGroup: createGroup, getXmlnsAttributes: getXmlnsAttributes, getMetadata: getMetadata, getMetadataWorkTitle: getMetadataWorkTitle, getMetadataWorkCreator: getMetadataWorkCreator, getMetadataWorkSource: getMetadataWorkSource, getMetadataWorkLicense: getMetadataWorkLicense, getMetadataWorkContributor: getMetadataWorkContributor, getMetadataWorkAgents: getMetadataWorkAgents, getMetadataLicense: getMetadataLicense, getViewBox: getViewBox, addMargin: addMargin, addRadius: addRadius, addBackgroundColor: addBackgroundColor, addScale: addScale, addTranslate: addTranslate, addRotate: addRotate, addFlip: addFlip, addViewboxMask: addViewboxMask, createAttrString: createAttrString, removeWhitespace: removeWhitespace }); function createLegacyWrapper(style) { return function (random, options) { var _result$head; // @ts-ignore options = Object.assign(options, merge(style, options)); var result = style.create({ prng: create(random.seed), options: options }); return "\n<svg ".concat(createAttrString(result.attributes), ">\n").concat(getMetadata(style), "\n").concat((_result$head = result.head) !== null && _result$head !== void 0 ? _result$head : '', "\n").concat(result.body, "\n</svg>\n"); }; } var style = /*#__PURE__*/Object.freeze({ __proto__: null, createLegacyWrapper: createLegacyWrapper }); var index = /*#__PURE__*/Object.freeze({ __proto__: null, escape: escape, options: options, prng: prng, svg: svg, style: style, schema: schema, helper: helper }); function createAvatar(style) { var _options$radius, _result$head, _result$head2; var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; options = merge(style, options); var prngInstance = create(options.seed); var result = style.create({ prng: prngInstance, options: options }); if (options.size) { result.attributes.width = options.size.toString(); result.attributes.height = options.size.toString(); } else { if (options.width) { result.attributes.width = options.width.toString(); } if (options.height) { result.attributes.height = options.height.toString(); } } if (options.scale !== undefined && options.scale !== 100) { result.body = addScale(result, options.scale); } else if (options.margin) { result.body = addMargin(result, options); } if (options.flip) { result.body = addFlip(result); } if (options.rotate) { result.body = addRotate(result, options.rotate); } if (options.translateX || options.translateY) { result.body = addTranslate(result, options.translateX, options.translateY); } if (options.backgroundColor) { var backgroundColor = Array.isArray(options.backgroundColor) ? prngInstance.pick(options.backgroundColor) : options.backgroundColor; result.body = addBackgroundColor(result, backgroundColor); } result.body = addViewboxMask(result, (_options$radius = options.radius) !== null && _options$radius !== void 0 ? _options$radius : 0); var hasMetadata = Boolean((_result$head = result.head) === null || _result$head === void 0 ? void 0 : _result$head.match(/<metadata([^>]*)>/)); var avatar = removeWhitespace("\n<svg ".concat(createAttrString(result.attributes), ">\n").concat(hasMetadata ? '' : getMetadata(style), "\n").concat((_result$head2 = result.head) !== null && _result$head2 !== void 0 ? _result$head2 : '', "\n").concat(result.body, "\n</svg>\n")); if (options.dataUri) { return "data:image/svg+xml;utf8,".concat(encodeURIComponent(avatar)); } /** @deprecated - will be removed with version 5.0 */ if (options.base64) { // @see https://www.base64encoder.io/javascript/ var encoded = encodeURIComponent(avatar).replace(/%([0-9A-F]{2})/g, function (match, p1) { return String.fromCharCode(parseInt("0x".concat(p1))); }); // @ts-ignore return "data:image/svg+xml;base64,".concat(btoa(encoded)); } return avatar; } /** * @deprecated use `createAvatar` function instead. */ var Avatars = /*#__PURE__*/function () { /** * @param spriteCollection */ function Avatars(spriteCollection, defaultOptions) { _classCallCheck(this, Avatars); _defineProperty(this, "spriteCollection", void 0); _defineProperty(this, "defaultOptions", void 0); this.spriteCollection = spriteCollection; this.defaultOptions = defaultOptions; } /** * Creates an avatar * * @param seed */ _createClass(Avatars, [{ key: "create", value: function create(seed, options) { var _this = this; var style = { meta: {}, schema: {}, create: function create(_ref) { var prng = _ref.prng, styleOptions = _ref.options; var svg = Parser.parse(_this.spriteCollection(new Random(prng.seed), styleOptions)); var head = []; var body = []; svg.children.forEach(function (child) { if (_this.isBody(child)) { body.push(child); } else { head.push(child); } }); return { attributes: svg.attributes, head: head.map(function (v) { return Parser.stringify(v); }).join(''), body: body.map(function (v) { return Parser.stringify(v); }).join('') }; } }; // @ts-ignore return createAvatar(style, _objectSpread2(_objectSpread2(_objectSpread2({}, this.defaultOptions), options), {}, { seed: seed })); } }, { key: "isBody", value: function isBody(element) { return element.type === 'element' && ['title', 'desc', 'defs', 'metadata'].indexOf(element.name) === -1; } }]); return Avatars; }(); _defineProperty(Avatars, "random", Random); _defineProperty(Avatars, "color", Color); _defineProperty(Avatars, "parser", Parser); export { index$1 as color, createAvatar, Avatars as default, schema$1 as schema, index as utils };