feat(md-bg): Add solid color background support
This commit is contained in:
@@ -7,10 +7,17 @@ export interface BgProps {
|
||||
fit?: "cover" | "contain" | "fill" | "none" | "scale-down";
|
||||
}
|
||||
|
||||
function isImagePath(value: string): boolean {
|
||||
return (
|
||||
/^(\.{0,2}\/|[a-zA-Z]:\\|https?:\/\/)/i.test(value) ||
|
||||
/\.(png|jpg|jpeg|gif|svg|webp|bmp)(\?|$)/i.test(value)
|
||||
);
|
||||
}
|
||||
|
||||
customElement("md-bg", { fit: "cover" }, (props, { element }) => {
|
||||
noShadowDOM();
|
||||
|
||||
const rawSrc = element?.textContent?.trim() || "";
|
||||
const rawValue = element?.textContent?.trim() || "";
|
||||
|
||||
if (element) {
|
||||
element.textContent = "";
|
||||
@@ -20,17 +27,24 @@ customElement("md-bg", { fit: "cover" }, (props, { element }) => {
|
||||
const articlePath =
|
||||
element?.closest("article[data-src]")?.getAttribute("data-src") || "";
|
||||
|
||||
const resolvedSrc = resolvePath(articlePath, rawSrc);
|
||||
const isImage = isImagePath(rawValue);
|
||||
|
||||
const styles: Partial<CSSStyleDeclaration> = {} as any;
|
||||
|
||||
if (isImage) {
|
||||
const resolvedSrc = resolvePath(articlePath, rawValue);
|
||||
styles.backgroundImage = `url(${resolvedSrc})`;
|
||||
styles.backgroundSize = props.fit || "cover";
|
||||
styles.backgroundPosition = "center";
|
||||
styles.backgroundRepeat = "no-repeat";
|
||||
} else {
|
||||
styles.backgroundColor = rawValue || undefined;
|
||||
}
|
||||
|
||||
const handle = registerStyle({
|
||||
key: "backgroundImage",
|
||||
article: articleEl,
|
||||
styles: {
|
||||
backgroundImage: `url(${resolvedSrc})`,
|
||||
backgroundSize: props.fit || "cover",
|
||||
backgroundPosition: "center",
|
||||
backgroundRepeat: "no-repeat",
|
||||
} as any,
|
||||
styles,
|
||||
});
|
||||
|
||||
onCleanup(() => handle.dispose());
|
||||
|
||||
Reference in New Issue
Block a user