uikit/dist/remote/BiImage.js
Mohamadzadeh 96a434129a
All checks were successful
Build and Deploy Next.js + Nginx Docker Image / build-and-deploy (push) Successful in 1m1s
Build and Deploy Next.js + Nginx Docker Image / deploy (push) Successful in 7s
uikit-v1.3.0-vite-swr-biimage
2026-10-27 13:55:26 +03:30

234 lines
8.6 KiB
JavaScript

// Self-contained remote image element: no host CSS, Chakra, Next, fonts or other runtime dependencies.
// The existing uikit/utils processImage implementation is bundled into the downloadable remote file.
const processImage = (
url,
{ w, h, q = 70, webp = true, g = "sm" } = {},
) => {
if (!url) return "";
const resizePart = w || h ? `/rs:auto:${w || 0}:${h || 0}:0` : "";
return `https://img.d.aiengines.ir/preset:sharp${resizePart}/q:${q}/g:${g}/plain/${url}${webp ? "@webp" : ""}`;
};
const TAG_NAME = "uikit-bi-image";
const CDN_BASE = "https://cdn.d.aiengines.ir/";
const PLACEHOLDER_COLOR = "#E5E7EB";
function resolveSource(src) {
if (typeof src !== "string" || !src.trim()) return "";
const value = src.trim();
if (/^https?:\/\//i.test(value)) return value;
if (value.startsWith("//")) return `https:${value}`;
// Browser-local sources cannot be fetched by the remote image proxy.
if (/^(data:image\/|blob:)/i.test(value)) return value;
return `${CDN_BASE}${value.replace(/^\/+/, "")}`;
}
function cssSize(value) {
if (value === undefined || value === null || value === "") return undefined;
return typeof value === "number" ? `${value}px` : value;
}
function isConstrained(value) {
return value !== undefined && value !== null && value !== "" && value !== "auto";
}
function dimension(value) {
return Number.isFinite(value) && value > 0 ? Math.ceil(value) : 0;
}
function imageRequest(src, w, h) {
// Process only remotely fetchable URLs; keep data/blob sources local.
return /^(blob:|data:)/i.test(src)
? src
: processImage(src, { w, h, q: 100, webp: true });
}
class BiImageElement extends HTMLElement {
constructor() {
super();
this._props = {};
this._image = document.createElement("img");
// display:contents makes the actual <img> participate in its parent's layout,
// including flex/grid and intrinsic width:auto + height:<length> sizing.
this._image.addEventListener("load", (event) => this._onLoad(event));
this._image.addEventListener("error", (event) => this._onError(event));
this._image.addEventListener("click", (event) => this._props.onClick?.(event));
this._observer = null;
this._request = "";
this._primary = "";
this._fallback = "";
this._stage = "empty";
this._layoutHasImage = false;
}
connectedCallback() {
this.style.display = "contents";
if (!this.contains(this._image)) this.appendChild(this._image);
this._observe();
this._measure();
}
disconnectedCallback() {
this._observer?.disconnect();
this._observer = null;
if (this._resizeHandler) {
window.removeEventListener("resize", this._resizeHandler);
this._resizeHandler = null;
}
}
set componentProps(value) {
const props = value || {};
const nextPrimary = resolveSource(props.src);
// A fallback is intentionally app-local: `/placeholder.svg` means the app's asset,
// not a CDN image key. The placeholder is not passed through the optimizer.
const nextFallback = typeof props.fallbackSrc === "string" ? props.fallbackSrc.trim() : "";
const sourceChanged = nextPrimary !== this._primary || nextFallback !== this._fallback;
this._props = props;
this._primary = nextPrimary;
this._fallback = nextFallback;
this._applyPresentation();
if (sourceChanged) {
this._request = "";
this._stage = nextPrimary ? "primary" : nextFallback ? "fallback" : "empty";
this._layoutHasImage = false;
// When the input changes, discard the previous intrinsic ratio immediately.
this._image.removeAttribute("src");
}
if (this.isConnected) this._measure();
}
get componentProps() { return this._props; }
_applyPresentation() {
const p = this._props;
const image = this._image;
image.removeAttribute("style");
image.style.display = "block";
image.style.backgroundColor = PLACEHOLDER_COLOR;
image.style.width = cssSize(p.width ?? p.w) ?? "auto";
image.style.height = cssSize(p.height ?? p.h) ?? "auto";
if (p.objectFit != null) image.style.objectFit = p.objectFit;
if (p.objectPosition != null) image.style.objectPosition = p.objectPosition;
if (p.style && typeof p.style === "object") {
const unitless = new Set(["opacity", "flex", "flexGrow", "flexShrink", "order", "zIndex", "lineHeight", "fontWeight", "zoom", "aspectRatio", "gridRow", "gridColumn"]);
for (const [property, value] of Object.entries(p.style)) {
if (value === undefined || value === null) continue;
const cssValue = typeof value === "number" && value !== 0 && !unitless.has(property)
? `${value}px` : String(value);
if (property.startsWith("--")) image.style.setProperty(property, cssValue);
else image.style[property] = cssValue;
}
}
image.className = p.className || "";
image.alt = p.alt ?? "";
for (const name of ["title", "loading", "decoding", "crossOrigin", "referrerPolicy", "fetchPriority", "sizes", "draggable", "id"]) {
const attr = name === "crossOrigin" ? "crossorigin"
: name === "referrerPolicy" ? "referrerpolicy"
: name === "fetchPriority" ? "fetchpriority" : name;
if (p[name] === undefined || p[name] === null || p[name] === false) image.removeAttribute(attr);
else image.setAttribute(attr, String(p[name]));
}
for (const [name, value] of Object.entries(p)) {
if (!name.startsWith("aria-") && !name.startsWith("data-")) continue;
if (value === undefined || value === null) image.removeAttribute(name);
else image.setAttribute(name, String(value));
}
}
_observe() {
if (this._observer || this._resizeHandler) return;
if (typeof ResizeObserver !== "undefined") {
this._observer = new ResizeObserver(() => this._measure());
this._observer.observe(this._image);
} else {
this._resizeHandler = () => this._measure();
window.addEventListener("resize", this._resizeHandler);
}
}
_measure() {
if (!this.isConnected) return;
if (this._stage === "empty") return;
if (this._stage === "fallback") {
this._showFallback();
return;
}
if (this._stage === "failed") return;
const p = this._props;
const image = this._image;
const rect = image.getBoundingClientRect();
const explicitW = p.style?.width ?? p.width ?? p.w;
const explicitH = p.style?.height ?? p.height ?? p.h;
let useWidth = isConstrained(explicitW);
let useHeight = isConstrained(explicitH);
// Class-based CSS can impose a rendered width/height even without inline props.
// Before the image is loaded, the nonzero axis is a safe first-size hint.
if (!useWidth && !useHeight && !this._layoutHasImage && !this._request) {
if (rect.width > 0 && !rect.height) useWidth = true;
else if (rect.height > 0 && !rect.width) useHeight = true;
else if (rect.width > 0 && rect.height > 0) {
useWidth = true;
useHeight = true;
}
}
// A single constrained axis MUST leave the other at zero. This lets the proxy
// preserve aspect ratio (e.g. height:70px; width:auto) and avoids resize loops.
let w = useWidth ? dimension(rect.width) : 0;
let h = useHeight ? dimension(rect.height) : 0;
// If only max-width / max-height constrained the loaded image, discover that
// after first load and request the smaller rendered image without cropping.
if (!useWidth && !useHeight && this._layoutHasImage) {
if (image.naturalWidth > 0 && rect.width > 0 && rect.width < image.naturalWidth - 1) {
w = dimension(rect.width);
} else if (image.naturalHeight > 0 && rect.height > 0 && rect.height < image.naturalHeight - 1) {
h = dimension(rect.height);
}
}
const next = imageRequest(this._primary, w, h);
if (next !== this._request) {
this._request = next;
this._layoutHasImage = false;
image.src = next;
}
}
_showFallback() {
if (this._fallback) {
if (this._image.getAttribute("src") !== this._fallback) {
this._image.src = this._fallback;
}
} else {
this._image.removeAttribute("src");
}
}
_onLoad(event) {
if (this._stage === "primary") {
this._layoutHasImage = true;
this._measure();
}
this._props.onLoad?.(event);
}
_onError(event) {
if (this._stage === "primary") {
this._stage = this._fallback ? "fallback" : "failed";
this._showFallback();
} else if (this._stage === "fallback") {
this._stage = "failed";
this._image.removeAttribute("src");
}
this._props.onError?.(event);
}
}
if (!customElements.get(TAG_NAME)) {
customElements.define(TAG_NAME, BiImageElement);
}