p5
Version:
[](https://www.npmjs.com/package/p5)
345 lines (344 loc) • 15 kB
JavaScript
//#region src/accessibility/describe.js
/**
* @module Environment
* @submodule Environment
* @for p5
*/
function describe(p5, fn) {
const descContainer = "_Description";
const fallbackDescId = "_fallbackDesc";
const fallbackTableId = "_fallbackTable";
const fallbackTableElId = "_fte_";
const labelContainer = "_Label";
const labelDescId = "_labelDesc";
const labelTableId = "_labelTable";
const labelTableElId = "_lte_";
/**
* Creates a screen reader-accessible description of the canvas.
*
* The first parameter, `text`, is the description of the canvas.
*
* The second parameter, `display`, is optional and can be `LABEL` or
* `FALLBACK`. The third parameter, `lang`, is optional and sets the language
* of the description for screen readers. However, if only the optional 'lang'
* parameter is passed, it will be treated as the second optional parameter and
* the default option 'FALLBACK' will be used as the display.
*
*
* Read
* <a href="/learn/accessible-labels.html">Writing accessible canvas descriptions</a>
* to learn more about making sketches accessible.
*
* @method describe
* @param {String} text description of the canvas.
* @param {(FALLBACK|LABEL)} [display] either LABEL or FALLBACK.
* @param {String} [lang] valid lang attribute.
*
* @example
* function setup() {
* background('pink');
*
* // Draw a heart.
* fill('red');
* noStroke();
* circle(67, 67, 20);
* circle(83, 67, 20);
* triangle(91, 73, 75, 95, 59, 73);
*
* // Add a general description of the canvas.
* describe('A pink square with a red heart in the bottom-right corner.');
* }
*
* @example
* function setup() {
* background('pink');
*
* // Draw a heart.
* fill('red');
* noStroke();
* circle(67, 67, 20);
* circle(83, 67, 20);
* triangle(91, 73, 75, 95, 59, 73);
*
* // Add a general description of the canvas
* // and display it for debugging.
* describe('A pink square with a red heart in the bottom-right corner.', LABEL);
* }
*
* @example
* function setup(){
* createCanvas(100, 100);
* };
*
* function draw() {
* background(200);
*
* // The expression
* // frameCount % 100
* // causes x to increase from 0
* // to 99, then restart from 0.
* let x = frameCount % 100;
*
* // Draw the circle.
* fill(0, 255, 0);
* circle(x, 50, 40);
*
* // Add a general description of the canvas.
* describe(`A green circle at (${x}, 50) moves from left to right on a gray square.`);
* }
*
* @example
* function setup(){
* createCanvas(100, 100);
* }
*
* function draw() {
* background(200);
*
* // The expression
* // frameCount % 100
* // causes x to increase from 0
* // to 99, then restart from 0.
* let x = frameCount % 100;
*
* // Draw the circle.
* fill(0, 255, 0);
* circle(x, 50, 40);
*
* // Add a general description of the canvas
* // and display it for debugging.
* describe(`A green circle at (${x}, 50) moves from left to right on a gray square.`, LABEL);
* }
*/
/**
* @method describe
* @param {String} text description of the canvas.
* @param {String} [lang] valid lang attribute.
*/
fn.describe = function(text, display, lang) {
if (typeof text !== "string") return;
const cnvId = this.canvas.id;
text = _descriptionText(text);
if (!this.dummyDOM) this.dummyDOM = document.getElementById(cnvId).parentNode;
if (!this.descriptions) this.descriptions = {};
if (this.descriptions.fallback) {
if (this.descriptions.fallback.innerHTML !== text) this.descriptions.fallback.innerHTML = text;
} else this._describeHTML("fallback", text);
if (display === this.LABEL) {
if (this.descriptions.label) {
if (this.descriptions.label.innerHTML !== text) this.descriptions.label.innerHTML = text;
} else this._describeHTML("label", text);
}
_setDescriptionLang(this, lang);
};
/**
* Creates a screen reader-accessible description of elements in the canvas.
*
* Elements are shapes or groups of shapes that create meaning together. For
* example, a few overlapping circles could make an "eye" element.
*
* The first parameter, `name`, is the name of the element.
*
* The second parameter, `text`, is the description of the element.
*
* The third parameter, `display`, is optional and can be `LABEL` or
* `FALLBACK`. The fourth parameter, `lang`, is optional and sets the language
* of the description for screen readers. However, if only the optional 'lang'
* parameter is passed, it will be treated as the third optional parameter and
* the default option 'FALLBACK' will be used as the display.
*
* If `LABEL` is passed, as in `describe('A description.', LABEL)`,
* the description will be visible in a div element next to the canvas. Using
* `LABEL` creates unhelpful duplicates for screen readers. Only use `LABEL`
* during development. If `FALLBACK` is passed, as in `describe('A description.', FALLBACK)`,
* the description will only be visible to screen readers. This is the default mode.
*
* Read
* <a href="/learn/accessible-labels.html">Writing accessible canvas descriptions</a>
* to learn more about making sketches accessible.
*
* @method describeElement
* @param {String} name name of the element.
* @param {String} text description of the element.
* @param {(FALLBACK|LABEL)} [display] either LABEL or FALLBACK.
* @param {String} [lang] valid lang attribute.
* @example
* function setup() {
* background('pink');
*
* // Describe the first element
* // and draw it.
* describeElement('Circle', 'A yellow circle in the top-left corner.');
* noStroke();
* fill('yellow');
* circle(25, 25, 40);
*
* // Describe the second element
* // and draw it.
* describeElement('Heart', 'A red heart in the bottom-right corner.');
* fill('red');
* circle(66.6, 66.6, 20);
* circle(83.2, 66.6, 20);
* triangle(91.2, 72.6, 75, 95, 58.6, 72.6);
*
* // Add a general description of the canvas.
* describe('A red heart and yellow circle over a pink background.');
* }
*
* @example
* function setup() {
* background('pink');
*
* // Describe the first element
* // and draw it. Display the
* // description for debugging.
* describeElement('Circle', 'A yellow circle in the top-left corner.', LABEL);
* noStroke();
* fill('yellow');
* circle(25, 25, 40);
*
* // Describe the second element
* // and draw it. Display the
* // description for debugging.
* describeElement('Heart', 'A red heart in the bottom-right corner.', LABEL);
* fill('red');
* circle(66.6, 66.6, 20);
* circle(83.2, 66.6, 20);
* triangle(91.2, 72.6, 75, 95, 58.6, 72.6);
*
* // Add a general description of the canvas.
* describe('A red heart and yellow circle over a pink background.');
* }
*/
/**
* @method describeElement
* @param {String} name name of the element.
* @param {String} text description of the element.
* @param {String} [lang] valid lang attribute.
*/
fn.describeElement = function(name, text, display, lang) {
if (typeof text !== "string" || typeof name !== "string") return;
const cnvId = this.canvas.id;
text = _descriptionText(text);
let elementName = _elementName(name);
name = name.replace(/[^a-zA-Z0-9]/g, "");
let langAttr = typeof lang === "string" ? ` lang="${lang}"` : "";
let inner = `<th scope="row"${langAttr}>${elementName}</th><td${langAttr}>${text}</td>`;
if (!this.dummyDOM) this.dummyDOM = document.getElementById(cnvId).parentNode;
if (!this.descriptions) this.descriptions = { fallbackElements: {} };
else if (!this.descriptions.fallbackElements) this.descriptions.fallbackElements = {};
if (this.descriptions.fallbackElements[name]) {
if (this.descriptions.fallbackElements[name].innerHTML !== inner) this.descriptions.fallbackElements[name].innerHTML = inner;
} else this._describeElementHTML("fallback", name, inner);
if (display === this.LABEL) {
if (!this.descriptions.labelElements) this.descriptions.labelElements = {};
if (this.descriptions.labelElements[name]) {
if (this.descriptions.labelElements[name].innerHTML !== inner) this.descriptions.labelElements[name].innerHTML = inner;
} else this._describeElementHTML("label", name, inner);
}
_setDescriptionLang(this, lang);
};
p5.registerDecorator("p5.prototype.describe", function(target) {
return function(text, display, lang) {
if (arguments.length === 2 && typeof display === "string") {
if (display === this.LABEL || display === this.FALLBACK) return target.call(this, text, display, void 0);
return target.call(this, text, void 0, display);
}
if (!_checkDescriptionOptions(this, "describe", display, lang)) return;
return target.call(this, text, display, lang);
};
});
p5.registerDecorator("p5.prototype.describeElement", function(target) {
return function(name, text, display, lang) {
if (arguments.length === 3 && typeof display === "string") {
if (display === this.LABEL || display === this.FALLBACK) return target.call(this, name, text, display, void 0);
return target.call(this, name, text, void 0, display);
}
if (!_checkDescriptionOptions(this, "describeElement", display, lang)) return;
return target.call(this, name, text, display, lang);
};
});
function _checkDescriptionOptions(pInst, methodName, display, lang) {
if (!(display === void 0 || display === pInst.LABEL || display === pInst.FALLBACK) || !(lang === void 0 || typeof lang === "string")) {
p5._friendlyError(`${methodName}() expects display (LABEL or FALLBACK) before lang.`, methodName);
return false;
}
return true;
}
function _setDescriptionLang(pInst, lang) {
const canvas = pInst.canvas.elt || pInst.elt || pInst.canvas;
if (typeof lang === "string") canvas.setAttribute("lang", lang);
else canvas.removeAttribute("lang");
if (pInst.descriptions.fallback) {
if (typeof lang === "string") pInst.descriptions.fallback.setAttribute("lang", lang);
else pInst.descriptions.fallback.removeAttribute("lang");
}
if (pInst.descriptions.label) {
if (typeof lang === "string") pInst.descriptions.label.setAttribute("lang", lang);
else pInst.descriptions.label.removeAttribute("lang");
}
}
function _descriptionText(text) {
if (text === "label" || text === "fallback") throw new Error("description should not be LABEL or FALLBACK");
if (!text.endsWith(".") && !text.endsWith(";") && !text.endsWith(",") && !text.endsWith("?") && !text.endsWith("!")) text = text + ".";
return text;
}
fn._describeHTML = function(type, text) {
const cnvId = this.canvas.id;
if (type === "fallback") {
if (!this.dummyDOM.querySelector(`#${cnvId + descContainer}`)) {
let html = `<div id="${cnvId}${descContainer}" role="region" aria-label="Canvas Description"><p id="${cnvId}${fallbackDescId}"></p></div>`;
if (!this.dummyDOM.querySelector(`#${cnvId}accessibleOutput`)) this.dummyDOM.querySelector(`#${cnvId}`).innerHTML = html;
else this.dummyDOM.querySelector(`#${cnvId}accessibleOutput`).insertAdjacentHTML("beforebegin", html);
} else this.dummyDOM.querySelector("#" + cnvId + fallbackTableId).insertAdjacentHTML("beforebegin", `<p id="${cnvId + fallbackDescId}"></p>`);
this.descriptions.fallback = this.dummyDOM.querySelector(`#${cnvId}${fallbackDescId}`);
this.descriptions.fallback.innerHTML = text;
return;
} else if (type === "label") {
if (!this.dummyDOM.querySelector(`#${cnvId + labelContainer}`)) {
let html = `<div id="${cnvId}${labelContainer}" class="p5Label"><p id="${cnvId}${labelDescId}"></p></div>`;
if (!this.dummyDOM.querySelector(`#${cnvId}accessibleOutputLabel`)) this.dummyDOM.querySelector("#" + cnvId).insertAdjacentHTML("afterend", html);
else this.dummyDOM.querySelector(`#${cnvId}accessibleOutputLabel`).insertAdjacentHTML("beforebegin", html);
} else if (this.dummyDOM.querySelector(`#${cnvId + labelTableId}`)) this.dummyDOM.querySelector(`#${cnvId + labelTableId}`).insertAdjacentHTML("beforebegin", `<p id="${cnvId}${labelDescId}"></p>`);
this.descriptions.label = this.dummyDOM.querySelector("#" + cnvId + labelDescId);
this.descriptions.label.innerHTML = text;
return;
}
};
function _elementName(name) {
if (name === "label" || name === "fallback") throw new Error("element name should not be LABEL or FALLBACK");
if (name.endsWith(".") || name.endsWith(";") || name.endsWith(",")) name = name.replace(/.$/, ":");
else if (!name.endsWith(":")) name = name + ":";
return name;
}
fn._describeElementHTML = function(type, name, text) {
const cnvId = this.canvas.id;
if (type === "fallback") {
if (!this.dummyDOM.querySelector(`#${cnvId + descContainer}`)) {
let html = `<div id="${cnvId}${descContainer}" role="region" aria-label="Canvas Description"><table id="${cnvId}${fallbackTableId}"><caption>Canvas elements and their descriptions</caption></table></div>`;
if (!this.dummyDOM.querySelector(`#${cnvId}accessibleOutput`)) this.dummyDOM.querySelector("#" + cnvId).innerHTML = html;
else this.dummyDOM.querySelector(`#${cnvId}accessibleOutput`).insertAdjacentHTML("beforebegin", html);
} else if (!this.dummyDOM.querySelector("#" + cnvId + fallbackTableId)) this.dummyDOM.querySelector("#" + cnvId + fallbackDescId).insertAdjacentHTML("afterend", `<table id="${cnvId}${fallbackTableId}"><caption>Canvas elements and their descriptions</caption></table>`);
let tableRow = document.createElement("tr");
tableRow.id = cnvId + fallbackTableElId + name;
this.dummyDOM.querySelector("#" + cnvId + fallbackTableId).appendChild(tableRow);
this.descriptions.fallbackElements[name] = this.dummyDOM.querySelector(`#${cnvId}${fallbackTableElId}${name}`);
this.descriptions.fallbackElements[name].innerHTML = text;
return;
} else if (type === "label") {
if (!this.dummyDOM.querySelector(`#${cnvId + labelContainer}`)) {
let html = `<div id="${cnvId}${labelContainer}" class="p5Label"><table id="${cnvId}${labelTableId}"></table></div>`;
if (!this.dummyDOM.querySelector(`#${cnvId}accessibleOutputLabel`)) this.dummyDOM.querySelector("#" + cnvId).insertAdjacentHTML("afterend", html);
else this.dummyDOM.querySelector(`#${cnvId}accessibleOutputLabel`).insertAdjacentHTML("beforebegin", html);
} else if (!this.dummyDOM.querySelector(`#${cnvId + labelTableId}`)) this.dummyDOM.querySelector("#" + cnvId + labelDescId).insertAdjacentHTML("afterend", `<table id="${cnvId + labelTableId}"></table>`);
let tableRow = document.createElement("tr");
tableRow.id = cnvId + labelTableElId + name;
this.dummyDOM.querySelector("#" + cnvId + labelTableId).appendChild(tableRow);
this.descriptions.labelElements[name] = this.dummyDOM.querySelector(`#${cnvId}${labelTableElId}${name}`);
this.descriptions.labelElements[name].innerHTML = text;
}
};
}
if (typeof p5 !== "undefined") describe(p5, p5.prototype);
//#endregion
export { describe as default };