初始提交
This commit is contained in:
@@ -0,0 +1,48 @@
|
||||
import {
|
||||
getEditableDescendants,
|
||||
useEditableDescendants,
|
||||
} from "@html_editor/others/embedded_component_utils";
|
||||
import { Component, onMounted, onWillStart, proxy } from "@odoo/owl";
|
||||
import { isMobileOS } from "@web/core/browser/feature_detection";
|
||||
import { Dropdown } from "@web/core/dropdown/dropdown";
|
||||
import { DropdownItem } from "@web/core/dropdown/dropdown_item";
|
||||
|
||||
export class ReadonlyVoiceTranscription extends Component {
|
||||
static template = "ai.ReadonlyVoiceTranscription";
|
||||
static components = { Dropdown, DropdownItem };
|
||||
|
||||
setup() {
|
||||
const { descendants, refs } = useEditableDescendants();
|
||||
this.descendants = descendants;
|
||||
this.descendantRefs = refs;
|
||||
this.isMobileOS = isMobileOS();
|
||||
this.supportedLanguages = [];
|
||||
this.state = proxy({
|
||||
currentTab: "notes",
|
||||
isOpened: true,
|
||||
hasSummary: this.descendants.summaryContent.textContent.trim() !== "",
|
||||
});
|
||||
|
||||
onWillStart(() => {
|
||||
if (this.state.hasSummary) {
|
||||
this.state.currentTab = "summary";
|
||||
}
|
||||
});
|
||||
|
||||
onMounted(() => {
|
||||
this.state.firstRecordingDate =
|
||||
this.descendants.transcriptContent.querySelector("b")?.innerText;
|
||||
});
|
||||
}
|
||||
|
||||
setCurrentTab(tabName) {
|
||||
this.state["currentTab"] = tabName;
|
||||
}
|
||||
}
|
||||
|
||||
export const aiReadonlyVoiceTranscriptionEmbeddedComponent = {
|
||||
name: "voice-transcription",
|
||||
Component: ReadonlyVoiceTranscription,
|
||||
getEditableDescendants,
|
||||
getProps: (host) => ({ host }),
|
||||
};
|
||||
@@ -0,0 +1,80 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<templates id="template" xml:space="preserve">
|
||||
<t t-name="ai.ReadonlyVoiceTranscription">
|
||||
<details class="transcript-block border mb-2" t-att-open="this.state.isOpened">
|
||||
<summary class="d-flex bg-100 px-2 py-1 fw-bold gap-2 flex-sm-row flex-column align-items-sm-center flex-wrap" t-on-click="() => this.state.isOpened = !this.state.isOpened" t-att-class="{'py-2': !this.state.isOpened}">
|
||||
<t t-if="this.state.isOpened">
|
||||
<t t-if="!this.isMobileOS">
|
||||
<div class="d-flex align-items-center">
|
||||
<i class="oi flex-0 me-2" data-icon="arrow_drop_down" />
|
||||
<ul class="nav gap-1" role="tablist">
|
||||
<li t-if="this.state.hasSummary || this.state.status === 'summarizing'">
|
||||
<button
|
||||
class="btn flex-grow-1 flex-sm-grow-0 w-100 w-sm-auto"
|
||||
t-att-class="{'btn-secondary active': this.state.currentTab === 'summary'}"
|
||||
t-on-click.stop="() => this.setCurrentTab('summary')">
|
||||
<img src="/ai/static/description/icon.png" class="ai-icon-sm me-1 w-1"/>
|
||||
Summary
|
||||
</button>
|
||||
</li>
|
||||
<li>
|
||||
<button class="btn flex-sm-grow-0 w-100 w-sm-auto"
|
||||
t-att-class="{'btn-secondary active': this.state.currentTab === 'notes'}"
|
||||
t-on-click.stop="() => this.setCurrentTab('notes')">
|
||||
<i class="oi me-1" data-icon="menu"/>
|
||||
Notes
|
||||
</button>
|
||||
</li>
|
||||
<li>
|
||||
<button
|
||||
class="btn flex-sm-grow-0 w-100 w-sm-auto"
|
||||
t-att-class="{'btn-secondary active': this.state.currentTab === 'transcript'}"
|
||||
t-on-click.stop="() => this.setCurrentTab('transcript')"
|
||||
>
|
||||
<i class="oi me-1" data-icon="mic"/>
|
||||
Transcript
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</t>
|
||||
<t t-else="">
|
||||
<Dropdown>
|
||||
<button class="btn btn-secondary o-dropdown-caret px-2 px-sm-3">
|
||||
<t t-if="this.state.currentTab === 'summary'">
|
||||
<img src="/ai/static/description/icon.png" class="ai-icon-sm me-1"/> Summary
|
||||
</t>
|
||||
<t t-elif="this.state.currentTab === 'notes'">
|
||||
<i class="oi me-1" data-icon="menu"/>Notes
|
||||
</t>
|
||||
<t t-else="">
|
||||
<i class="oi me-1" data-icon="mic"/>Transcript
|
||||
</t>
|
||||
</button>
|
||||
<t t-set-slot="content">
|
||||
<DropdownItem class="`btn btn-link ${this.state.currentTab === 'summary' ? 'active' : ''}`" onSelected="(ev) => this.setCurrentTab('summary')">
|
||||
<img src="/ai/static/description/icon.png" class="ai-icon-sm me-1"/>Summary
|
||||
</DropdownItem>
|
||||
<DropdownItem class="`btn btn-link ${this.state.currentTab === 'notes' ? 'active' : ''}`" onSelected="(ev) => this.setCurrentTab('notes')">
|
||||
<i class="oi me-1" data-icon="menu"/>Notes
|
||||
</DropdownItem>
|
||||
<DropdownItem class="`btn btn-link ${this.state.currentTab === 'transcript' ? 'active' : ''}`" onSelected="(ev) => this.setCurrentTab('transcript')">
|
||||
<i class="oi me-1" data-icon="mic"/>Transcript
|
||||
</DropdownItem>
|
||||
</t>
|
||||
</Dropdown>
|
||||
</t>
|
||||
</t>
|
||||
<t t-else="">
|
||||
<div class="d-flex align-items-center">
|
||||
<i class="oi flex-0 me-1" data-icon="arrow_right"/>
|
||||
Voice Recording <span t-out="this.state.firstRecordingDate" class="ms-2 fw-normal text-muted"/>
|
||||
</div>
|
||||
</t>
|
||||
</summary>
|
||||
<div id="summary-content" class="detail-content overflow-auto" t-att-class="{'d-none': this.state.currentTab !== 'summary'}" t-ref="this.descendantRefs.summaryContent"/>
|
||||
<div id="notes-content" class="detail-content overflow-auto" t-att-class="{'d-none': this.state.currentTab !== 'notes'}" t-ref="this.descendantRefs.notesContent"/>
|
||||
<div id="transcript-content" class="detail-content overflow-auto" t-att-class="{'d-none': this.state.currentTab !== 'transcript'}" t-ref="this.descendantRefs.transcriptContent"/>
|
||||
</details>
|
||||
</t>
|
||||
</templates>
|
||||
@@ -0,0 +1,357 @@
|
||||
import {
|
||||
getEditableDescendants,
|
||||
useEditableDescendants,
|
||||
} from "@html_editor/others/embedded_component_utils";
|
||||
import { browser } from "@web/core/browser/browser";
|
||||
import { rpc, RPCError } from "@web/core/network/rpc";
|
||||
import {
|
||||
Component,
|
||||
markup,
|
||||
onMounted,
|
||||
onWillDestroy,
|
||||
onWillStart,
|
||||
onWillUnmount,
|
||||
proxy,
|
||||
t, useListener,
|
||||
useProps,
|
||||
} from "@odoo/owl";
|
||||
import { user } from "@web/core/user";
|
||||
import { useBus, useService } from "@web/core/utils/hooks";
|
||||
import { _t } from "@web/core/l10n/translation";
|
||||
import { AudioVisualizer } from "@ai/components/audio_visualizer/audio_visualizer";
|
||||
import { Dropdown } from "@web/core/dropdown/dropdown";
|
||||
import { DropdownItem } from "@web/core/dropdown/dropdown_item";
|
||||
import AudioProcessor, { ProcessorState } from "@ai/core/audio/audio_processor";
|
||||
import RealtimeClient from "@ai/core/realtime_client";
|
||||
import { AITranscriptionEvent, transcriptionBus } from "@ai/core/transcription_bus";
|
||||
|
||||
export class VoiceTranscription extends Component {
|
||||
static components = { AudioVisualizer, Dropdown, DropdownItem };
|
||||
static template = "ai.VoiceTranscription";
|
||||
|
||||
props = useProps({
|
||||
onTranscriptionStarted: t.function(),
|
||||
onTranscriptionUpdated: t.function(),
|
||||
onSummaryUpdated: t.function(),
|
||||
});
|
||||
|
||||
setup() {
|
||||
super.setup();
|
||||
const { descendants, refs } = useEditableDescendants();
|
||||
this.descendants = descendants;
|
||||
this.descendantRefs = refs;
|
||||
this.actionService = useService("action");
|
||||
this.notificationService = useService("notification");
|
||||
this.ui = useService("ui");
|
||||
this.orm = useService("orm");
|
||||
this.mailStore = useService("mail.store");
|
||||
|
||||
this.shouldCommit = false;
|
||||
this.supportedLanguages = [];
|
||||
|
||||
this.iapTransactionToken = null;
|
||||
this.usage = {};
|
||||
|
||||
const currentLanguage = user.lang.replace("-", "_");
|
||||
const hasSummary = this.descendants.summaryContent.textContent.trim() !== "";
|
||||
this.state = proxy({
|
||||
frequencies: new Uint8Array(),
|
||||
currentTab: "notes",
|
||||
currentLanguage: {
|
||||
code: currentLanguage,
|
||||
shortCode: currentLanguage.split("_")[0],
|
||||
},
|
||||
hasSummary,
|
||||
isOpened: true,
|
||||
isRecording: false,
|
||||
status: "idle",
|
||||
});
|
||||
|
||||
this.summaryObserver = new MutationObserver((mutationList) => {
|
||||
for (const mutation of mutationList) {
|
||||
if (mutation.type === "childList" || mutation.type === "characterData") {
|
||||
this.state.hasSummary =
|
||||
this.descendants.summaryContent.textContent.trim() !== "";
|
||||
}
|
||||
}
|
||||
});
|
||||
this.summaryObserver.observe(this.descendants.summaryContent, {
|
||||
childList: true,
|
||||
characterData: true,
|
||||
});
|
||||
|
||||
this.realtimeClient = RealtimeClient.getInstance();
|
||||
|
||||
// To take care of the case where the user closes the tab while the transcription is active
|
||||
useListener(browser, "pagehide", () => this.resetIAPTracking());
|
||||
|
||||
// Subscribe to event for the RealtimeClient
|
||||
useBus(transcriptionBus, AITranscriptionEvent.REALTIME_CLIENT_MESSAGE, (event) => {
|
||||
if (this.state.status !== "recording") {
|
||||
return;
|
||||
}
|
||||
const data = event.detail;
|
||||
if (data.type === "conversation.item.input_audio_transcription.completed") {
|
||||
this.usage["input_tokens"]["text"] += data.usage.input_token_details?.text_tokens || 0;
|
||||
this.usage["input_tokens"]["audio"] += data.usage.input_token_details?.audio_tokens || 0;
|
||||
this.usage["output_tokens"] += data.usage.output_tokens || 0;
|
||||
this.usage["duration_seconds"] += data.usage.duration || 0;
|
||||
|
||||
this.props.onTranscriptionUpdated(
|
||||
"delta",
|
||||
this.descendants.transcriptContent,
|
||||
data.transcript
|
||||
);
|
||||
if (this.shouldCommit) {
|
||||
this.props.onTranscriptionUpdated(
|
||||
"completed",
|
||||
this.descendants.transcriptContent
|
||||
);
|
||||
this.shouldCommit = false;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
this.audioProcessor = AudioProcessor.getInstance();
|
||||
|
||||
// Subscribe events for the AudioProcessor
|
||||
useBus(transcriptionBus, AITranscriptionEvent.AUDIO_PROCESSOR_DATA, (event) =>
|
||||
this.realtimeClient.send(event.detail)
|
||||
);
|
||||
useBus(
|
||||
transcriptionBus,
|
||||
AITranscriptionEvent.AUDIO_PROCESSOR_FREQUENCY,
|
||||
(event) => (this.state.frequencies = event.detail)
|
||||
);
|
||||
useBus(transcriptionBus, AITranscriptionEvent.AUDIO_PROCESSOR_STATE, (event) => {
|
||||
if (this.state.status !== "recording") {
|
||||
return;
|
||||
}
|
||||
switch (event.detail) {
|
||||
case "recording":
|
||||
this.props.onTranscriptionUpdated(
|
||||
"listening",
|
||||
this.descendants.transcriptContent,
|
||||
_t("AI is listening...")
|
||||
);
|
||||
break;
|
||||
case "stopped":
|
||||
this.shouldCommit = true;
|
||||
break;
|
||||
}
|
||||
});
|
||||
|
||||
onWillStart(async () => {
|
||||
const languages = await this.orm.call("res.lang", "get_installed", []);
|
||||
this.supportedLanguages = languages.map(([code]) => ({
|
||||
shortCode: code.split("_")[0],
|
||||
code,
|
||||
}));
|
||||
|
||||
if (this.audioProcessor.state !== ProcessorState.IDLE) {
|
||||
this.state.status = "recording";
|
||||
}
|
||||
|
||||
this.transcriptionComposer = await this.orm.call(
|
||||
"ai.composer",
|
||||
"retrieve_transcription_composer",
|
||||
[],
|
||||
{
|
||||
record_model: this.env.model?.config.resModel,
|
||||
}
|
||||
);
|
||||
|
||||
if (this.state.hasSummary) {
|
||||
this.state.currentTab = "summary";
|
||||
}
|
||||
});
|
||||
|
||||
onMounted(() => {
|
||||
this.state.firstRecordingDate =
|
||||
this.descendants.transcriptContent.querySelector("b")?.innerText;
|
||||
});
|
||||
|
||||
onWillUnmount(() => {
|
||||
this.resetIAPTracking();
|
||||
});
|
||||
|
||||
onWillDestroy(() => {
|
||||
this.summaryObserver.disconnect();
|
||||
});
|
||||
}
|
||||
|
||||
async resetIAPTracking() {
|
||||
if (this.iapTransactionToken !== null) {
|
||||
try {
|
||||
await rpc("/ai/transcription/report_realtime_session_usage", {
|
||||
"iap_transaction_token": this.iapTransactionToken,
|
||||
"usage": this.usage,
|
||||
});
|
||||
} catch (e) {
|
||||
console.error("Failed to report usage to IAP", e);
|
||||
}
|
||||
}
|
||||
this.iapTransactionToken = null;
|
||||
this.usage = {
|
||||
"input_tokens": {
|
||||
"text": 0,
|
||||
"audio": 0,
|
||||
},
|
||||
"output_tokens": 0,
|
||||
"duration_seconds": 0,
|
||||
};
|
||||
}
|
||||
|
||||
setCurrentTab(tabName) {
|
||||
this.state["currentTab"] = tabName;
|
||||
}
|
||||
|
||||
async toggleRecording() {
|
||||
this.state.isRecording = !this.state.isRecording;
|
||||
if (this.state.status === "idle") {
|
||||
const transcriptPrompt = this.descendants.notesContent;
|
||||
try {
|
||||
this.state.status = "waiting";
|
||||
const response = await rpc("/ai/transcription/session", {
|
||||
language: this.state.currentLanguage.shortCode,
|
||||
prompt: transcriptPrompt?.innerText.trim(),
|
||||
});
|
||||
if (response["status"] === "success") {
|
||||
const sessionToken = response["session_token"];
|
||||
await this.resetIAPTracking();
|
||||
this.iapTransactionToken = response["iap_transaction_token"];
|
||||
this.realtimeClient.connect(sessionToken);
|
||||
this.state.status = "recording";
|
||||
this.props.onTranscriptionStarted(
|
||||
this.descendants.transcriptContent,
|
||||
this.state.currentLanguage.code.replace("_", "-")
|
||||
);
|
||||
await this.audioProcessor.start();
|
||||
this.setCurrentTab("transcript");
|
||||
}
|
||||
else if (response["status"] === "insufficient_credit") {
|
||||
// The notification is already handled by call_odoo_ai
|
||||
this.state.status = "idle";
|
||||
this.state.isRecording = false;
|
||||
}
|
||||
} catch (error) {
|
||||
this.state.status = "idle";
|
||||
this.state.isRecording = false;
|
||||
if (error instanceof DOMException && error.name === "NotAllowedError") {
|
||||
this.notificationService.add(
|
||||
_t(
|
||||
"You must allow the access to your microphone to start the recording. Try refreshing the page and start again."
|
||||
),
|
||||
{
|
||||
title: _t("Access error"),
|
||||
type: "danger",
|
||||
}
|
||||
);
|
||||
} else if (
|
||||
error instanceof RPCError &&
|
||||
error.data.name === "odoo.exceptions.UserError"
|
||||
) {
|
||||
this.notificationService.add(error.data.message, {
|
||||
type: "danger",
|
||||
});
|
||||
} else {
|
||||
this.notificationService.add(_t("Unable to start the recording."), {
|
||||
title: _t("An error occurred"),
|
||||
type: "danger",
|
||||
});
|
||||
}
|
||||
}
|
||||
} else if (this.state.status === "recording") {
|
||||
await this.resetIAPTracking();
|
||||
this.audioProcessor.stop();
|
||||
this.realtimeClient.disconnect();
|
||||
this.props.onTranscriptionUpdated("stopped", this.descendants.transcriptContent);
|
||||
this.updateSummary();
|
||||
}
|
||||
}
|
||||
|
||||
async updateSummary(promptButton = null) {
|
||||
this.state.status = "summarizing";
|
||||
const summary = await this.getSummary(promptButton);
|
||||
if (summary) {
|
||||
this.props.onSummaryUpdated(this.descendants.summaryContent, summary);
|
||||
this.setCurrentTab("summary");
|
||||
}
|
||||
this.state.status = "idle";
|
||||
}
|
||||
|
||||
async getSummary(promptButton = null) {
|
||||
const textToSummarize = this.getTranscriptContent();
|
||||
if (!this.transcriptionComposer || textToSummarize?.trim() === "") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const message = await rpc("/ai/transcription/summary", {
|
||||
composer_id: this.transcriptionComposer.id,
|
||||
summarization_instructions: `You MUST provide the summary in the following language: ${this.state.currentLanguage.code}`,
|
||||
text_to_summarize: textToSummarize,
|
||||
ai_prompt_button_context: {
|
||||
ai_prompt_button_ref: promptButton?.id,
|
||||
rendering_record_id: this.env.model?.config.resId,
|
||||
},
|
||||
});
|
||||
return markup(message);
|
||||
}
|
||||
|
||||
getTranscriptContent() {
|
||||
const transcriptElements =
|
||||
this.descendants.transcriptContent.querySelectorAll("blockquote");
|
||||
const transcript = [];
|
||||
transcriptElements.forEach((element) => {
|
||||
const innerText = element.innerText.trim();
|
||||
if (innerText !== "") {
|
||||
transcript.push(innerText);
|
||||
}
|
||||
});
|
||||
return transcript.join("\n");
|
||||
}
|
||||
|
||||
async openComposer() {
|
||||
const model = this.env.model;
|
||||
await model?.root.save();
|
||||
this.actionService.doAction(
|
||||
{
|
||||
type: "ir.actions.act_window",
|
||||
name: _t("Share transcript summary"),
|
||||
view_mode: "form",
|
||||
res_model: "mail.compose.message",
|
||||
views: [[false, "form"]],
|
||||
target: "new",
|
||||
view_id: false,
|
||||
context: {
|
||||
default_model: model?.config.resModel,
|
||||
default_res_ids: [model?.config.resId],
|
||||
default_subject: _t("Share transcript summary"),
|
||||
default_body: this.descendants.summaryContent.innerHTML,
|
||||
is_full_composer: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
onClose: async () => {
|
||||
const thread = this.mailStore["mail.thread"].get({
|
||||
model: model?.config.resModel,
|
||||
id: model?.config.resId,
|
||||
});
|
||||
await thread?.fetchNewMessages();
|
||||
},
|
||||
}
|
||||
);
|
||||
}
|
||||
get sortedPromptButtons() {
|
||||
return (this.transcriptionComposer.available_prompt_ids || []).sort(
|
||||
(a, b) => a.sequence - b.sequence
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export const aiVoiceTranscriptionEmbeddedComponent = {
|
||||
name: "voice-transcription",
|
||||
Component: VoiceTranscription,
|
||||
getEditableDescendants: getEditableDescendants,
|
||||
getProps: (host) => ({ host }),
|
||||
};
|
||||
@@ -0,0 +1,68 @@
|
||||
.ai-icon-sm {
|
||||
width: 1rem;
|
||||
}
|
||||
|
||||
[data-embedded="voice-transcription"] {
|
||||
$rounding: 4px;
|
||||
|
||||
blockquote {
|
||||
font-style: normal;
|
||||
border-width: 2px;
|
||||
padding-left: 0.5rem;
|
||||
}
|
||||
|
||||
blockquote::after {
|
||||
padding-left: 0.5rem;
|
||||
}
|
||||
|
||||
.transcript-block {
|
||||
padding: 0.5em 0.5em 0;
|
||||
border-radius: $rounding;
|
||||
}
|
||||
|
||||
.transcript-block>summary {
|
||||
margin: -0.5em -0.5em 0;
|
||||
border-radius: $rounding;
|
||||
|
||||
&::marker {
|
||||
content: "a";
|
||||
}
|
||||
}
|
||||
|
||||
.transcript-block[open] {
|
||||
padding: 0.5em;
|
||||
}
|
||||
|
||||
.transcript-block .detail-content {
|
||||
max-height: 500px;
|
||||
}
|
||||
|
||||
.transcript-block[open]>summary {
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
margin-bottom: 0.8em;
|
||||
border-radius: $rounding $rounding 0 0;
|
||||
}
|
||||
|
||||
.o-ai-summary-processing * {
|
||||
color: #6c757d;
|
||||
}
|
||||
|
||||
.o-ai-transcription-listening {
|
||||
color: #6c757d;
|
||||
animation: fade-in-out 2s infinite;
|
||||
}
|
||||
|
||||
@keyframes fade-in-out {
|
||||
0% {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
50% {
|
||||
opacity: 0.4;
|
||||
}
|
||||
|
||||
100% {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<templates id="template" xml:space="preserve">
|
||||
<t t-name="ai.VoiceTranscription">
|
||||
<details class="transcript-block border mb-2" t-att-open="this.state.isOpened">
|
||||
<summary class="d-flex bg-100 px-2 py-1 fw-bold gap-1 justify-content-between" t-on-click="() => this.state.isOpened = !this.state.isOpened" t-att-class="{'py-2': !this.state.isOpened}">
|
||||
<t t-if="this.state.isOpened">
|
||||
<t t-if="this.ui.size gt 2">
|
||||
<div class="d-flex align-items-center">
|
||||
<i class="oi flex-0 me-2" data-icon="arrow_drop_down" />
|
||||
<ul class="nav gap-1 px-0 bg-transparent" role="tablist">
|
||||
<li t-if="this.state.hasSummary || this.state.status === 'summarizing'">
|
||||
<button
|
||||
class="btn flex-grow-1 flex-sm-grow-0 w-100 w-sm-auto text-muted"
|
||||
t-att-class="{'btn-secondary active text-primary': this.state.currentTab === 'summary'}"
|
||||
t-on-click.stop="() => this.setCurrentTab('summary')"
|
||||
t-att-disabled="this.state.status === 'summarizing'">
|
||||
<t t-if="this.state.status === 'summarizing'">
|
||||
<div class="spinner-border spinner-border-sm me-1" role="status"/>
|
||||
Processing...
|
||||
</t>
|
||||
<t t-else="">
|
||||
<img src="/ai/static/description/icon.png" class="ai-icon-sm me-1 w-1"/>
|
||||
Summary
|
||||
</t>
|
||||
</button>
|
||||
</li>
|
||||
<li>
|
||||
<button class="btn flex-sm-grow-0 w-100 w-sm-auto text-muted"
|
||||
t-att-class="{'btn-secondary active text-primary': this.state.currentTab === 'notes'}"
|
||||
t-on-click.stop="() => this.setCurrentTab('notes')">
|
||||
<i class="oi me-1" data-icon="menu"/>
|
||||
Notes
|
||||
</button>
|
||||
</li>
|
||||
<li>
|
||||
<button
|
||||
class="btn flex-sm-grow-0 w-100 w-sm-auto text-muted"
|
||||
t-att-class="{'btn-secondary active text-primary': this.state.currentTab === 'transcript'}"
|
||||
t-on-click.stop="() => this.setCurrentTab('transcript')">
|
||||
<i class="oi me-1" data-icon="mic"/>
|
||||
Transcript
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
<AudioVisualizer t-if="this.state.status === 'recording' and this.state.frequencies.length > 0" frequencies="this.state.frequencies"/>
|
||||
<div class="d-flex flex-wrap gap-1" t-if="this.state.currentTab !== 'summary'">
|
||||
<Dropdown t-if="this.supportedLanguages?.length > 1">
|
||||
<button class="btn btn-secondary o-dropdown-caret px-2">
|
||||
<t t-out="this.state.currentLanguage.shortCode" />
|
||||
</button>
|
||||
<t t-set-slot="content">
|
||||
<t t-foreach="this.supportedLanguages" t-as="language" t-key="language_index">
|
||||
<DropdownItem class="`btn btn-link ${language.code === this.state.currentLanguage.code ? 'active' : ''}`" onSelected="() => this.state.currentLanguage = language">
|
||||
<t t-out="language.shortCode" />
|
||||
</DropdownItem>
|
||||
</t>
|
||||
</t>
|
||||
</Dropdown>
|
||||
<button
|
||||
class="btn btn-secondary flex-sm-grow-0 w-100 w-sm-auto"
|
||||
t-on-click.stop="this.toggleRecording"
|
||||
t-att-disabled="this.state.status === 'summarizing' || this.state.status === 'waiting'">
|
||||
<t t-if="this.state.status === 'recording'">
|
||||
<i class="oi text-danger me-1" data-icon="stop"/>
|
||||
Stop Recording
|
||||
</t>
|
||||
<t t-else="">
|
||||
<i class="oi oi-filled text-danger me-1" data-icon="circle"/>
|
||||
Start Recording
|
||||
</t>
|
||||
</button>
|
||||
</div>
|
||||
<button class="btn btn-secondary ms-lg-auto" t-on-click.stop="this.openComposer" t-att-disabled="this.state.status === 'summarizing'" t-else="">
|
||||
<i class="oi oi-filled me-1" data-icon="mail"/>
|
||||
Share by email
|
||||
</button>
|
||||
</t>
|
||||
<t t-else="">
|
||||
<Dropdown>
|
||||
<button class="btn btn-secondary o-dropdown-caret px-2 px-sm-3">
|
||||
<t t-if="this.state.currentTab === 'summary'">
|
||||
<img src="/ai/static/description/icon.png" class="ai-icon-sm me-1"/> Summary
|
||||
</t>
|
||||
<t t-elif="this.state.currentTab === 'notes'">
|
||||
<i class="oi me-1" data-icon="menu"/>Notes
|
||||
</t>
|
||||
<t t-else="">
|
||||
<i class="oi me-1" data-icon="mic"/>Transcript
|
||||
</t>
|
||||
</button>
|
||||
<t t-set-slot="content">
|
||||
<DropdownItem class="`btn btn-link ${this.state.currentTab === 'summary' ? 'active' : ''}`" onSelected="(ev) => this.setCurrentTab('summary')">
|
||||
<img src="/ai/static/description/icon.png" class="ai-icon-sm me-1"/>Summary
|
||||
</DropdownItem>
|
||||
<DropdownItem class="`btn btn-link ${this.state.currentTab === 'notes' ? 'active' : ''}`" onSelected="(ev) => this.setCurrentTab('notes')">
|
||||
<i class="oi me-1" data-icon="menu"/>Notes
|
||||
</DropdownItem>
|
||||
<DropdownItem class="`btn btn-link ${this.state.currentTab === 'transcript' ? 'active' : ''}`" onSelected="(ev) => this.setCurrentTab('transcript')">
|
||||
<i class="oi me-1" data-icon="mic"/>Transcript
|
||||
</DropdownItem>
|
||||
</t>
|
||||
</Dropdown>
|
||||
<AudioVisualizer t-if="this.state.status === 'recording' and this.state.frequencies.length > 0" frequencies="this.state.frequencies"/>
|
||||
<div class="d-flex">
|
||||
<Dropdown t-if="this.state.hasSummary || this.supportedLanguages?.length > 1">
|
||||
<button class="btn">
|
||||
<i class="oi" data-icon="more_vert"/>
|
||||
</button>
|
||||
<t t-set-slot="content">
|
||||
<DropdownItem class="'btn btn-link p-0'">
|
||||
<Dropdown t-if="this.supportedLanguages?.length > 1">
|
||||
<button class="btn o-dropdown-caret">
|
||||
Language
|
||||
<span class="ms-2 fw-normal text-muted">
|
||||
<t t-out="this.state.currentLanguage.shortCode" />
|
||||
</span>
|
||||
</button>
|
||||
<t t-set-slot="content">
|
||||
<t t-foreach="this.supportedLanguages" t-as="language" t-key="language_index">
|
||||
<DropdownItem
|
||||
class="`btn btn-link ${language.code === this.state.currentLanguage.code ? 'active' : ''}`"
|
||||
onSelected="() => this.state.currentLanguage = language">
|
||||
<t t-out="language.shortCode" />
|
||||
</DropdownItem>
|
||||
</t>
|
||||
</t>
|
||||
</Dropdown>
|
||||
</DropdownItem>
|
||||
<DropdownItem class="'btn btn-link'" t-if="this.state.hasSummary" onSelected="(ev) => this.openComposer()">
|
||||
<i class="oi oi-filled me-1" data-icon="mail"/>
|
||||
Share by email
|
||||
</DropdownItem>
|
||||
</t>
|
||||
</Dropdown>
|
||||
<button
|
||||
class="btn btn-secondary px-2 px-sm-3"
|
||||
t-on-click.stop="this.toggleRecording"
|
||||
t-att-disabled="this.state.status === 'summarizing' || this.state.status === 'waiting'">
|
||||
<t t-if="this.state.status === 'recording'">
|
||||
<i class="oi text-danger me-1" data-icon="stop" />
|
||||
Stop
|
||||
</t>
|
||||
<t t-else="">
|
||||
<i class="oi oi-filled text-danger me-1" data-icon="circle" />
|
||||
Start
|
||||
</t>
|
||||
</button>
|
||||
</div>
|
||||
</t>
|
||||
</t>
|
||||
<t t-else="">
|
||||
<div class="d-flex align-items-center">
|
||||
<i class="oi flex-0 me-1" data-icon="arrow_right"/>
|
||||
Voice Recording <span t-out="this.state.firstRecordingDate" class="ms-2 fw-normal text-muted"/>
|
||||
</div>
|
||||
<AudioVisualizer t-if="this.state.status === 'recording' and this.state.frequencies.length > 0" frequencies="this.state.frequencies" maxHeight="24"/>
|
||||
</t>
|
||||
</summary>
|
||||
<div class="detail-content overflow-auto" t-att-class="{'d-none': this.state.currentTab !== 'summary'}">
|
||||
<header t-if="this.sortedPromptButtons.length > 0" class="d-flex gap-2 flex-wrap mb-2">
|
||||
<t t-if="this.ui.size gt 2">
|
||||
<t t-foreach="this.sortedPromptButtons" t-as="promptButton" t-key="promptButton_index">
|
||||
<button class="btn btn-secondary" t-on-click="() => this.updateSummary(promptButton)">
|
||||
<t t-out="promptButton.name" />
|
||||
</button>
|
||||
</t>
|
||||
</t>
|
||||
<t t-else="">
|
||||
<Dropdown>
|
||||
<button class="btn btn-secondary o-dropdown-caret">Actions</button>
|
||||
<t t-set-slot="content">
|
||||
<t t-foreach="this.sortedPromptButtons" t-as="promptButton" t-key="promptButton_index">
|
||||
<DropdownItem class="'btn btn-link'" onSelected="() => this.updateSummary(promptButton)">
|
||||
<t t-out="promptButton.name"/>
|
||||
</DropdownItem>
|
||||
</t>
|
||||
</t>
|
||||
</Dropdown>
|
||||
</t>
|
||||
</header>
|
||||
<div id="summary-content" t-ref="this.descendantRefs.summaryContent" t-att-class="{ 'o-ai-summary-processing': this.state.status === 'summarizing' }"/>
|
||||
</div>
|
||||
<div id="notes-content" class="detail-content overflow-auto" t-att-class="{'d-none': this.state.currentTab !== 'notes'}" t-ref="this.descendantRefs.notesContent"/>
|
||||
<div id="transcript-content" class="detail-content overflow-auto" t-att-class="{'d-none': this.state.currentTab !== 'transcript'}" t-ref="this.descendantRefs.transcriptContent"/>
|
||||
</details>
|
||||
</t>
|
||||
</templates>
|
||||
18
ai/static/src/editor/embedded_components/embedding_sets.js
Normal file
18
ai/static/src/editor/embedded_components/embedding_sets.js
Normal file
@@ -0,0 +1,18 @@
|
||||
import {
|
||||
MAIN_EMBEDDINGS,
|
||||
READONLY_MAIN_EMBEDDINGS,
|
||||
} from "@html_editor/others/embedded_components/embedding_sets";
|
||||
import { user } from "@web/core/user";
|
||||
import { aiVoiceTranscriptionEmbeddedComponent } from "./core/voice_transcription";
|
||||
import { aiReadonlyVoiceTranscriptionEmbeddedComponent } from "./core/readonly_voice_transcription";
|
||||
|
||||
// If the user is an internal user, we use the editable version of the voice transcription embedded component,
|
||||
// otherwise we use the readonly component.
|
||||
// NOTE: "readonly" component used inside the editor will still allow editing text content of the component,
|
||||
// Thanks to the editable descendents concept.
|
||||
MAIN_EMBEDDINGS.push(
|
||||
user.isInternalUser
|
||||
? aiVoiceTranscriptionEmbeddedComponent
|
||||
: aiReadonlyVoiceTranscriptionEmbeddedComponent
|
||||
);
|
||||
READONLY_MAIN_EMBEDDINGS.push(aiReadonlyVoiceTranscriptionEmbeddedComponent);
|
||||
@@ -0,0 +1,11 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<templates>
|
||||
<t t-name="ai.VoiceTranscriptionBlueprint">
|
||||
<div data-embedded="voice-transcription" t-att-data-embedded-props="embeddedProps"
|
||||
data-oe-protected="true">
|
||||
<div data-embedded-editable="summaryContent" data-oe-protected="false" />
|
||||
<div data-embedded-editable="notesContent" data-oe-protected="false" />
|
||||
<div data-embedded-editable="transcriptContent" data-oe-protected="false" />
|
||||
</div>
|
||||
</t>
|
||||
</templates>
|
||||
@@ -0,0 +1,270 @@
|
||||
import { Plugin } from "@html_editor/plugin";
|
||||
import { EMBEDDED_COMPONENT_PLUGINS } from "@html_editor/plugin_sets";
|
||||
import { selectElements } from "@html_editor/utils/dom_traversal";
|
||||
import { withSequence } from "@html_editor/utils/resource";
|
||||
import { _t } from "@web/core/l10n/translation";
|
||||
import { createElementWithContent } from "@web/core/utils/html";
|
||||
import { renderToElement } from "@web/core/utils/render";
|
||||
|
||||
const RECORDER_SELECTOR = "[data-embedded='voice-transcription']";
|
||||
const NOTES_CONTENT_SELECTOR = "[data-embedded-editable='notesContent']";
|
||||
const TRANSCRIPT_CONTENT_SELECTOR = "[data-embedded-editable='transcriptContent']";
|
||||
|
||||
export class TranscriptionPlugin extends Plugin {
|
||||
static id = "voice-transcription";
|
||||
static dependencies = [
|
||||
"baseContainer",
|
||||
"dom",
|
||||
"history",
|
||||
"lineBreak",
|
||||
"split",
|
||||
"embeddedComponents",
|
||||
];
|
||||
|
||||
resources = {
|
||||
hints: [
|
||||
{
|
||||
selector: `${RECORDER_SELECTOR} ${NOTES_CONTENT_SELECTOR}:not(:focus) > *:only-child`,
|
||||
text: _t("Add notes about your upcoming meeting"),
|
||||
},
|
||||
{
|
||||
selector: `${RECORDER_SELECTOR} ${TRANSCRIPT_CONTENT_SELECTOR}:not(:focus) > *:only-child`,
|
||||
text: _t("Start recording to get a real-time transcript of the conversation"),
|
||||
},
|
||||
],
|
||||
hint_targets_providers: (_selectionData, editable) => [
|
||||
...editable.querySelectorAll(
|
||||
`${RECORDER_SELECTOR} ${NOTES_CONTENT_SELECTOR}:not(:focus) > *:only-child, ${RECORDER_SELECTOR} ${TRANSCRIPT_CONTENT_SELECTOR}:not(:focus) > *:only-child`
|
||||
),
|
||||
],
|
||||
user_commands: [
|
||||
{
|
||||
id: "openTranscriptDialog",
|
||||
title: _t("Voice Transcript"),
|
||||
description: _t("Dictate text or record a meeting"),
|
||||
run: this.insertTranscriptionComponent.bind(this),
|
||||
},
|
||||
],
|
||||
powerbox_items: [
|
||||
{
|
||||
keywords: [_t("AI")],
|
||||
categoryId: "ai",
|
||||
commandId: "openTranscriptDialog",
|
||||
icon: "mic",
|
||||
},
|
||||
],
|
||||
on_will_mount_component_handlers: this.setupTranscriptionComponent.bind(this),
|
||||
normalize_processors: withSequence(Infinity, this.normalize.bind(this)),
|
||||
};
|
||||
|
||||
setup() {
|
||||
super.setup();
|
||||
this.peerId = this.config.collaboration?.peerId ?? "";
|
||||
}
|
||||
|
||||
get dataId() {
|
||||
let id = "current-transcript";
|
||||
if (this.peerId !== "") {
|
||||
id += `-${this.peerId}`;
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
insertTranscriptionComponent() {
|
||||
const transcriptBlock = renderToElement("ai.VoiceTranscriptionBlueprint");
|
||||
this.dependencies.dom.insert(transcriptBlock);
|
||||
this.dependencies.history.commit();
|
||||
}
|
||||
|
||||
setupTranscriptionComponent({ name, props }) {
|
||||
if (name === "voice-transcription") {
|
||||
Object.assign(props, {
|
||||
onTranscriptionStarted: (component, currentLanguage) =>
|
||||
this.startTranscription(component, currentLanguage),
|
||||
onTranscriptionUpdated: (state, transcriptionEditable, textContent) =>
|
||||
this.updateTranscription(state, transcriptionEditable, textContent),
|
||||
onSummaryUpdated: (summaryEditable, transcript) =>
|
||||
this.updateSummary(summaryEditable, transcript),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds information about the current recording to the transcriptEditable (i.e. the current date).
|
||||
*
|
||||
* @param {HTMLElement} transcriptionEditable - the editable for the transcription
|
||||
* @param {string} currentLanguage - the current language code for the transcription (i.e. en-US)
|
||||
*/
|
||||
startTranscription(transcriptionEditable, currentLanguage) {
|
||||
const today = new Date();
|
||||
const timeString = today.toLocaleTimeString([currentLanguage], {
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
});
|
||||
|
||||
const textElement = document.createElement("p");
|
||||
const boldElement = document.createElement("b");
|
||||
|
||||
boldElement.textContent = `${today.toLocaleDateString()} - ${timeString}`;
|
||||
textElement.appendChild(boldElement);
|
||||
if (transcriptionEditable.textContent.trim() === "") {
|
||||
transcriptionEditable.replaceChildren(textElement);
|
||||
} else {
|
||||
transcriptionEditable.appendChild(textElement);
|
||||
}
|
||||
this.cleanupTranscript(transcriptionEditable);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles update to the transcription based on recording states.
|
||||
*
|
||||
* @param {('listening'|'delta'|'completed'|'stopped')} state - the state of the recording.
|
||||
* @param {HTMLElement} component - the componente to update.
|
||||
* @param {string} textContent - text content to insert into the transcript editable
|
||||
*/
|
||||
updateTranscription(state, component, textContent = "") {
|
||||
switch (state) {
|
||||
case "listening": {
|
||||
this.getOrCreateListeningNode(component);
|
||||
this.dependencies.history.commit();
|
||||
break;
|
||||
}
|
||||
case "delta":
|
||||
this.updateDelta(component, textContent);
|
||||
break;
|
||||
case "completed":
|
||||
this.commitTranscription(component);
|
||||
break;
|
||||
case "stopped": {
|
||||
this.cleanupTranscript(component);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates or retrieve the "AI is listening..." block.
|
||||
*
|
||||
* @param {HTMLElement} transcriptEditable the editable where to look for the block.
|
||||
*/
|
||||
getOrCreateListeningNode(transcriptEditable) {
|
||||
const currentTranscript = this.getOrCreateTranscriptionItem(transcriptEditable);
|
||||
let listeningNode = transcriptEditable.querySelector(".o-ai-transcription-listening");
|
||||
if (!listeningNode) {
|
||||
listeningNode = document.createElement("span");
|
||||
listeningNode.classList.add("o-ai-transcription-listening", "px-1");
|
||||
listeningNode.setAttribute("data-oe-protected", "true");
|
||||
listeningNode.textContent = _t("AI is listening...");
|
||||
currentTranscript.appendChild(listeningNode);
|
||||
}
|
||||
return listeningNode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a "current transcript" node and adds it to the transcriptEditable node.
|
||||
*
|
||||
* @param {HTMLElement} transcriptEditable - the component to insert the transcription into
|
||||
* @returns {HTMLElement} the current transcript node
|
||||
*/
|
||||
getOrCreateTranscriptionItem(transcriptEditable) {
|
||||
const id = this.dataId;
|
||||
let textElement = transcriptEditable.querySelector(`[data-id='${id}']`);
|
||||
if (!textElement) {
|
||||
textElement = document.createElement("blockquote");
|
||||
textElement.setAttribute("data-id", id);
|
||||
// HACK: These two attributes are added to prevent a glitch that resets transcript
|
||||
// component state on save
|
||||
textElement.setAttribute("data-o-mail-quote-node", "1");
|
||||
textElement.setAttribute("data-o-mail-quote", "1");
|
||||
transcriptEditable.appendChild(textElement);
|
||||
}
|
||||
return textElement;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a new element to the current transcript block.
|
||||
*
|
||||
* @param {HTMLElement} component the editable to add the text to.
|
||||
* @param {string} textContent the text to add to the current transcript.
|
||||
*/
|
||||
updateDelta(component, textContent) {
|
||||
const textElement = this.getOrCreateTranscriptionItem(component);
|
||||
const listeningNode = this.getOrCreateListeningNode(component);
|
||||
listeningNode.remove();
|
||||
textElement.textContent = `${textElement.textContent} ${textContent}`;
|
||||
this.dependencies.history.commit();
|
||||
}
|
||||
|
||||
/**
|
||||
* Commits the current transcript block and removes listening block.
|
||||
*
|
||||
* @param {HTMLElement} component the editable containing the block to commit.
|
||||
*/
|
||||
commitTranscription(component) {
|
||||
const currentTranscript = this.getOrCreateTranscriptionItem(component);
|
||||
if (currentTranscript) {
|
||||
currentTranscript.removeAttribute("data-id");
|
||||
}
|
||||
const listeningNode = component.querySelector(".o-ai-transcription-listening");
|
||||
listeningNode?.remove();
|
||||
this.dependencies.history.commit();
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the listening nodes and empty `current-transcript`
|
||||
*
|
||||
* @param {HTMLElement} transcriptionEditable - the component to perform the cleanup on
|
||||
*/
|
||||
cleanupTranscript(transcriptionEditable) {
|
||||
const listeningNode = transcriptionEditable.querySelector(".o-ai-transcription-listening");
|
||||
listeningNode?.remove();
|
||||
|
||||
const currentTranscript = transcriptionEditable.querySelector(`[data-id='${this.dataId}']`);
|
||||
if (currentTranscript) {
|
||||
currentTranscript.removeAttribute("data-id");
|
||||
}
|
||||
|
||||
const emptyBlockquotes = transcriptionEditable.querySelectorAll("blockquote");
|
||||
let blockRemoved = false;
|
||||
emptyBlockquotes.forEach((element) => {
|
||||
if (element.textContent.trim() === "") {
|
||||
element.remove();
|
||||
blockRemoved = true;
|
||||
}
|
||||
});
|
||||
if (blockRemoved) {
|
||||
this.dependencies.history.commit();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace the content of the summaryEditable by the provided transcript.
|
||||
*
|
||||
* @param {HTMLElement} summaryEditable - the editable where the summary will be inserted.
|
||||
* @param {Markup} transcriptHTML - the html to insert within the summary editable
|
||||
*/
|
||||
updateSummary(summaryEditable, transcriptHTML) {
|
||||
summaryEditable.replaceChildren(
|
||||
...createElementWithContent("div", transcriptHTML).children
|
||||
);
|
||||
this.dependencies.history.commit();
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalizes transcription components. Will add <br> tags to empty editables.
|
||||
*
|
||||
* @param {Element} element - the element to normalize
|
||||
*/
|
||||
normalize(element) {
|
||||
for (const emptyRecorderNode of selectElements(
|
||||
element,
|
||||
`${RECORDER_SELECTOR} [data-embedded-editable]:empty`
|
||||
)) {
|
||||
const baseContainer = this.dependencies.baseContainer.createBaseContainer();
|
||||
emptyRecorderNode.replaceChildren(baseContainer);
|
||||
}
|
||||
return element;
|
||||
}
|
||||
}
|
||||
|
||||
EMBEDDED_COMPONENT_PLUGINS.push(TranscriptionPlugin);
|
||||
263
ai/static/src/editor/plugins/chatgpt_plugin.js
Normal file
263
ai/static/src/editor/plugins/chatgpt_plugin.js
Normal file
@@ -0,0 +1,263 @@
|
||||
import { _t } from "@web/core/l10n/translation";
|
||||
import { Plugin } from "@html_editor/plugin";
|
||||
import {
|
||||
firstLeaf,
|
||||
lastLeaf,
|
||||
closestElement,
|
||||
getCommonAncestor,
|
||||
} from "@html_editor/utils/dom_traversal";
|
||||
import { withSequence } from "@html_editor/utils/resource";
|
||||
import { isContentEditable } from "@html_editor/utils/dom_info";
|
||||
import { nodeSize } from "@html_editor/utils/position";
|
||||
import { unwrapContents } from "@html_editor/utils/dom";
|
||||
import { MAIN_PLUGINS } from "@html_editor/plugin_sets";
|
||||
import { user } from "@web/core/user";
|
||||
import { MAIL_CORE_PLUGINS } from "@mail/core/common/plugin/plugin_sets";
|
||||
|
||||
export class ChatGPTPlugin extends Plugin {
|
||||
static id = "chatgpt";
|
||||
static dependencies = [
|
||||
"baseContainer",
|
||||
"selection",
|
||||
"history",
|
||||
"dom",
|
||||
"sanitize",
|
||||
"dialog",
|
||||
"split",
|
||||
"format",
|
||||
];
|
||||
static shared = ["openDialog"];
|
||||
resources = {
|
||||
user_commands: [
|
||||
{
|
||||
id: "openChatGPTDialog",
|
||||
title: _t("AI"),
|
||||
description: _t("Generate or transform content with AI"),
|
||||
run: this.openDialog.bind(this),
|
||||
isAvailable: () => user.isInternalUser,
|
||||
},
|
||||
],
|
||||
toolbar_groups: withSequence(50, {
|
||||
id: "ai",
|
||||
}),
|
||||
toolbar_items: [
|
||||
{
|
||||
id: "chatgpt",
|
||||
groupId: "ai",
|
||||
commandId: "openChatGPTDialog",
|
||||
namespaces: ["compact", "expanded"],
|
||||
icon: "o_ai_icon",
|
||||
isDisabled: this.isNotReplaceableByAI.bind(this),
|
||||
},
|
||||
],
|
||||
powerbox_categories: withSequence(70, { id: "ai", name: _t("AI Tools") }),
|
||||
powerbox_items: {
|
||||
keywords: [_t("AI")],
|
||||
categoryId: "ai",
|
||||
commandId: "openChatGPTDialog",
|
||||
icon: "wand_stars",
|
||||
},
|
||||
power_buttons: withSequence(20, {
|
||||
commandId: "openChatGPTDialog",
|
||||
icon: "o_ai_icon",
|
||||
}),
|
||||
clean_for_save_processors: this.cleanForSave.bind(this),
|
||||
};
|
||||
|
||||
isNotReplaceableByAI(selection = this.dependencies.selection.getEditableSelection()) {
|
||||
if (selection.isCollapsed) {
|
||||
return false;
|
||||
}
|
||||
const isEmpty = !selection.toString().replace(/\s+/g, "");
|
||||
const cannotReplace = this.dependencies.selection
|
||||
.getTargetedNodes()
|
||||
.find((el) => this.dependencies.split.isUnsplittable(el) || !isContentEditable(el));
|
||||
return cannotReplace || isEmpty;
|
||||
}
|
||||
|
||||
createSelectBlock(nodes) {
|
||||
const connectedNodes = nodes.filter((node) => node.isConnected);
|
||||
if (!connectedNodes.length) {
|
||||
return;
|
||||
}
|
||||
const firstInsertedNode = connectedNodes[0];
|
||||
const lastInsertedNode = connectedNodes[connectedNodes.length - 1];
|
||||
const anchorNode = firstLeaf(firstInsertedNode);
|
||||
const focusNode = lastLeaf(lastInsertedNode);
|
||||
const commonAncestor = getCommonAncestor([anchorNode, focusNode]);
|
||||
return {
|
||||
anchorNode: anchorNode,
|
||||
anchorOffset: 0,
|
||||
focusNode: focusNode,
|
||||
focusOffset: nodeSize(focusNode),
|
||||
startContainer: anchorNode,
|
||||
startOffset: 0,
|
||||
endContainer: focusNode,
|
||||
endOffset: nodeSize(focusNode),
|
||||
commonAncestorContainer: commonAncestor,
|
||||
};
|
||||
}
|
||||
|
||||
async openDialog(params = {}) {
|
||||
const selection = this.dependencies.selection.getEditableSelection();
|
||||
const dialogParams = {
|
||||
insert: (content, selection) => {
|
||||
if (selection) {
|
||||
this.dependencies.selection.setSelection(selection);
|
||||
this.dependencies.format.removeSelectionFormats();
|
||||
}
|
||||
const insertedNodes = this.dependencies.dom.insert(content);
|
||||
this.dependencies.history.commit();
|
||||
// Add a frame around the inserted content to highlight it for 2
|
||||
// seconds.
|
||||
const start = insertedNodes?.length && closestElement(insertedNodes[0]);
|
||||
const end =
|
||||
insertedNodes?.length &&
|
||||
closestElement(insertedNodes[insertedNodes.length - 1]);
|
||||
if (start && end) {
|
||||
const divContainer = this.editable.parentElement;
|
||||
let [parent, left, top] = [
|
||||
start.offsetParent,
|
||||
start.offsetLeft,
|
||||
start.offsetTop - start.scrollTop,
|
||||
];
|
||||
while (parent && !parent.contains(divContainer)) {
|
||||
left += parent.offsetLeft;
|
||||
top += parent.offsetTop - parent.scrollTop;
|
||||
parent = parent.offsetParent;
|
||||
}
|
||||
let [endParent, endTop] = [end.offsetParent, end.offsetTop - end.scrollTop];
|
||||
while (endParent && !endParent.contains(divContainer)) {
|
||||
endTop += endParent.offsetTop - endParent.scrollTop;
|
||||
endParent = endParent.offsetParent;
|
||||
}
|
||||
const div = document.createElement("div");
|
||||
div.classList.add("o-chatgpt-content");
|
||||
const FRAME_PADDING = 3;
|
||||
div.style.left = `${left - FRAME_PADDING}px`;
|
||||
div.style.top = `${top - FRAME_PADDING}px`;
|
||||
div.style.width = `${
|
||||
Math.max(start.offsetWidth, end.offsetWidth) + FRAME_PADDING * 2
|
||||
}px`;
|
||||
div.style.height = `${endTop + end.offsetHeight - top + FRAME_PADDING * 2}px`;
|
||||
divContainer.prepend(div);
|
||||
setTimeout(() => div.remove(), 2000);
|
||||
}
|
||||
},
|
||||
selectPreviousInsertion: (selectionId) => {
|
||||
const targetElement = this.editable.querySelector(
|
||||
`[data-ai-selection-id="${selectionId}"]`
|
||||
);
|
||||
if (targetElement) {
|
||||
return this.createSelectBlock([targetElement]);
|
||||
}
|
||||
},
|
||||
...params,
|
||||
};
|
||||
dialogParams.baseContainer = this.dependencies.baseContainer.getDefaultNodeName();
|
||||
// collapse to end
|
||||
let callerComp,
|
||||
recordModel,
|
||||
recordId,
|
||||
recordData,
|
||||
recordFields,
|
||||
callerId,
|
||||
channelTitle,
|
||||
textSelection;
|
||||
const { resModel, resId, data, fields, id } = this.config.getRecordInfo();
|
||||
const textOfEditable = this.editable.innerText;
|
||||
if (selection.isCollapsed) {
|
||||
if (resModel === "mail.compose.message") {
|
||||
callerComp = "mail_composer";
|
||||
recordModel = data.model;
|
||||
recordId = Number(data.res_ids.slice(1, -1)); // resIds should look like so `[id]`, the slice and cast allows to extract the id
|
||||
recordData = data;
|
||||
channelTitle = data.subject;
|
||||
callerId = id;
|
||||
} else {
|
||||
callerComp = params.callerComp || "html_field_record";
|
||||
recordModel = resModel;
|
||||
recordId = resId;
|
||||
recordData = data;
|
||||
recordFields = fields;
|
||||
channelTitle = params.channelTitle || data?.display_name || _t("Editor");
|
||||
callerId = resId || id;
|
||||
}
|
||||
textSelection = {
|
||||
selectionId: `ai-selection-${Date.now()}-${Math.floor(Math.random() * 1000)}`,
|
||||
};
|
||||
} else {
|
||||
callerComp = "html_field_text_select";
|
||||
recordModel = resModel;
|
||||
recordId = resId;
|
||||
recordData = data;
|
||||
recordFields = fields;
|
||||
channelTitle = _t("Text Selection");
|
||||
callerId = resId || id;
|
||||
|
||||
const textOfSelection = selection.toString();
|
||||
const selectionId = `ai-selection-${Date.now()}-${Math.floor(Math.random() * 1000)}`;
|
||||
const wrapper = this.document.createElement("span");
|
||||
wrapper.dataset.aiSelectionId = selectionId;
|
||||
wrapper.classList.add("o_ai_selection_wrapper");
|
||||
|
||||
const range = this.document.getSelection().getRangeAt(0);
|
||||
const contents = range.extractContents();
|
||||
wrapper.appendChild(contents);
|
||||
range.insertNode(wrapper);
|
||||
|
||||
textSelection = {
|
||||
selectionId: selectionId,
|
||||
textContent: textOfSelection,
|
||||
};
|
||||
}
|
||||
await this.services.aiChatLauncher.launchAIChat({
|
||||
interfaceKey: callerComp,
|
||||
recordModel: recordModel,
|
||||
recordId: recordId,
|
||||
originalRecordData: recordData,
|
||||
originalRecordFields: recordFields,
|
||||
aiSpecialActions: {
|
||||
insert: dialogParams.insert,
|
||||
selectPreviousInsertion: dialogParams.selectPreviousInsertion,
|
||||
},
|
||||
channelTitle: channelTitle,
|
||||
aiChatSourceId: callerId,
|
||||
textSelection: textSelection,
|
||||
textOfEditable: textOfEditable,
|
||||
});
|
||||
if (this.services.ui.isSmall) {
|
||||
// TODO: Find a better way and avoid modifying range
|
||||
// HACK: In the case of opening through dropdown:
|
||||
// - when dropdown open, it keep the element focused before the open
|
||||
// - when opening the dialog through the dropdown, the dropdown closes
|
||||
// - upon close, the generic code of the dropdown sets focus on the kept element (in our case, the editable)
|
||||
// - we need to remove the range after the generic code of the dropdown is triggered so we hack it by removing the range in the next tick
|
||||
Promise.resolve().then(() => {
|
||||
// If the dialog is opened on a small screen, remove all selection
|
||||
// because the selection can be seen through the dialog on some devices.
|
||||
this.document.getSelection()?.removeAllRanges();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
cleanForSave(root) {
|
||||
const aiInsertedElements = root.querySelectorAll(`span[data-ai-selection-id]`);
|
||||
const elements = [...aiInsertedElements];
|
||||
for (const element of elements) {
|
||||
unwrapContents(element);
|
||||
}
|
||||
return root;
|
||||
}
|
||||
|
||||
destroy() {
|
||||
const { resModel } = this.config.getRecordInfo();
|
||||
if (resModel !== "mail.compose.message") {
|
||||
this.services["mail.store"].aiInsertButtonTarget = false;
|
||||
}
|
||||
super.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
MAIN_PLUGINS.push(ChatGPTPlugin);
|
||||
MAIL_CORE_PLUGINS.push(ChatGPTPlugin);
|
||||
Reference in New Issue
Block a user