diff --git a/api-surface.json b/api-surface.json index dc56d868..aabf2dfd 100644 --- a/api-surface.json +++ b/api-surface.json @@ -347,7 +347,8 @@ "./expo-router", "./node", "./react", - "./schema" + "./schema", + "./web" ], "exports": { ".": [ @@ -420,6 +421,10 @@ "PageHead", "PageHeadProps" ], + "./web": [ + "PageHead", + "PageHeadProps" + ], "./node": [ "AuditExportOptions", "AuditProblem", diff --git a/docs/docs/seo/api.md b/docs/docs/seo/api.md index b688e7b2..9f108002 100644 --- a/docs/docs/seo/api.md +++ b/docs/docs/seo/api.md @@ -67,6 +67,10 @@ Each returns a `JsonLd` with `@context: 'https://schema.org'` and `@type` set. E - `` — the same `PageMeta` props as the Expo Router `PageHead`, for an app with no Expo Router: React Navigation on react-native-web, a Vite build, an Electron renderer. Writes the `toHeadTags` records to `document.head` in an effect and takes them out on unmount, so the two adapters write the same head. A tag of the same name, property or `rel` that was there before, from the template or from a screen below, is taken out while this head is on and put back when it goes, and the `hreflang` links go as one set, so no language of the head below stays: a screen mounted over another wins, and the one below gets its head back. `active={false}` takes the head out for a screen that stays mounted behind another; a React Navigation screen passes `useIsFocused()`. Native renders `null`. An effect never runs on a server, so a static file gets its head from `headTagsHtml` at build time. +## `@rootnative/seo/web` — peers: react, react-native; no router + +- `` — the same props as the `/dom` `PageHead`, for an app with no Expo Router that renders on a server or prerenders at build time. Renders the `toHeadTags` records as ``, `<meta>` and `<link>` elements. React 19 moves them into `<head>`, on the server and in the browser, so the HTML file has the head and no `headTagsHtml` step is necessary. The JSON-LD is a `<script type="application/ld+json">` in the page body. After the first render it takes out the `<title>` and each head tag in a page slot that it did not render (the tags of the HTML template), and puts them back when it goes. React does not merge two heads: a screen that stays mounted behind another passes `active={false}` (with React Navigation, `useIsFocused()`), or the head holds the tags of both. Native renders `null`. Use `/dom` for an app that only renders in the browser and stacks screens: there, a screen mounted over another wins with no `active` prop. + ## `@rootnative/seo/expo-image` — optional peer: expo-image `>=57.0.0` - `<Picture source alt width height srcSet? sizes? contentFit? loading? fetchPriority? site? style? testID?>` — an image a crawler sees. On the web a plain `<img>` with `src`, `alt`, `width`, `height`, `loading` (default `lazy`), `decoding="async"` and `object-fit` from `contentFit` (default `cover`); on native `expo-image` with `alt` and `accessibilityLabel`. `srcSet` lists more files of the image as `{ source, width }`, with the width in pixels: the web writes `srcset` and `sizes`, so the browser picks a file by the shown width and the pixel density before any script runs, and native gives the files to `expo-image` in place of `source`, which picks one by the view size and the screen scale. Pass `sizes` with `srcSet`, for example `'160px'`; without it the browser takes `100vw`. `fetchPriority="high"` on the hero image, the one the page is built around: the web writes `fetchpriority`, so the browser starts that download before layout, and native gives `expo-image` the value as `priority`. `source` is absolute, or a path under the site URL like `PageMeta.image`: the web gets the path under the host, native the absolute URL, and a relative one needs the site from `SeoProvider` or the `site` prop. `style` is a React Native image style that comes after the `width` and `height` box, so a size in `style` wins; set a side to `undefined` to let `flex` or `aspectRatio` size it. The web lays out the `<img>` as a react-native-web view, and flattens the style to CSS. `alt=""` marks a decorative image. diff --git a/docs/docs/seo/checklist.md b/docs/docs/seo/checklist.md index 2cda634c..ad237a37 100644 --- a/docs/docs/seo/checklist.md +++ b/docs/docs/seo/checklist.md @@ -349,6 +349,27 @@ const head = headTagsHtml(toHeadTags(site, { title: 'Trek', url: '/' })) const html = template.replace('</head>', `${head}</head>`) ``` +### An app that renders on a server + +An app with no Expo Router that renders its pages on a server, or prerenders +them at build time, takes `PageHead` from `@rootnative/seo/web`. It has the +same props. It renders the tags as elements, and React 19 moves them into +`<head>` on the server and in the browser. So the HTML file has the head of +the page, and you need no `headTagsHtml` step. + +```tsx +import { PageHead } from '@rootnative/seo/web' + +export function MovieScreen() { + return <PageHead title={data.title} url={`/movies/${data.id}`} /> +} +``` + +React does not merge two heads. A screen that stays mounted behind another +must pass `active={false}`, or the head holds the tags of both screens. The +tags of your HTML template in the same slots are taken out while the page +is on, and put back when it goes. + ### Per-route `noindex` An overlay route, a filter sheet, or a per-device screen is a page the diff --git a/docs/static/llms-full.txt b/docs/static/llms-full.txt index 7ccdde68..b1213e43 100644 --- a/docs/static/llms-full.txt +++ b/docs/static/llms-full.txt @@ -3154,6 +3154,10 @@ Each returns a `JsonLd` with `@context: 'https://schema.org'` and `@type` set. E - `<PageHead {...meta} site? active?>` — the same `PageMeta` props as the Expo Router `PageHead`, for an app with no Expo Router: React Navigation on react-native-web, a Vite build, an Electron renderer. Writes the `toHeadTags` records to `document.head` in an effect and takes them out on unmount, so the two adapters write the same head. A tag of the same name, property or `rel` that was there before, from the template or from a screen below, is taken out while this head is on and put back when it goes, and the `hreflang` links go as one set, so no language of the head below stays: a screen mounted over another wins, and the one below gets its head back. `active={false}` takes the head out for a screen that stays mounted behind another; a React Navigation screen passes `useIsFocused()`. Native renders `null`. An effect never runs on a server, so a static file gets its head from `headTagsHtml` at build time. +## `@rootnative/seo/web` — peers: react, react-native; no router + +- `<PageHead {...meta} site? active?>` — the same props as the `/dom` `PageHead`, for an app with no Expo Router that renders on a server or prerenders at build time. Renders the `toHeadTags` records as `<title>`, `<meta>` and `<link>` elements. React 19 moves them into `<head>`, on the server and in the browser, so the HTML file has the head and no `headTagsHtml` step is necessary. The JSON-LD is a `<script type="application/ld+json">` in the page body. After the first render it takes out the `<title>` and each head tag in a page slot that it did not render (the tags of the HTML template), and puts them back when it goes. React does not merge two heads: a screen that stays mounted behind another passes `active={false}` (with React Navigation, `useIsFocused()`), or the head holds the tags of both. Native renders `null`. Use `/dom` for an app that only renders in the browser and stacks screens: there, a screen mounted over another wins with no `active` prop. + ## `@rootnative/seo/expo-image` — optional peer: expo-image `>=57.0.0` - `<Picture source alt width height srcSet? sizes? contentFit? loading? fetchPriority? site? style? testID?>` — an image a crawler sees. On the web a plain `<img>` with `src`, `alt`, `width`, `height`, `loading` (default `lazy`), `decoding="async"` and `object-fit` from `contentFit` (default `cover`); on native `expo-image` with `alt` and `accessibilityLabel`. `srcSet` lists more files of the image as `{ source, width }`, with the width in pixels: the web writes `srcset` and `sizes`, so the browser picks a file by the shown width and the pixel density before any script runs, and native gives the files to `expo-image` in place of `source`, which picks one by the view size and the screen scale. Pass `sizes` with `srcSet`, for example `'160px'`; without it the browser takes `100vw`. `fetchPriority="high"` on the hero image, the one the page is built around: the web writes `fetchpriority`, so the browser starts that download before layout, and native gives `expo-image` the value as `priority`. `source` is absolute, or a path under the site URL like `PageMeta.image`: the web gets the path under the host, native the absolute URL, and a relative one needs the site from `SeoProvider` or the `site` prop. `style` is a React Native image style that comes after the `width` and `height` box, so a size in `style` wins; set a side to `undefined` to let `flex` or `aspectRatio` size it. The web lays out the `<img>` as a react-native-web view, and flattens the style to CSS. `alt=""` marks a decorative image. diff --git a/packages/seo/README.md b/packages/seo/README.md index f40312fc..3691e21b 100644 --- a/packages/seo/README.md +++ b/packages/seo/README.md @@ -21,6 +21,7 @@ pnpm add @rootnative/seo | `@rootnative/seo/expo-router` | `expo-router` | `PageHead`, `RouteHead`, `shellTags` | | `@rootnative/seo/expo-image` | `expo-image` | `Picture`: a plain `<img>` on the web, `expo-image` on native | | `@rootnative/seo/dom` | `react`, `react-native` | `PageHead` for an app with no Expo Router: writes the same tags to `document.head` | +| `@rootnative/seo/web` | `react`, `react-native` | `PageHead` for an app with no Expo Router that renders on a server or prerenders: the same tags as elements, which React moves into the head | | `@rootnative/seo/node` | Node | `writeSeoFiles`, `auditExport`, `browseExport`, `serveExport`, the `rootnative-seo` command, `readExport`, `writeSitemap`, `writeRobots`, `writeManifest` | ## Quick start (Expo Router) diff --git a/packages/seo/llms.txt b/packages/seo/llms.txt index f226c9a8..b94f4a52 100644 --- a/packages/seo/llms.txt +++ b/packages/seo/llms.txt @@ -81,6 +81,10 @@ Each returns a `JsonLd` with `@context: 'https://schema.org'` and `@type` set. E - `<PageHead {...meta} site? active?>` — the same `PageMeta` props as the Expo Router `PageHead`, for an app with no Expo Router: React Navigation on react-native-web, a Vite build, an Electron renderer. Writes the `toHeadTags` records to `document.head` in an effect and takes them out on unmount, so the two adapters write the same head. A tag of the same name, property or `rel` that was there before, from the template or from a screen below, is taken out while this head is on and put back when it goes, and the `hreflang` links go as one set, so no language of the head below stays: a screen mounted over another wins, and the one below gets its head back. `active={false}` takes the head out for a screen that stays mounted behind another; a React Navigation screen passes `useIsFocused()`. Native renders `null`. An effect never runs on a server, so a static file gets its head from `headTagsHtml` at build time. +## `@rootnative/seo/web` — peers: react, react-native; no router + +- `<PageHead {...meta} site? active?>` — the same props as the `/dom` `PageHead`, for an app with no Expo Router that renders on a server or prerenders at build time. Renders the `toHeadTags` records as `<title>`, `<meta>` and `<link>` elements. React 19 moves them into `<head>`, on the server and in the browser, so the HTML file has the head and no `headTagsHtml` step is necessary. The JSON-LD is a `<script type="application/ld+json">` in the page body. After the first render it takes out the `<title>` and each head tag in a page slot that it did not render (the tags of the HTML template), and puts them back when it goes. React does not merge two heads: a screen that stays mounted behind another passes `active={false}` (with React Navigation, `useIsFocused()`), or the head holds the tags of both. Native renders `null`. Use `/dom` for an app that only renders in the browser and stacks screens: there, a screen mounted over another wins with no `active` prop. + ## `@rootnative/seo/expo-image` — optional peer: expo-image `>=57.0.0` - `<Picture source alt width height srcSet? sizes? contentFit? loading? fetchPriority? site? style? testID?>` — an image a crawler sees. On the web a plain `<img>` with `src`, `alt`, `width`, `height`, `loading` (default `lazy`), `decoding="async"` and `object-fit` from `contentFit` (default `cover`); on native `expo-image` with `alt` and `accessibilityLabel`. `srcSet` lists more files of the image as `{ source, width }`, with the width in pixels: the web writes `srcset` and `sizes`, so the browser picks a file by the shown width and the pixel density before any script runs, and native gives the files to `expo-image` in place of `source`, which picks one by the view size and the screen scale. Pass `sizes` with `srcSet`, for example `'160px'`; without it the browser takes `100vw`. `fetchPriority="high"` on the hero image, the one the page is built around: the web writes `fetchpriority`, so the browser starts that download before layout, and native gives `expo-image` the value as `priority`. `source` is absolute, or a path under the site URL like `PageMeta.image`: the web gets the path under the host, native the absolute URL, and a relative one needs the site from `SeoProvider` or the `site` prop. `style` is a React Native image style that comes after the `width` and `height` box, so a size in `style` wins; set a side to `undefined` to let `flex` or `aspectRatio` size it. The web lays out the `<img>` as a react-native-web view, and flattens the style to CSS. `alt=""` marks a decorative image. diff --git a/packages/seo/package.json b/packages/seo/package.json index a4c4adb7..930f2797 100644 --- a/packages/seo/package.json +++ b/packages/seo/package.json @@ -44,6 +44,12 @@ "import": "./dist/dom/index.mjs", "default": "./dist/dom/index.mjs" }, + "./web": { + "types": "./dist/web/index.d.mts", + "react-native": "./dist/web/index.mjs", + "import": "./dist/web/index.mjs", + "default": "./dist/web/index.mjs" + }, "./expo-image": { "types": "./dist/expo-image/index.d.mts", "react-native": "./dist/expo-image/index.mjs", @@ -70,6 +76,9 @@ "dom": [ "dist/dom/index.d.mts" ], + "web": [ + "dist/web/index.d.mts" + ], "expo-image": [ "dist/expo-image/index.d.mts" ], diff --git a/packages/seo/src/__tests__/web-head-server.test.tsx b/packages/seo/src/__tests__/web-head-server.test.tsx new file mode 100644 index 00000000..8c6aa620 --- /dev/null +++ b/packages/seo/src/__tests__/web-head-server.test.tsx @@ -0,0 +1,49 @@ +import { renderToString } from 'react-dom/server' +import { defineSite } from '../index' +import { SeoProvider } from '../react' +import { movie } from '../schema' +import { PageHead } from '../web' + +// The component renders nothing on native, and this project runs as native. +// `react-dom/server` needs a `MessageChannel`, which the `web` project does +// not have, so the server render is tested here. +jest.mock('react-native', () => ({ Platform: { OS: 'web' } })) + +const site = defineSite({ name: 'Trek', url: 'https://example.com/app' }) + +describe('PageHead from /web on a server', () => { + it('puts the head in the HTML', () => { + const html = renderToString( + <SeoProvider site={site}> + <PageHead + title="Dune" + description="A duke moves to a desert planet." + url="/movies/1" + alternates={[ + { lang: 'en', url: '/movies/1' }, + { lang: 'de', url: '/de/movies/1' }, + ]} + jsonLd={[ + movie({ name: 'Dune', url: 'https://example.com/app/movies/1' }), + ]} + /> + </SeoProvider>, + ) + expect(html).toContain('>Dune | Trek') + expect(html).toContain('content="A duke moves to a desert planet."') + expect(html).toContain( + '') + }) + + it('renders no tag while active is false', () => { + const html = renderToString( + + + , + ) + expect(html).toBe('') + }) +}) diff --git a/packages/seo/src/__tests__/web/web-head.web.test.tsx b/packages/seo/src/__tests__/web/web-head.web.test.tsx new file mode 100644 index 00000000..74260c20 --- /dev/null +++ b/packages/seo/src/__tests__/web/web-head.web.test.tsx @@ -0,0 +1,162 @@ +import { cleanup, render } from '@testing-library/react' +import { PageHead as DomPageHead } from '../../dom' +import { defineSite } from '../../index' +import { SeoProvider } from '../../react' +import { movie } from '../../schema' +import type { PageMeta } from '../../types' +import { PageHead } from '../../web' + +const site = defineSite({ + name: 'Trek', + url: 'https://example.com/app', + twitterSite: '@trek', +}) + +const dune: PageMeta = { + title: 'Dune', + description: 'A duke moves to a desert planet.', + url: '/movies/1', + image: '/posters/dune.jpg', + imageSize: { width: 1200, height: 630 }, + type: 'video.movie', + alternates: [ + { lang: 'en', url: '/movies/1' }, + { lang: 'de', url: '/de/movies/1' }, + ], + jsonLd: [movie({ name: 'Dune', url: 'https://example.com/app/movies/1' })], +} + +/** One line per head tag, with no renderer marker, sorted. */ +function headSignature(): string[] { + return Array.from(document.head.children) + .filter( + (node) => + node.tagName !== 'STYLE' && + node.tagName !== 'SCRIPT' && + !(node.tagName === 'TITLE' && node.textContent === ''), + ) + .map((node) => { + const attributes = Array.from(node.attributes) + .filter((attribute) => !attribute.name.startsWith('data-')) + .map((attribute) => `${attribute.name}="${attribute.value}"`) + .sort() + .join(' ') + return `${node.tagName.toLowerCase()} ${attributes} ${node.textContent}` + }) + .sort() +} + +function jsonLdTexts(root: ParentNode): string[] { + return Array.from( + root.querySelectorAll('script[type="application/ld+json"]'), + ).map((node) => node.textContent ?? '') +} + +function content(selector: string): string[] { + return Array.from(document.head.querySelectorAll(selector)).map( + (node) => node.getAttribute('content') ?? node.getAttribute('href') ?? '', + ) +} + +// React removes its own head tags on unmount, so the unmount comes first. +afterEach(() => { + cleanup() + document.head.innerHTML = '' + document.title = '' +}) + +describe('PageHead from /web', () => { + it('writes the same head as the /dom PageHead, from one PageMeta', () => { + const dom = render( + + + , + ) + const fromDom = headSignature() + const domTitle = document.title + const domJsonLd = jsonLdTexts(document) + dom.unmount() + + const { container } = render( + + + , + ) + expect(fromDom.length).toBeGreaterThan(10) + expect(headSignature()).toEqual(fromDom) + expect(document.title).toBe(domTitle) + expect(domJsonLd).toHaveLength(1) + expect(jsonLdTexts(container)).toEqual(domJsonLd) + }) + + it('replaces its tags on a change and takes them out on unmount', () => { + const { rerender, unmount } = render( + + + , + ) + expect(document.title).toBe('One | Trek') + expect(content('meta[name="description"]')).toEqual(['First']) + + rerender( + + + , + ) + expect(document.title).toBe('Two | Trek') + expect(content('meta[name="description"]')).toEqual([]) + expect(content('link[rel="canonical"]')).toEqual([ + 'https://example.com/app/two', + ]) + + unmount() + expect(headSignature()).toHaveLength(0) + expect(document.title).toBe('') + }) + + it('takes the template tags of its slots out while it is on, and puts them back', () => { + document.head.innerHTML = + 'Template' + const { unmount } = render( + + + , + ) + expect(document.title).toBe('Trailer | Trek') + expect(content('meta[name="description"]')).toEqual(['From the page']) + expect(content('meta[name="robots"]')).toEqual(['noindex']) + expect(content('link[rel="canonical"]')).toEqual([]) + expect(content('meta[property="og:image"]')).toEqual([]) + expect(document.head.querySelector('meta[charset]')).not.toBeNull() + + unmount() + expect(document.title).toBe('Template') + expect(content('meta[name="description"]')).toEqual(['From the template']) + expect(content('link[rel="canonical"]')).toEqual(['/template']) + expect(content('meta[property="og:image"]')).toEqual(['/template.jpg']) + }) + + it('renders no tag while active is false', () => { + const list = (active: boolean) => ( + + + {active ? null : ( + + )} + + ) + const { rerender, container } = render(list(false)) + expect(document.title).toBe('Item | Trek') + expect(content('meta[name="description"]')).toEqual(['The item']) + + rerender(list(true)) + expect(document.title).toBe('List | Trek') + expect(content('meta[name="description"]')).toEqual(['The list']) + expect(jsonLdTexts(container)).toHaveLength(0) + }) +}) diff --git a/packages/seo/src/web/PageHead.tsx b/packages/seo/src/web/PageHead.tsx new file mode 100644 index 00000000..eec6636a --- /dev/null +++ b/packages/seo/src/web/PageHead.tsx @@ -0,0 +1,123 @@ +import { useEffect } from 'react' +import { Platform } from 'react-native' +import { toHeadTags } from '../head' +import { inPageSlot } from '../headSlots' +import { pageLang } from '../lang' +import { useDocumentLang } from '../react/documentLang' +import { useSite } from '../react/SeoProvider' +import type { HeadTag, PageMeta, Site } from '../types' + +export type PageHeadProps = PageMeta & { + /** Wins over the site from `SeoProvider`. */ + site?: Site + /** + * `false` renders no tag, for a screen that stays mounted behind another. + * A React Navigation screen passes `useIsFocused()`. + * @default true + */ + active?: boolean +} + +/** On each head tag this component renders, so the sweep leaves it. */ +const OWNER = { 'data-rootnative-seo': '' } +const OWNER_ATTRIBUTE = 'data-rootnative-seo' + +function elementOf(tag: HeadTag, index: number) { + switch (tag.tag) { + case 'title': + return ( + + {tag.text} + + ) + case 'meta': + return 'name' in tag ? ( + + ) : ( + + ) + case 'link': + return ( + + ) + // React moves a title, a meta tag and a link into the head. It leaves a + // script with no `src` in place, and a crawler reads JSON-LD in the body. + case 'script': + return ( +