Skip to content

Commit

Permalink
Fix broken deserialization of deps (#65)
Browse files Browse the repository at this point in the history
  • Loading branch information
jcheng5 authored Oct 30, 2023
1 parent 0b3eee2 commit 2aaf6fb
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 4 deletions.
6 changes: 2 additions & 4 deletions htmltools/_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -1146,9 +1146,7 @@ def _static_extract_serialized_html_deps(
) -> tuple[str, list[HTMLDependency]]:
# Scan for HTML dependencies that were serialized via
# HTMLdependency.get_tag_representation()
pattern = (
r'<script type="application/json" data-html-dependency="">(.*?)</script>'
)
pattern = r'<script type="application/json" data-html-dependency="">((?:.|\r|\n)*?)</script>'
dep_strs = re.findall(pattern, html)
# html = re.sub(pattern, "", html)

Expand Down Expand Up @@ -1446,7 +1444,7 @@ def as_html_tags(
scripts = [Tag("script", **s) for s in d["script"]]
return TagList(*metas, *links, *scripts, self.head)

def serialize_to_script_json(self, indent: int = 0, eol: str = "\n") -> Tag:
def serialize_to_script_json(self, indent: int | None = None) -> Tag:
res = {
"name": self.name,
"version": str(self.version),
Expand Down
39 changes: 39 additions & 0 deletions tests/test_html_document.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from tempfile import TemporaryDirectory
from typing import Union

import htmltools as ht
from htmltools import (
HTMLDependency,
HTMLDocument,
Expand Down Expand Up @@ -263,3 +264,41 @@ def tagify(self):
testdep_files = os.listdir(os.path.join(tmpdir, "mylib", "testdep"))
testdep_files.sort()
assert testdep_files == ["testdep.css", "testdep.js"]


def test_json_roundtrip():
testdep = HTMLDependency(
"testdep",
"1.0",
source={"package": "htmltools", "subdir": "libtest/testdep"},
script={"src": "testdep.js"},
stylesheet={"href": "testdep.css"},
)
testdep2 = HTMLDependency(
"testdep2",
"1.0",
source={"package": "htmltools", "subdir": "libtest/testdep"},
script={"src": "testdep.js"},
stylesheet={"href": "testdep.css"},
)

old_mode = ht.html_dependency_render_mode
ht.html_dependency_render_mode = "json"
try:
x = ht.TagList(
[
ht.HTML('<meta data-foo="">'),
div("hello world", testdep),
# Also make sure it would work even with indents
ht.HTML(testdep2.serialize_to_script_json(indent=2)),
]
)
x_str = str(x)
rendered = ht.HTMLTextDocument(
x_str, deps_replace_pattern='<meta data-foo="">'
).render()
assert "testdep" in [d.name for d in rendered["dependencies"]]
assert "testdep2" in [d.name for d in rendered["dependencies"]]

finally:
ht.html_dependency_render_mode = old_mode

0 comments on commit 2aaf6fb

Please sign in to comment.