Files
svelte-formula11/src/lib/components/cards/Card.svelte

85 lines
2.4 KiB
Svelte

<script lang="ts">
import type { Snippet } from "svelte";
import { LazyImage } from "$lib/components";
import { error } from "@sveltejs/kit";
import type { HTMLAttributes } from "svelte/elements";
interface CardProps extends HTMLAttributes<HTMLDivElement> {
children: Snippet;
/** The URL for a possible header image. Leave undefined for no header image. Set to empty string for an image not yet loaded. */
imgsrc?: string;
/** The width of the image. Required if imgsrc is set */
imgwidth?: number;
/** The height of the image. Required if imgsrc is set */
imgheight?: number;
/** The id of the header image element for JS access. */
imgid?: string;
/** Hide the header image element. It can be shown by removing the "hidden" property using JS and the imgid. */
imghidden?: boolean;
/** If the header image is positioned at the left of the card */
imgleft?: boolean;
/** If the header image has a shadow */
imgshadow?: boolean;
/** Extra classes to pass to the card header image */
extraimgclass?: string;
/** Extra classes to pass to the card content div */
extraclass?: string;
/** The width class for the card, defaults to [w-auto] */
width?: string;
/** An optional event handler for clicking the image */
imgonclick?: (event: Event) => void;
}
let {
children,
imgsrc = undefined,
imgwidth = undefined,
imgheight = undefined,
imgid = undefined,
imghidden = false,
imgleft = false,
imgshadow = true,
extraimgclass = "",
extraclass = "",
width = "w-auto",
imgonclick = undefined,
...restProps
}: CardProps = $props();
if (imgsrc && (!imgwidth || !imgheight)) {
error(400, "imgwidth and imgheight need to be specified when setting an imgsrc!");
}
</script>
<div class="card {width} overflow-hidden bg-white shadow {imgleft ? 'flex' : ''}">
<!-- Allow empty strings for images that only appear after user action -->
{#if imgsrc !== undefined}
<LazyImage
id={imgid}
src={imgsrc}
alt="Card header"
draggable="false"
class="select-none {imgshadow ? 'shadow' : ''} {extraimgclass}"
hidden={imghidden}
imgwidth={imgwidth ?? 0}
imgheight={imgheight ?? 0}
onclick={imgonclick}
/>
{/if}
<div class="p-2 {extraclass}" {...restProps}>
{@render children()}
</div>
</div>