Skip to content

Commit

Permalink
Merge pull request #815 from sveltejs/gh-374
Browse files Browse the repository at this point in the history
a11y checks
  • Loading branch information
Rich-Harris authored Sep 5, 2017
2 parents 66c382a + 7c6ea13 commit ad59771
Show file tree
Hide file tree
Showing 74 changed files with 686 additions and 232 deletions.
2 changes: 1 addition & 1 deletion src/generators/dom/preprocess.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import Block from './Block';
import { trimStart, trimEnd } from '../../utils/trim';
import { assign } from '../../shared/index.js';
import getStaticAttributeValue from '../shared/getStaticAttributeValue';
import getStaticAttributeValue from '../../utils/getStaticAttributeValue';
import { DomGenerator } from './index';
import { Node } from '../../interfaces';
import { State } from './interfaces';
Expand Down
2 changes: 1 addition & 1 deletion src/generators/dom/visitors/Element/Attribute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import deindent from '../../../../utils/deindent';
import visitStyleAttribute, { optimizeStyle } from './StyleAttribute';
import { stringify } from '../../../../utils/stringify';
import getExpressionPrecedence from '../../../../utils/getExpressionPrecedence';
import getStaticAttributeValue from '../../../shared/getStaticAttributeValue';
import getStaticAttributeValue from '../../../../utils/getStaticAttributeValue';
import { DomGenerator } from '../../index';
import Block from '../../Block';
import { Node } from '../../../../interfaces';
Expand Down
2 changes: 1 addition & 1 deletion src/generators/dom/visitors/Element/Binding.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import deindent from '../../../../utils/deindent';
import flattenReference from '../../../../utils/flattenReference';
import getStaticAttributeValue from '../../../shared/getStaticAttributeValue';
import getStaticAttributeValue from '../../../../utils/getStaticAttributeValue';
import { DomGenerator } from '../../index';
import Block from '../../Block';
import { Node } from '../../../../interfaces';
Expand Down
4 changes: 2 additions & 2 deletions src/generators/dom/visitors/Element/Element.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import visitEventHandler from './EventHandler';
import visitBinding from './Binding';
import visitRef from './Ref';
import * as namespaces from '../../../../utils/namespaces';
import getStaticAttributeValue from '../../../shared/getStaticAttributeValue';
import getStaticAttributeValue from '../../../../utils/getStaticAttributeValue';
import addTransitions from './addTransitions';
import { DomGenerator } from '../../index';
import Block from '../../Block';
Expand Down Expand Up @@ -102,7 +102,7 @@ export default function visitElement(

if (node._cssRefAttribute) {
block.builders.hydrate.addLine(
`@setAttribute(${name}, "svelte-ref-${node._cssRefAttribute}", ");`
`@setAttribute(${name}, "svelte-ref-${node._cssRefAttribute}", "");`
)
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/generators/dom/visitors/Element/StyleAttribute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import attributeLookup from './lookup';
import deindent from '../../../../utils/deindent';
import { stringify } from '../../../../utils/stringify';
import getExpressionPrecedence from '../../../../utils/getExpressionPrecedence';
import getStaticAttributeValue from '../../../shared/getStaticAttributeValue';
import getStaticAttributeValue from '../../../../utils/getStaticAttributeValue';
import { DomGenerator } from '../../index';
import Block from '../../Block';
import { Node } from '../../../../interfaces';
Expand Down
2 changes: 1 addition & 1 deletion src/generators/dom/visitors/Slot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { DomGenerator } from '../index';
import deindent from '../../../utils/deindent';
import visit from '../visit';
import Block from '../Block';
import getStaticAttributeValue from '../../shared/getStaticAttributeValue';
import getStaticAttributeValue from '../../../utils/getStaticAttributeValue';
import { Node } from '../../../interfaces';
import { State } from '../interfaces';

Expand Down
15 changes: 0 additions & 15 deletions src/generators/shared/getStaticAttributeValue.ts

This file was deleted.

2 changes: 1 addition & 1 deletion src/interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ export interface CompileOptions {
cascade?: boolean;
hydratable?: boolean;
legacy?: boolean;
customElement: CustomElementOptions | true;
customElement?: CustomElementOptions | true;

onerror?: (error: Error) => void;
onwarn?: (warning: Warning) => void;
Expand Down
17 changes: 17 additions & 0 deletions src/utils/getStaticAttributeValue.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { Node } from '../interfaces';

export default function getStaticAttributeValue(node: Node, name: string) {
const attribute = node.attributes.find(
(attr: Node) => attr.name.toLowerCase() === name
);

if (!attribute) return null;

if (attribute.value.length === 0) return '';

if (attribute.value.length === 1 && attribute.value[0].type === 'Text') {
return attribute.value[0].data;
}

return null;
}
171 changes: 171 additions & 0 deletions src/validate/html/a11y.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
import * as namespaces from '../../utils/namespaces';
import getStaticAttributeValue from '../../utils/getStaticAttributeValue';
import fuzzymatch from '../utils/fuzzymatch';
import validateEventHandler from './validateEventHandler';
import { Validator } from '../index';
import { Node } from '../../interfaces';

const ariaAttributes = 'activedescendant atomic autocomplete busy checked controls describedby disabled dropeffect expanded flowto grabbed haspopup hidden invalid label labelledby level live multiline multiselectable orientation owns posinset pressed readonly relevant required selected setsize sort valuemax valuemin valuenow valuetext'.split(' ');
const ariaAttributeSet = new Set(ariaAttributes);

const ariaRoles = 'alert alertdialog application article banner button checkbox columnheader combobox command complementary composite contentinfo definition dialog directory document form grid gridcell group heading img input landmark link list listbox listitem log main marquee math menu menubar menuitem menuitemcheckbox menuitemradio navigation note option presentation progressbar radio radiogroup range region roletype row rowgroup rowheader scrollbar search section sectionhead select separator slider spinbutton status structure tab tablist tabpanel textbox timer toolbar tooltip tree treegrid treeitem widget window'.split(' ');
const ariaRoleSet = new Set(ariaRoles);

const invisibleElements = new Set(['meta', 'html', 'script', 'style']);

export default function a11y(
validator: Validator,
node: Node,
elementStack: Node[]
) {
if (node.type === 'Text') {
// accessible-emoji
return;
}

if (node.type !== 'Element') return;

const attributeMap = new Map();
node.attributes.forEach((attribute: Node) => {
const name = attribute.name.toLowerCase();

// aria-props
if (name.startsWith('aria-')) {
if (invisibleElements.has(node.name)) {
// aria-unsupported-elements
validator.warn(`A11y: <${node.name}> should not have aria-* attributes`, attribute.start);
}

const type = name.slice(5);
if (!ariaAttributeSet.has(type)) {
const match = fuzzymatch(type, ariaAttributes);
let message = `A11y: Unknown aria attribute 'aria-${type}'`;
if (match) message += ` (did you mean '${match}'?)`;

validator.warn(message, attribute.start);
}
}

// aria-role
if (name === 'role') {
if (invisibleElements.has(node.name)) {
// aria-unsupported-elements
validator.warn(`A11y: <${node.name}> should not have role attribute`, attribute.start);
}

const value = getStaticAttributeValue(node, 'role');
if (value && !ariaRoleSet.has(value)) {
const match = fuzzymatch(value, ariaRoles);
let message = `A11y: Unknown role '${value}'`;
if (match) message += ` (did you mean '${match}'?)`;

validator.warn(message, attribute.start);
}
}

// no-access-key
if (name === 'accesskey') {
validator.warn(`A11y: Avoid using accesskey`, attribute.start);
}

// no-autofocus
if (name === 'autofocus') {
validator.warn(`A11y: Avoid using autofocus`, attribute.start);
}

// scope
if (name === 'scope' && node.name !== 'th') {
validator.warn(`A11y: The scope attribute should only be used with <th> elements`, attribute.start);
}

// tabindex-no-positive
if (name === 'tabindex') {
const value = getStaticAttributeValue(node, 'tabindex');
if (!isNaN(value) && +value > 0) {
validator.warn(`A11y: avoid tabindex values above zero`, attribute.start);
}
}

attributeMap.set(attribute.name, attribute);
});

function shouldHaveAttribute(attributes: string[], name = node.name) {
if (attributes.length === 0 || !attributes.some((name: string) => attributeMap.has(name))) {
const article = /^[aeiou]/.test(attributes[0]) ? 'an' : 'a';
const sequence = attributes.length > 1 ?
attributes.slice(0, -1).join(', ') + ` or ${attributes[attributes.length - 1]}` :
attributes[0];

validator.warn(`A11y: <${name}> element should have ${article} ${sequence} attribute`, node.start);
}
}

function shouldHaveContent() {
if (node.children.length === 0) {
validator.warn(`A11y: <${node.name}> element should have child content`, node.start);
}
}

if (node.name === 'a') {
// anchor-is-valid
const href = attributeMap.get('href');
if (attributeMap.has('href')) {
const value = getStaticAttributeValue(node, 'href');
if (value === '' || value === '#') {
validator.warn(`A11y: '${value}' is not a valid href attribute`, href.start);
}
} else {
validator.warn(`A11y: <a> element should have an href attribute`, node.start);
}

// anchor-has-content
shouldHaveContent();
}

if (node.name === 'img') shouldHaveAttribute(['alt']);
if (node.name === 'area') shouldHaveAttribute(['alt', 'aria-label', 'aria-labelledby']);
if (node.name === 'object') shouldHaveAttribute(['title', 'aria-label', 'aria-labelledby']);
if (node.name === 'input' && getStaticAttributeValue(node, 'type') === 'image') {
shouldHaveAttribute(['alt', 'aria-label', 'aria-labelledby'], 'input type="image"');
}

// heading-has-content
if (/^h[1-6]$/.test(node.name)) {
shouldHaveContent();

if (attributeMap.has('aria-hidden')) {
validator.warn(`A11y: <${node.name}> element should not be hidden`, attributeMap.get('aria-hidden').start);
}
}

// iframe-has-title
if (node.name === 'iframe') {
shouldHaveAttribute(['title']);
}

// no-distracting-elements
if (node.name === 'marquee' || node.name === 'blink') {
validator.warn(`A11y: Avoid <${node.name}> elements`, node.start);
}

if (node.name === 'figcaption') {
const parent = elementStack[elementStack.length - 1];
if (parent) {
if (parent.name !== 'figure') {
validator.warn(`A11y: <figcaption> must be an immediate child of <figure>`, node.start);
} else {
const index = parent.children.indexOf(node);
if (index !== 0 && index !== parent.children.length - 1) {
validator.warn(`A11y: <figcaption> must be first or last child of <figure>`, node.start);
}
}
}
}
}

function getValue(attribute: Node) {
if (attribute.value.length === 0) return '';
if (attribute.value.length === 1 && attribute.value[0].type === 'Text') return attribute.value[0].data;

return null;
}
30 changes: 7 additions & 23 deletions src/validate/html/index.ts
Original file line number Diff line number Diff line change
@@ -1,41 +1,27 @@
import * as namespaces from '../../utils/namespaces';
import validateElement from './validateElement';
import validateWindow from './validateWindow';
import a11y from './a11y';
import fuzzymatch from '../utils/fuzzymatch'
import flattenReference from '../../utils/flattenReference';
import { Validator } from '../index';
import { Node } from '../../interfaces';

const svg = /^(?:altGlyph|altGlyphDef|altGlyphItem|animate|animateColor|animateMotion|animateTransform|circle|clipPath|color-profile|cursor|defs|desc|discard|ellipse|feBlend|feColorMatrix|feComponentTransfer|feComposite|feConvolveMatrix|feDiffuseLighting|feDisplacementMap|feDistantLight|feDropShadow|feFlood|feFuncA|feFuncB|feFuncG|feFuncR|feGaussianBlur|feImage|feMerge|feMergeNode|feMorphology|feOffset|fePointLight|feSpecularLighting|feSpotLight|feTile|feTurbulence|filter|font|font-face|font-face-format|font-face-name|font-face-src|font-face-uri|foreignObject|g|glyph|glyphRef|hatch|hatchpath|hkern|image|line|linearGradient|marker|mask|mesh|meshgradient|meshpatch|meshrow|metadata|missing-glyph|mpath|path|pattern|polygon|polyline|radialGradient|rect|set|solidcolor|stop|switch|symbol|text|textPath|title|tref|tspan|unknown|use|view|vkern)$/;

const meta = new Map([[':Window', validateWindow]]);

export default function validateHtml(validator: Validator, html: Node) {
let elementDepth = 0;

const refs = new Map();
const refCallees: Node[] = [];
const elementStack: Node[] = [];

function visit(node: Node) {
if (node.type === 'Element') {
if (
elementDepth === 0 &&
validator.namespace !== namespaces.svg &&
svg.test(node.name)
) {
validator.warn(
`<${node.name}> is an SVG element – did you forget to add { namespace: 'svg' } ?`,
node.start
);
}
a11y(validator, node, elementStack);

if (node.type === 'Element') {
if (meta.has(node.name)) {
return meta.get(node.name)(validator, node, refs, refCallees);
}

elementDepth += 1;

validateElement(validator, node, refs, refCallees);
validateElement(validator, node, refs, refCallees, elementStack);
} else if (node.type === 'EachBlock') {
if (validator.helpers.has(node.context)) {
let c = node.expression.end;
Expand All @@ -53,16 +39,14 @@ export default function validateHtml(validator: Validator, html: Node) {
}

if (node.children) {
if (node.type === 'Element') elementStack.push(node);
node.children.forEach(visit);
if (node.type === 'Element') elementStack.pop();
}

if (node.else) {
visit(node.else);
}

if (node.type === 'Element') {
elementDepth -= 1;
}
}

html.children.forEach(visit);
Expand Down
18 changes: 17 additions & 1 deletion src/validate/html/validateElement.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,17 @@
import * as namespaces from '../../utils/namespaces';
import validateEventHandler from './validateEventHandler';
import { Validator } from '../index';
import { Node } from '../../interfaces';

export default function validateElement(validator: Validator, node: Node, refs: Map<string, Node[]>, refCallees: Node[]) {
const svg = /^(?:altGlyph|altGlyphDef|altGlyphItem|animate|animateColor|animateMotion|animateTransform|circle|clipPath|color-profile|cursor|defs|desc|discard|ellipse|feBlend|feColorMatrix|feComponentTransfer|feComposite|feConvolveMatrix|feDiffuseLighting|feDisplacementMap|feDistantLight|feDropShadow|feFlood|feFuncA|feFuncB|feFuncG|feFuncR|feGaussianBlur|feImage|feMerge|feMergeNode|feMorphology|feOffset|fePointLight|feSpecularLighting|feSpotLight|feTile|feTurbulence|filter|font|font-face|font-face-format|font-face-name|font-face-src|font-face-uri|foreignObject|g|glyph|glyphRef|hatch|hatchpath|hkern|image|line|linearGradient|marker|mask|mesh|meshgradient|meshpatch|meshrow|metadata|missing-glyph|mpath|path|pattern|polygon|polyline|radialGradient|rect|set|solidcolor|stop|switch|symbol|text|textPath|title|tref|tspan|unknown|use|view|vkern)$/;

export default function validateElement(
validator: Validator,
node: Node,
refs: Map<string, Node[]>,
refCallees: Node[],
elementStack: Node[]
) {
const isComponent =
node.name === ':Self' || validator.components.has(node.name);

Expand All @@ -11,6 +20,13 @@ export default function validateElement(validator: Validator, node: Node, refs:
validator.warn(`${node.name} component is not defined`, node.start);
}

if (elementStack.length === 0 && validator.namespace !== namespaces.svg && svg.test(node.name)) {
validator.warn(
`<${node.name}> is an SVG element – did you forget to add { namespace: 'svg' } ?`,
node.start
);
}

if (node.name === 'slot') {
const nameAttribute = node.attributes.find((attribute: Node) => attribute.name === 'name');
if (nameAttribute) {
Expand Down
6 changes: 2 additions & 4 deletions src/validate/js/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,14 +57,12 @@ export default function validateJs(validator: Validator, js: Node) {
const match = fuzzymatch(prop.key.name, validPropList);
if (match) {
validator.error(
`Unexpected property '${prop.key
.name}' (did you mean '${match}'?)`,
`Unexpected property '${prop.key.name}' (did you mean '${match}'?)`,
prop.start
);
} else if (/FunctionExpression/.test(prop.value.type)) {
validator.error(
`Unexpected property '${prop.key
.name}' (did you mean to include it in 'methods'?)`,
`Unexpected property '${prop.key.name}' (did you mean to include it in 'methods'?)`,
prop.start
);
} else {
Expand Down
Loading

0 comments on commit ad59771

Please sign in to comment.