This commit is contained in:
+64
@@ -0,0 +1,64 @@
|
||||
import type { TagToken } from '../common/token.js';
|
||||
import type { TreeAdapterTypeMap } from '../tree-adapters/interface.js';
|
||||
export declare enum EntryType {
|
||||
Marker = 0,
|
||||
Element = 1
|
||||
}
|
||||
interface MarkerEntry<T extends TreeAdapterTypeMap> {
|
||||
type: EntryType.Marker;
|
||||
older: Entry<T> | null;
|
||||
newer: Entry<T> | null;
|
||||
/** The index of the entries before this marker. */
|
||||
outerIndex: RegionIndex<T> | null;
|
||||
}
|
||||
/** The entries with one tag name after one marker are chained from a head, newest first. */
|
||||
interface SameTagLink<T extends TreeAdapterTypeMap> {
|
||||
olderSameTag: ElementEntry<T> | null;
|
||||
}
|
||||
export interface ElementEntry<T extends TreeAdapterTypeMap> extends SameTagLink<T> {
|
||||
type: EntryType.Element;
|
||||
element: T['element'];
|
||||
token: TagToken;
|
||||
older: Entry<T> | null;
|
||||
newer: Entry<T> | null;
|
||||
/** The entry's group of entries with the same tag name and attributes; null until indexed. */
|
||||
ark: Ark<T> | null;
|
||||
/** The next newer entry with the same tag name, or the chain's head; null until indexed. */
|
||||
newerSameTag: SameTagLink<T> | null;
|
||||
}
|
||||
export type Entry<T extends TreeAdapterTypeMap> = MarkerEntry<T> | ElementEntry<T>;
|
||||
/** The entries after one marker with one tag name and attributes, oldest first, and their key in the region's arks. */
|
||||
interface Ark<T extends TreeAdapterTypeMap> {
|
||||
entries: ElementEntry<T>[];
|
||||
key: string;
|
||||
}
|
||||
/** The entries after one marker by tag name and attributes, and the newest of them by tag name. */
|
||||
interface RegionIndex<T extends TreeAdapterTypeMap> {
|
||||
arks: Map<string, Ark<T>>;
|
||||
tagNames: Map<string, SameTagLink<T>>;
|
||||
}
|
||||
export declare class FormattingElementList<T extends TreeAdapterTypeMap> {
|
||||
newest: Entry<T> | null;
|
||||
bookmark: Entry<T> | null;
|
||||
/** The index of the entries after the last marker; null only while there are at most NOAH_ARK_CAPACITY of them. */
|
||||
private index;
|
||||
/** The entries by element, except possibly those after the last marker while they are not indexed. */
|
||||
private elementEntries;
|
||||
/** Returns the entry's ark, or null if the entries after the last marker are not indexed. */
|
||||
private _insertElementEntry;
|
||||
private _addToIndex;
|
||||
insertMarker(): void;
|
||||
pushElement(element: T['element'], token: TagToken): void;
|
||||
insertElementAfterBookmark(element: T['element'], token: TagToken): void;
|
||||
removeEntry(entry: ElementEntry<T>): void;
|
||||
replaceElement(entry: ElementEntry<T>, element: T['element']): void;
|
||||
/**
|
||||
* Clears the list of formatting elements up to the last marker.
|
||||
*
|
||||
* @see https://html.spec.whatwg.org/multipage/parsing.html#clear-the-list-of-active-formatting-elements-up-to-the-last-marker
|
||||
*/
|
||||
clearToLastMarker(): void;
|
||||
getElementEntryInScopeWithTagName(tagName: string): ElementEntry<T> | null;
|
||||
getElementEntry(element: T['element']): ElementEntry<T> | undefined;
|
||||
}
|
||||
export {};
|
||||
+193
@@ -0,0 +1,193 @@
|
||||
//Const
|
||||
const NOAH_ARK_CAPACITY = 3;
|
||||
export var EntryType;
|
||||
(function (EntryType) {
|
||||
EntryType[EntryType["Marker"] = 0] = "Marker";
|
||||
EntryType[EntryType["Element"] = 1] = "Element";
|
||||
})(EntryType || (EntryType = {}));
|
||||
//List of formatting elements
|
||||
export class FormattingElementList {
|
||||
constructor() {
|
||||
this.newest = null;
|
||||
this.bookmark = null;
|
||||
/** The index of the entries after the last marker; null only while there are at most NOAH_ARK_CAPACITY of them. */
|
||||
this.index = null;
|
||||
/** The entries by element, except possibly those after the last marker while they are not indexed. */
|
||||
this.elementEntries = new Map();
|
||||
}
|
||||
/** Returns the entry's ark, or null if the entries after the last marker are not indexed. */
|
||||
_insertElementEntry(element, token, older) {
|
||||
const newer = older === null ? null : older.newer;
|
||||
const entry = {
|
||||
type: EntryType.Element,
|
||||
element,
|
||||
token,
|
||||
older,
|
||||
newer,
|
||||
ark: null,
|
||||
olderSameTag: null,
|
||||
newerSameTag: null,
|
||||
};
|
||||
if (newer === null) {
|
||||
this.newest = entry;
|
||||
}
|
||||
else {
|
||||
newer.older = entry;
|
||||
}
|
||||
if (older !== null) {
|
||||
older.newer = entry;
|
||||
}
|
||||
return this.index === null ? null : this._addToIndex(this.index, entry);
|
||||
}
|
||||
_addToIndex(index, entry) {
|
||||
const { tagName, attrs } = entry.token;
|
||||
// Names are unique and the tokenizer replaces NUL, so the sorted pairs identify the attribute set.
|
||||
// Sorting costs O(k log k) comparisons for a tag with k attributes.
|
||||
const key = tagName +
|
||||
attrs
|
||||
.map(({ name, value }) => `\0${name}\0${value}`)
|
||||
.sort()
|
||||
.join('');
|
||||
let ark = index.arks.get(key);
|
||||
if (ark === undefined) {
|
||||
ark = { entries: [], key };
|
||||
index.arks.set(key, ark);
|
||||
}
|
||||
ark.entries.push(entry);
|
||||
entry.ark = ark;
|
||||
this.elementEntries.set(entry.element, entry);
|
||||
let head = index.tagNames.get(tagName);
|
||||
if (head === undefined) {
|
||||
head = { olderSameTag: null };
|
||||
index.tagNames.set(tagName, head);
|
||||
}
|
||||
entry.olderSameTag = head.olderSameTag;
|
||||
entry.newerSameTag = head;
|
||||
if (head.olderSameTag !== null) {
|
||||
head.olderSameTag.newerSameTag = entry;
|
||||
}
|
||||
head.olderSameTag = entry;
|
||||
return ark;
|
||||
}
|
||||
//Mutations
|
||||
insertMarker() {
|
||||
if (this.index === null) {
|
||||
for (let entry = this.newest; entry !== null && entry.type === EntryType.Element; entry = entry.older) {
|
||||
this.elementEntries.set(entry.element, entry);
|
||||
}
|
||||
}
|
||||
const marker = {
|
||||
type: EntryType.Marker,
|
||||
older: this.newest,
|
||||
newer: null,
|
||||
outerIndex: this.index,
|
||||
};
|
||||
if (this.newest !== null) {
|
||||
this.newest.newer = marker;
|
||||
}
|
||||
this.newest = marker;
|
||||
this.index = null;
|
||||
}
|
||||
pushElement(element, token) {
|
||||
if (this.index === null) {
|
||||
let oldest = null;
|
||||
let count = 0;
|
||||
for (let entry = this.newest; entry !== null && entry.type === EntryType.Element; entry = entry.older) {
|
||||
oldest = entry;
|
||||
count++;
|
||||
}
|
||||
if (count >= NOAH_ARK_CAPACITY) {
|
||||
this.index = { arks: new Map(), tagNames: new Map() };
|
||||
for (let entry = oldest; entry !== null && entry.type === EntryType.Element; entry = entry.newer) {
|
||||
this._addToIndex(this.index, entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
const ark = this._insertElementEntry(element, token, this.newest);
|
||||
if (ark !== null && ark.entries.length > NOAH_ARK_CAPACITY) {
|
||||
this.removeEntry(ark.entries[0]);
|
||||
}
|
||||
}
|
||||
insertElementAfterBookmark(element, token) {
|
||||
// Like the formatting element's entry that it replaces, this entry is the newest with its tag name. The bookmark
|
||||
// is used once per adoption-agency step and released here, so it does not keep a cleared region reachable.
|
||||
const { bookmark } = this;
|
||||
this.bookmark = null;
|
||||
this._insertElementEntry(element, token, bookmark);
|
||||
}
|
||||
removeEntry(entry) {
|
||||
var _a;
|
||||
// An `a` start tag removes its entry even when the adoption agency already has, so skip unlinked entries.
|
||||
if (entry.newer === null ? this.newest !== entry : entry.newer.older !== entry) {
|
||||
return;
|
||||
}
|
||||
this.elementEntries.delete(entry.element);
|
||||
if (entry.newer === null) {
|
||||
this.newest = entry.older;
|
||||
}
|
||||
else {
|
||||
entry.newer.older = entry.older;
|
||||
}
|
||||
if (entry.older !== null) {
|
||||
entry.older.newer = entry.newer;
|
||||
}
|
||||
if (entry.ark !== null) {
|
||||
const { entries, key } = entry.ark;
|
||||
entries.splice(entries.indexOf(entry), 1);
|
||||
// Entries are removed only after the last marker, so an emptied ark is dropped from the last region's index.
|
||||
if (entries.length === 0)
|
||||
(_a = this.index) === null || _a === void 0 ? void 0 : _a.arks.delete(key);
|
||||
}
|
||||
if (entry.newerSameTag !== null) {
|
||||
entry.newerSameTag.olderSameTag = entry.olderSameTag;
|
||||
if (entry.olderSameTag !== null) {
|
||||
entry.olderSameTag.newerSameTag = entry.newerSameTag;
|
||||
}
|
||||
}
|
||||
}
|
||||
replaceElement(entry, element) {
|
||||
if (this.elementEntries.delete(entry.element)) {
|
||||
this.elementEntries.set(element, entry);
|
||||
}
|
||||
entry.element = element;
|
||||
}
|
||||
/**
|
||||
* Clears the list of formatting elements up to the last marker.
|
||||
*
|
||||
* @see https://html.spec.whatwg.org/multipage/parsing.html#clear-the-list-of-active-formatting-elements-up-to-the-last-marker
|
||||
*/
|
||||
clearToLastMarker() {
|
||||
let marker = this.newest;
|
||||
for (; marker !== null && marker.type === EntryType.Element; marker = marker.older) {
|
||||
this.elementEntries.delete(marker.element);
|
||||
}
|
||||
this.newest = marker === null ? null : marker.older;
|
||||
this.index = marker === null ? null : marker.outerIndex;
|
||||
if (this.newest !== null) {
|
||||
this.newest.newer = null;
|
||||
}
|
||||
}
|
||||
//Search
|
||||
getElementEntryInScopeWithTagName(tagName) {
|
||||
var _a, _b;
|
||||
if (this.index !== null) {
|
||||
return (_b = (_a = this.index.tagNames.get(tagName)) === null || _a === void 0 ? void 0 : _a.olderSameTag) !== null && _b !== void 0 ? _b : null;
|
||||
}
|
||||
for (let entry = this.newest; entry !== null && entry.type === EntryType.Element; entry = entry.older) {
|
||||
if (entry.token.tagName === tagName) {
|
||||
return entry;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
getElementEntry(element) {
|
||||
if (this.index === null) {
|
||||
for (let entry = this.newest; entry !== null && entry.type === EntryType.Element; entry = entry.older) {
|
||||
if (entry.element === element) {
|
||||
return entry;
|
||||
}
|
||||
}
|
||||
}
|
||||
return this.elementEntries.get(element);
|
||||
}
|
||||
}
|
||||
+230
@@ -0,0 +1,230 @@
|
||||
import { Tokenizer, TokenizerMode, type TokenHandler } from '../tokenizer/index.js';
|
||||
import { OpenElementStack, type StackHandler } from './open-element-stack.js';
|
||||
import { FormattingElementList } from './formatting-element-list.js';
|
||||
import { ERR, type ParserErrorHandler } from '../common/error-codes.js';
|
||||
import { TAG_ID as $, NS } from '../common/html.js';
|
||||
import type { TreeAdapter, TreeAdapterTypeMap } from '../tree-adapters/interface.js';
|
||||
import { type Token, type CommentToken, type CharacterToken, type TagToken, type DoctypeToken, type EOFToken, type LocationWithAttributes, type Attribute } from '../common/token.js';
|
||||
export declare enum InsertionMode {
|
||||
INITIAL = 0,
|
||||
BEFORE_HTML = 1,
|
||||
BEFORE_HEAD = 2,
|
||||
IN_HEAD = 3,
|
||||
IN_HEAD_NO_SCRIPT = 4,
|
||||
AFTER_HEAD = 5,
|
||||
IN_BODY = 6,
|
||||
TEXT = 7,
|
||||
IN_TABLE = 8,
|
||||
IN_TABLE_TEXT = 9,
|
||||
IN_CAPTION = 10,
|
||||
IN_COLUMN_GROUP = 11,
|
||||
IN_TABLE_BODY = 12,
|
||||
IN_ROW = 13,
|
||||
IN_CELL = 14,
|
||||
IN_SELECT = 15,
|
||||
IN_SELECT_IN_TABLE = 16,
|
||||
IN_TEMPLATE = 17,
|
||||
AFTER_BODY = 18,
|
||||
IN_FRAMESET = 19,
|
||||
AFTER_FRAMESET = 20,
|
||||
AFTER_AFTER_BODY = 21,
|
||||
AFTER_AFTER_FRAMESET = 22
|
||||
}
|
||||
interface InsertionLocation<T extends TreeAdapterTypeMap> {
|
||||
parent: T['parentNode'];
|
||||
beforeElement: T['element'] | null;
|
||||
}
|
||||
export interface ParserOptions<T extends TreeAdapterTypeMap> {
|
||||
/**
|
||||
* The [scripting flag](https://html.spec.whatwg.org/multipage/parsing.html#scripting-flag). If set
|
||||
* to `true`, `noscript` element content will be parsed as text.
|
||||
*
|
||||
* @default `true`
|
||||
*/
|
||||
scriptingEnabled?: boolean;
|
||||
/**
|
||||
* Enables source code location information. When enabled, each node (except the root node)
|
||||
* will have a `sourceCodeLocation` property. If the node is not an empty element, `sourceCodeLocation` will
|
||||
* be a {@link ElementLocation} object, otherwise it will be {@link Location}.
|
||||
* If the element was implicitly created by the parser (as part of
|
||||
* [tree correction](https://html.spec.whatwg.org/multipage/syntax.html#an-introduction-to-error-handling-and-strange-cases-in-the-parser)),
|
||||
* its `sourceCodeLocation` property will be `undefined`.
|
||||
*
|
||||
* @default `false`
|
||||
*/
|
||||
sourceCodeLocationInfo?: boolean;
|
||||
/**
|
||||
* Specifies the resulting tree format.
|
||||
*
|
||||
* @default `treeAdapters.default`
|
||||
*/
|
||||
treeAdapter?: TreeAdapter<T>;
|
||||
/**
|
||||
* Callback for parse errors.
|
||||
*
|
||||
* @default `null`
|
||||
*/
|
||||
onParseError?: ParserErrorHandler | null;
|
||||
}
|
||||
export declare class Parser<T extends TreeAdapterTypeMap> implements TokenHandler, StackHandler<T> {
|
||||
/** @internal */
|
||||
fragmentContext: T['element'] | null;
|
||||
/** @internal */
|
||||
scriptHandler: null | ((pendingScript: T['element']) => void);
|
||||
treeAdapter: TreeAdapter<T>;
|
||||
/** @internal */
|
||||
onParseError: ParserErrorHandler | null;
|
||||
protected currentToken: Token | null;
|
||||
options: Required<ParserOptions<T>>;
|
||||
document: T['document'];
|
||||
constructor(options?: ParserOptions<T>, document?: T['document'],
|
||||
/** @internal */
|
||||
fragmentContext?: T['element'] | null,
|
||||
/** @internal */
|
||||
scriptHandler?: null | ((pendingScript: T['element']) => void));
|
||||
static parse<T extends TreeAdapterTypeMap>(html: string, options?: ParserOptions<T>): T['document'];
|
||||
static getFragmentParser<T extends TreeAdapterTypeMap>(fragmentContext?: T['parentNode'] | null, options?: ParserOptions<T>): Parser<T>;
|
||||
getFragment(): T['documentFragment'];
|
||||
tokenizer: Tokenizer;
|
||||
stopped: boolean;
|
||||
/** @internal */
|
||||
insertionMode: InsertionMode;
|
||||
/** @internal */
|
||||
originalInsertionMode: InsertionMode;
|
||||
/** @internal */
|
||||
fragmentContextID: $;
|
||||
/** @internal */
|
||||
headElement: null | T['element'];
|
||||
/** @internal */
|
||||
formElement: null | T['element'];
|
||||
/** @internal */
|
||||
openElements: OpenElementStack<T>;
|
||||
/** @internal */
|
||||
activeFormattingElements: FormattingElementList<T>;
|
||||
/** Indicates that the current node is not an element in the HTML namespace */
|
||||
protected currentNotInHTML: boolean;
|
||||
/**
|
||||
* The topmost template insertion mode is the last element.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
tmplInsertionModeStack: InsertionMode[];
|
||||
/** @internal */
|
||||
pendingCharacterTokens: CharacterToken[];
|
||||
/** @internal */
|
||||
hasNonWhitespacePendingCharacterToken: boolean;
|
||||
/** @internal */
|
||||
framesetOk: boolean;
|
||||
/** @internal */
|
||||
skipNextNewLine: boolean;
|
||||
/** @internal */
|
||||
fosterParentingEnabled: boolean;
|
||||
/** @internal */
|
||||
_err(token: Token, code: ERR, beforeToken?: boolean): void;
|
||||
/** @internal */
|
||||
onItemPush(node: T['parentNode'], tid: number, isTop: boolean): void;
|
||||
/** @internal */
|
||||
onItemPop(node: T['parentNode'], isTop: boolean): void;
|
||||
protected _setContextModes(current: T['parentNode'] | undefined, tid: number | undefined): void;
|
||||
/** @protected */
|
||||
_switchToTextParsing(currentToken: TagToken, nextTokenizerState: (typeof TokenizerMode)[keyof typeof TokenizerMode]): void;
|
||||
switchToPlaintextParsing(): void;
|
||||
/** @protected */
|
||||
_getAdjustedCurrentElement(): T['element'];
|
||||
/** @protected */
|
||||
_findFormInFragmentContext(): void;
|
||||
protected _initTokenizerForFragmentParsing(): void;
|
||||
/** @protected */
|
||||
_setDocumentType(token: DoctypeToken): void;
|
||||
/** @protected */
|
||||
_attachElementToTree(element: T['element'], location: LocationWithAttributes | null, insertionLocation: InsertionLocation<T>): void;
|
||||
/** @protected */
|
||||
_getInsertionLocation(): InsertionLocation<T>;
|
||||
/** @protected */
|
||||
_createElement(tagName: string, namespaceURI: NS, attrs: Attribute[], intendedParent: T['parentNode']): T['element'];
|
||||
/**
|
||||
* For self-closing tags. Add an element to the tree, but skip adding it
|
||||
* to the stack.
|
||||
*/
|
||||
/** @protected */
|
||||
_appendElement(token: TagToken, namespaceURI: NS): void;
|
||||
/** @protected */
|
||||
_insertElement(token: TagToken, namespaceURI: NS): void;
|
||||
/** @protected */
|
||||
_insertFakeElement(tagName: string, tagID: $): void;
|
||||
/** @protected */
|
||||
_insertTemplate(token: TagToken): void;
|
||||
/** @protected */
|
||||
_insertFakeRootElement(): void;
|
||||
/** @protected */
|
||||
_appendCommentNode(token: CommentToken, parent: T['parentNode']): void;
|
||||
/** @protected */
|
||||
_insertCharacters(token: CharacterToken): void;
|
||||
/** @protected */
|
||||
_adoptNodes(donor: T['parentNode'], recipient: T['parentNode']): void;
|
||||
/** @protected */
|
||||
_setEndLocation(element: T['element'], closingToken: Token): void;
|
||||
protected shouldProcessStartTagTokenInForeignContent(token: TagToken): boolean;
|
||||
/** @protected */
|
||||
_processToken(token: Token): void;
|
||||
/**
|
||||
* Whether each open MathML `annotation-xml` element, or the fragment context, is an HTML integration point. The
|
||||
* standard decides this by the element's start tag, so its attributes are read once; `onItemPop` drops the entry.
|
||||
*/
|
||||
private annotationXmlIntegrationPoints;
|
||||
/** @protected */
|
||||
_isIntegrationPoint(tid: $, element: T['element'], foreignNS?: NS): boolean;
|
||||
/** @protected */
|
||||
_reconstructActiveFormattingElements(): void;
|
||||
/** @protected */
|
||||
_closeTableCell(): void;
|
||||
/** @protected */
|
||||
_closePElement(): void;
|
||||
/** @protected */
|
||||
_resetInsertionMode(): void;
|
||||
/** @protected */
|
||||
_resetInsertionModeForSelect(selectIdx: number): void;
|
||||
/** @protected */
|
||||
_isElementCausesFosterParenting(tn: $): boolean;
|
||||
/** @protected */
|
||||
_shouldFosterParentOnInsertion(): boolean;
|
||||
/** @protected */
|
||||
_findFosterParentingLocation(): InsertionLocation<T>;
|
||||
/** @protected */
|
||||
_fosterParentElement(element: T['element']): void;
|
||||
/** @protected */
|
||||
_isSpecialElement(element: T['element'], id: $): boolean;
|
||||
/** @internal */
|
||||
onCharacter(token: CharacterToken): void;
|
||||
/** @internal */
|
||||
onNullCharacter(token: CharacterToken): void;
|
||||
/** @internal */
|
||||
onComment(token: CommentToken): void;
|
||||
/** @internal */
|
||||
onDoctype(token: DoctypeToken): void;
|
||||
/** @internal */
|
||||
onStartTag(token: TagToken): void;
|
||||
/**
|
||||
* Processes a given start tag.
|
||||
*
|
||||
* `onStartTag` checks if a self-closing tag was recognized. When a token
|
||||
* is moved inbetween multiple insertion modes, this check for self-closing
|
||||
* could lead to false positives. To avoid this, `_processStartTag` is used
|
||||
* for nested calls.
|
||||
*
|
||||
* @param token The token to process.
|
||||
* @protected
|
||||
*/
|
||||
_processStartTag(token: TagToken): void;
|
||||
/** @protected */
|
||||
_startTagOutsideForeignContent(token: TagToken): void;
|
||||
/** @internal */
|
||||
onEndTag(token: TagToken): void;
|
||||
/** @protected */
|
||||
_endTagOutsideForeignContent(token: TagToken): void;
|
||||
/** @internal */
|
||||
onEof(token: EOFToken): void;
|
||||
/** @internal */
|
||||
onWhitespaceCharacter(token: CharacterToken): void;
|
||||
}
|
||||
export {};
|
||||
+3308
File diff suppressed because it is too large
Load Diff
+130
@@ -0,0 +1,130 @@
|
||||
import { TAG_ID as $, NS } from '../common/html.js';
|
||||
import type { TreeAdapter, TreeAdapterTypeMap } from '../tree-adapters/interface.js';
|
||||
export interface StackHandler<T extends TreeAdapterTypeMap> {
|
||||
onItemPush: (node: T['parentNode'], tid: number, isTop: boolean) => void;
|
||||
onItemPop: (node: T['parentNode'], isTop: boolean) => void;
|
||||
}
|
||||
/**
|
||||
* The stack of open elements. Each element has a slot in `items` and `tagIDs`. Once the stack is `INDEX_DEPTH` deep, it
|
||||
* indexes its elements so that the searches the parser repeats per token take constant time: it chains the elements
|
||||
* with each key, so that the topmost one is found without a scan, and counts per slot the special elements and scope
|
||||
* boundaries at or below it, which tell whether one lies between two slots. Removing an element from the middle then
|
||||
* leaves its slot free instead of moving the elements above it; `slotBelow` and `slotAbove` step over free slots, and
|
||||
* `depth` counts the open elements.
|
||||
*/
|
||||
export declare class OpenElementStack<T extends TreeAdapterTypeMap> {
|
||||
private treeAdapter;
|
||||
private handler;
|
||||
items: T['parentNode'][];
|
||||
tagIDs: $[];
|
||||
current: T['parentNode'] | undefined;
|
||||
/** The slot of the current element. */
|
||||
stackTop: number;
|
||||
/** The number of open elements. */
|
||||
depth: number;
|
||||
tmplCount: number;
|
||||
currentTagId: number | undefined;
|
||||
private indexed;
|
||||
/** The slot of the open element below, and above, each open element's slot; -1 for none. */
|
||||
private below;
|
||||
private above;
|
||||
private keys;
|
||||
/** The slot of the next lower, and higher, open element with the same key; -1 for none. */
|
||||
private keyPrev;
|
||||
private keyNext;
|
||||
/** The slot of the topmost open element with each key, -1 for none. */
|
||||
private keyTops;
|
||||
private nameKeys;
|
||||
/** Per slot, the open special elements, list item boundaries and scope boundaries at or below it. */
|
||||
private specials;
|
||||
private listItemBoundaries;
|
||||
private scopeBoundaries;
|
||||
/** Per slot, the slot of the topmost open HTML element at or below it, or -1. */
|
||||
private htmlSlots;
|
||||
private formattingSlots;
|
||||
get currentTmplContentOrNode(): T['parentNode'];
|
||||
constructor(document: T['document'], treeAdapter: TreeAdapter<T>, handler: StackHandler<T>);
|
||||
/** The slot of an open element, or -1. */
|
||||
_indexOf(element: T['element']): number;
|
||||
/** The slot of the open element below the one at `idx`, or -1. */
|
||||
slotBelow(idx: number): number;
|
||||
/** The slot of the open element above the one at `idx`, or -1. */
|
||||
slotAbove(idx: number): number;
|
||||
private _isInTemplate;
|
||||
private _updateCurrentElement;
|
||||
private _nameKey;
|
||||
/** Indexes the open elements once the stack is `INDEX_DEPTH` deep. */
|
||||
private _indexAll;
|
||||
/** Indexes the element at `slot`, above the open element at `belowIdx`. */
|
||||
private _index;
|
||||
/** Puts the indexed element at `slot` above the one at `belowIdx`, and counts the elements of each class. */
|
||||
private _link;
|
||||
/** Takes the element at `slot` out of the index, except for the links between slots. */
|
||||
private _unindex;
|
||||
/** Moves the indexed element at `from` down to the free slot `to`, keeping its key chain in order. */
|
||||
private _move;
|
||||
/** The slot of the topmost open HTML element with this tag, or -1. */
|
||||
indexOfTopmost(tagID: $): number;
|
||||
/** The slot of the topmost open HTML element with any of these tags, or -1. */
|
||||
indexOfTopmostOf(tagIDs: readonly $[]): number;
|
||||
/** The slot of the topmost open element in this namespace with this tag name, or -1. */
|
||||
indexOfTopmostByName(ns: NS, tagName: string): number;
|
||||
/** The slot of the topmost open HTML element, or -1. */
|
||||
indexOfTopmostHtmlElement(): number;
|
||||
/** Whether an element of the classes is open above the slot `idx`, on a stack that is not indexed. */
|
||||
private _hasAbove;
|
||||
/** Whether a special element is open above the slot `idx`. */
|
||||
hasSpecialElementAbove(idx: number): boolean;
|
||||
/** Whether a special element other than HTML `address`, `div` and `p` is open above the slot `idx`. */
|
||||
hasListItemBoundaryAbove(idx: number): boolean;
|
||||
push(element: T['element'], tagID: $): void;
|
||||
/** Pops the current element without calling the handler. */
|
||||
private _popCurrent;
|
||||
pop(): void;
|
||||
replace(oldElement: T['element'], newElement: T['element']): void;
|
||||
/**
|
||||
* The adoption agency's last stack step: removes the formatting element at `formattingIdx` and opens `element`
|
||||
* directly above the furthest block at `furthestBlockIdx`. On an indexed stack, only formatting elements the agency
|
||||
* kept are still open between them; the furthest block, with those directly below it, moves down by one slot, and
|
||||
* `element` takes the furthest block's slot. No open element above the furthest block moves, and as all these
|
||||
* elements are HTML elements and only the furthest block is special, the counts above it stay the same.
|
||||
*/
|
||||
replaceFormattingElement(formattingIdx: number, furthestBlockIdx: number, element: T['element'], tagID: $): void;
|
||||
popUntilTagNamePopped(tagName: $): void;
|
||||
shortenToLength(idx: number): void;
|
||||
popUntilElementPopped(element: T['element']): void;
|
||||
popUntilNumberedHeaderPopped(): void;
|
||||
popUntilTableCellPopped(): void;
|
||||
popAllUpToHtmlElement(): void;
|
||||
clearBackToTableContext(): void;
|
||||
clearBackToTableBodyContext(): void;
|
||||
clearBackToTableRowContext(): void;
|
||||
remove(element: T['element']): void;
|
||||
/** Removes the open element at the slot `idx`; on an indexed stack, the elements above it keep their slots. */
|
||||
removeAt(idx: number): void;
|
||||
tryPeekProperlyNestedBodyElement(): T['element'] | null;
|
||||
contains(element: T['element']): boolean;
|
||||
getCommonAncestor(element: T['element']): T['element'] | null;
|
||||
isRootHtmlElementCurrent(): boolean;
|
||||
/**
|
||||
* On an indexed stack: whether no element of the `scope` class is open above the slot `target`. A target that is not
|
||||
* open is in scope only on a stack without such an element, as a scan from the top would end there.
|
||||
*/
|
||||
private _isInScope;
|
||||
/**
|
||||
* On a stack that is not indexed: whether an HTML element with the tag, or one of the tags, and if passed the element
|
||||
* itself, is open above every element of the `scope` class; true if neither is open.
|
||||
*/
|
||||
private _scanScope;
|
||||
/** If `element` is passed, only that element (which has to be a `tagName` element) is looked for. */
|
||||
hasInScope(tagName: $, element?: T['element'] | null): boolean;
|
||||
hasInListItemScope(tagName: $): boolean;
|
||||
hasInButtonScope(tagName: $): boolean;
|
||||
hasNumberedHeaderInScope(): boolean;
|
||||
hasInTableScope(tagName: $): boolean;
|
||||
hasTableBodyContextInTableScope(): boolean;
|
||||
hasInSelectScope(tagName: $): boolean;
|
||||
generateImpliedEndTags(): void;
|
||||
generateImpliedEndTagsThoroughly(): void;
|
||||
generateImpliedEndTagsWithExclusion(exclusionId: $): void;
|
||||
}
|
||||
+674
@@ -0,0 +1,674 @@
|
||||
import { TAG_ID as $, NS, SPECIAL_ELEMENTS, getTagID } from '../common/html.js';
|
||||
//Element utils
|
||||
const IMPLICIT_END_TAG_REQUIRED = new Set([$.DD, $.DT, $.LI, $.OPTGROUP, $.OPTION, $.P, $.RB, $.RP, $.RT, $.RTC]);
|
||||
const IMPLICIT_END_TAG_REQUIRED_THOROUGHLY = new Set([
|
||||
...IMPLICIT_END_TAG_REQUIRED,
|
||||
$.CAPTION,
|
||||
$.COLGROUP,
|
||||
$.TBODY,
|
||||
$.TD,
|
||||
$.TFOOT,
|
||||
$.TH,
|
||||
$.THEAD,
|
||||
$.TR,
|
||||
]);
|
||||
/** A stack this deep starts to index its elements; a shallower one is cheaper to scan than to index. */
|
||||
const INDEX_DEPTH = 64;
|
||||
/*
|
||||
* Every open element has a key: an HTML element its tag ID, an SVG or MathML element its tag ID plus the offsets below,
|
||||
* and any other element (an unknown tag, or another namespace) a key from `NAME_KEYS` up, assigned per stack by
|
||||
* namespace and tag name.
|
||||
*/
|
||||
const SVG_KEYS = 256;
|
||||
const MATHML_KEYS = 512;
|
||||
const NAME_KEYS = 768;
|
||||
const NUMBERED_HEADERS = [$.H1, $.H2, $.H3, $.H4, $.H5, $.H6];
|
||||
const TABLE_BODIES = [$.TBODY, $.TFOOT, $.THEAD];
|
||||
const TABLE_ROW_CONTEXT = [$.TR, $.TEMPLATE, $.HTML];
|
||||
const TABLE_BODY_CONTEXT = [...TABLE_BODIES, $.TEMPLATE, $.HTML];
|
||||
const TABLE_CONTEXT = [$.TABLE, $.TEMPLATE, $.HTML];
|
||||
const TABLE_CELLS = [$.TD, $.TH];
|
||||
// Classes of keys: special elements, the special elements that end the search for a list item to close (all but
|
||||
// HTML `address`, `div` and `p`), and the elements that bound each kind of scope.
|
||||
const SPECIAL = 1;
|
||||
const LIST_ITEM_BOUNDARY = 2;
|
||||
const SCOPE = 4;
|
||||
const LIST_ITEM_SCOPE = 8;
|
||||
const BUTTON_SCOPE = 16;
|
||||
const TABLE_SCOPE = 32;
|
||||
const KEY_CLASSES = new Uint8Array(NAME_KEYS);
|
||||
for (const [ns, offset] of [
|
||||
[NS.HTML, 0],
|
||||
[NS.SVG, SVG_KEYS],
|
||||
[NS.MATHML, MATHML_KEYS],
|
||||
]) {
|
||||
for (const tn of SPECIAL_ELEMENTS[ns]) {
|
||||
KEY_CLASSES[offset + tn] =
|
||||
ns === NS.HTML && (tn === $.ADDRESS || tn === $.DIV || tn === $.P) ? SPECIAL : SPECIAL | LIST_ITEM_BOUNDARY;
|
||||
}
|
||||
}
|
||||
for (const key of [
|
||||
$.APPLET,
|
||||
$.CAPTION,
|
||||
$.HTML,
|
||||
$.MARQUEE,
|
||||
$.OBJECT,
|
||||
$.TABLE,
|
||||
$.TD,
|
||||
$.TEMPLATE,
|
||||
$.TH,
|
||||
SVG_KEYS + $.DESC,
|
||||
SVG_KEYS + $.FOREIGN_OBJECT,
|
||||
SVG_KEYS + $.TITLE,
|
||||
MATHML_KEYS + $.ANNOTATION_XML,
|
||||
MATHML_KEYS + $.MI,
|
||||
MATHML_KEYS + $.MN,
|
||||
MATHML_KEYS + $.MO,
|
||||
MATHML_KEYS + $.MS,
|
||||
MATHML_KEYS + $.MTEXT,
|
||||
]) {
|
||||
KEY_CLASSES[key] |= SCOPE | LIST_ITEM_SCOPE | BUTTON_SCOPE;
|
||||
}
|
||||
KEY_CLASSES[$.OL] |= LIST_ITEM_SCOPE;
|
||||
KEY_CLASSES[$.UL] |= LIST_ITEM_SCOPE;
|
||||
KEY_CLASSES[$.BUTTON] |= BUTTON_SCOPE;
|
||||
KEY_CLASSES[$.TABLE] |= TABLE_SCOPE;
|
||||
KEY_CLASSES[$.HTML] |= TABLE_SCOPE;
|
||||
// The adoption agency and the reconstruction look up formatting elements by element.
|
||||
const FORMATTING_TAGS = new Uint8Array(NAME_KEYS);
|
||||
for (const tn of [$.A, $.B, $.BIG, $.CODE, $.EM, $.FONT, $.I, $.NOBR, $.S, $.SMALL, $.STRIKE, $.STRONG, $.TT, $.U]) {
|
||||
FORMATTING_TAGS[tn] = 1;
|
||||
}
|
||||
/** The key of an element with a tag ID in HTML, SVG or MathML, or -1 for an element keyed by its name. */
|
||||
function tagKey(ns, tagID) {
|
||||
if (tagID === $.UNKNOWN)
|
||||
return -1;
|
||||
switch (ns) {
|
||||
case NS.HTML: {
|
||||
return tagID;
|
||||
}
|
||||
case NS.SVG: {
|
||||
return SVG_KEYS + tagID;
|
||||
}
|
||||
case NS.MATHML: {
|
||||
return MATHML_KEYS + tagID;
|
||||
}
|
||||
default: {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* The stack of open elements. Each element has a slot in `items` and `tagIDs`. Once the stack is `INDEX_DEPTH` deep, it
|
||||
* indexes its elements so that the searches the parser repeats per token take constant time: it chains the elements
|
||||
* with each key, so that the topmost one is found without a scan, and counts per slot the special elements and scope
|
||||
* boundaries at or below it, which tell whether one lies between two slots. Removing an element from the middle then
|
||||
* leaves its slot free instead of moving the elements above it; `slotBelow` and `slotAbove` step over free slots, and
|
||||
* `depth` counts the open elements.
|
||||
*/
|
||||
export class OpenElementStack {
|
||||
get currentTmplContentOrNode() {
|
||||
return this._isInTemplate() ? this.treeAdapter.getTemplateContent(this.current) : this.current;
|
||||
}
|
||||
constructor(document, treeAdapter, handler) {
|
||||
this.treeAdapter = treeAdapter;
|
||||
this.handler = handler;
|
||||
this.items = [];
|
||||
this.tagIDs = [];
|
||||
/** The slot of the current element. */
|
||||
this.stackTop = -1;
|
||||
/** The number of open elements. */
|
||||
this.depth = 0;
|
||||
this.tmplCount = 0;
|
||||
this.currentTagId = $.UNKNOWN;
|
||||
this.indexed = false;
|
||||
/** The slot of the open element below, and above, each open element's slot; -1 for none. */
|
||||
this.below = [];
|
||||
this.above = [];
|
||||
this.keys = [];
|
||||
/** The slot of the next lower, and higher, open element with the same key; -1 for none. */
|
||||
this.keyPrev = [];
|
||||
this.keyNext = [];
|
||||
/** The slot of the topmost open element with each key, -1 for none. */
|
||||
this.keyTops = new Int32Array(0);
|
||||
/** Per slot, the open special elements, list item boundaries and scope boundaries at or below it. */
|
||||
this.specials = [];
|
||||
this.listItemBoundaries = [];
|
||||
this.scopeBoundaries = [];
|
||||
/** Per slot, the slot of the topmost open HTML element at or below it, or -1. */
|
||||
this.htmlSlots = [];
|
||||
this.formattingSlots = new Map();
|
||||
this.current = document;
|
||||
}
|
||||
/** The slot of an open element, or -1. */
|
||||
_indexOf(element) {
|
||||
if (this.indexed) {
|
||||
const idx = this.formattingSlots.get(element);
|
||||
if (idx !== undefined)
|
||||
return idx;
|
||||
// A formatting element is in `formattingSlots` while it is open.
|
||||
if (FORMATTING_TAGS[getTagID(this.treeAdapter.getTagName(element))])
|
||||
return -1;
|
||||
}
|
||||
return this.items.lastIndexOf(element, this.stackTop);
|
||||
}
|
||||
/** The slot of the open element below the one at `idx`, or -1. */
|
||||
slotBelow(idx) {
|
||||
return this.indexed ? this.below[idx] : idx - 1;
|
||||
}
|
||||
/** The slot of the open element above the one at `idx`, or -1. */
|
||||
slotAbove(idx) {
|
||||
if (this.indexed)
|
||||
return this.above[idx];
|
||||
return idx === this.stackTop ? -1 : idx + 1;
|
||||
}
|
||||
//Update current element
|
||||
_isInTemplate() {
|
||||
return this.currentTagId === $.TEMPLATE && this.treeAdapter.getNamespaceURI(this.current) === NS.HTML;
|
||||
}
|
||||
_updateCurrentElement() {
|
||||
this.current = this.items[this.stackTop];
|
||||
this.currentTagId = this.tagIDs[this.stackTop];
|
||||
}
|
||||
//Index
|
||||
_nameKey(ns, tagName, create) {
|
||||
var _a, _b;
|
||||
const name = `${ns} ${tagName}`;
|
||||
let key = (_a = this.nameKeys) === null || _a === void 0 ? void 0 : _a.get(name);
|
||||
if (key === undefined && create) {
|
||||
(_b = this.nameKeys) !== null && _b !== void 0 ? _b : (this.nameKeys = new Map());
|
||||
key = NAME_KEYS + this.nameKeys.size;
|
||||
this.nameKeys.set(name, key);
|
||||
if (key === this.keyTops.length) {
|
||||
const keyTops = new Int32Array(2 * key).fill(-1);
|
||||
keyTops.set(this.keyTops);
|
||||
this.keyTops = keyTops;
|
||||
}
|
||||
}
|
||||
return key !== null && key !== void 0 ? key : -1;
|
||||
}
|
||||
/** Indexes the open elements once the stack is `INDEX_DEPTH` deep. */
|
||||
_indexAll() {
|
||||
this.indexed = true;
|
||||
this.keyTops = new Int32Array(NAME_KEYS).fill(-1);
|
||||
for (let i = 0; i <= this.stackTop; i++)
|
||||
this._index(i, i - 1);
|
||||
}
|
||||
/** Indexes the element at `slot`, above the open element at `belowIdx`. */
|
||||
_index(slot, belowIdx) {
|
||||
const element = this.items[slot];
|
||||
const tagID = this.tagIDs[slot];
|
||||
const ns = this.treeAdapter.getNamespaceURI(element);
|
||||
let key = tagKey(ns, tagID);
|
||||
if (key === -1)
|
||||
key = this._nameKey(ns, this.treeAdapter.getTagName(element), true);
|
||||
const keyPrev = this.keyTops[key];
|
||||
this.keys[slot] = key;
|
||||
this.keyPrev[slot] = keyPrev;
|
||||
this.keyNext[slot] = -1;
|
||||
if (keyPrev !== -1)
|
||||
this.keyNext[keyPrev] = slot;
|
||||
this.keyTops[key] = slot;
|
||||
this.above[slot] = -1;
|
||||
this._link(slot, belowIdx, ns === NS.HTML);
|
||||
if (FORMATTING_TAGS[tagID])
|
||||
this.formattingSlots.set(element, slot);
|
||||
}
|
||||
/** Puts the indexed element at `slot` above the one at `belowIdx`, and counts the elements of each class. */
|
||||
_link(slot, belowIdx, isHtml) {
|
||||
const key = this.keys[slot];
|
||||
const classes = key < NAME_KEYS ? KEY_CLASSES[key] : 0;
|
||||
this.below[slot] = belowIdx;
|
||||
if (belowIdx === -1) {
|
||||
this.specials[slot] = classes & SPECIAL;
|
||||
this.listItemBoundaries[slot] = (classes & LIST_ITEM_BOUNDARY) >> 1;
|
||||
this.scopeBoundaries[slot] = (classes & SCOPE) >> 2;
|
||||
this.htmlSlots[slot] = isHtml ? slot : -1;
|
||||
}
|
||||
else {
|
||||
this.above[belowIdx] = slot;
|
||||
this.specials[slot] = this.specials[belowIdx] + (classes & SPECIAL);
|
||||
this.listItemBoundaries[slot] = this.listItemBoundaries[belowIdx] + ((classes & LIST_ITEM_BOUNDARY) >> 1);
|
||||
this.scopeBoundaries[slot] = this.scopeBoundaries[belowIdx] + ((classes & SCOPE) >> 2);
|
||||
this.htmlSlots[slot] = isHtml ? slot : this.htmlSlots[belowIdx];
|
||||
}
|
||||
}
|
||||
/** Takes the element at `slot` out of the index, except for the links between slots. */
|
||||
_unindex(slot) {
|
||||
const key = this.keys[slot];
|
||||
const keyPrev = this.keyPrev[slot];
|
||||
const keyNext = this.keyNext[slot];
|
||||
if (keyPrev !== -1)
|
||||
this.keyNext[keyPrev] = keyNext;
|
||||
if (keyNext === -1)
|
||||
this.keyTops[key] = keyPrev;
|
||||
else
|
||||
this.keyPrev[keyNext] = keyPrev;
|
||||
if (FORMATTING_TAGS[this.tagIDs[slot]])
|
||||
this.formattingSlots.delete(this.items[slot]);
|
||||
}
|
||||
/** Moves the indexed element at `from` down to the free slot `to`, keeping its key chain in order. */
|
||||
_move(from, to) {
|
||||
const element = this.items[from];
|
||||
const key = this.keys[from];
|
||||
const keyPrev = this.keyPrev[from];
|
||||
const keyNext = this.keyNext[from];
|
||||
this.items[to] = element;
|
||||
this.tagIDs[to] = this.tagIDs[from];
|
||||
this.keys[to] = key;
|
||||
this.keyPrev[to] = keyPrev;
|
||||
this.keyNext[to] = keyNext;
|
||||
if (keyPrev !== -1)
|
||||
this.keyNext[keyPrev] = to;
|
||||
if (keyNext === -1)
|
||||
this.keyTops[key] = to;
|
||||
else
|
||||
this.keyPrev[keyNext] = to;
|
||||
if (FORMATTING_TAGS[this.tagIDs[to]])
|
||||
this.formattingSlots.set(element, to);
|
||||
}
|
||||
//Search by tag
|
||||
/** The slot of the topmost open HTML element with this tag, or -1. */
|
||||
indexOfTopmost(tagID) {
|
||||
if (this.indexed)
|
||||
return this.keyTops[tagID];
|
||||
for (let i = this.stackTop; i >= 0; i--) {
|
||||
if (this.tagIDs[i] === tagID && this.treeAdapter.getNamespaceURI(this.items[i]) === NS.HTML)
|
||||
return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
/** The slot of the topmost open HTML element with any of these tags, or -1. */
|
||||
indexOfTopmostOf(tagIDs) {
|
||||
if (this.indexed) {
|
||||
let top = -1;
|
||||
for (const tagID of tagIDs) {
|
||||
if (this.keyTops[tagID] > top)
|
||||
top = this.keyTops[tagID];
|
||||
}
|
||||
return top;
|
||||
}
|
||||
for (let i = this.stackTop; i >= 0; i--) {
|
||||
if (tagIDs.includes(this.tagIDs[i]) && this.treeAdapter.getNamespaceURI(this.items[i]) === NS.HTML)
|
||||
return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
/** The slot of the topmost open element in this namespace with this tag name, or -1. */
|
||||
indexOfTopmostByName(ns, tagName) {
|
||||
if (this.indexed) {
|
||||
let key = tagKey(ns, getTagID(tagName));
|
||||
if (key === -1)
|
||||
key = this._nameKey(ns, tagName, false);
|
||||
return key === -1 ? -1 : this.keyTops[key];
|
||||
}
|
||||
for (let i = this.stackTop; i >= 0; i--) {
|
||||
const element = this.items[i];
|
||||
if (this.treeAdapter.getTagName(element) === tagName && this.treeAdapter.getNamespaceURI(element) === ns) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
/** The slot of the topmost open HTML element, or -1. */
|
||||
indexOfTopmostHtmlElement() {
|
||||
if (this.indexed)
|
||||
return this.stackTop === -1 ? -1 : this.htmlSlots[this.stackTop];
|
||||
let i = this.stackTop;
|
||||
while (i >= 0 && this.treeAdapter.getNamespaceURI(this.items[i]) !== NS.HTML)
|
||||
i--;
|
||||
return i;
|
||||
}
|
||||
/** Whether an element of the classes is open above the slot `idx`, on a stack that is not indexed. */
|
||||
_hasAbove(idx, classes) {
|
||||
for (let i = this.stackTop; i > idx; i--) {
|
||||
const key = tagKey(this.treeAdapter.getNamespaceURI(this.items[i]), this.tagIDs[i]);
|
||||
if (key !== -1 && KEY_CLASSES[key] & classes)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
/** Whether a special element is open above the slot `idx`. */
|
||||
hasSpecialElementAbove(idx) {
|
||||
return this.indexed ? this.specials[this.stackTop] !== this.specials[idx] : this._hasAbove(idx, SPECIAL);
|
||||
}
|
||||
/** Whether a special element other than HTML `address`, `div` and `p` is open above the slot `idx`. */
|
||||
hasListItemBoundaryAbove(idx) {
|
||||
return this.indexed
|
||||
? this.listItemBoundaries[this.stackTop] !== this.listItemBoundaries[idx]
|
||||
: this._hasAbove(idx, LIST_ITEM_BOUNDARY);
|
||||
}
|
||||
//Mutations
|
||||
push(element, tagID) {
|
||||
const belowIdx = this.stackTop;
|
||||
this.stackTop++;
|
||||
this.depth++;
|
||||
this.items[this.stackTop] = element;
|
||||
this.current = element;
|
||||
this.tagIDs[this.stackTop] = tagID;
|
||||
this.currentTagId = tagID;
|
||||
if (this.indexed)
|
||||
this._index(this.stackTop, belowIdx);
|
||||
else if (this.depth === INDEX_DEPTH)
|
||||
this._indexAll();
|
||||
if (this._isInTemplate()) {
|
||||
this.tmplCount++;
|
||||
}
|
||||
this.handler.onItemPush(element, tagID, true);
|
||||
}
|
||||
/** Pops the current element without calling the handler. */
|
||||
_popCurrent() {
|
||||
if (this.tmplCount > 0 && this._isInTemplate()) {
|
||||
this.tmplCount--;
|
||||
}
|
||||
if (this.indexed) {
|
||||
this._unindex(this.stackTop);
|
||||
this.stackTop = this.below[this.stackTop];
|
||||
if (this.stackTop !== -1)
|
||||
this.above[this.stackTop] = -1;
|
||||
}
|
||||
else {
|
||||
this.stackTop--;
|
||||
}
|
||||
this.depth--;
|
||||
this._updateCurrentElement();
|
||||
}
|
||||
pop() {
|
||||
const popped = this.current;
|
||||
this._popCurrent();
|
||||
this.handler.onItemPop(popped, true);
|
||||
}
|
||||
replace(oldElement, newElement) {
|
||||
const idx = this._indexOf(oldElement);
|
||||
this.items[idx] = newElement;
|
||||
if (this.indexed && FORMATTING_TAGS[this.tagIDs[idx]]) {
|
||||
this.formattingSlots.delete(oldElement);
|
||||
this.formattingSlots.set(newElement, idx);
|
||||
}
|
||||
if (idx === this.stackTop) {
|
||||
this.current = newElement;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* The adoption agency's last stack step: removes the formatting element at `formattingIdx` and opens `element`
|
||||
* directly above the furthest block at `furthestBlockIdx`. On an indexed stack, only formatting elements the agency
|
||||
* kept are still open between them; the furthest block, with those directly below it, moves down by one slot, and
|
||||
* `element` takes the furthest block's slot. No open element above the furthest block moves, and as all these
|
||||
* elements are HTML elements and only the furthest block is special, the counts above it stay the same.
|
||||
*/
|
||||
replaceFormattingElement(formattingIdx, furthestBlockIdx, element, tagID) {
|
||||
const formattingElement = this.items[formattingIdx];
|
||||
if (!this.indexed) {
|
||||
this.items.splice(formattingIdx, 1);
|
||||
this.tagIDs.splice(formattingIdx, 1);
|
||||
this.handler.onItemPop(formattingElement, false);
|
||||
this.items.splice(furthestBlockIdx, 0, element);
|
||||
this.tagIDs.splice(furthestBlockIdx, 0, tagID);
|
||||
if (furthestBlockIdx === this.stackTop)
|
||||
this._updateCurrentElement();
|
||||
if (this.current && this.currentTagId !== undefined) {
|
||||
this.handler.onItemPush(this.current, this.currentTagId, furthestBlockIdx === this.stackTop);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const key = this.keys[formattingIdx];
|
||||
const belowIdx = this.below[formattingIdx];
|
||||
const aboveIdx = this.above[furthestBlockIdx];
|
||||
const kept = [];
|
||||
for (let i = this.above[formattingIdx]; i !== furthestBlockIdx; i = this.above[i])
|
||||
kept.push(i);
|
||||
// The list keeps open formatting elements in stack order, so a kept element with the formatting element's tag
|
||||
// would have been the formatting element: the next element with its key is above the furthest block.
|
||||
const keyNext = this.keyNext[formattingIdx];
|
||||
this._unindex(formattingIdx);
|
||||
this.items[formattingIdx] = undefined;
|
||||
this.handler.onItemPop(formattingElement, false);
|
||||
let free = furthestBlockIdx - 1;
|
||||
while (kept.length > 0 && kept[kept.length - 1] === free) {
|
||||
kept.pop();
|
||||
free--;
|
||||
}
|
||||
for (let i = free + 1; i <= furthestBlockIdx; i++)
|
||||
this._move(i, i - 1);
|
||||
const keyPrev = keyNext === -1 ? this.keyTops[key] : this.keyPrev[keyNext];
|
||||
this.items[furthestBlockIdx] = element;
|
||||
this.tagIDs[furthestBlockIdx] = tagID;
|
||||
this.keys[furthestBlockIdx] = key;
|
||||
this.keyPrev[furthestBlockIdx] = keyPrev;
|
||||
this.keyNext[furthestBlockIdx] = keyNext;
|
||||
if (keyPrev !== -1)
|
||||
this.keyNext[keyPrev] = furthestBlockIdx;
|
||||
if (keyNext === -1)
|
||||
this.keyTops[key] = furthestBlockIdx;
|
||||
else
|
||||
this.keyPrev[keyNext] = furthestBlockIdx;
|
||||
if (FORMATTING_TAGS[tagID])
|
||||
this.formattingSlots.set(element, furthestBlockIdx);
|
||||
let prev = belowIdx;
|
||||
for (const i of kept) {
|
||||
this._link(i, prev, true);
|
||||
prev = i;
|
||||
}
|
||||
for (let i = free; i < furthestBlockIdx; i++) {
|
||||
this._link(i, prev, true);
|
||||
prev = i;
|
||||
}
|
||||
this._link(furthestBlockIdx, prev, true);
|
||||
if (aboveIdx === -1)
|
||||
this._updateCurrentElement();
|
||||
if (this.current && this.currentTagId !== undefined) {
|
||||
this.handler.onItemPush(this.current, this.currentTagId, aboveIdx === -1);
|
||||
}
|
||||
}
|
||||
popUntilTagNamePopped(tagName) {
|
||||
this.shortenToLength(Math.max(this.indexOfTopmost(tagName), 0));
|
||||
}
|
||||
shortenToLength(idx) {
|
||||
while (this.stackTop >= idx) {
|
||||
const popped = this.current;
|
||||
this._popCurrent();
|
||||
this.handler.onItemPop(popped, this.stackTop < idx);
|
||||
}
|
||||
}
|
||||
popUntilElementPopped(element) {
|
||||
const idx = this._indexOf(element);
|
||||
this.shortenToLength(Math.max(idx, 0));
|
||||
}
|
||||
popUntilNumberedHeaderPopped() {
|
||||
this.shortenToLength(Math.max(this.indexOfTopmostOf(NUMBERED_HEADERS), 0));
|
||||
}
|
||||
popUntilTableCellPopped() {
|
||||
this.shortenToLength(Math.max(this.indexOfTopmostOf(TABLE_CELLS), 0));
|
||||
}
|
||||
popAllUpToHtmlElement() {
|
||||
//NOTE: here we assume that the root <html> element is always first in the open element stack, so
|
||||
//we perform this fast stack clean up.
|
||||
this.tmplCount = 0;
|
||||
this.shortenToLength(1);
|
||||
}
|
||||
clearBackToTableContext() {
|
||||
this.shortenToLength(this.indexOfTopmostOf(TABLE_CONTEXT) + 1);
|
||||
}
|
||||
clearBackToTableBodyContext() {
|
||||
this.shortenToLength(this.indexOfTopmostOf(TABLE_BODY_CONTEXT) + 1);
|
||||
}
|
||||
clearBackToTableRowContext() {
|
||||
this.shortenToLength(this.indexOfTopmostOf(TABLE_ROW_CONTEXT) + 1);
|
||||
}
|
||||
remove(element) {
|
||||
const idx = this._indexOf(element);
|
||||
if (idx !== -1)
|
||||
this.removeAt(idx);
|
||||
}
|
||||
/** Removes the open element at the slot `idx`; on an indexed stack, the elements above it keep their slots. */
|
||||
removeAt(idx) {
|
||||
if (idx === this.stackTop) {
|
||||
this.pop();
|
||||
return;
|
||||
}
|
||||
const element = this.items[idx];
|
||||
this.depth--;
|
||||
if (this.indexed) {
|
||||
const classes = this.keys[idx] < NAME_KEYS ? KEY_CLASSES[this.keys[idx]] : 0;
|
||||
const belowIdx = this.below[idx];
|
||||
const aboveIdx = this.above[idx];
|
||||
this._unindex(idx);
|
||||
this.items[idx] = undefined;
|
||||
this.below[aboveIdx] = belowIdx;
|
||||
if (belowIdx !== -1)
|
||||
this.above[belowIdx] = aboveIdx;
|
||||
if (classes !== 0) {
|
||||
for (let i = aboveIdx; i !== -1; i = this.above[i]) {
|
||||
this.specials[i] -= classes & SPECIAL;
|
||||
this.listItemBoundaries[i] -= (classes & LIST_ITEM_BOUNDARY) >> 1;
|
||||
this.scopeBoundaries[i] -= (classes & SCOPE) >> 2;
|
||||
}
|
||||
}
|
||||
// Foreign elements directly above an HTML element refer to it as the topmost HTML element below them.
|
||||
const html = belowIdx === -1 ? -1 : this.htmlSlots[belowIdx];
|
||||
for (let i = aboveIdx; i !== -1 && this.htmlSlots[i] === idx; i = this.above[i]) {
|
||||
this.htmlSlots[i] = html;
|
||||
}
|
||||
}
|
||||
else {
|
||||
this.items.splice(idx, 1);
|
||||
this.tagIDs.splice(idx, 1);
|
||||
this.stackTop--;
|
||||
this._updateCurrentElement();
|
||||
}
|
||||
this.handler.onItemPop(element, false);
|
||||
}
|
||||
//Search
|
||||
tryPeekProperlyNestedBodyElement() {
|
||||
//Properly nested <body> element (should be second element in stack).
|
||||
return this.stackTop >= 1 && this.tagIDs[1] === $.BODY ? this.items[1] : null;
|
||||
}
|
||||
contains(element) {
|
||||
return this._indexOf(element) > -1;
|
||||
}
|
||||
getCommonAncestor(element) {
|
||||
const idx = this._indexOf(element);
|
||||
const belowIdx = idx === -1 ? -1 : this.slotBelow(idx);
|
||||
return belowIdx === -1 ? null : this.items[belowIdx];
|
||||
}
|
||||
isRootHtmlElementCurrent() {
|
||||
return this.stackTop === 0 && this.tagIDs[0] === $.HTML;
|
||||
}
|
||||
//Element in scope
|
||||
/**
|
||||
* On an indexed stack: whether no element of the `scope` class is open above the slot `target`. A target that is not
|
||||
* open is in scope only on a stack without such an element, as a scan from the top would end there.
|
||||
*/
|
||||
_isInScope(target, scope) {
|
||||
let boundary = -1;
|
||||
switch (scope) {
|
||||
case LIST_ITEM_SCOPE: {
|
||||
boundary = Math.max(this.keyTops[$.OL], this.keyTops[$.UL]);
|
||||
break;
|
||||
}
|
||||
case BUTTON_SCOPE: {
|
||||
boundary = this.keyTops[$.BUTTON];
|
||||
break;
|
||||
}
|
||||
case TABLE_SCOPE: {
|
||||
boundary = Math.max(this.keyTops[$.TABLE], this.keyTops[$.HTML]);
|
||||
return target === -1 ? boundary === -1 : target >= boundary;
|
||||
}
|
||||
default:
|
||||
// Only the scope boundaries
|
||||
}
|
||||
return target === -1
|
||||
? boundary === -1 && (this.stackTop === -1 || this.scopeBoundaries[this.stackTop] === 0)
|
||||
: target >= boundary && this.scopeBoundaries[this.stackTop] === this.scopeBoundaries[target];
|
||||
}
|
||||
/**
|
||||
* On a stack that is not indexed: whether an HTML element with the tag, or one of the tags, and if passed the element
|
||||
* itself, is open above every element of the `scope` class; true if neither is open.
|
||||
*/
|
||||
_scanScope(tagID, tagIDs, scope, element) {
|
||||
for (let i = this.stackTop; i >= 0; i--) {
|
||||
const key = tagKey(this.treeAdapter.getNamespaceURI(this.items[i]), this.tagIDs[i]);
|
||||
if (key === -1)
|
||||
continue;
|
||||
if ((tagIDs ? tagIDs.includes(key) : key === tagID) && (!element || this.items[i] === element))
|
||||
return true;
|
||||
if (KEY_CLASSES[key] & scope)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
/** If `element` is passed, only that element (which has to be a `tagName` element) is looked for. */
|
||||
hasInScope(tagName, element) {
|
||||
if (!this.indexed)
|
||||
return this._scanScope(tagName, null, SCOPE, element);
|
||||
return this._isInScope(element ? this._indexOf(element) : this.keyTops[tagName], SCOPE);
|
||||
}
|
||||
hasInListItemScope(tagName) {
|
||||
return this.indexed
|
||||
? this._isInScope(this.keyTops[tagName], LIST_ITEM_SCOPE)
|
||||
: this._scanScope(tagName, null, LIST_ITEM_SCOPE);
|
||||
}
|
||||
hasInButtonScope(tagName) {
|
||||
return this.indexed
|
||||
? this._isInScope(this.keyTops[tagName], BUTTON_SCOPE)
|
||||
: this._scanScope(tagName, null, BUTTON_SCOPE);
|
||||
}
|
||||
hasNumberedHeaderInScope() {
|
||||
return this.indexed
|
||||
? this._isInScope(this.indexOfTopmostOf(NUMBERED_HEADERS), SCOPE)
|
||||
: this._scanScope($.UNKNOWN, NUMBERED_HEADERS, SCOPE);
|
||||
}
|
||||
hasInTableScope(tagName) {
|
||||
return this.indexed
|
||||
? this._isInScope(this.keyTops[tagName], TABLE_SCOPE)
|
||||
: this._scanScope(tagName, null, TABLE_SCOPE);
|
||||
}
|
||||
hasTableBodyContextInTableScope() {
|
||||
return this.indexed
|
||||
? this._isInScope(this.indexOfTopmostOf(TABLE_BODIES), TABLE_SCOPE)
|
||||
: this._scanScope($.UNKNOWN, TABLE_BODIES, TABLE_SCOPE);
|
||||
}
|
||||
hasInSelectScope(tagName) {
|
||||
for (let i = this.stackTop; i >= 0; i = this.slotBelow(i)) {
|
||||
if (this.treeAdapter.getNamespaceURI(this.items[i]) !== NS.HTML) {
|
||||
continue;
|
||||
}
|
||||
switch (this.tagIDs[i]) {
|
||||
case tagName: {
|
||||
return true;
|
||||
}
|
||||
case $.OPTION:
|
||||
case $.OPTGROUP: {
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
//Implied end tags
|
||||
generateImpliedEndTags() {
|
||||
while (this.currentTagId !== undefined &&
|
||||
IMPLICIT_END_TAG_REQUIRED.has(this.currentTagId) &&
|
||||
this.treeAdapter.getNamespaceURI(this.current) === NS.HTML) {
|
||||
this.pop();
|
||||
}
|
||||
}
|
||||
generateImpliedEndTagsThoroughly() {
|
||||
while (this.currentTagId !== undefined &&
|
||||
IMPLICIT_END_TAG_REQUIRED_THOROUGHLY.has(this.currentTagId) &&
|
||||
this.treeAdapter.getNamespaceURI(this.current) === NS.HTML) {
|
||||
this.pop();
|
||||
}
|
||||
}
|
||||
generateImpliedEndTagsWithExclusion(exclusionId) {
|
||||
while (this.currentTagId !== undefined &&
|
||||
this.currentTagId !== exclusionId &&
|
||||
IMPLICIT_END_TAG_REQUIRED_THOROUGHLY.has(this.currentTagId) &&
|
||||
this.treeAdapter.getNamespaceURI(this.current) === NS.HTML) {
|
||||
this.pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user