非推奨のexecCommandでUndo/Redo履歴保持する
問題:valueを直接変更するとブラウザの履歴が消える
AIチャットなどを自作する際、テンプレート機能でtextareaの値を直接変更したいケースがあります。単純に実装すると、Ctrl+ZやCmd+Shift+ZなどUndo/Redoが正常に動作しなくなります。
解決法:document.execCommand('insertText')
document.execCommand('insertText') を使うと、ブラウザの編集履歴を保持したままテキストを挿入できます。
execCommand(commandName, showDefaultUI, valueArgument)
import { useRef, useState } from 'react';
function TextEditor() {
const [text, setText] = useState('');
const textareaRef = useRef<HTMLTextAreaElement>(null);
const handleTemplateInsert = (template: string) => {
const textarea = textareaRef.current;
if (!textarea) {
setText(template);
return;
}
textarea.focus();
textarea.select();
const success = document.execCommand('insertText', false, template);
if (success) {
setText(textarea.value);
return;
}
setText(template);
};
return (
<>
<button onClick={handleTemplateInsert}>テンプレート挿入</button>
<textarea
ref={textareaRef}
value={text}
onChange={(e) => setText(e.target.value)}
/>
</>
);
}
Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.
Note: Although the execCommand() method is deprecated, there are still some valid use cases that do not yet have viable alternatives. For example, unlike direct DOM manipulation, modifications performed by execCommand() preserve the undo buffer (edit history). For these use cases, you can still use this method, but test to ensure cross-browser compatibility, such as by using document.queryCommandSupported().
execCommand は非推奨(Deprecated)ですが、Undo/Redo履歴を保持する標準的な代替手段はなさそうです。フォールバックもできるため、UX重視すると利用する価値はあるかもしれません。
Discussion