From e6038bbc8736d161fd34b433dbda78610c9285a5 Mon Sep 17 00:00:00 2001 From: Eric Bailey Date: Mon, 28 Sep 2026 09:24:07 -0500 Subject: [PATCH] Revert "Extract image compression into media module" (#11804) --- src/lib/media/image/cache.test.ts | 113 -------- src/lib/media/image/cache.ts | 45 ---- src/lib/media/image/compress.boundary.test.ts | 80 ------ src/lib/media/image/compress.test.ts | 243 ------------------ src/lib/media/image/compress.ts | 104 -------- src/lib/media/image/testSetup.ts | 7 - src/state/gallery.ts | 140 +++++++++- 7 files changed, 133 insertions(+), 599 deletions(-) delete mode 100644 src/lib/media/image/cache.test.ts delete mode 100644 src/lib/media/image/cache.ts delete mode 100644 src/lib/media/image/compress.boundary.test.ts delete mode 100644 src/lib/media/image/compress.test.ts delete mode 100644 src/lib/media/image/compress.ts delete mode 100644 src/lib/media/image/testSetup.ts diff --git a/src/lib/media/image/cache.test.ts b/src/lib/media/image/cache.test.ts deleted file mode 100644 index f39db15a2..000000000 --- a/src/lib/media/image/cache.test.ts +++ /dev/null @@ -1,113 +0,0 @@ -import '#/lib/media/image/testSetup' - -import {makeDirectoryAsync, moveAsync} from 'expo-file-system/legacy' -import {nanoid} from 'nanoid/non-secure' - -import { - getImageCacheDirectory, - joinPath, - moveIfNecessary, -} from '#/lib/media/image/cache' -import {IS_NATIVE} from '#/env' - -jest.mock('expo-file-system/legacy', () => ({ - cacheDirectory: 'file:///cache/', - makeDirectoryAsync: jest.fn().mockResolvedValue(undefined), - moveAsync: jest.fn().mockResolvedValue(undefined), -})) - -jest.mock('nanoid/non-secure', () => ({ - nanoid: jest.fn(() => 'unique-id'), -})) - -beforeEach(() => { - jest.clearAllMocks() -}) - -it.each([ - ['file:///cache', 'bsky-composer'], - ['file:///cache/', 'bsky-composer'], - ['file:///cache', '/bsky-composer'], - ['file:///cache/', '/bsky-composer'], -])('joins cache paths with exactly one slash (%s, %s)', (parent, child) => { - expect(joinPath(parent, child)).toBe('file:///cache/bsky-composer') -}) - -it('uses the composer cache on native and no cache on web', () => { - expect(getImageCacheDirectory()).toBe( - IS_NATIVE ? 'file:///cache/bsky-composer' : null, - ) - expect(getImageCacheDirectory()).toBe(getImageCacheDirectory()) -}) - -it.each([ - 'file:///temporary.jpg', - '/temporary.jpg', - 'data:image/jpeg;base64,AAAA', - 'blob:fake-image', -])( - 'moves uncached output on native without normalizing the source (%s)', - async from => { - const output = await moveIfNecessary(from) - if (IS_NATIVE) { - expect(output).toBe('file:///cache/bsky-composer/unique-id') - expect(nanoid).toHaveBeenCalledWith(36) - expect(makeDirectoryAsync).toHaveBeenCalledWith( - 'file:///cache/bsky-composer', - { - intermediates: true, - }, - ) - expect(moveAsync).toHaveBeenCalledWith({from, to: output}) - expect( - jest.mocked(makeDirectoryAsync).mock.invocationCallOrder[0], - ).toBeLessThan(jest.mocked(moveAsync).mock.invocationCallOrder[0]) - } else { - expect(output).toBe(from) - expect(nanoid).not.toHaveBeenCalled() - expect(makeDirectoryAsync).not.toHaveBeenCalled() - expect(moveAsync).not.toHaveBeenCalled() - } - }, -) - -it('leaves already cached output in place', async () => { - const from = 'file:///cache/bsky-composer/already-cached' - expect(await moveIfNecessary(from)).toBe(from) - expect(makeDirectoryAsync).not.toHaveBeenCalled() - expect(moveAsync).not.toHaveBeenCalled() - expect(nanoid).not.toHaveBeenCalled() -}) - -if (IS_NATIVE) { - it('waits for directory creation before moving', async () => { - let finishDirectory!: () => void - jest - .mocked(makeDirectoryAsync) - .mockImplementationOnce( - () => new Promise(resolve => (finishDirectory = resolve)), - ) - const moving = moveIfNecessary('file:///temporary.jpg') - expect(moveAsync).not.toHaveBeenCalled() - finishDirectory() - await moving - expect(moveAsync).toHaveBeenCalledTimes(1) - }) - - it('propagates directory creation failures without moving', async () => { - jest - .mocked(makeDirectoryAsync) - .mockRejectedValueOnce(new Error('mkdir failed')) - await expect(moveIfNecessary('file:///temporary.jpg')).rejects.toThrow( - 'mkdir failed', - ) - expect(moveAsync).not.toHaveBeenCalled() - }) - - it('propagates move failures rather than returning an unusable path', async () => { - jest.mocked(moveAsync).mockRejectedValueOnce(new Error('move failed')) - await expect(moveIfNecessary('file:///temporary.jpg')).rejects.toThrow( - 'move failed', - ) - }) -} diff --git a/src/lib/media/image/cache.ts b/src/lib/media/image/cache.ts deleted file mode 100644 index 649406515..000000000 --- a/src/lib/media/image/cache.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { - cacheDirectory, - makeDirectoryAsync, - moveAsync, -} from 'expo-file-system/legacy' -import {nanoid} from 'nanoid/non-secure' - -import {IS_NATIVE} from '#/env' - -let _imageCacheDirectory: string - -export function getImageCacheDirectory(): string | null { - if (IS_NATIVE) { - return (_imageCacheDirectory ??= joinPath(cacheDirectory!, 'bsky-composer')) - } - - return null -} - -export async function moveIfNecessary(from: string) { - const cacheDir = IS_NATIVE && getImageCacheDirectory() - - if (cacheDir && !from.startsWith(cacheDir)) { - const to = joinPath(cacheDir, nanoid(36)) - - await makeDirectoryAsync(cacheDir, {intermediates: true}) - await moveAsync({from, to}) - - return to - } - - return from -} - -export function joinPath(a: string, b: string) { - if (a.endsWith('/')) { - if (b.startsWith('/')) { - return a.slice(0, -1) + b - } - return a + b - } else if (b.startsWith('/')) { - return a + b - } - return a + '/' + b -} diff --git a/src/lib/media/image/compress.boundary.test.ts b/src/lib/media/image/compress.boundary.test.ts deleted file mode 100644 index eef7c6243..000000000 --- a/src/lib/media/image/compress.boundary.test.ts +++ /dev/null @@ -1,80 +0,0 @@ -import '#/lib/media/image/testSetup' - -import {type ImageManipulatorContext} from 'expo-image-manipulator' - -jest.mock('expo-file-system/legacy', () => ({ - cacheDirectory: 'file:///cache/', - makeDirectoryAsync: jest.fn().mockResolvedValue(undefined), - moveAsync: jest.fn().mockResolvedValue(undefined), -})) - -it('imports and runs the production compressor without loading the app UI graph', async () => { - jest.resetModules() - - /* - * Only the Expo renderer/filesystem are faked. In particular, do not mock - * gallery, picker, or any app module: a transitive UI import must be visible. - */ - const {ImageManipulator} = - require('expo-image-manipulator') as typeof import('expo-image-manipulator') - jest.mocked(ImageManipulator.manipulate).mockImplementation( - () => - ({ - resize: jest.fn(), - renderAsync: jest.fn().mockResolvedValue({ - saveAsync: jest.fn().mockResolvedValue({ - uri: 'data:image/jpeg;base64,AAAA', - base64: 'AAAA', - width: 10, - height: 10, - }), - release: jest.fn(), - }), - release: jest.fn(), - }) as unknown as ImageManipulatorContext, - ) - - const {compressImage} = - require('#/lib/media/image/compress') as typeof import('#/lib/media/image/compress') - expect(jest.isMockFunction(compressImage)).toBe(false) - - const appModules = () => - Object.keys(require.cache) - .filter(path => path.startsWith(`${process.cwd()}/src/`)) - .map(path => path.slice(`${process.cwd()}/src/`.length)) - .sort() - - const allowedModules = [ - 'env/common.ts', - require.resolve('#/env').endsWith('.web.ts') - ? 'env/index.web.ts' - : 'env/index.ts', - 'lib/media/image/cache.ts', - 'lib/media/image/compress.ts', - 'lib/media/image-manipulator.ts', - 'lib/media/util.ts', - ] - expect(appModules()).toContain('lib/media/image/compress.ts') - expect(appModules().filter(path => !allowedModules.includes(path))).toEqual( - [], - ) - - await expect( - compressImage( - { - alt: '', - source: { - id: 'image', - path: 'fake-source', - width: 10, - height: 10, - mime: 'image/png', - }, - }, - {maxDimension: 10, maxSize: 3}, - ), - ).resolves.toMatchObject({mime: 'image/jpeg', size: 3}) - - /* Exercise lazy imports too, not just the compressor's module initialization. */ - expect(appModules()).toEqual(allowedModules.sort()) -}) diff --git a/src/lib/media/image/compress.test.ts b/src/lib/media/image/compress.test.ts deleted file mode 100644 index da8a95728..000000000 --- a/src/lib/media/image/compress.test.ts +++ /dev/null @@ -1,243 +0,0 @@ -import '#/lib/media/image/testSetup' - -import {makeDirectoryAsync, moveAsync} from 'expo-file-system/legacy' -import { - ImageManipulator, - type ImageManipulatorContext, - type ImageResult, - type SaveOptions, -} from 'expo-image-manipulator' -import {nanoid} from 'nanoid/non-secure' - -import {compressImage} from '#/lib/media/image/compress' -import {type ComposerImage} from '#/state/gallery' -import {IS_NATIVE} from '#/env' - -jest.mock('expo-file-system/legacy', () => ({ - cacheDirectory: 'file:///cache/', - makeDirectoryAsync: jest.fn().mockResolvedValue(undefined), - moveAsync: jest.fn().mockResolvedValue(undefined), -})) - -jest.mock('nanoid/non-secure', () => ({nanoid: jest.fn()})) - -const source: ComposerImage = { - alt: 'Alt text', - source: { - id: 'source-id', - path: 'file:///original.png', - width: 6000, - height: 3001, - mime: 'image/png', - }, -} - -function fakeRenderer( - result: ( - options: SaveOptions, - index: number, - ) => Partial = () => ({}), -) { - const renders: { - resize: jest.Mock]> - release: jest.Mock - image: { - saveAsync: jest.Mock, [SaveOptions]> - release: jest.Mock - } - }[] = [] - - jest.mocked(ImageManipulator.manipulate).mockImplementation(() => { - const index = renders.length + 1 - const resize = jest.fn]>() - const image = { - saveAsync: jest.fn((options: SaveOptions) => - Promise.resolve().then(() => ({ - uri: `file:///rendered-${index}.jpg`, - ...resize.mock.calls[0][0], - base64: 'AAAA', - ...result(options, index), - })), - ), - release: jest.fn(), - } - const context = { - resize, - release: jest.fn(), - renderAsync: jest.fn().mockResolvedValue(image), - } - renders.push({...context, image}) - return context as unknown as ImageManipulatorContext - }) - - return renders -} - -function qualities(renders: ReturnType) { - return renders.map(render => render.image.saveAsync.mock.calls[0][0].compress) -} - -beforeEach(() => { - jest.clearAllMocks() - let id = 0 - jest.mocked(nanoid).mockImplementation(() => `cached-${++id}`) -}) - -it('searches through full JPEG quality, preserves input and returns rendered metadata', async () => { - const renders = fakeRenderer(() => ({width: 1999, height: 999})) - const policy = Object.freeze({maxDimension: 2000, maxSize: 3}) - const before = JSON.parse(JSON.stringify(source)) - - const output = await compressImage(source, policy) - - expect(qualities(renders)).toEqual([0.51, 0.76, 0.89, 0.95, 0.98, 1]) - expect(output).toEqual({ - path: IS_NATIVE - ? 'file:///cache/bsky-composer/cached-6' - : 'file:///rendered-6.jpg', - width: 1999, - height: 999, - mime: 'image/jpeg', - size: 3, - }) - expect(source).toEqual(before) - for (const render of renders) { - expect(render.resize).toHaveBeenCalledWith({width: 2000, height: 1000}) - expect(render.image.saveAsync).toHaveBeenCalledWith({ - compress: expect.any(Number), - format: 'jpeg', - base64: true, - }) - expect(render.release).toHaveBeenCalledTimes(1) - expect(render.image.release).toHaveBeenCalledTimes(1) - } - expect(ImageManipulator.manipulate).toHaveBeenCalledTimes(6) - expect(ImageManipulator.manipulate).toHaveBeenCalledWith(source.source.path) - expect(moveAsync).toHaveBeenCalledTimes(IS_NATIVE ? 6 : 0) - expect(makeDirectoryAsync).toHaveBeenCalledTimes(IS_NATIVE ? 6 : 0) -}) - -it('prefers the transformed source without reapplying crop operations', async () => { - const renders = fakeRenderer() - const transformed = { - path: 'file:///cropped.png', - width: 3333, - height: 6000, - mime: 'image/png', - } - - await compressImage( - { - ...source, - transformed, - manips: {crop: {originX: 1, originY: 2, width: 3333, height: 6000}}, - }, - {maxDimension: 2000, maxSize: 3}, - ) - - expect(ImageManipulator.manipulate).toHaveBeenCalledWith(transformed.path) - expect(ImageManipulator.manipulate).not.toHaveBeenCalledWith( - source.source.path, - ) - expect(renders[0].resize).toHaveBeenCalledWith({width: 1111, height: 2000}) -}) - -it.each([ - {width: 50, height: 100}, - {width: 100, height: 50}, - {width: 100, height: 100}, -])('does not upscale $width x $height', async dimensions => { - const renders = fakeRenderer() - await compressImage( - {...source, source: {...source.source, ...dimensions}}, - {maxDimension: 100, maxSize: 3}, - ) - expect(renders[0].resize).toHaveBeenCalledWith(dimensions) -}) - -it('keeps the last fitting result and only moves accepted renders', async () => { - const renders = fakeRenderer(options => ({ - base64: options.compress! <= 0.7 ? 'AAAA' : 'AAAAAAAA', - })) - - const output = await compressImage(source, {maxDimension: 2000, maxSize: 3}) - - expect(qualities(renders)).toEqual([0.51, 0.76, 0.64, 0.7, 0.73, 0.72, 0.71]) - expect(output.path).toBe( - IS_NATIVE - ? 'file:///cache/bsky-composer/cached-3' - : 'file:///rendered-4.jpg', - ) - expect(moveAsync).toHaveBeenCalledTimes(IS_NATIVE ? 3 : 0) - if (IS_NATIVE) { - expect(jest.mocked(moveAsync).mock.calls.map(([{from}]) => from)).toEqual([ - 'file:///rendered-1.jpg', - 'file:///rendered-3.jpg', - 'file:///rendered-4.jpg', - ]) - } -}) - -it('reduces dimensions by 0.8 rather than rendering at quality 13', async () => { - const renders = fakeRenderer((_options, index) => ({ - base64: index <= 2 ? 'AAAAAAAA' : 'AAAA', - })) - const policy = Object.freeze({maxDimension: 2001, maxSize: 3}) - await compressImage(source, policy) - - expect(qualities(renders)).toEqual([ - 0.51, 0.26, 0.51, 0.76, 0.89, 0.95, 0.98, 1, - ]) - expect(renders.map(render => render.resize.mock.calls[0][0])).toEqual([ - {width: 2001, height: 1000}, - {width: 2001, height: 1000}, - ...Array(6).fill({width: 1600, height: 800}), - ]) - expect(policy.maxDimension).toBe(2001) -}) - -it.each(['AAAAAAAA', undefined, ''])( - 'stops after four dimension attempts for oversized or missing base64 (%s)', - async base64 => { - const renders = fakeRenderer(() => ({base64})) - await expect( - compressImage(source, {maxDimension: 4000, maxSize: 3}), - ).rejects.toThrow('Unable to compress image') - - expect(qualities(renders)).toEqual([ - 0.51, 0.26, 0.51, 0.26, 0.51, 0.26, 0.51, 0.26, - ]) - expect(renders.map(render => render.resize.mock.calls[0][0].width)).toEqual( - [4000, 4000, 3200, 3200, 2560, 2560, 2048, 2048], - ) - expect(moveAsync).not.toHaveBeenCalled() - expect(makeDirectoryAsync).not.toHaveBeenCalled() - }, -) - -it('propagates render errors and releases the manipulator context', async () => { - const release = jest.fn() - jest.mocked(ImageManipulator.manipulate).mockReturnValue({ - resize: jest.fn(), - renderAsync: jest.fn().mockRejectedValue(new Error('render failed')), - release, - } as unknown as ImageManipulatorContext) - - await expect( - compressImage(source, {maxDimension: 2000, maxSize: 3}), - ).rejects.toThrow('render failed') - expect(release).toHaveBeenCalledTimes(1) - expect(moveAsync).not.toHaveBeenCalled() -}) - -it('propagates save errors and releases both native handles', async () => { - const renders = fakeRenderer(() => { - throw new Error('save failed') - }) - await expect( - compressImage(source, {maxDimension: 2000, maxSize: 3}), - ).rejects.toThrow('save failed') - expect(renders[0].release).toHaveBeenCalledTimes(1) - expect(renders[0].image.release).toHaveBeenCalledTimes(1) - expect(moveAsync).not.toHaveBeenCalled() -}) diff --git a/src/lib/media/image/compress.ts b/src/lib/media/image/compress.ts deleted file mode 100644 index 1f8b3b51d..000000000 --- a/src/lib/media/image/compress.ts +++ /dev/null @@ -1,104 +0,0 @@ -import {SaveFormat} from 'expo-image-manipulator' - -import {moveIfNecessary} from '#/lib/media/image/cache' -import {renderImage} from '#/lib/media/image-manipulator' -import {type PickerImage} from '#/lib/media/picker.shared' -import {getDataUriSize} from '#/lib/media/util' -import {type ComposerImage} from '#/state/gallery' - -export async function compressImage( - img: ComposerImage, - {maxDimension, maxSize}: {maxDimension: number; maxSize: number}, -): Promise { - const source = img.transformed || img.source - - let attempts = 0 - /* - * Seeded from `maxDimension` but shrunk per attempt below, so keep the - * passed-in value pristine. - */ - let currentDimension = maxDimension - const maxBytes = maxSize - - let minQualityPercentage = 0 - let maxQualityPercentage = 101 // exclusive - let newDataUri - - while (maxQualityPercentage - minQualityPercentage > 1) { - if (attempts >= 4) break - - const [w, h] = containImageRes( - source.width, - source.height, - currentDimension, - ) - const qualityPercentage = Math.round( - (maxQualityPercentage + minQualityPercentage) / 2, - ) - - /* - * In the event the image doesn't compress well, we want to avoid - * unecessary iterations. In this case, binary search will check 51, 26, - * 13(rounded). We don't want to go below 25, so if we've halved to 13, - * reset the loop and reduce the image dimensions instead. - */ - if (qualityPercentage <= 13) { - minQualityPercentage = 0 - maxQualityPercentage = 101 - attempts++ - /* - * max.width -> 0.8x -> 0.64x -> 0.512x -> ~0.41x - * e.g. 4000px -> 3200px -> 2560px -> 2048px -> ~1638px - */ - currentDimension = Math.floor(currentDimension * 0.8) - continue - } - - const res = await renderImage( - source.path, - context => context.resize({width: w, height: h}), - { - compress: qualityPercentage / 100, - format: SaveFormat.JPEG, - base64: true, - }, - ) - - const base64 = res.base64 - const size = base64 ? getDataUriSize(base64) : 0 - if (base64 && size <= maxBytes) { - minQualityPercentage = qualityPercentage - newDataUri = { - path: await moveIfNecessary(res.uri), - width: res.width, - height: res.height, - mime: 'image/jpeg', - size, - } - } else { - maxQualityPercentage = qualityPercentage - } - } - - if (newDataUri) { - return newDataUri - } - - throw new Error(`Unable to compress image`) -} - -function containImageRes( - w: number, - h: number, - max: number, -): [width: number, height: number] { - let scale = 1 - - if (w > max || h > max) { - scale = w > h ? max / w : max / h - w = Math.floor(w * scale) - h = Math.floor(h * scale) - } - - return [w, h] -} diff --git a/src/lib/media/image/testSetup.ts b/src/lib/media/image/testSetup.ts deleted file mode 100644 index fb0727e3d..000000000 --- a/src/lib/media/image/testSetup.ts +++ /dev/null @@ -1,7 +0,0 @@ -/* JSDOM lacks matchMedia; keep the real platform-specific env module in tests. */ -if (typeof window !== 'undefined' && !window.matchMedia) { - Object.defineProperty(window, 'matchMedia', { - configurable: true, - value: jest.fn().mockReturnValue({matches: false}), - }) -} diff --git a/src/state/gallery.ts b/src/state/gallery.ts index c74858c88..15c3a9e5b 100644 --- a/src/state/gallery.ts +++ b/src/state/gallery.ts @@ -3,24 +3,20 @@ import { copyAsync, deleteAsync, makeDirectoryAsync, + moveAsync, } from 'expo-file-system/legacy' import {type ImageManipulatorContext, SaveFormat} from 'expo-image-manipulator' import {nanoid} from 'nanoid/non-secure' -import { - getImageCacheDirectory, - joinPath, - moveIfNecessary, -} from '#/lib/media/image/cache' import {renderImage} from '#/lib/media/image-manipulator' import {getImageDim} from '#/lib/media/manip' import {openCropper} from '#/lib/media/picker' +import {type PickerImage} from '#/lib/media/picker.shared' +import {getDataUriSize} from '#/lib/media/util' import {isCancelledError} from '#/lib/strings/errors' import {logger} from '#/logger' import {IS_NATIVE, IS_WEB} from '#/env' -export {compressImage} from '#/lib/media/image/compress' - export type ImageTransformation = { crop?: Parameters[0] } @@ -54,6 +50,16 @@ type ComposerImageWithTransformation = ComposerImageBase & { export type ComposerImage = ComposerImageWithoutTransformation | ComposerImageWithTransformation +let _imageCacheDirectory: string + +function getImageCacheDirectory(): string | null { + if (IS_NATIVE) { + return (_imageCacheDirectory ??= joinPath(cacheDirectory!, 'bsky-composer')) + } + + return null +} + export async function createComposerImage( raw: ImageMeta, ): Promise { @@ -187,6 +193,98 @@ export function resetImageManipulation( return img } +export async function compressImage( + img: ComposerImage, + {maxDimension, maxSize}: {maxDimension: number; maxSize: number}, +): Promise { + const source = img.transformed || img.source + + let attempts = 0 + // Seeded from `maxDimension` but shrunk per attempt below, so keep the + // passed-in value pristine. + let currentDimension = maxDimension + const maxBytes = maxSize + + let minQualityPercentage = 0 + let maxQualityPercentage = 101 // exclusive + let newDataUri + + while (maxQualityPercentage - minQualityPercentage > 1) { + if (attempts >= 4) break + + const [w, h] = containImageRes( + source.width, + source.height, + currentDimension, + ) + const qualityPercentage = Math.round( + (maxQualityPercentage + minQualityPercentage) / 2, + ) + + /* + * In the event the image doesn't compress well, we want to avoid + * unecessary iterations. In this case, binary search will check 51, 26, + * 13(rounded). We don't want to go below 25, so if we've halved to 13, + * reset the loop and reduce the image dimensions instead. + */ + if (qualityPercentage <= 13) { + minQualityPercentage = 0 + maxQualityPercentage = 101 + attempts++ + // max.width → 0.8× → 0.64× → 0.512× → ~0.41× + // e.g. 4000px → 3200px → 2560px → 2048px → ~1638px + currentDimension = Math.floor(currentDimension * 0.8) + continue + } + + const res = await renderImage( + source.path, + context => context.resize({width: w, height: h}), + { + compress: qualityPercentage / 100, + format: SaveFormat.JPEG, + base64: true, + }, + ) + + const base64 = res.base64 + const size = base64 ? getDataUriSize(base64) : 0 + if (base64 && size <= maxBytes) { + minQualityPercentage = qualityPercentage + newDataUri = { + path: await moveIfNecessary(res.uri), + width: res.width, + height: res.height, + mime: 'image/jpeg', + size, + } + } else { + maxQualityPercentage = qualityPercentage + } + } + + if (newDataUri) { + return newDataUri + } + + throw new Error(`Unable to compress image`) +} + +async function moveIfNecessary(from: string) { + const cacheDir = IS_NATIVE && getImageCacheDirectory() + + if (cacheDir && !from.startsWith(cacheDir)) { + const to = joinPath(cacheDir, nanoid(36)) + + await makeDirectoryAsync(cacheDir, {intermediates: true}) + await moveAsync({from, to}) + + return to + } + + return from +} + /** * Copy a file from a potentially temporary location to our cache directory. * This ensures picker files are available for draft saving even if the original @@ -284,3 +382,31 @@ export async function purgeTemporaryImageFiles() { ), ) } + +function joinPath(a: string, b: string) { + if (a.endsWith('/')) { + if (b.startsWith('/')) { + return a.slice(0, -1) + b + } + return a + b + } else if (b.startsWith('/')) { + return a + b + } + return a + '/' + b +} + +function containImageRes( + w: number, + h: number, + max: number, +): [width: number, height: number] { + let scale = 1 + + if (w > max || h > max) { + scale = w > h ? max / w : max / h + w = Math.floor(w * scale) + h = Math.floor(h * scale) + } + + return [w, h] +} -- knotmirror 0.0.1