Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork27
Hypertext Abstract Syntax Tree format
syntax-tree/hast
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
HypertextAbstractSyntaxTree format.
hast is a specification for representingHTML(and embeddedSVG orMathML)as an abstract syntax tree.It implements theunist spec.
This document may not be released.Seereleases for released documents.The latest released version is2.4.0.
- Introduction
- Types
- Nodes (abstract)
- Nodes
- Other types
- Glossary
- List of utilities
- Related HTML utilities
- References
- Security
- Related
- Contribute
- Acknowledgments
- License
This document defines a format for representing hypertext as anabstract syntax tree.Development of hast started in April 2016 forrehype.This specification is written in aWeb IDL-like grammar.
hast extendsunist,a format for syntax trees,to benefit from itsecosystem of utilities.
hast relates toJavaScript in that it has anecosystem of utilitiesfor working with compliant syntax trees in JavaScript.However,hast is not limited to JavaScript and can be used in other programminglanguages.
hast relates to theunified andrehypeprojects in that hast syntax trees are used throughout their ecosystems.
The reason for introducing a new “virtual” DOM is primarily:
- TheDOM is very heavy to implement outside of the browser,a lean and stripped down virtual DOM can be used everywhere
- Most virtual DOMs do not focus on ease of use in transformations
- Other virtual DOMs cannot represent the syntax of HTML in its entirety(think comments and document types)
- Neither the DOM nor virtual DOMs focus on positional information
If you are using TypeScript,you can use the hast types by installing them with npm:
npm install @types/hast
interface Literal<: UnistLiteral { value:string}
Literal (UnistLiteral) represents a node in hastcontaining a value.
interface Parent<: UnistParent { children: [Comment| Doctype| Element|Text]}
Parent (UnistParent) represents a node in hastcontaining other nodes (said to bechildren).
Its content is limited to only other hast content.
interface Comment<: Literal { type:'comment'}
Comment (Literal) represents aComment([DOM]).
For example,the following HTML:
<!--Charlie-->Yields:
{type:'comment',value:'Charlie'}
interface Doctype<: Node { type:'doctype'}
Doctype (Node) represents aDocumentType ([DOM]).
For example,the following HTML:
<!doctype html>Yields:
{type:'doctype'}
interface Element<: Parent { type:'element' tagName:string properties: Properties content: Root? children: [Comment| Element|Text]}
Element (Parent) represents anElement([DOM]).
AtagName field must be present.It represents the element’slocal name([DOM]).
Theproperties field represents information associated with the element.The value of theproperties field implements theProperties interface.
If thetagName field is'template',acontent field can be present.The value of thecontent field implements theRoot interface.
If thetagName field is'template',the element must be aleaf.
If thetagName field is'noscript',itschildren should be represented as ifscripting is disabled ([HTML]).
For example,the following HTML:
<ahref="https://alpha.com"class="bravo"download></a>
Yields:
{type:'element',tagName:'a',properties:{href:'https://alpha.com',className:['bravo'],download:true},children:[]}
interface Root<: Parent { type:'root'}
Root (Parent) represents a document.
Root can be used as theroot of atree,or as a value of thecontent field on a'template'Element,never as achild.
interfaceText<: Literal { type:'text'}
Text (Literal) represents aText([DOM]).
For example,the following HTML:
<span>Foxtrot</span>
Yields:
{type:'element',tagName:'span',properties:{},children:[{type:'text',value:'Foxtrot'}]}
interface Properties {}Properties represents information associated with an element.
Every field must be aPropertyName and every value aPropertyValue.
typedefstring PropertyNameProperty names are keys onProperties objects and reflectHTML,SVG,ARIA,XML,XMLNS,or XLink attribute names.Often,they have the same value as the corresponding attribute(for example,id is a property name reflecting theid attribute name),but there are some notable differences.
These rules aren’t simple.Use
hastscript(orproperty-informationdirectly)to help.
The following rules are used to transform HTML attribute names to propertynames.These rules are based onhow ARIA is reflected in the DOM([ARIA]),and differs from how some(older)HTML attributes are reflected in the DOM.
- any name referencing a combinations of multiple words(such as “stroke miter limit”) becomes a camelcased property namecapitalizing each word boundary;this includes combinations that are sometimes written as several words;for example,
stroke-miterlimitbecomesstrokeMiterLimit,autocorrectbecomesautoCorrect,andallowfullscreenbecomesallowFullScreen - any name that can be hyphenated,becomes a camelcased property name capitalizing each boundary;for example,“read-only” becomes
readOnly - compound words that are not used with spaces or hyphens are treated as anormal word and the previous rules apply;for example,“placeholder”,“strikethrough”,and “playback” stay the same
- acronyms in names are treated as a normal word and the previous rules apply;for example,
itemidbecomeitemIdandbgcolorbecomesbgColor
Some jargon is seen as one word even though it may not be seen as such bydictionaries.For example,nohref becomesnoHref,playsinline becomesplaysInline,andaccept-charset becomesacceptCharset.
The HTML attributesclass andfor respectively becomeclassName andhtmlFor in alignment with the DOM.No other attributes gain different names as properties,other than a change in casing.
property-information lists all property names.
The property name rules differ from how HTML is reflected in the DOM for thefollowing attributes:
View list of differences
charoffbecomescharOff(notchOff)charstayschar(does not becomech)relstaysrel(does not becomerelList)checkedstayschecked(does not becomedefaultChecked)mutedstaysmuted(does not becomedefaultMuted)valuestaysvalue(does not becomedefaultValue)selectedstaysselected(does not becomedefaultSelected)allowfullscreenbecomesallowFullScreen(notallowFullscreen)hreflangbecomeshrefLang, nothreflangautoplaybecomesautoPlay, notautoplayautocompletebecomesautoComplete(notautocomplete)autofocusbecomesautoFocus, notautofocusenctypebecomesencType, notenctypeformenctypebecomesformEncType(notformEnctype)vspacebecomesvSpace, notvspacehspacebecomeshSpace, nothspacelowsrcbecomeslowSrc, notlowsrc
typedef any PropertyValue
Property values should reflect the data type determined by their property name.For example,the HTML<div hidden></div> has ahidden attribute,which is reflected as ahidden property name set to the property valuetrue,and<input minlength="5">,which has aminlength attribute,is reflected as aminLength property name set to the property value5.
InJSON,the value
nullmust be treated as if the property was not included.InJavaScript,bothnullandundefinedmust be similarly ignored.
The DOM has strict rules on how it coerces HTML to expected values,whereas hast is more lenient in how it reflects the source.Where the DOM treats<div hidden="no"></div> as having a value oftrue and<img width="yes"> as having a value of0,these should be reflected as'no' and'yes',respectively,in hast.
The reason for this is to allow plugins and utilities to inspect thesenon-standard values.
The DOM also specifies comma separated and space separated lists attributevalues.In hast, these should be treated as ordered lists.For example,<div></div> is represented as['alpha', 'bravo'].
There’s no special format for the property value of the
styleproperty name.
See§Glossary insyntax-tree/unist.
See§List of utilities insyntax-tree/unistfor more utilities.
hastscript— create treeshast-util-assert— assert nodeshast-util-class-list— simulate the browser’sclassListAPI for hast nodeshast-util-classnames— merge class names togetherhast-util-embedded— check if a node is an embedded elementhast-util-excerpt— truncate the tree to a commenthast-util-find-and-replace— find and replace text in a treehast-util-format— format whitespacehast-util-from-dom— transform from DOM treehast-util-from-html— parse from HTMLhast-util-from-parse5— transform from Parse5’s ASThast-util-from-selector— parse CSS selectors to nodeshast-util-from-string— set the plain-text value of a node (textContent)hast-util-from-text— set the plain-text value of a node (innerText)hast-util-from-webparser— transform Webparser’s AST to hasthast-util-has-property— check if an element has a certain propertyhast-util-heading— check if a node is heading contenthast-util-heading-rank— get the rank (also known as depth or level) of headingshast-util-interactive— check if a node is interactivehast-util-is-body-ok-link— check if alinkelement is “Body OK”hast-util-is-conditional-comment— check ifnodeis a conditional commenthast-util-is-css-link— check ifnodeis a CSSlinkhast-util-is-css-style— check ifnodeis a CSSstylehast-util-is-element— check ifnodeis a (certain) elementhast-util-is-event-handler— check ifpropertyis an event handlerhast-util-is-javascript— check ifnodeis a JavaScriptscripthast-util-labelable— check ifnodeis labelablehast-util-minify-whitespace— minify whitespace between elementshast-util-parse-selector— create an element from a simple CSS selectorhast-util-phrasing— check if a node is phrasing contenthast-util-raw— parse a tree againhast-util-reading-time— estimate the reading timehast-util-sanitize— sanitize nodeshast-util-script-supporting— check ifnodeis script-supporting contenthast-util-select—querySelector,querySelectorAll, andmatcheshast-util-sectioning— check ifnodeis sectioning contenthast-util-shift-heading— change heading rank (depth, level)hast-util-table-cell-style— transform deprecated styling attributes on table cells to inline styleshast-util-to-dom— transform to a DOM treehast-util-to-estree— transform to estree (JavaScript AST) JSXhast-util-to-html— serialize as HTMLhast-util-to-jsx— transform hast to JSXhast-util-to-jsx-runtime— transform to preact, react, solid, svelte, vue, etchast-util-to-mdast— transform to mdast (markdown)hast-util-to-nlcst— transform to nlcst (natural language)hast-util-to-parse5— transform to Parse5’s ASThast-util-to-portable-text— transform to portable texthast-util-to-string— get the plain-text value of a node (textContent)hast-util-to-text— get the plain-text value of a node (innerText)hast-util-to-xast— transform to xast (xml)hast-util-transparent— check ifnodeis transparent contenthast-util-truncate— truncate the tree to a certain number of charactershast-util-whitespace— check ifnodeis inter-element whitespace
a-rel— List of link types forrelona/areaaria-attributes— List of ARIA attributescollapse-white-space— Replace multiple white-space characters with a single spacecomma-separated-tokens— Parse/stringify comma separated tokenshtml-tag-names— List of HTML tag nameshtml-dangerous-encodings— List of dangerous HTML character encoding labelshtml-encodings— List of HTML character encoding labelshtml-element-attributes— Map of HTML attributeshtml-event-attributes— List of HTML event handler content attributeshtml-void-elements— List of void HTML tag nameslink-rel— List of link types forrelonlinkmathml-tag-names— List of MathML tag namesmeta-name— List of values fornameonmetaproperty-information— Information on HTML propertiesspace-separated-tokens— Parse/stringify space separated tokenssvg-tag-names— List of SVG tag namessvg-element-attributes— Map of SVG attributessvg-event-attributes— List of SVG event handler content attributesweb-namespaces— Map of web namespaces
- unist:Universal Syntax Tree.T. Wormer; et al.
- JavaScript:ECMAScript Language Specification.Ecma International.
- HTML:HTML Standard,A. van Kesteren; et al.WHATWG.
- DOM:DOM Standard,A. van Kesteren,A. Gregor,Ms2ger.WHATWG.
- SVG:Scalable Vector Graphics (SVG),N. Andronikos,R. Atanassov,T. Bah,B. Birtles,B. Brinza,C. Concolato,E. Dahlström,C. Lilley,C. McCormack,D. Schepers,R. Schwerdtfeger,D. Storey,S. Takagi,J. Watt.W3C.
- MathML:Mathematical Markup Language Standard,D. Carlisle,P. Ion,R. Miner.W3C.
- ARIA:Accessible Rich Internet Applications (WAI-ARIA),J. Diggs,J. Craig,S. McCarron,M. Cooper.W3C.
- JSONThe JavaScript Object Notation (JSON) Data Interchange Format,T. Bray.IETF.
- Web IDL:Web IDL,C. McCormack.W3C.
As hast represents HTML,and improper use of HTML can open you up to across-site scripting (XSS) attack,improper use of hast is also unsafe.Always be careful with user input and usehast-util-santize to make the hast tree safe.
- mdast— Markdown Abstract Syntax Tree format
- nlcst— Natural Language Concrete Syntax Tree format
- xast— Extensible Abstract Syntax Tree
Seecontributing.md insyntax-tree/.github for ways to get started.Seesupport.md for ways to get help.
A curated list of awesome syntax-tree,unist,mdast,hast,xast,and nlcst resources can be found inawesome syntax-tree.
This project has acode of conduct.By interacting with this repository,organization,or community you agree to abide by its terms.
The initial release of this project was authored by@wooorm.
Special thanks to@eush77 for their work,ideas,and incredibly valuable feedback!
Thanks to@andrewburgess,@arobase-che,@arystan-sw,@BarryThePenguin,@brechtcs,@ChristianMurphy,@ChristopherBiscardi,@craftzdog,@cupojoe,@davidtheclark,@derhuerst,@detj,@DxCx,@erquhart,@flurmbo,@Hamms,@Hypercubed,@inklesspen,@jeffal,@jlevy,@Justineo,@lfittl,@kgryte,@kmck,@kthjm,@KyleAMathews,@macklinu,@medfreeman,@Murderlon,@nevik,@nokome,@phiresky,@revolunet,@rhysd,@Rokt33r,@rubys,@s1n,@Sarah-Seo,@sethvincent,@simov,@StarpTech,@stefanprobst,@stuff,@subhero24,@tripodsan,@tunnckoCore,@vhf,@voischev, and@zjaml,for contributing to hast and related projects!
About
Hypertext Abstract Syntax Tree format
Topics
Resources
Code of conduct
Contributing
Security policy
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Sponsor this project
Uh oh!
There was an error while loading.Please reload this page.
Uh oh!
There was an error while loading.Please reload this page.