Greasy Fork

中英文之间加空白

自动替你在网页中所有的中文字和半形的英文、数字、符号之间插入空白,让文字变得美观好看。

当前为 2023-07-15 提交的版本,查看 最新版本

// ==UserScript==
// @name                中英文之间加空白
// @name:zh-TW          中英文之間加空白

// @version             0.1.2
// @author              CY Fung
// @namespace           UserScript
// @license             MIT
// @require             https://cdn.jsdelivr.net/gh/cyfung1031/pangu.js@ffd0d877c53e207f9545a8ed782065fa302a781f/dist/web/pangu.js

// @match               http://*/*
// @match               https://*/*
// @exclude             /^https?://\S+\.(txt|png|jpg|jpeg|gif|xml|svg|manifest|log|ini)[^\/]*$/
// @exclude             /^https://www.google\..+tbm=isch/
// @exclude             https://translate.google.*
// @exclude             https://www.bilibili.com/video/*

// @grant               GM_setValue
// @run-at              document-end
// @allFrames           true
// @inject-into         content

// @description         自动替你在网页中所有的中文字和半形的英文、数字、符号之间插入空白,让文字变得美观好看。
// @description:zh-TW   自動替你在網頁中所有的中文字和半形的英文、數字、符號之間插入空白,讓文字變得美觀好看。

// ==/UserScript==


((__CONTEXT__) => {

  const { Promise, requestAnimationFrame } = __CONTEXT__;


  class Mutex {

    constructor() {
      this.p = Promise.resolve()
    }

    lockWith(f) {
      this.p = this.p.then(() => new Promise(f).catch(console.warn))
    }

  }

  let busy = false;

  const mutex = new Mutex();

  const pending = [];

  function executor(f) {
    mutex.lockWith(unlock => {
      if (busy) {
        unlock();
        return;
      }
      busy = true;
      Promise.resolve().then(() => {
        f();
      }).then(() => {
        busy = false;
      }).then(unlock);
    });
  }

  document.addEventListener('DOMNodeInserted', function (e) {
    if (!busy) {
      pending.push(e.target)
    }
  }, { capture: false, passive: true });

  function f77() {

    executor(() => {
      if (pending.length >= 1) {
        const arr = pending.slice(0);
        pending.length = 0;
        pangu.spacingPageTitle();
        for (const s of arr) (s.isConnected === true) && pangu.spacingNode(s);
      }
    });

  }


  function main() {


    if (!document.body) {
      requestAnimationFrame(main);
      return;
    }


    executor(() => {

      pangu.spacingPageTitle();
      pangu.spacingPageBody();
    });

    let bodyDOM = document.body;

    let m33 = 0;
    const observer = new MutationObserver(async (mutations) => {
      f77();
      if (m33++ > 1e9) m33 = 9;
      let tid = m33;
      await new Promise(requestAnimationFrame);
      if (tid !== m33) return;
      let tmp = document.body;
      if (tmp != bodyDOM) {
        bodyDOM = tmp;
        observer.takeRecords();
        observer.disconnect();
        observer.observe(bodyDOM, config);
        f77();
      }

    });
    const config = {
      childList: true,
      subtree: true
    };
    observer.observe(bodyDOM, config);
    f77();

  }
  main();





})({ Promise, requestAnimationFrame });