discourse-ai/assets/javascripts/discourse/connectors/after-d-editor/ai-helper-context-menu.js

417 lines
10 KiB
JavaScript
Raw Normal View History

2023-08-23 13:35:40 -04:00
import Component from "@glimmer/component";
import { tracked } from "@glimmer/tracking";
2023-11-03 07:30:09 -04:00
import { action } from "@ember/object";
import { inject as service } from "@ember/service";
import { createPopper } from "@popperjs/core";
2023-08-23 13:35:40 -04:00
import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
import { caretPosition, getCaretPosition } from "discourse/lib/utilities";
2023-11-03 07:30:09 -04:00
import { INPUT_DELAY } from "discourse-common/config/environment";
import { afterRender, bind, debounce } from "discourse-common/utils/decorators";
import { showComposerAIHelper } from "../../lib/show-ai-helper";
2023-08-23 13:35:40 -04:00
export default class AiHelperContextMenu extends Component {
static shouldRender(outletArgs, helper) {
return showComposerAIHelper(outletArgs, helper, "context_menu");
2023-08-23 13:35:40 -04:00
}
@service currentUser;
2023-08-23 13:35:40 -04:00
@service siteSettings;
@service modal;
@service capabilities;
2023-08-23 13:35:40 -04:00
@tracked showContextMenu = false;
@tracked caretCoords;
@tracked virtualElement;
@tracked selectedText = "";
2023-08-24 20:49:24 -04:00
@tracked newSelectedText;
2023-08-23 13:35:40 -04:00
@tracked loading = false;
@tracked lastUsedOption = null;
2023-08-24 20:49:24 -04:00
@tracked showDiffModal = false;
@tracked showThumbnailModal = false;
2023-08-24 20:49:24 -04:00
@tracked diff;
@tracked popperPlacement = "top-start";
@tracked previousMenuState = null;
@tracked customPromptValue = "";
2023-12-20 13:46:22 -05:00
@tracked initialValue = "";
@tracked thumbnailSuggestions = null;
@tracked selectionRange = { x: 0, y: 0 };
@tracked lastSelectionRange = null;
2023-08-23 13:35:40 -04:00
CONTEXT_MENU_STATES = {
triggers: "TRIGGERS",
options: "OPTIONS",
resets: "RESETS",
loading: "LOADING",
2023-08-24 20:49:24 -04:00
review: "REVIEW",
2023-08-23 13:35:40 -04:00
};
prompts = [];
promptTypes = {};
minSelectionChars = 3;
2023-08-23 13:35:40 -04:00
@tracked _menuState = this.CONTEXT_MENU_STATES.triggers;
2023-08-23 13:35:40 -04:00
@tracked _popper;
@tracked _dEditorInput;
@tracked _customPromptInput;
2023-08-23 13:35:40 -04:00
@tracked _contextMenu;
@tracked _activeAIRequest = null;
2023-08-23 13:35:40 -04:00
willDestroy() {
super.willDestroy(...arguments);
document.removeEventListener("selectionchange", this.selectionChanged);
document.removeEventListener("keydown", this.onKeyDown);
2023-08-23 13:35:40 -04:00
this._popper?.destroy();
}
get menuState() {
return this._menuState;
}
set menuState(newState) {
this.previousMenuState = this._menuState;
this._menuState = newState;
}
get helperOptions() {
let prompts = this.currentUser?.ai_helper_prompts;
2023-08-23 13:35:40 -04:00
prompts = prompts
.filter((p) => p.location.includes("composer"))
.filter((p) => p.name !== "generate_titles");
// Find the custom_prompt object and move it to the beginning of the array
const customPromptIndex = prompts.findIndex(
(p) => p.name === "custom_prompt"
);
if (customPromptIndex !== -1) {
const customPrompt = prompts.splice(customPromptIndex, 1)[0];
prompts.unshift(customPrompt);
}
if (!this._showUserCustomPrompts()) {
prompts = prompts.filter((p) => p.name !== "custom_prompt");
}
prompts.forEach((p) => {
this.prompts[p.id] = p;
});
2023-08-23 13:35:40 -04:00
this.promptTypes = prompts.reduce((memo, p) => {
memo[p.name] = p.prompt_type;
return memo;
}, {});
return prompts;
2023-08-23 13:35:40 -04:00
}
@bind
selectionChanged() {
if (document.activeElement !== this._dEditorInput) {
2023-08-23 13:35:40 -04:00
return;
}
const canSelect = Boolean(
window.getSelection() &&
document.activeElement &&
document.activeElement.value
);
this.selectedText = canSelect
? document.activeElement.value.substring(
document.activeElement.selectionStart,
document.activeElement.selectionEnd
)
: "";
2023-12-20 13:46:22 -05:00
this.selectionRange = canSelect
? {
x: document.activeElement.selectionStart,
y: document.activeElement.selectionEnd,
}
: { x: 0, y: 0 };
2023-09-13 12:53:19 -04:00
if (this.selectedText?.length === 0) {
2023-08-23 13:35:40 -04:00
this.closeContextMenu();
return;
}
if (this.selectedText?.length < this.minSelectionChars) {
return;
}
2023-08-23 13:35:40 -04:00
this._onSelectionChanged();
}
@bind
updatePosition() {
if (!this.showContextMenu) {
return;
}
this.positionContextMenu();
}
@bind
onKeyDown(event) {
if (event.key === "Escape") {
return this.closeContextMenu();
}
if (
event.key === "Backspace" &&
this.selectedText &&
this.menuState === this.CONTEXT_MENU_STATES.triggers
) {
return this.closeContextMenu();
}
}
2023-08-23 13:35:40 -04:00
@debounce(INPUT_DELAY)
_onSelectionChanged() {
this.positionContextMenu();
this.showContextMenu = true;
}
generateGetBoundingClientRect(width = 0, height = 0, x = 0, y = 0) {
return () => ({
width,
height,
top: y,
right: x,
bottom: y,
left: x,
});
}
get canCloseContextMenu() {
if (document.activeElement === this._customPromptInput) {
return false;
}
if (this.loading && this._activeAIRequest !== null) {
return false;
}
if (this.menuState === this.CONTEXT_MENU_STATES.review) {
return false;
}
return true;
}
2023-08-23 13:35:40 -04:00
closeContextMenu() {
if (!this.canCloseContextMenu) {
return;
}
2023-08-23 13:35:40 -04:00
this.showContextMenu = false;
this.menuState = this.CONTEXT_MENU_STATES.triggers;
this.customPromptValue = "";
2023-08-23 13:35:40 -04:00
}
_updateSuggestedByAI(data) {
2023-08-24 20:49:24 -04:00
this.newSelectedText = data.suggestions[0];
if (data.diff) {
this.diff = data.diff;
}
2023-12-20 13:46:22 -05:00
this._insertAt(
this.selectionRange.x,
this.selectionRange.y,
this.newSelectedText
);
2023-08-24 20:49:24 -04:00
this.menuState = this.CONTEXT_MENU_STATES.review;
2023-08-23 13:35:40 -04:00
}
2023-12-20 13:46:22 -05:00
_insertAt(start, end, text) {
this._dEditorInput.setSelectionRange(start, end);
this._dEditorInput.focus();
document.execCommand("insertText", false, text);
}
_toggleLoadingState(loading) {
if (loading) {
this._dEditorInput.classList.add("loading");
return (this.loading = true);
}
this._dEditorInput.classList.remove("loading");
return (this.loading = false);
}
_showUserCustomPrompts() {
return this.currentUser?.can_use_custom_prompts;
}
handleBoundaries() {
const textAreaWrapper = document
.querySelector(".d-editor-textarea-wrapper")
.getBoundingClientRect();
const buttonBar = document
.querySelector(".d-editor-button-bar")
.getBoundingClientRect();
const boundaryElement = {
top: buttonBar.bottom,
bottom: textAreaWrapper.bottom,
};
const contextMenuRect = this._contextMenu.getBoundingClientRect();
// Hide context menu if it's scrolled out of bounds:
if (contextMenuRect.top < boundaryElement.top) {
this._contextMenu.classList.add("out-of-bounds");
} else if (contextMenuRect.bottom > boundaryElement.bottom) {
this._contextMenu.classList.add("out-of-bounds");
} else {
this._contextMenu.classList.remove("out-of-bounds");
}
// Position context menu at based on if interfering with button bar
if (this.caretCoords.y - contextMenuRect.height < boundaryElement.top) {
this.popperPlacement = "bottom-start";
} else {
this.popperPlacement = "top-start";
}
}
2023-08-23 13:35:40 -04:00
@afterRender
positionContextMenu() {
this._contextMenu = document.querySelector(".ai-helper-context-menu");
this.caretCoords = getCaretPosition(this._dEditorInput, {
pos: caretPosition(this._dEditorInput),
});
// prevent overflow of context menu outside of editor
this.handleBoundaries();
2023-08-23 13:35:40 -04:00
this.virtualElement = {
getBoundingClientRect: this.generateGetBoundingClientRect(
this._contextMenu.clientWidth,
this._contextMenu.clientHeight,
this.caretCoords.x,
this.caretCoords.y
),
};
this._popper = createPopper(this.virtualElement, this._contextMenu, {
placement: this.popperPlacement,
2023-08-23 13:35:40 -04:00
modifiers: [
{
name: "offset",
options: {
offset: [10, 0],
},
},
],
});
}
@action
setupContextMenu() {
document.addEventListener("selectionchange", this.selectionChanged);
document.addEventListener("keydown", this.onKeyDown);
2023-08-23 13:35:40 -04:00
this._dEditorInput = document.querySelector(".d-editor-input");
if (this._dEditorInput) {
this._dEditorInput.addEventListener("scroll", this.updatePosition);
}
}
@action
setupCustomPrompt() {
this._customPromptInput = document.querySelector(
".ai-custom-prompt__input"
);
this._customPromptInput.focus();
}
2023-08-23 13:35:40 -04:00
@action
toggleAiHelperOptions() {
this.menuState = this.CONTEXT_MENU_STATES.options;
}
@action
undoAIAction() {
if (this.capabilities.isFirefox) {
// execCommand("undo") is no not supported in Firefox so we insert old text at range
this._insertAt(
this.lastSelectionRange.x,
this.lastSelectionRange.y,
this.initialValue
);
} else {
document.execCommand("undo", false, null);
}
// context menu is prevented from closing when in review state
// so we change to reset state quickly before closing
this.menuState = this.CONTEXT_MENU_STATES.resets;
2023-08-23 13:35:40 -04:00
this.closeContextMenu();
}
@action
async updateSelected(option) {
this._toggleLoadingState(true);
2023-08-23 13:35:40 -04:00
this.lastUsedOption = option;
this.menuState = this.CONTEXT_MENU_STATES.loading;
2023-12-20 13:46:22 -05:00
this.initialValue = this.selectedText;
this.lastSelectionRange = this.selectionRange;
2023-08-23 13:35:40 -04:00
this._activeAIRequest = ajax("/discourse-ai/ai-helper/suggest", {
2023-08-23 13:35:40 -04:00
method: "POST",
data: {
mode: option.id,
text: this.selectedText,
custom_prompt: this.customPromptValue,
},
});
this._activeAIRequest
2023-08-23 13:35:40 -04:00
.then((data) => {
2023-08-24 20:49:24 -04:00
// resets the values if new suggestion is started:
this.diff = null;
this.newSelectedText = null;
this.thumbnailSuggestions = null;
if (option.name === "illustrate_post") {
this._toggleLoadingState(false);
this.closeContextMenu();
this.showThumbnailModal = true;
this.thumbnailSuggestions = data.thumbnails;
} else {
this._updateSuggestedByAI(data);
}
2023-08-23 13:35:40 -04:00
})
.catch(popupAjaxError)
.finally(() => {
this._toggleLoadingState(false);
2023-08-23 13:35:40 -04:00
});
return this._activeAIRequest;
2023-08-23 13:35:40 -04:00
}
2023-08-24 20:49:24 -04:00
@action
viewChanges() {
this.showDiffModal = true;
}
@action
confirmChanges() {
this.menuState = this.CONTEXT_MENU_STATES.resets;
}
@action
cancelAIAction() {
if (this._activeAIRequest) {
this._activeAIRequest.abort();
this._activeAIRequest = null;
this._toggleLoadingState(false);
this.closeContextMenu();
}
}
@action
togglePreviousMenu() {
this.menuState = this.previousMenuState;
}
2023-08-23 13:35:40 -04:00
}