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

Enable TypeScript Strict Mode #154

Merged
merged 6 commits into from
Dec 17, 2024
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/node-vibrant/__tests__/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
__screenshots__/
2 changes: 1 addition & 1 deletion packages/node-vibrant/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@
"scripts": {
"build": "vite build",
"test:lib": "vitest run",
"test:watch": "vitest watch"
"test:lib:watch": "vitest watch"
},
"bugs": {
"url": "https://github.com/akfish/node-vibrant/issues"
Expand Down
3 changes: 3 additions & 0 deletions packages/vibrant-color/src/converter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ export function hexToRgb(hex: string): Vec3 {

if (!m) throw new RangeError(`'${hex}' is not a valid hex color`);

if (!m[1] || !m[2] || !m[3])
throw new RangeError(`'${hex}' is not a valid hex color`);

return [m[1], m[2], m[3]].map((s) => parseInt(s, 16)) as Vec3;
}

Expand Down
12 changes: 6 additions & 6 deletions packages/vibrant-color/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export class Swatch {
return filters.length > 0
? colors.filter(({ r, g, b }) => {
for (let j = 0; j < filters.length; j++) {
if (!filters[j](r, g, b, 255)) return false;
if (!filters[j]?.(r, g, b, 255)) return false;
}
return true;
})
Expand All @@ -43,11 +43,11 @@ export class Swatch {
static clone(swatch: Swatch) {
return new Swatch(swatch._rgb, swatch._population);
}
private _hsl: Vec3;
private _rgb: Vec3;
private _yiq: number;
private _population: number;
private _hex: string;
private _hsl: Vec3 | undefined;
private _yiq: number | undefined;
private _hex: string | undefined;

/**
* The red value in the RGB value
Expand Down Expand Up @@ -148,8 +148,8 @@ export class Swatch {
return this._yiq;
}

private _titleTextColor: string;
private _bodyTextColor: string;
private _titleTextColor: string | undefined;
private _bodyTextColor: string | undefined;

get titleTextColor() {
if (!this._titleTextColor) {
Expand Down
101 changes: 48 additions & 53 deletions packages/vibrant-core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export interface VibrantStatic {
}

export default class Vibrant {
private _result: ProcessResult;
private _result: ProcessResult | undefined;
private static _pipeline: Pipeline;

static use(pipeline: Pipeline) {
Expand Down Expand Up @@ -44,8 +44,6 @@ export default class Vibrant {
image: Image,
opts?: Partial<ProcessOptions>
): Promise<ProcessResult> {
const { quantizer } = this.opts;

image.scaleDown(this.opts);

const processOpts = buildProcessOptions(this.opts, opts);
Expand All @@ -63,73 +61,70 @@ export default class Vibrant {
);
}

getPalette(name: string, cb?: Callback<Palette>): Promise<Palette>;
getPalette(cb?: Callback<Palette>): Promise<Palette>;
getPalette(): Promise<Palette> {
async getPalette(name: string, cb?: Callback<Palette>): Promise<Palette>;
async getPalette(cb?: Callback<Palette>): Promise<Palette>;
async getPalette(): Promise<Palette> {
const arg0 = arguments[0];
const arg1 = arguments[1];
const name = typeof arg0 === "string" ? arg0 : "default";
const cb = typeof arg0 === "string" ? arg1 : arg0;
const image = new this.opts.ImageClass();
return image
.load(this._src)
.then((image) => this._process(image, { generators: [name] }))
.then((result) => {
this._result = result;
return result.palettes[name];
})
.then((res) => {
image.remove();
if (cb) {
cb(undefined, res);
}
return res;
})
.catch((err) => {
image.remove();
if (cb) {
cb(err);
}
return Promise.reject(err);
try {
let image1 = await image.load(this._src);
let result1: ProcessResult = await this._process(image1, {
generators: [name],
});
this._result = result1;
let res = result1.palettes[name];
if (!res) {
throw new Error(`Palette with name ${name} not found`);
}
image.remove();
if (cb) {
cb(undefined, res);
}
return res;
} catch (err) {
image.remove();
if (cb) {
cb(err);
}
return Promise.reject(err);
}
}

getPalettes(
async getPalettes(
names: string[],
cb?: Callback<Palette>
): Promise<{ [name: string]: Palette }>;
getPalettes(cb?: Callback<Palette>): Promise<{ [name: string]: Palette }>;
getPalettes(): Promise<{ [name: string]: Palette }> {
async getPalettes(
cb?: Callback<Palette>
): Promise<{ [name: string]: Palette }>;
async getPalettes(): Promise<{ [name: string]: Palette }> {
const arg0 = arguments[0];
const arg1 = arguments[1];
const names = Array.isArray(arg0) ? arg0 : ["*"];
const cb = Array.isArray(arg0) ? arg1 : arg0;
const image = new this.opts.ImageClass();
return image
.load(this._src)
.then((image) =>
this._process(image, {
generators: names,
})
)
.then((result) => {
this._result = result;
return result.palettes;
})
.then((res) => {
image.remove();
if (cb) {
cb(undefined, res);
}
return res;
})
.catch((err) => {
image.remove();
if (cb) {
cb(err);
}
return Promise.reject(err);
try {
let image1 = await image.load(this._src);
let result1: ProcessResult = await this._process(image1, {
generators: names,
});
this._result = result1;
let res: any = result1.palettes;
image.remove();
if (cb) {
cb(undefined, res);
}
return res;
} catch (err) {
image.remove();
if (cb) {
cb(err);
}
return Promise.reject(err);
}
}
}

Expand Down
4 changes: 2 additions & 2 deletions packages/vibrant-core/src/pipeline/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ export class BasicPipeline implements Pipeline {

return {
name,
fn: stage.get(name),
fn: stage.get(name)!,
options,
};
}
Expand Down Expand Up @@ -131,7 +131,7 @@ export class BasicPipeline implements Pipeline {
// Map the values to the expected name
return Promise.resolve(
promiseArr.reduce((promises, promiseVal, i) => {
promises[generators[i].name] = promiseVal;
promises[generators[i]!.name] = promiseVal;
return promises;
}, {} as { [name: string]: Palette })
);
Expand Down
1 change: 1 addition & 0 deletions packages/vibrant-core/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export function mapValues<T, R>(
for (const key in o) {
if (o.hasOwnProperty(key)) {
const v = o[key];
if (!v) continue;
result[key] = mapper(v);
}
}
Expand Down
7 changes: 4 additions & 3 deletions packages/vibrant-generator-default/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ function _createComparisonValue(
for (let i = 0; i < values.length; i += 2) {
const value = values[i];
const weight = values[i + 1];
if (!value || !weight) continue;
sum += value * weight;
weightSum += weight;
}
Expand Down Expand Up @@ -240,7 +241,7 @@ function _generateVariationColors(

function _generateEmptySwatches(
palette: Palette,
maxPopulation: number,
_maxPopulation: number,
opts: DefaultGeneratorOptions
): void {
if (!palette.Vibrant && !palette.DarkVibrant && !palette.LightVibrant) {
Expand Down Expand Up @@ -291,7 +292,7 @@ function _generateEmptySwatches(
}
}

const DefaultGenerator: Generator = (
const DefaultGenerator: Generator = ((
swatches: Array<Swatch>,
opts?: DefaultGeneratorOptions
): Palette => {
Expand All @@ -302,6 +303,6 @@ const DefaultGenerator: Generator = (
_generateEmptySwatches(palette, maxPopulation, opts);

return palette;
};
}) as never;

export default DefaultGenerator;
88 changes: 68 additions & 20 deletions packages/vibrant-image-browser/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,46 @@ function isSameOrigin(a: string, b: string): boolean {
}

export default class BrowserImage extends ImageBase {
image: HTMLImageElement;
private _canvas: HTMLCanvasElement;
private _context: CanvasRenderingContext2D;
private _width: number;
private _height: number;
image: HTMLImageElement | undefined;
private _canvas: HTMLCanvasElement | undefined;
private _context: CanvasRenderingContext2D | undefined;
private _width: number | undefined;
private _height: number | undefined;

private _getCanvas() {
if (!this._canvas) {
throw new Error("Canvas is not initialized");
}

return this._canvas;
}
private _getContext() {
if (!this._context) {
throw new Error("Context is not initialized");
}

return this._context;
}
private _getWidth() {
if (!this._width) {
throw new Error("Width is not initialized");
}

return this._width;
}
private _getHeight() {
if (!this._height) {
throw new Error("Height is not initialized");
}

return this._height;
}

private _initCanvas(): void {
const img = this.image;
if (!img) {
throw new Error("Image is not initialized");
}
const canvas = (this._canvas = document.createElement("canvas"));
const context = canvas.getContext("2d");

Expand All @@ -52,7 +85,8 @@ export default class BrowserImage extends ImageBase {

document.body.appendChild(canvas);
}
load(image: ImageSource): Promise<ImageBase> {

load(image: ImageSource): Promise<this> {
let img: HTMLImageElement;
let src: string;
if (typeof image === "string") {
Expand All @@ -74,7 +108,7 @@ export default class BrowserImage extends ImageBase {
}
this.image = img;

return new Promise<ImageBase>((resolve, reject) => {
return new Promise<this>((resolve, reject) => {
const onImageLoad = () => {
this._initCanvas();
resolve(this);
Expand All @@ -85,37 +119,51 @@ export default class BrowserImage extends ImageBase {
onImageLoad();
} else {
img.onload = onImageLoad;
img.onerror = (e) => reject(new Error(`Fail to load image: ${src}`));
img.onerror = (_e) => reject(new Error(`Fail to load image: ${src}`));
}
});
}

clear(): void {
this._context.clearRect(0, 0, this._width, this._height);
this._getContext().clearRect(0, 0, this._getWidth(), this._getHeight());
}

update(imageData: VibrantImageData): void {
this._context.putImageData(imageData as ImageData, 0, 0);
this._getContext().putImageData(imageData as ImageData, 0, 0);
}

getWidth(): number {
return this._width;
return this._getWidth();
}

getHeight(): number {
return this._height;
return this._getHeight();
}
resize(targetWidth: number, targetHeight: number, ratio: number): void {
const { _canvas: canvas, _context: context, image: img } = this;

this._width = canvas.width = targetWidth;
this._height = canvas.height = targetHeight;
resize(targetWidth: number, targetHeight: number, ratio: number): void {
if (!this.image) {
throw new Error("Image is not initialized");
}
this._width = this._getCanvas().width = targetWidth;
this._height = this._getCanvas().height = targetHeight;

context.scale(ratio, ratio);
context.drawImage(img, 0, 0);
this._getContext().scale(ratio, ratio);
this._getContext().drawImage(this.image, 0, 0);
}

getPixelCount(): number {
return this._width * this._height;
return this._getWidth() * this._getHeight();
}

getImageData(): ImageData {
return this._context.getImageData(0, 0, this._width, this._height);
return this._getContext().getImageData(
0,
0,
this._getWidth(),
this._getHeight()
);
}

remove(): void {
if (this._canvas && this._canvas.parentNode) {
this._canvas.parentNode.removeChild(this._canvas);
Expand Down
Loading
Loading