미디어위키:Gadget-dictionary.js: 두 판 사이의 차이

편집 요약 없음
편집 요약 없음
 
(같은 사용자의 중간 판 31개는 보이지 않습니다)
1번째 줄: 1번째 줄:
/* ▣ Dictionary gadget
/* ▣ Dictionary “검색 전용” 가젯
   ─ 검색창 + 버튼/Enter
   - 표 없이: 검색 → 결과 카드 or “없음” 메시지
  ─ 완전 일치 카드형 결과
   - 단어(키)에 들어 있는 위키문법을 실제로 렌더링
   ─ 미일치 → “단어가 없습니다” 한 줄
-------------------------------------------------- */
-------------------------------------------------- */
mw.loader.using(
mw.loader.using(
   ['oojs-ui-core', 'oojs-ui.styles.icons-interactions'],
   ['oojs-ui-core', 'oojs-ui.styles.icons-interactions', 'mediawiki.api'],
   function () {
   function () {


     /* Ⅰ. 사전 JSON을 메모리에 로드 (소문자 키) */
     /* ────────── Ⅰ. 사전 JSON 로드 ────────── */
     var dataNode  = document.getElementById('dictionary-json');
     var jsonNode = document.getElementById('dictionary-json');
     var dict      = dataNode ? JSON.parse(dataNode.textContent) : {};
    if (!jsonNode) return;                        // 사전 없는 페이지
     var dictLower  = {};
     var dictRaw  = JSON.parse(jsonNode.textContent);
     Object.keys(dict).forEach(function (k) {
     var dict    = {};                           // 소문자+정규화 키 → {rawKey, def}
       dictLower[k.toLowerCase()] = dict[k];
 
     Object.keys(dictRaw).forEach(function (k) {
       const normKey = k.normalize('NFC').toLowerCase();  // ★ 정규화 추가
      dict[normKey] = { raw: k, def: dictRaw[k] };
     });
     });


     /* Ⅱ. 한 번만 CSS 삽입 */
     /* ────────── Ⅱ. CSS 삽입(1회) ────────── */
     if (!document.getElementById('dict-card-style')) {
     if (!document.getElementById('dict-card-style')) {
       mw.util.addCSS(`
       mw.util.addCSS(`
         .dict-result-card {
.dictionary-container .oo-ui-inputWidget-input, .dictionary-container .oo-ui-buttonElement-button {
          padding: 12px 16px; border: 1px solid #ccc; border-radius: 8px;
background: var(--bg) !important;
          background: var(--background-color, #f9f9f9); margin: 8px 0;
color: var(--text) !important;
        }
border: 1px solid var(--border) !important;
         .dict-result-card .term {
height: 36px !important;
          font-weight: 600; font-size: 1.1em; margin-right: 0.4em;
}
        }
.oo-ui-inputWidget-input {
         .dict-no-match {
border-radius: 0.5rem 0 0 0.5rem !important;
          padding: 8px; color: #d33;
padding-left: 11px !important;
        }`).id = 'dict-card-style';
}
.oo-ui-buttonElement-button {
border-radius: 0 0.5rem 0.5rem 0 !important;
padding-top: 6px;
padding-bottom: 6px;
}
         .dict-card   {padding:20px 20px 8px !important; border:1px solid light-dark(#ccc, #555);border-radius:0.8rem;margin: 1em 0 0.5em !important;
                      background:var(--altbg); padding-top: }
         .dict-card .term{font-weight:600;font-size:1.5em;margin-right:.4em; padding:8px; padding-bottom: 3px; margin-bottom: -15px; padding-top: 4px; }
.dict-card .def{padding-left:8px; padding-right:8px; margin-bottom: -3px;}
         .dict-none    {padding:8px;color:light-dark(#d33, HSL(0, 71%, 75%));}
      `).id = 'dict-card-style';
    }
 
    /* ────────── Ⅲ. 위키텍스트 → HTML 파서 헬퍼 ────────── */
    var api = new mw.Api();
    function parseWikitext(wikitext) {
      return api.get({
        action:  'parse',
        format:  'json',
        contentmodel: 'wikitext',
        prop:    'text',
        text:    wikitext,
        disablelimitreport: 1,
        disableeditsection: 1,
        pst: 0, wrapshtml: 1
      }).then(function (data) {
        return (data.parse && data.parse.text) ? data.parse.text['*'] : mw.html.escape(wikitext);
      });
     }
     }


     /* . 페이지(또는 Ajax 미리보기)가 로드될 때마다 */
     /* ────────── Ⅳ. 페이지 로드 때 UI 주입 ────────── */
     mw.hook('wikipage.content').add(function ($content) {
     mw.hook('wikipage.content').add(function ($content) {
      $content.find('.dictionary-container').each(function () {
        var $box = $(this);
        if ($box.children().length) return;      // 이미 UI가 있음


      var $table = $content.find('.mw-dictionary').first();
        /* 1) 검색창 + 버튼 */
      if (!$table.length) return;
        var input  = new OO.ui.TextInputWidget({ placeholder: '단어 입력…', icons:['search'] });
      if ($table.prev('.dict-search-wrapper').length) return;   // 이미 처리된 페이지
        var button = new OO.ui.ButtonWidget({ label:'검색', icon:'search', flags:['progressive'] });
        var field  = new OO.ui.ActionFieldLayout(input, button, {align:'top'})
                    .$element.css('margin-bottom','10px');


      /* 1) 검색창 + 버튼 */
        /* 2) 결과 영역 */
      var input  = new OO.ui.TextInputWidget({
        var $result = $('<div class="dict-result"></div>');
        placeholder: '단어 입력…',
         $box.append(field, $result);
         icons: ['search']
 
      });
         /* 3) 검색 실행 – 단어·뜻 모두 위키텍스트 → HTML */
      var button = new OO.ui.ButtonWidget({
        function run() {
         label: '검색', icon: 'search', flags: ['progressive']
          const qRaw = input.getValue().trim();
      });
          const q    = qRaw.normalize('NFC');        // ★ 정규화 추가
      var field = new OO.ui.ActionFieldLayout(input, button, {align: 'top'})
          const keyL  = q.toLowerCase();
                  .$element.addClass('dict-search-wrapper')
 
                  .css('margin-bottom', '10px');
          if (!qRaw) {                    // 검색어 비우면 결과 초기화
      $table.before(field);
            $result.empty();
            return;
          }


      /* 2) 결과 행 2종 (카드 / 없음) ─ 처음에는 숨김 */
          if (dict.hasOwnProperty(keyL)) {
      var $cardRow = $('<tr class="dict-row-card" style="display:none"><td colspan="2"></td></tr>');
            const entry = dict[keyL];
      var $noneRow = $('<tr class="dict-row-none" style="display:none"><td colspan="2" class="dict-no-match">해당 단어가 없습니다.</td></tr>');
      var $tbody  = $table;                // Lua 모듈이 <tbody> 없이 직접 <tr> 나열했음
      $tbody.find('tr').first().after($cardRow, $noneRow);  // 헤더 바로 뒤 삽입
      var $cardCell = $cardRow.children('td');


      /* 3) 검색 로직 */
            Promise.all([
      function apply() {
              parseWikitext(entry.raw),  // ① 단어
        var key  = input.getValue().trim();
              parseWikitext(entry.def)   // ② 정의
        var lower = key.toLowerCase();
            ]).then(function (parts) {
              const htmlKey = parts[0], htmlDef = parts[1];


        /* 입력 없으면 표 리셋 */
              $result.html(
        if (!key) {
                '<div class="term">' + htmlKey + '</div>' +
          $cardRow.hide(); $noneRow.hide();
                '<div class="def">'  + htmlDef + '</div>'
          $table.find('tr').not('.dict-row-card, .dict-row-none').show();
              );
          return;
            }).catch(function () {
        }
              $result.html(
                '<div class="term">' + mw.html.escape(entry.raw) + '</div>' +
                '<div class="def">'  + mw.html.escape(entry.def) + '</div>'
              );
            });


        /* 완전 일치 */
          } else {
        if (dictLower.hasOwnProperty(lower)) {
            $result.html('<div class="dict-none">해당 단어가 없습니다.</div>');
          var defi = mw.html.escape(dictLower[lower]);
           }
          $cardCell.html(
            '<div class="dict-result-card">' +
              '<span class="term">' + mw.html.escape(key) + '</span>' +
              '<span class="def">'  + defi + '</span>' +
            '</div>'
          );
          $cardRow.show();  $noneRow.hide();
           $table.find('tr').not('.dict-row-card, .dict-row-none').not(':has(th)').hide();
          return;
         }
         }


         /* 미일치 */
         button.on('click', run);
        $cardRow.hide();
        input.on('enter', run);
        $noneRow.show();
      });
        $table.find('tr').not('.dict-row-card, .dict-row-none').not(':has(th)').hide();
      }
 
      /* 4) 이벤트 연결 */
      button.on('click', apply);
      input.on('enter', apply);
     });
     });
   }
   }
);
);

2026년 1월 25일 (일) 05:02 기준 최신판

/* ▣ Dictionary “검색 전용” 가젯 ▣
   - 표 없이: 검색 → 결과 카드 or “없음” 메시지
   - 단어(키)에 들어 있는 위키문법을 실제로 렌더링
-------------------------------------------------- */
mw.loader.using(
  ['oojs-ui-core', 'oojs-ui.styles.icons-interactions', 'mediawiki.api'],
  function () {

    /* ────────── Ⅰ. 사전 JSON 로드 ────────── */
    var jsonNode = document.getElementById('dictionary-json');
    if (!jsonNode) return;                        // 사전 없는 페이지
    var dictRaw  = JSON.parse(jsonNode.textContent);
    var dict     = {};                            // 소문자+정규화 키 → {rawKey, def}

    Object.keys(dictRaw).forEach(function (k) {
      const normKey = k.normalize('NFC').toLowerCase();   // ★ 정규화 추가
      dict[normKey] = { raw: k, def: dictRaw[k] };
    });

    /* ────────── Ⅱ. CSS 삽입(1회) ────────── */
    if (!document.getElementById('dict-card-style')) {
      mw.util.addCSS(`
.dictionary-container .oo-ui-inputWidget-input, .dictionary-container .oo-ui-buttonElement-button {
background: var(--bg) !important;
color: var(--text) !important;
border: 1px solid var(--border) !important;
height: 36px !important;
}
.oo-ui-inputWidget-input {
border-radius: 0.5rem 0 0 0.5rem !important;
padding-left: 11px !important;
}
.oo-ui-buttonElement-button {
border-radius: 0 0.5rem 0.5rem 0 !important;
padding-top: 6px;
padding-bottom: 6px;
}
        .dict-card    {padding:20px 20px 8px !important; border:1px solid light-dark(#ccc, #555);border-radius:0.8rem;margin: 1em 0 0.5em !important;
                       background:var(--altbg); padding-top: }
        .dict-card .term{font-weight:600;font-size:1.5em;margin-right:.4em; padding:8px; padding-bottom: 3px; margin-bottom: -15px; padding-top: 4px; }
.dict-card .def{padding-left:8px; padding-right:8px; margin-bottom: -3px;}
        .dict-none    {padding:8px;color:light-dark(#d33, HSL(0, 71%, 75%));}
      `).id = 'dict-card-style';
    }

    /* ────────── Ⅲ. 위키텍스트 → HTML 파서 헬퍼 ────────── */
    var api = new mw.Api();
    function parseWikitext(wikitext) {
      return api.get({
        action:  'parse',
        format:  'json',
        contentmodel: 'wikitext',
        prop:    'text',
        text:    wikitext,
        disablelimitreport: 1,
        disableeditsection: 1,
        pst: 0, wrapshtml: 1
      }).then(function (data) {
        return (data.parse && data.parse.text) ? data.parse.text['*'] : mw.html.escape(wikitext);
      });
    }

    /* ────────── Ⅳ. 페이지 로드 때 UI 주입 ────────── */
    mw.hook('wikipage.content').add(function ($content) {
      $content.find('.dictionary-container').each(function () {
        var $box = $(this);
        if ($box.children().length) return;       // 이미 UI가 있음

        /* 1) 검색창 + 버튼 */
        var input  = new OO.ui.TextInputWidget({ placeholder: '단어 입력…', icons:['search'] });
        var button = new OO.ui.ButtonWidget({ label:'검색', icon:'search', flags:['progressive'] });
        var field  = new OO.ui.ActionFieldLayout(input, button, {align:'top'})
                     .$element.css('margin-bottom','10px');

        /* 2) 결과 영역 */
        var $result = $('<div class="dict-result"></div>');
        $box.append(field, $result);

        /* 3) 검색 실행 – 단어·뜻 모두 위키텍스트 → HTML */
        function run() {
          const qRaw  = input.getValue().trim();
          const q     = qRaw.normalize('NFC');        // ★ 정규화 추가
          const keyL  = q.toLowerCase();

          if (!qRaw) {                    // 검색어 비우면 결과 초기화
            $result.empty();
            return;
          }

          if (dict.hasOwnProperty(keyL)) {
            const entry = dict[keyL];

            Promise.all([
              parseWikitext(entry.raw),   // ① 단어
              parseWikitext(entry.def)    // ② 정의
            ]).then(function (parts) {
              const htmlKey = parts[0], htmlDef = parts[1];

              $result.html(
                '<div class="term">' + htmlKey + '</div>' +
                '<div class="def">'  + htmlDef + '</div>'
              );
            }).catch(function () {
              $result.html(
                '<div class="term">' + mw.html.escape(entry.raw) + '</div>' +
                '<div class="def">'  + mw.html.escape(entry.def) + '</div>'
              );
            });

          } else {
            $result.html('<div class="dict-none">해당 단어가 없습니다.</div>');
          }
        }

        button.on('click', run);
        input.on('enter', run);
      });
    });
  }
);