22
33from __future__ import annotations
44
5- import base64
65import json
76from typing import TYPE_CHECKING
87
@@ -74,14 +73,13 @@ async def exec_js_fn(
7473 return await tab .send_command ("Runtime.callFunctionOn" , params = params )
7574
7675
77- _TEXT_FORMATS = ("svg" , "json" ) # eps
78-
79-
80- async def get_bytes (self , response ) -> tuple [None , bytes , None | Exception ]:
76+ def check_kaleido_js_response (
77+ response ,
78+ ) -> tuple [
79+ dict ,
80+ Exception | None ,
81+ ]:
8182 # TODO(AJP) provoke a js error and return js error
82-
83- # check_js could be another function, the next two sections should be
84- # factored out
8583 js_response = json .loads (
8684 response .get (
8785 "result" ,
@@ -95,34 +93,37 @@ async def get_bytes(self, response) -> tuple[None, bytes, None | Exception]:
9593 "value" ,
9694 ),
9795 )
96+ if not js_response : # not loved, neither {}
97+ return {}, RuntimeError (
98+ f"JS Response not understood: { response } " ,
99+ )
98100
99101 if js_response ["code" ] != 0 :
100- return None , KaleidoError (js_response ["code" ], js_response ["message" ])
101-
102- # this shouldn't be in here
103- if (response_format := js_response .get ("format" )) == "pdf" :
104- pdf_params = {
105- "printBackground" : True ,
106- "marginTop" : 0.1 ,
107- "marginBottom" : 0.1 ,
108- "marginLeft" : 0.1 ,
109- "marginRight" : 0.1 ,
110- "preferCSSPageSize" : True ,
111- "pageRanges" : "1" ,
112- }
113- pdf_response = await self .tab .send_command (
114- "Page.printToPDF" ,
115- params = pdf_params ,
116- )
117- e = _get_error (pdf_response )
118- if e :
119- return e
120- img_raw = pdf_response .get ("result" ).get ("data" )
121- else :
122- img_raw = js_response .get ("result" )
123-
124- # Base64 decode binary types
125- if response_format not in _TEXT_FORMATS :
126- return base64 .b64decode (img_raw ), None
127- else :
128- return str .encode (img_raw ), None
102+ return {}, KaleidoError (js_response ["code" ], js_response ["message" ])
103+
104+ return js_response
105+
106+
107+ async def print_pdf (
108+ tab : choreographer .Tab ,
109+ ) -> tuple [
110+ str ,
111+ Exception | None ,
112+ ]:
113+ pdf_params = {
114+ "printBackground" : True ,
115+ "marginTop" : 0.1 ,
116+ "marginBottom" : 0.1 ,
117+ "marginLeft" : 0.1 ,
118+ "marginRight" : 0.1 ,
119+ "preferCSSPageSize" : True ,
120+ "pageRanges" : "1" ,
121+ }
122+ pdf_response = await tab .send_command (
123+ "Page.printToPDF" ,
124+ params = pdf_params ,
125+ )
126+ e = _get_error (pdf_response )
127+ if e :
128+ return "" , e
129+ return pdf_response .get ("result" , {}).get ("data" ), None
0 commit comments