@sarawebs/sb-utils
Version:
SaraWebs utility functions for web apps and tools
231 lines (201 loc) • 5.41 kB
JavaScript
;
Object.defineProperty(exports, '__esModule', { value: true });
/**
* Generates a random ID with optional prefix.
* @param {string} [prefix=''] - Prefix to prepend to the ID.
* @returns {string} - A unique ID like 'myapp-XXXXXXX'.
*/
function generateID(prefix = "") {
return `${prefix ? prefix + "-" : ""}${crypto.randomUUID().slice(0, 8)}`;
}
/**
* Appends a copyright notice to the footer.
*
* @param {Object} [options={}] - Configuration options.
* @param {string} [options.title='This Website'] - The title to display before the © symbol.
* @param {string} [options.site='https://sarawebs.com'] - The URL to link the company name to.
* @param {string} [options.company='SaraWebs'] - The company or author's name to display.
* @param {number} [options.year=currentYear] - The year to display. Defaults to the current year.
*/
function addCopyRight({
title = "This Website",
site = "https://sarawebs.com",
company = "SaraWebs",
year = new Date().getFullYear(),
} = {}) {
const footer = document.querySelector("footer");
if (!footer) return;
const div = document.createElement("div");
const p = document.createElement("p");
p.style.textAlign = "center";
p.innerHTML = `
${title} © ${year}<br>
Built with ❤️ by
<a href="${site}" target="_blank" rel="noopener" style="color:#207de9;text-decoration:none;">${company}</a>
`;
div.appendChild(p);
footer.appendChild(div);
}
/**
* Generates a 2D board array and applies a push function.
* @param {number} rows - Number of rows.
* @param {number} cols - Number of columns.
* @param {Function} pushFunc - Callback to push into each cell.
* @returns {Array<Array>} - Generated 2D board.
*/
function createBoard(rows, cols, pushFunc) {
const board = [];
for (let i = 0; i < rows; i++) {
board[i] = [];
for (let j = 0; j < cols; j++) {
pushFunc(board[i], i, j);
}
}
return board;
}
/**
* Returns a random color, either from a provided palette or by generating a random hex color.
* @param {string[]} [palette] - Optional array of hex color strings.
* @returns {string} - A random color in hex format.
*/
function getRandomColor(palette) {
const defaultPalette = [
"#8e1330",
"#8a6c1d",
"#406555",
"#7c0e45",
"#8d1978",
"#181770",
"#cc38d7",
"#47504e",
"#0fa080",
"#0f64a0",
"#460fa0",
"#a00f65",
"#a00f24",
"#0f94a0",
"#0fa067",
"#0fa03c",
"#38a00f",
"#a09d0f",
"#a0670f",
"#a0370f",
"#a00f0f",
"#2b634d",
"#2b4c63",
"#2e6bc6",
"#1992d4",
];
const activePalette =
Array.isArray(palette) && palette.length > 0 ? palette : defaultPalette;
return activePalette[Math.floor(Math.random() * activePalette.length)];
}
// src/dom.js
class ElementBuilder {
constructor(type) {
this.el = document.createElement(type);
}
addClass(...classes) {
this.el.classList.add(...classes);
return this;
}
setId(id) {
this.el.id = id;
return this;
}
setText(text) {
this.el.textContent = text;
return this;
}
setAttr(name, value) {
this.el.setAttribute(name, value);
return this;
}
on(event, handler) {
this.el.addEventListener(event, handler);
return this;
}
append(child) {
this.el.appendChild(
child instanceof ElementBuilder ? child.build() : child,
);
return this;
}
build() {
return this.el;
}
}
function labelAndInput({
labelText,
inputType,
id,
name,
required = false,
}) {
const label = new ElementBuilder("label")
.setAttr("for", id)
.setText(labelText);
const input = new ElementBuilder("input")
.setAttr("type", inputType)
.setAttr("id", id)
.setAttr("name", name);
if (required) {
input.setAttr("required", "");
}
return [label, input];
}
class LinkPreviewFetcher {
constructor(apiKey, httpClient = (...args) => fetch(...args)) {
this.apiKey = apiKey;
this.httpClient = httpClient;
this.apiEndpoint = "https://api.linkpreview.net/";
}
buildUrl(targetUrl) {
const encodedUrl = encodeURIComponent(targetUrl);
return `${this.apiEndpoint}?key=${this.apiKey}&q=${encodedUrl}`;
}
async fetchPreview(targetUrl) {
const requestUrl = this.buildUrl(targetUrl);
try {
const response = await this.httpClient(requestUrl);
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
const data = await response.json();
return this.parseResponse(data);
} catch (err) {
console.error("LinkPreviewFetcher error:", err);
throw err;
}
}
parseResponse(data) {
return {
title: data.title || "",
description: data.description || "",
image: data.image || "",
url: data.url || "",
};
}
}
// src/index.js
const sb_utils = {
generateID,
addCopyRight,
createBoard,
getRandomColor,
ElementBuilder,
labelAndInput,
LinkPreviewFetcher,
};
if (typeof window !== "undefined") {
window.sb = sb_utils;
}
exports.ElementBuilder = ElementBuilder;
exports.LinkPreviewFetcher = LinkPreviewFetcher;
exports.addCopyRight = addCopyRight;
exports.createBoard = createBoard;
exports.default = sb_utils;
exports.generateID = generateID;
exports.getRandomColor = getRandomColor;
exports.labelAndInput = labelAndInput;
//# sourceMappingURL=index.cjs.map