Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Autoconvert assets if browser supports it #18012

Merged
merged 19 commits into from
Apr 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 7 additions & 1 deletion api/src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,31 +6,37 @@ import { getMilliseconds } from './utils/get-milliseconds.js';
export const SYSTEM_ASSET_ALLOW_LIST: TransformationParams[] = [
{
key: 'system-small-cover',
format: 'auto',
transforms: [['resize', { width: 64, height: 64, fit: 'cover' }]],
},
{
key: 'system-small-contain',
format: 'auto',
transforms: [['resize', { width: 64, fit: 'contain' }]],
},
{
key: 'system-medium-cover',
format: 'auto',
transforms: [['resize', { width: 300, height: 300, fit: 'cover' }]],
},
{
key: 'system-medium-contain',
format: 'auto',
transforms: [['resize', { width: 300, fit: 'contain' }]],
},
{
key: 'system-large-cover',
format: 'auto',
transforms: [['resize', { width: 800, height: 800, fit: 'cover' }]],
},
{
key: 'system-large-contain',
format: 'auto',
transforms: [['resize', { width: 800, fit: 'contain' }]],
},
];

export const ASSET_TRANSFORM_QUERY_KEYS = [
export const ASSET_TRANSFORM_QUERY_KEYS: Array<keyof TransformationParams> = [
'key',
'transforms',
'width',
Expand Down
18 changes: 15 additions & 3 deletions api/src/controllers/assets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import logger from '../logger.js';
import useCollection from '../middleware/use-collection.js';
import { AssetsService } from '../services/assets.js';
import { PayloadService } from '../services/payload.js';
import { TransformationMethods, TransformationParams, TransformationPreset } from '../types/assets.js';
import { TransformationMethods, TransformationParams } from '../types/assets.js';
import asyncHandler from '../utils/async-handler.js';
import { getCacheControlHeader } from '../utils/get-cache-headers.js';
import { getConfigFromEnv } from '../utils/get-config-from-env.js';
Expand Down Expand Up @@ -139,12 +139,24 @@ router.get(
schema: req.schema,
});

const transformation: TransformationParams | TransformationPreset = res.locals['transformation'].key
? (res.locals['shortcuts'] as TransformationPreset[]).find(
const transformation: TransformationParams = res.locals['transformation'].key
? (res.locals['shortcuts'] as TransformationParams[]).find(
(transformation) => transformation['key'] === res.locals['transformation'].key
)
: res.locals['transformation'];

if (transformation.format === 'auto' && req.headers.accept) {
let format: Exclude<TransformationParams['format'], 'auto'> = 'jpg';

if (req.headers.accept.includes('image/webp')) {
format = 'webp';
} else if (req.headers.accept.includes('image/avif')) {
format = 'avif';
}

transformation.format = format;
}

let range: Range | undefined = undefined;

if (req.headers.range) {
Expand Down
2 changes: 2 additions & 0 deletions api/src/database/system-data/fields/settings.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,8 @@ fields:
options:
allowNone: true
choices:
- value: 'auto'
text: 'Auto'
- value: jpeg
text: JPEG
- value: png
Expand Down
10 changes: 2 additions & 8 deletions api/src/services/assets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,7 @@ import { RangeNotSatisfiableException } from '../exceptions/range-not-satisfiabl
import { ServiceUnavailableException } from '../exceptions/service-unavailable.js';
import logger from '../logger.js';
import { getStorage } from '../storage/index.js';
import type {
AbstractServiceOptions,
File,
Transformation,
TransformationParams,
TransformationPreset,
} from '../types/index.js';
import type { AbstractServiceOptions, File, Transformation, TransformationParams } from '../types/index.js';
import { getMilliseconds } from '../utils/get-milliseconds.js';
import * as TransformationUtils from '../utils/transformations.js';
import { AuthorizationService } from './authorization.js';
Expand All @@ -41,7 +35,7 @@ export class AssetsService {

async getAsset(
id: string,
transformation: TransformationParams | TransformationPreset,
transformation: TransformationParams,
range?: Range
): Promise<{ stream: Readable; file: any; stat: Stat }> {
const storage = await getStorage();
Expand Down
18 changes: 4 additions & 14 deletions api/src/types/assets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,21 +65,11 @@ export type TransformationMap = {

export type Transformation = TransformationMap[keyof TransformationMap];

export type TransformationResize = Pick<ResizeOptions, 'width' | 'height' | 'fit' | 'withoutEnlargement'>;

export type TransformationParams = {
key?: string;
transforms?: Transformation[];
};

// Transformation preset is defined in the admin UI.
export type TransformationPreset = TransformationPresetFormat &
TransformationPresetResize &
TransformationParams & { key: string };

export type TransformationPresetFormat = {
format?: 'jpg' | 'jpeg' | 'png' | 'webp' | 'tiff' | 'avif';
format?: 'auto' | 'jpg' | 'jpeg' | 'png' | 'webp' | 'tiff' | 'avif';
paescuj marked this conversation as resolved.
Show resolved Hide resolved
quality?: number;
};

export type TransformationPresetResize = Pick<ResizeOptions, 'width' | 'height' | 'fit' | 'withoutEnlargement'>;

// @NOTE Keys used in TransformationParams should match ASSET_GENERATION_QUERY_KEYS in constants.ts
} & TransformationResize;
85 changes: 22 additions & 63 deletions api/src/utils/transformations.ts
Original file line number Diff line number Diff line change
@@ -1,70 +1,29 @@
import { isNil } from 'lodash-es';
import type {
File,
Transformation,
TransformationParams,
TransformationPreset,
TransformationPresetFormat,
TransformationPresetResize,
} from '../types/index.js';
import type { File, Transformation, TransformationParams } from '../types/index.js';

// Extract transforms from a preset
export function resolvePreset(input: TransformationParams | TransformationPreset, file: File): Transformation[] {
// Do the format conversion last
return [extractResize(input), ...(input.transforms ?? []), extractToFormat(input, file)].filter(
(transform): transform is Transformation => transform !== undefined
);
}

function extractOptions<T extends Record<string, any>>(
keys: (keyof T)[],
numberKeys: (keyof T)[] = [],
booleanKeys: (keyof T)[] = []
) {
return function (input: TransformationParams | TransformationPreset): T {
return Object.entries(input).reduce(
(config, [key, value]) =>
keys.includes(key as any) && isNil(value) === false
? {
...config,
[key]: numberKeys.includes(key as any)
? +value!
: booleanKeys.includes(key as any)
? Boolean(value)
: value,
}
: config,
{} as T
);
};
}
export function resolvePreset(input: TransformationParams, file: File): Transformation[] {
const transforms = input.transforms ?? [];

// Extract format transform from a preset
function extractToFormat(input: TransformationParams | TransformationPreset, file: File): Transformation | undefined {
const options = extractOptions<TransformationPresetFormat>(['format', 'quality'], ['quality'])(input);
return Object.keys(options).length > 0
? [
'toFormat',
options.format || (file.type!.split('/')[1] as any),
{
quality: options.quality,
},
]
: undefined;
}
if (input.format || input.quality)
transforms.push([
'toFormat',
input.format || (file.type!.split('/')[1] as any),
{
quality: input.quality ? Number(input.quality) : undefined,
},
]);

function extractResize(input: TransformationParams | TransformationPreset): Transformation | undefined {
const resizable = ['width', 'height'].some((key) => key in input);
if (!resizable) return undefined;
if (input.width || input.height)
transforms.push([
'resize',
{
width: input.width ? Number(input.width) : undefined,
height: input.height ? Number(input.height) : undefined,
fit: input.fit,
withoutEnlargement: input.withoutEnlargement ? Boolean(input.withoutEnlargement) : undefined,
},
]);

return [
'resize',
extractOptions<TransformationPresetResize>(
['width', 'height', 'fit', 'withoutEnlargement'],
['width', 'height'],
['withoutEnlargement']
)(input),
];
return transforms;
}

/**
Expand Down
2 changes: 1 addition & 1 deletion docs/configuration/project-settings.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ following options to limit what transformations are possible.
- **Height** — Sets the height of the image.
- **Quality** — Adjusts the compression or quality of the image.
- **Upscaling** — When enabled, images won't be upscaled.
- **Format** — Changes the output format to JPG, PNG, WebP, or TIFF.
- **Format** — Changes the output format.
- **Additional Transformations** — Adds additional transformations using
[Sharp](https://sharp.pixelplumbing.com/api-constructor).

Expand Down
3 changes: 2 additions & 1 deletion docs/reference/files.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,8 @@ grained control:
- **`height`** — The **height** of the thumbnail in pixels
- **`quality`** — The optional **quality** of the thumbnail (`1` to `100`)
- **`withoutEnlargement`** — Disable image up-scaling
- **`format`** — What file format to return the thumbnail in. One of `jpg`, `png`, `webp`, `tiff`
- **`format`** — What file format to return the thumbnail in. One of `auto`, `jpg`, `png`, `webp`, `tiff`
- `auto` — Will try to format it in `webp` or `avif` if the browser supports it, otherwise it will fallback to `jpg`.

### Advanced Transformations

Expand Down