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/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/docs/http-api.rst b/docs/http-api.rst index 688f55da..5dc8a904 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,10 +195,25 @@ or one a plugin's shortcode is bound to — comes back as an object rather than "html": "Example" }] -``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. +An image field holds one image, and comes back the same way: + +.. code-block:: json + + ["photo", { + "type": "image", + "url": "https://example.com/deck.jpg", + "alt": "The deck at night", + "html": "\"The" + }] + +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 +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"}``. diff --git a/docs/plugins.rst b/docs/plugins.rst index 4a7a1d45..c43b4e8f 100644 --- a/docs/plugins.rst +++ b/docs/plugins.rst @@ -208,14 +208,47 @@ 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 **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``. + +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; +``http:``, ``javascript:`` and ``data:`` are refused: + +.. code-block:: json + + {"photo": {"type": "image", "url": "https://example.com/front.jpg", + "alt": "The shop front, with its green door"}} + +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:: + + 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``. @@ -262,6 +295,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 diff --git a/e2e-tests/e2e_test_data_initial.json b/e2e-tests/e2e_test_data_initial.json index b02a205c..50d2321e 100644 --- a/e2e-tests/e2e_test_data_initial.json +++ b/e2e-tests/e2e_test_data_initial.json @@ -42,7 +42,12 @@ "lighting" ], "uuid": "c8ecf476-5968-40da-ba5c-e810ad9ff203", - "remark": "very old bridge" + "remark": "very old bridge", + "photo": { + "type": "image", + "url": "https://upload.wikimedia.org/wikipedia/commons/thumb/f/f3/WroclawMostZwierzyniecki.jpg/500px-WroclawMostZwierzyniecki.jpg", + "alt": "Most Zwierzyniecki" + } }, { "name": "Milenijny", @@ -288,6 +293,7 @@ } }, "visible_data": [ + "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 abff7da6..48b34859 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, 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") expect(close_button).to_be_visible() 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/DesktopPopup.jsx b/frontend/src/components/MarkerPopup/DesktopPopup.jsx index d065815d..f3a11116 100644 --- a/frontend/src/components/MarkerPopup/DesktopPopup.jsx +++ b/frontend/src/components/MarkerPopup/DesktopPopup.jsx @@ -1,4 +1,4 @@ -import React, { useEffect } from 'react'; +import React, { useCallback, useEffect, useRef } from 'react'; import PropTypes from 'prop-types'; import { Popup } from 'react-leaflet'; import { useLeafletContext } from '@react-leaflet/core'; @@ -23,6 +23,7 @@ const StyledPopup = styled(Popup)` */ const DesktopPopup = ({ children }) => { const context = useLeafletContext(); + const popupRef = useRef(null); useEffect(() => { // Popup binds itself to the overlay container in its own effect, and child effects run @@ -30,7 +31,25 @@ const DesktopPopup = ({ children }) => { context.overlayContainer?.openPopup(); }, [context]); - return {children}; + // react-leaflet re-lays out and re-pans the popup only when its children change. An image + // the server rendered grows the popup when it arrives, after that - upwards, as the popup + // hangs from its marker - so without this its top, close button included, ends up above + // the map. `load` and `error` do not bubble, hence the capture phase. A callback ref, + // because react-leaflet renders the children only once Leaflet has made the popup's + // content node, after this component's own effects have run. + const contentRef = useCallback(node => { + const relayout = () => popupRef.current?.update(); + if (node) { + node.addEventListener('load', relayout, true); + node.addEventListener('error', relayout, true); + } + }, []); + + return ( + +
{children}
+
+ ); }; DesktopPopup.propTypes = { diff --git a/frontend/src/components/MarkerPopup/LocationDetails.jsx b/frontend/src/components/MarkerPopup/LocationDetails.jsx index 8da9bb68..957bcd47 100644 --- a/frontend/src/components/MarkerPopup/LocationDetails.jsx +++ b/frontend/src/components/MarkerPopup/LocationDetails.jsx @@ -1,5 +1,5 @@ import PropTypes from 'prop-types'; -import styled from 'styled-components'; +import styled, { keyframes } from 'styled-components'; import ExploreIcon from '@mui/icons-material/Explore'; import ReportProblemOutlinedIcon from '@mui/icons-material/ReportProblemOutlined'; import ShareIcon from '@mui/icons-material/Share'; @@ -112,6 +112,111 @@ const CTAContainer = styled.div` } `; +// The map's loading spinner (MapLoadingOverlay's DefaultSpinner) as an image, so it can be an +// ``'s own background: the server's markup has no element of ours to put one in. +const ring = arc => + `url("data:image/svg+xml,${encodeURIComponent( + `` + + `` + + `${arc}`, + )}")`; +const spinner = ring( + ``, +); +const spinnerStill = ring(''); + +const fadeIn = keyframes` + from { + opacity: 0; + } + to { + opacity: 1; + } +`; + +// 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. +// Until a photo has fully arrived it is not shown - a browser would draw it top-down as it +// downloads - and holds a spinner in a placeholder of about the height it will take; +// `markLoadState` says when it has arrived, or failed to. +const ImagesContainer = styled.div` + display: flex; + flex-direction: column; + gap: 8px; + margin: 0 8px 16px 8px; + + > span { + display: block; + } + + img { + display: block; + width: 100%; + max-width: 100%; + height: 180px; + border-radius: 8px; + background: #f5f5f5 ${spinner} center / 50px no-repeat; + /* Draws the downloading picture outside its own box, leaving only the background. */ + object-position: -10000px 0; + } + + img[data-load-state='loaded'] { + width: auto; + height: auto; + background: none; + object-position: 50% 50%; + animation: ${fadeIn} 0.2s ease-out; + } + + /* A broken-image icon tells a visitor nothing they can act on. */ + img[data-load-state='error'] { + display: none; + } + + @media (prefers-reduced-motion: reduce) { + img { + background-image: ${spinnerStill}; + } + + img[data-load-state='loaded'] { + background-image: none; + animation: none; + } + } +`; + +const markImage = (img, loaded) => { + img.dataset.loadState = loaded ? 'loaded' : 'error'; // eslint-disable-line no-param-reassign +}; + +/** + * Marks each `` under `node` as `loaded` or `error` once it settles, for the CSS above. + * The markup is the server's, so React attaches no `onLoad` to it; `load` and `error` do not + * bubble, hence the capture phase. An image already settled - from the cache - is marked now. + */ +const markLoadState = node => { + if (!node) return; + node.querySelectorAll('img').forEach(img => { + if (img.complete) markImage(img, img.naturalWidth > 0); + }); + const onSettle = event => { + if (event.target instanceof HTMLImageElement) + markImage(event.target, event.type === 'load'); + }; + node.addEventListener('load', onSettle, true); + node.addEventListener('error', onSettle, true); +}; + +const ImagesSection = ({ children }) => ( + {children} +); + +ImagesSection.propTypes = { + children: PropTypes.node.isRequired, +}; + const ActionButton = styled.button` cursor: pointer; display: flex; @@ -140,7 +245,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 +327,25 @@ 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 = new Map([ + ['image', 'images'], + ['CTA', 'actions'], +]); + +// In display order. A `labelled` section pairs each value with its field name. +const SECTIONS = [ + { key: 'images', Container: ImagesSection, labelled: false }, + { key: 'details', Container: DetailsGrid, labelled: true }, + { key: 'actions', Container: CTAContainer, labelled: false }, +]; + +const sectionOf = ([, value]) => SECTION_BY_TYPE.get(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 +354,39 @@ 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 ( + + {/* 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 + + ), + )} + + ); + })} + +); LocationDetails.propTypes = { place: PropTypes.shape({ diff --git a/frontend/src/components/MarkerPopup/serverHtmlField.jsx b/frontend/src/components/MarkerPopup/serverHtmlField.jsx index 8cbab526..d69a6056 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 @@ -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 = { diff --git a/frontend/tests/MarkerPopup/DesktopPopup.test.jsx b/frontend/tests/MarkerPopup/DesktopPopup.test.jsx new file mode 100644 index 00000000..b653cb17 --- /dev/null +++ b/frontend/tests/MarkerPopup/DesktopPopup.test.jsx @@ -0,0 +1,60 @@ +import React from 'react'; +import PropTypes from 'prop-types'; +import '@testing-library/jest-dom'; +import { render, act, fireEvent } from '@testing-library/react'; +import { MapContainer, Marker } from 'react-leaflet'; +import { Popup as LeafletPopup } from 'leaflet'; +import DesktopPopup from '../../src/components/MarkerPopup/DesktopPopup'; + +// Content the way the server sends it: markup React does not own, so React never sees the +// image's `load` - only the browser does. +const ServerImage = () => ( + // eslint-disable-next-line react/no-danger -- stands in for serverHtmlField's markup + ' }} /> +); + +const TestMap = ({ withPopup }) => ( + + + {withPopup && ( + + + + )} + + +); + +TestMap.propTypes = { withPopup: PropTypes.bool.isRequired }; + +// As in the app: the marker is on the map first, and the popup mounts once it is clicked. +const renderPopup = async () => { + const { rerender } = render(); + await act(async () => rerender()); +}; + +describe('DesktopPopup', () => { + let update; + + beforeEach(() => { + update = jest.spyOn(LeafletPopup.prototype, 'update'); + }); + + afterEach(() => { + update.mockRestore(); + }); + + it.each(['load', 'error'])( + 're-lays out and re-pans the popup when an image in it fires %s', + async eventName => { + await renderPopup(); + const img = document.querySelector('.leaflet-popup-content img'); + expect(img).toBeInTheDocument(); + update.mockClear(); + + fireEvent(img, new Event(eventName)); + + expect(update).toHaveBeenCalledTimes(1); + }, + ); +}); diff --git a/frontend/tests/MarkerPopup/Images.test.jsx b/frontend/tests/MarkerPopup/Images.test.jsx new file mode 100644 index 00000000..f8e21083 --- /dev/null +++ b/frontend/tests/MarkerPopup/Images.test.jsx @@ -0,0 +1,57 @@ +import React from 'react'; +import '@testing-library/jest-dom'; +import { render, fireEvent } from '@testing-library/react'; +import LocationDetailsBox from '../../src/components/MarkerPopup/LocationDetails'; + +// 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', + 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('front')).not.toBeInTheDocument(); + + const html = container.innerHTML; + expect(html.indexOf(' { + const renderImages = () => + render().container; + + it('holds a placeholder until an image settles', () => { + const imgs = renderImages().querySelectorAll('img'); + imgs.forEach(img => expect(img).not.toHaveAttribute('data-load-state')); + }); + + it('marks an image loaded when it arrives', () => { + const [front, inside] = renderImages().querySelectorAll('img'); + fireEvent.load(front); + expect(front).toHaveAttribute('data-load-state', 'loaded'); + expect(inside).not.toHaveAttribute('data-load-state'); + }); + + it('marks an image failed when it cannot be fetched', () => { + const [front] = renderImages().querySelectorAll('img'); + fireEvent.error(front); + expect(front).toHaveAttribute('data-load-state', 'error'); + }); + }); +}); diff --git a/frontend/tests/MarkerPopup/LocationDetailsBox.test.jsx b/frontend/tests/MarkerPopup/LocationDetailsBox.test.jsx index eeb78d76..4fc2204b 100644 --- a/frontend/tests/MarkerPopup/LocationDetailsBox.test.jsx +++ b/frontend/tests/MarkerPopup/LocationDetailsBox.test.jsx @@ -99,6 +99,32 @@ 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(); + }); + + 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/frontend/tests/services/endpoints.test.js b/frontend/tests/services/endpoints.test.js new file mode 100644 index 00000000..7380de17 --- /dev/null +++ b/frontend/tests/services/endpoints.test.js @@ -0,0 +1,21 @@ +import { withLang } from '../../src/services/http/endpoints'; + +describe('withLang', () => { + 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..cb8f57d9 100644 --- a/goodmap/api/core_api.py +++ b/goodmap/api/core_api.py @@ -12,7 +12,6 @@ from platzky import FeatureFlagSet from platzky.attachment import create_attachment from platzky.config import AttachmentConfig, LanguagesMapping -from platzky.shortcodes import Shortcode from spectree import Response, SpecTree from spectree.models import Tag from werkzeug.exceptions import HTTPException @@ -42,7 +41,7 @@ ) from goodmap.exceptions import LocationValidationError from goodmap.feature_flags import CategoriesHelp -from goodmap.formatter import prepare_pin +from goodmap.formatter import PinFormatter from goodmap.json_security import ( MAX_JSON_DEPTH_LOCATION, JSONDepthError, @@ -203,7 +202,7 @@ def core_pages( location_model, photo_attachment_config: AttachmentConfig, feature_flags: FeatureFlagSet, - shortcodes: dict[str, Shortcode], + pin_formatter: PinFormatter, pin_marker_fields: PinMarkerFields, ) -> Blueprint: # Routes with translated responses (pin fields, schema, categories) are query_locale @@ -427,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 = prepare_pin(location.model_dump(), visible_data, meta_data, shortcodes) - 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/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)) diff --git a/goodmap/field_types.py b/goodmap/field_types.py index 1861cf80..15472b1e 100644 --- a/goodmap/field_types.py +++ b/goodmap/field_types.py @@ -2,14 +2,22 @@ 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 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 one of platzky's built-ins - ``image``, so a +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. + +An image field holds one image - ``{"type": "image", "url": …, "alt": …}`` - described by +the ``alt`` its data gives it. """ from collections.abc import Sequence @@ -17,6 +25,7 @@ from markupsafe import Markup, escape from platzky.shortcodes import Shortcode, ShortcodeAttr, ShortcodeAttrs, UrlNotPermitted +from platzky.shortcodes.image import image_shortcode from platzky.shortcodes.link import LinkShortcode #: Schemes that navigate the browser somewhere, and so are worth a new tab. @@ -91,7 +100,9 @@ class CTAFieldShortcode(HyperlinkFieldShortcode): description = "A marker field holding a URL, shown as a call-to-action button." -#: Field ``type`` -> the shortcode rendering it, keyed by the name written in the data. +#: 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] = { - shortcode.name: shortcode for shortcode in (HyperlinkFieldShortcode(), CTAFieldShortcode()) + s.name: s for s in (image_shortcode, HyperlinkFieldShortcode(), CTAFieldShortcode()) } diff --git a/goodmap/formatter.py b/goodmap/formatter.py index f288813b..b4fde335 100644 --- a/goodmap/formatter.py +++ b/goodmap/formatter.py @@ -1,33 +1,33 @@ """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.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. Nor does an empty string: ``gettext("")`` is the catalogue's header. 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, str): + return gettext(text) if text else text if isinstance(text, list): - return list(map(gettext, text)) - elif isinstance(text, dict): - return text - else: - return gettext(text) + return [safe_gettext(item) for item in text] + return text -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 @@ -40,28 +40,18 @@ def _builtin_shortcode(value): Returns: The Shortcode for the declared ``type``, or None when it names none goodmap ships. """ - if not isinstance(value, dict): - return None - field_type = value.get("type") - if not isinstance(field_type, str): - return None - return BUILTIN_FIELD_TYPES.get(field_type) + field_type = value.get("type") if isinstance(value, dict) else None + 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 a plugin's alike display without shipping any frontend code. The entry's own keys travel alongside for a React field plugin rendering from the data instead - a bare value under - the shortcode's ``content_key``, the name that plugin would look for. ``type`` is stamped - last, so an entry cannot redirect its own field at another renderer. - - Because that bare value travels alongside, a shortcode's rendering is presentation, not - concealment: one that masks or drops part of what it displays still ships the original - here for anyone reading the response. Nothing in goodmap reads it - the popup needs only - ``html`` and ``type`` - so it is carried purely for a field plugin that would rather - render from the data, and could be dropped if none turns up wanting it. + the shortcode's ``content_key``. ``type`` is stamped last, so an entry cannot redirect + its own field at another renderer. Args: shortcode: The Shortcode rendering this field. @@ -74,43 +64,93 @@ 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]: - """Format one location into the translated payload its map popup renders. +def _drop_html_from_field(value: JsonValue) -> JsonValue: + """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 + suggested point, an imported dataset - and must not be mistaken for goodmap's own output. Args: - place: The location's data. - visible_fields: Field names to show in the popup. - meta_data: 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. + value: The field's value from the location data. Returns: - Title, subtitle, position, metadata, and ``data`` as ``[label, value]`` pairs. + The value without ``html``. """ - plugins = shortcodes or {} - data = [] - for field in visible_fields: - if field not in place: - continue + if not isinstance(value, dict): + return value + return {key: item for key, item in value.items() if key != "html"} + + +class PinFormatter: + """Formats locations into the translated payload their map popups render. + + 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, 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. + 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._plugin_shortcodes = plugin_shortcodes or {} + + def prepare_pin(self, place) -> dict[str, Any]: + """Format one location. + + Args: + place: The location's data. + + Returns: + Title, subtitle, position, metadata, and ``data`` as ``[label, value]`` pairs. + """ + return { + "title": place["name"], + "subtitle": lazy_gettext(place["type_of_place"]), # TODO should not be obligatory + "position": place["position"], + # 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._build_entry(place, field)) + ], + } + + def _build_entry(self, place, field): + """Build one field's ``[label, value]`` pair for the popup, both translated. + + Args: + place: The location's data. + field: The field's name. + + Returns: + 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 place.get(field) is None: + return None 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"} - data.append([gettext(field), value]) - pin_data = { - "title": place["name"], - "subtitle": lazy_gettext(place["type_of_place"]), # TODO this should not be obligatory - "position": place["position"], - "metadata": { - gettext(field): safe_gettext(place[field]) for field in meta_data if field in place - }, - "data": data, - } - return pin_data + if field in self._plugin_shortcodes: + value = _render_field(self._plugin_shortcodes[field], value) + elif builtin := _find_builtin_shortcode(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 - a refused image, say - would leave a label over a blank. + return None + else: + value = _drop_html_from_field(value) + return [gettext(field), value] diff --git a/goodmap/goodmap.py b/goodmap/goodmap.py index 9f952e2f..03ea366d 100644 --- a/goodmap/goodmap.py +++ b/goodmap/goodmap.py @@ -25,8 +25,11 @@ 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 from goodmap.initial_view import resolve_initial_view from goodmap.marker_styles import resolve_marker_styles from goodmap.plugin import CAPABILITY_BASES, GoodmapPluginBase @@ -200,6 +203,11 @@ 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)) + # 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) @@ -274,7 +282,7 @@ def handle_csrf_error(error): location_model, photo_attachment_config=photo_attachment_config, feature_flags=config.feature_flags, - shortcodes=shortcodes, + pin_formatter=PinFormatter(visible_fields, meta_fields, shortcodes), pin_marker_fields=pin_marker_fields, ) app.register_blueprint(cp) 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_core_api.py b/tests/unit_tests/test_core_api.py index 39926f17..2562badc 100644 --- a/tests/unit_tests/test_core_api.py +++ b/tests/unit_tests/test_core_api.py @@ -591,7 +591,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", @@ -1208,3 +1209,20 @@ def to_dict(self, flat=False): assert isinstance(locations[0], dict) assert "uuid" in locations[0] assert "position" in locations[0] + + +def test_location_image_is_rendered_with_its_alt(): + config_data = get_test_config_data() + data = config_data["DB"]["DATA"] + data["data"][0]["photo"] = { + "type": "image", + "url": "https://example.com/1.jpg", + "alt": "The bridge at dusk", + } + 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 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 cc1276ff..bbce9734 100644 --- a/tests/unit_tests/test_formatter.py +++ b/tests/unit_tests/test_formatter.py @@ -1,10 +1,11 @@ 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.formatter import prepare_pin +from goodmap.formatter import PinFormatter test_place = { "name": "LASSO", @@ -33,7 +34,11 @@ 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 = prepare_pin(place, ["promo_code"], [], shortcodes={"promo_code": _FakeShortcode()}) + result = PinFormatter( + ["promo_code"], + [], + plugin_shortcodes={"promo_code": _FakeShortcode()}, + ).prepare_pin(place) assert result["data"] == [ ["promo_code", {"type": "promo_code", "code": "SAVE20", "html": ":SAVE20"}] ] @@ -42,7 +47,11 @@ 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 = prepare_pin(place, ["promo_code"], [], shortcodes={"promo_code": _FakeShortcode()}) + result = PinFormatter( + ["promo_code"], + [], + plugin_shortcodes={"promo_code": _FakeShortcode()}, + ).prepare_pin(place) assert result["data"] == [ [ "promo_code", @@ -58,7 +67,11 @@ 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 = prepare_pin(place, ["promo_code"], [], shortcodes={"promo_code": _FakeShortcode()}) + result = PinFormatter( + ["promo_code"], + [], + plugin_shortcodes={"promo_code": _FakeShortcode()}, + ).prepare_pin(place) assert result["data"] == [ ["promo_code", {"type": "promo_code", "code": "X", "html": ":X"}] ] @@ -77,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 = prepare_pin(place, ["website"], []) + result = PinFormatter(["website"], []).prepare_pin(place) assert result["data"] == [ [ "website", @@ -102,14 +115,14 @@ def test_hyperlink_uses_display_value_as_the_link_text(): "displayValue": "Example", }, } - result = 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 = prepare_pin(place, ["email"], []) + result = PinFormatter(["email"], []).prepare_pin(place) assert result["data"][0][1]["html"] == ( 'mailto:hi@example.com' ) @@ -125,7 +138,7 @@ def test_hyperlink_with_a_refused_url_keeps_its_text_unlinked(): "displayValue": "x", }, } - result = prepare_pin(place, ["website"], []) + result = PinFormatter(["website"], []).prepare_pin(place) assert result["data"][0][1]["html"] == "<b>x</b>" @@ -135,7 +148,7 @@ def test_cta_is_rendered_as_a_link_too(): **test_place, "CTA": {"type": "CTA", "value": "https://example.com", "displayValue": "Go"}, } - result = prepare_pin(place, ["CTA"], []) + result = PinFormatter(["CTA"], []).prepare_pin(place) assert result["data"][0][1]["html"] == ( 'Go' ) @@ -146,35 +159,43 @@ def test_cta_with_a_refused_url_keeps_its_text_unlinked(): **test_place, "CTA": {"type": "CTA", "value": "data:text/html,x", "displayValue": "Go"}, } - result = 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 = prepare_pin(place, ["promo_code"], [], shortcodes={"promo_code": _FakeShortcode()}) + result = PinFormatter( + ["promo_code"], + [], + plugin_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 = 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 = 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 = prepare_pin(place, ["promo_code"], [], shortcodes={"promo_code": _DefaultShortcode()}) + result = PinFormatter( + ["promo_code"], + [], + plugin_shortcodes={"promo_code": _DefaultShortcode()}, + ).prepare_pin(place) assert result["data"] == [ ["promo_code", {"type": "promo_code", "content": "SAVE20", "html": "SAVE20"}] ] @@ -194,7 +215,14 @@ def test_formatting_when_missing_visible_field(): ], "metadata": {}, } - assert prepare_pin(test_place, visible_fields, []) == 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"], []).prepare_pin(place)["data"] + assert data == [["plain_text", "text"]] def test_html_in_the_data_is_dropped_rather_than_rendered_as_markup(): @@ -205,14 +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 = 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 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"]) @@ -227,5 +255,66 @@ def test_a_blank_display_value_falls_back_to_the_url(display_value): "displayValue": display_value, }, } - result = prepare_pin(place, ["website"], []) + result = PinFormatter(["website"], []).prepare_pin(place) assert ">https://example.com" in result["data"][0][1]["html"] + + +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_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"] == '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_html_from_the_data_is_not_passed_on(): + html = _render_photo(url="https://example.com/1.jpg", html="")["html"] + assert "