diff options
| author | bptato <nincsnevem662@gmail.com> | 2021-07-30 20:23:34 +0200 |
|---|---|---|
| committer | bptato <nincsnevem662@gmail.com> | 2021-07-30 20:25:38 +0200 |
| commit | 34b023515599bc746c10c597467ecb07f53c49fe (patch) | |
| tree | 38e77bb205bf94c63387dae4f7d859cda7bb9ce6 /src/html | |
| parent | 94a10242dca6181ef8f15a37e7083069ead09559 (diff) | |
| download | chawan-34b023515599bc746c10c597467ecb07f53c49fe.tar.gz | |
CSS selectors and re-organization
Diffstat (limited to 'src/html')
| -rw-r--r-- | src/html/dom.nim | 492 | ||||
| -rw-r--r-- | src/html/entity.nim | 28 | ||||
| -rw-r--r-- | src/html/htmlparser.nim | 540 |
3 files changed, 1060 insertions, 0 deletions
diff --git a/src/html/dom.nim b/src/html/dom.nim new file mode 100644 index 00000000..74ebe5ea --- /dev/null +++ b/src/html/dom.nim @@ -0,0 +1,492 @@ +import terminal +import uri +import unicode +import strutils +import tables +import streams +import sequtils +import sugar + +import ../css/style +import ../css/cssparser +import ../css/selector + +import ../types/enums +import ../types/tagtypes + +import ../utils/twtstr + +import ../io/twtio + +const css = staticRead"../../res/default.css" +let stylesheet = parseCSS(newStringStream(css)) + +type + EventTarget* = ref EventTargetObj + EventTargetObj = object of RootObj + + Node* = ref NodeObj + NodeObj = object of EventTargetObj + nodeType*: NodeType + childNodes*: seq[Node] + children*: seq[Element] + isConnected*: bool + nextSibling*: Node + previousSibling*: Node + parentNode*: Node + parentElement*: Element + ownerDocument*: Document + + rawtext*: string + fmttext*: seq[string] + x*: int + y*: int + ex*: int + ey*: int + width*: int + height*: int + hidden*: bool + + Attr* = ref AttrObj + AttrObj = object of NodeObj + namespaceURI*: string + prefix*: string + localName*: string + name*: string + value*: string + ownerElement*: Element + + Document* = ref DocumentObj + DocumentObj = object of NodeObj + location*: Uri + type_elements*: array[low(TagType)..high(TagType), seq[Element]] + id_elements*: Table[string, seq[Element]] + class_elements*: Table[string, seq[Element]] + all_elements*: seq[Element] + head*: HTMLElement + body*: HTMLElement + + CharacterData* = ref CharacterDataObj + CharacterDataObj = object of NodeObj + data*: string + length*: int + + Text* = ref TextObj + TextObj = object of CharacterDataObj + wholeText*: string + + Comment* = ref CommentObj + CommentObj = object of CharacterDataObj + + Element* = ref ElementObj + ElementObj = object of NodeObj + namespaceURI*: string + prefix*: string + localName*: string + tagName*: string + tagType*: TagType + + id*: string + classList*: seq[string] + attributes*: Table[string, Attr] + box*: CSSBox + + HTMLElement* = ref HTMLElementObj + HTMLElementObj = object of ElementObj + + HTMLInputElement* = ref HTMLInputElementObj + HTMLInputElementObj = object of HTMLElementObj + itype*: InputType + autofocus*: bool + required*: bool + value*: string + size*: int + + HTMLAnchorElement* = ref HTMLAnchorElementObj + HTMLAnchorElementObj = object of HTMLElementObj + href*: string + + HTMLSelectElement* = ref HTMLSelectElementObj + HTMLSelectElementObj = object of HTMLElementObj + name*: string + value*: string + valueSet*: bool + + HTMLSpanElement* = ref HTMLSpanElementObj + HTMLSpanElementObj = object of HTMLElementObj + + HTMLOptionElement* = ref HTMLOptionElementObj + HTMLOptionElementObj = object of HTMLElementObj + value*: string + + HTMLHeadingElement* = ref HTMLHeadingElementObj + HTMLHeadingElementObj = object of HTMLElementObj + rank*: uint16 + + HTMLBRElement* = ref HTMLBRElementObj + HTMLBRElementObj = object of HTMLElementObj + + +func firstChild(node: Node): Node = + if node.childNodes.len == 0: + return nil + return node.childNodes[0] + +func lastChild(node: Node): Node = + if node.childNodes.len == 0: + return nil + return node.childNodes[^1] + +func firstElementChild(node: Node): Element = + if node.children.len == 0: + return nil + return node.children[0] + +func lastElementChild(node: Node): Element = + if node.children.len == 0: + return nil + return node.children[^1] + +func `$`*(element: Element): string = + return "Element of " & $element.tagType + +#TODO +func nodeAttr*(node: Node): HtmlElement = + case node.nodeType + of TEXT_NODE: return HtmlElement(node.parentElement) + of ELEMENT_NODE: return HtmlElement(node) + else: assert(false) + +func getStyle*(node: Node): CSS2Properties = + case node.nodeType + of TEXT_NODE: return node.parentElement.box.props + of ELEMENT_NODE: return Element(node).box.props + else: assert(false) + +func displayed*(node: Node): bool = + return node.rawtext.len > 0 and node.getStyle().display != DISPLAY_NONE + +func isTextNode*(node: Node): bool = + return node.nodeType == TEXT_NODE + +func isElemNode*(node: Node): bool = + return node.nodeType == ELEMENT_NODE + +func isComment*(node: Node): bool = + return node.nodeType == COMMENT_NODE + +func isCData*(node: Node): bool = + return node.nodeType == CDATA_SECTION_NODE + +func isDocument*(node: Node): bool = + return node.nodeType == DOCUMENT_NODE + +func getFmtLen*(htmlNode: Node): int = + return htmlNode.fmttext.join().runeLen() + +func getRawLen*(htmlNode: Node): int = + return htmlNode.rawtext.runeLen() + +func firstNode*(htmlNode: Node): bool = + return htmlNode.parentElement != nil and htmlNode.parentElement.childNodes[0] == htmlNode + +func lastNode*(htmlNode: Node): bool = + return htmlNode.parentElement != nil and htmlNode.parentElement.childNodes[^1] == htmlNode + +func toInputType*(str: string): InputType = + case str + of "button": INPUT_BUTTON + of "checkbox": INPUT_CHECKBOX + of "color": INPUT_COLOR + of "date": INPUT_DATE + of "datetime_local": INPUT_DATETIME_LOCAL + of "email": INPUT_EMAIL + of "file": INPUT_FILE + of "hidden": INPUT_HIDDEN + of "image": INPUT_IMAGE + of "month": INPUT_MONTH + of "number": INPUT_NUMBER + of "password": INPUT_PASSWORD + of "radio": INPUT_RADIO + of "range": INPUT_RANGE + of "reset": INPUT_RESET + of "search": INPUT_SEARCH + of "submit": INPUT_SUBMIT + of "tel": INPUT_TEL + of "text": INPUT_TEXT + of "time": INPUT_TIME + of "url": INPUT_URL + of "week": INPUT_WEEK + else: INPUT_UNKNOWN + +func toInputSize*(str: string): int = + if str.len == 0: + return 20 + for c in str: + if not c.isDigit(): + return 20 + return str.parseInt() + +func getFmtInput(inputElement: HtmlInputElement): seq[string] = + case inputElement.itype + of INPUT_TEXT, INPUT_SEARCH: + let valueFit = fitValueToSize(inputElement.value, inputElement.size) + return valueFit.ansiStyle(styleUnderscore).ansiReset().buttonFmt() + of INPUT_SUBMIT: + return inputElement.value.buttonFmt() + else: discard + +func getRawInput(inputElement: HtmlInputElement): string = + case inputElement.itype + of INPUT_TEXT, INPUT_SEARCH: + return inputElement.value.fitValueToSize(inputElement.size).buttonRaw() + of INPUT_SUBMIT: + return inputElement.value.buttonRaw() + else: discard + +#TODO +func ancestor*(htmlNode: Node, tagType: TagType): HtmlElement = + result = HtmlElement(htmlNode.parentElement) + while result != nil and result.tagType != tagType: + result = HtmlElement(result.parentElement) + +proc getRawText*(htmlNode: Node): string = + if htmlNode.isElemNode(): + case HtmlElement(htmlNode).tagType + of TAG_INPUT: return HtmlInputElement(htmlNode).getRawInput() + else: return "" + elif htmlNode.isTextNode(): + let chardata = CharacterData(htmlNode) + #eprint "char data", chardata.data + if htmlNode.parentElement != nil and htmlNode.parentElement.tagType != TAG_PRE: + result = chardata.data.remove("\n") + if unicode.strip(result).runeLen() > 0: + if htmlNode.getStyle().display != DISPLAY_INLINE: + result = unicode.strip(result) + else: + result = "" + else: + result = unicode.strip(chardata.data) + if htmlNode.parentElement != nil and htmlNode.parentElement.tagType == TAG_OPTION: + result = result.buttonRaw() + else: + assert(false) + +func getFmtText*(node: Node): seq[string] = + if node.isElemNode(): + case HtmlElement(node).tagType + of TAG_INPUT: return HtmlInputElement(node).getFmtInput() + else: return @[] + elif node.isTextNode(): + let chardata = CharacterData(node) + result &= chardata.data + if node.parentElement != nil: + let style = node.getStyle() + if style.hasColor(): + result = result.ansiFgColor(style.termColor()) + + if node.parentElement.tagType == TAG_OPTION: + result = result.ansiFgColor(fgRed).ansiReset() + + if style.bold: + result = result.ansiStyle(styleBright).ansiReset() + if style.italic: + result = result.ansiStyle(styleItalic).ansiReset() + if style.underscore: + result = result.ansiStyle(styleUnderscore).ansiReset() + else: + assert(false, node.rawtext) + else: + assert(false) + +func newText*(): Text = + new(result) + result.nodeType = TEXT_NODE + +func newComment*(): Comment = + new(result) + result.nodeType = COMMENT_NODE + +func newBox*(element: HTMLElement): CSSBox = + new(result) + result.props = CSS2Properties() + +func newHtmlElement*(tagType: TagType): HTMLElement = + case tagType + of TAG_INPUT: + result = new(HTMLInputElement) + of TAG_A: + result = new(HTMLAnchorElement) + of TAG_SELECT: + result = new(HTMLSelectElement) + of TAG_OPTION: + result = new(HTMLOptionElement) + of TAG_H1, TAG_H2, TAG_H3, TAG_H4, TAG_H5, TAG_H6: + result = new(HTMLHeadingElement) + of TAG_BR: + result = new(HTMLBRElement) + of TAG_SPAN: + result = new(HTMLSpanElement) + else: + new(result) + + result.nodeType = ELEMENT_NODE + result.tagType = tagType + result.box = result.newBox() + +func newDocument*(): Document = + new(result) + result.head = newHtmlElement(TAG_HEAD) + result.body = newHtmlElement(TAG_BODY) + result.nodeType = DOCUMENT_NODE + +func newAttr*(parent: Element, key: string, value: string): Attr = + new(result) + result.nodeType = ATTRIBUTE_NODE + result.ownerElement = parent + result.name = key + result.value = value + +func getAttrValue*(element: Element, s: string): string = + let attr = element.attributes.getOrDefault(s, nil) + if attr != nil: + return attr.value + return "" + +#TODO case sensitivity +func attrSelectorMatches(elem: Element, sel: Selector): bool = + case sel.rel + of ' ': return sel.attr in elem.attributes + of '=': return elem.getAttrValue(sel.attr) == sel.value + of '~': return sel.value in unicode.split(elem.getAttrValue(sel.attr)) + of '|': + let val = elem.getAttrValue(sel.attr) + return val == sel.value or sel.value.startsWith(val & '-') + of '^': return elem.getAttrValue(sel.attr).startsWith(sel.value) + of '$': return elem.getAttrValue(sel.attr).endsWith(sel.value) + of '*': return elem.getAttrValue(sel.attr).contains(sel.value) + else: return false + +func pseudoSelectorMatches(elem: Element, sel: Selector): bool = + case sel.pseudo + of "first-child": return elem.parentNode.firstElementChild == elem + of "last-child": return elem.parentNode.lastElementChild == elem + else: return false + +func pseudoElemSelectorMatches(elem: Element, sel: Selector): bool = + case sel.elem + of "after": return false + of "before": return false + else: return false + +func selectorMatches(elem: Element, sel: Selector): bool = + case sel.t + of TYPE_SELECTOR: + return elem.tagType == sel.tag + of CLASS_SELECTOR: + return sel.class in elem.classList + of ID_SELECTOR: + return sel.id == elem.id + of ATTR_SELECTOR: + return elem.attrSelectorMatches(sel) + of PSEUDO_SELECTOR: + return pseudoSelectorMatches(elem, sel) + of PSELEM_SELECTOR: + return pseudoElemSelectorMatches(elem, sel) + of UNIVERSAL_SELECTOR: + return true + of FUNC_SELECTOR: + return false + +func selectorsMatch(elem: Element, selectors: SelectorList): bool = + for sel in selectors.sels: + if not selectorMatches(elem, sel): + return false + return true + +func selectElems(document: Document, sel: Selector): seq[Element] = + case sel.t + of TYPE_SELECTOR: + return document.type_elements[sel.tag] + of ID_SELECTOR: + return document.id_elements[sel.id] + of CLASS_SELECTOR: + return document.class_elements[sel.class] + of UNIVERSAL_SELECTOR: + return document.all_elements + #TODO: following selectors are rather inefficient + of ATTR_SELECTOR: + return document.all_elements.filter((elem) => attrSelectorMatches(elem, sel)) + of PSEUDO_SELECTOR: + return document.all_elements.filter((elem) => pseudoSelectorMatches(elem, sel)) + of PSELEM_SELECTOR: + return document.all_elements.filter((elem) => pseudoElemSelectorMatches(elem, sel)) + of FUNC_SELECTOR: + if sel.name == "not": + return document.all_elements.filter((elem) => not selectorsMatch(elem, sel.selectors)) + return newSeq[Element]() + +func optimizeSelectorList(selectors: SelectorList): SelectorList = + new(result) + #pass 1: check for invalid sequences + var i = 1 + while i < selectors.len: + let sel = selectors[i] + if sel.t == TYPE_SELECTOR or sel.t == UNIVERSAL_SELECTOR: + return SelectorList() + inc i + + #pass 2: move selectors in combination + if selectors.len > 1: + var i = 0 + var slow = SelectorList() + if selectors[0].t == UNIVERSAL_SELECTOR: + inc i + + while i < selectors.len: + if selectors[i].t in {ATTR_SELECTOR, PSEUDO_SELECTOR, PSELEM_SELECTOR}: + slow.add(selectors[i]) + else: + result.add(selectors[i]) + inc i + + result.add(slow) + else: + result.add(selectors[0]) + +func selectElems(document: Document, selectors: SelectorList): seq[Element] = + assert(selectors.len > 0) + let sellist = optimizeSelectorList(selectors) + result = document.selectElems(selectors[0]) + var i = 1 + + while i < sellist.len: + if sellist[i].t == FUNC_SELECTOR: + if sellist[i].name == "not": + result = result.filter((elem) => not selectorsMatch(elem, sellist[i].selectors)) + else: + result = result.filter((elem) => selectorMatches(elem, sellist[i])) + inc i + +proc querySelector*(document: Document, q: string): seq[Element] = + let ss = newStringStream(q) + let cvals = parseCSSListOfComponentValues(ss) + let selectors = parseSelectors(cvals) + + for sel in selectors: + result.add(document.selectElems(sel)) + +proc applyRule(elem: Element, rule: CSSRule) = + let selectors = parseSelectors(rule.prelude) + for sel in selectors: + if elem.selectorsMatch(sel): + eprint "match!" + +proc applyRules(document: Document, rules: CSSStylesheet) = + var stack: seq[Element] + + stack.add(document.firstElementChild) + while stack.len > 0: + let elem = stack.pop() + for child in elem.children: + stack.add(child) diff --git a/src/html/entity.nim b/src/html/entity.nim new file mode 100644 index 00000000..79c57ca0 --- /dev/null +++ b/src/html/entity.nim @@ -0,0 +1,28 @@ +import json + +import ../utils/radixtree + +const entity = staticRead"../../res/entity.json" +when defined(small): + proc genEntityMap(data: seq[tuple[a: string, b: string]]): RadixNode[string] = + result = newRadixTree[string]() + for pair in data: + result[pair.a] = pair.b + + proc genEntityTable(): seq[tuple[a: string, b: string]] = + let entityJson = parseJson(entity) + + for k, v in entityJson: + result.add((k.substr(1), v{"characters"}.getStr())) + const entityTable = genEntityTable() + let entityMap* = genEntityMap(entityTable) +else: + proc genEntityMap(): StaticRadixTree[string] = + let entityJson = parseJson(entity) + var entityMap = newStaticRadixTree[string]() + + for k, v in entityJson: + entityMap[k.substr(1)] = v{"characters"}.getStr() + + return entityMap + const entityMap* = genEntityMap() diff --git a/src/html/htmlparser.nim b/src/html/htmlparser.nim new file mode 100644 index 00000000..f43bcf40 --- /dev/null +++ b/src/html/htmlparser.nim @@ -0,0 +1,540 @@ +import streams +import unicode +import strutils +import tables +import json + +import ../types/enums +import ../types/tagtypes + +import ../utils/twtstr +import ../utils/radixtree + +import ../io/twtio + +import dom +import entity + +type + HTMLParseState = object + closed: bool + parents: seq[Node] + parsedNode: Node + a: string + b: string + attrs: seq[string] + in_comment: bool + in_script: bool + in_style: bool + in_noscript: bool + in_body: bool + parentNode: Node + textNode: Text + +#func newHtmlElement(tagType: TagType, parentNode: Node): HtmlElement = +# case tagType +# of TAG_INPUT: result = new(HtmlInputElement) +# of TAG_A: result = new(HtmlAnchorElement) +# of TAG_SELECT: result = new(HtmlSelectElement) +# of TAG_OPTION: result = new(HtmlOptionElement) +# else: result = new(HtmlElement) +# +# result.nodeType = ELEMENT_NODE +# result.tagType = tagType +# result.parentNode = parentNode +# if parentNode.isElemNode(): +# result.parentElement = HtmlElement(parentNode) +# +# if tagType in DisplayInlineTags: +# result.display = DISPLAY_INLINE +# elif tagType in DisplayBlockTags: +# result.display = DISPLAY_BLOCK +# elif tagType in DisplayInlineBlockTags: +# result.display = DISPLAY_INLINE_BLOCK +# elif tagType == TAG_LI: +# result.display = DISPLAY_LIST_ITEM +# else: +# result.display = DISPLAY_NONE +# +# case tagType +# of TAG_CENTER: +# result.centered = true +# of TAG_B: +# result.bold = true +# of TAG_I: +# result.italic = true +# of TAG_U: +# result.underscore = true +# of TAG_HEAD: +# result.hidden = true +# of TAG_STYLE: +# result.hidden = true +# of TAG_SCRIPT: +# result.hidden = true +# of TAG_OPTION: +# result.hidden = true #TODO +# of TAG_PRE, TAG_TD, TAG_TH: +# result.margin = 1 +# of TAG_UL, TAG_OL: +# result.indent = 2 +# result.margin = 1 +# of TAG_H1, TAG_H2, TAG_H3, TAG_H4, TAG_H5, TAG_H6: +# result.bold = true +# result.margin = 1 +# of TAG_A: +# result.islink = true +# of TAG_INPUT: +# HtmlInputElement(result).size = 20 +# else: discard +# +# if parentNode.isElemNode(): +# let parent = HtmlElement(parentNode) +# result.centered = result.centered or parent.centered +# result.bold = result.bold or parent.bold +# result.italic = result.italic or parent.italic +# result.underscore = result.underscore or parent.underscore +# result.hidden = result.hidden or parent.hidden +# result.islink = result.islink or parent.islink + +func inputSize*(str: string): int = + if str.len == 0: + return 20 + for c in str: + if not c.isDigit: + return 20 + return str.parseInt() + +#w3m's getescapecmd and parse_tag, transpiled to nim. +#(C) Copyright 1994-2002 by Akinori Ito +#(C) Copyright 2002-2011 by Akinori Ito, Hironori Sakamoto, Fumitoshi Ukai +# +#Use, modification and redistribution of this software is hereby granted, +#provided that this entire copyright notice is included on any copies of +#this software and applications and derivations thereof. +# +#This software is provided on an "as is" basis, without warranty of any +#kind, either expressed or implied, as to any matter including, but not +#limited to warranty of fitness of purpose, or merchantability, or +#results obtained from use of this software. +proc getescapecmd(buf: string, at: var int): string = + var i = at + + if buf[i] == '#': #num + inc i + var num: int + if buf[i].tolower() == 'x': #hex + inc i + if not isdigit(buf[i]): + at = i + return "" + + num = hexValue(buf[i]) + inc i + while i < buf.len and hexValue(buf[i]) != -1: + num *= 0x10 + num += hexValue(buf[i]) + inc i + else: #dec + if not isDigit(buf[i]): + at = i + return "" + + num = decValue(buf[i]) + inc i + while i < buf.len and isDigit(buf[i]): + num *= 10 + num += decValue(buf[i]) + inc i + + if buf[i] == ';': + inc i + at = i + return $(Rune(num)) + elif not isAlphaAscii(buf[i]): + return "" + + #TODO this could be way more efficient (and radixnode needs better interface) + when defined(small): + var n = entityMap + var s = "" + while true: + s &= buf[i] + if not entityMap.hasPrefix(s, n): + break + let pn = n + n = n{s} + if n != pn: + s = "" + inc i + + if n.leaf: + at = i + return n.value + else: + var n = 0 + var s = "" + while true: + s &= buf[i] + if not entityMap.hasPrefix(s, n): + break + let pn = n + n = entityMap{s, n} + if n != pn: + s = "" + inc i + + if entityMap.nodes[n].leaf: + at = i + return entityMap.nodes[n].value + + return "" + +type + DOMParsedTag = object + tagid: TagType + attrs: Table[string, string] + open: bool + +proc parse_tag(buf: string, at: var int): DOMParsedTag = + var tag = DOMParsedTag() + tag.open = true + + #Parse tag name + var tagname = "" + inc at + if buf[at] == '/': + inc at + tag.open = false + at = skipBlanks(buf, at) + + while at < buf.len and not buf[at].isWhitespace() and not (tag.open and buf[at] == '/') and buf[at] != '>': + tagname &= buf[at].tolower() + at += buf.runeLenAt(at) + + tag.tagid = tagType(tagname) + at = skipBlanks(buf, at) + + while at < buf.len and buf[at] != '>': + var value = "" + var attrname = "" + while at < buf.len and buf[at] != '=' and not buf[at].isWhitespace() and buf[at] != '>': + attrname &= buf[at].tolower() + at += buf.runeLenAt(at) + + at = skipBlanks(buf, at) + if buf[at] == '=': + inc at + at = skipBlanks(buf, at) + if at < buf.len and (buf[at] == '"' or buf[at] == '\''): + let startc = buf[at] + inc at + while at < buf.len and buf[at] != startc: + var r: Rune + fastRuneAt(buf, at, r) + if r == Rune('&'): + value &= getescapecmd(buf, at) + else: + value &= $r + if at < buf.len: + inc at + elif at < buf.len: + while at < buf.len and not buf[at].isWhitespace() and buf[at] != '>': + value &= buf[at] + at += buf.runeLenAt(at) + + if attrname.len > 0: + tag.attrs[attrname] = value + + while at < buf.len and buf[at] != '>': + at += buf.runeLenAt(at) + + if at < buf.len and buf[at] == '>': + inc at + return tag + +proc insertNode(parent: Node, node: Node) = + parent.childNodes.add(node) + + if parent.childNodes.len > 1: + let prevSibling = parent.childNodes[^1] + prevSibling.nextSibling = node + node.previousSibling = prevSibling + + node.parentNode = parent + if parent.nodeType == ELEMENT_NODE: + node.parentElement = (Element)parent + + if parent.ownerDocument != nil: + node.ownerDocument = parent.ownerDocument + elif parent.nodeType == DOCUMENT_NODE: + node.ownerDocument = (Document)parent + + if node.nodeType == ELEMENT_NODE: + parent.children.add((Element)node) + + let element = ((Element)node) + if element.ownerDocument != nil: + node.ownerDocument.all_elements.add((Element)node) + element.ownerDocument.type_elements[element.tagType].add(element) + if element.id != "": + if not (element.id in element.ownerDocument.id_elements): + element.ownerDocument.id_elements[element.id] = newSeq[Element]() + element.ownerDocument.id_elements[element.id].add(element) + + for c in element.classList: + if not (c in element.ownerDocument.class_elements): + element.ownerDocument.class_elements[c] = newSeq[Element]() + element.ownerDocument.class_elements[c].add(element) + +proc processDocumentBody(state: var HTMLParseState) = + if not state.in_body: + state.in_body = true + if state.parentNode.ownerDocument != nil: + state.parentNode = state.parentNode.ownerDocument.body + +proc processDocumentStartNode(state: var HTMLParseState, newNode: Node) = + if state.parentNode.nodeType == ELEMENT_NODE and ((Element)state.parentNode).tagType == TAG_HTML: + if state.in_body: + state.parentNode = state.parentNode.ownerDocument.body + else: + state.parentNode = state.parentNode.ownerDocument.head + + insertNode(state.parentNode, newNode) + state.parentNode = newNode + +proc processDocumentEndNode(state: var HTMLParseState) = + if state.parentNode == nil or state.parentNode.parentNode == nil: + return + state.parentNode = state.parentNode.parentNode + +proc processDocumentText(state: var HTMLParseState) = + if state.textNode != nil and state.textNode.data.len > 0: + processDocumentBody(state) + if state.textNode == nil: + state.textNode = newText() + + processDocumentStartNode(state, state.textNode) + processDocumentEndNode(state) + +proc processDocumentStartElement(state: var HTMLParseState, element: Element, tag: DOMParsedTag) = + var add = true + + for k, v in tag.attrs: + element.attributes[k] = element.newAttr(k, v) + + element.id = element.getAttrValue("id") + if element.attributes.hasKey("class"): + for w in unicode.split(element.attributes["class"].value, Rune(' ')): + element.classList.add(w) + + case element.tagType + of TAG_SCRIPT: + state.in_script = true + of TAG_NOSCRIPT: + state.in_noscript = true + of TAG_STYLE: + state.in_style = true + of TAG_SELECT: + HTMLSelectElement(element).name = element.getAttrValue("name") + HTMLSelectElement(element).value = element.getAttrValue("value") + of TAG_INPUT: + HTMLInputElement(element).value = element.getAttrValue("value") + HTMLInputElement(element).itype = element.getAttrValue("type").inputType() + HTMLInputElement(element).size = element.getAttrValue("size").inputSize() + of TAG_A: + HTMLAnchorElement(element).href = element.getAttrValue("href") + of TAG_OPTION: + HTMLOptionElement(element).value = element.getAttrValue("href") + of TAG_HTML: + add = false + of TAG_HEAD: + add = false + of TAG_BODY: + add = false + processDocumentBody(state) + else: discard + + if state.parentNode.nodeType == ELEMENT_NODE: + case element.tagType + of TAG_LI, TAG_P: + if Element(state.parentNode).tagType == element.tagType: + processDocumentEndNode(state) + of TAG_H1: + HTMLHeadingElement(element).rank = 1 + of TAG_H2: + HTMLHeadingElement(element).rank = 2 + of TAG_H3: + HTMLHeadingElement(element).rank = 3 + of TAG_H4: + HTMLHeadingElement(element).rank = 4 + of TAG_H5: + HTMLHeadingElement(element).rank = 5 + of TAG_H6: + HTMLHeadingElement(element).rank = 6 + else: discard + + if add: + processDocumentStartNode(state, element) + + if element.tagType in VoidTagTypes: + processDocumentEndNode(state) + +proc processDocumentEndElement(state: var HTMLParseState, tag: DOMParsedTag) = + if tag.tagid in VoidTagTypes: + return + if tag.tagid == TAG_HEAD: + state.in_body = true + return + if tag.tagid == TAG_BODY: + return + if state.parentNode.nodeType == ELEMENT_NODE: + if Element(state.parentNode).tagType in {TAG_LI, TAG_P}: + processDocumentEndNode(state) + + processDocumentEndNode(state) + +proc processDocumentTag(state: var HTMLParseState, tag: DOMParsedTag) = + if state.in_script: + if tag.tagid == TAG_SCRIPT: + state.in_script = false + else: + return + + if state.in_style: + if tag.tagid == TAG_STYLE: + state.in_style = false + else: + return + + if state.in_noscript: + if tag.tagid == TAG_NOSCRIPT: + state.in_noscript = false + else: + return + + if tag.open: + processDocumentStartElement(state, newHtmlElement(tag.tagid), tag) + else: + processDocumentEndElement(state, tag) + +proc processDocumentPart(state: var HTMLParseState, buf: string) = + var at = 0 + var max = 0 + var was_script = false + + max = buf.len + + while at < max: + case buf[at] + of '&': + inc at + let p = getescapecmd(buf, at) + if state.in_comment: + CharacterData(state.parentNode).data &= p + else: + processDocumentText(state) + state.textNode.data &= p + of '<': + if state.in_comment: + CharacterData(state.parentNode).data &= buf[at] + inc at + else: + var p = at + inc p + if p < max and buf[p] == '!': + inc p + if p < max and buf[p] == '-': + inc p + if p < max and buf[p] == '-': + inc p + at = p + state.in_comment = true + processDocumentStartNode(state, newComment()) + if state.textNode != nil: + state.textNode.rawtext = state.textNode.getRawText() + state.textNode = nil + else: + #TODO for doctype + while p < max and buf[p] != '>': + inc p + at = p + continue + + if not state.in_comment: + if state.textNode != nil: + state.textNode.rawtext = state.textNode.getRawText() + state.textNode = nil + p = at + var tag = parse_tag(buf, at) + was_script = state.in_script + + processDocumentTag(state, tag) +# if (was_script) { +# if (state->in_script) { +# ptr = p; +# processDocumentText(&state->parentNode, &state->textNode); +# Strcat_char(((CharacterData *)state->textNode)->data, *ptr++); +# } else if (buffer->javascript_enabled) { +# loadJSToBuffer(buffer, childTextContentNode(state->parentNode->lastChild)->ptr, "<inline>", state->document); +# } +# } + elif buf[at] == '-' and state.in_comment: + var p = at + inc p + if p < max and buf[p] == '-': + inc p + if p < max and buf[p] == '>': + inc p + at = p + state.in_comment = false + processDocumentEndNode(state) + + if state.in_comment: + CharacterData(state.parentNode).data &= buf[at] + inc at + else: + var r: Rune + fastRuneAt(buf, at, r) + if state.in_comment: + CharacterData(state.parentNode).data &= $r + else: + processDocumentText(state) + state.textNode.data &= $r + +proc parseHtml*(inputStream: Stream): Document = + let document = newDocument() + let html = newHtmlElement(TAG_HTML) + insertNode(document, html) + insertNode(html, document.head) + insertNode(html, document.body) + #eprint document.body.firstElementChild != nil + + var state = HTMLParseState() + state.parentNode = html + + var till_when = false + + var buf = "" + var lineBuf: string + while not inputStream.atEnd(): + lineBuf = inputStream.readLine() + buf &= lineBuf + + var at = 0 + while at < lineBuf.len: + case lineBuf[at] + of '<': + till_when = true + of '>': + till_when = false + else: discard + at += lineBuf.runeLenAt(at) + + if till_when: + continue + + processDocumentPart(state, buf) + buf = "" + + inputStream.close() + return document |