refactor(lqip-loader): remove unused palette option (#6992)

This commit is contained in:
Joshua Chen 2022-03-25 10:23:42 +08:00 committed by GitHub
parent 395136a731
commit d3065b8ad2
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
8 changed files with 20 additions and 469 deletions

View file

@ -6,7 +6,7 @@
*/
import path from 'path';
import {base64, palette} from '../lqip';
import {base64} from '../lqip';
const imgPath = path.join(__dirname, '__fixtures__', 'endi.jpg');
const invalidPath = path.join(__dirname, '__fixtures__', 'docusaurus.svg');
@ -23,11 +23,3 @@ describe('base64', () => {
await expect(base64(imgPath)).resolves.toContain(expectedBase64);
});
});
describe('palette', () => {
it('generates a valid color palette', async () => {
const imgPalette = await palette(imgPath);
expect(imgPalette).toHaveLength(6);
expect(imgPalette).toContain('#578ca1');
});
});

View file

@ -1,45 +0,0 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import path from 'path';
import Vibrant from 'node-vibrant';
import type {Palette} from 'node-vibrant/lib/color';
import {toPalette, toBase64} from '../utils';
describe('toBase64', () => {
it('returns a properly formatted Base64 image string', () => {
const mockedMimeType = 'image/jpeg';
const mockedBase64Data = Buffer.from('hello world');
expect(toBase64(mockedMimeType, mockedBase64Data)).toBe(
'data:image/jpeg;base64,aGVsbG8gd29ybGQ=',
);
});
});
describe('toPalette', () => {
let correctTestSwatch: Palette = {};
let testSwatchWithNull: Palette & {Vibrant?: null} = {};
beforeAll(() => {
const imgPath = path.join(__dirname, '__fixtures__/endi.jpg');
const vibrant = new Vibrant(imgPath, {});
return vibrant.getPalette().then((palette) => {
correctTestSwatch = {...palette};
testSwatchWithNull = {...palette, Vibrant: null};
});
});
it('returns 6 hex colours sorted by popularity', () => {
expect(toPalette(correctTestSwatch)).toHaveLength(6);
});
it('returns 5 hex colours with no errors if a palette was incomplete', () => {
expect(toPalette(testSwatchWithNull)).toHaveLength(5);
});
});

View file

@ -22,13 +22,6 @@ export default async function lqipLoader(
}
const callback = this.async();
const imgPath = this.resourcePath;
const config = this.getOptions() ?? {};
config.base64 = 'base64' in config ? config.base64 : true;
// color palette generation is set to false by default
// since it is little bit slower than base64 generation
config.palette = 'palette' in config ? config.palette : false;
let content = contentBuffer.toString('utf8');
const contentIsUrlExport =
/^(?:export default|module.exports =) "data:.*base64,.*/.test(content);
@ -53,24 +46,11 @@ export default async function lqipLoader(
)!.groups!.source!;
}
const outputPromises: [Promise<string> | null, Promise<string[]> | null] = [
config.base64 === true ? lqip.base64(imgPath) : null,
config.palette === true ? lqip.palette(imgPath) : null,
];
try {
const data = await Promise.all(outputPromises);
if (data) {
const [preSrc, palette] = data;
const finalObject = JSON.stringify({src: 'STUB', preSrc, palette});
const result = `module.exports = ${finalObject.replace(
'"STUB"',
source,
)};`;
callback(null, result);
} else {
callback(new Error('ERROR'), undefined);
}
const preSrc = await lqip.base64(imgPath);
const finalObject = JSON.stringify({src: 'STUB', preSrc});
const result = `module.exports = ${finalObject.replace('"STUB"', source)};`;
callback(null, result);
} catch (err) {
console.error(err);
callback(new Error('ERROR'), undefined);

View file

@ -6,10 +6,8 @@
*/
import logger from '@docusaurus/logger';
import Vibrant from 'node-vibrant';
import path from 'path';
import sharp from 'sharp';
import {toPalette, toBase64} from './utils';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const {version} = require('../package.json');
@ -22,6 +20,13 @@ const SUPPORTED_MIMES: Record<string, string> = {
png: 'image/png',
};
/**
* it returns a Base64 image string with required formatting
* to work on the web (<img src=".." /> or in CSS url('..'))
*/
const toBase64 = (extMimeType: string, data: Buffer): string =>
`data:${extMimeType};base64,${data.toString('base64')}`;
export async function base64(file: string): Promise<string> {
let extension = path.extname(file);
extension = extension.split('.').pop()!;
@ -39,14 +44,3 @@ export async function base64(file: string): Promise<string> {
throw err;
}
}
export async function palette(file: string): Promise<string[]> {
const vibrant = new Vibrant(file, {});
try {
const pal = await vibrant.getPalette();
return toPalette(pal);
} catch (err) {
logger.error`Generation of color palette failed for image path=${file}.`;
throw err;
}
}

View file

@ -1,34 +0,0 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import _ from 'lodash';
import type {Palette} from 'node-vibrant/lib/color';
/**
* it returns a Base64 image string with required formatting
* to work on the web (<img src=".." /> or in CSS url('..'))
*/
export const toBase64 = (extMimeType: string, data: Buffer): string =>
`data:${extMimeType};base64,${data.toString('base64')}`;
/**
* takes a color swatch object, converts it to an array & returns
* only hex color
*/
export const toPalette = (swatch: Palette): string[] => {
let palette = Object.keys(swatch).reduce((result, key) => {
if (swatch[key] !== null) {
result.push({
popularity: swatch[key]!.getPopulation(),
hex: swatch[key]!.getHex(),
});
}
return result;
}, [] as {popularity: number; hex: string}[]);
palette = _.sortBy(palette, ['popularity']);
return palette.map((color) => color.hex).reverse();
};