Skip to content

Mysterious egg dafl 2 #4020

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Feb 12, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 70 additions & 29 deletions addons/html_builder/static/src/plugins/image_gallery_option.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { registry } from "@web/core/registry";
import { Plugin } from "@html_editor/plugin";
import { applyModifications, loadImageInfo } from "@html_editor/utils/image_processing";

class ImageGalleryOption extends Plugin {
static id = "ImageGalleryOption";
Expand All @@ -17,19 +18,25 @@ class ImageGalleryOption extends Plugin {
getActions() {
return {
addImage: {
load: async () =>
new Promise((resolve) => {
load: async ({ editingElement }) => {
let selectedImages;
await new Promise((resolve) => {
this.dependencies.media.openMediaDialog({
onlyImages: true,
multiImages: true,
save: (images) => {
resolve(images);
selectedImages = images;
resolve();
},
});
}),
});
await transformImagesToWebp(selectedImages);
setImageProperties(editingElement, selectedImages);
const clonedContainerImg = await cloneContainerImages(editingElement);
return [...clonedContainerImg, ...selectedImages];
},
apply: ({ editingElement, loadResult: images }) => {
addImages(images, editingElement);
this.dependencies.history.addStep();
setImages(editingElement, images);
},
},
removeAllImages: {
Expand All @@ -43,13 +50,13 @@ class ImageGalleryOption extends Plugin {
/**
* Add the images selected in the media dialog in the gallery
*/
function addImages(images, imageGalleryElement) {
const container = getContainer(imageGalleryElement);
if (!container) {
return;
async function setImages(imageGalleryElement, images) {
if (getMode(imageGalleryElement) === "masonry") {
masonry(imageGalleryElement, images);
}
container.append(...images);
}

function setImageProperties(imageGalleryElement, images) {
const lastImage = getImages(imageGalleryElement).at(-1);
let lastIndex = lastImage ? getIndex(lastImage) : -1;
for (const image of images) {
Expand All @@ -62,24 +69,41 @@ function addImages(images, imageGalleryElement) {
"object-fit-cover"
);
image.dataset.index = ++lastIndex;
// TODO: Change mimetype
}
relayout(imageGalleryElement);
}

/**
* Redraw the current layout
* @param {Element} imageGalleryElement
*/
function relayout(imageGalleryElement) {
// TODO DAFL: implement other layout
if (getMode(imageGalleryElement) === "masonry") {
masonry(imageGalleryElement);
async function transformImagesToWebp(images) {
const imagePromises = [];
for (const imgEl of images) {
imagePromises.push(
new Promise((resolve) => {
loadImageInfo(imgEl).then(() => {
if (
imgEl.dataset.mimetype &&
!["image/gif", "image/svg+xml", "image/webp"].includes(
imgEl.dataset.mimetype
)
) {
// Convert to webp but keep original width.
imgEl.dataset.mimetype = "image/webp";
applyModifications(imgEl, {
mimetype: "image/webp",
}).then((src) => {
imgEl.src = src;
imgEl.classList.add("o_modified_image_to_save");
resolve();
});
} else {
resolve();
}
});
})
);
}
return Promise.all(imagePromises);
}

function masonry(imageGalleryElement) {
const imagesHolder = getImageHolder(imageGalleryElement);
function masonry(imageGalleryElement, images) {
const columnsNumber = getColumns(imageGalleryElement);
const colClass = "col-lg-" + 12 / columnsNumber;
const columns = [];
Expand All @@ -96,7 +120,7 @@ function masonry(imageGalleryElement) {
}

// Dispatch images in columns by always putting the next one in the smallest height column
for (const imageEl of imagesHolder) {
for (const imageEl of images) {
let min = Infinity;
let smallestColEl;
for (const colEl of columns) {
Expand All @@ -109,11 +133,7 @@ function masonry(imageGalleryElement) {
smallestColEl = colEl;
}
}
// Only on Chrome: appended images are sometimes invisible
// and not correctly loaded from cache, we use a clone of the
// image to force the loading.
const newImg = imageEl.cloneNode(true);
smallestColEl.append(newImg);
smallestColEl.append(imageEl);
}
}

Expand Down Expand Up @@ -149,6 +169,27 @@ function getImageHolder(currentContainer) {
return [...images].map((image) => image.closest("a") || image);
}

async function cloneContainerImages(imageGalleryElement) {
const imagesHolder = getImageHolder(imageGalleryElement);
const newImgs = [];
const imgLoaded = [];
for (const image of imagesHolder) {
// Only on Chrome: appended images are sometimes invisible
// and not correctly loaded from cache, we use a clone of the
// image to force the loading.
const newImg = image.cloneNode(true);
newImg.loading = "eager";
imgLoaded.push(
newImg.decode().then(() => {
newImg.loading = "lazy";
})
);
newImgs.push(newImg);
}
await Promise.all(imgLoaded);
return newImgs;
}

/**
* Relayout the imageGalleryElement with the "masonry" layout.
* @param {Element} imageGalleryElement
Expand Down
3 changes: 0 additions & 3 deletions addons/html_builder/static/src/plugins/image_tool_option.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import {
loadImage,
} from "@html_editor/utils/image_processing";
import { Component } from "@odoo/owl";
import { loadBundle } from "@web/core/assets";
import { registry } from "@web/core/registry";
import { defaultBuilderComponents } from "../core/default_builder_components";
import { AddElementOption } from "./add_element_option";
Expand Down Expand Up @@ -44,7 +43,6 @@ class ImageToolOptionPlugin extends Plugin {
// todo: This seems quite heavy for a simple reset. Retrieve some
// metadata, to load the image crop, to call processImageCrop, just to
// reset the crop. We might want to simplify this.
await loadBundle("html_editor.assets_image_cropper");
const croppedImage = editingElement;

const container = document.createElement("div");
Expand Down Expand Up @@ -109,7 +107,6 @@ class ImageToolOptionPlugin extends Plugin {
}
},
load: async ({ editingElement, param: glFilterName }) => {
await loadBundle("html_editor.assets_image_cropper");
editingElement.dataset.glFilter = glFilterName;
const newSrc = await applyModifications(editingElement, {
mimetype: getImageMimetype(editingElement),
Expand Down
61 changes: 55 additions & 6 deletions addons/html_builder/static/tests/options/image_gallery.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,49 @@ import { expect, test } from "@odoo/hoot";
import { contains, onRpc } from "@web/../tests/web_test_helpers";
import { defineWebsiteModels, dummyBase64Img, setupWebsiteBuilder } from "../helpers";
import { animationFrame, click, queryAll, waitFor } from "@odoo/hoot-dom";
import { MockResponse } from "@web/../lib/hoot/mock/network";

defineWebsiteModels();

test("Add image in gallery", async () => {
onRpc("/web/dataset/call_kw/ir.attachment/search_read", (test) => [
onRpc("/web/dataset/call_kw/ir.attachment/search_read", () => [
{
id: 1,
name: "logo",
mimetype: "image/png",
image_src: "/web/static/img/logo2.png",
image_src: "/web/image/hoot.png",
access_token: false,
public: true,
},
]);

onRpc("/html_editor/get_image_info", () => {
expect.step("get_image_info");
return {
attachment: {
id: 1,
},
original: {
id: 1,
image_src: "/web/image/hoot.png",
mimetype: "image/png",
},
};
});

onRpc(
"/web/image/hoot.png",
() => {
const mockResponse = new MockResponse({ ok: 200 });
const base64Image =
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAIAQMAAAD+wSzIAAAABlBMVEX///+/v7+jQ3Y5AAAADklEQVQI12P4AIX8EAgALgAD/aNpbtEAAAAASUVORK5CYII=";
const blob = dataURItoBlob(base64Image);
mockResponse.blob = () => blob;
return mockResponse;
},
{ pure: true }
);

await setupWebsiteBuilder(
`
<section class="s_image_gallery o_masonry" data-columns="2">
Expand All @@ -35,17 +64,37 @@ test("Add image in gallery", async () => {
);
await contains(":iframe .first_img").click();
expect("[data-action-id='addImage']").toHaveCount(1);
await click("[data-action-id='addImage']");
await animationFrame();
await contains("[data-action-id='addImage']").click();
// We use "click" instead of contains.click because contains wait for the image to be visible.
// In this test we don't want to wait ~800ms for the image to be visible but we can still click on it
await click("img.o_we_attachment_highlight");
await animationFrame();
await click(".modal-footer button");
await waitFor(":iframe img[data-index='6']");
await contains(".modal-footer button").click();
await waitFor(":iframe .o_masonry_col img[data-index='6']");

const columns = queryAll(":iframe .o_masonry_col");
const columnImgs = columns.map((column) =>
[...column.children].map((img) => img.dataset.index)
);

expect(columnImgs).toEqual([["1", "3", "4", "5", "6"], ["2"]]);
expect.verifySteps(["get_image_info"]);
expect(":iframe .o_masonry_col img[data-index='6']").toHaveAttribute(
"data-mimetype",
"image/webp"
);
expect(":iframe .o_masonry_col img[data-index='6']").toHaveAttribute(
"data-mimetype-before-conversion",
"image/png"
);
});

function dataURItoBlob(dataURI) {
const binary = atob(dataURI.split(",")[1]);
const array = [];
const mimeString = dataURI.split(",")[0].split(":")[1].split(";")[0];
for (let i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
return new Blob([new Uint8Array(array)], { type: mimeString });
}
3 changes: 0 additions & 3 deletions addons/html_editor/static/src/main/media/image_crop_plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { registry } from "@web/core/registry";
import { Plugin } from "../../plugin";
import { _t } from "@web/core/l10n/translation";
import { ImageCrop } from "./image_crop";
import { loadBundle } from "@web/core/assets";
import { withSequence } from "@html_editor/utils/resource";

export class ImageCropPlugin extends Plugin {
Expand Down Expand Up @@ -58,8 +57,6 @@ export class ImageCropPlugin extends Plugin {
this.dependencies.history.addStep();
};

await loadBundle("html_editor.assets_image_cropper");

registry.category("main_components").add("ImageCropping", {
Component: ImageCrop,
props: { ...this.imageCropProps, onClose, onSave, document: this.document },
Expand Down
2 changes: 2 additions & 0 deletions addons/html_editor/static/src/utils/image_processing.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { rpc } from "@web/core/network/rpc";
import { pick } from "@web/core/utils/objects";
import { getAffineApproximation, getProjective } from "./perspective_utils";
import { loadBundle } from "@web/core/assets";

// Fields returned by cropperjs 'getData' method, also need to be passed when
// initializing the cropper to reuse the previous crop.
Expand Down Expand Up @@ -495,6 +496,7 @@ function _getImageSizeFromCache(src) {
* @param {DOMStringMap} dataset dataset containing the cropperDataFields
*/
export async function activateCropper(image, aspectRatio, dataset, cropperOptions) {
await loadBundle("html_editor.assets_image_cropper");
const oldSrc = image.src;
const newSrc = await _loadImageObjectURL(image.getAttribute("src"));
image.src = newSrc;
Expand Down
6 changes: 5 additions & 1 deletion addons/web/static/lib/hoot/mock/network.js
Original file line number Diff line number Diff line change
Expand Up @@ -779,7 +779,11 @@ export class MockXMLHttpRequest extends EventTarget {
headers: this._headers,
});
this._status = response.status;
this._response = await response.text();
if (new URL(this._url, mockLocation.origin).protocol === "blob:") {
this._response = await response.arrayBuffer();
} else {
this._response = await response.text();
}
this.dispatchEvent(new ProgressEvent("load"));
} catch (error) {
this.dispatchEvent(new ProgressEvent("error", { error }));
Expand Down