feat(StyleUrlResolver): rewrite url in styles

This commit is contained in:
Victor Berchet 2015-02-23 16:29:03 +01:00
parent ff406e65dc
commit edb797e191
2 changed files with 76 additions and 0 deletions

View File

@ -0,0 +1,35 @@
// Some of the code comes from WebComponents.JS
// https://github.com/webcomponents/webcomponentsjs/blob/master/src/HTMLImports/path.js
import {RegExp, RegExpWrapper, StringWrapper} from 'angular2/src/facade/lang';
import {UrlResolver} from './url_resolver';
export class StyleUrlResolver {
_resolver: UrlResolver;
constructor(resolver: UrlResolver) {
this._resolver = resolver;
}
resolveUrls(cssText: string, baseUrl: string) {
cssText = this._replaceUrls(cssText, _cssUrlRe, baseUrl);
cssText = this._replaceUrls(cssText, _cssImportRe, baseUrl);
return cssText;
}
_replaceUrls(cssText: string, re: RegExp, baseUrl: string) {
return StringWrapper.replaceAllMapped(cssText, re, (m) => {
var pre = m[1];
var url = StringWrapper.replaceAll(m[2], _quoteRe, '');
var post = m[3];
var resolvedUrl = this._resolver.resolve(baseUrl, url);
return pre + "'" + resolvedUrl + "'" + post;
});
}
}
var _cssUrlRe = RegExpWrapper.create('(url\\()([^)]*)(\\))');
var _cssImportRe = RegExpWrapper.create('(@import[\\s]+(?!url\\())([^;]*)(;)');
var _quoteRe = RegExpWrapper.create('[\'"]');

View File

@ -0,0 +1,41 @@
import {describe, it, expect, beforeEach, ddescribe, iit, xit, el} from 'angular2/test_lib';
import {StyleUrlResolver} from 'angular2/src/core/compiler/style_url_resolver';
import {UrlResolver} from 'angular2/src/core/compiler/url_resolver';
export function main() {
describe('StyleUrlResolver', () => {
it('should resolve urls', () => {
var styleUrlResolver = new StyleUrlResolver(new FakeUrlResolver());
var css = `
@import '1.css';
@import "2.css";
@import url('3.css');
@import url("4.css");
.foo {
background-image: url("double.jpg");
background-image: url('simple.jpg');
}`;
var expectedCss = `
@import 'base/1.css';
@import 'base/2.css';
@import url('base/3.css');
@import url('base/4.css');
.foo {
background-image: url('base/double.jpg');
background-image: url('base/simple.jpg');
}`;
var resolvedCss = styleUrlResolver.resolveUrls(css, 'base');
expect(resolvedCss).toEqual(expectedCss);
});
});
}
class FakeUrlResolver extends UrlResolver {
resolve(baseUrl: string, url: string): string {
return baseUrl + '/' + url;
}
}