fn-ui-avatars 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Fábio Nascimento
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,141 @@
1
+ [![npm version](https://img.shields.io/npm/v/fn-ui-avatars.svg)](https://www.npmjs.com/package/fn-ui-avatars)
2
+ [![npm bundle size](https://img.shields.io/bundlephobia/minzip/fn-ui-avatars)](https://bundlephobia.com/result?p=fn-ui-avatars)
3
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
4
+
5
+ Auto-generate consistent, colorful initials avatars using the [UI-Avatars](https://ui-avatars.com/) API.
6
+
7
+ Colors are **deterministic** — the same name always produces the same background color, across sessions and devices. It also features **Smart Contrast**, automatically switching the text color between black and white to ensure maximum legibility based on the generated background.
8
+
9
+ ---
10
+
11
+ ## Installation
12
+
13
+ ```bash
14
+ npm install fn-ui-avatars
15
+ ```
16
+
17
+ ---
18
+
19
+ ## Usage
20
+
21
+ ### In the browser (vanilla JS)
22
+
23
+ Add `data-name` to any `<img>` element and call `loadAvatars()` after the DOM is ready:
24
+
25
+ ```html
26
+ <img class="fn-ui-avatars" data-name="Maria Silva" alt="Avatar">
27
+ <img class="fn-ui-avatars" data-name="João Ferreira" alt="Avatar">
28
+
29
+ <script type="module">
30
+ import { loadAvatars } from 'fn-ui-avatars';
31
+
32
+ document.addEventListener('DOMContentLoaded', () => {
33
+ loadAvatars(); // targets 'img.fn-ui-avatars' by default
34
+ });
35
+ </script>
36
+ ```
37
+
38
+ ### Generate a single URL
39
+
40
+ ```js
41
+ import { getAvatarUrl } from 'fn-ui-avatars';
42
+
43
+ const url = getAvatarUrl('Maria Silva');
44
+ // → https://eu.ui-avatars.com/api/?size=192&...&name=Maria+Silva&...
45
+
46
+ document.querySelector('#my-avatar').src = url;
47
+ ```
48
+
49
+ ### With React (or any component framework)
50
+
51
+ ```jsx
52
+ import { getAvatarUrl } from 'fn-ui-avatars';
53
+
54
+ function Avatar({ name }) {
55
+ return <img src={getAvatarUrl(name)} alt={name} />;
56
+ }
57
+ ```
58
+
59
+ ### CommonJS (Node / older bundlers)
60
+
61
+ ```js
62
+ const { getAvatarUrl, loadAvatars } = require('fn-ui-avatars');
63
+ ```
64
+
65
+ ---
66
+
67
+ ## API
68
+
69
+ ### `getAvatarUrl(name, options?)`
70
+
71
+ Returns a UI-Avatars URL string for the given name.
72
+
73
+ | Parameter | Type | Description |
74
+ |---|---|---|
75
+ | `name` | `string` | Full name (e.g. `"Maria Silva"`). Required. |
76
+ | `options` | `object` | Optional configuration (see below). |
77
+
78
+ **Options:**
79
+
80
+ | Option | Type | Default | Description |
81
+ |---|---|---|---|
82
+ | `size` | `number` | `192` | Image size in pixels. |
83
+ | `fontSize` | `number` | `0.33` | Font size ratio (`0.1`–`1`). |
84
+ | `length` | `number` | `2` | Number of initials to display. |
85
+ | `rounded` | `boolean` | `true` | Circular avatar. |
86
+ | `color` | `string` | `'fff'` | Text color (hex without `#`). |
87
+ | `format` | `string` | `'svg'` | Image format: `'svg'` or `'png'`. |
88
+ | `baseUrl` | `string` | `'https://eu.ui-avatars.com/api/'` | Custom API base URL. |
89
+
90
+ ---
91
+
92
+ ### `loadAvatars(selector?, options?)`
93
+
94
+ Scans the DOM and injects `src` attributes into matching elements that have `data-name` set and no existing `src`.
95
+
96
+ | Parameter | Type | Default | Description |
97
+ |---|---|---|---|
98
+ | `selector` | `string` | `'img.fn-ui-avatars'` | CSS selector for target elements. |
99
+ | `options` | `object` | `{}` | Same options as `getAvatarUrl`. |
100
+
101
+ Returns the number of avatars injected.
102
+
103
+ > ⚠️ This function requires a browser environment (`document` must be defined).
104
+
105
+ ---
106
+
107
+ ### `hashCode(str)` / `intToRGB(i)`
108
+
109
+ Low-level utility functions, exported for advanced use cases (e.g. generating matching border colors, custom backgrounds).
110
+
111
+ ```js
112
+ import { hashCode, intToRGB } from 'fn-ui-avatars';
113
+
114
+ const hex = intToRGB(hashCode('Maria Silva')); // → e.g. "4A7BCC"
115
+ ```
116
+
117
+ ---
118
+
119
+ ## How colors work
120
+
121
+ Each name is hashed with a simple djb2-style algorithm, and the resulting integer is masked to produce a 6-digit hex color. This ensures:
122
+
123
+ - The same name **always** gets the same color.
124
+ - Different names get visually distinct colors.
125
+ - No configuration or storage required.
126
+
127
+ ---
128
+
129
+ ## Running tests
130
+
131
+ ```bash
132
+ npm test
133
+ ```
134
+
135
+ No external test runner needed — tests use only Node's built-in assert.
136
+
137
+ ---
138
+
139
+ ## License
140
+
141
+ MIT
package/dist/index.cjs ADDED
@@ -0,0 +1,99 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ getAvatarUrl: () => getAvatarUrl,
24
+ hashCode: () => hashCode,
25
+ intToRGB: () => intToRGB,
26
+ loadAvatars: () => loadAvatars
27
+ });
28
+ module.exports = __toCommonJS(index_exports);
29
+ var DEFAULT_OPTIONS = {
30
+ size: 192,
31
+ fontSize: 0.33,
32
+ length: 2,
33
+ rounded: true,
34
+ color: "fff",
35
+ format: "svg",
36
+ baseUrl: "https://eu.ui-avatars.com/api/"
37
+ };
38
+ function hashCode(str) {
39
+ let hash = 0;
40
+ for (let i = 0; i < str.length; i++) {
41
+ hash = str.charCodeAt(i) + ((hash << 5) - hash);
42
+ }
43
+ return hash;
44
+ }
45
+ function intToRGB(i) {
46
+ const c = (i & 16777215).toString(16).toUpperCase();
47
+ return "000000".substring(0, 6 - c.length) + c;
48
+ }
49
+ function isLightColor(hex) {
50
+ const r = parseInt(hex.substring(0, 2), 16);
51
+ const g = parseInt(hex.substring(2, 4), 16);
52
+ const b = parseInt(hex.substring(4, 6), 16);
53
+ const yiq = (r * 299 + g * 587 + b * 114) / 1e3;
54
+ return yiq >= 128;
55
+ }
56
+ function getAvatarUrl(name, options = {}) {
57
+ if (!name || typeof name !== "string") {
58
+ throw new Error('fn-ui-avatars: "name" must be a non-empty string.');
59
+ }
60
+ const opts = { ...DEFAULT_OPTIONS, ...options };
61
+ const encoded = name.trim().replace(/\s+/g, "+");
62
+ const background = intToRGB(hashCode(encoded));
63
+ const textColor = options.color ? opts.color : isLightColor(background) ? "000" : "fff";
64
+ const query = [
65
+ `size=${opts.size}`,
66
+ `font-size=${opts.fontSize}`,
67
+ `length=${opts.length}`,
68
+ `background=${background}`,
69
+ `color=${textColor}`,
70
+ `rounded=${opts.rounded}`,
71
+ `name=${encoded}`,
72
+ `format=${opts.format}`
73
+ ].join("&");
74
+ return `${opts.baseUrl}?${query}`;
75
+ }
76
+ function loadAvatars(selector = "img.fn-ui-avatar", options = {}) {
77
+ if (typeof document === "undefined") {
78
+ throw new Error("fn-ui-avatars: loadAvatars() requires a browser environment.");
79
+ }
80
+ const elements = document.querySelectorAll(selector);
81
+ let count = 0;
82
+ elements.forEach((el) => {
83
+ if (!el.getAttribute("src")) {
84
+ const name = el.dataset.name;
85
+ if (name) {
86
+ el.src = getAvatarUrl(name, options);
87
+ count++;
88
+ }
89
+ }
90
+ });
91
+ return count;
92
+ }
93
+ // Annotate the CommonJS export names for ESM import in node:
94
+ 0 && (module.exports = {
95
+ getAvatarUrl,
96
+ hashCode,
97
+ intToRGB,
98
+ loadAvatars
99
+ });
@@ -0,0 +1,33 @@
1
+ /**
2
+ * fn-ui-avatars
3
+ * Automatically generate consistent, colorful avatars using UI-Avatars API.
4
+ * Colors are deterministic — the same name always produces the same color.
5
+ */
6
+ interface AvatarOptions {
7
+ size?: number;
8
+ fontSize?: number;
9
+ length?: number;
10
+ rounded?: boolean;
11
+ color?: string;
12
+ format?: 'svg' | 'png';
13
+ baseUrl?: string;
14
+ }
15
+ /**
16
+ * Generates a numeric hash from a string.
17
+ */
18
+ declare function hashCode(str: string): number;
19
+ /**
20
+ * Converts an integer to a 6-character hex color string (without #).
21
+ */
22
+ declare function intToRGB(i: number): string;
23
+ /**
24
+ * Generates a UI-Avatars URL for a given name.
25
+ */
26
+ declare function getAvatarUrl(name: string, options?: AvatarOptions): string;
27
+ /**
28
+ * Scans the DOM for matching elements and injects avatar src attributes
29
+ * where no src is already set.
30
+ */
31
+ declare function loadAvatars(selector?: string, options?: AvatarOptions): number;
32
+
33
+ export { type AvatarOptions, getAvatarUrl, hashCode, intToRGB, loadAvatars };
@@ -0,0 +1,33 @@
1
+ /**
2
+ * fn-ui-avatars
3
+ * Automatically generate consistent, colorful avatars using UI-Avatars API.
4
+ * Colors are deterministic — the same name always produces the same color.
5
+ */
6
+ interface AvatarOptions {
7
+ size?: number;
8
+ fontSize?: number;
9
+ length?: number;
10
+ rounded?: boolean;
11
+ color?: string;
12
+ format?: 'svg' | 'png';
13
+ baseUrl?: string;
14
+ }
15
+ /**
16
+ * Generates a numeric hash from a string.
17
+ */
18
+ declare function hashCode(str: string): number;
19
+ /**
20
+ * Converts an integer to a 6-character hex color string (without #).
21
+ */
22
+ declare function intToRGB(i: number): string;
23
+ /**
24
+ * Generates a UI-Avatars URL for a given name.
25
+ */
26
+ declare function getAvatarUrl(name: string, options?: AvatarOptions): string;
27
+ /**
28
+ * Scans the DOM for matching elements and injects avatar src attributes
29
+ * where no src is already set.
30
+ */
31
+ declare function loadAvatars(selector?: string, options?: AvatarOptions): number;
32
+
33
+ export { type AvatarOptions, getAvatarUrl, hashCode, intToRGB, loadAvatars };
package/dist/index.js ADDED
@@ -0,0 +1,71 @@
1
+ // src/index.ts
2
+ var DEFAULT_OPTIONS = {
3
+ size: 192,
4
+ fontSize: 0.33,
5
+ length: 2,
6
+ rounded: true,
7
+ color: "fff",
8
+ format: "svg",
9
+ baseUrl: "https://eu.ui-avatars.com/api/"
10
+ };
11
+ function hashCode(str) {
12
+ let hash = 0;
13
+ for (let i = 0; i < str.length; i++) {
14
+ hash = str.charCodeAt(i) + ((hash << 5) - hash);
15
+ }
16
+ return hash;
17
+ }
18
+ function intToRGB(i) {
19
+ const c = (i & 16777215).toString(16).toUpperCase();
20
+ return "000000".substring(0, 6 - c.length) + c;
21
+ }
22
+ function isLightColor(hex) {
23
+ const r = parseInt(hex.substring(0, 2), 16);
24
+ const g = parseInt(hex.substring(2, 4), 16);
25
+ const b = parseInt(hex.substring(4, 6), 16);
26
+ const yiq = (r * 299 + g * 587 + b * 114) / 1e3;
27
+ return yiq >= 128;
28
+ }
29
+ function getAvatarUrl(name, options = {}) {
30
+ if (!name || typeof name !== "string") {
31
+ throw new Error('fn-ui-avatars: "name" must be a non-empty string.');
32
+ }
33
+ const opts = { ...DEFAULT_OPTIONS, ...options };
34
+ const encoded = name.trim().replace(/\s+/g, "+");
35
+ const background = intToRGB(hashCode(encoded));
36
+ const textColor = options.color ? opts.color : isLightColor(background) ? "000" : "fff";
37
+ const query = [
38
+ `size=${opts.size}`,
39
+ `font-size=${opts.fontSize}`,
40
+ `length=${opts.length}`,
41
+ `background=${background}`,
42
+ `color=${textColor}`,
43
+ `rounded=${opts.rounded}`,
44
+ `name=${encoded}`,
45
+ `format=${opts.format}`
46
+ ].join("&");
47
+ return `${opts.baseUrl}?${query}`;
48
+ }
49
+ function loadAvatars(selector = "img.fn-ui-avatar", options = {}) {
50
+ if (typeof document === "undefined") {
51
+ throw new Error("fn-ui-avatars: loadAvatars() requires a browser environment.");
52
+ }
53
+ const elements = document.querySelectorAll(selector);
54
+ let count = 0;
55
+ elements.forEach((el) => {
56
+ if (!el.getAttribute("src")) {
57
+ const name = el.dataset.name;
58
+ if (name) {
59
+ el.src = getAvatarUrl(name, options);
60
+ count++;
61
+ }
62
+ }
63
+ });
64
+ return count;
65
+ }
66
+ export {
67
+ getAvatarUrl,
68
+ hashCode,
69
+ intToRGB,
70
+ loadAvatars
71
+ };
package/package.json ADDED
@@ -0,0 +1,52 @@
1
+ {
2
+ "name": "fn-ui-avatars",
3
+ "version": "1.0.0",
4
+ "description": "Automatically generate consistent, colorful avatars using UI-Avatars API",
5
+ "main": "./dist/index.js",
6
+ "module": "./dist/index.mjs",
7
+ "types": "./dist/index.d.ts",
8
+ "type": "module",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.mjs",
13
+ "require": "./dist/index.js"
14
+ }
15
+ },
16
+ "files": [
17
+ "dist/",
18
+ "README.md",
19
+ "LICENSE"
20
+ ],
21
+ "scripts": {
22
+ "build": "tsup src/index.ts --format cjs,esm --dts",
23
+ "pretest": "npm run build",
24
+ "test": "node test/index.test.js",
25
+ "prepublishOnly": "npm run build && npm test"
26
+ },
27
+ "keywords": [
28
+ "avatar",
29
+ "initials",
30
+ "ui-avatars",
31
+ "gravatar",
32
+ "placeholder",
33
+ "user-avatar"
34
+ ],
35
+ "author": "Fábio Nascimento <f_nascimento9@hotmail.com>",
36
+ "license": "MIT",
37
+ "repository": {
38
+ "type": "git",
39
+ "url": "git+https://github.com/fnasciment0/fn-ui-avatars.git"
40
+ },
41
+ "bugs": {
42
+ "url": "https://github.com/fnasciment0/fn-ui-avatars/issues"
43
+ },
44
+ "homepage": "https://github.com/fnasciment0/fn-ui-avatars#readme",
45
+ "engines": {
46
+ "node": ">=14"
47
+ },
48
+ "devDependencies": {
49
+ "tsup": "^8.5.1",
50
+ "typescript": "^6.0.3"
51
+ }
52
+ }