Coverage for src/ipyvizzustory/storylib/story.py: 100%
83 statements
« prev ^ index » next coverage.py v7.2.2, created at 2023-03-25 14:00 +0100
« prev ^ index » next coverage.py v7.2.2, created at 2023-03-25 14:00 +0100
1"""A module for working with presentation stories."""
3from typing import Optional, Union, List
4from os import PathLike
5import json
6import uuid
8from ipyvizzu import RawJavaScriptEncoder, Data, Style, Config # , PlainAnimation
10from ipyvizzustory.storylib.animation import DataFilter
11from ipyvizzustory.storylib.template import (
12 VIZZU_STORY,
13 DISPLAY_TEMPLATE,
14 DISPLAY_INDENT,
15)
18class Step(dict):
19 """A class for representing a step of a slide."""
21 def __init__(
22 self,
23 *animations: Union[Data, Style, Config],
24 **anim_options: Optional[Union[str, int, float, dict]],
25 ):
26 """
27 Step constructor.
29 Note:
30 Do not set `anim_options` argument, it will raise `NotImplementedError` error.
32 Args:
33 *animations: List of `ipyvizzu.Data`, `ipyvizzu.Config` and `ipyvizzu.Style` objects.
34 A `Step` can contain each of the above once.
35 **anim_options (optional): Animation options such as duration.
37 Raises:
38 ValueError: If `animations` are not set.
39 NotImplementedError: If `anim_options` are set.
40 """
42 super().__init__()
43 if not animations:
44 raise ValueError("No animation was set.")
45 self._update(*animations)
47 if anim_options:
48 # self["animOptions"] = PlainAnimation(**anim_options).build()
49 raise NotImplementedError("Anim options are not supported.")
51 def _update(self, *animations: Union[Data, Style, Config]) -> None:
52 for animation in animations:
53 if not animation or type(animation) not in [
54 Data,
55 Style,
56 Config,
57 ]: # pylint: disable=unidiomatic-typecheck
58 raise TypeError("Type must be Data, Style or Config.")
59 if type(animation) == Data: # pylint: disable=unidiomatic-typecheck
60 animation = DataFilter(animation)
62 builded_animation = animation.build()
63 common_keys = set(builded_animation).intersection(set(self))
64 if common_keys:
65 raise ValueError(f"Animation is already merged: {common_keys}")
66 self.update(builded_animation)
69class Slide(list):
70 """A class for representing a slide of a presentation story."""
72 def __init__(self, step: Optional[Step] = None):
73 """
74 Slide constructor.
76 Args:
77 step (optional): The first step can also be added to the slide in the constructor.
78 """
80 super().__init__()
81 if step:
82 self.add_step(step)
84 def add_step(self, step: Step) -> None:
85 """
86 A method for adding a step for the slide.
88 Args:
89 step: The next step of the slide.
91 Raises:
92 TypeError: If the type of the `step` is not `Step`.
93 """
95 if not step or type(step) != Step: # pylint: disable=unidiomatic-typecheck
96 raise TypeError("Type must be Step.")
97 self.append(step)
100class StorySize:
101 """A class for representing the size of a presentation story."""
103 def __init__(self, width: Optional[str] = None, height: Optional[str] = None):
104 """
105 StorySize constructor.
107 Args:
108 width (optional): The width of a presentation story.
109 height (optional): The height of a presentation story.
110 """
111 self._width = width
112 self._height = height
114 self._style = ""
115 if any([width is not None, height is not None]):
116 width = "" if width is None else f"width: {width};"
117 height = "" if height is None else f"height: {height};"
118 self._style = f"vizzuPlayer.style.cssText = '{width}{height}'"
120 @property
121 def width(self) -> Optional[str]:
122 """A property for returning the width of a presentation story."""
124 return self._width
126 @property
127 def height(self) -> Optional[str]:
128 """A property for returning the height of a presentation story."""
130 return self._height
132 @property
133 def style(self) -> str:
134 """
135 A property for returning the cssText width and height of a presentation story.
137 Note:
138 If `width` and `height` are not set it returns an empty string.
139 """
141 return self._style
144class Story(dict):
145 """A class for representing a presentation story."""
147 def __init__(self, data: Data, style: Optional[Style] = None):
148 """
149 Presentation Story constructor.
151 Args:
152 data: Data set for the whole presentation story.
153 After initialization `data` can not be modified,
154 but it can be filtered.
155 style (optional): Style settings for the presentation story.
156 `style` can be changed at each presentation step.
158 Raises:
159 TypeError: If the type of the `data` is not `ipyvizzu.Data`.
160 TypeError: If the type of the `style` is not `ipyvizzu.Style`.
161 """
163 super().__init__()
165 self._size: StorySize = StorySize()
167 self._features: List[str] = []
168 self._events: List[str] = []
170 if not data or type(data) != Data: # pylint: disable=unidiomatic-typecheck
171 raise TypeError("Type must be Data.")
172 self.update(data.build())
174 if style:
175 if type(style) != Style: # pylint: disable=unidiomatic-typecheck
176 raise TypeError("Type must be Style.")
177 self.update(style.build())
179 self["slides"] = []
181 def add_slide(self, slide: Slide) -> None:
182 """
183 A method for adding a slide for the story.
185 Args:
186 slide: The next slide of the story.
188 Raises:
189 TypeError: If the type of the `slide` is not `Slide`.
190 """
192 if not slide or type(slide) != Slide: # pylint: disable=unidiomatic-typecheck
193 raise TypeError("Type must be Slide.")
194 self["slides"].append(slide)
196 def set_feature(self, name: str, enabled: bool) -> None:
197 """
198 A method for enabling or disabling a feature of the story.
200 Args:
201 name: The name of the feature.
202 enabled: True if enabled or False if disabled.
203 """
205 self._features.append(f"chart.feature('{name}', {json.dumps(enabled)});")
207 def add_event(self, event: str, handler: str) -> None:
208 """
209 A method for creating and turning on an event handler.
211 Args:
212 event: The name of the event.
213 handler: The handler JavaScript expression as string.
214 """
216 self._events.append(
217 f"chart.on('{event}', event => {{{' '.join(handler.split())}}});"
218 )
220 def set_size(
221 self, width: Optional[str] = None, height: Optional[str] = None
222 ) -> None:
223 """
224 A method for setting width/height settings.
226 Args:
227 width (optional): The width of the presentation story.
228 height (optional): The height of the presentation story.
229 """
231 self._size = StorySize(width=width, height=height)
233 def to_html(self) -> str:
234 """
235 A method for assembling the html code.
237 Returns:
238 The assembled html code as string.
239 """
241 vizzu_player_data = f"{json.dumps(self, cls=RawJavaScriptEncoder)}"
242 return DISPLAY_TEMPLATE.format(
243 id=uuid.uuid4().hex[:7],
244 vizzu_story=VIZZU_STORY,
245 vizzu_player_data=vizzu_player_data,
246 chart_size=self._size.style,
247 chart_features=f"\n{DISPLAY_INDENT * 3}".join(self._features),
248 chart_events=f"\n{DISPLAY_INDENT * 3}".join(self._events),
249 )
251 def export_to_html(self, filename: PathLike) -> None:
252 """
253 A method for exporting the story into html file.
255 Args:
256 filename: The path of the target html file.
257 """
259 with open(filename, "w", encoding="utf8") as file_desc:
260 file_desc.write(self.to_html())