-
Notifications
You must be signed in to change notification settings - Fork 24.8k
/
imgix_loader.ts
57 lines (49 loc) 路 1.86 KB
/
imgix_loader.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Provider, 傻RuntimeError as RuntimeError} from '@angular/core';
import {RuntimeErrorCode} from '../../../errors';
import {PRECONNECT_CHECK_BLOCKLIST} from '../preconnect_link_checker';
import {IMAGE_LOADER, ImageLoaderConfig} from './image_loader';
import {isValidPath, normalizePath, normalizeSrc} from './loader_utils';
/**
* Function that generates a built-in ImageLoader for Imgix and turns it
* into an Angular provider.
*
* @param path path to the desired Imgix origin,
* e.g. https://somepath.imgix.net or https://images.mysite.com
* @returns Provider that provides an ImageLoader function
*/
export function provideImgixLoader(path: string, options: {ensurePreconnect?: boolean} = {
ensurePreconnect: true
}) {
if (ngDevMode && !isValidPath(path)) {
throwInvalidPathError(path);
}
path = normalizePath(path);
const providers: Provider[] = [{
provide: IMAGE_LOADER,
useValue: (config: ImageLoaderConfig) => {
const url = new URL(`${path}/${normalizeSrc(config.src)}`);
// This setting ensures the smallest allowable format is set.
url.searchParams.set('auto', 'format');
config.width && url.searchParams.set('w', config.width.toString());
return url.href;
}
}];
if (ngDevMode && Boolean(options.ensurePreconnect) === true) {
providers.push({provide: PRECONNECT_CHECK_BLOCKLIST, useValue: [path], multi: true});
}
return providers;
}
function throwInvalidPathError(path: unknown): never {
throw new RuntimeError(
RuntimeErrorCode.INVALID_INPUT,
`ImgixLoader has detected an invalid path: ` +
`expecting a path like https://somepath.imgix.net/` +
`but got: \`${path}\``);
}