the editable site (validation-lab)

This commit is contained in:
kpgarrod committed 2026-11-21 08:03:55 +01:00
commit 3ac81d5a52
13454 files changed
+2227005

No files matched your search

+4
View File
@@ -0,0 +1,4 @@
export { toText } from "./lib/index.js";
export type Options = import("./lib/index.js").Options;
export type Whitespace = import("./lib/index.js").Whitespace;
//# sourceMappingURL=index.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.js"],"names":[],"mappings":";sBACa,OAAO,gBAAgB,EAAE,OAAO;yBAChC,OAAO,gBAAgB,EAAE,UAAU"}
+6
View File
@@ -0,0 +1,6 @@
/**
* @typedef {import('./lib/index.js').Options} Options
* @typedef {import('./lib/index.js').Whitespace} Whitespace
*/
export {toText} from './lib/index.js'
+84
View File
@@ -0,0 +1,84 @@
/**
* Get the plain-text value of a node.
*
* ###### Algorithm
*
* * if `tree` is a comment, returns its `value`
* * if `tree` is a text, applies normal whitespace collapsing to its
* `value`, as defined by the CSS Text spec
* * if `tree` is a root or element, applies an algorithm similar to the
* `innerText` getter as defined by HTML
*
* ###### Notes
*
* > 👉 **Note**: the algorithm acts as if `tree` is being rendered, and as if
* > we’re a CSS-supporting user agent, with scripting enabled.
*
* * if `tree` is an element that is not displayed (such as a `head`), we’ll
* still use the `innerText` algorithm instead of switching to `textContent`
* * if descendants of `tree` are elements that are not displayed, they are
* ignored
* * CSS is not considered, except for the default user agent style sheet
* * a line feed is collapsed instead of ignored in cases where Fullwidth, Wide,
* or Halfwidth East Asian Width characters are used, the same goes for a case
* with Chinese, Japanese, or Yi writing systems
* * replaced elements (such as `audio`) are treated like non-replaced elements
*
* @param {Nodes} tree
* Tree to turn into text.
* @param {Readonly<Options> | null | undefined} [options]
* Configuration (optional).
* @returns {string}
* Serialized `tree`.
*/
export function toText(tree: Nodes, options?: Readonly<Options> | null | undefined): string;
/**
* Forced break.
*/
export type BreakForce = {
/**
* Value.
*/
value: "\t" | "\n";
};
/**
* Specific break:
*
* * `0` — collapsible space
* * `1` — line ending
* * `2` — blank line
*/
export type BreakNumber = 0 | 1 | 2;
/**
* Info on current collection.
*/
export type CollectionInfo = {
/**
* Whether a row comes later in the nearest table, after the current node or
* after the row group it is in.
*/
rowAfter?: boolean | undefined;
/**
* Current whitespace setting.
*/
whitespace: Whitespace;
};
/**
* Item in a collection.
*/
export type Item = BreakForce | BreakNumber | string;
/**
* Configuration.
*/
export type Options = {
/**
* Initial CSS whitespace setting to use (default: `'normal'`).
*/
whitespace?: Whitespace | null | undefined;
};
/**
* Valid and useful whitespace values (from CSS).
*/
export type Whitespace = "normal" | "nowrap" | "pre" | "pre-wrap";
import type { Nodes } from 'hast';
//# sourceMappingURL=index.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.js"],"names":[],"mappings":"AAkIA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,6BAPW,KAAK,YAEL,QAAQ,CAAC,OAAO,CAAC,GAAG,IAAI,GAAG,SAAS,GAElC,MAAM,CAqHlB;;;;;;;;WA9Qa,IAAI,GAAG,IAAI;;;;;;;;;0BAKZ,CAAC,GAAG,CAAC,GAAG,CAAC;;;;;;;;;eAWR,OAAO,GAAG,SAAS;;;;gBAGnB,UAAU;;;;;mBAKX,UAAU,GAAG,WAAW,GAAG,MAAM;;;;;;;;iBAOhC,UAAU,GAAG,IAAI,GAAG,SAAS;;;;;yBAK9B,QAAQ,GAAG,QAAQ,GAAG,KAAK,GAAG,UAAU;2BA1CI,MAAM"}
+751
View File
@@ -0,0 +1,751 @@
/**
* @import {Comment, Element, Nodes, Parents, Text} from 'hast'
*/
/**
* @typedef BreakForce
* Forced break.
* @property {'\t' | '\n'} value
* Value.
*/
/**
* @typedef {0 | 1 | 2} BreakNumber
* Specific break:
*
* * `0` — collapsible space
* * `1` — line ending
* * `2` — blank line
*/
/**
* @typedef CollectionInfo
* Info on current collection.
* @property {boolean | undefined} [rowAfter]
* Whether a row comes later in the nearest table, after the current node or
* after the row group it is in.
* @property {Whitespace} whitespace
* Current whitespace setting.
*/
/**
* @typedef {BreakForce | BreakNumber | string} Item
* Item in a collection.
*/
/**
* @typedef Options
* Configuration.
* @property {Whitespace | null | undefined} [whitespace='normal']
* Initial CSS whitespace setting to use (default: `'normal'`).
*/
/**
* @typedef {'normal' | 'nowrap' | 'pre' | 'pre-wrap'} Whitespace
* Valid and useful whitespace values (from CSS).
*/
/** @type {BreakForce} */
const forcedLineFeed = {value: '\n'}
/** @type {BreakForce} */
const forcedTab = {value: '\t'}
const searchLineFeeds = /\n/g
const searchTabOrSpaces = /[\t ]+/g
const startsWithTabOrSpace = /^[\t ]/
const endsWithTabOrSpace = /[\t ]$/
const trimTabOrSpaces = /^[\t ]+|[\t ]+$/g
const whitespaceOnly = /^[\t\n\f\r ]+$/
const tablePartNames = new Set([
'caption',
'col',
'colgroup',
'tbody',
'td',
'tfoot',
'th',
'thead',
'tr'
])
// Note that we don’t need to include void elements here as they don’t have text.
// See: <https://github.com/wooorm/html-void-elements>
const notRenderedNames = new Set([
// List from: <https://html.spec.whatwg.org/multipage/rendering.html#hidden-elements>
'datalist',
'head',
'noembed',
'noframes',
'noscript', // Act as if we support scripting.
'rp',
'script',
'style',
'template',
'title'
])
// See: <https://html.spec.whatwg.org/multipage/rendering.html#the-css-user-agent-style-sheet-and-presentational-hints>
const blockOrCaptionNames = new Set([
'address', // Flow content
'article', // Sections and headings
'aside', // Sections and headings
'blockquote', // Flow content
'body', // Page
'caption', // `table-caption`
'center', // Flow content (legacy)
'dd', // Lists
'dialog', // Flow content
'dir', // Lists (legacy)
'dl', // Lists
'dt', // Lists
'div', // Flow content
'figure', // Flow content
'figcaption', // Flow content
'footer', // Flow content
'form', // Flow content
'h1', // Sections and headings
'h2', // Sections and headings
'h3', // Sections and headings
'h4', // Sections and headings
'h5', // Sections and headings
'h6', // Sections and headings
'header', // Flow content
'hgroup', // Sections and headings
'hr', // Flow content
'html', // Page
'legend', // Flow content
'li', // Lists (as `display: list-item`)
'listing', // Flow content (legacy)
'main', // Flow content
'menu', // Lists
'nav', // Sections and headings
'ol', // Lists
'p', // Flow content
'plaintext', // Flow content (legacy)
'pre', // Flow content
'section', // Sections and headings
'ul', // Lists
'xmp' // Flow content (legacy)
])
/**
* Get the plain-text value of a node.
*
* ###### Algorithm
*
* * if `tree` is a comment, returns its `value`
* * if `tree` is a text, applies normal whitespace collapsing to its
* `value`, as defined by the CSS Text spec
* * if `tree` is a root or element, applies an algorithm similar to the
* `innerText` getter as defined by HTML
*
* ###### Notes
*
* > 👉 **Note**: the algorithm acts as if `tree` is being rendered, and as if
* > we’re a CSS-supporting user agent, with scripting enabled.
*
* * if `tree` is an element that is not displayed (such as a `head`), we’ll
* still use the `innerText` algorithm instead of switching to `textContent`
* * if descendants of `tree` are elements that are not displayed, they are
* ignored
* * CSS is not considered, except for the default user agent style sheet
* * a line feed is collapsed instead of ignored in cases where Fullwidth, Wide,
* or Halfwidth East Asian Width characters are used, the same goes for a case
* with Chinese, Japanese, or Yi writing systems
* * replaced elements (such as `audio`) are treated like non-replaced elements
*
* @param {Nodes} tree
* Tree to turn into text.
* @param {Readonly<Options> | null | undefined} [options]
* Configuration (optional).
* @returns {string}
* Serialized `tree`.
*/
export function toText(tree, options) {
const options_ = options || {}
const children = 'children' in tree ? tree.children : []
// The edges of inline elements are not block boundaries.
const inline =
tree.type === 'element' &&
tree.tagName !== 'p' &&
tree.tagName !== 'table' &&
!blockOrCaptionNames.has(tree.tagName) &&
!tablePartNames.has(tree.tagName)
let inTable = false
if (tree.type === 'element') {
inTable = tree.tagName === 'table' || rowGroup(tree)
}
const whitespace = inferWhitespace(tree, {
whitespace: options_.whitespace || 'normal'
})
/** @type {Array<Item>} */
const results = []
// Treat `text` and `comment` as having normal white-space.
// This deviates from the spec as in the DOM the node’s `.data` has to be
// returned.
// If you want that behavior use `hast-util-to-string`.
// All other nodes are later handled as if they are `element`s (so the
// algorithm also works on a `root`).
// Nodes without children are treated as a void element, so `doctype` is thus
// ignored.
if (tree.type === 'text' || tree.type === 'comment') {
append(results, collectText(tree))
}
// 1. If this element is not being rendered, or if the user agent is a
// non-CSS user agent, then return the same value as the textContent IDL
// attribute on this element.
//
// Note: we’re not supporting stylesheets so we’re acting as if the node
// is rendered.
//
// If you want that behavior use `hast-util-to-string`.
// Important: we’ll have to account for this later though.
// 2. Let results be a new empty list.
let index = -1
// 3. For each child node node of this element:
while (++index < children.length) {
// 3.1. Let current be the list resulting in running the inner text
// collection steps with node.
// Each item in results will either be a JavaScript string or a
// positive integer (a required line break count).
// 3.2. For each item item in current, append item to results.
append(
results,
renderedTextCollection(
children[index],
index,
/** @type {Parents} */ (tree),
{
rowAfter: inTable ? inferRowAfter(tree, index, undefined) : undefined,
whitespace
}
)
)
}
// 4. Remove any items from results that are the empty string.
// 5. Remove any runs of consecutive required line break count items at the
// start or end of results.
// 6. Replace each remaining run of consecutive required line break count
// items with a string consisting of as many U+000A LINE FEED (LF)
// characters as the maximum of the values in the required line break
// count items.
// Note: a run of only `0`s (collapsible spaces) is a space, unless it is
// next to a forced break, or at the edge of a block.
let force = false
/** @type {Array<string>} */
const result = []
/** @type {number | undefined} */
let count = inline ? -1 : undefined
index = -1
while (++index < results.length) {
const value = results[index]
if (typeof value === 'number') {
if (count !== undefined && value > count) count = value
} else if (value) {
const forceBefore = force
force = typeof value === 'object'
if (
count !== undefined &&
count > (force || forceBefore ? 0 : -1) &&
(result.length > 0 || count === 0)
) {
result.push('\n'.repeat(count) || ' ')
}
count = -1
result.push(typeof value === 'object' ? value.value : value)
}
}
if (inline && count === 0 && !force) {
result.push(' ')
}
// 7. Return the concatenation of the string items in results.
return result.join('')
}
/**
* <https://html.spec.whatwg.org/multipage/dom.html#rendered-text-collection-steps>
*
* @param {Nodes} node
* Node.
* @param {number} index
* Index of `node` in `parent`.
* @param {Parents} parent
* Parent of `node`.
* @param {CollectionInfo} info
* Info on current collection.
* @returns {Array<Item>}
* Items.
*/
function renderedTextCollection(node, index, parent, info) {
if (node.type === 'element') {
return collectElement(node, index, parent, info)
}
if (node.type === 'text') {
// White space in a table, row group, or row, between table parts, is not
// rendered.
//
// See: <https://drafts.csswg.org/css-tables-3/#fixup-algorithm>
if (
whitespaceOnly.test(node.value) &&
parent.type === 'element' &&
(parent.tagName === 'table' ||
parent.tagName === 'tr' ||
rowGroup(parent))
) {
const before = parent.children[index - 1]
const after = parent.children[index + 1]
if (
(!before ||
(before.type === 'element' && tablePartNames.has(before.tagName))) &&
(!after ||
(after.type === 'element' && tablePartNames.has(after.tagName)))
) {
return []
}
}
return info.whitespace === 'normal'
? collectText(node)
: collectPreText(node)
}
return []
}
/**
* Collect an element.
*
* @param {Element} node
* Element node.
* @param {number} position
* Index of `node` in `parent`.
* @param {Parents} parent
* Parent of `node`.
* @param {CollectionInfo} info
* Info on current collection.
* @returns {Array<Item>}
* Items.
*/
function collectElement(node, position, parent, info) {
// First we infer the `white-space` property.
const whitespace = inferWhitespace(node, info)
const children = node.children || []
const inTable = node.tagName === 'table' || rowGroup(node)
let index = -1
/** @type {Array<Item>} */
const items = []
// We’re ignoring point 3, and exiting without any content here, because we
// deviated from the spec in `toText` at step 3.
if (
notRenderedNames.has(node.tagName) ||
// Hidden attribute.
node.properties?.hidden ||
// From: <https://html.spec.whatwg.org/multipage/rendering.html#flow-content-3>
(node.tagName === 'dialog' && !node.properties?.open)
) {
return items
}
/** @type {BreakNumber | undefined} */
let prefix
/** @type {BreakForce | BreakNumber | undefined} */
let suffix
// 2. If node’s computed value of `visibility` is not `visible`, then return
// items.
//
// Note: Ignored, as everything is visible by default user agent styles.
// 3. If node is not being rendered, then return items. [...]
//
// Note: We already did this above.
// See `collectText` for step 4.
// 5. If node is a `<br>` element, then append a string containing a single
// U+000A LINE FEED (LF) character to items.
if (node.tagName === 'br') {
suffix = forcedLineFeed
}
// 7. If node’s computed value of `display` is `table-row`, and node’s CSS
// box is not the last `table-row` box of the nearest ancestor `table`
// box, then append a string containing a single U+000A LINE FEED (LF)
// character to items.
//
// See: <https://html.spec.whatwg.org/multipage/rendering.html#tables-2>
// Note: needs further investigation as this does not account for implicit
// rows.
else if (row(node) && (info.rowAfter || after(parent, position, row))) {
suffix = forcedLineFeed
}
// 8. If node is a `<p>` element, then append 2 (a required line break count)
// at the beginning and end of items.
else if (node.tagName === 'p') {
prefix = 2
suffix = 2
}
// 9. If node’s used value of `display` is block-level or `table-caption`,
// then append 1 (a required line break count) at the beginning and end of
// items.
else if (blockOrCaptionNames.has(node.tagName)) {
prefix = 1
suffix = 1
}
// 1. Let items be the result of running the inner text collection steps with
// each child node of node in tree order, and then concatenating the
// results to a single list.
while (++index < children.length) {
append(
items,
renderedTextCollection(children[index], index, node, {
rowAfter: inTable
? inferRowAfter(node, index, info.rowAfter)
: undefined,
whitespace
})
)
}
// 6. If node’s computed value of `display` is `table-cell`, and node’s CSS
// box is not the last `table-cell` box of its enclosing `table-row` box,
// then append a string containing a single U+0009 CHARACTER TABULATION
// (tab) character to items.
//
// See: <https://html.spec.whatwg.org/multipage/rendering.html#tables-2>
if (cell(node) && after(parent, position, cell)) {
items.push(forcedTab)
}
// Add the pre- and suffix.
if (prefix) items.unshift(prefix)
if (suffix) items.push(suffix)
return items
}
/**
* 4. If node is a Text node, then for each CSS text box produced by node,
* in content order, compute the text of the box after application of the
* CSS `white-space` processing rules and `text-transform` rules, set
* items to the list of the resulting strings, and return items.
* The CSS `white-space` processing rules are slightly modified:
* collapsible spaces at the end of lines are always collapsed, but they
* are only removed if the line is the last line of the block, or it ends
* with a br element.
* Soft hyphens should be preserved.
*
* Note: See `collectText` and `collectPreText`.
* Note: we don’t deal with `text-transform`, no element has that by
* default.
*
* See: <https://drafts.csswg.org/css-text/#white-space-phase-1>
*
* @param {Comment | Text} node
* Text node.
* @returns {Array<Item>}
* Result.
*/
function collectText(node) {
// […] ignoring bidi formatting characters (characters with the
// Bidi_Control property [UAX9]: ALM, LTR, RTL, LRE-RLO, LRI-PDI) as if
// they were not there.
const value = String(node.value).replace(
/[\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069]/g,
''
)
/** @type {Array<string>} */
const lines = []
/** @type {Array<Item>} */
const result = []
let start = 0
// Collapsible spaces at the start or end of the node collapse with spaces
// around it, or are removed at the start or end of a line, so they are
// added as `0`.
if (startsWithTabOrSpace.test(value)) result.push(0)
while (start <= value.length) {
searchLineFeeds.lastIndex = start
const match = searchLineFeeds.exec(value)
const end = match && 'index' in match ? match.index : value.length
lines.push(trimAndCollapseSpacesAndTabs(value.slice(start, end)))
start = end + 1
}
// Collapsible segment breaks are transformed for rendering according to the
// segment break transformation rules.
// So here we jump to 4.1.2 of [CSSTEXT]:
// Any collapsible segment break immediately following another collapsible
// segment break is removed
let index = -1
/** @type {BreakNumber | undefined} */
let join
while (++index < lines.length) {
// * If the character immediately before or immediately after the segment
// break is the zero-width space character (U+200B), then the break is
// removed, leaving behind the zero-width space.
if (
lines[index].charCodeAt(lines[index].length - 1) === 0x20_0b /* ZWSP */ ||
(index < lines.length - 1 &&
lines[index + 1].charCodeAt(0) === 0x20_0b) /* ZWSP */
) {
result.push(lines[index])
join = undefined
}
// * Otherwise, if the East Asian Width property [UAX11] of both the
// character before and after the segment break is Fullwidth, Wide, or
// Halfwidth (not Ambiguous), and neither side is Hangul, then the
// segment break is removed.
//
// Note: ignored.
// * Otherwise, if the writing system of the segment break is Chinese,
// Japanese, or Yi, and the character before or after the segment break
// is punctuation or a symbol (Unicode general category P* or S*) and
// has an East Asian Width property of Ambiguous, and the character on
// the other side of the segment break is Fullwidth, Wide, or Halfwidth,
// and not Hangul, then the segment break is removed.
//
// Note: ignored.
// * Otherwise, the segment break is converted to a space (U+0020).
else if (lines[index]) {
if (typeof join === 'number') result.push(join)
result.push(lines[index])
join = 0
} else if (index === 0 || index === lines.length - 1) {
// If this line is empty, and it’s the first or last, add a space.
// Note that this function is only called in normal whitespace, so we
// don’t worry about `pre`.
result.push(0)
}
}
if (endsWithTabOrSpace.test(value)) result.push(0)
return result
}
/**
* Collect a text node as “pre” whitespace.
*
* @param {Text} node
* Text node.
* @returns {Array<Item>}
* Result.
*/
function collectPreText(node) {
return [String(node.value)]
}
/**
* 3. Every collapsible tab is converted to a collapsible space (U+0020).
* 4. Any collapsible space immediately following another collapsible
* space—even one outside the boundary of the inline containing that
* space, provided both spaces are within the same inline formatting
* context—is collapsed to have zero advance width. (It is invisible,
* but retains its soft wrap opportunity, if any.)
*
* Note: spaces at the start and end of the node are handled in
* `collectText`.
*
* @param {string} value
* Value to collapse.
* @returns {string}
* Result.
*/
function trimAndCollapseSpacesAndTabs(value) {
return value.replace(trimTabOrSpaces, '').replace(searchTabOrSpaces, ' ')
}
/**
* Figure out the whitespace of a node.
*
* We don’t support void elements here (so `nobr wbr` -> `normal` is ignored).
*
* @param {Nodes} node
* Node (typically `Element`).
* @param {CollectionInfo} info
* Info on current collection.
* @returns {Whitespace}
* Applied whitespace.
*/
function inferWhitespace(node, info) {
if (node.type === 'element') {
switch (node.tagName) {
case 'listing':
case 'plaintext':
case 'xmp': {
return 'pre'
}
case 'nobr': {
return 'nowrap'
}
case 'pre': {
return node.properties?.wrap ? 'pre-wrap' : 'pre'
}
case 'td':
case 'th': {
return node.properties?.noWrap ? 'nowrap' : info.whitespace
}
case 'textarea': {
return 'pre-wrap'
}
default:
}
}
return info.whitespace
}
/**
* Check if a row comes later in a table.
*
* @param {Nodes} parent
* Table or row group.
* @param {number} index
* Index of child in `parent`.
* @param {boolean | undefined} rowAfter
* Whether a row comes after `parent`, if it is a row group.
* @returns {boolean | undefined}
* Whether a row comes after the child in the nearest table.
*/
function inferRowAfter(parent, index, rowAfter) {
return parent.type === 'element' && parent.tagName === 'table'
? after(parent, index, rowOrRowGroupWithRow)
: rowAfter
}
/**
* Check if an element after `index` in `parent` passes `test`.
*
* @param {Parents} parent
* Parent.
* @param {number} index
* Index of a child in `parent`; elements after it are checked.
* @param {(node: Element) => boolean} test
* Check.
* @returns {boolean}
* Whether an element after `index` passes `test`.
*/
function after(parent, index, test) {
while (++index < parent.children.length) {
const child = parent.children[index]
if (child.type === 'element' && test(child)) return true
}
return false
}
/**
* Append items to a list; without `...spread` which overflows.
*
* @template Kind
* Item.
* @param {Array<Kind>} list
* List to append to.
* @param {Array<Kind>} items
* Items to append.
* @returns {undefined}
* Nothing.
*/
function append(list, items) {
let index = -1
while (++index < items.length) {
list.push(items[index])
}
}
/**
* Check if an element is a cell.
*
* @param {Element} node
* Element.
* @returns {boolean}
* Whether `node` is a cell.
*/
function cell(node) {
return node.tagName === 'td' || node.tagName === 'th'
}
/**
* Check if an element is a row group; hot path so a basic regular function.
*
* @param {Element} node
* Element.
* @returns {boolean}
* Whether `node` is a row group.
*/
function rowGroup(node) {
return (
node.tagName === 'tbody' ||
node.tagName === 'tfoot' ||
node.tagName === 'thead'
)
}
/**
* Check if an element is a row, or a row group with a row.
*
* @param {Element} node
* Element.
* @returns {boolean}
* Whether `node` is a row or a row group with a row.
*/
function rowOrRowGroupWithRow(node) {
if (row(node)) return true
if (rowGroup(node)) {
let index = -1
while (++index < node.children.length) {
const child = node.children[index]
if (child.type === 'element' && row(child)) return true
}
}
return false
}
/**
* Check if an element is a row.
*
* @param {Element} node
* Element.
* @returns {boolean}
* Whether `node` is a row.
*/
function row(node) {
return node.tagName === 'tr'
}
+22
View File
@@ -0,0 +1,22 @@
(The MIT License)
Copyright (c) Titus Wormer <tituswormer@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+78
View File
@@ -0,0 +1,78 @@
{
"author": "Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)",
"bugs": "https://github.com/syntax-tree/hast-util-to-text/issues",
"contributors": [
"Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)"
],
"dependencies": {
"@types/hast": "^3.0.0"
},
"description": "hast utility to get the plain-text value of a node according to the `innerText` algorithm",
"devDependencies": {
"@types/node": "^26.0.0",
"c8": "^12.0.0",
"hastscript": "^9.0.0",
"prettier": "^3.0.0",
"remark-cli": "^12.0.0",
"remark-preset-wooorm": "^11.0.0",
"type-coverage": "^2.0.0",
"typescript": "^6.0.0",
"xo": "^5.0.0"
},
"exports": "./index.js",
"files": [
"lib/",
"index.d.ts.map",
"index.d.ts",
"index.js"
],
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/unified"
},
"keywords": [
"content",
"hast-util",
"hast",
"html",
"innertext",
"string",
"unist",
"utility",
"util",
"text"
],
"license": "MIT",
"name": "hast-util-to-text",
"prettier": {
"bracketSpacing": false,
"semi": false,
"singleQuote": true,
"tabWidth": 2,
"trailingComma": "none",
"useTabs": false
},
"repository": "syntax-tree/hast-util-to-text",
"remarkConfig": {
"plugins": [
"remark-preset-wooorm"
]
},
"scripts": {
"build": "tsc --build --clean && tsc --build && type-coverage",
"format": "remark --frail --output --quiet -- . && prettier --log-level warn --write -- . && xo --fix",
"prepack": "npm run build && npm run format",
"test-api": "node --conditions development test.js",
"test-coverage": "c8 --100 --reporter lcov -- npm run test-api",
"test": "npm run build && npm run format && npm run test-coverage"
},
"sideEffects": false,
"typeCoverage": {
"atLeast": 100,
"detail": true,
"ignoreCatch": true,
"strict": true
},
"type": "module",
"version": "4.0.5"
}
+284
View File
@@ -0,0 +1,284 @@
# hast-util-to-text
[![Build][build-badge]][build]
[![Coverage][coverage-badge]][coverage]
[![Downloads][downloads-badge]][downloads]
[![Size][size-badge]][size]
[![Sponsors][sponsors-badge]][collective]
[![Backers][backers-badge]][collective]
[![Chat][chat-badge]][chat]
[hast][] utility to get the plain-text value of a node.
## Contents
* [What is this?](#what-is-this)
* [When should I use this?](#when-should-i-use-this)
* [Install](#install)
* [Use](#use)
* [API](#api)
* [`toText(tree[, options])`](#totexttree-options)
* [`Options`](#options)
* [`Whitespace`](#whitespace)
* [Types](#types)
* [Compatibility](#compatibility)
* [Security](#security)
* [Related](#related)
* [Contribute](#contribute)
* [License](#license)
## What is this?
This package is a utility that takes a [hast][] node and gets its plain-text
value.
It is like the DOMs `Node#innerText`, which is a bit nicer than
`Node#textContent`, because this turns `<br>` elements into line breaks and
uses `'\t'` (tabs) between table cells.
There are some small deviations from the spec, because the DOM has knowledge of
associated CSS, and can take into account that elements have `display: none` or
`text-transform` association with them, and this utility can’t do that.
## When should I use this?
This is a small utility that is useful when you want a plain-text version of a
node that is close to how it’s “visible” to users.
This utility is similar to [`hast-util-to-string`][hast-util-to-string], which
is simpler, and more like the `Node#textContent` algorithm discussed above.
There is also a package [`hast-util-from-text`][hast-util-from-text], which sort
of does the inverse: it takes a string, sets that as text on the node, while
turning line endings into `<br>`s
## Install
This package is [ESM only][esm].
In Node.js (version 16+), install with [npm][]:
```sh
npm install hast-util-to-text
```
In Deno with [`esm.sh`][esmsh]:
```js
import {toText} from 'https://esm.sh/hast-util-to-text@4'
```
In browsers with [`esm.sh`][esmsh]:
```html
<script type="module">
import {toText} from 'https://esm.sh/hast-util-to-text@4?bundle'
</script>
```
## Use
```js
import {h} from 'hastscript'
import {toText} from 'hast-util-to-text'
const tree = h('div', [
h('h1', {hidden: true}, 'Alpha.'),
h('article', [
h('p', ['Bravo', h('br'), 'charlie.']),
h('p', 'Delta echo \t foxtrot.')
])
])
console.log(toText(tree))
```
Yields:
```text
Bravo
charlie.
Delta echo foxtrot.
```
## API
This package exports the identifier [`toText`][api-to-text].
There is no default export.
### `toText(tree[, options])`
Get the plain-text value of a node.
###### Parameters
* `tree` ([`Node`][node])
— tree to turn into text
* `options` ([`Options`][api-options], optional)
— configuration
###### Returns
Serialized `tree` (`string`).
###### Algorithm
* if `tree` is a [comment][], returns its `value`
* if `tree` is a [text][], applies normal whitespace collapsing to its
`value`, as defined by the [CSS Text][css] spec
* if `tree` is a [root][] or [element][], applies an algorithm similar to the
`innerText` getter as defined by [HTML][]
###### Notes
> 👉 **Note**: the algorithm acts as if `tree` is being rendered, and as if
> we’re a CSS-supporting user agent, with scripting enabled.
* if `tree` is an element that is not displayed (such as a `head`), we’ll
still use the `innerText` algorithm instead of switching to `textContent`
* if descendants of `tree` are elements that are not displayed, they are
ignored
* CSS is not considered, except for the default user agent style sheet
* a line feed is collapsed instead of ignored in cases where Fullwidth, Wide,
or Halfwidth East Asian Width characters are used, the same goes for a case
with Chinese, Japanese, or Yi writing systems
* replaced elements (such as `audio`) are treated like non-replaced elements
### `Options`
Configuration (TypeScript type).
##### Fields
* `whitespace` ([`Whitespace`][api-whitespace], default: `'normal'`)
— default whitespace setting to use
### `Whitespace`
Valid and useful whitespace values (from [CSS][]) (TypeScript type).
##### Type
```ts
type Whitespace = 'normal' | 'nowrap' | 'pre' | 'pre-wrap'
```
## Types
This package is fully typed with [TypeScript][].
It exports the additional types [`Options`][api-options] and
[`Whitespace`][api-whitespace].
## Compatibility
Projects maintained by the unified collective are compatible with maintained
versions of Node.js.
When we cut a new major release, we drop support for unmaintained versions of
Node.
This means we try to keep the current release line, `hast-util-to-text@^4`,
compatible with Node.js 16.
## Security
`hast-util-to-text` does not change the syntax tree so there are no
openings for [cross-site scripting (XSS)][xss] attacks.
## Related
* [`hast-util-to-string`][hast-util-to-string]
— get the plain-text value (`textContent`)
* [`hast-util-from-text`][hast-util-from-text]
— set the plain-text value (`innerText`)
* [`hast-util-from-string`
](https://github.com/rehypejs/rehype-minify/tree/main/packages/hast-util-from-string)
— set the plain-text value (`textContent`)
## Contribute
See [`contributing.md`][contributing] in [`syntax-tree/.github`][health] for
ways to get started.
See [`support.md`][support] for ways to get help.
This project has a [code of conduct][coc].
By interacting with this repository, organization, or community you agree to
abide by its terms.
## License
[MIT][license] © [Titus Wormer][author]
<!-- Definitions -->
[api-options]: #options
[api-to-text]: #totexttree-options
[api-whitespace]: #whitespace
[author]: https://wooorm.com
[backers-badge]: https://opencollective.com/unified/backers/badge.svg
[build]: https://github.com/syntax-tree/hast-util-to-text/actions
[build-badge]: https://github.com/syntax-tree/hast-util-to-text/workflows/main/badge.svg
[chat]: https://github.com/syntax-tree/unist/discussions
[chat-badge]: https://img.shields.io/badge/chat-discussions-success.svg
[coc]: https://github.com/syntax-tree/.github/blob/main/code-of-conduct.md
[collective]: https://opencollective.com/unified
[comment]: https://github.com/syntax-tree/hast#comment
[contributing]: https://github.com/syntax-tree/.github/blob/main/contributing.md
[coverage]: https://codecov.io/github/syntax-tree/hast-util-to-text
[coverage-badge]: https://img.shields.io/codecov/c/github/syntax-tree/hast-util-to-text.svg
[css]: https://drafts.csswg.org/css-text/#white-space-phase-1
[downloads]: https://www.npmjs.com/package/hast-util-to-text
[downloads-badge]: https://img.shields.io/npm/dm/hast-util-to-text.svg
[element]: https://github.com/syntax-tree/hast#element
[esm]: https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c
[esmsh]: https://esm.sh
[hast]: https://github.com/syntax-tree/hast
[hast-util-from-text]: https://github.com/syntax-tree/hast-util-from-text
[hast-util-to-string]: https://github.com/rehypejs/rehype-minify/tree/main/packages/hast-util-to-string
[health]: https://github.com/syntax-tree/.github
[html]: https://html.spec.whatwg.org/multipage/dom.html#the-innertext-idl-attribute
[license]: license
[node]: https://github.com/syntax-tree/hast#nodes
[npm]: https://docs.npmjs.com/cli/install
[root]: https://github.com/syntax-tree/hast#root
[size]: https://bundlejs.com/?q=hast-util-to-text
[size-badge]: https://img.shields.io/badge/dynamic/json?label=minzipped%20size\&query=$.size.compressedSize\&url=https://deno.bundlejs.com/?q=hast-util-to-text
[sponsors-badge]: https://opencollective.com/unified/sponsors/badge.svg
[support]: https://github.com/syntax-tree/.github/blob/main/support.md
[text]: https://github.com/syntax-tree/hast#text
[typescript]: https://www.typescriptlang.org
[xss]: https://en.wikipedia.org/wiki/Cross-site_scripting