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
@@ -0,0 +1,642 @@
1
+ """Present line changes from source snippets or hand-authored hunks."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable, Iterator, Sequence
6
+ from dataclasses import dataclass, field, replace
7
+ from difflib import SequenceMatcher
8
+ from itertools import groupby, zip_longest
9
+ from typing import Literal
10
+
11
+ from ...context import Context
12
+ from ...identity import ViewIdentity
13
+ from ...layout import (
14
+ FIRST_BASELINE,
15
+ Layout,
16
+ LayoutChild,
17
+ LayoutContext,
18
+ LayoutOverflow,
19
+ LayoutPlan,
20
+ Placement,
21
+ ProposedSize,
22
+ )
23
+ from ...theme import (
24
+ CodeTextStyle,
25
+ Color,
26
+ ColorStyle,
27
+ MutedColor,
28
+ PrimaryColor,
29
+ SpacingUnit,
30
+ SurfaceColor,
31
+ Typography,
32
+ )
33
+ from ...tokens import DesignToken, TokenResolver
34
+ from ...units import Length, pt, require_length
35
+ from .._code_source import _code_text, _highlight_lines, _source_lines
36
+ from ..code import CodeHighlighter, CodeLine, _resolve_code_line, _scope
37
+ from ..layout_view import LayoutView
38
+ from ..modifier_views import FrameMaximum, unbounded
39
+ from ..rectangle import Rectangle
40
+ from ..text import Text
41
+ from ..view import View
42
+ from .semantic_view import StyledSemanticView
43
+
44
+ DiffRole = Literal["context", "added", "removed"]
45
+ DiffLayout = Literal["unified", "split"]
46
+
47
+
48
+ def _single_line(value: str, name: str) -> None:
49
+ if not isinstance(value, str):
50
+ raise TypeError(f"{name} must be a string")
51
+ if "\n" in value or "\r" in value:
52
+ raise ValueError(f"{name} must be a single line")
53
+
54
+
55
+ @dataclass(frozen=True)
56
+ class DiffLine:
57
+ """One source line with optional one-based source numbers and a build key.
58
+
59
+ For context lines, old_content can supply different syntax spans for the
60
+ old side of a split diff. Both versions must have the same source text.
61
+ """
62
+
63
+ role: DiffRole
64
+ content: str | CodeLine
65
+ old_number: int | None = None
66
+ new_number: int | None = None
67
+ key: str | int | None = None
68
+ old_content: CodeLine | None = None
69
+
70
+ def __post_init__(self) -> None:
71
+ if self.role not in ("context", "added", "removed"):
72
+ raise ValueError(f"Unknown diff line role: {self.role!r}")
73
+ _single_line(self.text, "DiffLine content")
74
+ for number in (self.old_number, self.new_number):
75
+ if number is not None and (type(number) is not int or number < 1):
76
+ raise ValueError("Diff line numbers must be positive integers")
77
+ if self.role == "added" and self.old_number is not None:
78
+ raise ValueError("An added line cannot have an old number")
79
+ if self.role == "removed" and self.new_number is not None:
80
+ raise ValueError("A removed line cannot have a new number")
81
+ if self.old_content is not None and (
82
+ self.role != "context"
83
+ or not isinstance(self.old_content, CodeLine)
84
+ or _code_text(self.old_content) != self.text
85
+ ):
86
+ raise ValueError(
87
+ "old_content requires a context CodeLine with matching text"
88
+ )
89
+
90
+ @property
91
+ def text(self) -> str:
92
+ """The source text shared by all renderings of the line."""
93
+ return (
94
+ _code_text(self.content)
95
+ if isinstance(self.content, CodeLine)
96
+ else self.content
97
+ )
98
+
99
+
100
+ def _check_keys(keys: Sequence[str | int | None], name: str) -> None:
101
+ explicit = [str(key) for key in keys if key is not None]
102
+ if len(explicit) != len(set(explicit)):
103
+ raise ValueError(f"{name} keys must be unique")
104
+
105
+
106
+ @dataclass(frozen=True, init=False)
107
+ class DiffHunk:
108
+ """A contiguous excerpt with an optional header and build key."""
109
+
110
+ lines: tuple[DiffLine, ...]
111
+ header: str | None
112
+ key: str | int | None
113
+
114
+ def __init__(
115
+ self,
116
+ *lines: DiffLine,
117
+ header: str | None = None,
118
+ key: str | int | None = None,
119
+ ) -> None:
120
+ if not lines:
121
+ raise ValueError("A diff hunk requires at least one line")
122
+ if not all(isinstance(line, DiffLine) for line in lines):
123
+ raise TypeError("DiffHunk accepts DiffLine values")
124
+ if header is not None:
125
+ _single_line(header, "DiffHunk header")
126
+ _check_keys([line.key for line in lines], "Diff line")
127
+ object.__setattr__(self, "lines", lines)
128
+ object.__setattr__(self, "header", header)
129
+ object.__setattr__(self, "key", key)
130
+
131
+
132
+ @dataclass(frozen=True, init=False)
133
+ class Diff(StyledSemanticView["Diff.Style"]):
134
+ """Show source changes as one listing or two aligned columns."""
135
+
136
+ @dataclass(frozen=True)
137
+ class LineStyle:
138
+ """Control a role's marker, text, fill, and leading rule independently."""
139
+
140
+ marker: str = ""
141
+ foreground: ColorStyle | None = None
142
+ background: ColorStyle | None = None
143
+ accent: ColorStyle | None = None
144
+ marker_foreground: ColorStyle | None = None
145
+
146
+ def __post_init__(self) -> None:
147
+ _single_line(self.marker, "Diff marker")
148
+
149
+ @dataclass(frozen=True)
150
+ class Style:
151
+ typography: Typography
152
+ background: ColorStyle = SurfaceColor
153
+ foreground: ColorStyle = PrimaryColor
154
+ number_foreground: ColorStyle = MutedColor
155
+ hunk_foreground: ColorStyle = MutedColor
156
+ hunk_background: ColorStyle | None = None
157
+ divider: ColorStyle | None = MutedColor
158
+ context: Diff.LineStyle = field(default_factory=lambda: Diff.LineStyle())
159
+ added: Diff.LineStyle = field(
160
+ default_factory=lambda: Diff.LineStyle(marker="+")
161
+ )
162
+ removed: Diff.LineStyle = field(
163
+ default_factory=lambda: Diff.LineStyle(marker="−")
164
+ )
165
+ show_line_numbers: bool = True
166
+ show_hunk_headers: bool = True
167
+ empty_message: str = "No changes"
168
+ padding: Length = pt(12)
169
+ row_padding: Length = pt(2)
170
+ gutter_spacing: Length = pt(8)
171
+ hunk_spacing: Length = pt(6)
172
+ column_gap: Length = pt(8)
173
+ accent_width: Length = pt(2)
174
+ divider_width: Length = pt(1)
175
+
176
+ def __post_init__(self) -> None:
177
+ _single_line(self.empty_message, "Diff empty message")
178
+ for value in (
179
+ self.padding,
180
+ self.row_padding,
181
+ self.gutter_spacing,
182
+ self.hunk_spacing,
183
+ self.column_gap,
184
+ self.accent_width,
185
+ self.divider_width,
186
+ ):
187
+ require_length(value)
188
+ if value < pt(0):
189
+ raise ValueError("Diff style lengths must be nonnegative")
190
+
191
+ @staticmethod
192
+ def _default_style(values: TokenResolver) -> Style:
193
+ surface = values[SurfaceColor]
194
+ muted = values[MutedColor]
195
+ spacing = values[SpacingUnit]
196
+ return Diff.Style(
197
+ values[CodeTextStyle],
198
+ added=Diff.LineStyle(
199
+ marker="+", background=surface.mix(Color("#3CB878"), 0.18)
200
+ ),
201
+ removed=Diff.LineStyle(
202
+ marker="−", background=surface.mix(Color("#DF6270"), 0.18)
203
+ ),
204
+ hunk_background=surface.mix(muted, 0.12),
205
+ divider=surface.mix(muted, 0.45),
206
+ padding=spacing * 3,
207
+ row_padding=spacing / 2,
208
+ gutter_spacing=spacing * 2,
209
+ hunk_spacing=spacing * 1.5,
210
+ column_gap=spacing * 2,
211
+ )
212
+
213
+ style_token = DesignToken[Style](
214
+ "component.diff", lambda values: Diff._default_style(values), value_type=Style
215
+ )
216
+
217
+ hunks: tuple[DiffHunk, ...]
218
+ language: str | None
219
+ layout: DiffLayout
220
+ width: FrameMaximum | None
221
+
222
+ def __init__(
223
+ self,
224
+ *hunks: DiffHunk,
225
+ language: str | None = None,
226
+ layout: DiffLayout = "unified",
227
+ width: FrameMaximum | None = None,
228
+ ) -> None:
229
+ if not all(isinstance(hunk, DiffHunk) for hunk in hunks):
230
+ raise TypeError("Diff accepts DiffHunk values")
231
+ _check_keys([hunk.key for hunk in hunks], "Diff hunk")
232
+ _scope(language, "Diff.language")
233
+ if layout not in ("unified", "split"):
234
+ raise ValueError("Diff layout must be 'unified' or 'split'")
235
+ if isinstance(width, Length):
236
+ if width <= pt(0):
237
+ raise ValueError("Diff width must be positive")
238
+ elif width is not None and width is not unbounded:
239
+ raise TypeError("Diff width must be a Length or unbounded")
240
+ object.__setattr__(self, "hunks", hunks)
241
+ object.__setattr__(self, "language", language)
242
+ object.__setattr__(self, "layout", layout)
243
+ object.__setattr__(self, "width", width)
244
+
245
+ @classmethod
246
+ def from_text(
247
+ cls,
248
+ before: str,
249
+ after: str,
250
+ *,
251
+ language: str | None = None,
252
+ highlighter: CodeHighlighter | None = None,
253
+ context_lines: int | None = 3,
254
+ layout: DiffLayout = "unified",
255
+ width: FrameMaximum | None = None,
256
+ ) -> Diff:
257
+ """Compare snippets, with optional whole-source syntax highlighting.
258
+
259
+ Use None for context_lines to keep all unchanged lines around changes.
260
+ A final line terminator does not create an extra displayed line.
261
+ """
262
+ if context_lines is not None and (
263
+ type(context_lines) is not int or context_lines < 0
264
+ ):
265
+ raise ValueError("context_lines must be a nonnegative integer or None")
266
+ if highlighter is not None and language is None:
267
+ raise ValueError("A highlighter requires a language")
268
+ _scope(language, "Diff.language")
269
+ before, old_text = _source_lines(before)
270
+ after, new_text = _source_lines(after)
271
+ if old_text == new_text:
272
+ return cls(language=language, layout=layout, width=width)
273
+
274
+ old = _highlight_lines(before, old_text, language, highlighter)
275
+ new = _highlight_lines(after, new_text, language, highlighter)
276
+ matcher = SequenceMatcher(None, old_text, new_text, autojunk=False)
277
+ context = max(len(old), len(new)) if context_lines is None else context_lines
278
+ hunks = []
279
+ for group in matcher.get_grouped_opcodes(context):
280
+ lines = []
281
+ for tag, i, j, k, m in group:
282
+ if tag == "equal":
283
+ for a, b in zip(range(i, j), range(k, m)):
284
+ old_line = old[a]
285
+ lines.append(
286
+ DiffLine(
287
+ "context",
288
+ new[b],
289
+ old_number=a + 1,
290
+ new_number=b + 1,
291
+ old_content=old_line
292
+ if isinstance(old_line, CodeLine)
293
+ else None,
294
+ )
295
+ )
296
+ continue
297
+ lines.extend(
298
+ DiffLine("removed", old[a], old_number=a + 1) for a in range(i, j)
299
+ )
300
+ lines.extend(
301
+ DiffLine("added", new[b], new_number=b + 1) for b in range(k, m)
302
+ )
303
+ old_range = _hunk_range(group[0][1], group[-1][2])
304
+ new_range = _hunk_range(group[0][3], group[-1][4])
305
+ hunks.append(DiffHunk(*lines, header=f"@@ -{old_range} +{new_range} @@"))
306
+ return cls(*hunks, language=language, layout=layout, width=width)
307
+
308
+ def body(self, context: Context) -> View:
309
+ style = context.environment[self.style_token]
310
+ split = self.layout == "split"
311
+ children: list[View] = []
312
+ rows: list[_Row] = []
313
+
314
+ def add(view: View, key: str) -> int:
315
+ index = len(children)
316
+ children.append(view.key(key))
317
+ return index
318
+
319
+ def fill(color: ColorStyle | None, key: str) -> int | None:
320
+ return add(Rectangle(fill=color), key) if color is not None else None
321
+
322
+ def auxiliary(text: str, color: ColorStyle, key: str) -> int:
323
+ return add(Text(text, flow="verbatim").foreground_style(color), key)
324
+
325
+ def label(text: str, key: str, background: ColorStyle | None = None) -> _Row:
326
+ return _Row(
327
+ (
328
+ _Cell(
329
+ content=auxiliary(text, style.hunk_foreground, key),
330
+ fill=fill(background, f"{key}:fill"),
331
+ ),
332
+ )
333
+ )
334
+
335
+ def cell(
336
+ item: tuple[int, DiffLine],
337
+ hunk_key: str,
338
+ side: Literal["old", "new", "unified"],
339
+ ) -> _Cell:
340
+ line_index, line = item
341
+ key = f"{hunk_key}:line:{_item_key(line.key, line_index)}:{side}"
342
+ line_style = {
343
+ "context": style.context,
344
+ "added": style.added,
345
+ "removed": style.removed,
346
+ }[line.role]
347
+
348
+ content = (
349
+ line.old_content
350
+ if side == "old" and line.old_content is not None
351
+ else line.content
352
+ )
353
+ text = (
354
+ _resolve_code_line(content, self.language, context)
355
+ if isinstance(content, CodeLine)
356
+ else content
357
+ )
358
+ source = Text(text, flow="verbatim").foreground_style(
359
+ line_style.foreground or style.foreground
360
+ )
361
+ gutters: list[_Gutter] = []
362
+ if style.show_line_numbers:
363
+ for column, (number, name) in enumerate(
364
+ ((line.old_number, "old"), (line.new_number, "new"))
365
+ ):
366
+ if (name == "old" and side == "new") or (
367
+ name == "new" and side == "old"
368
+ ):
369
+ continue
370
+ index = (
371
+ auxiliary(
372
+ str(number), style.number_foreground, f"{key}:{name}-number"
373
+ )
374
+ if number is not None
375
+ else None
376
+ )
377
+ gutters.append(_Gutter(column, index))
378
+ marker_color = (
379
+ line_style.marker_foreground
380
+ or line_style.accent
381
+ or line_style.foreground
382
+ or style.foreground
383
+ )
384
+ marker = (
385
+ auxiliary(line_style.marker, marker_color, f"{key}:marker")
386
+ if line_style.marker
387
+ else None
388
+ )
389
+ gutters.append(_Gutter(2, marker))
390
+ return _Cell(
391
+ content=add(source, key),
392
+ gutters=tuple(gutters),
393
+ fill=fill(line_style.background, f"{key}:fill"),
394
+ accent=fill(line_style.accent, f"{key}:accent")
395
+ if style.accent_width > pt(0)
396
+ else None,
397
+ )
398
+
399
+ for hunk_index, hunk in enumerate(self.hunks):
400
+ hunk_key = f"hunk:{_item_key(hunk.key, hunk_index)}"
401
+ first_row = len(rows)
402
+ if style.show_hunk_headers and hunk.header is not None:
403
+ rows.append(
404
+ label(hunk.header, f"{hunk_key}:header", style.hunk_background)
405
+ )
406
+ if split:
407
+ for row_index, (left, right) in enumerate(_split_rows(hunk.lines)):
408
+ old = cell(left, hunk_key, "old") if left is not None else None
409
+ new = cell(right, hunk_key, "new") if right is not None else None
410
+ divider = (
411
+ fill(style.divider, f"{hunk_key}:divider:{row_index}")
412
+ if style.divider_width > pt(0)
413
+ else None
414
+ )
415
+ rows.append(_Row((old, new), divider))
416
+ else:
417
+ rows.extend(
418
+ _Row((cell(item, hunk_key, "unified"),))
419
+ for item in enumerate(hunk.lines)
420
+ )
421
+ if first_row:
422
+ rows[first_row] = replace(
423
+ rows[first_row], space_before=style.hunk_spacing
424
+ )
425
+ if not rows:
426
+ rows.append(label(style.empty_message, "empty"))
427
+
428
+ policy = _DiffLayout(tuple(rows), style, self.width)
429
+ return (
430
+ _DiffListing(policy, children)
431
+ .font(style.typography)
432
+ .background(Rectangle(fill=style.background))
433
+ )
434
+
435
+
436
+ def _hunk_range(start: int, end: int) -> str:
437
+ count = end - start
438
+ if count == 0:
439
+ return f"{start},0"
440
+ return str(start + 1) if count == 1 else f"{start + 1},{count}"
441
+
442
+
443
+ def _item_key(key: str | int | None, index: int) -> str:
444
+ if key is None:
445
+ return f"index:{index}"
446
+ # Length-prefix the user key before adding descendant parts.
447
+ value = str(key)
448
+ return f"key:{len(value)}:{value}"
449
+
450
+
451
+ _IndexedLine = tuple[int, DiffLine]
452
+
453
+
454
+ def _split_rows(
455
+ lines: tuple[DiffLine, ...],
456
+ ) -> Iterator[tuple[_IndexedLine | None, _IndexedLine | None]]:
457
+ for is_context, group in groupby(
458
+ enumerate(lines), lambda item: item[1].role == "context"
459
+ ):
460
+ if is_context:
461
+ yield from ((item, item) for item in group)
462
+ else:
463
+ removed: list[_IndexedLine] = []
464
+ added: list[_IndexedLine] = []
465
+ for item in group:
466
+ (removed if item[1].role == "removed" else added).append(item)
467
+ yield from zip_longest(removed, added)
468
+
469
+
470
+ @dataclass(frozen=True)
471
+ class _Gutter:
472
+ column: int
473
+ content: int | None
474
+
475
+
476
+ @dataclass(frozen=True)
477
+ class _Cell:
478
+ content: int
479
+ gutters: tuple[_Gutter, ...] = ()
480
+ fill: int | None = None
481
+ accent: int | None = None
482
+
483
+ def text_indices(self) -> Iterator[int]:
484
+ yield self.content
485
+ yield from (
486
+ gutter.content for gutter in self.gutters if gutter.content is not None
487
+ )
488
+
489
+
490
+ @dataclass(frozen=True)
491
+ class _Row:
492
+ cells: tuple[_Cell | None, ...]
493
+ divider: int | None = None
494
+ space_before: Length = pt(0)
495
+
496
+
497
+ class _DiffListing(LayoutView):
498
+ def __init__(self, layout: _DiffLayout, children: Sequence[View]) -> None:
499
+ super().__init__(*children)
500
+ object.__setattr__(self, "_layout", layout)
501
+
502
+ _layout: _DiffLayout
503
+
504
+ def resolve_layout(self, lookup: Callable[[str], ViewIdentity]) -> Layout:
505
+ return self._layout
506
+
507
+
508
+ @dataclass(frozen=True)
509
+ class _DiffLayout:
510
+ rows: tuple[_Row, ...]
511
+ style: Diff.Style
512
+ width: FrameMaximum | None
513
+
514
+ def measure(
515
+ self,
516
+ proposal: ProposedSize,
517
+ children: Sequence[LayoutChild],
518
+ context: LayoutContext,
519
+ ) -> LayoutPlan:
520
+ style = self.style
521
+ cells = [cell for row in self.rows for cell in row.cells if cell is not None]
522
+ gutter_widths = [pt(0)] * 3
523
+ text_plans: dict[int, LayoutPlan] = {}
524
+ for cell in cells:
525
+ text_plans[cell.content] = children[cell.content].measure(ProposedSize())
526
+ for column, index in (
527
+ (gutter.column, gutter.content) for gutter in cell.gutters
528
+ ):
529
+ if index is not None:
530
+ plan = children[index].measure(ProposedSize())
531
+ text_plans[index] = plan
532
+ gutter_widths[column] = max(gutter_widths[column], plan.width)
533
+ gutter_advances = [
534
+ width + style.gutter_spacing if width > pt(0) else pt(0)
535
+ for width in gutter_widths
536
+ ]
537
+
538
+ inset = (
539
+ max(style.padding, style.accent_width)
540
+ if any(cell.accent is not None for cell in cells)
541
+ else style.padding
542
+ )
543
+ gap = (
544
+ max(style.column_gap, style.divider_width)
545
+ if any(row.divider is not None for row in self.rows)
546
+ else style.column_gap
547
+ )
548
+ required = pt(0)
549
+ for row in self.rows:
550
+ for candidate in row.cells:
551
+ if candidate is None:
552
+ continue
553
+ gutter_extent = sum(
554
+ (gutter_advances[g.column] for g in candidate.gutters), pt(0)
555
+ )
556
+ cell_width = (
557
+ inset * 2 + gutter_extent + text_plans[candidate.content].width
558
+ )
559
+ row_width = cell_width if len(row.cells) == 1 else cell_width * 2 + gap
560
+ required = max(required, row_width)
561
+ if isinstance(self.width, Length):
562
+ width = self.width
563
+ elif self.width is unbounded and proposal.width is not None:
564
+ width = proposal.width
565
+ else:
566
+ width = required
567
+ if required - width > pt(1e-6):
568
+ raise LayoutOverflow(
569
+ None, (width, proposal.height or pt(0)), (required, None)
570
+ )
571
+
572
+ placements = []
573
+ y = style.padding
574
+
575
+ def decoration(
576
+ index: int, x: Length, width: Length, height: Length
577
+ ) -> Placement:
578
+ child = children[index]
579
+ return Placement(
580
+ child, child.measure(ProposedSize(width, height)), x, y, False
581
+ )
582
+
583
+ for row in self.rows:
584
+ y += row.space_before
585
+ cell_width = width if len(row.cells) == 1 else (width - gap) / 2
586
+ pairs = [
587
+ (side, cell) for side, cell in enumerate(row.cells) if cell is not None
588
+ ]
589
+ plans = [
590
+ text_plans[index] for _, cell in pairs for index in cell.text_indices()
591
+ ]
592
+ baseline = max(plan.vertical_guide(FIRST_BASELINE) for plan in plans)
593
+ below_baseline = max(
594
+ plan.height - plan.vertical_guide(FIRST_BASELINE) for plan in plans
595
+ )
596
+ height = baseline + below_baseline + style.row_padding * 2
597
+ if row.divider is not None:
598
+ x = cell_width + (gap - style.divider_width) / 2
599
+ placements.append(
600
+ decoration(row.divider, x, style.divider_width, height)
601
+ )
602
+ for side, cell in pairs:
603
+ x = side * (cell_width + gap)
604
+ if cell.fill is not None:
605
+ placements.append(decoration(cell.fill, x, cell_width, height))
606
+ if cell.accent is not None:
607
+ placements.append(
608
+ decoration(cell.accent, x, style.accent_width, height)
609
+ )
610
+
611
+ x += inset
612
+ for gutter in cell.gutters:
613
+ index = gutter.content
614
+ if index is not None:
615
+ plan = text_plans[index]
616
+ offset = gutter_widths[gutter.column] - plan.width
617
+ placements.append(
618
+ Placement(
619
+ children[index],
620
+ plan,
621
+ x + offset,
622
+ y
623
+ + style.row_padding
624
+ + baseline
625
+ - plan.vertical_guide(FIRST_BASELINE),
626
+ )
627
+ )
628
+ x += gutter_advances[gutter.column]
629
+ plan = text_plans[cell.content]
630
+ placements.append(
631
+ Placement(
632
+ children[cell.content],
633
+ plan,
634
+ x,
635
+ y
636
+ + style.row_padding
637
+ + baseline
638
+ - plan.vertical_guide(FIRST_BASELINE),
639
+ )
640
+ )
641
+ y += height
642
+ return LayoutPlan(width, y + style.padding, tuple(placements))