mirror of
https://github.com/GoogleChromeLabs/squoosh.git
synced 2025-11-12 16:57:26 +00:00
Compare commits
41 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
956e064c8c | ||
|
|
5270553f27 | ||
|
|
3005098f67 | ||
|
|
9b879609f3 | ||
|
|
9008d1c380 | ||
|
|
915f4cd4e6 | ||
|
|
7dd842a870 | ||
|
|
2e478b323a | ||
|
|
f24d41ba74 | ||
|
|
cb3c66fc5b | ||
|
|
3315188bb3 | ||
|
|
efad4f612f | ||
|
|
7998cf247b | ||
|
|
0041d24aa3 | ||
|
|
2fa2e567a6 | ||
|
|
98f61ba60c | ||
|
|
672c57b61f | ||
|
|
bfe74b5fb2 | ||
|
|
1507a44141 | ||
|
|
bb3bd2d46a | ||
|
|
4df3a7df83 | ||
|
|
853b305465 | ||
|
|
9a230adc03 | ||
|
|
3039c84738 | ||
|
|
bfa5cd085d | ||
|
|
7c282b30b1 | ||
|
|
06fa3c541e | ||
|
|
c9e31ac1f7 | ||
|
|
e248486d3d | ||
|
|
b32a52d236 | ||
|
|
a24b4d6d4d | ||
|
|
b831aa0075 | ||
|
|
bf4d4b78cb | ||
|
|
496896e36e | ||
|
|
6b88ec1f8a | ||
|
|
3af5f3a96d | ||
|
|
ddc5564515 | ||
|
|
bc5da7ef06 | ||
|
|
45221c0b03 | ||
|
|
d29cf2ffa7 | ||
|
|
f6c0b89d1f |
@@ -1,6 +1,7 @@
|
|||||||
# Long-term cache by default.
|
# Long-term cache by default.
|
||||||
/*
|
/*
|
||||||
Cache-Control: max-age=31536000
|
Cache-Control: max-age=31536000
|
||||||
|
Access-Control-Allow-Origin: *
|
||||||
|
|
||||||
# And here are the exceptions:
|
# And here are the exceptions:
|
||||||
/
|
/
|
||||||
@@ -9,6 +10,9 @@
|
|||||||
/serviceworker.js
|
/serviceworker.js
|
||||||
Cache-Control: no-cache
|
Cache-Control: no-cache
|
||||||
|
|
||||||
|
/sdk.mjs
|
||||||
|
Cache-Control: no-cache
|
||||||
|
|
||||||
/manifest.json
|
/manifest.json
|
||||||
Cache-Control: must-revalidate, max-age=3600
|
Cache-Control: must-revalidate, max-age=3600
|
||||||
|
|
||||||
|
|||||||
1
codecs/resize/.gitignore
vendored
1
codecs/resize/.gitignore
vendored
@@ -3,3 +3,4 @@ target
|
|||||||
Cargo.lock
|
Cargo.lock
|
||||||
bin/
|
bin/
|
||||||
pkg/README.md
|
pkg/README.md
|
||||||
|
lut.inc
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "resize"
|
name = "squooshresize"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
authors = ["Surma <surma@surma.link>"]
|
authors = ["Surma <surma@surma.link>"]
|
||||||
|
|
||||||
|
|||||||
53
codecs/resize/benchmark.js
Normal file
53
codecs/resize/benchmark.js
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
// THIS IS NOT A NODE SCRIPT
|
||||||
|
// This is a d8 script. Please install jsvu[1] and install v8.
|
||||||
|
// Then run `npm run --silent benchmark`.
|
||||||
|
// [1]: https://github.com/GoogleChromeLabs/jsvu
|
||||||
|
|
||||||
|
self = global = this;
|
||||||
|
load("./pkg/resize.js");
|
||||||
|
|
||||||
|
async function init() {
|
||||||
|
// Adjustable constants.
|
||||||
|
const inputDimensions = 2000;
|
||||||
|
const outputDimensions = 1500;
|
||||||
|
const algorithm = 3; // Lanczos
|
||||||
|
const iterations = new Array(100);
|
||||||
|
|
||||||
|
// Constants. Don’t change.
|
||||||
|
const imageByteSize = inputDimensions * inputDimensions * 4;
|
||||||
|
const imageBuffer = new Uint8ClampedArray(imageByteSize);
|
||||||
|
|
||||||
|
const module = await WebAssembly.compile(readbuffer("./pkg/resize_bg.wasm"));
|
||||||
|
await wasm_bindgen(module);
|
||||||
|
[[false, false], [true, false], [false, true], [true, true]].forEach(
|
||||||
|
opts => {
|
||||||
|
print(`\npremultiplication: ${opts[0]}`);
|
||||||
|
print(`color space conversion: ${opts[1]}`);
|
||||||
|
print(`==============================`);
|
||||||
|
for (let i = 0; i < 100; i++) {
|
||||||
|
const start = Date.now();
|
||||||
|
wasm_bindgen.resize(
|
||||||
|
imageBuffer,
|
||||||
|
inputDimensions,
|
||||||
|
inputDimensions,
|
||||||
|
outputDimensions,
|
||||||
|
outputDimensions,
|
||||||
|
algorithm,
|
||||||
|
...opts
|
||||||
|
);
|
||||||
|
iterations[i] = Date.now() - start;
|
||||||
|
}
|
||||||
|
const average =
|
||||||
|
iterations.reduce((sum, c) => sum + c) / iterations.length;
|
||||||
|
const stddev = Math.sqrt(
|
||||||
|
iterations
|
||||||
|
.map(i => Math.pow(i - average, 2))
|
||||||
|
.reduce((sum, c) => sum + c) / iterations.length
|
||||||
|
);
|
||||||
|
print(`n = ${iterations.length}`);
|
||||||
|
print(`Average: ${average}`);
|
||||||
|
print(`StdDev: ${stddev}`);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
init().catch(e => console.error(e, e.stack));
|
||||||
23
codecs/resize/build.rs
Normal file
23
codecs/resize/build.rs
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
include!("./src/srgb.rs");
|
||||||
|
|
||||||
|
use std::io::Write;
|
||||||
|
|
||||||
|
fn main() -> std::io::Result<()> {
|
||||||
|
let mut srgb_to_linear_lut = String::from("static SRGB_TO_LINEAR_LUT: [f32; 256] = [");
|
||||||
|
let mut linear_to_srgb_lut = String::from("static LINEAR_TO_SRGB_LUT: [f32; 256] = [");
|
||||||
|
for i in 0..256 {
|
||||||
|
srgb_to_linear_lut.push_str(&format!("{0:.7}", srgb_to_linear((i as f32) / 255.0)));
|
||||||
|
srgb_to_linear_lut.push_str(",");
|
||||||
|
linear_to_srgb_lut.push_str(&format!("{0:.7}", linear_to_srgb((i as f32) / 255.0)));
|
||||||
|
linear_to_srgb_lut.push_str(",");
|
||||||
|
}
|
||||||
|
srgb_to_linear_lut.pop().unwrap();
|
||||||
|
linear_to_srgb_lut.pop().unwrap();
|
||||||
|
srgb_to_linear_lut.push_str("];");
|
||||||
|
linear_to_srgb_lut.push_str("];");
|
||||||
|
|
||||||
|
let mut file = std::fs::File::create("src/lut.inc")?;
|
||||||
|
file.write_all(srgb_to_linear_lut.as_bytes())?;
|
||||||
|
file.write_all(linear_to_srgb_lut.as_bytes())?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@
|
|||||||
"name": "resize",
|
"name": "resize",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build:image": "docker build -t squoosh-resize .",
|
"build:image": "docker build -t squoosh-resize .",
|
||||||
"build": "docker run --rm -v $(pwd):/src squoosh-resize ./build.sh"
|
"build": "docker run --rm -v $(pwd):/src squoosh-resize ./build.sh",
|
||||||
|
"benchmark": "v8 --no-liftoff --no-wasm-tier-up ./benchmark.js"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
4
codecs/resize/pkg/resize.d.ts
vendored
4
codecs/resize/pkg/resize.d.ts
vendored
@@ -6,6 +6,8 @@
|
|||||||
* @param {number} arg3
|
* @param {number} arg3
|
||||||
* @param {number} arg4
|
* @param {number} arg4
|
||||||
* @param {number} arg5
|
* @param {number} arg5
|
||||||
|
* @param {boolean} arg6
|
||||||
|
* @param {boolean} arg7
|
||||||
* @returns {Uint8Array}
|
* @returns {Uint8Array}
|
||||||
*/
|
*/
|
||||||
export function resize(arg0: Uint8Array, arg1: number, arg2: number, arg3: number, arg4: number, arg5: number): Uint8Array;
|
export function resize(arg0: Uint8Array, arg1: number, arg2: number, arg3: number, arg4: number, arg5: number, arg6: boolean, arg7: boolean): Uint8Array;
|
||||||
|
|||||||
@@ -46,13 +46,15 @@
|
|||||||
* @param {number} arg3
|
* @param {number} arg3
|
||||||
* @param {number} arg4
|
* @param {number} arg4
|
||||||
* @param {number} arg5
|
* @param {number} arg5
|
||||||
|
* @param {boolean} arg6
|
||||||
|
* @param {boolean} arg7
|
||||||
* @returns {Uint8Array}
|
* @returns {Uint8Array}
|
||||||
*/
|
*/
|
||||||
__exports.resize = function(arg0, arg1, arg2, arg3, arg4, arg5) {
|
__exports.resize = function(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7) {
|
||||||
const ptr0 = passArray8ToWasm(arg0);
|
const ptr0 = passArray8ToWasm(arg0);
|
||||||
const len0 = WASM_VECTOR_LEN;
|
const len0 = WASM_VECTOR_LEN;
|
||||||
const retptr = globalArgumentPtr();
|
const retptr = globalArgumentPtr();
|
||||||
wasm.resize(retptr, ptr0, len0, arg1, arg2, arg3, arg4, arg5);
|
wasm.resize(retptr, ptr0, len0, arg1, arg2, arg3, arg4, arg5, arg6, arg7);
|
||||||
const mem = getUint32Memory();
|
const mem = getUint32Memory();
|
||||||
const rustptr = mem[retptr / 4];
|
const rustptr = mem[retptr / 4];
|
||||||
const rustlen = mem[retptr / 4 + 1];
|
const rustlen = mem[retptr / 4 + 1];
|
||||||
|
|||||||
2
codecs/resize/pkg/resize_bg.d.ts
vendored
2
codecs/resize/pkg/resize_bg.d.ts
vendored
@@ -3,4 +3,4 @@ export const memory: WebAssembly.Memory;
|
|||||||
export function __wbindgen_global_argument_ptr(): number;
|
export function __wbindgen_global_argument_ptr(): number;
|
||||||
export function __wbindgen_malloc(a: number): number;
|
export function __wbindgen_malloc(a: number): number;
|
||||||
export function __wbindgen_free(a: number, b: number): void;
|
export function __wbindgen_free(a: number, b: number): void;
|
||||||
export function resize(a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number): void;
|
export function resize(a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number, i: number, j: number): void;
|
||||||
|
|||||||
Binary file not shown.
@@ -9,6 +9,9 @@ use resize::Pixel::RGBA;
|
|||||||
use resize::Type;
|
use resize::Type;
|
||||||
use wasm_bindgen::prelude::*;
|
use wasm_bindgen::prelude::*;
|
||||||
|
|
||||||
|
mod srgb;
|
||||||
|
use srgb::Clamp;
|
||||||
|
|
||||||
cfg_if! {
|
cfg_if! {
|
||||||
// When the `wee_alloc` feature is enabled, use `wee_alloc` as the global
|
// When the `wee_alloc` feature is enabled, use `wee_alloc` as the global
|
||||||
// allocator.
|
// allocator.
|
||||||
@@ -19,15 +22,50 @@ cfg_if! {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
include!("./lut.inc");
|
||||||
|
|
||||||
|
// If `with_space_conversion` is true, this function returns 2 functions that
|
||||||
|
// convert from sRGB to linear RGB and vice versa. If `with_space_conversion` is
|
||||||
|
// false, the 2 functions returned do nothing.
|
||||||
|
fn converter_funcs(with_space_conversion: bool) -> ((fn(u8) -> f32), (fn(f32) -> u8)) {
|
||||||
|
if with_space_conversion {
|
||||||
|
(
|
||||||
|
|v| SRGB_TO_LINEAR_LUT[v as usize] * 255.0,
|
||||||
|
|v| (LINEAR_TO_SRGB_LUT[v as usize] * 255.0) as u8,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
(|v| v as f32, |v| v as u8)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// If `with_alpha_premultiplication` is true, this function returns a function
|
||||||
|
// that premultiply the alpha channel with the given channel value and another
|
||||||
|
// function that reverses that process. If `with_alpha_premultiplication` is
|
||||||
|
// false, the functions just return the channel value.
|
||||||
|
fn alpha_multiplier_funcs(
|
||||||
|
with_alpha_premultiplication: bool,
|
||||||
|
) -> ((fn(f32, u8) -> u8), (fn(u8, u8) -> f32)) {
|
||||||
|
if with_alpha_premultiplication {
|
||||||
|
(
|
||||||
|
|v, a| (v * (a as f32) / 255.0) as u8,
|
||||||
|
|v, a| (v as f32) * 255.0 / (a as f32).clamp(0.0, 255.0),
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
(|v, _a| v as u8, |v, _a| v as f32)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[wasm_bindgen]
|
#[wasm_bindgen]
|
||||||
#[no_mangle]
|
#[no_mangle]
|
||||||
pub fn resize(
|
pub fn resize(
|
||||||
input_image: Vec<u8>,
|
mut input_image: Vec<u8>,
|
||||||
input_width: usize,
|
input_width: usize,
|
||||||
input_height: usize,
|
input_height: usize,
|
||||||
output_width: usize,
|
output_width: usize,
|
||||||
output_height: usize,
|
output_height: usize,
|
||||||
typ_idx: usize,
|
typ_idx: usize,
|
||||||
|
premultiply: bool,
|
||||||
|
color_space_conversion: bool,
|
||||||
) -> Vec<u8> {
|
) -> Vec<u8> {
|
||||||
let typ = match typ_idx {
|
let typ = match typ_idx {
|
||||||
0 => Type::Triangle,
|
0 => Type::Triangle,
|
||||||
@@ -36,7 +74,23 @@ pub fn resize(
|
|||||||
3 => Type::Lanczos3,
|
3 => Type::Lanczos3,
|
||||||
_ => panic!("Nope"),
|
_ => panic!("Nope"),
|
||||||
};
|
};
|
||||||
|
let num_input_pixels = input_width * input_height;
|
||||||
let num_output_pixels = output_width * output_height;
|
let num_output_pixels = output_width * output_height;
|
||||||
|
|
||||||
|
let (to_linear, to_color_space) = converter_funcs(color_space_conversion);
|
||||||
|
let (premultiplier, demultiplier) = alpha_multiplier_funcs(premultiply);
|
||||||
|
|
||||||
|
// If both options are false, there is no preprocessing on the pixel valus
|
||||||
|
// and we can skip the loop.
|
||||||
|
if premultiply || color_space_conversion {
|
||||||
|
for i in 0..num_input_pixels {
|
||||||
|
for j in 0..3 {
|
||||||
|
input_image[4 * i + j] =
|
||||||
|
premultiplier(to_linear(input_image[4 * i + j]), input_image[4 * i + 3]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
let mut resizer = resize::new(
|
let mut resizer = resize::new(
|
||||||
input_width,
|
input_width,
|
||||||
input_height,
|
input_height,
|
||||||
@@ -48,5 +102,20 @@ pub fn resize(
|
|||||||
let mut output_image = Vec::<u8>::with_capacity(num_output_pixels * 4);
|
let mut output_image = Vec::<u8>::with_capacity(num_output_pixels * 4);
|
||||||
output_image.resize(num_output_pixels * 4, 0);
|
output_image.resize(num_output_pixels * 4, 0);
|
||||||
resizer.resize(input_image.as_slice(), output_image.as_mut_slice());
|
resizer.resize(input_image.as_slice(), output_image.as_mut_slice());
|
||||||
|
|
||||||
|
if premultiply || color_space_conversion {
|
||||||
|
for i in 0..num_output_pixels {
|
||||||
|
for j in 0..3 {
|
||||||
|
// We don’t need to worry about division by zero, as division by zero
|
||||||
|
// is well-defined on floats to return ±Inf. ±Inf is converted to 0
|
||||||
|
// when casting to integers.
|
||||||
|
output_image[4 * i + j] = to_color_space(demultiplier(
|
||||||
|
output_image[4 * i + j],
|
||||||
|
output_image[4 * i + 3],
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return output_image;
|
return output_image;
|
||||||
}
|
}
|
||||||
|
|||||||
29
codecs/resize/src/srgb.rs
Normal file
29
codecs/resize/src/srgb.rs
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
pub trait Clamp: std::cmp::PartialOrd + Sized {
|
||||||
|
fn clamp(self, min: Self, max: Self) -> Self {
|
||||||
|
if self.lt(&min) {
|
||||||
|
min
|
||||||
|
} else if self.gt(&max) {
|
||||||
|
max
|
||||||
|
} else {
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Clamp for f32 {}
|
||||||
|
|
||||||
|
pub fn srgb_to_linear(v: f32) -> f32 {
|
||||||
|
if v < 0.04045 {
|
||||||
|
v / 12.92
|
||||||
|
} else {
|
||||||
|
((v + 0.055) / 1.055).powf(2.4).clamp(0.0, 1.0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn linear_to_srgb(v: f32) -> f32 {
|
||||||
|
if v < 0.0031308 {
|
||||||
|
v * 12.92
|
||||||
|
} else {
|
||||||
|
(1.055 * v.powf(1.0 / 2.4) - 0.055).clamp(0.0, 1.0)
|
||||||
|
}
|
||||||
|
}
|
||||||
3836
package-lock.json
generated
3836
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
24
package.json
24
package.json
@@ -1,12 +1,13 @@
|
|||||||
{
|
{
|
||||||
"private": true,
|
"private": true,
|
||||||
"name": "squoosh",
|
"name": "squoosh",
|
||||||
"version": "1.4.0",
|
"version": "1.6.0",
|
||||||
"license": "apache-2.0",
|
"license": "apache-2.0",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
"build:sdk": "microbundle --compress -f es -o build/sdk.mjs -i src/sdk.ts",
|
||||||
"start": "webpack-dev-server --host 0.0.0.0 --hot",
|
"start": "webpack-dev-server --host 0.0.0.0 --hot",
|
||||||
"build": "webpack -p",
|
"build": "webpack -p && npm run build:sdk",
|
||||||
"lint": "tslint -c tslint.json -p tsconfig.json -t verbose",
|
"lint": "tslint -c tslint.json -p tsconfig.json -t verbose 'src/**/*.{ts,tsx,js,jsx}'",
|
||||||
"lintfix": "tslint -c tslint.json -p tsconfig.json -t verbose --fix 'src/**/*.{ts,tsx,js,jsx}'",
|
"lintfix": "tslint -c tslint.json -p tsconfig.json -t verbose --fix 'src/**/*.{ts,tsx,js,jsx}'",
|
||||||
"sizereport": "node config/size-report.js"
|
"sizereport": "node config/size-report.js"
|
||||||
},
|
},
|
||||||
@@ -16,18 +17,18 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/node": "10.12.29",
|
"@types/node": "10.14.1",
|
||||||
"@types/pretty-bytes": "5.1.0",
|
"@types/pretty-bytes": "5.1.0",
|
||||||
"@types/webassembly-js-api": "0.0.2",
|
"@types/webassembly-js-api": "0.0.2",
|
||||||
"@webcomponents/custom-elements": "1.2.1",
|
"@webcomponents/custom-elements": "1.2.1",
|
||||||
"@webpack-cli/serve": "0.1.3",
|
"@webpack-cli/serve": "0.1.3",
|
||||||
"assets-webpack-plugin": "3.9.10",
|
"assets-webpack-plugin": "3.9.10",
|
||||||
"chokidar": "2.1.2",
|
|
||||||
"chalk": "2.4.2",
|
"chalk": "2.4.2",
|
||||||
|
"chokidar": "2.1.2",
|
||||||
"classnames": "2.2.6",
|
"classnames": "2.2.6",
|
||||||
"clean-webpack-plugin": "1.0.1",
|
"clean-webpack-plugin": "1.0.1",
|
||||||
"comlink": "3.1.1",
|
"copy-webpack-plugin": "5.0.1",
|
||||||
"copy-webpack-plugin": "5.0.0",
|
"comlink": "^3.2.0",
|
||||||
"critters-webpack-plugin": "2.3.0",
|
"critters-webpack-plugin": "2.3.0",
|
||||||
"css-loader": "1.0.1",
|
"css-loader": "1.0.1",
|
||||||
"ejs": "2.6.1",
|
"ejs": "2.6.1",
|
||||||
@@ -41,6 +42,7 @@
|
|||||||
"idb-keyval": "3.1.0",
|
"idb-keyval": "3.1.0",
|
||||||
"linkstate": "1.1.1",
|
"linkstate": "1.1.1",
|
||||||
"loader-utils": "1.2.3",
|
"loader-utils": "1.2.3",
|
||||||
|
"microbundle": "^0.10.1",
|
||||||
"mini-css-extract-plugin": "0.5.0",
|
"mini-css-extract-plugin": "0.5.0",
|
||||||
"minimatch": "3.0.4",
|
"minimatch": "3.0.4",
|
||||||
"node-fetch": "2.3.0",
|
"node-fetch": "2.3.0",
|
||||||
@@ -51,7 +53,7 @@
|
|||||||
"prerender-loader": "1.3.0",
|
"prerender-loader": "1.3.0",
|
||||||
"pretty-bytes": "5.1.0",
|
"pretty-bytes": "5.1.0",
|
||||||
"progress-bar-webpack-plugin": "1.12.1",
|
"progress-bar-webpack-plugin": "1.12.1",
|
||||||
"raw-loader": "1.0.0",
|
"raw-loader": "2.0.0",
|
||||||
"readdirp": "2.2.1",
|
"readdirp": "2.2.1",
|
||||||
"sass-loader": "7.1.0",
|
"sass-loader": "7.1.0",
|
||||||
"script-ext-html-webpack-plugin": "2.1.3",
|
"script-ext-html-webpack-plugin": "2.1.3",
|
||||||
@@ -59,16 +61,16 @@
|
|||||||
"style-loader": "0.23.1",
|
"style-loader": "0.23.1",
|
||||||
"terser-webpack-plugin": "1.2.3",
|
"terser-webpack-plugin": "1.2.3",
|
||||||
"ts-loader": "5.3.3",
|
"ts-loader": "5.3.3",
|
||||||
"tslint": "5.13.1",
|
"tslint": "5.14.0",
|
||||||
"tslint-config-airbnb": "5.11.1",
|
"tslint-config-airbnb": "5.11.1",
|
||||||
"tslint-config-semistandard": "7.0.0",
|
"tslint-config-semistandard": "7.0.0",
|
||||||
"tslint-react": "3.6.0",
|
"tslint-react": "3.6.0",
|
||||||
"typed-css-modules": "0.4.1",
|
"typed-css-modules": "0.4.2",
|
||||||
"typescript": "3.3.3333",
|
"typescript": "3.3.3333",
|
||||||
"url-loader": "1.1.2",
|
"url-loader": "1.1.2",
|
||||||
"webpack": "4.28.0",
|
"webpack": "4.28.0",
|
||||||
"webpack-bundle-analyzer": "3.1.0",
|
"webpack-bundle-analyzer": "3.1.0",
|
||||||
"webpack-cli": "3.2.3",
|
"webpack-cli": "3.3.0",
|
||||||
"webpack-dev-server": "3.2.1",
|
"webpack-dev-server": "3.2.1",
|
||||||
"worker-plugin": "3.1.0"
|
"worker-plugin": "3.1.0"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
import { h, Component } from 'preact';
|
import { h, Component } from 'preact';
|
||||||
import linkState from 'linkstate';
|
import linkState from 'linkstate';
|
||||||
import { bind, linkRef } from '../../lib/initial-util';
|
import { bind, linkRef } from '../../lib/initial-util';
|
||||||
import { inputFieldValueAsNumber, inputFieldValue, preventDefault } from '../../lib/util';
|
import {
|
||||||
import { ResizeOptions } from './processor-meta';
|
inputFieldValueAsNumber, inputFieldValue, preventDefault, inputFieldChecked,
|
||||||
|
} from '../../lib/util';
|
||||||
|
import { ResizeOptions, isWorkerOptions } from './processor-meta';
|
||||||
import * as style from '../../components/Options/style.scss';
|
import * as style from '../../components/Options/style.scss';
|
||||||
import Checkbox from '../../components/checkbox';
|
import Checkbox from '../../components/checkbox';
|
||||||
import Expander from '../../components/expander';
|
import Expander from '../../components/expander';
|
||||||
@@ -38,6 +40,8 @@ export default class ResizerOptions extends Component<Props, State> {
|
|||||||
width: inputFieldValueAsNumber(width),
|
width: inputFieldValueAsNumber(width),
|
||||||
height: inputFieldValueAsNumber(height),
|
height: inputFieldValueAsNumber(height),
|
||||||
method: form.resizeMethod.value,
|
method: form.resizeMethod.value,
|
||||||
|
premultiply: inputFieldChecked(form.premultiply, true),
|
||||||
|
linearRGB: inputFieldChecked(form.linearRGB, true),
|
||||||
// Casting, as the formfield only returns the correct values.
|
// Casting, as the formfield only returns the correct values.
|
||||||
fitMethod: inputFieldValue(form.fitMethod, options.fitMethod) as ResizeOptions['fitMethod'],
|
fitMethod: inputFieldValue(form.fitMethod, options.fitMethod) as ResizeOptions['fitMethod'],
|
||||||
};
|
};
|
||||||
@@ -90,7 +94,7 @@ export default class ResizerOptions extends Component<Props, State> {
|
|||||||
<option value="lanczos3">Lanczos3</option>
|
<option value="lanczos3">Lanczos3</option>
|
||||||
<option value="mitchell">Mitchell</option>
|
<option value="mitchell">Mitchell</option>
|
||||||
<option value="catrom">Catmull-Rom</option>
|
<option value="catrom">Catmull-Rom</option>
|
||||||
<option value="triangle">Triangle</option>
|
<option value="triangle">Triangle (bilinear)</option>
|
||||||
<option value="browser-pixelated">Browser pixelated</option>
|
<option value="browser-pixelated">Browser pixelated</option>
|
||||||
<option value="browser-low">Browser low quality</option>
|
<option value="browser-low">Browser low quality</option>
|
||||||
<option value="browser-medium">Browser medium quality</option>
|
<option value="browser-medium">Browser medium quality</option>
|
||||||
@@ -121,6 +125,30 @@ export default class ResizerOptions extends Component<Props, State> {
|
|||||||
onInput={this.onHeightInput}
|
onInput={this.onHeightInput}
|
||||||
/>
|
/>
|
||||||
</label>
|
</label>
|
||||||
|
<Expander>
|
||||||
|
{isWorkerOptions(options) ?
|
||||||
|
<label class={style.optionInputFirst}>
|
||||||
|
<Checkbox
|
||||||
|
name="premultiply"
|
||||||
|
checked={options.premultiply}
|
||||||
|
onChange={this.onChange}
|
||||||
|
/>
|
||||||
|
Premultiply alpha channel
|
||||||
|
</label>
|
||||||
|
: null
|
||||||
|
}
|
||||||
|
{isWorkerOptions(options) ?
|
||||||
|
<label class={style.optionInputFirst}>
|
||||||
|
<Checkbox
|
||||||
|
name="linearRGB"
|
||||||
|
checked={options.linearRGB}
|
||||||
|
onChange={this.onChange}
|
||||||
|
/>
|
||||||
|
Linear RGB
|
||||||
|
</label>
|
||||||
|
: null
|
||||||
|
}
|
||||||
|
</Expander>
|
||||||
<label class={style.optionInputFirst}>
|
<label class={style.optionInputFirst}>
|
||||||
<Checkbox
|
<Checkbox
|
||||||
name="maintainAspect"
|
name="maintainAspect"
|
||||||
|
|||||||
@@ -1,25 +1,38 @@
|
|||||||
type BrowserResizeMethods = 'browser-pixelated' | 'browser-low' | 'browser-medium' | 'browser-high';
|
type BrowserResizeMethods = 'browser-pixelated' | 'browser-low' | 'browser-medium' | 'browser-high';
|
||||||
type WorkerResizeMethods = 'point' | 'triangle' | 'catrom' | 'mitchell' | 'lanczos3';
|
type WorkerResizeMethods = 'triangle' | 'catrom' | 'mitchell' | 'lanczos3';
|
||||||
|
const workerResizeMethods: WorkerResizeMethods[] = ['triangle', 'catrom', 'mitchell', 'lanczos3'];
|
||||||
|
|
||||||
export interface ResizeOptions {
|
export type ResizeOptions = BrowserResizeOptions | WorkerResizeOptions | VectorResizeOptions;
|
||||||
|
|
||||||
|
export interface ResizeOptionsCommon {
|
||||||
width: number;
|
width: number;
|
||||||
height: number;
|
height: number;
|
||||||
method: 'vector' | BrowserResizeMethods | WorkerResizeMethods;
|
|
||||||
fitMethod: 'stretch' | 'contain';
|
fitMethod: 'stretch' | 'contain';
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface BrowserResizeOptions extends ResizeOptions {
|
export interface BrowserResizeOptions extends ResizeOptionsCommon {
|
||||||
method: BrowserResizeMethods;
|
method: BrowserResizeMethods;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface WorkerResizeOptions extends ResizeOptions {
|
export interface WorkerResizeOptions extends ResizeOptionsCommon {
|
||||||
method: WorkerResizeMethods;
|
method: WorkerResizeMethods;
|
||||||
|
premultiply: boolean;
|
||||||
|
linearRGB: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface VectorResizeOptions extends ResizeOptions {
|
export interface VectorResizeOptions extends ResizeOptionsCommon {
|
||||||
method: 'vector';
|
method: 'vector';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return whether a set of options are worker resize options.
|
||||||
|
*
|
||||||
|
* @param opts
|
||||||
|
*/
|
||||||
|
export function isWorkerOptions(opts: ResizeOptions): opts is WorkerResizeOptions {
|
||||||
|
return (workerResizeMethods as string[]).includes(opts.method);
|
||||||
|
}
|
||||||
|
|
||||||
export const defaultOptions: ResizeOptions = {
|
export const defaultOptions: ResizeOptions = {
|
||||||
// Width and height will always default to the image size.
|
// Width and height will always default to the image size.
|
||||||
// This is set elsewhere.
|
// This is set elsewhere.
|
||||||
@@ -28,4 +41,6 @@ export const defaultOptions: ResizeOptions = {
|
|||||||
// This will be set to 'vector' if the input is SVG.
|
// This will be set to 'vector' if the input is SVG.
|
||||||
method: 'lanczos3',
|
method: 'lanczos3',
|
||||||
fitMethod: 'stretch',
|
fitMethod: 'stretch',
|
||||||
|
premultiply: true,
|
||||||
|
linearRGB: true,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -45,7 +45,7 @@ export async function resize(data: ImageData, opts: WorkerResizeOptions): Promis
|
|||||||
|
|
||||||
const result = wasm_bindgen.resize(
|
const result = wasm_bindgen.resize(
|
||||||
new Uint8Array(input.data.buffer), input.width, input.height, opts.width, opts.height,
|
new Uint8Array(input.data.buffer), input.width, input.height, opts.width, opts.height,
|
||||||
resizeMethods.indexOf(opts.method),
|
resizeMethods.indexOf(opts.method), opts.premultiply, opts.linearRGB,
|
||||||
);
|
);
|
||||||
|
|
||||||
return new ImageData(new Uint8ClampedArray(result.buffer), opts.width, opts.height);
|
return new ImageData(new Uint8ClampedArray(result.buffer), opts.width, opts.height);
|
||||||
|
|||||||
106
src/components/App/client-api.ts
Normal file
106
src/components/App/client-api.ts
Normal file
@@ -0,0 +1,106 @@
|
|||||||
|
import App from './index';
|
||||||
|
import { SquooshStartEventType, SquooshSideEventType } from '../compress/index';
|
||||||
|
|
||||||
|
import { expose } from 'comlink';
|
||||||
|
|
||||||
|
export interface ReadyMessage {
|
||||||
|
type: 'READY';
|
||||||
|
version: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function exposeAPI(app: App) {
|
||||||
|
if (window === top) {
|
||||||
|
// Someone opened Squoosh in a window rather than an iframe.
|
||||||
|
// This can be deceiving and we won’t allow that.
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
self.parent.postMessage({ type: 'READY', version: MAJOR_VERSION }, '*');
|
||||||
|
self.addEventListener('message', (event: MessageEvent) => {
|
||||||
|
if (event.data !== 'READY?') {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
event.stopImmediatePropagation();
|
||||||
|
self.parent.postMessage({ type: 'READY', version: MAJOR_VERSION } as ReadyMessage, '*');
|
||||||
|
});
|
||||||
|
expose(new API(app), self.parent);
|
||||||
|
}
|
||||||
|
|
||||||
|
function addRemovableGlobalListener<
|
||||||
|
K extends keyof GlobalEventHandlersEventMap
|
||||||
|
>(name: K, listener: (ev: GlobalEventHandlersEventMap[K]) => void): () => void {
|
||||||
|
document.addEventListener(name, listener);
|
||||||
|
return () => document.removeEventListener(name, listener);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The API class contains the methods that are exposed via Comlink to the
|
||||||
|
* outside world.
|
||||||
|
*/
|
||||||
|
export class API {
|
||||||
|
/**
|
||||||
|
* Internal constructor. Do not call.
|
||||||
|
*/
|
||||||
|
constructor(private _app: App) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Loads a given file into Squoosh.
|
||||||
|
* @param blob The `Blob` to load
|
||||||
|
* @param name The name of the file. The extension of this name will be used
|
||||||
|
* to deterime which decoder to use.
|
||||||
|
*/
|
||||||
|
setFile(blob: Blob, name: string) {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
document.addEventListener(SquooshStartEventType.START, () => resolve(), {
|
||||||
|
once: true,
|
||||||
|
});
|
||||||
|
this._app.openFile(new File([blob], name));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Grabs one side from Squoosh as a `File`.
|
||||||
|
* @param side The side which to grab. 0 = left, 1 = right.
|
||||||
|
*/
|
||||||
|
async getBlob(side: 0 | 1) {
|
||||||
|
if (!this._app.state.file || !this._app.compressInstance) {
|
||||||
|
throw new Error('No file has been loaded');
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
!this._app.compressInstance!.state.loading &&
|
||||||
|
!this._app.compressInstance!.state.sides[side].loading
|
||||||
|
) {
|
||||||
|
return this._app.compressInstance!.state.sides[side].file;
|
||||||
|
}
|
||||||
|
|
||||||
|
const listeners: ReturnType<typeof addRemovableGlobalListener>[] = [];
|
||||||
|
|
||||||
|
const r = new Promise((resolve, reject) => {
|
||||||
|
listeners.push(
|
||||||
|
addRemovableGlobalListener(SquooshSideEventType.DONE, (event) => {
|
||||||
|
if (event.side !== side) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
resolve(this._app.compressInstance!.state.sides[side].file);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
listeners.push(
|
||||||
|
addRemovableGlobalListener(SquooshSideEventType.ABORT, (event) => {
|
||||||
|
if (event.side !== side) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
reject(new DOMException('Aborted', 'AbortError'));
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
listeners.push(
|
||||||
|
addRemovableGlobalListener(SquooshSideEventType.ERROR, (event) => {
|
||||||
|
if (event.side !== side) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
reject(event.error);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
r.then(() => listeners.forEach(remove => remove()));
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -36,6 +36,7 @@ export default class App extends Component<Props, State> {
|
|||||||
file: undefined,
|
file: undefined,
|
||||||
Compress: undefined,
|
Compress: undefined,
|
||||||
};
|
};
|
||||||
|
compressInstance?: import('../compress').default;
|
||||||
|
|
||||||
snackbar?: SnackBarElement;
|
snackbar?: SnackBarElement;
|
||||||
|
|
||||||
@@ -69,6 +70,14 @@ export default class App extends Component<Props, State> {
|
|||||||
});
|
});
|
||||||
|
|
||||||
window.addEventListener('popstate', this.onPopState);
|
window.addEventListener('popstate', this.onPopState);
|
||||||
|
import(
|
||||||
|
/* webpackChunkName: "client-api" */
|
||||||
|
'./client-api').then(m => m.exposeAPI(this));
|
||||||
|
}
|
||||||
|
|
||||||
|
@bind openFile(file: File | Fileish) {
|
||||||
|
this.openEditor();
|
||||||
|
this.setState({ file });
|
||||||
}
|
}
|
||||||
|
|
||||||
@bind
|
@bind
|
||||||
@@ -81,8 +90,7 @@ export default class App extends Component<Props, State> {
|
|||||||
|
|
||||||
@bind
|
@bind
|
||||||
private onIntroPickFile(file: File | Fileish) {
|
private onIntroPickFile(file: File | Fileish) {
|
||||||
this.openEditor();
|
return this.openFile(file);
|
||||||
this.setState({ file });
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@bind
|
@bind
|
||||||
@@ -110,7 +118,12 @@ export default class App extends Component<Props, State> {
|
|||||||
{!isEditorOpen
|
{!isEditorOpen
|
||||||
? <Intro onFile={this.onIntroPickFile} showSnack={this.showSnack} />
|
? <Intro onFile={this.onIntroPickFile} showSnack={this.showSnack} />
|
||||||
: (Compress)
|
: (Compress)
|
||||||
? <Compress file={file!} showSnack={this.showSnack} onBack={back} />
|
? <Compress
|
||||||
|
ref={i => this.compressInstance = i}
|
||||||
|
file={file!}
|
||||||
|
showSnack={this.showSnack}
|
||||||
|
onBack={back}
|
||||||
|
/>
|
||||||
: <loading-spinner class={style.appLoader}/>
|
: <loading-spinner class={style.appLoader}/>
|
||||||
}
|
}
|
||||||
<snack-bar ref={linkRef(this, 'snackbar')} />
|
<snack-bar ref={linkRef(this, 'snackbar')} />
|
||||||
|
|||||||
@@ -18,23 +18,13 @@ import * as browserTIFF from '../../codecs/browser-tiff/encoder-meta';
|
|||||||
import * as browserJP2 from '../../codecs/browser-jp2/encoder-meta';
|
import * as browserJP2 from '../../codecs/browser-jp2/encoder-meta';
|
||||||
import * as browserBMP from '../../codecs/browser-bmp/encoder-meta';
|
import * as browserBMP from '../../codecs/browser-bmp/encoder-meta';
|
||||||
import * as browserPDF from '../../codecs/browser-pdf/encoder-meta';
|
import * as browserPDF from '../../codecs/browser-pdf/encoder-meta';
|
||||||
import {
|
import { EncoderState, EncoderType, EncoderOptions, encoderMap } from '../../codecs/encoders';
|
||||||
EncoderState,
|
import { PreprocessorState, defaultPreprocessorState } from '../../codecs/preprocessors';
|
||||||
EncoderType,
|
|
||||||
EncoderOptions,
|
|
||||||
encoderMap,
|
|
||||||
} from '../../codecs/encoders';
|
|
||||||
import {
|
|
||||||
PreprocessorState,
|
|
||||||
defaultPreprocessorState,
|
|
||||||
} from '../../codecs/preprocessors';
|
|
||||||
import { decodeImage } from '../../codecs/decoders';
|
import { decodeImage } from '../../codecs/decoders';
|
||||||
import { cleanMerge, cleanSet } from '../../lib/clean-modify';
|
import { cleanMerge, cleanSet } from '../../lib/clean-modify';
|
||||||
import Processor from '../../codecs/processor';
|
import Processor from '../../codecs/processor';
|
||||||
import {
|
import {
|
||||||
VectorResizeOptions,
|
BrowserResizeOptions, isWorkerOptions as isWorkerResizeOptions,
|
||||||
BrowserResizeOptions,
|
|
||||||
WorkerResizeOptions,
|
|
||||||
} from '../../codecs/resize/processor-meta';
|
} from '../../codecs/resize/processor-meta';
|
||||||
import './custom-els/MultiPanel';
|
import './custom-els/MultiPanel';
|
||||||
import Results from '../results';
|
import Results from '../results';
|
||||||
@@ -42,6 +32,51 @@ import { ExpandIcon, CopyAcrossIconProps } from '../../lib/icons';
|
|||||||
import SnackBarElement from '../../lib/SnackBar';
|
import SnackBarElement from '../../lib/SnackBar';
|
||||||
import { InputProcessorState, defaultInputProcessorState } from '../../codecs/input-processors';
|
import { InputProcessorState, defaultInputProcessorState } from '../../codecs/input-processors';
|
||||||
|
|
||||||
|
// Safari and Edge don't quite support extending Event, this works around it.
|
||||||
|
function fixExtendedEvent(instance: Event, type: Function) {
|
||||||
|
if (!(instance instanceof type)) {
|
||||||
|
Object.setPrototypeOf(instance, type.prototype);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
export enum SquooshStartEventType {
|
||||||
|
START = 'squoosh:start',
|
||||||
|
}
|
||||||
|
export class SquooshStartEvent extends Event {
|
||||||
|
constructor(init?: EventInit) {
|
||||||
|
super(SquooshStartEventType.START, init);
|
||||||
|
fixExtendedEvent(this, SquooshStartEvent);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const enum SquooshSideEventType {
|
||||||
|
DONE = 'squoosh:done',
|
||||||
|
ABORT = 'squoosh:abort',
|
||||||
|
ERROR = 'squoosh:error',
|
||||||
|
}
|
||||||
|
export interface SquooshSideEventInit extends EventInit {
|
||||||
|
side: 0|1;
|
||||||
|
error?: Error;
|
||||||
|
}
|
||||||
|
export class SquooshSideEvent extends Event {
|
||||||
|
public side: 0|1;
|
||||||
|
public error?: Error;
|
||||||
|
constructor(name: SquooshSideEventType, init: SquooshSideEventInit) {
|
||||||
|
super(name, init);
|
||||||
|
fixExtendedEvent(this, SquooshSideEvent);
|
||||||
|
this.side = init.side;
|
||||||
|
this.error = init.error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
declare global {
|
||||||
|
interface GlobalEventHandlersEventMap {
|
||||||
|
[SquooshStartEventType.START]: SquooshStartEvent;
|
||||||
|
[SquooshSideEventType.DONE]: SquooshSideEvent;
|
||||||
|
[SquooshSideEventType.ABORT]: SquooshSideEvent;
|
||||||
|
[SquooshSideEventType.ERROR]: SquooshSideEvent;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export interface SourceImage {
|
export interface SourceImage {
|
||||||
file: File | Fileish;
|
file: File | Fileish;
|
||||||
decoded: ImageData;
|
decoded: ImageData;
|
||||||
@@ -114,12 +149,12 @@ async function preprocessImage(
|
|||||||
if (preprocessData.resize.method === 'vector' && source.vectorImage) {
|
if (preprocessData.resize.method === 'vector' && source.vectorImage) {
|
||||||
result = processor.vectorResize(
|
result = processor.vectorResize(
|
||||||
source.vectorImage,
|
source.vectorImage,
|
||||||
preprocessData.resize as VectorResizeOptions,
|
preprocessData.resize,
|
||||||
);
|
);
|
||||||
} else if (preprocessData.resize.method.startsWith('browser-')) {
|
} else if (isWorkerResizeOptions(preprocessData.resize)) {
|
||||||
result = processor.resize(result, preprocessData.resize as BrowserResizeOptions);
|
result = await processor.workerResize(result, preprocessData.resize);
|
||||||
} else {
|
} else {
|
||||||
result = await processor.workerResize(result, preprocessData.resize as WorkerResizeOptions);
|
result = processor.resize(result, preprocessData.resize as BrowserResizeOptions);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (preprocessData.quantizer.enabled) {
|
if (preprocessData.quantizer.enabled) {
|
||||||
@@ -405,8 +440,7 @@ export default class Compress extends Component<Props, State> {
|
|||||||
// Either processor is good enough here.
|
// Either processor is good enough here.
|
||||||
const processor = this.leftProcessor;
|
const processor = this.leftProcessor;
|
||||||
|
|
||||||
this.setState({ loadingCounter, loading: true });
|
this.setState({ loadingCounter, loading: true }, this.signalLoadingStart);
|
||||||
|
|
||||||
// Abort any current encode jobs, as they're redundant now.
|
// Abort any current encode jobs, as they're redundant now.
|
||||||
this.leftProcessor.abortCurrent();
|
this.leftProcessor.abortCurrent();
|
||||||
this.rightProcessor.abortCurrent();
|
this.rightProcessor.abortCurrent();
|
||||||
@@ -484,6 +518,35 @@ export default class Compress extends Component<Props, State> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@bind
|
||||||
|
private dispatchSideEvent(type: SquooshSideEventType, init: SquooshSideEventInit) {
|
||||||
|
document.dispatchEvent(
|
||||||
|
new SquooshSideEvent(type, init),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@bind
|
||||||
|
private signalLoadingStart() {
|
||||||
|
document.dispatchEvent(
|
||||||
|
new SquooshStartEvent(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@bind
|
||||||
|
private signalProcessingDone(side: 0|1) {
|
||||||
|
this.dispatchSideEvent(SquooshSideEventType.DONE, { side });
|
||||||
|
}
|
||||||
|
|
||||||
|
@bind
|
||||||
|
private signalProcessingAbort(side: 0|1) {
|
||||||
|
this.dispatchSideEvent(SquooshSideEventType.ABORT, { side });
|
||||||
|
}
|
||||||
|
|
||||||
|
@bind
|
||||||
|
private signalProcessingError(side: 0|1, msg: string) {
|
||||||
|
this.dispatchSideEvent(SquooshSideEventType.ERROR, { side, error: new Error(msg) });
|
||||||
|
}
|
||||||
|
|
||||||
private async updateImage(index: number, options: UpdateImageOptions = {}): Promise<void> {
|
private async updateImage(index: number, options: UpdateImageOptions = {}): Promise<void> {
|
||||||
const {
|
const {
|
||||||
skipPreprocessing = false,
|
skipPreprocessing = false,
|
||||||
@@ -545,8 +608,13 @@ export default class Compress extends Component<Props, State> {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (err.name === 'AbortError') return;
|
if (err.name === 'AbortError') {
|
||||||
this.props.showSnack(`Processing error (type=${settings.encoderState.type}): ${err}`);
|
this.signalProcessingAbort(index as 0|1);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const errorMsg = `Processing error (type=${settings.encoderState.type}): ${err}`;
|
||||||
|
this.signalProcessingError(index as 0|1, errorMsg);
|
||||||
|
this.props.showSnack(errorMsg);
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -569,7 +637,7 @@ export default class Compress extends Component<Props, State> {
|
|||||||
encodedSettings: settings,
|
encodedSettings: settings,
|
||||||
});
|
});
|
||||||
|
|
||||||
this.setState({ sides });
|
this.setState({ sides }, () => this.signalProcessingDone(index as 0|1));
|
||||||
}
|
}
|
||||||
|
|
||||||
render({ onBack }: Props, { loading, sides, source, mobileView }: State) {
|
render({ onBack }: Props, { loading, sides, source, mobileView }: State) {
|
||||||
|
|||||||
1
src/missing-types.d.ts
vendored
1
src/missing-types.d.ts
vendored
@@ -34,6 +34,7 @@ declare module 'url-loader!*' {
|
|||||||
}
|
}
|
||||||
|
|
||||||
declare var VERSION: string;
|
declare var VERSION: string;
|
||||||
|
declare var MAJOR_VERSION: string;
|
||||||
|
|
||||||
declare var ga: {
|
declare var ga: {
|
||||||
(...args: any[]): void;
|
(...args: any[]): void;
|
||||||
|
|||||||
41
src/sdk.ts
Normal file
41
src/sdk.ts
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
import { proxy, ProxyResult } from 'comlink';
|
||||||
|
|
||||||
|
import { API, ReadyMessage } from './components/App/client-api';
|
||||||
|
|
||||||
|
// @ts-ignore
|
||||||
|
import { version } from '../package.json';
|
||||||
|
const MAJOR_VERSION = (version.split('.')[0] as string);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This function will load an iFrame
|
||||||
|
* @param {HTMLIFrameElement} ifr iFrame that will be used to load squoosh
|
||||||
|
* @param {string} src URL of squoosh instance to use
|
||||||
|
*/
|
||||||
|
export default async function loader(
|
||||||
|
ifr: HTMLIFrameElement,
|
||||||
|
src: string = 'https://squoosh.app',
|
||||||
|
): Promise<ProxyResult<API>> {
|
||||||
|
ifr.src = src;
|
||||||
|
await new Promise(resolve => (ifr.onload = resolve));
|
||||||
|
ifr.contentWindow!.postMessage('READY?', '*');
|
||||||
|
await new Promise((resolve) => {
|
||||||
|
window.addEventListener('message', function l(ev) {
|
||||||
|
const msg = ev.data as ReadyMessage;
|
||||||
|
if (!msg || msg.type !== 'READY') {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (msg.version !== MAJOR_VERSION) {
|
||||||
|
throw Error(
|
||||||
|
`Version mismatch. SDK version ${MAJOR_VERSION}, Squoosh version ${
|
||||||
|
msg.version
|
||||||
|
}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
ev.stopPropagation();
|
||||||
|
window.removeEventListener('message', l);
|
||||||
|
resolve();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
return proxy(ifr.contentWindow!);
|
||||||
|
}
|
||||||
@@ -263,6 +263,7 @@ module.exports = async function (_, env) {
|
|||||||
// Inline constants during build, so they can be folded by UglifyJS.
|
// Inline constants during build, so they can be folded by UglifyJS.
|
||||||
new webpack.DefinePlugin({
|
new webpack.DefinePlugin({
|
||||||
VERSION: JSON.stringify(VERSION),
|
VERSION: JSON.stringify(VERSION),
|
||||||
|
MAJOR_VERSION: JSON.stringify(VERSION.split(".")[0]),
|
||||||
// We set node.process=false later in this config.
|
// We set node.process=false later in this config.
|
||||||
// Here we make sure if (process && process.foo) still works:
|
// Here we make sure if (process && process.foo) still works:
|
||||||
process: '{}'
|
process: '{}'
|
||||||
|
|||||||
Reference in New Issue
Block a user