// 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 participate in its parent's layout, // including flex/grid and intrinsic width:auto + height: 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