Skip to content

Commit 772727e

Browse files
authored
Render Vue components from Jinja with vue_component_html (#14698)
vue_component_html writes a Vue component's script tag and element without reading web.ctx, so Jinja templates can use it on FastAPI as well as web.py. render_component now builds its markup with it and only adds the web.py once-per-request script tracking; its unused json_encode argument is removed. String attribute values are now HTML-escaped. /search/bulk and the /status testing panel use the new helper.
1 parent 4e7ff9d commit 772727e

10 files changed

Lines changed: 96 additions & 39 deletions

File tree

‎docs/frontend/README.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,11 @@ Build:
5353
make components # via docker compose run --rm home make components — no dev/watch mode documented for this pipeline
5454
```
5555

56+
Unlike Lit components, each Vue component is its own `ol-<Name>.js`, so a page that uses one must load that script too. `vue_component_html(name, attrs)` in `openlibrary/plugins/upstream/utils.py` writes both the script tag and the element. Dict and list attributes are JSON- then URL-encoded, so the component reads them with `JSON.parse(decodeURIComponent(...))`.
57+
58+
- **Jinja:** it isn't a Jinja global, so pass it in: `render_jinja_template("x.html.jinja", vue_component_html=vue_component_html)`, then `{{ vue_component_html("BulkSearch") }}`.
59+
- **Templetor (web.py only):** `$:render_component("MergeUI", attrs=...)` does the same, and writes each script tag only once per request. It keeps that in `web.ctx`, so never use it on FastAPI.
60+
5661
---
5762

5863
## Design Tokens (Two-Tier System)

‎openlibrary/fastapi/search.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@
3535
from openlibrary.i18n import gettext as _
3636
from openlibrary.plugins.inside.code import RESULTS_PER_PAGE, hit_editions, render_inside_body
3737
from openlibrary.plugins.upstream.mybooks import get_reading_states_async
38-
from openlibrary.plugins.upstream.utils import get_coverstore_public_url
38+
from openlibrary.plugins.upstream.utils import get_coverstore_public_url, vue_component_html
3939
from openlibrary.plugins.worksearch.code import (
4040
default_spellcheck_count,
4141
run_solr_query_async,
@@ -675,7 +675,7 @@ async def search_lists(nav: SearchNavDep, user: CurrentUserDep, q: str = "", pag
675675
async def bulk_search() -> SitePage:
676676
# TODO: Retire the web.py `bulk_search` handler (it still serves /search/bulk
677677
# in production) once production routes /search/bulk here.
678-
body = render_jinja_template("bulk_search/bulk_search.html.jinja")
678+
body = render_jinja_template("bulk_search/bulk_search.html.jinja", vue_component_html=vue_component_html)
679679
return SitePage(body, page=PageMeta(title=_("Bulk Search (beta)")))
680680

681681

‎openlibrary/macros/TestingEnvironment.html.jinja‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,8 +66,8 @@
6666
"viewJenkins": _("View Jenkins"),
6767
"noPrs": _("No PRs in testing set.")
6868
} %}
69-
{{ render_component('TestingEnvironment', attrs={
69+
{{ vue_component_html('TestingEnvironment', attrs={
7070
'maintainer': 'true' if is_maintainer else 'false',
7171
'jenkins-url': jenkins_job_url,
7272
'i18n': i18n_strings,
73-
}) | safe }}
73+
}) }}

‎openlibrary/plugins/upstream/tests/test_utils.py‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import json
12
from collections.abc import Sequence
23
from typing import TYPE_CHECKING
34
from unittest.mock import Mock
@@ -462,3 +463,41 @@ def test_user_object_uses_current_site(mock_site, monkeypatch, legacy):
462463
else:
463464
monkeypatch.setitem(web.ctx, "site", Mock())
464465
assert utils.get_user_object("alice").displayname == "Alice"
466+
467+
468+
@pytest.fixture
469+
def fake_static_url(monkeypatch):
470+
monkeypatch.setattr("openlibrary.plugins.upstream.code.static_url", lambda p: f"/static/{p}?v=1")
471+
472+
473+
def test_vue_component_html_loads_the_component_and_renders_its_element(fake_static_url):
474+
assert utils.vue_component_html("MergeUI") == (
475+
'<script type="module" src="/static/build/components/production/ol-MergeUI.js?v=1"></script><ol-merge-ui></ol-merge-ui>'
476+
)
477+
assert '<script type="module" async defer src=' in utils.vue_component_html("MergeUI", async_defer=True)
478+
479+
480+
def test_vue_component_html_attributes_reach_the_component_intact(fake_static_url):
481+
"""Dicts and lists decode with ``JSON.parse(decodeURIComponent(...))``; strings as written."""
482+
from urllib.parse import unquote
483+
484+
from lxml import html as lxml_html
485+
486+
attrs = {"i18n": {"retry": 'Try "again" & <go>'}, "ids": [1, "2"], "jenkins-url": 'https://x/?a=1&b="2"'}
487+
488+
element = lxml_html.fragment_fromstring(str(utils.vue_component_html("TestingEnvironment", attrs=attrs)), create_parent=True)[1]
489+
490+
assert element.tag == "ol-testing-environment"
491+
assert json.loads(unquote(element.get("i18n"))) == attrs["i18n"]
492+
assert json.loads(unquote(element.get("ids"))) == attrs["ids"]
493+
assert element.get("jenkins-url") == attrs["jenkins-url"]
494+
495+
496+
def test_render_component_loads_each_component_script_once_per_request(fake_static_url, monkeypatch):
497+
monkeypatch.setattr(web, "ctx", web.storage())
498+
499+
first = utils.render_component("HelloWorld", attrs={"a": "1"})
500+
second = utils.render_component("HelloWorld")
501+
502+
assert first == utils.vue_component_html("HelloWorld", attrs={"a": "1"})
503+
assert second == "<ol-hello-world></ol-hello-world>"

‎openlibrary/plugins/upstream/utils.py‎

Lines changed: 37 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
import web
3333
import yaml
3434
from babel.lists import format_list
35+
from markupsafe import Markup
3536
from web.template import TemplateResult
3637
from web.utils import Storage
3738

@@ -188,36 +189,48 @@ def kebab_case(upper_camel_case: str) -> str:
188189

189190

190191
@public
191-
def render_component(
192-
name: str,
193-
attrs: dict | None = None,
194-
json_encode: bool = True,
195-
asyncDefer=False,
196-
) -> str:
197-
"""
198-
:param str name: Name of the component (excluding extension)
199-
:param dict attrs: attributes to add to the component element
192+
def vue_component_html(name: str, attrs: dict | None = None, async_defer: bool = False) -> Markup:
193+
"""The script tag and custom element that render the Vue component built from ``openlibrary/components/<name>.vue``.
194+
195+
Reads no request state, so it is safe in Jinja templates served by FastAPI.
196+
197+
:param name: component name, e.g. ``"BulkSearch"`` for ``<ol-bulk-search>``
198+
:param attrs: element attributes. Dicts and lists are JSON- then URL-encoded;
199+
the component reads them back with ``JSON.parse(decodeURIComponent(...))``.
200200
"""
201+
return _vue_component_script(name, async_defer) + _vue_component_element(name, attrs)
202+
203+
204+
def _vue_component_script(name: str, async_defer: bool) -> Markup:
201205
from openlibrary.plugins.upstream.code import static_url
202206

203-
attrs = attrs or {}
204-
attrs_str = ""
205-
for key, val in attrs.items():
206-
if (json_encode and isinstance(val, dict)) or isinstance(val, list):
207-
val = json.dumps(val)
208-
# On the Vue side use decodeURIComponent to decode
209-
val = urllib.parse.quote(val)
210-
attrs_str += f' {key}="{val}"'
211-
html = ""
207+
url = static_url(f"build/components/production/ol-{name}.js")
208+
async_attrs = " async defer" if async_defer else ""
209+
return Markup('<script type="module"{} src="{}"></script>').format(async_attrs, url)
210+
212211

212+
def _vue_component_element(name: str, attrs: dict | None) -> Markup:
213+
tag = kebab_case(name)
214+
attrs_html = Markup("")
215+
for key, val in (attrs or {}).items():
216+
if isinstance(val, dict | list):
217+
val = urllib.parse.quote(json.dumps(val))
218+
attrs_html += Markup(' {}="{}"').format(key, val)
219+
return Markup("<ol-{0}{1}></ol-{0}>").format(tag, attrs_html)
220+
221+
222+
@public
223+
def render_component(name: str, attrs: dict | None = None, asyncDefer=False) -> str:
224+
""":func:`vue_component_html` for Templetor pages on web.py.
225+
226+
Writes each component's script tag only once per request, tracked in ``web.ctx``,
227+
so it must not run on FastAPI.
228+
"""
229+
html = Markup("")
213230
if name not in (included := web.ctx.setdefault("included-components", [])):
214-
url = static_url("build/components/production/ol-%s.js" % name)
215-
script_attrs = "" if not asyncDefer else "async defer"
216-
html += f'<script type="module" {script_attrs} src="{url}"></script>'
231+
html += _vue_component_script(name, asyncDefer)
217232
included.append(name)
218-
219-
html += f"<ol-{kebab_case(name)} {attrs_str}></ol-{kebab_case(name)}>"
220-
return html
233+
return html + _vue_component_element(name, attrs)
221234

222235

223236
@public

‎openlibrary/plugins/worksearch/bulk_search.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,14 @@
55
from infogami.utils import delegate
66
from openlibrary.core.jinja import render_jinja_template
77
from openlibrary.i18n import gettext as _
8+
from openlibrary.plugins.upstream.utils import vue_component_html
89

910

1011
class bulk_search(delegate.page):
1112
path = "/search/bulk"
1213

1314
def GET(self):
14-
body = render_jinja_template("bulk_search/bulk_search.html.jinja")
15+
body = render_jinja_template("bulk_search/bulk_search.html.jinja", vue_component_html=vue_component_html)
1516
# web.py's layout reads the title off the result, already escaped, as from Templetor's $var.
1617
return web.template.TemplateResult(__body__=body, title=escape(_("Bulk Search (beta)")))
1718

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,4 @@
11
<div id="contentHead">
22
<h1>{{ _("Bulk Search (beta)") }}</h1>
33
</div>
4-
<script type="module"
5-
src="{{ static_url('build/components/production/ol-BulkSearch.js') }}"></script>
6-
<ol-bulk-search>
7-
</ol-bulk-search>
4+
{{ vue_component_html("BulkSearch") }}

‎openlibrary/templates/status.html‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ <h1>$_("Server status")</h1>
4040
<div id="contentBody">
4141

4242
$if show_testing:
43-
$:render_jinja_template("TestingEnvironment.html.jinja", is_maintainer=is_maintainer, jenkins_job_url=jenkins_job_url, render_component=render_component)
43+
$:render_jinja_template("TestingEnvironment.html.jinja", is_maintainer=is_maintainer, jenkins_job_url=jenkins_job_url, vue_component_html=vue_component_html)
4444
$elif has_testing_state:
4545
<div class="notice testing-env-notice">
4646
$_("The testing environment panel is only visible to maintainers.")

‎openlibrary/tests/core/test_jinja.py‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -102,13 +102,13 @@ def _stub_render_templetor(name, *a, **kw):
102102

103103
env.globals["icon"] = lambda *a, **kw: ""
104104

105-
# The TestingEnvironment macro renders a Vue component via
106-
# render_component(); this env has no component build output, so stub it
107-
# the same way render_templetor_template is stubbed above.
108-
def _stub_render_component(*a, **kw):
105+
# Templates that render a Vue component are passed vue_component_html; this
106+
# env has no component build output, so stub it the same way
107+
# render_templetor_template is stubbed above.
108+
def _stub_vue_component_html(*a, **kw):
109109
return ""
110110

111-
env.globals["render_component"] = _stub_render_component
111+
env.globals["vue_component_html"] = _stub_vue_component_html
112112

113113
# static_url is a true Jinja global (like icon) — used by many templates.
114114
# For validation, stub it so it does not require built files on disk.

‎openlibrary/tests/fastapi/conftest.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -292,6 +292,8 @@ def site_page_app(monkeypatch) -> Callable[..., FastAPI]:
292292
from a recognized crawler if it sends ``x-recognized-bot: 1``.
293293
"""
294294
monkeypatch.setitem(get_jinja_env().globals, "static_url", lambda p: f"/static/{p}")
295+
# vue_component_html imports static_url itself rather than using the Jinja global.
296+
monkeypatch.setattr("openlibrary.plugins.upstream.code.static_url", lambda p: f"/static/{p}")
295297
monkeypatch.setitem(get_jinja_env().globals, "icon", lambda *a, **kw: "")
296298
# A linked archive.org account, so the header shows the account title (with the joined date).
297299
monkeypatch.setattr("openlibrary.core.shell.user.get_internet_archive_id", lambda key: "@ia")

0 commit comments

Comments
 (0)