WaniKani Quick Type

Speed up your your lessons: Check and accept answers for meanings after a minimal amount of typed characters.

2024-06-23 या दिनांकाला. सर्वात नवीन आवृत्ती पाहा.

// ==UserScript==
// @name         WaniKani Quick Type
// @namespace    wkquicktype
// @description  Speed up your your lessons: Check and accept answers for meanings after a minimal amount of typed characters.
// @match        https://www.wanikani.com/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=wanikani.com
// @version      1.0.0
// @author       polysoda
// @license      MIT; http://opensource.org/licenses/MIT
// @run-at       document-end
// @grant        none
// @require      https://cdnjs.cloudflare.com/ajax/libs/toastify-js/1.6.1/toastify.css
// ==/UserScript==

/* jshint esversion: 8 */

(async function (wkItemInfo, wkof) {
  'use strict';

  if (!wkof) {
    alert("WK Autocomplete requires Wanikani Open Framework." +
      "You will now be forwarded to installation instructions.");
    window.location.href = "https://community.wanikani.com/t/" +
      "instructions-installing-wanikani-open-framework/28549";
    return;
  } else {
    wkof.include('Menu, Settings');
    wkof.ready('Menu, Settings')
      .then(load_settings)
      .then(install_menu)
  }
  
  const inputClass = ".quiz-input__input";
  const inputElement = document.querySelector(inputClass);
  const enterEvent = new KeyboardEvent("keydown", {
    key: "Enter",
    code: "Enter",
    which: 13,
    keyCode: 13,
    bubbles: true,
    cancelable: true,
  });
  let id;
  let lessonType;
  let essentialMeanings;
  // settings vars
  let maxMeaningsCount = 8;
  let maxCharCount = 3;
  let enableToast = true;
  let toastLocation = "Top";
  let useSpaceEscape = true;

  // load assets (toastify css)
  const css = 'https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.css';
  let promises = [];
  promises[0] = wkof.load_css(css, true /* use_cache */);
  Promise.all(promises);

  if (inputElement === null) return;

  window.addEventListener("willShowNextQuestion", (e) => {
    console.log("Event:  willShowNextQuestion");
      setTimeout(setEssentialMeanings, 500);
  });

  inputElement.addEventListener('keydown', event => {
    setTimeout(function () {
      let inputValue = inputElement.value;
      if (!useSpaceEscape){
        inputValue = inputValue.replace(/^\s?/, '');
      }
      const inputCharCount = inputValue.length;
      if (lessonType !== "meaning") return;
      if (inputCharCount >= maxCharCount) {
        event.preventDefault();
        const essentialMeaning = getMatchingMeaning(inputValue, essentialMeanings);
        if (essentialMeaning !== null) {
          inputElement.value = essentialMeaning;
          if(enableToast && inputCharCount == maxCharCount && essentialMeaning !== maxCharCount){
            showToast(String("👍 " +  inputValue + " → " + essentialMeaning));
          }
          inputElement.dispatchEvent(enterEvent);
        }
      }
    }, 150);
  });

  function setEssentialMeanings() {
    id = wkItemInfo.currentState.id;
    const synonyms = getSynonymsById(id);
    const meanings = wkItemInfo.currentState.meaning;
    lessonType = wkItemInfo.currentState.under[0];
    essentialMeanings = combineArrays(synonyms, meanings, maxMeaningsCount);
  }

  function getMatchingMeaning(prefix, stringArray) {
    if (stringArray == null || prefix == null) {
      return null;
    }

    function normalizeUmlauts(str) {
      return str
        .replace(/ä/g, 'ae')
        .replace(/ü/g, 'ue')
        .replace(/ö/g, 'oe')
        .replace(/ß/g, 'ss')
        .toLowerCase();
    }

    const normalizedPrefix = normalizeUmlauts(prefix.toLowerCase());

    for (let item of stringArray) {
      const normalizedItem = normalizeUmlauts(item.toLowerCase());
      if (normalizedItem.startsWith(normalizedPrefix)) {
        return item;
      }
    }
    return null;
  }


  function getSynonymsById(id) {
    const scriptTag = document.querySelector('script[data-quiz-user-synonyms-target="synonyms"]');
    if (scriptTag) {
      const synonymsData = JSON.parse(scriptTag.textContent);
      return synonymsData[id] || [];
    } else {
      console.error('The script tag with the specified type and data attribute was not found.');
      return [];
    }
  }

  function combineArrays(array1, array2, x) {
    const firstPart = array1.slice(0, x);
    const secondPart = array2.slice(0, x);
    const combinedArray = [...firstPart, ...secondPart];
    return combinedArray;
  }

  function showToast(text) {
    toastLocation = toastLocation.toLowerCase();
    Toastify({
      text: text,
      duration: 2000,
      close: false,
      gravity: toastLocation, // `top` or `bottom`
      position: "center", // `left`, `center` or `right`
      stopOnFocus: true, // Prevents dismissing of toast on hover
      style: {
        background: "linear-gradient(339deg, rgba(0,185,155,1) 0%, rgba(23,218,157,1) 100%)",
        fontSize: "12px",
        fontWeight: "bold",
        borderRadius: "8px",
        color: "#fff"
      }
    }).showToast();
  }

  appendStyleElem();
  function appendStyleElem() {
    const styleElem = document.createElement("style");
    styleElem.innerHTML = `
      .demo-style {
      }
      `;
    document.head.append(styleElem);
  }

  // ––––––– Settings ––––––– //
  // This function is called when the Settings module is ready to use.
  function load_settings() {
    let defaults = {
      maxMeaningsCount: 8,
      maxCharCount: 3
    };
    wkof.Settings.load('wanikaniQuickType', defaults)
      .then(update_settings);
  }

  // Add settings menu to the menu
  function install_menu() {
    let config = {
      name: 'wanikaniQuickType',
      submenu: 'Settings',
      title: 'Quick Type',
      on_click: open_settings
    };
    wkof.Menu.insert_script_link(config);
  }

  // Define settings menu layout
  function open_settings(items) {
    let config = {
      script_id: 'wanikaniQuickType',
      title: 'Quick Type',
      on_save: update_settings,
      on_close: update_settings,
      content: {
        maxCharCount: {
          type: 'number',
          label: "Character count",
          hover_tip: "The amount of typed characters after which the check of the meanings is started.",
          default: 3,
          min: 1,
          max: 10
        },
        maxMeaningsCount: {
          type: 'number',
          label: "Meanings count",
          hover_tip: "The count of synonyms and meanings items to include in check of the meanings",
          default: 8,
          min: 1,
          max: 8
        },
        enableToast: {
          type: 'checkbox',
          label:          "Enable notification with meaning info",
          hover_tip:      "A quick info will be shown with the matched meaning based on the short input.",
          default:        true
        },
        toastLocation: {
          type: 'dropdown',
          label:          "Notifiocation location",
          hover_tip:      "The location of the info toast.",
          default:        "Top",
          content: {
              top: "Top",
              bottom: "Bottom",
          }
      },
        useSpaceEscape: {
          type: 'checkbox',
          label:          "Disable with leading space",
          hover_tip:      "Type a space charakter at the beginning to temporarily disable Quick Type",
          default:        true
        }
      }
    }
    let dialog = new wkof.Settings(config);
    dialog.open();
  }

  function update_settings(settings) {
    maxMeaningsCount = settings.maxMeaningsCount;
    maxCharCount = settings.maxCharCount;
    enableToast = settings.enableToast;
    toastLocation = settings.toastLocation;
    useSpaceEscape = settings.useSpaceEscape;
    wkof.Settings.save("wanikaniQuickType");
  }

})(window.wkItemInfo, window.wkof);