feat: move imageSize function to util file

This commit is contained in:
Jacob Overgaard
2024-09-20 09:04:21 +02:00
parent 5ac2a8ddb6
commit fe4796ae27
3 changed files with 31 additions and 30 deletions

View File

@@ -1,3 +1,4 @@
import { imageSize } from '../../utils/index.js';
import { UmbTiptapExtensionApiBase, type UmbTiptapExtensionArgs } from '../types.js';
import {
TemporaryFileStatus,
@@ -98,7 +99,7 @@ export default class UmbTiptapMediaUploadExtension extends UmbTiptapExtensionApi
return;
}
let { width, height } = await this.#imageSize(URL.createObjectURL(upload.file));
let { width, height } = await imageSize(URL.createObjectURL(upload.file));
if (maxImageSize > 0 && width > maxImageSize) {
const ratio = maxImageSize / width;
@@ -131,33 +132,4 @@ export default class UmbTiptapMediaUploadExtension extends UmbTiptapExtensionApi
#filterFiles(files: FileList): File[] {
return Array.from(files).filter((file) => this.allowedFileTypes.includes(file.type));
}
/**
* Get the dimensions of an image from a URL.
* @param {string} url The URL of the image. It can be a local file (blob url) or a remote file.
* @returns {Promise<{width: number, height: number}>} The width and height of the image as downloaded from the URL.
*/
#imageSize(url: string): Promise<{ width: number; height: number }> {
const img = new Image();
const promise = new Promise<{ width: number; height: number }>((resolve, reject) => {
img.onload = () => {
// Natural size is the actual image size regardless of rendering.
// The 'normal' `width`/`height` are for the **rendered** size.
const width = img.naturalWidth;
const height = img.naturalHeight;
// Resolve promise with the width and height
resolve({ width, height });
};
// Reject promise on error
img.onerror = reject;
});
// Setting the source makes it start downloading and eventually call `onload`
img.src = url;
return promise;
}
}

View File

@@ -1,2 +1,3 @@
export * from './components/index.js';
export * from './extensions/index.js';
export * from './utils/index.js';

View File

@@ -0,0 +1,28 @@
/**
* Get the dimensions of an image from a URL.
* @param {string} url The URL of the image. It can be a local file (blob url) or a remote file.
* @returns {Promise<{width: number, height: number}>} The width and height of the image as downloaded from the URL.
*/
export function imageSize(url: string): Promise<{ width: number; height: number }> {
const img = new Image();
const promise = new Promise<{ width: number; height: number }>((resolve, reject) => {
img.onload = () => {
// Natural size is the actual image size regardless of rendering.
// The 'normal' `width`/`height` are for the **rendered** size.
const width = img.naturalWidth;
const height = img.naturalHeight;
// Resolve promise with the width and height
resolve({ width, height });
};
// Reject promise on error
img.onerror = reject;
});
// Setting the source makes it start downloading and eventually call `onload`
img.src = url;
return promise;
}