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

1"""A module for working with presentation stories.""" 

2 

3from typing import Optional, Union, List 

4from os import PathLike 

5import json 

6import uuid 

7 

8from ipyvizzu import RawJavaScriptEncoder, Data, Style, Config # , PlainAnimation 

9 

10from ipyvizzustory.storylib.animation import DataFilter 

11from ipyvizzustory.storylib.template import ( 

12 VIZZU_STORY, 

13 DISPLAY_TEMPLATE, 

14 DISPLAY_INDENT, 

15) 

16 

17 

18class Step(dict): 

19 """A class for representing a step of a slide.""" 

20 

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. 

28 

29 Note: 

30 Do not set `anim_options` argument, it will raise `NotImplementedError` error. 

31 

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. 

36 

37 Raises: 

38 ValueError: If `animations` are not set. 

39 NotImplementedError: If `anim_options` are set. 

40 """ 

41 

42 super().__init__() 

43 if not animations: 

44 raise ValueError("No animation was set.") 

45 self._update(*animations) 

46 

47 if anim_options: 

48 # self["animOptions"] = PlainAnimation(**anim_options).build() 

49 raise NotImplementedError("Anim options are not supported.") 

50 

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) 

61 

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) 

67 

68 

69class Slide(list): 

70 """A class for representing a slide of a presentation story.""" 

71 

72 def __init__(self, step: Optional[Step] = None): 

73 """ 

74 Slide constructor. 

75 

76 Args: 

77 step (optional): The first step can also be added to the slide in the constructor. 

78 """ 

79 

80 super().__init__() 

81 if step: 

82 self.add_step(step) 

83 

84 def add_step(self, step: Step) -> None: 

85 """ 

86 A method for adding a step for the slide. 

87 

88 Args: 

89 step: The next step of the slide. 

90 

91 Raises: 

92 TypeError: If the type of the `step` is not `Step`. 

93 """ 

94 

95 if not step or type(step) != Step: # pylint: disable=unidiomatic-typecheck 

96 raise TypeError("Type must be Step.") 

97 self.append(step) 

98 

99 

100class StorySize: 

101 """A class for representing the size of a presentation story.""" 

102 

103 def __init__(self, width: Optional[str] = None, height: Optional[str] = None): 

104 """ 

105 StorySize constructor. 

106 

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 

113 

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}'" 

119 

120 @property 

121 def width(self) -> Optional[str]: 

122 """A property for returning the width of a presentation story.""" 

123 

124 return self._width 

125 

126 @property 

127 def height(self) -> Optional[str]: 

128 """A property for returning the height of a presentation story.""" 

129 

130 return self._height 

131 

132 @property 

133 def style(self) -> str: 

134 """ 

135 A property for returning the cssText width and height of a presentation story. 

136 

137 Note: 

138 If `width` and `height` are not set it returns an empty string. 

139 """ 

140 

141 return self._style 

142 

143 

144class Story(dict): 

145 """A class for representing a presentation story.""" 

146 

147 def __init__(self, data: Data, style: Optional[Style] = None): 

148 """ 

149 Presentation Story constructor. 

150 

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. 

157 

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 """ 

162 

163 super().__init__() 

164 

165 self._size: StorySize = StorySize() 

166 

167 self._features: List[str] = [] 

168 self._events: List[str] = [] 

169 

170 if not data or type(data) != Data: # pylint: disable=unidiomatic-typecheck 

171 raise TypeError("Type must be Data.") 

172 self.update(data.build()) 

173 

174 if style: 

175 if type(style) != Style: # pylint: disable=unidiomatic-typecheck 

176 raise TypeError("Type must be Style.") 

177 self.update(style.build()) 

178 

179 self["slides"] = [] 

180 

181 def add_slide(self, slide: Slide) -> None: 

182 """ 

183 A method for adding a slide for the story. 

184 

185 Args: 

186 slide: The next slide of the story. 

187 

188 Raises: 

189 TypeError: If the type of the `slide` is not `Slide`. 

190 """ 

191 

192 if not slide or type(slide) != Slide: # pylint: disable=unidiomatic-typecheck 

193 raise TypeError("Type must be Slide.") 

194 self["slides"].append(slide) 

195 

196 def set_feature(self, name: str, enabled: bool) -> None: 

197 """ 

198 A method for enabling or disabling a feature of the story. 

199 

200 Args: 

201 name: The name of the feature. 

202 enabled: True if enabled or False if disabled. 

203 """ 

204 

205 self._features.append(f"chart.feature('{name}', {json.dumps(enabled)});") 

206 

207 def add_event(self, event: str, handler: str) -> None: 

208 """ 

209 A method for creating and turning on an event handler. 

210 

211 Args: 

212 event: The name of the event. 

213 handler: The handler JavaScript expression as string. 

214 """ 

215 

216 self._events.append( 

217 f"chart.on('{event}', event => {{{' '.join(handler.split())}}});" 

218 ) 

219 

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. 

225 

226 Args: 

227 width (optional): The width of the presentation story. 

228 height (optional): The height of the presentation story. 

229 """ 

230 

231 self._size = StorySize(width=width, height=height) 

232 

233 def to_html(self) -> str: 

234 """ 

235 A method for assembling the html code. 

236 

237 Returns: 

238 The assembled html code as string. 

239 """ 

240 

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 ) 

250 

251 def export_to_html(self, filename: PathLike) -> None: 

252 """ 

253 A method for exporting the story into html file. 

254 

255 Args: 

256 filename: The path of the target html file. 

257 """ 

258 

259 with open(filename, "w", encoding="utf8") as file_desc: 

260 file_desc.write(self.to_html())