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.

GalleryConfig(hidden=False, icon=None, theme=None, group=None, order=0, canvas_template=None, extra_context=dict(), param_defaults=dict(), 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.

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
133
134
135
136
137
138
139
140
141
142
@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_variant(name)

Return the variant matching name, or None.

Source code in dj_design_system/gallery.py
169
170
171
172
173
174
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) 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 built-in variants ("basic", "maximal") so they do not clutter the sidebar tree, and True for custom named variants. Explicitly set to True or False to override this default.

from_dict(data, name=None) classmethod

Create a Variant from a dictionary or mapping.

Source code in dj_design_system/gallery.py
58
59
60
61
62
63
64
@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)

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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
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()