1 | import {getJSON, getImage, ResourceType} from '../util/ajax';
|
2 |
|
3 | import browser from '../util/browser';
|
4 | import {RGBAImage} from '../util/image';
|
5 |
|
6 | import type {StyleImage} from './style_image';
|
7 | import type {RequestManager} from '../util/request_manager';
|
8 | import type {Callback} from '../types/callback';
|
9 | import type {Cancelable} from '../types/cancelable';
|
10 |
|
11 | export default function(
|
12 | baseURL: string,
|
13 | requestManager: RequestManager,
|
14 | pixelRatio: number,
|
15 | callback: Callback<{[_: string]: StyleImage}>
|
16 | ): Cancelable {
|
17 | let json: any, image, error;
|
18 | const format = pixelRatio > 1 ? '@2x' : '';
|
19 |
|
20 | let jsonRequest = getJSON(requestManager.transformRequest(requestManager.normalizeSpriteURL(baseURL, format, '.json'), ResourceType.SpriteJSON), (err?: Error | null, data?: any | null) => {
|
21 | jsonRequest = null;
|
22 | if (!error) {
|
23 | error = err;
|
24 | json = data;
|
25 | maybeComplete();
|
26 | }
|
27 | });
|
28 |
|
29 | let imageRequest = getImage(requestManager.transformRequest(requestManager.normalizeSpriteURL(baseURL, format, '.png'), ResourceType.SpriteImage), (err, img) => {
|
30 | imageRequest = null;
|
31 | if (!error) {
|
32 | error = err;
|
33 | image = img;
|
34 | maybeComplete();
|
35 | }
|
36 | });
|
37 |
|
38 | function maybeComplete() {
|
39 | if (error) {
|
40 | callback(error);
|
41 | } else if (json && image) {
|
42 | const imageData = browser.getImageData(image);
|
43 | const result = {};
|
44 |
|
45 | for (const id in json) {
|
46 | const {width, height, x, y, sdf, pixelRatio, stretchX, stretchY, content} = json[id];
|
47 | const data = new RGBAImage({width, height});
|
48 | RGBAImage.copy(imageData, data, {x, y}, {x: 0, y: 0}, {width, height});
|
49 | result[id] = {data, pixelRatio, sdf, stretchX, stretchY, content};
|
50 | }
|
51 |
|
52 | callback(null, result);
|
53 | }
|
54 | }
|
55 |
|
56 | return {
|
57 | cancel() {
|
58 | if (jsonRequest) {
|
59 | jsonRequest.cancel();
|
60 | jsonRequest = null;
|
61 | }
|
62 | if (imageRequest) {
|
63 | imageRequest.cancel();
|
64 | imageRequest = null;
|
65 | }
|
66 | }
|
67 | };
|
68 | }
|