实战中学习浏览器工作原理 — HTML 解析与 CSS 计算

{"type":"doc","content":[{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"我是"},{"type":"text","marks":[{"type":"strong"}],"text":"三钻"},{"type":"text","text":",一个在"},{"type":"text","marks":[{"type":"strong"}],"text":"《技术银河》"},{"type":"text","text":"中等你们一起来终生漂泊学习。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"点赞是力量,关注是认可,评论是关爱!下期再见 👋!"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":1},"content":[{"type":"text","text":"前言"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"上一部分我们完成了从 HTTP 发送 Request,到接收到 Response,并且把 Response 中的文本都解析出来。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"这一部分我们主要讲解如何做 HTML 解析 和 CSS 计算这两个部分。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/98/98bb960d57051aad896271950ca11e40.png","alt":null,"title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"根据我们上部分列出的一个完整的浏览器架构的话,蓝色背景的部分就是我们目前已经完成的流程。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/b3/b34c995f506fd74ab4d6e4adb20b4706.png","alt":null,"title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":1},"content":[{"type":"text","text":"HTML 解析"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"HTML parse 模块的文件拆分"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"思路:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"为了方便文件管理,我们把 parser 单独拆分到文件中"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"parser 接收 HTML 文本作为参数,返回一棵 DOM 树"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"加入 HTML Parser"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"上一篇文章中我们最后获得了一个 "},{"type":"codeinline","content":[{"type":"text","text":"Response"}]},{"type":"text","text":" 对象"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"这里我们就考虑如何利用这个 "},{"type":"codeinline","content":[{"type":"text","text":"Response"}]},{"type":"text","text":" 中的 body 内容"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"所以我们应该从获得 Response 之后,把 body 内容传给 parser 中的 parseHTML 方法进行解析"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在真正的浏览器中,我们是应该逐段的传给 parser 处理,然后逐段的返回"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"因为这里我们的目标只是简单实现浏览器工作的原理,所以我们只需要统一解析然后返回就好"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"这样我们更容易理解,代码也更加清晰易懂"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"文件:client.js"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"javascript"},"content":[{"type":"text","text":"// 这个是 client.js\n\n // 1. 引入 parser.js\nconst parser = require('./parser.js');\n\n// ...\n//... 之前的代码在此处忽略\n// ...\n\nlet response = await request.send();\n\n// 2. 在 `请求方法` 中,获得 response 后加入 HTML 的解析代码\nlet dom = parser.parseHTML(response.body);"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"文件:parser.js"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"javascript"},"content":[{"type":"text","text":"/**\n * 解析器\n * @filename parser.js\n * @author 三钻\n * @version v1.0.0\n */\n\nmodule.exports.parseHTML = function (html) {\n console.log(html); // 这里我们先 console.log 打印一下返回的 HTML 内容\n};"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"用有效状态机 (FSM) 实现 HTML的分析"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"我们用 FSM 来实现 HTML 的分析"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在 HTML 标准中,已经规定了 HTML 的状态"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"我们的浏览器只挑选其中一部分状态,完成一个最简版本"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"HTML 标准里面已经把整个状态机中的状态都设计好了,我们直接就看HTML标准中给我们设计好的状态:https://html.spec.whatwg.org/multipage/,我们直接翻到 “Tokenization” 查看列出的状态,这里就是所有 HTML 的词法。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"有些同学在读这个标准的时候会说 “我看不懂”,“我太难了”,“我看懵了”。其实我们看不懂是因为这里面的标准是写给浏览器实现者去看的,但是用实现我们的浏览器的状态机之后,我们就可以看懂了,而且发现这里面写的非常像我们的代码。这个标准中写的就是伪代码。我们只需要把这里面的伪代码写成真实代码就可以了。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在 HTML 中有80个状态,但是在我们这里,因为只需要走一遍浏览器工作的流程,我们就不一一实现了,我们在其中挑选一部分来实现即可。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"下面我们来初始化一下我们的 "},{"type":"codeinline","content":[{"type":"text","text":"parseHTML"}]},{"type":"text","text":" 的状态机:(把上面的 "},{"type":"codeinline","content":[{"type":"text","text":"parser.js"}]},{"type":"text","text":" 的基础上进行修改)"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"文件:parser.js"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"javascript"},"content":[{"type":"text","text":"/**\n * 解析器\n * @filename parser.js\n * @author 三钻\n * @version v1.0.0\n */\n\nconst EOF = Symbol('EOF'); // EOF: end of file\n\nfunction data(char) {}\n\n/**\n * HTTP 解析\n * @param {string} html 文本\n */\nmodule.exports.parseHTML = function (html) {\n let state = data;\n for (let char of html) {\n state = state(char);\n }\n state = state(EOF);\n};"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"+ 上面的代码中用了一个小技巧,因为 HTML 最后是有一个文件终结的"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"+ 所有最后需要给他一个结束字符(重点是这里用一个没有特别意义的字符)"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"+ 我们这里使用了 "},{"type":"codeinline","content":[{"type":"text","text":"Symbol"}]},{"type":"text","text":" 创建了一个 "},{"type":"codeinline","content":[{"type":"text","text":"EOF"}]},{"type":"text","text":" 字符,代表 End of file (文件结束)"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"解析标签"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"HTML 有三种标签"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"numberedlist","attrs":{"start":"1","normalizeStart":1},"content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":1,"align":null,"origin":null},"content":[{"type":"text","text":"开始标签"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":2,"align":null,"origin":null},"content":[{"type":"text","text":"结束标签"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":3,"align":null,"origin":null},"content":[{"type":"text","text":"自封闭标签"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"思路:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"主要的标签有:开始标签,结束标签和自封闭标签"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在这一步我们暂时忽略属性"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"文件:parser.js"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"javascript"},"content":[{"type":"text","text":"/**\n * 解析器\n * @filename parser.js\n * @author 三钻\n * @version v1.0.0\n */\n\nconst EOF = Symbol('EOF'); // EOF: end of file\n\n/**\n * HTML 数据开始阅读状态\n * --------------------------------\n * 1. 如果找到 `` 就报错\n * 3. 如果是结束符合,也是报错\n * @param {*} char\n */\nfunction endTagOpen(char) {\n if (char.match(/^[a-zA-Z]$/)) {\n return tagName(char);\n } else if (char === '>') {\n // 报错 —— 没有结束标签\n } else if (char === EOF) {\n // 报错 —— 结束标签不合法\n }\n}\n\n/**\n * 标签名状态\n * --------------------------------\n * 1. 如果 `\\t`(Tab符)、`\\n`(空格符)、`\\f`(禁止符)或者是空格,这里就是属性的开始\n * 2. 如果找到 `/` 就是自关闭标签\n * 3. 如果是字母字符那还是标签名\n * 4. 如果是 `>` 就是开始标签结束\n * 5. 其他就是继续寻找标签名\n * @param {*} char\n */\nfunction tagName(char) {\n if (c.match(/^[\\t\\n\\f ]$/)) {\n return beforeAttributeName;\n } else if (char === '/') {\n return selfClosingStartTag;\n } else if (c.match(/^[a-zA-Z]$/)) {\n return tagName;\n } else if (char === '>') {\n return data;\n } else {\n return tagName;\n }\n}\n\n\n/**\n * 标签属性状态\n * --------------------------------\n * 1. 如果遇到 `/` 就是自封闭标签状态\n * 2. 如果遇到字母就是属性名\n * 3. 如果遇到 `>` 就是标签结束\n * 4. 如果遇到 `=` 下来就是属性值\n * 5. 其他情况继续进入属性抓取\n * @param {*} char\n */\nfunction beforeAttributeName(char) {\n if (char === '/') {\n return selfClosingStartTag;\n } else if (char.match(/^[\\t\\n\\f ]$/)) {\n return beforeAttributeName;\n } else if (char === '>') {\n return data;\n } else if (char === '=') {\n return beforeAttributeName;\n } else {\n return beforeAttributeName;\n }\n}\n\n/**\n * 自封闭标签状态\n * --------------------------------\n * 1. 如果遇到 `>` 就是自封闭标签结束\n * 2. 如果遇到 `EOF` 即使报错\n * 3. 其他字符也是报错\n * @param {*} char\n */\nfunction selfClosingStartTag(char) {\n if (char === '>') {\n return data;\n } else if (char === 'EOF') {\n } else {\n }\n}\n\n/**\n * HTTP 解析\n * @param {string} html 文本\n */\nmodule.exports.parseHTML = function (html) {\n let state = data;\n for (let char of html) {\n state = state(char);\n }\n state = state(EOF);\n};\n"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"创建元素"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在状态机中,除了状态迁移,我们还会加入业务逻辑"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"我们在标签结束状态提交标签 token"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"业务逻辑:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"首先我们需要建立一个 "},{"type":"codeinline","content":[{"type":"text","text":"currentToken"}]},{"type":"text","text":" 来暂存当前的 Token(这里我们是用于存放开始和结束标签 token 的)"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"然后建立一个 "},{"type":"codeinline","content":[{"type":"text","text":"emit()"}]},{"type":"text","text":" 方法来接收最后创建完毕的 Token(这里后面会用逐个 Token 来创建 DOM 树)"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"HTML 数据开始状态 —— data"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" + 如果找到的是 "},{"type":"codeinline","content":[{"type":"text","text":"EOF"}]},{"type":"text","text":",那就直接 emit 一个 type: ‘EOF’ 的 Token"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" + 如果是文本内容的话,直接 emit "},{"type":"codeinline","content":[{"type":"text","text":"{type: 'text', content: char}"}]},{"type":"text","text":" 的 token"}]},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"标签开始状态 —— tagOpen"},{"type":"text","text":" "}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" + 如果匹配中的是字母,那就是开始标签"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" + 直接记录开始标签 Token 对象 "},{"type":"codeinline","content":[{"type":"text","text":"{type: 'startTag, tagName: ''}"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" + 在 "},{"type":"codeinline","content":[{"type":"text","text":"tagName()"}]},{"type":"text","text":" 状态中我们会把整个完整的标签名拼接好"}]},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"标签结束状态 —— endTagOpen"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" + 如果匹配到字符,那就是结束标签名"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" + 直接记录结束标签 Token 对象 "},{"type":"codeinline","content":[{"type":"text","text":"{type: 'endTag', tagName: ''}"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" + 雷同,后面会在 "},{"type":"codeinline","content":[{"type":"text","text":"tagName()"}]},{"type":"text","text":" 状态中我们会把整个完整的标签名拼接好"}]},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"标签名状态 —— tagName"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" + 这里就是最核心的业务区了"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" + 在第三种情况下,匹配到字母时,那就是需要拼接标签名的时候"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" + 这里我们直接给 "},{"type":"codeinline","content":[{"type":"text","text":"currentTag"}]},{"type":"text","text":" 追加字母即可"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" + 当我们匹配到 "},{"type":"codeinline","content":[{"type":"text","text":">"}]},{"type":"text","text":" 字符时,就是这个标签结束的时候,这个时候我们已经拥有一个完整的标签 Token了"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" + 所以这里我们直接把 "},{"type":"codeinline","content":[{"type":"text","text":"currentToken"}]},{"type":"text","text":" emit 出去"}]},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"标签属性状态 —— beforeAttributeName"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" + 在匹配到 "},{"type":"codeinline","content":[{"type":"text","text":">"}]},{"type":"text","text":" 字符的时候,这里就是标签结束的时候,所以可以 emit "},{"type":"codeinline","content":[{"type":"text","text":"currentToken"}]},{"type":"text","text":" 的时候"}]},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"自封闭标签状态 —— selfClosingStartTag"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" + 这里追加了一个逻辑"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" + 在匹配到 "},{"type":"codeinline","content":[{"type":"text","text":">"}]},{"type":"text","text":" 字符时,就是自闭标签结束的时候"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" + 这里我们直接给 "},{"type":"codeinline","content":[{"type":"text","text":"currentToken"}]},{"type":"text","text":" 追加一个 "},{"type":"codeinline","content":[{"type":"text","text":"isSelfClosing = true"}]},{"type":"text","text":" 的状态"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" + 然后直接可以把 "},{"type":"codeinline","content":[{"type":"text","text":"currentToken"}]},{"type":"text","text":" emit 出去了"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"文件:parser.js"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"javascript"},"content":[{"type":"text","text":"/**\n * 解析器\n * @filename parser.js\n * @author 三钻\n * @version v1.0.0\n */\n\nlet currentToken = null;\n\n/**\n * 输出 HTML token\n * @param {*} token\n */\nfunction emit(token) {\n console.log(token);\n}\n\nconst EOF = Symbol('EOF'); // EOF: end of file\n\n/**\n * HTML 数据开始阅读状态\n * --------------------------------\n * 1. 如果找到 `` 就报错\n * 3. 如果是结束符合,也是报错\n * @param {*} char\n */\nfunction endTagOpen(char) {\n if (char.match(/^[a-zA-Z]$/)) {\n currentToken = {\n type: 'endTag',\n tagName: '',\n };\n return tagName(char);\n } else if (char === '>') {\n // 报错 —— 没有结束标签\n } else if (char === EOF) {\n // 报错 —— 结束标签不合法\n }\n}\n\n/**\n * 标签名状态\n * --------------------------------\n * 1. 如果 `\\t`(Tab符)、`\\n`(空格符)、`\\f`(禁止符)或者是空格,这里就是属性的开始\n * 2. 如果找到 `/` 就是自关闭标签\n * 3. 如果是字母字符那还是标签名\n * 4. 如果是 `>` 就是开始标签结束\n * 5. 其他就是继续寻找标签名\n * @param {*} char\n */\nfunction tagName(char) {\n if (char.match(/^[\\t\\n\\f ]$/)) {\n return beforeAttributeName;\n } else if (char === '/') {\n return selfClosingStartTag;\n } else if (char.match(/^[a-zA-Z]$/)) {\n currentToken.tagName += char;\n return tagName;\n } else if (char === '>') {\n emit(currentToken);\n return data;\n } else {\n return tagName;\n }\n}\n\n/**\n * 标签属性状态\n * --------------------------------\n * 1. 如果遇到 `/` 就是自封闭标签状态\n * 2. 如果遇到字母就是属性名\n * 3. 如果遇到 `>` 就是标签结束\n * 4. 如果遇到 `=` 下来就是属性值\n * 5. 其他情况继续进入属性抓取\n * @param {*} char\n */\nfunction beforeAttributeName(char) {\n if (char === '/') {\n return selfClosingStartTag;\n } else if (char.match(/^[\\t\\n\\f ]$/)) {\n return beforeAttributeName;\n } else if (char === '>') {\n emit(currentToken);\n return data;\n } else if (char === '=') {\n return beforeAttributeName;\n } else {\n return beforeAttributeName;\n }\n}\n\n/**\n * 自封闭标签状态\n * --------------------------------\n * 1. 如果遇到 `>` 就是自封闭标签结束\n * 2. 如果遇到 `EOF` 即使报错\n * 3. 其他字符也是报错\n * @param {*} char\n */\nfunction selfClosingStartTag(char) {\n if (char === '>') {\n currentToken.isSelfClosing = true;\n emit(currentToken);\n return data;\n } else if (char === 'EOF') {\n } else {\n }\n}\n\n/**\n * HTTP 解析\n * @param {string} html 文本\n */\nmodule.exports.parseHTML = function (html) {\n let state = data;\n for (let char of html) {\n state = state(char);\n }\n state = state(EOF);\n};\n"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"处理属性"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"属性值分为单引号、双引号、无引号三种写法,因此需要较多状态处理"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"处理属性的方式跟标签类似"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"属性结束时,我们把属性加到标签 Token 上"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"业务逻辑:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"首先我们需要定义一个 "},{"type":"codeinline","content":[{"type":"text","text":"currentAttribute"}]},{"type":"text","text":" 来存放当前找到的属性"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"然后在里面叠加属性的名字和属性值,都完成后再放入 "},{"type":"codeinline","content":[{"type":"text","text":"currrentToken"}]},{"type":"text","text":" 之中"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"标签属性名开始状态 —— beforeAttributeName"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" + 这里如果遇到 空格,换行,回车等字符就可以再次进入标签属性名开始状态,继续等待属性的字符"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" + 如果我们遇到 "},{"type":"codeinline","content":[{"type":"text","text":"/"}]},{"type":"text","text":"或者"},{"type":"codeinline","content":[{"type":"text","text":">"}]},{"type":"text","text":"就是标签直接结束了,我们就可以进入属性结束状态"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" + 如果遇到 "},{"type":"codeinline","content":[{"type":"text","text":"="}]},{"type":"text","text":" 或者 "},{"type":"codeinline","content":[{"type":"text","text":"EOF"}]},{"type":"text","text":" 这里就有 HTML 语法错误,正常来说就会返回 "},{"type":"codeinline","content":[{"type":"text","text":"parse error"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" + 其他情况的话,就是刚刚开始属性名,这里就可以创建新的 "},{"type":"codeinline","content":[{"type":"text","text":"currentAttribute"}]},{"type":"text","text":" 对象 "},{"type":"codeinline","content":[{"type":"text","text":"{name: '', value: ''}"}]},{"type":"text","text":",然后返回属性名状态"}]},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"属性名状态 —— attributeName"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" + 如果我们遇到空格、换行、回车、"},{"type":"codeinline","content":[{"type":"text","text":"/"}]},{"type":"text","text":"、"},{"type":"codeinline","content":[{"type":"text","text":">"}]},{"type":"text","text":" 或者是 "},{"type":"codeinline","content":[{"type":"text","text":"EOF"}]},{"type":"text","text":"等字符时,就可以判定这个属性已经结束了,可以直接迁移到 "},{"type":"codeinline","content":[{"type":"text","text":"afterAttributeName"}]},{"type":"text","text":" 状态"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" + 如果我们遇到一个 "},{"type":"codeinline","content":[{"type":"text","text":"="}]},{"type":"text","text":" 字符,证明我们的属性名读取完毕,下来就是属性值了"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" + 如果我们遇到 "},{"type":"codeinline","content":[{"type":"text","text":"\\u0000"}]},{"type":"text","text":" 那就是解析错误,直接抛出 "},{"type":"codeinline","content":[{"type":"text","text":"Parse error"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" + 最后所有其他的都是当前属性名的字符,直接叠加到 "},{"type":"codeinline","content":[{"type":"text","text":"currentAttribute"}]},{"type":"text","text":" 的 "},{"type":"codeinline","content":[{"type":"text","text":"name"}]},{"type":"text","text":" 值中,然后继续进入属性名状态继续读取属性名字符"}]},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"属性值开始状态 —— beforeAttributeValue"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" + 如果我们遇到空格、换行、回车、"},{"type":"codeinline","content":[{"type":"text","text":"/"}]},{"type":"text","text":"、"},{"type":"codeinline","content":[{"type":"text","text":">"}]},{"type":"text","text":" 或者是 "},{"type":"codeinline","content":[{"type":"text","text":"EOF"}]},{"type":"text","text":"等字符时,我们继续往后寻找属性值,所以继续返回 "},{"type":"codeinline","content":[{"type":"text","text":"beforeAttributeValue"}]},{"type":"text","text":" 状态"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" + 如果遇到 "},{"type":"codeinline","content":[{"type":"text","text":"\""}]},{"type":"text","text":" 就是双引号属性值,进入 "},{"type":"codeinline","content":[{"type":"text","text":"doubleQuotedAttributeValue"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" + 如果遇到 "},{"type":"codeinline","content":[{"type":"text","text":"'"}]},{"type":"text","text":" 就是单引号属性值,进入 "},{"type":"codeinline","content":[{"type":"text","text":"singleQuotedAttributeValue"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" + 其他情况就是遇到没有引号的属性值,使用 "},{"type":"codeinline","content":[{"type":"text","text":"reconsume"}]},{"type":"text","text":" 的技巧进入 "},{"type":"codeinline","content":[{"type":"text","text":"unquotedAttributeValue(char)"}]}]},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"双引号属性值状态 -- doubleQuotedAttributeValue"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" + 这里我们死等 "},{"type":"codeinline","content":[{"type":"text","text":"\""}]},{"type":"text","text":" 字符,到达这个字符证明这个属性的名和值都读取完毕,可以直接把这两个值放入当前 Token 了"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" + 如果遇到 "},{"type":"codeinline","content":[{"type":"text","text":"\\u0000"}]},{"type":"text","text":" 或者 "},{"type":"codeinline","content":[{"type":"text","text":"EOF"}]},{"type":"text","text":" 就是 HTML 语法错误,直接抛出 "},{"type":"codeinline","content":[{"type":"text","text":"Parse error"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" + 其他情况就是继续读取属性值,并且叠加到 "},{"type":"codeinline","content":[{"type":"text","text":"currentAttribute"}]},{"type":"text","text":" 的 "},{"type":"codeinline","content":[{"type":"text","text":"value"}]},{"type":"text","text":" 中,然后继续进入 "},{"type":"text","marks":[{"type":"strong"}],"text":"doubleQuotedAttributeValue"}]},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"单引号属性值状态 —— singleQuotedAttributeValue"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" + 与双引号雷同,这里我们死等 "},{"type":"codeinline","content":[{"type":"text","text":"'"}]},{"type":"text","text":" 字符,到达这个字符证明这个属性的名和值都读取完毕,可以直接把这两个值放入当前 Token 了"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" + 如果遇到 "},{"type":"codeinline","content":[{"type":"text","text":"\\u0000"}]},{"type":"text","text":" 或者 "},{"type":"codeinline","content":[{"type":"text","text":"EOF"}]},{"type":"text","text":" 就是 HTML 语法错误,直接抛出 "},{"type":"codeinline","content":[{"type":"text","text":"Parse error"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" + 其他情况就是继续读取属性值,并且叠加到 "},{"type":"codeinline","content":[{"type":"text","text":"currentAttribute"}]},{"type":"text","text":" 的 "},{"type":"codeinline","content":[{"type":"text","text":"value"}]},{"type":"text","text":" 中,然后继续进入 "},{"type":"text","marks":[{"type":"strong"}],"text":"singleQuotedAttributeValue"}]},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"引号结束状态 —— afterQuotedAttributeValue"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" + 如果我们遇到空格、换行、回车等字符时,证明还有可能有属性值,所以我们迁移到 "},{"type":"codeinline","content":[{"type":"text","text":"beforeAttributeName"}]},{"type":"text","text":" 状态"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" + 这个时候遇到一个 "},{"type":"codeinline","content":[{"type":"text","text":"/"}]},{"type":"text","text":" 字符,因为之前我们读的是属性,属性都是在开始标签中的,在开始标签遇到 "},{"type":"codeinline","content":[{"type":"text","text":"/"}]},{"type":"text","text":" ,那肯定是自封闭标签了。所以这里直接迁移到 "},{"type":"codeinline","content":[{"type":"text","text":"selfClosingStartTag"}]},{"type":"text","text":" 状态"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" + 如果遇到 "},{"type":"codeinline","content":[{"type":"text","text":">"}]},{"type":"text","text":" 字符,证明标签要结束了,直接把当前组装好的属性名和值加入 "},{"type":"codeinline","content":[{"type":"text","text":"currentToken"}]},{"type":"text","text":", 然后直接 emit 出去"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" + 如果遇到 "},{"type":"codeinline","content":[{"type":"text","text":"EOF"}]},{"type":"text","text":" 那就是 HTML 语法错误,抛出 "},{"type":"codeinline","content":[{"type":"text","text":"Parse error"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" + 其他情况按照浏览器规范,这里属于属性之间缺少空格的解析错误 (Parse error: missing-whitespace-between-attributes)"}]},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"无引号属性值状态 —— unquotedAttributeValue"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" + 如果我们遇到空格、换行、回车等字符时,证明属性值结束,这个时候我们就可以直接把当前属性加入 currentToken,然后还有可能有其他属性,所以进入 "},{"type":"codeinline","content":[{"type":"text","text":"beforeAttributeName"}]},{"type":"text","text":" 状态"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" + 如果遇到 "},{"type":"codeinline","content":[{"type":"text","text":"/"}]},{"type":"text","text":" 证明标签是一个自封闭标签,先把当前属性加入 currentToken 然后进入 "},{"type":"codeinline","content":[{"type":"text","text":"selfClosingStartTag"}]},{"type":"text","text":" 状态"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" + 如果遇到 "},{"type":"codeinline","content":[{"type":"text","text":">"}]},{"type":"text","text":" 证明标签正常结束了,先把当前属性加入 currentToken 然后直接 emit token"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" + 遇到其他不合法字符都直接抛出 "},{"type":"codeinline","content":[{"type":"text","text":"Parse error"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" + 其他情况就是还在读取属性值的字符,所以叠加当前字符到属性值中,然后继续回到 "},{"type":"codeinline","content":[{"type":"text","text":"unquotedAttributeValue"}]}]},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"属性名结束状态 —— afterAttributeName"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" + 如果我们遇到空格、换行、回车等字符时,证明还没有找到结束字符,继续寻找,所以重新进入 "},{"type":"codeinline","content":[{"type":"text","text":"afterAttributeName"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" + 如果遇到 "},{"type":"codeinline","content":[{"type":"text","text":"/"}]},{"type":"text","text":" 证明这个标签是自封闭标签,直接迁移到 "},{"type":"codeinline","content":[{"type":"text","text":"selfClosingStartTag"}]},{"type":"text","text":" 状态"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" + 如果遇到 "},{"type":"codeinline","content":[{"type":"text","text":"="}]},{"type":"text","text":" 字符证明下一个字符开始就是属性值了,迁移到 "},{"type":"codeinline","content":[{"type":"text","text":"beforeAttributeValue"}]},{"type":"text","text":" 状态"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" + 如果遇到 "},{"type":"codeinline","content":[{"type":"text","text":">"}]},{"type":"text","text":" 字符,证明标签正常结束了,先把当前属性加入 currentToken 然后直接 emit token"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" + 如果遇到 "},{"type":"codeinline","content":[{"type":"text","text":"EOF"}]},{"type":"text","text":" 证明HTML 文本异常结束了,直接抛出 "},{"type":"codeinline","content":[{"type":"text","text":"Parse error"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" + 其他情况下,属于属性名又开始了,所以把上一个属性加入 currentToken 然后继续记录下一个属性"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"文件名:parser.js"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"javascript"},"content":[{"type":"text","text":"/**\n * 解析器\n * @filename parser.js\n * @author 三钻\n * @version v1.0.0\n */\n\nlet currentToken = null;\nlet currentAttribute = null;\n\n/**\n * 输出 HTML token\n * @param {*} token\n */\nfunction emit(token) {\n console.log(token);\n}\n\nconst EOF = Symbol('EOF'); // EOF: end of file\n\n/**\n * HTML 数据开始阅读状态\n * --------------------------------\n * 1. 如果找到 `` 就报错\n * 3. 如果是结束符合,也是报错\n * @param {*} char\n */\nfunction endTagOpen(char) {\n if (char.match(/^[a-zA-Z]$/)) {\n currentToken = {\n type: 'endTag',\n tagName: '',\n };\n return tagName(char);\n } else if (char === '>') {\n // 报错 —— 没有结束标签\n } else if (char === EOF) {\n // 报错 —— 结束标签不合法\n }\n}\n\n/**\n * 标签名状态\n * --------------------------------\n * 1. 如果 `\\t`(Tab符)、`\\n`(空格符)、`\\f`(禁止符)或者是空格,这里就是属性的开始\n * 2. 如果找到 `/` 就是自关闭标签\n * 3. 如果是字母字符那还是标签名\n * 4. 如果是 `>` 就是开始标签结束\n * 5. 其他就是继续寻找标签名\n * @param {*} char\n */\nfunction tagName(char) {\n if (char.match(/^[\\t\\n\\f ]$/)) {\n return beforeAttributeName;\n } else if (char === '/') {\n return selfClosingStartTag;\n } else if (char.match(/^[a-zA-Z]$/)) {\n currentToken.tagName += char;\n return tagName;\n } else if (char === '>') {\n emit(currentToken);\n return data;\n } else {\n return tagName;\n }\n}\n\n/**\n * 标签属性名开始状态\n * --------------------------------\n * 1. 如果遇到 `/` 就是自封闭标签状态\n * 2. 如果遇到字母就是属性名\n * 3. 如果遇到 `>` 就是标签结束\n * 4. 如果遇到 `=` 下来就是属性值\n * 5. 其他情况继续进入属性抓取\n * @param {*} char\n */\nfunction beforeAttributeName(char) {\n if (char.match(/^[\\t\\n\\f ]$/)) {\n return beforeAttributeName;\n } else if (char === '/' || char === '>') {\n return afterAttributeName(char);\n } else if (char === '=' || char === EOF) {\n throw new Error('Parse error');\n } else {\n currentAttribute = {\n name: '',\n value: '',\n };\n return attributeName(char);\n }\n}\n\n/**\n * 属性名状态\n * @param {*} char\n */\nfunction attributeName(char) {\n if (char.match(/^[\\t\\n\\f ]$/) || char === '/' || char === '>' || char === EOF) {\n return afterAttributeName(char);\n } else if (char === '=') {\n return beforeAttributeValue;\n } else if (char === '\\u0000') {\n throw new Error('Parse error');\n } else {\n currentAttribute.name += char;\n return attributeName;\n }\n}\n\n/**\n * 属性值开始状态\n * @param {*} char\n */\nfunction beforeAttributeValue(char) {\n if (char.match(/^[\\t\\n\\f ]$/) || char === '/' || char === '>' || char === EOF) {\n return beforeAttributeValue;\n } else if (char === '\"') {\n return doubleQuotedAttributeValue;\n } else if (char === \"'\") {\n return singleQuotedAttributeValue;\n } else if (char === '>') {\n // return data;\n } else {\n return unquotedAttributeValue(char);\n }\n}\n\n/**\n * 双引号属性值状态\n * @param {*} char\n */\nfunction doubleQuotedAttributeValue(char) {\n if (char === '\"') {\n currentToken[currentAttribute.name] = currentAttribute.value;\n return afterQuotedAttributeValue;\n } else if (char === '\\u0000') {\n throw new Error('Parse error');\n } else if (char === EOF) {\n throw new Error('Parse error');\n } else {\n currentAttribute.value += char;\n return doubleQuotedAttributeValue;\n }\n}\n\n/**\n * 单引号属性值状态\n * @param {*} char\n */\nfunction singleQuotedAttributeValue(char) {\n if (char === \"'\") {\n currentToken[currentAttribute.name] = currentAttribute.value;\n return afterQuotedAttributeValue;\n } else if (char === '\\u0000') {\n throw new Error('Parse error');\n } else if (char === EOF) {\n throw new Error('Parse error');\n } else {\n currentAttribute.value += char;\n return singleQuotedAttributeValue;\n }\n}\n\n/**\n * 引号结束状态\n * @param {*} char\n */\nfunction afterQuotedAttributeValue(char) {\n if (char.match(/^[\\t\\n\\f ]$/)) {\n return beforeAttributeName;\n } else if (char === '/') {\n return selfClosingStartTag;\n } else if (char === '>') {\n currentToken[currentAttribute.name] = currentAttribute.value;\n emit(currentToken);\n return data;\n } else if (char === EOF) {\n throw new Error('Parse error: eof-in-tag');\n } else {\n throw new Error('Parse error: missing-whitespace-between-attributes');\n }\n}\n\n/**\n * 无引号属性值状态\n * @param {*} char\n */\nfunction unquotedAttributeValue(char) {\n if (char.match(/^[\\t\\n\\f ]$/)) {\n currentToken[currentAttribute.name] = currentAttribute.value;\n return beforeAttributeName;\n } else if (char === '/') {\n currentToken[currentAttribute.name] = currentAttribute.value;\n return selfClosingStartTag;\n } else if (char === '>') {\n currentToken[currentAttribute.name] = currentAttribute.value;\n emit(currentToken);\n return data;\n } else if (char === '\\u0000') {\n throw new Error('Parse error');\n } else if (char === '\"' || char === \"'\" || char === '') {\n currentToken[currentAttribute.name] = currentAttribute.value;\n emit(currentToken);\n return data;\n } else if (char === EOF) {\n throw new Error('Parse error');\n } else {\n currentToken[currentAttribute.name] = currentAttribute.value;\n currentAttribute = {\n name: '',\n value: '',\n };\n return attributeName(char);\n }\n}\n\n/**\n * 自封闭标签状态\n * --------------------------------\n * 1. 如果遇到 `>` 就是自封闭标签结束\n * 2. 如果遇到 `EOF` 即使报错\n * 3. 其他字符也是报错\n * @param {*} char\n */\nfunction selfClosingStartTag(char) {\n if (char === '>') {\n currentToken.isSelfClosing = true;\n emit(currentToken);\n return data;\n } else if (char === 'EOF') {\n } else {\n }\n}\n\n/**\n * HTTP 解析\n * @param {string} html 文本\n */\nmodule.exports.parseHTML = function (html) {\n let state = data;\n for (let char of html) {\n state = state(char);\n }\n state = state(EOF);\n};\n"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"用 token 构建 DOM 树"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"这里我们开始语法分析,这个与复杂的 JavaScript 的语法相比就非常简单,所以我们只需要用栈基于可以完成分析。但是如果我们要做一个完整的浏览器,只用栈肯定是不行的,因为浏览器是有容错性的,如果我们没有编写结束标签的话,浏览器是会去为我们补错机制的。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"那么我做的这个简单的浏览器就不需要对使用者做的那么友好,而只对实现者做的更友好即可。所以我们在实现的过程中就不做那么多特殊情况的处理了。简单用一个栈实现浏览器的 HTML 语法解析,并且构建 一个 DOM 树。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"从标签构建 DOM 树的基本技巧是使用栈"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"遇到开始标签时创建元素并入栈,遇到结束标签时出栈"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"自封闭节点可视为入栈后立刻出栈"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"任何元素的父元素是它入栈前的栈顶"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"文件:parser.js 中的 emit() 函数部分"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"javascript"},"content":[{"type":"text","text":"// 默认给予根节点 document\nlet stack = [{ type: 'document', children: [] }];\n\n/**\n * 输出 HTML token\n * @param {*} token\n */\nfunction emit(token) {\n if (token.type === 'text') return;\n\n // 记录上一个元素 - 栈顶\n let top = stack[stack.length - 1];\n\n // 如果是开始标签\n if (token.type == 'startTag') {\n let element = {\n type: 'element',\n children: [],\n attributes: [],\n };\n\n element.tagName = token.tagName;\n\n for (let prop in token) {\n if (prop !== 'type' && prop != 'tagName') {\n element.attributes.push({\n name: prop,\n value: token[prop],\n });\n }\n }\n\n // 对偶操作\n top.children.push(element);\n element.parent = top;\n\n if (!token.isSelfClosing) stack.push(element);\n\n currentTextNode = null;\n } else if (token.type == 'endTag') {\n if (top.tagName !== token.tagName) {\n throw new Error('Parse error: Tag start end not matched');\n } else {\n stack.pop();\n }\n\n currentTextNode = null;\n }\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":" 将文本节点加到 DOM 树"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"这里是 HTML 解析的最后一步,把文本节点合并后加入 DOM 树里面。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"文本节点与自封闭标签处理类似"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"多个文本节点需要合并"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"文件:parser.js 中的 emit() 函数部分"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"javascript"},"content":[{"type":"text","text":"let currentToken = null;\nlet currentAttribute = null;\nlet currentTextNode = null;\n\n// 默认给予根节点 document\nlet stack = [{ type: 'document', children: [] }];\n\n/**\n * 输出 HTML token\n * @param {*} token\n */\nfunction emit(token) {\n // 记录上一个元素 - 栈顶\n let top = stack[stack.length - 1];\n\n // 如果是开始标签\n if (token.type == 'startTag') {\n let element = {\n type: 'element',\n children: [],\n attributes: [],\n };\n\n element.tagName = token.tagName;\n\n for (let prop in token) {\n if (prop !== 'type' && prop != 'tagName') {\n element.attributes.push({\n name: prop,\n value: token[prop],\n });\n }\n }\n\n // 对偶操作\n top.children.push(element);\n element.parent = top;\n\n if (!token.isSelfClosing) stack.push(element);\n\n currentTextNode = null;\n } else if (token.type == 'endTag') {\n if (top.tagName !== token.tagName) {\n throw new Error('Parse error: Tag start end not matched');\n } else {\n stack.pop();\n }\n\n currentTextNode = null;\n } else if (token.type === 'text') {\n if (currentTextNode === null) {\n currentTextNode = {\n type: 'text',\n content: '',\n };\n top.children.push(currentTextNode);\n }\n\n currentTextNode.content += token.content;\n }\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/b3/b34c995f506fd74ab4d6e4adb20b4706.png","alt":null,"title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":1},"content":[{"type":"text","text":"CSS 计算"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"完成 HTML 解析并且获得了我们的 DOM 树之后,我们可以通过 CSS 计算来生成带 CSS 的 DOM 树。CSS Computing 表示的就是我们 CSS 规则里面所包含的那些 CSS 属性,应用到匹配这些选择器的元素上。 "}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"开始这个代码编写之前,我们先来看看z在整个浏览器工作流程中,我们完成了哪些流程,到达了哪里。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/be/be7d64ed5ccbdc032ca0d337bf14a391.png","alt":null,"title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"上面的图,我们看到 "},{"type":"codeinline","content":[{"type":"text","text":"蓝色"}]},{"type":"text","text":" 部分就是已经完成的:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"上一篇文章我们完成了 HTTP 请求"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"然后通过获得的报文,解析出所有 HTTP 信息,里面就包括了 HTML 内容"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"然后通过 HTTP 内容解析,我们构建了我们的 DOM 树"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"接下来就是 CSS 计算 (CSS Computing)"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"目前的 DOM 树只有我们的 HTML 语言里面描述的那些语义信息,我们像完成渲染,我们需要 CSS 信息。 那有的同学就会说我们把所有的样式写到 style 里面可不可以呢?如果我们这样写呢,我们就不需要经历这个 CSS 计算的过程了。但是虽然我们只是做一个虚拟的浏览器,但是还是希望呈现一个比较完成的浏览器流程,所以我们还是会让 DOM 树参与 CSS 计算的过程。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"所以这里我们就让 DOM 树挂上 CSS 信息,然后在渲染的过程中能使用。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在编写这个代码之前,我们需要准备一个环境。如果我们需要做 CSS 计算,我们就需要对 CSS 的语法与词法进行分析。然后这个过程如果是手动来实现的话,是需要较多的编译原理基础知识的,但是这些编译基础知识的深度对我们知识想了解浏览器工作原理并不是重点。所以这里我们就偷个懒,直接用 npm 上的一个"},{"type":"codeinline","content":[{"type":"text","text":"css"}]},{"type":"text","text":"现成包即可。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"其实这个 "},{"type":"codeinline","content":[{"type":"text","text":"css"}]},{"type":"text","text":" 包,就是一个 CSS parser,可以帮助我们完成 CSS 代码转译成 AST 抽象语法树。 我们所要做的就是根据这棵抽象语法树抽出各种 CSS 规则,并且把他们运用到我们的 HTML 元素上。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"那么我们第一步就是先拿到 CSS 的规则,所以叫做 “收集 CSS 规则”"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"收集 CSS 规则"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"遇到 style 标签时,我们把 CSS 规则保存起来"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"文件:parser.js 中的 emit() 函数"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"+ 我们在 tagName === 'endTag' 的判断中加入了判断当前标签是否 "},{"type":"codeinline","content":[{"type":"text","text":"style"}]},{"type":"text","text":" 标签"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"+ 如果是,我们就可以获取 "},{"type":"codeinline","content":[{"type":"text","text":"style"}]},{"type":"text","text":" 标签里面所有的内容进行 CSS 分析"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"+ 这里非常简单我们加入一个 "},{"type":"codeinline","content":[{"type":"text","text":"addCSSRule(top.children[0].content)"}]},{"type":"text","text":"的函数即可"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"+ 而,"},{"type":"codeinline","content":[{"type":"text","text":"top"}]},{"type":"text","text":" 就是当前元素,"},{"type":"codeinline","content":[{"type":"text","text":"children[0]"}]},{"type":"text","text":" 就是 text 元素,而 "},{"type":"codeinline","content":[{"type":"text","text":".content"}]},{"type":"text","text":" 就是所有的 CSS 规则文本"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"+ 这里我们需要注意一个点,我们忽略了在实际情况中还有 "},{"type":"codeinline","content":[{"type":"text","text":"link"}]},{"type":"text","text":" 标签引入 CSS 文件的情况。但是这个过程涉及到多层异步请求和 HTML 解析的过程,为了简化我们的代码的复杂度,这里就不做这个实现了。当然实际的浏览器是会比我们做的虚拟浏览器复杂的多。"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"javascript"},"content":[{"type":"text","text":"/**\n * 输出 HTML token\n * @param {*} token\n */\nfunction emit(token) {\n // 记录上一个元素 - 栈顶\n let top = stack[stack.length - 1];\n\n // 如果是开始标签\n if (token.type == 'startTag') {\n // ............. 省略了这部分代码 .....................\n } else if (token.type == 'endTag') {\n // 校验开始标签是否被结束\n // 不是:直接抛出错误,是:直接出栈\n if (top.tagName !== token.tagName) {\n throw new Error('Parse error: Tag start end not matched');\n } else {\n // 遇到 style 标签时,执行添加 CSS 规则的操作\n if (top.tagName === 'style') {\n addCSSRule(top.children[0].content);\n }\n stack.pop();\n }\n\n currentTextNode = null;\n } else if (token.type === 'text') {\n // ............. 省略了这部分代码 .....................\n }\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"这里我们调用 CSS Parser 来分析 CSS 规则"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"文件:parser.js 中加入 addCSSRule() 函数"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"+ 首先我们需要通过 node 引入 "},{"type":"codeinline","content":[{"type":"text","text":"css"}]},{"type":"text","text":" 包"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"+ 然后调用 "},{"type":"codeinline","content":[{"type":"text","text":"css.parse(text)"}]},{"type":"text","text":" 获得 AST 抽象语法树"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"+ 最后通过使用 "},{"type":"codeinline","content":[{"type":"text","text":"..."}]},{"type":"text","text":" 的特性展开了 "},{"type":"codeinline","content":[{"type":"text","text":"ast.stylesheet.rules"}]},{"type":"text","text":" 中的所有对象,并且加入到 "},{"type":"codeinline","content":[{"type":"text","text":"rules"}]},{"type":"text","text":" 里面"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"javascript"},"content":[{"type":"text","text":"const css = require('css');\n\nlet rules = [];\n/**\n * 把 CSS 规则暂存到一个数字里\n * @param {*} text\n */\nfunction addCSSRule(text) {\n var ast = css.parse(text);\n console.log(JSON.stringify(ast, null, ' '));\n rules.push(...ast.stylesheet.rules);\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"这里我们必须要仔细研究此库分析 CSS 规则的格式"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"最终 AST 输出的结果:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"codeinline","content":[{"type":"text","text":"type"}]},{"type":"text","text":" 类型是 "},{"type":"codeinline","content":[{"type":"text","text":"stylesheet"}]},{"type":"text","text":" 样式表"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"然后在 "},{"type":"codeinline","content":[{"type":"text","text":"stylesheet"}]},{"type":"text","text":" 中有 "},{"type":"codeinline","content":[{"type":"text","text":"rules"}]},{"type":"text","text":" 的 CSS 规则数组"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"codeinline","content":[{"type":"text","text":"rules"}]},{"type":"text","text":" 数组中就有一个 "},{"type":"codeinline","content":[{"type":"text","text":"declarations"}]},{"type":"text","text":" 数组,这里面就是我们 CSS 样式的信息了"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"拿第一个 delarations 来说明,他的属性为 "},{"type":"codeinline","content":[{"type":"text","text":"width"}]},{"type":"text","text":", 属性值为 "},{"type":"codeinline","content":[{"type":"text","text":"100px"}]},{"type":"text","text":",这些就是我们需要的 CSS 规则了"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"javascript"},"content":[{"type":"text","text":"{\n type: \"stylesheet\",\n stylesheet: {\n source: undefined,\n rules: [\n {\n type: \"rule\",\n selectors: [\n \"body div #myId\",\n ],\n declarations: [\n {\n type: \"declaration\",\n property: \"width\",\n value: \"100px\",\n position: {\n start: {\n line: 3,\n column: 9,\n },\n end: {\n line: 3,\n column: 21,\n },\n source: undefined,\n },\n },\n {\n type: \"declaration\",\n property: \"background-color\",\n value: \"#ff5000\",\n position: {\n start: {\n line: 4,\n column: 9,\n },\n end: {\n line: 4,\n column: 34,\n },\n source: undefined,\n },\n },\n ],\n position: {\n start: {\n line: 2,\n column: 7,\n },\n end: {\n line: 5,\n column: 8,\n },\n source: undefined,\n },\n },\n ],\n parsingErrors: [\n ],\n },\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"这里还有一个问题需要我们注意的,像 "},{"type":"codeinline","content":[{"type":"text","text":"body div #myId"}]},{"type":"text","text":" 这种带有空格的标签选择器,是不会逐个给我们单独分析出来的,所以这种我们是需要在后面自己逐个分解分析。除非是 "},{"type":"codeinline","content":[{"type":"text","text":","}]},{"type":"text","text":" 逗号分隔的选择器才会被拆解成多个 "},{"type":"codeinline","content":[{"type":"text","text":"delarations"}]},{"type":"text","text":"。"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"添加调用"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"上一步我们收集好了 CSS 规则,这一步我们就是要找一个合适的时机把这些规则应用上。应用的时机肯定是越早越好,CSS 设计里面有一个潜规则,就是 CSS 设计会尽量保证所有的选择器都能够在 "},{"type":"codeinline","content":[{"type":"text","text":"startTag"}]},{"type":"text","text":" 进入的时候就能被判断。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"当然,我们后面又加了一些高级的选择器之后,这个规则有了一定的松动,但是大部分的规则仍然是去遵循这个规则的,当我们 DOM 树构建到元素的 startTag 的步骤,就已经可以判断出来它能匹配那些 CSS 规则了"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"当我们创建一个元素后,立即计算CSS"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"我们假设:理论上,当我们分析一个元素时,所有的 CSS 规则已经被收集完毕"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在真实浏览器中,可能遇到写在 body 的 style 标签,需要重新 CSS 计算的情况,这里我们忽略"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"文件:parser.js 的 emit() 函数加入 computeCSS() 函数调用"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"javascript"},"content":[{"type":"text","text":"/**\n * 输出 HTML token\n * @param {*} token\n */\nfunction emit(token) {\n // 记录上一个元素 - 栈顶\n let top = stack[stack.length - 1];\n\n // 如果是开始标签\n if (token.type == 'startTag') {\n let element = {\n type: 'element',\n children: [],\n attributes: [],\n };\n\n element.tagName = token.tagName;\n\n // 叠加标签属性\n for (let prop in token) {\n if (prop !== 'type' && prop != 'tagName') {\n element.attributes.push({\n name: prop,\n value: token[prop],\n });\n }\n }\n\n // 元素构建好之后直接开始 CSS 计算\n computeCSS(element);\n\n // 对偶操作\n top.children.push(element);\n element.parent = top;\n // 自封闭标签之外,其他都入栈\n if (!token.isSelfClosing) stack.push(element);\n\n currentTextNode = null;\n } else if (token.type == 'endTag') {\n // ............. 省略了这部分代码 .....................\n } else if (token.type === 'text') {\n // ............. 省略了这部分代码 .....................\n }\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"文件:parser.js 中加入 computeCSS() 函数"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"javascript"},"content":[{"type":"text","text":"/**\n * 对元素进行 CSS 计算\n * @param {*} element\n */\nfunction computeCSS(element) {\n console.log(rules);\n console.log('compute CSS for Element', element);\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"获取父元素序列"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"为什么需要获取父元素序列呢?因为我们今天的选择器大多数都是跟元素的父元素相关的。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在 computeCSS 函数中,我们必须知道元素的所有父级元素才能判断元素与规则是否匹配"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"我们从上一步骤的 stack,可以获取本元素的父元素"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"因为我们首先获取的是 “当前元素”,所以我们获得和计算父元素匹配的顺序是从内向外"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"文件:parser.js 中的 computeCSS() 函数"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"+ 因为栈里面的元素是会不断的变化的,所以后期元素会在栈中发生变化,就会可能被污染。所以这里我们用了一个"},{"type":"codeinline","content":[{"type":"text","text":"slice"}]},{"type":"text","text":"来复制这个元素。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"+ 然后我们用了 "},{"type":"codeinline","content":[{"type":"text","text":"reverse()"}]},{"type":"text","text":" 把元素的顺序倒过来,为什么我们需要颠倒元素的顺序呢?是因为我们的标签匹配是会从当前元素开始逐级的往外匹配(也就是一级一级往父级元素去匹配的) "}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"javascript"},"content":[{"type":"text","text":"/**\n * 对元素进行 CSS 计算\n * @param {*} element\n */\nfunction computeCSS(element) {\n var elements = stack.slice().reverse();\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"选择器与元素的匹配"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"首先我们来了解一下选择器的机构,其实选择器其实是有一个层级结构的:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"最外层叫选择器列表,这个我们的 CSS parser 已经帮我们做了拆分"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"选择器列表里面的,叫做复杂选择器,这个是由空格分隔了我们的复合选择器"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"复杂选择器是根据亲代关系,去选择元素的"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"复合选择器,是针对一个元素的本身的属性和特征的判断"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"而复合原则性选择器,它又是由紧连着的一对选择器而构成的"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在我们的模拟浏览器中,我们可以假设一个复杂选择器中只包含简单选择器"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"我们就把这种情况当成而外有精力的同学自行去实现了哈"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"思路:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"选择器也要从当前元素向外排列"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"复杂选择器拆成对单个元素的选择器,用循环匹配父级元素队列"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"javascript"},"content":[{"type":"text","text":"/**\n * 匹配函数下一节会重点实现\n * @param {*} element\n * @param {*} selector\n */\nfunction match(element, selector) {}\n\n/**\n * 对元素进行 CSS 计算\n * @param {*} element\n */\nfunction computeCSS(element) {\n var elements = stack.slice().reverse();\n\n if (!elements.computedStyle) element.computedStyle = {};\n // 这里循环 CSS 规则,让规则与元素匹配\n // 1. 如果当前选择器匹配不中当前元素直接 continue\n // 2. 当前元素匹配中了,就一直往外寻找父级元素找到能匹配上选择器的元素\n // 3. 最后检验匹配中的元素是否等于选择器的总数,是就是全部匹配了,不是就是不匹配\n for (let rule of rules) {\n let selectorParts = rule.selectors[0].split(' ').reverse();\n\n if (!match(element, selectorParts[0])) continue;\n\n let matched = false;\n\n let j = 1;\n for (let i = 0; i < elements.length; i++) {\n if (match(elements[i], selectorParts[j])) j++;\n }\n\n if (j >= selectorParts.length) matched = true;\n\n if (matched) console.log('Element', element, 'matched rule', rule);\n }\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"计算选择器与元素"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"上一节我们没有完成 "},{"type":"codeinline","content":[{"type":"text","text":"match"}]},{"type":"text","text":" 匹配函数的实现,那这一部分我们来一起实现元素与选择器的匹配逻辑。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"根据选择器的类型和元素属性,计算是否与当前元素匹配"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"这里仅仅实现了三种基本选择器,实际的浏览器中要处理复合选择器 "}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"同学们可以自己尝试一下实现复合选择器,实现支持空格的 Class 选择器"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"javascript"},"content":[{"type":"text","text":"/**\n * 匹配元素和选择器\n * @param {Object} element 当前元素\n * @param {String} selector CSS 选择器\n */\nfunction match(element, selector) {\n if (!selector || !element.attributes) return false;\n\n if (selector.charAt(0) === '#') {\n let attr = element.attributes.filter(attr => attr.name === 'id')[0];\n if (attr && attr.value === selector.replace('#', '')) return true;\n } else if (selector.charAt(0) === '.') {\n let attr = element.attributes.filter(attr => attr.name === 'class')[0];\n if (attr && attr.value === selector.replace('.', '')) return true;\n } else {\n if (element.tagName === selector) return true;\n }\n\n return false;\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":" 生成 computed 属性"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"这一部分我们生成 computed 属性,这里我们只需要把 "},{"type":"codeinline","content":[{"type":"text","text":"delarations"}]},{"type":"text","text":" 里面声明的属性给他加到我们的元素的 "},{"type":"codeinline","content":[{"type":"text","text":"computed"}]},{"type":"text","text":" 上就可以了。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"一旦选择器匹配中了,就把选择器中的属性应用到元素上"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"然后形成 computedStyle"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"javascript"},"content":[{"type":"text","text":"/**\n * 对元素进行 CSS 计算\n * @param {*} element\n */\nfunction computeCSS(element) {\n var elements = stack.slice().reverse();\n\n if (!elements.computedStyle) element.computedStyle = {};\n // 这里循环 CSS 规则,让规则与元素匹配\n // 1. 如果当前选择器匹配不中当前元素直接 continue\n // 2. 当前元素匹配中了,就一直往外寻找父级元素找到能匹配上选择器的元素\n // 3. 最后检验匹配中的元素是否等于选择器的总数,是就是全部匹配了,不是就是不匹配\n for (let rule of rules) {\n let selectorParts = rule.selectors[0].split(' ').reverse();\n\n if (!match(element, selectorParts[0])) continue;\n\n let matched = false;\n\n let j = 1;\n for (let i = 0; i < elements.length; i++) {\n if (match(elements[i], selectorParts[j])) j++;\n }\n\n if (j >= selectorParts.length) matched = true;\n\n if (matched) {\n let computedStyle = element.computedStyle;\n for (let declaration of rule.declarations) {\n if (!computedStyle[declaration.property]) computedStyle[declaration.property] = {};\n computedStyle[declaration.property].value = declaration.value;\n }\n console.log(computedStyle);\n }\n }\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"看完代码的同学,或者自己去实现这个代码时候的同学,应该会发现这个代码中有一个问题。如果我们回去看看我们的 HTML 代码中的 style 样式表,我们发现 HTML 中的 "},{"type":"codeinline","content":[{"type":"text","text":"img"}]},{"type":"text","text":" 标签会被两个 CSS 选择器匹配中,分别是 "},{"type":"codeinline","content":[{"type":"text","text":"body div #myId"}]},{"type":"text","text":" 和 "},{"type":"codeinline","content":[{"type":"text","text":"body div img"}]},{"type":"text","text":"。这样就会导致前面匹配中后加入 "},{"type":"codeinline","content":[{"type":"text","text":"computedStyle"}]},{"type":"text","text":" 的属性值会被后面匹配中的属性值所覆盖。但是根据 CSS 中的权重规则,ID选择器是高于标签选择器的。这个问题我们下一部分会和同学们一起解决掉哦。"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":" Specificity 的计算逻辑"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"上一节的代码中,我们只是把匹配中的选择器中的属性直接覆盖上一个,但是其实在 CSS 里面是有一个 "},{"type":"codeinline","content":[{"type":"text","text":"specification"}]},{"type":"text","text":" 的规定。"},{"type":"codeinline","content":[{"type":"text","text":"specification"}]},{"type":"text","text":" 翻译成中文,很多时候都会被翻译成 "},{"type":"codeinline","content":[{"type":"text","text":"优先级"}]},{"type":"text","text":",当然在理论上是对的,但是在英文中呢,优先级是 "},{"type":"codeinline","content":[{"type":"text","text":"priority"}]},{"type":"text","text":",所以 "},{"type":"codeinline","content":[{"type":"text","text":"specificity"}]},{"type":"text","text":" 是 "},{"type":"codeinline","content":[{"type":"text","text":"专指程度"}]},{"type":"text","text":"。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"放在 CSS 中理解就是,ID 选择器中的专指度是会比 CLASS 选择器的高,所以 CSS 中的 "},{"type":"text","marks":[{"type":"strong"}],"text":"ID 的属性会覆盖 CLASS 的属性"},{"type":"text","text":"。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"好我们先来理解一下 "},{"type":"codeinline","content":[{"type":"text","text":"specification"}]},{"type":"text","text":" 是什么?"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"首先 "},{"type":"codeinline","content":[{"type":"text","text":"specifity"}]},{"type":"text","text":" 会有四个元素"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"按照 CSS 中优先级的顺序来说就是 inline style > id > class > tag"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"所以把这个生成为 "},{"type":"codeinline","content":[{"type":"text","text":"specificity"}]},{"type":"text","text":" 就是 "},{"type":"codeinline","content":[{"type":"text","text":"[0, 0, 0, 0]"}]}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"数组里面每一个数字都是代表在样式表中出现的次数"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"下面我们用一些例子来分析一下,我们应该如何用 "},{"type":"codeinline","content":[{"type":"text","text":"specificity"}]},{"type":"text","text":" 来分辨优先级的:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"A组选择器"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"A 选择器:"},{"type":"codeinline","content":[{"type":"text","text":"div div #id"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"A 的 "},{"type":"codeinline","content":[{"type":"text","text":"specification"}]},{"type":"text","text":" :[0, 1, 0, 2]"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"+ id 出现了一次,所以第二位数字是 "},{"type":"codeinline","content":[{"type":"text","text":"1"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"+ div tag 出现了两次,所以第四位数是 "},{"type":"codeinline","content":[{"type":"text","text":"2"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"B组选择器"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"B 选择器:"},{"type":"codeinline","content":[{"type":"text","text":"div #my #id"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"B 的 "},{"type":"codeinline","content":[{"type":"text","text":"specification"}]},{"type":"text","text":":[0, 2, 0, 1]"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"+ id 出现了两次,所以第二位数字是 "},{"type":"codeinline","content":[{"type":"text","text":"2"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"+ div tag 出现了一次,所以第四位数是 "},{"type":"codeinline","content":[{"type":"text","text":"1"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"好,那么我们怎么去比较上面的两种选择器,那个更大呢?"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"numberedlist","attrs":{"start":"1","normalizeStart":1},"content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":1,"align":null,"origin":null},"content":[{"type":"text","text":"我们需要从左到右开始比对;"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":2,"align":null,"origin":null},"content":[{"type":"text","text":"遇到同位置的数值一样的,就可以直接跳过;"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":3,"align":null,"origin":null},"content":[{"type":"text","text":"直到我们找到一对数值是有不一样的,这个时候就看是哪个选择器中的数值更大,那个选择器的优先级就更高;"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":4,"align":null,"origin":null},"content":[{"type":"text","text":"只要有一对比对出大小后,后面的就不需要再比对了。"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"用上面 A 和 B 两种选择器来做对比的话,第一对两个都是 "},{"type":"codeinline","content":[{"type":"text","text":"0"}]},{"type":"text","text":",所以可以直接跳过。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"然后第二位数值对,A选择器是 "},{"type":"codeinline","content":[{"type":"text","text":"1"}]},{"type":"text","text":",B选择器是 "},{"type":"codeinline","content":[{"type":"text","text":"2"}]},{"type":"text","text":",很明显 B 要比 A 大,所以 B 选择器中的属性就要覆盖 A 的。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"说到这里同学们应该都明白 CSS 中 "},{"type":"codeinline","content":[{"type":"text","text":"specificity"}]},{"type":"text","text":" 的规则和对比原理了,下来我们一起来看看如何实现这个代码逻辑。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"CSS 规则根据 specificity 和后来优先规则覆盖"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"specificity 是个四元组,越左边权重越高"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"一个 CSS 规则的 specificity 根据包含的简单选择器相加而成"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"文件:parser.js 中添加一个 "},{"type":"codeinline","content":[{"type":"text","text":"specificity"}]},{"type":"text","text":" 函数,来计算一个选择器的 specificity"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"javascript"},"content":[{"type":"text","text":"/**\n * 计算选择器的 specificity\n * @param {*} selector\n */\nfunction specificity(selector) {\n let p = [0, 0, 0, 0];\n let selectorParts = selector.split(' ');\n for (let part of selectorParts) {\n if (part.charAt(0) === '#') {\n p[1] += 1;\n } else if (part.charAt(0) === '.') {\n p[2] += 1;\n } else {\n p[3] += 1;\n }\n }\n return p;\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"文件:parser.js 添加一个 "},{"type":"codeinline","content":[{"type":"text","text":"compare"}]},{"type":"text","text":" 函数,来对比两个选择器的 specificity"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"javascript"},"content":[{"type":"text","text":"/**\n * 对比两个选择器的 specificity\n * @param {*} sp1\n * @param {*} sp2\n */\nfunction compare(sp1, sp2) {\n for (let i = 0; i <= 3; i++) {\n if (i === 3) return sp1[3] - sp2[3];\n if (sp1[i] - sp2[i]) return sp1[i] - sp2[i];\n }\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"文件:parser.js 的 "},{"type":"codeinline","content":[{"type":"text","text":"computeCSS"}]},{"type":"text","text":" 中修改匹配中元素后的属性赋值逻辑"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"javascript"},"content":[{"type":"text","text":"/**\n * 对元素进行 CSS 计算\n * @param {*} element\n */\nfunction computeCSS(element) {\n var elements = stack.slice().reverse();\n\n if (!elements.computedStyle) element.computedStyle = {};\n // 这里循环 CSS 规则,让规则与元素匹配\n // 1. 如果当前选择器匹配不中当前元素直接 continue\n // 2. 当前元素匹配中了,就一直往外寻找父级元素找到能匹配上选择器的元素\n // 3. 最后检验匹配中的元素是否等于选择器的总数,是就是全部匹配了,不是就是不匹配\n for (let rule of rules) {\n let selectorParts = rule.selectors[0].split(' ').reverse();\n\n if (!match(element, selectorParts[0])) continue;\n\n let matched = false;\n\n let j = 1;\n for (let i = 0; i < elements.length; i++) {\n if (match(elements[i], selectorParts[j])) j++;\n }\n\n if (j >= selectorParts.length) matched = true;\n\n if (matched) {\n let sp = specificity(rule.selectors[0]);\n let computedStyle = element.computedStyle;\n for (let declaration of rule.declarations) {\n if (!computedStyle[declaration.property]) computedStyle[declaration.property] = {};\n\n if (!computedStyle[declaration.property].specificity) {\n computedStyle[declaration.property].value = declaration.value;\n computedStyle[declaration.property].specificity = sp;\n } else if (compare(computedStyle[declaration.property].specificity, sp) < 0) {\n computedStyle[declaration.property].value = declaration.value;\n computedStyle[declaration.property].specificity = sp;\n }\n }\n }\n }\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/b3/b34c995f506fd74ab4d6e4adb20b4706.png","alt":null,"title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":1},"content":[{"type":"text","text":"最后"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"我们这里就完成了浏览器工作原理中的 HTML 解析和 CSS 计算。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"下一篇文章我们来一起完成排版和渲染两个浏览器过程。敬请期待!"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/b3/b34c995f506fd74ab4d6e4adb20b4706.png","alt":null,"title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/32/325465f9600893ac4bac99e6b756f096.png","alt":null,"title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}}]}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章