deckkit 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- deckkit/__init__.py +12 -0
- deckkit/_bundled_fonts.py +54 -0
- deckkit/_diagnostics.py +48 -0
- deckkit/_font_assets/SOURCES.txt +9 -0
- deckkit/_font_assets/SourceCodePro-Bold.ttf +0 -0
- deckkit/_font_assets/SourceCodePro-BoldIt.ttf +0 -0
- deckkit/_font_assets/SourceCodePro-It.ttf +0 -0
- deckkit/_font_assets/SourceCodePro-LICENSE.txt +93 -0
- deckkit/_font_assets/SourceCodePro-Regular.ttf +0 -0
- deckkit/_font_assets/SourceSans3-Bold.ttf +0 -0
- deckkit/_font_assets/SourceSans3-BoldIt.ttf +0 -0
- deckkit/_font_assets/SourceSans3-It.ttf +0 -0
- deckkit/_font_assets/SourceSans3-LICENSE.txt +93 -0
- deckkit/_font_assets/SourceSans3-Regular.ttf +0 -0
- deckkit/_variable_evaluation.py +82 -0
- deckkit/animation.py +211 -0
- deckkit/annotations.py +161 -0
- deckkit/backends/__init__.py +1 -0
- deckkit/backends/_font_embedding.py +41 -0
- deckkit/backends/_pptx_fonts.py +230 -0
- deckkit/backends/_pptx_shadows.py +241 -0
- deckkit/backends/_pptx_tables.py +251 -0
- deckkit/backends/pptx.py +1225 -0
- deckkit/backends/pptx_animation.py +175 -0
- deckkit/backends/svg.py +527 -0
- deckkit/canvas/__init__.py +40 -0
- deckkit/canvas/_geometry.py +49 -0
- deckkit/canvas/clipping.py +336 -0
- deckkit/canvas/context.py +34 -0
- deckkit/canvas/elements.py +306 -0
- deckkit/canvas/path.py +250 -0
- deckkit/canvas/scene.py +74 -0
- deckkit/canvas/style.py +31 -0
- deckkit/charts/__init__.py +59 -0
- deckkit/charts/axes.py +249 -0
- deckkit/charts/chart.py +244 -0
- deckkit/charts/content.py +132 -0
- deckkit/charts/context.py +45 -0
- deckkit/charts/interval.py +166 -0
- deckkit/charts/legends.py +82 -0
- deckkit/charts/marks.py +410 -0
- deckkit/charts/scales.py +205 -0
- deckkit/citations.py +200 -0
- deckkit/compiler.py +410 -0
- deckkit/context.py +72 -0
- deckkit/deck.py +168 -0
- deckkit/drawables/__init__.py +42 -0
- deckkit/drawables/bounds.py +17 -0
- deckkit/drawables/connector.py +22 -0
- deckkit/drawables/drawable.py +38 -0
- deckkit/drawables/ellipse.py +21 -0
- deckkit/drawables/group.py +10 -0
- deckkit/drawables/image.py +14 -0
- deckkit/drawables/line.py +18 -0
- deckkit/drawables/path.py +78 -0
- deckkit/drawables/rectangle.py +24 -0
- deckkit/drawables/rich_text.py +176 -0
- deckkit/drawables/table.py +42 -0
- deckkit/drawables/text.py +29 -0
- deckkit/effects.py +84 -0
- deckkit/expanded_views.py +561 -0
- deckkit/fonts.py +329 -0
- deckkit/geometry.py +48 -0
- deckkit/identity.py +72 -0
- deckkit/layout.py +398 -0
- deckkit/layouts/__init__.py +20 -0
- deckkit/layouts/_content.py +27 -0
- deckkit/layouts/annotations.py +217 -0
- deckkit/layouts/containers.py +202 -0
- deckkit/layouts/grid.py +299 -0
- deckkit/layouts/modifiers.py +200 -0
- deckkit/layouts/primitives.py +213 -0
- deckkit/layouts/table.py +139 -0
- deckkit/measurement.py +420 -0
- deckkit/paint.py +73 -0
- deckkit/py.typed +0 -0
- deckkit/reconcile.py +119 -0
- deckkit/semantic.py +47 -0
- deckkit/theme.py +364 -0
- deckkit/themes/__init__.py +91 -0
- deckkit/themes/clarity.py +98 -0
- deckkit/tokens.py +226 -0
- deckkit/units.py +73 -0
- deckkit/variables.py +212 -0
- deckkit/view_expansion.py +185 -0
- deckkit/views/__init__.py +100 -0
- deckkit/views/_code_source.py +42 -0
- deckkit/views/_drawing.py +52 -0
- deckkit/views/canvas.py +27 -0
- deckkit/views/code.py +481 -0
- deckkit/views/code_evolution.py +284 -0
- deckkit/views/composite_view.py +19 -0
- deckkit/views/divider.py +38 -0
- deckkit/views/ellipse.py +38 -0
- deckkit/views/grid.py +156 -0
- deckkit/views/hstack.py +43 -0
- deckkit/views/image.py +43 -0
- deckkit/views/layout_view.py +30 -0
- deckkit/views/line.py +31 -0
- deckkit/views/modifier_views.py +281 -0
- deckkit/views/path.py +36 -0
- deckkit/views/primitive_view.py +16 -0
- deckkit/views/pygments_highlighter.py +67 -0
- deckkit/views/rectangle.py +61 -0
- deckkit/views/section_number.py +21 -0
- deckkit/views/semantic/__init__.py +51 -0
- deckkit/views/semantic/before_after.py +109 -0
- deckkit/views/semantic/bullet_graph.py +216 -0
- deckkit/views/semantic/card.py +129 -0
- deckkit/views/semantic/code_block.py +41 -0
- deckkit/views/semantic/diff.py +642 -0
- deckkit/views/semantic/estimate_interval.py +137 -0
- deckkit/views/semantic/figure.py +55 -0
- deckkit/views/semantic/item_list.py +171 -0
- deckkit/views/semantic/metric.py +74 -0
- deckkit/views/semantic/pill.py +69 -0
- deckkit/views/semantic/pipeline.py +94 -0
- deckkit/views/semantic/pipeline_stage.py +59 -0
- deckkit/views/semantic/semantic_view.py +76 -0
- deckkit/views/semantic/sparkline.py +164 -0
- deckkit/views/semantic/table.py +439 -0
- deckkit/views/semantic/terminal.py +361 -0
- deckkit/views/semantic/timeline.py +158 -0
- deckkit/views/slide.py +37 -0
- deckkit/views/slide_number.py +20 -0
- deckkit/views/slides/__init__.py +16 -0
- deckkit/views/slides/section_slide.py +89 -0
- deckkit/views/slides/slide_margins.py +32 -0
- deckkit/views/slides/slide_with_margins.py +22 -0
- deckkit/views/slides/title_and_content.py +49 -0
- deckkit/views/slides/title_and_content_slide.py +55 -0
- deckkit/views/spacer.py +45 -0
- deckkit/views/stack.py +36 -0
- deckkit/views/text.py +142 -0
- deckkit/views/view.py +229 -0
- deckkit/views/vstack.py +31 -0
- deckkit/views/zstack.py +27 -0
- deckkit-0.1.0.dist-info/METADATA +123 -0
- deckkit-0.1.0.dist-info/RECORD +144 -0
- deckkit-0.1.0.dist-info/WHEEL +5 -0
- deckkit-0.1.0.dist-info/licenses/LICENSE +21 -0
- deckkit-0.1.0.dist-info/licenses/src/deckkit/_font_assets/SourceCodePro-LICENSE.txt +93 -0
- deckkit-0.1.0.dist-info/licenses/src/deckkit/_font_assets/SourceSans3-LICENSE.txt +93 -0
- deckkit-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""Base support for semantic, theme-overridable presentation components."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from abc import ABC
|
|
6
|
+
from collections.abc import Callable
|
|
7
|
+
from dataclasses import dataclass, replace
|
|
8
|
+
from typing import Any, Generic, TypeVar, cast, overload
|
|
9
|
+
|
|
10
|
+
from typing_extensions import Self
|
|
11
|
+
|
|
12
|
+
from ...context import Context
|
|
13
|
+
from ...tokens import DesignToken, TokenAssignment, TokenResolver
|
|
14
|
+
from ..composite_view import CompositeView
|
|
15
|
+
from ..view import View
|
|
16
|
+
|
|
17
|
+
StyleT = TypeVar("StyleT")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True)
|
|
21
|
+
class _StyleFields(TokenAssignment[StyleT]):
|
|
22
|
+
token: DesignToken[StyleT]
|
|
23
|
+
changes: tuple[tuple[str, object], ...]
|
|
24
|
+
|
|
25
|
+
def resolve(self, values: TokenResolver) -> StyleT:
|
|
26
|
+
inherited = values.inherited(self.token)
|
|
27
|
+
return cast(StyleT, replace(cast(Any, inherited), **dict(self.changes)))
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class SemanticView(CompositeView, ABC):
|
|
31
|
+
"""Base class for composites whose presentation may be supplied by a theme.
|
|
32
|
+
|
|
33
|
+
Subclasses implement :meth:`body` just like any other composite. During
|
|
34
|
+
expansion, themes may provide a recipe through ``render_semantic``;
|
|
35
|
+
otherwise that body is used.
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
def _resolve_body(
|
|
39
|
+
self, context: Context, *, on_theme_override: Callable[[], None] | None = None
|
|
40
|
+
) -> View:
|
|
41
|
+
"""Resolve a theme recipe, falling back to the authored body."""
|
|
42
|
+
recipe = context.environment.theme.render_semantic(self, context)
|
|
43
|
+
if recipe is None:
|
|
44
|
+
return self.body(context)
|
|
45
|
+
if on_theme_override is not None:
|
|
46
|
+
on_theme_override()
|
|
47
|
+
return recipe
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class StyledSemanticView(SemanticView, Generic[StyleT]):
|
|
51
|
+
"""A semantic component with a scoped, replaceable style token."""
|
|
52
|
+
|
|
53
|
+
style_token: DesignToken[StyleT]
|
|
54
|
+
|
|
55
|
+
@overload
|
|
56
|
+
def style(self, style: StyleT, /) -> Self: ...
|
|
57
|
+
|
|
58
|
+
@overload
|
|
59
|
+
def style(self, **changes: object) -> Self: ...
|
|
60
|
+
|
|
61
|
+
def style(self, *styles: StyleT, **changes: object) -> Self:
|
|
62
|
+
"""Replace the complete style or derive selected dataclass fields."""
|
|
63
|
+
if styles:
|
|
64
|
+
if len(styles) != 1 or changes:
|
|
65
|
+
raise TypeError(
|
|
66
|
+
"style accepts either a complete style or keyword fields"
|
|
67
|
+
)
|
|
68
|
+
return self.with_token(self.style_token, self.style_token.set(styles[0]))
|
|
69
|
+
return self.with_token(
|
|
70
|
+
self.style_token,
|
|
71
|
+
_StyleFields(self.style_token, tuple(sorted(changes.items()))),
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
def transform_style(self, transform: Callable[[StyleT], StyleT]) -> Self:
|
|
75
|
+
"""Derive this component's style from the inherited style."""
|
|
76
|
+
return self.with_token(self.style_token, self.style_token.derive(transform))
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
"""A compact, themeable chart of an ordered series."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Iterable
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from math import isfinite
|
|
8
|
+
from typing import overload
|
|
9
|
+
|
|
10
|
+
from typing_extensions import Self
|
|
11
|
+
|
|
12
|
+
from ...canvas import CanvasElement, Line, Stroke
|
|
13
|
+
from ...charts.chart import Chart, ChartInsets
|
|
14
|
+
from ...charts.content import ChartContent, DomainContribution, value
|
|
15
|
+
from ...charts.context import ChartContext
|
|
16
|
+
from ...charts.marks import LineMark
|
|
17
|
+
from ...charts.scales import LinearScale, LinearScaleSpec
|
|
18
|
+
from ...context import Context
|
|
19
|
+
from ...geometry import Point
|
|
20
|
+
from ...theme import AccentColor, MutedColor, SpacingUnit
|
|
21
|
+
from ...tokens import DesignToken, TokenResolver
|
|
22
|
+
from ...units import Length, pt, require_length
|
|
23
|
+
from ..modifier_views import unbounded
|
|
24
|
+
from ..view import View
|
|
25
|
+
from .semantic_view import StyledSemanticView
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass(frozen=True)
|
|
29
|
+
class _Reference(ChartContent):
|
|
30
|
+
value: float
|
|
31
|
+
stroke: Stroke
|
|
32
|
+
|
|
33
|
+
def domain_contributions(self) -> tuple[DomainContribution, ...]:
|
|
34
|
+
return (DomainContribution.quantitative("y", (self.value,)),)
|
|
35
|
+
|
|
36
|
+
def lower(self, context: ChartContext) -> Iterable[CanvasElement]:
|
|
37
|
+
scale = context.y_scale
|
|
38
|
+
assert isinstance(scale, LinearScale)
|
|
39
|
+
if not scale.domain[0] <= self.value <= scale.domain[1]:
|
|
40
|
+
return
|
|
41
|
+
bounds = context.plot_bounds
|
|
42
|
+
if bounds.width > pt(0) and bounds.height > pt(0):
|
|
43
|
+
y = context.position("y", self.value)
|
|
44
|
+
if bounds.y <= y <= bounds.y + bounds.height:
|
|
45
|
+
yield Line(
|
|
46
|
+
Point(bounds.x, y),
|
|
47
|
+
Point(bounds.x + bounds.width, y),
|
|
48
|
+
self.stroke,
|
|
49
|
+
key="reference",
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass(frozen=True, init=False)
|
|
54
|
+
class Sparkline(StyledSemanticView["Sparkline.Style"]):
|
|
55
|
+
"""Show a compact trend, with an optional shared domain and reference line."""
|
|
56
|
+
|
|
57
|
+
@dataclass(frozen=True)
|
|
58
|
+
class Style:
|
|
59
|
+
ideal_width: Length
|
|
60
|
+
height: Length
|
|
61
|
+
padding: Length
|
|
62
|
+
stroke: Stroke
|
|
63
|
+
point_radius: Length
|
|
64
|
+
reference_stroke: Stroke
|
|
65
|
+
|
|
66
|
+
def __post_init__(self) -> None:
|
|
67
|
+
for length in (
|
|
68
|
+
self.ideal_width,
|
|
69
|
+
self.height,
|
|
70
|
+
self.padding,
|
|
71
|
+
self.point_radius,
|
|
72
|
+
):
|
|
73
|
+
require_length(length)
|
|
74
|
+
if length < pt(0):
|
|
75
|
+
raise ValueError("Sparkline style lengths must be nonnegative")
|
|
76
|
+
if self.ideal_width == pt(0) or self.height == pt(0):
|
|
77
|
+
raise ValueError("Sparkline ideal width and height must be positive")
|
|
78
|
+
if not isinstance(self.stroke, Stroke) or not isinstance(
|
|
79
|
+
self.reference_stroke, Stroke
|
|
80
|
+
):
|
|
81
|
+
raise TypeError("Sparkline styles must use Stroke values")
|
|
82
|
+
|
|
83
|
+
@staticmethod
|
|
84
|
+
def _default_style(values: TokenResolver) -> Style:
|
|
85
|
+
unit = values[SpacingUnit]
|
|
86
|
+
return Sparkline.Style(
|
|
87
|
+
ideal_width=unit * 18,
|
|
88
|
+
height=unit * 6,
|
|
89
|
+
padding=unit / 3,
|
|
90
|
+
stroke=Stroke(AccentColor, unit / 3, line_cap="round", line_join="round"),
|
|
91
|
+
point_radius=unit / 2,
|
|
92
|
+
reference_stroke=Stroke(MutedColor, unit / 6, opacity=0.5),
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
style_token = DesignToken[Style](
|
|
96
|
+
"component.sparkline",
|
|
97
|
+
lambda values: Sparkline._default_style(values),
|
|
98
|
+
value_type=Style,
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
values: tuple[float | None, ...]
|
|
102
|
+
domain: tuple[float, float] | None
|
|
103
|
+
reference: float | None
|
|
104
|
+
|
|
105
|
+
def __init__(
|
|
106
|
+
self,
|
|
107
|
+
values: Iterable[float | None],
|
|
108
|
+
*,
|
|
109
|
+
domain: tuple[float, float] | None = None,
|
|
110
|
+
reference: float | None = None,
|
|
111
|
+
) -> None:
|
|
112
|
+
observations = tuple(values)
|
|
113
|
+
if any(number is not None and not isfinite(number) for number in observations):
|
|
114
|
+
raise ValueError("Sparkline values must be finite or None")
|
|
115
|
+
if reference is not None and not isfinite(reference):
|
|
116
|
+
raise ValueError("Sparkline reference must be finite")
|
|
117
|
+
if domain is not None:
|
|
118
|
+
domain = LinearScaleSpec(domain=domain, nice=False).infer_domain(())
|
|
119
|
+
object.__setattr__(self, "values", observations)
|
|
120
|
+
object.__setattr__(self, "domain", domain)
|
|
121
|
+
object.__setattr__(self, "reference", reference)
|
|
122
|
+
|
|
123
|
+
# The base method accepts fields from any style dataclass.
|
|
124
|
+
@overload # type: ignore[override]
|
|
125
|
+
def style(self, style: Sparkline.Style, /) -> Self: ...
|
|
126
|
+
|
|
127
|
+
@overload
|
|
128
|
+
def style(
|
|
129
|
+
self,
|
|
130
|
+
*,
|
|
131
|
+
ideal_width: Length = ...,
|
|
132
|
+
height: Length = ...,
|
|
133
|
+
padding: Length = ...,
|
|
134
|
+
stroke: Stroke = ...,
|
|
135
|
+
point_radius: Length = ...,
|
|
136
|
+
reference_stroke: Stroke = ...,
|
|
137
|
+
) -> Self: ...
|
|
138
|
+
|
|
139
|
+
def style(self, *styles: Sparkline.Style, **changes: object) -> Self:
|
|
140
|
+
"""Replace the style or override specific sparkline fields."""
|
|
141
|
+
return super().style(*styles, **changes)
|
|
142
|
+
|
|
143
|
+
def body(self, context: Context) -> View:
|
|
144
|
+
style = context.environment[self.style_token]
|
|
145
|
+
trend = LineMark(
|
|
146
|
+
enumerate(self.values),
|
|
147
|
+
x=value("Observation", lambda item: item[0]),
|
|
148
|
+
y=value("Value", lambda item: item[1]),
|
|
149
|
+
stroke=style.stroke,
|
|
150
|
+
point_radius=style.point_radius,
|
|
151
|
+
series="sparkline",
|
|
152
|
+
)
|
|
153
|
+
marks: tuple[ChartContent, ...] = (trend,)
|
|
154
|
+
if self.reference is not None:
|
|
155
|
+
marks = (_Reference(self.reference, style.reference_stroke), trend)
|
|
156
|
+
return Chart(
|
|
157
|
+
*marks,
|
|
158
|
+
x_scale=LinearScaleSpec(nice=False),
|
|
159
|
+
y_scale=LinearScaleSpec(domain=self.domain, nice=False),
|
|
160
|
+
plot_insets=ChartInsets(*((style.padding,) * 4)),
|
|
161
|
+
x_axis=None,
|
|
162
|
+
y_axis=None,
|
|
163
|
+
legend=None,
|
|
164
|
+
).frame(ideal_width=style.ideal_width, max_width=unbounded, height=style.height)
|
|
@@ -0,0 +1,439 @@
|
|
|
1
|
+
"""Tables with typed columns, custom cell views, and shared layout."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable, Iterable
|
|
6
|
+
from dataclasses import dataclass, field, replace
|
|
7
|
+
from decimal import Decimal
|
|
8
|
+
from numbers import Real
|
|
9
|
+
from typing import Any, Generic, Literal, TypeVar, overload
|
|
10
|
+
|
|
11
|
+
from typing_extensions import Self, TypeAlias
|
|
12
|
+
|
|
13
|
+
from ...canvas import Stroke
|
|
14
|
+
from ...context import Context
|
|
15
|
+
from ...drawables.table import TableCellGeometry, TableRowGeometry
|
|
16
|
+
from ...geometry import RelativePoint
|
|
17
|
+
from ...identity import ViewIdentity
|
|
18
|
+
from ...layout import Layout
|
|
19
|
+
from ...layouts.grid import ColumnWidth
|
|
20
|
+
from ...layouts.table import TableLayout, TableRowLayout
|
|
21
|
+
from ...theme import (
|
|
22
|
+
AccentColor,
|
|
23
|
+
CaptionTextStyle,
|
|
24
|
+
Color,
|
|
25
|
+
ColorStyle,
|
|
26
|
+
MutedColor,
|
|
27
|
+
PrimaryColor,
|
|
28
|
+
SpacingUnit,
|
|
29
|
+
SurfaceColor,
|
|
30
|
+
Typography,
|
|
31
|
+
)
|
|
32
|
+
from ...tokens import DesignToken, TokenResolver
|
|
33
|
+
from ...units import Length, pt, require_length
|
|
34
|
+
from ..composite_view import CompositeView
|
|
35
|
+
from ..layout_view import LayoutView
|
|
36
|
+
from ..modifier_views import EdgeInsets, _padding_insets
|
|
37
|
+
from ..text import Text
|
|
38
|
+
from ..view import View
|
|
39
|
+
from .semantic_view import StyledSemanticView
|
|
40
|
+
|
|
41
|
+
__all__ = ["CellStyle", "ColumnWidth", "RowStyle", "Table", "TableColumn"]
|
|
42
|
+
|
|
43
|
+
RowT = TypeVar("RowT")
|
|
44
|
+
ValueT = TypeVar("ValueT")
|
|
45
|
+
_Pptx: TypeAlias = Literal["shapes", "native"]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass(frozen=True)
|
|
49
|
+
class CellStyle:
|
|
50
|
+
"""Optional overrides for a cell's content and its surrounding area."""
|
|
51
|
+
|
|
52
|
+
background: ColorStyle | None = None
|
|
53
|
+
foreground: ColorStyle | None = None
|
|
54
|
+
font: DesignToken[Typography] | Typography | None = None
|
|
55
|
+
padding: Length | EdgeInsets | None = None
|
|
56
|
+
alignment: RelativePoint | None = None
|
|
57
|
+
|
|
58
|
+
def __post_init__(self) -> None:
|
|
59
|
+
if self.padding is not None:
|
|
60
|
+
_padding_insets(self.padding, None)
|
|
61
|
+
if self.alignment is not None and (
|
|
62
|
+
not 0 <= self.alignment.x <= 1 or not 0 <= self.alignment.y <= 1
|
|
63
|
+
):
|
|
64
|
+
raise ValueError("Table cell alignment must be within the cell")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@dataclass(frozen=True)
|
|
68
|
+
class RowStyle:
|
|
69
|
+
"""Appearance and vertical padding for a complete table row."""
|
|
70
|
+
|
|
71
|
+
background: ColorStyle | None = None
|
|
72
|
+
foreground: ColorStyle | None = None
|
|
73
|
+
font: DesignToken[Typography] | Typography | None = None
|
|
74
|
+
vertical_padding: Length | None = None
|
|
75
|
+
rule_above: Stroke | None = None
|
|
76
|
+
rule_below: Stroke | None = None
|
|
77
|
+
|
|
78
|
+
def __post_init__(self) -> None:
|
|
79
|
+
if self.vertical_padding is not None:
|
|
80
|
+
require_length(self.vertical_padding)
|
|
81
|
+
if self.vertical_padding < pt(0):
|
|
82
|
+
raise ValueError("Table row padding must be nonnegative")
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
@dataclass(frozen=True)
|
|
86
|
+
class TableColumn(Generic[RowT, ValueT]):
|
|
87
|
+
"""Select and display one typed value per row."""
|
|
88
|
+
|
|
89
|
+
title: str | View
|
|
90
|
+
value: Callable[[RowT], ValueT]
|
|
91
|
+
format: Callable[[ValueT], str] | None = None
|
|
92
|
+
cell: Callable[[ValueT], View] | None = None
|
|
93
|
+
width: Length | ColumnWidth = field(default_factory=ColumnWidth)
|
|
94
|
+
style: CellStyle = CellStyle()
|
|
95
|
+
header_style: CellStyle = CellStyle()
|
|
96
|
+
style_cell: Callable[[ValueT, CellStyle], CellStyle] | None = None
|
|
97
|
+
separator: Stroke | None = None
|
|
98
|
+
key: str | int | None = None
|
|
99
|
+
|
|
100
|
+
def __post_init__(self) -> None:
|
|
101
|
+
if not isinstance(self.title, (str, View)):
|
|
102
|
+
raise TypeError("TableColumn.title must be a string or a View")
|
|
103
|
+
if self.cell is not None and self.format is not None:
|
|
104
|
+
raise ValueError("TableColumn accepts a formatter or a cell view factory")
|
|
105
|
+
for callback in (self.format, self.cell, self.style_cell):
|
|
106
|
+
if callback is not None and not callable(callback):
|
|
107
|
+
raise TypeError("Table column callbacks must be callable")
|
|
108
|
+
if not callable(self.value):
|
|
109
|
+
raise TypeError("TableColumn.value must be callable")
|
|
110
|
+
if not isinstance(self.width, ColumnWidth):
|
|
111
|
+
require_length(self.width)
|
|
112
|
+
if self.width <= pt(0):
|
|
113
|
+
raise ValueError("A fixed table column width must be positive")
|
|
114
|
+
|
|
115
|
+
def _content(self, value: ValueT) -> View:
|
|
116
|
+
if self.cell is not None:
|
|
117
|
+
result = self.cell(value)
|
|
118
|
+
if not isinstance(result, View):
|
|
119
|
+
raise TypeError("TableColumn.cell must return a View")
|
|
120
|
+
return result
|
|
121
|
+
label = (
|
|
122
|
+
self.format(value)
|
|
123
|
+
if self.format is not None
|
|
124
|
+
else ("" if value is None else str(value))
|
|
125
|
+
)
|
|
126
|
+
if not isinstance(label, str):
|
|
127
|
+
raise TypeError("TableColumn.format must return a string")
|
|
128
|
+
return Text(label)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _color(style: ColorStyle | None, context: Context) -> str | None:
|
|
132
|
+
if style is None:
|
|
133
|
+
return None
|
|
134
|
+
return (style if isinstance(style, Color) else context.environment[style]).hex
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _stroke(stroke: Stroke | None, context: Context) -> Stroke | None:
|
|
138
|
+
if stroke is not None and isinstance(stroke.style, DesignToken):
|
|
139
|
+
return replace(stroke, style=context.environment[stroke.style])
|
|
140
|
+
return stroke
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _numeric(values: tuple[object, ...]) -> bool:
|
|
144
|
+
present = [value for value in values if value is not None]
|
|
145
|
+
return bool(present) and all(
|
|
146
|
+
isinstance(value, (Real, Decimal)) and not isinstance(value, bool)
|
|
147
|
+
for value in present
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
@dataclass(frozen=True)
|
|
152
|
+
class _Cell(CompositeView):
|
|
153
|
+
content: View
|
|
154
|
+
style: CellStyle
|
|
155
|
+
|
|
156
|
+
def body(self, context: Context) -> View:
|
|
157
|
+
return self.content
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
@dataclass(frozen=True, init=False)
|
|
161
|
+
class _RowGrid(LayoutView):
|
|
162
|
+
policy: TableRowLayout
|
|
163
|
+
|
|
164
|
+
def __init__(self, policy: TableRowLayout, cells: tuple[View, ...]) -> None:
|
|
165
|
+
object.__setattr__(self, "policy", policy)
|
|
166
|
+
super().__init__(*cells)
|
|
167
|
+
|
|
168
|
+
def resolve_layout(self, lookup: Callable[[str], ViewIdentity]) -> Layout:
|
|
169
|
+
return self.policy
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
@dataclass(frozen=True)
|
|
173
|
+
class _Row(CompositeView):
|
|
174
|
+
grid: _RowGrid
|
|
175
|
+
|
|
176
|
+
def body(self, context: Context) -> View:
|
|
177
|
+
return self.grid
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
@dataclass(frozen=True, init=False)
|
|
181
|
+
class _TableGrid(LayoutView):
|
|
182
|
+
policy: TableLayout
|
|
183
|
+
|
|
184
|
+
def __init__(self, policy: TableLayout, rows: tuple[View, ...]) -> None:
|
|
185
|
+
object.__setattr__(self, "policy", policy)
|
|
186
|
+
super().__init__(*rows)
|
|
187
|
+
|
|
188
|
+
def resolve_layout(self, lookup: Callable[[str], ViewIdentity]) -> Layout:
|
|
189
|
+
return self.policy
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
@dataclass(frozen=True, init=False)
|
|
193
|
+
class Table(StyledSemanticView["Table.Style"], Generic[RowT]):
|
|
194
|
+
"""Arrange typed rows in a shared grid with editable shape export by default."""
|
|
195
|
+
|
|
196
|
+
@dataclass(frozen=True)
|
|
197
|
+
class Style:
|
|
198
|
+
header: RowStyle
|
|
199
|
+
body: RowStyle
|
|
200
|
+
alternate_row: RowStyle | None = None
|
|
201
|
+
cell: CellStyle = CellStyle()
|
|
202
|
+
row_separator: Stroke | None = None
|
|
203
|
+
|
|
204
|
+
@staticmethod
|
|
205
|
+
def _default_style(values: TokenResolver) -> Style:
|
|
206
|
+
unit = values[SpacingUnit]
|
|
207
|
+
return Table.Style(
|
|
208
|
+
header=RowStyle(
|
|
209
|
+
foreground=MutedColor,
|
|
210
|
+
font=CaptionTextStyle,
|
|
211
|
+
rule_below=Stroke(AccentColor, unit / 3),
|
|
212
|
+
),
|
|
213
|
+
body=RowStyle(foreground=PrimaryColor),
|
|
214
|
+
cell=CellStyle(
|
|
215
|
+
padding=EdgeInsets(
|
|
216
|
+
top=unit * 2, leading=unit * 3, bottom=unit * 2, trailing=unit * 3
|
|
217
|
+
)
|
|
218
|
+
),
|
|
219
|
+
row_separator=Stroke(
|
|
220
|
+
values[MutedColor].mix(values[SurfaceColor], 0.76), unit / 6
|
|
221
|
+
),
|
|
222
|
+
)
|
|
223
|
+
|
|
224
|
+
style_token = DesignToken[Style](
|
|
225
|
+
"component.table", lambda values: Table._default_style(values), value_type=Style
|
|
226
|
+
)
|
|
227
|
+
|
|
228
|
+
rows: tuple[RowT, ...]
|
|
229
|
+
columns: tuple[TableColumn[RowT, Any], ...]
|
|
230
|
+
row_key: Callable[[RowT], str | int] | None
|
|
231
|
+
row_style: Callable[[RowT, int, RowStyle], RowStyle] | None
|
|
232
|
+
pptx: _Pptx
|
|
233
|
+
|
|
234
|
+
def __init__(
|
|
235
|
+
self,
|
|
236
|
+
rows: Iterable[RowT],
|
|
237
|
+
*,
|
|
238
|
+
columns: Iterable[TableColumn[RowT, Any]],
|
|
239
|
+
row_key: Callable[[RowT], str | int] | None = None,
|
|
240
|
+
row_style: Callable[[RowT, int, RowStyle], RowStyle] | None = None,
|
|
241
|
+
pptx: _Pptx = "shapes",
|
|
242
|
+
) -> None:
|
|
243
|
+
column_tuple = tuple(columns)
|
|
244
|
+
if not column_tuple:
|
|
245
|
+
raise ValueError("Table requires at least one column")
|
|
246
|
+
if not all(isinstance(column, TableColumn) for column in column_tuple):
|
|
247
|
+
raise TypeError("Table columns must be TableColumn instances")
|
|
248
|
+
if pptx not in ("shapes", "native"):
|
|
249
|
+
raise ValueError("Table.pptx must be 'shapes' or 'native'")
|
|
250
|
+
for callback in (row_key, row_style):
|
|
251
|
+
if callback is not None and not callable(callback):
|
|
252
|
+
raise TypeError("Table row callbacks must be callable")
|
|
253
|
+
object.__setattr__(self, "rows", tuple(rows))
|
|
254
|
+
object.__setattr__(self, "columns", column_tuple)
|
|
255
|
+
object.__setattr__(self, "row_key", row_key)
|
|
256
|
+
object.__setattr__(self, "row_style", row_style)
|
|
257
|
+
object.__setattr__(self, "pptx", pptx)
|
|
258
|
+
|
|
259
|
+
# The base method accepts fields from any style dataclass.
|
|
260
|
+
@overload # type: ignore[override]
|
|
261
|
+
def style(self, style: Table.Style, /) -> Self: ...
|
|
262
|
+
|
|
263
|
+
@overload
|
|
264
|
+
def style(
|
|
265
|
+
self,
|
|
266
|
+
*,
|
|
267
|
+
header: RowStyle = ...,
|
|
268
|
+
body: RowStyle = ...,
|
|
269
|
+
alternate_row: RowStyle | None = ...,
|
|
270
|
+
cell: CellStyle = ...,
|
|
271
|
+
row_separator: Stroke | None = ...,
|
|
272
|
+
) -> Self: ...
|
|
273
|
+
|
|
274
|
+
def style(self, *styles: Table.Style, **changes: object) -> Self:
|
|
275
|
+
"""Replace the table style or override specific fields."""
|
|
276
|
+
return super().style(*styles, **changes)
|
|
277
|
+
|
|
278
|
+
def body(self, context: Context) -> View:
|
|
279
|
+
style = context.environment[self.style_token]
|
|
280
|
+
column_keys = tuple(
|
|
281
|
+
str(column.key if column.key is not None else index)
|
|
282
|
+
for index, column in enumerate(self.columns)
|
|
283
|
+
)
|
|
284
|
+
if len(set(column_keys)) != len(column_keys):
|
|
285
|
+
raise ValueError("Table column keys must be unique")
|
|
286
|
+
row_keys = tuple(
|
|
287
|
+
str(self.row_key(row) if self.row_key is not None else index)
|
|
288
|
+
for index, row in enumerate(self.rows)
|
|
289
|
+
)
|
|
290
|
+
if len(set(row_keys)) != len(row_keys):
|
|
291
|
+
raise ValueError("Table row keys must be unique")
|
|
292
|
+
|
|
293
|
+
values = tuple(
|
|
294
|
+
tuple(column.value(row) for row in self.rows) for column in self.columns
|
|
295
|
+
)
|
|
296
|
+
widths = tuple(column.width for column in self.columns)
|
|
297
|
+
numeric = tuple(_numeric(items) for items in values)
|
|
298
|
+
row_styles = [style.header]
|
|
299
|
+
alternate = (
|
|
300
|
+
_alternate_style(style.body, style.alternate_row)
|
|
301
|
+
if style.alternate_row is not None
|
|
302
|
+
else style.body
|
|
303
|
+
)
|
|
304
|
+
for index, row in enumerate(self.rows):
|
|
305
|
+
row_base = alternate if index % 2 else style.body
|
|
306
|
+
result = (
|
|
307
|
+
self.row_style(row, index, row_base) if self.row_style else row_base
|
|
308
|
+
)
|
|
309
|
+
if not isinstance(result, RowStyle):
|
|
310
|
+
raise TypeError("Table.row_style must return a RowStyle")
|
|
311
|
+
row_styles.append(result)
|
|
312
|
+
|
|
313
|
+
geometry = []
|
|
314
|
+
views: list[View] = []
|
|
315
|
+
for index, row_style in enumerate(row_styles):
|
|
316
|
+
is_header = index == 0
|
|
317
|
+
cells, cell_views = [], []
|
|
318
|
+
for j, column in enumerate(self.columns):
|
|
319
|
+
if is_header:
|
|
320
|
+
label = column.title
|
|
321
|
+
view = Text(label) if isinstance(label, str) else label
|
|
322
|
+
patch = column.header_style
|
|
323
|
+
plain = isinstance(label, str)
|
|
324
|
+
else:
|
|
325
|
+
value = values[j][index - 1]
|
|
326
|
+
view = column._content(value)
|
|
327
|
+
patch = column.style
|
|
328
|
+
plain = column.cell is None
|
|
329
|
+
default_alignment = (
|
|
330
|
+
RelativePoint.right if numeric[j] else RelativePoint.left
|
|
331
|
+
)
|
|
332
|
+
base = _cell_style(
|
|
333
|
+
style.cell,
|
|
334
|
+
row_style,
|
|
335
|
+
patch,
|
|
336
|
+
default_alignment,
|
|
337
|
+
column.style.alignment,
|
|
338
|
+
)
|
|
339
|
+
if not is_header and column.style_cell is not None:
|
|
340
|
+
base = column.style_cell(value, base)
|
|
341
|
+
if not isinstance(base, CellStyle):
|
|
342
|
+
raise TypeError(
|
|
343
|
+
"TableColumn.style_cell must return a CellStyle"
|
|
344
|
+
)
|
|
345
|
+
padding = _padding_insets(
|
|
346
|
+
base.padding if base.padding is not None else pt(0), None
|
|
347
|
+
)
|
|
348
|
+
cells.append(
|
|
349
|
+
TableCellGeometry(
|
|
350
|
+
padding,
|
|
351
|
+
base.alignment or default_alignment,
|
|
352
|
+
_color(base.background, context),
|
|
353
|
+
plain,
|
|
354
|
+
)
|
|
355
|
+
)
|
|
356
|
+
cell: View = _Cell(view, base).key(column_keys[j])
|
|
357
|
+
# Scope defaults to the cell so a custom view can override them.
|
|
358
|
+
if base.foreground is not None:
|
|
359
|
+
cell = cell.foreground_style(base.foreground)
|
|
360
|
+
if base.font is not None:
|
|
361
|
+
cell = cell.font(base.font)
|
|
362
|
+
cell_views.append(cell)
|
|
363
|
+
measured_row = TableRowGeometry(
|
|
364
|
+
tuple(cells), _color(row_style.background, context)
|
|
365
|
+
)
|
|
366
|
+
geometry.append(measured_row)
|
|
367
|
+
key = "header" if is_header else f"row:{row_keys[index - 1]}"
|
|
368
|
+
views.append(
|
|
369
|
+
_Row(
|
|
370
|
+
_RowGrid(TableRowLayout(measured_row, widths), tuple(cell_views))
|
|
371
|
+
).key(key)
|
|
372
|
+
)
|
|
373
|
+
|
|
374
|
+
horizontal = [row_styles[0].rule_above]
|
|
375
|
+
for index, (above, below) in enumerate(zip(row_styles, row_styles[1:])):
|
|
376
|
+
interior = style.row_separator if index > 0 else None
|
|
377
|
+
horizontal.append(below.rule_above or above.rule_below or interior)
|
|
378
|
+
horizontal.append(row_styles[-1].rule_below)
|
|
379
|
+
native_error = None
|
|
380
|
+
if self.pptx == "native":
|
|
381
|
+
for column in self.columns:
|
|
382
|
+
if column.cell is not None or isinstance(column.title, View):
|
|
383
|
+
native_error = f"column {column.key if column.key is not None else column.title!r} uses a custom view"
|
|
384
|
+
break
|
|
385
|
+
return _TableGrid(
|
|
386
|
+
TableLayout(
|
|
387
|
+
widths,
|
|
388
|
+
numeric,
|
|
389
|
+
tuple(geometry),
|
|
390
|
+
tuple(_stroke(rule, context) for rule in horizontal),
|
|
391
|
+
tuple(_stroke(column.separator, context) for column in self.columns),
|
|
392
|
+
self.pptx == "native",
|
|
393
|
+
native_error,
|
|
394
|
+
),
|
|
395
|
+
tuple(views),
|
|
396
|
+
)
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
def _cell_style(
|
|
400
|
+
default: CellStyle,
|
|
401
|
+
row: RowStyle,
|
|
402
|
+
column: CellStyle,
|
|
403
|
+
alignment: RelativePoint,
|
|
404
|
+
column_alignment: RelativePoint | None,
|
|
405
|
+
) -> CellStyle:
|
|
406
|
+
padding = _padding_insets(
|
|
407
|
+
default.padding if default.padding is not None else pt(0), None
|
|
408
|
+
)
|
|
409
|
+
if row.vertical_padding is not None:
|
|
410
|
+
padding = replace(
|
|
411
|
+
padding, top=row.vertical_padding, bottom=row.vertical_padding
|
|
412
|
+
)
|
|
413
|
+
return CellStyle(
|
|
414
|
+
background=column.background
|
|
415
|
+
if column.background is not None
|
|
416
|
+
else default.background,
|
|
417
|
+
foreground=column.foreground or row.foreground or default.foreground,
|
|
418
|
+
font=column.font or row.font or default.font,
|
|
419
|
+
padding=column.padding if column.padding is not None else padding,
|
|
420
|
+
alignment=column.alignment
|
|
421
|
+
or column_alignment
|
|
422
|
+
or default.alignment
|
|
423
|
+
or alignment,
|
|
424
|
+
)
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
def _alternate_style(body: RowStyle, alternate: RowStyle) -> RowStyle:
|
|
428
|
+
return RowStyle(
|
|
429
|
+
background=alternate.background or body.background,
|
|
430
|
+
foreground=alternate.foreground or body.foreground,
|
|
431
|
+
font=alternate.font or body.font,
|
|
432
|
+
vertical_padding=(
|
|
433
|
+
alternate.vertical_padding
|
|
434
|
+
if alternate.vertical_padding is not None
|
|
435
|
+
else body.vertical_padding
|
|
436
|
+
),
|
|
437
|
+
rule_above=alternate.rule_above or body.rule_above,
|
|
438
|
+
rule_below=alternate.rule_below or body.rule_below,
|
|
439
|
+
)
|