ai*
This commit is contained in:
14
ai_website/static/src/ai_processing_state.js
Normal file
14
ai_website/static/src/ai_processing_state.js
Normal file
@@ -0,0 +1,14 @@
|
||||
/** Shared state tracking whether the current AI turn (including any
|
||||
* multi-step tool loop, e.g. create_page navigation) is still in progress. */
|
||||
let pendingAiResponsePromise = null;
|
||||
|
||||
export function getAiResponsePromise() {
|
||||
return pendingAiResponsePromise;
|
||||
}
|
||||
|
||||
export function setAiResponsePromise(promise) {
|
||||
pendingAiResponsePromise = promise;
|
||||
pendingAiResponsePromise.finally(() => {
|
||||
pendingAiResponsePromise = null;
|
||||
});
|
||||
}
|
||||
33
ai_website/static/src/builder/ai_generated_scripts_panel.js
Normal file
33
ai_website/static/src/builder/ai_generated_scripts_panel.js
Normal file
@@ -0,0 +1,33 @@
|
||||
import { Component, t, useProps } from "@odoo/owl";
|
||||
import { useOperation } from "@html_builder/core/operation_plugin";
|
||||
import { getScriptTitle } from "../utils";
|
||||
|
||||
export class AiGeneratedScriptsPanel extends Component {
|
||||
static template = "ai_website.AiGeneratedScriptsPanel";
|
||||
|
||||
props = useProps({
|
||||
scripts: t.array(),
|
||||
});
|
||||
|
||||
setup() {
|
||||
this.callOperation = useOperation();
|
||||
}
|
||||
|
||||
get shared() {
|
||||
return this.env.editor.shared;
|
||||
}
|
||||
|
||||
getScriptTitle = getScriptTitle;
|
||||
|
||||
stopScript(scriptEl) {
|
||||
this.shared.aiScript.stopScript(scriptEl);
|
||||
}
|
||||
|
||||
runScript(scriptEl) {
|
||||
this.shared.aiScript.runScript(scriptEl);
|
||||
}
|
||||
|
||||
removeScript(scriptEl) {
|
||||
this.callOperation(() => this.shared.aiScript.removeScript(scriptEl));
|
||||
}
|
||||
}
|
||||
32
ai_website/static/src/builder/ai_generated_scripts_panel.xml
Normal file
32
ai_website/static/src/builder/ai_generated_scripts_panel.xml
Normal file
@@ -0,0 +1,32 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<templates xml:space="preserve">
|
||||
|
||||
<t t-name="ai_website.AiGeneratedScriptsPanel">
|
||||
<div class="o_we_ai_gen_scripts_panel d-contents" t-if="this.props.scripts.length">
|
||||
<div class="o_panel_header">
|
||||
AI-generated scripts
|
||||
</div>
|
||||
<t t-foreach="this.props.scripts" t-as="script" t-key="script_index">
|
||||
<div class="o_script_entry d-flex py-1 align-items-center justify-content-between">
|
||||
<div class="o_title" t-out="this.getScriptTitle(script.el)"/>
|
||||
<div class="ms-2">
|
||||
<t t-if="!script.isStopped">
|
||||
<button class="btn" t-on-click="() => this.stopScript(script.el)">
|
||||
<i class='oi o_text_orange' data-icon='pause'/>
|
||||
</button>
|
||||
</t>
|
||||
<t t-else="">
|
||||
<button class="btn" t-on-click="() => this.runScript(script.el)">
|
||||
<i class="oi text-success" data-icon="play_arrow"/>
|
||||
</button>
|
||||
</t>
|
||||
<button class="btn" t-on-click="() => this.removeScript(script.el)">
|
||||
<i class="oi oi-filled text-danger" data-icon="delete"/>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</t>
|
||||
</div>
|
||||
</t>
|
||||
|
||||
</templates>
|
||||
9
ai_website/static/src/builder/ai_website_builder.scss
Normal file
9
ai_website/static/src/builder/ai_website_builder.scss
Normal file
@@ -0,0 +1,9 @@
|
||||
.o_we_ai_gen_scripts_panel {
|
||||
.o_panel_header {
|
||||
padding: $o-we-sidebar-content-field-spacing 0;
|
||||
}
|
||||
|
||||
.o_script_entry {
|
||||
padding: $o-we-sidebar-content-field-spacing $o-we-sidebar-content-field-clickable-spacing;
|
||||
}
|
||||
}
|
||||
833
ai_website/static/src/builder/ai_website_builder_plugin.js
Normal file
833
ai_website/static/src/builder/ai_website_builder_plugin.js
Normal file
@@ -0,0 +1,833 @@
|
||||
import { Plugin } from "@html_editor/plugin";
|
||||
import { _t } from "@web/core/l10n/translation";
|
||||
import { registry } from "@web/core/registry";
|
||||
import { rpc } from "@web/core/network/rpc";
|
||||
import { browser } from "@web/core/browser/browser";
|
||||
import { getModelName } from "@website/builder/plugins/form/utils";
|
||||
import { aiChannelBus } from "@ai/utils/ai_channel_bus";
|
||||
import { getData, triggers } from "@ai/utils/bus_data_getter";
|
||||
import { getCSSVariableValue, getHtmlStyle } from "@html_editor/utils/formatting";
|
||||
import { EDITOR_COLOR_CSS_VARIABLES } from "@html_editor/utils/color";
|
||||
import {
|
||||
AI_EDITABLE_ZONE_SELECTORS,
|
||||
AI_WEBSITE_TYPING_TIMEOUT,
|
||||
isAiWebsiteBuilderChannel,
|
||||
isPageAiEditable,
|
||||
pollForData,
|
||||
} from "@ai_website/utils";
|
||||
import { aiClientToolsRegistry } from "@ai/discuss/core/common/ai_client_tool_registry";
|
||||
import { getAiResponsePromise } from "@ai_website/ai_processing_state";
|
||||
|
||||
triggers.add("aiWebsitePage");
|
||||
|
||||
const CSS_RELOAD_MAX_WAIT = 4000;
|
||||
const EDITOR_RELOAD_MAX_WAIT = 30000;
|
||||
const SCRAPER_RECOVERY_DELAY = 5000;
|
||||
|
||||
const ANIMATION_RUNTIME_CLASSES = [
|
||||
"o_visible",
|
||||
"o_animated",
|
||||
"o_animating",
|
||||
"o_animate_preview",
|
||||
"o_animate_in_dropdown",
|
||||
];
|
||||
const ANIMATION_RUNTIME_STYLE_PROPS = ["visibility", "animation-play-state", "animation-name"];
|
||||
|
||||
/**
|
||||
* AI Website Builder Plugin — integrates AI generation with the website builder.
|
||||
*/
|
||||
export class AiWebsiteBuilderPlugin extends Plugin {
|
||||
static id = "aiWebsiteBuilder";
|
||||
static dependencies = [
|
||||
"aiScript",
|
||||
"customizeWebsite",
|
||||
"externalImageSave",
|
||||
"history",
|
||||
"operation",
|
||||
"position",
|
||||
"sanitize",
|
||||
"savePlugin",
|
||||
"websiteFormOption",
|
||||
];
|
||||
|
||||
static shared = ["registerClientToolWithMutex"];
|
||||
|
||||
aiTools = [];
|
||||
|
||||
resources = {
|
||||
on_editor_started_handlers: () => {
|
||||
this.scraperRecoveryStarted = true;
|
||||
this.recoverScraperResults();
|
||||
},
|
||||
};
|
||||
|
||||
setup() {
|
||||
const bus = this.services.bus_service;
|
||||
this.scraperResumes = new Set();
|
||||
this.scraperResumeAttempts = new Set();
|
||||
// CSS reloads are still bus-driven: they are also fired by the
|
||||
// server-side refinement pass, outside of any tool call.
|
||||
// Keep the bound handler so it can be unsubscribed on destroy: the bus
|
||||
// service outlives the plugin and a stale handler would otherwise run
|
||||
// on a destroyed editor (e.g. after a menu edit reloads it).
|
||||
this.busHandlers = {
|
||||
"ai_website/reload_css_bundles": () => this.reloadCssBundles(),
|
||||
"ai_website/scraper_result_ready": this.resumeAfterScraping.bind(this),
|
||||
};
|
||||
for (const [eventName, handler] of Object.entries(this.busHandlers)) {
|
||||
bus.subscribe(eventName, handler);
|
||||
}
|
||||
// Skip when a recovery is already scheduled
|
||||
this.onBusConnected = () => {
|
||||
if (!this.scraperRecoveryTimer) {
|
||||
this.recoverScraperResults();
|
||||
}
|
||||
};
|
||||
for (const event of ["BUS:CONNECT", "BUS:RECONNECT"]) {
|
||||
bus.addEventListener(event, this.onBusConnected);
|
||||
}
|
||||
bus.start();
|
||||
this.registerClientToolWithMutex("website_apply_html", (params) =>
|
||||
this.applyActions(params)
|
||||
);
|
||||
this.registerClientToolWithMutex("website_reload_editor", (params) =>
|
||||
this.reloadEditor(params)
|
||||
);
|
||||
this.registerClientToolWithMutex("website_set_form_action", (params) =>
|
||||
this.setFormAction(params)
|
||||
);
|
||||
// `useDataGetter` is an Owl hook and a plugin is not a component.
|
||||
this.onFinalizeRequest = () =>
|
||||
aiChannelBus.trigger("aiWebsitePage!", {
|
||||
finalizePage: this.finalizePage.bind(this),
|
||||
});
|
||||
aiChannelBus.addEventListener("aiWebsitePage?", this.onFinalizeRequest);
|
||||
this.onPageContextRequest = () => {
|
||||
if (!this.isDestroyed) {
|
||||
aiChannelBus.trigger("view!", { website_page: this.getPageAiContext() });
|
||||
}
|
||||
};
|
||||
aiChannelBus.addEventListener("view?", this.onPageContextRequest);
|
||||
aiChannelBus.trigger("aiWebsiteEditorStarted");
|
||||
this.toggleAiChatWindows(true);
|
||||
|
||||
this.registerClientToolWithMutex("ai_website_navigate_to_edit", (params) =>
|
||||
this.navigateToEditClientTool(params)
|
||||
);
|
||||
|
||||
// If the iframe navigated to a new page while the agent was still
|
||||
// working (e.g. after create_page), the previous loading screen
|
||||
// was destroyed with the old iframe document.
|
||||
// Re-apply the same block used for a normal AI turn so the new page
|
||||
// stays locked until the agent finishes (or the safety timeout hits).
|
||||
const aiResponsePromise = getAiResponsePromise();
|
||||
if (aiResponsePromise) {
|
||||
(async () => {
|
||||
const builder = await pollForData("htmlBuilder");
|
||||
if (!builder) {
|
||||
return;
|
||||
}
|
||||
const unblockBuilderUI = builder.blockBuilderUI();
|
||||
const timeoutId = browser.setTimeout(
|
||||
() => unblockBuilderUI(),
|
||||
AI_WEBSITE_TYPING_TIMEOUT
|
||||
);
|
||||
aiResponsePromise.finally(() => {
|
||||
browser.clearTimeout(timeoutId);
|
||||
unblockBuilderUI();
|
||||
});
|
||||
})();
|
||||
}
|
||||
}
|
||||
|
||||
destroy() {
|
||||
browser.clearTimeout(this.scraperRecoveryTimer);
|
||||
for (const event of ["BUS:CONNECT", "BUS:RECONNECT"]) {
|
||||
this.services.bus_service.removeEventListener(event, this.onBusConnected);
|
||||
}
|
||||
for (const [eventName, handler] of Object.entries(this.busHandlers)) {
|
||||
this.services.bus_service.unsubscribe(eventName, handler);
|
||||
}
|
||||
// If the editor is reloading because of a tool (e.g., menu edit), the
|
||||
// user is still in the AI chat: keep it open for the new instance.
|
||||
// The tool triggering the reload should take care of cleaning the
|
||||
// registry by removing the client tools bound to the instance of
|
||||
// `AiWebsiteBuilderPlugin` that is about to be destroyed. This can't
|
||||
// be done in `destroy`, as it may run after the new instance's `setup`
|
||||
if (!this.isReloadingEditor) {
|
||||
this.removeWebsiteBuilderClientToolsFromRegistry();
|
||||
this.toggleAiChatWindows(false);
|
||||
}
|
||||
aiChannelBus.removeEventListener("aiWebsitePage?", this.onFinalizeRequest);
|
||||
aiChannelBus.removeEventListener("view?", this.onPageContextRequest);
|
||||
super.destroy();
|
||||
}
|
||||
|
||||
/**
|
||||
* Reload the CSS bundles and wait for the new stylesheet.
|
||||
*
|
||||
* `reloadBundles` is debounced, and a debounced call that gets superseded never
|
||||
* resolves — so cap the wait rather than hang the build on it. Never rejects:
|
||||
* a stale palette is worth shipping, losing the whole page is not.
|
||||
*/
|
||||
reloadCssBundles() {
|
||||
let timeoutId;
|
||||
|
||||
const timeoutPromise = new Promise((resolve) => {
|
||||
timeoutId = setTimeout(() => {
|
||||
console.warn(`ai_website: CSS reload not confirmed after ${CSS_RELOAD_MAX_WAIT}ms`);
|
||||
resolve();
|
||||
}, CSS_RELOAD_MAX_WAIT);
|
||||
});
|
||||
|
||||
const reloadPromise = this.dependencies.customizeWebsite.reloadBundles().catch((error) => {
|
||||
console.warn("ai_website: CSS reload failed", error);
|
||||
});
|
||||
|
||||
return Promise.race([reloadPromise, timeoutPromise]).finally(() => {
|
||||
clearTimeout(timeoutId);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Finalize a full-page build composed by the AI (images, shapes, CSS polish),
|
||||
* then apply the result. Called from the `finalize_website_page` client tool.
|
||||
*
|
||||
* @param {string} html
|
||||
* @param {Array} [otherActions] zone-scoped edits bundled in the same tool call
|
||||
* (e.g. a footer edit); applied together with the finalized page rather than
|
||||
* as a separate tool call, so they land deterministically instead of racing it.
|
||||
* @param {Object} [targetPage] identity of the page the AI composed
|
||||
*/
|
||||
async finalizePage(html, otherActions = [], targetPage) {
|
||||
// The brand kit's palette must be live in the page before it is read off it,
|
||||
// or every shape gets painted the previous colours.
|
||||
await this.reloadCssBundles();
|
||||
let hasFailedStep = false;
|
||||
try {
|
||||
// Only the palette and the page path are used server-side.
|
||||
const page = (await getData("view"))?.website_page;
|
||||
let step = "images";
|
||||
while (step) {
|
||||
const result = await rpc("/ai_website/finalize_page", {
|
||||
html,
|
||||
step,
|
||||
current_view_info: page && {
|
||||
website_page: {
|
||||
website_id: page.website_id,
|
||||
location: page.location,
|
||||
css_variables: page.css_variables,
|
||||
},
|
||||
},
|
||||
});
|
||||
html = result.html;
|
||||
hasFailedStep ||= Boolean(result.error);
|
||||
step = result.next_step;
|
||||
}
|
||||
} catch (e) {
|
||||
this.services.notification.add(
|
||||
_t("The page could not be finalized. Please try again."),
|
||||
{ type: "danger" }
|
||||
);
|
||||
console.error(e);
|
||||
throw e;
|
||||
}
|
||||
const report = this.applyActions({
|
||||
actions: [
|
||||
{ zone: "main", mode: "replace", selector: "", content: html },
|
||||
...otherActions,
|
||||
],
|
||||
target_page: targetPage,
|
||||
});
|
||||
// Pick up the SCSS the CSS pass wrote while the page was being finalized.
|
||||
await this.reloadCssBundles();
|
||||
if (hasFailedStep) {
|
||||
this.services.notification.add(
|
||||
_t("The page was built but could not be fully finished."),
|
||||
{ type: "warning" }
|
||||
);
|
||||
}
|
||||
return report;
|
||||
}
|
||||
|
||||
removeWebsiteBuilderClientToolsFromRegistry() {
|
||||
this.aiTools.forEach((name) => aiClientToolsRegistry.remove(name));
|
||||
}
|
||||
|
||||
/**
|
||||
* Add an entry in the client tool registry. The tool call is wrapped
|
||||
* into operation.next() to be executed in the builder mutex.
|
||||
*
|
||||
* @param {String} name - name of the registry entry
|
||||
* @param {Function} callback - tool function
|
||||
*/
|
||||
registerClientToolWithMutex(name, callback) {
|
||||
this.aiTools.push(name);
|
||||
aiClientToolsRegistry.add(
|
||||
name,
|
||||
async (_, params) => {
|
||||
let ran = false;
|
||||
let result;
|
||||
await this.dependencies.operation.next(async () => {
|
||||
ran = true;
|
||||
result = await callback(params);
|
||||
});
|
||||
if (!ran) {
|
||||
throw new Error(
|
||||
"The builder discarded this operation (a previous " +
|
||||
"operation timed out); the page was NOT modified."
|
||||
);
|
||||
}
|
||||
return result;
|
||||
},
|
||||
{ force: true }
|
||||
);
|
||||
}
|
||||
|
||||
async navigateToEditClientTool(params) {
|
||||
await this.onNavigateToEdit(params);
|
||||
// goToWebsite()'s own promise resolves as soon as the outer action
|
||||
// component mounts, well before the destination page's WebsiteBuilder
|
||||
// component (and its `view?` data-getter listener, which current_view_info
|
||||
// depends on) is actually ready. Rather than guess at how long that takes,
|
||||
// poll the actual thing we need until it succeeds.
|
||||
await pollForData("view");
|
||||
return params.success_message;
|
||||
}
|
||||
|
||||
onNavigateToEdit({ url, save }) {
|
||||
return (async () => {
|
||||
if (save) {
|
||||
// Finish staging the user's latest DOM changes before saving.
|
||||
// Save through this editor instance and await its RPC before
|
||||
// replacing it with the editor for the new page.
|
||||
this.dependencies.history.commit();
|
||||
await this.dependencies.savePlugin.save();
|
||||
} else {
|
||||
this.dependencies.history.reset();
|
||||
}
|
||||
await this.services.website.goToWebsite({ path: url, edition: true });
|
||||
})();
|
||||
}
|
||||
|
||||
toggleAiChatWindows(unfold) {
|
||||
const mailStore = this.services["mail.store"];
|
||||
if (!mailStore?.chatHub) {
|
||||
return;
|
||||
}
|
||||
[...mailStore.chatHub[unfold ? "folded" : "opened"]]
|
||||
.filter((w) => isAiWebsiteBuilderChannel(w.channel))
|
||||
.forEach((w) => (unfold ? w.open() : w.fold()));
|
||||
}
|
||||
|
||||
scheduleScraperRecovery() {
|
||||
if (!this.isDestroyed && !this.scraperRecoveryTimer) {
|
||||
this.scraperRecoveryTimer = browser.setTimeout(() => {
|
||||
this.scraperRecoveryTimer = undefined;
|
||||
this.recoverScraperResults();
|
||||
}, SCRAPER_RECOVERY_DELAY);
|
||||
}
|
||||
}
|
||||
|
||||
async recoverScraperResults() {
|
||||
const website = this.services.website;
|
||||
const page = website?.currentWebsite;
|
||||
if (
|
||||
this.isDestroyed ||
|
||||
!this.scraperRecoveryStarted ||
|
||||
this.recoveringScraperResults ||
|
||||
!website?.isDesigner ||
|
||||
page?.metadata?.translatable ||
|
||||
page?.metadata?.mainObject?.model !== "website.page"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
this.recoveringScraperResults = true;
|
||||
try {
|
||||
const results = await rpc("/ai_website/ready_scraper_results", {
|
||||
website_id: page.id,
|
||||
main_object: page.metadata.mainObject,
|
||||
});
|
||||
// Coalesce duplicate bus events until the server has been checked
|
||||
// again, while allowing an unconsumed result to be retried.
|
||||
for (const key of this.scraperResumeAttempts) {
|
||||
if (!this.scraperResumes.has(key)) {
|
||||
this.scraperResumeAttempts.delete(key);
|
||||
}
|
||||
}
|
||||
for (const result of results) {
|
||||
await this.resumeAfterScraping(result);
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn("ai_website: could not recover scraping results", error);
|
||||
this.scheduleScraperRecovery();
|
||||
} finally {
|
||||
this.recoveringScraperResults = false;
|
||||
}
|
||||
}
|
||||
|
||||
async resumeAfterScraping({
|
||||
channel_id: channelId,
|
||||
session_id: sessionId,
|
||||
resume_token: resumeToken,
|
||||
target_page: targetPage,
|
||||
tool_call_id: callId,
|
||||
}) {
|
||||
if (this.isDestroyed || !this.isEditingTargetPage(targetPage)) {
|
||||
return;
|
||||
}
|
||||
const resumeKey = `${channelId}:${callId}`;
|
||||
if (this.scraperResumeAttempts.has(resumeKey)) {
|
||||
return;
|
||||
}
|
||||
this.scraperResumes.add(resumeKey);
|
||||
this.scraperResumeAttempts.add(resumeKey);
|
||||
try {
|
||||
const channel = await this.services["mail.store"]["discuss.channel"].getOrFetch(channelId);
|
||||
if (
|
||||
this.isDestroyed ||
|
||||
!isAiWebsiteBuilderChannel(channel) ||
|
||||
!this.isEditingTargetPage(targetPage)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
await channel.thread.requestAiSessionAdvance("/ai/resume_pending_interaction", {
|
||||
session_id: sessionId,
|
||||
resume_token: resumeToken,
|
||||
response: { kind: "async", call_id: callId },
|
||||
});
|
||||
} catch (error) {
|
||||
console.warn("ai_website: could not resume after scraping", error);
|
||||
} finally {
|
||||
// A completed HTTP request may have declined a busy session lock.
|
||||
// Only the server knows whether the result was consumed: check again
|
||||
// after a delay, then stop once no ready call remains.
|
||||
this.scraperResumes.delete(resumeKey);
|
||||
this.scheduleScraperRecovery();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the page open in the builder is the one the AI made its edits for.
|
||||
* It prevents from applying the changes if the user moved off the original page.
|
||||
*
|
||||
* @param {{ main_object: { model: string, id: number }, location: string }} [targetPage]
|
||||
*/
|
||||
isEditingTargetPage(targetPage) {
|
||||
const targetObject = targetPage?.main_object;
|
||||
if (!targetObject?.model) {
|
||||
// The sender did not say which page it edited: nothing to check against.
|
||||
return true;
|
||||
}
|
||||
const currentObject = this.services.website?.currentWebsite?.metadata?.mainObject;
|
||||
return (
|
||||
currentObject?.model === targetObject.model &&
|
||||
currentObject?.id === targetObject.id &&
|
||||
(targetPage.website_id === undefined ||
|
||||
targetPage.website_id === this.services.website?.currentWebsite?.id)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Try to apply AI-generated changes to the page and report the result.
|
||||
*
|
||||
* @param {{
|
||||
* actions: [{
|
||||
* mode: string,
|
||||
* zone: string,
|
||||
* selector: string,
|
||||
* content: string,
|
||||
* }],
|
||||
* target_page: { main_object: { model: string, id: number }, location: string },
|
||||
* }} payload
|
||||
* @returns {Object[]} the apply report
|
||||
*/
|
||||
applyActions({ actions, target_page: targetPage }) {
|
||||
if (this.isDestroyed) {
|
||||
throw new Error(
|
||||
"The editor was closed or reloaded before these changes could " +
|
||||
"be applied; the page was NOT modified."
|
||||
);
|
||||
}
|
||||
if (!this.isEditingTargetPage(targetPage)) {
|
||||
this.services.notification.add(
|
||||
_t(
|
||||
"The AI finished changes meant for %s, which is no longer the page being edited. They were not applied.",
|
||||
targetPage.location || _t("another page")
|
||||
),
|
||||
{ type: "warning" }
|
||||
);
|
||||
throw new Error("The page being edited has changed; the changes were NOT applied.");
|
||||
}
|
||||
const edits = [];
|
||||
const results = [];
|
||||
for (const { zone, mode, selector, content } of actions) {
|
||||
const result = {
|
||||
description: `${mode}${selector ? ` on "${selector}"` : ""} in ${zone}`,
|
||||
};
|
||||
results.push(result);
|
||||
const zoneEl = this.editable.querySelector(AI_EDITABLE_ZONE_SELECTORS[zone]);
|
||||
if (!zoneEl) {
|
||||
result.error = `Zone element not found for zone: ${zone}`;
|
||||
continue;
|
||||
}
|
||||
zoneEl.dataset.containsAiContent = "true";
|
||||
// Queued changes can be applied before the save plugin starts
|
||||
// observing mutations on a newly redirected page. Mark its
|
||||
// enclosing view dirty explicitly so Save persists the AI edit.
|
||||
zoneEl.closest(".o_savable")?.classList.add("o_dirty");
|
||||
// sanitized during parsing - we can't trust LLM output
|
||||
const { sanitizedContent, wasSanitized } = this.parseAndSanitizeHtml(content);
|
||||
if (wasSanitized) {
|
||||
if (!sanitizedContent.hasChildNodes()) {
|
||||
result.error = "Everything was dropped by the sanitizer";
|
||||
continue;
|
||||
}
|
||||
result.sanitizer_note =
|
||||
"The editor removed unsafe or unsupported markup from your HTML. " +
|
||||
"`sanitized_html` is what is actually on the page: compare it with " +
|
||||
"what you sent, and tell the user what is missing.";
|
||||
// Read before insertion: appending the fragment empties it.
|
||||
result.sanitized_html = [...sanitizedContent.childNodes]
|
||||
.map((node) => node.outerHTML ?? node.textContent)
|
||||
.join("");
|
||||
}
|
||||
if (!selector) {
|
||||
// If we have sections wrapped in some container, we should
|
||||
// unwrap it.
|
||||
if (
|
||||
sanitizedContent.children.length === 1 &&
|
||||
sanitizedContent.firstElementChild.querySelectorAll(":scope > section").length >
|
||||
1
|
||||
) {
|
||||
sanitizedContent.replaceChildren(
|
||||
...sanitizedContent.firstElementChild.children
|
||||
);
|
||||
}
|
||||
this.dependencies.aiScript.stopScripts(zoneEl);
|
||||
this.markAiContent(sanitizedContent);
|
||||
zoneEl.replaceChildren(sanitizedContent);
|
||||
this.dependencies.aiScript.restartScripts(zoneEl);
|
||||
continue;
|
||||
}
|
||||
let targetEls;
|
||||
try {
|
||||
targetEls = zoneEl.querySelectorAll(selector);
|
||||
} catch (err) {
|
||||
if (err.name === "SyntaxError") {
|
||||
// Catches only errors from non-string or malformed selectors. The check for err.name is
|
||||
// required as some browser may throw another type of error such as DOMException.
|
||||
result.error = `Invalid CSS selector: ${selector}`;
|
||||
continue;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
if (!targetEls.length) {
|
||||
result.error = `Nothing matches ${selector}`;
|
||||
continue;
|
||||
}
|
||||
this.markAiContent(sanitizedContent);
|
||||
const methods = {
|
||||
after: (el) => {
|
||||
el.after(sanitizedContent.cloneNode(true));
|
||||
this.dependencies.aiScript.restartScripts(el.nextElementSibling);
|
||||
},
|
||||
before: (el) => {
|
||||
el.before(sanitizedContent.cloneNode(true));
|
||||
this.dependencies.aiScript.restartScripts(el.previousElementSibling);
|
||||
},
|
||||
replace: (el) => {
|
||||
this.dependencies.aiScript.stopScripts(el);
|
||||
const cloneEl = sanitizedContent.cloneNode(true);
|
||||
const newEl = cloneEl.firstElementChild;
|
||||
el.replaceWith(cloneEl);
|
||||
if (sanitizedContent.childElementCount === 1) {
|
||||
this.trigger("on_ai_website_element_replaced_handlers", el, newEl);
|
||||
}
|
||||
if (newEl) {
|
||||
this.dependencies.aiScript.restartScripts(newEl);
|
||||
}
|
||||
},
|
||||
};
|
||||
edits.push(() => targetEls.forEach(methods[mode]));
|
||||
}
|
||||
|
||||
// Execute all the edits at the end so the selectors are done on the
|
||||
// original DOM and not affected by previous edits.
|
||||
// This may happen with selectors such as :nth-child().
|
||||
edits.forEach((edit) => edit());
|
||||
this.dependencies.history.commit();
|
||||
return results;
|
||||
}
|
||||
|
||||
markAiContent(rootEl) {
|
||||
for (const el of rootEl.children) {
|
||||
el.dataset.containsAiContent = "true";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Wire a form to an action exactly like the editor's action switch
|
||||
* (`SelectAction`), and/or set hidden destination fields like the
|
||||
* sidebar's action fields do (`AddActionFieldAction`), then report the
|
||||
* resulting form and the action's destination fields (with candidate
|
||||
* records) so the agent can let the user choose the destinations.
|
||||
*
|
||||
* @param {Object} params
|
||||
* @param {String} params.selector CSS selector of the form or its section
|
||||
* @param {String} params.action_key `website_form_key` of the target action
|
||||
* @param {Array<{name: String, value: String}>} params.fields hidden
|
||||
* destination/preset values to set
|
||||
* @returns {Object} The result payload for the AI agent. Includes `error`
|
||||
* on failure. On success, includes `form_html`, `destination_fields`
|
||||
* and optionally `previous_form_html`, `note`, and an array of
|
||||
* `field_errors`.
|
||||
*/
|
||||
async setFormAction({ selector, action_key, fields }) {
|
||||
const targetEl = this.editable.querySelector(selector);
|
||||
const formEl = targetEl?.closest("form") || targetEl?.querySelector("form");
|
||||
if (!formEl || !formEl.closest(".s_website_form")) {
|
||||
return {
|
||||
error:
|
||||
`No website form matches "${selector}". The form must keep its ` +
|
||||
"s_website_form section structure; re-apply the form snippet if it was lost.",
|
||||
};
|
||||
}
|
||||
const formOptionPlugin = this.dependencies.websiteFormOption;
|
||||
const models = await formOptionPlugin.fetchModels(formEl);
|
||||
const targetForm = models.find((m) => (m.website_form_key || m.model) === action_key);
|
||||
if (!targetForm) {
|
||||
return {
|
||||
error:
|
||||
`Unknown form action "${action_key}". Available actions: ` +
|
||||
`${models.map((m) => m.website_form_key || m.model).join(", ")}.`,
|
||||
};
|
||||
}
|
||||
const result = { field_errors: [] };
|
||||
const formInfo = await formOptionPlugin.prepareFormModel(formEl, targetForm);
|
||||
if (formEl.dataset.model_name !== targetForm.model) {
|
||||
if (formEl.getAttribute("hide-change-model")) {
|
||||
return {
|
||||
error: "This form's action cannot be changed (the form is managed by its page).",
|
||||
};
|
||||
}
|
||||
const activeForm = models.find((m) => m.model === getModelName(formEl)) || targetForm;
|
||||
result.previous_form_html = formEl.outerHTML;
|
||||
await formOptionPlugin.applyFormModel(formEl, activeForm, targetForm.id, formInfo);
|
||||
}
|
||||
const authorizedFields = await formOptionPlugin.fetchAuthorizedFields(formEl);
|
||||
for (const { name, value } of fields || []) {
|
||||
const fieldDef = authorizedFields[name];
|
||||
if (!fieldDef || fieldDef._property) {
|
||||
result.field_errors.push(
|
||||
`"${name}" is not a field of ${targetForm.model}; not set.`
|
||||
);
|
||||
continue;
|
||||
}
|
||||
let fieldValue = value;
|
||||
if (["many2one", "integer"].includes(fieldDef.type)) {
|
||||
fieldValue = parseInt(value);
|
||||
if (isNaN(fieldValue)) {
|
||||
result.field_errors.push(
|
||||
`"${name}" takes the numeric id of the targeted record, not "${value}"; not set.`
|
||||
);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
formOptionPlugin.addHiddenField(formEl, fieldValue, name);
|
||||
}
|
||||
this.dependencies.history.commit();
|
||||
if (!result.field_errors.length) {
|
||||
delete result.field_errors;
|
||||
}
|
||||
result.form_html = formEl.outerHTML;
|
||||
result.destination_fields = (formInfo.fields || []).map((field) => ({
|
||||
name: field.name,
|
||||
label: field.string,
|
||||
required: !!field.required,
|
||||
prefilled_value:
|
||||
formEl.querySelector(`.s_website_form_dnone input[name="${field.name}"]`)?.value ||
|
||||
"",
|
||||
candidates: (field.records || [])
|
||||
.slice(0, 20)
|
||||
.map(({ id, display_name }) => ({ id, display_name })),
|
||||
}));
|
||||
if (result.destination_fields.length) {
|
||||
result.note =
|
||||
"Every destination field above must be confirmed by the user before the " +
|
||||
"form is done, a prefilled_value is a default, NOT a user choice.";
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Save the pending page edit and reload the editor. Used to render
|
||||
* changes that require a reload such as changes to website menu.
|
||||
*/
|
||||
async reloadEditor(returnMessage) {
|
||||
if (this.isReloadingEditor) {
|
||||
// A reload is already on the way.
|
||||
throw new Error(
|
||||
"A reload of the editor is already in progress; this call did " +
|
||||
"nothing. Ask for the current page state before editing further."
|
||||
);
|
||||
}
|
||||
this.isReloadingEditor = true;
|
||||
this.removeWebsiteBuilderClientToolsFromRegistry();
|
||||
aiChannelBus.removeEventListener("view?", this.onPageContextRequest);
|
||||
const nextEditorStarted = Promise.race([
|
||||
new Promise((resolve) =>
|
||||
aiChannelBus.addEventListener("aiWebsiteEditorStarted", () => resolve(true), {
|
||||
once: true,
|
||||
})
|
||||
),
|
||||
new Promise((resolve) => setTimeout(() => resolve(false), EDITOR_RELOAD_MAX_WAIT)),
|
||||
]);
|
||||
try {
|
||||
await this.dependencies.savePlugin.save();
|
||||
await this.config.reloadEditor();
|
||||
} catch (e) {
|
||||
this.isReloadingEditor = false;
|
||||
throw e;
|
||||
}
|
||||
if (!(await nextEditorStarted)) {
|
||||
console.warn(`AI Website: editor hasn't reloaded after ${EDITOR_RELOAD_MAX_WAIT} ms`);
|
||||
}
|
||||
return returnMessage;
|
||||
}
|
||||
|
||||
getPageAiContext() {
|
||||
// Mutations from a recent user edit may still be staged when the chat
|
||||
// request is sent. Commit them before reporting pending_changes so the
|
||||
// agent can ask whether to save or discard them.
|
||||
this.dependencies.history.commit();
|
||||
|
||||
const websiteService = this.services.website;
|
||||
const metadata = websiteService.currentWebsite.metadata;
|
||||
// Collect context before cloning: extensions may update the editable DOM.
|
||||
const extraContext = Object.assign(
|
||||
{},
|
||||
...this.trigger("on_ai_website_page_context_handlers")
|
||||
);
|
||||
|
||||
const getZoneContent = (zoneSelector) => {
|
||||
const el = this.editable.querySelector(zoneSelector);
|
||||
if (!el) {
|
||||
return "";
|
||||
}
|
||||
const clone = el.cloneNode(true);
|
||||
for (const animatedEl of clone.querySelectorAll(".o_animate, .o_animate_preview")) {
|
||||
animatedEl.classList.remove(...ANIMATION_RUNTIME_CLASSES);
|
||||
for (const prop of ANIMATION_RUNTIME_STYLE_PROPS) {
|
||||
animatedEl.style.removeProperty(prop);
|
||||
}
|
||||
if (!animatedEl.getAttribute("style")) {
|
||||
animatedEl.removeAttribute("style");
|
||||
}
|
||||
}
|
||||
return clone.innerHTML;
|
||||
};
|
||||
|
||||
const getOdooCssVariables = () => {
|
||||
const htmlStyle = getHtmlStyle(this.document);
|
||||
const cssVarValues = {};
|
||||
for (const varName of EDITOR_COLOR_CSS_VARIABLES.filter(
|
||||
(v) => v.startsWith("o-cc") || v.startsWith("o-color-")
|
||||
)) {
|
||||
cssVarValues[varName] = getCSSVariableValue(varName, htmlStyle);
|
||||
}
|
||||
return cssVarValues;
|
||||
};
|
||||
|
||||
const pageContext = {
|
||||
website_id: websiteService.currentWebsite?.id,
|
||||
title: metadata.title,
|
||||
lang: metadata.lang,
|
||||
direction: metadata.direction,
|
||||
location: websiteService.currentLocation,
|
||||
main_object: metadata.mainObject,
|
||||
is_page_ai_editable: isPageAiEditable(websiteService),
|
||||
editable_zones: {
|
||||
main: getZoneContent(AI_EDITABLE_ZONE_SELECTORS.main),
|
||||
footer: getZoneContent(AI_EDITABLE_ZONE_SELECTORS.footer),
|
||||
},
|
||||
css_variables: getOdooCssVariables(),
|
||||
pending_changes: this.dependencies.history.canUndo(),
|
||||
};
|
||||
return Object.assign(pageContext, extraContext);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitize HTML via DOMPurify (SanitizePlugin) before adding it to the
|
||||
* page. Returns the sanitized content, and whether anything was dropped
|
||||
* from what was given.
|
||||
*
|
||||
* @param {string} html - the HTML content to sanitize
|
||||
* @returns {{
|
||||
* sanitizedContent: DocumentFragment,
|
||||
* wasSanitized: boolean
|
||||
* }}
|
||||
*/
|
||||
parseAndSanitizeHtml(html) {
|
||||
const parser = new DOMParser();
|
||||
const doc = parser.parseFromString(`<div>${html}</div>`, "text/html");
|
||||
const fragment = this.document.createDocumentFragment();
|
||||
let wasSanitized = false;
|
||||
for (const child of [...doc.body.firstChild.childNodes]) {
|
||||
const imported = this.document.importNode(child, true);
|
||||
if (imported.nodeType === Node.ELEMENT_NODE) {
|
||||
try {
|
||||
this.dependencies.aiScript.normalizeScripts(imported);
|
||||
// DOMPurify's DOM-clobbering guard strips `name` attributes
|
||||
// whose value collides with a form property (e.g. the
|
||||
// crm.lead/project.task required field literally named
|
||||
// "name"), silently unbinding the field. The stock editor
|
||||
// ships those very attributes, so restore the ones that
|
||||
// were explicitly present on form inputs.
|
||||
const namedInputEls = [
|
||||
...imported.querySelectorAll(".s_website_form_input[name]"),
|
||||
];
|
||||
const savedNames = namedInputEls.map((el) => [el, el.getAttribute("name")]);
|
||||
// Re-set them before the snapshot: `setAttribute` appends,
|
||||
// so putting a name back below would otherwise move it in
|
||||
// the serialization and read as a sanitization.
|
||||
for (const [el, name] of savedNames) {
|
||||
el.removeAttribute("name");
|
||||
el.setAttribute("name", name);
|
||||
}
|
||||
const beforeSanitize = imported.outerHTML;
|
||||
const restoreScripts = this.dependencies.aiScript.detachScripts(imported);
|
||||
this.dependencies.sanitize.sanitize(imported);
|
||||
restoreScripts();
|
||||
for (const [el, name] of savedNames) {
|
||||
if (!el.getAttribute("name") && imported.contains(el)) {
|
||||
el.setAttribute("name", name);
|
||||
}
|
||||
}
|
||||
wasSanitized ||= imported.outerHTML !== beforeSanitize;
|
||||
this.trigger("on_ai_website_html_imported_handlers", imported);
|
||||
fragment.appendChild(imported);
|
||||
} catch (e) {
|
||||
if (e instanceof TypeError) {
|
||||
wasSanitized = true;
|
||||
continue;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
} else if (imported.nodeType === Node.TEXT_NODE) {
|
||||
fragment.appendChild(imported);
|
||||
} else {
|
||||
// All other node types may potentially be unsafe and are
|
||||
// dropped (comments, PIs, CDATA, ...)
|
||||
wasSanitized = true;
|
||||
}
|
||||
}
|
||||
// The agent works from images it found on other sites, so it hands us URLs
|
||||
// pointing at those sites. Flag them here rather than asking the agent to call a
|
||||
// tool for it: they are then downloaded into Odoo when the user saves the page.
|
||||
this.dependencies.externalImageSave.markExternalImages(fragment);
|
||||
return { sanitizedContent: fragment, wasSanitized };
|
||||
}
|
||||
}
|
||||
|
||||
registry.category("website-plugins").add(AiWebsiteBuilderPlugin.id, AiWebsiteBuilderPlugin);
|
||||
@@ -0,0 +1,369 @@
|
||||
import { Plugin } from "@html_editor/plugin";
|
||||
import { getActiveHotkey } from "@web/core/hotkeys/hotkey_utils";
|
||||
import { _t } from "@web/core/l10n/translation";
|
||||
import { registry } from "@web/core/registry";
|
||||
import { uuid } from "@web/core/utils/strings";
|
||||
import { aiChannelBus } from "@ai/utils/ai_channel_bus";
|
||||
import {
|
||||
AI_EDITABLE_ZONE_SELECTORS,
|
||||
AI_WEBSITE_ELEMENT_SELECTION_COMMAND,
|
||||
AI_WEBSITE_ELEMENT_SELECTION_STATE,
|
||||
isAiWebsiteBuilderChannel,
|
||||
} from "@ai_website/utils";
|
||||
|
||||
export class AiWebsiteElementSelectionPlugin extends Plugin {
|
||||
static id = "aiWebsiteElementSelection";
|
||||
static dependencies = ["aiWebsiteBuilder", "builderOptions", "localOverlay"];
|
||||
|
||||
// Resources are available before setup, including during the base plugin's setup.
|
||||
selections = new Map();
|
||||
hoverOverlay = null;
|
||||
pickerActive = false;
|
||||
|
||||
resources = {
|
||||
system_attributes: ["data-ai-id"],
|
||||
clean_for_save_processors: this.cleanEditorMarkers.bind(this),
|
||||
on_layout_geometry_change_handlers: this.refreshSelectionOverlays.bind(this),
|
||||
on_committed_to_history_handlers: this.reconcileSelection.bind(this),
|
||||
on_ai_website_page_context_handlers: () => {
|
||||
const selectedElements = this.consumeSelectedElementsContext();
|
||||
return selectedElements.length ? { selected_elements: selectedElements } : {};
|
||||
},
|
||||
on_ai_website_html_imported_handlers: this.cleanEditorMarkers.bind(this),
|
||||
on_ai_website_element_replaced_handlers: (oldElement, newElement) => {
|
||||
if (oldElement.dataset.aiId) {
|
||||
newElement.dataset.aiId = oldElement.dataset.aiId;
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
setup() {
|
||||
this.dependencies.aiWebsiteBuilder.registerClientToolWithMutex(
|
||||
"fetch_website_styles",
|
||||
(params) => this.getElementStyles(params)
|
||||
);
|
||||
this.pickerOverlayContainer = this.config.localOverlayContainers?.ref();
|
||||
this.selectionOverlayContainer = this.dependencies.localOverlay.makeLocalOverlay(
|
||||
"ai-website-selection-overlay-container"
|
||||
);
|
||||
this.document.body.append(this.selectionOverlayContainer);
|
||||
this.onSelectionCommand = this.onSelectionCommand.bind(this);
|
||||
aiChannelBus.addEventListener(
|
||||
AI_WEBSITE_ELEMENT_SELECTION_COMMAND,
|
||||
this.onSelectionCommand
|
||||
);
|
||||
for (const eventName of ["pointerdown", "pointerup", "click", "dblclick"]) {
|
||||
this.addGlobalDomListener(eventName, this.onPickerEvent, true);
|
||||
}
|
||||
this.addDomListener(window, "keydown", this.onPickerEscape, true, true);
|
||||
if (this.window !== window) {
|
||||
this.addDomListener(this.window, "keydown", this.onPickerEscape, true, true);
|
||||
}
|
||||
this.addDomListener(this.editable, "mousemove", this.onPickerHover);
|
||||
this.addDomListener(this.editable, "mouseleave", () => this.setHoveredTarget(null));
|
||||
this.addDomListener(this.document, "scroll", this.refreshSelectionOverlays, true);
|
||||
this.emitSelectionState();
|
||||
}
|
||||
|
||||
destroy() {
|
||||
aiChannelBus.removeEventListener(
|
||||
AI_WEBSITE_ELEMENT_SELECTION_COMMAND,
|
||||
this.onSelectionCommand
|
||||
);
|
||||
this.setPickerActive(false);
|
||||
this.cleanEditorMarkers(this.editable);
|
||||
aiChannelBus.trigger(AI_WEBSITE_ELEMENT_SELECTION_STATE, {
|
||||
available: false,
|
||||
pickerActive: false,
|
||||
elements: [],
|
||||
});
|
||||
|
||||
super.destroy();
|
||||
}
|
||||
|
||||
onSelectionCommand({ detail: command }) {
|
||||
switch (command.type) {
|
||||
case "request_state":
|
||||
break;
|
||||
case "toggle_picker":
|
||||
this.setPickerActive(!this.pickerActive);
|
||||
if (this.pickerActive) {
|
||||
this.dependencies.builderOptions.deactivateContainers();
|
||||
}
|
||||
break;
|
||||
case "deselect":
|
||||
this.removeSelection(command.id);
|
||||
break;
|
||||
case "stop_picker":
|
||||
this.setPickerActive(false);
|
||||
break;
|
||||
case "release":
|
||||
this.setPickerActive(false);
|
||||
this.selections.forEach(({ overlay }) => overlay.remove());
|
||||
this.selections.clear();
|
||||
break;
|
||||
case "prepare_send":
|
||||
command.elementLabels = this.getSelectionState().elements.map(({ label }) => label);
|
||||
this.setPickerActive(false);
|
||||
break;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
this.emitSelectionState();
|
||||
}
|
||||
|
||||
emitSelectionState() {
|
||||
aiChannelBus.trigger(AI_WEBSITE_ELEMENT_SELECTION_STATE, this.getSelectionState());
|
||||
}
|
||||
|
||||
getElementStyles({ elements }) {
|
||||
return {
|
||||
elements: elements.map(({ id, properties }) => {
|
||||
const target = this.editable.querySelector(`[data-ai-id="${id}"]`);
|
||||
if (!target) {
|
||||
return { id, error: "Element is no longer available" };
|
||||
}
|
||||
const computedStyle = this.window.getComputedStyle(target);
|
||||
return {
|
||||
id,
|
||||
styles: Object.fromEntries(
|
||||
properties.map((property) => [
|
||||
property,
|
||||
computedStyle.getPropertyValue(property),
|
||||
])
|
||||
),
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
onPickerEvent(event) {
|
||||
if (!this.pickerActive || event.button !== 0) {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
event.stopImmediatePropagation();
|
||||
if (event.type === "click" && event.detail <= 1) {
|
||||
this.selectElement(event.target);
|
||||
}
|
||||
}
|
||||
|
||||
onPickerEscape(event) {
|
||||
if (!this.pickerActive || getActiveHotkey(event) !== "escape") {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
event.stopImmediatePropagation();
|
||||
this.setPickerActive(false);
|
||||
this.emitSelectionState();
|
||||
[...this.services["mail.store"].chatHub.opened]
|
||||
.find((chatWindow) => isAiWebsiteBuilderChannel(chatWindow.channel))
|
||||
?.focus();
|
||||
}
|
||||
|
||||
onPickerHover(event) {
|
||||
if (!this.pickerActive) {
|
||||
return;
|
||||
}
|
||||
const target = this.dependencies.builderOptions.closestWithOption(event.target);
|
||||
this.setHoveredTarget(target && this.isInsideEditableZone(target) ? target : null);
|
||||
}
|
||||
|
||||
createOverlay(target) {
|
||||
const overlay = this.selectionOverlayContainer.ownerDocument.createElement("div");
|
||||
const entry = { target, overlay };
|
||||
overlay.className = "o-ai-website-selection-overlay";
|
||||
this.selectionOverlayContainer.append(overlay);
|
||||
this.refreshSelectionOverlay(entry);
|
||||
return entry;
|
||||
}
|
||||
|
||||
refreshSelectionOverlay({ target, overlay }) {
|
||||
if (!target.isConnected) {
|
||||
return;
|
||||
}
|
||||
const style = this.window.getComputedStyle(target);
|
||||
const targetRect = target.getBoundingClientRect();
|
||||
const overlayContainerRect = this.selectionOverlayContainer.getBoundingClientRect();
|
||||
const fixedTop = Math.max(
|
||||
0,
|
||||
...[...this.document.querySelectorAll(".o_top_fixed_element")].map(
|
||||
(element) => element.getBoundingClientRect().bottom
|
||||
)
|
||||
);
|
||||
const clippedTop = Math.min(targetRect.height, Math.max(0, fixedTop - targetRect.top));
|
||||
Object.assign(overlay.style, {
|
||||
position: "absolute",
|
||||
boxSizing: "border-box",
|
||||
border: "2px solid #00d9ff",
|
||||
background: "rgba(0, 217, 255, 0.12)",
|
||||
width: `${targetRect.width}px`,
|
||||
height: `${targetRect.height}px`,
|
||||
top: `${targetRect.top - overlayContainerRect.top}px`,
|
||||
left: `${targetRect.left - overlayContainerRect.left}px`,
|
||||
clipPath: clippedTop ? `inset(${clippedTop}px 0 0)` : "",
|
||||
borderRadius: style.borderRadius,
|
||||
});
|
||||
}
|
||||
|
||||
refreshSelectionOverlays() {
|
||||
if (this.hoverOverlay) {
|
||||
if (this.hoverOverlay.target.isConnected) {
|
||||
this.refreshSelectionOverlay(this.hoverOverlay);
|
||||
} else {
|
||||
this.setHoveredTarget(null);
|
||||
}
|
||||
}
|
||||
for (const entry of this.selections.values()) {
|
||||
this.refreshSelectionOverlay(entry);
|
||||
}
|
||||
}
|
||||
|
||||
setHoveredTarget(target) {
|
||||
if (this.hoverOverlay?.target === target) {
|
||||
return;
|
||||
}
|
||||
this.hoverOverlay?.overlay.remove();
|
||||
const isSelected = this.selections.has(target?.dataset.aiId);
|
||||
this.hoverOverlay = target && !isSelected ? this.createOverlay(target) : null;
|
||||
}
|
||||
|
||||
setPickerActive(active) {
|
||||
this.pickerActive = active;
|
||||
this.document.documentElement.classList.toggle("o-ai-website-picker-active", active);
|
||||
this.pickerOverlayContainer?.classList.toggle("o-ai-website-picker-active", active);
|
||||
if (!active) {
|
||||
this.setHoveredTarget(null);
|
||||
}
|
||||
}
|
||||
|
||||
isInsideEditableZone(target) {
|
||||
for (const selector of Object.values(AI_EDITABLE_ZONE_SELECTORS)) {
|
||||
const zone = this.editable.querySelector(selector);
|
||||
if (zone && zone !== target && zone.contains(target)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
selectElement(rawTarget) {
|
||||
const target = this.dependencies.builderOptions.closestWithOption(rawTarget);
|
||||
if (!target || !this.isInsideEditableZone(target)) {
|
||||
this.services.notification.add(
|
||||
_t("This area cannot be targeted. Select a website building block instead."),
|
||||
{ type: "warning" }
|
||||
);
|
||||
return;
|
||||
}
|
||||
const id = target.dataset.aiId || `ai-${uuid()}`;
|
||||
if (this.selections.has(id)) {
|
||||
this.removeSelection(id);
|
||||
this.emitSelectionState();
|
||||
return;
|
||||
}
|
||||
|
||||
for (const [selectedId, { target: selectedTarget }] of this.selections) {
|
||||
if (selectedTarget.contains(target) || target.contains(selectedTarget)) {
|
||||
this.removeSelection(selectedId);
|
||||
}
|
||||
}
|
||||
target.dataset.aiId = id;
|
||||
this.setHoveredTarget(null);
|
||||
this.selections.set(id, this.createOverlay(target));
|
||||
this.emitSelectionState();
|
||||
}
|
||||
|
||||
removeSelection(id) {
|
||||
const selection = this.selections.get(id);
|
||||
selection.overlay.remove();
|
||||
this.selections.delete(id);
|
||||
}
|
||||
|
||||
reconcileSelection() {
|
||||
const hadSelections = Boolean(this.selections.size);
|
||||
for (const [id, selection] of this.selections) {
|
||||
const { target } = selection;
|
||||
if (!this.isInsideEditableZone(target) || target.dataset.aiId !== id) {
|
||||
this.removeSelection(id);
|
||||
} else {
|
||||
this.refreshSelectionOverlay(selection);
|
||||
}
|
||||
}
|
||||
if (hadSelections) {
|
||||
this.emitSelectionState();
|
||||
}
|
||||
}
|
||||
|
||||
getSelectionState() {
|
||||
return {
|
||||
available: true,
|
||||
pickerActive: this.pickerActive,
|
||||
elements: [...this.selections].map(([id, { target }]) => {
|
||||
const tag = target.tagName.toLowerCase();
|
||||
// First line with a letter/number, skipping icon/emoji-only lines.
|
||||
const firstReadableLine = target.innerText
|
||||
.trim()
|
||||
.split("\n")
|
||||
.map((line) => line.trim())
|
||||
.find((line) => /[\p{L}\p{N}]/u.test(line));
|
||||
return {
|
||||
id,
|
||||
label: firstReadableLine?.slice(0, 60) || `<${tag}>`,
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
consumeSelectedElementsContext() {
|
||||
const context = [...this.selections].map(([id, { target }]) => {
|
||||
const style = this.window.getComputedStyle(target);
|
||||
const rect = target.getBoundingClientRect();
|
||||
return {
|
||||
id,
|
||||
tag: target.tagName.toLowerCase(),
|
||||
text: target.innerText.replace(/\s+/g, " ").trim().slice(0, 200),
|
||||
size: {
|
||||
width: Math.round(rect.width),
|
||||
height: Math.round(rect.height),
|
||||
},
|
||||
computed_style: {
|
||||
display: style.display,
|
||||
position: style.position,
|
||||
margin: style.margin,
|
||||
padding: style.padding,
|
||||
color: style.color,
|
||||
font: style.font,
|
||||
"text-align": style.textAlign,
|
||||
"background-color": style.backgroundColor,
|
||||
border: style.border,
|
||||
"border-radius": style.borderRadius,
|
||||
"flex-flow": style.flexFlow,
|
||||
"justify-content": style.justifyContent,
|
||||
"align-items": style.alignItems,
|
||||
gap: style.gap,
|
||||
"grid-template-columns": style.gridTemplateColumns,
|
||||
"object-fit": style.objectFit,
|
||||
"object-position": style.objectPosition,
|
||||
"aspect-ratio": style.aspectRatio,
|
||||
},
|
||||
};
|
||||
});
|
||||
this.selections.forEach(({ overlay }) => overlay.remove());
|
||||
this.selections.clear();
|
||||
this.emitSelectionState();
|
||||
return context;
|
||||
}
|
||||
|
||||
cleanEditorMarkers(root) {
|
||||
root.removeAttribute("data-ai-id");
|
||||
root.querySelectorAll("[data-ai-id]").forEach((el) => {
|
||||
el.removeAttribute("data-ai-id");
|
||||
});
|
||||
return root;
|
||||
}
|
||||
}
|
||||
|
||||
registry
|
||||
.category("website-plugins")
|
||||
.add(AiWebsiteElementSelectionPlugin.id, AiWebsiteElementSelectionPlugin);
|
||||
171
ai_website/static/src/builder/external_image_save_plugin.js
Normal file
171
ai_website/static/src/builder/external_image_save_plugin.js
Normal file
@@ -0,0 +1,171 @@
|
||||
import { Plugin } from "@html_editor/plugin";
|
||||
import { registry } from "@web/core/registry";
|
||||
import { rpc } from "@web/core/network/rpc";
|
||||
import { _t } from "@web/core/l10n/translation";
|
||||
|
||||
export const EXTERNAL_IMAGE_TO_SAVE_CLASS = "o_external_image_to_save";
|
||||
|
||||
// External image URLs inside a CSS `url()`, e.g. `background-image: url("https://…")`.
|
||||
const CSS_URL_RE = /url\(\s*['"]?([^'")\s]+)['"]?\s*\)/gi;
|
||||
// A srcset is a comma separated list of `<url> [descriptor]` candidates.
|
||||
const SRCSET_CANDIDATE_RE = /(?:^|,)\s*([^\s,]+)/g;
|
||||
|
||||
/**
|
||||
* Copies external images into Odoo attachments when the page is saved.
|
||||
*
|
||||
* A page that references an image on someone else's server breaks as soon as that
|
||||
* server removes it, starts blocking hotlinks or goes away, and it silently sends
|
||||
* visitors to a third party. Instead we want to save the images as attachements.
|
||||
*
|
||||
* Only elements flagged with {@link EXTERNAL_IMAGE_TO_SAVE_CLASS} are considered: the
|
||||
* download makes the server fetch a caller-provided URL, so it stays opt-in per image
|
||||
* instead of scanning the whole editable on every save.
|
||||
*/
|
||||
export class ExternalImageSavePlugin extends Plugin {
|
||||
static id = "externalImageSave";
|
||||
static shared = ["markExternalImages", "localizeExternalImages"];
|
||||
|
||||
/** @type {import("plugins").WebsiteResources} */
|
||||
resources = {
|
||||
on_will_save_handlers: this.localizeExternalImages.bind(this),
|
||||
};
|
||||
|
||||
/**
|
||||
* Flag every element of `rootEl` pointing at an image hosted elsewhere, so that
|
||||
* {@link localizeExternalImages} copies it into Odoo on the next save.
|
||||
*
|
||||
* @param {HTMLElement|DocumentFragment} rootEl
|
||||
*/
|
||||
markExternalImages(rootEl) {
|
||||
const selector = "img[src], img[srcset], [style]";
|
||||
for (const el of rootEl.querySelectorAll(selector)) {
|
||||
if (this.getExternalImageUrls(el).length) {
|
||||
el.classList.add(EXTERNAL_IMAGE_TO_SAVE_CLASS);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Download the flagged external images into attachments and point the elements at
|
||||
* the local copies.
|
||||
*
|
||||
* A URL that cannot be downloaded keeps its external value and its flag, so the
|
||||
* page still renders and a later save tries again; failing the save instead would
|
||||
* lose the user's work over a third-party server being slow.
|
||||
*
|
||||
* @param {HTMLElement} [editableEl]
|
||||
*/
|
||||
async localizeExternalImages(editableEl = this.editable) {
|
||||
const els = [...editableEl.querySelectorAll(`.${EXTERNAL_IMAGE_TO_SAVE_CLASS}`)];
|
||||
const urls = new Set(els.flatMap((el) => this.getExternalImageUrls(el)));
|
||||
if (!urls.size) {
|
||||
// Nothing external left: the images were replaced or removed since they
|
||||
// were flagged.
|
||||
this.clearFlags(els);
|
||||
return;
|
||||
}
|
||||
|
||||
let sources = {};
|
||||
let errors = {};
|
||||
try {
|
||||
({ sources = {}, errors = {} } = await rpc("/ai_website/localize_external_images", {
|
||||
urls: [...urls],
|
||||
}));
|
||||
} catch {
|
||||
this.notifyFailures(urls.size);
|
||||
return;
|
||||
}
|
||||
|
||||
for (const el of els) {
|
||||
this.remapUrls(el, sources);
|
||||
}
|
||||
// Keep the flag only where an external URL survived, so the next save retries it.
|
||||
this.clearFlags(els.filter((el) => !this.getExternalImageUrls(el).length));
|
||||
const failureCount = Object.keys(errors).length;
|
||||
if (failureCount) {
|
||||
this.notifyFailures(failureCount);
|
||||
}
|
||||
}
|
||||
|
||||
clearFlags(els) {
|
||||
for (const el of els) {
|
||||
el.classList.remove(EXTERNAL_IMAGE_TO_SAVE_CLASS);
|
||||
}
|
||||
}
|
||||
|
||||
notifyFailures(count) {
|
||||
this.services.notification.add(
|
||||
_t(
|
||||
"%s image(s) are still hosted on another website and may stop working. You can save again to retry saving them.",
|
||||
count
|
||||
),
|
||||
{ type: "warning" }
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {HTMLElement} el
|
||||
* @returns {string[]} the external image URLs of `el`, as written in the document
|
||||
*/
|
||||
getExternalImageUrls(el) {
|
||||
const urls = [
|
||||
el.getAttribute("src"),
|
||||
...this.matchAll(el.getAttribute("srcset"), SRCSET_CANDIDATE_RE),
|
||||
...this.matchAll(el.style.backgroundImage, CSS_URL_RE),
|
||||
];
|
||||
return urls.filter((url) => this.isExternalUrl(url));
|
||||
}
|
||||
|
||||
matchAll(value, regex) {
|
||||
return value ? [...value.matchAll(regex)].map((match) => match[1]) : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace the external URLs of `el` by the local ones of `sources`, keyed by
|
||||
* absolute URL.
|
||||
*
|
||||
* @param {HTMLElement} el
|
||||
* @param {Object.<string, string>} sources
|
||||
*/
|
||||
remapUrls(el, sources) {
|
||||
for (const url of this.getExternalImageUrls(el)) {
|
||||
const localUrl = sources[this.resolveUrl(url)];
|
||||
if (!localUrl) {
|
||||
continue;
|
||||
}
|
||||
for (const attribute of ["src", "srcset"]) {
|
||||
const value = el.getAttribute(attribute);
|
||||
if (value?.includes(url)) {
|
||||
el.setAttribute(attribute, value.replaceAll(url, localUrl));
|
||||
}
|
||||
}
|
||||
if (el.style.backgroundImage.includes(url)) {
|
||||
el.style.backgroundImage = el.style.backgroundImage.replaceAll(url, localUrl);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An image is external when it is served over HTTP(S) by another origin than the
|
||||
* website itself. Relative URLs, `data:` and `blob:` sources are already local or
|
||||
* cannot be downloaded, and are left alone.
|
||||
*/
|
||||
isExternalUrl(url) {
|
||||
const resolvedUrl = url && this.resolveUrl(url);
|
||||
if (!resolvedUrl) {
|
||||
return false;
|
||||
}
|
||||
const { protocol, origin } = new URL(resolvedUrl);
|
||||
return ["http:", "https:"].includes(protocol) && origin !== this.document.location.origin;
|
||||
}
|
||||
|
||||
resolveUrl(url) {
|
||||
try {
|
||||
return new URL(url, this.document.location.href).href;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
registry.category("website-plugins").add(ExternalImageSavePlugin.id, ExternalImageSavePlugin);
|
||||
7
ai_website/static/src/builder/media_dialog_patch.js
Normal file
7
ai_website/static/src/builder/media_dialog_patch.js
Normal file
@@ -0,0 +1,7 @@
|
||||
import { mediaDialogProps } from "@html_editor/main/media/media_dialog/media_dialog";
|
||||
import { patch } from "@web/core/utils/patch";
|
||||
import { t } from "@odoo/owl";
|
||||
|
||||
patch(mediaDialogProps, {
|
||||
imageSrc: t.string().optional(),
|
||||
});
|
||||
3
ai_website/static/src/builder/option_container.scss
Normal file
3
ai_website/static/src/builder/option_container.scss
Normal file
@@ -0,0 +1,3 @@
|
||||
.o_ai_content_badge {
|
||||
color: $o-we-color-accent;
|
||||
}
|
||||
15
ai_website/static/src/builder/option_container.xml
Normal file
15
ai_website/static/src/builder/option_container.xml
Normal file
@@ -0,0 +1,15 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<templates xml:space="preserve">
|
||||
|
||||
<t t-name="html_builder.OptionsContainer" t-inherit="html_builder.OptionsContainer" t-inherit-mode="extension">
|
||||
<xpath expr="//span[@t-out='this.title']" position="after">
|
||||
<span
|
||||
t-if="this.props.editingElement.matches('[data-contains-ai-content]')"
|
||||
class="ms-1 fw-bold o_ai_content_badge"
|
||||
style="font-size: 0.7em;"
|
||||
data-tooltip="Customized by AI. Standard builder options may be limited or behave differently."
|
||||
>AI</span>
|
||||
</xpath>
|
||||
</t>
|
||||
|
||||
</templates>
|
||||
220
ai_website/static/src/builder/plugins/ai_script_plugin.js
Normal file
220
ai_website/static/src/builder/plugins/ai_script_plugin.js
Normal file
@@ -0,0 +1,220 @@
|
||||
import { Plugin } from "@html_editor/plugin";
|
||||
import { withSequence } from "@html_editor/utils/resource";
|
||||
import { registry } from "@web/core/registry";
|
||||
import { _t } from "@web/core/l10n/translation";
|
||||
import { AiGeneratedScriptsPanel } from "../ai_generated_scripts_panel";
|
||||
import { proxy } from "@odoo/owl";
|
||||
import { getScriptTitle } from "../../utils";
|
||||
|
||||
export class AiScriptPlugin extends Plugin {
|
||||
static id = "aiScript";
|
||||
static dependencies = ["domObserver", "history"];
|
||||
static shared = [
|
||||
"detachScripts",
|
||||
"removeScript",
|
||||
"restartScripts",
|
||||
"runScript",
|
||||
"normalizeScripts",
|
||||
"stopScripts",
|
||||
"stopScript",
|
||||
];
|
||||
|
||||
aiGeneratedScriptsPanelProps = proxy({ scripts: [] });
|
||||
|
||||
resources = {
|
||||
lower_panel_entries: withSequence(10, {
|
||||
Component: AiGeneratedScriptsPanel,
|
||||
props: this.aiGeneratedScriptsPanelProps,
|
||||
}),
|
||||
on_normalized_handlers: this.updateAiGeneratedScriptsPanelProps.bind(this),
|
||||
on_ai_script_update_handlers: this.updateAiGeneratedScriptsPanelProps.bind(this),
|
||||
system_attributes: ["data-ai-script-stopped", "data-ai-tracked", "data-ai-temp"],
|
||||
on_will_save_handlers: (rootEl) => {
|
||||
this.stopScripts(rootEl);
|
||||
this.cleanAiMutations(rootEl);
|
||||
},
|
||||
on_saved_handlers: this.restartScripts.bind(this),
|
||||
on_snippet_dropped_handlers: ({ snippetEl }) => this.restartScripts(snippetEl),
|
||||
};
|
||||
|
||||
setup() {
|
||||
this.aiScriptsManager = this.window.__aiScriptsManager__?.manager;
|
||||
this.domObserver = this.dependencies.domObserver;
|
||||
if (this.aiScriptsManager) {
|
||||
this.aiScriptsManager.runCallback = (fn, args, { scriptEl }) => {
|
||||
try {
|
||||
return this.domObserver.ignore(() => fn(...args));
|
||||
} catch (error) {
|
||||
console.warn("AI script failed:", error);
|
||||
this.stopScript(scriptEl);
|
||||
this.services.notification.add(
|
||||
_t(
|
||||
'Script "%s" got an error and has been paused. Please, prompt AI again to fix it.',
|
||||
getScriptTitle(scriptEl)
|
||||
),
|
||||
{
|
||||
type: "danger",
|
||||
}
|
||||
);
|
||||
}
|
||||
};
|
||||
}
|
||||
this.restartScripts(this.editable);
|
||||
this.updateAiGeneratedScriptsPanelProps();
|
||||
}
|
||||
|
||||
destroy() {
|
||||
this.aiScriptsManager?.disposeAll();
|
||||
super.destroy();
|
||||
}
|
||||
|
||||
updateAiGeneratedScriptsPanelProps() {
|
||||
const scriptEls = [...this.editable.querySelectorAll("script[data-ai-script-id]")];
|
||||
this.aiGeneratedScriptsPanelProps.scripts = scriptEls.map((el) => ({
|
||||
el,
|
||||
isStopped: el.dataset.aiScriptStopped,
|
||||
}));
|
||||
}
|
||||
|
||||
insertScript(parentEl, scriptId, scriptContent) {
|
||||
const scriptEl = this.document.createElement("script");
|
||||
scriptEl.dataset.aiScriptId = scriptId;
|
||||
scriptEl.textContent = scriptContent;
|
||||
const protectedInsert = this.aiScriptsManager.protectMutations(() => {
|
||||
const existingScriptEl = parentEl.querySelector(
|
||||
`script[data-ai-script-id="${scriptId}"]`
|
||||
);
|
||||
if (existingScriptEl) {
|
||||
this.aiScriptsManager.disposeScript(existingScriptEl);
|
||||
existingScriptEl.remove();
|
||||
}
|
||||
parentEl.appendChild(scriptEl);
|
||||
});
|
||||
protectedInsert();
|
||||
return scriptEl;
|
||||
}
|
||||
|
||||
removeScript(el) {
|
||||
const parentEl = el.parentElement;
|
||||
if (!parentEl) {
|
||||
return;
|
||||
}
|
||||
const scriptId = el.dataset.aiScriptId;
|
||||
const scriptContent = el.textContent;
|
||||
let currentScriptEl = el;
|
||||
|
||||
const removeCurrentScript = () => {
|
||||
this.aiScriptsManager.disposeScript(currentScriptEl);
|
||||
currentScriptEl.remove();
|
||||
};
|
||||
this.domObserver.stageCustomMutation({
|
||||
apply: () => removeCurrentScript(),
|
||||
revert: () => {
|
||||
currentScriptEl = this.insertScript(parentEl, scriptId, scriptContent);
|
||||
},
|
||||
});
|
||||
removeCurrentScript();
|
||||
}
|
||||
|
||||
stopScripts(rootEl = this.editable) {
|
||||
const scriptEls = rootEl.querySelectorAll("script[data-ai-script-id]");
|
||||
for (const scriptEl of scriptEls) {
|
||||
this.stopScript(scriptEl);
|
||||
}
|
||||
}
|
||||
|
||||
stopScript(scriptEl) {
|
||||
this.domObserver.ignore(() => this.aiScriptsManager.disposeScript(scriptEl));
|
||||
scriptEl.setAttribute("data-ai-script-stopped", "1");
|
||||
this.trigger("on_ai_script_update_handlers");
|
||||
}
|
||||
|
||||
runScript(scriptEl) {
|
||||
if (!scriptEl.dataset.aiScriptStopped) {
|
||||
return;
|
||||
}
|
||||
const parentEl = scriptEl.parentElement;
|
||||
this.domObserver.ignore(() =>
|
||||
this.insertScript(parentEl, scriptEl.dataset.aiScriptId, scriptEl.textContent)
|
||||
);
|
||||
this.trigger("on_ai_script_update_handlers");
|
||||
}
|
||||
|
||||
restartScripts(rootEl = this.editable) {
|
||||
this.cleanAiMutations(rootEl);
|
||||
if (rootEl.matches("script[data-ai-script-id]")) {
|
||||
this.insertScript(rootEl.parentNode, rootEl.dataset.aiScriptId, rootEl.textContent);
|
||||
return;
|
||||
}
|
||||
const scriptEls = rootEl.querySelectorAll("script[data-ai-script-id]");
|
||||
for (const scriptEl of scriptEls) {
|
||||
// This "restarts" the scripts.
|
||||
this.insertScript(
|
||||
scriptEl.parentNode,
|
||||
scriptEl.dataset.aiScriptId,
|
||||
scriptEl.textContent
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
cleanAiMutations(rootEl = this.editable) {
|
||||
rootEl.querySelectorAll("[data-ai-temp]").forEach((el) => el.remove());
|
||||
rootEl.querySelectorAll("[data-ai-tracked]").forEach((el) => {
|
||||
this.aiScriptsManager.restoreElement(el);
|
||||
});
|
||||
rootEl.querySelectorAll("[data-ai-script-stopped]").forEach((el) => {
|
||||
delete el.dataset.aiScriptStopped;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Swap the scripts of `el` for placeholders, and return the callback that
|
||||
* puts them back once `el` has been sanitized.
|
||||
*
|
||||
* @param {Element} el
|
||||
* @returns {Function} restores the detached scripts
|
||||
*/
|
||||
detachScripts(el) {
|
||||
const replaceScript = (scriptEl) => {
|
||||
const placeholderEl = this.document.createElement("span");
|
||||
if (scriptEl.dataset.aiScriptId) {
|
||||
placeholderEl.dataset.aiScriptPlaceholderId = scriptEl.dataset.aiScriptId;
|
||||
scriptEl.replaceWith(placeholderEl);
|
||||
return placeholderEl;
|
||||
}
|
||||
};
|
||||
// If el itself is a script just swap it for a placeholder.
|
||||
if (el.matches("script")) {
|
||||
const placeholderEl = replaceScript(el);
|
||||
return () => placeholderEl?.replaceWith(el);
|
||||
}
|
||||
const scriptEls = [...el.querySelectorAll("script")];
|
||||
scriptEls.forEach(replaceScript);
|
||||
return () => {
|
||||
scriptEls.forEach((scriptEl) => {
|
||||
if (scriptEl.dataset.aiScriptId) {
|
||||
const placeholderEl = el.querySelector(
|
||||
`[data-ai-script-placeholder-id="${scriptEl.dataset.aiScriptId}"]`
|
||||
);
|
||||
placeholderEl.replaceWith(scriptEl);
|
||||
}
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
normalizeScripts(el) {
|
||||
const scriptEls = el.querySelectorAll("[data-ai-script-id]");
|
||||
for (const scriptEl of scriptEls) {
|
||||
// We need to make the id unique, to avoid possible collisions.
|
||||
if (scriptEl.dataset.aiScriptId.split("--").length === 1) {
|
||||
scriptEl.dataset.aiScriptId += `--${this.getScriptUniqueId()}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
getScriptUniqueId() {
|
||||
return Date.now().toString(36) + Math.random().toString(36).substring(2);
|
||||
}
|
||||
}
|
||||
|
||||
registry.category("website-plugins").add(AiScriptPlugin.id, AiScriptPlugin);
|
||||
@@ -0,0 +1,15 @@
|
||||
import { patch } from "@web/core/utils/patch";
|
||||
import { SetCoverBackgroundAction } from "@website/builder/plugins/options/cover_properties_option_plugin";
|
||||
|
||||
patch(SetCoverBackgroundAction.prototype, {
|
||||
getMediaDialogProps({ editingElement }) {
|
||||
const props = super.getMediaDialogProps({ editingElement });
|
||||
const backgroundImageSrc =
|
||||
editingElement.querySelector(".o_record_cover_image")?.style.backgroundImage;
|
||||
const path = backgroundImageSrc?.match(/url\(["']?([^"']+)["']?\)/)?.[1];
|
||||
return {
|
||||
...props,
|
||||
imageSrc: path,
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Plugin } from "@html_editor/plugin";
|
||||
import { registry } from "@web/core/registry";
|
||||
|
||||
export class AiWebsiteBuilderTranslationPlugin extends Plugin {
|
||||
static id = "aiWebsiteBuilderTranslation";
|
||||
setup() {
|
||||
this.stopAiScripts();
|
||||
}
|
||||
|
||||
stopAiScripts(rootEl = this.editable) {
|
||||
rootEl.querySelectorAll("script[data-ai-script-id]").forEach((scriptEl) => {
|
||||
this.window.__aiScriptsManager__.manager.disposeScript(scriptEl);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
registry
|
||||
.category("translation-plugins")
|
||||
.add(AiWebsiteBuilderTranslationPlugin.id, AiWebsiteBuilderTranslationPlugin);
|
||||
50
ai_website/static/src/builder/website_builder_patch.js
Normal file
50
ai_website/static/src/builder/website_builder_patch.js
Normal file
@@ -0,0 +1,50 @@
|
||||
import { _t } from "@web/core/l10n/translation";
|
||||
import { patch } from "@web/core/utils/patch";
|
||||
import { WebsiteBuilder } from "@website/builder/website_builder";
|
||||
import { useBus } from "@web/core/utils/hooks";
|
||||
import { isPageAiEditable } from "../utils";
|
||||
|
||||
patch(WebsiteBuilder.prototype, {
|
||||
setup() {
|
||||
super.setup();
|
||||
useBus(this.env.bus, "RELOAD_EDITOR", async (ev) => await this.reloadEditor(ev.detail));
|
||||
},
|
||||
get isPageAiEditable() {
|
||||
return isPageAiEditable(this.websiteService);
|
||||
},
|
||||
get aiAssistantTooltip() {
|
||||
if (!this.isPageAiEditable) {
|
||||
return _t("The AI Assistant is not yet available on this page");
|
||||
}
|
||||
if (!this.websiteService.isDesigner) {
|
||||
return _t("The AI Assistant requires 'Editor and Designer' access");
|
||||
}
|
||||
return _t("AI Assistant");
|
||||
},
|
||||
get isTranslationMode() {
|
||||
return this.websiteService.currentWebsite?.metadata.translatable;
|
||||
},
|
||||
async onAiChatClick() {
|
||||
const launcher = this.env.services["aiChatLauncher"];
|
||||
if (!launcher) {
|
||||
this.env.services["notification"].add("AI service not available.", { type: "warning" });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await launcher.launchAIChat({
|
||||
interfaceKey: "website_builder_ai",
|
||||
channelTitle: "AI Website Assistant",
|
||||
});
|
||||
} catch (e) {
|
||||
this.env.services["notification"].add("Failed to open AI chat.", { type: "danger" });
|
||||
console.error(e);
|
||||
}
|
||||
},
|
||||
async reloadEditor({ save = true } = {}) {
|
||||
if (save) {
|
||||
this.editor.shared.history.commit();
|
||||
await this.editor.shared.savePlugin.save();
|
||||
}
|
||||
await this.editor.config.reloadEditor({ target: "main" });
|
||||
},
|
||||
});
|
||||
94
ai_website/static/src/components/dialog/add_page_dialog.js
Normal file
94
ai_website/static/src/components/dialog/add_page_dialog.js
Normal file
@@ -0,0 +1,94 @@
|
||||
import { proxy } from "@odoo/owl";
|
||||
import { _t } from "@web/core/l10n/translation";
|
||||
import { patch } from "@web/core/utils/patch";
|
||||
import { rpc } from "@web/core/network/rpc";
|
||||
import { useService } from "@web/core/utils/hooks";
|
||||
import { AddPageConfirmDialog } from "@website/components/dialog/add_page_dialog";
|
||||
|
||||
patch(AddPageConfirmDialog.prototype, {
|
||||
setup() {
|
||||
super.setup();
|
||||
this.notification = useService("notification");
|
||||
this.state = proxy({
|
||||
...this.state,
|
||||
instructions: "",
|
||||
tone: "",
|
||||
generateText: false,
|
||||
loading: false,
|
||||
});
|
||||
|
||||
this.tones = {
|
||||
concise: {
|
||||
title: _t("Concise"),
|
||||
description: "Keep it short and to the point",
|
||||
},
|
||||
professional: {
|
||||
title: _t("Professional"),
|
||||
description: "Use a formal, professional tone",
|
||||
},
|
||||
friendly: {
|
||||
title: _t("Friendly"),
|
||||
description: "Keep it relaxed and easygoing",
|
||||
},
|
||||
persuasive: {
|
||||
title: _t("Persuasive"),
|
||||
description: "Make it more action-oriented",
|
||||
},
|
||||
informative: {
|
||||
title: _t("Informative"),
|
||||
description: "Make it clear and explanatory",
|
||||
},
|
||||
};
|
||||
},
|
||||
|
||||
onChangeGenerateText(value) {
|
||||
this.state.generateText = value;
|
||||
},
|
||||
|
||||
onToneSelect(ev) {
|
||||
const tone = ev.target.dataset.tone;
|
||||
if (tone === this.state.tone) {
|
||||
this.state.tone = "";
|
||||
return;
|
||||
}
|
||||
this.state.tone = tone;
|
||||
},
|
||||
|
||||
get buttonTitle() {
|
||||
if (this.state.generateText) {
|
||||
return _t("Create with AI");
|
||||
}
|
||||
return _t("Create");
|
||||
},
|
||||
|
||||
async processSectionsArch() {
|
||||
if (this.state.sectionsArch) {
|
||||
const aiGeneratedContent = await rpc("/ai_website/generate_page", {
|
||||
instructions: this.state.instructions || "",
|
||||
name: this.state.name,
|
||||
sectionsArch: this.state.sectionsArch,
|
||||
tone: this.state.tone ? this.tones[this.state.tone] : "",
|
||||
templateId: this.state.templateId || "",
|
||||
});
|
||||
if (aiGeneratedContent && aiGeneratedContent.html) {
|
||||
if (aiGeneratedContent.error) {
|
||||
this.notification.add(aiGeneratedContent.error, {
|
||||
type: "danger",
|
||||
sticky: true,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
this.state.sectionsArch = aiGeneratedContent.html;
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
async addPage() {
|
||||
if (this.state.generateText) {
|
||||
this.state.loading = true;
|
||||
await this.processSectionsArch();
|
||||
}
|
||||
await super.addPage();
|
||||
this.state.loading = false;
|
||||
},
|
||||
});
|
||||
53
ai_website/static/src/components/dialog/add_page_dialog.xml
Normal file
53
ai_website/static/src/components/dialog/add_page_dialog.xml
Normal file
@@ -0,0 +1,53 @@
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<templates xml:space="preserve">
|
||||
|
||||
<t t-name="ai_website.AddPageConfirmDialog" t-inherit="website.AddPageConfirmDialog" t-inherit-mode="extension">
|
||||
<xpath expr="//WebsiteDialog" position="attributes">
|
||||
<attribute name="primaryTitle">this.buttonTitle</attribute>
|
||||
</xpath>
|
||||
<xpath expr="//div[@class='row gy-4']" position="attributes">
|
||||
<attribute name="t-att-class">this.state.loading ? 'row gy-4 opacity-50 pe-none' : 'row gy-4'</attribute>
|
||||
</xpath>
|
||||
<xpath expr="//div[@class='row gy-4']" position="inside">
|
||||
<div t-if="this.state.loading" class="d-flex justify-content-center w-100 position-absolute" style="bottom: 160px;">
|
||||
<div class="text-muted">
|
||||
<i class="oi oi-spin me-2" data-icon="progress_activity"></i>
|
||||
Generating content...
|
||||
</div>
|
||||
</div>
|
||||
</xpath>
|
||||
<xpath expr="//Switch[contains(@label.translate, 'Add to menu')]" position="after">
|
||||
<div t-if="!!this.state.sectionsArch" class="offset-md-3 col-md-9">
|
||||
<Switch extraClasses="'d-inline-flex align-items-center text-start'"
|
||||
value="this.state.generateText"
|
||||
onChange="(checked) => this.onChangeGenerateText(checked)"
|
||||
labelIcon="'o_ai_icon'"
|
||||
labelIconClass="'oi-lg o_ai_icon_color'"
|
||||
label.translate="Generate text"/>
|
||||
</div>
|
||||
<t t-if="this.state.generateText">
|
||||
<label class="col-form-label col-md-3">
|
||||
Instructions
|
||||
</label>
|
||||
<div class="col-md-9">
|
||||
<textarea t-model.proxy="this.state.instructions"
|
||||
class="form-control"
|
||||
rows="4"
|
||||
placeholder="Describe the page with keywords..."></textarea>
|
||||
</div>
|
||||
<div class="btn-group offset-md-3 col-md-9 text-start" role="group" aria-label="Tone Selection">
|
||||
<t t-foreach="Object.keys(this.tones)" t-as="toneOption" t-key="toneOption">
|
||||
<button
|
||||
t-att-class="'btn btn-sm me-1 rounded-pill ' + (this.state.tone === toneOption ? 'btn-primary' : 'btn-outline-secondary')"
|
||||
t-att-title="this.tones[toneOption].title"
|
||||
t-on-click="this.onToneSelect"
|
||||
t-att-data-tone="toneOption"
|
||||
>
|
||||
<t t-out="this.tones[toneOption].title"/>
|
||||
</button>
|
||||
</t>
|
||||
</div>
|
||||
</t>
|
||||
</xpath>
|
||||
</t>
|
||||
</templates>
|
||||
99
ai_website/static/src/components/dialog/seo_patch.js
Normal file
99
ai_website/static/src/components/dialog/seo_patch.js
Normal file
@@ -0,0 +1,99 @@
|
||||
import { rpc } from "@web/core/network/rpc";
|
||||
import { useService } from "@web/core/utils/hooks";
|
||||
import { patch } from "@web/core/utils/patch";
|
||||
import { TitleDescription, OptimizeSEODialog, seoContext } from "@website/components/dialog/seo";
|
||||
|
||||
const SCHEMA = {
|
||||
type: "object",
|
||||
properties: {
|
||||
title: {
|
||||
type: "string",
|
||||
description: "The title of the web page.",
|
||||
minLength: 50,
|
||||
},
|
||||
description: {
|
||||
type: "string",
|
||||
description: "The description of the web page.",
|
||||
minLength: 100,
|
||||
},
|
||||
keywords: {
|
||||
type: "array",
|
||||
description: "A list of relevant keyword based on the web page content.",
|
||||
items: {
|
||||
type: "string",
|
||||
},
|
||||
maxItems: 10,
|
||||
},
|
||||
},
|
||||
required: ["title", "description", "keywords"],
|
||||
additionalProperties: false,
|
||||
};
|
||||
|
||||
const getAISeo = async (component, onlyKeywords = false) => {
|
||||
/** @type{HTMLElement} */
|
||||
const pageTextContentEl = component.website.pageDocument.documentElement.querySelector("main");
|
||||
|
||||
// Filtering down on actual interesting elements for seo
|
||||
// getting rid of noise for the agent
|
||||
const textElements = pageTextContentEl.querySelectorAll("h1, h2, h3, a, p");
|
||||
|
||||
// We only keep elements that are visible to the user
|
||||
// since it would most likely be what the user would
|
||||
// use if he had to do SEO manually
|
||||
let pageContentStr = "";
|
||||
textElements.forEach((element) => {
|
||||
const isVisible = element.checkVisibility({
|
||||
checkOpacity: true,
|
||||
checkVisibilityCSS: true,
|
||||
});
|
||||
if (!isVisible) {
|
||||
return;
|
||||
}
|
||||
pageContentStr += `\n\n${element.outerHTML}`;
|
||||
});
|
||||
|
||||
const seoOutput = await rpc("/ai/get_direct_response", {
|
||||
interface_key: "website_seo_ai",
|
||||
prompt: JSON.stringify({
|
||||
website_name: component.website.currentWebsite.name,
|
||||
language: component.website.currentWebsite.metadata.lang,
|
||||
website_content: pageContentStr,
|
||||
}),
|
||||
schema: SCHEMA,
|
||||
});
|
||||
|
||||
const parsedOutput = JSON.parse(seoOutput);
|
||||
|
||||
if (parsedOutput.keywords.length > 0) {
|
||||
component.seoContext.keywords = parsedOutput.keywords;
|
||||
}
|
||||
if (!onlyKeywords) {
|
||||
component.seoContext.title = parsedOutput.title;
|
||||
component.seoContext.description = parsedOutput.description;
|
||||
}
|
||||
};
|
||||
|
||||
patch(TitleDescription.prototype, {
|
||||
setup() {
|
||||
super.setup();
|
||||
this.orm = useService("orm");
|
||||
},
|
||||
async autoFill() {
|
||||
await getAISeo(this);
|
||||
},
|
||||
});
|
||||
|
||||
patch(OptimizeSEODialog.prototype, {
|
||||
async save() {
|
||||
const metaImageSrc = seoContext.metaImage;
|
||||
if (metaImageSrc) {
|
||||
const match = metaImageSrc.match(/\/web\/image\/(\d+)-/);
|
||||
if (match) {
|
||||
await this.orm.call("ai.attachment.vacuum", "mark_attachments_used", [], {
|
||||
attachment_ids: [parseInt(match[1])],
|
||||
});
|
||||
}
|
||||
}
|
||||
await super.save();
|
||||
},
|
||||
});
|
||||
10
ai_website/static/src/components/dialog/seo_patch.xml
Normal file
10
ai_website/static/src/components/dialog/seo_patch.xml
Normal file
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<templates xml:space="preserve">
|
||||
<t t-name="ai_website.TitleDescription" t-inherit="website.TitleDescription" t-inherit-mode="extension">
|
||||
<xpath expr="//span[contains(text(), 'Need help to optimize?')]/following-sibling::button/span" position="replace">
|
||||
<span><span class="oi-fw o_ai_icon_color d-inline-block align-top me-1" data-icon="o_ai_icon"/> Update with AI</span>
|
||||
</xpath>
|
||||
<xpath expr="//span[contains(text(), 'Need help to optimize?')]/following-sibling::button/i" position="replace">
|
||||
</xpath>
|
||||
</t>
|
||||
</templates>
|
||||
25
ai_website/static/src/discuss/chat_window_model_patch.js
Normal file
25
ai_website/static/src/discuss/chat_window_model_patch.js
Normal file
@@ -0,0 +1,25 @@
|
||||
import { ChatWindow } from "@mail/core/common/chat_window_model";
|
||||
import { patch } from "@web/core/utils/patch";
|
||||
import { aiChannelBus } from "@ai/utils/ai_channel_bus";
|
||||
import {
|
||||
AI_WEBSITE_ELEMENT_SELECTION_COMMAND,
|
||||
isAiWebsiteBuilderChannel,
|
||||
} from "@ai_website/utils";
|
||||
|
||||
patch(ChatWindow.prototype, {
|
||||
fold() {
|
||||
if (isAiWebsiteBuilderChannel(this.channel)) {
|
||||
aiChannelBus.trigger(AI_WEBSITE_ELEMENT_SELECTION_COMMAND, {
|
||||
type: "stop_picker",
|
||||
});
|
||||
}
|
||||
return super.fold(...arguments);
|
||||
},
|
||||
_onClose() {
|
||||
const isAiWebsiteBuilder = isAiWebsiteBuilderChannel(this.channel);
|
||||
super._onClose(...arguments);
|
||||
if (isAiWebsiteBuilder) {
|
||||
aiChannelBus.trigger(AI_WEBSITE_ELEMENT_SELECTION_COMMAND, { type: "release" });
|
||||
}
|
||||
},
|
||||
});
|
||||
24
ai_website/static/src/discuss/client_tools.js
Normal file
24
ai_website/static/src/discuss/client_tools.js
Normal file
@@ -0,0 +1,24 @@
|
||||
import "@ai/client_tools";
|
||||
import { aiClientToolsRegistry } from "@ai/discuss/core/common/ai_client_tool_registry";
|
||||
import { getData } from "@ai/utils/bus_data_getter";
|
||||
|
||||
aiClientToolsRegistry.add("finalize_website_page", async (thread, params) => {
|
||||
const page = await getData("aiWebsitePage");
|
||||
const report = await page.finalizePage(params.html, params.other_actions, params.target_page);
|
||||
return { note: params.note, actions: report };
|
||||
});
|
||||
|
||||
// The default `reload` re-inits the whole website builder action, which bounces
|
||||
// the user back to the homepage. Inside the builder, reload the editor in place.
|
||||
const defaultReload = aiClientToolsRegistry.get("reload");
|
||||
aiClientToolsRegistry.add(
|
||||
"reload",
|
||||
async (thread, params) => {
|
||||
const env = thread?.store?.env;
|
||||
if (!env?.services?.website?.currentWebsite) {
|
||||
return defaultReload(thread, params);
|
||||
}
|
||||
env.bus.trigger("RELOAD_EDITOR", { save: false });
|
||||
},
|
||||
{ force: true },
|
||||
);
|
||||
62
ai_website/static/src/discuss/composer_patch.js
Normal file
62
ai_website/static/src/discuss/composer_patch.js
Normal file
@@ -0,0 +1,62 @@
|
||||
import { Composer } from "@mail/core/common/composer";
|
||||
import { ComposerAction, registerComposerAction } from "@mail/core/common/composer_actions";
|
||||
import { onMounted, proxy } from "@odoo/owl";
|
||||
import { _t } from "@web/core/l10n/translation";
|
||||
import { patch } from "@web/core/utils/patch";
|
||||
import { useBus } from "@web/core/utils/hooks";
|
||||
import { aiChannelBus } from "@ai/utils/ai_channel_bus";
|
||||
import {
|
||||
AI_WEBSITE_ELEMENT_SELECTION_COMMAND,
|
||||
AI_WEBSITE_ELEMENT_SELECTION_STATE,
|
||||
isAiWebsiteBuilderChannel,
|
||||
} from "@ai_website/utils";
|
||||
|
||||
patch(ComposerAction.prototype, {
|
||||
_getAiComposerActions() {
|
||||
return [...super._getAiComposerActions(), "select-element"];
|
||||
},
|
||||
});
|
||||
|
||||
patch(Composer.prototype, {
|
||||
setup() {
|
||||
super.setup();
|
||||
this.aiWebsiteSelectionState = proxy({
|
||||
available: false,
|
||||
pickerActive: false,
|
||||
elements: [],
|
||||
});
|
||||
if (isAiWebsiteBuilderChannel(this.thread?.channel)) {
|
||||
useBus(aiChannelBus, AI_WEBSITE_ELEMENT_SELECTION_STATE, ({ detail }) => {
|
||||
Object.assign(this.aiWebsiteSelectionState, detail);
|
||||
});
|
||||
onMounted(() => {
|
||||
aiChannelBus.trigger(AI_WEBSITE_ELEMENT_SELECTION_COMMAND, {
|
||||
type: "request_state",
|
||||
});
|
||||
});
|
||||
}
|
||||
},
|
||||
deselectAiWebsiteElement(id) {
|
||||
aiChannelBus.trigger(AI_WEBSITE_ELEMENT_SELECTION_COMMAND, {
|
||||
type: "deselect",
|
||||
id,
|
||||
});
|
||||
},
|
||||
getAiWebsiteElementRemoveLabel(element) {
|
||||
return _t("Remove %(element)s", { element: element.label });
|
||||
},
|
||||
});
|
||||
|
||||
registerComposerAction("select-element", {
|
||||
condition: ({ owner }) => owner.aiWebsiteSelectionState.available,
|
||||
disabledCondition: ({ owner }) => owner.isAiAgentGenerating,
|
||||
icon: "pan_tool_alt",
|
||||
isActive: ({ owner }) => owner.aiWebsiteSelectionState.pickerActive,
|
||||
name: _t("Select Elements"),
|
||||
onSelected: () => {
|
||||
aiChannelBus.trigger(AI_WEBSITE_ELEMENT_SELECTION_COMMAND, {
|
||||
type: "toggle_picker",
|
||||
});
|
||||
},
|
||||
sequence: 30,
|
||||
});
|
||||
4
ai_website/static/src/discuss/composer_patch.scss
Normal file
4
ai_website/static/src/discuss/composer_patch.scss
Normal file
@@ -0,0 +1,4 @@
|
||||
.o-ai-website-selection-chip {
|
||||
background-color: $o-gray-800;
|
||||
color: $o-white;
|
||||
}
|
||||
39
ai_website/static/src/discuss/composer_patch.xml
Normal file
39
ai_website/static/src/discuss/composer_patch.xml
Normal file
@@ -0,0 +1,39 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<templates xml:space="preserve">
|
||||
|
||||
<t t-name="ai_website.ComposerElementSelection"
|
||||
t-inherit="mail.Composer"
|
||||
t-inherit-mode="extension">
|
||||
<xpath expr="//div[hasclass('o-mail-Composer-coreHeader')]" position="inside">
|
||||
<div t-if="this.aiWebsiteSelectionState.elements.length"
|
||||
class="o-ai-website-selection-chips d-flex flex-wrap gap-1 px-1 pb-1">
|
||||
<span t-foreach="this.aiWebsiteSelectionState.elements" t-as="element" t-key="element.id"
|
||||
class="o-ai-website-selection-chip badge rounded-pill d-inline-flex align-items-center gap-1">
|
||||
<span class="text-truncate" style="max-width: 180px" t-out="element.label"/>
|
||||
<button type="button" class="btn btn-link text-reset p-0 border-0 lh-1"
|
||||
t-att-disabled="this.isAiAgentGenerating"
|
||||
t-att-aria-label="this.getAiWebsiteElementRemoveLabel(element)"
|
||||
t-on-click="() => this.deselectAiWebsiteElement(element.id)">
|
||||
<i class="oi" data-icon="close"/>
|
||||
</button>
|
||||
</span>
|
||||
</div>
|
||||
</xpath>
|
||||
</t>
|
||||
|
||||
<t t-name="ai_website.MessageElementSelection"
|
||||
t-inherit="mail.Message"
|
||||
t-inherit-mode="extension">
|
||||
<xpath expr="//div[hasclass('o-mail-Message-textContent')]" position="before">
|
||||
<div t-if="this.message.ai_website_element_labels?.length"
|
||||
class="d-flex flex-wrap justify-content-end gap-1 mb-1">
|
||||
<span t-foreach="this.message.ai_website_element_labels"
|
||||
t-as="label"
|
||||
t-key="label_index"
|
||||
class="o-ai-website-selection-chip badge rounded-pill"
|
||||
t-out="label"/>
|
||||
</div>
|
||||
</xpath>
|
||||
</t>
|
||||
|
||||
</templates>
|
||||
29
ai_website/static/src/discuss/message_actions_patch.js
Normal file
29
ai_website/static/src/discuss/message_actions_patch.js
Normal file
@@ -0,0 +1,29 @@
|
||||
import { registerMessageAction } from "@mail/core/common/message_actions";
|
||||
import { AIMessageActions } from "@ai/discuss/message_actions_patch";
|
||||
import { _t } from "@web/core/l10n/translation";
|
||||
import { useService } from "@web/core/utils/hooks";
|
||||
import { isAiWebsiteBuilderChannel, isEditorSidebarOpen, isPageAiEditable } from "../utils";
|
||||
|
||||
function openWebsiteBuilder({ owner }) {
|
||||
const website = owner.websiteService;
|
||||
website.goToWebsite({
|
||||
path: isPageAiEditable(website) ? website.currentLocation : "/",
|
||||
lang: website.currentWebsite?.default_lang_id.code,
|
||||
edition: true,
|
||||
});
|
||||
}
|
||||
|
||||
AIMessageActions.push("open-website-builder");
|
||||
registerMessageAction("open-website-builder", {
|
||||
setup({ owner }) {
|
||||
owner.websiteService = useService("website");
|
||||
},
|
||||
condition: ({ owner, channel, message }) =>
|
||||
isAiWebsiteBuilderChannel(channel) &&
|
||||
!isEditorSidebarOpen(owner.websiteService) &&
|
||||
!message.isSelfAuthored &&
|
||||
message.eq(channel?.newestMessage),
|
||||
name: _t("Open Website Builder"),
|
||||
onSelected: openWebsiteBuilder,
|
||||
sequence: 5,
|
||||
});
|
||||
62
ai_website/static/src/discuss/thread_model_patch.js
Normal file
62
ai_website/static/src/discuss/thread_model_patch.js
Normal file
@@ -0,0 +1,62 @@
|
||||
import { Thread } from "@mail/core/common/thread_model";
|
||||
import { patch } from "@web/core/utils/patch";
|
||||
import { aiChannelBus } from "@ai/utils/ai_channel_bus";
|
||||
import {
|
||||
AI_WEBSITE_ELEMENT_SELECTION_COMMAND,
|
||||
isAiWebsiteBuilderChannel,
|
||||
} from "../utils";
|
||||
import { getData } from "@ai/utils/bus_data_getter";
|
||||
import { setAiResponsePromise } from "@ai_website/ai_processing_state";
|
||||
|
||||
patch(Thread.prototype, {
|
||||
setup() {
|
||||
super.setup(...arguments);
|
||||
// IMPROVEMENT: Block the editor only during Website tool execution, rather than every AI exchange.
|
||||
this.onChange(
|
||||
() => [isAiWebsiteBuilderChannel(this.channel) && this.channel.isAiGenerating],
|
||||
(isGenerating) => {
|
||||
if (!isGenerating) {
|
||||
return;
|
||||
}
|
||||
let active = true;
|
||||
let unblockBuilderUI;
|
||||
let resolveTurn;
|
||||
// Set the AiResponsePromise so that if we navigate to a new page while the
|
||||
// agent is still working, it will kepe the block up and remove it once the
|
||||
// worker is finished.
|
||||
setAiResponsePromise(new Promise((resolve) => (resolveTurn = resolve)));
|
||||
getData("htmlBuilder")
|
||||
.catch(() => null) // The builder may not be loaded in this browser.
|
||||
.then((builder) => {
|
||||
if (active) {
|
||||
unblockBuilderUI = builder?.blockBuilderUI(1_500);
|
||||
}
|
||||
});
|
||||
|
||||
// Release when activity stops or this thread is removed.
|
||||
return () => {
|
||||
active = false;
|
||||
unblockBuilderUI?.();
|
||||
resolveTurn();
|
||||
};
|
||||
},
|
||||
);
|
||||
},
|
||||
async post(body, postData = {}, extraData = {}) {
|
||||
if (isAiWebsiteBuilderChannel(this.channel)) {
|
||||
const prepareCommand = { type: "prepare_send" };
|
||||
aiChannelBus.trigger(AI_WEBSITE_ELEMENT_SELECTION_COMMAND, prepareCommand);
|
||||
if (prepareCommand.elementLabels?.length) {
|
||||
extraData = {
|
||||
...extraData,
|
||||
context: {
|
||||
...extraData.context,
|
||||
ai_website_element_labels: prepareCommand.elementLabels,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return super.post(body, postData, extraData);
|
||||
},
|
||||
});
|
||||
BIN
ai_website/static/src/img/snippet_previews/ai_livechat.webp
Normal file
BIN
ai_website/static/src/img/snippet_previews/ai_livechat.webp
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 2.6 KiB |
BIN
ai_website/static/src/img/snippets_thumbs/ai.png
Normal file
BIN
ai_website/static/src/img/snippets_thumbs/ai.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 2.8 KiB |
75
ai_website/static/src/public/ai_script_manager.js
Normal file
75
ai_website/static/src/public/ai_script_manager.js
Normal file
@@ -0,0 +1,75 @@
|
||||
/** @odoo-module ignore **/
|
||||
|
||||
class AiScriptsManager {
|
||||
constructor() {
|
||||
this.observerEntries = new Set();
|
||||
}
|
||||
|
||||
// Run `fn(...args)`. Overridden by the builder to run the call inside the
|
||||
// editor's mutation-ignoring scope, so AI mutations stay out of history.
|
||||
runCallback(fn, args) {
|
||||
return fn(...args);
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrap a callback so the mutations it makes are attributed to AI code.
|
||||
*
|
||||
* @param {Function} fn
|
||||
* @returns {Function}
|
||||
*/
|
||||
protectMutations(fn, scriptEl) {
|
||||
return (...args) => {
|
||||
try {
|
||||
this.flushObservers(false);
|
||||
return this.runCallback(fn, args, { scriptEl });
|
||||
} finally {
|
||||
// Changes done in this microtick are made by an AI script.
|
||||
this.flushObservers(true);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
whenReady(fn, scriptEl) {
|
||||
const run = this.protectMutations(fn, scriptEl);
|
||||
if (document.readyState === "loading") {
|
||||
document.addEventListener("DOMContentLoaded", run, { once: true });
|
||||
} else {
|
||||
run();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {boolean} aiChanges - whether queued mutations were made by an AI
|
||||
* script.
|
||||
*/
|
||||
flushObservers(aiChanges) {
|
||||
// Flush all tracked observers, so pending mutations are correctly
|
||||
// marked.
|
||||
for (const { observer, handleRecords } of this.observerEntries) {
|
||||
const records = observer.takeRecords();
|
||||
if (records.length) {
|
||||
handleRecords(records, aiChanges);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// AI uses next functions in its script to track mutations, however they are
|
||||
// needed only for people with the editor access, so we define dummy
|
||||
// placeholders here, and replace them for the real ones in
|
||||
// `ai_script_tracking`.
|
||||
trackElement() {}
|
||||
registerCleanup() {}
|
||||
}
|
||||
|
||||
const manager = new AiScriptsManager();
|
||||
|
||||
function getApi(scriptEl) {
|
||||
return Object.freeze({
|
||||
protectMutations: (fn) => manager.protectMutations(fn, scriptEl),
|
||||
trackElement: (element) => manager.trackElement(element, scriptEl),
|
||||
registerCleanup: (cleanupFn) => manager.registerCleanup(cleanupFn, scriptEl),
|
||||
whenReady: (fn) => manager.whenReady(fn, scriptEl),
|
||||
});
|
||||
}
|
||||
|
||||
window.__aiScriptsManager__ = { getApi, manager };
|
||||
264
ai_website/static/src/public/ai_script_tracking.js
Normal file
264
ai_website/static/src/public/ai_script_tracking.js
Normal file
@@ -0,0 +1,264 @@
|
||||
/** @odoo-module ignore **/
|
||||
|
||||
// Only served to users who can open the builder.
|
||||
|
||||
const trackedElementsMap = new Map();
|
||||
const scriptElementsMap = new Map();
|
||||
const scriptCleanupMap = new Map();
|
||||
|
||||
// A single observer watches every tracked element, so that `protectMutations`
|
||||
// flushes the whole page with one `takeRecords()`.
|
||||
let observerEntry = null;
|
||||
|
||||
/**
|
||||
* @param {AiScriptsManager} manager
|
||||
* @returns {{observer: MutationObserver, handleRecords: Function}}
|
||||
*/
|
||||
function getObserverEntry(manager) {
|
||||
if (!observerEntry) {
|
||||
const handleRecords = (mutations, isAIChange) => {
|
||||
for (const mutation of mutations) {
|
||||
trackedElementsMap.get(mutation.target)?.handleRecord(mutation, isAIChange);
|
||||
}
|
||||
};
|
||||
observerEntry = {
|
||||
observer: new MutationObserver((records) => handleRecords(records, false)),
|
||||
handleRecords,
|
||||
};
|
||||
manager.observerEntries.add(observerEntry);
|
||||
}
|
||||
return observerEntry;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {AiScriptsManager} manager
|
||||
*/
|
||||
function stopObserving(manager) {
|
||||
if (observerEntry) {
|
||||
observerEntry.observer.disconnect();
|
||||
manager.observerEntries.delete(observerEntry);
|
||||
observerEntry = null;
|
||||
}
|
||||
}
|
||||
|
||||
function runScriptCleanup(scriptEl) {
|
||||
try {
|
||||
const cleanupFn = scriptCleanupMap.get(scriptEl);
|
||||
if (cleanupFn) {
|
||||
cleanupFn();
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn("AI script cleanup failed:", error);
|
||||
}
|
||||
}
|
||||
|
||||
let styleParserEl = null;
|
||||
|
||||
/**
|
||||
* Parse a style attribute string into a Map of property -> {value, priority}.
|
||||
*
|
||||
* @param {string|null} styleStr
|
||||
* @returns {Map<string, {value: string, priority: string}>}
|
||||
*/
|
||||
function parseStyleMap(styleStr) {
|
||||
const map = new Map();
|
||||
if (!styleStr) {
|
||||
return map;
|
||||
}
|
||||
// Reused across calls: this runs on every style mutation of every tracked
|
||||
// element, i.e. once per frame per element for an animated one.
|
||||
styleParserEl ||= document.createElement("div");
|
||||
styleParserEl.style.cssText = styleStr;
|
||||
for (let i = 0; i < styleParserEl.style.length; i++) {
|
||||
const prop = styleParserEl.style[i];
|
||||
map.set(prop, {
|
||||
value: styleParserEl.style.getPropertyValue(prop),
|
||||
priority: styleParserEl.style.getPropertyPriority(prop),
|
||||
});
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
function parseClassSet(classStr) {
|
||||
return new Set((classStr || "").split(/\s+/).filter(Boolean));
|
||||
}
|
||||
|
||||
Object.assign(window.__aiScriptsManager__.manager, {
|
||||
trackElement(element, scriptEl) {
|
||||
if (!element) {
|
||||
return;
|
||||
}
|
||||
// Several scripts may mutate the same element.
|
||||
if (scriptEl) {
|
||||
if (!scriptElementsMap.has(scriptEl)) {
|
||||
scriptElementsMap.set(scriptEl, new Set());
|
||||
}
|
||||
scriptElementsMap.get(scriptEl).add(element);
|
||||
}
|
||||
if (trackedElementsMap.has(element)) {
|
||||
return;
|
||||
}
|
||||
element.dataset.aiTracked = "true";
|
||||
|
||||
// Per-property AI ownership tracking.
|
||||
// Each map stores property -> original value before AI touched it.
|
||||
// A `null` value means the property did not exist before AI added it.
|
||||
// `class` instead stores className -> whether AI added it,`true` must
|
||||
// be removed, `false` was removed by AI and must be added back.
|
||||
const aiElementModifications = {
|
||||
attr: new Map(),
|
||||
style: new Map(),
|
||||
class: new Map(),
|
||||
};
|
||||
|
||||
const handleRecord = (mutation, isAIChange) => {
|
||||
const attr = mutation.attributeName;
|
||||
|
||||
if (isAIChange) {
|
||||
if (attr === "style") {
|
||||
const oldStyles = parseStyleMap(mutation.oldValue);
|
||||
// Properties AI code added or changed.
|
||||
for (let i = 0; i < element.style.length; i++) {
|
||||
const prop = element.style[i];
|
||||
const oldEntry = oldStyles.get(prop);
|
||||
const newVal = element.style.getPropertyValue(prop);
|
||||
if (!oldEntry || oldEntry.value !== newVal) {
|
||||
// Only record the first pre-AI value.
|
||||
if (!aiElementModifications.style.has(prop)) {
|
||||
aiElementModifications.style.set(prop, oldEntry ?? null);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Properties AI code removed.
|
||||
for (const [prop, entry] of oldStyles) {
|
||||
if (
|
||||
!element.style.getPropertyValue(prop) &&
|
||||
!aiElementModifications.style.has(prop)
|
||||
) {
|
||||
aiElementModifications.style.set(prop, entry);
|
||||
}
|
||||
}
|
||||
} else if (attr === "class") {
|
||||
const oldClasses = parseClassSet(mutation.oldValue);
|
||||
for (const cls of element.classList) {
|
||||
if (!oldClasses.has(cls) && !aiElementModifications.class.has(cls)) {
|
||||
aiElementModifications.class.set(cls, true);
|
||||
}
|
||||
}
|
||||
for (const cls of oldClasses) {
|
||||
if (
|
||||
!element.classList.contains(cls) &&
|
||||
!aiElementModifications.class.has(cls)
|
||||
) {
|
||||
aiElementModifications.class.set(cls, false);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (!aiElementModifications.attr.has(attr)) {
|
||||
aiElementModifications.attr.set(attr, mutation.oldValue);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (attr === "style") {
|
||||
const oldStyles = parseStyleMap(mutation.oldValue);
|
||||
// Properties changed by non-AI code.
|
||||
for (let i = 0; i < element.style.length; i++) {
|
||||
const prop = element.style[i];
|
||||
const oldEntry = oldStyles.get(prop);
|
||||
if (!oldEntry || oldEntry.value !== element.style.getPropertyValue(prop)) {
|
||||
aiElementModifications.style.delete(prop);
|
||||
}
|
||||
}
|
||||
// Properties removed by non-AI code.
|
||||
for (const [prop] of oldStyles) {
|
||||
if (!element.style.getPropertyValue(prop)) {
|
||||
aiElementModifications.style.delete(prop);
|
||||
}
|
||||
}
|
||||
} else if (attr === "class") {
|
||||
const oldClasses = parseClassSet(mutation.oldValue);
|
||||
// Classes added by non-AI code.
|
||||
for (const cls of element.classList) {
|
||||
if (!oldClasses.has(cls)) {
|
||||
aiElementModifications.class.delete(cls);
|
||||
}
|
||||
}
|
||||
// Classes removed by non-AI code.
|
||||
for (const cls of oldClasses) {
|
||||
if (!element.classList.contains(cls)) {
|
||||
aiElementModifications.class.delete(cls);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
aiElementModifications.attr.delete(attr);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
trackedElementsMap.set(element, { aiElementModifications, handleRecord });
|
||||
getObserverEntry(this).observer.observe(element, {
|
||||
attributes: true,
|
||||
attributeOldValue: true,
|
||||
});
|
||||
},
|
||||
|
||||
restoreElement(targetEl) {
|
||||
const entry = trackedElementsMap.get(targetEl);
|
||||
if (entry) {
|
||||
const { aiElementModifications } = entry;
|
||||
// Untrack before reverting, so that the records the revert itself
|
||||
// produces are ignored.
|
||||
trackedElementsMap.delete(targetEl);
|
||||
if (!trackedElementsMap.size) {
|
||||
stopObserving(this);
|
||||
}
|
||||
|
||||
// Revert AI-overridden style properties.
|
||||
for (const [prop, original] of aiElementModifications.style) {
|
||||
if (original === null) {
|
||||
targetEl.style.removeProperty(prop);
|
||||
} else {
|
||||
targetEl.style.setProperty(prop, original.value, original.priority);
|
||||
}
|
||||
}
|
||||
|
||||
// Revert AI-overridden classes: drop the ones it added, restore the ones it removed.
|
||||
for (const [cls, wasAdded] of aiElementModifications.class) {
|
||||
targetEl.classList.toggle(cls, !wasAdded);
|
||||
}
|
||||
|
||||
// Revert AI-overridden attributes.
|
||||
for (const [attr, originalVal] of aiElementModifications.attr) {
|
||||
if (originalVal === null) {
|
||||
targetEl.removeAttribute(attr);
|
||||
} else {
|
||||
targetEl.setAttribute(attr, originalVal);
|
||||
}
|
||||
}
|
||||
}
|
||||
delete targetEl.dataset.aiTracked;
|
||||
},
|
||||
|
||||
registerCleanup(cleanupFn, scriptEl) {
|
||||
scriptCleanupMap.set(scriptEl, cleanupFn);
|
||||
},
|
||||
|
||||
disposeScript(scriptEl) {
|
||||
runScriptCleanup(scriptEl);
|
||||
const elements = scriptElementsMap.get(scriptEl);
|
||||
if (elements) {
|
||||
elements.forEach((el) => this.restoreElement(el));
|
||||
scriptElementsMap.delete(scriptEl);
|
||||
}
|
||||
},
|
||||
|
||||
disposeAll() {
|
||||
document.querySelectorAll("script[data-ai-script-id]").forEach(runScriptCleanup);
|
||||
for (const element of [...trackedElementsMap.keys()]) {
|
||||
this.restoreElement(element);
|
||||
}
|
||||
stopObserving(this);
|
||||
this.observerEntries.clear();
|
||||
scriptElementsMap.clear();
|
||||
},
|
||||
});
|
||||
13
ai_website/static/src/scss/element_selection.scss
Normal file
13
ai_website/static/src/scss/element_selection.scss
Normal file
@@ -0,0 +1,13 @@
|
||||
div[data-oe-local-overlay-id="ai-website-selection-overlay-container"] {
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
html.o-ai-website-picker-active * {
|
||||
cursor: pointer !important;
|
||||
}
|
||||
|
||||
.o-ai-website-picker-active {
|
||||
[data-oe-local-overlay-id="builder-overlay-container"] {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
53
ai_website/static/src/utils.js
Normal file
53
ai_website/static/src/utils.js
Normal file
@@ -0,0 +1,53 @@
|
||||
import { browser } from "@web/core/browser/browser";
|
||||
import { getData } from "@ai/utils/bus_data_getter";
|
||||
|
||||
export const AI_EDITABLE_ZONE_SELECTORS = {
|
||||
main: "div#wrap",
|
||||
footer: "footer#bottom > #footer",
|
||||
};
|
||||
|
||||
export const AI_WEBSITE_ELEMENT_SELECTION_COMMAND = "AI Website: Element Selection Command";
|
||||
export const AI_WEBSITE_ELEMENT_SELECTION_STATE = "AI Website: Element Selection State";
|
||||
export const AI_WEBSITE_TYPING_TIMEOUT = 180_000; // 3 minutes
|
||||
|
||||
const DATA_POLL_ATTEMPTS = 50;
|
||||
const DATA_POLL_INTERVAL = 200;
|
||||
|
||||
/**
|
||||
* While waiting for the builder to mount, we keep calling getData until we get a response or we
|
||||
* give up.
|
||||
*/
|
||||
export async function pollForData(dataSource) {
|
||||
for (let attempt = 0; attempt < DATA_POLL_ATTEMPTS; attempt++) {
|
||||
const data = await getData(dataSource);
|
||||
if (data) {
|
||||
return data;
|
||||
}
|
||||
await new Promise((resolve) => browser.setTimeout(resolve, DATA_POLL_INTERVAL));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function isEditorSidebarOpen(websiteService) {
|
||||
return websiteService.context.edition;
|
||||
}
|
||||
|
||||
/**
|
||||
* Currently, a page is editable by the website builder AI if it exists in the
|
||||
* website.page model. Which is not the case for controller-rendered pages like
|
||||
* /shop or /blog.
|
||||
*/
|
||||
export function isPageAiEditable(websiteService) {
|
||||
const model = websiteService.currentWebsite?.metadata?.mainObject?.model;
|
||||
return model === "website.page" || model === "product.template";
|
||||
}
|
||||
|
||||
export function isAiWebsiteBuilderChannel(channel) {
|
||||
return channel?.aiRootSession?.ai_composer_id?.interface_key === "website_builder_ai";
|
||||
}
|
||||
|
||||
export function getScriptTitle(scriptEl) {
|
||||
const humanReadableTitle = scriptEl.dataset.aiScriptId.split("--")[0];
|
||||
const title = humanReadableTitle.replaceAll("_", " ");
|
||||
return title[0].toUpperCase() + title.slice(1);
|
||||
}
|
||||
20
ai_website/static/src/xml/website_builder.xml
Normal file
20
ai_website/static/src/xml/website_builder.xml
Normal file
@@ -0,0 +1,20 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<templates xml:space="preserve">
|
||||
|
||||
<!-- Add AI button to the builder top actions bar -->
|
||||
<t t-name="website.WebsiteBuilder" t-inherit="website.WebsiteBuilder" t-inherit-mode="extension">
|
||||
<xpath expr="//t[@t-set-slot='extraActions']/div[hasclass('o-website-discard-save-buttons')]" position="before">
|
||||
<span t-if="!this.isTranslationMode" t-att-title="this.aiAssistantTooltip">
|
||||
<button
|
||||
t-on-click="this.onAiChatClick" type="button"
|
||||
class="o-hb-btn btn d-flex align-items-center justify-content-center"
|
||||
t-att-disabled="!this.isPageAiEditable || !this.websiteService.isDesigner"
|
||||
data-action="ai-chat"
|
||||
style="--btn-font-size: 14px; padding: 2px 6px;">
|
||||
<img src="/ai/static/description/icon.png" alt="AI" style="width: 20px; height: 20px; object-fit: contain;"/>
|
||||
</button>
|
||||
</span>
|
||||
</xpath>
|
||||
</t>
|
||||
|
||||
</templates>
|
||||
172
ai_website/static/tests/ai_scripts_manager.test.js
Normal file
172
ai_website/static/tests/ai_scripts_manager.test.js
Normal file
@@ -0,0 +1,172 @@
|
||||
import { click, describe, expect, test, microTick, queryFirst } from "@odoo/hoot";
|
||||
import { defineWebsiteModels } from "@website/../tests/builder/website_helpers";
|
||||
import { defineAIModels } from "@ai/../tests/ai_test_helpers";
|
||||
import { loadBundle } from "@web/core/assets";
|
||||
import { setupAiWebsiteBuilder } from "./ai_website_test_helpers";
|
||||
|
||||
defineAIModels();
|
||||
defineWebsiteModels({
|
||||
includeMailModels: false,
|
||||
});
|
||||
|
||||
async function setupScriptsManager(websiteContent) {
|
||||
await setupAiWebsiteBuilder(websiteContent, { openEditor: false });
|
||||
await loadBundle("website.website_builder_assets");
|
||||
const doc = queryFirst(":iframe");
|
||||
const manager = doc.defaultView.__aiScriptsManager__.manager;
|
||||
return {
|
||||
doc,
|
||||
manager,
|
||||
addScript(scriptId) {
|
||||
const scriptEl = doc.createElement("script");
|
||||
scriptEl.dataset.aiScriptId = scriptId;
|
||||
doc.querySelector("#wrap").appendChild(scriptEl);
|
||||
return scriptEl;
|
||||
},
|
||||
aiRun(fn) {
|
||||
manager.protectMutations(fn)();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("AI scripts manager", () => {
|
||||
// TODO SERU: find a way to make this work functionally.
|
||||
test.todo("stopping one of two scripts should keep the other script's changes", async () => {
|
||||
const { manager, addScript, aiRun } = await setupScriptsManager(
|
||||
`<section><div class="target" style="color: blue;">content</div></section>`
|
||||
);
|
||||
const target = queryFirst(":iframe .target");
|
||||
const scriptA = addScript("script_a");
|
||||
const scriptB = addScript("script_b");
|
||||
|
||||
aiRun(() => {
|
||||
manager.trackElement(target, scriptA);
|
||||
target.style.color = "red";
|
||||
});
|
||||
aiRun(() => {
|
||||
manager.trackElement(target, scriptB);
|
||||
target.classList.add("from-b");
|
||||
});
|
||||
|
||||
manager.disposeScript(scriptB);
|
||||
expect(target).not.toHaveClass("from-b");
|
||||
expect(target.style.color).toBe("red");
|
||||
});
|
||||
|
||||
test("stopping a script should leave the element usable by the script still running", async () => {
|
||||
const { manager, addScript, aiRun } = await setupScriptsManager(
|
||||
`<section><div class="target" style="color: blue;">content</div></section>`
|
||||
);
|
||||
const target = queryFirst(":iframe .target");
|
||||
const original = target.outerHTML;
|
||||
const scriptA = addScript("script_a");
|
||||
const scriptB = addScript("script_b");
|
||||
|
||||
aiRun(() => {
|
||||
manager.trackElement(target, scriptA);
|
||||
target.style.color = "red";
|
||||
});
|
||||
aiRun(() => {
|
||||
manager.trackElement(target, scriptB);
|
||||
target.classList.add("from-b");
|
||||
});
|
||||
|
||||
manager.disposeScript(scriptA);
|
||||
expect(target.outerHTML).toBe(original);
|
||||
|
||||
aiRun(() => {
|
||||
manager.trackElement(target, scriptB);
|
||||
target.style.opacity = "0.5";
|
||||
});
|
||||
expect(target.outerHTML).not.toBe(original);
|
||||
manager.disposeScript(scriptB);
|
||||
expect(target.outerHTML).toBe(original);
|
||||
});
|
||||
|
||||
test("a user edit on an AI-owned property should save this change", async () => {
|
||||
const { manager, addScript, aiRun } = await setupScriptsManager(
|
||||
`<section><div class="target" style="color: blue;">content</div></section>`
|
||||
);
|
||||
const target = queryFirst(":iframe .target");
|
||||
const scriptEl = addScript("script_a");
|
||||
|
||||
aiRun(() => {
|
||||
manager.trackElement(target, scriptEl);
|
||||
target.style.color = "red";
|
||||
});
|
||||
await microTick();
|
||||
|
||||
// The user overrides the property the AI made.
|
||||
target.style.color = "green";
|
||||
await microTick();
|
||||
|
||||
// The script then writes it again: the value to restore is now the
|
||||
// user's one, not the original one.
|
||||
aiRun(() => {
|
||||
target.style.color = "purple";
|
||||
});
|
||||
await microTick();
|
||||
|
||||
manager.disposeScript(scriptEl);
|
||||
expect(target.style.color).toBe("green");
|
||||
});
|
||||
|
||||
test("disposeAll should leave the page clean and trackable again", async () => {
|
||||
const { manager, addScript, aiRun } = await setupScriptsManager(
|
||||
`<section><div class="target" style="color: blue;">content</div></section>`
|
||||
);
|
||||
const target = queryFirst(":iframe .target");
|
||||
const original = target.outerHTML;
|
||||
const scriptA = addScript("script_a");
|
||||
|
||||
aiRun(() => {
|
||||
manager.trackElement(target, scriptA);
|
||||
target.style.color = "red";
|
||||
});
|
||||
|
||||
manager.disposeAll();
|
||||
expect(target.outerHTML).toBe(original);
|
||||
expect(":iframe [data-ai-tracked]").toHaveCount(0);
|
||||
|
||||
// The scripts are restarted (e.g. when leaving the editor): tracking
|
||||
// must work again on the same element.
|
||||
const scriptB = addScript("script_b");
|
||||
aiRun(() => {
|
||||
manager.trackElement(target, scriptB);
|
||||
target.style.color = "green";
|
||||
});
|
||||
manager.disposeScript(scriptB);
|
||||
expect(target.outerHTML).toBe(original);
|
||||
});
|
||||
|
||||
test("should correctly handle ai and non-ai mutations done together", async () => {
|
||||
const { manager, addScript } = await setupScriptsManager(
|
||||
`<section><button class="target" style="color: blue; font-size: 10px;">Click</button></section>`
|
||||
);
|
||||
const target = queryFirst(":iframe .target");
|
||||
const scriptEl = addScript("script_a");
|
||||
|
||||
// Both listeners answer the same click, but the AI's one should be
|
||||
// revertable.
|
||||
target.addEventListener(
|
||||
"click",
|
||||
manager.protectMutations(() => {
|
||||
manager.trackElement(target, scriptEl);
|
||||
target.style.color = "red";
|
||||
})
|
||||
);
|
||||
target.addEventListener("click", () => {
|
||||
target.style.fontSize = "20px";
|
||||
});
|
||||
|
||||
await click(target);
|
||||
await microTick();
|
||||
expect(target.style.color).toBe("red");
|
||||
expect(target.style.fontSize).toBe("20px");
|
||||
|
||||
// Should revert ai script's changes, while keeping the normal ones.
|
||||
manager.disposeScript(scriptEl);
|
||||
expect(target.style.color).toBe("blue");
|
||||
expect(target.style.fontSize).toBe("20px");
|
||||
});
|
||||
});
|
||||
1321
ai_website/static/tests/ai_website_builder.test.js
Normal file
1321
ai_website/static/tests/ai_website_builder.test.js
Normal file
File diff suppressed because it is too large
Load Diff
15
ai_website/static/tests/ai_website_test_helpers.js
Normal file
15
ai_website/static/tests/ai_website_test_helpers.js
Normal file
@@ -0,0 +1,15 @@
|
||||
import { queryOne } from "@odoo/hoot-dom";
|
||||
import { loadBundle } from "@web/core/assets";
|
||||
import { setupWebsiteBuilder } from "@website/../tests/builder/website_helpers";
|
||||
|
||||
export async function setupAiWebsiteBuilder(websiteContent, options = {}) {
|
||||
const { openEditor = true, ...rest } = options;
|
||||
const result = await setupWebsiteBuilder(websiteContent, { ...rest, openEditor: false });
|
||||
const targetDoc = queryOne(":iframe");
|
||||
await loadBundle("ai_website.ai_assets", { targetDoc });
|
||||
await loadBundle("ai_website.ai_editor_assets", { targetDoc });
|
||||
if (openEditor) {
|
||||
await result.openBuilderSidebar();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
49
ai_website/static/tests/image_snippet.test.js
Normal file
49
ai_website/static/tests/image_snippet.test.js
Normal file
@@ -0,0 +1,49 @@
|
||||
import { expect, test } from "@odoo/hoot";
|
||||
import { animationFrame, click, waitFor } from "@odoo/hoot-dom";
|
||||
import { registry } from "@web/core/registry";
|
||||
import { contains, patchWithCleanup } from "@web/../tests/web_test_helpers";
|
||||
import { getDragHelper, waitForEndOfOperation } from "@html_builder/../tests/helpers";
|
||||
import {
|
||||
defineWebsiteModels,
|
||||
setupWebsiteBuilder,
|
||||
} from "@website/../tests/builder/website_helpers";
|
||||
|
||||
defineWebsiteModels();
|
||||
|
||||
test("dropping image snippet and clicking AI button keeps placeholder", async () => {
|
||||
// Mock aiChatLauncher service to avoid RPCs and complex setup
|
||||
const aiChatLauncher = registry.category("services").get("aiChatLauncher");
|
||||
patchWithCleanup(aiChatLauncher, {
|
||||
start() {
|
||||
return {
|
||||
launchAIChat: async () => ({ id: "test_thread", channel: {} }),
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
// The text is added to introduce a drop zone for snippets.
|
||||
await setupWebsiteBuilder(`<div><p>Text</p></div>`);
|
||||
|
||||
// Drag the snippet from the sidebar to the content
|
||||
const { moveTo, drop } = await contains(
|
||||
".o-website-builder_sidebar [name='Image'] .o_snippet_thumbnail"
|
||||
).drag();
|
||||
await moveTo(":iframe .oe_drop_zone");
|
||||
await drop(getDragHelper());
|
||||
|
||||
// Verify media dialog opens
|
||||
await animationFrame();
|
||||
await waitFor(".o_select_media_dialog");
|
||||
expect(".o_select_media_dialog").toHaveCount(1);
|
||||
|
||||
// Click the AI button
|
||||
await click("button[title='Generate Image with AI']");
|
||||
await animationFrame();
|
||||
|
||||
// Verify media dialog is closed
|
||||
expect(".o_select_media_dialog").toHaveCount(0);
|
||||
|
||||
// Verify snippet is dropped (not discarded)
|
||||
await waitForEndOfOperation();
|
||||
expect("[data-snippet='s_image']").toHaveCount(1);
|
||||
});
|
||||
@@ -0,0 +1,3 @@
|
||||
import { registerRoute } from "@mail/../tests/mock_server/mail_mock_server";
|
||||
|
||||
registerRoute("/ai_website/ready_scraper_results", () => []);
|
||||
@@ -0,0 +1,112 @@
|
||||
/** @odoo-module **/
|
||||
import { registerWebsitePreviewTour, clickOnSave } from "@website/js/tours/tour_utils";
|
||||
import { deliverAIResults, setupAIResults } from "@ai/../tests/tours/ai_tour_helpers";
|
||||
|
||||
registerWebsitePreviewTour(
|
||||
"replace_website_image_with_ai_tour",
|
||||
{
|
||||
edition: true,
|
||||
},
|
||||
() => [
|
||||
{
|
||||
content:
|
||||
"Double-click the image on the website to open the Media Dialog to replace the image",
|
||||
trigger: ":iframe #test_image",
|
||||
run: "dblclick",
|
||||
},
|
||||
{
|
||||
content: "Wait for Media Dialog to open and click on the AI button",
|
||||
trigger: ".o_select_media_dialog button[title='Generate Image with AI']",
|
||||
run: "click",
|
||||
},
|
||||
setupAIResults(),
|
||||
{
|
||||
content:
|
||||
"Click on the prompt button 'Help me generate an image' in the AI chat channel",
|
||||
trigger: ".ai-chat-prompt-button:contains('Help me generate an image')",
|
||||
run: "click",
|
||||
},
|
||||
{
|
||||
content: "Verify the message 'Help me generate an image' is posted in the chat channel",
|
||||
trigger: ".o-mail-Message:contains('Help me generate an image')",
|
||||
},
|
||||
deliverAIResults(),
|
||||
{
|
||||
content: "Click on the 'Use This' button",
|
||||
trigger: "button[name='media_dialog_use_this']:not(:visible)",
|
||||
run: "click",
|
||||
},
|
||||
{
|
||||
content: "Verify the image on the website is replaced by the first AI generated image",
|
||||
trigger: ":iframe img[data-original-src*='AI%20Generated%201']",
|
||||
},
|
||||
{
|
||||
content: "Hover over the first AI generated image again",
|
||||
trigger: ".o-mail-Message:contains('AI Generated 1') .o-mail-AttachmentList img",
|
||||
run: "hover",
|
||||
},
|
||||
{
|
||||
content: "Verify that 'Try again' button is visible and click on it",
|
||||
trigger: "button[name='regenerate_image']:visible",
|
||||
run: "click",
|
||||
},
|
||||
deliverAIResults(),
|
||||
{
|
||||
content: "Click the 'Use This' button for the second AI generated image",
|
||||
trigger:
|
||||
".o-mail-Message:contains('AI Generated 2') button[name='media_dialog_use_this']:not(:visible)",
|
||||
run: "click",
|
||||
},
|
||||
{
|
||||
content: "Verify the image on the website is replaced by the second AI generated image",
|
||||
trigger: ":iframe img[data-original-src*='AI%20Generated%202']",
|
||||
},
|
||||
{
|
||||
content: "Focus the image",
|
||||
trigger: ":iframe img[data-original-src*='AI%20Generated%202']",
|
||||
run: "click",
|
||||
},
|
||||
{
|
||||
content: "First Undo (Ctrl + z)",
|
||||
trigger: "body",
|
||||
run: "press ctrl+z",
|
||||
},
|
||||
{
|
||||
content: "Verify that the image on the website is the first AI generated image",
|
||||
trigger: ":iframe img[data-original-src*='AI%20Generated%201']",
|
||||
},
|
||||
{
|
||||
content: "Second Undo (Ctrl + z)",
|
||||
trigger: "body",
|
||||
run: "press ctrl+z",
|
||||
},
|
||||
{
|
||||
content: "Verify the image on the website is the initial image",
|
||||
trigger: ":iframe #test_image",
|
||||
},
|
||||
{
|
||||
content: "First Redo (Ctrl + y)",
|
||||
trigger: "body",
|
||||
run: "press ctrl+y",
|
||||
},
|
||||
{
|
||||
content: "Verify the image on the website is the first AI generated image",
|
||||
trigger: ":iframe img[data-original-src*='AI%20Generated%201']",
|
||||
},
|
||||
{
|
||||
content: "Second Redo (Ctrl + y)",
|
||||
trigger: "body",
|
||||
run: "press ctrl+y",
|
||||
},
|
||||
{
|
||||
content: "Verify the image on the website is the second AI generated image",
|
||||
trigger: ":iframe img[data-original-src*='AI%20Generated%202']",
|
||||
},
|
||||
...clickOnSave(),
|
||||
{
|
||||
content:
|
||||
"Verify the final image on the website after save is the second AI generated image",
|
||||
trigger: ":iframe img[data-original-src*='AI%20Generated%202']",
|
||||
},
|
||||
],
|
||||
);
|
||||
Reference in New Issue
Block a user