From ea5be91328699484976c991628c670e2d23b1a00 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Krzysztof=20Ko=C5=82odzi=C5=84ski?= Date: Sat, 17 Oct 2026 20:49:42 +0200 Subject: [PATCH 01/34] feat: added images to markers --- docs/configuration.rst | 27 +++- docs/http-api.rst | 15 +- docs/plugins.rst | 40 +++++- .../MarkerPopup/LocationDetails.jsx | 110 +++++++++------ .../MarkerPopup/serverHtmlField.jsx | 4 +- frontend/tests/MarkerPopup/Images.test.jsx | 51 +++++++ frontend/tests/services/endpoints.test.js | 21 +++ goodmap/api/core_api.py | 6 +- goodmap/config.py | 4 + goodmap/field_types.py | 19 ++- goodmap/formatter.py | 111 ++++++++++++--- goodmap/goodmap.py | 5 + tests/unit_tests/test_alt_template.py | 63 +++++++++ tests/unit_tests/test_core_api.py | 30 ++++ tests/unit_tests/test_formatter.py | 128 ++++++++++++++++++ 15 files changed, 568 insertions(+), 66 deletions(-) create mode 100644 frontend/tests/MarkerPopup/Images.test.jsx create mode 100644 frontend/tests/services/endpoints.test.js create mode 100644 tests/unit_tests/test_alt_template.py diff --git a/docs/configuration.rst b/docs/configuration.rst index 466a7131..9335263d 100644 --- a/docs/configuration.rst +++ b/docs/configuration.rst @@ -13,7 +13,8 @@ filterable fields, the popup contents — lives in the data source instead, docu :doc:`data-source`. Because Goodmap is built on platzky, a Goodmap config *is* a platzky config plus the keys -Goodmap adds of its own — ``GOODMAP_FRONTEND_LIB_URL`` and ``ATTACHMENT``. Keys not listed +Goodmap adds of its own — ``GOODMAP_FRONTEND_LIB_URL``, ``ATTACHMENT`` and +``IMAGE_ALT_TEMPLATE``. Keys not listed here are passed through to platzky; see :doc:`platzky's configuration docs ` for the rest. @@ -159,6 +160,30 @@ Basic keys browser first, with a warning that quality may drop; if it is still too large it is rejected. An unsupported format is rejected outright. +.. _config-image-alt-template: + +``IMAGE_ALT_TEMPLATE`` + The ``alt`` text given to a marker image that carries none of its own (see + :ref:`plugins-builtin-field-types`), so a screen reader can say what the photo shows. + It is a `Jinja `_ template, rendered once + per point with that point's fields as variables: + + .. code-block:: yaml + + IMAGE_ALT_TEMPLATE: >- + {{ _('photo of') }} {{ type_of_place }}, + {{ _('free') if is_free == 'true' else _('paid') }}, + {{ amenities | join(', ') }} + + Field values arrive already translated, and ``_()`` translates the template's own text. + A field the point lacks prints as nothing, and runs of whitespace are collapsed. Omit the + key and an image is described by the point's ``name``. + + The template runs in Jinja's sandbox, so it can read the point's values and nothing + behind them. One that does not parse stops the app at startup; one that fails for a + particular point — the sandbox refusing an attribute, say — logs a warning and falls + back to the point's name, so its popup still opens. + .. _config-feature-flags: Feature flags diff --git a/docs/http-api.rst b/docs/http-api.rst index 688f55da..0eef3c2a 100644 --- a/docs/http-api.rst +++ b/docs/http-api.rst @@ -183,7 +183,7 @@ list of ``[label, value]`` pairs — the fields listed in ``visible_data``, in t with both label and value translated. ``metadata`` holds the ``meta_data`` fields. Fields in neither list are not returned at all. -A field GoodMap renders — one naming a built-in ``type`` such as ``hyperlink`` or ``CTA``, +A field GoodMap renders — one naming a built-in ``type`` such as ``hyperlink``, ``CTA`` or ``image``, or one a plugin's shortcode is bound to — comes back as an object rather than a bare value: .. code-block:: json @@ -195,6 +195,19 @@ or one a plugin's shortcode is bound to — comes back as an object rather than "html": "Example" }] +A field naming a built-in type may hold several values under ``items``, each returned with +its own ``html``. Items that render to nothing are dropped, and a built-in field left with +nothing to show is left out of ``data``: + +.. code-block:: json + + ["images", { + "type": "image", + "items": [{"url": "https://example.com/front.jpg", "alt": "photo of big bridge", + "html": "\"photo"}], + "html": "\"photo" + }] + ``html`` is the rendering to display and ``type`` says what produced it; the entry's own keys travel alongside for a client that would rather render from the data. See :ref:`plugins-builtin-field-types` for which types GoodMap ships and diff --git a/docs/plugins.rst b/docs/plugins.rst index 4a7a1d45..f4d36f5d 100644 --- a/docs/plugins.rst +++ b/docs/plugins.rst @@ -208,14 +208,48 @@ That lookup is safe only because the catalogue is closed: an entry may name a ty and nothing else, so it can never point its own field at a plugin's renderer. ``prepare_pin`` consults it only where no plugin shortcode claimed the field by name. -A plugin cannot take over ``hyperlink`` or ``CTA`` either. The server always emits ``html`` +Alongside its own, goodmap offers an **allowlist** of platzky's built-in shortcodes — +currently ``image`` — so a point can carry photos. It is an allowlist rather than the whole +set because the entries naming these types are data nobody vouched for: a suggested point or +an imported dataset naming platzky's ``html`` would put raw markup into the popup. Adding +another, ``figure`` say, is one word in ``_PLATZKY_FIELD_TYPES``. + +A field naming one of these types may hold several values under ``items``. Each is rendered +on its own and returned with its own ``html`` — what a gallery field plugin on ``image`` would +lay out — while the field's ``html`` joins them for the popup. An item the shortcode refuses +is dropped from both, and a field left with nothing to show is left out of the popup +altogether. ``items`` is for goodmap's own types only: a field a plugin's shortcode is bound +to keeps exactly the rendering that shortcode gives it. + +An image URL must be ``http``, ``https`` or a path on the site itself (``/static/…``) — +platzky's image policy; ``javascript:`` and ``data:`` are refused: + +.. code-block:: json + + {"images": {"type": "image", + "items": [{"url": "https://example.com/front.jpg"}, + {"url": "https://example.com/inside.jpg", "alt": "The counter"}]}} + +A single photo is a one-element ``items``. An item without ``alt`` is described by +:ref:`IMAGE_ALT_TEMPLATE `; one with its own wins, including an +empty ``alt`` for a purely decorative image; an ``alt`` of ``null`` counts as not given. +Image fields are shown full-width under the popup's title, without a label. + +.. note:: + + Unlike a link, an image is fetched as soon as its popup opens. Whoever hosts an image + URL in your data therefore learns the IP address of everyone who opens that point, and + when — which is why a suggested point's images deserve the same scrutiny as its text + before it is approved, and why an imported dataset's should come from hosts you trust. + +A plugin cannot take over ``hyperlink``, ``CTA`` or ``image`` either. The server always emits ``html`` for a type it renders, so that HTML is always the innermost stage — a field plugin attached to one of these types wraps it and cannot replace it. The two share a rendering, because they only ever differed in presentation: both are a URL and the text to show for it. Which one a field is decides where the popup puts it — a line -among the details, or a button below them — which ``LocationDetails`` decides from the field -name. +among the details, or a button below them — which ``LocationDetails`` decides from the +value's ``type`` in its ``SECTION_BY_TYPE`` table. A field plugin is a ``MarkerFieldPluginBase`` whose component is a stage ``({ input, config }) => element`` — it receives the previous stage's output as ``input``. diff --git a/frontend/src/components/MarkerPopup/LocationDetails.jsx b/frontend/src/components/MarkerPopup/LocationDetails.jsx index 8da9bb68..b78aa7c0 100644 --- a/frontend/src/components/MarkerPopup/LocationDetails.jsx +++ b/frontend/src/components/MarkerPopup/LocationDetails.jsx @@ -112,6 +112,31 @@ const CTAContainer = styled.div` } `; +// Images the server rendered (`type: "image"`, platzky's [image] shortcode) arrive as plain +// `` tags, so their size is decided here: the popup's width, whatever the data asked for. +const ImagesContainer = styled.div` + display: flex; + flex-direction: column; + gap: 8px; + margin: 0 8px 16px 8px; + + > span { + display: block; + } + + img { + display: block; + max-width: 100%; + height: auto; + border-radius: 8px; + } + + /* Several images in one field arrive as one span, so the flex gap does not reach them. */ + img + img { + margin-top: 8px; + } +`; + const ActionButton = styled.button` cursor: pointer; display: flex; @@ -140,7 +165,7 @@ const isCustomValue = value => value !== null && typeof value === 'object' && !A /** * Component that renders a location detail value. - * Handles both standard values (strings, numbers, arrays) and custom typed values (hyperlinks, CTAs). + * Handles both standard values (strings, numbers, arrays) and typed values the server rendered. * * @param {Object} props - Component props * @param {string|number|Array|Object} props.valueToDisplay - Value to display, can be primitive or custom type object @@ -222,10 +247,22 @@ NavigateMeButton.propTypes = { }).isRequired, }; +// Which popup section a field shows in, by its value's `type` - never by its label, which is +// `gettext(field)` and so differs per locale. Anything not listed is a labelled detail. +const SECTION_BY_TYPE = { image: 'images', CTA: 'actions' }; + +// In display order. A `labelled` section pairs each value with its field name. +const SECTIONS = [ + { key: 'images', Container: ImagesContainer, labelled: false }, + { key: 'details', Container: DetailsGrid, labelled: true }, + { key: 'actions', Container: CTAContainer, labelled: false }, +]; + +const sectionOf = ([, value]) => SECTION_BY_TYPE[value?.type] ?? 'details'; + /** - * Component that renders location details including title, subtitle, and categorized data. - * Separates data into regular categories and CTA (Call-To-Action) categories. - * Displays data in a grid layout with category labels and values. + * Component that renders location details: title, subtitle, then each section of fields. + * Fields are placed in a section by their value's `type` (see SECTION_BY_TYPE). * * @param {Object} props - Component props * @param {Object} props.place - Location data object @@ -234,42 +271,35 @@ NavigateMeButton.propTypes = { * @param {Array<[string, *]>} props.place.data - Array of [category, value] tuples * @returns {React.ReactElement} Div containing formatted location details */ -const LocationDetails = ({ place }) => { - // Selected by the value's `type`, not by the field's label: the label is `gettext(field)`, - // so matching on it would drop the button in any locale that translates "CTA", and would - // miss a field that declares `type: "CTA"` under a name of its own. - const isCTA = ([, value]) => value?.type === 'CTA'; - const categoriesWithSubcategories = place.data.filter(entry => !isCTA(entry)); - const CTACategories = place.data.filter(isCTA); - - return ( - - - {place.title} - {place.subtitle && {place.subtitle}} - - - - {categoriesWithSubcategories.map(([category, value]) => ( - - {category} - - - - - ))} - - - {CTACategories.length > 0 && ( - - {CTACategories.map(([, value]) => ( - - ))} - - )} - - ); -}; +const LocationDetails = ({ place }) => ( + + + {place.title} + {place.subtitle && {place.subtitle}} + + + {SECTIONS.map(({ key, Container, labelled }) => { + const entries = place.data.filter(entry => sectionOf(entry) === key); + if (entries.length === 0) return null; + return ( + + {entries.map(([category, value]) => + labelled ? ( + + {category} + + + + + ) : ( + + ), + )} + + ); + })} + +); LocationDetails.propTypes = { place: PropTypes.shape({ diff --git a/frontend/src/components/MarkerPopup/serverHtmlField.jsx b/frontend/src/components/MarkerPopup/serverHtmlField.jsx index 8cbab526..d061f487 100644 --- a/frontend/src/components/MarkerPopup/serverHtmlField.jsx +++ b/frontend/src/components/MarkerPopup/serverHtmlField.jsx @@ -4,8 +4,8 @@ import PropTypes from 'prop-types'; /** * Renders the HTML the server produced for a field value. * - * A platzky plugin's shortcode and goodmap's own built-in types (`hyperlink`, `CTA` — see - * goodmap/field_types.py) both arrive this way, and neither needs a component here. That is + * A platzky plugin's shortcode and goodmap's own built-in types (`hyperlink`, `CTA`, `image` — + * see goodmap/field_types.py) both arrive this way, and neither needs a component here. That is * the point: a field type is added by teaching the server to render it, not by shipping React. * * The markup is deliberately not sanitized. It is goodmap's own or comes from an installed diff --git a/frontend/tests/MarkerPopup/Images.test.jsx b/frontend/tests/MarkerPopup/Images.test.jsx new file mode 100644 index 00000000..315726ac --- /dev/null +++ b/frontend/tests/MarkerPopup/Images.test.jsx @@ -0,0 +1,51 @@ +import React from 'react'; +import '@testing-library/jest-dom'; +import { render } from '@testing-library/react'; +import LocationDetailsBox from '../../src/components/MarkerPopup/LocationDetails'; + +// An `images` field as `prepare_pin` sends it: platzky's [image] shortcode rendered each item, +// and the field's `html` joins them. +const images = { + type: 'image', + items: [ + { + url: 'https://example.com/1.jpg', + alt: 'Front', + html: 'Front', + }, + { + url: 'https://example.com/2.jpg', + alt: 'Inside', + html: 'Inside', + }, + ], + html: 'FrontInside', +}; + +const place = data => ({ + title: 'Most Grunwaldzki', + position: [51.1095, 17.0525], + subtitle: 'big bridge', + data, + metadata: { uuid: '21231' }, +}); + +describe('Images', () => { + it('shows every image above the details, without a label', () => { + const { container, getAllByRole, queryByText } = render( + , + ); + + const shown = getAllByRole('img'); + expect(shown.map(img => img.getAttribute('alt'))).toEqual(['Front', 'Inside']); + expect(queryByText('images')).not.toBeInTheDocument(); + + const html = container.innerHTML; + expect(html.indexOf(' { + afterEach(() => { + delete globalThis.APP_LANG; + }); + + it('adds the page language as the lang query argument', () => { + globalThis.APP_LANG = 'en'; + expect(withLang('/api/categories-full')).toBe('/api/categories-full?lang=en'); + }); + + it('appends to an existing query string', () => { + globalThis.APP_LANG = 'uk'; + expect(withLang('/api/location?x=1')).toBe('/api/location?x=1&lang=uk'); + }); + + it('leaves the URL unchanged when the page has no language', () => { + expect(withLang('/api/categories-full')).toBe('/api/categories-full'); + }); +}); diff --git a/goodmap/api/core_api.py b/goodmap/api/core_api.py index a7ebe73d..56c0a073 100644 --- a/goodmap/api/core_api.py +++ b/goodmap/api/core_api.py @@ -9,6 +9,7 @@ import pysupercluster from flask import Blueprint, current_app, jsonify, make_response, request from flask_babel import gettext +from jinja2 import Template from platzky import FeatureFlagSet from platzky.attachment import create_attachment from platzky.config import AttachmentConfig, LanguagesMapping @@ -205,6 +206,7 @@ def core_pages( feature_flags: FeatureFlagSet, shortcodes: dict[str, Shortcode], pin_marker_fields: PinMarkerFields, + alt_template: Template | None = None, ) -> Blueprint: # Routes with translated responses (pin fields, schema, categories) are query_locale # routes: they follow the calling page's language, sent as ``?lang=``, since /api is @@ -429,7 +431,9 @@ def get_location(location_id): visible_data = database.get_visible_data() meta_data = database.get_meta_data() - formatted_data = prepare_pin(location.model_dump(), visible_data, meta_data, shortcodes) + formatted_data = prepare_pin( + location.model_dump(), visible_data, meta_data, shortcodes, alt_template + ) return jsonify(formatted_data) @core_api_blueprint.route("/version", methods=["GET"]) diff --git a/goodmap/config.py b/goodmap/config.py index 6f986233..918f4c99 100644 --- a/goodmap/config.py +++ b/goodmap/config.py @@ -38,6 +38,10 @@ class GoodmapConfig(PlatzkyConfig): alias="ATTACHMENT", ) + # Jinja template describing a place to any of its images that carries no ``alt`` of its + # own; see goodmap.alt_template. Unset, an image is described by the place's name. + image_alt_template: str | None = Field(default=None, alias="IMAGE_ALT_TEMPLATE") + @classmethod def model_validate( cls, diff --git a/goodmap/field_types.py b/goodmap/field_types.py index 1861cf80..b4e89cb2 100644 --- a/goodmap/field_types.py +++ b/goodmap/field_types.py @@ -10,6 +10,15 @@ declares, so any field can ask to be a ``hyperlink`` whatever it is called. That lookup is safe only because this catalogue is closed: an entry may name a type in here and nothing else, and so can never point itself at a plugin's renderer. + +The catalogue is goodmap's own types plus an allowlist of platzky's built-ins - ``image``, +so a place can carry photos. An allowlist rather than the whole set, because the entries +naming these types are data nobody vouched for, and platzky's ``html`` would hand them raw +markup in the popup. + +A field may hold several values of its type under ``items`` - +``{"type": "image", "items": [{"url": …}, …]}`` - each rendered on its own; see +:func:`goodmap.formatter.prepare_pin`. """ from collections.abc import Sequence @@ -17,6 +26,7 @@ from markupsafe import Markup, escape from platzky.shortcodes import Shortcode, ShortcodeAttr, ShortcodeAttrs, UrlNotPermitted +from platzky.shortcodes.builtins import get_builtin_shortcodes from platzky.shortcodes.link import LinkShortcode #: Schemes that navigate the browser somewhere, and so are worth a new tab. @@ -91,7 +101,14 @@ class CTAFieldShortcode(HyperlinkFieldShortcode): description = "A marker field holding a URL, shown as a call-to-action button." +#: platzky built-ins a marker field may name as its ``type``. An allowlist, not the whole +#: set: ``html`` would let an entry nobody vouched for emit raw markup into the popup. +_PLATZKY_FIELD_TYPES = ("image",) + +_platzky_shortcodes = get_builtin_shortcodes() + #: Field ``type`` -> the shortcode rendering it, keyed by the name written in the data. BUILTIN_FIELD_TYPES: dict[str, Shortcode] = { - shortcode.name: shortcode for shortcode in (HyperlinkFieldShortcode(), CTAFieldShortcode()) + **{name: _platzky_shortcodes[name] for name in _PLATZKY_FIELD_TYPES}, + **{s.name: s for s in (HyperlinkFieldShortcode(), CTAFieldShortcode())}, } diff --git a/goodmap/formatter.py b/goodmap/formatter.py index f288813b..a734b64f 100644 --- a/goodmap/formatter.py +++ b/goodmap/formatter.py @@ -1,30 +1,35 @@ """Formatters for translating and preparing location data for display.""" import logging +from functools import cache from typing import Any from flask_babel import gettext, lazy_gettext +from goodmap.alt_template import render_alt from goodmap.field_types import BUILTIN_FIELD_TYPES logger = logging.getLogger(__name__) def safe_gettext(text): - """Translate ``text``, mapping over a list and leaving a dict alone. + """Translate ``text``, mapping over a list; anything that is not text is left alone. + + A dict, a number or a position has nothing for ``gettext`` to look up, so it comes back + as it is - which is what lets one helper translate popup values and alt template + context alike. Args: - text: A str, a list of str, or a dict. + text: A str, a list, or any other field value. Returns: The translation, in the same shape as the input. """ - if isinstance(text, list): - return list(map(gettext, text)) - elif isinstance(text, dict): - return text - else: + if isinstance(text, str): return gettext(text) + if isinstance(text, list): + return [safe_gettext(item) if isinstance(item, str) else item for item in text] + return text def _builtin_shortcode(value): @@ -74,7 +79,66 @@ def _rendered_field(shortcode, value): return {**entry, "type": shortcode.name, "html": shortcode.render_value(value)} -def prepare_pin(place, visible_fields, meta_data, shortcodes=None) -> dict[str, Any]: +def _rendered_builtin(shortcode, value, defaults): + """Build the payload for a field naming one of goodmap's own types. + + Two things only goodmap's own types get, because goodmap knows what their rendering + means - a plugin's field keeps exactly the rendering its shortcode gives it: + + * ``items``: a field holding several values lists them there, each rendered on its own + and returned with its own ``html`` - what a gallery plugin would lay out - while the + field's ``html`` joins them for the popup. An item the shortcode refuses renders to + nothing and is dropped from both. + * defaults derived from the place, such as an image's ``alt``. An entry's own value wins; + a ``null`` counts as absent, so imported data with ``"alt": null`` is still described + rather than marked decorative. + + Args: + shortcode: The built-in Shortcode the field's ``type`` named. + value: The field's value from the location data - a dict, since it named a type. + defaults: ``defaults(shortcode)`` -> the place-derived attributes it declares. + + Returns: + The field payload, carrying ``type`` and ``html``, and ``items`` when it had them. + """ + fallback = defaults(shortcode) + + def rendered(entry): + given = {key: item for key, item in entry.items() if item is not None} + return _rendered_field(shortcode, {**fallback, **given}) + + if not isinstance(value.get("items"), list): + return rendered(value) + items = [rendered(item) for item in value["items"] if isinstance(item, dict)] + items = [{k: v for k, v in item.items() if k != "type"} for item in items if item["html"]] + html = "".join(item["html"] for item in items) + return {**value, "items": items, "type": shortcode.name, "html": html} + + +def _without_html(value): + """Drop any ``html`` an unrendered field brought with it, its ``items`` included. + + ``html`` is this payload's word for "the server rendered this", and the popup injects it + as markup. Nothing rendered this field, so an ``html`` here came from the data - a + suggested point, an imported dataset - and must not be mistaken for goodmap's own output. + + Args: + value: The field's value from the location data. + + Returns: + The value without ``html``, at the top level or on any item. + """ + if not isinstance(value, dict): + return value + stripped = {key: item for key, item in value.items() if key != "html"} + if isinstance(stripped.get("items"), list): + stripped["items"] = [_without_html(item) for item in stripped["items"]] + return stripped + + +def prepare_pin( + place, visible_fields, meta_data, shortcodes=None, alt_template=None +) -> dict[str, Any]: """Format one location into the translated payload its map popup renders. Args: @@ -84,25 +148,38 @@ def prepare_pin(place, visible_fields, meta_data, shortcodes=None) -> dict[str, shortcodes: Field name → the platzky Shortcode bound to it. A plugin claims a field by name; anything else may still name a built-in ``type`` in its own data (see :mod:`goodmap.field_types`). Either way one shortcode renders it. + alt_template: The compiled ``IMAGE_ALT_TEMPLATE`` (see :mod:`goodmap.alt_template`), + describing the place to any image that does not describe itself. Returns: Title, subtitle, position, metadata, and ``data`` as ``[label, value]`` pairs. """ plugins = shortcodes or {} + + @cache + def describe(): + # Rendered once per pin, and only once an image asks for it. + return render_alt(alt_template, {field: safe_gettext(v) for field, v in place.items()}) + + def defaults(shortcode): + declared = {attribute.name for attribute in shortcode.attributes} + return {"alt": describe()} if alt_template and "alt" in declared else {} + data = [] for field in visible_fields: if field not in place: continue value = safe_gettext(place[field]) - shortcode = plugins.get(field) or _builtin_shortcode(value) - if shortcode is not None: - value = _rendered_field(shortcode, value) - elif isinstance(value, dict) and "html" in value: - # ``html`` is this payload's word for "the server rendered this", and the popup - # injects it as markup. Nothing rendered this field, so an ``html`` here came - # from the data - a suggested point, an imported dataset - and must not be - # mistaken for goodmap's own output. - value = {key: item for key, item in value.items() if key != "html"} + if field in plugins: + value = _rendered_field(plugins[field], value) + elif builtin := _builtin_shortcode(value): + value = _rendered_builtin(builtin, value, defaults) + if not value["html"]: + # Goodmap's own types have nothing to show but their ``html``, so one that + # rendered nothing - every image refused - would leave a label over a blank. + continue + else: + value = _without_html(value) data.append([gettext(field), value]) pin_data = { "title": place["name"], diff --git a/goodmap/goodmap.py b/goodmap/goodmap.py index 9f952e2f..3efde13d 100644 --- a/goodmap/goodmap.py +++ b/goodmap/goodmap.py @@ -14,6 +14,7 @@ from platzky.models import CmsModule from platzky.shortcodes import Shortcode +from goodmap.alt_template import compile_alt_template from goodmap.api.admin_api import admin_pages from goodmap.api.api_models import PinMarkerFields from goodmap.api.core_api import core_pages @@ -200,6 +201,9 @@ def create_app_from_config(config: GoodmapConfig) -> platzky.Engine: # page load (see goodmap.initial_view). initial_view = resolve_initial_view(get_initial_view(app.db)(app.db)) + # Compiled here for the same reason: a template that does not parse fails the boot. + alt_template = compile_alt_template(config.image_alt_template) + location_model = create_location_model(location_obligatory_fields, categories) app.db = extend_db_with_goodmap_queries(app.db, location_model) @@ -276,6 +280,7 @@ def handle_csrf_error(error): feature_flags=config.feature_flags, shortcodes=shortcodes, pin_marker_fields=pin_marker_fields, + alt_template=alt_template, ) app.register_blueprint(cp) diff --git a/tests/unit_tests/test_alt_template.py b/tests/unit_tests/test_alt_template.py new file mode 100644 index 00000000..f83e84d0 --- /dev/null +++ b/tests/unit_tests/test_alt_template.py @@ -0,0 +1,63 @@ +import logging + +import pytest +from jinja2 import TemplateSyntaxError + +from goodmap import alt_template +from goodmap.alt_template import compile_alt_template, render_alt + +place = { + "name": "Grunwaldzki", + "type_of_place": "big bridge", + "is_free": "true", + "amenities": ["lighting", "benches"], +} + + +def test_default_describes_the_place_by_its_name(): + assert render_alt(compile_alt_template(None), place) == "Grunwaldzki" + + +@pytest.mark.parametrize(("is_free", "expected"), [("true", "free"), ("false", "paid")]) +def test_conditional(is_free, expected): + template = compile_alt_template("{{ 'free' if is_free == 'true' else 'paid' }}") + assert render_alt(template, {**place, "is_free": is_free}) == expected + + +def test_lists_are_joined_by_the_template(): + template = compile_alt_template("{{ amenities | join(', ') }}") + assert render_alt(template, place) == "lighting, benches" + + +def test_missing_field_prints_empty_and_whitespace_collapses(): + template = compile_alt_template("photo of\n {{ speed_limit }} {{ type_of_place }} ") + assert render_alt(template, place) == "photo of big bridge" + + +def test_template_text_can_be_translated(monkeypatch): + monkeypatch.setitem(alt_template._environment.globals, "_", lambda text: f"{text}-pl") + template = compile_alt_template("{{ _('photo of') }} {{ name }}") + assert render_alt(template, place) == "photo of-pl Grunwaldzki" + + +def test_syntax_error_raises_at_compile_time(): + with pytest.raises(TemplateSyntaxError): + compile_alt_template("{{ name") + + +def test_sandbox_refusal_falls_back_to_the_name(caplog): + template = compile_alt_template("{{ name.__class__.__mro__ }}") + with caplog.at_level(logging.WARNING): + assert render_alt(template, place) == "Grunwaldzki" + assert "IMAGE_ALT_TEMPLATE" in caplog.text + + +def test_none_prints_as_nothing(): + """``model_dump`` keeps an unset optional field as None, which Jinja would print.""" + template = compile_alt_template("{{ name }} {{ remark }}") + assert render_alt(template, {**place, "remark": None}) == "Grunwaldzki" + + +def test_any_render_error_falls_back_to_the_name(): + template = compile_alt_template("{{ name }} {{ 100 // capacity }}") + assert render_alt(template, {**place, "capacity": 0}) == "Grunwaldzki" diff --git a/tests/unit_tests/test_core_api.py b/tests/unit_tests/test_core_api.py index 39926f17..13318107 100644 --- a/tests/unit_tests/test_core_api.py +++ b/tests/unit_tests/test_core_api.py @@ -3,6 +3,7 @@ import flask_babel import pytest +from jinja2 import TemplateSyntaxError from goodmap.api.core_api import get_default_issue_options, make_tuple_translation from goodmap.config import GoodmapConfig @@ -1208,3 +1209,32 @@ def to_dict(self, flat=False): assert isinstance(locations[0], dict) assert "uuid" in locations[0] assert "position" in locations[0] + + +def _app_with_images(**config): + config_data = {**get_test_config_data(), **config} + data = config_data["DB"]["DATA"] + data["data"][0]["images"] = { + "type": "image", + "items": [{"url": "https://example.com/1.jpg"}, {"url": "https://example.com/2.jpg"}], + } + data["visible_data"] = [*data["visible_data"], "images"] + return create_app_from_config(GoodmapConfig.model_validate(config_data)).test_client() + + +def test_location_images_are_described_by_the_configured_alt_template(): + client = _app_with_images(IMAGE_ALT_TEMPLATE="photo of {{ type_of_place }}") + response = client.get("/api/location/11111111-1111-1111-1111-111111111111") + images = dict(response.json["data"])["images"] + assert [item["alt"] for item in images["items"]] == ["photo of test-place"] * 2 + + +def test_location_images_default_to_the_place_name(): + client = _app_with_images() + response = client.get("/api/location/11111111-1111-1111-1111-111111111111") + assert 'alt="test"' in dict(response.json["data"])["images"]["html"] + + +def test_unparseable_alt_template_fails_the_boot(): + with pytest.raises(TemplateSyntaxError): + _app_with_images(IMAGE_ALT_TEMPLATE="{{ name") diff --git a/tests/unit_tests/test_formatter.py b/tests/unit_tests/test_formatter.py index cc1276ff..544f21d3 100644 --- a/tests/unit_tests/test_formatter.py +++ b/tests/unit_tests/test_formatter.py @@ -4,6 +4,7 @@ from markupsafe import Markup from platzky.shortcodes.shortcode import Shortcode, ShortcodeAttr, ShortcodeAttrs +from goodmap.alt_template import compile_alt_template from goodmap.formatter import prepare_pin test_place = { @@ -229,3 +230,130 @@ def test_a_blank_display_value_falls_back_to_the_url(display_value): } result = prepare_pin(place, ["website"], []) assert ">https://example.com" in result["data"][0][1]["html"] + + +def _images(*items): + return {**test_place, "images": {"type": "image", "items": list(items)}} + + +def test_image_items_are_each_rendered_and_joined(): + """Each item keeps its own ``html`` for a gallery plugin; the field's joins them.""" + place = _images({"url": "https://example.com/1.jpg"}, {"url": "https://example.com/2.jpg"}) + value = prepare_pin(place, ["images"], [])["data"][0][1] + assert value["type"] == "image" + assert [item["html"] for item in value["items"]] == [ + '', + '', + ] + assert value["html"] == "".join(item["html"] for item in value["items"]) + + +def test_image_passes_width_and_height_through(): + place = _images({"url": "https://example.com/1.jpg", "width": 400, "height": 300}) + html = prepare_pin(place, ["images"], [])["data"][0][1]["html"] + assert html == '' + + +@pytest.mark.parametrize( + "item", + [ + {"url": "javascript:alert(1)"}, + {"url": "data:image/png;base64,AAAA"}, + {"alt": "no url"}, + {"url": "https://example.com/1.jpg", "width": "wide"}, + ], +) +def test_refused_image_item_is_dropped(item): + place = _images(item, {"url": "https://example.com/ok.jpg"}) + value = prepare_pin(place, ["images"], [])["data"][0][1] + assert [i["url"] for i in value["items"]] == ["https://example.com/ok.jpg"] + assert value["html"] == '' + + +def test_image_field_with_every_item_refused_is_left_out(): + """A label over a blank says nothing; the popup does not need to know why.""" + place = _images({"url": "javascript:alert(1)"}) + assert prepare_pin(place, ["images"], [])["data"] == [] + + +def test_image_alt_defaults_to_the_template_and_an_items_own_alt_wins(): + place = _images( + {"url": "https://example.com/1.jpg"}, + {"url": "https://example.com/2.jpg", "alt": "Own"}, + {"url": "https://example.com/3.jpg", "alt": ""}, + ) + template = compile_alt_template("{{ type_of_place }} {{ name }}") + items = prepare_pin(place, ["images"], [], alt_template=template)["data"][0][1]["items"] + assert [item["alt"] for item in items] == ["container LASSO", "Own", ""] + + +def test_alt_default_is_not_given_to_a_type_without_alt(): + place = {**test_place, "website": {"type": "hyperlink", "value": "https://example.com"}} + value = prepare_pin(place, ["website"], [], alt_template=compile_alt_template(None)) + assert "alt" not in value["data"][0][1] + + +def test_platzky_builtins_outside_the_allowlist_are_not_rendered(): + """``html`` would hand data nobody vouched for raw markup in the popup.""" + place = { + **test_place, + "evil": {"type": "html", "html": "x", "items": [{"html": ""}]}, + } + value = prepare_pin(place, ["evil"], [])["data"][0][1] + assert value == {"type": "html", "items": [{}]} + + +def test_alt_template_sees_translated_field_values(monkeypatch): + monkeypatch.setattr("goodmap.formatter.gettext", lambda text: f"{text}-pl") + template = compile_alt_template("{{ type_of_place }} {{ types | join(',') }}") + place = _images({"url": "https://example.com/1.jpg"}) + items = prepare_pin(place, ["images"], [], alt_template=template)["data"][0][1]["items"] + assert items[0]["alt"] == "container-pl shoes-pl" + + +def test_image_alt_null_counts_as_absent(): + """Imported data writing ``"alt": null`` means "not given", not "decorative".""" + place = _images({"url": "https://example.com/1.jpg", "alt": None}) + template = compile_alt_template(None) + items = prepare_pin(place, ["images"], [], alt_template=template)["data"][0][1]["items"] + assert items[0]["alt"] == "LASSO" + + +def test_alt_template_is_not_rendered_for_a_pin_without_images(monkeypatch): + calls = [] + monkeypatch.setattr("goodmap.formatter.render_alt", lambda *args: calls.append(args) or "") + place = {**test_place, "website": {"type": "hyperlink", "value": "https://example.com"}} + prepare_pin(place, ["website", "plain_text"], [], alt_template=compile_alt_template(None)) + assert calls == [] + + +def test_alt_template_is_rendered_once_per_pin(monkeypatch): + calls = [] + monkeypatch.setattr("goodmap.formatter.render_alt", lambda *args: calls.append(args) or "x") + place = { + **_images({"url": "https://example.com/1.jpg"}, {"url": "https://example.com/2.jpg"}), + "more": {"type": "image", "items": [{"url": "https://example.com/3.jpg"}]}, + } + prepare_pin(place, ["images", "more"], [], alt_template=compile_alt_template(None)) + assert len(calls) == 1 + + +class _AltShortcode(_FakeShortcode): + attributes = ShortcodeAttrs([ShortcodeAttr("alt", "test")]) + + def render(self, attrs: ShortcodeAttrs, content: str, children: Sequence[Markup]) -> str: + return f"{attrs.alt}:{content}" + + +def test_plugin_field_keeps_its_own_rendering(): + """``items`` and place-derived defaults are for goodmap's own types only.""" + place = {**test_place, "promo_code": {"code": "X", "items": [{"code": "Y"}]}} + value = prepare_pin( + place, + ["promo_code"], + [], + shortcodes={"promo_code": _AltShortcode()}, + alt_template=compile_alt_template(None), + )["data"][0][1] + assert value["html"] == ":X" + assert value["items"] == [{"code": "Y"}] From 3b71e38735ee16b11dcdce1df3e11da0baa8aef7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Krzysztof=20Ko=C5=82odzi=C5=84ski?= Date: Tue, 20 Oct 2026 01:29:50 +0200 Subject: [PATCH 02/34] added missing file --- goodmap/alt_template.py | 74 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 goodmap/alt_template.py diff --git a/goodmap/alt_template.py b/goodmap/alt_template.py new file mode 100644 index 00000000..7789f648 --- /dev/null +++ b/goodmap/alt_template.py @@ -0,0 +1,74 @@ +"""The default ``alt`` text for a marker image, built from the place it belongs to. + +An image item may carry its own ``alt``; most will not, and an image with no description is +invisible to a screen reader. So the operator writes one template, ``IMAGE_ALT_TEMPLATE``, +and every image without its own ``alt`` gets that template rendered against its place. + +The template is Jinja, which the operator already knows and Flask already ships, run in the +immutable sandbox so a template can reach the place's values and nothing behind them. It +is compiled once at startup - a syntax error fails the boot, not every popup - and rendered +per pin with the place's fields, already translated, as its context. +""" + +import logging +import re +from collections.abc import Mapping +from typing import Any + +from flask_babel import gettext +from jinja2 import Template +from jinja2.sandbox import ImmutableSandboxedEnvironment + +logger = logging.getLogger(__name__) + +#: Used when the operator sets no template: every location has a name. +DEFAULT_ALT_TEMPLATE = "{{ name }}" + +# No autoescape: the result is an attribute value, and the image shortcode escapes it +# where it interpolates it. Escaping here as well would show ``&`` in the alt. +# ``finalize`` prints None as nothing: ``model_dump`` keeps an unset optional field as None, +# and a screen reader would otherwise read out "None". +_environment = ImmutableSandboxedEnvironment( + autoescape=False, finalize=lambda value: "" if value is None else value +) +_environment.globals["_"] = gettext + +_WHITESPACE = re.compile(r"\s+") + + +def compile_alt_template(source: str | None) -> Template: + """Compile the operator's alt template, or the default when there is none. + + Args: + source: The ``IMAGE_ALT_TEMPLATE`` config value. + + Returns: + The compiled template. + + Raises: + jinja2.TemplateSyntaxError: If the template does not parse. + """ + return _environment.from_string(source or DEFAULT_ALT_TEMPLATE) + + +def render_alt(template: Template, context: Mapping[str, Any]) -> str: + """Render the alt text for one place. + + A template that parsed can still fail on a particular place - the sandbox refusing an + attribute, a filter given the wrong type, a division by a field that is zero - and a + popup is not worth losing over its alt text, so any failure falls back to the place's + name. + + Args: + template: From :func:`compile_alt_template`. + context: The place's fields, already translated. + + Returns: + The alt text, with whitespace runs collapsed. + """ + try: + rendered = template.render(context) + except Exception: # whatever the template raised, the popup still opens + logger.warning("IMAGE_ALT_TEMPLATE failed for a location; using its name.", exc_info=True) + rendered = str(context.get("name", "")) + return _WHITESPACE.sub(" ", rendered).strip() From 5b2b582384007c1b979f9764c987a4c8fb9721dc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Krzysztof=20Ko=C5=82odzi=C5=84ski?= Date: Wed, 21 Oct 2026 12:41:26 +0200 Subject: [PATCH 03/34] fix linting --- goodmap/alt_template.py | 9 ++++++--- goodmap/formatter.py | 8 +++++--- tests/unit_tests/test_alt_template.py | 6 ++++-- tests/unit_tests/test_core_api.py | 2 ++ tests/unit_tests/test_formatter.py | 23 ++++++++++++++++++----- 5 files changed, 35 insertions(+), 13 deletions(-) diff --git a/goodmap/alt_template.py b/goodmap/alt_template.py index 7789f648..0cfe967f 100644 --- a/goodmap/alt_template.py +++ b/goodmap/alt_template.py @@ -24,13 +24,16 @@ #: Used when the operator sets no template: every location has a name. DEFAULT_ALT_TEMPLATE = "{{ name }}" + # No autoescape: the result is an attribute value, and the image shortcode escapes it # where it interpolates it. Escaping here as well would show ``&`` in the alt. # ``finalize`` prints None as nothing: ``model_dump`` keeps an unset optional field as None, # and a screen reader would otherwise read out "None". -_environment = ImmutableSandboxedEnvironment( - autoescape=False, finalize=lambda value: "" if value is None else value -) +def _finalize(value: object) -> object: + return "" if value is None else value + + +_environment = ImmutableSandboxedEnvironment(autoescape=False, finalize=_finalize) _environment.globals["_"] = gettext _WHITESPACE = re.compile(r"\s+") diff --git a/goodmap/formatter.py b/goodmap/formatter.py index a734b64f..ec7da1d6 100644 --- a/goodmap/formatter.py +++ b/goodmap/formatter.py @@ -157,13 +157,15 @@ def prepare_pin( plugins = shortcodes or {} @cache - def describe(): + def describe(template): # Rendered once per pin, and only once an image asks for it. - return render_alt(alt_template, {field: safe_gettext(v) for field, v in place.items()}) + return render_alt(template, {field: safe_gettext(v) for field, v in place.items()}) def defaults(shortcode): + if alt_template is None: + return {} declared = {attribute.name for attribute in shortcode.attributes} - return {"alt": describe()} if alt_template and "alt" in declared else {} + return {"alt": describe(alt_template)} if "alt" in declared else {} data = [] for field in visible_fields: diff --git a/tests/unit_tests/test_alt_template.py b/tests/unit_tests/test_alt_template.py index f83e84d0..8eda7bca 100644 --- a/tests/unit_tests/test_alt_template.py +++ b/tests/unit_tests/test_alt_template.py @@ -3,7 +3,6 @@ import pytest from jinja2 import TemplateSyntaxError -from goodmap import alt_template from goodmap.alt_template import compile_alt_template, render_alt place = { @@ -35,8 +34,11 @@ def test_missing_field_prints_empty_and_whitespace_collapses(): def test_template_text_can_be_translated(monkeypatch): - monkeypatch.setitem(alt_template._environment.globals, "_", lambda text: f"{text}-pl") + def translate(text: str) -> str: + return f"{text}-pl" + template = compile_alt_template("{{ _('photo of') }} {{ name }}") + monkeypatch.setitem(template.environment.globals, "_", translate) assert render_alt(template, place) == "photo of-pl Grunwaldzki" diff --git a/tests/unit_tests/test_core_api.py b/tests/unit_tests/test_core_api.py index 13318107..ea761ab2 100644 --- a/tests/unit_tests/test_core_api.py +++ b/tests/unit_tests/test_core_api.py @@ -1225,6 +1225,7 @@ def _app_with_images(**config): def test_location_images_are_described_by_the_configured_alt_template(): client = _app_with_images(IMAGE_ALT_TEMPLATE="photo of {{ type_of_place }}") response = client.get("/api/location/11111111-1111-1111-1111-111111111111") + assert response.json is not None images = dict(response.json["data"])["images"] assert [item["alt"] for item in images["items"]] == ["photo of test-place"] * 2 @@ -1232,6 +1233,7 @@ def test_location_images_are_described_by_the_configured_alt_template(): def test_location_images_default_to_the_place_name(): client = _app_with_images() response = client.get("/api/location/11111111-1111-1111-1111-111111111111") + assert response.json is not None assert 'alt="test"' in dict(response.json["data"])["images"]["html"] diff --git a/tests/unit_tests/test_formatter.py b/tests/unit_tests/test_formatter.py index 544f21d3..77455d13 100644 --- a/tests/unit_tests/test_formatter.py +++ b/tests/unit_tests/test_formatter.py @@ -304,7 +304,10 @@ def test_platzky_builtins_outside_the_allowlist_are_not_rendered(): def test_alt_template_sees_translated_field_values(monkeypatch): - monkeypatch.setattr("goodmap.formatter.gettext", lambda text: f"{text}-pl") + def translate(text: str) -> str: + return f"{text}-pl" + + monkeypatch.setattr("goodmap.formatter.gettext", translate) template = compile_alt_template("{{ type_of_place }} {{ types | join(',') }}") place = _images({"url": "https://example.com/1.jpg"}) items = prepare_pin(place, ["images"], [], alt_template=template)["data"][0][1]["items"] @@ -320,16 +323,26 @@ def test_image_alt_null_counts_as_absent(): def test_alt_template_is_not_rendered_for_a_pin_without_images(monkeypatch): - calls = [] - monkeypatch.setattr("goodmap.formatter.render_alt", lambda *args: calls.append(args) or "") + calls: list[tuple[object, ...]] = [] + + def render_alt(*args: object) -> str: + calls.append(args) + return "" + + monkeypatch.setattr("goodmap.formatter.render_alt", render_alt) place = {**test_place, "website": {"type": "hyperlink", "value": "https://example.com"}} prepare_pin(place, ["website", "plain_text"], [], alt_template=compile_alt_template(None)) assert calls == [] def test_alt_template_is_rendered_once_per_pin(monkeypatch): - calls = [] - monkeypatch.setattr("goodmap.formatter.render_alt", lambda *args: calls.append(args) or "x") + calls: list[tuple[object, ...]] = [] + + def render_alt(*args: object) -> str: + calls.append(args) + return "x" + + monkeypatch.setattr("goodmap.formatter.render_alt", render_alt) place = { **_images({"url": "https://example.com/1.jpg"}, {"url": "https://example.com/2.jpg"}), "more": {"type": "image", "items": [{"url": "https://example.com/3.jpg"}]}, From c45791509d4701686d06a512f140635a44218618 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Krzysztof=20Ko=C5=82odzi=C5=84ski?= Date: Wed, 21 Oct 2026 13:47:39 +0200 Subject: [PATCH 04/34] added photo to e2e test --- e2e-tests/e2e_test_data_initial.json | 11 ++++++++++- e2e-tests/tests/basic/test_popup.py | 3 +++ .../src/components/MarkerPopup/serverHtmlField.jsx | 1 + 3 files changed, 14 insertions(+), 1 deletion(-) diff --git a/e2e-tests/e2e_test_data_initial.json b/e2e-tests/e2e_test_data_initial.json index b02a205c..43386c52 100644 --- a/e2e-tests/e2e_test_data_initial.json +++ b/e2e-tests/e2e_test_data_initial.json @@ -42,7 +42,15 @@ "lighting" ], "uuid": "c8ecf476-5968-40da-ba5c-e810ad9ff203", - "remark": "very old bridge" + "remark": "very old bridge", + "photos": { + "type": "image", + "items": [ + { + "url": "https://upload.wikimedia.org/wikipedia/commons/thumb/f/f3/WroclawMostZwierzyniecki.jpg/500px-WroclawMostZwierzyniecki.jpg" + } + ] + } }, { "name": "Milenijny", @@ -288,6 +296,7 @@ } }, "visible_data": [ + "photos", "remark", "accessible_by", "type_of_place", diff --git a/e2e-tests/tests/basic/test_popup.py b/e2e-tests/tests/basic/test_popup.py index abff7da6..8dbe136d 100644 --- a/e2e-tests/tests/basic/test_popup.py +++ b/e2e-tests/tests/basic/test_popup.py @@ -32,6 +32,9 @@ def test_displays_popup_title_subtitle_categories_and_cta(self, page: Page, wind verify_popup_content(page, EXPECTED_PLACE_ZWIERZYNIECKA) + # The seeded photo has no alt of its own, so the default template names the place. + expect(popup.locator('img[alt="Zwierzyniecka"]')).to_be_attached() + # Verify close button and click it close_button = page.locator(".leaflet-popup-close-button") expect(close_button).to_be_visible() diff --git a/frontend/src/components/MarkerPopup/serverHtmlField.jsx b/frontend/src/components/MarkerPopup/serverHtmlField.jsx index d061f487..d69a6056 100644 --- a/frontend/src/components/MarkerPopup/serverHtmlField.jsx +++ b/frontend/src/components/MarkerPopup/serverHtmlField.jsx @@ -19,6 +19,7 @@ import PropTypes from 'prop-types'; * cannot replace it — the server always emits `html` for a type it renders, so there is * always a seed beneath the wrapper. */ +// eslint-disable-next-line react/no-danger -- trusted server-rendered markup, see above const ServerHtmlField = ({ input }) => ; ServerHtmlField.propTypes = { From 4ec18c31f26d9be41b10f645ed091f70c688ff54 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Krzysztof=20Ko=C5=82odzi=C5=84ski?= Date: Wed, 21 Oct 2026 13:57:56 +0200 Subject: [PATCH 05/34] fixes after review --- frontend/src/components/MarkerPopup/LocationDetails.jsx | 7 +++++-- frontend/tests/MarkerPopup/LocationDetailsBox.test.jsx | 9 +++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/frontend/src/components/MarkerPopup/LocationDetails.jsx b/frontend/src/components/MarkerPopup/LocationDetails.jsx index b78aa7c0..3202d20b 100644 --- a/frontend/src/components/MarkerPopup/LocationDetails.jsx +++ b/frontend/src/components/MarkerPopup/LocationDetails.jsx @@ -249,7 +249,10 @@ NavigateMeButton.propTypes = { // Which popup section a field shows in, by its value's `type` - never by its label, which is // `gettext(field)` and so differs per locale. Anything not listed is a labelled detail. -const SECTION_BY_TYPE = { image: 'images', CTA: 'actions' }; +const SECTION_BY_TYPE = new Map([ + ['image', 'images'], + ['CTA', 'actions'], +]); // In display order. A `labelled` section pairs each value with its field name. const SECTIONS = [ @@ -258,7 +261,7 @@ const SECTIONS = [ { key: 'actions', Container: CTAContainer, labelled: false }, ]; -const sectionOf = ([, value]) => SECTION_BY_TYPE[value?.type] ?? 'details'; +const sectionOf = ([, value]) => SECTION_BY_TYPE.get(value?.type) ?? 'details'; /** * Component that renders location details: title, subtitle, then each section of fields. diff --git a/frontend/tests/MarkerPopup/LocationDetailsBox.test.jsx b/frontend/tests/MarkerPopup/LocationDetailsBox.test.jsx index eeb78d76..c2624d5d 100644 --- a/frontend/tests/MarkerPopup/LocationDetailsBox.test.jsx +++ b/frontend/tests/MarkerPopup/LocationDetailsBox.test.jsx @@ -99,6 +99,15 @@ describe('should render marker popup correctly', () => { render(), ).not.toThrow(); }); + + it('keeps a field whose type names an Object.prototype property', () => { + const place = { + ...correctMarkerData, + data: [['oddType', { type: 'constructor', value: 'still shown' }]], + }; + render(); + expect(screen.getByText('oddType')).toBeInTheDocument(); + }); }); describe('should handle plugin fields', () => { From 1378feeaee4c254d0ee7e50262c5a6edef6354ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Krzysztof=20Ko=C5=82odzi=C5=84ski?= Date: Wed, 21 Oct 2026 14:37:16 +0200 Subject: [PATCH 06/34] better examples --- docs/api-reference.rst | 2 +- docs/configuration.rst | 6 +++--- docs/http-api.rst | 30 ++++++++++++++++++++---------- 3 files changed, 24 insertions(+), 14 deletions(-) diff --git a/docs/api-reference.rst b/docs/api-reference.rst index acdff11f..dd8fbf9b 100644 --- a/docs/api-reference.rst +++ b/docs/api-reference.rst @@ -96,7 +96,7 @@ Formatting Turning a point into what its popup shows: translation of category keys, option values and field names on the way out (:ref:`config-translations`), and the rendering of a field's value into HTML — by a plugin's shortcode, or by one of the field types goodmap builds in -(:ref:`plugins-builtin-field-types`). +(:ref:`built-in field types `). .. automodule:: goodmap.formatter :members: diff --git a/docs/configuration.rst b/docs/configuration.rst index 9335263d..1f51db22 100644 --- a/docs/configuration.rst +++ b/docs/configuration.rst @@ -164,9 +164,9 @@ Basic keys ``IMAGE_ALT_TEMPLATE`` The ``alt`` text given to a marker image that carries none of its own (see - :ref:`plugins-builtin-field-types`), so a screen reader can say what the photo shows. - It is a `Jinja `_ template, rendered once - per point with that point's fields as variables: + :ref:`built-in field types `), so a screen reader can say + what the photo shows. It is a `Jinja `_ + template, rendered once per point with that point's fields as variables: .. code-block:: yaml diff --git a/docs/http-api.rst b/docs/http-api.rst index 0eef3c2a..4c49df8d 100644 --- a/docs/http-api.rst +++ b/docs/http-api.rst @@ -195,23 +195,33 @@ or one a plugin's shortcode is bound to — comes back as an object rather than "html": "Example" }] -A field naming a built-in type may hold several values under ``items``, each returned with -its own ``html``. Items that render to nothing are dropped, and a built-in field left with -nothing to show is left out of ``data``: +A field naming a built-in type may hold several values under ``items``. Each item comes back +with its own ``html``, and the field's ``html`` joins them. Items that render to nothing are +dropped, and a built-in field left with nothing to show is left out of ``data``. Stored as +``{"type": "image", "items": [{"url": ".../front.jpg"}, {"url": ".../deck.jpg", "alt": +"The deck at night"}]}``, an image field comes back as: .. code-block:: json ["images", { "type": "image", - "items": [{"url": "https://example.com/front.jpg", "alt": "photo of big bridge", - "html": "\"photo"}], - "html": "\"photo" + "items": [ + {"url": "https://example.com/front.jpg", "alt": "Zwierzyniecka", + "html": "\"Zwierzyniecka\""}, + {"url": "https://example.com/deck.jpg", "alt": "The deck at night", + "html": "\"The"} + ], + "html": "\"Zwierzyniecka\"\"The" }] -``html`` is the rendering to display and ``type`` says what produced it; the entry's own -keys travel alongside for a client that would rather render from the data. See -:ref:`plugins-builtin-field-types` for which types GoodMap ships and -:ref:`plugins-shortcode-rendered-fields` for how a plugin adds one. +The first item had no ``alt``, so :ref:`IMAGE_ALT_TEMPLATE ` +described it: by default, with the point's ``name``. + +``html`` is always the server's rendering, never a value taken from the data: it is what to +display, and ``type`` says what produced it. The entry's own keys travel alongside for a +client that would rather render from the data; such a client must escape them itself. See +:ref:`built-in field types ` for which types GoodMap ships and +:ref:`shortcode-rendered fields ` for how a plugin adds one. The path segment must be a valid UUID; anything else fails routing with ``404``. A well-formed UUID that does not exist also gives ``404 {"message": "Location not found"}``. From b4f63098c6e79a1ebeb57a6d17687b92ed780047 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Krzysztof=20Ko=C5=82odzi=C5=84ski?= Date: Wed, 21 Oct 2026 15:25:59 +0200 Subject: [PATCH 07/34] fixes after review --- docs/configuration.rst | 5 +- docs/plugins.rst | 21 ++--- .../Map/components/AccessibilityTable.jsx | 12 ++- .../MarkerPopup/LocationDetails.jsx | 15 +++- .../MarkerPopup/LocationDetailsBox.test.jsx | 17 ++++ goodmap/alt_template.py | 44 ++++++++--- goodmap/api/core_api.py | 4 +- goodmap/field_types.py | 54 ++++++++++--- goodmap/formatter.py | 48 ++++++----- tests/unit_tests/test_alt_template.py | 2 +- tests/unit_tests/test_formatter.py | 79 ++++++++++++++++++- 11 files changed, 239 insertions(+), 62 deletions(-) diff --git a/docs/configuration.rst b/docs/configuration.rst index 1f51db22..390012dd 100644 --- a/docs/configuration.rst +++ b/docs/configuration.rst @@ -172,10 +172,13 @@ Basic keys IMAGE_ALT_TEMPLATE: >- {{ _('photo of') }} {{ type_of_place }}, - {{ _('free') if is_free == 'true' else _('paid') }}, + {{ _('free') if raw.is_free == 'true' else _('paid') }}, {{ amenities | join(', ') }} Field values arrive already translated, and ``_()`` translates the template's own text. + Compare against ``raw``, the point's fields as stored: a translated value differs per + language — ``is_free`` may read ``tak`` — so ``is_free == 'true'`` would hold in one + language only. A field itself named ``raw`` takes the name over. A field the point lacks prints as nothing, and runs of whitespace are collapsed. Omit the key and an image is described by the point's ``name``. diff --git a/docs/plugins.rst b/docs/plugins.rst index f4d36f5d..950b60c2 100644 --- a/docs/plugins.rst +++ b/docs/plugins.rst @@ -208,21 +208,24 @@ That lookup is safe only because the catalogue is closed: an entry may name a ty and nothing else, so it can never point its own field at a plugin's renderer. ``prepare_pin`` consults it only where no plugin shortcode claimed the field by name. -Alongside its own, goodmap offers an **allowlist** of platzky's built-in shortcodes — -currently ``image`` — so a point can carry photos. It is an allowlist rather than the whole -set because the entries naming these types are data nobody vouched for: a suggested point or -an imported dataset naming platzky's ``html`` would put raw markup into the popup. Adding -another, ``figure`` say, is one word in ``_PLATZKY_FIELD_TYPES``. +Alongside its own, goodmap offers **one** of platzky's built-in shortcodes — ``image``, as +``ImageFieldShortcode`` — so a point can carry photos. Not the whole set, because the entries +naming these types are data nobody vouched for: a suggested point or an imported dataset +naming platzky's ``html`` would put raw markup into the popup. Offering another, ``figure`` +say, means adding it to ``BUILTIN_FIELD_TYPES`` under the same URL policy as ``image``. A field naming one of these types may hold several values under ``items``. Each is rendered on its own and returned with its own ``html`` — what a gallery field plugin on ``image`` would -lay out — while the field's ``html`` joins them for the popup. An item the shortcode refuses -is dropped from both, and a field left with nothing to show is left out of the popup +lay out — while the field's ``html`` joins them for the popup (``hyperlink`` items with +``", "`` between, the rest with nothing, the popup's CSS spacing them). An item the shortcode +refuses is dropped from both, as is one that is not an object — a bare URL string, say, +which logs a warning — and a field left with nothing to show is left out of the popup altogether. ``items`` is for goodmap's own types only: a field a plugin's shortcode is bound to keeps exactly the rendering that shortcode gives it. -An image URL must be ``http``, ``https`` or a path on the site itself (``/static/…``) — -platzky's image policy; ``javascript:`` and ``data:`` are refused: +An image URL must be ``https`` or a path on the site itself (``/static/…``) — stricter than +platzky's image policy, which also takes plain ``http``, since a marker image is fetched by +every visitor who opens the point; ``http:``, ``javascript:`` and ``data:`` are refused: .. code-block:: json diff --git a/frontend/src/components/Map/components/AccessibilityTable.jsx b/frontend/src/components/Map/components/AccessibilityTable.jsx index 062e02e1..89357057 100644 --- a/frontend/src/components/Map/components/AccessibilityTable.jsx +++ b/frontend/src/components/Map/components/AccessibilityTable.jsx @@ -27,6 +27,12 @@ import { useFilters } from '../../../context/FiltersContext'; * @param {Function} props.setIsAccessibilityTableOpen - Callback to close the table and return to map view * @returns {React.ReactElement} Table container with location data and back button */ +// Server-rendered images carry no size of their own; the popup bounds them in its +// ImagesContainer, and a table cell needs the same or one photo stretches its whole row. +const imageCellSx = { + '& img': { display: 'block', maxWidth: 160, height: 'auto', margin: '0 auto' }, +}; + const AccessibilityTable = ({ userPosition, setIsAccessibilityTableOpen }) => { const { selectedFilters } = useFilters(); const { t } = useTranslation(); @@ -108,7 +114,11 @@ const AccessibilityTable = ({ userPosition, setIsAccessibilityTableOpen }) => { sx={{ '&:last-child td, &:last-child th': { border: 0 } }} > {row.map((cell, cellIndex) => ( - + {cell.type ? : cell} ))} diff --git a/frontend/src/components/MarkerPopup/LocationDetails.jsx b/frontend/src/components/MarkerPopup/LocationDetails.jsx index 3202d20b..2b1311e2 100644 --- a/frontend/src/components/MarkerPopup/LocationDetails.jsx +++ b/frontend/src/components/MarkerPopup/LocationDetails.jsx @@ -110,6 +110,11 @@ const CTAContainer = styled.div` outline: 2px solid ${() => globalThis.SECONDARY_COLOR || 'black'}; outline-offset: 2px; } + + /* Several CTAs in one field arrive as one span, so the flex gap does not reach them. */ + a + a { + margin-top: 8px; + } `; // Images the server rendered (`type: "image"`, platzky's [image] shortcode) arrive as plain @@ -286,16 +291,20 @@ const LocationDetails = ({ place }) => ( if (entries.length === 0) return null; return ( - {entries.map(([category, value]) => + {/* Keyed by position: labels are translated, so two fields may share one. + The server's order is fixed per place, so the position is stable. */} + {entries.map(([category, value], index) => labelled ? ( - + // eslint-disable-next-line react/no-array-index-key + {category} ) : ( - + // eslint-disable-next-line react/no-array-index-key + ), )} diff --git a/frontend/tests/MarkerPopup/LocationDetailsBox.test.jsx b/frontend/tests/MarkerPopup/LocationDetailsBox.test.jsx index c2624d5d..4fc2204b 100644 --- a/frontend/tests/MarkerPopup/LocationDetailsBox.test.jsx +++ b/frontend/tests/MarkerPopup/LocationDetailsBox.test.jsx @@ -108,6 +108,23 @@ describe('should render marker popup correctly', () => { render(); expect(screen.getByText('oddType')).toBeInTheDocument(); }); + + it('keeps both of two fields whose translated labels coincide', () => { + const cta = text => ({ type: 'CTA', html: `${text}` }); + const place = { + ...correctMarkerData, + data: [ + ['link', cta('first')], + ['link', cta('second')], + ], + }; + const consoleError = jest.spyOn(console, 'error').mockImplementation(() => {}); + render(); + expect(screen.getByText('first')).toBeInTheDocument(); + expect(screen.getByText('second')).toBeInTheDocument(); + expect(consoleError).not.toHaveBeenCalled(); + consoleError.mockRestore(); + }); }); describe('should handle plugin fields', () => { diff --git a/goodmap/alt_template.py b/goodmap/alt_template.py index 0cfe967f..f79096d3 100644 --- a/goodmap/alt_template.py +++ b/goodmap/alt_template.py @@ -7,16 +7,19 @@ The template is Jinja, which the operator already knows and Flask already ships, run in the immutable sandbox so a template can reach the place's values and nothing behind them. It is compiled once at startup - a syntax error fails the boot, not every popup - and rendered -per pin with the place's fields, already translated, as its context. +per pin with the place's fields, already translated, as its context. A translated value is +the wrong thing to compare against - ``is_free`` reads ``tak`` in Polish - so the stored +values are there too, untranslated, as ``raw``. """ import logging import re -from collections.abc import Mapping +from collections.abc import Callable, Mapping +from dataclasses import dataclass from typing import Any from flask_babel import gettext -from jinja2 import Template +from jinja2 import Template, meta from jinja2.sandbox import ImmutableSandboxedEnvironment logger = logging.getLogger(__name__) @@ -39,7 +42,15 @@ def _finalize(value: object) -> object: _WHITESPACE = re.compile(r"\s+") -def compile_alt_template(source: str | None) -> Template: +@dataclass(frozen=True) +class AltTemplate: + """A compiled alt template, and the names it reads, so only those need translating.""" + + template: Template + names: frozenset[str] + + +def compile_alt_template(source: str | None) -> AltTemplate: """Compile the operator's alt template, or the default when there is none. Args: @@ -51,10 +62,18 @@ def compile_alt_template(source: str | None) -> Template: Raises: jinja2.TemplateSyntaxError: If the template does not parse. """ - return _environment.from_string(source or DEFAULT_ALT_TEMPLATE) + source = source or DEFAULT_ALT_TEMPLATE + names = meta.find_undeclared_variables(_environment.parse(source)) + return AltTemplate(_environment.from_string(source), frozenset(names)) + + +def _untranslated(value: Any) -> Any: + return value -def render_alt(template: Template, context: Mapping[str, Any]) -> str: +def render_alt( + alt: AltTemplate, place: Mapping[str, Any], translate: Callable[[Any], Any] = _untranslated +) -> str: """Render the alt text for one place. A template that parsed can still fail on a particular place - the sandbox refusing an @@ -63,15 +82,20 @@ def render_alt(template: Template, context: Mapping[str, Any]) -> str: name. Args: - template: From :func:`compile_alt_template`. - context: The place's fields, already translated. + alt: From :func:`compile_alt_template`. + place: The place's fields, as stored. + translate: Applied to each field the template reads; ``raw`` is left as stored. Returns: The alt text, with whitespace runs collapsed. """ + # A field that is itself called ``raw`` keeps its name; the stored values are then out + # of the template's reach, which beats renaming a field the operator chose. + context = {"raw": place} + context.update({name: translate(place[name]) for name in alt.names if name in place}) try: - rendered = template.render(context) + rendered = alt.template.render(context) except Exception: # whatever the template raised, the popup still opens logger.warning("IMAGE_ALT_TEMPLATE failed for a location; using its name.", exc_info=True) - rendered = str(context.get("name", "")) + rendered = str(place.get("name", "")) return _WHITESPACE.sub(" ", rendered).strip() diff --git a/goodmap/api/core_api.py b/goodmap/api/core_api.py index 56c0a073..709de5ed 100644 --- a/goodmap/api/core_api.py +++ b/goodmap/api/core_api.py @@ -9,7 +9,6 @@ import pysupercluster from flask import Blueprint, current_app, jsonify, make_response, request from flask_babel import gettext -from jinja2 import Template from platzky import FeatureFlagSet from platzky.attachment import create_attachment from platzky.config import AttachmentConfig, LanguagesMapping @@ -18,6 +17,7 @@ from spectree.models import Tag from werkzeug.exceptions import HTTPException +from goodmap.alt_template import AltTemplate from goodmap.api.api_models import ( CategoriesFullResponse, ClusteredQueryParams, @@ -206,7 +206,7 @@ def core_pages( feature_flags: FeatureFlagSet, shortcodes: dict[str, Shortcode], pin_marker_fields: PinMarkerFields, - alt_template: Template | None = None, + alt_template: AltTemplate | None = None, ) -> Blueprint: # Routes with translated responses (pin fields, schema, categories) are query_locale # routes: they follow the calling page's language, sent as ``?lang=``, since /api is diff --git a/goodmap/field_types.py b/goodmap/field_types.py index b4e89cb2..91fb10c9 100644 --- a/goodmap/field_types.py +++ b/goodmap/field_types.py @@ -11,10 +11,10 @@ safe only because this catalogue is closed: an entry may name a type in here and nothing else, and so can never point itself at a plugin's renderer. -The catalogue is goodmap's own types plus an allowlist of platzky's built-ins - ``image``, -so a place can carry photos. An allowlist rather than the whole set, because the entries -naming these types are data nobody vouched for, and platzky's ``html`` would hand them raw -markup in the popup. +The catalogue is goodmap's own types plus one of platzky's built-ins - ``image``, so a +place can carry photos, restricted to ``https``. One rather than the whole set, because the +entries naming these types are data nobody vouched for, and platzky's ``html`` would hand +them raw markup in the popup. A field may hold several values of its type under ``items`` - ``{"type": "image", "items": [{"url": …}, …]}`` - each rendered on its own; see @@ -26,8 +26,9 @@ from markupsafe import Markup, escape from platzky.shortcodes import Shortcode, ShortcodeAttr, ShortcodeAttrs, UrlNotPermitted -from platzky.shortcodes.builtins import get_builtin_shortcodes +from platzky.shortcodes.image import ImageShortcode from platzky.shortcodes.link import LinkShortcode +from platzky.shortcodes.urls import UrlPolicy #: Schemes that navigate the browser somewhere, and so are worth a new tab. _NEW_TAB_SCHEMES = frozenset({"http", "https"}) @@ -101,14 +102,43 @@ class CTAFieldShortcode(HyperlinkFieldShortcode): description = "A marker field holding a URL, shown as a call-to-action button." -#: platzky built-ins a marker field may name as its ``type``. An allowlist, not the whole -#: set: ``html`` would let an entry nobody vouched for emit raw markup into the popup. -_PLATZKY_FIELD_TYPES = ("image",) +#: Stricter than platzky's image policy, which also takes plain ``http``. +_MARKER_IMAGE_URL_POLICY = UrlPolicy(frozenset({"https"})) -_platzky_shortcodes = get_builtin_shortcodes() -#: Field ``type`` -> the shortcode rendering it, keyed by the name written in the data. +class ImageFieldShortcode(ImageShortcode): + """platzky's ``[image]``, held to ``https`` or a path on the site itself. + + A marker image comes from data nobody vouched for and is fetched the moment its popup + opens. Over plain ``http`` that fetch is readable and alterable on the way, and an https + deployment would show a mixed-content warning for it. + """ + + def render(self, attrs: ShortcodeAttrs, content: str, children: Sequence[Markup]) -> str: + """Refuse a URL the marker policy does not permit, then render as ``[image]``. + + Args: + attrs: The item's stored keys, ``url`` among them. + content: Unused - image is a void element. + children: Unused - image is a void element. + + Returns: + An ```` tag. + + Raises: + UrlNotPermitted: If the URL is not ``https`` or a path on the site. + """ + _MARKER_IMAGE_URL_POLICY.check(attrs.url) + return super().render(attrs, content, children) + + +#: Field ``type`` -> the shortcode rendering it, keyed by the name written in the data. Of +#: platzky's built-ins only ``image`` is here: ``html`` would let an entry nobody vouched +#: for emit raw markup into the popup. BUILTIN_FIELD_TYPES: dict[str, Shortcode] = { - **{name: _platzky_shortcodes[name] for name in _PLATZKY_FIELD_TYPES}, - **{s.name: s for s in (HyperlinkFieldShortcode(), CTAFieldShortcode())}, + s.name: s for s in (ImageFieldShortcode(), HyperlinkFieldShortcode(), CTAFieldShortcode()) } + +#: Field ``type`` -> what goes between its ``items`` in the field's ``html``. Images and CTAs +#: are laid out by the popup's CSS; links share a line in the details, so need a separator. +ITEM_SEPARATORS = {"hyperlink": ", "} diff --git a/goodmap/formatter.py b/goodmap/formatter.py index ec7da1d6..8328b8d8 100644 --- a/goodmap/formatter.py +++ b/goodmap/formatter.py @@ -1,23 +1,25 @@ """Formatters for translating and preparing location data for display.""" import logging -from functools import cache from typing import Any from flask_babel import gettext, lazy_gettext -from goodmap.alt_template import render_alt -from goodmap.field_types import BUILTIN_FIELD_TYPES +from goodmap.alt_template import compile_alt_template, render_alt +from goodmap.field_types import BUILTIN_FIELD_TYPES, ITEM_SEPARATORS logger = logging.getLogger(__name__) +#: What a caller that passes no ``IMAGE_ALT_TEMPLATE`` gets: the place's name, as configured. +_DEFAULT_ALT_TEMPLATE = compile_alt_template(None) + def safe_gettext(text): """Translate ``text``, mapping over a list; anything that is not text is left alone. A dict, a number or a position has nothing for ``gettext`` to look up, so it comes back as it is - which is what lets one helper translate popup values and alt template - context alike. + context alike. Nor does an empty string: ``gettext("")`` is the catalogue's header. Args: text: A str, a list, or any other field value. @@ -26,9 +28,9 @@ def safe_gettext(text): The translation, in the same shape as the input. """ if isinstance(text, str): - return gettext(text) + return gettext(text) if text else text if isinstance(text, list): - return [safe_gettext(item) if isinstance(item, str) else item for item in text] + return [safe_gettext(item) for item in text] return text @@ -87,8 +89,9 @@ def _rendered_builtin(shortcode, value, defaults): * ``items``: a field holding several values lists them there, each rendered on its own and returned with its own ``html`` - what a gallery plugin would lay out - while the - field's ``html`` joins them for the popup. An item the shortcode refuses renders to - nothing and is dropped from both. + field's ``html`` joins them for the popup, with the type's + :data:`~goodmap.field_types.ITEM_SEPARATORS` entry between. An item the shortcode + refuses renders to nothing and is dropped from both, as is one that is not an object. * defaults derived from the place, such as an image's ``alt``. An entry's own value wins; a ``null`` counts as absent, so imported data with ``"alt": null`` is still described rather than marked decorative. @@ -109,9 +112,16 @@ def rendered(entry): if not isinstance(value.get("items"), list): return rendered(value) - items = [rendered(item) for item in value["items"] if isinstance(item, dict)] + entries = value["items"] + if not all(isinstance(item, dict) for item in entries): + logger.warning( + "Dropping %s items that are not objects; write each as e.g. {%r: ...}.", + shortcode.name, + next(iter(shortcode.attributes)).name, + ) + items = [rendered(item) for item in entries if isinstance(item, dict)] items = [{k: v for k, v in item.items() if k != "type"} for item in items if item["html"]] - html = "".join(item["html"] for item in items) + html = ITEM_SEPARATORS.get(shortcode.name, "").join(item["html"] for item in items) return {**value, "items": items, "type": shortcode.name, "html": html} @@ -149,23 +159,23 @@ def prepare_pin( by name; anything else may still name a built-in ``type`` in its own data (see :mod:`goodmap.field_types`). Either way one shortcode renders it. alt_template: The compiled ``IMAGE_ALT_TEMPLATE`` (see :mod:`goodmap.alt_template`), - describing the place to any image that does not describe itself. + describing the place to any image that does not describe itself. Omitted, the + place's name does, as when the key is not configured. Returns: Title, subtitle, position, metadata, and ``data`` as ``[label, value]`` pairs. """ plugins = shortcodes or {} - - @cache - def describe(template): - # Rendered once per pin, and only once an image asks for it. - return render_alt(template, {field: safe_gettext(v) for field, v in place.items()}) + alt = None def defaults(shortcode): - if alt_template is None: + # Rendered once per pin, and only once an image asks for it. + nonlocal alt + if "alt" not in {attribute.name for attribute in shortcode.attributes}: return {} - declared = {attribute.name for attribute in shortcode.attributes} - return {"alt": describe(alt_template)} if "alt" in declared else {} + if alt is None: + alt = render_alt(alt_template or _DEFAULT_ALT_TEMPLATE, place, safe_gettext) + return {"alt": alt} data = [] for field in visible_fields: diff --git a/tests/unit_tests/test_alt_template.py b/tests/unit_tests/test_alt_template.py index 8eda7bca..bb05874b 100644 --- a/tests/unit_tests/test_alt_template.py +++ b/tests/unit_tests/test_alt_template.py @@ -38,7 +38,7 @@ def translate(text: str) -> str: return f"{text}-pl" template = compile_alt_template("{{ _('photo of') }} {{ name }}") - monkeypatch.setitem(template.environment.globals, "_", translate) + monkeypatch.setitem(template.template.environment.globals, "_", translate) assert render_alt(template, place) == "photo of-pl Grunwaldzki" diff --git a/tests/unit_tests/test_formatter.py b/tests/unit_tests/test_formatter.py index 77455d13..dbe02234 100644 --- a/tests/unit_tests/test_formatter.py +++ b/tests/unit_tests/test_formatter.py @@ -1,3 +1,4 @@ +import logging from collections.abc import Sequence import pytest @@ -242,8 +243,8 @@ def test_image_items_are_each_rendered_and_joined(): value = prepare_pin(place, ["images"], [])["data"][0][1] assert value["type"] == "image" assert [item["html"] for item in value["items"]] == [ - '', - '', + 'LASSO', + 'LASSO', ] assert value["html"] == "".join(item["html"] for item in value["items"]) @@ -251,7 +252,7 @@ def test_image_items_are_each_rendered_and_joined(): def test_image_passes_width_and_height_through(): place = _images({"url": "https://example.com/1.jpg", "width": 400, "height": 300}) html = prepare_pin(place, ["images"], [])["data"][0][1]["html"] - assert html == '' + assert html == 'LASSO' @pytest.mark.parametrize( @@ -259,6 +260,7 @@ def test_image_passes_width_and_height_through(): [ {"url": "javascript:alert(1)"}, {"url": "data:image/png;base64,AAAA"}, + {"url": "http://example.com/1.jpg"}, {"alt": "no url"}, {"url": "https://example.com/1.jpg", "width": "wide"}, ], @@ -267,7 +269,32 @@ def test_refused_image_item_is_dropped(item): place = _images(item, {"url": "https://example.com/ok.jpg"}) value = prepare_pin(place, ["images"], [])["data"][0][1] assert [i["url"] for i in value["items"]] == ["https://example.com/ok.jpg"] - assert value["html"] == '' + assert value["html"] == 'LASSO' + + +def test_image_on_a_site_path_is_accepted(): + html = prepare_pin(_images({"url": "/static/1.jpg"}), ["images"], [])["data"][0][1]["html"] + assert html == 'LASSO' + + +def test_image_item_that_is_not_an_object_is_dropped_with_a_warning(caplog): + place = _images("https://example.com/bare.jpg", {"url": "https://example.com/ok.jpg"}) + with caplog.at_level(logging.WARNING): + value = prepare_pin(place, ["images"], [])["data"][0][1] + assert [i["url"] for i in value["items"]] == ["https://example.com/ok.jpg"] + assert "{'url': ...}" in caplog.text + + +def test_hyperlink_items_are_separated(): + place = { + **test_place, + "links": { + "type": "hyperlink", + "items": [{"value": "https://a.org"}, {"value": "https://b.org"}], + }, + } + html = prepare_pin(place, ["links"], [])["data"][0][1]["html"] + assert ", str: assert items[0]["alt"] == "container-pl shoes-pl" +def test_alt_template_compares_against_raw_values(monkeypatch): + """A translated value differs per language; ``raw`` does not.""" + + def gettext(text: str) -> str: + return {"true": "tak"}.get(text, text) + + monkeypatch.setattr("goodmap.formatter.gettext", gettext) + template = compile_alt_template( + "{{ 'free' if raw.is_free == 'true' else 'paid' }} {{ is_free }}" + ) + place = {**_images({"url": "https://example.com/1.jpg"}), "is_free": "true"} + items = prepare_pin(place, ["images"], [], alt_template=template)["data"][0][1]["items"] + assert items[0]["alt"] == "free tak" + + +def test_alt_template_empty_field_prints_nothing(monkeypatch): + """``gettext("")`` is the catalogue's header, which a screen reader would read out.""" + + def gettext(text: str) -> str: + return text or "HEADER" + + monkeypatch.setattr("goodmap.formatter.gettext", gettext) + template = compile_alt_template("{{ name }} {{ remark }}") + place = {**_images({"url": "https://example.com/1.jpg"}), "remark": ""} + items = prepare_pin(place, ["images"], [], alt_template=template)["data"][0][1]["items"] + assert items[0]["alt"] == "LASSO" + + +def test_alt_template_translates_only_the_fields_it_reads(monkeypatch): + translated: list[object] = [] + + def gettext(text: str) -> str: + translated.append(text) + return text + + monkeypatch.setattr("goodmap.formatter.gettext", gettext) + place = _images({"url": "https://example.com/1.jpg"}) + prepare_pin(place, [], []) # nothing visible: only the alt could translate anything + translated.clear() + prepare_pin(place, ["images"], [], alt_template=compile_alt_template("{{ name }}")) + assert "random_string" not in translated + assert "LASSO" in translated + + def test_image_alt_null_counts_as_absent(): """Imported data writing ``"alt": null`` means "not given", not "decorative".""" place = _images({"url": "https://example.com/1.jpg", "alt": None}) From 643964ec499e0ee1d147bdc0fe8a40858a027082 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Krzysztof=20Ko=C5=82odzi=C5=84ski?= Date: Wed, 21 Oct 2026 16:39:01 +0200 Subject: [PATCH 08/34] simplify --- docs/http-api.rst | 13 +++++----- docs/plugins.rst | 25 +++++++++--------- goodmap/field_types.py | 41 ++++-------------------------- goodmap/formatter.py | 16 +++++++----- poetry.lock | 8 +++--- pyproject.toml | 2 +- tests/unit_tests/test_formatter.py | 20 +++++++++++---- 7 files changed, 53 insertions(+), 72 deletions(-) diff --git a/docs/http-api.rst b/docs/http-api.rst index 4c49df8d..e5e9f38d 100644 --- a/docs/http-api.rst +++ b/docs/http-api.rst @@ -195,9 +195,10 @@ or one a plugin's shortcode is bound to — comes back as an object rather than "html": "Example" }] -A field naming a built-in type may hold several values under ``items``. Each item comes back -with its own ``html``, and the field's ``html`` joins them. Items that render to nothing are -dropped, and a built-in field left with nothing to show is left out of ``data``. Stored as +A field naming a built-in type may hold several values under ``items``. The field's ``html`` +renders them all; ``items`` lists them as data, without ``html`` of their own. Items that +render to nothing are dropped from both, and a built-in field left with nothing to show is +left out of ``data``. Stored as ``{"type": "image", "items": [{"url": ".../front.jpg"}, {"url": ".../deck.jpg", "alt": "The deck at night"}]}``, an image field comes back as: @@ -206,10 +207,8 @@ dropped, and a built-in field left with nothing to show is left out of ``data``. ["images", { "type": "image", "items": [ - {"url": "https://example.com/front.jpg", "alt": "Zwierzyniecka", - "html": "\"Zwierzyniecka\""}, - {"url": "https://example.com/deck.jpg", "alt": "The deck at night", - "html": "\"The"} + {"url": "https://example.com/front.jpg", "alt": "Zwierzyniecka"}, + {"url": "https://example.com/deck.jpg", "alt": "The deck at night"} ], "html": "\"Zwierzyniecka\"\"The" }] diff --git a/docs/plugins.rst b/docs/plugins.rst index 950b60c2..834f1ca8 100644 --- a/docs/plugins.rst +++ b/docs/plugins.rst @@ -208,24 +208,25 @@ That lookup is safe only because the catalogue is closed: an entry may name a ty and nothing else, so it can never point its own field at a plugin's renderer. ``prepare_pin`` consults it only where no plugin shortcode claimed the field by name. -Alongside its own, goodmap offers **one** of platzky's built-in shortcodes — ``image``, as -``ImageFieldShortcode`` — so a point can carry photos. Not the whole set, because the entries +Alongside its own, goodmap offers **one** of platzky's built-in shortcodes — ``image`` — so +a point can carry photos. Not the whole set, because the entries naming these types are data nobody vouched for: a suggested point or an imported dataset naming platzky's ``html`` would put raw markup into the popup. Offering another, ``figure`` -say, means adding it to ``BUILTIN_FIELD_TYPES`` under the same URL policy as ``image``. +say, means adding it to ``BUILTIN_FIELD_TYPES``. A field naming one of these types may hold several values under ``items``. Each is rendered -on its own and returned with its own ``html`` — what a gallery field plugin on ``image`` would -lay out — while the field's ``html`` joins them for the popup (``hyperlink`` items with -``", "`` between, the rest with nothing, the popup's CSS spacing them). An item the shortcode -refuses is dropped from both, as is one that is not an object — a bare URL string, say, -which logs a warning — and a field left with nothing to show is left out of the popup -altogether. ``items`` is for goodmap's own types only: a field a plugin's shortcode is bound +on its own and the renderings joined into the field's ``html`` (``hyperlink`` items with +``", "`` between, the rest with nothing, the popup's CSS spacing them); the items go back as +plain data, without ``html`` of their own. An item the shortcode refuses is dropped, as is +one that is not an object — a bare URL string, say, which logs a warning — and a field left +with nothing to show is left out of the popup altogether. A gallery wanting a layout of its +own does not reach into ``image``: it brings its own type, either a shortcode bound to the +field by name or a field ``type`` of its own that the data names instead. ``items`` is for goodmap's own types only: a field a plugin's shortcode is bound to keeps exactly the rendering that shortcode gives it. -An image URL must be ``https`` or a path on the site itself (``/static/…``) — stricter than -platzky's image policy, which also takes plain ``http``, since a marker image is fetched by -every visitor who opens the point; ``http:``, ``javascript:`` and ``data:`` are refused: +An image URL must be ``https`` or a path on the site itself (``/static/…``) — platzky's +image policy, since an image is fetched by every visitor who opens the point; +``http:``, ``javascript:`` and ``data:`` are refused: .. code-block:: json diff --git a/goodmap/field_types.py b/goodmap/field_types.py index 91fb10c9..52e73d31 100644 --- a/goodmap/field_types.py +++ b/goodmap/field_types.py @@ -12,9 +12,9 @@ else, and so can never point itself at a plugin's renderer. The catalogue is goodmap's own types plus one of platzky's built-ins - ``image``, so a -place can carry photos, restricted to ``https``. One rather than the whole set, because the -entries naming these types are data nobody vouched for, and platzky's ``html`` would hand -them raw markup in the popup. +place can carry photos; platzky holds its URLs to ``https`` or a path on the site. One +rather than the whole set, because the entries naming these types are data nobody vouched +for, and platzky's ``html`` would hand them raw markup in the popup. A field may hold several values of its type under ``items`` - ``{"type": "image", "items": [{"url": …}, …]}`` - each rendered on its own; see @@ -26,9 +26,8 @@ from markupsafe import Markup, escape from platzky.shortcodes import Shortcode, ShortcodeAttr, ShortcodeAttrs, UrlNotPermitted -from platzky.shortcodes.image import ImageShortcode +from platzky.shortcodes.image import image_shortcode from platzky.shortcodes.link import LinkShortcode -from platzky.shortcodes.urls import UrlPolicy #: Schemes that navigate the browser somewhere, and so are worth a new tab. _NEW_TAB_SCHEMES = frozenset({"http", "https"}) @@ -102,41 +101,11 @@ class CTAFieldShortcode(HyperlinkFieldShortcode): description = "A marker field holding a URL, shown as a call-to-action button." -#: Stricter than platzky's image policy, which also takes plain ``http``. -_MARKER_IMAGE_URL_POLICY = UrlPolicy(frozenset({"https"})) - - -class ImageFieldShortcode(ImageShortcode): - """platzky's ``[image]``, held to ``https`` or a path on the site itself. - - A marker image comes from data nobody vouched for and is fetched the moment its popup - opens. Over plain ``http`` that fetch is readable and alterable on the way, and an https - deployment would show a mixed-content warning for it. - """ - - def render(self, attrs: ShortcodeAttrs, content: str, children: Sequence[Markup]) -> str: - """Refuse a URL the marker policy does not permit, then render as ``[image]``. - - Args: - attrs: The item's stored keys, ``url`` among them. - content: Unused - image is a void element. - children: Unused - image is a void element. - - Returns: - An ```` tag. - - Raises: - UrlNotPermitted: If the URL is not ``https`` or a path on the site. - """ - _MARKER_IMAGE_URL_POLICY.check(attrs.url) - return super().render(attrs, content, children) - - #: Field ``type`` -> the shortcode rendering it, keyed by the name written in the data. Of #: platzky's built-ins only ``image`` is here: ``html`` would let an entry nobody vouched #: for emit raw markup into the popup. BUILTIN_FIELD_TYPES: dict[str, Shortcode] = { - s.name: s for s in (ImageFieldShortcode(), HyperlinkFieldShortcode(), CTAFieldShortcode()) + s.name: s for s in (image_shortcode, HyperlinkFieldShortcode(), CTAFieldShortcode()) } #: Field ``type`` -> what goes between its ``items`` in the field's ``html``. Images and CTAs diff --git a/goodmap/formatter.py b/goodmap/formatter.py index 8328b8d8..4873d435 100644 --- a/goodmap/formatter.py +++ b/goodmap/formatter.py @@ -87,11 +87,12 @@ def _rendered_builtin(shortcode, value, defaults): Two things only goodmap's own types get, because goodmap knows what their rendering means - a plugin's field keeps exactly the rendering its shortcode gives it: - * ``items``: a field holding several values lists them there, each rendered on its own - and returned with its own ``html`` - what a gallery plugin would lay out - while the - field's ``html`` joins them for the popup, with the type's - :data:`~goodmap.field_types.ITEM_SEPARATORS` entry between. An item the shortcode - refuses renders to nothing and is dropped from both, as is one that is not an object. + * ``items``: a field holding several values lists them there. Each is rendered on its + own and the renderings joined into the field's ``html``, with the type's + :data:`~goodmap.field_types.ITEM_SEPARATORS` entry between; the items themselves go + back as data, without ``html``. An item the shortcode refuses renders to nothing and + is dropped, as is one that is not an object. A gallery wanting its own layout binds + its own shortcode to the field, or the field names the gallery's type instead. * defaults derived from the place, such as an image's ``alt``. An entry's own value wins; a ``null`` counts as absent, so imported data with ``"alt": null`` is still described rather than marked decorative. @@ -120,9 +121,10 @@ def rendered(entry): next(iter(shortcode.attributes)).name, ) items = [rendered(item) for item in entries if isinstance(item, dict)] - items = [{k: v for k, v in item.items() if k != "type"} for item in items if item["html"]] + items = [item for item in items if item["html"]] html = ITEM_SEPARATORS.get(shortcode.name, "").join(item["html"] for item in items) - return {**value, "items": items, "type": shortcode.name, "html": html} + data = [{k: v for k, v in item.items() if k not in ("type", "html")} for item in items] + return {**value, "items": data, "type": shortcode.name, "html": html} def _without_html(value): diff --git a/poetry.lock b/poetry.lock index e53493c4..ba031305 100644 --- a/poetry.lock +++ b/poetry.lock @@ -2465,14 +2465,14 @@ files = [ [[package]] name = "platzky" -version = "2.0.0a18" +version = "2.0.0a19" description = "Not only blog engine" optional = false python-versions = "<4.0,>=3.10" groups = ["main"] files = [ - {file = "platzky-2.0.0a18-py3-none-any.whl", hash = "sha256:8854970c968db75451043a6c804caf9ca2e543e102aaf228a4905a6eb567b7e1"}, - {file = "platzky-2.0.0a18.tar.gz", hash = "sha256:0be1ed1cb7172d5ac3f8883004c25151f071e8de9bc47a7968913902c1f6920d"}, + {file = "platzky-2.0.0a19-py3-none-any.whl", hash = "sha256:6bd5c1f5798b1567c27b126c390fb10ea041e11a0deeb51731b9684dd41aeb8d"}, + {file = "platzky-2.0.0a19.tar.gz", hash = "sha256:bbdb7f69b9f64295f17cb7f96c4cea8aaaac7f8cc6110c77e589ee7405ceb8ff"}, ] [package.dependencies] @@ -4538,4 +4538,4 @@ docs = ["myst-parser", "sphinx", "sphinx-rtd-theme"] [metadata] lock-version = "2.1" python-versions = "^3.10" -content-hash = "e47221bf36a7d54d77c021080738e18d396f0aa11021549ef859f56e15ef5559" +content-hash = "5ee3d953b7a7cbbfa74de9fd8ea12cb32c956111d061fa26fdf532310c46b7af" diff --git a/pyproject.toml b/pyproject.toml index fedc1631..04e82b9c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -22,7 +22,7 @@ Flask-WTF = "^1.2.1" gql = "^3.4.0" aiohttp = "^3.8.4" pydantic = "^2.12.0" -platzky = "2.0.0a18" +platzky = "2.0.0a19" deprecation = "^2.1.0" numpy = "^2.2.0" # Using fork because official PyPI version (0.7.7) has outdated numpy setup hack diff --git a/tests/unit_tests/test_formatter.py b/tests/unit_tests/test_formatter.py index dbe02234..ab9ad989 100644 --- a/tests/unit_tests/test_formatter.py +++ b/tests/unit_tests/test_formatter.py @@ -238,15 +238,25 @@ def _images(*items): def test_image_items_are_each_rendered_and_joined(): - """Each item keeps its own ``html`` for a gallery plugin; the field's joins them.""" + """The field's ``html`` joins the items' renderings; the items stay plain data.""" place = _images({"url": "https://example.com/1.jpg"}, {"url": "https://example.com/2.jpg"}) value = prepare_pin(place, ["images"], [])["data"][0][1] assert value["type"] == "image" - assert [item["html"] for item in value["items"]] == [ - 'LASSO', - 'LASSO', + assert value["html"] == ( + 'LASSO' + 'LASSO' + ) + assert value["items"] == [ + {"url": "https://example.com/1.jpg", "alt": "LASSO"}, + {"url": "https://example.com/2.jpg", "alt": "LASSO"}, ] - assert value["html"] == "".join(item["html"] for item in value["items"]) + + +def test_image_items_html_from_the_data_is_not_passed_on(): + place = _images({"url": "https://example.com/1.jpg", "html": ""}) + value = prepare_pin(place, ["images"], [])["data"][0][1] + assert "html" not in value["items"][0] + assert ""}) - value = prepare_pin(place, ["images"], [])["data"][0][1] + value = PinFormatter().prepare_pin(place, ["images"], [])["data"][0][1] assert "html" not in value["items"][0] assert ""}]}, } - value = prepare_pin(place, ["evil"], [])["data"][0][1] + value = PinFormatter().prepare_pin(place, ["evil"], [])["data"][0][1] assert value == {"type": "html", "items": [{}]} @@ -347,7 +363,9 @@ def translate(text: str) -> str: monkeypatch.setattr("goodmap.translation.gettext", translate) template = AltTemplate("{{ _(type_of_place) }} {{ _(types) | join(',') }} {{ name }}") place = _images({"url": "https://example.com/1.jpg"}) - items = prepare_pin(place, ["images"], [], alt_template=template)["data"][0][1]["items"] + items = PinFormatter(alt_template=template).prepare_pin(place, ["images"], [])["data"][0][1][ + "items" + ] assert items[0]["alt"] == "container-pl shoes-pl LASSO" @@ -360,7 +378,9 @@ def gettext(text: str) -> str: monkeypatch.setattr("goodmap.translation.gettext", gettext) template = AltTemplate("{{ 'free' if is_free == 'true' else 'paid' }} {{ _(is_free) }}") place = {**_images({"url": "https://example.com/1.jpg"}), "is_free": "true"} - items = prepare_pin(place, ["images"], [], alt_template=template)["data"][0][1]["items"] + items = PinFormatter(alt_template=template).prepare_pin(place, ["images"], [])["data"][0][1][ + "items" + ] assert items[0]["alt"] == "free tak" @@ -373,7 +393,9 @@ def gettext(text: str) -> str: monkeypatch.setattr("goodmap.translation.gettext", gettext) template = AltTemplate("{{ name }} {{ _(remark) }}") place = {**_images({"url": "https://example.com/1.jpg"}), "remark": ""} - items = prepare_pin(place, ["images"], [], alt_template=template)["data"][0][1]["items"] + items = PinFormatter(alt_template=template).prepare_pin(place, ["images"], [])["data"][0][1][ + "items" + ] assert items[0]["alt"] == "LASSO" @@ -386,9 +408,11 @@ def gettext(text: str) -> str: monkeypatch.setattr("goodmap.translation.gettext", gettext) place = _images({"url": "https://example.com/1.jpg"}) - prepare_pin(place, [], []) # nothing visible: only the alt could translate anything + PinFormatter().prepare_pin( + place, [], [] + ) # nothing visible: only the alt could translate anything translated.clear() - prepare_pin(place, ["images"], [], alt_template=AltTemplate("{{ _(name) }}")) + PinFormatter(alt_template=AltTemplate("{{ _(name) }}")).prepare_pin(place, ["images"], []) assert "random_string" not in translated assert "LASSO" in translated @@ -397,7 +421,9 @@ def test_image_alt_null_counts_as_absent(): """Imported data writing ``"alt": null`` means "not given", not "decorative".""" place = _images({"url": "https://example.com/1.jpg", "alt": None}) template = AltTemplate(DEFAULT_ALT_TEMPLATE) - items = prepare_pin(place, ["images"], [], alt_template=template)["data"][0][1]["items"] + items = PinFormatter(alt_template=template).prepare_pin(place, ["images"], [])["data"][0][1][ + "items" + ] assert items[0]["alt"] == "LASSO" @@ -410,16 +436,14 @@ def render(*args: object) -> str: monkeypatch.setattr(AltTemplate, "render", render) place = {**test_place, "website": {"type": "hyperlink", "value": "https://example.com"}} - prepare_pin( - place, - ["website", "plain_text"], - [], - alt_template=AltTemplate(DEFAULT_ALT_TEMPLATE), + PinFormatter(alt_template=AltTemplate(DEFAULT_ALT_TEMPLATE)).prepare_pin( + place, ["website", "plain_text"], [] ) assert calls == [] -def test_alt_template_is_rendered_once_per_pin(monkeypatch): +def test_alt_template_is_rendered_once_per_image_field(monkeypatch): + """Not once per image: a field's items share the place's description.""" calls: list[tuple[object, ...]] = [] def render(*args: object) -> str: @@ -431,8 +455,10 @@ def render(*args: object) -> str: **_images({"url": "https://example.com/1.jpg"}, {"url": "https://example.com/2.jpg"}), "more": {"type": "image", "items": [{"url": "https://example.com/3.jpg"}]}, } - prepare_pin(place, ["images", "more"], [], alt_template=AltTemplate(DEFAULT_ALT_TEMPLATE)) - assert len(calls) == 1 + PinFormatter(alt_template=AltTemplate(DEFAULT_ALT_TEMPLATE)).prepare_pin( + place, ["images", "more"], [] + ) + assert len(calls) == 2 # "images" with two items, and "more" class _AltShortcode(_FakeShortcode): @@ -445,12 +471,8 @@ def render(self, attrs: ShortcodeAttrs, content: str, children: Sequence[Markup] def test_plugin_field_keeps_its_own_rendering(): """``items`` and place-derived defaults are for goodmap's own types only.""" place = {**test_place, "promo_code": {"code": "X", "items": [{"code": "Y"}]}} - value = prepare_pin( - place, - ["promo_code"], - [], - shortcodes={"promo_code": _AltShortcode()}, - alt_template=AltTemplate(DEFAULT_ALT_TEMPLATE), - )["data"][0][1] + value = PinFormatter( + shortcodes={"promo_code": _AltShortcode()}, alt_template=AltTemplate(DEFAULT_ALT_TEMPLATE) + ).prepare_pin(place, ["promo_code"], [])["data"][0][1] assert value["html"] == ":X" assert value["items"] == [{"code": "Y"}] diff --git a/tests/unit_tests/test_goodmap.py b/tests/unit_tests/test_goodmap.py index aef4c828..88994f6c 100644 --- a/tests/unit_tests/test_goodmap.py +++ b/tests/unit_tests/test_goodmap.py @@ -883,11 +883,11 @@ class _PluginB(ContentTransformerPluginBase): ) captured: dict[str, Any] = {} - orig_core_pages = goodmap.core_pages + orig_pin_formatter = goodmap.PinFormatter - def _spy_core_pages(*args: Any, **kwargs: Any) -> Any: - captured["shortcodes"] = kwargs.get("shortcodes", {}) - return orig_core_pages(*args, **kwargs) + def _spy_pin_formatter(shortcodes: Any, alt_template: Any) -> Any: + captured["shortcodes"] = shortcodes + return orig_pin_formatter(shortcodes, alt_template) field_ep = mock.MagicMock() field_ep.name = "field_plugin" @@ -897,7 +897,7 @@ def _spy_core_pages(*args: Any, **kwargs: Any) -> Any: post_ep.name = "post_plugin" post_ep.load.return_value = _PluginB - with mock.patch("goodmap.goodmap.core_pages", side_effect=_spy_core_pages): + with mock.patch("goodmap.goodmap.PinFormatter", side_effect=_spy_pin_formatter): with _patch_entry_points({"platzky.plugins": [field_ep, post_ep]}): goodmap.create_app_from_config(config) From 038aab4272da1f3428bb136086b393c183f752d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Krzysztof=20Ko=C5=82odzi=C5=84ski?= Date: Thu, 22 Oct 2026 13:48:40 +0200 Subject: [PATCH 23/34] faster formatter --- docs/data-source.rst | 4 +- docs/deployment.rst | 5 +- goodmap/api/core_api.py | 5 +- goodmap/formatter.py | 21 ++++-- goodmap/goodmap.py | 9 ++- tests/unit_tests/test_formatter.py | 113 +++++++++++++++-------------- tests/unit_tests/test_goodmap.py | 10 ++- 7 files changed, 92 insertions(+), 75 deletions(-) diff --git a/docs/data-source.rst b/docs/data-source.rst index 378f6ee6..2a19304b 100644 --- a/docs/data-source.rst +++ b/docs/data-source.rst @@ -463,8 +463,8 @@ JSON file The whole structure above in one file on disk. Read per request, so edits to ``data`` show up on the next refresh — though the schema keys (``categories``, -``location_obligatory_fields``, ``visible_data``) are read once at startup and need a -restart. Writes — new suggestions and reports — are written back atomically via a +``location_obligatory_fields``, ``visible_data``, ``meta_data``) are read once at startup +and need a restart. Writes — new suggestions and reports — are written back atomically via a temporary file and a rename, so a crash mid-write cannot truncate your data. Best for: development, and small-to-medium read-mostly maps served by a single process. diff --git a/docs/deployment.rst b/docs/deployment.rst index dc474f21..420f52fb 100644 --- a/docs/deployment.rst +++ b/docs/deployment.rst @@ -119,8 +119,9 @@ incoming reports change it while the app runs. - **google_json** — the blob is your source of truth and the app never writes to it. Bucket object versioning gives you history. -Schema keys (``categories``, ``visible_data``, ``location_obligatory_fields``) are read -at startup, so changing them means restarting the app. Point data is re-read per request. +Schema keys (``categories``, ``visible_data``, ``meta_data``, +``location_obligatory_fields``) are read at startup, so changing them means restarting the +app. Point data is re-read per request. Upgrading --------- diff --git a/goodmap/api/core_api.py b/goodmap/api/core_api.py index 01081bff..cb8f57d9 100644 --- a/goodmap/api/core_api.py +++ b/goodmap/api/core_api.py @@ -426,10 +426,7 @@ def get_location(location_id): logger.info(ERROR_LOCATION_NOT_FOUND, extra={"uuid": location_id}) return api_error(ERROR_LOCATION_NOT_FOUND, 404) - visible_data = database.get_visible_data() - meta_data = database.get_meta_data() - formatted_data = pin_formatter.prepare_pin(location.model_dump(), visible_data, meta_data) - return jsonify(formatted_data) + return jsonify(pin_formatter.prepare_pin(location.model_dump())) @core_api_blueprint.route("/version", methods=["GET"]) @spec.validate(tags=[TAG_META], resp=Response(HTTP_200=VersionResponse)) diff --git a/goodmap/formatter.py b/goodmap/formatter.py index 692c9928..9d53270d 100644 --- a/goodmap/formatter.py +++ b/goodmap/formatter.py @@ -76,14 +76,17 @@ def _without_html(value): class PinFormatter: """Formats locations into the translated payload their map popups render. - Built once at startup with the settings that do not change per request; the fields to - show are passed per call, since they come from the data source. + Built once at startup with every setting it needs, the fields to show included: like + marker styles, they are read from the data source when the app starts, so changing them + takes a restart. """ - def __init__(self, shortcodes=None, alt_template=None): + def __init__(self, visible_fields, meta_fields, shortcodes=None, alt_template=None): """Hold the formatting settings. Args: + visible_fields: Field names to show in the popup, in order. + meta_fields: Field names to carry as metadata. shortcodes: Field name -> the platzky Shortcode bound to it. A plugin claims a field by name; anything else may still name a built-in ``type`` in its own data (see :mod:`goodmap.field_types`). Either way one shortcode renders it. @@ -91,27 +94,29 @@ def __init__(self, shortcodes=None, alt_template=None): describing the place to any image that does not describe itself. Omitted, the place's name does, as when the key is not configured. """ + self._visible_fields = visible_fields + self._meta_fields = meta_fields self._plugins = shortcodes or {} self._alt_template = alt_template or _DEFAULT_ALT_TEMPLATE - def prepare_pin(self, place, visible_fields, meta_data) -> dict[str, Any]: + def prepare_pin(self, place) -> dict[str, Any]: """Format one location. Args: place: The location's data. - visible_fields: Field names to show in the popup. - meta_data: Field names to carry as metadata. Returns: Title, subtitle, position, metadata, and ``data`` as ``[label, value]`` pairs. """ - entries = (self._entry(place, field) for field in visible_fields if field in place) + entries = (self._entry(place, field) for field in self._visible_fields if field in place) return { "title": place["name"], "subtitle": lazy_gettext(place["type_of_place"]), # TODO should not be obligatory "position": place["position"], "metadata": { - gettext(field): safe_gettext(place[field]) for field in meta_data if field in place + gettext(field): safe_gettext(place[field]) + for field in self._meta_fields + if field in place }, "data": [entry for entry in entries if entry is not None], } diff --git a/goodmap/goodmap.py b/goodmap/goodmap.py index af65aaae..1047c1ac 100644 --- a/goodmap/goodmap.py +++ b/goodmap/goodmap.py @@ -26,6 +26,8 @@ get_initial_view, get_location_obligatory_fields, get_marker_styles, + get_meta_data, + get_visible_data, ) from goodmap.feature_flags import EnableAdminPanel from goodmap.formatter import PinFormatter @@ -205,6 +207,11 @@ def create_app_from_config(config: GoodmapConfig) -> platzky.Engine: # Compiled here for the same reason: a template that does not parse fails the boot. alt_template = AltTemplate(config.image_alt_template) + # Which fields a popup shows, and which it carries as metadata: map configuration like + # the view above, read once rather than on every popup, so changing it takes a restart. + visible_fields = get_visible_data(app.db)(app.db) + meta_fields = get_meta_data(app.db)(app.db) + location_model = create_location_model(location_obligatory_fields, categories) app.db = extend_db_with_goodmap_queries(app.db, location_model) @@ -279,7 +286,7 @@ def handle_csrf_error(error): location_model, photo_attachment_config=photo_attachment_config, feature_flags=config.feature_flags, - pin_formatter=PinFormatter(shortcodes, alt_template), + pin_formatter=PinFormatter(visible_fields, meta_fields, shortcodes, alt_template), pin_marker_fields=pin_marker_fields, ) app.register_blueprint(cp) diff --git a/tests/unit_tests/test_formatter.py b/tests/unit_tests/test_formatter.py index 15a840aa..bdffca37 100644 --- a/tests/unit_tests/test_formatter.py +++ b/tests/unit_tests/test_formatter.py @@ -35,9 +35,9 @@ def render(self, attrs: ShortcodeAttrs, content: str, children: Sequence[Markup] def test_field_plugin_renders_the_value_as_html(): """The shortcode renders its own field, so a plugin needs no frontend code here.""" place = {**test_place, "promo_code": "SAVE20"} - result = PinFormatter(shortcodes={"promo_code": _FakeShortcode()}).prepare_pin( - place, ["promo_code"], [] - ) + result = PinFormatter( + ["promo_code"], [], shortcodes={"promo_code": _FakeShortcode()} + ).prepare_pin(place) assert result["data"] == [ ["promo_code", {"type": "promo_code", "code": "SAVE20", "html": ":SAVE20"}] ] @@ -46,9 +46,9 @@ def test_field_plugin_renders_the_value_as_html(): def test_field_plugin_carries_entry_keys_for_a_react_renderer(): """A field plugin rendering from the data gets the entry's own keys alongside.""" place = {**test_place, "promo_code": {"code": "SAVE20", "color": "red"}} - result = PinFormatter(shortcodes={"promo_code": _FakeShortcode()}).prepare_pin( - place, ["promo_code"], [] - ) + result = PinFormatter( + ["promo_code"], [], shortcodes={"promo_code": _FakeShortcode()} + ).prepare_pin(place) assert result["data"] == [ [ "promo_code", @@ -64,9 +64,9 @@ def test_field_plugin_carries_entry_keys_for_a_react_renderer(): def test_entry_cannot_redirect_its_field_at_another_renderer(): place = {**test_place, "promo_code": {"code": "X", "type": "hyperlink"}} - result = PinFormatter(shortcodes={"promo_code": _FakeShortcode()}).prepare_pin( - place, ["promo_code"], [] - ) + result = PinFormatter( + ["promo_code"], [], shortcodes={"promo_code": _FakeShortcode()} + ).prepare_pin(place) assert result["data"] == [ ["promo_code", {"type": "promo_code", "code": "X", "html": ":X"}] ] @@ -85,7 +85,7 @@ def render(self, attrs: ShortcodeAttrs, content: str, children: Sequence[Markup] def test_hyperlink_field_is_rendered_server_side(): """A built-in type named in the data is rendered here, so the frontend needs no component.""" place = {**test_place, "website": {"type": "hyperlink", "value": "https://example.com"}} - result = PinFormatter().prepare_pin(place, ["website"], []) + result = PinFormatter(["website"], []).prepare_pin(place) assert result["data"] == [ [ "website", @@ -110,14 +110,14 @@ def test_hyperlink_uses_display_value_as_the_link_text(): "displayValue": "Example", }, } - result = PinFormatter().prepare_pin(place, ["website"], []) + result = PinFormatter(["website"], []).prepare_pin(place) assert ">Example" in result["data"][0][1]["html"] def test_hyperlink_accepts_contact_schemes(): """mailto:/tel: are how a place's contact details are written, and they navigate nowhere.""" place = {**test_place, "email": {"type": "hyperlink", "value": "mailto:hi@example.com"}} - result = PinFormatter().prepare_pin(place, ["email"], []) + result = PinFormatter(["email"], []).prepare_pin(place) assert result["data"][0][1]["html"] == ( 'mailto:hi@example.com' ) @@ -133,7 +133,7 @@ def test_hyperlink_with_a_refused_url_keeps_its_text_unlinked(): "displayValue": "x", }, } - result = PinFormatter().prepare_pin(place, ["website"], []) + result = PinFormatter(["website"], []).prepare_pin(place) assert result["data"][0][1]["html"] == "<b>x</b>" @@ -143,7 +143,7 @@ def test_cta_is_rendered_as_a_link_too(): **test_place, "CTA": {"type": "CTA", "value": "https://example.com", "displayValue": "Go"}, } - result = PinFormatter().prepare_pin(place, ["CTA"], []) + result = PinFormatter(["CTA"], []).prepare_pin(place) assert result["data"][0][1]["html"] == ( 'Go' ) @@ -154,39 +154,39 @@ def test_cta_with_a_refused_url_keeps_its_text_unlinked(): **test_place, "CTA": {"type": "CTA", "value": "data:text/html,x", "displayValue": "Go"}, } - result = PinFormatter().prepare_pin(place, ["CTA"], []) + result = PinFormatter(["CTA"], []).prepare_pin(place) assert result["data"][0][1]["html"] == "Go" def test_a_plugin_bound_field_is_not_reached_by_a_builtin_type(): """The plugin owns its field outright; the data cannot redirect it at a built-in.""" place = {**test_place, "promo_code": {"code": "X", "type": "hyperlink", "value": "https://e.x"}} - result = PinFormatter(shortcodes={"promo_code": _FakeShortcode()}).prepare_pin( - place, ["promo_code"], [] - ) + result = PinFormatter( + ["promo_code"], [], shortcodes={"promo_code": _FakeShortcode()} + ).prepare_pin(place) assert result["data"][0][1]["type"] == "promo_code" assert result["data"][0][1]["html"] == ":X" def test_an_unknown_type_is_left_alone(): place = {**test_place, "thing": {"type": "not_a_field_type", "value": "x"}} - result = PinFormatter().prepare_pin(place, ["thing"], []) + result = PinFormatter(["thing"], []).prepare_pin(place) assert result["data"] == [["thing", {"type": "not_a_field_type", "value": "x"}]] def test_a_non_string_type_is_not_looked_up(): """A stored ``type`` is data, and an unhashable one must not reach the registry lookup.""" place = {**test_place, "thing": {"type": ["hyperlink"], "value": "x"}} - result = PinFormatter().prepare_pin(place, ["thing"], []) + result = PinFormatter(["thing"], []).prepare_pin(place) assert result["data"] == [["thing", {"type": ["hyperlink"], "value": "x"}]] def test_bare_value_lands_under_the_default_content_key(): """Without a declared ``content_key`` a bare value is stored under ``content``.""" place = {**test_place, "promo_code": "SAVE20"} - result = PinFormatter(shortcodes={"promo_code": _DefaultShortcode()}).prepare_pin( - place, ["promo_code"], [] - ) + result = PinFormatter( + ["promo_code"], [], shortcodes={"promo_code": _DefaultShortcode()} + ).prepare_pin(place) assert result["data"] == [ ["promo_code", {"type": "promo_code", "content": "SAVE20", "html": "SAVE20"}] ] @@ -206,7 +206,7 @@ def test_formatting_when_missing_visible_field(): ], "metadata": {}, } - assert PinFormatter().prepare_pin(test_place, visible_fields, []) == expected_data + assert PinFormatter(visible_fields, []).prepare_pin(test_place) == expected_data def test_html_in_the_data_is_dropped_rather_than_rendered_as_markup(): @@ -217,14 +217,14 @@ def test_html_in_the_data_is_dropped_rather_than_rendered_as_markup(): stripped rather than passed on to be injected. """ place = {**test_place, "evil": {"html": "", "value": "hi"}} - result = PinFormatter().prepare_pin(place, ["evil"], []) + result = PinFormatter(["evil"], []).prepare_pin(place) assert result["data"] == [["evil", {"value": "hi"}]] def test_a_rendered_field_still_gets_its_html(): """The guard above must not disturb a field something actually rendered.""" place = {**test_place, "website": {"type": "hyperlink", "value": "https://example.com"}} - assert "html" in PinFormatter().prepare_pin(place, ["website"], [])["data"][0][1] + assert "html" in PinFormatter(["website"], []).prepare_pin(place)["data"][0][1] @pytest.mark.parametrize("display_value", ["", None], ids=["empty", "null"]) @@ -239,7 +239,7 @@ def test_a_blank_display_value_falls_back_to_the_url(display_value): "displayValue": display_value, }, } - result = PinFormatter().prepare_pin(place, ["website"], []) + result = PinFormatter(["website"], []).prepare_pin(place) assert ">https://example.com" in result["data"][0][1]["html"] @@ -250,7 +250,7 @@ def _images(*items): def test_image_items_are_each_rendered_and_joined(): """The field's ``html`` joins the items' renderings; the items stay plain data.""" place = _images({"url": "https://example.com/1.jpg"}, {"url": "https://example.com/2.jpg"}) - value = PinFormatter().prepare_pin(place, ["images"], [])["data"][0][1] + value = PinFormatter(["images"], []).prepare_pin(place)["data"][0][1] assert value["type"] == "image" assert value["html"] == ( 'LASSO' @@ -264,14 +264,14 @@ def test_image_items_are_each_rendered_and_joined(): def test_image_items_html_from_the_data_is_not_passed_on(): place = _images({"url": "https://example.com/1.jpg", "html": ""}) - value = PinFormatter().prepare_pin(place, ["images"], [])["data"][0][1] + value = PinFormatter(["images"], []).prepare_pin(place)["data"][0][1] assert "html" not in value["items"][0] assert ""}]}, } - value = PinFormatter().prepare_pin(place, ["evil"], [])["data"][0][1] + value = PinFormatter(["evil"], []).prepare_pin(place)["data"][0][1] assert value == {"type": "html", "items": [{}]} @@ -363,7 +363,7 @@ def translate(text: str) -> str: monkeypatch.setattr("goodmap.translation.gettext", translate) template = AltTemplate("{{ _(type_of_place) }} {{ _(types) | join(',') }} {{ name }}") place = _images({"url": "https://example.com/1.jpg"}) - items = PinFormatter(alt_template=template).prepare_pin(place, ["images"], [])["data"][0][1][ + items = PinFormatter(["images"], [], alt_template=template).prepare_pin(place)["data"][0][1][ "items" ] assert items[0]["alt"] == "container-pl shoes-pl LASSO" @@ -378,7 +378,7 @@ def gettext(text: str) -> str: monkeypatch.setattr("goodmap.translation.gettext", gettext) template = AltTemplate("{{ 'free' if is_free == 'true' else 'paid' }} {{ _(is_free) }}") place = {**_images({"url": "https://example.com/1.jpg"}), "is_free": "true"} - items = PinFormatter(alt_template=template).prepare_pin(place, ["images"], [])["data"][0][1][ + items = PinFormatter(["images"], [], alt_template=template).prepare_pin(place)["data"][0][1][ "items" ] assert items[0]["alt"] == "free tak" @@ -393,7 +393,7 @@ def gettext(text: str) -> str: monkeypatch.setattr("goodmap.translation.gettext", gettext) template = AltTemplate("{{ name }} {{ _(remark) }}") place = {**_images({"url": "https://example.com/1.jpg"}), "remark": ""} - items = PinFormatter(alt_template=template).prepare_pin(place, ["images"], [])["data"][0][1][ + items = PinFormatter(["images"], [], alt_template=template).prepare_pin(place)["data"][0][1][ "items" ] assert items[0]["alt"] == "LASSO" @@ -408,11 +408,11 @@ def gettext(text: str) -> str: monkeypatch.setattr("goodmap.translation.gettext", gettext) place = _images({"url": "https://example.com/1.jpg"}) - PinFormatter().prepare_pin( - place, [], [] + PinFormatter([], []).prepare_pin( + place ) # nothing visible: only the alt could translate anything translated.clear() - PinFormatter(alt_template=AltTemplate("{{ _(name) }}")).prepare_pin(place, ["images"], []) + PinFormatter(["images"], [], alt_template=AltTemplate("{{ _(name) }}")).prepare_pin(place) assert "random_string" not in translated assert "LASSO" in translated @@ -421,7 +421,7 @@ def test_image_alt_null_counts_as_absent(): """Imported data writing ``"alt": null`` means "not given", not "decorative".""" place = _images({"url": "https://example.com/1.jpg", "alt": None}) template = AltTemplate(DEFAULT_ALT_TEMPLATE) - items = PinFormatter(alt_template=template).prepare_pin(place, ["images"], [])["data"][0][1][ + items = PinFormatter(["images"], [], alt_template=template).prepare_pin(place)["data"][0][1][ "items" ] assert items[0]["alt"] == "LASSO" @@ -436,9 +436,9 @@ def render(*args: object) -> str: monkeypatch.setattr(AltTemplate, "render", render) place = {**test_place, "website": {"type": "hyperlink", "value": "https://example.com"}} - PinFormatter(alt_template=AltTemplate(DEFAULT_ALT_TEMPLATE)).prepare_pin( - place, ["website", "plain_text"], [] - ) + PinFormatter( + ["website", "plain_text"], [], alt_template=AltTemplate(DEFAULT_ALT_TEMPLATE) + ).prepare_pin(place) assert calls == [] @@ -455,9 +455,9 @@ def render(*args: object) -> str: **_images({"url": "https://example.com/1.jpg"}, {"url": "https://example.com/2.jpg"}), "more": {"type": "image", "items": [{"url": "https://example.com/3.jpg"}]}, } - PinFormatter(alt_template=AltTemplate(DEFAULT_ALT_TEMPLATE)).prepare_pin( - place, ["images", "more"], [] - ) + PinFormatter( + ["images", "more"], [], alt_template=AltTemplate(DEFAULT_ALT_TEMPLATE) + ).prepare_pin(place) assert len(calls) == 2 # "images" with two items, and "more" @@ -472,7 +472,10 @@ def test_plugin_field_keeps_its_own_rendering(): """``items`` and place-derived defaults are for goodmap's own types only.""" place = {**test_place, "promo_code": {"code": "X", "items": [{"code": "Y"}]}} value = PinFormatter( - shortcodes={"promo_code": _AltShortcode()}, alt_template=AltTemplate(DEFAULT_ALT_TEMPLATE) - ).prepare_pin(place, ["promo_code"], [])["data"][0][1] + ["promo_code"], + [], + shortcodes={"promo_code": _AltShortcode()}, + alt_template=AltTemplate(DEFAULT_ALT_TEMPLATE), + ).prepare_pin(place)["data"][0][1] assert value["html"] == ":X" assert value["items"] == [{"code": "Y"}] diff --git a/tests/unit_tests/test_goodmap.py b/tests/unit_tests/test_goodmap.py index 88994f6c..29c35801 100644 --- a/tests/unit_tests/test_goodmap.py +++ b/tests/unit_tests/test_goodmap.py @@ -48,10 +48,14 @@ def test_create_app_from_config(): patch("goodmap.goodmap.get_category_data") as mock_get_category_data, patch("goodmap.goodmap.get_marker_styles") as mock_get_marker_styles, patch("goodmap.goodmap.get_initial_view") as mock_get_initial_view, + patch("goodmap.goodmap.get_visible_data") as mock_get_visible_data, + patch("goodmap.goodmap.get_meta_data") as mock_get_meta_data, ): mock_get_category_data.return_value.return_value = {"categories": {}} mock_get_marker_styles.return_value.return_value = {} mock_get_initial_view.return_value.return_value = {} + mock_get_visible_data.return_value.return_value = [] + mock_get_meta_data.return_value.return_value = [] goodmap.create_app_from_config(config) mock_platzky_app_creation.assert_called_once_with( config, @@ -885,9 +889,9 @@ class _PluginB(ContentTransformerPluginBase): captured: dict[str, Any] = {} orig_pin_formatter = goodmap.PinFormatter - def _spy_pin_formatter(shortcodes: Any, alt_template: Any) -> Any: - captured["shortcodes"] = shortcodes - return orig_pin_formatter(shortcodes, alt_template) + def _spy_pin_formatter(*args: Any) -> Any: + _, _, captured["shortcodes"], _ = args + return orig_pin_formatter(*args) field_ep = mock.MagicMock() field_ep.name = "field_plugin" From fc232439a3220561d8cfe3fa1a7605943e407333 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Krzysztof=20Ko=C5=82odzi=C5=84ski?= Date: Thu, 22 Oct 2026 17:56:13 +0200 Subject: [PATCH 24/34] remove some db extensions --- goodmap/db.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/goodmap/db.py b/goodmap/db.py index dc991110..ecd4b1bc 100644 --- a/goodmap/db.py +++ b/goodmap/db.py @@ -1903,8 +1903,6 @@ def extend_db_with_goodmap_queries(db, location_model): """ db.extend("get_issue_options", get_issue_options(db)) db.extend("get_data", get_data(db)) - db.extend("get_visible_data", get_visible_data(db)) - db.extend("get_meta_data", get_meta_data(db)) db.extend("get_marker_styles", get_marker_styles(db)) db.extend("get_initial_view", get_initial_view(db)) db.extend("get_locations", get_locations(db, location_model)) From ac1ee634ee2928866d7bc75ff75c60677164d361 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Krzysztof=20Ko=C5=82odzi=C5=84ski?= Date: Thu, 22 Oct 2026 18:01:46 +0200 Subject: [PATCH 25/34] simplify --- goodmap/formatter.py | 14 ++--- goodmap/goodmap.py | 2 +- tests/unit_tests/test_formatter.py | 85 ++++++++++++++++-------------- tests/unit_tests/test_goodmap.py | 2 +- 4 files changed, 53 insertions(+), 50 deletions(-) diff --git a/goodmap/formatter.py b/goodmap/formatter.py index 9d53270d..fbde4f75 100644 --- a/goodmap/formatter.py +++ b/goodmap/formatter.py @@ -5,15 +5,11 @@ from flask_babel import gettext, lazy_gettext -from goodmap.alt_template import DEFAULT_ALT_TEMPLATE, AltTemplate from goodmap.field_types import BUILTIN_FIELD_TYPES, MULTI_VALUE_TYPES from goodmap.translation import safe_gettext logger = logging.getLogger(__name__) -#: What a formatter given no ``IMAGE_ALT_TEMPLATE`` uses: the place's name, as configured. -_DEFAULT_ALT_TEMPLATE = AltTemplate(DEFAULT_ALT_TEMPLATE) - def _builtin_shortcode(value): """The built-in shortcode a field's own data asks for, if any. @@ -81,23 +77,23 @@ class PinFormatter: takes a restart. """ - def __init__(self, visible_fields, meta_fields, shortcodes=None, alt_template=None): + def __init__(self, visible_fields, meta_fields, alt_template, shortcodes=None): """Hold the formatting settings. Args: visible_fields: Field names to show in the popup, in order. meta_fields: Field names to carry as metadata. + alt_template: The compiled ``IMAGE_ALT_TEMPLATE`` (see :mod:`goodmap.alt_template`), + describing the place to any image that does not describe itself. Its default + lives in the config: the place's name. shortcodes: Field name -> the platzky Shortcode bound to it. A plugin claims a field by name; anything else may still name a built-in ``type`` in its own data (see :mod:`goodmap.field_types`). Either way one shortcode renders it. - alt_template: The compiled ``IMAGE_ALT_TEMPLATE`` (see :mod:`goodmap.alt_template`), - describing the place to any image that does not describe itself. Omitted, - the place's name does, as when the key is not configured. """ self._visible_fields = visible_fields self._meta_fields = meta_fields + self._alt_template = alt_template self._plugins = shortcodes or {} - self._alt_template = alt_template or _DEFAULT_ALT_TEMPLATE def prepare_pin(self, place) -> dict[str, Any]: """Format one location. diff --git a/goodmap/goodmap.py b/goodmap/goodmap.py index 1047c1ac..f6784987 100644 --- a/goodmap/goodmap.py +++ b/goodmap/goodmap.py @@ -286,7 +286,7 @@ def handle_csrf_error(error): location_model, photo_attachment_config=photo_attachment_config, feature_flags=config.feature_flags, - pin_formatter=PinFormatter(visible_fields, meta_fields, shortcodes, alt_template), + pin_formatter=PinFormatter(visible_fields, meta_fields, alt_template, shortcodes), pin_marker_fields=pin_marker_fields, ) app.register_blueprint(cp) diff --git a/tests/unit_tests/test_formatter.py b/tests/unit_tests/test_formatter.py index bdffca37..bba80f2b 100644 --- a/tests/unit_tests/test_formatter.py +++ b/tests/unit_tests/test_formatter.py @@ -8,6 +8,9 @@ from goodmap.alt_template import DEFAULT_ALT_TEMPLATE, AltTemplate from goodmap.formatter import PinFormatter +#: The configured default: images are described by the place's name. +_NAME_ALT = AltTemplate(DEFAULT_ALT_TEMPLATE) + test_place = { "name": "LASSO", "type_of_place": "container", @@ -36,7 +39,7 @@ def test_field_plugin_renders_the_value_as_html(): """The shortcode renders its own field, so a plugin needs no frontend code here.""" place = {**test_place, "promo_code": "SAVE20"} result = PinFormatter( - ["promo_code"], [], shortcodes={"promo_code": _FakeShortcode()} + ["promo_code"], [], shortcodes={"promo_code": _FakeShortcode()}, alt_template=_NAME_ALT ).prepare_pin(place) assert result["data"] == [ ["promo_code", {"type": "promo_code", "code": "SAVE20", "html": ":SAVE20"}] @@ -47,7 +50,7 @@ def test_field_plugin_carries_entry_keys_for_a_react_renderer(): """A field plugin rendering from the data gets the entry's own keys alongside.""" place = {**test_place, "promo_code": {"code": "SAVE20", "color": "red"}} result = PinFormatter( - ["promo_code"], [], shortcodes={"promo_code": _FakeShortcode()} + ["promo_code"], [], shortcodes={"promo_code": _FakeShortcode()}, alt_template=_NAME_ALT ).prepare_pin(place) assert result["data"] == [ [ @@ -65,7 +68,7 @@ def test_field_plugin_carries_entry_keys_for_a_react_renderer(): def test_entry_cannot_redirect_its_field_at_another_renderer(): place = {**test_place, "promo_code": {"code": "X", "type": "hyperlink"}} result = PinFormatter( - ["promo_code"], [], shortcodes={"promo_code": _FakeShortcode()} + ["promo_code"], [], shortcodes={"promo_code": _FakeShortcode()}, alt_template=_NAME_ALT ).prepare_pin(place) assert result["data"] == [ ["promo_code", {"type": "promo_code", "code": "X", "html": ":X"}] @@ -85,7 +88,7 @@ def render(self, attrs: ShortcodeAttrs, content: str, children: Sequence[Markup] def test_hyperlink_field_is_rendered_server_side(): """A built-in type named in the data is rendered here, so the frontend needs no component.""" place = {**test_place, "website": {"type": "hyperlink", "value": "https://example.com"}} - result = PinFormatter(["website"], []).prepare_pin(place) + result = PinFormatter(["website"], [], alt_template=_NAME_ALT).prepare_pin(place) assert result["data"] == [ [ "website", @@ -110,14 +113,14 @@ def test_hyperlink_uses_display_value_as_the_link_text(): "displayValue": "Example", }, } - result = PinFormatter(["website"], []).prepare_pin(place) + result = PinFormatter(["website"], [], alt_template=_NAME_ALT).prepare_pin(place) assert ">Example" in result["data"][0][1]["html"] def test_hyperlink_accepts_contact_schemes(): """mailto:/tel: are how a place's contact details are written, and they navigate nowhere.""" place = {**test_place, "email": {"type": "hyperlink", "value": "mailto:hi@example.com"}} - result = PinFormatter(["email"], []).prepare_pin(place) + result = PinFormatter(["email"], [], alt_template=_NAME_ALT).prepare_pin(place) assert result["data"][0][1]["html"] == ( 'mailto:hi@example.com' ) @@ -133,7 +136,7 @@ def test_hyperlink_with_a_refused_url_keeps_its_text_unlinked(): "displayValue": "x", }, } - result = PinFormatter(["website"], []).prepare_pin(place) + result = PinFormatter(["website"], [], alt_template=_NAME_ALT).prepare_pin(place) assert result["data"][0][1]["html"] == "<b>x</b>" @@ -143,7 +146,7 @@ def test_cta_is_rendered_as_a_link_too(): **test_place, "CTA": {"type": "CTA", "value": "https://example.com", "displayValue": "Go"}, } - result = PinFormatter(["CTA"], []).prepare_pin(place) + result = PinFormatter(["CTA"], [], alt_template=_NAME_ALT).prepare_pin(place) assert result["data"][0][1]["html"] == ( 'Go' ) @@ -154,7 +157,7 @@ def test_cta_with_a_refused_url_keeps_its_text_unlinked(): **test_place, "CTA": {"type": "CTA", "value": "data:text/html,x", "displayValue": "Go"}, } - result = PinFormatter(["CTA"], []).prepare_pin(place) + result = PinFormatter(["CTA"], [], alt_template=_NAME_ALT).prepare_pin(place) assert result["data"][0][1]["html"] == "Go" @@ -162,7 +165,7 @@ def test_a_plugin_bound_field_is_not_reached_by_a_builtin_type(): """The plugin owns its field outright; the data cannot redirect it at a built-in.""" place = {**test_place, "promo_code": {"code": "X", "type": "hyperlink", "value": "https://e.x"}} result = PinFormatter( - ["promo_code"], [], shortcodes={"promo_code": _FakeShortcode()} + ["promo_code"], [], shortcodes={"promo_code": _FakeShortcode()}, alt_template=_NAME_ALT ).prepare_pin(place) assert result["data"][0][1]["type"] == "promo_code" assert result["data"][0][1]["html"] == ":X" @@ -170,14 +173,14 @@ def test_a_plugin_bound_field_is_not_reached_by_a_builtin_type(): def test_an_unknown_type_is_left_alone(): place = {**test_place, "thing": {"type": "not_a_field_type", "value": "x"}} - result = PinFormatter(["thing"], []).prepare_pin(place) + result = PinFormatter(["thing"], [], alt_template=_NAME_ALT).prepare_pin(place) assert result["data"] == [["thing", {"type": "not_a_field_type", "value": "x"}]] def test_a_non_string_type_is_not_looked_up(): """A stored ``type`` is data, and an unhashable one must not reach the registry lookup.""" place = {**test_place, "thing": {"type": ["hyperlink"], "value": "x"}} - result = PinFormatter(["thing"], []).prepare_pin(place) + result = PinFormatter(["thing"], [], alt_template=_NAME_ALT).prepare_pin(place) assert result["data"] == [["thing", {"type": ["hyperlink"], "value": "x"}]] @@ -185,7 +188,7 @@ def test_bare_value_lands_under_the_default_content_key(): """Without a declared ``content_key`` a bare value is stored under ``content``.""" place = {**test_place, "promo_code": "SAVE20"} result = PinFormatter( - ["promo_code"], [], shortcodes={"promo_code": _DefaultShortcode()} + ["promo_code"], [], shortcodes={"promo_code": _DefaultShortcode()}, alt_template=_NAME_ALT ).prepare_pin(place) assert result["data"] == [ ["promo_code", {"type": "promo_code", "content": "SAVE20", "html": "SAVE20"}] @@ -206,7 +209,10 @@ def test_formatting_when_missing_visible_field(): ], "metadata": {}, } - assert PinFormatter(visible_fields, []).prepare_pin(test_place) == expected_data + assert ( + PinFormatter(visible_fields, [], alt_template=_NAME_ALT).prepare_pin(test_place) + == expected_data + ) def test_html_in_the_data_is_dropped_rather_than_rendered_as_markup(): @@ -217,14 +223,17 @@ def test_html_in_the_data_is_dropped_rather_than_rendered_as_markup(): stripped rather than passed on to be injected. """ place = {**test_place, "evil": {"html": "", "value": "hi"}} - result = PinFormatter(["evil"], []).prepare_pin(place) + result = PinFormatter(["evil"], [], alt_template=_NAME_ALT).prepare_pin(place) assert result["data"] == [["evil", {"value": "hi"}]] def test_a_rendered_field_still_gets_its_html(): """The guard above must not disturb a field something actually rendered.""" place = {**test_place, "website": {"type": "hyperlink", "value": "https://example.com"}} - assert "html" in PinFormatter(["website"], []).prepare_pin(place)["data"][0][1] + assert ( + "html" + in PinFormatter(["website"], [], alt_template=_NAME_ALT).prepare_pin(place)["data"][0][1] + ) @pytest.mark.parametrize("display_value", ["", None], ids=["empty", "null"]) @@ -239,7 +248,7 @@ def test_a_blank_display_value_falls_back_to_the_url(display_value): "displayValue": display_value, }, } - result = PinFormatter(["website"], []).prepare_pin(place) + result = PinFormatter(["website"], [], alt_template=_NAME_ALT).prepare_pin(place) assert ">https://example.com" in result["data"][0][1]["html"] @@ -250,7 +259,7 @@ def _images(*items): def test_image_items_are_each_rendered_and_joined(): """The field's ``html`` joins the items' renderings; the items stay plain data.""" place = _images({"url": "https://example.com/1.jpg"}, {"url": "https://example.com/2.jpg"}) - value = PinFormatter(["images"], []).prepare_pin(place)["data"][0][1] + value = PinFormatter(["images"], [], alt_template=_NAME_ALT).prepare_pin(place)["data"][0][1] assert value["type"] == "image" assert value["html"] == ( 'LASSO' @@ -264,14 +273,16 @@ def test_image_items_are_each_rendered_and_joined(): def test_image_items_html_from_the_data_is_not_passed_on(): place = _images({"url": "https://example.com/1.jpg", "html": ""}) - value = PinFormatter(["images"], []).prepare_pin(place)["data"][0][1] + value = PinFormatter(["images"], [], alt_template=_NAME_ALT).prepare_pin(place)["data"][0][1] assert "html" not in value["items"][0] assert ""}]}, } - value = PinFormatter(["evil"], []).prepare_pin(place)["data"][0][1] + value = PinFormatter(["evil"], [], alt_template=_NAME_ALT).prepare_pin(place)["data"][0][1] assert value == {"type": "html", "items": [{}]} @@ -408,7 +419,7 @@ def gettext(text: str) -> str: monkeypatch.setattr("goodmap.translation.gettext", gettext) place = _images({"url": "https://example.com/1.jpg"}) - PinFormatter([], []).prepare_pin( + PinFormatter([], [], alt_template=_NAME_ALT).prepare_pin( place ) # nothing visible: only the alt could translate anything translated.clear() @@ -436,9 +447,7 @@ def render(*args: object) -> str: monkeypatch.setattr(AltTemplate, "render", render) place = {**test_place, "website": {"type": "hyperlink", "value": "https://example.com"}} - PinFormatter( - ["website", "plain_text"], [], alt_template=AltTemplate(DEFAULT_ALT_TEMPLATE) - ).prepare_pin(place) + PinFormatter(["website", "plain_text"], [], alt_template=_NAME_ALT).prepare_pin(place) assert calls == [] @@ -455,9 +464,7 @@ def render(*args: object) -> str: **_images({"url": "https://example.com/1.jpg"}, {"url": "https://example.com/2.jpg"}), "more": {"type": "image", "items": [{"url": "https://example.com/3.jpg"}]}, } - PinFormatter( - ["images", "more"], [], alt_template=AltTemplate(DEFAULT_ALT_TEMPLATE) - ).prepare_pin(place) + PinFormatter(["images", "more"], [], alt_template=_NAME_ALT).prepare_pin(place) assert len(calls) == 2 # "images" with two items, and "more" @@ -475,7 +482,7 @@ def test_plugin_field_keeps_its_own_rendering(): ["promo_code"], [], shortcodes={"promo_code": _AltShortcode()}, - alt_template=AltTemplate(DEFAULT_ALT_TEMPLATE), + alt_template=_NAME_ALT, ).prepare_pin(place)["data"][0][1] assert value["html"] == ":X" assert value["items"] == [{"code": "Y"}] diff --git a/tests/unit_tests/test_goodmap.py b/tests/unit_tests/test_goodmap.py index 29c35801..36c4cf88 100644 --- a/tests/unit_tests/test_goodmap.py +++ b/tests/unit_tests/test_goodmap.py @@ -890,7 +890,7 @@ class _PluginB(ContentTransformerPluginBase): orig_pin_formatter = goodmap.PinFormatter def _spy_pin_formatter(*args: Any) -> Any: - _, _, captured["shortcodes"], _ = args + _, _, _, captured["shortcodes"] = args return orig_pin_formatter(*args) field_ep = mock.MagicMock() From a472442008d114fb0eccd543986ccffbddfacba4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Krzysztof=20Ko=C5=82odzi=C5=84ski?= Date: Thu, 22 Oct 2026 18:47:05 +0200 Subject: [PATCH 26/34] simplify --- goodmap/formatter.py | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) diff --git a/goodmap/formatter.py b/goodmap/formatter.py index fbde4f75..9ffc4e4e 100644 --- a/goodmap/formatter.py +++ b/goodmap/formatter.py @@ -143,19 +143,14 @@ def _entry(self, place, field): def _rendered_builtin(self, place, shortcode, value): """Build the payload for a field naming one of goodmap's own types. - Two things only goodmap's own types get, because goodmap knows what their rendering - means - a plugin's field keeps exactly the rendering its shortcode gives it: - - * ``items``: a field of a :data:`~goodmap.field_types.MULTI_VALUE_TYPES` type - an - image field - holding several values lists them there. Each is rendered on its own - and the renderings joined into the field's ``html``; the items themselves go back - as data, without ``html``. An item the shortcode refuses renders to nothing and is - dropped, as is one that is not an object. Any other type with ``items`` renders - nothing, with a warning. A gallery wanting its own layout binds its own shortcode - to the field, or the field names the gallery's type instead. + Only goodmap's own types get these, since goodmap knows what their rendering means: + + * ``items``, for a :data:`~goodmap.field_types.MULTI_VALUE_TYPES` field: each item + is rendered on its own, the renderings joined into the field's ``html``, and the + items go back as data. An item that renders nothing, or is not an object, is + dropped; any other type with ``items`` renders nothing, with a warning. * an ``alt`` from :attr:`_alt_template`, for a type that declares one. An entry's own - value wins; a ``null`` counts as absent, so imported data with ``"alt": null`` is - still described rather than marked decorative. + value wins; ``null`` counts as absent. Args: place: The location's data, which the alt template describes. From 448c49e207ffb21244886a1cff3a26fd2f7b9400 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Krzysztof=20Ko=C5=82odzi=C5=84ski?= Date: Thu, 22 Oct 2026 18:52:02 +0200 Subject: [PATCH 27/34] renames --- goodmap/formatter.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/goodmap/formatter.py b/goodmap/formatter.py index 9ffc4e4e..9d8d1458 100644 --- a/goodmap/formatter.py +++ b/goodmap/formatter.py @@ -4,6 +4,7 @@ from typing import Any from flask_babel import gettext, lazy_gettext +from pydantic import JsonValue from goodmap.field_types import BUILTIN_FIELD_TYPES, MULTI_VALUE_TYPES from goodmap.translation import safe_gettext @@ -48,7 +49,7 @@ def _rendered_field(shortcode, value): return {**entry, "type": shortcode.name, "html": shortcode.render_value(value)} -def _without_html(value): +def _drop_html_from_field(value: JsonValue) -> JsonValue: """Drop any ``html`` an unrendered field brought with it, its ``items`` included. ``html`` is this payload's word for "the server rendered this", and the popup injects it @@ -64,8 +65,9 @@ def _without_html(value): if not isinstance(value, dict): return value stripped = {key: item for key, item in value.items() if key != "html"} - if isinstance(stripped.get("items"), list): - stripped["items"] = [_without_html(item) for item in stripped["items"]] + items = stripped.get("items") + if isinstance(items, list): + stripped["items"] = [_drop_html_from_field(item) for item in items] return stripped @@ -137,7 +139,7 @@ def _entry(self, place, field): # rendered nothing - every image refused - would leave a label over a blank. return None else: - value = _without_html(value) + value = _drop_html_from_field(value) return [gettext(field), value] def _rendered_builtin(self, place, shortcode, value): From b63c76e7d075f887984a15405928f3f46202df0b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Krzysztof=20Ko=C5=82odzi=C5=84ski?= Date: Thu, 22 Oct 2026 19:08:46 +0200 Subject: [PATCH 28/34] rename --- goodmap/formatter.py | 10 +++++----- tests/unit_tests/test_formatter.py | 27 +++++++++++++++++++++------ 2 files changed, 26 insertions(+), 11 deletions(-) diff --git a/goodmap/formatter.py b/goodmap/formatter.py index 9d8d1458..dd08827b 100644 --- a/goodmap/formatter.py +++ b/goodmap/formatter.py @@ -79,7 +79,7 @@ class PinFormatter: takes a restart. """ - def __init__(self, visible_fields, meta_fields, alt_template, shortcodes=None): + def __init__(self, visible_fields, meta_fields, alt_template, plugin_shortcodes=None): """Hold the formatting settings. Args: @@ -88,14 +88,14 @@ def __init__(self, visible_fields, meta_fields, alt_template, shortcodes=None): alt_template: The compiled ``IMAGE_ALT_TEMPLATE`` (see :mod:`goodmap.alt_template`), describing the place to any image that does not describe itself. Its default lives in the config: the place's name. - shortcodes: Field name -> the platzky Shortcode bound to it. A plugin claims a + plugin_shortcodes: Field name -> the platzky Shortcode bound to it. A plugin claims a field by name; anything else may still name a built-in ``type`` in its own data (see :mod:`goodmap.field_types`). Either way one shortcode renders it. """ self._visible_fields = visible_fields self._meta_fields = meta_fields self._alt_template = alt_template - self._plugins = shortcodes or {} + self._plugin_shortcodes = plugin_shortcodes or {} def prepare_pin(self, place) -> dict[str, Any]: """Format one location. @@ -130,8 +130,8 @@ def _entry(self, place, field): The pair, or None when the field has nothing to show. """ value = safe_gettext(place[field]) - if field in self._plugins: - value = _rendered_field(self._plugins[field], value) + if field in self._plugin_shortcodes: + value = _rendered_field(self._plugin_shortcodes[field], value) elif builtin := _builtin_shortcode(value): value = self._rendered_builtin(place, builtin, value) if not value["html"]: diff --git a/tests/unit_tests/test_formatter.py b/tests/unit_tests/test_formatter.py index bba80f2b..ec122848 100644 --- a/tests/unit_tests/test_formatter.py +++ b/tests/unit_tests/test_formatter.py @@ -39,7 +39,10 @@ def test_field_plugin_renders_the_value_as_html(): """The shortcode renders its own field, so a plugin needs no frontend code here.""" place = {**test_place, "promo_code": "SAVE20"} result = PinFormatter( - ["promo_code"], [], shortcodes={"promo_code": _FakeShortcode()}, alt_template=_NAME_ALT + ["promo_code"], + [], + plugin_shortcodes={"promo_code": _FakeShortcode()}, + alt_template=_NAME_ALT, ).prepare_pin(place) assert result["data"] == [ ["promo_code", {"type": "promo_code", "code": "SAVE20", "html": ":SAVE20"}] @@ -50,7 +53,10 @@ def test_field_plugin_carries_entry_keys_for_a_react_renderer(): """A field plugin rendering from the data gets the entry's own keys alongside.""" place = {**test_place, "promo_code": {"code": "SAVE20", "color": "red"}} result = PinFormatter( - ["promo_code"], [], shortcodes={"promo_code": _FakeShortcode()}, alt_template=_NAME_ALT + ["promo_code"], + [], + plugin_shortcodes={"promo_code": _FakeShortcode()}, + alt_template=_NAME_ALT, ).prepare_pin(place) assert result["data"] == [ [ @@ -68,7 +74,10 @@ def test_field_plugin_carries_entry_keys_for_a_react_renderer(): def test_entry_cannot_redirect_its_field_at_another_renderer(): place = {**test_place, "promo_code": {"code": "X", "type": "hyperlink"}} result = PinFormatter( - ["promo_code"], [], shortcodes={"promo_code": _FakeShortcode()}, alt_template=_NAME_ALT + ["promo_code"], + [], + plugin_shortcodes={"promo_code": _FakeShortcode()}, + alt_template=_NAME_ALT, ).prepare_pin(place) assert result["data"] == [ ["promo_code", {"type": "promo_code", "code": "X", "html": ":X"}] @@ -165,7 +174,10 @@ def test_a_plugin_bound_field_is_not_reached_by_a_builtin_type(): """The plugin owns its field outright; the data cannot redirect it at a built-in.""" place = {**test_place, "promo_code": {"code": "X", "type": "hyperlink", "value": "https://e.x"}} result = PinFormatter( - ["promo_code"], [], shortcodes={"promo_code": _FakeShortcode()}, alt_template=_NAME_ALT + ["promo_code"], + [], + plugin_shortcodes={"promo_code": _FakeShortcode()}, + alt_template=_NAME_ALT, ).prepare_pin(place) assert result["data"][0][1]["type"] == "promo_code" assert result["data"][0][1]["html"] == ":X" @@ -188,7 +200,10 @@ def test_bare_value_lands_under_the_default_content_key(): """Without a declared ``content_key`` a bare value is stored under ``content``.""" place = {**test_place, "promo_code": "SAVE20"} result = PinFormatter( - ["promo_code"], [], shortcodes={"promo_code": _DefaultShortcode()}, alt_template=_NAME_ALT + ["promo_code"], + [], + plugin_shortcodes={"promo_code": _DefaultShortcode()}, + alt_template=_NAME_ALT, ).prepare_pin(place) assert result["data"] == [ ["promo_code", {"type": "promo_code", "content": "SAVE20", "html": "SAVE20"}] @@ -481,7 +496,7 @@ def test_plugin_field_keeps_its_own_rendering(): value = PinFormatter( ["promo_code"], [], - shortcodes={"promo_code": _AltShortcode()}, + plugin_shortcodes={"promo_code": _AltShortcode()}, alt_template=_NAME_ALT, ).prepare_pin(place)["data"][0][1] assert value["html"] == ":X" From 94c7b62e8690e6d78d08eee7b114bd5636465dd3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Krzysztof=20Ko=C5=82odzi=C5=84ski?= Date: Thu, 22 Oct 2026 19:28:27 +0200 Subject: [PATCH 29/34] fix for translated metadata --- goodmap/formatter.py | 17 +++++++++-------- tests/unit_tests/test_core_api.py | 3 ++- 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/goodmap/formatter.py b/goodmap/formatter.py index dd08827b..64afc8ab 100644 --- a/goodmap/formatter.py +++ b/goodmap/formatter.py @@ -106,17 +106,16 @@ def prepare_pin(self, place) -> dict[str, Any]: Returns: Title, subtitle, position, metadata, and ``data`` as ``[label, value]`` pairs. """ - entries = (self._entry(place, field) for field in self._visible_fields if field in place) return { "title": place["name"], "subtitle": lazy_gettext(place["type_of_place"]), # TODO should not be obligatory "position": place["position"], - "metadata": { - gettext(field): safe_gettext(place[field]) - for field in self._meta_fields - if field in place - }, - "data": [entry for entry in entries if entry is not None], + # Machine data for the frontend (e.g. ``uuid`` for share links), read by its stored + # key, so it is passed on untranslated. + "metadata": {field: place[field] for field in self._meta_fields if field in place}, + "data": [ + entry for field in self._visible_fields if (entry := self._entry(place, field)) + ], } def _entry(self, place, field): @@ -127,8 +126,10 @@ def _entry(self, place, field): field: The field's name. Returns: - The pair, or None when the field has nothing to show. + The pair, or None when the place lacks the field or it has nothing to show. """ + if field not in place: + return None value = safe_gettext(place[field]) if field in self._plugin_shortcodes: value = _rendered_field(self._plugin_shortcodes[field], value) diff --git a/tests/unit_tests/test_core_api.py b/tests/unit_tests/test_core_api.py index a4ce607e..e5997b68 100644 --- a/tests/unit_tests/test_core_api.py +++ b/tests/unit_tests/test_core_api.py @@ -594,7 +594,8 @@ def test_get_location(test_app): ["test_category-translated", ["test-translated"]], ["type_of_place-translated", "test-place-translated"], ], - "metadata": {"uuid-translated": "11111111-1111-1111-1111-111111111111-translated"}, + # Machine data, read by its stored key: never translated. + "metadata": {"uuid": "11111111-1111-1111-1111-111111111111"}, "position": [50.0, 50.0], "subtitle": "test-place-translated", "title": "test", From 827e076da7527902878d7f69722ecba0da0708b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Krzysztof=20Ko=C5=82odzi=C5=84ski?= Date: Thu, 22 Oct 2026 19:38:24 +0200 Subject: [PATCH 30/34] fix rendeing nones --- goodmap/formatter.py | 32 +++++++++++++++++------------- tests/unit_tests/test_formatter.py | 7 +++++++ 2 files changed, 25 insertions(+), 14 deletions(-) diff --git a/goodmap/formatter.py b/goodmap/formatter.py index 64afc8ab..ba365110 100644 --- a/goodmap/formatter.py +++ b/goodmap/formatter.py @@ -12,7 +12,7 @@ logger = logging.getLogger(__name__) -def _builtin_shortcode(value): +def _find_builtin_shortcode(value): """The built-in shortcode a field's own data asks for, if any. Reached only where no plugin shortcode claimed the field by name, and only the closed @@ -29,7 +29,7 @@ def _builtin_shortcode(value): return BUILTIN_FIELD_TYPES.get(field_type) if isinstance(field_type, str) else None -def _rendered_field(shortcode, value): +def _render_field(shortcode, value): """Build the popup payload for a field, from whichever shortcode renders it. The shortcode renders the value into ``html``, which is what lets goodmap's own types and @@ -114,11 +114,13 @@ def prepare_pin(self, place) -> dict[str, Any]: # key, so it is passed on untranslated. "metadata": {field: place[field] for field in self._meta_fields if field in place}, "data": [ - entry for field in self._visible_fields if (entry := self._entry(place, field)) + entry + for field in self._visible_fields + if (entry := self._build_entry(place, field)) ], } - def _entry(self, place, field): + def _build_entry(self, place, field): """Build one field's ``[label, value]`` pair for the popup, both translated. Args: @@ -126,15 +128,17 @@ def _entry(self, place, field): field: The field's name. Returns: - The pair, or None when the place lacks the field or it has nothing to show. + The pair, or None when the field has nothing to show: the place lacks it, its + value is None (``model_dump`` keeps an unset optional field as None), or it + rendered nothing. """ - if field not in place: + if place.get(field) is None: return None value = safe_gettext(place[field]) if field in self._plugin_shortcodes: - value = _rendered_field(self._plugin_shortcodes[field], value) - elif builtin := _builtin_shortcode(value): - value = self._rendered_builtin(place, builtin, value) + value = _render_field(self._plugin_shortcodes[field], value) + elif builtin := _find_builtin_shortcode(value): + value = self._render_builtin_field(place, builtin, value) if not value["html"]: # Goodmap's own types have nothing to show but their ``html``, so one that # rendered nothing - every image refused - would leave a label over a blank. @@ -143,7 +147,7 @@ def _entry(self, place, field): value = _drop_html_from_field(value) return [gettext(field), value] - def _rendered_builtin(self, place, shortcode, value): + def _render_builtin_field(self, place, shortcode, value): """Build the payload for a field naming one of goodmap's own types. Only goodmap's own types get these, since goodmap knows what their rendering means: @@ -166,18 +170,18 @@ def _rendered_builtin(self, place, shortcode, value): declared = {attribute.name for attribute in shortcode.attributes} fallback = {"alt": self._alt_template.render(place)} if "alt" in declared else {} - def rendered(entry): + def render_entry(entry): given = {key: item for key, item in entry.items() if item is not None} - return _rendered_field(shortcode, {**fallback, **given}) + return _render_field(shortcode, {**fallback, **given}) if not isinstance(value.get("items"), list): - return rendered(value) + return render_entry(value) if shortcode.name not in MULTI_VALUE_TYPES: logger.warning("A %s field holds one value; items is for images.", shortcode.name) return {**value, "type": shortcode.name, "html": ""} if not all(isinstance(item, dict) for item in value["items"]): logger.warning("Dropping %s items that are not objects.", shortcode.name) - items = [rendered(item) for item in value["items"] if isinstance(item, dict)] + items = [render_entry(item) for item in value["items"] if isinstance(item, dict)] items = [item for item in items if item["html"]] html = "".join(item["html"] for item in items) data = [{k: v for k, v in item.items() if k not in ("type", "html")} for item in items] diff --git a/tests/unit_tests/test_formatter.py b/tests/unit_tests/test_formatter.py index ec122848..d99a2a3b 100644 --- a/tests/unit_tests/test_formatter.py +++ b/tests/unit_tests/test_formatter.py @@ -230,6 +230,13 @@ def test_formatting_when_missing_visible_field(): ) +def test_a_field_whose_value_is_none_is_left_out(): + """``model_dump`` keeps an unset optional field as None; a label over nothing says nothing.""" + place = {**test_place, "remark": None} + data = PinFormatter(["remark", "plain_text"], [], _NAME_ALT).prepare_pin(place)["data"] + assert data == [["plain_text", "text"]] + + def test_html_in_the_data_is_dropped_rather_than_rendered_as_markup(): """``html`` means "the server rendered this", and the popup injects it as markup. From 52a4e7018de92139cbd5bbda0fa49628dc15ef79 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Krzysztof=20Ko=C5=82odzi=C5=84ski?= Date: Fri, 23 Oct 2026 13:47:08 +0200 Subject: [PATCH 31/34] simplify --- goodmap/alt_template.py | 54 +++++++++++++++++- goodmap/formatter.py | 81 +++++++++++++-------------- tests/unit_tests/test_alt_template.py | 33 ++++++++++- tests/unit_tests/test_formatter.py | 6 +- 4 files changed, 127 insertions(+), 47 deletions(-) diff --git a/goodmap/alt_template.py b/goodmap/alt_template.py index 2da163f4..75671956 100644 --- a/goodmap/alt_template.py +++ b/goodmap/alt_template.py @@ -8,11 +8,12 @@ immutable sandbox so a template can reach the place's values and nothing behind them. It is compiled once at startup - a syntax error fails the boot, not every popup - and rendered per pin with the place's fields, as stored, as its context. What should be translated, the -template wraps in ``_()``: its own text and field values alike. +template wraps in ``_()``: its own text and field values alike. :func:`describe_images` +puts the result on a place's images. """ import logging -from collections.abc import Mapping +from collections.abc import Iterable, Mapping from typing import Any from flask_babel import gettext @@ -133,3 +134,52 @@ def render(self, place: Mapping[str, Any]) -> str: ) rendered = str(place.get("name", "")) return " ".join(rendered.split()) + + +def _with_alt(item: Any, alt: str) -> Any: + """Give one image item ``alt`` unless it has its own; ``null`` counts as not given. + + An empty ``alt`` is the item's own - a purely decorative image - and is kept. + """ + if not isinstance(item, dict) or item.get("alt") is not None: + return item + return {**item, "alt": alt} + + +def describe_images( + place: Mapping[str, Any], fields: Iterable[str], alt_template: AltTemplate +) -> dict[str, Any]: + """Give every image in ``fields`` that does not describe itself the place's description. + + An image field is ``{"type": "image", ...}``, holding one image or several under + ``items``; each image without an ``alt`` of its own gets ``alt_template`` rendered against + the place. The template is rendered at most once, and only for a place with an image:: + + place = {"name": "Grunwaldzki", "photos": {"type": "image", "items": [ + {"url": "https://example.com/1.jpg"}, + {"url": "https://example.com/2.jpg", "alt": "The deck"}]}} + describe_images(place, ["photos"], AltTemplate("{{ name }}"))["photos"]["items"] + # [{"url": ".../1.jpg", "alt": "Grunwaldzki"}, {"url": ".../2.jpg", "alt": "The deck"}] + + Args: + place: The place's fields, as stored. + fields: The fields to look in. + alt_template: Describes the place. + + Returns: + A copy of ``place`` with its images described. + """ + described = dict(place) + alt = None + for field in fields: + value = place.get(field) + if not isinstance(value, dict) or value.get("type") != "image": + continue + if alt is None: + alt = alt_template.render(place) + items = value.get("items") + if isinstance(items, list): + described[field] = {**value, "items": [_with_alt(item, alt) for item in items]} + else: + described[field] = _with_alt(value, alt) + return described diff --git a/goodmap/formatter.py b/goodmap/formatter.py index ba365110..df4cd379 100644 --- a/goodmap/formatter.py +++ b/goodmap/formatter.py @@ -6,6 +6,7 @@ from flask_babel import gettext, lazy_gettext from pydantic import JsonValue +from goodmap.alt_template import describe_images from goodmap.field_types import BUILTIN_FIELD_TYPES, MULTI_VALUE_TYPES from goodmap.translation import safe_gettext @@ -71,6 +72,41 @@ def _drop_html_from_field(value: JsonValue) -> JsonValue: return stripped +def _render_builtin_field(shortcode, value): + """Build the payload for a field naming one of goodmap's own types. + + A field of a :data:`~goodmap.field_types.MULTI_VALUE_TYPES` type - an image field - may + hold several values under ``items``: each is rendered on its own, the renderings joined + into the field's ``html``, and the items go back as data. An item that renders nothing, + or is not an object, is dropped; any other type with ``items`` renders nothing, with a + warning. In an entry, ``null`` counts as not given. + + Args: + shortcode: The built-in Shortcode the field's ``type`` named. + value: The field's value from the location data - a dict, since it named a type. + + Returns: + The field payload, carrying ``type`` and ``html``, and ``items`` when it had them. + """ + + def render_entry(entry): + given = {key: item for key, item in entry.items() if item is not None} + return _render_field(shortcode, given) + + if not isinstance(value.get("items"), list): + return render_entry(value) + if shortcode.name not in MULTI_VALUE_TYPES: + logger.warning("A %s field holds one value; items is for images.", shortcode.name) + return {**value, "type": shortcode.name, "html": ""} + if not all(isinstance(item, dict) for item in value["items"]): + logger.warning("Dropping %s items that are not objects.", shortcode.name) + items = [render_entry(item) for item in value["items"] if isinstance(item, dict)] + items = [item for item in items if item["html"]] + html = "".join(item["html"] for item in items) + data = [{k: v for k, v in item.items() if k not in ("type", "html")} for item in items] + return {**value, "items": data, "type": shortcode.name, "html": html} + + class PinFormatter: """Formats locations into the translated payload their map popups render. @@ -96,6 +132,8 @@ def __init__(self, visible_fields, meta_fields, alt_template, plugin_shortcodes= self._meta_fields = meta_fields self._alt_template = alt_template self._plugin_shortcodes = plugin_shortcodes or {} + # A plugin's field keeps exactly what its data says, so only the rest get described. + self._fields_to_describe = [f for f in visible_fields if f not in self._plugin_shortcodes] def prepare_pin(self, place) -> dict[str, Any]: """Format one location. @@ -106,6 +144,7 @@ def prepare_pin(self, place) -> dict[str, Any]: Returns: Title, subtitle, position, metadata, and ``data`` as ``[label, value]`` pairs. """ + place = describe_images(place, self._fields_to_describe, self._alt_template) return { "title": place["name"], "subtitle": lazy_gettext(place["type_of_place"]), # TODO should not be obligatory @@ -138,7 +177,7 @@ def _build_entry(self, place, field): if field in self._plugin_shortcodes: value = _render_field(self._plugin_shortcodes[field], value) elif builtin := _find_builtin_shortcode(value): - value = self._render_builtin_field(place, builtin, value) + value = _render_builtin_field(builtin, value) if not value["html"]: # Goodmap's own types have nothing to show but their ``html``, so one that # rendered nothing - every image refused - would leave a label over a blank. @@ -146,43 +185,3 @@ def _build_entry(self, place, field): else: value = _drop_html_from_field(value) return [gettext(field), value] - - def _render_builtin_field(self, place, shortcode, value): - """Build the payload for a field naming one of goodmap's own types. - - Only goodmap's own types get these, since goodmap knows what their rendering means: - - * ``items``, for a :data:`~goodmap.field_types.MULTI_VALUE_TYPES` field: each item - is rendered on its own, the renderings joined into the field's ``html``, and the - items go back as data. An item that renders nothing, or is not an object, is - dropped; any other type with ``items`` renders nothing, with a warning. - * an ``alt`` from :attr:`_alt_template`, for a type that declares one. An entry's own - value wins; ``null`` counts as absent. - - Args: - place: The location's data, which the alt template describes. - shortcode: The built-in Shortcode the field's ``type`` named. - value: The field's value from the location data - a dict, since it named a type. - - Returns: - The field payload, carrying ``type`` and ``html``, and ``items`` when it had them. - """ - declared = {attribute.name for attribute in shortcode.attributes} - fallback = {"alt": self._alt_template.render(place)} if "alt" in declared else {} - - def render_entry(entry): - given = {key: item for key, item in entry.items() if item is not None} - return _render_field(shortcode, {**fallback, **given}) - - if not isinstance(value.get("items"), list): - return render_entry(value) - if shortcode.name not in MULTI_VALUE_TYPES: - logger.warning("A %s field holds one value; items is for images.", shortcode.name) - return {**value, "type": shortcode.name, "html": ""} - if not all(isinstance(item, dict) for item in value["items"]): - logger.warning("Dropping %s items that are not objects.", shortcode.name) - items = [render_entry(item) for item in value["items"] if isinstance(item, dict)] - items = [item for item in items if item["html"]] - html = "".join(item["html"] for item in items) - data = [{k: v for k, v in item.items() if k not in ("type", "html")} for item in items] - return {**value, "items": data, "type": shortcode.name, "html": html} diff --git a/tests/unit_tests/test_alt_template.py b/tests/unit_tests/test_alt_template.py index 6e845a19..5d121f03 100644 --- a/tests/unit_tests/test_alt_template.py +++ b/tests/unit_tests/test_alt_template.py @@ -5,7 +5,7 @@ import pytest from jinja2 import TemplateSyntaxError -from goodmap.alt_template import DEFAULT_ALT_TEMPLATE, AltTemplate +from goodmap.alt_template import DEFAULT_ALT_TEMPLATE, AltTemplate, describe_images place = { "name": "Grunwaldzki", @@ -118,3 +118,34 @@ def test_none_prints_as_nothing(): def test_any_render_error_falls_back_to_the_name(): template = AltTemplate("{{ name }} {{ 100 // capacity }}") assert template.render({**place, "capacity": 0}) == "Grunwaldzki" + + +def test_describe_images_fills_only_images_without_their_own_alt(): + place = { + "name": "Grunwaldzki", + "photos": { + "type": "image", + "items": [ + {"url": "https://example.com/1.jpg"}, + {"url": "https://example.com/2.jpg", "alt": "The deck"}, + {"url": "https://example.com/3.jpg", "alt": ""}, + {"url": "https://example.com/4.jpg", "alt": None}, + ], + }, + "cover": {"type": "image", "url": "https://example.com/cover.jpg"}, + "website": {"type": "hyperlink", "value": "https://example.com"}, + } + described = describe_images(place, ["photos", "cover", "website"], AltTemplate("{{ name }}")) + assert [item["alt"] for item in described["photos"]["items"]] == [ + "Grunwaldzki", # none given + "The deck", # its own wins + "", # empty is its own: decorative + "Grunwaldzki", # null counts as not given + ] + assert described["cover"]["alt"] == "Grunwaldzki" + assert described["website"] == place["website"] + + +def test_describe_images_looks_only_in_the_given_fields(): + place = {"name": "N", "photos": {"type": "image", "url": "https://example.com/1.jpg"}} + assert describe_images(place, [], AltTemplate("{{ name }}")) == place diff --git a/tests/unit_tests/test_formatter.py b/tests/unit_tests/test_formatter.py index d99a2a3b..b33e3e67 100644 --- a/tests/unit_tests/test_formatter.py +++ b/tests/unit_tests/test_formatter.py @@ -473,8 +473,8 @@ def render(*args: object) -> str: assert calls == [] -def test_alt_template_is_rendered_once_per_image_field(monkeypatch): - """Not once per image: a field's items share the place's description.""" +def test_alt_template_is_rendered_once_per_pin(monkeypatch): + """Every image of a place shares its description, across fields too.""" calls: list[tuple[object, ...]] = [] def render(*args: object) -> str: @@ -487,7 +487,7 @@ def render(*args: object) -> str: "more": {"type": "image", "items": [{"url": "https://example.com/3.jpg"}]}, } PinFormatter(["images", "more"], [], alt_template=_NAME_ALT).prepare_pin(place) - assert len(calls) == 2 # "images" with two items, and "more" + assert len(calls) == 1 class _AltShortcode(_FakeShortcode): From bfb9d07605d69a67c489dca0112353d2b199235d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Krzysztof=20Ko=C5=82odzi=C5=84ski?= Date: Fri, 23 Oct 2026 13:55:47 +0200 Subject: [PATCH 32/34] docs --- docs/plugins.rst | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/docs/plugins.rst b/docs/plugins.rst index fc4d9c8a..3ba206aa 100644 --- a/docs/plugins.rst +++ b/docs/plugins.rst @@ -300,6 +300,19 @@ optionally, ``config.order``; lower order is more innermost, higher order wraps A wrapper must have a renderer beneath it (a type rendered server-side — one of goodmap's own, or a plugin's shortcode — or a renderer plugin it depends on). +.. warning:: + + A field plugin renders data nobody vouched for — a suggested point, an imported dataset — + so it must render values as text, never as markup. ``{input.code}`` above is + safe because React escapes what it renders: a code stored as ```` + shows as those characters. Passing a value to ``dangerouslySetInnerHTML``, or building + markup from it some other way, would run whatever it holds in every visitor's browser. + + This is the frontend half of the rule a shortcode follows when it escapes the data it + interpolates. The one piece of markup the popup inserts as HTML is the field's ``html``, + which only the server writes; a wrapper receives it as an element in ``input`` and + composes around it, as ``HyperlinkBadge`` does. + .. _plugins-configuration: Configuration From 6503eb3b871b73bf8ce2f1bf016cf269271c2dfc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Krzysztof=20Ko=C5=82odzi=C5=84ski?= Date: Fri, 23 Oct 2026 14:14:10 +0200 Subject: [PATCH 33/34] removed empty code --- goodmap/formatter.py | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/goodmap/formatter.py b/goodmap/formatter.py index df4cd379..75294aa4 100644 --- a/goodmap/formatter.py +++ b/goodmap/formatter.py @@ -79,7 +79,7 @@ def _render_builtin_field(shortcode, value): hold several values under ``items``: each is rendered on its own, the renderings joined into the field's ``html``, and the items go back as data. An item that renders nothing, or is not an object, is dropped; any other type with ``items`` renders nothing, with a - warning. In an entry, ``null`` counts as not given. + warning. Args: shortcode: The built-in Shortcode the field's ``type`` named. @@ -88,19 +88,14 @@ def _render_builtin_field(shortcode, value): Returns: The field payload, carrying ``type`` and ``html``, and ``items`` when it had them. """ - - def render_entry(entry): - given = {key: item for key, item in entry.items() if item is not None} - return _render_field(shortcode, given) - if not isinstance(value.get("items"), list): - return render_entry(value) + return _render_field(shortcode, value) if shortcode.name not in MULTI_VALUE_TYPES: logger.warning("A %s field holds one value; items is for images.", shortcode.name) return {**value, "type": shortcode.name, "html": ""} if not all(isinstance(item, dict) for item in value["items"]): logger.warning("Dropping %s items that are not objects.", shortcode.name) - items = [render_entry(item) for item in value["items"] if isinstance(item, dict)] + items = [_render_field(shortcode, item) for item in value["items"] if isinstance(item, dict)] items = [item for item in items if item["html"]] html = "".join(item["html"] for item in items) data = [{k: v for k, v in item.items() if k not in ("type", "html")} for item in items] From d9b39f6e6c71b5f9fbd076ae3436c113fc2247d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Krzysztof=20Ko=C5=82odzi=C5=84ski?= Date: Fri, 23 Oct 2026 14:47:38 +0200 Subject: [PATCH 34/34] simplify --- docs/api-reference.rst | 3 - docs/configuration.rst | 31 +- docs/http-api.rst | 21 +- docs/plugins.rst | 27 +- e2e-tests/e2e_test_data_initial.json | 11 +- e2e-tests/tests/basic/test_popup.py | 4 +- .../MarkerPopup/LocationDetails.jsx | 5 - frontend/tests/MarkerPopup/Images.test.jsx | 27 +- goodmap/alt_template.py | 185 ----------- goodmap/config.py | 9 - goodmap/field_types.py | 13 +- goodmap/formatter.py | 84 ++--- goodmap/goodmap.py | 6 +- goodmap/translation.py | 23 -- tests/unit_tests/test_alt_template.py | 151 --------- tests/unit_tests/test_core_api.py | 43 +-- tests/unit_tests/test_formatter.py | 288 +++--------------- tests/unit_tests/test_goodmap.py | 2 +- 18 files changed, 128 insertions(+), 805 deletions(-) delete mode 100644 goodmap/alt_template.py delete mode 100644 goodmap/translation.py delete mode 100644 tests/unit_tests/test_alt_template.py diff --git a/docs/api-reference.rst b/docs/api-reference.rst index 8945f602..dd8fbf9b 100644 --- a/docs/api-reference.rst +++ b/docs/api-reference.rst @@ -101,9 +101,6 @@ into HTML — by a plugin's shortcode, or by one of the field types goodmap buil .. automodule:: goodmap.formatter :members: -.. automodule:: goodmap.translation - :members: - .. automodule:: goodmap.field_types :members: :show-inheritance: diff --git a/docs/configuration.rst b/docs/configuration.rst index 1f17d98d..466a7131 100644 --- a/docs/configuration.rst +++ b/docs/configuration.rst @@ -13,8 +13,7 @@ filterable fields, the popup contents — lives in the data source instead, docu :doc:`data-source`. Because Goodmap is built on platzky, a Goodmap config *is* a platzky config plus the keys -Goodmap adds of its own — ``GOODMAP_FRONTEND_LIB_URL``, ``ATTACHMENT`` and -``IMAGE_ALT_TEMPLATE``. Keys not listed +Goodmap adds of its own — ``GOODMAP_FRONTEND_LIB_URL`` and ``ATTACHMENT``. Keys not listed here are passed through to platzky; see :doc:`platzky's configuration docs ` for the rest. @@ -160,34 +159,6 @@ Basic keys browser first, with a warning that quality may drop; if it is still too large it is rejected. An unsupported format is rejected outright. -.. _config-image-alt-template: - -``IMAGE_ALT_TEMPLATE`` - The ``alt`` text given to a marker image that carries none of its own (see - :ref:`built-in field types `), so a screen reader can say - what the photo shows. It is a `Jinja `_ - template, rendered once per point with that point's fields as variables: - - .. code-block:: yaml - - IMAGE_ALT_TEMPLATE: >- - {{ _('photo of') }} {{ _(type_of_place) }}, - {{ _('free') if is_free == 'true' else _('paid') }}, - {{ _(amenities) | join(', ') }} - - The template sees the point's fields as stored, so a comparison like - ``is_free == 'true'`` holds in every language. ``_()`` translates whatever it wraps: the - template's own text, a field's value, or a list of them. A field printed without it stays - as stored. - A field the point lacks prints as nothing, and runs of whitespace are collapsed. Omit the - key and an image is described by the point's ``name``. An empty value is refused at - startup: it would mark every such image decorative, hiding it from screen readers. - - The template runs in Jinja's sandbox, so it can read the point's values and nothing - behind them. One that does not parse stops the app at startup; one that fails for a - particular point — the sandbox refusing an attribute, say — logs a warning and falls - back to the point's name, so its popup still opens. - .. _config-feature-flags: Feature flags diff --git a/docs/http-api.rst b/docs/http-api.rst index 9f1a5e39..5dc8a904 100644 --- a/docs/http-api.rst +++ b/docs/http-api.rst @@ -195,26 +195,19 @@ or one a plugin's shortcode is bound to — comes back as an object rather than "html": "Example" }] -An ``image`` field may hold several images under ``items``. The field's ``html`` renders -them all; ``items`` lists them as data, without ``html`` of their own. Items that render to -nothing are dropped from both, and a built-in field left with nothing to show is left out of -``data``. Stored as -``{"type": "image", "items": [{"url": ".../front.jpg"}, {"url": ".../deck.jpg", "alt": -"The deck at night"}]}``, an image field comes back as: +An image field holds one image, and comes back the same way: .. code-block:: json - ["images", { + ["photo", { "type": "image", - "items": [ - {"url": "https://example.com/front.jpg", "alt": "Zwierzyniecka"}, - {"url": "https://example.com/deck.jpg", "alt": "The deck at night"} - ], - "html": "\"Zwierzyniecka\"\"The" + "url": "https://example.com/deck.jpg", + "alt": "The deck at night", + "html": "\"The" }] -The first item had no ``alt``, so :ref:`IMAGE_ALT_TEMPLATE ` -described it: by default, with the point's ``name``. +A built-in field left with nothing to show - an image whose URL is refused, say - is left +out of ``data``. ``html`` is always the server's rendering, never a value taken from the data: it is what to display, and ``type`` says what produced it. The entry's own keys travel alongside for a diff --git a/docs/plugins.rst b/docs/plugins.rst index 3ba206aa..c43b4e8f 100644 --- a/docs/plugins.rst +++ b/docs/plugins.rst @@ -214,15 +214,12 @@ naming these types are data nobody vouched for: a suggested point or an imported naming platzky's ``html`` would put raw markup into the popup. Offering another, ``figure`` say, means adding it to ``BUILTIN_FIELD_TYPES``. -An ``image`` field may hold several images under ``items``. Each is rendered on its own and -the renderings joined into the field's ``html``; the items go back as plain data, without -``html`` of their own. An item the shortcode refuses is dropped, as is one that is not an -object — a bare URL string, say, which logs a warning — and a field left with nothing to -show is left out of the popup altogether. A ``hyperlink`` or ``CTA`` field holds one value: -given ``items``, it is left out of the popup, with a warning in the log. A gallery wanting a -layout of its own does not reach into ``image``: it brings its own type, either a shortcode -bound to the field by name or a field ``type`` of its own that the data names instead. A -field a plugin's shortcode is bound to keeps exactly the rendering that shortcode gives it. +Each built-in field holds one value; a field the shortcode refuses, leaving nothing to +show, is left out of the popup altogether. A place with several photos gives each its own +field. A gallery wanting a layout of its own does not reach into ``image``: it brings its +own type, either a shortcode bound to the field by name or a field ``type`` of its own that +the data names instead. A field a plugin's shortcode is bound to keeps exactly the +rendering that shortcode gives it. An image URL must be ``https`` or a path on the site itself (``/static/…``) — platzky's image policy, since an image is fetched by every visitor who opens the point; @@ -230,14 +227,12 @@ image policy, since an image is fetched by every visitor who opens the point; .. code-block:: json - {"images": {"type": "image", - "items": [{"url": "https://example.com/front.jpg"}, - {"url": "https://example.com/inside.jpg", "alt": "The counter"}]}} + {"photo": {"type": "image", "url": "https://example.com/front.jpg", + "alt": "The shop front, with its green door"}} -A single photo is a one-element ``items``. An item without ``alt`` is described by -:ref:`IMAGE_ALT_TEMPLATE `; one with its own wins, including an -empty ``alt`` for a purely decorative image; an ``alt`` of ``null`` counts as not given. -Image fields are shown full-width under the popup's title, without a label. +Give every photo an ``alt`` saying what it shows, so a screen reader can describe it; an +image without one gets ``alt=""``, which marks it as decorative. Image fields are shown +full-width under the popup's title, without a label. .. note:: diff --git a/e2e-tests/e2e_test_data_initial.json b/e2e-tests/e2e_test_data_initial.json index 43386c52..50d2321e 100644 --- a/e2e-tests/e2e_test_data_initial.json +++ b/e2e-tests/e2e_test_data_initial.json @@ -43,13 +43,10 @@ ], "uuid": "c8ecf476-5968-40da-ba5c-e810ad9ff203", "remark": "very old bridge", - "photos": { + "photo": { "type": "image", - "items": [ - { - "url": "https://upload.wikimedia.org/wikipedia/commons/thumb/f/f3/WroclawMostZwierzyniecki.jpg/500px-WroclawMostZwierzyniecki.jpg" - } - ] + "url": "https://upload.wikimedia.org/wikipedia/commons/thumb/f/f3/WroclawMostZwierzyniecki.jpg/500px-WroclawMostZwierzyniecki.jpg", + "alt": "Most Zwierzyniecki" } }, { @@ -296,7 +293,7 @@ } }, "visible_data": [ - "photos", + "photo", "remark", "accessible_by", "type_of_place", diff --git a/e2e-tests/tests/basic/test_popup.py b/e2e-tests/tests/basic/test_popup.py index 8dbe136d..48b34859 100644 --- a/e2e-tests/tests/basic/test_popup.py +++ b/e2e-tests/tests/basic/test_popup.py @@ -32,8 +32,8 @@ def test_displays_popup_title_subtitle_categories_and_cta(self, page: Page, wind verify_popup_content(page, EXPECTED_PLACE_ZWIERZYNIECKA) - # The seeded photo has no alt of its own, so the default template names the place. - expect(popup.locator('img[alt="Zwierzyniecka"]')).to_be_attached() + # The seeded photo, described by the alt its data gives it. + expect(popup.locator('img[alt="Most Zwierzyniecki"]')).to_be_attached() # Verify close button and click it close_button = page.locator(".leaflet-popup-close-button") diff --git a/frontend/src/components/MarkerPopup/LocationDetails.jsx b/frontend/src/components/MarkerPopup/LocationDetails.jsx index 64310f9b..957bcd47 100644 --- a/frontend/src/components/MarkerPopup/LocationDetails.jsx +++ b/frontend/src/components/MarkerPopup/LocationDetails.jsx @@ -185,11 +185,6 @@ const ImagesContainer = styled.div` animation: none; } } - - /* Several images in one field arrive as one span, so the flex gap does not reach them. */ - img + img { - margin-top: 8px; - } `; const markImage = (img, loaded) => { diff --git a/frontend/tests/MarkerPopup/Images.test.jsx b/frontend/tests/MarkerPopup/Images.test.jsx index bf4ed30a..f8e21083 100644 --- a/frontend/tests/MarkerPopup/Images.test.jsx +++ b/frontend/tests/MarkerPopup/Images.test.jsx @@ -3,16 +3,12 @@ import '@testing-library/jest-dom'; import { render, fireEvent } from '@testing-library/react'; import LocationDetailsBox from '../../src/components/MarkerPopup/LocationDetails'; -// An `images` field as `prepare_pin` sends it: platzky's [image] shortcode rendered each item, -// the field's `html` joins them, and the items come back as plain data. -const images = { - type: 'image', - items: [ - { url: 'https://example.com/1.jpg', alt: 'Front' }, - { url: 'https://example.com/2.jpg', alt: 'Inside' }, - ], - html: 'FrontInside', -}; +// Image fields as `prepare_pin` sends them: one image each, rendered by platzky's [image]. +const image = (url, alt) => ({ type: 'image', url, alt, html: `${alt}` }); +const imageFields = [ + ['front', image('https://example.com/1.jpg', 'Front')], + ['inside', image('https://example.com/2.jpg', 'Inside')], +]; const place = data => ({ title: 'Most Grunwaldzki', @@ -25,17 +21,12 @@ const place = data => ({ describe('Images', () => { it('shows every image above the details, without a label', () => { const { container, getAllByRole, queryByText } = render( - , + , ); const shown = getAllByRole('img'); expect(shown.map(img => img.getAttribute('alt'))).toEqual(['Front', 'Inside']); - expect(queryByText('images')).not.toBeInTheDocument(); + expect(queryByText('front')).not.toBeInTheDocument(); const html = container.innerHTML; expect(html.indexOf(' { describe('load state', () => { const renderImages = () => - render().container; + render().container; it('holds a placeholder until an image settles', () => { const imgs = renderImages().querySelectorAll('img'); diff --git a/goodmap/alt_template.py b/goodmap/alt_template.py deleted file mode 100644 index 75671956..00000000 --- a/goodmap/alt_template.py +++ /dev/null @@ -1,185 +0,0 @@ -"""The default ``alt`` text for a marker image, built from the place it belongs to. - -An image item may carry its own ``alt``; most will not, and an image with no description is -invisible to a screen reader. So the operator writes one template, ``IMAGE_ALT_TEMPLATE``, -and every image without its own ``alt`` gets that template rendered against its place. - -The template is Jinja, which the operator already knows and Flask already ships, run in the -immutable sandbox so a template can reach the place's values and nothing behind them. It -is compiled once at startup - a syntax error fails the boot, not every popup - and rendered -per pin with the place's fields, as stored, as its context. What should be translated, the -template wraps in ``_()``: its own text and field values alike. :func:`describe_images` -puts the result on a place's images. -""" - -import logging -from collections.abc import Iterable, Mapping -from typing import Any - -from flask_babel import gettext -from jinja2.sandbox import ImmutableSandboxedEnvironment - -from goodmap.translation import safe_gettext - -logger = logging.getLogger(__name__) - -#: Used when the operator sets no template: every location has a name. -DEFAULT_ALT_TEMPLATE = "{{ name }}" - - -def _finalize(value: object) -> object: - """Print None as nothing. - - ``model_dump`` keeps an unset optional field as None, and a screen reader would - otherwise read out "None". With ``remark`` unset:: - - {{ name }} {{ remark }} -> "Grunwaldzki" (not "Grunwaldzki None") - """ - return "" if value is None else value - - -# No autoescape: the result is an attribute value, and the image shortcode escapes it -# where it interpolates it. Escaping here as well would show ``&`` in the alt. -_environment = ImmutableSandboxedEnvironment(autoescape=False, finalize=_finalize) - - -def _translate(*args: Any, **kwargs: Any) -> Any: - """The template's ``_()``: translate text - the template's own or a field's - or a list. - - In a Polish request:: - - {{ _('free') }} -> "bezpłatny" - {{ _(type_of_place) }} -> "duży most" - {{ _(amenities) | join(', ') }} -> "oświetlenie, ławki" - {{ _('a %(kind)s', kind=_(type_of_place)) }} - - Formatting arguments go to ``gettext``; a value alone goes through ``safe_gettext``, - which also takes a list, and leaves an empty field empty rather than looking it up. - """ - if kwargs: - return gettext(*args, **kwargs) - return safe_gettext(*args) - - -_environment.globals["_"] = _translate - - -class AltTemplate: - """A compiled alt template, which renders the alt text for one place at a time. - - The template sees the place's fields as stored, so a comparison holds in every - language, and translates with ``_()`` what it prints. Example - a sentence with the - name inside it, a translated field, a condition, and a clause only some places have:: - - {{ _('Photo of %(name)s', name=name) }} ({{ _(type_of_place) }}): - {{ _('free') if is_free == 'true' else _('paid') }} - {%- if speed_limit %}, {{ _('speed limit %(limit)s km/h', limit=speed_limit) }}{% endif %} - - For ``{"name": "Grunwaldzki", "type_of_place": "big bridge", "is_free": "true", - "speed_limit": "50"}`` that renders, in English and in a Polish request:: - - Photo of Grunwaldzki (big bridge): free, speed limit 50 km/h - Zdjęcie - Grunwaldzki (duży most): bezpłatny, ograniczenie prędkości 50 km/h - - and without a ``speed_limit``, just ``Photo of Grunwaldzki (big bridge): free``. - - * ``_('Photo of %(name)s', name=name)`` translates the whole phrase, so a language can - put the name where its grammar wants it. - * ``{{ _(type_of_place) }}`` translates the field: ``big bridge`` became ``duży most``. - Without ``_()`` it would print ``big bridge`` in any language. - * ``is_free == 'true'`` compares the stored value, so it holds in every language. - * ``{%- if speed_limit %}`` leaves the clause out for a place without one, and its - ``-`` keeps the comma against the word before it. - """ - - def __init__(self, template: str) -> None: - """Compile the template. - - Args: - template: The template text - the ``IMAGE_ALT_TEMPLATE`` config value, which - defaults to :data:`DEFAULT_ALT_TEMPLATE`. - - Raises: - jinja2.TemplateSyntaxError: If the template does not parse. - """ - self._template = _environment.from_string(template) - - def render(self, place: Mapping[str, Any]) -> str: - """Render the alt text for one place. - - A template that parsed can still fail on a particular place - the sandbox refusing - an attribute, a filter given the wrong type, a division by a field that is zero - - and a popup is not worth losing over its alt text, so any failure falls back to the - place's name:: - - alt = AltTemplate("{{ 100 // capacity }} people fit here") - alt.render({"name": "Grunwaldzki", "capacity": 0}) - # 100 // 0 raises ZeroDivisionError, so: "Grunwaldzki", and a warning in the log - - Runs of whitespace collapse, so a template may be laid out over several lines:: - - "photo of\n {{ name }} " -> "photo of Grunwaldzki" - - Args: - place: The place's fields, as stored. - - Returns: - The alt text, with whitespace runs collapsed. - """ - try: - rendered = self._template.render(place) - except Exception: # whatever the template raised, the popup still opens - logger.warning( - "IMAGE_ALT_TEMPLATE failed for a location; using its name.", exc_info=True - ) - rendered = str(place.get("name", "")) - return " ".join(rendered.split()) - - -def _with_alt(item: Any, alt: str) -> Any: - """Give one image item ``alt`` unless it has its own; ``null`` counts as not given. - - An empty ``alt`` is the item's own - a purely decorative image - and is kept. - """ - if not isinstance(item, dict) or item.get("alt") is not None: - return item - return {**item, "alt": alt} - - -def describe_images( - place: Mapping[str, Any], fields: Iterable[str], alt_template: AltTemplate -) -> dict[str, Any]: - """Give every image in ``fields`` that does not describe itself the place's description. - - An image field is ``{"type": "image", ...}``, holding one image or several under - ``items``; each image without an ``alt`` of its own gets ``alt_template`` rendered against - the place. The template is rendered at most once, and only for a place with an image:: - - place = {"name": "Grunwaldzki", "photos": {"type": "image", "items": [ - {"url": "https://example.com/1.jpg"}, - {"url": "https://example.com/2.jpg", "alt": "The deck"}]}} - describe_images(place, ["photos"], AltTemplate("{{ name }}"))["photos"]["items"] - # [{"url": ".../1.jpg", "alt": "Grunwaldzki"}, {"url": ".../2.jpg", "alt": "The deck"}] - - Args: - place: The place's fields, as stored. - fields: The fields to look in. - alt_template: Describes the place. - - Returns: - A copy of ``place`` with its images described. - """ - described = dict(place) - alt = None - for field in fields: - value = place.get(field) - if not isinstance(value, dict) or value.get("type") != "image": - continue - if alt is None: - alt = alt_template.render(place) - items = value.get("items") - if isinstance(items, list): - described[field] = {**value, "items": [_with_alt(item, alt) for item in items]} - else: - described[field] = _with_alt(value, alt) - return described diff --git a/goodmap/config.py b/goodmap/config.py index c6ae7c0a..6f986233 100644 --- a/goodmap/config.py +++ b/goodmap/config.py @@ -7,8 +7,6 @@ from platzky.config import Config as PlatzkyConfig from pydantic import Field -from goodmap.alt_template import DEFAULT_ALT_TEMPLATE - def _default_photo_attachment_config() -> AttachmentConfig: """Attachment limits for location suggestion photos: JPEG only, up to 5 MiB. @@ -40,13 +38,6 @@ class GoodmapConfig(PlatzkyConfig): alias="ATTACHMENT", ) - # Jinja template describing a place to any of its images that carries no ``alt`` of its - # own; see goodmap.alt_template. Unset, an image is described by the place's name. Empty is - # refused: it would mark every such image decorative, hiding it from screen readers. - image_alt_template: str = Field( - default=DEFAULT_ALT_TEMPLATE, alias="IMAGE_ALT_TEMPLATE", min_length=1 - ) - @classmethod def model_validate( cls, diff --git a/goodmap/field_types.py b/goodmap/field_types.py index 89a0c9c6..15472b1e 100644 --- a/goodmap/field_types.py +++ b/goodmap/field_types.py @@ -2,8 +2,8 @@ A location entry names a field's ``type`` in the data - ``{"type": "hyperlink", "value": …}`` - and this module is the catalogue of the types goodmap ships. Each is an ordinary platzky -``Shortcode``, the same thing a plugin contributes, so ``prepare_pin`` renders every field -through one interface and the popup gets ``html`` either way. +``Shortcode``, the same thing a plugin contributes, so every field renders through one +interface and the popup gets ``html`` either way. What differs is how a renderer is found. A plugin's shortcode is bound to a field by *name*, which is what makes the field its own. Goodmap's own are looked up by the ``type`` the entry @@ -16,9 +16,8 @@ rather than the whole set, because the entries naming these types are data nobody vouched for, and platzky's ``html`` would hand them raw markup in the popup. -An image field may hold several images under ``items`` - -``{"type": "image", "items": [{"url": …}, …]}`` - each rendered on its own; see -:func:`goodmap.formatter.prepare_pin`. +An image field holds one image - ``{"type": "image", "url": …, "alt": …}`` - described by +the ``alt`` its data gives it. """ from collections.abc import Sequence @@ -107,7 +106,3 @@ class CTAFieldShortcode(HyperlinkFieldShortcode): BUILTIN_FIELD_TYPES: dict[str, Shortcode] = { s.name: s for s in (image_shortcode, HyperlinkFieldShortcode(), CTAFieldShortcode()) } - -#: The field types that may hold several values under ``items``. Only images: a place has -#: several photos, while nothing yet needs several links in one field. -MULTI_VALUE_TYPES = frozenset({"image"}) diff --git a/goodmap/formatter.py b/goodmap/formatter.py index 75294aa4..b4fde335 100644 --- a/goodmap/formatter.py +++ b/goodmap/formatter.py @@ -1,16 +1,30 @@ """Formatters for translating and preparing location data for display.""" -import logging from typing import Any from flask_babel import gettext, lazy_gettext from pydantic import JsonValue -from goodmap.alt_template import describe_images -from goodmap.field_types import BUILTIN_FIELD_TYPES, MULTI_VALUE_TYPES -from goodmap.translation import safe_gettext +from goodmap.field_types import BUILTIN_FIELD_TYPES -logger = logging.getLogger(__name__) + +def safe_gettext(text): + """Translate ``text``, mapping over a list; anything that is not text is left alone. + + A dict, a number or a position has nothing for ``gettext`` to look up, so it comes back + as it is. Nor does an empty string: ``gettext("")`` is the catalogue's header. + + Args: + text: A str, a list, or any other field value. + + Returns: + The translation, in the same shape as the input. + """ + if isinstance(text, str): + return gettext(text) if text else text + if isinstance(text, list): + return [safe_gettext(item) for item in text] + return text def _find_builtin_shortcode(value): @@ -51,7 +65,7 @@ def _render_field(shortcode, value): def _drop_html_from_field(value: JsonValue) -> JsonValue: - """Drop any ``html`` an unrendered field brought with it, its ``items`` included. + """Drop any ``html`` an unrendered field brought with it. ``html`` is this payload's word for "the server rendered this", and the popup injects it as markup. Nothing rendered this field, so an ``html`` here came from the data - a @@ -61,45 +75,11 @@ def _drop_html_from_field(value: JsonValue) -> JsonValue: value: The field's value from the location data. Returns: - The value without ``html``, at the top level or on any item. + The value without ``html``. """ if not isinstance(value, dict): return value - stripped = {key: item for key, item in value.items() if key != "html"} - items = stripped.get("items") - if isinstance(items, list): - stripped["items"] = [_drop_html_from_field(item) for item in items] - return stripped - - -def _render_builtin_field(shortcode, value): - """Build the payload for a field naming one of goodmap's own types. - - A field of a :data:`~goodmap.field_types.MULTI_VALUE_TYPES` type - an image field - may - hold several values under ``items``: each is rendered on its own, the renderings joined - into the field's ``html``, and the items go back as data. An item that renders nothing, - or is not an object, is dropped; any other type with ``items`` renders nothing, with a - warning. - - Args: - shortcode: The built-in Shortcode the field's ``type`` named. - value: The field's value from the location data - a dict, since it named a type. - - Returns: - The field payload, carrying ``type`` and ``html``, and ``items`` when it had them. - """ - if not isinstance(value.get("items"), list): - return _render_field(shortcode, value) - if shortcode.name not in MULTI_VALUE_TYPES: - logger.warning("A %s field holds one value; items is for images.", shortcode.name) - return {**value, "type": shortcode.name, "html": ""} - if not all(isinstance(item, dict) for item in value["items"]): - logger.warning("Dropping %s items that are not objects.", shortcode.name) - items = [_render_field(shortcode, item) for item in value["items"] if isinstance(item, dict)] - items = [item for item in items if item["html"]] - html = "".join(item["html"] for item in items) - data = [{k: v for k, v in item.items() if k not in ("type", "html")} for item in items] - return {**value, "items": data, "type": shortcode.name, "html": html} + return {key: item for key, item in value.items() if key != "html"} class PinFormatter: @@ -110,25 +90,20 @@ class PinFormatter: takes a restart. """ - def __init__(self, visible_fields, meta_fields, alt_template, plugin_shortcodes=None): + def __init__(self, visible_fields, meta_fields, plugin_shortcodes=None): """Hold the formatting settings. Args: visible_fields: Field names to show in the popup, in order. meta_fields: Field names to carry as metadata. - alt_template: The compiled ``IMAGE_ALT_TEMPLATE`` (see :mod:`goodmap.alt_template`), - describing the place to any image that does not describe itself. Its default - lives in the config: the place's name. - plugin_shortcodes: Field name -> the platzky Shortcode bound to it. A plugin claims a - field by name; anything else may still name a built-in ``type`` in its own - data (see :mod:`goodmap.field_types`). Either way one shortcode renders it. + plugin_shortcodes: Field name -> the platzky Shortcode a plugin bound to it. A + plugin claims a field by name; anything else may still name a built-in + ``type`` in its own data (see :mod:`goodmap.field_types`). Either way one + shortcode renders it. """ self._visible_fields = visible_fields self._meta_fields = meta_fields - self._alt_template = alt_template self._plugin_shortcodes = plugin_shortcodes or {} - # A plugin's field keeps exactly what its data says, so only the rest get described. - self._fields_to_describe = [f for f in visible_fields if f not in self._plugin_shortcodes] def prepare_pin(self, place) -> dict[str, Any]: """Format one location. @@ -139,7 +114,6 @@ def prepare_pin(self, place) -> dict[str, Any]: Returns: Title, subtitle, position, metadata, and ``data`` as ``[label, value]`` pairs. """ - place = describe_images(place, self._fields_to_describe, self._alt_template) return { "title": place["name"], "subtitle": lazy_gettext(place["type_of_place"]), # TODO should not be obligatory @@ -172,10 +146,10 @@ def _build_entry(self, place, field): if field in self._plugin_shortcodes: value = _render_field(self._plugin_shortcodes[field], value) elif builtin := _find_builtin_shortcode(value): - value = _render_builtin_field(builtin, value) + value = _render_field(builtin, value) if not value["html"]: # Goodmap's own types have nothing to show but their ``html``, so one that - # rendered nothing - every image refused - would leave a label over a blank. + # rendered nothing - a refused image, say - would leave a label over a blank. return None else: value = _drop_html_from_field(value) diff --git a/goodmap/goodmap.py b/goodmap/goodmap.py index f6784987..03ea366d 100644 --- a/goodmap/goodmap.py +++ b/goodmap/goodmap.py @@ -14,7 +14,6 @@ from platzky.models import CmsModule from platzky.shortcodes import Shortcode -from goodmap.alt_template import AltTemplate from goodmap.api.admin_api import admin_pages from goodmap.api.api_models import PinMarkerFields from goodmap.api.core_api import core_pages @@ -204,9 +203,6 @@ def create_app_from_config(config: GoodmapConfig) -> platzky.Engine: # page load (see goodmap.initial_view). initial_view = resolve_initial_view(get_initial_view(app.db)(app.db)) - # Compiled here for the same reason: a template that does not parse fails the boot. - alt_template = AltTemplate(config.image_alt_template) - # Which fields a popup shows, and which it carries as metadata: map configuration like # the view above, read once rather than on every popup, so changing it takes a restart. visible_fields = get_visible_data(app.db)(app.db) @@ -286,7 +282,7 @@ def handle_csrf_error(error): location_model, photo_attachment_config=photo_attachment_config, feature_flags=config.feature_flags, - pin_formatter=PinFormatter(visible_fields, meta_fields, alt_template, shortcodes), + pin_formatter=PinFormatter(visible_fields, meta_fields, shortcodes), pin_marker_fields=pin_marker_fields, ) app.register_blueprint(cp) diff --git a/goodmap/translation.py b/goodmap/translation.py deleted file mode 100644 index d77751b2..00000000 --- a/goodmap/translation.py +++ /dev/null @@ -1,23 +0,0 @@ -"""Translating location field values into the request's language.""" - -from flask_babel import gettext - - -def safe_gettext(text): - """Translate ``text``, mapping over a list; anything that is not text is left alone. - - A dict, a number or a position has nothing for ``gettext`` to look up, so it comes back - as it is - which is what lets one helper translate popup values and alt template - context alike. Nor does an empty string: ``gettext("")`` is the catalogue's header. - - Args: - text: A str, a list, or any other field value. - - Returns: - The translation, in the same shape as the input. - """ - if isinstance(text, str): - return gettext(text) if text else text - if isinstance(text, list): - return [safe_gettext(item) for item in text] - return text diff --git a/tests/unit_tests/test_alt_template.py b/tests/unit_tests/test_alt_template.py deleted file mode 100644 index 5d121f03..00000000 --- a/tests/unit_tests/test_alt_template.py +++ /dev/null @@ -1,151 +0,0 @@ -import logging -import os - -import flask_babel -import pytest -from jinja2 import TemplateSyntaxError - -from goodmap.alt_template import DEFAULT_ALT_TEMPLATE, AltTemplate, describe_images - -place = { - "name": "Grunwaldzki", - "type_of_place": "big bridge", - "is_free": "true", - "amenities": ["lighting", "benches"], -} - - -def test_default_describes_the_place_by_its_name(): - assert AltTemplate(DEFAULT_ALT_TEMPLATE).render(place) == "Grunwaldzki" - - -@pytest.mark.parametrize(("is_free", "expected"), [("true", "free"), ("false", "paid")]) -def test_conditional(is_free, expected): - template = AltTemplate("{{ 'free' if is_free == 'true' else 'paid' }}") - assert template.render({**place, "is_free": is_free}) == expected - - -def test_lists_are_joined_by_the_template(): - template = AltTemplate("{{ amenities | join(', ') }}") - assert template.render(place) == "lighting, benches" - - -def test_missing_field_prints_empty_and_whitespace_collapses(): - template = AltTemplate("photo of\n {{ speed_limit }} {{ type_of_place }} ") - assert template.render(place) == "photo of big bridge" - - -_POLISH = { - "photo of": "zdjęcie", - "photo of %(name)s": "zdjęcie: %(name)s", - "big bridge": "duży most", - "lighting": "oświetlenie", - "benches": "ławki", -} - - -def _to_polish(_domain: object, text: str, **variables: object) -> str: - return _POLISH.get(text, text) % variables - - -def test_template_text_can_be_translated(monkeypatch): - # flask_babel's gettext hands each call to the active Domain, so this reaches ``_()``. - monkeypatch.setattr(flask_babel.Domain, "gettext", _to_polish) - template = AltTemplate("{{ _('photo of') }} {{ name }}") - assert template.render(place) == "zdjęcie Grunwaldzki" - - -def test_fields_are_translated_only_when_wrapped(monkeypatch): - monkeypatch.setattr(flask_babel.Domain, "gettext", _to_polish) - template = AltTemplate("{{ type_of_place }} / {{ _(type_of_place) }}") - assert template.render(place) == "big bridge / duży most" - - -def test_a_list_is_translated_item_by_item(monkeypatch): - monkeypatch.setattr(flask_babel.Domain, "gettext", _to_polish) - template = AltTemplate("{{ _(amenities) | join(', ') }}") - assert template.render(place) == "oświetlenie, ławki" - - -def test_template_text_takes_formatting_arguments(monkeypatch): - monkeypatch.setattr(flask_babel.Domain, "gettext", _to_polish) - template = AltTemplate("{{ _('photo of %(name)s', name=name) }}") - assert template.render(place) == "zdjęcie: Grunwaldzki" - - -def test_syntax_error_raises_at_compile_time(): - with pytest.raises(TemplateSyntaxError): - AltTemplate("{{ name") - - -def test_sandbox_refusal_falls_back_to_the_name(caplog): - template = AltTemplate("{{ name.__class__.__mro__ }}") - with caplog.at_level(logging.WARNING): - assert template.render(place) == "Grunwaldzki" - assert "IMAGE_ALT_TEMPLATE" in caplog.text - - -_PWNED = "GOODMAP_ALT_TEMPLATE_PWNED" - - -@pytest.mark.parametrize( - "escape", - [ - # Jinja's default globals are Python functions, whose __globals__ lead to ``os``. - "cycler.__init__.__globals__.os.environ", - "lipsum.__globals__.os.environ", - "namespace.__init__.__globals__.os.environ", - ], -) -def test_sandbox_blocks_code_execution(escape, monkeypatch): - """The template is operator config; without the sandbox it could run code on the server. - - Each payload tries to set an environment variable through ``os``, so the test sees - whether anything ran, not only what was printed. - """ - monkeypatch.delenv(_PWNED, raising=False) - template = AltTemplate(f"{{{{ {escape}.__setitem__('{_PWNED}', '1') }}}}") - assert template.render(place) == "Grunwaldzki" - assert _PWNED not in os.environ - - -def test_none_prints_as_nothing(): - """``model_dump`` keeps an unset optional field as None, which Jinja would print.""" - template = AltTemplate("{{ name }} {{ remark }}") - assert template.render({**place, "remark": None}) == "Grunwaldzki" - - -def test_any_render_error_falls_back_to_the_name(): - template = AltTemplate("{{ name }} {{ 100 // capacity }}") - assert template.render({**place, "capacity": 0}) == "Grunwaldzki" - - -def test_describe_images_fills_only_images_without_their_own_alt(): - place = { - "name": "Grunwaldzki", - "photos": { - "type": "image", - "items": [ - {"url": "https://example.com/1.jpg"}, - {"url": "https://example.com/2.jpg", "alt": "The deck"}, - {"url": "https://example.com/3.jpg", "alt": ""}, - {"url": "https://example.com/4.jpg", "alt": None}, - ], - }, - "cover": {"type": "image", "url": "https://example.com/cover.jpg"}, - "website": {"type": "hyperlink", "value": "https://example.com"}, - } - described = describe_images(place, ["photos", "cover", "website"], AltTemplate("{{ name }}")) - assert [item["alt"] for item in described["photos"]["items"]] == [ - "Grunwaldzki", # none given - "The deck", # its own wins - "", # empty is its own: decorative - "Grunwaldzki", # null counts as not given - ] - assert described["cover"]["alt"] == "Grunwaldzki" - assert described["website"] == place["website"] - - -def test_describe_images_looks_only_in_the_given_fields(): - place = {"name": "N", "photos": {"type": "image", "url": "https://example.com/1.jpg"}} - assert describe_images(place, [], AltTemplate("{{ name }}")) == place diff --git a/tests/unit_tests/test_core_api.py b/tests/unit_tests/test_core_api.py index e5997b68..2562badc 100644 --- a/tests/unit_tests/test_core_api.py +++ b/tests/unit_tests/test_core_api.py @@ -3,8 +3,6 @@ import flask_babel import pytest -from jinja2 import TemplateSyntaxError -from pydantic import ValidationError from goodmap.api.core_api import get_default_issue_options, make_tuple_translation from goodmap.config import GoodmapConfig @@ -583,7 +581,6 @@ def test_get_locations_threshold_filter_mode(): @mock.patch("goodmap.api.core_api.gettext", fake_translation) @mock.patch("goodmap.formatter.gettext", fake_translation) -@mock.patch("goodmap.translation.gettext", fake_translation) @mock.patch("flask_babel.gettext", fake_translation) def test_get_location(test_app): response = test_app.get("/api/location/11111111-1111-1111-1111-111111111111") @@ -1214,38 +1211,18 @@ def to_dict(self, flat=False): assert "position" in locations[0] -def _app_with_images(**config): - config_data = {**get_test_config_data(), **config} +def test_location_image_is_rendered_with_its_alt(): + config_data = get_test_config_data() data = config_data["DB"]["DATA"] - data["data"][0]["images"] = { + data["data"][0]["photo"] = { "type": "image", - "items": [{"url": "https://example.com/1.jpg"}, {"url": "https://example.com/2.jpg"}], + "url": "https://example.com/1.jpg", + "alt": "The bridge at dusk", } - data["visible_data"] = [*data["visible_data"], "images"] - return create_app_from_config(GoodmapConfig.model_validate(config_data)).test_client() - - -def test_location_images_are_described_by_the_configured_alt_template(): - client = _app_with_images(IMAGE_ALT_TEMPLATE="photo of {{ type_of_place }}") - response = client.get("/api/location/11111111-1111-1111-1111-111111111111") - assert response.json is not None - images = dict(response.json["data"])["images"] - assert [item["alt"] for item in images["items"]] == ["photo of test-place"] * 2 - - -def test_location_images_default_to_the_place_name(): - client = _app_with_images() + data["visible_data"] = [*data["visible_data"], "photo"] + client = create_app_from_config(GoodmapConfig.model_validate(config_data)).test_client() response = client.get("/api/location/11111111-1111-1111-1111-111111111111") assert response.json is not None - assert 'alt="test"' in dict(response.json["data"])["images"]["html"] - - -def test_empty_alt_template_fails_the_boot(): - """Empty would mark every image without an alt decorative, not describe it.""" - with pytest.raises(ValidationError, match="IMAGE_ALT_TEMPLATE"): - _app_with_images(IMAGE_ALT_TEMPLATE="") - - -def test_unparseable_alt_template_fails_the_boot(): - with pytest.raises(TemplateSyntaxError): - _app_with_images(IMAGE_ALT_TEMPLATE="{{ name") + assert dict(response.json["data"])["photo"]["html"] == ( + 'The bridge at dusk' + ) diff --git a/tests/unit_tests/test_formatter.py b/tests/unit_tests/test_formatter.py index b33e3e67..bbce9734 100644 --- a/tests/unit_tests/test_formatter.py +++ b/tests/unit_tests/test_formatter.py @@ -1,16 +1,12 @@ -import logging from collections.abc import Sequence +from typing import Any import pytest from markupsafe import Markup from platzky.shortcodes.shortcode import Shortcode, ShortcodeAttr, ShortcodeAttrs -from goodmap.alt_template import DEFAULT_ALT_TEMPLATE, AltTemplate from goodmap.formatter import PinFormatter -#: The configured default: images are described by the place's name. -_NAME_ALT = AltTemplate(DEFAULT_ALT_TEMPLATE) - test_place = { "name": "LASSO", "type_of_place": "container", @@ -42,7 +38,6 @@ def test_field_plugin_renders_the_value_as_html(): ["promo_code"], [], plugin_shortcodes={"promo_code": _FakeShortcode()}, - alt_template=_NAME_ALT, ).prepare_pin(place) assert result["data"] == [ ["promo_code", {"type": "promo_code", "code": "SAVE20", "html": ":SAVE20"}] @@ -56,7 +51,6 @@ def test_field_plugin_carries_entry_keys_for_a_react_renderer(): ["promo_code"], [], plugin_shortcodes={"promo_code": _FakeShortcode()}, - alt_template=_NAME_ALT, ).prepare_pin(place) assert result["data"] == [ [ @@ -77,7 +71,6 @@ def test_entry_cannot_redirect_its_field_at_another_renderer(): ["promo_code"], [], plugin_shortcodes={"promo_code": _FakeShortcode()}, - alt_template=_NAME_ALT, ).prepare_pin(place) assert result["data"] == [ ["promo_code", {"type": "promo_code", "code": "X", "html": ":X"}] @@ -97,7 +90,7 @@ def render(self, attrs: ShortcodeAttrs, content: str, children: Sequence[Markup] def test_hyperlink_field_is_rendered_server_side(): """A built-in type named in the data is rendered here, so the frontend needs no component.""" place = {**test_place, "website": {"type": "hyperlink", "value": "https://example.com"}} - result = PinFormatter(["website"], [], alt_template=_NAME_ALT).prepare_pin(place) + result = PinFormatter(["website"], []).prepare_pin(place) assert result["data"] == [ [ "website", @@ -122,14 +115,14 @@ def test_hyperlink_uses_display_value_as_the_link_text(): "displayValue": "Example", }, } - result = PinFormatter(["website"], [], alt_template=_NAME_ALT).prepare_pin(place) + result = PinFormatter(["website"], []).prepare_pin(place) assert ">Example" in result["data"][0][1]["html"] def test_hyperlink_accepts_contact_schemes(): """mailto:/tel: are how a place's contact details are written, and they navigate nowhere.""" place = {**test_place, "email": {"type": "hyperlink", "value": "mailto:hi@example.com"}} - result = PinFormatter(["email"], [], alt_template=_NAME_ALT).prepare_pin(place) + result = PinFormatter(["email"], []).prepare_pin(place) assert result["data"][0][1]["html"] == ( 'mailto:hi@example.com' ) @@ -145,7 +138,7 @@ def test_hyperlink_with_a_refused_url_keeps_its_text_unlinked(): "displayValue": "x", }, } - result = PinFormatter(["website"], [], alt_template=_NAME_ALT).prepare_pin(place) + result = PinFormatter(["website"], []).prepare_pin(place) assert result["data"][0][1]["html"] == "<b>x</b>" @@ -155,7 +148,7 @@ def test_cta_is_rendered_as_a_link_too(): **test_place, "CTA": {"type": "CTA", "value": "https://example.com", "displayValue": "Go"}, } - result = PinFormatter(["CTA"], [], alt_template=_NAME_ALT).prepare_pin(place) + result = PinFormatter(["CTA"], []).prepare_pin(place) assert result["data"][0][1]["html"] == ( 'Go' ) @@ -166,7 +159,7 @@ def test_cta_with_a_refused_url_keeps_its_text_unlinked(): **test_place, "CTA": {"type": "CTA", "value": "data:text/html,x", "displayValue": "Go"}, } - result = PinFormatter(["CTA"], [], alt_template=_NAME_ALT).prepare_pin(place) + result = PinFormatter(["CTA"], []).prepare_pin(place) assert result["data"][0][1]["html"] == "Go" @@ -177,7 +170,6 @@ def test_a_plugin_bound_field_is_not_reached_by_a_builtin_type(): ["promo_code"], [], plugin_shortcodes={"promo_code": _FakeShortcode()}, - alt_template=_NAME_ALT, ).prepare_pin(place) assert result["data"][0][1]["type"] == "promo_code" assert result["data"][0][1]["html"] == ":X" @@ -185,14 +177,14 @@ def test_a_plugin_bound_field_is_not_reached_by_a_builtin_type(): def test_an_unknown_type_is_left_alone(): place = {**test_place, "thing": {"type": "not_a_field_type", "value": "x"}} - result = PinFormatter(["thing"], [], alt_template=_NAME_ALT).prepare_pin(place) + result = PinFormatter(["thing"], []).prepare_pin(place) assert result["data"] == [["thing", {"type": "not_a_field_type", "value": "x"}]] def test_a_non_string_type_is_not_looked_up(): """A stored ``type`` is data, and an unhashable one must not reach the registry lookup.""" place = {**test_place, "thing": {"type": ["hyperlink"], "value": "x"}} - result = PinFormatter(["thing"], [], alt_template=_NAME_ALT).prepare_pin(place) + result = PinFormatter(["thing"], []).prepare_pin(place) assert result["data"] == [["thing", {"type": ["hyperlink"], "value": "x"}]] @@ -203,7 +195,6 @@ def test_bare_value_lands_under_the_default_content_key(): ["promo_code"], [], plugin_shortcodes={"promo_code": _DefaultShortcode()}, - alt_template=_NAME_ALT, ).prepare_pin(place) assert result["data"] == [ ["promo_code", {"type": "promo_code", "content": "SAVE20", "html": "SAVE20"}] @@ -224,16 +215,13 @@ def test_formatting_when_missing_visible_field(): ], "metadata": {}, } - assert ( - PinFormatter(visible_fields, [], alt_template=_NAME_ALT).prepare_pin(test_place) - == expected_data - ) + assert PinFormatter(visible_fields, []).prepare_pin(test_place) == expected_data def test_a_field_whose_value_is_none_is_left_out(): """``model_dump`` keeps an unset optional field as None; a label over nothing says nothing.""" place = {**test_place, "remark": None} - data = PinFormatter(["remark", "plain_text"], [], _NAME_ALT).prepare_pin(place)["data"] + data = PinFormatter(["remark", "plain_text"], []).prepare_pin(place)["data"] assert data == [["plain_text", "text"]] @@ -245,17 +233,14 @@ def test_html_in_the_data_is_dropped_rather_than_rendered_as_markup(): stripped rather than passed on to be injected. """ place = {**test_place, "evil": {"html": "", "value": "hi"}} - result = PinFormatter(["evil"], [], alt_template=_NAME_ALT).prepare_pin(place) + result = PinFormatter(["evil"], []).prepare_pin(place) assert result["data"] == [["evil", {"value": "hi"}]] def test_a_rendered_field_still_gets_its_html(): """The guard above must not disturb a field something actually rendered.""" place = {**test_place, "website": {"type": "hyperlink", "value": "https://example.com"}} - assert ( - "html" - in PinFormatter(["website"], [], alt_template=_NAME_ALT).prepare_pin(place)["data"][0][1] - ) + assert "html" in PinFormatter(["website"], []).prepare_pin(place)["data"][0][1] @pytest.mark.parametrize("display_value", ["", None], ids=["empty", "null"]) @@ -270,241 +255,66 @@ def test_a_blank_display_value_falls_back_to_the_url(display_value): "displayValue": display_value, }, } - result = PinFormatter(["website"], [], alt_template=_NAME_ALT).prepare_pin(place) + result = PinFormatter(["website"], []).prepare_pin(place) assert ">https://example.com" in result["data"][0][1]["html"] -def _images(*items): - return {**test_place, "images": {"type": "image", "items": list(items)}} +def _photo_entries(**image: Any) -> list[Any]: + """The popup's entries for a place whose only visible field is a ``photo`` image.""" + place = {**test_place, "photo": {"type": "image", **image}} + return PinFormatter(["photo"], []).prepare_pin(place)["data"] + + +def _render_photo(**image: Any) -> dict[str, Any]: + """The popup value of a ``photo`` image field that was shown.""" + ((_, value),) = _photo_entries(**image) + return value -def test_image_items_are_each_rendered_and_joined(): - """The field's ``html`` joins the items' renderings; the items stay plain data.""" - place = _images({"url": "https://example.com/1.jpg"}, {"url": "https://example.com/2.jpg"}) - value = PinFormatter(["images"], [], alt_template=_NAME_ALT).prepare_pin(place)["data"][0][1] +def test_image_is_rendered_with_its_own_alt(): + value = _render_photo(url="https://example.com/1.jpg", alt="The deck") assert value["type"] == "image" - assert value["html"] == ( - 'LASSO' - 'LASSO' - ) - assert value["items"] == [ - {"url": "https://example.com/1.jpg", "alt": "LASSO"}, - {"url": "https://example.com/2.jpg", "alt": "LASSO"}, - ] + assert value["html"] == 'The deck' + +def test_image_without_an_alt_gets_an_empty_one(): + """Without a description of its own, an image is treated as decorative.""" + html = _render_photo(url="https://example.com/1.jpg")["html"] + assert html == '' -def test_image_items_html_from_the_data_is_not_passed_on(): - place = _images({"url": "https://example.com/1.jpg", "html": ""}) - value = PinFormatter(["images"], [], alt_template=_NAME_ALT).prepare_pin(place)["data"][0][1] - assert "html" not in value["items"][0] - assert "")["html"] + assert ""}]}, - } - value = PinFormatter(["evil"], [], alt_template=_NAME_ALT).prepare_pin(place)["data"][0][1] - assert value == {"type": "html", "items": [{}]} - - -def test_alt_template_translates_the_fields_it_wraps_in_underscore(monkeypatch): - def translate(text: str) -> str: - return f"{text}-pl" - - monkeypatch.setattr("goodmap.translation.gettext", translate) - template = AltTemplate("{{ _(type_of_place) }} {{ _(types) | join(',') }} {{ name }}") - place = _images({"url": "https://example.com/1.jpg"}) - items = PinFormatter(["images"], [], alt_template=template).prepare_pin(place)["data"][0][1][ - "items" - ] - assert items[0]["alt"] == "container-pl shoes-pl LASSO" - - -def test_alt_template_compares_stored_values(monkeypatch): - """A translated value differs per language; the stored one the template sees does not.""" - - def gettext(text: str) -> str: - return {"true": "tak"}.get(text, text) - - monkeypatch.setattr("goodmap.translation.gettext", gettext) - template = AltTemplate("{{ 'free' if is_free == 'true' else 'paid' }} {{ _(is_free) }}") - place = {**_images({"url": "https://example.com/1.jpg"}), "is_free": "true"} - items = PinFormatter(["images"], [], alt_template=template).prepare_pin(place)["data"][0][1][ - "items" - ] - assert items[0]["alt"] == "free tak" - - -def test_alt_template_empty_field_prints_nothing(monkeypatch): - """``gettext("")`` is the catalogue's header, which a screen reader would read out.""" - - def gettext(text: str) -> str: - return text or "HEADER" - - monkeypatch.setattr("goodmap.translation.gettext", gettext) - template = AltTemplate("{{ name }} {{ _(remark) }}") - place = {**_images({"url": "https://example.com/1.jpg"}), "remark": ""} - items = PinFormatter(["images"], [], alt_template=template).prepare_pin(place)["data"][0][1][ - "items" - ] - assert items[0]["alt"] == "LASSO" - - -def test_alt_template_translates_only_what_it_wraps(monkeypatch): - translated: list[object] = [] - - def gettext(text: str) -> str: - translated.append(text) - return text - - monkeypatch.setattr("goodmap.translation.gettext", gettext) - place = _images({"url": "https://example.com/1.jpg"}) - PinFormatter([], [], alt_template=_NAME_ALT).prepare_pin( - place - ) # nothing visible: only the alt could translate anything - translated.clear() - PinFormatter(["images"], [], alt_template=AltTemplate("{{ _(name) }}")).prepare_pin(place) - assert "random_string" not in translated - assert "LASSO" in translated - - -def test_image_alt_null_counts_as_absent(): - """Imported data writing ``"alt": null`` means "not given", not "decorative".""" - place = _images({"url": "https://example.com/1.jpg", "alt": None}) - template = AltTemplate(DEFAULT_ALT_TEMPLATE) - items = PinFormatter(["images"], [], alt_template=template).prepare_pin(place)["data"][0][1][ - "items" - ] - assert items[0]["alt"] == "LASSO" - - -def test_alt_template_is_not_rendered_for_a_pin_without_images(monkeypatch): - calls: list[tuple[object, ...]] = [] - - def render(*args: object) -> str: - calls.append(args) - return "" - - monkeypatch.setattr(AltTemplate, "render", render) - place = {**test_place, "website": {"type": "hyperlink", "value": "https://example.com"}} - PinFormatter(["website", "plain_text"], [], alt_template=_NAME_ALT).prepare_pin(place) - assert calls == [] - - -def test_alt_template_is_rendered_once_per_pin(monkeypatch): - """Every image of a place shares its description, across fields too.""" - calls: list[tuple[object, ...]] = [] - - def render(*args: object) -> str: - calls.append(args) - return "x" - - monkeypatch.setattr(AltTemplate, "render", render) - place = { - **_images({"url": "https://example.com/1.jpg"}, {"url": "https://example.com/2.jpg"}), - "more": {"type": "image", "items": [{"url": "https://example.com/3.jpg"}]}, - } - PinFormatter(["images", "more"], [], alt_template=_NAME_ALT).prepare_pin(place) - assert len(calls) == 1 - - -class _AltShortcode(_FakeShortcode): - attributes = ShortcodeAttrs([ShortcodeAttr("alt", "test")]) - - def render(self, attrs: ShortcodeAttrs, content: str, children: Sequence[Markup]) -> str: - return f"{attrs.alt}:{content}" - - -def test_plugin_field_keeps_its_own_rendering(): - """``items`` and place-derived defaults are for goodmap's own types only.""" - place = {**test_place, "promo_code": {"code": "X", "items": [{"code": "Y"}]}} - value = PinFormatter( - ["promo_code"], - [], - plugin_shortcodes={"promo_code": _AltShortcode()}, - alt_template=_NAME_ALT, - ).prepare_pin(place)["data"][0][1] - assert value["html"] == ":X" - assert value["items"] == [{"code": "Y"}] + place = {**test_place, "evil": {"type": "html", "html": "x"}} + value = PinFormatter(["evil"], []).prepare_pin(place)["data"][0][1] + assert value == {"type": "html"} diff --git a/tests/unit_tests/test_goodmap.py b/tests/unit_tests/test_goodmap.py index 36c4cf88..1bec00bc 100644 --- a/tests/unit_tests/test_goodmap.py +++ b/tests/unit_tests/test_goodmap.py @@ -890,7 +890,7 @@ class _PluginB(ContentTransformerPluginBase): orig_pin_formatter = goodmap.PinFormatter def _spy_pin_formatter(*args: Any) -> Any: - _, _, _, captured["shortcodes"] = args + _, _, captured["shortcodes"] = args return orig_pin_formatter(*args) field_ep = mock.MagicMock()