Merge branch 'master' into kosmos

# Conflicts:
#	release/assets/main-B0NMnAnz.js
#	release/assets/modules-4-12-Cm6sjFOx.js
#	release/assets/modules-4-12-CvJU34cM.js
#	release/assets/modules-4-12-QkPgoTHI.js
#	release/index.html
This commit is contained in:
raucao committed 2026-11-28 02:57:59 +04:00
commit 90929f8ca3
12 files changed
+933 -318

No files matched your search

+30 -26
View File
@@ -10,7 +10,7 @@ import { isMobile } from '../utils/device';
import Blurhash from './blurhash';
const MAX_IMAGE_DIMENSION = 1920;
const IMAGE_QUALITY = 0.9;
const IMAGE_QUALITY = 0.85;
const MAX_THUMBNAIL_DIMENSION = 350;
const THUMBNAIL_QUALITY = 0.9;
@@ -46,30 +46,34 @@ export default class PlacePhotoUploadItem extends Component {
}
}
// Swap the preview from the raw (multi-megapixel) file URL to the small
// processed thumbnail, so the browser can release the decoded original.
updateThumbnailPreview(blob) {
if (this.thumbnailUrl) {
URL.revokeObjectURL(this.thumbnailUrl);
}
this.thumbnailUrl = URL.createObjectURL(blob);
}
uploadTask = task(async (file) => {
this.error = '';
this.statusText = 'Processing';
try {
// 1. Process main image and generate blurhash in worker
const mainData = await this.imageProcessor.process(
file,
MAX_IMAGE_DIMENSION,
IMAGE_QUALITY,
true // computeBlurhash
);
// 1. Process main image, thumbnail and blurhash in a single worker pass.
const { mainBlob, mainDim, thumbBlob, blurhash } =
await this.imageProcessor.processPhoto(file, {
maxDimension: MAX_IMAGE_DIMENSION,
quality: IMAGE_QUALITY,
thumbMaxDimension: MAX_THUMBNAIL_DIMENSION,
thumbQuality: THUMBNAIL_QUALITY,
computeBlurhash: true,
});
this.blurhash = mainData.blurhash;
this.blurhash = blurhash;
this.updateThumbnailPreview(thumbBlob);
// 2. Process thumbnail (no blurhash needed)
const thumbData = await this.imageProcessor.process(
file,
MAX_THUMBNAIL_DIMENSION,
THUMBNAIL_QUALITY,
false
);
// 3. Upload main image
// 4. Upload thumbnail
// 2. Upload main image
// 3. Upload thumbnail
let mainResult, thumbResult;
const isMobileDevice = isMobile();
@@ -85,20 +89,20 @@ export default class PlacePhotoUploadItem extends Component {
if (isMobileDevice) {
// Mobile: sequential uploads to preserve bandwidth and memory
mainResult = await this.blossom.upload(mainData.blob, {
mainResult = await this.blossom.upload(mainBlob, {
sequential: true,
onProgress: mainProgress,
});
thumbResult = await this.blossom.upload(thumbData.blob, {
thumbResult = await this.blossom.upload(thumbBlob, {
sequential: true,
onProgress: thumbProgress,
});
} else {
// Desktop: concurrent uploads
const mainUploadPromise = this.blossom.upload(mainData.blob, {
const mainUploadPromise = this.blossom.upload(mainBlob, {
onProgress: mainProgress,
});
const thumbUploadPromise = this.blossom.upload(thumbData.blob, {
const thumbUploadPromise = this.blossom.upload(thumbBlob, {
onProgress: thumbProgress,
});
@@ -114,9 +118,9 @@ export default class PlacePhotoUploadItem extends Component {
url: mainResult.url,
fallbackUrls: mainResult.fallbackUrls,
thumbUrl: thumbResult.url,
blurhash: mainData.blurhash,
blurhash,
type: 'image/jpeg',
dim: mainData.dim,
dim: mainDim,
hash: mainResult.hash,
thumbHash: thumbResult.hash,
});
@@ -135,7 +139,7 @@ export default class PlacePhotoUploadItem extends Component {
{{#if this.blurhash}}
<Blurhash @hash={{this.blurhash}} class="place-header-photo-blur" />
{{/if}}
<img src={{this.thumbnailUrl}} alt="thumbnail" />
<img src={{this.thumbnailUrl}} alt="thumbnail" decoding="async" />
{{#if this.uploadTask.isRunning}}
<div class="overlay">
+82 -23
View File
@@ -2,6 +2,33 @@ import Service from '@ember/service';
// We use the special Vite query parameter to load this as a web worker
import Worker from '../workers/image-processor?worker';
/**
* Scale `width`/`height` down to fit within `maxDimension` while preserving
* aspect ratio. Never upscales.
*
* @param {number} width
* @param {number} height
* @param {number} maxDimension
* @returns {{ width: number, height: number }}
*/
export function fitWithin(width, height, maxDimension) {
if (width <= maxDimension && height <= maxDimension) {
return { width, height };
}
if (width >= height) {
return {
width: maxDimension,
height: Math.round(height * (maxDimension / width)),
};
}
return {
width: Math.round(width * (maxDimension / height)),
height: maxDimension,
};
}
export default class ImageProcessorService extends Service {
_worker = null;
_callbacks = new Map();
@@ -25,13 +52,22 @@ export default class ImageProcessorService extends Service {
}
_handleMessage(e) {
const { id, success, blob, dim, blurhash, error } = e.data;
const {
id,
success,
mainBlob,
mainDim,
thumbBlob,
thumbDim,
blurhash,
error,
} = e.data;
const resolver = this._callbacks.get(id);
if (resolver) {
this._callbacks.delete(id);
if (success) {
resolver.resolve({ blob, dim, blurhash });
resolver.resolve({ mainBlob, mainDim, thumbBlob, thumbDim, blurhash });
} else {
resolver.reject(new Error(error));
}
@@ -71,45 +107,68 @@ export default class ImageProcessorService extends Service {
});
}
async process(file, maxDimension, quality, computeBlurhash = false) {
/**
* Process a photo in a single worker pass: decode the original once, resize
* it to the main and thumbnail dimensions, and (optionally) generate a
* BlurHash from a tiny downscale.
*
* @param {File|Blob} file
* @param {object} options
* @param {number} options.maxDimension Longest edge of the main image.
* @param {number} options.quality JPEG quality of the main image.
* @param {number} options.thumbMaxDimension Longest edge of the thumbnail.
* @param {number} options.thumbQuality JPEG quality of the thumbnail.
* @param {boolean} [options.computeBlurhash]
* @returns {Promise<{ mainBlob: Blob, mainDim: string, thumbBlob: Blob, thumbDim: string, blurhash: string|null }>}
*/
async processPhoto(file, options = {}) {
const {
maxDimension,
quality,
thumbMaxDimension,
thumbQuality,
computeBlurhash = false,
} = options;
if (!this._worker) {
// Fallback if worker initialization failed (e.g. incredibly old browsers)
throw new Error('Image processor worker is not available.');
}
try {
// 1. Get dimensions safely on the main thread
// 1. Get dimensions safely on the main thread.
const { width: origWidth, height: origHeight } =
await this._getImageDimensions(file);
// 2. Calculate aspect-ratio preserving dimensions
let targetWidth = origWidth;
let targetHeight = origHeight;
// 2. Calculate aspect-ratio preserving dimensions for both outputs.
const { width: mainWidth, height: mainHeight } = fitWithin(
origWidth,
origHeight,
maxDimension
);
const { width: thumbWidth, height: thumbHeight } = fitWithin(
origWidth,
origHeight,
thumbMaxDimension
);
if (origWidth > origHeight) {
if (origWidth > maxDimension) {
targetHeight = Math.round(origHeight * (maxDimension / origWidth));
targetWidth = maxDimension;
}
} else {
if (origHeight > maxDimension) {
targetWidth = Math.round(origWidth * (maxDimension / origHeight));
targetHeight = maxDimension;
}
}
// 3. Send to worker for processing
// 3. Send to worker for processing.
return new Promise((resolve, reject) => {
const id = ++this._msgId;
this._callbacks.set(id, { resolve, reject });
this._worker.postMessage({
type: 'PROCESS_IMAGE',
type: 'PROCESS_PHOTO',
id,
file,
targetWidth,
targetHeight,
origWidth,
origHeight,
mainWidth,
mainHeight,
quality,
thumbWidth,
thumbHeight,
thumbQuality,
computeBlurhash,
});
});
+216 -83
View File
@@ -1,101 +1,223 @@
import { encode } from 'blurhash';
self.onmessage = async (e) => {
// Ignore internal browser/Vite/extension pings that don't match our exact job signature
if (e.data?.type !== 'PROCESS_IMAGE') return;
// BlurHash 4x3 only encodes 12 low-frequency color components, so encoding from
// a tiny canvas produces a visually identical hash to encoding the full-size
// image — at a fraction of the cost. Marco renders the hash at 32x18
// (see app/components/blurhash.gjs), so 64px on the long edge is plenty.
const BLURHASH_MAX_DIMENSION = 64;
const { id, file, targetWidth, targetHeight, quality, computeBlurhash } =
e.data;
// Draw a decoded bitmap into a fresh OffscreenCanvas at the exact target size,
// then release the bitmap.
function drawBitmapToCanvas(bitmap, targetWidth, targetHeight) {
const canvas = new OffscreenCanvas(targetWidth, targetHeight);
const ctx = canvas.getContext('2d');
if (!ctx) {
throw new Error('Failed to get 2d context from OffscreenCanvas');
}
ctx.imageSmoothingEnabled = true;
ctx.imageSmoothingQuality = 'high';
ctx.drawImage(bitmap, 0, 0, targetWidth, targetHeight);
bitmap.close();
return canvas;
}
try {
let finalCanvas;
let finalCtx;
// Software scaling fallback used when the browser cannot (or refuses to) resize
// natively. Steps down by halves with bilinear filtering, releasing each
// intermediate canvas immediately, then makes one high-quality pass to the
// exact target. Avoids the old full-resolution duplicate canvas.
function steppedScale(source, targetWidth, targetHeight) {
const canHalve =
source.width * 0.5 > targetWidth && source.height * 0.5 > targetHeight;
// --- 1. Attempt Hardware Resizing (Happy Path) ---
try {
const resizedBitmap = await createImageBitmap(file, {
// Close enough to the target that a single pass is best quality.
if (!canHalve) {
return drawBitmapToCanvas(source, targetWidth, targetHeight);
}
// First halving straight from the decoded bitmap — no full-size copy.
let currentCanvas = new OffscreenCanvas(
Math.floor(source.width * 0.5),
Math.floor(source.height * 0.5)
);
let ctx = currentCanvas.getContext('2d');
ctx.imageSmoothingEnabled = true;
ctx.imageSmoothingQuality = 'medium';
ctx.drawImage(source, 0, 0, currentCanvas.width, currentCanvas.height);
source.close();
// Step down by halves until the next halving would undershoot the target.
while (
currentCanvas.width * 0.5 > targetWidth &&
currentCanvas.height * 0.5 > targetHeight
) {
const nextCanvas = new OffscreenCanvas(
Math.floor(currentCanvas.width * 0.5),
Math.floor(currentCanvas.height * 0.5)
);
const nextCtx = nextCanvas.getContext('2d');
nextCtx.imageSmoothingEnabled = true;
nextCtx.imageSmoothingQuality = 'medium';
nextCtx.drawImage(currentCanvas, 0, 0, nextCanvas.width, nextCanvas.height);
// Release the previous canvas' backing store immediately.
currentCanvas.width = 0;
currentCanvas.height = 0;
currentCanvas = nextCanvas;
}
// Final high-quality resize to the exact target.
const finalCanvas = new OffscreenCanvas(targetWidth, targetHeight);
const finalCtx = finalCanvas.getContext('2d');
finalCtx.imageSmoothingEnabled = true;
finalCtx.imageSmoothingQuality = 'high';
finalCtx.drawImage(currentCanvas, 0, 0, targetWidth, targetHeight);
currentCanvas.width = 0;
currentCanvas.height = 0;
return finalCanvas;
}
// Decode the original file once and resize it to the target dimensions.
//
// Strategy:
// 1. Try native/hardware resizing directly from the File.
// 2. If that throws (Android's `content://` File descriptor bug in workers),
// retry via an in-memory Blob so the browser can still DCT-scale natively.
// 3. Validate the browser actually honored the resize request; if not — or if
// both attempts failed — fall back to stepped software scaling, reusing the
// already-decoded bitmap where possible.
async function decodeResized(file, targetWidth, targetHeight, needsResize) {
const resizeOptions = needsResize
? {
resizeWidth: targetWidth,
resizeHeight: targetHeight,
resizeQuality: 'high',
});
finalCanvas = new OffscreenCanvas(targetWidth, targetHeight);
finalCtx = finalCanvas.getContext('2d');
if (!finalCtx) {
throw new Error('Failed to get 2d context from OffscreenCanvas');
}
finalCtx.drawImage(resizedBitmap, 0, 0, targetWidth, targetHeight);
resizedBitmap.close();
} catch (hwError) {
console.warn(
'Hardware resize failed, falling back to stepped software scaling:',
hwError
);
: {};
// --- 2. Fallback to Stepped Software Scaling (Robust Path) ---
// Bypass Android File descriptor bug by reading into memory
const buffer = await file.arrayBuffer();
const blob = new Blob([buffer], { type: file.type });
const isExactTarget = (bitmap) =>
bitmap.width === targetWidth && bitmap.height === targetHeight;
const source = await createImageBitmap(blob);
let srcWidth = source.width;
let srcHeight = source.height;
// 1. Happy path: decode + resize straight from the File.
try {
const bitmap = await createImageBitmap(file, resizeOptions);
return isExactTarget(bitmap)
? drawBitmapToCanvas(bitmap, targetWidth, targetHeight)
: steppedScale(bitmap, targetWidth, targetHeight);
} catch (fileError) {
console.warn(
'Hardware resize from File failed, retrying via in-memory Blob:',
fileError
);
}
let currentCanvas = new OffscreenCanvas(srcWidth, srcHeight);
let ctx = currentCanvas.getContext('2d');
// 2. Android workaround: read into memory and retry native resizing.
const buffer = await file.arrayBuffer();
const blob = new Blob([buffer], { type: file.type });
ctx.imageSmoothingEnabled = true;
ctx.imageSmoothingQuality = 'high';
ctx.drawImage(source, 0, 0);
try {
const bitmap = await createImageBitmap(blob, resizeOptions);
return isExactTarget(bitmap)
? drawBitmapToCanvas(bitmap, targetWidth, targetHeight)
: steppedScale(bitmap, targetWidth, targetHeight);
} catch (blobError) {
console.warn(
'Hardware resize from Blob failed, falling back to stepped software scaling:',
blobError
);
}
// Step down by halves until near target
while (
currentCanvas.width * 0.5 > targetWidth &&
currentCanvas.height * 0.5 > targetHeight
) {
const nextCanvas = new OffscreenCanvas(
Math.floor(currentCanvas.width * 0.5),
Math.floor(currentCanvas.height * 0.5)
);
const nextCtx = nextCanvas.getContext('2d');
// 3. Last resort: decode at full size and scale in steps.
const source = await createImageBitmap(blob);
return steppedScale(source, targetWidth, targetHeight);
}
nextCtx.imageSmoothingEnabled = true;
nextCtx.imageSmoothingQuality = 'high';
// Derive the thumbnail from the already-resized main canvas — the original file
// is never decoded a second time.
async function deriveThumbnail(mainCanvas, thumbWidth, thumbHeight) {
// Main image is already thumbnail-sized; reuse it as-is.
if (mainCanvas.width === thumbWidth && mainCanvas.height === thumbHeight) {
return mainCanvas;
}
nextCtx.drawImage(
currentCanvas,
0,
0,
nextCanvas.width,
nextCanvas.height
);
try {
const bitmap = await createImageBitmap(mainCanvas, {
resizeWidth: thumbWidth,
resizeHeight: thumbHeight,
resizeQuality: 'high',
});
return bitmap.width === thumbWidth && bitmap.height === thumbHeight
? drawBitmapToCanvas(bitmap, thumbWidth, thumbHeight)
: steppedScale(bitmap, thumbWidth, thumbHeight);
} catch (thumbError) {
console.warn(
'Native thumbnail resize failed, scaling from canvas:',
thumbError
);
const bitmap = await createImageBitmap(mainCanvas);
return steppedScale(bitmap, thumbWidth, thumbHeight);
}
}
currentCanvas = nextCanvas;
}
// Encode a BlurHash from a tiny, aspect-preserving downscale of the source.
function computeBlurhash(source) {
const scale = Math.min(
1,
BLURHASH_MAX_DIMENSION / Math.max(source.width, source.height)
);
const width = Math.max(1, Math.round(source.width * scale));
const height = Math.max(1, Math.round(source.height * scale));
// Final resize to exact target
finalCanvas = new OffscreenCanvas(targetWidth, targetHeight);
finalCtx = finalCanvas.getContext('2d');
const canvas = new OffscreenCanvas(width, height);
const ctx = canvas.getContext('2d', { willReadFrequently: true });
ctx.imageSmoothingEnabled = true;
ctx.imageSmoothingQuality = 'high';
ctx.drawImage(source, 0, 0, width, height);
finalCtx.imageSmoothingEnabled = true;
finalCtx.imageSmoothingQuality = 'high';
const imageData = ctx.getImageData(0, 0, width, height);
return encode(imageData.data, width, height, 4, 3);
}
finalCtx.drawImage(currentCanvas, 0, 0, targetWidth, targetHeight);
self.onmessage = async (e) => {
// Ignore internal browser/Vite/extension pings that don't match our job signature.
if (e.data?.type !== 'PROCESS_PHOTO') return;
source.close();
}
const {
id,
file,
origWidth,
origHeight,
mainWidth,
mainHeight,
quality,
thumbWidth,
thumbHeight,
thumbQuality,
computeBlurhash: shouldComputeBlurhash,
} = e.data;
// --- 3. Generate Blurhash (if requested) ---
try {
// 1. Decode + resize the original exactly once for the main image.
const needsResize = origWidth !== mainWidth || origHeight !== mainHeight;
const mainCanvas = await decodeResized(
file,
mainWidth,
mainHeight,
needsResize
);
// 2. Derive the thumbnail from the main canvas (no second decode).
const thumbCanvas = await deriveThumbnail(
mainCanvas,
thumbWidth,
thumbHeight
);
// 3. Generate BlurHash from a tiny canvas, if requested.
let blurhash = null;
if (computeBlurhash) {
if (shouldComputeBlurhash) {
try {
const imageData = finalCtx.getImageData(
0,
0,
targetWidth,
targetHeight
);
blurhash = encode(imageData.data, targetWidth, targetHeight, 4, 3);
blurhash = computeBlurhash(thumbCanvas);
} catch (blurhashError) {
console.warn(
'Could not generate blurhash (possible canvas fingerprinting protection):',
@@ -104,20 +226,31 @@ self.onmessage = async (e) => {
}
}
// --- 4. Compress to JPEG Blob ---
const finalBlob = await finalCanvas.convertToBlob({
type: 'image/jpeg',
quality: quality,
});
const mainDim = `${mainCanvas.width}x${mainCanvas.height}`;
const thumbDim = `${thumbCanvas.width}x${thumbCanvas.height}`;
const dim = `${targetWidth}x${targetHeight}`;
// 4. Compress both images to JPEG concurrently.
const [mainBlob, thumbBlob] = await Promise.all([
mainCanvas.convertToBlob({ type: 'image/jpeg', quality }),
thumbCanvas.convertToBlob({ type: 'image/jpeg', quality: thumbQuality }),
]);
// --- 5. Send results back to main thread ---
// Release canvas backing stores now that the blobs are materialized.
mainCanvas.width = 0;
mainCanvas.height = 0;
if (thumbCanvas !== mainCanvas) {
thumbCanvas.width = 0;
thumbCanvas.height = 0;
}
// 5. Send results back to the main thread.
self.postMessage({
id,
success: true,
blob: finalBlob,
dim,
mainBlob,
mainDim,
thumbBlob,
thumbDim,
blurhash,
});
} catch (error) {
+252
View File
@@ -0,0 +1,252 @@
# Photo Upload Performance — Optimization Plan
Why photo processing is slow on most devices, and how to make it fast without any
noticeable loss in picture quality.
> Status: **Implemented** (see git history on this branch). This document is
> kept as the design record for the optimization.
> Scope: client-side image processing + upload pipeline for place photos
> (the `place-photo-upload*` components, the `image-processor` service, and the
> `image-processor` worker). Does not cover blossom server-side behavior,
> relay publishing, or rendering/gallery code beyond the preview `<img>`.
>
> Implementation choices: BlurHash input capped at **64px**; main image JPEG
> quality set to **0.85** (thumbnail stays at 0.9).
## 1. Summary
Adding a photo currently decodes the multi-megapixel original up to five times,
builds a full-resolution `OffscreenCanvas` copy, and — worst of all — runs
`blurhash.encode()` over **every full-resolution pixel** (~33M iterations for a
4:3 1920px image). On a fast desktop CPU that single BlurHash call measured
**~1.3 s**; on mid-range/older phones and cold workers it easily reaches
**5–15+ seconds**. This is the dominant cost and it happens before the upload
even starts.
The plan below removes the redundant decodes, shrinks the BlurHash input to a
tiny canvas, hardens the Android fallback, and derives the thumbnail from the
already-resized main image. Expected result: **seconds → ~100–300 ms** of
processing on most devices, with no visually noticeable quality loss (same
dimensions, EXIF/GPS still stripped, visually identical BlurHash; main JPEG
quality from 0.9 → 0.85 as requested).
## 2. Root causes
Four concrete bottlenecks, ordered by impact. The first one alone accounts for
roughly 70–90% of the processing time.
### 2.1 BlurHash is encoded on the full 1920px image
- `app/components/place-photo-upload-item.gjs:54-59` requests
`computeBlurhash = true` on the **1920px main image** (up to ~2.76 MP for 4:3,
e.g. `1920×1440`).
- `app/workers/image-processor.js:90-98` calls
`finalCtx.getImageData(0, 0, targetWidth, targetHeight)` — an **~11 MB
GPU→CPU readback** — and passes all ~2.76M pixels to
`blurhash.encode(..., 4, 3)`.
- Inside `blurhash@2.0.5`, `encode` loops over every pixel **12 times**
(`4×3` components ≈ **33.2M iterations**), calling `Math.cos` ~66M times and
`Math.pow(..., 2.4)` ~100M times with no lookup tables, in a **column-major**
loop that thrashes CPU caches across the 11 MB RGBA buffer.
- BlurHash `4×3` encodes only **12 low-frequency DCT color components** — it is
designed to be encoded from a _small_ image. Marco decodes it at `32×18`
(`app/components/blurhash.gjs:11-12`), so the extra input pixels contribute
nothing visible.
Measured with the `blurhash@2.0.5` algorithm in Node on a fast desktop CPU
(warmed up; mobile is slower):
| Input size | Pixels | Time |
| ----------- | ------ | -------- |
| `1920×1440` | 2.76M | ~1312 ms |
| `350×263` | 92K | ~47 ms |
| `64×48` | 3072 | ~2.2 ms |
| `32×24` | 768 | ~0.6 ms |
Encoding from a `64×48` input is **~600× faster** than from `1920×1440`.
A visual comparison of the produced hashes (synthetic photo scene):
full-res `L:EDJLW-J7W.TOjcspjbNgfRsnjt` vs `64×48` downscale
`L?EDGDbXJ7W;ThjcspjvNgf8soju` — visually identical at render size.
### 2.2 The original multi-megapixel file is decoded up to five times
- `app/components/place-photo-upload-item.gjs:54-69` calls
`imageProcessor.process(file, ...)` **twice sequentially** on the raw original
`file`: once for the 1920px main image, then again from scratch for the 350px
thumbnail.
- Each call runs `_getImageDimensions(file)` via `new Image()` on the **main
thread** (`app/services/image-processor.js:54-72`), then sends the full
12MP–48MP file to the worker to decode and downscale all over again.
- Meanwhile `app/components/place-photo-upload-item.gjs:30,138` mounts
`<img src={{URL.createObjectURL(file)}}>` (without `decoding="async"`),
decoding the full original on the main thread just to show the preview box.
Rough decode budget for a single 12MP photo today: `new Image()` (dims) +
preview `<img>` + worker main decode + `new Image()` (dims again) + worker
thumbnail decode = **5 full decodes**, plus 2 dimension parses.
### 2.3 Android fallback skips hardware resize and burns huge RAM/CPU
In `app/workers/image-processor.js:15-49`, when
`createImageBitmap(file, { resizeWidth, resizeHeight, resizeQuality: 'high' })`
fails because of Android's worker `File` descriptor bug (`content://` URI), the
`catch` block reads `file.arrayBuffer()` into an in-memory `Blob` — **but never
retries `createImageBitmap(blob, { resizeWidth, resizeHeight, ... })`**.
Instead it immediately drops into stepped _software_ scaling at full resolution:
- Decodes the full 12MP–48MP image (`48–192 MB` RGBA).
- Allocates a **redundant same-size** `OffscreenCanvas(srcWidth, srcHeight)`
(another `48–192 MB`!) and copies the full bitmap into it before the first
halving step (`app/workers/image-processor.js:44-49`).
- Uses `imageSmoothingQuality = 'high'` (expensive Lanczos/bicubic) on every
multi-megapixel halving pass.
- Never zeroes out intermediate canvases
(`canvas.width = 0; canvas.height = 0`), keeping peak RAM high and triggering
GC/memory pressure on phones.
- Because the thumbnail ran as a separate job, Android did all of this **twice**.
### 2.4 Silent un-stepped fallback if a browser ignores `resizeWidth`/`resizeHeight`
If `createImageBitmap` succeeds without honoring `resizeWidth`/`resizeHeight`
(returning full-size dimensions), `app/workers/image-processor.js:27` draws the
full bitmap directly into `finalCanvas` in one pass with default smoothing,
producing a poor (and slow) downscale. There is currently no check for this.
## 3. Optimization plan
### 3.1 Compute BlurHash from a tiny downscaled canvas
**File:** `app/workers/image-processor.js`
- Draw the (already-resized) thumbnail/main canvas onto a tiny
`OffscreenCanvas` capped at **64px** (preserving aspect ratio), using
`getContext('2d', { willReadFrequently: true })`.
- Read `getImageData` from that tiny canvas (~3–12 KB instead of ~11 MB) and run
`blurhash.encode(data, w, h, 4, 3)`.
- Keep the existing `try/catch` so canvas-fingerprinting-protection failures
still degrade gracefully.
**Impact:** BlurHash time **1–15 s → <3 ms**; output visually identical.
**Notes for review:** `32px` vs `64px` is a pick-your-poison knob —
`64px` is a touch closer to full-res hashes at a still-trivial ~2 ms. Default in
this plan: **64px**.
### 3.2 Single-pass worker job for main image + thumbnail + BlurHash
**Files:** `app/workers/image-processor.js`, `app/services/image-processor.js`,
`app/components/place-photo-upload-item.gjs`
Replace the two sequential `process()` calls with a single job, e.g.
`processPhoto(file, options)` / worker message `PROCESS_PHOTO`:
1. Call `_getImageDimensions(file)` **once** on the main thread (keeps native
browser EXIF-orientation handling and JPEG/PNG/WebP/HEIC/AVIF support).
2. Calculate **both** main (`≤1920px`) and thumbnail (`≤350px`) target
dimensions up front.
3. Inside the worker, decode/resize the original `file` **once** to
`mainCanvas` (same resize logic as today, hardened per 3.3).
4. Derive `thumbCanvas` directly from `mainCanvas`:
- Preferred:
`createImageBitmap(mainCanvas, { resizeWidth: thumbW, resizeHeight: thumbH, resizeQuality: 'high' })`.
- Fallback: fast stepped draw `1920 → ~700–960 → 350`.
- If the original is already within `maxDimension`, skip main downscaling;
if it is already `≤ thumbMaxDimension` on both axes, derive the thumbnail
without any downscaling.
- Visually indistinguishable from scaling the 4032px original directly,
because stepped scaling passes through ~1920px anyway.
5. Derive the tiny `≤64px` BlurHash canvas from `thumbCanvas` (per 3.1).
6. Run `mainCanvas.convertToBlob(...)` and `thumbCanvas.convertToBlob(...)`
concurrently via `Promise.all` with the **unchanged** quality settings
(`IMAGE_QUALITY = 0.9`, `THUMBNAIL_QUALITY = 0.9`).
7. Post back `{ mainBlob, mainDim, thumbBlob, thumbDim, blurhash }`.
8. EXIF/GPS metadata stripping via canvas re-encoding is **100% intact** —
re-encoding through a canvas still drops all metadata.
`app/components/place-photo-upload-item.gjs` then makes a single
`imageProcessor.processPhoto(...)` call and uploads `mainBlob`/`thumbBlob` as
before (including the existing mobile-sequential vs desktop-concurrent upload
branches, which are orthogonal to this change).
### 3.3 Harden and speed up the resize & Android fallback path
**File:** `app/workers/image-processor.js`
1. **Retry hardware resize with an in-memory `Blob` before software scaling:**
1. Try `createImageBitmap(file, resizeOpts)` (omit
`resizeWidth`/`resizeHeight`/`resizeQuality` when no resize is needed).
2. If that throws (Android `content://` `File` descriptor bug), read
`file.arrayBuffer()` → `new Blob([buffer], { type: file.type })` and
**retry `createImageBitmap(blob, resizeOpts)`**. This lets Android Chrome
use native/Skia DCT-scaled JPEG decoding instead of full-res software
canvases.
3. Check `bitmap.width === targetWidth && bitmap.height === targetHeight`.
Only fall back to stepped canvas scaling if resizing failed _or was
ignored_ (fixes 2.4), reusing the decoded `ImageBitmap` when available.
2. **Optimize the stepped software-scaling fallback:**
- Eliminate the redundant full-size `OffscreenCanvas(srcWidth, srcHeight)`
copy — draw `source` directly into the first halved canvas
(`Math.floor(srcWidth * 0.5)` × `Math.floor(srcHeight * 0.5)`), then call
`source.close()` immediately.
- Use `imageSmoothingQuality = 'medium'` on intermediate 2× halving passes
and `'high'` only on the final pass to the exact target dimensions.
- Zero out each old intermediate canvas (`prev.width = 0; prev.height = 0`)
right after copying from it, to release backing memory immediately.
### 3.4 Lighter preview handling
**File:** `app/components/place-photo-upload-item.gjs`
- Add `decoding="async"` to the preview `<img src={{this.thumbnailUrl}}>`.
- Once processing finishes (now ~100–300 ms instead of many seconds), swap
`this.thumbnailUrl` to an object URL created from the processed thumbnail
blob and revoke the original raw-file object URL, so the browser releases the
multi-megapixel decoded original from GPU/RAM while the user writes alt text
and picks tags. Keep `URL.revokeObjectURL` in `willDestroy` for both URLs.
### 3.5 Optional: JPEG quality for upload speed
Sections 3.1–3.4 alone bring processing from seconds to ~100–300 ms on most
devices without touching JPEG quality. The remaining lever is upload size.
**Applied:** main `IMAGE_QUALITY` lowered `0.9 → 0.85`; `THUMBNAIL_QUALITY`
kept at `0.9`.
Lowering `THUMBNAIL_QUALITY` to `0.82` would shrink file sizes further with no
noticeable visual loss on thumbnails, but is left untouched here.
## 4. Files touched
| File | Change |
| ---------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- |
| `app/workers/image-processor.js` | Single-pass job; tiny BlurHash canvas; Android `Blob` retry; stepped-scaling + memory fixes. |
| `app/services/image-processor.js` | New `processPhoto(file, options)` API; keep `_getImageDimensions`; keep `process()` or remove once callers migrated. |
| `app/components/place-photo-upload-item.gjs` | One `processPhoto` call; `decoding="async"`; swap preview URL to processed blob. |
| `tests/unit/services/image-processor-test.js` | New unit tests (see 5). |
| `tests/integration/components/place-photo-upload-test.gjs` | Ensure existing tests still pass; add coverage if needed. |
## 5. Verification & tests
- **Unit tests** for `ImageProcessorService` / worker contract:
- dimension math (landscape, portrait, square, already-small no-upscale);
- single-pass output contains main blob, thumbnail blob, dims, and blurhash;
- thumbnail derived from main (no second decode);
- small image (`≤ thumbMaxDimension`) does not downscale;
- error handling when the worker is unavailable.
- **Integration:** `place-photo-upload-test.gjs` must still pass.
- **Manual/perf:** process a 12MP+ photo (JPEG and a HEIC/AVIF where supported)
on desktop Chrome and Android Chrome; confirm processing completes in
well under 1 s, the BlurHash placeholder looks correct, and the uploaded
`imeta`/`dim`/`thumb`/`blurhash` tags are unchanged.
- Run `pnpm lint` and `pnpm test`.
## 6. Expected outcome
| Metric | Before | After |
| ------------------------------ | ------------------------------- | ------------------------------------ |
| BlurHash encode (1920×1440) | ~1.3 s desktop / 5–15 s mobile | <3 ms |
| Full decodes per photo | up to 5 | 1 (+1 dim parse) |
| Peak worker RAM (Android path) | 48–192 MB ×2 + redundant copies | ~48–192 MB once |
| Total processing | seconds | ~100–300 ms |
| Output quality | — | main JPEG 0.9 → 0.85, else unchanged |
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "marco",
"version": "1.36.3",
"version": "1.36.4",
"private": true,
"description": "Unhosted maps app",
"repository": {
+219
View File
@@ -0,0 +1,219 @@
(function() {
var t = [
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"A",
"B",
"C",
"D",
"E",
"F",
"G",
"H",
"I",
"J",
"K",
"L",
"M",
"N",
"O",
"P",
"Q",
"R",
"S",
"T",
"U",
"V",
"W",
"X",
"Y",
"Z",
"a",
"b",
"c",
"d",
"e",
"f",
"g",
"h",
"i",
"j",
"k",
"l",
"m",
"n",
"o",
"p",
"q",
"r",
"s",
"t",
"u",
"v",
"w",
"x",
"y",
"z",
"#",
"$",
"%",
"*",
"+",
",",
"-",
".",
":",
";",
"=",
"?",
"@",
"[",
"]",
"^",
"_",
"{",
"|",
"}",
"~"
], e = (e, a) => {
var i = "";
for (let h = 1; h <= a; h++) {
let r = Math.floor(e) / Math.pow(83, a - h) % 83;
i += t[Math.floor(r)];
}
return i;
}, a = (t) => {
let e = t / 255;
return e <= .04045 ? e / 12.92 : Math.pow((e + .055) / 1.055, 2.4);
}, i = (t) => {
let e = Math.max(0, Math.min(1, t));
return e <= .0031308 ? Math.trunc(12.92 * e * 255 + .5) : Math.trunc(255 * (1.055 * Math.pow(e, .4166666666666667) - .055) + .5);
}, h = (t, e) => ((t) => t < 0 ? -1 : 1)(t) * Math.pow(Math.abs(t), e), r = class extends Error {
constructor(t) {
super(t), this.name = "ValidationError", this.message = t;
}
}, o = (t, e, i, h) => {
let r = 0, o = 0, n = 0, l = 4 * e;
for (let g = 0; g < e; g++) {
let e = 4 * g;
for (let s = 0; s < i; s++) {
let i = e + s * l, m = h(g, s);
r += m * a(t[i]), o += m * a(t[i + 1]), n += m * a(t[i + 2]);
}
}
let s = 1 / (e * i);
return [
r * s,
o * s,
n * s
];
};
function n(t, e, a) {
const i = new OffscreenCanvas(e, a), h = i.getContext("2d");
if (!h) throw new Error("Failed to get 2d context from OffscreenCanvas");
return h.imageSmoothingEnabled = !0, h.imageSmoothingQuality = "high", h.drawImage(t, 0, 0, e, a), t.close(), i;
}
function l(t, e, a) {
if (!(.5 * t.width > e && .5 * t.height > a)) return n(t, e, a);
let i = new OffscreenCanvas(Math.floor(.5 * t.width), Math.floor(.5 * t.height)), h = i.getContext("2d");
for (h.imageSmoothingEnabled = !0, h.imageSmoothingQuality = "medium", h.drawImage(t, 0, 0, i.width, i.height), t.close(); .5 * i.width > e && .5 * i.height > a;) {
const t = new OffscreenCanvas(Math.floor(.5 * i.width), Math.floor(.5 * i.height)), e = t.getContext("2d");
e.imageSmoothingEnabled = !0, e.imageSmoothingQuality = "medium", e.drawImage(i, 0, 0, t.width, t.height), i.width = 0, i.height = 0, i = t;
}
const r = new OffscreenCanvas(e, a), o = r.getContext("2d");
return o.imageSmoothingEnabled = !0, o.imageSmoothingQuality = "high", o.drawImage(i, 0, 0, e, a), i.width = 0, i.height = 0, r;
}
self.onmessage = async (t) => {
if ("PROCESS_PHOTO" !== t.data?.type) return;
const { id: a, file: s, origWidth: g, origHeight: m, mainWidth: c, mainHeight: f, quality: d, thumbWidth: u, thumbHeight: w, thumbQuality: M, computeBlurhash: y } = t.data;
try {
const t = await async function(t, e, a, i) {
const h = i ? {
resizeWidth: e,
resizeHeight: a,
resizeQuality: "high"
} : {}, r = (t) => t.width === e && t.height === a;
try {
const i = await createImageBitmap(t, h);
return r(i) ? n(i, e, a) : l(i, e, a);
} catch (g) {
console.warn("Hardware resize from File failed, retrying via in-memory Blob:", g);
}
const o = await t.arrayBuffer(), s = new Blob([o], { type: t.type });
try {
const t = await createImageBitmap(s, h);
return r(t) ? n(t, e, a) : l(t, e, a);
} catch (m) {
console.warn("Hardware resize from Blob failed, falling back to stepped software scaling:", m);
}
return l(await createImageBitmap(s), e, a);
}(s, c, f, g !== c || m !== f), b = await async function(t, e, a) {
if (t.width === e && t.height === a) return t;
try {
const i = await createImageBitmap(t, {
resizeWidth: e,
resizeHeight: a,
resizeQuality: "high"
});
return i.width === e && i.height === a ? n(i, e, a) : l(i, e, a);
} catch (i) {
return console.warn("Native thumbnail resize failed, scaling from canvas:", i), l(await createImageBitmap(t), e, a);
}
}(t, u, w);
let x = null;
if (y) try {
x = function(t) {
const a = Math.min(1, 64 / Math.max(t.width, t.height)), n = Math.max(1, Math.round(t.width * a)), l = Math.max(1, Math.round(t.height * a)), s = new OffscreenCanvas(n, l).getContext("2d", { willReadFrequently: !0 });
return s.imageSmoothingEnabled = !0, s.imageSmoothingQuality = "high", s.drawImage(t, 0, 0, n, l), ((t, a, n) => {
if (a * n * 4 !== t.length) throw new r("Width and height must match the pixels array");
let l = [];
for (let e = 0; e < 3; e++) for (let i = 0; i < 4; i++) {
let h = 0 == i && 0 == e ? 1 : 2, r = o(t, a, n, (t, r) => h * Math.cos(Math.PI * i * t / a) * Math.cos(Math.PI * e * r / n));
l.push(r);
}
let s, g = l[0], m = l.slice(1), c = "";
if (c += e(21, 1), m.length > 0) {
let t = Math.max(...m.map((t) => Math.max(...t))), a = Math.floor(Math.max(0, Math.min(82, Math.floor(166 * t - .5))));
s = (a + 1) / 166, c += e(a, 1);
} else s = 1, c += e(0, 1);
return c += e(((t) => (i(t[0]) << 16) + (i(t[1]) << 8) + i(t[2]))(g), 4), m.forEach((t) => {
c += e(((t, e) => 19 * Math.floor(Math.max(0, Math.min(18, Math.floor(9 * h(t[0] / e, .5) + 9.5)))) * 19 + 19 * Math.floor(Math.max(0, Math.min(18, Math.floor(9 * h(t[1] / e, .5) + 9.5)))) + Math.floor(Math.max(0, Math.min(18, Math.floor(9 * h(t[2] / e, .5) + 9.5)))))(t, s), 2);
}), c;
})(s.getImageData(0, 0, n, l).data, n, l);
}(b);
} catch (p) {
console.warn("Could not generate blurhash (possible canvas fingerprinting protection):", p);
}
const v = `${t.width}x${t.height}`, B = `${b.width}x${b.height}`, [C, I] = await Promise.all([t.convertToBlob({
type: "image/jpeg",
quality: d
}), b.convertToBlob({
type: "image/jpeg",
quality: M
})]);
t.width = 0, t.height = 0, b !== t && (b.width = 0, b.height = 0), self.postMessage({
id: a,
success: !0,
mainBlob: C,
mainDim: v,
thumbBlob: I,
thumbDim: B,
blurhash: x
});
} catch (b) {
self.postMessage({
id: a,
success: !1,
error: b.message
});
}
};
})();
-182
View File
@@ -1,182 +0,0 @@
var q = [
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"A",
"B",
"C",
"D",
"E",
"F",
"G",
"H",
"I",
"J",
"K",
"L",
"M",
"N",
"O",
"P",
"Q",
"R",
"S",
"T",
"U",
"V",
"W",
"X",
"Y",
"Z",
"a",
"b",
"c",
"d",
"e",
"f",
"g",
"h",
"i",
"j",
"k",
"l",
"m",
"n",
"o",
"p",
"q",
"r",
"s",
"t",
"u",
"v",
"w",
"x",
"y",
"z",
"#",
"$",
"%",
"*",
"+",
",",
"-",
".",
":",
";",
"=",
"?",
"@",
"[",
"]",
"^",
"_",
"{",
"|",
"}",
"~"
], p = (t, e) => {
var a = "";
for (let o = 1; o <= e; o++) {
let h = Math.floor(t) / Math.pow(83, e - o) % 83;
a += q[Math.floor(h)];
}
return a;
}, f = (t) => {
let e = t / 255;
return e <= .04045 ? e / 12.92 : Math.pow((e + .055) / 1.055, 2.4);
}, h = (t) => {
let e = Math.max(0, Math.min(1, t));
return e <= .0031308 ? Math.trunc(12.92 * e * 255 + .5) : Math.trunc(255 * (1.055 * Math.pow(e, .4166666666666667) - .055) + .5);
}, M = (t, e) => ((t) => t < 0 ? -1 : 1)(t) * Math.pow(Math.abs(t), e), d = class extends Error {
constructor(t) {
super(t), this.name = "ValidationError", this.message = t;
}
}, D = (t, e, a, o) => {
let h = 0, r = 0, n = 0, i = 4 * e;
for (let l = 0; l < e; l++) {
let e = 4 * l;
for (let s = 0; s < a; s++) {
let a = e + s * i, g = o(l, s);
h += g * f(t[a]), r += g * f(t[a + 1]), n += g * f(t[a + 2]);
}
}
let s = 1 / (e * a);
return [
h * s,
r * s,
n * s
];
}, S = (t, e, a, o, r) => {
if (o < 1 || o > 9 || r < 1 || r > 9) throw new d("BlurHash must have between 1 and 9 components");
if (e * a * 4 !== t.length) throw new d("Width and height must match the pixels array");
let n = [];
for (let h = 0; h < r; h++) for (let r = 0; r < o; r++) {
let o = 0 == r && 0 == h ? 1 : 2, i = D(t, e, a, (t, n) => o * Math.cos(Math.PI * r * t / e) * Math.cos(Math.PI * h * n / a));
n.push(i);
}
let i, s = n[0], l = n.slice(1), g = "";
if (g += p(o - 1 + 9 * (r - 1), 1), l.length > 0) {
let t = Math.max(...l.map((t) => Math.max(...t))), e = Math.floor(Math.max(0, Math.min(82, Math.floor(166 * t - .5))));
i = (e + 1) / 166, g += p(e, 1);
} else i = 1, g += p(0, 1);
return g += p(((t) => (h(t[0]) << 16) + (h(t[1]) << 8) + h(t[2]))(s), 4), l.forEach((t) => {
g += p(((t, e) => 19 * Math.floor(Math.max(0, Math.min(18, Math.floor(9 * M(t[0] / e, .5) + 9.5)))) * 19 + 19 * Math.floor(Math.max(0, Math.min(18, Math.floor(9 * M(t[1] / e, .5) + 9.5)))) + Math.floor(Math.max(0, Math.min(18, Math.floor(9 * M(t[2] / e, .5) + 9.5)))))(t, i), 2);
}), g;
};
self.onmessage = async (t) => {
if ("PROCESS_IMAGE" !== t.data?.type) return;
const { id: e, file: a, targetWidth: o, targetHeight: h, quality: r, computeBlurhash: n } = t.data;
try {
let t, l;
try {
const e = await createImageBitmap(a, {
resizeWidth: o,
resizeHeight: h,
resizeQuality: "high"
});
if (t = new OffscreenCanvas(o, h), l = t.getContext("2d"), !l) throw new Error("Failed to get 2d context from OffscreenCanvas");
l.drawImage(e, 0, 0, o, h), e.close();
} catch (i) {
console.warn("Hardware resize failed, falling back to stepped software scaling:", i);
const e = await a.arrayBuffer(), r = new Blob([e], { type: a.type }), n = await createImageBitmap(r);
let s = n.width, g = n.height, f = new OffscreenCanvas(s, g), c = f.getContext("2d");
for (c.imageSmoothingEnabled = !0, c.imageSmoothingQuality = "high", c.drawImage(n, 0, 0); .5 * f.width > o && .5 * f.height > h;) {
const t = new OffscreenCanvas(Math.floor(.5 * f.width), Math.floor(.5 * f.height)), e = t.getContext("2d");
e.imageSmoothingEnabled = !0, e.imageSmoothingQuality = "high", e.drawImage(f, 0, 0, t.width, t.height), f = t;
}
t = new OffscreenCanvas(o, h), l = t.getContext("2d"), l.imageSmoothingEnabled = !0, l.imageSmoothingQuality = "high", l.drawImage(f, 0, 0, o, h), n.close();
}
let g = null;
if (n) try {
const t = l.getImageData(0, 0, o, h);
g = S(t.data, o, h, 4, 3);
} catch (s) {
console.warn("Could not generate blurhash (possible canvas fingerprinting protection):", s);
}
const f = await t.convertToBlob({
type: "image/jpeg",
quality: r
}), c = `${o}x${h}`;
self.postMessage({
id: e,
success: !0,
blob: f,
dim: c,
blurhash: g
});
} catch (l) {
self.postMessage({
id: e,
success: !1,
error: l.message
});
}
};
+1
View File
@@ -0,0 +1 @@
var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,s=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),a=(e,n)=>{let r={};for(var i in e)t(r,i,{get:e[i],enumerable:!0});return n||t(r,Symbol.toStringTag,{value:"Module"}),r},l=(e,i,o,a)=>{if(i&&"object"==typeof i||"function"==typeof i)for(var l,c=r(i),u=0,h=c.length;u<h;u++)l=c[u],s.call(e,l)||l===o||t(e,l,{get:(e=>i[e]).bind(null,l),enumerable:!(a=n(i,l))||a.enumerable});return e},c=(n,r,o)=>(o=null!=n?e(i(n)):{},l(!r&&n&&n.__esModule&&s.call(n,"default")?o:t(o,"default",{value:n,enumerable:!0}),n)),u=(e=>"undefined"!=typeof require?require:"undefined"!=typeof Proxy?new Proxy(e,{get:(e,t)=>("undefined"!=typeof require?require:e)[t]}):e)(function(e){if("undefined"!=typeof require)return require.apply(this,arguments);throw Error('Calling `require` for "'+e+"\" in an environment that doesn't expose the `require` function. See https://rolldown.rs/in-depth/bundling-cjs#require-external-modules for more details.")});!function(){const e=document.createElement("link").relList;if(!(e&&e.supports&&e.supports("modulepreload"))){for(const e of document.querySelectorAll('link[rel="modulepreload"]'))t(e);new MutationObserver(e=>{for(const n of e)if("childList"===n.type)for(const e of n.addedNodes)"LINK"===e.tagName&&"modulepreload"===e.rel&&t(e)}).observe(document,{childList:!0,subtree:!0})}function t(e){if(e.ep)return;e.ep=!0;const t=function(e){const t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),"use-credentials"===e.crossOrigin?t.credentials="include":"anonymous"===e.crossOrigin?t.credentials="omit":t.credentials="same-origin",t}(e);fetch(e.href,t)}}();var h,d=Object.prototype,p=Symbol("undefined"),f=function(e){return e[e.ADD=0]="ADD",e[e.ONCE=1]="ONCE",e[e.REMOVE=2]="REMOVE",e}(f||{}),g=1,m=class{_descriptors;_mixins;_isInit;_lazyChains;_values;_revisions;source;proto;_parent;_listeners;_listenersVersion=1;_inheritedEnd=-1;_flattenedVersion=0;constructor(e){this._parent=void 0,this._descriptors=void 0,this._mixins=void 0,this._lazyChains=void 0,this._values=void 0,this._revisions=void 0,this._isInit=!1,this.source=e,this.proto=void 0===e.constructor?void 0:e.constructor.prototype,this._listeners=void 0}get parent(){let e=this._parent;if(void 0===e){let t=y(this.source);this._parent=e=null===t||t===d?null:_(t)}return e}setInitializing(){this._isInit=!0}unsetInitializing(){this._isInit=!1}isInitializing(){return this._isInit}isPrototypeMeta(e){return this.proto===this.source&&this.source===e}_getOrCreateOwnMap(e){return this[e]||(this[e]=Object.create(null))}_getOrCreateOwnSet(e){return this[e]||(this[e]=new Set)}_findInheritedMap(e,t){let n=this;for(;null!==n;){let r=n[e];if(void 0!==r){let e=r.get(t);if(void 0!==e)return e}n=n.parent}}_hasInInheritedSet(e,t){let n=this;for(;null!==n;){let r=n[e];if(void 0!==r&&r.has(t))return!0;n=n.parent}return!1}valueFor(e){let t=this._values;return void 0!==t?t[e]:void 0}setValueFor(e,t){this._getOrCreateOwnMap("_values")[e]=t}revisionFor(e){let t=this._revisions;return void 0!==t?t[e]:void 0}setRevisionFor(e,t){this._getOrCreateOwnMap("_revisions")[e]=t}writableLazyChainsFor(e){let t=this._getOrCreateOwnMap("_lazyChains"),n=t[e];return void 0===n&&(n=t[e]=[]),n}readableLazyChainsFor(e){let t=this._lazyChains;if(void 0!==t)return t[e]}addMixin(e){this._getOrCreateOwnSet("_mixins").add(e)}hasMixin(e){return this._hasInInheritedSet("_mixins",e)}forEachMixins(e){let t,n=this;for(;null!==n;){let r=n._mixins;void 0!==r&&(t=void 0===t?new Set:t,r.forEach(n=>{t.has(n)||(t.add(n),e(n))})),n=n.parent}}writeDescriptors(e,t){(this._descriptors||(this._descriptors=new Map)).set(e,t)}peekDescriptors(e){let t=this._findInheritedMap("_descriptors",e);return t===p?void 0:t}removeDescriptors(e){this.writeDescriptors(e,p)}forEachDescriptors(e){let t,n=this;for(;null!==n;){let r=n._descriptors;void 0!==r&&(t=void 0===t?new Set:t,r.forEach((n,r)=>{t.has(r)||(t.add(r),n!==p&&e(r,n))})),n=n.parent}}addToListeners(e,t,n,r,i){this.pushListener(e,t,n,r?f.ONCE:f.ADD,i)}removeFromListeners(e,t,n){this.pushListener(e,t,n,f.REMOVE)}pushListener(e,t,n,r,i=!1){let s=this.writableListeners(),o=x(s,e,t,n);if(-1!==o&&o<this._inheritedEnd&&(s.splice(o,1),this._inheritedEnd--,o=-1),-1===o)s.push({event:e,target:t,method:n,kind:r,sync:i});else{let e=s[o];r===f.REMOVE&&e.kind!==f.REMOVE?s.splice(o,1):(e.kind=r,e.sync=i)}}writableListeners(){return this._flattenedVersion!==g||this.source!==this.proto&&-1!==this._inheritedEnd||g++,-1===this._inheritedEnd&&(this._inheritedEnd=0,this._listeners=[]),this._listeners}flattenedListeners(){if(this._flattenedVersion<g){let e=this.parent;if(null!==e){let t=e.flattenedListeners();if(void 0!==t)if(void 0===this._listeners)this._listeners=t;else{let e=this._listeners;this._inheritedEnd>0&&(e.splice(0,this._inheritedEnd),this._inheritedEnd=0);for(Line truncated
-1
View File
@@ -1 +0,0 @@
var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,s=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),a=(e,n)=>{let r={};for(var i in e)t(r,i,{get:e[i],enumerable:!0});return n||t(r,Symbol.toStringTag,{value:"Module"}),r},l=(e,i,o,a)=>{if(i&&"object"==typeof i||"function"==typeof i)for(var l,c=r(i),u=0,h=c.length;u<h;u++)l=c[u],s.call(e,l)||l===o||t(e,l,{get:(e=>i[e]).bind(null,l),enumerable:!(a=n(i,l))||a.enumerable});return e},c=(n,r,o)=>(o=null!=n?e(i(n)):{},l(!r&&n&&n.__esModule&&s.call(n,"default")?o:t(o,"default",{value:n,enumerable:!0}),n)),u=(e=>"undefined"!=typeof require?require:"undefined"!=typeof Proxy?new Proxy(e,{get:(e,t)=>("undefined"!=typeof require?require:e)[t]}):e)(function(e){if("undefined"!=typeof require)return require.apply(this,arguments);throw Error('Calling `require` for "'+e+"\" in an environment that doesn't expose the `require` function. See https://rolldown.rs/in-depth/bundling-cjs#require-external-modules for more details.")});!function(){const e=document.createElement("link").relList;if(!(e&&e.supports&&e.supports("modulepreload"))){for(const e of document.querySelectorAll('link[rel="modulepreload"]'))t(e);new MutationObserver(e=>{for(const n of e)if("childList"===n.type)for(const e of n.addedNodes)"LINK"===e.tagName&&"modulepreload"===e.rel&&t(e)}).observe(document,{childList:!0,subtree:!0})}function t(e){if(e.ep)return;e.ep=!0;const t=function(e){const t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),"use-credentials"===e.crossOrigin?t.credentials="include":"anonymous"===e.crossOrigin?t.credentials="omit":t.credentials="same-origin",t}(e);fetch(e.href,t)}}();var h,d=Object.prototype,p=Symbol("undefined"),f=function(e){return e[e.ADD=0]="ADD",e[e.ONCE=1]="ONCE",e[e.REMOVE=2]="REMOVE",e}(f||{}),g=1,m=class{_descriptors;_mixins;_isInit;_lazyChains;_values;_revisions;source;proto;_parent;_listeners;_listenersVersion=1;_inheritedEnd=-1;_flattenedVersion=0;constructor(e){this._parent=void 0,this._descriptors=void 0,this._mixins=void 0,this._lazyChains=void 0,this._values=void 0,this._revisions=void 0,this._isInit=!1,this.source=e,this.proto=void 0===e.constructor?void 0:e.constructor.prototype,this._listeners=void 0}get parent(){let e=this._parent;if(void 0===e){let t=y(this.source);this._parent=e=null===t||t===d?null:_(t)}return e}setInitializing(){this._isInit=!0}unsetInitializing(){this._isInit=!1}isInitializing(){return this._isInit}isPrototypeMeta(e){return this.proto===this.source&&this.source===e}_getOrCreateOwnMap(e){return this[e]||(this[e]=Object.create(null))}_getOrCreateOwnSet(e){return this[e]||(this[e]=new Set)}_findInheritedMap(e,t){let n=this;for(;null!==n;){let r=n[e];if(void 0!==r){let e=r.get(t);if(void 0!==e)return e}n=n.parent}}_hasInInheritedSet(e,t){let n=this;for(;null!==n;){let r=n[e];if(void 0!==r&&r.has(t))return!0;n=n.parent}return!1}valueFor(e){let t=this._values;return void 0!==t?t[e]:void 0}setValueFor(e,t){this._getOrCreateOwnMap("_values")[e]=t}revisionFor(e){let t=this._revisions;return void 0!==t?t[e]:void 0}setRevisionFor(e,t){this._getOrCreateOwnMap("_revisions")[e]=t}writableLazyChainsFor(e){let t=this._getOrCreateOwnMap("_lazyChains"),n=t[e];return void 0===n&&(n=t[e]=[]),n}readableLazyChainsFor(e){let t=this._lazyChains;if(void 0!==t)return t[e]}addMixin(e){this._getOrCreateOwnSet("_mixins").add(e)}hasMixin(e){return this._hasInInheritedSet("_mixins",e)}forEachMixins(e){let t,n=this;for(;null!==n;){let r=n._mixins;void 0!==r&&(t=void 0===t?new Set:t,r.forEach(n=>{t.has(n)||(t.add(n),e(n))})),n=n.parent}}writeDescriptors(e,t){(this._descriptors||(this._descriptors=new Map)).set(e,t)}peekDescriptors(e){let t=this._findInheritedMap("_descriptors",e);return t===p?void 0:t}removeDescriptors(e){this.writeDescriptors(e,p)}forEachDescriptors(e){let t,n=this;for(;null!==n;){let r=n._descriptors;void 0!==r&&(t=void 0===t?new Set:t,r.forEach((n,r)=>{t.has(r)||(t.add(r),n!==p&&e(r,n))})),n=n.parent}}addToListeners(e,t,n,r,i){this.pushListener(e,t,n,r?f.ONCE:f.ADD,i)}removeFromListeners(e,t,n){this.pushListener(e,t,n,f.REMOVE)}pushListener(e,t,n,r,i=!1){let s=this.writableListeners(),o=x(s,e,t,n);if(-1!==o&&o<this._inheritedEnd&&(s.splice(o,1),this._inheritedEnd--,o=-1),-1===o)s.push({event:e,target:t,method:n,kind:r,sync:i});else{let e=s[o];r===f.REMOVE&&e.kind!==f.REMOVE?s.splice(o,1):(e.kind=r,e.sync=i)}}writableListeners(){return this._flattenedVersion!==g||this.source!==this.proto&&-1!==this._inheritedEnd||g++,-1===this._inheritedEnd&&(this._inheritedEnd=0,this._listeners=[]),this._listeners}flattenedListeners(){if(this._flattenedVersion<g){let e=this.parent;if(null!==e){let t=e.flattenedListeners();if(void 0!==t)if(void 0===this._listeners)this._listeners=t;else{let e=this._listeners;this._inheritedEnd>0&&(e.splice(0,this._inheritedEnd),this._inheritedEnd=0);for(Line truncated
@@ -1 +1 @@
import{$ as e,$n as t,$t as a,A as n,An as s,Ar as r,At as i,B as o,Bn as l,Br as g,Bt as d,C as h,Cn as c,Cr as u,Ct as p,D as _,Dn as m,Dr as y,Dt as C,E as b,En as f,Er as A,Et as M,F as I,Fn as D,Fr as T,Ft as v,G as O,Gn as E,Gr as S,Gt as R,H as j,Hn as x,Hr as w,Ht as P,I as N,In as V,Ir as F,It as G,J as L,Jn as k,Jr as U,Jt as Y,K as B,Kn as H,Kr as $,Kt as z,L as W,Ln as q,Lr as Z,Lt as J,M as K,Mn as X,Mr as Q,Mt as ee,N as te,Nn as ae,Nr as ne,Nt as se,O as re,On as ie,Or as oe,Ot as le,P as ge,Pn as de,Pr as he,Pt as ce,Q as ue,Qn as pe,Qt as _e,R as me,Rn as ye,Rr as Ce,Rt as be,S as fe,Sn as Ae,Sr as Me,St as Ie,T as De,Tn as Te,Tr as ve,Tt as Oe,U as Ee,Un as Se,Ur as Re,Ut as je,V as xe,Vn as we,Vr as Pe,Vt as Ne,W as Ve,Wn as Fe,Wr as Ge,Wt as Le,X as ke,Xn as Ue,Xr as Ye,Xt as Be,Y as He,Yn as $e,Yr as ze,Yt as We,Z as qe,Zn as Ze,Zr as Je,Zt as Ke,_ as Xe,_n as Qe,_r as et,_t as tt,a as at,an as nt,ar as st,at as rt,b as it,bn as ot,br as lt,bt as gt,c as dt,cn as ht,cr as ct,ct as ut,d as pt,dn as _t,dr as mt,dt as yt,en as Ct,er as bt,et as ft,f as At,fn as Mt,fr as It,ft as Dt,g as Tt,gn as vt,gr as Ot,gt as Et,h as St,hn as Rt,hr as jt,ht as xt,i as wt,in as Pt,ir as Nt,it as Vt,j as Ft,jn as Gt,jr as Lt,jt as kt,k as Ut,kn as Yt,kr as Bt,kt as Ht,l as $t,ln as zt,lr as Wt,lt as qt,m as Zt,mn as Jt,mr as Kt,mt as Xt,n as Qt,nn as ea,nr as ta,nt as aa,o as na,on as sa,or as ra,ot as ia,p as oa,pn as la,pr as ga,pt as da,q as ha,qn as ca,qr as ua,qt as pa,r as _a,rn as ma,rr as ya,rt as Ca,s as ba,sn as fa,sr as Aa,st as Ma,t as Ia,tn as Da,tr as Ta,tt as va,u as Oa,un as Ea,ur as Sa,ut as Ra,v as ja,vn as xa,vr as wa,vt as Pa,w as Na,wn as Va,wr as Fa,wt as Ga,x as La,xn as ka,xr as Ua,xt as Ya,y as Ba,yn as Ha,yr as $a,yt as za,z as Wa,zn as qa,zr as Za,zt as Ja}from"./main-B0NMnAnz.js";var Ka=Je({default:()=>Jt}),Xa=Je({default:()=>tn}),Qa={willChange:"_arrangedContentArrayWillChange",didChange:"_arrangedContentArrayDidChange"};function en(e,t){return"[]"===t?(e._revalidate(),e._arrTag):"length"===t?(e._revalidate(),e._lengthTag):F(e,t)}var tn=class extends V{_objectsDirtyIndex=0;_objects=null;_lengthDirty=!0;_length=0;_arrangedContent=null;_arrangedContentIsUpdating=!1;_arrangedContentTag=null;_arrangedContentRevision=null;_lengthTag=null;_arrTag=null;init(e){super.init(e),y(this,en)}[Ot](){this._revalidate()}willDestroy(){this._removeArrangedContentArrayObserver()}objectAtContent(e){let t=It(this,"arrangedContent");return Fa(t,e)}replace(e,t,a){this.replaceContent(e,t,a)}replaceContent(e,t,a){let n=It(this,"content");Wt(n,e,t,a)}objectAt(e){if(this._revalidate(),null===this._objects&&(this._objects=[]),-1!==this._objectsDirtyIndex&&e>=this._objectsDirtyIndex){let e=It(this,"arrangedContent");if(e){let t=this._objects.length=It(e,"length");for(let e=this._objectsDirtyIndex;e<t;e++)this._objects[e]=this.objectAtContent(e)}else this._objects.length=0;this._objectsDirtyIndex=-1}return this._objects[e]}get length(){if(this._revalidate(),this._lengthDirty){let e=It(this,"arrangedContent");this._length=e?It(e,"length"):0,this._lengthDirty=!1}return Ce(this._lengthTag),this._length}set length(e){let t,a=this.length-e;if(0===a)return;a<0&&(t=new Array(-a),a=0);let n=It(this,"content");n&&(Wt(n,e,a,t),this._invalidate())}_updateArrangedContentArray(e){let t=null===this._objects?0:this._objects.length,a=e?It(e,"length"):0;this._removeArrangedContentArrayObserver(),Aa(this,0,t,a),this._invalidate(),ra(this,0,t,a,!1),this._addArrangedContentArrayObserver(e)}_addArrangedContentArrayObserver(e){e&&!e.isDestroyed&&(st(e,this,Qa),this._arrangedContent=e)}_removeArrangedContentArrayObserver(){this._arrangedContent&&ct(this._arrangedContent,this,Qa)}_arrangedContentArrayWillChange(){}_arrangedContentArrayDidChange(e,t,a,n){Aa(this,t,a,n);let s=t;s<0&&(s+=It(this._arrangedContent,"length")+a-n),(-1===this._objectsDirtyIndex||this._objectsDirtyIndex>s)&&(this._objectsDirtyIndex=s),this._lengthDirty=!0,ra(this,t,a,n,!1)}_invalidate(){this._objectsDirtyIndex=0,this._lengthDirty=!0}_revalidate(){if(!0!==this._arrangedContentIsUpdating&&(null===this._arrangedContentTag||!Za(this._arrangedContentTag,this._arrangedContentRevision))){let e=this.get("arrangedContent");null===this._arrangedContentTag?this._addArrangedContentArrayObserver(e):(this._arrangedContentIsUpdating=!0,this._updateArrangedContentArray(e),this._arrangedContentIsUpdating=!1);let t=this._arrangedContentTag=F(this,"arrangedContent");this._arrangedContentRevision=g(this._arrangedContentTag),T(e)?(this._lengthTag=Z([t,ve(e,"length")]),this._arrTag=Z([t,ve(e,"[]")])):this._lengthTag=this._arrTag=t}}};tn.reopen(Jt,{arrangedContent:Sa("content")});var an=Je({Meta:()=>S,UNDEFINED:()=>$,counters:()=>ua,meta:()=>U,peekMeta:()=>ze,setMeta:()=>Ye}),nn=Je({ActionHandler:()=>l,Comparable:()=>vt,ContainerProxyMixin:()=>_t,MutableEnumerable:()=>Qe,RSVP:()=>k,RegistryProxyMixin:()=>Ea,TargetActionSupport:()=>ja,_ProxyMixin:()=>O,_contentFor:()=>B,onerrorLine truncated
import{$ as e,$n as t,$t as a,A as n,An as s,Ar as r,At as i,B as o,Bn as l,Br as g,Bt as d,C as h,Cn as c,Cr as u,Ct as p,D as _,Dn as m,Dr as y,Dt as C,E as b,En as f,Er as A,Et as M,F as I,Fn as D,Fr as T,Ft as v,G as O,Gn as E,Gr as S,Gt as R,H as j,Hn as x,Hr as w,Ht as P,I as N,In as V,Ir as F,It as G,J as L,Jn as k,Jr as U,Jt as Y,K as B,Kn as H,Kr as $,Kt as z,L as W,Ln as q,Lr as Z,Lt as J,M as K,Mn as X,Mr as Q,Mt as ee,N as te,Nn as ae,Nr as ne,Nt as se,O as re,On as ie,Or as oe,Ot as le,P as ge,Pn as de,Pr as he,Pt as ce,Q as ue,Qn as pe,Qt as _e,R as me,Rn as ye,Rr as Ce,Rt as be,S as fe,Sn as Ae,Sr as Me,St as Ie,T as De,Tn as Te,Tr as ve,Tt as Oe,U as Ee,Un as Se,Ur as Re,Ut as je,V as xe,Vn as we,Vr as Pe,Vt as Ne,W as Ve,Wn as Fe,Wr as Ge,Wt as Le,X as ke,Xn as Ue,Xr as Ye,Xt as Be,Y as He,Yn as $e,Yr as ze,Yt as We,Z as qe,Zn as Ze,Zr as Je,Zt as Ke,_ as Xe,_n as Qe,_r as et,_t as tt,a as at,an as nt,ar as st,at as rt,b as it,bn as ot,br as lt,bt as gt,c as dt,cn as ht,cr as ct,ct as ut,d as pt,dn as _t,dr as mt,dt as yt,en as Ct,er as bt,et as ft,f as At,fn as Mt,fr as It,ft as Dt,g as Tt,gn as vt,gr as Ot,gt as Et,h as St,hn as Rt,hr as jt,ht as xt,i as wt,in as Pt,ir as Nt,it as Vt,j as Ft,jn as Gt,jr as Lt,jt as kt,k as Ut,kn as Yt,kr as Bt,kt as Ht,l as $t,ln as zt,lr as Wt,lt as qt,m as Zt,mn as Jt,mr as Kt,mt as Xt,n as Qt,nn as ea,nr as ta,nt as aa,o as na,on as sa,or as ra,ot as ia,p as oa,pn as la,pr as ga,pt as da,q as ha,qn as ca,qr as ua,qt as pa,r as _a,rn as ma,rr as ya,rt as Ca,s as ba,sn as fa,sr as Aa,st as Ma,t as Ia,tn as Da,tr as Ta,tt as va,u as Oa,un as Ea,ur as Sa,ut as Ra,v as ja,vn as xa,vr as wa,vt as Pa,w as Na,wn as Va,wr as Fa,wt as Ga,x as La,xn as ka,xr as Ua,xt as Ya,y as Ba,yn as Ha,yr as $a,yt as za,z as Wa,zn as qa,zr as Za,zt as Ja}from"./main-B-1wPM4A.js";var Ka=Je({default:()=>Jt}),Xa=Je({default:()=>tn}),Qa={willChange:"_arrangedContentArrayWillChange",didChange:"_arrangedContentArrayDidChange"};function en(e,t){return"[]"===t?(e._revalidate(),e._arrTag):"length"===t?(e._revalidate(),e._lengthTag):F(e,t)}var tn=class extends V{_objectsDirtyIndex=0;_objects=null;_lengthDirty=!0;_length=0;_arrangedContent=null;_arrangedContentIsUpdating=!1;_arrangedContentTag=null;_arrangedContentRevision=null;_lengthTag=null;_arrTag=null;init(e){super.init(e),y(this,en)}[Ot](){this._revalidate()}willDestroy(){this._removeArrangedContentArrayObserver()}objectAtContent(e){let t=It(this,"arrangedContent");return Fa(t,e)}replace(e,t,a){this.replaceContent(e,t,a)}replaceContent(e,t,a){let n=It(this,"content");Wt(n,e,t,a)}objectAt(e){if(this._revalidate(),null===this._objects&&(this._objects=[]),-1!==this._objectsDirtyIndex&&e>=this._objectsDirtyIndex){let e=It(this,"arrangedContent");if(e){let t=this._objects.length=It(e,"length");for(let e=this._objectsDirtyIndex;e<t;e++)this._objects[e]=this.objectAtContent(e)}else this._objects.length=0;this._objectsDirtyIndex=-1}return this._objects[e]}get length(){if(this._revalidate(),this._lengthDirty){let e=It(this,"arrangedContent");this._length=e?It(e,"length"):0,this._lengthDirty=!1}return Ce(this._lengthTag),this._length}set length(e){let t,a=this.length-e;if(0===a)return;a<0&&(t=new Array(-a),a=0);let n=It(this,"content");n&&(Wt(n,e,a,t),this._invalidate())}_updateArrangedContentArray(e){let t=null===this._objects?0:this._objects.length,a=e?It(e,"length"):0;this._removeArrangedContentArrayObserver(),Aa(this,0,t,a),this._invalidate(),ra(this,0,t,a,!1),this._addArrangedContentArrayObserver(e)}_addArrangedContentArrayObserver(e){e&&!e.isDestroyed&&(st(e,this,Qa),this._arrangedContent=e)}_removeArrangedContentArrayObserver(){this._arrangedContent&&ct(this._arrangedContent,this,Qa)}_arrangedContentArrayWillChange(){}_arrangedContentArrayDidChange(e,t,a,n){Aa(this,t,a,n);let s=t;s<0&&(s+=It(this._arrangedContent,"length")+a-n),(-1===this._objectsDirtyIndex||this._objectsDirtyIndex>s)&&(this._objectsDirtyIndex=s),this._lengthDirty=!0,ra(this,t,a,n,!1)}_invalidate(){this._objectsDirtyIndex=0,this._lengthDirty=!0}_revalidate(){if(!0!==this._arrangedContentIsUpdating&&(null===this._arrangedContentTag||!Za(this._arrangedContentTag,this._arrangedContentRevision))){let e=this.get("arrangedContent");null===this._arrangedContentTag?this._addArrangedContentArrayObserver(e):(this._arrangedContentIsUpdating=!0,this._updateArrangedContentArray(e),this._arrangedContentIsUpdating=!1);let t=this._arrangedContentTag=F(this,"arrangedContent");this._arrangedContentRevision=g(this._arrangedContentTag),T(e)?(this._lengthTag=Z([t,ve(e,"length")]),this._arrTag=Z([t,ve(e,"[]")])):this._lengthTag=this._arrTag=t}}};tn.reopen(Jt,{arrangedContent:Sa("content")});var an=Je({Meta:()=>S,UNDEFINED:()=>$,counters:()=>ua,meta:()=>U,peekMeta:()=>ze,setMeta:()=>Ye}),nn=Je({ActionHandler:()=>l,Comparable:()=>vt,ContainerProxyMixin:()=>_t,MutableEnumerable:()=>Qe,RSVP:()=>k,RegistryProxyMixin:()=>Ea,TargetActionSupport:()=>ja,_ProxyMixin:()=>O,_contentFor:()=>B,onerrorLine truncated
+1 -1
View File
@@ -42,7 +42,7 @@
<meta name="msapplication-TileColor" content="#F6E9A6">
<meta name="msapplication-TileImage" content="/icons/icon-144.png">
<script type="module" crossorigin src="/assets/main-B0NMnAnz.js"></script>
<script type="module" crossorigin src="/assets/main-B-1wPM4A.js"></script>
<link rel="stylesheet" crossorigin href="/assets/main-D1ODG1Dj.css">
</head>
<body>
+130
View File
@@ -0,0 +1,130 @@
import { module, test } from 'qunit';
import { setupTest } from 'marco/tests/helpers';
import { fitWithin } from 'marco/services/image-processor';
module('Unit | Service | image-processor', function (hooks) {
setupTest(hooks);
function setupService(context, dimensions = { width: 100, height: 100 }) {
const service = context.owner.lookup('service:image-processor');
// Don't leave a real worker running during tests.
service._worker?.terminate?.();
service._getImageDimensions = async () => dimensions;
return service;
}
test('fitWithin preserves aspect ratio and never upscales', function (assert) {
assert.deepEqual(fitWithin(4000, 3000, 1920), {
width: 1920,
height: 1440,
});
assert.deepEqual(fitWithin(3000, 4000, 1920), {
width: 1440,
height: 1920,
});
assert.deepEqual(fitWithin(4000, 4000, 1920), {
width: 1920,
height: 1920,
});
assert.deepEqual(fitWithin(800, 600, 1920), { width: 800, height: 600 });
assert.deepEqual(fitWithin(1920, 1080, 1920), {
width: 1920,
height: 1080,
});
});
test('fitWithin rounds the derived dimension', function (assert) {
const { width, height } = fitWithin(4032, 3024, 1920);
assert.strictEqual(width, 1920);
assert.strictEqual(height, 1440);
});
test('processPhoto sends both main and thumbnail dimensions to the worker', async function (assert) {
const service = setupService(this, { width: 4000, height: 3000 });
let sent;
service._worker = {
postMessage(message) {
sent = message;
// Respond synchronously; the resolver is registered before postMessage.
service._handleMessage({
data: {
id: message.id,
success: true,
mainBlob: 'main',
mainDim: '1920x1440',
thumbBlob: 'thumb',
thumbDim: '350x263',
blurhash: 'LKO2',
},
});
},
terminate() {},
};
const result = await service.processPhoto(new Blob(['x']), {
maxDimension: 1920,
quality: 0.9,
thumbMaxDimension: 350,
thumbQuality: 0.9,
computeBlurhash: true,
});
assert.strictEqual(sent.type, 'PROCESS_PHOTO');
assert.strictEqual(sent.origWidth, 4000);
assert.strictEqual(sent.origHeight, 3000);
assert.strictEqual(sent.mainWidth, 1920);
assert.strictEqual(sent.mainHeight, 1440);
assert.strictEqual(sent.thumbWidth, 350);
assert.strictEqual(sent.thumbHeight, 263);
assert.strictEqual(sent.quality, 0.9);
assert.strictEqual(sent.thumbQuality, 0.9);
assert.strictEqual(sent.computeBlurhash, true);
assert.deepEqual(result, {
mainBlob: 'main',
mainDim: '1920x1440',
thumbBlob: 'thumb',
thumbDim: '350x263',
blurhash: 'LKO2',
});
});
test('processPhoto rejects when the worker is unavailable', async function (assert) {
const service = setupService(this);
service._worker = null;
await assert.rejects(
service.processPhoto(new Blob(['x']), {
maxDimension: 1920,
quality: 0.9,
thumbMaxDimension: 350,
thumbQuality: 0.9,
}),
/not available/
);
});
test('processPhoto rejects when the worker reports an error', async function (assert) {
const service = setupService(this);
service._worker = {
postMessage(message) {
service._handleMessage({
data: { id: message.id, success: false, error: 'boom' },
});
},
terminate() {},
};
await assert.rejects(
service.processPhoto(new Blob(['x']), {
maxDimension: 1920,
quality: 0.9,
thumbMaxDimension: 350,
thumbQuality: 0.9,
}),
/boom/
);
});
});