use of com.steadystate.css.dom.CSSStyleDeclarationImpl in project java-to-graphviz by randomnoun.
the class StylesheetApplier method apply.
/**
* actually inline the styles
*/
public void apply() {
final Multimap<Element, StyleApplication> elementMatches = ArrayListMultimap.create();
final CSSOMParser inlineParser = new CSSOMParser();
inlineParser.setErrorHandler(new ExceptionErrorHandler());
// factor in elements' style attributes
NodeTraversor.traverse(new NodeVisitor() {
@Override
public void head(Node node, int depth) {
if (node instanceof Element && node.hasAttr("style")) {
// parse the CSS into a CSSStyleDeclaration
InputSource input = new InputSource(new StringReader(node.attr("style")));
CSSStyleDeclaration declaration = null;
try {
declaration = inlineParser.parseStyleDeclaration(input);
} catch (IOException e) {
// again, this should never happen, cuz we're just reading from a string
e.printStackTrace();
}
node.removeAttr("style");
elementMatches.put(((Element) node), new InlineStyleApplication(declaration));
}
}
@Override
public void tail(Node node, int depth) {
}
}, htmlDocument.body());
// compute which rules match which elements
CSSRuleList rules = styleSheet.getCssRules();
for (int i = 0; i < rules.getLength(); i++) {
if (rules.item(i) instanceof CSSStyleRule) {
CSSStyleRuleImpl rule = (CSSStyleRuleImpl) rules.item(i);
// for each selector in the rule... (separated by commas)
for (int j = 0; j < rule.getSelectors().getLength(); j++) {
Selector selector = rule.getSelectors().item(j);
Elements matches = null;
// selector.toString() converts a~=b to a~="b" which then includes the double quotes in the regex
// could remove this but the jsoup impl to ~= is wrong anyway ( should be performing a word search, not a regex )
matches = htmlDocument.select(selector.toString());
// for each matched element....
for (Element match : matches) {
elementMatches.put(match, new RuleStyleApplication(selector, rule.getStyle()));
}
}
}
}
Map<Element, CSSStyleDeclaration> inlinedStyles = new HashMap<Element, CSSStyleDeclaration>();
// calculate overrides
for (Element element : elementMatches.keySet()) {
CSSStyleDeclaration properties = new CSSStyleDeclarationImpl();
List<StyleApplication> matchedRules = new ArrayList<StyleApplication>(elementMatches.get(element));
Collections.sort(matchedRules, orderBySpecificity);
for (StyleApplication matchedRule : matchedRules) {
CSSStyleDeclaration cssBlock = matchedRule.getCssBlock();
for (int i = 0; i < cssBlock.getLength(); i++) {
String propertyKey = cssBlock.item(i);
CSSValue propertyValue = cssBlock.getPropertyCSSValue(propertyKey);
// TODO: !important
properties.setProperty(propertyKey, propertyValue.getCssText(), "");
}
}
inlinedStyles.put(element, properties);
}
// apply to DOM
for (Map.Entry<Element, CSSStyleDeclaration> entry : inlinedStyles.entrySet()) {
entry.getKey().attr("style", entry.getValue().getCssText());
}
}
Aggregations