外部projectのリンク内で補完windowを開くテスト
仕上げ
/icons/done.icon正規表現テスト
ちゃんと別々にマッチする
斜体はマッチしない
code:script.js
class suggestWindow{
constructor() {
this.box = document.createElement('div');
this.box.classList.add('form-group');
this.box.style.position = 'absolute';
this.container = document.createElement('div');
this.container.classList.add('dropdown');
this.box.appendChild(this.container);
this.items = document.createElement('ul');
this.items.classList.add('dropdown-menu');
this.items.style.whiteSpace='nowrap'; // 文字列を折り返さない
this.container.appendChild(this.items);
this.editor = document.getElementById('editor');
this.editor.appendChild(this.box);
}
// 入力補完window を開く
open() {
this.container.classList.add('open');
}
close() {
this.container.classList.remove('open');
}
// 入力候補に表示するアイテムを更新する
updateItems(items) {
const newList = document.createElement('ul');
newList.classList.add('dropdown-menu');
newList.style.whiteSpace='nowrap';
for(const item of items) {
let listItem = document.createElement('li');
listItem.classList.add('dropdown-item');
listItem.innerHTML = item;
newList.appendChild(listItem)
}
this.items.replaceWith(newList);
this.items = newList; // これを書かないと置き換えが完了しない
}
}
const suggestion=new suggestWindow();
suggestion.editor.addEventListener('keyup',() => {
let text= 'No line is focused.'
if(suggestion.editor.getElementsByClassName('cursor-line').length!=0){
let line = suggestion.editor.getElementsByClassName('cursor-line')0; text = line.textContent;
}
// cursorを含む文字列のみ抽出
const cursor = document.getElementById('text-input');
const matchedString = matches
// cursorを含む外部projectリンクは一つしかないはずなので、filterではなくfindを使う
.find(match => {
const cursorLine = suggestion.editor
.getElementsByClassName('cursor-line')0; // '['の右端の座標
const startLeft = cursorLine
.getElementsByClassName(c-${match.index+1})0 .offsetLeft;
// ']'の左端の座標
const endLeft = cursorLine
.getElementsByClassName(c-${match.index + match[0].length -1})0 .offsetLeft;
// cursorの左端の座標
const cursorLeft = parseInt(cursor.style.left);
return startLeft <= cursorLeft && cursorLeft <= endLeft;
});
if(!matchedString) {
suggestion.close();
return;
}
suggestion.open();
// 入力補完windowの位置を更新する
suggestion.box.style.top = ${parseInt(cursor.style.top) + parseInt(cursor.style.height) + 3}px;
suggestion.box.style.left = ${parseInt(cursor.style.left)}px;
});