feat(md-bg): Add solid color background support

This commit is contained in:
hyper
2026-06-30 18:24:38 +08:00
parent 936ccb7433
commit f337acd142
2 changed files with 34 additions and 9 deletions
+22 -8
View File
@@ -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());