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.
Files changed (144) hide show
  1. deckkit/__init__.py +12 -0
  2. deckkit/_bundled_fonts.py +54 -0
  3. deckkit/_diagnostics.py +48 -0
  4. deckkit/_font_assets/SOURCES.txt +9 -0
  5. deckkit/_font_assets/SourceCodePro-Bold.ttf +0 -0
  6. deckkit/_font_assets/SourceCodePro-BoldIt.ttf +0 -0
  7. deckkit/_font_assets/SourceCodePro-It.ttf +0 -0
  8. deckkit/_font_assets/SourceCodePro-LICENSE.txt +93 -0
  9. deckkit/_font_assets/SourceCodePro-Regular.ttf +0 -0
  10. deckkit/_font_assets/SourceSans3-Bold.ttf +0 -0
  11. deckkit/_font_assets/SourceSans3-BoldIt.ttf +0 -0
  12. deckkit/_font_assets/SourceSans3-It.ttf +0 -0
  13. deckkit/_font_assets/SourceSans3-LICENSE.txt +93 -0
  14. deckkit/_font_assets/SourceSans3-Regular.ttf +0 -0
  15. deckkit/_variable_evaluation.py +82 -0
  16. deckkit/animation.py +211 -0
  17. deckkit/annotations.py +161 -0
  18. deckkit/backends/__init__.py +1 -0
  19. deckkit/backends/_font_embedding.py +41 -0
  20. deckkit/backends/_pptx_fonts.py +230 -0
  21. deckkit/backends/_pptx_shadows.py +241 -0
  22. deckkit/backends/_pptx_tables.py +251 -0
  23. deckkit/backends/pptx.py +1225 -0
  24. deckkit/backends/pptx_animation.py +175 -0
  25. deckkit/backends/svg.py +527 -0
  26. deckkit/canvas/__init__.py +40 -0
  27. deckkit/canvas/_geometry.py +49 -0
  28. deckkit/canvas/clipping.py +336 -0
  29. deckkit/canvas/context.py +34 -0
  30. deckkit/canvas/elements.py +306 -0
  31. deckkit/canvas/path.py +250 -0
  32. deckkit/canvas/scene.py +74 -0
  33. deckkit/canvas/style.py +31 -0
  34. deckkit/charts/__init__.py +59 -0
  35. deckkit/charts/axes.py +249 -0
  36. deckkit/charts/chart.py +244 -0
  37. deckkit/charts/content.py +132 -0
  38. deckkit/charts/context.py +45 -0
  39. deckkit/charts/interval.py +166 -0
  40. deckkit/charts/legends.py +82 -0
  41. deckkit/charts/marks.py +410 -0
  42. deckkit/charts/scales.py +205 -0
  43. deckkit/citations.py +200 -0
  44. deckkit/compiler.py +410 -0
  45. deckkit/context.py +72 -0
  46. deckkit/deck.py +168 -0
  47. deckkit/drawables/__init__.py +42 -0
  48. deckkit/drawables/bounds.py +17 -0
  49. deckkit/drawables/connector.py +22 -0
  50. deckkit/drawables/drawable.py +38 -0
  51. deckkit/drawables/ellipse.py +21 -0
  52. deckkit/drawables/group.py +10 -0
  53. deckkit/drawables/image.py +14 -0
  54. deckkit/drawables/line.py +18 -0
  55. deckkit/drawables/path.py +78 -0
  56. deckkit/drawables/rectangle.py +24 -0
  57. deckkit/drawables/rich_text.py +176 -0
  58. deckkit/drawables/table.py +42 -0
  59. deckkit/drawables/text.py +29 -0
  60. deckkit/effects.py +84 -0
  61. deckkit/expanded_views.py +561 -0
  62. deckkit/fonts.py +329 -0
  63. deckkit/geometry.py +48 -0
  64. deckkit/identity.py +72 -0
  65. deckkit/layout.py +398 -0
  66. deckkit/layouts/__init__.py +20 -0
  67. deckkit/layouts/_content.py +27 -0
  68. deckkit/layouts/annotations.py +217 -0
  69. deckkit/layouts/containers.py +202 -0
  70. deckkit/layouts/grid.py +299 -0
  71. deckkit/layouts/modifiers.py +200 -0
  72. deckkit/layouts/primitives.py +213 -0
  73. deckkit/layouts/table.py +139 -0
  74. deckkit/measurement.py +420 -0
  75. deckkit/paint.py +73 -0
  76. deckkit/py.typed +0 -0
  77. deckkit/reconcile.py +119 -0
  78. deckkit/semantic.py +47 -0
  79. deckkit/theme.py +364 -0
  80. deckkit/themes/__init__.py +91 -0
  81. deckkit/themes/clarity.py +98 -0
  82. deckkit/tokens.py +226 -0
  83. deckkit/units.py +73 -0
  84. deckkit/variables.py +212 -0
  85. deckkit/view_expansion.py +185 -0
  86. deckkit/views/__init__.py +100 -0
  87. deckkit/views/_code_source.py +42 -0
  88. deckkit/views/_drawing.py +52 -0
  89. deckkit/views/canvas.py +27 -0
  90. deckkit/views/code.py +481 -0
  91. deckkit/views/code_evolution.py +284 -0
  92. deckkit/views/composite_view.py +19 -0
  93. deckkit/views/divider.py +38 -0
  94. deckkit/views/ellipse.py +38 -0
  95. deckkit/views/grid.py +156 -0
  96. deckkit/views/hstack.py +43 -0
  97. deckkit/views/image.py +43 -0
  98. deckkit/views/layout_view.py +30 -0
  99. deckkit/views/line.py +31 -0
  100. deckkit/views/modifier_views.py +281 -0
  101. deckkit/views/path.py +36 -0
  102. deckkit/views/primitive_view.py +16 -0
  103. deckkit/views/pygments_highlighter.py +67 -0
  104. deckkit/views/rectangle.py +61 -0
  105. deckkit/views/section_number.py +21 -0
  106. deckkit/views/semantic/__init__.py +51 -0
  107. deckkit/views/semantic/before_after.py +109 -0
  108. deckkit/views/semantic/bullet_graph.py +216 -0
  109. deckkit/views/semantic/card.py +129 -0
  110. deckkit/views/semantic/code_block.py +41 -0
  111. deckkit/views/semantic/diff.py +642 -0
  112. deckkit/views/semantic/estimate_interval.py +137 -0
  113. deckkit/views/semantic/figure.py +55 -0
  114. deckkit/views/semantic/item_list.py +171 -0
  115. deckkit/views/semantic/metric.py +74 -0
  116. deckkit/views/semantic/pill.py +69 -0
  117. deckkit/views/semantic/pipeline.py +94 -0
  118. deckkit/views/semantic/pipeline_stage.py +59 -0
  119. deckkit/views/semantic/semantic_view.py +76 -0
  120. deckkit/views/semantic/sparkline.py +164 -0
  121. deckkit/views/semantic/table.py +439 -0
  122. deckkit/views/semantic/terminal.py +361 -0
  123. deckkit/views/semantic/timeline.py +158 -0
  124. deckkit/views/slide.py +37 -0
  125. deckkit/views/slide_number.py +20 -0
  126. deckkit/views/slides/__init__.py +16 -0
  127. deckkit/views/slides/section_slide.py +89 -0
  128. deckkit/views/slides/slide_margins.py +32 -0
  129. deckkit/views/slides/slide_with_margins.py +22 -0
  130. deckkit/views/slides/title_and_content.py +49 -0
  131. deckkit/views/slides/title_and_content_slide.py +55 -0
  132. deckkit/views/spacer.py +45 -0
  133. deckkit/views/stack.py +36 -0
  134. deckkit/views/text.py +142 -0
  135. deckkit/views/view.py +229 -0
  136. deckkit/views/vstack.py +31 -0
  137. deckkit/views/zstack.py +27 -0
  138. deckkit-0.1.0.dist-info/METADATA +123 -0
  139. deckkit-0.1.0.dist-info/RECORD +144 -0
  140. deckkit-0.1.0.dist-info/WHEEL +5 -0
  141. deckkit-0.1.0.dist-info/licenses/LICENSE +21 -0
  142. deckkit-0.1.0.dist-info/licenses/src/deckkit/_font_assets/SourceCodePro-LICENSE.txt +93 -0
  143. deckkit-0.1.0.dist-info/licenses/src/deckkit/_font_assets/SourceSans3-LICENSE.txt +93 -0
  144. deckkit-0.1.0.dist-info/top_level.txt +1 -0
deckkit/citations.py ADDED
@@ -0,0 +1,200 @@
1
+ """Bibliographic source data and theme-overridable citation views."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from builtins import format as format_value
6
+ from collections.abc import Mapping
7
+ from dataclasses import dataclass
8
+ from types import MappingProxyType
9
+
10
+ from .context import Context
11
+ from .expanded_views import ExpandedContainer, ExpandedDeferred, ExpandedMetadata
12
+ from .layouts import PassthroughLayout
13
+ from .theme import SpacingUnit
14
+ from .variables import _VARIABLE_VALUES, Occurrence, Variable
15
+ from .view_expansion import expand_view
16
+ from .views.primitive_view import PrimitiveView
17
+ from .views.semantic.semantic_view import SemanticView
18
+ from .views.text import Text
19
+ from .views.view import View
20
+ from .views.vstack import VStack
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class Author:
25
+ """A personal name whose parts can be rendered in different orders."""
26
+
27
+ family: str
28
+ given: str = ""
29
+
30
+ def __post_init__(self) -> None:
31
+ if not isinstance(self.family, str) or not self.family.strip():
32
+ raise ValueError("Author.family must be a nonempty string")
33
+ if not isinstance(self.given, str):
34
+ raise TypeError("Author.given must be a string")
35
+
36
+ @property
37
+ def name(self) -> str:
38
+ return f"{self.given} {self.family}" if self.given else self.family
39
+
40
+
41
+ @dataclass(frozen=True)
42
+ class Reference:
43
+ """Metadata for a work cited in a deck."""
44
+
45
+ title: str
46
+ authors: tuple[Author | str, ...] = ()
47
+ year: int | str | None = None
48
+ container: str | None = None
49
+ publisher: str | None = None
50
+ url: str | None = None
51
+ doi: str | None = None
52
+ kind: str | None = None
53
+ volume: str | None = None
54
+ issue: str | None = None
55
+ pages: str | None = None
56
+
57
+ def __post_init__(self) -> None:
58
+ if not isinstance(self.title, str) or not self.title.strip():
59
+ raise ValueError("Reference.title must be a nonempty string")
60
+ if isinstance(self.authors, str):
61
+ raise TypeError("Reference.authors must be a sequence of authors")
62
+ authors = tuple(self.authors)
63
+ if any(
64
+ not isinstance(author, Author)
65
+ and (not isinstance(author, str) or not author.strip())
66
+ for author in authors
67
+ ):
68
+ raise ValueError("Reference.authors must contain authors or nonempty names")
69
+ object.__setattr__(self, "authors", authors)
70
+
71
+
72
+ @dataclass(frozen=True)
73
+ class Citation(SemanticView):
74
+ """An in-slide citation of one work, optionally at a location within it."""
75
+
76
+ source_key: str
77
+ reference: Reference
78
+ occurrence: Occurrence[Mapping[str, int]]
79
+ locator: str | None = None
80
+
81
+ def number(self, *, format: str = "d") -> View:
82
+ """Display the work's assigned number with a Python format specifier."""
83
+ return self.occurrence.view(
84
+ format=lambda numbers: format_value(numbers[self.source_key], format)
85
+ )
86
+
87
+ def body(self, context: Context) -> View:
88
+ locator = f", {self.locator}" if self.locator else ""
89
+ return self.occurrence.view(
90
+ format=lambda numbers: f"[{numbers[self.source_key]}{locator}]"
91
+ )
92
+
93
+
94
+ @dataclass(frozen=True)
95
+ class BibliographyEntry(SemanticView):
96
+ """One cited work and its number, available to the theme as data."""
97
+
98
+ source_key: str
99
+ reference: Reference
100
+ number: int
101
+
102
+ def body(self, context: Context) -> View:
103
+ reference = self.reference
104
+ authors = ", ".join(
105
+ author.name if isinstance(author, Author) else author
106
+ for author in reference.authors
107
+ )
108
+ year = f" ({reference.year})" if reference.year is not None else ""
109
+ byline = authors + year if authors else year.strip()
110
+ link = reference.url or (
111
+ f"https://doi.org/{reference.doi}" if reference.doi else None
112
+ )
113
+ parts = (
114
+ f"{byline}." if byline else None,
115
+ reference.title,
116
+ reference.container,
117
+ reference.volume,
118
+ f"({reference.issue})" if reference.issue else None,
119
+ reference.pages,
120
+ reference.publisher,
121
+ link,
122
+ )
123
+ return Text(f"[{self.number}] " + " ".join(part for part in parts if part))
124
+
125
+
126
+ @dataclass(frozen=True)
127
+ class Bibliography(SemanticView):
128
+ """The cited works available at the chosen point in the deck."""
129
+
130
+ entries: tuple[BibliographyEntry, ...]
131
+
132
+ def body(self, context: Context) -> View:
133
+ return VStack(
134
+ *(entry.key(entry.source_key) for entry in self.entries),
135
+ spacing=context.environment[SpacingUnit],
136
+ )
137
+
138
+
139
+ @dataclass(frozen=True)
140
+ class _BibliographySelection(PrimitiveView):
141
+ sources: Mapping[str, Reference]
142
+ numbers: Variable[Mapping[str, int]]
143
+ final: bool
144
+
145
+ def expand(self, context: Context, metadata: ExpandedMetadata) -> ExpandedDeferred:
146
+ def resolve(resolved_context: Context) -> ExpandedContainer:
147
+ values = resolved_context.environment[_VARIABLE_VALUES]
148
+ numbers = values.value(self.numbers, final=self.final)
149
+ bibliography = Bibliography(
150
+ tuple(
151
+ BibliographyEntry(key, self.sources[key], number)
152
+ for key, number in numbers.items()
153
+ )
154
+ )
155
+ child = expand_view(
156
+ bibliography, resolved_context, root=metadata.view_identity
157
+ )
158
+ return ExpandedContainer(metadata, PassthroughLayout(), (child,))
159
+
160
+ return ExpandedDeferred(metadata, PassthroughLayout(), resolve, context)
161
+
162
+
163
+ class Citations:
164
+ """A catalog whose citation numbers are local to the compiled deck."""
165
+
166
+ def __init__(self, sources: Mapping[str, Reference]) -> None:
167
+ catalog = dict(sources)
168
+ for key, reference in catalog.items():
169
+ if not isinstance(key, str) or not key:
170
+ raise ValueError("Citation keys must be nonempty strings")
171
+ if not isinstance(reference, Reference):
172
+ raise TypeError("Citation sources must be Reference records")
173
+ self.sources: Mapping[str, Reference] = MappingProxyType(catalog)
174
+ self._numbers: Variable[Mapping[str, int]] = Variable(
175
+ initial=MappingProxyType({})
176
+ )
177
+
178
+ def cite(self, key: str, *, locator: str | None = None) -> Citation:
179
+ """Display a citation and register the work at its first occurrence."""
180
+ if key not in self.sources:
181
+ raise KeyError(f"Unknown citation source {key!r}")
182
+ occurrence = self._numbers.update(
183
+ lambda numbers: MappingProxyType({**numbers, key: len(numbers) + 1}),
184
+ key=key,
185
+ )
186
+ return occurrence.anchor(Citation(key, self.sources[key], occurrence, locator))
187
+
188
+ def bibliography(self, *, final: bool = False) -> View:
189
+ """List sources cited through the current build or through the whole deck."""
190
+ return _BibliographySelection(self.sources, self._numbers, final)
191
+
192
+
193
+ __all__ = [
194
+ "Author",
195
+ "Bibliography",
196
+ "BibliographyEntry",
197
+ "Citation",
198
+ "Citations",
199
+ "Reference",
200
+ ]
deckkit/compiler.py ADDED
@@ -0,0 +1,410 @@
1
+ from __future__ import annotations
2
+
3
+ from contextlib import nullcontext
4
+ from dataclasses import dataclass, field, fields, replace
5
+ from typing import TYPE_CHECKING, Any
6
+
7
+ from ._bundled_fonts import DefaultFontResolver
8
+
9
+ from .animation import (
10
+ Animation,
11
+ AnimationProgram,
12
+ BuildProgram,
13
+ EffectInstance,
14
+ EffectKind,
15
+ SlideTimeline,
16
+ TimelineStep,
17
+ Transition,
18
+ VisualState,
19
+ )
20
+ from .deck import Deck
21
+ from ._diagnostics import SlideLocation
22
+ from .drawables import (
23
+ Drawable,
24
+ DrawableGroup,
25
+ DrawableLine,
26
+ DrawablePath,
27
+ DrawableRichText,
28
+ DrawableText,
29
+ )
30
+ from .expanded_views import ExpandedView
31
+ from .fonts import FontResolver
32
+ from .geometry import Point
33
+ from .layout import LayoutContext, LayoutEngine
34
+ from .measurement import PillowMeasurer, TextMeasurer
35
+ from .reconcile import Change, reconcile, with_geometry
36
+ from .theme import Theme
37
+ from .units import Length, pt, require_length
38
+ from .views import Context, Environment, Slide, State, View
39
+
40
+ if TYPE_CHECKING:
41
+ from ._variable_evaluation import VariableBuild, VariableEvaluation
42
+ from .variables import Variable
43
+
44
+
45
+ @dataclass(frozen=True)
46
+ class CompiledView:
47
+ """One view evaluated for one state, environment and canvas.
48
+
49
+ The resolved tree preserves logical identity/properties for reconciliation;
50
+ the layout contains measured text and concrete geometry for export. Both
51
+ artifacts come from the same evaluation. This is not an animation or a
52
+ backend document, and it does not retain the source state or environment.
53
+ """
54
+
55
+ expanded_tree: ExpandedView
56
+ drawable: Drawable
57
+
58
+
59
+ @dataclass(frozen=True)
60
+ class CompiledDeck:
61
+ """Ordered logical slides, each with zero or more presentation steps."""
62
+
63
+ slides: tuple[CompiledSlide, ...]
64
+
65
+ @classmethod
66
+ def from_views(cls, *views: CompiledView) -> CompiledDeck:
67
+ """Package already-compiled single views as static logical slides."""
68
+ return cls(
69
+ tuple(CompiledSlide((view,), AnimationProgram(())) for view in views)
70
+ )
71
+
72
+ def expanding_steps(self) -> CompiledDeck:
73
+ """Return a static deck containing every animation endpoint as a slide."""
74
+ return CompiledDeck(
75
+ tuple(page for slide in self.slides for page in slide.expanding_steps())
76
+ )
77
+
78
+
79
+ @dataclass(frozen=True)
80
+ class CompiledSlide:
81
+ """One logical slide compiled at every presentation-step boundary."""
82
+
83
+ states: tuple[CompiledView, ...]
84
+ animation: AnimationProgram
85
+ label: str | None = field(default=None, compare=False, repr=False)
86
+
87
+ def __post_init__(self) -> None:
88
+ if not self.states:
89
+ raise ValueError("A compiled slide requires an initial state")
90
+ if len(self.states) != len(self.animation.builds) + 1:
91
+ raise ValueError("Compiled slide states must match its animation steps")
92
+
93
+ @property
94
+ def initial(self) -> CompiledView:
95
+ return self.states[0]
96
+
97
+ @property
98
+ def is_animated(self) -> bool:
99
+ return bool(self.animation.builds)
100
+
101
+ def expanding_steps(self) -> tuple[CompiledSlide, ...]:
102
+ """Represent every endpoint as an independent static logical slide."""
103
+ return tuple(
104
+ CompiledSlide((state,), AnimationProgram(()), label=self.label)
105
+ for state in self.states
106
+ )
107
+
108
+
109
+ @dataclass(frozen=True)
110
+ class _AnimatedDrawable:
111
+ drawable: Drawable
112
+ animation: Animation
113
+ transition: Transition | None
114
+
115
+
116
+ def _preserve_text_placement(states: list[CompiledView]) -> tuple[CompiledView, ...]:
117
+ """Use row placement for a text identity whenever any build requires it."""
118
+ row_identities = {
119
+ node.identity
120
+ for view in states
121
+ for node in view.drawable.walk()
122
+ if isinstance(node, (DrawableText, DrawableRichText))
123
+ and node.text_placement == "rows"
124
+ }
125
+ if not row_identities:
126
+ return tuple(states)
127
+
128
+ def place_rows(node: Drawable) -> Drawable:
129
+ if isinstance(node, DrawableGroup):
130
+ children = tuple(place_rows(child) for child in node.children)
131
+ if any(new is not old for new, old in zip(children, node.children)):
132
+ return replace(node, children=children)
133
+ elif isinstance(node, (DrawableText, DrawableRichText)):
134
+ if node.identity in row_identities and node.text_placement == "block":
135
+ return replace(node, text_placement="rows")
136
+ return node
137
+
138
+ return tuple(replace(view, drawable=place_rows(view.drawable)) for view in states)
139
+
140
+
141
+ def _animation_index(
142
+ root: Drawable, default: Animation
143
+ ) -> dict[str, _AnimatedDrawable]:
144
+ result: dict[str, _AnimatedDrawable] = {}
145
+
146
+ def visit(
147
+ node: Drawable,
148
+ inherited_animation: Animation,
149
+ inherited_transition: Transition | None,
150
+ ) -> None:
151
+ if node.metadata.animation_boundary:
152
+ inherited_animation = Animation.discrete()
153
+ inherited_transition = None
154
+ animation = (
155
+ node.metadata.animation
156
+ if node.metadata.animation is not None
157
+ else inherited_animation
158
+ )
159
+ transition = node.metadata.transition or inherited_transition
160
+ if isinstance(node, DrawableRichText) or (
161
+ not node.children and not isinstance(node, DrawableGroup)
162
+ ):
163
+ result[node.identity] = _AnimatedDrawable(node, animation, transition)
164
+ return
165
+ for child in node.children:
166
+ visit(child, animation, transition)
167
+
168
+ visit(root, default, None)
169
+ return result
170
+
171
+
172
+ def _visual_properties(drawable: Drawable) -> tuple[tuple[str, Any], ...]:
173
+ # Rich-text metrics describe its runs and highlights in local coordinates.
174
+ # Fallback drawables have absolute positions that change when the block moves.
175
+ ignored = {
176
+ "identity",
177
+ "bounds",
178
+ "content_bounds",
179
+ "metadata",
180
+ "children",
181
+ "_children",
182
+ }
183
+ properties = {
184
+ item.name: getattr(drawable, item.name)
185
+ for item in fields(drawable)
186
+ if item.name not in ignored
187
+ }
188
+
189
+ def local(point: Point) -> tuple[float, float]:
190
+ return (
191
+ round((point.x - drawable.bounds.x).points, 9),
192
+ round((point.y - drawable.bounds.y).points, 9),
193
+ )
194
+
195
+ # These drawables store scene-space points. Compare their geometry relative
196
+ # to their layout bounds so ordinary translations can use motion effects.
197
+ if isinstance(drawable, DrawableLine):
198
+ properties["start"] = local(drawable.start)
199
+ properties["end"] = local(drawable.end)
200
+ elif isinstance(drawable, DrawablePath):
201
+ properties["commands"] = tuple(
202
+ (type(command), tuple(local(point) for point in command.points))
203
+ for command in drawable.commands
204
+ )
205
+ clip = drawable.metadata.shadow_clip
206
+ if clip is not None:
207
+ clip = replace(clip, x=clip.x - drawable.bounds.x, y=clip.y - drawable.bounds.y)
208
+ return (
209
+ ("opacity", drawable.metadata.opacity),
210
+ ("shadow", drawable.metadata.shadow),
211
+ ("shadow_clip", clip),
212
+ *properties.items(),
213
+ )
214
+
215
+
216
+ def _compile_build(
217
+ before: CompiledView, after: CompiledView, step: TimelineStep
218
+ ) -> BuildProgram:
219
+ old = _animation_index(before.drawable, step.animation)
220
+ new = _animation_index(after.drawable, step.animation)
221
+ effects: list[EffectInstance] = []
222
+ for identity in sorted(old.keys() | new.keys()):
223
+ a, b = old.get(identity), new.get(identity)
224
+ if a is None:
225
+ assert b is not None
226
+ effects.append(
227
+ EffectInstance(
228
+ identity,
229
+ EffectKind.INSERT,
230
+ None,
231
+ VisualState(b.drawable.bounds, b.drawable),
232
+ animation=b.animation,
233
+ transition=b.transition,
234
+ )
235
+ )
236
+ elif b is None:
237
+ effects.append(
238
+ EffectInstance(
239
+ identity,
240
+ EffectKind.REMOVE,
241
+ VisualState(a.drawable.bounds, a.drawable),
242
+ None,
243
+ animation=a.animation,
244
+ transition=a.transition,
245
+ )
246
+ )
247
+ else:
248
+ if type(a.drawable) is not type(b.drawable) or _visual_properties(
249
+ a.drawable
250
+ ) != _visual_properties(b.drawable):
251
+ effects.append(
252
+ EffectInstance(
253
+ identity,
254
+ EffectKind.CHANGE,
255
+ VisualState(a.drawable.bounds, a.drawable),
256
+ VisualState(b.drawable.bounds, b.drawable),
257
+ b.animation,
258
+ )
259
+ )
260
+ elif a.drawable.bounds != b.drawable.bounds:
261
+ effects.append(
262
+ EffectInstance(
263
+ identity,
264
+ EffectKind.MOVE,
265
+ VisualState(a.drawable.bounds, a.drawable),
266
+ VisualState(b.drawable.bounds, b.drawable),
267
+ b.animation,
268
+ )
269
+ )
270
+ return BuildProgram(step.trigger, tuple(effects))
271
+
272
+
273
+ class Compiler:
274
+ def __init__(
275
+ self,
276
+ theme: Theme,
277
+ *,
278
+ width: Length = pt(960),
279
+ height: Length = pt(540),
280
+ measurer: TextMeasurer | None = None,
281
+ font_resolver: FontResolver | None = None,
282
+ ) -> None:
283
+ require_length(width)
284
+ require_length(height)
285
+ self.environment = Environment(theme)
286
+ self.width, self.height = width, height
287
+ self.measurer = measurer if measurer is not None else PillowMeasurer()
288
+ self.font_resolver = (
289
+ font_resolver if font_resolver is not None else DefaultFontResolver()
290
+ )
291
+ self.layout_engine = LayoutEngine(
292
+ LayoutContext(self.measurer, self.font_resolver)
293
+ )
294
+
295
+ def compile_view(
296
+ self, view: View, state: State | None = None, *, slide_number: int = 1
297
+ ) -> CompiledView:
298
+ evaluation = self._variable_evaluation(slide_number)
299
+ slide = view if isinstance(view, Slide) else None
300
+ location = (
301
+ SlideLocation(slide_number, slide._diagnostic_label()) if slide else None
302
+ )
303
+ with location.context(0) if location else nullcontext():
304
+ evaluation.begin_slide(slide)
305
+ build = evaluation.expand(
306
+ view, Context(state if state is not None else State(), self.environment)
307
+ )
308
+ return self._layout_build(evaluation, build)
309
+
310
+ @staticmethod
311
+ def _variable_evaluation(
312
+ slide_number: int, variables: tuple[Variable[Any], ...] = ()
313
+ ) -> VariableEvaluation:
314
+ from ._variable_evaluation import VariableEvaluation
315
+
316
+ if isinstance(slide_number, bool) or not isinstance(slide_number, int):
317
+ raise TypeError("Slide number must be an integer")
318
+ if slide_number < 1:
319
+ raise ValueError("Slide number must be positive")
320
+ return VariableEvaluation(variables, first_slide_number=slide_number)
321
+
322
+ def _layout_build(
323
+ self, evaluation: VariableEvaluation, build: VariableBuild
324
+ ) -> CompiledView:
325
+ expanded_tree = evaluation.resolve(build)
326
+ return CompiledView(
327
+ expanded_tree,
328
+ self.layout_engine.layout_view(expanded_tree, self.width, self.height),
329
+ )
330
+
331
+ def compile_slide(
332
+ self, slide: Slide, state: State | None = None, *, slide_number: int = 1
333
+ ) -> CompiledSlide:
334
+ """Compile a slide's initial state and all declared timeline steps."""
335
+ evaluation = self._variable_evaluation(slide_number)
336
+ if not isinstance(slide, Slide):
337
+ raise TypeError("compile_slide() requires a Slide")
338
+ location = SlideLocation(slide_number, slide._diagnostic_label())
339
+ timeline, builds = self._expand_slide(evaluation, slide, state, location)
340
+ return self._layout_slide(evaluation, timeline, builds, location)
341
+
342
+ def _expand_slide(
343
+ self,
344
+ evaluation: VariableEvaluation,
345
+ slide: Slide,
346
+ state: State | None,
347
+ location: SlideLocation,
348
+ ) -> tuple[SlideTimeline, tuple[VariableBuild, ...]]:
349
+ shared = state if state is not None else State()
350
+ with location.context():
351
+ timeline = slide.timeline()
352
+ if not isinstance(timeline, SlideTimeline):
353
+ raise TypeError("Slide.timeline() must return SlideTimeline")
354
+ evaluation.begin_slide(slide)
355
+ builds = []
356
+ for index, local in enumerate(
357
+ (timeline.initial, *(step.state for step in timeline.subsequent))
358
+ ):
359
+ with location.context(index):
360
+ builds.append(
361
+ evaluation.expand(
362
+ slide, Context(shared.merging(local), self.environment)
363
+ )
364
+ )
365
+ return timeline, tuple(builds)
366
+
367
+ def _layout_slide(
368
+ self,
369
+ evaluation: VariableEvaluation,
370
+ timeline: SlideTimeline,
371
+ builds: tuple[VariableBuild, ...],
372
+ location: SlideLocation,
373
+ ) -> CompiledSlide:
374
+ layouts = []
375
+ for index, build in enumerate(builds):
376
+ with location.context(index):
377
+ layouts.append(self._layout_build(evaluation, build))
378
+ with location.context():
379
+ states = _preserve_text_placement(layouts)
380
+ programs = []
381
+ for index, (before, after, step) in enumerate(
382
+ zip(states, states[1:], timeline.subsequent), start=1
383
+ ):
384
+ with location.context(index):
385
+ programs.append(_compile_build(before, after, step))
386
+ return CompiledSlide(
387
+ states, AnimationProgram(tuple(programs)), label=location.label
388
+ )
389
+
390
+ def compile_deck(self, deck: Deck, state: State | None = None) -> CompiledDeck:
391
+ """Compile every slide timeline, overlaying it on optional shared state."""
392
+ evaluation = self._variable_evaluation(1, deck.variables)
393
+ slides = []
394
+ for number, slide in enumerate(deck, start=1):
395
+ location = SlideLocation(number, slide._diagnostic_label())
396
+ timeline, builds = self._expand_slide(evaluation, slide, state, location)
397
+ slides.append((location, timeline, builds))
398
+ return CompiledDeck(
399
+ tuple(
400
+ self._layout_slide(evaluation, timeline, builds, location)
401
+ for location, timeline, builds in slides
402
+ )
403
+ )
404
+
405
+ def changes(self, before: CompiledView, after: CompiledView) -> tuple[Change, ...]:
406
+ return with_geometry(
407
+ reconcile(before.expanded_tree, after.expanded_tree),
408
+ before.drawable,
409
+ after.drawable,
410
+ )
deckkit/context.py ADDED
@@ -0,0 +1,72 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Iterator, Mapping
4
+ from dataclasses import dataclass, field
5
+ from types import MappingProxyType
6
+ from typing import TYPE_CHECKING, Any, TypeVar
7
+
8
+ from .tokens import DesignToken, TokenAssignment, TokenResolver
9
+
10
+ if TYPE_CHECKING:
11
+ from .theme import Theme
12
+
13
+ T = TypeVar("T")
14
+
15
+
16
+ class State(Mapping[str, Any]):
17
+ def __init__(self, **values: Any) -> None:
18
+ self._values = MappingProxyType(values)
19
+
20
+ def __getitem__(self, key: str) -> Any:
21
+ return self._values[key]
22
+
23
+ def __iter__(self) -> Iterator[str]:
24
+ return iter(self._values)
25
+
26
+ def __len__(self) -> int:
27
+ return len(self._values)
28
+
29
+ def merging(self, overrides: State) -> State:
30
+ """Return a snapshot in which slide-local values override shared values."""
31
+ return State(**{**self._values, **overrides._values})
32
+
33
+
34
+ @dataclass(frozen=True)
35
+ class Environment:
36
+ """The active inherited design-token resolution scope."""
37
+
38
+ theme: Theme
39
+ _tokens: TokenResolver | None = field(default=None, repr=False, compare=False)
40
+
41
+ def __post_init__(self) -> None:
42
+ if self._tokens is None:
43
+ object.__setattr__(self, "_tokens", self.theme.token_resolver())
44
+
45
+ def __getitem__(self, token: DesignToken[T]) -> T:
46
+ """Resolve a design token against this inherited scope."""
47
+ assert self._tokens is not None
48
+ return self._tokens[token]
49
+
50
+ def get(self, token: DesignToken[T]) -> T:
51
+ """Resolve a design token using method-call syntax."""
52
+ return self[token]
53
+
54
+ def with_token(
55
+ self, token: DesignToken[T], assignment: TokenAssignment[T]
56
+ ) -> Environment:
57
+ """Return a child scope with one token override."""
58
+ assert self._tokens is not None
59
+ return Environment(self.theme, self._tokens.with_token(token, assignment))
60
+
61
+ def with_tokens(
62
+ self, overrides: Mapping[DesignToken[Any], TokenAssignment[Any]]
63
+ ) -> Environment:
64
+ """Return a child scope with a group of token overrides."""
65
+ assert self._tokens is not None
66
+ return Environment(self.theme, self._tokens.with_tokens(overrides))
67
+
68
+
69
+ @dataclass(frozen=True)
70
+ class Context:
71
+ state: State
72
+ environment: Environment