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,100 @@
|
|
|
1
|
+
"""Author-facing views; implementations live in individual modules."""
|
|
2
|
+
|
|
3
|
+
from ..context import (
|
|
4
|
+
Context,
|
|
5
|
+
Environment,
|
|
6
|
+
State,
|
|
7
|
+
)
|
|
8
|
+
from ..layout import VerticalAlignment
|
|
9
|
+
from ..layouts.grid import ColumnWidth
|
|
10
|
+
from .canvas import Canvas
|
|
11
|
+
from .code import (
|
|
12
|
+
Code,
|
|
13
|
+
CodeHighlighter,
|
|
14
|
+
CodeLine,
|
|
15
|
+
CodeMark,
|
|
16
|
+
CodeMarkRegion,
|
|
17
|
+
CodeMarkRegionStyle,
|
|
18
|
+
CodeMarkRun,
|
|
19
|
+
CodeMarks,
|
|
20
|
+
CodeMarkView,
|
|
21
|
+
CodeSpan,
|
|
22
|
+
)
|
|
23
|
+
from .code_evolution import CodeEvolution
|
|
24
|
+
from .divider import Divider
|
|
25
|
+
from .ellipse import Ellipse
|
|
26
|
+
from .grid import Grid, GridCell, GridRow
|
|
27
|
+
from .hstack import HStack
|
|
28
|
+
from .image import Image
|
|
29
|
+
from .layout_view import LayoutView
|
|
30
|
+
from .line import Line
|
|
31
|
+
from .modifier_views import Edge, EdgeInsets, EdgeSet, FrameSpec, unbounded
|
|
32
|
+
from .path import Path
|
|
33
|
+
from .rectangle import Rectangle
|
|
34
|
+
from .section_number import SectionNumber
|
|
35
|
+
from .slide import Slide
|
|
36
|
+
from .slide_number import SlideNumber
|
|
37
|
+
from .spacer import Spacer
|
|
38
|
+
from .stack import Stack
|
|
39
|
+
from .text import Text, TextLine, TextSpan
|
|
40
|
+
from .view import Modifier, View
|
|
41
|
+
from .vstack import VStack
|
|
42
|
+
from .zstack import ZStack
|
|
43
|
+
|
|
44
|
+
__all__ = [
|
|
45
|
+
"Canvas",
|
|
46
|
+
"ColumnWidth",
|
|
47
|
+
"Context",
|
|
48
|
+
"Divider",
|
|
49
|
+
"Edge",
|
|
50
|
+
"EdgeInsets",
|
|
51
|
+
"EdgeSet",
|
|
52
|
+
"Ellipse",
|
|
53
|
+
"Environment",
|
|
54
|
+
"FrameSpec",
|
|
55
|
+
"Grid",
|
|
56
|
+
"GridCell",
|
|
57
|
+
"GridRow",
|
|
58
|
+
"HStack",
|
|
59
|
+
"Image",
|
|
60
|
+
"LayoutView",
|
|
61
|
+
"Line",
|
|
62
|
+
"Modifier",
|
|
63
|
+
"Path",
|
|
64
|
+
"Rectangle",
|
|
65
|
+
"SectionNumber",
|
|
66
|
+
"Slide",
|
|
67
|
+
"SlideNumber",
|
|
68
|
+
"Spacer",
|
|
69
|
+
"Stack",
|
|
70
|
+
"State",
|
|
71
|
+
"Text",
|
|
72
|
+
"TextLine",
|
|
73
|
+
"TextSpan",
|
|
74
|
+
"VStack",
|
|
75
|
+
"VerticalAlignment",
|
|
76
|
+
"View",
|
|
77
|
+
"ZStack",
|
|
78
|
+
"unbounded",
|
|
79
|
+
]
|
|
80
|
+
|
|
81
|
+
from .composite_view import CompositeView
|
|
82
|
+
from .primitive_view import PrimitiveView
|
|
83
|
+
from .pygments_highlighter import PygmentsHighlighter
|
|
84
|
+
|
|
85
|
+
__all__ += [
|
|
86
|
+
"Code",
|
|
87
|
+
"CodeEvolution",
|
|
88
|
+
"CodeHighlighter",
|
|
89
|
+
"CodeLine",
|
|
90
|
+
"CodeMark",
|
|
91
|
+
"CodeMarkRegion",
|
|
92
|
+
"CodeMarkRegionStyle",
|
|
93
|
+
"CodeMarkRun",
|
|
94
|
+
"CodeMarkView",
|
|
95
|
+
"CodeMarks",
|
|
96
|
+
"CodeSpan",
|
|
97
|
+
"CompositeView",
|
|
98
|
+
"PrimitiveView",
|
|
99
|
+
"PygmentsHighlighter",
|
|
100
|
+
]
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Shared source handling for code comparisons."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Sequence
|
|
6
|
+
|
|
7
|
+
from .code import Code, CodeHighlighter, CodeLine
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _code_text(line: CodeLine) -> str:
|
|
11
|
+
return "".join(span.text for span in line.spans)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _source_lines(source: str) -> tuple[str, tuple[str, ...]]:
|
|
15
|
+
if not isinstance(source, str):
|
|
16
|
+
raise TypeError("Code sources must be strings")
|
|
17
|
+
normalized = source.replace("\r\n", "\n").replace("\r", "\n")
|
|
18
|
+
return normalized, tuple(
|
|
19
|
+
normalized.removesuffix("\n").split("\n")
|
|
20
|
+
) if normalized else ()
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _highlight_lines(
|
|
24
|
+
source: str,
|
|
25
|
+
lines: tuple[str, ...],
|
|
26
|
+
language: str | None,
|
|
27
|
+
highlighter: CodeHighlighter | None,
|
|
28
|
+
) -> Sequence[str | CodeLine]:
|
|
29
|
+
if not lines or language is None:
|
|
30
|
+
return lines
|
|
31
|
+
highlighted = Code.highlight(
|
|
32
|
+
source, language=language, highlighter=highlighter
|
|
33
|
+
).lines
|
|
34
|
+
if (
|
|
35
|
+
source.endswith("\n")
|
|
36
|
+
and len(highlighted) == len(lines) + 1
|
|
37
|
+
and not _code_text(highlighted[-1])
|
|
38
|
+
):
|
|
39
|
+
highlighted = highlighted[:-1]
|
|
40
|
+
if tuple(map(_code_text, highlighted)) != lines:
|
|
41
|
+
raise ValueError("Code highlighters must preserve source lines and whitespace")
|
|
42
|
+
return highlighted
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""Resolve a layout shape using the same paint and geometry as Canvas."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import replace
|
|
6
|
+
|
|
7
|
+
from ..canvas import Stroke
|
|
8
|
+
from ..canvas.elements import Ellipse as CanvasEllipse
|
|
9
|
+
from ..canvas.elements import Line as CanvasLine
|
|
10
|
+
from ..canvas.path import Path as CanvasPath
|
|
11
|
+
from ..context import Context, Environment
|
|
12
|
+
from ..expanded_views import ExpandedDrawing, ExpandedMetadata
|
|
13
|
+
from ..layouts.primitives import DrawingLayout
|
|
14
|
+
from ..theme import Color, ColorStyle
|
|
15
|
+
from ..units import pt
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def resolve_stroke(paint: Stroke, environment: Environment) -> Stroke:
|
|
19
|
+
style = paint.style
|
|
20
|
+
return (
|
|
21
|
+
paint if isinstance(style, Color) else replace(paint, style=environment[style])
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def expand_drawing(
|
|
26
|
+
element: CanvasEllipse | CanvasLine | CanvasPath,
|
|
27
|
+
context: Context,
|
|
28
|
+
metadata: ExpandedMetadata,
|
|
29
|
+
) -> ExpandedDrawing:
|
|
30
|
+
environment = context.environment
|
|
31
|
+
|
|
32
|
+
def color(style: ColorStyle) -> Color:
|
|
33
|
+
return style if isinstance(style, Color) else environment[style]
|
|
34
|
+
|
|
35
|
+
if isinstance(element, CanvasLine):
|
|
36
|
+
element = replace(element, stroke=resolve_stroke(element.stroke, environment))
|
|
37
|
+
else:
|
|
38
|
+
element = replace(
|
|
39
|
+
element,
|
|
40
|
+
fill=color(element.fill) if element.fill is not None else None,
|
|
41
|
+
stroke=resolve_stroke(element.stroke, environment)
|
|
42
|
+
if element.stroke is not None
|
|
43
|
+
else None,
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
if isinstance(element, CanvasEllipse):
|
|
47
|
+
return ExpandedDrawing(metadata, DrawingLayout(environment), element, None)
|
|
48
|
+
|
|
49
|
+
bounds = element.anchor_bounds
|
|
50
|
+
thickness = element.stroke.width if element.stroke is not None else pt(0)
|
|
51
|
+
size = (max(bounds.width, thickness), max(bounds.height, thickness))
|
|
52
|
+
return ExpandedDrawing(metadata, DrawingLayout(environment, size), element, bounds)
|
deckkit/views/canvas.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
|
|
5
|
+
from ..canvas import CanvasRenderer
|
|
6
|
+
from ..context import Context
|
|
7
|
+
from ..expanded_views import ExpandedCanvas, ExpandedMetadata
|
|
8
|
+
from ..layouts import CanvasLayout
|
|
9
|
+
from .primitive_view import PrimitiveView
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass(frozen=True)
|
|
13
|
+
class Canvas(PrimitiveView):
|
|
14
|
+
"""A size-dependent retained drawing scene in local physical coordinates."""
|
|
15
|
+
|
|
16
|
+
renderer: CanvasRenderer
|
|
17
|
+
|
|
18
|
+
def __post_init__(self) -> None:
|
|
19
|
+
if not callable(self.renderer):
|
|
20
|
+
raise TypeError("Canvas renderer must be callable")
|
|
21
|
+
|
|
22
|
+
def expand(self, context: Context, metadata: ExpandedMetadata) -> ExpandedCanvas:
|
|
23
|
+
return ExpandedCanvas(
|
|
24
|
+
metadata,
|
|
25
|
+
CanvasLayout(self.renderer, context.environment),
|
|
26
|
+
self.renderer,
|
|
27
|
+
)
|
deckkit/views/code.py
ADDED
|
@@ -0,0 +1,481 @@
|
|
|
1
|
+
"""Syntax-aware, whitespace-preserving code text."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
6
|
+
from dataclasses import dataclass, replace
|
|
7
|
+
from hashlib import blake2b
|
|
8
|
+
from itertools import groupby
|
|
9
|
+
from typing import Protocol
|
|
10
|
+
|
|
11
|
+
from ..canvas import Stroke
|
|
12
|
+
from ..context import Context
|
|
13
|
+
from ..identity import ViewIdentity
|
|
14
|
+
from ..layout import (
|
|
15
|
+
Layout,
|
|
16
|
+
LayoutChild,
|
|
17
|
+
LayoutContext,
|
|
18
|
+
LayoutPlan,
|
|
19
|
+
Placement,
|
|
20
|
+
ProposedSize,
|
|
21
|
+
)
|
|
22
|
+
from ..measurement import MeasuredRichText, MeasuredTextLine
|
|
23
|
+
from ..theme import AccentColor, CodeTextStyle, Color, ColorStyle, Typography
|
|
24
|
+
from ..tokens import DesignToken
|
|
25
|
+
from ..units import Length, pt, require_length
|
|
26
|
+
from .composite_view import CompositeView
|
|
27
|
+
from .layout_view import LayoutView
|
|
28
|
+
from .rectangle import Rectangle
|
|
29
|
+
from .text import Text, TextLine, TextSpan
|
|
30
|
+
from .view import View
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _scope(value: str | None, name: str) -> None:
|
|
34
|
+
if value is not None and (
|
|
35
|
+
not value
|
|
36
|
+
or value != value.strip()
|
|
37
|
+
or any(not part for part in value.split("."))
|
|
38
|
+
):
|
|
39
|
+
raise ValueError(f"{name} must be a dot-separated scope")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True)
|
|
43
|
+
class CodeSpan:
|
|
44
|
+
"""A source fragment classified by a language-defined token scope."""
|
|
45
|
+
|
|
46
|
+
text: str
|
|
47
|
+
token: str | None = None
|
|
48
|
+
foreground_style: ColorStyle | None = None
|
|
49
|
+
background_style: ColorStyle | None = None
|
|
50
|
+
font_style: DesignToken[Typography] | None = None
|
|
51
|
+
|
|
52
|
+
def __post_init__(self) -> None:
|
|
53
|
+
if not isinstance(self.text, str):
|
|
54
|
+
raise TypeError("CodeSpan.text must be a string")
|
|
55
|
+
if "\n" in self.text:
|
|
56
|
+
raise ValueError(
|
|
57
|
+
"CodeSpan cannot contain newlines; use separate CodeLine values"
|
|
58
|
+
)
|
|
59
|
+
_scope(self.token, "CodeSpan.token")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass(frozen=True, init=False)
|
|
63
|
+
class CodeMark:
|
|
64
|
+
"""A named band that retains its identity as it moves between code lines."""
|
|
65
|
+
|
|
66
|
+
role: str
|
|
67
|
+
key: str
|
|
68
|
+
|
|
69
|
+
def __init__(self, role: str, key: str | int) -> None:
|
|
70
|
+
if not isinstance(role, str) or not role.strip():
|
|
71
|
+
raise ValueError("CodeMark.role must name a mark role")
|
|
72
|
+
if not isinstance(key, (str, int)) or not str(key):
|
|
73
|
+
raise ValueError("CodeMark.key must name a mark")
|
|
74
|
+
object.__setattr__(self, "role", role)
|
|
75
|
+
object.__setattr__(self, "key", str(key))
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
@dataclass(frozen=True, init=False)
|
|
79
|
+
class CodeLine:
|
|
80
|
+
"""One logical source line with optional styling and build identity."""
|
|
81
|
+
|
|
82
|
+
spans: tuple[CodeSpan, ...]
|
|
83
|
+
background_style: ColorStyle | None
|
|
84
|
+
mark: str | None
|
|
85
|
+
key: str | None
|
|
86
|
+
mark_key: str | None
|
|
87
|
+
marks: tuple[CodeMark, ...]
|
|
88
|
+
|
|
89
|
+
def __init__(
|
|
90
|
+
self,
|
|
91
|
+
*spans: CodeSpan | str,
|
|
92
|
+
background_style: ColorStyle | None = None,
|
|
93
|
+
mark: str | None = None,
|
|
94
|
+
key: str | int | None = None,
|
|
95
|
+
mark_key: str | int | None = None,
|
|
96
|
+
marks: Sequence[CodeMark] = (),
|
|
97
|
+
) -> None:
|
|
98
|
+
if mark is not None and (not isinstance(mark, str) or not mark.strip()):
|
|
99
|
+
raise ValueError("CodeLine.mark must name a mark role")
|
|
100
|
+
if mark_key is not None and mark is None:
|
|
101
|
+
raise ValueError("CodeLine.mark_key requires a mark role")
|
|
102
|
+
bands = tuple(marks)
|
|
103
|
+
if not all(isinstance(band, CodeMark) for band in bands):
|
|
104
|
+
raise TypeError("CodeLine.marks must contain CodeMark values")
|
|
105
|
+
normalized = []
|
|
106
|
+
for span in spans:
|
|
107
|
+
if isinstance(span, CodeSpan):
|
|
108
|
+
normalized.append(span)
|
|
109
|
+
elif isinstance(span, str):
|
|
110
|
+
normalized.append(CodeSpan(span))
|
|
111
|
+
else:
|
|
112
|
+
raise TypeError("CodeLine values must be strings or CodeSpan values")
|
|
113
|
+
object.__setattr__(self, "spans", tuple(normalized) or (CodeSpan(""),))
|
|
114
|
+
object.__setattr__(self, "background_style", background_style)
|
|
115
|
+
object.__setattr__(self, "mark", mark)
|
|
116
|
+
object.__setattr__(self, "key", None if key is None else str(key))
|
|
117
|
+
object.__setattr__(
|
|
118
|
+
self, "mark_key", None if mark_key is None else str(mark_key)
|
|
119
|
+
)
|
|
120
|
+
object.__setattr__(self, "marks", bands)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
@dataclass(frozen=True)
|
|
124
|
+
class CodeMarkRun:
|
|
125
|
+
"""A contiguous mark, addressed by zero-based line and role ordinal."""
|
|
126
|
+
|
|
127
|
+
role: str
|
|
128
|
+
ordinal: int
|
|
129
|
+
first_line: int
|
|
130
|
+
line_count: int
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
CodeMarkView = Callable[[CodeMarkRun], View]
|
|
134
|
+
CodeMarks = DesignToken[Mapping[str, CodeMarkView]](
|
|
135
|
+
"code.marks",
|
|
136
|
+
lambda _: {
|
|
137
|
+
"highlight": lambda run: Rectangle(fill=AccentColor).opacity(0.18),
|
|
138
|
+
"added": lambda run: Rectangle(fill=Color("#24A36A")).opacity(0.22),
|
|
139
|
+
"edited": lambda run: Rectangle(fill=Color("#D79528")).opacity(0.24),
|
|
140
|
+
"focus": lambda run: Rectangle(
|
|
141
|
+
fill_opacity=0, stroke=Stroke(AccentColor, pt(1.5))
|
|
142
|
+
),
|
|
143
|
+
},
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
@dataclass(frozen=True)
|
|
148
|
+
class CodeMarkRegion:
|
|
149
|
+
"""The horizontal space used by code marks.
|
|
150
|
+
|
|
151
|
+
With `fill_width`, use the proposed listing width when available.
|
|
152
|
+
Otherwise, use the measured text width. Add both side extensions.
|
|
153
|
+
"""
|
|
154
|
+
|
|
155
|
+
leading: Length = pt(0)
|
|
156
|
+
trailing: Length = pt(0)
|
|
157
|
+
fill_width: bool = False
|
|
158
|
+
|
|
159
|
+
def __post_init__(self) -> None:
|
|
160
|
+
for extent in (self.leading, self.trailing):
|
|
161
|
+
require_length(extent)
|
|
162
|
+
if extent < pt(0):
|
|
163
|
+
raise ValueError("Code mark extensions must be nonnegative")
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
CodeMarkRegionStyle = DesignToken[CodeMarkRegion](
|
|
167
|
+
"code.mark_region", lambda _: CodeMarkRegion(), value_type=CodeMarkRegion
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
class CodeHighlighter(Protocol):
|
|
172
|
+
"""Convert source text into Deckkit's code representation."""
|
|
173
|
+
|
|
174
|
+
def highlight(self, source: str, language: str) -> tuple[CodeLine, ...]: ...
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _resolve_code_line(
|
|
178
|
+
line: CodeLine, language: str | None, context: Context
|
|
179
|
+
) -> TextLine:
|
|
180
|
+
theme = context.environment.theme
|
|
181
|
+
spans = []
|
|
182
|
+
for span in line.spans:
|
|
183
|
+
style = theme.code_style(language, span.token)
|
|
184
|
+
spans.append(
|
|
185
|
+
TextSpan(
|
|
186
|
+
span.text,
|
|
187
|
+
span.font_style or style.font_style,
|
|
188
|
+
span.foreground_style or style.foreground_style,
|
|
189
|
+
span.background_style or style.background_style,
|
|
190
|
+
)
|
|
191
|
+
)
|
|
192
|
+
return TextLine(*spans, background_style=line.background_style)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
@dataclass(frozen=True, init=False)
|
|
196
|
+
class Code(CompositeView):
|
|
197
|
+
"""Syntax-aware code text without block-level decoration."""
|
|
198
|
+
|
|
199
|
+
lines: tuple[CodeLine, ...]
|
|
200
|
+
language: str | None
|
|
201
|
+
animate_lines: bool
|
|
202
|
+
|
|
203
|
+
def __init__(
|
|
204
|
+
self,
|
|
205
|
+
content: str | CodeLine,
|
|
206
|
+
*lines: CodeLine,
|
|
207
|
+
language: str | None = None,
|
|
208
|
+
animate_lines: bool = False,
|
|
209
|
+
) -> None:
|
|
210
|
+
_scope(language, "Code.language")
|
|
211
|
+
if isinstance(content, str):
|
|
212
|
+
if lines:
|
|
213
|
+
raise TypeError("Additional CodeLine values require a CodeLine first")
|
|
214
|
+
structured = tuple(CodeLine(line) for line in content.split("\n"))
|
|
215
|
+
elif isinstance(content, CodeLine) and all(
|
|
216
|
+
isinstance(line, CodeLine) for line in lines
|
|
217
|
+
):
|
|
218
|
+
structured = (content, *lines)
|
|
219
|
+
else:
|
|
220
|
+
raise TypeError("Code content must be a string or CodeLine")
|
|
221
|
+
object.__setattr__(self, "lines", structured)
|
|
222
|
+
object.__setattr__(self, "language", language)
|
|
223
|
+
object.__setattr__(self, "animate_lines", animate_lines)
|
|
224
|
+
keys = [line.key for line in structured if line.key is not None]
|
|
225
|
+
if animate_lines and len(keys) != len(set(keys)):
|
|
226
|
+
raise ValueError(
|
|
227
|
+
"CodeLine.key values must be unique in an animated listing"
|
|
228
|
+
)
|
|
229
|
+
|
|
230
|
+
@classmethod
|
|
231
|
+
def highlight(
|
|
232
|
+
cls,
|
|
233
|
+
source: str,
|
|
234
|
+
*,
|
|
235
|
+
language: str,
|
|
236
|
+
highlighter: CodeHighlighter | None = None,
|
|
237
|
+
animate_lines: bool = False,
|
|
238
|
+
) -> Code:
|
|
239
|
+
"""Tokenize source into semantic spans using a pluggable highlighter."""
|
|
240
|
+
if not isinstance(source, str):
|
|
241
|
+
raise TypeError("Code source must be a string")
|
|
242
|
+
_scope(language, "Code.language")
|
|
243
|
+
if highlighter is None:
|
|
244
|
+
from .pygments_highlighter import PygmentsHighlighter
|
|
245
|
+
|
|
246
|
+
highlighter = PygmentsHighlighter()
|
|
247
|
+
lines = highlighter.highlight(source, language)
|
|
248
|
+
if (
|
|
249
|
+
not isinstance(lines, tuple)
|
|
250
|
+
or not lines
|
|
251
|
+
or not all(isinstance(line, CodeLine) for line in lines)
|
|
252
|
+
):
|
|
253
|
+
raise TypeError(
|
|
254
|
+
"Code highlighters must return a nonempty tuple of CodeLine"
|
|
255
|
+
)
|
|
256
|
+
return cls(lines[0], *lines[1:], language=language, animate_lines=animate_lines)
|
|
257
|
+
|
|
258
|
+
def body(self, context: Context) -> View:
|
|
259
|
+
lines = [
|
|
260
|
+
_resolve_code_line(line, self.language, context) for line in self.lines
|
|
261
|
+
]
|
|
262
|
+
if self.animate_lines:
|
|
263
|
+
texts, indents = self._animated_text(lines)
|
|
264
|
+
else:
|
|
265
|
+
texts = [Text(lines[0], *lines[1:], flow="verbatim").font(CodeTextStyle)]
|
|
266
|
+
indents = {}
|
|
267
|
+
runs, marks = self._marks(context)
|
|
268
|
+
layout = _CodeLayout(
|
|
269
|
+
self.animate_lines,
|
|
270
|
+
tuple(indents),
|
|
271
|
+
runs,
|
|
272
|
+
context.environment[CodeMarkRegionStyle],
|
|
273
|
+
)
|
|
274
|
+
# Keep text at the same child slots when the number of marks changes.
|
|
275
|
+
return _CodeListing(layout, *texts, *indents.values(), *marks)
|
|
276
|
+
|
|
277
|
+
def _animated_text(
|
|
278
|
+
self, lines: Sequence[TextLine]
|
|
279
|
+
) -> tuple[list[View], dict[int, View]]:
|
|
280
|
+
texts: list[View] = []
|
|
281
|
+
indents: dict[int, View] = {}
|
|
282
|
+
counts: dict[str, int] = {}
|
|
283
|
+
for index, (line, text) in enumerate(zip(self.lines, lines)):
|
|
284
|
+
prefix, main = _split_indent(text)
|
|
285
|
+
if prefix:
|
|
286
|
+
indents[index] = Text(TextLine(*prefix), flow="verbatim").font(
|
|
287
|
+
CodeTextStyle
|
|
288
|
+
)
|
|
289
|
+
if line.key is None:
|
|
290
|
+
source = "".join(span.text for span in line.spans).lstrip(" \t")
|
|
291
|
+
digest = blake2b(source.encode("utf-8"), digest_size=16).hexdigest()
|
|
292
|
+
ordinal = counts.get(digest, 0)
|
|
293
|
+
counts[digest] = ordinal + 1
|
|
294
|
+
key = f"line:auto:{digest}:{ordinal}"
|
|
295
|
+
else:
|
|
296
|
+
key = f"line:explicit:{line.key}"
|
|
297
|
+
texts.append(Text(main, flow="verbatim").font(CodeTextStyle).key(key))
|
|
298
|
+
return texts, indents
|
|
299
|
+
|
|
300
|
+
def _marks(self, context: Context) -> tuple[tuple[CodeMarkRun, ...], list[View]]:
|
|
301
|
+
runs: list[CodeMarkRun] = []
|
|
302
|
+
marks: list[View] = []
|
|
303
|
+
ordinals: dict[str, int] = {}
|
|
304
|
+
implicit_ordinals: dict[str, int] = {}
|
|
305
|
+
keys: set[str] = set()
|
|
306
|
+
|
|
307
|
+
def add(role: str, explicit: str | None, first: int, count: int) -> None:
|
|
308
|
+
ordinal = ordinals.get(role, 0)
|
|
309
|
+
ordinals[role] = ordinal + 1
|
|
310
|
+
run = CodeMarkRun(role, ordinal, first, count)
|
|
311
|
+
factory = context.environment[CodeMarks].get(role)
|
|
312
|
+
if factory is None:
|
|
313
|
+
raise ValueError(f"CodeMarks has no view for role {role!r}")
|
|
314
|
+
identity: str | int
|
|
315
|
+
if explicit is None:
|
|
316
|
+
identity = implicit_ordinals.get(role, 0)
|
|
317
|
+
implicit_ordinals[role] = identity + 1
|
|
318
|
+
else:
|
|
319
|
+
identity = explicit
|
|
320
|
+
key = repr(("mark", role, identity))
|
|
321
|
+
if key in keys:
|
|
322
|
+
raise ValueError(
|
|
323
|
+
f"Code mark key {explicit!r} is repeated for role {role!r}"
|
|
324
|
+
)
|
|
325
|
+
keys.add(key)
|
|
326
|
+
runs.append(run)
|
|
327
|
+
marks.append(_CodeMark(factory(run)).key(key))
|
|
328
|
+
|
|
329
|
+
for (role, explicit), group in groupby(
|
|
330
|
+
enumerate(self.lines), key=lambda item: (item[1].mark, item[1].mark_key)
|
|
331
|
+
):
|
|
332
|
+
if role is not None:
|
|
333
|
+
members = tuple(group)
|
|
334
|
+
add(role, explicit, members[0][0], len(members))
|
|
335
|
+
|
|
336
|
+
layers: dict[CodeMark, list[int]] = {}
|
|
337
|
+
for index, line in enumerate(self.lines):
|
|
338
|
+
for mark in line.marks:
|
|
339
|
+
layers.setdefault(mark, []).append(index)
|
|
340
|
+
for mark, indices in layers.items():
|
|
341
|
+
first = indices[0]
|
|
342
|
+
if any(index != first + offset for offset, index in enumerate(indices)):
|
|
343
|
+
raise ValueError(
|
|
344
|
+
f"Code mark {mark.key!r} for role {mark.role!r} must cover contiguous lines once"
|
|
345
|
+
)
|
|
346
|
+
add(mark.role, mark.key, first, len(indices))
|
|
347
|
+
return tuple(runs), marks
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def _split_indent(line: TextLine) -> tuple[tuple[TextSpan, ...], TextLine]:
|
|
351
|
+
# Keep legacy backgrounds attached to their original text geometry.
|
|
352
|
+
if line.background_style is not None:
|
|
353
|
+
return (), line
|
|
354
|
+
prefix = []
|
|
355
|
+
for index, span in enumerate(line.spans):
|
|
356
|
+
text = span.text.lstrip(" \t")
|
|
357
|
+
if text != span.text:
|
|
358
|
+
if span.background_style is not None:
|
|
359
|
+
return (), line
|
|
360
|
+
prefix.append(replace(span, text=span.text[: len(span.text) - len(text)]))
|
|
361
|
+
if text:
|
|
362
|
+
if not prefix:
|
|
363
|
+
return (), line
|
|
364
|
+
remaining = (replace(span, text=text), *line.spans[index + 1 :])
|
|
365
|
+
# Expand tabs at their original columns, including tabs inside the line.
|
|
366
|
+
column = len("".join(part.text for part in prefix).expandtabs(4))
|
|
367
|
+
expanded = []
|
|
368
|
+
for part in remaining:
|
|
369
|
+
value = (" " * (column % 4) + part.text).expandtabs(4)[column % 4 :]
|
|
370
|
+
column += len(value)
|
|
371
|
+
expanded.append(replace(part, text=value))
|
|
372
|
+
return tuple(prefix), TextLine(*expanded)
|
|
373
|
+
return (), line
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
@dataclass(frozen=True)
|
|
377
|
+
class _CodeMark(CompositeView):
|
|
378
|
+
view: View
|
|
379
|
+
|
|
380
|
+
def body(self, context: Context) -> View:
|
|
381
|
+
return self.view
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
class _CodeListing(LayoutView):
|
|
385
|
+
def __init__(self, layout: _CodeLayout, *children: View) -> None:
|
|
386
|
+
super().__init__(*children)
|
|
387
|
+
object.__setattr__(self, "_layout", layout)
|
|
388
|
+
|
|
389
|
+
_layout: _CodeLayout
|
|
390
|
+
|
|
391
|
+
def resolve_layout(self, lookup: Callable[[str], ViewIdentity]) -> Layout:
|
|
392
|
+
return self._layout
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def _measured_lines(plan: LayoutPlan) -> tuple[MeasuredTextLine, ...]:
|
|
396
|
+
text = plan.properties["measured_text"]
|
|
397
|
+
assert isinstance(text, MeasuredRichText)
|
|
398
|
+
return text.lines
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
@dataclass(frozen=True)
|
|
402
|
+
class _CodeLayout:
|
|
403
|
+
animated: bool
|
|
404
|
+
indented_lines: tuple[int, ...]
|
|
405
|
+
runs: tuple[CodeMarkRun, ...]
|
|
406
|
+
region: CodeMarkRegion
|
|
407
|
+
|
|
408
|
+
def measure(
|
|
409
|
+
self,
|
|
410
|
+
proposal: ProposedSize,
|
|
411
|
+
children: Sequence[LayoutChild],
|
|
412
|
+
context: LayoutContext,
|
|
413
|
+
) -> LayoutPlan:
|
|
414
|
+
text_count = len(children) - len(self.indented_lines) - len(self.runs)
|
|
415
|
+
texts = children[:text_count]
|
|
416
|
+
indent_children = children[text_count : text_count + len(self.indented_lines)]
|
|
417
|
+
mark_children = children[text_count + len(self.indented_lines) :]
|
|
418
|
+
plans = [text.measure(proposal) for text in texts]
|
|
419
|
+
if self.animated or self.runs:
|
|
420
|
+
plans = [
|
|
421
|
+
replace(plan, properties={**plan.properties, "place_text_rows": True})
|
|
422
|
+
for plan in plans
|
|
423
|
+
]
|
|
424
|
+
if self.animated:
|
|
425
|
+
indents = {
|
|
426
|
+
index: child.measure(proposal)
|
|
427
|
+
for index, child in zip(self.indented_lines, indent_children)
|
|
428
|
+
}
|
|
429
|
+
width = max(
|
|
430
|
+
(plan.width + indents[index].width if index in indents else plan.width)
|
|
431
|
+
for index, plan in enumerate(plans)
|
|
432
|
+
)
|
|
433
|
+
text_placements = []
|
|
434
|
+
edges = [pt(0)]
|
|
435
|
+
for index, (child, plan) in enumerate(zip(texts, plans)):
|
|
436
|
+
indent = indents.get(index)
|
|
437
|
+
baseline = _measured_lines(plan)[0].baseline
|
|
438
|
+
offset = (
|
|
439
|
+
max(pt(0), _measured_lines(indent)[0].baseline - baseline)
|
|
440
|
+
if indent is not None
|
|
441
|
+
else pt(0)
|
|
442
|
+
)
|
|
443
|
+
text_placements.append(
|
|
444
|
+
Placement(
|
|
445
|
+
child,
|
|
446
|
+
plan,
|
|
447
|
+
indent.width if indent is not None else pt(0),
|
|
448
|
+
edges[-1] + offset,
|
|
449
|
+
)
|
|
450
|
+
)
|
|
451
|
+
height = max(
|
|
452
|
+
plan.height + offset, indent.height if indent is not None else pt(0)
|
|
453
|
+
)
|
|
454
|
+
edges.append(edges[-1] + height)
|
|
455
|
+
else:
|
|
456
|
+
plan = plans[0]
|
|
457
|
+
width = plan.width
|
|
458
|
+
text_placements = [Placement(texts[0], plan)]
|
|
459
|
+
edges = [pt(0)]
|
|
460
|
+
for line in _measured_lines(plan):
|
|
461
|
+
edges.append(edges[-1] + line.height)
|
|
462
|
+
|
|
463
|
+
region_width = (
|
|
464
|
+
(
|
|
465
|
+
proposal.width
|
|
466
|
+
if self.region.fill_width and proposal.width is not None
|
|
467
|
+
else width
|
|
468
|
+
)
|
|
469
|
+
+ self.region.leading
|
|
470
|
+
+ self.region.trailing
|
|
471
|
+
)
|
|
472
|
+
mark_placements = []
|
|
473
|
+
for child, run in zip(mark_children, self.runs):
|
|
474
|
+
top, bottom = edges[run.first_line], edges[run.first_line + run.line_count]
|
|
475
|
+
plan = child.measure(ProposedSize(region_width, bottom - top))
|
|
476
|
+
mark_placements.append(
|
|
477
|
+
Placement(
|
|
478
|
+
child, plan, -self.region.leading, top, propagates_guides=False
|
|
479
|
+
)
|
|
480
|
+
)
|
|
481
|
+
return LayoutPlan(width, edges[-1], (*mark_placements, *text_placements))
|