Skip to content

FilePreview

@experimental

Generic file preview shell with safe fallback behavior.


Quick Start

from faststrap import FilePreview

FilePreview("/files/report.pdf", title="Annual Report")
FilePreview("/files/photo.jpg", title="Team Photo")
FilePreview("/files/notes.md", title="Meeting Notes")

Features

  • Automatic file type inference from extension
  • Image preview via <img>
  • PDF preview via <iframe>
  • Text/code preview with safe fallback message
  • Custom fallback for unsupported types

Parameters

Parameter Type Default Description
src str required File URL or path.
kind str \| None None Explicit file kind: "image", "pdf", "text", "code", "unknown".
title str \| None None Optional title shown above the preview.
height str \| int \| None None Preview height (px or CSS string).
width str \| int \| None None Preview width (px or CSS string).
fallback str \| None None Custom fallback message for unsupported types.
**kwargs Any Extra wrapper attributes.

Usage Examples

Image Preview

FilePreview("/assets/diagram.png", title="Circuit Diagram")

PDF Document

FilePreview("/docs/manual.pdf", title="User Manual", height="600px")

Code File

FilePreview("/src/main.py", title="Main Script")

Custom Fallback

FilePreview(
    "/files/data.bin",
    title="Binary Data",
    fallback="Binary preview not supported. Download to view.",
)

Supported File Types

Extension(s) Inferred Kind
.png, .jpg, .jpeg, .gif, .svg, .webp image
.pdf pdf
.txt, .md, .csv, .json, .xml, .html text
.py, .js, .ts, .java, .c, .cpp, .rs, .go code
Other unknown

Notes

  • For production use, consider server-side content-type validation.
  • Marked @experimental.

API Reference

faststrap.components.display.file_preview.FilePreview(src, *, kind=None, title=None, height=None, width=None, fallback=None, **kwargs)

Generic file preview shell with safe fallback behavior.

Supports images, PDFs, and text/code files out of the box. For unsupported types, renders a safe fallback message.

Parameters:

Name Type Description Default
src str

File URL or path.

required
kind str | None

Explicit file kind: "image", "pdf", "text", "code", or "unknown". When None, inferred from the file extension.

None
title str | None

Optional title shown above the preview.

None
height str | int | None

Optional preview height (px or CSS string).

None
width str | int | None

Optional preview width (px or CSS string).

None
fallback str | None

Optional fallback message for unsupported file types.

None
**kwargs Any

Additional HTML attributes for the wrapper.

{}

Returns:

Type Description
Div

FastHTML Div element containing the file preview.

Source code in src/faststrap/components/display/file_preview.py
@register(category="display")
@experimental
def FilePreview(
    src: str,
    *,
    kind: str | None = None,
    title: str | None = None,
    height: str | int | None = None,
    width: str | int | None = None,
    fallback: str | None = None,
    **kwargs: Any,
) -> Div:
    """Generic file preview shell with safe fallback behavior.

    Supports images, PDFs, and text/code files out of the box.
    For unsupported types, renders a safe fallback message.

    Args:
        src: File URL or path.
        kind: Explicit file kind: ``"image"``, ``"pdf"``, ``"text"``,
            ``"code"``, or ``"unknown"``. When ``None``, inferred from
            the file extension.
        title: Optional title shown above the preview.
        height: Optional preview height (px or CSS string).
        width: Optional preview width (px or CSS string).
        fallback: Optional fallback message for unsupported file types.
        **kwargs: Additional HTML attributes for the wrapper.

    Returns:
        FastHTML ``Div`` element containing the file preview.
    """
    user_cls = kwargs.pop("cls", "")
    resolved_kind = kind or _infer_kind(src)

    size_style = _normalize_size(height, width)

    preview_children: list[Any] = []
    if resolved_kind == "image":
        preview_children.append(
            Img(
                src=src,
                cls="faststrap-file-preview-image",
                alt=title or "File preview",
                style=size_style or "",
            )
        )
    elif resolved_kind == "pdf":
        preview_children.append(
            Iframe(
                src=src,
                cls="faststrap-file-preview-pdf",
                style=f"height: {height or '500px'}; width: 100%; border: none;",
            )
        )
    elif resolved_kind in {"text", "code"}:
        preview_children.append(
            Pre(
                Span(f"// Preview not available for {resolved_kind} files.", cls="text-muted"),
                cls="faststrap-file-preview-text",
            )
        )
    else:
        msg = fallback or f"Preview not available for this file type ({resolved_kind})."
        preview_children.append(P(msg, cls="faststrap-file-preview-fallback text-muted mb-0"))

    header_children: list[Any] = []
    if title:
        header_children.append(Span(title, cls="fw-semibold"))

    children: list[Any] = []
    if header_children:
        children.append(Div(*header_children, cls="faststrap-file-preview-header mb-2"))
    children.append(Div(*preview_children, cls="faststrap-file-preview-body"))

    attrs: dict[str, Any] = {
        "cls": merge_classes("card faststrap-file-preview", user_cls),
        "data_fs_file_kind": resolved_kind,
    }
    attrs.update(convert_attrs(kwargs))
    return Div(*children, **attrs)