Skip to content

Gallery Configuration API Reference

All gallery configuration classes live in dj_design_system.gallery. Use GalleryConfig and Variant to configure component metadata, navigation hierarchy, canvas rendering, and variations.

Gallery configuration and variant definitions for components.

DocVariantConfig(key, name, label, strategy=DocVariantStrategy.MINIMAL, show_in_docs=True, kwargs=dict(), param_factory=None, slot_factory=None) dataclass

Normalized configuration for a standard documentation variant.

Attributes:

Name Type Description
key str

Identifier key in GALLERY_DOC_VARIANTS (e.g. "minimal", "maximal").

name str

Variant slug matched against GalleryConfig.variants (e.g. "basic", "maximal").

label str

Heading label displayed in the Usage documentation section.

strategy DocVariantStrategy

Built-in generation strategy used when the variant is not overridden in gallery.py.

show_in_docs bool

Whether this variant is included in component documentation by default.

kwargs dict[str, Any]

Optional static parameter overrides for custom global variants.

param_factory Callable[..., Any] | None

Reserved hook for custom parameter value factory callables.

slot_factory Callable[..., Any] | None

Reserved hook for custom slot content factory callables.

GalleryConfig(hidden=False, icon=None, theme=None, group=None, order=0, canvas_template=None, extra_context=dict(), param_defaults=dict(), doc_variants=None, variants=list()) dataclass

Explicit configuration for a component within the design system gallery.

Attributes:

Name Type Description
hidden bool

If True, hides the component and its variants from gallery navigation and search.

icon str | None

Custom icon name (e.g. "mdi:button") for the component in sidebar navigation.

theme str | None

Theme override for the component preview.

group str | None

Grouping category for sidebar navigation.

order int

Ordering priority integer for sidebar navigation. Lower numbers appear first.

canvas_template str | None

HTML template string for wrapping previews. Operates in Smart Hybrid mode: if {{ component }} is present, wraps the rendered component; otherwise renders as raw template syntax.

extra_context dict[str, Any]

Context variables passed to preview templates.

param_defaults dict[str, Any]

Mapping of param names to default values or callables.

doc_variants Mapping[str, Any] | Sequence[Any] | None

Optional component-level documentation variant overrides (mapping or sequence) layered on top of the global GALLERY_DOC_VARIANTS setting.

variants list[Variant]

List of named Variant instances. To construct from dictionary mappings, use GalleryConfig.from_dict(...).

from_dict(data) classmethod

Create a GalleryConfig from a dictionary or mapping.

Converts nested variant dictionaries or mappings into Variant instances.

Source code in dj_design_system/gallery.py
200
201
202
203
204
205
206
207
208
209
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> GalleryConfig:
    """Create a GalleryConfig from a dictionary or mapping.

    Converts nested variant dictionaries or mappings into Variant instances.
    """
    payload = dict(data)
    if "variants" in payload:
        payload["variants"] = cls._normalize_variants(payload["variants"])
    return cls(**payload)

get_doc_variants()

Return resolved documentation variant configurations for this component.

Source code in dj_design_system/gallery.py
242
243
244
245
246
247
248
249
250
251
252
def get_doc_variants(self) -> list[DocVariantConfig]:
    """Return resolved documentation variant configurations for this component."""
    from dj_design_system.settings import get_doc_variants, resolve_doc_variants

    global_variants = get_doc_variants()
    if self.doc_variants is None:
        return global_variants
    return resolve_doc_variants(
        raw_setting=self.doc_variants,
        base_variants=global_variants,
    )

get_variant(name)

Return the variant matching name, or None.

Source code in dj_design_system/gallery.py
254
255
256
257
258
259
def get_variant(self, name: str) -> Variant | None:
    """Return the variant matching *name*, or None."""
    for v in self.variants:
        if v.name == name:
            return v
    return None

Variant(name, label=None, description=None, kwargs=dict(), positional_args=tuple(), canvas_template=None, extra_context=dict(), icon=None, theme=None, show_in_nav=None, show_in_docs=None) dataclass

A named component variation with preset arguments and preview configurations.

Attributes:

Name Type Description
name str

Unique identifier slug for this variant (e.g. "basic", "danger").

label str | None

Human-readable display label in documentation and sidebar navigation. Defaults to title-cased name.

description str | None

Optional markdown text describing when/how to use this variant.

kwargs dict[str, Any]

Component keyword parameters passed to instantiation. Supports raw values, GalleryParameter instances, or dynamic callables.

positional_args tuple[Any, ...]

Positional argument values passed to the component tag.

canvas_template str | None

Optional variant-level HTML layout override for previewing this variant.

extra_context dict[str, Any]

Additional template context variables available during preview rendering.

icon str | None

Optional icon name or SVG path for sidebar navigation.

theme str | None

Optional theme override when previewing this variant.

show_in_nav bool | None

Whether to display this variant as a child node in the gallery sidebar navigation. When left as None, defaults to False for standard global documentation variants (e.g. "basic", "maximal", "defaults", "all_slots") so they do not clutter the sidebar tree, and True for custom named variants. Explicitly set to True or False to override this default.

show_in_docs bool | None

Whether to render this variant as an example in the component documentation pane. When left as None, defaults to True for enabled documentation variants (e.g. "basic", "maximal") and False for other variants.

from_dict(data, name=None) classmethod

Create a Variant from a dictionary or mapping.

Source code in dj_design_system/gallery.py
121
122
123
124
125
126
127
@classmethod
def from_dict(cls, data: Mapping[str, Any], name: str | None = None) -> Variant:
    """Create a Variant from a dictionary or mapping."""
    payload = dict(data)
    if name is not None and "name" not in payload:
        payload["name"] = name
    return cls(**payload)

is_shown_in_docs(*, doc_variants=None)

Return whether this variant should be rendered in component documentation.

Source code in dj_design_system/gallery.py
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
def is_shown_in_docs(
    self,
    *,
    doc_variants: Sequence[DocVariantConfig] | None = None,
) -> bool:
    """Return whether this variant should be rendered in component documentation."""
    if self._explicit_show_in_docs is not None:
        return self._explicit_show_in_docs
    from dj_design_system.settings import get_doc_variants

    resolved_doc_variants = (
        doc_variants if doc_variants is not None else get_doc_variants()
    )
    enabled_doc_names = {dv.name for dv in resolved_doc_variants if dv.show_in_docs}
    return self.name in enabled_doc_names

is_shown_in_nav(*, doc_variants=None)

Return whether this variant should be rendered in sidebar navigation.

Source code in dj_design_system/gallery.py
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
def is_shown_in_nav(
    self,
    *,
    doc_variants: Sequence[DocVariantConfig] | None = None,
) -> bool:
    """Return whether this variant should be rendered in sidebar navigation."""
    if self._explicit_show_in_nav is not None:
        return self._explicit_show_in_nav
    from dj_design_system.settings import get_doc_variants
    from dj_design_system.types import DocVariantStrategy

    resolved_doc_variants = (
        doc_variants if doc_variants is not None else get_doc_variants()
    )
    standard_doc_names = {
        dv.name
        for dv in resolved_doc_variants
        if dv.strategy != DocVariantStrategy.CUSTOM
    } | {dv.name for dv in get_doc_variants()}
    return self.name not in standard_doc_names

Discover, import, and return the GalleryConfig for a component.

Checks for {name}_gallery.py, {name}.gallery.py, or gallery.py within source_dir. If found, imports the module safely and extracts the config (or {name}_config) object. If legacy basic_kwargs or maximal_kwargs are present without a config, emits a DeprecationWarning and synthesizes a fallback config.

Source code in dj_design_system/gallery.py
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
def load_gallery_config(source_dir: Path, component_name: str) -> GalleryConfig:
    """Discover, import, and return the GalleryConfig for a component.

    Checks for ``{name}_gallery.py``, ``{name}.gallery.py``, or ``gallery.py``
    within *source_dir*. If found, imports the module safely and extracts
    the ``config`` (or ``{name}_config``) object. If legacy ``basic_kwargs``
    or ``maximal_kwargs`` are present without a config, emits a
    ``DeprecationWarning`` and synthesizes a fallback config.
    """
    candidates = [
        source_dir / f"{component_name}_gallery.py",
        source_dir / f"{component_name}.gallery.py",
        source_dir / "gallery.py",
    ]

    gallery_path = None
    for p in candidates:
        if p.is_file():
            gallery_path = p
            break

    if not gallery_path:
        return GalleryConfig()

    resolved_path = gallery_path.resolve()
    path_hash = hashlib.sha256(str(resolved_path).encode("utf-8")).hexdigest()[:16]
    mod_name = f"dj_design_system_gallery_{component_name}_{path_hash}"
    spec = importlib.util.spec_from_file_location(mod_name, resolved_path)
    if not (spec and spec.loader):
        return GalleryConfig()

    mod = importlib.util.module_from_spec(spec)
    sys.modules[mod_name] = mod
    source = resolved_path.read_text(encoding="utf-8")
    exec(compile(source, str(resolved_path), "exec"), mod.__dict__)

    cfg = getattr(mod, "config", None)
    if isinstance(cfg, GalleryConfig):
        return cfg
    if isinstance(cfg, Mapping):
        return GalleryConfig.from_dict(cfg)

    named_cfg = getattr(mod, f"{component_name}_config", None)
    if isinstance(named_cfg, GalleryConfig):
        return named_cfg
    if isinstance(named_cfg, Mapping):
        return GalleryConfig.from_dict(named_cfg)

    # Legacy fallback for basic_kwargs / maximal_kwargs
    basic_kwargs = getattr(mod, "basic_kwargs", None)
    maximal_kwargs = getattr(mod, "maximal_kwargs", None)
    if basic_kwargs is not None or maximal_kwargs is not None:
        warnings.warn(
            f"Component '{component_name}' defines legacy 'basic_kwargs' or 'maximal_kwargs' "
            f"in '{gallery_path.name}'. Defining kwargs directly in gallery files is deprecated "
            "and will be removed in a future release. Export 'config = GalleryConfig(...)' instead.",
            DeprecationWarning,
            stacklevel=2,
        )
        variants: list[Variant] = []
        if basic_kwargs is not None:
            variants.append(Variant(name="basic", kwargs=basic_kwargs))
        if maximal_kwargs is not None:
            variants.append(Variant(name="maximal", kwargs=maximal_kwargs))
        return GalleryConfig(variants=variants)

    return GalleryConfig()