From 72c760e9b8e70dc4c8d4cc08f453d58a8928a0ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20M=C3=BCller?= Date: Thu, 1 Sep 2022 23:24:07 +0200 Subject: [PATCH] feat(image): throw if alt text is missing (#4511) * feat(image): throw if no `alt` is provided * chore: add changeset * docs(image): update README * updated alt text stuff throughout * fixing with-mdx test suite * warn for missing alt text, will throw an error in a future release * final README tweaks Co-authored-by: Tony Sullivan Co-authored-by: Sarah Rainsberger --- .changeset/polite-pears-hope.md | 5 ++ packages/integrations/image/README.md | 60 ++++++++++++------ .../integrations/image/components/Image.astro | 9 +++ .../image/components/Picture.astro | 11 +++- .../integrations/image/components/index.ts | 14 ++++ .../basic-image/src/pages/index.astro | 12 ++-- .../no-alt-text-image/astro.config.mjs | 8 +++ .../fixtures/no-alt-text-image/package.json | 10 +++ .../no-alt-text-image/public/favicon.ico | Bin 0 -> 4286 bytes .../no-alt-text-image/server/server.mjs | 44 +++++++++++++ .../no-alt-text-image/src/assets/social.jpg | Bin 0 -> 25266 bytes .../no-alt-text-image/src/pages/index.astro | 13 ++++ .../no-alt-text-picture/astro.config.mjs | 8 +++ .../fixtures/no-alt-text-picture/package.json | 10 +++ .../no-alt-text-picture/public/favicon.ico | Bin 0 -> 4286 bytes .../no-alt-text-picture/server/server.mjs | 44 +++++++++++++ .../no-alt-text-picture/src/assets/social.jpg | Bin 0 -> 25266 bytes .../no-alt-text-picture/src/pages/index.astro | 13 ++++ .../fixtures/rotation/src/pages/index.astro | 36 +++++------ .../fixtures/with-mdx/src/pages/index.mdx | 10 +-- .../image/test/no-alt-text-image-ssg.test.js | 24 +++++++ .../image/test/no-alt-text-image-ssr.test.js | 33 ++++++++++ .../test/no-alt-text-picture-ssg.test.js | 24 +++++++ .../test/no-alt-text-picture-ssr.test.js | 33 ++++++++++ pnpm-lock.yaml | 20 ++++++ 25 files changed, 391 insertions(+), 50 deletions(-) create mode 100644 .changeset/polite-pears-hope.md create mode 100644 packages/integrations/image/test/fixtures/no-alt-text-image/astro.config.mjs create mode 100644 packages/integrations/image/test/fixtures/no-alt-text-image/package.json create mode 100644 packages/integrations/image/test/fixtures/no-alt-text-image/public/favicon.ico create mode 100644 packages/integrations/image/test/fixtures/no-alt-text-image/server/server.mjs create mode 100644 packages/integrations/image/test/fixtures/no-alt-text-image/src/assets/social.jpg create mode 100644 packages/integrations/image/test/fixtures/no-alt-text-image/src/pages/index.astro create mode 100644 packages/integrations/image/test/fixtures/no-alt-text-picture/astro.config.mjs create mode 100644 packages/integrations/image/test/fixtures/no-alt-text-picture/package.json create mode 100644 packages/integrations/image/test/fixtures/no-alt-text-picture/public/favicon.ico create mode 100644 packages/integrations/image/test/fixtures/no-alt-text-picture/server/server.mjs create mode 100644 packages/integrations/image/test/fixtures/no-alt-text-picture/src/assets/social.jpg create mode 100644 packages/integrations/image/test/fixtures/no-alt-text-picture/src/pages/index.astro create mode 100644 packages/integrations/image/test/no-alt-text-image-ssg.test.js create mode 100644 packages/integrations/image/test/no-alt-text-image-ssr.test.js create mode 100644 packages/integrations/image/test/no-alt-text-picture-ssg.test.js create mode 100644 packages/integrations/image/test/no-alt-text-picture-ssr.test.js diff --git a/.changeset/polite-pears-hope.md b/.changeset/polite-pears-hope.md new file mode 100644 index 000000000..6facd8e89 --- /dev/null +++ b/.changeset/polite-pears-hope.md @@ -0,0 +1,5 @@ +--- +'@astrojs/image': minor +--- + +feat: throw if alt text is missing diff --git a/packages/integrations/image/README.md b/packages/integrations/image/README.md index 7557c4ecd..a1ffa25ae 100644 --- a/packages/integrations/image/README.md +++ b/packages/integrations/image/README.md @@ -18,7 +18,7 @@ This **[Astro integration][astro-integration]** makes it easy to optimize images Images play a big role in overall site performance and usability. Serving properly sized images makes all the difference but is often tricky to automate. -This integration provides `` and `` components as well as a basic image transformer powered by [sharp](https://sharp.pixelplumbing.com/), with full support for static sites and server-side rendering. The built-in `sharp` transformer is also replacable, opening the door for future integrations that work with your favorite hosted image service. +This integration provides `` and `` components as well as a basic image transformer powered by [sharp](https://sharp.pixelplumbing.com/), with full support for static sites and server-side rendering. The built-in `sharp` transformer is also replaceable, opening the door for future integrations that work with your favorite hosted image service. ## Installation @@ -90,6 +90,10 @@ import { Image, Picture } from '@astrojs/image/components'; The included `sharp` transformer supports resizing images and encoding them to different image formats. Third-party image services will be able to add support for custom transformations as well (ex: `blur`, `filter`, `rotate`, etc). +Astro’s and components require the alt attribute which provides descriptive text for images. A warning will be logged if "alt" text is missing, and a future release of the integration will throw an error if no alt text is provided. + +If the image is merely decorative (i.e. doesn’t contribute to the understanding of the page), set alt="" so that the image is properly understood and ignored by screen readers. + ### `` The built-in `` component is used to create an optimized `` for both remote images hosted on other domains as well as local images imported from your project's `src` directory. @@ -108,10 +112,22 @@ Source for the original image file. For images located in your project's `src`: use the file path relative to the `src` directory. (e.g. `src="../assets/source-pic.png"`) - For images located in your `public` directory: use the URL path relative to the `public` directory. (e.g. `src="/images/public-image.jpg"`) +For images located in your `public` directory: use the URL path relative to the `public` directory. (e.g. `src="/images/public-image.jpg"`) For remote images, provide the full URL. (e.g. `src="https://astro.build/assets/blog/astro-1-release-update.avif"`) +#### alt + +

+ +**Type:** `string`
+**Required:** `true` +

+ +Defines an alternative text description of the image. + +Set to an empty string (alt="") if the image is not a key part of the content (it's decoration or a tracking pixel). + #### format

@@ -186,17 +202,23 @@ A `number` can also be provided, useful when the aspect ratio is calculated at b Source for the original image file. -For images in your project's repository, use the path relative to the `src` or `public` directory. For remote images, provide the full URL. +For images located in your project's `src`: use the file path relative to the `src` directory. (e.g. `src="../assets/source-pic.png"`) + +For images located in your `public` directory: use the URL path relative to the `public` directory. (e.g. `src="/images/public-image.jpg"`) + +For remote images, provide the full URL. (e.g. `src="https://astro.build/assets/blog/astro-1-release-update.avif"`) #### alt

**Type:** `string`
-**Default:** `undefined` +**Required:** `true`

-If provided, the `alt` string will be included on the built `` element. +Defines an alternative text description of the image. + +Set to an empty string (alt="") if the image is not a key part of the content (it's decoration or a tracking pixel). #### sizes @@ -266,7 +288,7 @@ const { src } = await getImage('../assets/hero.png'); - + ``` @@ -330,19 +352,19 @@ import heroImage from '../assets/hero.png'; --- // optimized image, keeping the original width, height, and image format - +descriptive text // height will be recalculated to match the original aspect ratio - +descriptive text // cropping to a specific width and height - +descriptive text // cropping to a specific aspect ratio and converting to an avif format - +descriptive text // image imports can also be inlined directly - +descriptive text ``` #### Images in `/public` @@ -356,11 +378,11 @@ For example, use an image located at `public/social.png` in either static or SSR ```astro title="src/pages/page.astro" --- import { Image } from '@astrojs/image/components'; -import socialImage from '/social.png'; +import socialImage from '/social.png'; --- // In static builds: the image will be built and optimized to `/dist`. // In SSR builds: the image will be optimized by the server when requested by a browser. - +descriptive text ``` ### Remote images @@ -375,13 +397,13 @@ const imageUrl = 'https://www.google.com/images/branding/googlelogo/2x/googlelog --- // cropping to a specific width and height - +descriptive text // height will be recalculated to match the aspect ratio - +descriptive text // cropping to a specific height and aspect ratio and converting to an avif format - +descriptive text ``` ### Responsive pictures @@ -401,13 +423,13 @@ const imageUrl = 'https://www.google.com/images/branding/googlelogo/2x/googlelog --- // Local image with multiple sizes - + // Remote image (aspect ratio is required) - + // Inlined imports are supported - + ``` ## Troubleshooting diff --git a/packages/integrations/image/components/Image.astro b/packages/integrations/image/components/Image.astro index 20efe6ee0..1777fffab 100644 --- a/packages/integrations/image/components/Image.astro +++ b/packages/integrations/image/components/Image.astro @@ -1,6 +1,7 @@ --- // @ts-ignore import { getImage } from '../dist/index.js'; +import { warnForMissingAlt } from './index.js'; import type { ImgHTMLAttributes } from './index.js'; import type { ImageMetadata, TransformOptions, OutputFormat } from '../dist/index.js'; @@ -8,10 +9,14 @@ interface LocalImageProps extends Omit, Omit { src: ImageMetadata | Promise<{ default: ImageMetadata }>; + /** Defines an alternative text description of the image. Set to an empty string (alt="") if the image is not a key part of the content (it's decoration or a tracking pixel). */ + alt: string; } interface RemoteImageProps extends TransformOptions, astroHTML.JSX.ImgHTMLAttributes { src: string; + /** Defines an alternative text description of the image. Set to an empty string (alt="") if the image is not a key part of the content (it's decoration or a tracking pixel). */ + alt: string; format: OutputFormat; width: number; height: number; @@ -21,6 +26,10 @@ export type Props = LocalImageProps | RemoteImageProps; const { loading = 'lazy', decoding = 'async', ...props } = Astro.props as Props; +if (props.alt === undefined || props.alt === null) { + warnForMissingAlt(); +} + const attrs = await getImage(props); --- diff --git a/packages/integrations/image/components/Picture.astro b/packages/integrations/image/components/Picture.astro index 36eab92b8..7fe43d9db 100644 --- a/packages/integrations/image/components/Picture.astro +++ b/packages/integrations/image/components/Picture.astro @@ -1,5 +1,6 @@ --- import { getPicture } from '../dist/index.js'; +import { warnForMissingAlt } from './index.js'; import type { ImgHTMLAttributes, HTMLAttributes } from './index.js'; import type { ImageMetadata, OutputFormat, TransformOptions } from '../dist/index.js'; @@ -8,7 +9,8 @@ interface LocalImageProps Omit, Pick { src: ImageMetadata | Promise<{ default: ImageMetadata }>; - alt?: string; + /** Defines an alternative text description of the image. Set to an empty string (alt="") if the image is not a key part of the content (it's decoration or a tracking pixel). */ + alt: string; sizes: HTMLImageElement['sizes']; widths: number[]; formats?: OutputFormat[]; @@ -19,7 +21,8 @@ interface RemoteImageProps TransformOptions, Pick { src: string; - alt?: string; + /** Defines an alternative text description of the image. Set to an empty string (alt="") if the image is not a key part of the content (it's decoration or a tracking pixel). */ + alt: string; sizes: HTMLImageElement['sizes']; widths: number[]; aspectRatio: TransformOptions['aspectRatio']; @@ -40,6 +43,10 @@ const { ...attrs } = Astro.props as Props; +if (alt === undefined || alt === null) { + warnForMissingAlt(); +} + const { image, sources } = await getPicture({ src, widths, formats, aspectRatio }); --- diff --git a/packages/integrations/image/components/index.ts b/packages/integrations/image/components/index.ts index 89d8edd03..6a8f420ad 100644 --- a/packages/integrations/image/components/index.ts +++ b/packages/integrations/image/components/index.ts @@ -11,3 +11,17 @@ export type HTMLAttributes = Omit< astroHTML.JSX.HTMLAttributes, 'client:list' | 'set:text' | 'set:html' | 'is:raw' >; + +let altWarningShown = false; + +export function warnForMissingAlt() { + if (altWarningShown === true) { return } + + altWarningShown = true; + + console.warn(`\n[@astrojs/image] "alt" text was not provided for an or component. + +A future release of @astrojs/image may throw a build error when "alt" text is missing. + +The "alt" attribute holds a text description of the image, which isn't mandatory but is incredibly useful for accessibility. Set to an empty string (alt="") if the image is not a key part of the content (it's decoration or a tracking pixel).\n`); +} diff --git a/packages/integrations/image/test/fixtures/basic-image/src/pages/index.astro b/packages/integrations/image/test/fixtures/basic-image/src/pages/index.astro index 4ded85521..6b203591b 100644 --- a/packages/integrations/image/test/fixtures/basic-image/src/pages/index.astro +++ b/packages/integrations/image/test/fixtures/basic-image/src/pages/index.astro @@ -9,16 +9,16 @@ import { Image } from '@astrojs/image/components'; - + hero
- + spaces
- + social-jpg
- + Google
- + inline
- + query diff --git a/packages/integrations/image/test/fixtures/no-alt-text-image/astro.config.mjs b/packages/integrations/image/test/fixtures/no-alt-text-image/astro.config.mjs new file mode 100644 index 000000000..7dafac3b6 --- /dev/null +++ b/packages/integrations/image/test/fixtures/no-alt-text-image/astro.config.mjs @@ -0,0 +1,8 @@ +import { defineConfig } from 'astro/config'; +import image from '@astrojs/image'; + +// https://astro.build/config +export default defineConfig({ + site: 'http://localhost:3000', + integrations: [image({ logLevel: 'silent' })] +}); diff --git a/packages/integrations/image/test/fixtures/no-alt-text-image/package.json b/packages/integrations/image/test/fixtures/no-alt-text-image/package.json new file mode 100644 index 000000000..10c615cd5 --- /dev/null +++ b/packages/integrations/image/test/fixtures/no-alt-text-image/package.json @@ -0,0 +1,10 @@ +{ + "name": "@test/no-alt-text-image", + "version": "0.0.0", + "private": true, + "dependencies": { + "@astrojs/image": "workspace:*", + "@astrojs/node": "workspace:*", + "astro": "workspace:*" + } +} diff --git a/packages/integrations/image/test/fixtures/no-alt-text-image/public/favicon.ico b/packages/integrations/image/test/fixtures/no-alt-text-image/public/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..578ad458b8906c08fbed84f42b045fea04db89d1 GIT binary patch literal 4286 zcmchZF=!M)6ox0}Fc8GdTHG!cdIY>nA!3n2f|wxIl0rn}Hl#=uf>?-!2r&jMEF^_k zh**lGut*gwBmoNv7AaB&2~nbzULg{WBhPQ{ZVzvF_HL8Cb&hv$_s#qN|IO^o>?+mA zuTW6tU%k~z<&{z+7$G%*nRsTcEO|90xy<-G5&JTt%CgZZCDT4%R?+{Vd^wh>P8_)} z`+dF$HQb9!>1o`Ivn;GInlCw{9T@Rt%q+d^T3Ke%cxkk;$v`{s^zCB9nHAv6w$Vbn z8fb<+eQTNM`;rf9#obfGnV#3+OQEUv4gU;{oA@zol%keY9-e>4W>p7AHmH~&!P7f7!Uj` zwgFeQ=<3G4O;mwWO`L!=R-=y3_~-DPjH3W^3f&jjCfC$o#|oGaahSL`_=f?$&Aa+W z2h8oZ+@?NUcjGW|aWJfbM*ZzxzmCPY`b~RobNrrj=rd`=)8-j`iSW64@0_b6?;GYk zNB+-fzOxlqZ?`y{OA$WigtZXa8)#p#=DPYxH=VeC_Q5q9Cv`mvW6*zU&Gnp1;oPM6 zaK_B3j(l^FyJgYeE9RrmDyhE7W2}}nW%ic#0v@i1E!yTey$W)U>fyd+!@2hWQ!Wa==NAtKoj`f3tp4y$Al`e;?)76?AjdaRR>|?&r)~3Git> zb1)a?uiv|R0_{m#A9c;7)eZ1y6l@yQ#oE*>(Z2fG-&&smPa2QTW>m*^K65^~`coP$ z8y5Y?iS<4Gz{Zg##$1mk)u-0;X|!xu^FCr;ce~X<&UWE&pBgqfYmEJTzpK9I%vr%b z3Ksd6qlPJLI%HFfeXK_^|BXiKZC>Ocu(Kk6hD3G-8usLzVG^q00Qh gz)s7ge@$ApxGu7=(6IGIk+uG&HTev01^#CH3$(Wk5&!@I literal 0 HcmV?d00001 diff --git a/packages/integrations/image/test/fixtures/no-alt-text-image/server/server.mjs b/packages/integrations/image/test/fixtures/no-alt-text-image/server/server.mjs new file mode 100644 index 000000000..d7a0a7a40 --- /dev/null +++ b/packages/integrations/image/test/fixtures/no-alt-text-image/server/server.mjs @@ -0,0 +1,44 @@ +import { createServer } from 'http'; +import fs from 'fs'; +import mime from 'mime'; +import { handler as ssrHandler } from '../dist/server/entry.mjs'; + +const clientRoot = new URL('../dist/client/', import.meta.url); + +async function handle(req, res) { + ssrHandler(req, res, async (err) => { + if (err) { + res.writeHead(500); + res.end(err.stack); + return; + } + + let local = new URL('.' + req.url, clientRoot); + try { + const data = await fs.promises.readFile(local); + res.writeHead(200, { + 'Content-Type': mime.getType(req.url), + }); + res.end(data); + } catch { + res.writeHead(404); + res.end(); + } + }); +} + +const server = createServer((req, res) => { + handle(req, res).catch((err) => { + console.error(err); + res.writeHead(500, { + 'Content-Type': 'text/plain', + }); + res.end(err.toString()); + }); +}); + +server.listen(8085); +console.log('Serving at http://localhost:8085'); + +// Silence weird