MdnDocsWidget.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. /**
  5. * This file contains functions to retrieve docs content from
  6. * MDN (developer.mozilla.org) for particular items, and to display
  7. * the content in a tooltip.
  8. *
  9. * At the moment it only supports fetching content for CSS properties,
  10. * but it might support other types of content in the future
  11. * (Web APIs, for example).
  12. *
  13. * It's split into two parts:
  14. *
  15. * - functions like getCssDocs that just fetch content from MDN,
  16. * without any constraints on what to do with the content. If you
  17. * want to embed the content in some custom way, use this.
  18. *
  19. * - the MdnDocsWidget class, that manages and updates a tooltip
  20. * document whose content is taken from MDN. If you want to embed
  21. * the content in a tooltip, use this in conjunction with Tooltip.js.
  22. */
  23. "use strict";
  24. const Services = require("Services");
  25. const defer = require("devtools/shared/defer");
  26. const {getCSSLexer} = require("devtools/shared/css/lexer");
  27. const EventEmitter = require("devtools/shared/event-emitter");
  28. const {gDevTools} = require("devtools/client/framework/devtools");
  29. const {LocalizationHelper} = require("devtools/shared/l10n");
  30. const L10N = new LocalizationHelper("devtools/client/locales/inspector.properties");
  31. const XHTML_NS = "http://www.w3.org/1999/xhtml";
  32. // Parameters for the XHR request
  33. // see https://developer.mozilla.org/en-US/docs/MDN/Kuma/API#Document_parameters
  34. const XHR_PARAMS = "?raw&macros";
  35. // URL for the XHR request
  36. var XHR_CSS_URL = "https://developer.mozilla.org/en-US/docs/Web/CSS/";
  37. // Parameters for the link to MDN in the tooltip, so
  38. // so we know which MDN visits come from this feature
  39. const PAGE_LINK_PARAMS =
  40. "?utm_source=mozilla&utm_medium=firefox-inspector&utm_campaign=default";
  41. // URL for the page link omits locale, so a locale-specific page will be loaded
  42. var PAGE_LINK_URL = "https://developer.mozilla.org/docs/Web/CSS/";
  43. exports.PAGE_LINK_URL = PAGE_LINK_URL;
  44. const PROPERTY_NAME_COLOR = "theme-fg-color5";
  45. const PROPERTY_VALUE_COLOR = "theme-fg-color1";
  46. const COMMENT_COLOR = "theme-comment";
  47. /**
  48. * Turns a string containing a series of CSS declarations into
  49. * a series of DOM nodes, with classes applied to provide syntax
  50. * highlighting.
  51. *
  52. * It uses the CSS tokenizer to generate a stream of CSS tokens.
  53. * https://dxr.mozilla.org/mozilla-central/source/dom/webidl/CSSLexer.webidl
  54. * lists all the token types.
  55. *
  56. * - "whitespace", "comment", and "symbol" tokens are appended as TEXT nodes,
  57. * and will inherit the default style for text.
  58. *
  59. * - "ident" tokens that we think are property names are considered to be
  60. * a property name, and are appended as SPAN nodes with a distinct color class.
  61. *
  62. * - "ident" nodes which we do not think are property names, and nodes
  63. * of all other types ("number", "url", "percentage", ...) are considered
  64. * to be part of a property value, and are appended as SPAN nodes with
  65. * a different color class.
  66. *
  67. * @param {Document} doc
  68. * Used to create nodes.
  69. *
  70. * @param {String} syntaxText
  71. * The CSS input. This is assumed to consist of a series of
  72. * CSS declarations, with trailing semicolons.
  73. *
  74. * @param {DOM node} syntaxSection
  75. * This is the parent for the output nodes. Generated nodes
  76. * are appended to this as children.
  77. */
  78. function appendSyntaxHighlightedCSS(cssText, parentElement) {
  79. let doc = parentElement.ownerDocument;
  80. let identClass = PROPERTY_NAME_COLOR;
  81. let lexer = getCSSLexer(cssText);
  82. /**
  83. * Create a SPAN node with the given text content and class.
  84. */
  85. function createStyledNode(textContent, className) {
  86. let newNode = doc.createElementNS(XHTML_NS, "span");
  87. newNode.classList.add(className);
  88. newNode.textContent = textContent;
  89. return newNode;
  90. }
  91. /**
  92. * If the symbol is ":", we will expect the next
  93. * "ident" token to be part of a property value.
  94. *
  95. * If the symbol is ";", we will expect the next
  96. * "ident" token to be a property name.
  97. */
  98. function updateIdentClass(tokenText) {
  99. if (tokenText === ":") {
  100. identClass = PROPERTY_VALUE_COLOR;
  101. } else if (tokenText === ";") {
  102. identClass = PROPERTY_NAME_COLOR;
  103. }
  104. }
  105. /**
  106. * Create the appropriate node for this token type.
  107. *
  108. * If this token is a symbol, also update our expectations
  109. * for what the next "ident" token represents.
  110. */
  111. function tokenToNode(token, tokenText) {
  112. switch (token.tokenType) {
  113. case "ident":
  114. return createStyledNode(tokenText, identClass);
  115. case "symbol":
  116. updateIdentClass(tokenText);
  117. return doc.createTextNode(tokenText);
  118. case "whitespace":
  119. return doc.createTextNode(tokenText);
  120. case "comment":
  121. return createStyledNode(tokenText, COMMENT_COLOR);
  122. default:
  123. return createStyledNode(tokenText, PROPERTY_VALUE_COLOR);
  124. }
  125. }
  126. let token = lexer.nextToken();
  127. while (token) {
  128. let tokenText = cssText.slice(token.startOffset, token.endOffset);
  129. let newNode = tokenToNode(token, tokenText);
  130. parentElement.appendChild(newNode);
  131. token = lexer.nextToken();
  132. }
  133. }
  134. exports.appendSyntaxHighlightedCSS = appendSyntaxHighlightedCSS;
  135. /**
  136. * Fetch an MDN page.
  137. *
  138. * @param {string} pageUrl
  139. * URL of the page to fetch.
  140. *
  141. * @return {promise}
  142. * The promise is resolved with the page as an XML document.
  143. *
  144. * The promise is rejected with an error message if
  145. * we could not load the page.
  146. */
  147. function getMdnPage(pageUrl) {
  148. let deferred = defer();
  149. let xhr = new XMLHttpRequest();
  150. xhr.addEventListener("load", onLoaded, false);
  151. xhr.addEventListener("error", onError, false);
  152. xhr.open("GET", pageUrl);
  153. xhr.responseType = "document";
  154. xhr.send();
  155. function onLoaded(e) {
  156. if (xhr.status != 200) {
  157. deferred.reject({page: pageUrl, status: xhr.status});
  158. } else {
  159. deferred.resolve(xhr.responseXML);
  160. }
  161. }
  162. function onError(e) {
  163. deferred.reject({page: pageUrl, status: xhr.status});
  164. }
  165. return deferred.promise;
  166. }
  167. /**
  168. * Gets some docs for the given CSS property.
  169. * Loads an MDN page for the property and gets some
  170. * information about the property.
  171. *
  172. * @param {string} cssProperty
  173. * The property for which we want docs.
  174. *
  175. * @return {promise}
  176. * The promise is resolved with an object containing:
  177. * - summary: a short summary of the property
  178. * - syntax: some example syntax
  179. *
  180. * The promise is rejected with an error message if
  181. * we could not load the page.
  182. */
  183. function getCssDocs(cssProperty) {
  184. let deferred = defer();
  185. let pageUrl = XHR_CSS_URL + cssProperty + XHR_PARAMS;
  186. getMdnPage(pageUrl).then(parseDocsFromResponse, handleRejection);
  187. function parseDocsFromResponse(responseDocument) {
  188. let theDocs = {};
  189. theDocs.summary = getSummary(responseDocument);
  190. theDocs.syntax = getSyntax(responseDocument);
  191. if (theDocs.summary || theDocs.syntax) {
  192. deferred.resolve(theDocs);
  193. } else {
  194. deferred.reject("Couldn't find the docs in the page.");
  195. }
  196. }
  197. function handleRejection(e) {
  198. deferred.reject(e.status);
  199. }
  200. return deferred.promise;
  201. }
  202. exports.getCssDocs = getCssDocs;
  203. /**
  204. * The MdnDocsWidget is used by tooltip code that needs to display docs
  205. * from MDN in a tooltip.
  206. *
  207. * In the constructor, the widget does some general setup that's not
  208. * dependent on the particular item we need docs for.
  209. *
  210. * After that, when the tooltip code needs to display docs for an item, it
  211. * asks the widget to retrieve the docs and update the document with them.
  212. *
  213. * @param {Element} tooltipContainer
  214. * A DOM element where the MdnDocs widget markup should be created.
  215. */
  216. function MdnDocsWidget(tooltipContainer) {
  217. EventEmitter.decorate(this);
  218. tooltipContainer.innerHTML =
  219. `<header>
  220. <h1 class="mdn-property-name theme-fg-color5"></h1>
  221. </header>
  222. <div class="mdn-property-info">
  223. <div class="mdn-summary"></div>
  224. <pre class="mdn-syntax devtools-monospace"></pre>
  225. </div>
  226. <footer>
  227. <a class="mdn-visit-page theme-link" href="#">Visit MDN (placeholder)</a>
  228. </footer>`;
  229. // fetch all the bits of the document that we will manipulate later
  230. this.elements = {
  231. heading: tooltipContainer.querySelector(".mdn-property-name"),
  232. summary: tooltipContainer.querySelector(".mdn-summary"),
  233. syntax: tooltipContainer.querySelector(".mdn-syntax"),
  234. info: tooltipContainer.querySelector(".mdn-property-info"),
  235. linkToMdn: tooltipContainer.querySelector(".mdn-visit-page")
  236. };
  237. // get the localized string for the link text
  238. this.elements.linkToMdn.textContent = L10N.getStr("docsTooltip.visitMDN");
  239. // listen for clicks and open in the browser window instead
  240. let mainWindow = Services.wm.getMostRecentWindow(gDevTools.chromeWindowType);
  241. this.elements.linkToMdn.addEventListener("click", (e) => {
  242. e.stopPropagation();
  243. e.preventDefault();
  244. mainWindow.openUILinkIn(e.target.href, "tab");
  245. this.emit("visitlink");
  246. });
  247. }
  248. exports.MdnDocsWidget = MdnDocsWidget;
  249. MdnDocsWidget.prototype = {
  250. /**
  251. * This is called just before the tooltip is displayed, and is
  252. * passed the CSS property for which we want to display help.
  253. *
  254. * Its job is to make sure the document contains the docs
  255. * content for that CSS property.
  256. *
  257. * First, it initializes the document, setting the things it can
  258. * set synchronously, resetting the things it needs to get
  259. * asynchronously, and making sure the throbber is throbbing.
  260. *
  261. * Then it tries to get the content asynchronously, updating
  262. * the document with the content or with an error message.
  263. *
  264. * It returns immediately, so the caller can display the tooltip
  265. * without waiting for the asynch operation to complete.
  266. *
  267. * @param {string} propertyName
  268. * The name of the CSS property for which we need to display help.
  269. */
  270. loadCssDocs: function (propertyName) {
  271. /**
  272. * Do all the setup we can do synchronously, and get the document in
  273. * a state where it can be displayed while we are waiting for the
  274. * MDN docs content to be retrieved.
  275. */
  276. function initializeDocument(propName) {
  277. // set property name heading
  278. elements.heading.textContent = propName;
  279. // set link target
  280. elements.linkToMdn.setAttribute("href",
  281. PAGE_LINK_URL + propName + PAGE_LINK_PARAMS);
  282. // clear docs summary and syntax
  283. elements.summary.textContent = "";
  284. while (elements.syntax.firstChild) {
  285. elements.syntax.firstChild.remove();
  286. }
  287. // reset the scroll position
  288. elements.info.scrollTop = 0;
  289. elements.info.scrollLeft = 0;
  290. // show the throbber
  291. elements.info.classList.add("devtools-throbber");
  292. }
  293. /**
  294. * This is called if we successfully got the docs content.
  295. * Finishes setting up the tooltip content, and disables the throbber.
  296. */
  297. function finalizeDocument({summary, syntax}) {
  298. // set docs summary and syntax
  299. elements.summary.textContent = summary;
  300. appendSyntaxHighlightedCSS(syntax, elements.syntax);
  301. // hide the throbber
  302. elements.info.classList.remove("devtools-throbber");
  303. deferred.resolve(this);
  304. }
  305. /**
  306. * This is called if we failed to get the docs content.
  307. * Sets the content to contain an error message, and disables the throbber.
  308. */
  309. function gotError(error) {
  310. // show error message
  311. elements.summary.textContent = L10N.getStr("docsTooltip.loadDocsError");
  312. // hide the throbber
  313. elements.info.classList.remove("devtools-throbber");
  314. // although gotError is called when there's an error, we have handled
  315. // the error, so call resolve not reject.
  316. deferred.resolve(this);
  317. }
  318. let deferred = defer();
  319. let elements = this.elements;
  320. initializeDocument(propertyName);
  321. getCssDocs(propertyName).then(finalizeDocument, gotError);
  322. return deferred.promise;
  323. },
  324. destroy: function () {
  325. this.elements = null;
  326. }
  327. };
  328. /**
  329. * Test whether a node is all whitespace.
  330. *
  331. * @return {boolean}
  332. * True if the node all whitespace, otherwise false.
  333. */
  334. function isAllWhitespace(node) {
  335. return !(/[^\t\n\r ]/.test(node.textContent));
  336. }
  337. /**
  338. * Test whether a node is a comment or whitespace node.
  339. *
  340. * @return {boolean}
  341. * True if the node is a comment node or is all whitespace, otherwise false.
  342. */
  343. function isIgnorable(node) {
  344. // Comment nodes (8), text nodes (3) or whitespace
  345. return (node.nodeType == 8) ||
  346. ((node.nodeType == 3) && isAllWhitespace(node));
  347. }
  348. /**
  349. * Get the next node, skipping comments and whitespace.
  350. *
  351. * @return {node}
  352. * The next sibling node that is not a comment or whitespace, or null if
  353. * there isn't one.
  354. */
  355. function nodeAfter(sib) {
  356. while ((sib = sib.nextSibling)) {
  357. if (!isIgnorable(sib)) {
  358. return sib;
  359. }
  360. }
  361. return null;
  362. }
  363. /**
  364. * Test whether the argument `node` is a node whose tag is `tagName`.
  365. *
  366. * @param {node} node
  367. * The code to test. May be null.
  368. *
  369. * @param {string} tagName
  370. * The tag name to test against.
  371. *
  372. * @return {boolean}
  373. * True if the node is not null and has the tag name `tagName`,
  374. * otherwise false.
  375. */
  376. function hasTagName(node, tagName) {
  377. return node && node.tagName &&
  378. node.tagName.toLowerCase() == tagName.toLowerCase();
  379. }
  380. /**
  381. * Given an MDN page, get the "summary" portion.
  382. *
  383. * This is the textContent of the first non-whitespace
  384. * element in the #Summary section of the document.
  385. *
  386. * It's expected to be a <P> element.
  387. *
  388. * @param {Document} mdnDocument
  389. * The document in which to look for the "summary" section.
  390. *
  391. * @return {string}
  392. * The summary section as a string, or null if it could not be found.
  393. */
  394. function getSummary(mdnDocument) {
  395. let summary = mdnDocument.getElementById("Summary");
  396. if (!hasTagName(summary, "H2")) {
  397. return null;
  398. }
  399. let firstParagraph = nodeAfter(summary);
  400. if (!hasTagName(firstParagraph, "P")) {
  401. return null;
  402. }
  403. return firstParagraph.textContent;
  404. }
  405. /**
  406. * Given an MDN page, get the "syntax" portion.
  407. *
  408. * First we get the #Syntax section of the document. The syntax
  409. * section we want is somewhere inside there.
  410. *
  411. * If the page is in the old structure, then the *first two*
  412. * non-whitespace elements in the #Syntax section will be <PRE>
  413. * nodes, and the second of these will be the syntax section.
  414. *
  415. * If the page is in the new structure, then the only the *first*
  416. * non-whitespace element in the #Syntax section will be a <PRE>
  417. * node, and it will be the syntax section.
  418. *
  419. * @param {Document} mdnDocument
  420. * The document in which to look for the "syntax" section.
  421. *
  422. * @return {string}
  423. * The syntax section as a string, or null if it could not be found.
  424. */
  425. function getSyntax(mdnDocument) {
  426. let syntax = mdnDocument.getElementById("Syntax");
  427. if (!hasTagName(syntax, "H2")) {
  428. return null;
  429. }
  430. let firstParagraph = nodeAfter(syntax);
  431. if (!hasTagName(firstParagraph, "PRE")) {
  432. return null;
  433. }
  434. let secondParagraph = nodeAfter(firstParagraph);
  435. if (hasTagName(secondParagraph, "PRE")) {
  436. return secondParagraph.textContent;
  437. }
  438. return firstParagraph.textContent;
  439. }
  440. /**
  441. * Use a different URL for CSS docs pages. Used only for testing.
  442. *
  443. * @param {string} baseUrl
  444. * The baseURL to use.
  445. */
  446. function setBaseCssDocsUrl(baseUrl) {
  447. PAGE_LINK_URL = baseUrl;
  448. XHR_CSS_URL = baseUrl;
  449. }
  450. exports.setBaseCssDocsUrl = setBaseCssDocsUrl;