Skip to content

Commit

Permalink
feat(common): Add new error for complex sizes values on ngOptimizedImage
Browse files Browse the repository at this point in the history
Adds a new error case which throws when a sizes value is provided which uses absolute pixel sizes instead of relative sizes, unless a srcset is provided. Tests are updated accordingly.
  • Loading branch information
atcastle committed Oct 5, 2022
1 parent 719c9a3 commit d0ab48f
Show file tree
Hide file tree
Showing 2 changed files with 1,056 additions and 979 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -347,12 +347,17 @@ export class NgOptimizedImage implements OnInit, OnChanges, OnDestroy {
assertNonEmptyInput(this, 'ngSrc', this.ngSrc);
assertValidNgSrcset(this, this.ngSrcset);
assertNoConflictingSrc(this);
assertNoConflictingSrcset(this);
if (this.ngSrcset) {
assertNoConflictingSrcset(this);
}
assertNotBase64Image(this);
assertNotBlobUrl(this);
assertNonEmptyWidthAndHeight(this);
assertValidLoadingInput(this);
assertNoImageDistortion(this, this.imgElement, this.renderer);
if (!this.srcset) {
assertNoComplexSizes(this);
}
if (this.priority) {
const checker = this.injector.get(PreconnectLinkChecker);
checker.assertPreconnect(this.getRewrittenSrc(), this.ngSrc);
Expand Down Expand Up @@ -383,7 +388,7 @@ export class NgOptimizedImage implements OnInit, OnChanges, OnDestroy {
// could affect the image's loading behavior.
this.setHostAttribute('src', this.getRewrittenSrc());
if (this.sizes) {
this.setHostAttribute('sizes', this.sizes)
this.setHostAttribute('sizes', this.sizes);
}
if (this.ngSrcset) {
this.setHostAttribute('srcset', this.getRewrittenSrcset());
Expand Down Expand Up @@ -550,6 +555,23 @@ function assertNotBase64Image(dir: NgOptimizedImage) {
}
}

/**
* Verifies that the 'sizes' only includes responsive values.
*/
function assertNoComplexSizes(dir: NgOptimizedImage) {
let sizes = dir.sizes;
if (sizes) {
if (sizes.match(/((\)|,)\s|^)\d+px/)) {
throw new RuntimeError(
RuntimeErrorCode.INVALID_INPUT,
`${imgDirectiveDetails(dir.ngSrc, false)} \`sizes\` was set to a string including ` +
`pixel values. For automatic \`srcset\` generation, \`sizes\` must only include responsive ` +
`values, such as \`sizes="50vw"\` or \`sizes="(min-width: 768px) 50vw, 100vw"\`. ` +
`To fix this, modify the \`sizes\` attribute, or provide your own \`srcset\` value directly.`);
}
}
}

/**
* Verifies that the `ngSrc` is not a Blob URL.
*/
Expand Down

0 comments on commit d0ab48f

Please sign in to comment.