416 lines
18 KiB
JavaScript
416 lines
18 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" : ""}`;
|
|
};
|
|
// Chakra-compatible presentation without requiring Chakra or its theme provider.
|
|
// Keep this module DOM-free so it can also be exercised by standalone Node tests.
|
|
const IMAGE_BREAKPOINTS = Object.freeze({
|
|
base: 0, sm: 30, md: 48, lg: 62, xl: 80, "2xl": 96,
|
|
});
|
|
const BREAKPOINT_NAMES = Object.keys(IMAGE_BREAKPOINTS);
|
|
const PSEUDOS = Object.freeze({
|
|
_hover: ":hover", _focus: ":focus", _focusVisible: ":focus-visible",
|
|
_active: ":active", _disabled: ":disabled", _checked: ":checked",
|
|
_focusWithin: ":focus-within", _first: ":first-child", _last: ":last-child",
|
|
_before: "::before", _after: "::after",
|
|
});
|
|
const ALIASES = Object.freeze({
|
|
w: "width", h: "height", minW: "minWidth", maxW: "maxWidth",
|
|
minH: "minHeight", maxH: "maxHeight", d: "display", pos: "position",
|
|
bg: "background", bgColor: "backgroundColor", bgImage: "backgroundImage",
|
|
rounded: "borderRadius", roundedTop: "borderTopRadius",
|
|
roundedBottom: "borderBottomRadius", shadow: "boxShadow",
|
|
fit: "objectFit", align: "objectPosition",
|
|
m: "margin", mt: "marginTop", mr: "marginRight", mb: "marginBottom", ml: "marginLeft",
|
|
mx: "marginInline", my: "marginBlock", marginX: "marginInline", marginY: "marginBlock",
|
|
p: "padding", pt: "paddingTop", pr: "paddingRight", pb: "paddingBottom", pl: "paddingLeft",
|
|
px: "paddingInline", py: "paddingBlock", paddingX: "paddingInline", paddingY: "paddingBlock",
|
|
insetX: "insetInline", insetY: "insetBlock",
|
|
flexDir: "flexDirection", flexWrap: "flexWrap", flexGrow: "flexGrow",
|
|
flexShrink: "flexShrink", alignSelf: "alignSelf", justifySelf: "justifySelf",
|
|
verticalAlign: "verticalAlign", textAlign: "textAlign", pointerEvents: "pointerEvents",
|
|
userSelect: "userSelect", boxSizing: "boxSizing",
|
|
borderX: "borderInline", borderY: "borderBlock",
|
|
});
|
|
const DIRECT_CSS = new Set(`width height minWidth maxWidth minHeight maxHeight display position top bottom left right
|
|
inset insetInline insetBlock insetInlineStart insetInlineEnd insetBlockStart insetBlockEnd
|
|
objectFit objectPosition aspectRatio opacity transform transformOrigin transition transitionProperty
|
|
transitionDuration transitionTimingFunction transitionDelay animation animationDuration
|
|
background backgroundColor backgroundImage backgroundSize backgroundPosition backgroundRepeat color
|
|
border borderWidth borderStyle borderColor borderRadius borderTopLeftRadius borderTopRightRadius
|
|
borderBottomLeftRadius borderBottomRightRadius borderTop borderRight borderBottom borderLeft
|
|
borderInline borderBlock outline outlineOffset outlineColor outlineWidth boxShadow boxSizing
|
|
margin marginTop marginRight marginBottom marginLeft marginInline marginBlock
|
|
padding paddingTop paddingRight paddingBottom paddingLeft paddingInline paddingBlock
|
|
cursor overflow overflowX overflowY overflowWrap visibility zIndex filter backdropFilter
|
|
mixBlendMode isolation float clear boxDecorationBreak
|
|
verticalAlign textAlign fontSize fontWeight fontFamily lineHeight letterSpacing whiteSpace
|
|
flex flexDirection flexWrap flexGrow flexShrink flexBasis order alignSelf justifySelf
|
|
alignItems justifyItems gridArea gridColumn gridRow gap rowGap columnGap
|
|
pointerEvents userSelect clipPath outlineStyle
|
|
`.trim().split(/\s+/));
|
|
const UNITLESS = new Set(`opacity flex flexGrow flexShrink order zIndex lineHeight fontWeight zoom
|
|
aspectRatio gridColumn gridRow animationIterationCount`.split(/\s+/));
|
|
const SPACE_PROPS = /^(?:margin|padding|gap|rowGap|columnGap|inset)/;
|
|
const RADIUS_TOKENS = {
|
|
none: "0px", sm: "0.125rem", base: "0.25rem", md: "0.375rem",
|
|
lg: "0.5rem", xl: "0.75rem", "2xl": "1rem", "3xl": "1.5rem", full: "9999px",
|
|
};
|
|
|
|
const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
const isResponsiveValue = (value) => Array.isArray(value) ||
|
|
(isObject(value) && Object.keys(value).some((key) => key in IMAGE_BREAKPOINTS));
|
|
|
|
function cssProperty(key) {
|
|
if (key.startsWith("--")) return key;
|
|
const name = ALIASES[key] ?? key;
|
|
return DIRECT_CSS.has(name) ? name : null;
|
|
}
|
|
function cssValue(key, value) {
|
|
if (value === null || value === undefined || value === false || isObject(value) || Array.isArray(value)) return null;
|
|
if (key === "borderRadius" && Object.hasOwn(RADIUS_TOKENS, String(value))) return RADIUS_TOKENS[value];
|
|
// Width and height have historically used numeric pixels in BiImage. Preserve that API.
|
|
if (typeof value === "number" && value !== 0 && !UNITLESS.has(key)) {
|
|
// Chakra spacing tokens are quarter-rems, whereas image dimensions are CSS pixels.
|
|
return SPACE_PROPS.test(key) ? `${value * 0.25}rem` : `${value}px`;
|
|
}
|
|
const text = String(value);
|
|
if (/^[a-z]+\.\d{1,3}$/i.test(text) && /(?:color|background|border)/i.test(key)) {
|
|
const token = text.replace(".", "-");
|
|
return `var(--chakra-colors-${token}, ${text})`;
|
|
}
|
|
return text;
|
|
}
|
|
|
|
/** Maps Chakra shorthand, responsive objects/arrays, and pseudo props to image CSS rules. */
|
|
function createImagePresentation(props = {}) {
|
|
const styles = { base: {} };
|
|
const pseudos = {};
|
|
const ensure = (bucket, key) => (bucket[key] ||= {});
|
|
function assign(property, rawValue, target = styles, pseudoKey = "") {
|
|
const key = cssProperty(property);
|
|
if (!key) return;
|
|
const bucket = target === styles ? styles : (pseudos[pseudoKey] ||= { base: {} });
|
|
if (isResponsiveValue(rawValue)) {
|
|
const values = Array.isArray(rawValue)
|
|
? rawValue.reduce((acc, item, idx) => { if (idx < BREAKPOINT_NAMES.length) acc[BREAKPOINT_NAMES[idx]] = item; return acc; }, {})
|
|
: rawValue;
|
|
for (const [breakpoint, item] of Object.entries(values)) {
|
|
if (!(breakpoint in IMAGE_BREAKPOINTS)) continue;
|
|
const formatted = cssValue(key, item);
|
|
if (formatted !== null) ensure(bucket, breakpoint)[key] = formatted;
|
|
}
|
|
} else {
|
|
const formatted = cssValue(key, rawValue);
|
|
if (formatted !== null) ensure(bucket, "base")[key] = formatted;
|
|
}
|
|
}
|
|
function read(source, target = styles, pseudoKey = "") {
|
|
if (!isObject(source)) return;
|
|
for (const [key, value] of Object.entries(source)) {
|
|
if (key === "boxSize") { assign("width", value, target, pseudoKey); assign("height", value, target, pseudoKey); }
|
|
else if (key in PSEUDOS && isObject(value)) read(value, pseudos, key);
|
|
else assign(key, value, target, pseudoKey);
|
|
}
|
|
}
|
|
// Defaults remain pixel-compatible with the original BiImage.
|
|
styles.base.display = "block";
|
|
styles.base.width = "auto";
|
|
styles.base.height = "auto";
|
|
if (props.boxSize !== undefined) read({ boxSize: props.boxSize });
|
|
// Explicit full-name Chakra props override aliases, as in the earlier BiImage API.
|
|
const { boxSize: _boxSize, ...otherProps } = props;
|
|
read(otherProps);
|
|
if (props.width !== undefined) assign("width", props.width);
|
|
if (props.height !== undefined) assign("height", props.height);
|
|
if (props.objectFit !== undefined) assign("objectFit", props.objectFit);
|
|
if (props.objectPosition !== undefined) assign("objectPosition", props.objectPosition);
|
|
// React's style prop overrides style-system props.
|
|
read(props.style);
|
|
read(props.sx);
|
|
return { styles, pseudos };
|
|
}
|
|
|
|
function kebabCase(value) {
|
|
return value.startsWith("--") ? value : value.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
|
|
}
|
|
function declarations(object, important = true) {
|
|
return Object.entries(object || {}).map(([property, value]) =>
|
|
`${kebabCase(property)}:${String(value).replace(/[{};]/g, "")} ${important ? "!important" : ""};`).join("");
|
|
}
|
|
|
|
/** Styles restricted to one custom element, without global Chakra CSS dependencies. */
|
|
function imagePresentationCSS(presentation, selector) {
|
|
const lines = [];
|
|
const rules = (styles, suffix = "") => {
|
|
if (!styles) return;
|
|
for (const [breakpoint, props] of Object.entries(styles)) {
|
|
if (!Object.keys(props || {}).length) continue;
|
|
if (breakpoint === "base") {
|
|
// Base image styles are set inline; pseudo base styles must override those.
|
|
if (suffix) lines.push(`${selector}${suffix}{${declarations(props)}}`);
|
|
} else if (breakpoint in IMAGE_BREAKPOINTS) {
|
|
lines.push(`@media (min-width:${IMAGE_BREAKPOINTS[breakpoint]}em){${selector}${suffix}{${declarations(props)}}}`);
|
|
}
|
|
}
|
|
};
|
|
rules(presentation.styles);
|
|
for (const [pseudoKey, styles] of Object.entries(presentation.pseudos)) {
|
|
rules(styles, PSEUDOS[pseudoKey]);
|
|
}
|
|
return lines.join("\n");
|
|
}
|
|
|
|
const TAG_NAME = "uikit-bi-image";
|
|
const CDN_BASE = "https://cdn.d.aiengines.ir/";
|
|
|
|
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(/^\/+/, "")}`;
|
|
}
|
|
|
|
let nextStyleId = 0;
|
|
|
|
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._styleId = `bi-${++nextStyleId}`;
|
|
this._styleElement = null;
|
|
this._image.setAttribute("data-bi-image", this._styleId);
|
|
for (const name of ["mouseEnter", "mouseLeave", "mouseMove", "mouseDown", "mouseUp", "focus", "blur", "doubleClick", "contextMenu", "keyDown", "keyUp"]) {
|
|
const domEvent = { mouseEnter: "mouseenter", mouseLeave: "mouseleave", doubleClick: "dblclick", contextMenu: "contextmenu", keyDown: "keydown", keyUp: "keyup" }[name] || name.toLowerCase();
|
|
this._image.addEventListener(domEvent, (event) => this._props[`on${name[0].toUpperCase()}${name.slice(1)}`]?.(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._applyPresentation();
|
|
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;
|
|
const presentation = createImagePresentation(p);
|
|
this._presentation = presentation;
|
|
image.removeAttribute("style");
|
|
for (const [name, value] of Object.entries(presentation.styles.base)) {
|
|
if (name.startsWith("--")) image.style.setProperty(name, value);
|
|
else image.style[name] = value;
|
|
}
|
|
// Responsive and pseudo styles are scoped to this image, not the host app.
|
|
// A normal <style> child works with display:contents and without ChakraProvider.
|
|
const selector = `uikit-bi-image > img[data-bi-image="${this._styleId}"]`;
|
|
const sheet = imagePresentationCSS(presentation, selector);
|
|
if (sheet) {
|
|
if (!this._styleElement) {
|
|
this._styleElement = document.createElement("style");
|
|
this._styleElement.setAttribute("data-bi-image-style", this._styleId);
|
|
}
|
|
if (this._styleElement.textContent !== sheet) this._styleElement.textContent = sheet;
|
|
if (this.isConnected && !this.contains(this._styleElement)) this.appendChild(this._styleElement);
|
|
} else if (this._styleElement) {
|
|
this._styleElement.remove();
|
|
this._styleElement = null;
|
|
}
|
|
image.className = p.className || "";
|
|
image.alt = p.alt ?? "";
|
|
for (const name of ["title", "loading", "decoding", "crossOrigin", "referrerPolicy", "fetchPriority", "sizes", "draggable", "id", "role", "tabIndex"]) {
|
|
const attr = name === "crossOrigin" ? "crossorigin"
|
|
: name === "referrerPolicy" ? "referrerpolicy"
|
|
: name === "fetchPriority" ? "fetchpriority" : name === "tabIndex" ? "tabindex" : 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();
|
|
// CSS media queries resolve Chakra responsive dimensions before measuring.
|
|
// offsetWidth/Height exclude hover transforms (scale), preventing needless refetches.
|
|
const actualWidth = image.offsetWidth || rect.width;
|
|
const actualHeight = image.offsetHeight || rect.height;
|
|
const configured = this._presentation?.styles || { base: {} };
|
|
// The computed width of an img with width:auto is a pixel length. It MUST NOT
|
|
// be treated as an explicit width, or height-only images become square.
|
|
const activeValue = (property) => {
|
|
let value = configured.base?.[property];
|
|
for (const [name, em] of Object.entries({ sm: 30, md: 48, lg: 62, xl: 80, "2xl": 96 })) {
|
|
if (configured[name]?.[property] !== undefined &&
|
|
(typeof window.matchMedia !== "function" || window.matchMedia(`(min-width:${em}em)`).matches)) {
|
|
value = configured[name][property];
|
|
}
|
|
}
|
|
return value;
|
|
};
|
|
let useWidth = isConstrained(activeValue("width"));
|
|
let useHeight = isConstrained(activeValue("height"));
|
|
|
|
// 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 (actualWidth > 0 && !actualHeight) useWidth = true;
|
|
else if (actualHeight > 0 && !actualWidth) useHeight = true;
|
|
else if (actualWidth > 0 && actualHeight > 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(actualWidth) : 0;
|
|
let h = useHeight ? dimension(actualHeight) : 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 && actualWidth > 0 && actualWidth < image.naturalWidth - 1) {
|
|
w = dimension(actualWidth);
|
|
} else if (image.naturalHeight > 0 && actualHeight > 0 && actualHeight < image.naturalHeight - 1) {
|
|
h = dimension(actualHeight);
|
|
}
|
|
}
|
|
|
|
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);
|
|
}
|