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/measurement.py ADDED
@@ -0,0 +1,420 @@
1
+ """Real shaped font metrics behind a replaceable measurement interface."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterator
6
+ from dataclasses import dataclass, replace
7
+ from functools import lru_cache
8
+ from pathlib import Path
9
+ from re import finditer
10
+ from typing import Literal, Protocol
11
+ from warnings import warn
12
+
13
+ import uharfbuzz as hb
14
+ from PIL import ImageFont
15
+ from regex import compile as compile_regex
16
+
17
+ from .fonts import Font, FontResolver, ResolvedFont
18
+ from .units import Length, pt, require_length
19
+
20
+ TextFlow = Literal["wrapped", "verbatim"]
21
+ _GRAPHEMES = compile_regex(r"\X")
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class StyledTextSpan:
26
+ text: str
27
+ font: Font
28
+ size: Length
29
+ line_spacing: float
30
+ color: str
31
+ background: str | None = None
32
+ line_height: Length | None = None
33
+ fallback_fonts: tuple[Font, ...] = ()
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class StyledTextLine:
38
+ spans: tuple[StyledTextSpan, ...]
39
+ background: str | None = None
40
+
41
+
42
+ @dataclass(frozen=True)
43
+ class MeasuredTextRun:
44
+ text: str
45
+ x: Length
46
+ width: Length
47
+ metrics: MeasuredText
48
+ font: ResolvedFont
49
+ requested_font: Font
50
+ font_size: Length
51
+ color: str
52
+ background: str | None
53
+ explicit_typeface: bool = False
54
+
55
+
56
+ @dataclass(frozen=True)
57
+ class MeasuredTextLine:
58
+ runs: tuple[MeasuredTextRun, ...]
59
+ width: Length
60
+ height: Length
61
+ baseline: Length
62
+ background: str | None
63
+
64
+
65
+ @dataclass(frozen=True)
66
+ class MeasuredRichText:
67
+ lines: tuple[MeasuredTextLine, ...]
68
+ width: Length
69
+ height: Length
70
+
71
+
72
+ @dataclass(frozen=True)
73
+ class MeasuredText:
74
+ lines: tuple[str, ...]
75
+ width: Length
76
+ height: Length
77
+ ascent: Length
78
+ line_height: Length
79
+ family: str
80
+ style: str
81
+ cap_height: Length | None = None
82
+ descent: Length | None = None
83
+
84
+ @property
85
+ def baseline(self) -> Length:
86
+ """Distance from the top of a line to its baseline."""
87
+ return _baseline_offset(self.ascent, self.descent, self.line_height)
88
+
89
+ def with_line_height(self, height: Length | None) -> MeasuredText:
90
+ """Apply an exact line height while preserving the measured glyph metrics."""
91
+ if height is None:
92
+ return self
93
+ return replace(self, line_height=height, height=height * len(self.lines))
94
+
95
+
96
+ def _baseline_offset(ascent: Length, descent: Length | None, height: Length) -> Length:
97
+ if descent is None:
98
+ return ascent
99
+ return ascent + (height - ascent - descent) / 2
100
+
101
+
102
+ class TextMeasurer(Protocol):
103
+ def measure(
104
+ self,
105
+ text: str,
106
+ face: ResolvedFont,
107
+ size: Length,
108
+ width: Length,
109
+ line_spacing: float,
110
+ flow: TextFlow = "wrapped",
111
+ ) -> MeasuredText: ...
112
+
113
+
114
+ @lru_cache(maxsize=128)
115
+ def _shaping_font(path: str, index: int) -> hb.Font:
116
+ return hb.Font(hb.Face(Path(path).read_bytes(), index))
117
+
118
+
119
+ def _shape(text: str, font: hb.Font) -> hb.Buffer:
120
+ buffer = hb.Buffer()
121
+ buffer.add_str(text)
122
+ buffer.guess_segment_properties()
123
+ hb.shape(font, buffer)
124
+ return buffer
125
+
126
+
127
+ @lru_cache(maxsize=2048)
128
+ def _missing_clusters(
129
+ text: str, face: ResolvedFont
130
+ ) -> tuple[frozenset[int], frozenset[int]]:
131
+ if not text:
132
+ return frozenset(), frozenset()
133
+ glyphs = _shape(text, _shaping_font(face.path, face.index)).glyph_infos
134
+ return (
135
+ frozenset(glyph.cluster for glyph in glyphs),
136
+ frozenset(glyph.cluster for glyph in glyphs if glyph.codepoint == 0),
137
+ )
138
+
139
+
140
+ def _font_runs(
141
+ text: str, source: StyledTextSpan, resolver: FontResolver, font_sample: str
142
+ ) -> Iterator[tuple[str, Font, ResolvedFont]]:
143
+ primary = resolver.resolve(source.font)
144
+ if not source.fallback_fonts or not text:
145
+ yield text, source.font, primary
146
+ return
147
+
148
+ if font_sample:
149
+ # A live field can only carry one typeface, even if its value changes.
150
+ for request in (source.font, *source.fallback_fonts):
151
+ face = resolver.resolve(request)
152
+ if not _missing_clusters(font_sample, face)[1]:
153
+ yield text, request, face
154
+ return
155
+ yield text, source.font, primary
156
+ return
157
+
158
+ clusters, missing = _missing_clusters(text, primary)
159
+ if not missing:
160
+ yield text, source.font, primary
161
+ return
162
+
163
+ # Split only at boundaries shared by HarfBuzz and Unicode grapheme clusters.
164
+ boundaries = [0]
165
+ boundaries.extend(
166
+ match.start()
167
+ for match in _GRAPHEMES.finditer(text)
168
+ if match.start() and match.start() in clusters
169
+ )
170
+ boundaries.append(len(text))
171
+ missing_starts = iter(sorted(missing))
172
+ next_missing = next(missing_starts, len(text))
173
+ run_start = 0
174
+ current = (source.font, primary)
175
+ for start, end in zip(boundaries, boundaries[1:]):
176
+ selected = (source.font, primary)
177
+ if next_missing < end:
178
+ while next_missing < end:
179
+ next_missing = next(missing_starts, len(text))
180
+ for request in source.fallback_fonts:
181
+ face = resolver.resolve(request)
182
+ if not _missing_clusters(text[start:end], face)[1]:
183
+ selected = (request, face)
184
+ break
185
+ if start == 0:
186
+ current = selected
187
+ elif current != selected:
188
+ yield text[run_start:start], *current
189
+ run_start, current = start, selected
190
+ yield text[run_start:], *current
191
+
192
+
193
+ class PillowMeasurer:
194
+ @staticmethod
195
+ @lru_cache(maxsize=128)
196
+ def _font(path: str, index: int, size: float) -> ImageFont.FreeTypeFont:
197
+ return ImageFont.truetype(
198
+ path, round(size * 4), index=index, layout_engine=ImageFont.Layout.BASIC
199
+ )
200
+
201
+ @staticmethod
202
+ @lru_cache(maxsize=2048)
203
+ def measure(
204
+ text: str,
205
+ face: ResolvedFont,
206
+ size: Length,
207
+ width: Length,
208
+ line_spacing: float = 1.1,
209
+ flow: TextFlow = "wrapped",
210
+ ) -> MeasuredText:
211
+ require_length(size)
212
+ require_length(width)
213
+ font = PillowMeasurer._font(face.path, face.index, size.points)
214
+ shaping_font = _shaping_font(face.path, face.index)
215
+
216
+ def length(value: str, *, check_coverage: bool = False) -> float:
217
+ if not value:
218
+ return 0.0
219
+ buffer = _shape(value, shaping_font)
220
+ if check_coverage and any(
221
+ info.codepoint == 0 for info in buffer.glyph_infos
222
+ ):
223
+ warn(
224
+ f"Measured font {font.getname()} is missing glyphs in {value!r}",
225
+ stacklevel=2,
226
+ )
227
+ return float(
228
+ sum(p.x_advance for p in buffer.glyph_positions)
229
+ * size.points
230
+ / shaping_font.face.upem
231
+ )
232
+
233
+ if flow == "verbatim":
234
+ lines = text.expandtabs(4).split("\n")
235
+ else:
236
+ lines = []
237
+ for paragraph in text.split("\n"):
238
+ line = ""
239
+ for word in paragraph.split():
240
+ candidate = f"{line} {word}" if line else word
241
+ if line and length(candidate) > width.points:
242
+ lines.append(line)
243
+ line = word
244
+ else:
245
+ line = candidate
246
+ lines.append(line)
247
+ ascent, descent = (v / 4 for v in font.getmetrics())
248
+ line_height = (ascent + descent) * line_spacing
249
+ family, style = font.getname()
250
+ cap_height = shaping_font.get_metric_position(hb.OTMetricsTag.CAP_HEIGHT)
251
+ if cap_height is None or cap_height <= 0:
252
+ glyph = shaping_font.get_nominal_glyph(ord("H"))
253
+ extents = (
254
+ shaping_font.get_glyph_extents(glyph) if glyph is not None else None
255
+ )
256
+ cap_height = extents.y_bearing if extents is not None else None
257
+ return MeasuredText(
258
+ tuple(lines),
259
+ pt(max((length(line, check_coverage=True) for line in lines), default=0)),
260
+ pt(len(lines) * line_height),
261
+ pt(ascent),
262
+ pt(line_height),
263
+ family or face.family,
264
+ style or "Regular",
265
+ pt(cap_height * size.points / shaping_font.face.upem)
266
+ if cap_height is not None and cap_height > 0
267
+ else None,
268
+ descent=pt(descent),
269
+ )
270
+
271
+
272
+ def layout_styled_text(
273
+ measurer: TextMeasurer,
274
+ resolver: FontResolver,
275
+ lines: tuple[StyledTextLine, ...],
276
+ width: Length,
277
+ flow: TextFlow,
278
+ *,
279
+ font_sample: str = "",
280
+ ) -> MeasuredRichText:
281
+ """Shape and wrap styled logical lines into positioned visual runs."""
282
+
283
+ @dataclass(frozen=True)
284
+ class Piece:
285
+ text: str
286
+ source: StyledTextSpan
287
+ font: ResolvedFont
288
+ requested_font: Font
289
+ metrics: MeasuredText
290
+
291
+ @property
292
+ def width(self) -> Length:
293
+ return self.metrics.width
294
+
295
+ def measure_pieces(text: str, source: StyledTextSpan) -> Iterator[Piece]:
296
+ for value, request, font in _font_runs(text, source, resolver, font_sample):
297
+ metrics = measurer.measure(
298
+ value, font, source.size, width, source.line_spacing, "verbatim"
299
+ )
300
+ yield Piece(
301
+ value,
302
+ source,
303
+ font,
304
+ request,
305
+ metrics.with_line_height(source.line_height),
306
+ )
307
+
308
+ def words(line: StyledTextLine) -> list[tuple[Piece | None, list[Piece]]]:
309
+ result: list[tuple[Piece | None, list[Piece]]] = []
310
+ pending_space: Piece | None = None
311
+ current: list[Piece] = []
312
+ for span in line.spans:
313
+ for match in finditer(r"\s+|\S+", span.text):
314
+ value = match.group()
315
+ if value.isspace():
316
+ if current:
317
+ result.append((pending_space, current))
318
+ current = []
319
+ pending_space = next(measure_pieces(" ", span))
320
+ else:
321
+ current.extend(measure_pieces(value, span))
322
+ if current:
323
+ result.append((pending_space, current))
324
+ return result
325
+
326
+ def preserved(line: StyledTextLine) -> list[Piece]:
327
+ result: list[Piece] = []
328
+ column = 0
329
+ for span in line.spans:
330
+ value = ""
331
+ for character in span.text:
332
+ if character == "\t":
333
+ spaces = 4 - column % 4
334
+ value += " " * spaces
335
+ column += spaces
336
+ else:
337
+ value += character
338
+ column += 1
339
+ if value or not result:
340
+ result.extend(measure_pieces(value, span))
341
+ return result
342
+
343
+ def visual(
344
+ pieces: list[Piece],
345
+ background: str | None,
346
+ fallback: StyledTextSpan,
347
+ ) -> MeasuredTextLine:
348
+ if not pieces:
349
+ pieces = [next(measure_pieces("", fallback))]
350
+ ascent = max((item.metrics.ascent for item in pieces), default=pt(0))
351
+ height = max((item.metrics.line_height for item in pieces), default=pt(0))
352
+ if any(item.requested_font != item.source.font for item in pieces):
353
+ height = max(
354
+ [
355
+ height,
356
+ *(
357
+ ascent + item.metrics.line_height - item.metrics.ascent
358
+ for item in pieces
359
+ if item.source.line_height is None
360
+ ),
361
+ ]
362
+ )
363
+ descents = [item.metrics.descent for item in pieces]
364
+ descent = (
365
+ max(value for value in descents if value is not None)
366
+ if None not in descents
367
+ else None
368
+ )
369
+ baseline = _baseline_offset(ascent, descent, height)
370
+ x = pt(0)
371
+ runs = []
372
+ for item in pieces:
373
+ runs.append(
374
+ MeasuredTextRun(
375
+ item.text,
376
+ x,
377
+ item.width,
378
+ item.metrics,
379
+ item.font,
380
+ item.requested_font,
381
+ item.source.size,
382
+ item.source.color,
383
+ item.source.background,
384
+ bool(item.source.fallback_fonts),
385
+ )
386
+ )
387
+ x += item.width
388
+ return MeasuredTextLine(tuple(runs), x, height, baseline, background)
389
+
390
+ visual_lines: list[MeasuredTextLine] = []
391
+ for logical in lines:
392
+ if flow == "verbatim":
393
+ visual_lines.append(
394
+ visual(preserved(logical), logical.background, logical.spans[0])
395
+ )
396
+ continue
397
+ current: list[Piece] = []
398
+ current_width = pt(0)
399
+ for separator, word in words(logical):
400
+ separator_width = (
401
+ separator.width if separator is not None and current else pt(0)
402
+ )
403
+ word_width = sum((item.width for item in word), pt(0))
404
+ if current and current_width + separator_width + word_width > width:
405
+ visual_lines.append(
406
+ visual(current, logical.background, logical.spans[0])
407
+ )
408
+ current, current_width = [], pt(0)
409
+ separator_width = pt(0)
410
+ if separator is not None and current:
411
+ current.append(separator)
412
+ current_width += separator_width
413
+ current.extend(word)
414
+ current_width += word_width
415
+ visual_lines.append(visual(current, logical.background, logical.spans[0]))
416
+ return MeasuredRichText(
417
+ tuple(visual_lines),
418
+ max((line.width for line in visual_lines), default=pt(0)),
419
+ sum((line.height for line in visual_lines), pt(0)),
420
+ )
deckkit/paint.py ADDED
@@ -0,0 +1,73 @@
1
+ """Author-facing gradients and their resolved paint data."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from math import isfinite
7
+
8
+ from .context import Environment
9
+ from .theme import Color, ColorStyle
10
+
11
+
12
+ @dataclass(frozen=True)
13
+ class GradientStop:
14
+ color: ColorStyle
15
+ offset: float
16
+ opacity: float = 1.0
17
+
18
+ def __post_init__(self) -> None:
19
+ if not 0 <= self.offset <= 1:
20
+ raise ValueError("Gradient offsets must be between zero and one")
21
+ if not 0 <= self.opacity <= 1:
22
+ raise ValueError("Gradient opacity must be between zero and one")
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class ResolvedGradientStop:
27
+ color: str
28
+ offset: float
29
+ opacity: float
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class ResolvedLinearGradient:
34
+ stops: tuple[ResolvedGradientStop, ...]
35
+ angle: float
36
+
37
+
38
+ @dataclass(frozen=True)
39
+ class LinearGradient:
40
+ """A linear fill with an angle in clockwise degrees from the positive x-axis."""
41
+
42
+ stops: tuple[GradientStop, ...]
43
+ angle: float = 0.0
44
+
45
+ def __post_init__(self) -> None:
46
+ stops = tuple(self.stops)
47
+ if len(stops) < 2:
48
+ raise ValueError("A linear gradient requires at least two stops")
49
+ if not all(isinstance(stop, GradientStop) for stop in stops):
50
+ raise TypeError("A linear gradient takes GradientStop values")
51
+ if any(a.offset > b.offset for a, b in zip(stops, stops[1:])):
52
+ raise ValueError("Gradient stops must be in ascending offset order")
53
+ if not isfinite(self.angle):
54
+ raise ValueError("Gradient angle must be finite")
55
+ object.__setattr__(self, "stops", stops)
56
+ object.__setattr__(self, "angle", self.angle % 360)
57
+
58
+ def resolve(self, environment: Environment) -> ResolvedLinearGradient:
59
+ return ResolvedLinearGradient(
60
+ tuple(
61
+ ResolvedGradientStop(
62
+ (
63
+ stop.color
64
+ if isinstance(stop.color, Color)
65
+ else environment[stop.color]
66
+ ).hex,
67
+ stop.offset,
68
+ stop.opacity,
69
+ )
70
+ for stop in self.stops
71
+ ),
72
+ self.angle,
73
+ )
deckkit/py.typed ADDED
File without changes
deckkit/reconcile.py ADDED
@@ -0,0 +1,119 @@
1
+ """Logical reconciliation first; geometry enrichment is a separate pass."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping, Sequence
6
+ from dataclasses import dataclass, fields
7
+ from typing import Any, Literal, TypeVar
8
+
9
+ from .animation import Animation, Transition
10
+ from .drawables import Bounds, Drawable
11
+ from .expanded_views import ExpandedView
12
+
13
+
14
+ @dataclass(frozen=True)
15
+ class Change:
16
+ identity: str
17
+ kind: Literal["insert", "remove", "properties", "reparent", "bounds"]
18
+ before: Mapping[str, Any] | Bounds | str | None = None
19
+ after: Mapping[str, Any] | Bounds | str | None = None
20
+ animation: Animation | None = None
21
+ transition: Transition | None = None
22
+
23
+
24
+ TreeT = TypeVar("TreeT", ExpandedView, Drawable)
25
+
26
+
27
+ def _properties(node: ExpandedView) -> dict[str, Any]:
28
+ tracked = {
29
+ item.name: getattr(node.metadata, item.name)
30
+ for item in fields(node.metadata)
31
+ if item.metadata.get("tracked", False)
32
+ }
33
+ tracked.update(
34
+ {
35
+ item.name: getattr(node, item.name)
36
+ for item in fields(node)
37
+ if item.metadata.get("tracked", False)
38
+ }
39
+ )
40
+ return tracked
41
+
42
+
43
+ def _index(root: TreeT) -> tuple[dict[str, TreeT], dict[str, str | None]]:
44
+ nodes: dict[str, TreeT] = {}
45
+ parents: dict[str, str | None] = {}
46
+
47
+ def visit(node: TreeT, parent: str | None) -> None:
48
+ nodes[node.identity] = node
49
+ parents[node.identity] = parent
50
+ for ch in node.children:
51
+ visit(ch, node.identity)
52
+
53
+ visit(root, None)
54
+ return nodes, parents
55
+
56
+
57
+ def reconcile(before: ExpandedView, after: ExpandedView) -> tuple[Change, ...]:
58
+ old, op = _index(before)
59
+ new, np = _index(after)
60
+ changes = []
61
+ for key in sorted(old.keys() | new.keys()):
62
+ a, b = old.get(key), new.get(key)
63
+ if a is None:
64
+ assert b is not None
65
+ changes.append(
66
+ Change(
67
+ key,
68
+ "insert",
69
+ after=_properties(b),
70
+ transition=b.transition,
71
+ )
72
+ )
73
+ elif b is None:
74
+ changes.append(
75
+ Change(
76
+ key,
77
+ "remove",
78
+ before=_properties(a),
79
+ transition=a.transition,
80
+ )
81
+ )
82
+ else:
83
+ if (
84
+ type(a) is not type(b)
85
+ or _properties(a) != _properties(b)
86
+ or a.modifiers != b.modifiers
87
+ ):
88
+ changes.append(
89
+ Change(
90
+ key,
91
+ "properties",
92
+ _properties(a),
93
+ _properties(b),
94
+ b.animation,
95
+ )
96
+ )
97
+ if op[key] != np[key]:
98
+ changes.append(Change(key, "reparent", op[key], np[key]))
99
+ return tuple(changes)
100
+
101
+
102
+ def with_geometry(
103
+ changes: Sequence[Change], before: Drawable, after: Drawable
104
+ ) -> tuple[Change, ...]:
105
+ old, _ = _index(before)
106
+ new, _ = _index(after)
107
+ result = list(changes)
108
+ for key in sorted(old.keys() & new.keys()):
109
+ if old[key].bounds != new[key].bounds:
110
+ result.append(
111
+ Change(
112
+ key,
113
+ "bounds",
114
+ old[key].bounds,
115
+ new[key].bounds,
116
+ new[key].metadata.animation,
117
+ )
118
+ )
119
+ return tuple(result)
deckkit/semantic.py ADDED
@@ -0,0 +1,47 @@
1
+ """Convenience exports; implementations live in deckkit.views.semantic."""
2
+
3
+ from .views.semantic import (
4
+ BeforeAfter,
5
+ BulletBand,
6
+ BulletGraph,
7
+ Card,
8
+ CellStyle,
9
+ ColumnWidth,
10
+ EstimateInterval,
11
+ ItemList,
12
+ ListItem,
13
+ Metric,
14
+ Pill,
15
+ Pipeline,
16
+ PipelineStage,
17
+ RowStyle,
18
+ SemanticView,
19
+ Sparkline,
20
+ Table,
21
+ TableColumn,
22
+ Timeline,
23
+ TimelineEvent,
24
+ )
25
+
26
+ __all__ = [
27
+ "BeforeAfter",
28
+ "BulletBand",
29
+ "BulletGraph",
30
+ "Card",
31
+ "CellStyle",
32
+ "ColumnWidth",
33
+ "EstimateInterval",
34
+ "ItemList",
35
+ "ListItem",
36
+ "Metric",
37
+ "Pill",
38
+ "Pipeline",
39
+ "PipelineStage",
40
+ "RowStyle",
41
+ "SemanticView",
42
+ "Sparkline",
43
+ "Table",
44
+ "TableColumn",
45
+ "Timeline",
46
+ "TimelineEvent",
47
+ ]