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

Adding clean-set #124

Merged
merged 5 commits into from
Aug 7, 2018
Merged
Show file tree
Hide file tree
Changes from 3 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
6 changes: 3 additions & 3 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

28 changes: 9 additions & 19 deletions src/components/App/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import {
} from '../../codecs/preprocessors';

import { decodeImage } from '../../codecs/decoders';
import { cleanMerge } from '../../lib/clean-modify';

interface SourceImage {
file: File;
Expand Down Expand Up @@ -151,9 +152,6 @@ export default class App extends Component<Props, State> {
type: EncoderType,
options?: EncoderOptions,
): void {
const images = this.state.images.slice() as [EncodedImage, EncodedImage];
const oldImage = images[index];

// Some type cheating here.
// encoderMap[type].defaultOptions is always safe.
// options should always be correct for the type, but TypeScript isn't smart enough.
Expand All @@ -162,12 +160,7 @@ export default class App extends Component<Props, State> {
options: options || encoderMap[type].defaultOptions,
} as EncoderState;

images[index] = {
...oldImage,
encoderState,
preprocessorState,
};

const images = cleanMerge(this.state.images, '' + index, { encoderState, preprocessorState });
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

const images = cleanMerge(
    this.state.images,
    '' + index,
    { encoderState, preprocessorState } as Partial<EncodedImage>
);

this.setState({ images });
}

Expand Down Expand Up @@ -246,19 +239,19 @@ export default class App extends Component<Props, State> {
async updateImage(index: number): Promise<void> {
const { source } = this.state;
if (!source) return;
let images = this.state.images.slice() as [EncodedImage, EncodedImage];

// Each time we trigger an async encode, the counter changes.
const loadingCounter = images[index].loadingCounter + 1;
const loadingCounter = this.state.images[index].loadingCounter + 1;

const image = images[index] = {
...images[index],
let images = cleanMerge(this.state.images, '' + index, {
loadingCounter,
loading: true,
};
});

this.setState({ images });

const image = images[index];

let file;
try {
source.preprocessed = await preprocessImage(source, image.preprocessorState);
Expand All @@ -283,16 +276,13 @@ export default class App extends Component<Props, State> {
throw err;
}

images = this.state.images.slice() as [EncodedImage, EncodedImage];

images[index] = {
...images[index],
images = cleanMerge(this.state.images, '' + index, {
file,
bmp,
downloadUrl: URL.createObjectURL(file),
loading: images[index].loadingCounter !== loadingCounter,
loadedCounter: loadingCounter,
};
});

this.setState({ images, error: '' });
}
Expand Down
23 changes: 8 additions & 15 deletions src/components/Options/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { h, Component } from 'preact';

import * as style from './style.scss';
import { bind } from '../../lib/util';
import { cleanSet, cleanMerge } from '../../lib/clean-modify';
import MozJpegEncoderOptions from '../../codecs/mozjpeg/options';
import BrowserJPEGEncoderOptions from '../../codecs/browser-jpeg/options';
import WebPEncoderOptions from '../../codecs/webp/options';
Expand Down Expand Up @@ -80,27 +82,18 @@ export default class Options extends Component<Props, State> {
@bind
onPreprocessorEnabledChange(event: Event) {
const el = event.currentTarget as HTMLInputElement;

const preprocessor = el.name.split('.')[0] as keyof PreprocessorState;

this.props.onPreprocessorOptionsChange({
...this.props.preprocessorState,
[preprocessor]: {
...this.props.preprocessorState[preprocessor],
enabled: el.checked,
},
});
this.props.onPreprocessorOptionsChange(
cleanSet(this.props.preprocessorState, `${preprocessor}.enabled`, el.checked),
);
}

@bind
onQuantizerOptionsChange(opts: QuantizeOptions) {
this.props.onPreprocessorOptionsChange({
...this.props.preprocessorState,
quantizer: {
...opts,
enabled: this.props.preprocessorState.quantizer.enabled,
},
});
this.props.onPreprocessorOptionsChange(
cleanMerge(this.props.preprocessorState, 'quantizer', opts),
);
}

render(
Expand Down
62 changes: 62 additions & 0 deletions src/lib/clean-modify.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
function cleanSetOrMerge<A = any[] | object>(
source: A,
keys: string | string[],
toSetOrMerge: any[] | object,
merge: boolean,
): A {
const splitKeys = typeof keys === 'string' ? keys.split('.') : keys;

// Going off road in terms of types, otherwise TypeScript doesn't like the access-by-index.
// The assumptions in this code break if the object contains things which aren't arrays or
// plain objects.
let last = copy(source) as any;
const newObject = last;

const lastIndex = splitKeys.length - 1;

for (const [i, key] of splitKeys.entries()) {
if (i !== lastIndex) {
// Copy everything along the path.
last = last[key] = copy(last[key]);
} else {
// Merge or set.
last[key] = merge ?
Object.assign(copy(last[key]), toSetOrMerge) :
toSetOrMerge;
}
}

return newObject;
}

function copy<A = any[] | object>(source: A): A {
// Some type cheating here, as TypeScript can't infer between generic types.
if (Array.isArray(source)) return [...source] as any;
return { ...(source as any) };
}

/**
* @param {(any[] | object)} source Object to copy from.
* @param {(string | string[])} keys Path to modify, eg "foo.bar.baz".
* @param {(any[] | object)} toMerge A value to merge into the value at the path.
*/
export function cleanMerge<A = any[] | object>(
source: A,
keys: string | string[],
toMerge: any[] | object,
): A {
return cleanSetOrMerge(source, keys, toMerge, true);
}

/**
* @param {(any[] | object)} source Object to copy from.
* @param {(string | string[])} keys Path to modify, eg "foo.bar.baz".
* @param {(any[] | object)} newValue A value to set at the path.
*/
export function cleanSet<A = any[] | object>(
source: A,
keys: string | string[],
newValue: any,
): A {
return cleanSetOrMerge(source, keys, newValue, false);
}