philipwalton/html-inspector

Passing in HTML/CSS in which to inspect

chriscoyier opened this issue · 5 comments

What are the chances of an API such that you can give HTMLInspector some HTML in which to inspect and provide feedback on?

The idea being, for a tool like CodePen, you could get some info on the HTML/CSS you have written, but it isn't available in the DOM on the page you are directly on

img

Is that a major change?

I think you could probably do that with the existing tool, assuming you're in the browser. That's basically what I do in the tests. Here's an example from the duplicate-ids rule test:

it("warns when the same ID attribute is used more than once", function() {
  var html = parseHTML(''
        + '<div id="foobar">'
        + '  <p id="foobar">Foo</p>'
        + '  <p id="barfoo">bar <em id="barfoo">Em</em></p>'
        + '</div>'
      )

  HTMLInspector.inspect({
    useRules: ["duplicate-ids"],
    domRoot: html,
    onComplete: onComplete
  })

  expect(log.length).to.equal(2)
  expect(log[0].message).to.equal("The id 'foobar' appears more than once in the document.")
  expect(log[1].message).to.equal("The id 'barfoo' appears more than once in the document.")
  expect(log[0].context).to.deep.equal([html, html.querySelector("p#foobar")])
  expect(log[1].context).to.deep.equal([html.querySelector("p#barfoo"), html.querySelector("em#barfoo")])
})

The parseHTML function in the second line is really nothing magical. It's just just delegating to innerHTML behind the scenes as you can see here.

If you needed to do this serve side for whatever reason I suppose you could use phantomJS, but that might be more complicated. Also keep in mind that since the markup is being parsed by a browser it won't report errors that are forgiven by a browser, like improperly closed tags and whatnot.

If you actually wanted to validate the HTML it might be better to POST to validator.nu as described in this issue.

Perfect. Will give it a go.

I noticed output like "This element has this class which isn't used in any stylesheet" kind of thing (in regular usage). Can I also specify a set of CSS to be checked against?

In that case I think it might make more sense to run HTML Inspector within the context of the generated <iframe>, and then maybe post message back to the parent with the results. HTML Inspector's CSS module gets the list of CSS rules by looping through the document.styleSheet object. In Codepen's case, it looks like this just works if run in the context of the generated <iframe>.

Here's an example. If you look at the console you'll see the CSS rules are showing up.
http://codepen.io/anon/pen/GInCp

Works great:

img

And yep, we should definitely ultimately run it in the full-page context and report back up the errors. I have notes in this code to do just that, but I might release with this wicked simple implementation first and see what kind feedback there is.

Sweet!