ngx-avatar
Version:
A universal avatar component for Angular applications that fetches / generates avatar based on the information you have about the user.
1,057 lines (1,029 loc) • 42.8 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core'), require('@angular/common'), require('ts-md5'), require('@angular/common/http'), require('rxjs/operators')) :
typeof define === 'function' && define.amd ? define('ngx-avatar', ['exports', '@angular/core', '@angular/common', 'ts-md5', '@angular/common/http', 'rxjs/operators'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global['ngx-avatar'] = {}, global.ng.core, global.ng.common, global.tsMd5, global.ng.common.http, global.rxjs.operators));
}(this, (function (exports, core, common, tsMd5, http, operators) { 'use strict';
/**
* Contract of all async sources.
* Every async source must implement the processResponse method that extracts the avatar url from the data
*/
var AsyncSource = /** @class */ (function () {
function AsyncSource(sourceId) {
this.sourceId = sourceId;
}
return AsyncSource;
}());
exports.AvatarSource = void 0;
(function (AvatarSource) {
AvatarSource["FACEBOOK"] = "facebook";
AvatarSource["GOOGLE"] = "google";
AvatarSource["TWITTER"] = "twitter";
AvatarSource["INSTAGRAM"] = "instagram";
AvatarSource["VKONTAKTE"] = "vkontakte";
AvatarSource["SKYPE"] = "skype";
AvatarSource["GRAVATAR"] = "gravatar";
AvatarSource["GITHUB"] = "github";
AvatarSource["CUSTOM"] = "custom";
AvatarSource["INITIALS"] = "initials";
AvatarSource["VALUE"] = "value";
})(exports.AvatarSource || (exports.AvatarSource = {}));
/**
* Facebook source implementation.
* Fetch avatar source based on facebook identifier
* and image size
*/
var Facebook = /** @class */ (function () {
function Facebook(sourceId) {
this.sourceId = sourceId;
this.sourceType = exports.AvatarSource.FACEBOOK;
}
Facebook.prototype.getAvatar = function (size) {
return ('https://graph.facebook.com/' +
(this.sourceId + "/picture?width=" + size + "&height=" + size));
};
return Facebook;
}());
/**
* Twitter source implementation.
* Fetch avatar source based on google identifier
* and image size
*/
var Twitter = /** @class */ (function () {
function Twitter(sourceId) {
this.sourceId = sourceId;
this.sourceType = exports.AvatarSource.TWITTER;
}
Twitter.prototype.getAvatar = function (size) {
var twitterImgSize = this.getImageSize(size);
return "https://twitter.com/" + this.sourceId + "/profile_image?size=" + twitterImgSize;
};
Twitter.prototype.getImageSize = function (size) {
if (size <= 24) {
return 'mini';
}
if (size <= 48) {
return 'normal';
}
if (size <= 73) {
return 'bigger';
}
return 'original';
};
return Twitter;
}());
/*! *****************************************************************************
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.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b)
if (Object.prototype.hasOwnProperty.call(b, p))
d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
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);
};
function __rest(s, e) {
var t = {};
for (var p in s)
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
}
function __decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
r = Reflect.decorate(decorators, target, key, desc);
else
for (var i = decorators.length - 1; i >= 0; i--)
if (d = decorators[i])
r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function __param(paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); };
}
function __metadata(metadataKey, metadataValue) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
return Reflect.metadata(metadataKey, metadataValue);
}
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try {
step(generator.next(value));
}
catch (e) {
reject(e);
} }
function rejected(value) { try {
step(generator["throw"](value));
}
catch (e) {
reject(e);
} }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function () { if (t[0] & 1)
throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f)
throw new TypeError("Generator is already executing.");
while (_)
try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done)
return t;
if (y = 0, t)
op = [op[0] & 2, t.value];
switch (op[0]) {
case 0:
case 1:
t = op;
break;
case 4:
_.label++;
return { value: op[1], done: false };
case 5:
_.label++;
y = op[1];
op = [0];
continue;
case 7:
op = _.ops.pop();
_.trys.pop();
continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
_ = 0;
continue;
}
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) {
_.label = op[1];
break;
}
if (op[0] === 6 && _.label < t[1]) {
_.label = t[1];
t = op;
break;
}
if (t && _.label < t[2]) {
_.label = t[2];
_.ops.push(op);
break;
}
if (t[2])
_.ops.pop();
_.trys.pop();
continue;
}
op = body.call(thisArg, _);
}
catch (e) {
op = [6, e];
y = 0;
}
finally {
f = t = 0;
}
if (op[0] & 5)
throw op[1];
return { value: op[0] ? op[1] : void 0, done: true };
}
}
var __createBinding = Object.create ? (function (o, m, k, k2) {
if (k2 === undefined)
k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function () { return m[k]; } });
}) : (function (o, m, k, k2) {
if (k2 === undefined)
k2 = k;
o[k2] = m[k];
});
function __exportStar(m, o) {
for (var p in m)
if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p))
__createBinding(o, m, p);
}
function __values(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m)
return m.call(o);
if (o && typeof o.length === "number")
return {
next: function () {
if (o && i >= o.length)
o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m)
return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done)
ar.push(r.value);
}
catch (error) {
e = { error: error };
}
finally {
try {
if (r && !r.done && (m = i["return"]))
m.call(i);
}
finally {
if (e)
throw e.error;
}
}
return ar;
}
/** @deprecated */
function __spread() {
for (var ar = [], i = 0; i < arguments.length; i++)
ar = ar.concat(__read(arguments[i]));
return ar;
}
/** @deprecated */
function __spreadArrays() {
for (var s = 0, i = 0, il = arguments.length; i < il; i++)
s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
}
function __spreadArray(to, from) {
for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
to[j] = from[i];
return to;
}
function __await(v) {
return this instanceof __await ? (this.v = v, this) : new __await(v);
}
function __asyncGenerator(thisArg, _arguments, generator) {
if (!Symbol.asyncIterator)
throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
function verb(n) { if (g[n])
i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
function resume(n, v) { try {
step(g[n](v));
}
catch (e) {
settle(q[0][3], e);
} }
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
function reject(value) { resume("throw", value); }
function settle(f, v) { if (f(v), q.shift(), q.length)
resume(q[0][0], q[0][1]); }
}
function __asyncDelegator(o) {
var i, p;
return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
}
function __asyncValues(o) {
if (!Symbol.asyncIterator)
throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function (v) { resolve({ value: v, done: d }); }, reject); }
}
function __makeTemplateObject(cooked, raw) {
if (Object.defineProperty) {
Object.defineProperty(cooked, "raw", { value: raw });
}
else {
cooked.raw = raw;
}
return cooked;
}
;
var __setModuleDefault = Object.create ? (function (o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function (o, v) {
o["default"] = v;
};
function __importStar(mod) {
if (mod && mod.__esModule)
return mod;
var result = {};
if (mod != null)
for (var k in mod)
if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k))
__createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
}
function __importDefault(mod) {
return (mod && mod.__esModule) ? mod : { default: mod };
}
function __classPrivateFieldGet(receiver, privateMap) {
if (!privateMap.has(receiver)) {
throw new TypeError("attempted to get private field on non-instance");
}
return privateMap.get(receiver);
}
function __classPrivateFieldSet(receiver, privateMap, value) {
if (!privateMap.has(receiver)) {
throw new TypeError("attempted to set private field on non-instance");
}
privateMap.set(receiver, value);
return value;
}
/**
* Google source implementation.
* Fetch avatar source based on google identifier
* and image size
*/
var Google = /** @class */ (function (_super) {
__extends(Google, _super);
function Google(sourceId) {
var _this = _super.call(this, sourceId) || this;
_this.sourceType = exports.AvatarSource.GOOGLE;
return _this;
}
Google.prototype.getAvatar = function () {
return "https://picasaweb.google.com/data/entry/api/user/" + this.sourceId + "?alt=json";
};
/**
* Extract google avatar from json data
*/
Google.prototype.processResponse = function (data, size) {
var avatarSrc = data.entry.gphoto$thumbnail.$t;
if (avatarSrc) {
return avatarSrc.replace('s64', 's' + size);
}
return null;
};
return Google;
}(AsyncSource));
/**
* Instagram source impelementation.
* Fetch avatar source based on instagram identifier
*/
var Instagram = /** @class */ (function (_super) {
__extends(Instagram, _super);
function Instagram(sourceId) {
var _this = _super.call(this, sourceId) || this;
_this.sourceType = exports.AvatarSource.INSTAGRAM;
return _this;
}
Instagram.prototype.getAvatar = function () {
return "https://www.instagram.com/" + this.sourceId + "/?__a=1";
};
/**
* extract instagram avatar from json data
*/
Instagram.prototype.processResponse = function (data, size) {
return data.graphql.user.profile_pic_url_hd + "&s=" + size;
};
return Instagram;
}(AsyncSource));
/**
* Custom source implementation.
* return custom image as an avatar
*
*/
var Custom = /** @class */ (function () {
function Custom(sourceId) {
this.sourceId = sourceId;
this.sourceType = exports.AvatarSource.CUSTOM;
}
Custom.prototype.getAvatar = function () {
return this.sourceId;
};
return Custom;
}());
/**
* Initials source implementation.
* return the initials of the given value
*/
var Initials = /** @class */ (function () {
function Initials(sourceId) {
this.sourceId = sourceId;
this.sourceType = exports.AvatarSource.INITIALS;
}
Initials.prototype.getAvatar = function (size) {
return this.getInitials(this.sourceId, size);
};
/**
* Returns the initial letters of a name in a string.
*/
Initials.prototype.getInitials = function (name, size) {
name = name.trim();
if (!name) {
return '';
}
var initials = name.split(' ');
if (size && size < initials.length) {
return this.constructInitials(initials.slice(0, size));
}
else {
return this.constructInitials(initials);
}
};
/**
* Iterates a person's name string to get the initials of each word in uppercase.
*/
Initials.prototype.constructInitials = function (elements) {
if (!elements || !elements.length) {
return '';
}
return elements
.filter(function (element) { return element && element.length > 0; })
.map(function (element) { return element[0].toUpperCase(); })
.join('');
};
return Initials;
}());
function isRetina() {
if (typeof window !== 'undefined' && window !== null) {
if (window.devicePixelRatio > 1.25) {
return true;
}
var mediaQuery = '(-webkit-min-device-pixel-ratio: 1.25), (min--moz-device-pixel-ratio: 1.25), (-o-min-device-pixel-ratio: 5/4), (min-resolution: 1.25dppx)';
if (window.matchMedia && window.matchMedia(mediaQuery).matches) {
return true;
}
}
return false;
}
/**
* Gravatar source implementation.
* Fetch avatar source based on gravatar email
*/
var Gravatar = /** @class */ (function () {
function Gravatar(value) {
this.value = value;
this.sourceType = exports.AvatarSource.GRAVATAR;
this.sourceId = value.match('^[a-f0-9]{32}$')
? value
: tsMd5.Md5.hashStr(value).toString();
}
Gravatar.prototype.getAvatar = function (size) {
var avatarSize = isRetina() ? size * 2 : size;
return "https://secure.gravatar.com/avatar/" + this.sourceId + "?s=" + avatarSize + "&d=404";
};
return Gravatar;
}());
/**
* Skype source implementation.
* Fetch avatar source based on skype identifier
*/
var Skype = /** @class */ (function () {
function Skype(sourceId) {
this.sourceId = sourceId;
this.sourceType = exports.AvatarSource.SKYPE;
}
Skype.prototype.getAvatar = function () {
return "https://api.skype.com/users/" + this.sourceId + "/profile/avatar";
};
return Skype;
}());
/**
* Value source implementation.
* return the value as avatar
*/
var Value = /** @class */ (function () {
function Value(sourceId) {
this.sourceId = sourceId;
this.sourceType = exports.AvatarSource.VALUE;
}
Value.prototype.getAvatar = function () {
return this.sourceId;
};
return Value;
}());
/**
* Vkontakte source implementation.
* Fetch avatar source based on vkontakte identifier
* and image size
*/
var apiVersion = 5.8;
var Vkontakte = /** @class */ (function (_super) {
__extends(Vkontakte, _super);
function Vkontakte(sourceId) {
var _this = _super.call(this, sourceId) || this;
_this.sourceType = exports.AvatarSource.VKONTAKTE;
return _this;
}
Vkontakte.prototype.getAvatar = function (size) {
var imgSize = this.getImageSize(size);
return "https://api.vk.com/method/users.get?user_id=" + this.sourceId + "&v=" + apiVersion + "&fields=" + imgSize;
};
/**
* extract vkontakte avatar from json data
*/
Vkontakte.prototype.processResponse = function (data) {
// avatar key property is the size used to generate avatar url
// size property is always the last key in the response object
var sizeProperty = Object.keys(data['response'][0]).pop();
if (!sizeProperty) {
return null;
}
// return avatar src
return data['response'][0][sizeProperty] || null;
};
/**
* Returns image size related to vkontakte API
*/
Vkontakte.prototype.getImageSize = function (size) {
if (size <= 50) {
return 'photo_50';
}
if (size <= 100) {
return 'photo_100';
}
if (size <= 200) {
return 'photo_200';
}
return 'photo_max';
};
return Vkontakte;
}(AsyncSource));
/**
* GitHub source implementation.
* Fetch avatar source based on github identifier
*/
var Github = /** @class */ (function (_super) {
__extends(Github, _super);
function Github(sourceId) {
var _this = _super.call(this, sourceId) || this;
_this.sourceType = exports.AvatarSource.GITHUB;
return _this;
}
Github.prototype.getAvatar = function () {
return "https://api.github.com/users/" + this.sourceId;
};
/**
* extract github avatar from json data
*/
Github.prototype.processResponse = function (data, size) {
if (size) {
return data.avatar_url + "&s=" + size;
}
return data.avatar_url;
};
return Github;
}(AsyncSource));
/**
* Factory class that implements factory method pattern.
* Used to create Source implementation class based
* on the source Type
*/
var SourceFactory = /** @class */ (function () {
function SourceFactory() {
this.sources = {};
this.sources[exports.AvatarSource.FACEBOOK] = Facebook;
this.sources[exports.AvatarSource.TWITTER] = Twitter;
this.sources[exports.AvatarSource.GOOGLE] = Google;
this.sources[exports.AvatarSource.INSTAGRAM] = Instagram;
this.sources[exports.AvatarSource.SKYPE] = Skype;
this.sources[exports.AvatarSource.GRAVATAR] = Gravatar;
this.sources[exports.AvatarSource.CUSTOM] = Custom;
this.sources[exports.AvatarSource.INITIALS] = Initials;
this.sources[exports.AvatarSource.VALUE] = Value;
this.sources[exports.AvatarSource.VKONTAKTE] = Vkontakte;
this.sources[exports.AvatarSource.GITHUB] = Github;
}
SourceFactory.prototype.newInstance = function (sourceType, sourceValue) {
return new this.sources[sourceType](sourceValue);
};
return SourceFactory;
}());
SourceFactory.decorators = [
{ type: core.Injectable }
];
SourceFactory.ctorParameters = function () { return []; };
/**
* Token used to inject the AvatarConfig object
*/
var AVATAR_CONFIG = new core.InjectionToken('avatar.config');
var AvatarConfigService = /** @class */ (function () {
function AvatarConfigService(userConfig) {
this.userConfig = userConfig;
}
AvatarConfigService.prototype.getAvatarSources = function (defaultSources) {
if (this.userConfig &&
this.userConfig.sourcePriorityOrder &&
this.userConfig.sourcePriorityOrder.length) {
var uniqueSources = __spread(new Set(this.userConfig.sourcePriorityOrder));
var validSources_1 = uniqueSources.filter(function (source) { return defaultSources.includes(source); });
return __spread(validSources_1, defaultSources.filter(function (source) { return !validSources_1.includes(source); }));
}
return defaultSources;
};
AvatarConfigService.prototype.getAvatarColors = function (defaultColors) {
return ((this.userConfig &&
this.userConfig.colors &&
this.userConfig.colors.length &&
this.userConfig.colors) ||
defaultColors);
};
return AvatarConfigService;
}());
AvatarConfigService.decorators = [
{ type: core.Injectable }
];
AvatarConfigService.ctorParameters = function () { return [
{ type: undefined, decorators: [{ type: core.Optional }, { type: core.Inject, args: [AVATAR_CONFIG,] }] }
]; };
/**
* list of Supported avatar sources
*/
var defaultSources = [
exports.AvatarSource.FACEBOOK,
exports.AvatarSource.GOOGLE,
exports.AvatarSource.TWITTER,
exports.AvatarSource.INSTAGRAM,
exports.AvatarSource.VKONTAKTE,
exports.AvatarSource.SKYPE,
exports.AvatarSource.GRAVATAR,
exports.AvatarSource.GITHUB,
exports.AvatarSource.CUSTOM,
exports.AvatarSource.INITIALS,
exports.AvatarSource.VALUE
];
/**
* list of default colors
*/
var defaultColors = [
'#1abc9c',
'#3498db',
'#f1c40f',
'#8e44ad',
'#e74c3c',
'#d35400',
'#2c3e50',
'#7f8c8d'
];
/**
* Provides utilities methods related to Avatar component
*/
var AvatarService = /** @class */ (function () {
function AvatarService(http, avatarConfigService) {
this.http = http;
this.avatarConfigService = avatarConfigService;
this.avatarSources = defaultSources;
this.avatarColors = defaultColors;
this.failedSources = new Map();
this.overrideAvatarSources();
this.overrideAvatarColors();
}
AvatarService.prototype.fetchAvatar = function (avatarUrl) {
return this.http.get(avatarUrl);
};
AvatarService.prototype.getRandomColor = function (avatarText) {
if (!avatarText) {
return 'transparent';
}
var asciiCodeSum = this.calculateAsciiCode(avatarText);
return this.avatarColors[asciiCodeSum % this.avatarColors.length];
};
AvatarService.prototype.compareSources = function (sourceType1, sourceType2) {
return (this.getSourcePriority(sourceType1) - this.getSourcePriority(sourceType2));
};
AvatarService.prototype.isSource = function (source) {
return this.avatarSources.includes(source);
};
AvatarService.prototype.isTextAvatar = function (sourceType) {
return [exports.AvatarSource.INITIALS, exports.AvatarSource.VALUE].includes(sourceType);
};
AvatarService.prototype.buildSourceKey = function (source) {
return source.sourceType + '-' + source.sourceId;
};
AvatarService.prototype.sourceHasFailedBefore = function (source) {
return this.failedSources.has(this.buildSourceKey(source));
};
AvatarService.prototype.markSourceAsFailed = function (source) {
this.failedSources.set(this.buildSourceKey(source), source);
};
AvatarService.prototype.overrideAvatarSources = function () {
this.avatarSources = this.avatarConfigService.getAvatarSources(defaultSources);
};
AvatarService.prototype.overrideAvatarColors = function () {
this.avatarColors = this.avatarConfigService.getAvatarColors(defaultColors);
};
AvatarService.prototype.calculateAsciiCode = function (value) {
return value
.split('')
.map(function (letter) { return letter.charCodeAt(0); })
.reduce(function (previous, current) { return previous + current; });
};
AvatarService.prototype.getSourcePriority = function (sourceType) {
return this.avatarSources.indexOf(sourceType);
};
return AvatarService;
}());
AvatarService.decorators = [
{ type: core.Injectable }
];
AvatarService.ctorParameters = function () { return [
{ type: http.HttpClient },
{ type: AvatarConfigService }
]; };
/**
* Universal avatar component that
* generates avatar from different sources
*
* export
* class AvatarComponent
* implements {OnChanges}
*/
var AvatarComponent = /** @class */ (function () {
function AvatarComponent(sourceFactory, avatarService) {
this.sourceFactory = sourceFactory;
this.avatarService = avatarService;
this.round = true;
this.size = 50;
this.textSizeRatio = 3;
this.fgColor = '#FFF';
this.style = {};
this.cornerRadius = 0;
this.initialsSize = 0;
this.clickOnAvatar = new core.EventEmitter();
this.isAlive = true;
this.avatarSrc = null;
this.avatarText = null;
this.avatarStyle = {};
this.hostStyle = {};
this.currentIndex = -1;
this.sources = [];
}
AvatarComponent.prototype.onAvatarClicked = function () {
this.clickOnAvatar.emit(this.sources[this.currentIndex]);
};
/**
* Detect inputs change
*
* param {{ [propKey: string]: SimpleChange }} changes
*
* memberof AvatarComponent
*/
AvatarComponent.prototype.ngOnChanges = function (changes) {
for (var propName in changes) {
if (this.avatarService.isSource(propName)) {
var sourceType = exports.AvatarSource[propName.toUpperCase()];
var currentValue = changes[propName].currentValue;
if (currentValue && typeof currentValue === 'string') {
this.addSource(sourceType, currentValue);
}
else {
this.removeSource(sourceType);
}
}
}
// reinitialize the avatar component when a source property value has changed
// the fallback system must be re-invoked with the new values.
this.initializeAvatar();
};
/**
* Fetch avatar source
*
* memberOf AvatarComponent
*/
AvatarComponent.prototype.fetchAvatarSource = function () {
var previousSource = this.sources[this.currentIndex];
if (previousSource) {
this.avatarService.markSourceAsFailed(previousSource);
}
var source = this.findNextSource();
if (!source) {
return;
}
if (this.avatarService.isTextAvatar(source.sourceType)) {
this.buildTextAvatar(source);
this.avatarSrc = null;
}
else {
this.buildImageAvatar(source);
}
};
AvatarComponent.prototype.findNextSource = function () {
while (++this.currentIndex < this.sources.length) {
var source = this.sources[this.currentIndex];
if (source && !this.avatarService.sourceHasFailedBefore(source)) {
return source;
}
}
return null;
};
AvatarComponent.prototype.ngOnDestroy = function () {
this.isAlive = false;
};
/**
* Initialize the avatar component and its fallback system
*/
AvatarComponent.prototype.initializeAvatar = function () {
this.currentIndex = -1;
if (this.sources.length > 0) {
this.sortAvatarSources();
this.fetchAvatarSource();
this.hostStyle = {
width: this.size + 'px',
height: this.size + 'px'
};
}
};
AvatarComponent.prototype.sortAvatarSources = function () {
var _this = this;
this.sources.sort(function (source1, source2) { return _this.avatarService.compareSources(source1.sourceType, source2.sourceType); });
};
AvatarComponent.prototype.buildTextAvatar = function (avatarSource) {
this.avatarText = avatarSource.getAvatar(+this.initialsSize);
this.avatarStyle = this.getInitialsStyle(avatarSource.sourceId);
};
AvatarComponent.prototype.buildImageAvatar = function (avatarSource) {
this.avatarStyle = this.getImageStyle();
if (avatarSource instanceof AsyncSource) {
this.fetchAndProcessAsyncAvatar(avatarSource);
}
else {
this.avatarSrc = avatarSource.getAvatar(+this.size);
}
};
/**
*
* returns initials style
*
* memberOf AvatarComponent
*/
AvatarComponent.prototype.getInitialsStyle = function (avatarValue) {
return Object.assign({ textAlign: 'center', borderRadius: this.round ? '100%' : this.cornerRadius + 'px', border: this.borderColor ? '1px solid ' + this.borderColor : '', textTransform: 'uppercase', color: this.fgColor, backgroundColor: this.bgColor
? this.bgColor
: this.avatarService.getRandomColor(avatarValue), font: Math.floor(+this.size / this.textSizeRatio) +
'px Helvetica, Arial, sans-serif', lineHeight: this.size + 'px' }, this.style);
};
/**
*
* returns image style
*
* memberOf AvatarComponent
*/
AvatarComponent.prototype.getImageStyle = function () {
return Object.assign({ maxWidth: '100%', borderRadius: this.round ? '50%' : this.cornerRadius + 'px', border: this.borderColor ? '1px solid ' + this.borderColor : '', width: this.size + 'px', height: this.size + 'px' }, this.style);
};
/**
* Fetch avatar image asynchronously.
*
* param {Source} source represents avatar source
* memberof AvatarComponent
*/
AvatarComponent.prototype.fetchAndProcessAsyncAvatar = function (source) {
var _this = this;
if (this.avatarService.sourceHasFailedBefore(source)) {
return;
}
this.avatarService
.fetchAvatar(source.getAvatar(+this.size))
.pipe(operators.takeWhile(function () { return _this.isAlive; }), operators.map(function (response) { return source.processResponse(response, +_this.size); }))
.subscribe(function (avatarSrc) { return (_this.avatarSrc = avatarSrc); }, function (err) {
_this.fetchAvatarSource();
});
};
/**
* Add avatar source
*
* param sourceType avatar source type e.g facebook,twitter, etc.
* param sourceValue source value e.g facebookId value, etc.
*/
AvatarComponent.prototype.addSource = function (sourceType, sourceValue) {
var source = this.sources.find(function (s) { return s.sourceType === sourceType; });
if (source) {
source.sourceId = sourceValue;
}
else {
this.sources.push(this.sourceFactory.newInstance(sourceType, sourceValue));
}
};
/**
* Remove avatar source
*
* param sourceType avatar source type e.g facebook,twitter, etc.
*/
AvatarComponent.prototype.removeSource = function (sourceType) {
this.sources = this.sources.filter(function (source) { return source.sourceType !== sourceType; });
};
return AvatarComponent;
}());
AvatarComponent.decorators = [
{ type: core.Component, args: [{
// tslint:disable-next-line:component-selector
selector: 'ngx-avatar',
template: "\n <div\n (click)=\"onAvatarClicked()\"\n class=\"avatar-container\"\n [ngStyle]=\"hostStyle\"\n >\n <img\n *ngIf=\"avatarSrc; else textAvatar\"\n [src]=\"avatarSrc\"\n [width]=\"size\"\n [height]=\"size\"\n [ngStyle]=\"avatarStyle\"\n (error)=\"fetchAvatarSource()\"\n class=\"avatar-content\"\n loading=\"lazy\"\n />\n <ng-template #textAvatar>\n <div *ngIf=\"avatarText\" class=\"avatar-content\" [ngStyle]=\"avatarStyle\">\n {{ avatarText }}\n </div>\n </ng-template>\n </div>\n ",
styles: ["\n :host {\n border-radius: 50%;\n }\n "]
},] }
];
AvatarComponent.ctorParameters = function () { return [
{ type: SourceFactory },
{ type: AvatarService }
]; };
AvatarComponent.propDecorators = {
round: [{ type: core.Input }],
size: [{ type: core.Input }],
textSizeRatio: [{ type: core.Input }],
bgColor: [{ type: core.Input }],
fgColor: [{ type: core.Input }],
borderColor: [{ type: core.Input }],
style: [{ type: core.Input }],
cornerRadius: [{ type: core.Input }],
facebook: [{ type: core.Input, args: ['facebookId',] }],
twitter: [{ type: core.Input, args: ['twitterId',] }],
google: [{ type: core.Input, args: ['googleId',] }],
instagram: [{ type: core.Input, args: ['instagramId',] }],
vkontakte: [{ type: core.Input, args: ['vkontakteId',] }],
skype: [{ type: core.Input, args: ['skypeId',] }],
gravatar: [{ type: core.Input, args: ['gravatarId',] }],
github: [{ type: core.Input, args: ['githubId',] }],
custom: [{ type: core.Input, args: ['src',] }],
initials: [{ type: core.Input, args: ['name',] }],
value: [{ type: core.Input }],
placeholder: [{ type: core.Input }],
initialsSize: [{ type: core.Input }],
clickOnAvatar: [{ type: core.Output }]
};
var AvatarModule = /** @class */ (function () {
function AvatarModule() {
}
AvatarModule.forRoot = function (avatarConfig) {
return {
ngModule: AvatarModule,
providers: [
{ provide: AVATAR_CONFIG, useValue: avatarConfig ? avatarConfig : {} }
]
};
};
return AvatarModule;
}());
AvatarModule.decorators = [
{ type: core.NgModule, args: [{
imports: [common.CommonModule],
declarations: [AvatarComponent],
providers: [SourceFactory, AvatarService, AvatarConfigService],
exports: [AvatarComponent]
},] }
];
/*
* Public API Surface of ngx-avatar
*/
/**
* Generated bundle index. Do not edit.
*/
exports.AvatarComponent = AvatarComponent;
exports.AvatarModule = AvatarModule;
exports.AvatarService = AvatarService;
exports.defaultColors = defaultColors;
exports.defaultSources = defaultSources;
exports.ɵa = SourceFactory;
exports.ɵb = AvatarConfigService;
exports.ɵc = AVATAR_CONFIG;
Object.defineProperty(exports, '__esModule', { value: true });
})));
//# sourceMappingURL=ngx-avatar.umd.js.map