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,175 @@
|
|
|
1
|
+
"""Lower backend-neutral builds into a PowerPoint-oriented animation plan."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from contextlib import nullcontext
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from enum import Enum
|
|
8
|
+
|
|
9
|
+
from .._diagnostics import SlideLocation
|
|
10
|
+
from ..animation import (
|
|
11
|
+
AfterPrevious,
|
|
12
|
+
AnimationProgram,
|
|
13
|
+
EffectInstance,
|
|
14
|
+
EffectKind,
|
|
15
|
+
FallbackPolicy,
|
|
16
|
+
OnAdvance,
|
|
17
|
+
TransitionEffect,
|
|
18
|
+
WithPrevious,
|
|
19
|
+
)
|
|
20
|
+
from ..compiler import CompiledSlide
|
|
21
|
+
from ..drawables import Bounds
|
|
22
|
+
from ..units import pt
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class PptxTrigger(str, Enum):
|
|
26
|
+
ON_CLICK = "on-click"
|
|
27
|
+
WITH_PREVIOUS = "with-previous"
|
|
28
|
+
AFTER_PREVIOUS = "after-previous"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class PptxBehaviorKind(str, Enum):
|
|
32
|
+
APPEAR = "appear"
|
|
33
|
+
DISAPPEAR = "disappear"
|
|
34
|
+
FADE_IN = "fade-in"
|
|
35
|
+
FADE_OUT = "fade-out"
|
|
36
|
+
MOTION = "motion"
|
|
37
|
+
CROSSFADE = "crossfade"
|
|
38
|
+
DISCRETE = "discrete"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass(frozen=True)
|
|
42
|
+
class PptxBehavior:
|
|
43
|
+
identity: str
|
|
44
|
+
kind: PptxBehaviorKind
|
|
45
|
+
duration_ms: int
|
|
46
|
+
delay_ms: int
|
|
47
|
+
before: Bounds | None = None
|
|
48
|
+
after: Bounds | None = None
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass(frozen=True)
|
|
52
|
+
class PptxBuild:
|
|
53
|
+
trigger: PptxTrigger
|
|
54
|
+
delay_ms: int
|
|
55
|
+
behaviors: tuple[PptxBehavior, ...]
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@dataclass(frozen=True)
|
|
59
|
+
class PptxLoweringDiagnostic:
|
|
60
|
+
identity: str
|
|
61
|
+
message: str
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@dataclass(frozen=True)
|
|
65
|
+
class PptxAnimationPlan:
|
|
66
|
+
builds: tuple[PptxBuild, ...]
|
|
67
|
+
diagnostics: tuple[PptxLoweringDiagnostic, ...] = ()
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class PptxLoweringError(ValueError):
|
|
71
|
+
pass
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _unsupported(
|
|
75
|
+
effect: EffectInstance, message: str
|
|
76
|
+
) -> tuple[PptxBehaviorKind, PptxLoweringDiagnostic | None]:
|
|
77
|
+
assert effect.animation is not None
|
|
78
|
+
fallback = effect.animation.fallback
|
|
79
|
+
if fallback is FallbackPolicy.ERROR:
|
|
80
|
+
raise PptxLoweringError(f"{effect.identity}: {message}")
|
|
81
|
+
if fallback is FallbackPolicy.DISCRETE:
|
|
82
|
+
return PptxBehaviorKind.DISCRETE, None
|
|
83
|
+
return PptxBehaviorKind.CROSSFADE, PptxLoweringDiagnostic(
|
|
84
|
+
effect.identity, f"{message}; using a crossfade"
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _trigger(value: object) -> tuple[PptxTrigger, int]:
|
|
89
|
+
if isinstance(value, OnAdvance):
|
|
90
|
+
return PptxTrigger.ON_CLICK, 0
|
|
91
|
+
if isinstance(value, WithPrevious):
|
|
92
|
+
return PptxTrigger.WITH_PREVIOUS, round(value.delay * 1000)
|
|
93
|
+
if isinstance(value, AfterPrevious):
|
|
94
|
+
return PptxTrigger.AFTER_PREVIOUS, round(value.delay * 1000)
|
|
95
|
+
raise TypeError(f"Unsupported build trigger: {type(value).__name__}")
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _same_size(before: Bounds, after: Bounds) -> bool:
|
|
99
|
+
# Layout arithmetic can introduce roundoff below one DrawingML unit.
|
|
100
|
+
emu = pt(1 / 12_700)
|
|
101
|
+
return all(
|
|
102
|
+
-emu < difference < emu
|
|
103
|
+
for difference in (after.width - before.width, after.height - before.height)
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _lower_effect(
|
|
108
|
+
effect: EffectInstance,
|
|
109
|
+
) -> tuple[PptxBehavior, PptxLoweringDiagnostic | None]:
|
|
110
|
+
before = effect.before.bounds if effect.before is not None else None
|
|
111
|
+
after = effect.after.bounds if effect.after is not None else None
|
|
112
|
+
animation = effect.animation
|
|
113
|
+
transition = effect.transition
|
|
114
|
+
timing = transition.animation if transition is not None else animation
|
|
115
|
+
assert timing is not None
|
|
116
|
+
duration = round(timing.duration * 1000)
|
|
117
|
+
delay = round(timing.delay * 1000)
|
|
118
|
+
diagnostic = None
|
|
119
|
+
|
|
120
|
+
if effect.kind is EffectKind.INSERT:
|
|
121
|
+
kind = (
|
|
122
|
+
PptxBehaviorKind.FADE_IN
|
|
123
|
+
if transition is not None and transition.insertion is TransitionEffect.FADE
|
|
124
|
+
else PptxBehaviorKind.APPEAR
|
|
125
|
+
)
|
|
126
|
+
elif effect.kind is EffectKind.REMOVE:
|
|
127
|
+
kind = (
|
|
128
|
+
PptxBehaviorKind.FADE_OUT
|
|
129
|
+
if transition is not None and transition.removal is TransitionEffect.FADE
|
|
130
|
+
else PptxBehaviorKind.DISAPPEAR
|
|
131
|
+
)
|
|
132
|
+
elif effect.kind is EffectKind.MOVE and before is not None and after is not None:
|
|
133
|
+
if animation.is_discrete:
|
|
134
|
+
kind = PptxBehaviorKind.DISCRETE
|
|
135
|
+
elif _same_size(before, after):
|
|
136
|
+
kind = PptxBehaviorKind.MOTION
|
|
137
|
+
else:
|
|
138
|
+
kind, diagnostic = _unsupported(
|
|
139
|
+
effect, "PPTX cannot reliably reproduce this resize"
|
|
140
|
+
)
|
|
141
|
+
elif effect.kind is EffectKind.CHANGE:
|
|
142
|
+
if animation.is_discrete:
|
|
143
|
+
kind = PptxBehaviorKind.DISCRETE
|
|
144
|
+
else:
|
|
145
|
+
kind, diagnostic = _unsupported(effect, "Visual content changed")
|
|
146
|
+
else:
|
|
147
|
+
kind = PptxBehaviorKind.DISCRETE
|
|
148
|
+
|
|
149
|
+
return PptxBehavior(
|
|
150
|
+
effect.identity, kind, duration, delay, before, after
|
|
151
|
+
), diagnostic
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def plan(
|
|
155
|
+
program: AnimationProgram, *, location: SlideLocation | None = None
|
|
156
|
+
) -> PptxAnimationPlan:
|
|
157
|
+
builds = []
|
|
158
|
+
diagnostics = []
|
|
159
|
+
for step, build in enumerate(program.builds, start=1):
|
|
160
|
+
with location.context(step) if location else nullcontext():
|
|
161
|
+
trigger, trigger_delay = _trigger(build.trigger)
|
|
162
|
+
behaviors = []
|
|
163
|
+
for effect in build.effects:
|
|
164
|
+
behavior, diagnostic = _lower_effect(effect)
|
|
165
|
+
behaviors.append(behavior)
|
|
166
|
+
if diagnostic is not None:
|
|
167
|
+
diagnostics.append(diagnostic)
|
|
168
|
+
builds.append(PptxBuild(trigger, trigger_delay, tuple(behaviors)))
|
|
169
|
+
return PptxAnimationPlan(tuple(builds), tuple(diagnostics))
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def plan_slide(
|
|
173
|
+
slide: CompiledSlide, *, location: SlideLocation | None = None
|
|
174
|
+
) -> PptxAnimationPlan:
|
|
175
|
+
return plan(slide.animation, location=location)
|
deckkit/backends/svg.py
ADDED
|
@@ -0,0 +1,527 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from base64 import b64encode
|
|
4
|
+
from io import BytesIO
|
|
5
|
+
from math import cos, radians, sin
|
|
6
|
+
from os import PathLike
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import TYPE_CHECKING
|
|
9
|
+
from xml.etree.ElementTree import Element, SubElement, tostring
|
|
10
|
+
|
|
11
|
+
from .._diagnostics import SlideLocation
|
|
12
|
+
from ..drawables import (
|
|
13
|
+
Bounds,
|
|
14
|
+
Drawable,
|
|
15
|
+
DrawableConnector,
|
|
16
|
+
DrawableEllipse,
|
|
17
|
+
DrawableGroup,
|
|
18
|
+
DrawableImage,
|
|
19
|
+
DrawableLine,
|
|
20
|
+
DrawablePath,
|
|
21
|
+
DrawableRectangle,
|
|
22
|
+
DrawableRichText,
|
|
23
|
+
DrawableText,
|
|
24
|
+
PathClose,
|
|
25
|
+
PathCubic,
|
|
26
|
+
PathLine,
|
|
27
|
+
PathMove,
|
|
28
|
+
PathQuadratic,
|
|
29
|
+
)
|
|
30
|
+
from ..effects import ResolvedShadow
|
|
31
|
+
from ..fonts import ResolvedFont
|
|
32
|
+
from ..paint import ResolvedLinearGradient
|
|
33
|
+
from ..units import Length, pt
|
|
34
|
+
from ._font_embedding import open_embeddable_font
|
|
35
|
+
|
|
36
|
+
if TYPE_CHECKING:
|
|
37
|
+
from ..compiler import CompiledDeck
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _font_weight(face: ResolvedFont) -> str:
|
|
41
|
+
weight = face.numeric_weight
|
|
42
|
+
return {400: "normal", 700: "bold"}.get(weight, str(weight))
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _embed_fonts(root: Element, layout: Drawable) -> dict[tuple[str, int], str]:
|
|
46
|
+
aliases: dict[tuple[str, int], str] = {}
|
|
47
|
+
rules = []
|
|
48
|
+
for node in layout.walk():
|
|
49
|
+
if not isinstance(node, DrawableText):
|
|
50
|
+
continue
|
|
51
|
+
face = node.font
|
|
52
|
+
key = (face.path, face.index)
|
|
53
|
+
if key in aliases:
|
|
54
|
+
continue
|
|
55
|
+
alias = f"deckkit-font-{len(aliases) + 1}"
|
|
56
|
+
aliases[key] = alias
|
|
57
|
+
buffer = BytesIO()
|
|
58
|
+
with open_embeddable_font(face.path, face.index) as font:
|
|
59
|
+
font.flavor = "woff"
|
|
60
|
+
font.save(buffer)
|
|
61
|
+
data = b64encode(buffer.getvalue()).decode("ascii")
|
|
62
|
+
style = "italic" if face.italic else "normal"
|
|
63
|
+
rules.append(
|
|
64
|
+
f"@font-face {{ font-family: {alias}; font-weight: {_font_weight(face)}; "
|
|
65
|
+
f"font-style: {style}; src: url(data:font/woff;base64,{data}) format('woff'); }}"
|
|
66
|
+
)
|
|
67
|
+
if rules:
|
|
68
|
+
SubElement(root, "style").text = "\n".join(rules)
|
|
69
|
+
return aliases
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def render(layout: Drawable, *, embed_fonts: bool = False) -> str:
|
|
73
|
+
"""Render a scene, optionally including the faces used to measure its text."""
|
|
74
|
+
viewport = Bounds(pt(0), pt(0), layout.bounds.width, layout.bounds.height)
|
|
75
|
+
return _render(layout, viewport, embed_fonts=embed_fonts, background=True)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def write_svg(
|
|
79
|
+
deck: CompiledDeck,
|
|
80
|
+
path: str | PathLike[str],
|
|
81
|
+
*,
|
|
82
|
+
slide: int = 1,
|
|
83
|
+
step: int = 0,
|
|
84
|
+
embed_fonts: bool = False,
|
|
85
|
+
) -> Path:
|
|
86
|
+
"""Write one state from an already compiled deck."""
|
|
87
|
+
if isinstance(slide, bool) or not isinstance(slide, int):
|
|
88
|
+
raise TypeError("Slide number must be an integer")
|
|
89
|
+
if isinstance(step, bool) or not isinstance(step, int):
|
|
90
|
+
raise TypeError("Build step must be an integer")
|
|
91
|
+
if not 1 <= slide <= len(deck.slides):
|
|
92
|
+
raise IndexError(
|
|
93
|
+
f"Slide {slide} is out of range for a {len(deck.slides)}-slide deck"
|
|
94
|
+
)
|
|
95
|
+
compiled = deck.slides[slide - 1]
|
|
96
|
+
states = compiled.states
|
|
97
|
+
if not 0 <= step < len(states):
|
|
98
|
+
raise IndexError(f"Build step {step} is out of range for slide {slide}")
|
|
99
|
+
with SlideLocation(slide, compiled.label).context(step):
|
|
100
|
+
return _write_scene(states[step].drawable, Path(path), embed_fonts=embed_fonts)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def write_svgs(
|
|
104
|
+
deck: CompiledDeck,
|
|
105
|
+
directory: str | PathLike[str],
|
|
106
|
+
*,
|
|
107
|
+
all_states: bool = False,
|
|
108
|
+
embed_fonts: bool = False,
|
|
109
|
+
) -> tuple[Path, ...]:
|
|
110
|
+
"""Write numbered SVGs in slide and step order from a compiled deck."""
|
|
111
|
+
target = Path(directory)
|
|
112
|
+
target.mkdir(parents=True, exist_ok=True)
|
|
113
|
+
paths = []
|
|
114
|
+
for number, slide in enumerate(deck.slides, start=1):
|
|
115
|
+
location = SlideLocation(number, slide.label)
|
|
116
|
+
states = slide.states if all_states else (slide.initial,)
|
|
117
|
+
for step, state in enumerate(states):
|
|
118
|
+
path = target / f"slide-{number:02d}-state-{step:02d}.svg"
|
|
119
|
+
with location.context(step):
|
|
120
|
+
paths.append(
|
|
121
|
+
_write_scene(state.drawable, path, embed_fonts=embed_fonts)
|
|
122
|
+
)
|
|
123
|
+
return tuple(paths)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _write_scene(layout: Drawable, path: Path, *, embed_fonts: bool) -> Path:
|
|
127
|
+
path.write_text(render(layout, embed_fonts=embed_fonts), encoding="utf-8")
|
|
128
|
+
return path
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _render(
|
|
132
|
+
layout: Drawable,
|
|
133
|
+
viewport: Bounds,
|
|
134
|
+
*,
|
|
135
|
+
embed_fonts: bool = False,
|
|
136
|
+
background: bool = False,
|
|
137
|
+
shadow_only: bool = False,
|
|
138
|
+
) -> str:
|
|
139
|
+
root = Element(
|
|
140
|
+
"svg",
|
|
141
|
+
xmlns="http://www.w3.org/2000/svg",
|
|
142
|
+
width=f"{viewport.width.points:g}pt",
|
|
143
|
+
height=f"{viewport.height.points:g}pt",
|
|
144
|
+
viewBox=(
|
|
145
|
+
f"{viewport.x.points:g} {viewport.y.points:g} "
|
|
146
|
+
f"{viewport.width.points:g} {viewport.height.points:g}"
|
|
147
|
+
),
|
|
148
|
+
)
|
|
149
|
+
font_aliases = _embed_fonts(root, layout) if embed_fonts else {}
|
|
150
|
+
if background:
|
|
151
|
+
SubElement(root, "rect", width="100%", height="100%", fill="white")
|
|
152
|
+
|
|
153
|
+
marker_count = 0
|
|
154
|
+
gradients: dict[tuple[Bounds, ResolvedLinearGradient], str] = {}
|
|
155
|
+
shadows: dict[tuple[ResolvedShadow, bool], str] = {}
|
|
156
|
+
clips: dict[Bounds, str] = {}
|
|
157
|
+
definitions: Element | None = None
|
|
158
|
+
|
|
159
|
+
def defs() -> Element:
|
|
160
|
+
nonlocal definitions
|
|
161
|
+
if definitions is None:
|
|
162
|
+
definitions = SubElement(root, "defs")
|
|
163
|
+
return definitions
|
|
164
|
+
|
|
165
|
+
def gradient_fill(bounds: Bounds, gradient: ResolvedLinearGradient) -> str:
|
|
166
|
+
key = (bounds, gradient)
|
|
167
|
+
if key not in gradients:
|
|
168
|
+
identifier = f"deckkit-gradient-{len(gradients) + 1}"
|
|
169
|
+
gradients[key] = f"url(#{identifier})"
|
|
170
|
+
angle = radians(gradient.angle)
|
|
171
|
+
dx, dy = cos(angle), sin(angle)
|
|
172
|
+
width, height = bounds.width.points, bounds.height.points
|
|
173
|
+
half = (abs(dx) * width + abs(dy) * height) / 2
|
|
174
|
+
cx = bounds.x.points + width / 2
|
|
175
|
+
cy = bounds.y.points + height / 2
|
|
176
|
+
definition = SubElement(
|
|
177
|
+
defs(),
|
|
178
|
+
"linearGradient",
|
|
179
|
+
id=identifier,
|
|
180
|
+
gradientUnits="userSpaceOnUse",
|
|
181
|
+
x1=f"{cx - half * dx:g}",
|
|
182
|
+
y1=f"{cy - half * dy:g}",
|
|
183
|
+
x2=f"{cx + half * dx:g}",
|
|
184
|
+
y2=f"{cy + half * dy:g}",
|
|
185
|
+
)
|
|
186
|
+
for stop in gradient.stops:
|
|
187
|
+
SubElement(
|
|
188
|
+
definition,
|
|
189
|
+
"stop",
|
|
190
|
+
offset=str(stop.offset),
|
|
191
|
+
attrib={
|
|
192
|
+
"stop-color": stop.color,
|
|
193
|
+
"stop-opacity": str(stop.opacity),
|
|
194
|
+
},
|
|
195
|
+
)
|
|
196
|
+
return gradients[key]
|
|
197
|
+
|
|
198
|
+
def shadow_filter(shadow: ResolvedShadow, only: bool) -> str:
|
|
199
|
+
key = (shadow, only)
|
|
200
|
+
if key not in shadows:
|
|
201
|
+
identifier = f"deckkit-shadow-{len(shadows) + 1}"
|
|
202
|
+
shadows[key] = f"url(#{identifier})"
|
|
203
|
+
# Include source pixels just outside the viewport that can cast into it.
|
|
204
|
+
inset_x = shadow.radius.points * 4 + abs(shadow.x.points)
|
|
205
|
+
inset_y = shadow.radius.points * 4 + abs(shadow.y.points)
|
|
206
|
+
effect = SubElement(
|
|
207
|
+
defs(),
|
|
208
|
+
"filter",
|
|
209
|
+
id=identifier,
|
|
210
|
+
filterUnits="userSpaceOnUse",
|
|
211
|
+
x=str(viewport.x.points - inset_x),
|
|
212
|
+
y=str(viewport.y.points - inset_y),
|
|
213
|
+
width=str(viewport.width.points + 2 * inset_x),
|
|
214
|
+
height=str(viewport.height.points + 2 * inset_y),
|
|
215
|
+
attrib={"color-interpolation-filters": "sRGB"},
|
|
216
|
+
)
|
|
217
|
+
SubElement(
|
|
218
|
+
effect,
|
|
219
|
+
"feGaussianBlur",
|
|
220
|
+
stdDeviation=str(shadow.radius.points),
|
|
221
|
+
attrib={"in": "SourceAlpha"},
|
|
222
|
+
)
|
|
223
|
+
SubElement(
|
|
224
|
+
effect,
|
|
225
|
+
"feOffset",
|
|
226
|
+
dx=str(shadow.x.points),
|
|
227
|
+
dy=str(shadow.y.points),
|
|
228
|
+
result="offset",
|
|
229
|
+
)
|
|
230
|
+
SubElement(
|
|
231
|
+
effect,
|
|
232
|
+
"feFlood",
|
|
233
|
+
attrib={
|
|
234
|
+
"flood-color": shadow.color,
|
|
235
|
+
"flood-opacity": str(shadow.opacity),
|
|
236
|
+
},
|
|
237
|
+
)
|
|
238
|
+
SubElement(
|
|
239
|
+
effect, "feComposite", in2="offset", operator="in", result="shadow"
|
|
240
|
+
)
|
|
241
|
+
if not only:
|
|
242
|
+
merge = SubElement(effect, "feMerge")
|
|
243
|
+
SubElement(merge, "feMergeNode", attrib={"in": "shadow"})
|
|
244
|
+
SubElement(merge, "feMergeNode", attrib={"in": "SourceGraphic"})
|
|
245
|
+
return shadows[key]
|
|
246
|
+
|
|
247
|
+
def clip_path(bounds: Bounds) -> str:
|
|
248
|
+
if bounds not in clips:
|
|
249
|
+
identifier = f"deckkit-shadow-clip-{len(clips) + 1}"
|
|
250
|
+
clips[bounds] = f"url(#{identifier})"
|
|
251
|
+
clip = SubElement(defs(), "clipPath", id=identifier)
|
|
252
|
+
SubElement(
|
|
253
|
+
clip,
|
|
254
|
+
"rect",
|
|
255
|
+
x=str(bounds.x.points),
|
|
256
|
+
y=str(bounds.y.points),
|
|
257
|
+
width=str(bounds.width.points),
|
|
258
|
+
height=str(bounds.height.points),
|
|
259
|
+
)
|
|
260
|
+
return clips[bounds]
|
|
261
|
+
|
|
262
|
+
def visit(node: Drawable, parent: Element, text_fill: str | None = None) -> None:
|
|
263
|
+
nonlocal marker_count
|
|
264
|
+
group = SubElement(parent, "g", id=node.identity)
|
|
265
|
+
if node.metadata.grouped:
|
|
266
|
+
group.set("data-deckkit-group", "true")
|
|
267
|
+
if node.metadata.shadow is not None:
|
|
268
|
+
if node.metadata.shadow_clip is not None:
|
|
269
|
+
group.set("clip-path", clip_path(node.metadata.shadow_clip))
|
|
270
|
+
group = SubElement(group, "g")
|
|
271
|
+
group.set(
|
|
272
|
+
"filter",
|
|
273
|
+
shadow_filter(node.metadata.shadow, shadow_only and node is layout),
|
|
274
|
+
)
|
|
275
|
+
group = SubElement(group, "g")
|
|
276
|
+
opacity = node.metadata.opacity
|
|
277
|
+
if isinstance(
|
|
278
|
+
node, (DrawableText, DrawableRectangle, DrawableEllipse, DrawableImage)
|
|
279
|
+
):
|
|
280
|
+
b = node.content_bounds
|
|
281
|
+
x, y, w, h = b.x.points, b.y.points, b.width.points, b.height.points
|
|
282
|
+
if isinstance(node, DrawableRectangle):
|
|
283
|
+
attributes = {
|
|
284
|
+
"x": str(x),
|
|
285
|
+
"y": str(y),
|
|
286
|
+
"width": str(w),
|
|
287
|
+
"height": str(h),
|
|
288
|
+
"fill": (
|
|
289
|
+
gradient_fill(node.content_bounds, node.gradient)
|
|
290
|
+
if node.gradient is not None
|
|
291
|
+
else node.color
|
|
292
|
+
),
|
|
293
|
+
}
|
|
294
|
+
if node.stroke is not None:
|
|
295
|
+
attributes.update(
|
|
296
|
+
_stroke_attributes(
|
|
297
|
+
node.stroke,
|
|
298
|
+
node.stroke_width,
|
|
299
|
+
node.dash,
|
|
300
|
+
node.line_cap,
|
|
301
|
+
node.line_join,
|
|
302
|
+
)
|
|
303
|
+
)
|
|
304
|
+
attributes["stroke-opacity"] = str(
|
|
305
|
+
node.stroke_opacity
|
|
306
|
+
if opacity == 1
|
|
307
|
+
else node.stroke_opacity * opacity
|
|
308
|
+
)
|
|
309
|
+
attributes["fill-opacity"] = str(
|
|
310
|
+
node.fill_opacity if opacity == 1 else node.fill_opacity * opacity
|
|
311
|
+
)
|
|
312
|
+
if node.corner_radius.points > 0:
|
|
313
|
+
attributes["rx"] = attributes["ry"] = str(node.corner_radius.points)
|
|
314
|
+
SubElement(group, "rect", attributes)
|
|
315
|
+
elif isinstance(node, DrawableEllipse):
|
|
316
|
+
attributes = {
|
|
317
|
+
"cx": str(x + w / 2),
|
|
318
|
+
"cy": str(y + h / 2),
|
|
319
|
+
"rx": str(w / 2),
|
|
320
|
+
"ry": str(h / 2),
|
|
321
|
+
"fill": node.fill or "none",
|
|
322
|
+
}
|
|
323
|
+
if node.stroke is not None:
|
|
324
|
+
attributes.update(
|
|
325
|
+
_stroke_attributes(
|
|
326
|
+
node.stroke,
|
|
327
|
+
node.stroke_width,
|
|
328
|
+
node.dash,
|
|
329
|
+
node.line_cap,
|
|
330
|
+
node.line_join,
|
|
331
|
+
)
|
|
332
|
+
)
|
|
333
|
+
attributes["stroke-opacity"] = str(
|
|
334
|
+
node.stroke_opacity
|
|
335
|
+
if opacity == 1
|
|
336
|
+
else node.stroke_opacity * opacity
|
|
337
|
+
)
|
|
338
|
+
attributes["fill-opacity"] = str(
|
|
339
|
+
node.fill_opacity if opacity == 1 else node.fill_opacity * opacity
|
|
340
|
+
)
|
|
341
|
+
SubElement(group, "ellipse", attributes)
|
|
342
|
+
elif isinstance(node, DrawableLine):
|
|
343
|
+
attributes = {
|
|
344
|
+
"x1": str(node.start.x.points),
|
|
345
|
+
"y1": str(node.start.y.points),
|
|
346
|
+
"x2": str(node.end.x.points),
|
|
347
|
+
"y2": str(node.end.y.points),
|
|
348
|
+
}
|
|
349
|
+
attributes.update(
|
|
350
|
+
_stroke_attributes(
|
|
351
|
+
node.color,
|
|
352
|
+
node.width,
|
|
353
|
+
node.dash,
|
|
354
|
+
node.line_cap,
|
|
355
|
+
node.line_join,
|
|
356
|
+
)
|
|
357
|
+
)
|
|
358
|
+
attributes["stroke-opacity"] = str(
|
|
359
|
+
node.opacity if opacity == 1 else node.opacity * opacity
|
|
360
|
+
)
|
|
361
|
+
SubElement(group, "line", attributes)
|
|
362
|
+
elif isinstance(node, DrawablePath):
|
|
363
|
+
parts = []
|
|
364
|
+
for command in node.commands:
|
|
365
|
+
if isinstance(command, PathMove):
|
|
366
|
+
parts.append(
|
|
367
|
+
f"M {command.point.x.points:g} {command.point.y.points:g}"
|
|
368
|
+
)
|
|
369
|
+
elif isinstance(command, PathLine):
|
|
370
|
+
parts.append(
|
|
371
|
+
f"L {command.point.x.points:g} {command.point.y.points:g}"
|
|
372
|
+
)
|
|
373
|
+
elif isinstance(command, PathQuadratic):
|
|
374
|
+
parts.append(
|
|
375
|
+
f"Q {command.control.x.points:g} {command.control.y.points:g} "
|
|
376
|
+
f"{command.end.x.points:g} {command.end.y.points:g}"
|
|
377
|
+
)
|
|
378
|
+
elif isinstance(command, PathCubic):
|
|
379
|
+
parts.append(
|
|
380
|
+
f"C {command.control1.x.points:g} {command.control1.y.points:g} "
|
|
381
|
+
f"{command.control2.x.points:g} {command.control2.y.points:g} "
|
|
382
|
+
f"{command.end.x.points:g} {command.end.y.points:g}"
|
|
383
|
+
)
|
|
384
|
+
elif isinstance(command, PathClose):
|
|
385
|
+
parts.append("Z")
|
|
386
|
+
attributes = {"d": " ".join(parts), "fill": node.fill or "none"}
|
|
387
|
+
if node.stroke is not None:
|
|
388
|
+
attributes.update(
|
|
389
|
+
_stroke_attributes(
|
|
390
|
+
node.stroke,
|
|
391
|
+
node.stroke_width,
|
|
392
|
+
node.dash,
|
|
393
|
+
node.line_cap,
|
|
394
|
+
node.line_join,
|
|
395
|
+
)
|
|
396
|
+
)
|
|
397
|
+
attributes["stroke-opacity"] = str(
|
|
398
|
+
node.stroke_opacity
|
|
399
|
+
if opacity == 1
|
|
400
|
+
else node.stroke_opacity * opacity
|
|
401
|
+
)
|
|
402
|
+
attributes["fill-opacity"] = str(
|
|
403
|
+
node.fill_opacity if opacity == 1 else node.fill_opacity * opacity
|
|
404
|
+
)
|
|
405
|
+
SubElement(group, "path", attributes)
|
|
406
|
+
elif isinstance(node, DrawableText):
|
|
407
|
+
m = node.metrics
|
|
408
|
+
face = node.font
|
|
409
|
+
text_attributes = {
|
|
410
|
+
"{http://www.w3.org/XML/1998/namespace}space": "preserve",
|
|
411
|
+
"font-family": font_aliases.get(
|
|
412
|
+
(face.path, face.index), face.typographic_family or face.family
|
|
413
|
+
),
|
|
414
|
+
"font-size": str(node.font_size.points),
|
|
415
|
+
"font-weight": _font_weight(face),
|
|
416
|
+
"font-style": "italic" if face.italic else "normal",
|
|
417
|
+
}
|
|
418
|
+
if opacity < 1:
|
|
419
|
+
text_attributes["fill-opacity"] = str(opacity)
|
|
420
|
+
if node.rotation:
|
|
421
|
+
text_attributes["transform"] = (
|
|
422
|
+
f"rotate({node.rotation:g} {x + w / 2:g} {y + h / 2:g})"
|
|
423
|
+
)
|
|
424
|
+
if node.gradient is not None:
|
|
425
|
+
text_fill = gradient_fill(node.content_bounds, node.gradient)
|
|
426
|
+
for i, line in enumerate(m.lines):
|
|
427
|
+
SubElement(
|
|
428
|
+
group,
|
|
429
|
+
"text",
|
|
430
|
+
x=str(x),
|
|
431
|
+
y=str(y + m.baseline.points + i * m.line_height.points),
|
|
432
|
+
fill=text_fill or node.color,
|
|
433
|
+
attrib=text_attributes,
|
|
434
|
+
).text = line
|
|
435
|
+
elif isinstance(node, DrawableImage):
|
|
436
|
+
SubElement(
|
|
437
|
+
group,
|
|
438
|
+
"image",
|
|
439
|
+
x=str(x),
|
|
440
|
+
y=str(y),
|
|
441
|
+
width=str(w),
|
|
442
|
+
height=str(h),
|
|
443
|
+
href=f"data:{node.mime};base64,{b64encode(node.data).decode()}",
|
|
444
|
+
attrib={"opacity": str(opacity)} if opacity < 1 else {},
|
|
445
|
+
preserveAspectRatio="xMidYMid meet"
|
|
446
|
+
if node.fit == "contain"
|
|
447
|
+
else "xMidYMid slice",
|
|
448
|
+
)
|
|
449
|
+
elif isinstance(node, DrawableConnector):
|
|
450
|
+
attributes = {
|
|
451
|
+
"x1": str(node.start.x.points),
|
|
452
|
+
"y1": str(node.start.y.points),
|
|
453
|
+
"x2": str(node.end.x.points),
|
|
454
|
+
"y2": str(node.end.y.points),
|
|
455
|
+
"stroke-opacity": str(
|
|
456
|
+
node.opacity if opacity == 1 else node.opacity * opacity
|
|
457
|
+
),
|
|
458
|
+
}
|
|
459
|
+
attributes.update(
|
|
460
|
+
_stroke_attributes(
|
|
461
|
+
node.color, node.width, node.dash, node.line_cap, node.line_join
|
|
462
|
+
)
|
|
463
|
+
)
|
|
464
|
+
for cap, attribute, orient in (
|
|
465
|
+
(node.start_cap, "marker-start", "auto-start-reverse"),
|
|
466
|
+
(node.end_cap, "marker-end", "auto"),
|
|
467
|
+
):
|
|
468
|
+
if cap == "arrow":
|
|
469
|
+
marker_count += 1
|
|
470
|
+
marker_id = f"deckkit-arrow-{marker_count}"
|
|
471
|
+
marker = SubElement(
|
|
472
|
+
group,
|
|
473
|
+
"marker",
|
|
474
|
+
id=marker_id,
|
|
475
|
+
markerWidth="6",
|
|
476
|
+
markerHeight="6",
|
|
477
|
+
refX="5",
|
|
478
|
+
refY="3",
|
|
479
|
+
orient=orient,
|
|
480
|
+
markerUnits="strokeWidth",
|
|
481
|
+
)
|
|
482
|
+
SubElement(
|
|
483
|
+
marker,
|
|
484
|
+
"path",
|
|
485
|
+
d="M 0 0 L 6 3 L 0 6 z",
|
|
486
|
+
fill=node.color,
|
|
487
|
+
attrib={
|
|
488
|
+
"fill-opacity": str(
|
|
489
|
+
node.opacity if opacity == 1 else node.opacity * opacity
|
|
490
|
+
)
|
|
491
|
+
},
|
|
492
|
+
)
|
|
493
|
+
attributes[attribute] = f"url(#{marker_id})"
|
|
494
|
+
SubElement(group, "line", attributes)
|
|
495
|
+
elif isinstance(node, DrawableRichText):
|
|
496
|
+
if node.rotation:
|
|
497
|
+
bounds = node.content_bounds
|
|
498
|
+
cx = (bounds.x + bounds.width / 2).points
|
|
499
|
+
cy = (bounds.y + bounds.height / 2).points
|
|
500
|
+
group.set("transform", f"rotate({node.rotation:g} {cx:g} {cy:g})")
|
|
501
|
+
if node.gradient is not None:
|
|
502
|
+
text_fill = gradient_fill(node.content_bounds, node.gradient)
|
|
503
|
+
elif not isinstance(node, DrawableGroup):
|
|
504
|
+
raise TypeError(f"SVG cannot render {type(node).__name__}")
|
|
505
|
+
for child in node.children:
|
|
506
|
+
visit(child, group, text_fill)
|
|
507
|
+
|
|
508
|
+
visit(layout, root)
|
|
509
|
+
return tostring(root, encoding="unicode")
|
|
510
|
+
|
|
511
|
+
|
|
512
|
+
def _stroke_attributes(
|
|
513
|
+
color: str,
|
|
514
|
+
width: Length,
|
|
515
|
+
dash: tuple[Length, ...],
|
|
516
|
+
line_cap: str = "butt",
|
|
517
|
+
line_join: str = "miter",
|
|
518
|
+
) -> dict[str, str]:
|
|
519
|
+
result = {
|
|
520
|
+
"stroke": color,
|
|
521
|
+
"stroke-width": str(width.points),
|
|
522
|
+
"stroke-linecap": line_cap,
|
|
523
|
+
"stroke-linejoin": line_join,
|
|
524
|
+
}
|
|
525
|
+
if dash:
|
|
526
|
+
result["stroke-dasharray"] = " ".join(str(value.points) for value in dash)
|
|
527
|
+
return result
|