2024-06-04 01:02:46 -05:00
|
|
|
import { fromByteArray } from 'base64-js';
|
|
|
|
|
2024-06-03 10:29:33 -05:00
|
|
|
import { imagesLibrary } from '@plugin/ImageLibrary';
|
2024-05-13 10:04:13 -05:00
|
|
|
import { detectMimeType } from '@plugin/utils';
|
|
|
|
|
|
|
|
import { Fill } from '@ui/lib/types/utils/fill';
|
|
|
|
import { ImageColor } from '@ui/lib/types/utils/imageColor';
|
|
|
|
|
|
|
|
export const translateImageFill = async (fill: ImagePaint): Promise<Fill | undefined> => {
|
|
|
|
const fillImage = await translateImage(fill.imageHash);
|
|
|
|
if (!fillImage) return;
|
|
|
|
|
|
|
|
return {
|
|
|
|
fillOpacity: !fill.visible ? 0 : fill.opacity,
|
2024-06-03 10:29:33 -05:00
|
|
|
fillImage
|
2024-05-13 10:04:13 -05:00
|
|
|
};
|
|
|
|
};
|
|
|
|
|
|
|
|
const translateImage = async (imageHash: string | null): Promise<ImageColor | undefined> => {
|
|
|
|
if (!imageHash) return;
|
|
|
|
|
2024-06-03 10:29:33 -05:00
|
|
|
const imageColor = imagesLibrary.get(imageHash) ?? (await generateAndRegister(imageHash));
|
|
|
|
|
|
|
|
if (!imageColor) return;
|
|
|
|
|
|
|
|
const { dataUri, ...rest } = imageColor;
|
|
|
|
|
|
|
|
return {
|
|
|
|
...rest,
|
|
|
|
imageHash
|
|
|
|
};
|
|
|
|
};
|
|
|
|
|
|
|
|
const generateAndRegister = async (imageHash: string) => {
|
2024-05-13 10:04:13 -05:00
|
|
|
const image = figma.getImageByHash(imageHash);
|
2024-06-03 10:29:33 -05:00
|
|
|
|
2024-05-13 10:04:13 -05:00
|
|
|
if (!image) return;
|
|
|
|
|
|
|
|
const bytes = await image.getBytesAsync();
|
2024-06-03 10:29:33 -05:00
|
|
|
const { width, height } = await image.getSizeAsync();
|
2024-06-04 01:02:46 -05:00
|
|
|
const b64 = fromByteArray(bytes);
|
2024-06-03 10:29:33 -05:00
|
|
|
const mtype = detectMimeType(b64);
|
|
|
|
const dataUri = `data:${mtype};base64,${b64}`;
|
2024-05-13 10:04:13 -05:00
|
|
|
|
2024-06-03 10:29:33 -05:00
|
|
|
const imageColor: ImageColor = {
|
|
|
|
width,
|
|
|
|
height,
|
|
|
|
mtype,
|
|
|
|
dataUri,
|
2024-05-13 10:04:13 -05:00
|
|
|
keepAspectRatio: true,
|
|
|
|
id: '00000000-0000-0000-0000-000000000000'
|
|
|
|
};
|
2024-06-03 10:29:33 -05:00
|
|
|
|
|
|
|
imagesLibrary.register(imageHash, imageColor);
|
|
|
|
|
|
|
|
return imageColor;
|
2024-05-13 10:04:13 -05:00
|
|
|
};
|