diggerio / digger-selector

The CSS selector parser used for digger
0 stars 0 forks source link

Calculate specifity #1

Open jpbochi opened 10 years ago

jpbochi commented 10 years ago

For the project I'm developing, it would be awesome if the result had the specificity of each phase.

I'm not sure how to include it there because a phase is an array of selector parts, and the specificity belongs to all of them together. I wonder if there's a good format for all that.

One interesting project that calculates selector specificity is https://github.com/keeganstreet/specificity

If adding this here is out of question, I'll try creating a separate project that joins both yours and @keeganstreet's.

Heres some helpful links about specificity: Documentation: https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity Tutorial: http://css-tricks.com/specifics-on-css-specificity/ Online calculator: http://specificity.keegan.st/

binocarlos commented 10 years ago

Hey,

I hadn't properly read about specifity so thanks for your note!

I want to keep this module as lean as possible because it is one of a bunch that are used in the browser.

I've updated the readme - the 'string' property was being included in each selector - this can be used in a map to combine to 2 modules nicely.

I've just hacked this in and not tested but something like this:

var parsed = Selector('product[price<=100] > caption.big, friend');

// map each phase (which is an array of selector parts)
parsed.phases = parsed.phases.map(function(phase){

  // get the string for the phase so we can get specifity
  var phasestring = phase.map(function(phase){
    return phase.string;
  }).join('');

  // get the specifity for this string
  var specifity = specificity.calculate(phasestring);

  return {
   selectors:phase,
   specifity:specifity
  }
})

parsed is now (roughly):

{
    "string": "product[price<=100] > caption.big, friend",
    "phases": [
        {
            specificty:..., // product[price<=100] > caption.big
            selectors:[...]
        },
        {
            specificty:..., // friend 
            selectors:[...]
        }
    ]
}

Let me know if that is gonna get it done for you : )

jpbochi commented 10 years ago

@binocarlos thanks for the quick reply. That code should do it. I'm a little sad I have to rebuild the phasestring, however.

binocarlos commented 10 years ago

@jpbochi indeed it is not a nice hack - it would be useful to have the string generated as part of the parsing process - I'm stuck for time but next chance I get I will patch that in

jpbochi commented 10 years ago

I might send a PR sooner or later. :)