소스 파일 : /navigation/navi_search.js (2022-08-09)     소스 설명 : 용어해설 분류 검색
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
// (2021.9.18, 차재복, Cha Jae Bok, http://www.ktword.co.kr)

// 용어해설 분류 `명칭 검색` 및 소스코드 `내용 검색`
// 호출 : [index.js] window.addEventListener (2)

function searchAction(e) {

    // 입력 문자열 취득
    let str;
    if(e.type=='keypress') str = e.target.value;
    if(e.type=='click') str = e.target.previousElementSibling.value;

    // 입력 valiadation
    if(str.length<=0) { alert('분류 검색어 입력 요망!'); return; }
    if(str.length<2) { alert('최소 2자 이상'); return; }
    if(str.length>15) { alert('최대 15자 미만 (현재 : '+str.length+'자)'); return; }

    // div 찾기 및 show
    const div = e.target.parentNode.querySelector('.srchResultDiv');
    if(!div) return;
    else div.style.display = 'block';
    // type 구분
    const type = div.dataset.type;

    // ajax Promise 검색 요청 파라미터 설정
    const url = '/test/navigation/naviFetch.php';
    const method = 'post';
    let choice;
        if(type=='bunryu') choice = 'bunryuSearch';
        else if(type=='source') choice = 'srcSearch';
    const parms = { 'choice' : choice, 'sh' : str };

    ajaxPromise(url, method, parms)
    .then(
        response => {

            if(type=='bunryu') {
                // div에 show, ajax 응답 결과 뿌리기
                div.innerHTML = response.str;
                // 응답 결과 중 매 줄 마다, idPath 찾고, 이곳에 이벤트 생성 및 이벤트 처리기 연결
                const idPathFocusEvent = div.querySelectorAll('span.idPathFocusEvent');
                idPathFocusEvent.forEach((elem) => {
                    elem.addEventListener('click', idPathFocusEventHandler);
                });
                // 접속 통계 등록
                stat_enroll('bunryuSearch',str);

            } else if(type=='source') {
                // div에 show, ajax 응답 결과 뿌리기
                div.innerHTML = response.html;
//                div.innerHTML = decodeURI(response.html);
                // 응답 결과 중 출력된 요소들에 이벤트 핸들러 등록
                const srcPathLineNo = div.querySelectorAll('.srcPathLineNo');
                srcPathLineNo.forEach((elem) => {
                    elem.addEventListener('click', (e) => {
                        e.preventDefault();
                        // 기존 검색결과 요소들 색깔로 원래 환원 및 선택된 요소 만 빨간색
                        srcPathLineNo.forEach( (el) => el.style.color = '' );
                        e.target.style.color = 'red';                    
                        // 소스 트리에서, 기존 열려진 (ol 요소들,detail_view 창) 모두 닫기, 
                        const startElem = document.getElementById('sourceStart');
                        startElem.querySelectorAll('.detail_view').forEach((view) => view.style.display='none');
                        // bullet 요소 화살표 방향 바꿈, idpath에 언급된 id 마다 차례로 open 시키고, 해당 line에 위치시킴
                        const path = e.target.dataset.path.split(',');
                        const idpath = ['0',...path];
                        const leafId = idpath.pop();            // 말단 노드 id
                        const line = e.target.dataset.line;     // 줄 번호
                        let li;

                        asynctodo(idpath,startElem)                    // navi_search.js
                        // 추가적으로, 소스 코드 보기 화면 오픈
                        .then(
                            response => {
                                li = startElem.querySelector("li[data-id='"+leafId+"']");
                                return detailSourceView(li);
                            }, error => { alert(error); }
                        )
                        .then(
                            response => { 
                                const startSecNo = parseInt((line-1) / 30);

                                const secBtn = li.querySelectorAll('.secBtn');
                                    secBtn.forEach( (elem) => { 
                                        if(elem.dataset.bno==startSecNo) elem.style.fontWeight='bold';
                                        else elem.style.fontWeight='normal';
                                    });

                                const secDiv = li.querySelectorAll('.secDiv');
                                    secDiv.forEach( (elem) => { 
                                        if(elem.dataset.dno==startSecNo) elem.style.display='block';
                                        else elem.style.display='none'; 
                                    });
                                let a = li.querySelector("a[data-id='"+leafId+"']");
                                a.focus();
                            }, error => { alert(error); }
                        );
                    });
                });
                // 접속 통계 등록
                stat_enroll('sourceSrch',str);
            }
            // 닫기 버튼 처리
            srchCloseBtn(div);          // navi_search.js
        },
        error => { alert(error); }
    );
}

// 검색 결과 닫기 버튼
function srchCloseBtn(div) {
    // 혹시 기존 버튼 있으면 삭제
    const oldBtn = div.parentNode.querySelector('.srcCloseBtn');
    if(oldBtn) oldBtn.remove();
    // div 직전에, 닫기 버튼 생성
    const closeBtn1 = document.createElement('button');
        closeBtn1.style.color = 'red';
        closeBtn1.innerText = '닫 기';
        closeBtn1.setAttribute('class','srcCloseBtn');
    div.parentNode.insertBefore(closeBtn1,div);

    // div 내 하단부에 닫기 버튼 생성
    div.appendChild(document.createElement('br'));
    const closeBtn2 = document.createElement('button');
        closeBtn2.style.width = '30%';
        closeBtn2.style.margin = '10px 10px 0px';
        closeBtn2.style.color = 'red';
        closeBtn2.innerText = ' 닫 기 ';
    div.appendChild(closeBtn2);

    // 닫기 이벤트 처리
    [closeBtn1,closeBtn2].forEach( (elem) => { 
        elem.addEventListener('click', (e) => {
            div.style.display = 'none';
            closeBtn1.remove();
        })
    });
}

// idPath 처리 및 포커스 동작
function idPathFocusEventHandler(e) {

    // 기존 요소들 색깔로 원래 환원
    const bunryuElems = this.closest('div').querySelectorAll('span.idPathFocusEvent');
    if(bunryuElems) bunryuElems.forEach( elem => { elem.style.color = ''; });
    // 선택된 요소 만 빨간색
    this.style.color = 'red';

    // olStart를 기준으로, idpath
    const str = this.dataset.idpath;
    const idPath = str.split(',');
    const startElem = document.getElementById('bunryuStart');
    asynctodo(idPath, startElem);

}

// 비동기 동작을 마치 동기 동작 처럼 수행함
// olStart 요소 밑에, idpath 배열 [id1,id2,id3 등...]에 언급된 id 마다 차례로 open 시킴
// async function asynctodo (idPath, olStart) {
async function asynctodo (idPath, startElem) {

    // 기존 열려진 ol 요소들 모두 닫기 및 bullet 요소 화살표 방향 바꿈
    const openOlTreeAll = startElem.querySelectorAll('ol.tree');
        openOlTreeAll.forEach( elem => { elem.style.display = 'none'; });
    const openLiAll = startElem.querySelectorAll('a.bullet');
        openLiAll.forEach( elem => { elem.innerText = '▷'; });

    // idpath에 언급된 id 마다 차례로 open 시킴
    const ol = startElem.querySelector("ol[data-id='"+idPath[0]+"']");
    if(ol) {
        if(ol.style.display == 'none') ol.style.display = 'block';
    } else
        await fetchDataCreateOl(startElem); 

    let li;
    for(i=0; i < idPath.length; i++) {
        li = startElem.querySelector("li[data-id='"+idPath[i]+"']");
        if(!li) continue;
//console.log(li);
        let olTree = li.querySelector('ol.tree');
        if(olTree) {
            if(olTree.style.display == 'none') 
                olTree.style.display = 'block';
        } else {
            if(!(li.dataset.child <= 0))
                await fetchDataCreateOl(li);
        }

        let a = li.querySelector("a[data-id='"+idPath[i]+"']");
        if(a) {
            a.innerText = '▽';
            a.focus();
        }

    }
}


Copyrightⓒ written by 차재복 (Cha Jae Bok)
"본 웹사이트 내 모든 저작물은 원출처를 밝히는 한 자유롭게 사용(상업화포함) 가능합니다"