phax / ph-css Goto Github PK
View Code? Open in Web Editor NEWAdvanced Java CSS 3 parser and builder
License: Apache License 2.0
Advanced Java CSS 3 parser and builder
License: Apache License 2.0
E.g. on the pexels.com website:
<a class="tiny-profile" data-track-action="home" data-track-label="leaderboard-item" href="/u/ibrahim-asad-45786/"> <img alt="Ibrahim Asad" class="tiny-profile__img" width="30" height="30" src="https://www.gravatar.com/avatar/5fbff6603f724a3b6bfc68b0172ed30b?s=60&d=retro"> <span class="tiny-profile__name">Ibrahim Asad</span> <span class="tiny-profile__downloads">
<svg viewbox="0 0 100 100" class="tiny-profile__downloads-icon">
<use xlink:href="#iconDownloads"></use>
</svg> 4.01K </span> </a>
Chrome shows: Unsafe attempt to load URL http://pexels.com/ from frame with URL http://dev.htmlhub.io:8888/?bookmark-admin=pexels. Domains, protocols and ports must match.
While the above example looks like the href might not actually be a server url, Chrome thinks it is, and anyhow, it didn't get picked up by AbstractModifyingCSSUrlVisitor.
BTW = fantastic library for replacing css embedded urls with data urls. Many thanks. Much appreciated.
Ian
Hello,
Nice library idea, it's missing.
Under what license is it delivered ?
Ideally , an Apache 2.0 license would be great, but I don't see any LICENSE file.
Thanks
Apologies for the poor bug report, but I'm hoping that this might ring a bell regardless.
I've been trying to include your library (4.0.0) in an Android project, but upon compiling I get this error:
Error:Gradle: Execution failed for task ':app:packageDebug'.
> Duplicate files copied in APK META-INF/buildinfo.xml
File 1: /home/pascal/.gradle/caches/modules-2/files-2.1/com.helger/ph-commons/6.1.0/7f96428cbbf7e4c88e9663d09070f24792321254/ph-commons-6.1.0.jar
File 2: /home/pascal/.gradle/caches/modules-2/files-2.1/com.helger/ph-css/4.0.0/3a0ce4d7bcd6eb6a162c3d8336fb70d2c0e4a4fa/ph-css-4.0.0.jar
Unfortunately I have no idea what the buildinfo.xml
is for and why this would be a problem. Have you seen this before? Is this expected? Is the Android build system just broken?
Thank you!
Hello Philip, there is a one more issue from our QA.
This is example of a bit broken CSS with empty block.
https://jsfiddle.net/b49056u9/3/
As you can see "pen" is blue, because empty block was skipped.
But this code will throw NPE
String css = ".pen {background-color: red;width:100px; height:100px} {* some incorrect block *} .pen {background-color: blue}";
CSSReaderSettings aSettings = new CSSReaderSettings()
.setCSSVersion(ECSSVersion.LATEST)
.setBrowserCompliantMode(true);
CascadingStyleSheet cascadingStyleSheet = CSSReader.readFromStringStream(css, aSettings);
CSSWriter writer = new CSSWriter(new CSSWriterSettings(ECSSVersion.LATEST, true));
System.out.println(writer.getCSSAsString(cascadingStyleSheet));
Hi
I am a newbie in you library, I have Style.css as :
.qsign
{
color:red;
}
I read a css using this :
var cssString = Utils.readStringFromAssets(context, "Style.css")
css=CSSReader.readFromString(cssString,ECSSVersion.CSS30)
Now how can I get color of qsign class?
fontface missing getDeclaration(), all the other rules have it.
This code
.a { background: url(''); }
causes the exception
18:48:26,118 [ERROR] ProxiedResourceHandler - Resource content could not be transformed. java.lang.IllegalArgumentException: The value of the string 'URI' may not be empty!
at com.phloc.commons.ValueEnforcer.notEmpty(ValueEnforcer.java:66)
at com.phloc.css.decl.CSSURI.setURI(CSSURI.java:76)
at com.phloc.css.decl.CSSURI.<init>(CSSURI.java:51)
at com.phloc.css.handler.CSSNodeToDomainObject._createExpressionURL(CSSNodeToDomainObject.java:389)
at com.phloc.css.handler.CSSNodeToDomainObject._createExpressionTerm(CSSNodeToDomainObject.java:477)
at com.phloc.css.handler.CSSNodeToDomainObject._createExpression(CSSNodeToDomainObject.java:505)
at com.phloc.css.handler.CSSNodeToDomainObject._createDeclaration(CSSNodeToDomainObject.java:548)
at com.phloc.css.handler.CSSNodeToDomainObject._createStyleRule(CSSNodeToDomainObject.java:597)
at com.phloc.css.handler.CSSNodeToDomainObject.createCascadingStyleSheetFromNode(CSSNodeToDomainObject.java:1115)
at com.phloc.css.handler.CSSHandler.readCascadingStyleSheetFromNode(CSSHandler.java:64)
at com.phloc.css.reader.CSSReader.readFromStream(CSSReader.java:1446)
at com.phloc.css.reader.CSSReader.readFromString(CSSReader.java:681)
Looks like convertion to AST works fine, but when converting from AST to object empty URLs are not expected.
However, they aren't invalid from CSS point of view, so probably should be parsed just fine. Or (as they are useless anyway) they can be thrown away when converting to AST.
Hello Philip,
Thank you for offering such a great project.
I copy paste the source file to my java project and some errors were found in
> com.helger.css.decl.visit.CSSVisitor
> com.helger.css.CSSFilenameHelper
> com.helger.css.CCSS
because there is no com.helger.commons.* package in this project.
Good afternoon,
Apologies for the poor grammar and supposed bug. I'm newer developer in android studio.
I trying to use your library with gradle/maven and when i run the app this message shows:
Error:PARSE ERROR:
Error:unsupported class file version 52.0
Error:...while parsing com/helger/commons/CGlobal.class
Error:1 error; aborting
:app:transformClassesWithDexForDebug FAILED
Error:Execution failed for task ':app:transformClassesWithDexForDebug'.
> com.android.build.api.transform.TransformException: java.lang.RuntimeException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.8.0_65\bin\java.exe'' finished with non-zero exit value 1
I tried to use this post in stackoverflow
http://stackoverflow.com/questions/37902840/got-unsupported-class-file-version-52-0-after-including-a-module-to-a-project
Nothing happens...
And when i saw your changelog about jdk 8, i tried to use this instead:
https://developer.android.com/preview/j8-jack.html?hl=en
I removed the duplicate files and this message shows:
Error:Library reading phase: Type javax.annotation.Untainted from file 'C:\Users\user\AndroidStudioProjects\CSSTest\app\build\intermediates\jill\debug\packaged\jsr305-3.0.1-dd0e9f5d0efb3025f6fde4238fd4a5c268f62a63.jar' has already been imported from file 'C:\Users\user\AndroidStudioProjects\CSSTest\app\build\intermediates\jill\debug\packaged\annotations-3.0.1u2-2b84c751906484cab0381cba276af74c2923d73b.jar', type 'javax.annotation.Untainted' (see property 'jack.import.type.policy' for type collision policy)
com.android.jack.api.v01.CompilationException: Library reading phase: Type javax.annotation.Untainted from file 'C:\Users\user\AndroidStudioProjects\CSSTest\app\build\intermediates\jill\debug\packaged\jsr305-3.0.1-dd0e9f5d0efb3025f6fde4238fd4a5c268f62a63.jar' has already been imported from file 'C:\Users\user\AndroidStudioProjects\CSSTest\app\build\intermediates\jill\debug\packaged\annotations-3.0.1u2-2b84c751906484cab0381cba276af74c2923d73b.jar', type 'javax.annotation.Untainted' (see property 'jack.import.type.policy' for type collision policy)
Hi,
I am looking for libraries that might help me convert CSS custom properties to plain CSS. Can you tell me if the Reader will handle CSS custom properties currently? And if so, it should be simple to then output the objects in plain CSS, yes?
More info on CSS custom properties here:
https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_variables
Thanks,
M
Hi,
I'm getting this error:
12:12:47.355 [main] ERROR c.h.c.h.LoggingCSSParseExceptionCallback - Failed to parse CSS: [1:9] Encountered text 'or' corresponding to token "or". Was expecting one of: <S>, "+", "-", ")", <STRING1>, <STRING2>, <NUMBER>, <HASH>, "inherit", "from", "to", <IDENT>, <EM>, <EX>, <PX>, <REM>, <VW>, <VH>, <VMIN>, <CH>, <DPI>, <DPCM>, <DPPX>, <LENGTH_CM>, <LENGTH_MM>, <LENGTH_IN>, <LENGTH_PT>, <LENGTH_PC>, <ANGLE_DEG>, <ANGLE_RAD>, <ANGLE_GRAD>, <ANGLE_TURN>, <TIME_MS>, <TIME_S>, <FREQ_HZ>, <FREQ_KHZ>, <PERCENTAGE>, <URL>, <FUNCTION_CALC>, "expression(", <FUNCTION>, <URANGE>
with the following minimal test case.
CascadingStyleSheet cascadingStyleSheet = CSSReader.readFromString("h1:lang(or) {}", ECSSVersion.LATEST);
this is derived from some css from the web which contained:
h2:lang(anp), h3:lang(anp), h4:lang(anp), h5:lang(anp), h6:lang(anp), h2:lang(as), h3:lang(as), h4:lang(as), h5:lang(as), h6:lang(as), h2:lang(bho), h3:lang(bho), h4:lang(bho), h5:lang(bho), h6:lang(bho), h2:lang(bh), h3:lang(bh), h4:lang(bh), h5:lang(bh), h6:lang(bh), h2:lang(bn), h3:lang(bn), h4:lang(bn), h5:lang(bn), h6:lang(bn), h2:lang(gu), h3:lang(gu), h4:lang(gu), h5:lang(gu), h6:lang(gu), h2:lang(hi), h3:lang(hi), h4:lang(hi), h5:lang(hi), h6:lang(hi), h2:lang(kn), h3:lang(kn), h4:lang(kn), h5:lang(kn), h6:lang(kn), h2:lang(ks), h3:lang(ks), h4:lang(ks), h5:lang(ks), h6:lang(ks), h2:lang(ml), h3:lang(ml), h4:lang(ml), h5:lang(ml), h6:lang(ml), h2:lang(mr), h3:lang(mr), h4:lang(mr), h5:lang(mr), h6:lang(mr), h2:lang(my), h3:lang(my), h4:lang(my), h5:lang(my), h6:lang(my), h2:lang(mai), h3:lang(mai), h4:lang(mai), h5:lang(mai), h6:lang(mai), h2:lang(ne), h3:lang(ne), h4:lang(ne), h5:lang(ne), h6:lang(ne), h2:lang(new), h3:lang(new), h4:lang(new), h5:lang(new), h6:lang(new), h2:lang(or), h3:lang(or), h4:lang(or), h5:lang(or), h6:lang(or), h2:lang(pa), h3:lang(pa), h4:lang(pa), h5:lang(pa), h6:lang(pa), h2:lang(pi), h3:lang(pi), h4:lang(pi), h5:lang(pi), h6:lang(pi), h2:lang(sa), h3:lang(sa), h4:lang(sa), h5:lang(sa), h6:lang(sa), h2:lang(ta), h3:lang(ta), h4:lang(ta), h5:lang(ta), h6:lang(ta), h2:lang(te), h3:lang(te), h4:lang(te), h5:lang(te), h6:lang(te) { line-height: 1.2em; }
I think it has to do with the terminal tokens defined in the grammar, one of which is 'or'. This probably collides with the expr rule somehow that is used for pseudo functions. Probably needs same hack as here: https://github.com/phax/ph-css/blob/master/ph-css/src/main/jjtree/ParserCSS30.jjt#L767
When the css has @-webkit-keyframes, @moz-keyframes etc you get a null stylesheet from:
CollectingCSSParseErrorHandler aErrors = new CollectingCSSParseErrorHandler(new LoggingCSSParseErrorHandler());
final CascadingStyleSheet stylesheet = CSSReader.readFromString(cssFileContent, ECSSVersion.CSS30, aErrors);
Luckily, I can use the sourceforge CSSOMParser to extract the keyframes rules before running the remaing css through your parser.
In the README, the link in "Please look at my personal Coding Styleguide for the naming conventions used in this project." doesn't work.
The project looks good, but it's somehow not easy to get it work quickly.
Simple Getting Started with some code examples would help a lot.
Thanks :)
Philip, my build using ps-css version 5.0.1 cannot be uploaded to appengine.
For now I am building with 4.1.5.
I don't know if or when Google plan to make java 8 available on appengine, but I'm telling you, because you made a great library, and I imagine there will be many other GAE devs anting to use it.
Thanks
Ian
the follow expression fails for me: calc((100% - (3 * 30px)) / 4)
Currently, a string property "m_sProperty" is used, can we switch to ECSSProperty? That will make the client code much easier and tidier.
E,g.
new DefaultCSSVisitor() {
@Override public void onDeclaration(@Nonnull CSSDeclaration declaration) {
// currently:
if (declaration.getProperty().equals("font") { ... }
// prefer enum:
if (declaration.getPropName() == ECSSProperty.FONT) { ...}
}
};
In CssReader#readFromStream(IHasInputStream, CSSReaderSettings)
, you call CssReader#getCharsetDeclaredInCSS(IHasInputStream)
which closes the InputStream
as a side-effect.
Once the input stream is closed, parsing it is less likely to work.
Hey Philip, hope you're doing well.
We have another non-recoverable CSS exception found in the wild, so this is similar to #19.
The CSS that is causing the failure is
//...
}
;
:root .cw18winwrap {
//...
fyi, the CSS is found on http://www.oracle.com/technetwork/java/javase/downloads/index.html web page. And it has a bunch of other errors (as validated by csslint.net) which don't cause failures, so current state of the parser is already much closer to what browsers have in terms of error-handling.
Hello,
Currently, my understanding of parsing is that you have to set a CSS version.
Is there a Relax parser that is able to understand different versions ?
In fact I am only interested in parsing URLs, I used com.helger.css.decl.visit.DefaultCSSUrlVisitor and the sample code referenced in your documentation.
Thanks
Hello Philip.
We found one minor issue in CSS parsing.
Parser doesn't support IE hacks like these
http://keithclark.co.uk/articles/moving-ie-specific-css-into-media-blocks/media-tests/
Could you add support for this one in 4.* thread?
Here is snippet to reproduce the issue.
String css = "@media \\0screen\\,screen\\9 {.test {margin-left: 0px}}"; CSSReaderSettings aSettings = new CSSReaderSettings() .setCSSVersion(ECSSVersion.LATEST) .setBrowserCompliantMode(true); CascadingStyleSheet cascadingStyleSheet = CSSReader.readFromStringStream(css, aSettings); CSSWriter writer = new CSSWriter(new CSSWriterSettings(ECSSVersion.LATEST, true)); System.out.println(writer.getCSSAsString(cascadingStyleSheet));
Long time, Philip. Another issue from the wild:
This:
body {
background: green;
}
@media print {
body {
@page {
margin: 0.5cm;
}
}
body {
background: red !important;
}
}
becomes this after the transformation (formatted):
body {
background: green;
}
@media print {
body {
}
}
body {
background: red !important;
}
As you can see, rule that is targeted only for print leaks to "global" area.
Here's the fiddle where you can see that browsers don't do that: https://jsfiddle.net/zyuxschg/
Error in @media rule. (Invalid token "and". Was expecting one of: , , .)
Happens when something like this present:
@media screen and (min-width: 768px) {.section {.
padding: 40px
}
}
Hi Philip,
We are using ph-css in our Android-App.
Today I started implementing parsing of colors and discovered, that there are dependencies to AWT in bot ECSSColor and CSSColorHelper. However, there is no AWT support on Android that I know of.
So sadly, I can't make use of those classes/ enums to determine what kind of Color it is, the CSS contains or get RGB values of named CSS colors.
The root of all evil lies in
final float [] aHSL = CSSColorHelper.getRGBAsHSLValue (nRed, nGreen, nBlue);
of ECSSColor's constructor. Is there a possibility or plan for you to ditch AWT dependencies, or move them somewhere else, so we don't have to have AWT in order to use ECSSColor?
We have a bug report for Apache JMeter, where a user wants to parse a css file that contains min--moz-device-pixel-ratio
. That variant seems to be missing in the enum ECSSMediaExpressionFeature
and as a result his log files are getting flooded with error messages.
It would be nice, if you could add this ancient mozilla feature.
Thanks,
Felix
Hello. I'm digging into this library for the first time and am trying to parse a stylesheet, in order to pull all font-family
/ font-face
declarations out of it. I've found that to be rather difficult - when working with a stylesheet instance, I have to call getAllStyleRules
, getAllMediaRules
, etc. etc., and iterate my way through many layers.
Is there any way to do this easier, without requiring so many manual calls? I would use getAllRules
but that returns a very generic rule instance (ICSSTopLevelRule
), and I'm trying to avoid having a large if statement chain within my code to check for relevant class instances, just to retrieve child declarations.
Imagine we have this piece of CSS:
.class{color:red;.class{color:green}.class{color:blue}
After parsing it will become smt. like:
.class{color:red}.class{color:blue}
i.e. first closing bracket will be treated as matched and invalid rule content (.class{color:green
) will be thrown away.
And browsers will throw away everything until the matching closing bracket: in our example it is everything after red;
. I.e. browser would treat the example like this:
.class{color:red;}
Is it possible to tweak parser to behave more like browsers do in such cases? Maybe some configuration options?
Thanks!
Hi!
I have the impression that the source location information is wrong in string that contain tabs. For instance try the following code:
import com.helger.css.ECSSVersion;
import com.helger.css.decl.CascadingStyleSheet;
import com.helger.css.reader.CSSReader;
public class TestCSS {
public static void main(String[] args) {
CascadingStyleSheet css1 = CSSReader.readFromString("body { }", ECSSVersion.LATEST);
System.out.println(css1.getAllStyleRules().getFirst().getSourceLocation());
CascadingStyleSheet css2 = CSSReader.readFromString("\tbody { }", ECSSVersion.LATEST);
System.out.println(css2.getAllStyleRules().getFirst().getSourceLocation());
}
}
I have the following output:
[firstTokenArea=[beginLine=1; beginColumn=1; endLine=1; endColumn=4]; lastTokenArea=[beginLine=1; beginColumn=8; endLine=1; endColumn=8]]
[firstTokenArea=[beginLine=1; beginColumn=9; endLine=1; endColumn=12]; lastTokenArea=[beginLine=1; beginColumn=16; endLine=1; endColumn=16]]
I had the impression that it should be beginColumn=2 etc... for the second no?
cloned with
git clone https://github.com/phax/ph-css
did mvn test
on Debian Jessie, openjdk version "1.8.0_102", Apache Maven 3.3.9
ph-css.txt
Then I did a mvn test in ph-css/ph-csscompress-maven-plugin and got errors as well:
ph-csscompress-maven-plugin.txt
My goal is to have a working example for javacc build using maven.
We are having this code that loads the CSS from a string:
CSSReaderSettings settings = new CSSReaderSettings();
settings.setCSSVersion(ECSSVersion.CSS30);
settings.setBrowserCompliantMode(false);
return CSSReader.readFromStringReader(initialStyles, settings);
If there is an error, for instance, if there is something malformed in the CSS (throws an Unrecoverable Error ), or incorrect in a line it returns null. There is any way to have it return everything but deleting the failing line?
For example:
@media (min--moz-device-pixel-ratio: 1.3),(-o-min-device-pixel-ratio: 2.6/2),(-webkit-min-device-pixel-ratio: 1.3),(min-device-pixel-ratio: 1.3),(min-resolution: 1.3dppx) {
.social .facebook a, .social .twitter a {
background-size: -webkit-background-size: 652px 295px;
background-size: 652px 295px;
}
}
Desired output, basicilly to ignore the failing line:
@media (min--moz-device-pixel-ratio: 1.3),(-o-min-device-pixel-ratio: 2.6/2),(-webkit-min-device-pixel-ratio: 1.3),(min-device-pixel-ratio: 1.3),(min-resolution: 1.3dppx) {
.social .facebook a, .social .twitter a {
background-size: 652px 295px;
}
}
As stated in RFC 3986:
Although schemes are case-
insensitive, the canonical form is lowercase and documents that
specify schemes must do so with lowercase letters. An implementation
should accept uppercase letters as equivalent to lowercase in scheme
names (e.g., allow "HTTP" as well as "http") for the sake of
robustness but should only produce lowercase scheme names for
consistency.
But ph-css
version 5.0.4 does not treat non-lowercase URIs as data URIs, eg.:
new CSSURI("DaTa:,someData").isDataURL()
returns false
even though it should return true
.
I believe that’s a minor bug.
Such URIs are not very common (and probably even less so in CSS files), yet when you try to handle all wild varieties of things that happen on the web in a fashion similar to web browser, this behaviour becomes an issue and a user of the library needs to manually check URI scheme.
Hi Philip. So, another issue from the fields. Here's the excerpt from one CSS file, and the error-handling is slightly different as outlined in comments:
/* correct part */
table.fast th, table.fast td {
padding: 10px 10px;
text-align: left;
}
/* error that should be skipped*/
table.fast th background:#eee;
/* first correct part that skipped by both browsers and parser algorithm */
.ir {
display: block;
}
/* correct part that is skipped by parser but is read by browsers */
div.flexible-detail-left {
margin-bottom: 30px;
}
/* end of skipped part */
.some { more: css; }
Test :
String css = "@font-face { font-family: 'NeutraText-Bold'; src: url(https://www.someFonts.com/NeutraText-Bold.otf); }";
for (ICSSTopLevelRule icssTopLevelRule : CSSReader.readFromStringStream(css, ECSSVersion.LATEST).getAllRules()) {
icssTopLevelRule.getAsCSSString();
}
From my understanding this due to order of static field initialization in CSSWriterSettings
in which DEFAULT_SETTINGS
is created before the default has been set.
Workaround is to create CSSWriterSettings
and setNewLineMode
and pass it to getAsCSSString
.
CascadingStyleSheet css = CSSReader.readFromString(css, Charset.forName("UTF-8"), ECSSVersion.CSS30);
This simply returns null.
The CSS that is being feed into CSSReader is actually output from jsass and can be found here:
http://pastebin.com/2ZiwyeaF
(don't judge, we are in the middle of a refactor)
Any insight would be greatly appreciated!
Cheers!
com.helger.css.parser.TokenMgrError extends Error. It would be better to extend Exception, or perhaps (if you do not want to avoid declaring it in the throws clause) RuntimeException. The reason being that most developers will wrap a block of code with catch(Exception) to handle any issues within it, and an Error will not be caught (because Errors are generally unrecoverable anyway). In our code, this resulted in the termination of the loop which was supposed to keep re-reading the CSS file when it changed (because an incorrect character in the CSS file caused a parse error).
A syntax error when parsing a CSS file is simply not in the same league as an "Error" (example Errors are OutOfMemoryError or a required Class file being missing).
Thank you.
References:
(1) http://www.javamex.com/tutorials/exceptions/exceptions_hierarchy.shtml
(2) http://docs.oracle.com/javase/7/docs/api/java/lang/Error.html
Original issue: https://code.google.com/p/phloc-css/issues/detail?id=20&can=1
Re-checked today. Looks like -moz-min-device-pixel-ratio
was fixed, but there are still warnings for min-device-pixel-ratio
:
[ WARN] CSSNodeToDomainObject - Media expression uses unknown feature 'min-device-pixel-ratio'
Hi again Philip, not a long time has passed =)
Here's another one from us.
Parser skips a bit more than browsers do.
public void proof()
{
String css = "/* correct part */\n" +
"table.fast th, table.fast td {\n" +
" padding: 10px 10px;\n" +
" text-align: left;\n" +
"}\n" +
"/* error that should be skipped*/\n" +
"table.fast th background:#eee;\n" +
"/* correct part that will be skipped too*/\n" +
"div.flexible-detail-left {\n" +
" margin-bottom: 30px;\n" +
"}\n" +
"/* end of skipped part*/\n" +
"@media (min-width: 700px) {\n" +
" div.flexible-detail-left {\n" +
" float: left;\n" +
" width: 50%;\n" +
" clear: left;\n" +
" margin-bottom: 0;\n" +
" }\n" +
"\n" +
" div.flexible-detail-right {\n" +
" float: right;\n" +
" width: 48%;\n" +
" clear: right;\n" +
" }\n" +
"}\n" +
"/* correct part in the end of css*/\n" +
"@media (min-width: 960px) {\n" +
" div.flexible-detail-left {\n" +
" width: 60%;\n" +
" }\n" +
"\n" +
" div.flexible-detail-right {\n" +
" width: 37%;\n" +
" }\n" +
"}\n";
CSSReaderSettings aSettings = new CSSReaderSettings()
.setCSSVersion(ECSSVersion.LATEST)
.setBrowserCompliantMode(true);
CascadingStyleSheet cascadingStyleSheet = CSSReader.readFromStringStream(css, aSettings);
CSSWriter writer = new CSSWriter(new CSSWriterSettings(ECSSVersion.LATEST, true));
System.out.println(writer.getCSSAsString(cascadingStyleSheet));
}
Original issue: https://code.google.com/p/phloc-css/issues/detail?id=19
When the parser finds an invalid rule, it skips this rule and all the following rules in a block. Browsers, however, skip only the invalid rule, leaving all the following rules in a block intact (this is the behavior that a few years ago was actively used by developers who created IE-specific hacks by prepending a *
or a _
to a selector (http://webdesignerwall.com/tutorials/css-specific-for-internet-explorer)).
So if imagine a block like this
.box {
background: gray; /* standard */
*background: green; /* IE 7 and below */
border-color: red;
}
then in the modern browsers it will be treated as this:
.box {
background: gray;
border-color: red;
}
while ph parser will treat it like this:
.box {
background: gray;
}
Hi, your tool is great, but I can't parse (and I'd need to) data URIs, like for example:
background-image:url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/Pgo8c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgdmlld0JveD0iMCAwIDEgMSIgcHJlc2VydmVBc3BlY3RSYXRpbz0ibm9uZSI+CiAgPGxpbmVhckdyYWRpZW50IGlkPSJncmFkLXVjZ2ctZ2VuZXJhdGVkIiBncmFkaWVudFVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgeDE9IjAlIiB5MT0iMCUiIHgyPSIwJSIgeTI9IjEwMCUiPgogICAgPHN0b3Agb2Zmc2V0PSIwJSIgc3RvcC1jb2xvcj0iIzJkYWZkOCIgc3RvcC1vcGFjaXR5PSIwIi8+CiAgICA8c3RvcCBvZmZzZXQ9IjEwMCUiIHN0b3AtY29sb3I9IiMwYTU5ODUiIHN0b3Atb3BhY2l0eT0iMSIvPgogIDwvbGluZWFyR3JhZGllbnQ+CiAgPHJlY3QgeD0iMCIgeT0iMCIgd2lkdGg9IjEiIGhlaWdodD0iMSIgZmlsbD0idXJsKCNncmFkLXVjZ2ctZ2VuZXJhdGVkKSIgLz4KPC9zdmc+);
I'd appreciate if this was supported, given that it is becoming a common feature of css style sheets.
thanks!
Hi again Philip, it's been a while!
I am having the following situation and I wonder if you could give any advice here. It's possible that it's not your parser's responsibility but perhaps you could point to a way to work around this with your APIs.
So, one of the goals of our application when it comes to CSS parsing is to transform all the url()-s in it. We do so by using the CSSVisitor.visitCSSUrl()
method.
However, when we have CSS like this:
body {
background: url(../bg.png);
}
.#f { color: red; }
the parser fails unrecoverably on the .#f
selector and so we're unable to transform the URLs. We're using v4.0.0 with CSS3 parser and .setBrowserCompliantMode(true)
- which, as I imagined, shouldn't have treated such error as unrecoverable - as browser doesn't.
Sorry if my questions are noob - I am by no means a Java programmer. Thanks
How can I loop through all the style rules including those from @media
?
See http://cssnext.io/features/#reduced-calc
font-size: calc(var(--fontSize) * 2)
cannot be parsed
As stated in https://developer.mozilla.org/en-US/docs/Web/CSS/calc, calc() rules may be nested as in height: calc(calc(2.25rem + 2px) - 1px * 2);
(taken form the bootstrap 4 CSS rules).
Unfortunately, this seems to break the stylesheet parser causing the following error:
com.helger.css.parser.ParseException: Encountered unexpected token: "calc(" <FUNCTION_CALC>
at line 3831, column 16.
Was expecting one of:
"("
"+"
"-"
"expression("
<ANGLE_DEG>
<ANGLE_GRAD>
<ANGLE_RAD>
<ANGLE_TURN>
<CH>
<DPCM>
<DPI>
<DPPX>
<EM>
<EX>
<FR>
<FREQ_HZ>
<FREQ_KHZ>
<FUNCTION>
<LENGTH_CM>
<LENGTH_IN>
<LENGTH_MM>
<LENGTH_PC>
<LENGTH_PT>
<LENGTH_Q>
<NUMBER>
<PERCENTAGE>
<PX>
<REM>
<S>
<TIME_MS>
<TIME_S>
<VH>
<VMAX>
<VMIN>
<VW>
at com.helger.css.parser.ParserCSS30.generateParseException(ParserCSS30.java:6696)
at com.helger.css.parser.ParserCSS30.jj_consume_token(ParserCSS30.java:6554)
at com.helger.css.parser.ParserCSS30.mathUnit(ParserCSS30.java:1017)
at com.helger.css.parser.ParserCSS30.mathProduct(ParserCSS30.java:1091)
at com.helger.css.parser.ParserCSS30.mathSum(ParserCSS30.java:1184)
at com.helger.css.parser.ParserCSS30.math(ParserCSS30.java:1217)
at com.helger.css.parser.ParserCSS30.exprTerm(ParserCSS30.java:1479)
at com.helger.css.parser.ParserCSS30.expr(ParserCSS30.java:1622)
at com.helger.css.parser.ParserCSS30.styleDeclaration(ParserCSS30.java:3090)
at com.helger.css.parser.ParserCSS30.styleDeclarationOrRule(ParserCSS30.java:3131)
at com.helger.css.parser.ParserCSS30.styleDeclarationList(ParserCSS30.java:3376)
at com.helger.css.parser.ParserCSS30.styleDeclarationBlock(ParserCSS30.java:3414)
at com.helger.css.parser.ParserCSS30.styleRule(ParserCSS30.java:3481)
at com.helger.css.parser.ParserCSS30.styleSheet(ParserCSS30.java:379)
at com.helger.css.reader.CSSReader._readStyleSheet(CSSReader.java:216)
at com.helger.css.reader.CSSReader.readFromStream(CSSReader.java:1067)
at com.helger.css.reader.CSSReader.readFromFile(CSSReader.java:765)
Please backport fix 34c80e9 to 4.x
What steps will reproduce the problem?
What is the expected output? What do you see instead?
original data
top:expression(eval(document.documentElement.scrollTop+document.documentElement.clientHeight-this.offsetHeight));
written by CSSWriter
top:expression(eval(document.documentElement.scrollTop+document.documentElement.clientHeight-this.offsetHeight);
it should be "));" at the end of the line.
because of this the browser does not analyze after that line.
What version of the product are you using? On what operating system?
phloc-css 3.7.7
OS X 10.9
JDK 1.7
Please provide any additional information below.
We are having trouble with some url properties with url(data:image). For example this CSS:
.hamburger {
| background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1024 1024'%3E%3Cpath style='fill:#ffffff;' d='M820 500c14 0 26-6 36-16s14-22 14-36c0-14-4-26-14-36-12-10-24-16-36-16 0 0-616 0-616 0-12 0-24 6-36 16-10 10-14 22-14 36s4 26 14 36c10 10 22 16 36 16 0 0 616 0 616 0zM204 602c-12 0-24 4-36 14-10 12-14 24-14 36 0 14 4 26 14 36s22 16 36 16c0 0 616 0 616 0 14 0 26-6 36-16s14-22 14-36c0-12-4-24-14-36-12-10-24-14-36-14 0 0-616 0-616 0zM820 294c14 0 26-4 36-14 10-12 14-24 14-36 0-14-4-26-14-36-12-10-24-16-36-16 0 0-616 0-616 0-12 0-24 6-36 16-10 10-14 22-14 36 0 12 4 24 14 36 10 10 22 14 36 14 0 0 616 0 616 0z'/%3E%3C/svg%3E");
| background-position: left 6px center;
| background-repeat: no-repeat;
| display: block;
| position: absolute;
| width: 36px;
| height: 29px;
| z-index: 1000;
| top: 1rem;
| left: 0.9rem;
| }
If I convert it and print it. It gets transformed to:
.hamburger {
background:url("http://localhost.comdata:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1024 1024'%3E%3Cpath style='fill:#ffffff;' d='M820 500c14 0 26-6 36-16s14-22 14-36c0-14-4-26-14-36-12-10-24-16-36-16 0 0-616 0-616 0-12 0-24 6-36 16-10 10-14 22-14 36s4 26 14 36c10 10 22 16 36 16 0 0 616 0 616 0zM204 602c-12 0-24 4-36 14-10 12-14 24-14 36 0 14 4 26 14 36s22 16 36 16c0 0 616 0 616 0 14 0 26-6 36-16s14-22 14-36c0-12-4-24-14-36-12-10-24-14-36-14 0 0-616 0-616 0zM820 294c14 0 26-4 36-14 10-12 14-24 14-36 0-14-4-26-14-36-12-10-24-16-36-16 0 0-616 0-616 0-12 0-24 6-36 16-10 10-14 22-14 36 0 12 4 24 14 36 10 10 22 14 36 14 0 0 616 0 616 0z'/%3E%3C/svg%3E");
background-position:left 6px center;
background-repeat:no-repeat;
display:block;
position:absolute;
width:36px;
height:29px;
top:1rem;
left:0.9rem;
}
Adding the hostname in front of the data:image.
Is this a known bug or something it can be avoided?
Thanks!
Parsing a particular CSS, I get :
java.lang.NullPointerException: The value of 'CSS' may not be null!
at com.helger.commons.ValueEnforcer.notNull(ValueEnforcer.java:86)
at com.helger.css.decl.visit.CSSVisitor.visitCSS(CSSVisitor.java:378)
at com.helger.css.decl.visit.CSSVisitor.visitCSSUrl(CSSVisitor.java:416)
at TestCSS.readFromStyleAttributeWithAPI(TestCSS.java:68)
at TestCSS.main(TestCSS.java:44)
I use attached code
TestCSS.java.zip
Attached css file:
test.css.zip
Thanks
It's often used to do media queries for IE specific browsers/versions
https://jeffclayton.wordpress.com/2014/07/22/internet-explorer-css-hacks-collection/
Hello,
Many thanks for the tool.
I have just noticed that rules containing the -webkit-calc math function cannot be parsed, and are omitted from the stylesheet.
Thanks,
Emmanuel
Hi all!
I want to remove the explicit CSS 2.1 parser from the code as well as I want to remove the version handling inside the code so that only CSS 3.0 is supported. This means that it's up to the implementer to create CSS 2.1 compliant code.
This would make the code more lightweight and I need to maintain only 1 grammaer, as I think that CSS 2.1 support is sufficient with ph-css 4.1.1 :)
Any thoughts on this?
// Philip
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.