Skip to content

Commit cd6b471

Browse files
committed
Fix typing errors.
1 parent 84afca4 commit cd6b471

4 files changed

Lines changed: 81 additions & 51 deletions

File tree

src/py/kaleido/_kaleido_tab/__init__.py

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
11
from __future__ import annotations
22

3+
import base64
34
from typing import TYPE_CHECKING
45

56
import logistro
67

8+
from kaleido._utils import to_thread
9+
710
from . import _devtools_utils as _dtools
811
from . import _js_logger
912
from ._errors import _raise_error
10-
from ._utils import to_thread
1113

1214
if TYPE_CHECKING:
1315
import asyncio
@@ -17,6 +19,9 @@
1719

1820
from kaleido import _fig_tools
1921

22+
23+
_TEXT_FORMATS = ("svg", "json") # eps
24+
2025
_logger = logistro.getLogger(__name__)
2126

2227

@@ -50,7 +55,7 @@ def __init__(self, tab, *, _stepper=False):
5055
5156
"""
5257
self.tab = tab
53-
self.js_logger = _js_logger.JavascriptLogger()
58+
self.js_logger = _js_logger.JavascriptLogger(self.tab)
5459
self._stepper = _stepper
5560

5661
async def navigate(self, url: str | Path = ""):
@@ -141,9 +146,28 @@ async def _calc_fig(
141146
)
142147
_raise_error(result)
143148

149+
# TODO(AJP): better define these error mechanics, is this a devtools
150+
# function or what
151+
# upon implementation of error, might not be necessary
152+
# to do these go-lang/c style returns
153+
# but we have to collect and associate
154+
# with the gather + profile
155+
# None-non return values are a problem
156+
# In general, need to better understand stuff here
157+
144158
_logger.debug2(f"Result of function call: {result}")
159+
js_response, error = _dtools.check_kaleido_js_response(result)
160+
if error:
161+
raise error
145162

146-
img_bytes, error = await _dtools.get_bytes(result)
163+
if (response_format := js_response.get("format")) == "pdf":
164+
img_raw, error = await _dtools.print_pdf(self.tab)
165+
else:
166+
img_raw = js_response.get("result") # type: ignore[assignment]
147167
if error:
148168
raise error
149-
return img_bytes
169+
170+
if response_format not in _TEXT_FORMATS:
171+
return base64.b64decode(img_raw), None
172+
else:
173+
return str.encode(img_raw), None

src/py/kaleido/_kaleido_tab/_devtools_utils.py

Lines changed: 38 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33
from __future__ import annotations
44

5-
import base64
65
import json
76
from 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

src/py/kaleido/_kaleido_tab/_js_logger.py

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -26,20 +26,21 @@ class JavascriptLogger:
2626
log: list[Any]
2727
"""A list of console outputs from the tab."""
2828

29-
def __init__(self) -> None:
29+
def __init__(self, tab: choreographer.Tab) -> None:
3030
self.log = []
31+
self.tab = tab
3132

32-
def activate(self, tab: choreographer.Tab):
33-
tab.unsubscribe("Runtime.consoleAPICalled")
34-
tab.subscribe(
33+
def activate(self):
34+
self.tab.unsubscribe("Runtime.consoleAPICalled")
35+
self.tab.subscribe(
3536
"Runtime.consoleAPICalled",
36-
_make_console_logger("tab js console", self.javascript_log),
37+
_make_console_logger("tab js console", self.log),
3738
)
3839

39-
def reset(self, tab: choreographer.Tab):
40-
tab.unsubscribe("Runtime.consoleAPICalled")
40+
def reset(self):
41+
self.tab.unsubscribe("Runtime.consoleAPICalled")
4142
self.log = []
42-
tab.subscribe(
43+
self.tab.subscribe(
4344
"Runtime.consoleAPICalled",
44-
_make_console_logger("tab js console", self.javascript_log),
45+
_make_console_logger("tab js console", self.log),
4546
)

src/py/kaleido/_page_generator.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,11 @@
88
from . import _utils
99

1010
if TYPE_CHECKING:
11-
UrlAndCharset = tuple[str | Path, str] # type: TypeAlias
11+
from typing import Tuple, Union
12+
13+
from typing_extensions import TypeAlias
14+
15+
UrlAndCharset: TypeAlias = Tuple[Union[str, Path], str]
1216
"""A tuple to explicitly set charset= in the <script> tag."""
1317

1418
_logger = logistro.getLogger(__name__)

0 commit comments

Comments
 (0)