Skip to content

Commit b8c0d11

Browse files
committed
Consider prompt position when preventing command palette trigger
1 parent 6734075 commit b8c0d11

File tree

1 file changed

+21
-7
lines changed

1 file changed

+21
-7
lines changed

src/components/CommandPalette/CommandPalette.tsx

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import React, { useEffect, useState } from "react";
2-
import { getVisibleSelectionRect, RichUtils } from "draft-js";
2+
import { ContentBlock, getVisibleSelectionRect, RichUtils } from "draft-js";
33

44
import { ENTITY_TYPE } from "../../api/constants";
55
import DraftUtils from "../../api/DraftUtils";
@@ -62,6 +62,12 @@ const getTargetPosition = (editorRect: DOMRect) => {
6262
return null;
6363
};
6464

65+
type Prompt = {
66+
text: string;
67+
position: number;
68+
block: ContentBlock;
69+
};
70+
6571
export interface CommandPaletteProps extends ToolbarProps {
6672
comboPlacement?: TooltipPlacement;
6773
noResultsText?: string;
@@ -87,23 +93,31 @@ const CommandPalette = ({
8793
const editorState = getEditorState();
8894
const prompt = DraftUtils.getCommandPalettePrompt(editorState);
8995
const promptText = prompt?.text || "";
96+
const promptPos = prompt?.position;
97+
const promptBlock = prompt?.block.getKey();
9098
const [shouldOpen, setShouldOpen] = useState(false);
91-
const [dismissedPrefix, setDismissedPrefix] = useState<string | null>(null);
99+
const [dismissedPrompt, setDismissedPrompt] = useState<Prompt | null>(null);
92100
useEffect(() => {
93101
if (promptText) {
94-
if (dismissedPrefix) {
95-
const open = !promptText.startsWith(dismissedPrefix);
102+
// When there is a previously-dismissed prompt, only open the palette if the prompt has changed:
103+
// - new position (char offset, block)
104+
// - new starting text
105+
if (dismissedPrompt) {
106+
const open =
107+
dismissedPrompt.position !== promptPos ||
108+
dismissedPrompt.block.getKey() !== promptBlock ||
109+
!promptText.startsWith(dismissedPrompt.text);
96110
setShouldOpen(open);
97111
if (open) {
98-
setDismissedPrefix(null);
112+
setDismissedPrompt(null);
99113
}
100114
} else {
101115
setShouldOpen(true);
102116
}
103117
} else {
104118
setShouldOpen(false);
105119
}
106-
}, [dismissedPrefix, promptText]);
120+
}, [dismissedPrompt, promptText, promptPos, promptBlock]);
107121

108122
if (!shouldOpen) {
109123
return null;
@@ -148,7 +162,7 @@ const CommandPalette = ({
148162
shouldOpen={shouldOpen}
149163
onHide={() => {
150164
if (prompt) {
151-
setDismissedPrefix(prompt.text);
165+
setDismissedPrompt(prompt);
152166
}
153167
setShouldOpen(false);
154168
}}

0 commit comments

Comments
 (0)