Handsontableのセルにコメントを記入しようとすると、下図のGIFのようにセル自体に記入されてしまうという不具合(?)があります。
コメント入力欄を1度クリックすれば、入力できるようにはなるのですが、ユーザー体験としてはとてもよろしくないですよね。
そこで今回、暫定的な回避策を見つけたので書き残します。
利用しているHandsontableのバージョンは15.0です。
なお、本記事で扱っているテーブル(GIFのテーブル)はHandsontableのドキュメント内で公開されているサンプルコードを利用しています。
発生手順
下記手順で、不具合が発生します。
英語入力だと問題ないので、日本語入力特有の問題のようです。
- セルを選択後、コンテキストメニューからコメントの追加を選択
- IMEが日本語入力の状態でキー入力を行う
- コメント入力欄ではなく、セルに入力されてしまう☹️
回避方法
セルが選択状態になっていることがよくなさそうなので、コメント入力欄が出現したときにセルの選択を解除する方法をとりました。
そのために、JSのMutationObserver
を利用してコメント入力欄の出現を監視します。
実装したコードです。
// コメント入力欄を監視対象のtargetとする
const target = document.querySelector('div.htComments') as HTMLElement
const observer = new MutationObserver(() => {
// targetのstyleが変化した際に実行する処理
if (
target.style.display === 'block' &&
document.activeElement === document.querySelector('textarea.htCommentTextArea')
) {
hot.deselectCell()
}
})
observer.observe(target, {
attributes: true,
attributeFilter: ['style'],
})
下記の条件をif文に入れています。その理由として、入れておかないとコメント入力済みのセルにマウスホバーしてコメント入力欄が出現した際にセルの選択が解除されてしまうからです。
document.activeElement === document.querySelector('textarea.htCommentTextArea')
【参考】サンプルのテーブルに適用した際のコード
import './styles.css';
import Handsontable from 'handsontable';
import 'handsontable/styles/handsontable.css';
import 'handsontable/styles/ht-theme-main.css';
const container = document.querySelector('#example1');
const hot = new Handsontable(container, {
data: [
['', 'Tesla', 'Nissan', 'Toyota', 'Honda', 'Mazda', 'Ford'],
['2017', 10, 11, 12, 13, 15, 16],
['2018', 10, 11, 12, 13, 15, 16],
['2019', 10, 11, 12, 13, 15, 16],
['2020', 10, 11, 12, 13, 15, 16],
['2021', 10, 11, 12, 13, 15, 16],
],
rowHeaders: true,
colHeaders: true,
contextMenu: true,
comments: true,
cell: [
{ row: 1, col: 1, comment: { value: 'Some comment' } },
{ row: 2, col: 2, comment: { value: 'More comments' } },
],
height: 'auto',
autoWrapRow: true,
autoWrapCol: true,
licenseKey: 'non-commercial-and-evaluation',
});
const target = document.querySelector('div.htComments');
const observer = new MutationObserver(() => {
// targetのstyleが変化した際に実行する処理
if (
target.style.display === 'block' &&
document.activeElement ===
document.querySelector('textarea.htCommentTextArea')
) {
hot.deselectCell();
}
});
observer.observe(target, {
attributes: true,
attributeFilter: ['style'],
});
…すると無事に日本語でコメント入力ができました!