yomichan lookup history

15/02/2023, 20:13:58

当前为 2023-02-16 提交的版本,查看 最新版本

// ==UserScript==
// @name        yomichan lookup history
// @namespace   Violentmonkey Scripts
// @match       *://*/*
// @grant       none
// @grant       GM_getValue
// @grant       GM_setValue
// @version     3.0
// @license MIT
// @author      grumpythomas
// @description 15/02/2023, 20:13:58
// ==/UserScript==

const dbKey = 'yomichan-lookup-history';
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;

(function () {
  let data = getData() || initData();
  const host = window.location.host;
  if (host.indexOf('localhost') > -1 || host.indexOf('therealgrumpythomas') > -1) {
    let hydrateInterval = window.setInterval(() => {
      if (unsafeWindow.hydrate) {
        unsafeWindow.hydrate(data);
        unsafeWindow.clearInterval(hydrateInterval);
      }
    }, 100);
  }


  document.addEventListener('selectionchange', debounce(() => {
    if (!window.getSelection) {
      return;
    }

    const selectedText = window.getSelection()?.toString()?.trim();
    if (!selectedText?.length) {
      return;
    }

    data = insertRow(data, selectedText, document.title);
  }, 1500));
})();

function initData() {
  return {
    created: Date.now(),
    lookups: [],
    sources: []
  };
}

function getData() {
  const rawData = GM_getValue(dbKey);
  if (!rawData) {
    return;
  }

  rawData.sources = rawData.sources || [];
  return JSON.parse(rawData);
}

function insertRow(data, lookup, source) {
  const dbLookup = { text: lookup, created: Date.now(), timezone };
  let dbSourceId = data.sources.findIndex(s => s.label === source);
  if (dbSourceId === -1) {
    dbSourceId = data.sources.push({ label: source })
  }

  dbLookup.sourceId = dbSourceId;
  data.lookups.push(dbLookup);
  GM_setValue(dbKey, JSON.stringify(data));
  return data;
}

function debounce(func, timeout) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => { func.apply(this, args); }, timeout);
  };
}