Socket
Socket
Sign inDemoInstall

@double-great/alt-text

Package Overview
Dependencies
3
Maintainers
2
Versions
17
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 2.0.0 to 3.0.0

.eslintrc.cjs

4

CHANGELOG.md
# Changelog
## 3.0.0
- Add configuration options to disable any rule and change the defaults for some rules that check against specific values.
## 2.0.0

@@ -4,0 +8,0 @@

42

dist/clues.d.ts

@@ -1,30 +0,28 @@

export interface Rule {
/** The name of the rule */
import { Alt, ConfigOption } from ".";
export declare type ClueProps = {
id: string;
heading: string;
/** Shortened URL to the rule's documentation. */
docs: string;
/** Recommendation on how to fix the rule. */
suggestion: (value?: number | string) => string;
/** Explanation of the rule and why it's important. */
rationale: string;
/** URLs to external sources to support the rule. */
source: string[];
/** Example of the correct usage. */
ok: string;
/** Example of the incorrect usage. */
notOk: string;
/** If available, URL to https://doublegreat.dev/listen/ test case to support the rule. */
listen?: string;
/** If applicable, list of strings to test the rule against. */
rules?: string[];
/** If applicable, a function to test the rule against the current `alt` value. */
fn?: (item: string, alt: string) => string | boolean;
};
export default class Clue {
id: string;
heading: string;
docs: string;
rationale: string;
source: string[];
ok: string;
notOk: string;
listen?: string;
recommendation: string;
config: any;
constructor(props: ClueProps);
check(alt: Alt, config?: ConfigOption): string | [] | string[];
setRecommendation(): void;
suggestion(): string;
document(): string;
}
/**
* Suggestions to improve alt text.
*/
interface Clue {
[rule: string]: Rule;
}
export declare const clues: Clue;
export {};

@@ -1,182 +0,58 @@

export const clues = {
notOnlySpace: {
heading: "Empty alt text",
docs: "https://tinyurl.com/y2o7uctu",
suggestion: () => `Alt text should not be a single space`,
rationale: 'If you use null (empty) alt text (`alt=""`) to hide decorative images, make sure that there is no space character in between the quotes. **If a space character is present, the image may not be effectively hidden from assistive technologies.** For instance, some screen readers will still announce the presence of an image if a space character is put between the quotes.',
source: ["https://www.w3.org/WAI/tutorials/images/tips/#tips"],
ok: '`<img src="photo.png" alt="">`',
notOk: '`<img src="photo.png" alt=" ">`',
},
charLength: {
heading: "Character length",
docs: "https://tinyurl.com/y2f7rhao",
suggestion: (value) => `Alt text length should be less than 125 characters${value ? `, it is currently ${value} characters` : ""}`,
rationale: "Alt text should be less than 125 characters in length. The JAWS screen reader reads alt text in 125 character chunks. Any information about the image, such as copyright information, image source or extra information should be placed in the caption text below the image.",
source: [
"https://accessibility.psu.edu/images/imageshtml/#alt",
"https://terrillthompson.com/tests/altlength.html",
],
ok: "George Washington and Lafayette on horseback talking to soldiers in snow at Valley Forge.",
notOk: "Caption: Painting “Washington and Lafayette at Valley Forge” by John Ward Dunsmore from 1907. Image courtesy of the Library of Congress.",
},
imageLink: {
heading: "Image is link",
docs: "https://tinyurl.com/yxhq2k5w",
suggestion: () => `Images inside a link tag require alt text that describes the purpose of the link`,
rationale: "Images inside a link tag require alt text that describes the purpose of the link.",
source: ["https://axesslab.com/alt-texts/#images-in-links"],
ok: '`<a href="https://github.com/double-great"><img src="logo.png" alt="double great on GitHub"></a>`',
notOk: '`<a href="https://github.com/double-great"><img src="logo.png" alt="double great logo"></a>`',
},
endPunctuation: {
heading: "End with punctuation",
docs: "https://tinyurl.com/y5krn3ny",
suggestion: () => `Alt text should end with punctuation`,
rationale: "End the alt text with a period, exclamation point, or question mark. This will make screen readers pause a bit after the last word in the alt text, which creates a more pleasant reading experience for the user.",
listen: "https://doublegreat.dev/listen/punctuation-in-alt-text/",
source: ["https://axesslab.com/alt-texts/#end-with-a-period"],
ok: "A child holding a photograph.",
notOk: "A child holding a photograph",
},
noAlt: {
heading: "Missing alt attribute",
docs: "https://tinyurl.com/yybc6bsy",
suggestion: () => `Missing "alt" attribute`,
rationale: "All images must have alternate text to convey their purpose and meaning to screen reader users.",
source: ["https://dequeuniversity.com/rules/axe/3.4/image-alt"],
ok: '`<img src="photograph.jpg" alt="A child holding a photograph.">`',
notOk: '`<img src="photograph.jpg">`',
},
contains: {
heading: "Alt text contains unhelpful words",
docs: "https://tinyurl.com/y3v3jgux",
fn: (item, alt) => alt.includes(item),
suggestion: (value) => `Alt text should not contain "${value}"`,
rules: [
"picture of",
"photo of",
"photograph of",
"image of",
"graphic of",
"screenshot of",
"screen shot of",
"photo:",
"photographer:",
],
rationale: "Screen readers announce the presence of an image before reading the alt text. Adding “picture of” or “photo of” is redundant in this context.",
source: [
"https://www.w3.org/WAI/tutorials/images/tips/#tips",
"https://axesslab.com/alt-texts/#dont-say-its-an-image",
],
ok: "Dog jumping through a hoop.",
notOk: "Image of a dog jumping through a hoop.",
},
exactMatch: {
heading: "Alt text is unhelpful",
docs: "https://tinyurl.com/yxwc2hof",
fn: (item, alt) => item == alt.trim(),
suggestion: (value) => `Alt text should not be "${value}"`,
rules: [
"image",
"icon",
"graphic",
"photo",
"photograph",
"placeholder",
"temp",
"alt",
"drawing",
"painting",
"artwork",
"logo",
"bullet",
"button",
"arrow",
"more",
"spacer",
"screenshot",
"screen shot",
"blank",
"empty",
"chart",
"table",
"diagram",
"graph",
"*",
],
rationale: "Usually, there’s no need to include words like “image”, “icon”, or “picture” in the alt text. People who can see will know this already, and screen readers announce the presence of an image.",
source: [
"https://www.w3.org/WAI/tutorials/images/tips/#tips",
"https://axesslab.com/alt-texts/#dont-say-its-an-image",
],
ok: "A child holding a photograph.",
notOk: "photograph",
},
endWith: {
heading: "Alt text should not end with",
docs: "https://tinyurl.com/yy2q8bbb",
fn: (item, alt) => alt.endsWith(item),
suggestion: (value) => `Alt text should not end with "${value}"`,
rules: [
".jpg",
".jpeg",
".gif",
".png",
".svg",
".webp",
"image",
"graphic",
],
rationale: "A file name in alt text does not provide helpful context.",
source: ["https://axesslab.com/alt-texts/"],
ok: "A child holding a photograph.",
notOk: "photograph.jpg",
},
startWith: {
heading: "Alt text should not start with",
docs: "https://tinyurl.com/y5y98ygu",
fn: (item, alt) => alt.startsWith(item),
suggestion: (value) => `Alt text should not start with "${value}"`,
rules: [
"picture",
"photo",
"photograph",
"photographer",
"image",
"graphic",
"screenshot",
"screen shot",
"spacer",
],
rationale: "Usually, there’s no need to include words like “image”, “icon”, or “picture” in the alt text. People who can see will know this already, and screen readers announce the presence of an image.",
source: [
"https://www.w3.org/WAI/tutorials/images/tips/#tips",
"https://axesslab.com/alt-texts/#dont-say-its-an-image",
],
ok: "A child holding a photograph.",
notOk: "Image of a child.",
},
decorative: {
heading: "Image is decorative",
docs: "https://tinyurl.com/yxnvejgv",
suggestion: () => `Empty alt text should only be used for decorative images`,
rationale: `Provide "null" \`alt\` attributes (using \`alt=""\`) for images which do not provide information or do not require alternative text because the image is described in the page content. Some developers will mistakenly leave off the alt attribute altogether on images which they deem do not need alternatives. This is not helpful to assistive technology users because the assistive technology, such as screen reader, will often read the source attribute (i.e., file name) as the alternative text. To tell assistive technology to ignore an image, use a "blank alternative text" attribute: \`alt=""\`.`,
source: ["https://dequeuniversity.com/rules/axe/3.0/image-alt"],
ok: '`<img src="decorative-photo.jpg" alt="">`',
notOk: '`<img src="quarterly-earnings-chart.png" alt=""/>`',
},
avoidEmoji: {
heading: "Avoid emoji",
docs: "https://tinyurl.com/yylrxrus",
suggestion: (value) => `Replace ${value || "emoji"} in alt text with descriptive text`,
rationale: `Emoji have their own text descriptions. These descriptions can vary between operating systems and software. The spoken description of the emoji may not match your visual intention.`,
listen: "https://doublegreat.dev/listen/emoji/",
source: [
"https://www.youtube.com/watch?v=uIbPcZq6izk",
"https://readabilityguidelines.co.uk/images/emojis/",
],
ok: '`<img src="cat.jpg" alt="An orange cat.">`',
notOk: '`<img src="cat.png" alt="An orange 🐈."/>`',
},
};
import pkg from "prettier";
const { format } = pkg;
export default class Clue {
constructor(props) {
this.id = props.id;
this.heading = props.heading;
this.docs = props.docs;
this.rationale = props.rationale;
this.source = props.source;
this.ok = props.ok;
this.notOk = props.notOk;
this.listen = props.listen;
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
check(alt, config) {
throw new Error("check() method not implemented.");
}
setRecommendation() {
throw new Error("setRecommendation() method not implemented.");
}
suggestion() {
return `${this.recommendation} (${this.docs}).`;
}
document() {
const codeDisable = format(`altText('My alt text.', ${JSON.stringify({
[this.id]: false,
})})`, { parser: "babel" });
const codeOptions = format(`altText("My alt text.", ${JSON.stringify({
[this.id]: this.config,
})})`, { parser: "babel" });
return `### ${this.heading}
Suggestion: \`${this.recommendation}\`
${this.rationale}
- ✅ ${this.ok}
- 🚫 ${this.notOk}
${this.listen
? `
Hear an example: <${this.listen}>
`
: ""}
Configuration:
\`\`\`js
// disable the rule:
${codeDisable}${this.config
? `
// adjust rule defaults:
${codeOptions}`
: ""}\`\`\`
Sources:
${this.source.map((link) => `- <${link}>\n`).join("")}`;
}
}

@@ -1,2 +0,1 @@

export declare type Alt = string;
/**

@@ -8,2 +7,31 @@ * Check for unhelpful alt text.

*/
export default function altText(alt?: Alt): string | undefined;
export default function altText(alt: string | undefined, config?: Config): string | undefined;
export declare const defaultConfig: Config;
export declare type Alt = string;
export declare type Config = {
[key: string]: any;
"image-is-decorative"?: boolean;
"avoid-emoji"?: boolean;
"contains-unhelpful-word"?: boolean | {
exclude: string[];
};
"character-length"?: boolean | {
length: number;
};
"end-with-punctuation"?: boolean;
"should-not-end-with"?: boolean | {
exclude: string[];
};
"is-unhelpful"?: boolean | {
exclude: string[];
};
"should-not-start-with"?: boolean | {
exclude: string[];
};
"empty-alt-text"?: boolean;
"image-is-link"?: boolean;
};
export declare type ConfigOption = boolean | {
exclude?: string[];
length?: number;
};

@@ -1,2 +0,10 @@

import { checkClue, checkPunctuation, checkLength, checkOnlySpace, checkEmoji, createSuggestion, } from "./rules.js";
import avoidEmoji from "./clues/avoid-emoji.js";
import charLength from "./clues/char-length.js";
import altContains from "./clues/contains.js";
import decorative from "./clues/decorative.js";
import endPunctuation from "./clues/end-punctuation.js";
import altEndsWith from "./clues/end-with.js";
import exactMatch from "./clues/exact-match.js";
import notOnlySpace from "./clues/not-only-space.js";
import altStartsWith from "./clues/start-with.js";
/**

@@ -8,14 +16,49 @@ * Check for unhelpful alt text.

*/
export default function altText(alt) {
if (!alt)
return createSuggestion("decorative");
alt = alt.toLowerCase();
const suggestion = [
...checkClue(alt),
...checkLength(alt),
...checkOnlySpace(alt),
...checkPunctuation(alt),
...checkEmoji(alt),
export default function altText(alt, config) {
// lowercase alt text to improve parsing
alt = alt === null || alt === void 0 ? void 0 : alt.toLowerCase();
// take into account user configuration settings
config = Object.assign(Object.assign({}, defaultConfig), config);
// if no alt text, throw image is decorative (if enabled)
if (!alt && config["image-is-decorative"] !== false) {
return decorative.check();
}
else if (!alt)
return undefined;
// list of rules
const rules = [
avoidEmoji,
altContains,
charLength,
endPunctuation,
altEndsWith,
exactMatch,
altStartsWith,
notOnlySpace,
];
// check all rules
let suggestion = [];
for (const rule of rules) {
// get the rule's id
const ruleConfig = config[rule.id];
// skip rule if it is diabled
if (ruleConfig === false)
continue;
// check rule and add any suggestions
suggestion = [...suggestion, ...rule.check(alt, ruleConfig)];
}
// return suggestions, if any
return suggestion.length ? suggestion.join(" ") : undefined;
}
export const defaultConfig = {
"image-is-decorative": true,
"avoid-emoji": true,
"contains-unhelpful-word": true,
"character-length": true,
"end-with-punctuation": true,
"should-not-end-with": true,
"is-unhelpful": true,
"should-not-start-with": true,
"empty-alt-text": true,
"image-is-link": true,
};
{
"name": "@double-great/alt-text",
"version": "2.0.0",
"version": "3.0.0",
"description": "Check for unhelpful alt text.",

@@ -9,7 +9,8 @@ "main": "dist/index.js",

"scripts": {
"lint": "eslint . --fix",
"lint": "eslint . --ext .js,.ts",
"pretest": "npm run lint",
"test": "jest",
"pretty-quick": "pretty-quick",
"write-docs": "tsc && node scripts/write-docs.js",
"write-docs": "tsc && node dist/docs.js",
"build": "tsc",
"prepublishOnly": "pinst --disable && tsc",

@@ -29,3 +30,3 @@ "postpublish": "pinst --enable"

"dependencies": {
"emoji-regex": "^10.0.0",
"emoji-regex": "^10.0.1",
"github-slugger": "^1.4.0",

@@ -35,16 +36,17 @@ "tinyurl": "^1.1.7"

"devDependencies": {
"@babel/eslint-parser": "^7.16.5",
"@babel/preset-env": "^7.16.8",
"@babel/preset-env": "^7.16.11",
"@babel/preset-typescript": "^7.16.7",
"@types/github-slugger": "^1.3.0",
"@types/jest": "^27.4.0",
"@types/node": "^17.0.8",
"eslint": "^8.6.0",
"eslint-config-prettier": "^8.3.0",
"husky": "^7.0.2",
"jest": "^27.4.7",
"pinst": "^2.1.6",
"@types/node": "^17.0.18",
"@typescript-eslint/eslint-plugin": "^5.15.0",
"@typescript-eslint/parser": "^5.15.0",
"eslint": "^8.11.0",
"eslint-config-prettier": "^8.5.0",
"husky": "^7.0.4",
"jest": "^27.5.1",
"pinst": "^3.0.0",
"prettier": "^2.5.1",
"pretty-quick": "^3.1.3",
"typescript": "^4.5.4"
"typescript": "^4.6.2"
},

@@ -60,6 +62,10 @@ "directories": {

"moduleNameMapper": {
"^./clues.js$": "<rootDir>/src/clues.ts",
"^./rules.js$": "<rootDir>/src/rules.ts"
}
"./clues.js$": "<rootDir>/src/clues.ts",
"./utils.js$": "<rootDir>/src/clues/utils.ts",
"./docs.js$": "<rootDir>/src/docs.ts",
"^./clues/(.*).js$": "<rootDir>/src/clues/$1.ts",
"..?/index.js$": "<rootDir>/src/index.ts"
},
"clearMocks": true
}
}

@@ -9,3 +9,3 @@ # alt-text ![Build Status](https://github.com/double-great/alt-text/workflows/Test/badge.svg)

`altText` checks for common issues found in alt text and suggests improvements.
This library checks for common issues found in alt text and suggests improvements.

@@ -22,3 +22,3 @@ Are you writing in markdown? We recommend using [remark-lint-alt-text](https://github.com/double-great/remark-lint-alt-text).

If `altText` detects an issue, it will return a suggestion to help you fix it. If `altText` doesn't detect any issues it will return `undefined`.
If the library detects an issue, it will return a suggestion to help you fix it. If it doesn't detect any issues it will return `undefined`.

@@ -32,5 +32,16 @@ ```js

console.log(altText("A photo of a dog"));
// Alt text should not contain "photo of" (https://git.io/JvqAM). Alt text should end with punctuation (https://git.io/JJk55).
// Alt text should not contain "photo of" (https://tinyurl.com/y3v3jgux). Alt text should end with punctuation (https://tinyurl.com/y5krn3ny).
```
The library is configured with best practices, but context is always important. You can disable any rule and pass custom configuration options for those that check against specific values.
Example:
```js
console.log(altText("A photo of a dog", { "end-with-punctuation": false }));
// Alt text should not contain "photo of" (https://tinyurl.com/y3v3jgux).
```
Each rule in the suggestions list below has full documentation on configuration options.
## Suggestions

@@ -40,2 +51,14 @@

- [Alt text contains unhelpful words (`contains-unhelpful-word`)](#alt-text-contains-unhelpful-words)
- [Alt text is unhelpful (`is-unhelpful`)](#alt-text-is-unhelpful)
- [Alt text should not end with (`should-not-end-with`)](#alt-text-should-not-end-with)
- [Alt text should not start with (`should-not-start-with`)](#alt-text-should-not-start-with)
- [Avoid emoji (`avoid-emoji`)](#avoid-emoji)
- [Character length (`character-length`)](#character-length)
- [Empty alt text (`empty-alt-text`)](#empty-alt-text)
- [End with punctuation (`end-with-punctuation`)](#end-with-punctuation)
- [Image is decorative (`image-is-decorative`)](#image-is-decorative)
- [Image is link (`image-is-link`)](#image-is-link)
- [Missing alt attribute (`no-alt`)](#missing-alt-attribute)
### Alt text contains unhelpful words

@@ -50,2 +73,26 @@

Configuration:
```js
// disable the rule:
altText("My alt text.", { "contains-unhelpful-word": false });
// adjust rule defaults:
altText("My alt text.", {
"contains-unhelpful-word": {
exclude: [
"graphic of",
"image of",
"photo of",
"photo:",
"photograph of",
"photographer:",
"picture of",
"screen shot of",
"screenshot of",
],
},
});
```
Sources:

@@ -65,2 +112,43 @@

Configuration:
```js
// disable the rule:
altText("My alt text.", { "is-unhelpful": false });
// adjust rule defaults:
altText("My alt text.", {
"is-unhelpful": {
exclude: [
"*",
"alt",
"arrow",
"artwork",
"blank",
"bullet",
"button",
"chart",
"diagram",
"drawing",
"empty",
"graph",
"graphic",
"icon",
"image",
"logo",
"more",
"painting",
"photo",
"photograph",
"placeholder",
"screen shot",
"screenshot",
"spacer",
"table",
"temp",
],
},
});
```
Sources:

@@ -80,2 +168,25 @@

Configuration:
```js
// disable the rule:
altText("My alt text.", { "should-not-end-with": false });
// adjust rule defaults:
altText("My alt text.", {
"should-not-end-with": {
exclude: [
".gif",
".jpeg",
".jpg",
".png",
".svg",
".webp",
"graphic",
"image",
],
},
});
```
Sources:

@@ -94,2 +205,26 @@

Configuration:
```js
// disable the rule:
altText("My alt text.", { "should-not-start-with": false });
// adjust rule defaults:
altText("My alt text.", {
"should-not-start-with": {
exclude: [
"graphic",
"image",
"photo",
"photograph",
"photographer",
"picture",
"screen shot",
"screenshot",
"spacer",
],
},
});
```
Sources:

@@ -111,2 +246,9 @@

Configuration:
```js
// disable the rule:
altText("My alt text.", { "avoid-emoji": false });
```
Sources:

@@ -126,2 +268,12 @@

Configuration:
```js
// disable the rule:
altText("My alt text.", { "character-length": false });
// adjust rule defaults:
altText("My alt text.", { "character-length": { length: 125 } });
```
Sources:

@@ -141,2 +293,9 @@

Configuration:
```js
// disable the rule:
altText("My alt text.", { "empty-alt-text": false });
```
Sources:

@@ -157,2 +316,9 @@

Configuration:
```js
// disable the rule:
altText("My alt text.", { "end-with-punctuation": false });
```
Sources:

@@ -171,2 +337,9 @@

Configuration:
```js
// disable the rule:
altText("My alt text.", { "image-is-decorative": false });
```
Sources:

@@ -185,2 +358,9 @@

Configuration:
```js
// disable the rule:
altText("My alt text.", { "image-is-link": false });
```
Sources:

@@ -199,4 +379,11 @@

Configuration:
```js
// disable the rule:
altText("My alt text.", { "no-alt": false });
```
Sources:
- <https://dequeuniversity.com/rules/axe/3.4/image-alt>
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc