Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: internalized relative links fix #202

Merged
merged 1 commit into from
Sep 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
package ch.sbb.polarion.extension.pdf_exporter.util.html;

import ch.sbb.polarion.extension.generic.regex.RegexMatcher;
import ch.sbb.polarion.extension.pdf_exporter.util.FileResourceProvider;
import com.polarion.core.util.StringUtils;

import java.util.Map;
import java.util.Optional;

public class ExternalCssInternalizer implements LinkInternalizer {

private static final String URL_REGEX = "url\\(\\s*([\"'])?(?<url>.*?)\\1?\\s*\\)";
private static final String DATA_PRECEDENCE = "data-precedence";
private static final String HREF = "href";
private final FileResourceProvider fileResourceProvider;

public ExternalCssInternalizer(FileResourceProvider fileResourceProvider) {
Expand All @@ -15,8 +20,9 @@ public ExternalCssInternalizer(FileResourceProvider fileResourceProvider) {

@Override
public Optional<String> inline(Map<String, String> attributes) {
String url = attributes.get(HREF);
if (!"stylesheet".equals(attributes.get("rel"))
|| !attributes.containsKey("href")) {
|| StringUtils.isEmptyTrimmed(url)) {
return Optional.empty();
}
StringBuilder inlinedContent = new StringBuilder("<style");
Expand All @@ -28,10 +34,25 @@ public Optional<String> inline(Map<String, String> attributes) {
.append("\"");
}
inlinedContent.append(">");
String url = attributes.get("href");
inlinedContent.append(new String(fileResourceProvider.getResourceAsBytes(url)));

String cssContent = new String(fileResourceProvider.getResourceAsBytes(url));
cssContent = processRelativeUrls(url, cssContent);
inlinedContent.append(cssContent);
inlinedContent.append("</style>");

return Optional.of(inlinedContent.toString());
}

private String processRelativeUrls(String resourceUrl, String cssContent) {
int lastSlashPosition = resourceUrl.lastIndexOf('/');
if (lastSlashPosition == -1) {
return cssContent;
}
String resourcePath = resourceUrl.substring(0, lastSlashPosition + 1);
return RegexMatcher.get(URL_REGEX).useJavaUtil().replace(cssContent, engine -> {
String url = engine.group("url");
return url.startsWith("/") || url.toLowerCase().startsWith("http:") || url.toLowerCase().startsWith("https:") ? null :
"url(%s%s)".formatted(resourcePath, url);
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public static Map<String, String> parseLinkTagAttributes(String linkTag) {
RegexMatcher.get(ATTRIBUTE_REGEX).useJavaUtil().processEntry(linkTag, regexEngine -> {
String attributeName = regexEngine.group(1);
String attributeValue = regexEngine.group(3);
attributes.put(attributeName, attributeValue);
attributes.put(attributeName.toLowerCase(), attributeValue);
});

return attributes;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,4 +50,30 @@ void shouldConvertStylesheetLinkAndTransferDataPrecedence() {
assertThat(result.get()).isEqualTo("""
<style data-precedence="test-data-precedence">test-stylesheet</style>""");
}

@Test
void shouldConvertStylesheetLinkAndProcessRelativeLinks() {
when(fileResourceProvider.getResourceAsBytes("/some/location/file.css")).thenReturn("""
@font-face {
src: url('../fonts/some-font.woff');
}
@font-face {
src: url('relative2/some-font2.woff');
}
@font-face {
src: url('/non-relative/fonts/some-font3.woff');
}
""".getBytes());
Optional<String> result = cssLinkInliner.inline(Map.of(
"rel", "stylesheet",
"href", "/some/location/file.css",
"data-precedence", "test-data-precedence"));

assertThat(result).isNotEmpty();
assertThat(result.get()).contains(
"src: url(/some/location/../fonts/some-font.woff)",
"src: url(/some/location/relative2/some-font2.woff)",
"src: url('/non-relative/fonts/some-font3.woff')"
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -56,14 +56,14 @@ void shouldCallInlinersForLinkTags() {
void shouldParseAttributesAndReplaceLinkTags() {
when(linkInternalizer1.inline(anyMap())).thenReturn(Optional.of("<style>replacement</style>"));
String resultHtml = htmlLinksHelper.internalizeLinks("""
<html lang='en'><head><link attr1="value1" attr2="value2">some content</head>""");
<html lang='en'><head><link attr1="value1" ATTR2="value2">some content</head>""");

assertThat(resultHtml).isEqualTo("""
<html lang='en'><head><style>replacement</style>some content</head>""");
@SuppressWarnings("unchecked")
ArgumentCaptor<Map<String, String>> captor = ArgumentCaptor.forClass(Map.class);
verify(linkInternalizer1).inline(captor.capture());
assertThat(captor.getValue()).containsExactly(Map.entry("attr1", "value1"), Map.entry("attr2", "value2"));
assertThat(captor.getValue()).containsExactly(Map.entry("attr1", "value1"), Map.entry("attr2", "value2")); // also it must lowercase attributes
}

@Test
Expand Down
Loading