Skip to content

Commit 8fefff4

Browse files
committed
COM-2479: - добавил возможность использовать изображения без изменения размера
1 parent 8590f6b commit 8fefff4

10 files changed

Lines changed: 78 additions & 77 deletions

example/react-entry.tsx

Lines changed: 22 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,23 @@ import React from 'react';
22
import ReactDOM from 'react-dom';
33
import { PictureSmart } from '../src/react';
44
import { backgroundCssSmart } from '../src/utils/backgroundCss';
5+
import { getOriginal } from '../src/utils'
56

67
// Adds 'webp' class to html element if the browser supports webp.
78
import '../src/utils/webpDetector'
89

910
const oneImageForAllBreakpoints = require.context('./images/oneImageForAllBreakpoints');
10-
// const differentBreakpoints = require.context('./images/differentBreakpoints');
11+
const differentBreakpoints = require.context('./images/differentBreakpoints');
1112

1213
const oneImageForAllBreakpointsWithoutResize = require.context('./images/oneImageForAllBreakpoints?dontresize');
1314

15+
// Usage example getOriginal ()
16+
const myImageDataDontresize = require('./images/oneImageForAllBreakpoints/all.png?dontresize')
17+
const myImageData = require('./images/oneImageForAllBreakpoints/all.png')
18+
19+
console.log(getOriginal(myImageData))
20+
console.log(getOriginal(myImageDataDontresize))
21+
1422
ReactDOM.render(
1523
<div>
1624
<h1>Example usage of csssr.images</h1>
@@ -19,21 +27,19 @@ ReactDOM.render(
1927
<h3>One image for all resolutions</h3>
2028
<PictureSmart requireImages={oneImageForAllBreakpointsWithoutResize} alt="One image for all resolutions" />
2129
<PictureSmart requireImages={oneImageForAllBreakpoints} alt="One image for all resolutions" />
22-
{/*<h3>Image with different breakpoints</h3>*/}
23-
{/*<PictureSmart requireImages={differentBreakpoints} alt="Image with different breakpoints" />*/}
24-
25-
26-
{/*<h2>As background css</h2>*/}
27-
{/*<h3>One image for all resolutions</h3>*/}
28-
{/*<div className="one-image-for-all-resolutions" style={{ width: '100%', height: '100%' }}>*/}
29-
{/* One image for all resolutions on background*/}
30-
{/*</div>*/}
31-
{/*<style>{backgroundCssSmart('.one-image-for-all-resolutions', oneImageForAllBreakpoints)}</style>*/}
32-
{/*<h3>Different breakpoints</h3>*/}
33-
{/*<div className="different-breakpoints" style={{ width: '100%', height: '100%' }}>*/}
34-
{/* Image with different breakpoints on background*/}
35-
{/*</div>*/}
36-
{/*<style>{backgroundCssSmart('.different-breakpoints', differentBreakpoints)}</style>*/}
30+
<h3>Image with different breakpoints</h3>
31+
<PictureSmart requireImages={differentBreakpoints} alt="Image with different breakpoints" />
32+
<h2>As background css</h2>
33+
<h3>One image for all resolutions</h3>
34+
<div className="one-image-for-all-resolutions" style={{ width: '100%', height: '100%' }}>
35+
One image for all resolutions on background
36+
</div>
37+
<style>{backgroundCssSmart('.one-image-for-all-resolutions', oneImageForAllBreakpoints)}</style>
38+
<h3>Different breakpoints</h3>
39+
<div className="different-breakpoints" style={{ width: '100%', height: '100%' }}>
40+
Image with different breakpoints on background
41+
</div>
42+
<style>{backgroundCssSmart('.different-breakpoints', differentBreakpoints)}</style>
3743
</div>,
3844
document.getElementById('app'),
3945
);

example/webpack.config.ts

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -52,9 +52,7 @@ const config: webpack.Configuration = {
5252
imagesHost: process.env.HOST || `http://${ip.address()}:8081`,
5353
host: process.env.IMGPROXY_HOST || 'http://localhost:8080',
5454
},
55-
// TODO использовать originalPixelRatio
56-
shouldResize: false,
57-
// originalPixelRatio: '1x',
55+
originalPixelRatio: '1x',
5856
},
5957
},
6058
{
@@ -95,8 +93,7 @@ const config: webpack.Configuration = {
9593
imagesHost: process.env.HOST || `http://${ip.address()}:8081`,
9694
host: process.env.IMGPROXY_HOST || 'http://localhost:8080',
9795
},
98-
shouldResize: true,
99-
// originalPixelRatio: '3x',
96+
originalPixelRatio: '3x',
10097
},
10198
},
10299
{

src/types.ts

Lines changed: 5 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,11 @@
11
export type Dpr = '1x' | '2x' | '3x';
22

3-
// TODO поправить этот тип
4-
// export type SrcSet = {
5-
// '1x': string;
6-
// } | {
7-
// '1x': string;
8-
// '2x': string;
9-
// } | {
10-
// '1x': string;
11-
// '2x': string;
12-
// '3x': string;
13-
// };
3+
export type CompressionRatio = {
4+
[dpr in Dpr]?: number;
5+
}
6+
147
export type SrcSet = {
15-
'1x': string;
16-
'2x'?: string;
17-
'3x'?: string;
8+
[dpr in Dpr]?: string;
189
};
1910

2011
export type ExtensionSrcSet = {

src/utils/getCompressionRatio.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import { Dpr, CompressionRatio } from '../types'
2+
3+
// [1x, 2x] -> {1x: 0.5, 2x: 0}
4+
5+
export const getCompressionRatio = (pixelRatios: Dpr[]): CompressionRatio => {
6+
const length = pixelRatios.length;
7+
8+
return pixelRatios.reduce((acc: CompressionRatio, item: Dpr, index: number) => {
9+
if (index + 1 === length) {
10+
acc[item]= 0
11+
return acc
12+
}
13+
14+
acc[item] = (index + 1) / length
15+
return acc
16+
},{})
17+
}

src/utils/getOriginal.ts

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
11
import { BreakpointSource } from '../types';
22

3-
export const getOriginal = (source: BreakpointSource): string => {
4-
// TODO здесь использовалось 3x изображение
5-
// Надо использовать самое большое по значению
6-
// или может быть сохранять где-то original раньше
7-
return source.srcSets[source.srcSets.length - 1].srcSet['1x']
3+
export const getOriginal = (source: BreakpointSource): string | undefined => {
4+
const srcSet = source.srcSets[source.srcSets.length - 1].srcSet;
5+
6+
return srcSet['3x'] || srcSet['2x'] || srcSet['1x']
87
}

src/utils/getPixelRations.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import { Dpr } from '../types';
2+
3+
export const getPixelRations = (originalPixelRatio: Dpr):Dpr[] => {
4+
switch (originalPixelRatio) {
5+
case '1x': return ['1x']
6+
case '2x': return ['1x','2x']
7+
case '3x': return ['1x', '2x', '3x']
8+
default: return ['1x']
9+
}
10+
}

src/utils/index.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,5 @@ export { getBreakpointMedia } from './getBreakpointMedia';
33
export { getSrcSetString } from './getSrcSetString';
44
export { getSources } from './getSources';
55
export { getOriginal } from './getOriginal';
6+
export { getPixelRations } from './getPixelRations'
7+
export { getCompressionRatio } from './getCompressionRatio'

src/webpack/imgproxyUrlBuilder.ts

Lines changed: 7 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import Imgproxy from 'imgproxy';
22
import { Dpr, SrcSet } from '../types'
3+
import { getCompressionRatio } from '../utils'
34

45
type ImgproxyUrlBuilderConfig = {
56
imagesHost: string;
@@ -25,20 +26,11 @@ export const getImgproxyUrlBuilder = ({
2526
};
2627

2728
return (pixelRatios: Dpr[], imagePath: string, extension: string): SrcSet => {
28-
// TODO выводить коэффициенты сжатия (изменения размера) из количества элементов массива
29-
// или из значений массива
30-
// [1x, 2x] -> {1x: 0.5, 2x: 1}
29+
const compressionsRatio = getCompressionRatio(pixelRatios)
3130

32-
if (pixelRatios.length === 1) {
33-
return {
34-
'1x': buildImgproxyUrl(imagePath, 1, extension),
35-
}
36-
}
37-
return {
38-
'1x': buildImgproxyUrl(imagePath, 0.3333, extension),
39-
'2x': buildImgproxyUrl(imagePath, 0.6666, extension),
40-
// 0 здесь означает, что не будет никакого изменения размеров картинки
41-
'3x': buildImgproxyUrl(imagePath, 0, extension),
42-
}
43-
};
31+
return pixelRatios.reduce((acc:SrcSet, item: Dpr) => {
32+
acc[item] = buildImgproxyUrl(imagePath, compressionsRatio[item] || 0, extension)
33+
return acc
34+
},{})
35+
}
4436
};

src/webpack/loader.ts

Lines changed: 7 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,10 @@ import path from 'path';
33
import loaderUtils from 'loader-utils';
44
import validateOptions from 'schema-utils';
55
import { getImgproxyUrlBuilder } from './imgproxyUrlBuilder';
6-
import { Breakpoint, OrderedBreakpointSource, SrcSet } from '../types';
6+
import { Breakpoint, OrderedBreakpointSource, SrcSet, Dpr } from '../types';
77
import { imageUrls } from './plugin';
88
import { schema } from './loaderOptionsSchema';
9-
import { getBreakpointMedia } from '../utils';
9+
import { getBreakpointMedia, getPixelRations } from '../utils';
1010

1111
// Такое имя используется, если нужна одна картинка для всех разрешений
1212
// В таком случаем не будут сгенерированы медиа выражения для разных breakpoint'ов
@@ -19,7 +19,7 @@ export type LoaderOptions = {
1919
imagesHost: string;
2020
host: string;
2121
};
22-
shouldResize: boolean;
22+
originalPixelRatio: Dpr;
2323
};
2424

2525
// Каждый импорт картинки проходит через этот лоадер и на выходе
@@ -30,12 +30,8 @@ export const loader = function (this: webpack.loader.LoaderContext, source: stri
3030

3131
validateOptions(schema, options, { name: 'Imgproxy responsive loader', baseDataPath: 'options' });
3232

33-
// TODO
34-
// Подготовить здесь массив с pixelRatios [1x 2x 3x] [1x 2x] [1x]
35-
// Я не уверен в каком порядке должны быть элементы массива
36-
33+
const pixelRations: Dpr[] = getPixelRations(options.originalPixelRatio)
3734
const breakpoints: Breakpoint[] = options.breakpoints;
38-
3935
// Такой результат приходит от file-loader 'module.exports = "/build/myImage/mobile.all-4b767a7b.png";'
4036
// Получаем оригинальное имя файла изображения (originalImageFileName = mobile.all.png)
4137
const originalImageFileName = path.relative(this.context, this.resourcePath);
@@ -90,18 +86,9 @@ export const loader = function (this: webpack.loader.LoaderContext, source: stri
9086
};
9187
} else {
9288
const buildUrlsForPixelRatios = getImgproxyUrlBuilder(options.imgproxy);
93-
console.log(options.shouldResize)
94-
if (options.shouldResize) {
95-
// TODO убрать хардкод, вынести в опции лоадера?
96-
// originalRatio: 3x -> 3x 2x 1x
97-
// originalRatio: 2x -> 2x 1x
98-
// originalRatio: 1x -> 1x
99-
webpSrcSet = buildUrlsForPixelRatios(['1x', '2x', '3x'], outputImagePath, 'webp');
100-
originalExtensionSrcSet = buildUrlsForPixelRatios(['1x', '2x', '3x'], outputImagePath, originalExtension);
101-
} else {
102-
webpSrcSet = buildUrlsForPixelRatios(['1x'], outputImagePath, 'webp');
103-
originalExtensionSrcSet = buildUrlsForPixelRatios(['1x'], outputImagePath, originalExtension);
104-
}
89+
webpSrcSet = buildUrlsForPixelRatios(pixelRations, outputImagePath, 'webp');
90+
originalExtensionSrcSet = buildUrlsForPixelRatios(pixelRations, outputImagePath, originalExtension);
91+
10592
data = {
10693
order,
10794
breakpointMedia,

src/webpack/loaderOptionsSchema.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,8 +48,8 @@ export const schema: JSONSchema7 = {
4848
},
4949
],
5050
},
51-
shouldResize: {
52-
type: 'boolean',
51+
originalPixelRatio: {
52+
type: 'string'
5353
}
5454
},
5555
required: ['breakpoints', 'imgproxy'],

0 commit comments

Comments
 (0)