Clip-to-Gist

One-click clipboard quote → GitHub Gist, with keyword highlighting and versioning

当前为 2025-05-03 提交的版本,查看 最新版本

您需要先安装一个扩展,例如 篡改猴Greasemonkey暴力猴,之后才能安装此脚本。

You will need to install an extension such as Tampermonkey to install this script.

您需要先安装一个扩展,例如 篡改猴暴力猴,之后才能安装此脚本。

您需要先安装一个扩展,例如 篡改猴Userscripts ,之后才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey,才能安装此脚本。

您需要先安装用户脚本管理器扩展后才能安装此脚本。

(我已经安装了用户脚本管理器,让我安装!)

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

(我已经安装了用户样式管理器,让我安装!)

// ==UserScript==
// @name         Clip-to-Gist
// @name:zh-CN   Clip-to-Gist 金句剪贴脚本(v2.2)
// @namespace    https://github.com/yourusername
// @version      2.2
// @description  One-click clipboard quote → GitHub Gist, with keyword highlighting and versioning
// @description:zh-CN 一键剪贴板金句并上传至 GitHub Gist,支持关键词标注、高亮及版本号
// @author       Your Name
// @match        *://*/*
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_xmlhttpRequest
// @grant        GM_addStyle
// @grant        GM_registerMenuCommand
// @run-at       document-idle
// @license      MIT
// ==/UserScript==

(function() {
  'use strict';

  // 初始版本号,如果不存在则从 1 开始
  const VERSION_KEY = 'clip2gistVersion';
  if (GM_getValue(VERSION_KEY) == null) {
    GM_setValue(VERSION_KEY, 1);
  }

  // 注册菜单:配置 Gist 参数
  GM_registerMenuCommand('配置 Gist 参数', openConfigModal);

  // 注入触发按钮(兼容移动端)
  insertTrigger();

  // 全局样式
  GM_addStyle(`
    #clip2gist-trigger {
      position: fixed !important;
      bottom: 20px !important;
      right: 20px !important;
      width: 40px; height: 40px;
      line-height: 40px; text-align: center;
      background: #4CAF50; color: #fff;
      border-radius: 50%; cursor: pointer;
      z-index: 999999 !important;
      font-size: 24px;
      box-shadow: 0 2px 6px rgba(0,0,0,0.3);
    }
    .clip2gist-mask {
      position: fixed; inset: 0; background: rgba(0,0,0,0.5);
      display: flex; align-items: center; justify-content: center;
      z-index: 10000;
    }
    .clip2gist-dialog {
      background: #fff; padding: 20px; border-radius: 8px;
      max-width: 90%; max-height: 90%; overflow: auto;
      box-shadow: 0 2px 10px rgba(0,0,0,0.3);
    }
    .clip2gist-dialog input {
      width: 100%; padding: 6px; margin: 4px 0 12px;
      box-sizing: border-box; font-size: 14px;
    }
    .clip2gist-dialog button {
      margin-left: 8px; padding: 6px 12px; font-size: 14px;
      cursor: pointer;
    }
    .clip2gist-word {
      display: inline-block; margin: 2px; padding: 4px 6px;
      border: 1px solid #ccc; border-radius: 4px; cursor: pointer;
      user-select: none;
    }
    .clip2gist-word.selected {
      background: #ffeb3b; border-color: #f1c40f;
    }
    #clip2gist-preview {
      margin-top: 12px; padding: 8px; border: 1px solid #ddd;
      min-height: 40px; font-family: monospace;
    }
  `);

  // 主流程:读取剪贴板
  async function mainFlow() {
    let text = '';
    try {
      text = await navigator.clipboard.readText();
    } catch (e) {
      return alert('请在 HTTPS 环境并授权剪贴板访问');
    }
    if (!text.trim()) {
      return alert('剪贴板内容为空');
    }
    showEditDialog(text.trim());
  }

  // 弹出编辑 & 标注对话框
  function showEditDialog(rawText) {
    const mask = document.createElement('div');
    mask.className = 'clip2gist-mask';
    const dlg = document.createElement('div');
    dlg.className = 'clip2gist-dialog';

    // 词块化区域
    const wordContainer = document.createElement('div');
    rawText.split(/\s+/).forEach(w => {
      const sp = document.createElement('span');
      sp.className = 'clip2gist-word';
      sp.textContent = w;
      sp.addEventListener('click', () => {
        sp.classList.toggle('selected');
        updatePreview();
      });
      wordContainer.appendChild(sp);
    });
    dlg.appendChild(wordContainer);

    // 预览区
    const preview = document.createElement('div');
    preview.id = 'clip2gist-preview';
    dlg.appendChild(preview);

    // 按钮行
    const btnRow = document.createElement('div');
    const cancelBtn = document.createElement('button');
    cancelBtn.textContent = '取消';
    cancelBtn.addEventListener('click', () => document.body.removeChild(mask));
    const configBtn = document.createElement('button');
    configBtn.textContent = '配置';
    configBtn.addEventListener('click', openConfigModal);
    const confirmBtn = document.createElement('button');
    confirmBtn.textContent = '确认';
    confirmBtn.addEventListener('click', onConfirm);
    btnRow.append(cancelBtn, configBtn, confirmBtn);
    dlg.appendChild(btnRow);

    mask.appendChild(dlg);
    document.body.appendChild(mask);

    updatePreview();

    // 更新预览:合并连续选中分组并加大括号
    function updatePreview() {
      const spans = Array.from(wordContainer.children);
      const final = [];
      for (let i = 0; i < spans.length;) {
        if (spans[i].classList.contains('selected')) {
          const group = [spans[i].textContent];
          let j = i + 1;
          while (j < spans.length && spans[j].classList.contains('selected')) {
            group.push(spans[j].textContent);
            j++;
          }
          final.push(`{${group.join(' ')}}`);
          i = j;
        } else {
          final.push(spans[i].textContent);
          i++;
        }
      }
      preview.textContent = final.join(' ');
    }

    // 确认并上传带版本号的内容到 Gist
    async function onConfirm() {
      const gistId = await GM_getValue('gistId');
      const token  = await GM_getValue('githubToken');
      if (!gistId || !token) {
        return alert('请先通过“配置 Gist 参数”填写 Gist ID 与 Token');
      }
      // 获取并增加版本号
      let ver = await GM_getValue(VERSION_KEY);
      const content = preview.textContent;
      // 格式:Version X
      const header = `版本 ${ver}`;
      // 拉取当前 Gist
      GM_xmlhttpRequest({
        method: 'GET',
        url: `https://api.github.com/gists/${gistId}`,
        headers: { Authorization: `token ${token}` },
        onload(resp1) {
          if (resp1.status !== 200) {
            return alert('拉取 Gist 失败:' + resp1.status);
          }
          const data = JSON.parse(resp1.responseText);
          const fname = Object.keys(data.files)[0];
          const old   = data.files[fname].content;
          // 插入一个分隔线 + 版本号 + 内容 + 旧内容
          const updated = `\n\n----\n${header}\n${content}` + old;
          // 更新 Gist
          GM_xmlhttpRequest({
            method: 'PATCH',
            url: `https://api.github.com/gists/${gistId}`,
            headers: {
              Authorization: `token ${token}`,
              'Content-Type': 'application/json'
            },
            data: JSON.stringify({ files: { [fname]: { content: updated } } }),
            onload(resp2) {
              if (resp2.status === 200) {
                alert(`上传成功 🎉,已发布版本 ${ver}`);
                GM_setValue(VERSION_KEY, ver + 1);
                document.body.removeChild(mask);
              } else {
                alert('上传失败:' + resp2.status);
              }
            }
          });
        }
      });
    }
  }

  // 弹出一次性填写 Gist ID & Token 的对话框
  function openConfigModal() {
    const mask = document.createElement('div');
    mask.className = 'clip2gist-mask';
    const dlg = document.createElement('div');
    dlg.className = 'clip2gist-dialog';

    const idLabel = document.createElement('label');
    idLabel.textContent = 'Gist ID:';
    const idInput = document.createElement('input');
    idInput.value = GM_getValue('gistId', '');

    const tkLabel = document.createElement('label');
    tkLabel.textContent = 'GitHub Token:';
    const tkInput = document.createElement('input');
    tkInput.value = GM_getValue('githubToken', '');

    dlg.append(idLabel, idInput, tkLabel, tkInput);

    const saveBtn = document.createElement('button');
    saveBtn.textContent = '保存';
    saveBtn.addEventListener('click', () => {
      GM_setValue('gistId', idInput.value.trim());
      GM_setValue('githubToken', tkInput.value.trim());
      alert('配置已保存');
      document.body.removeChild(mask);
    });

    const cancelBtn = document.createElement('button');
    cancelBtn.textContent = '取消';
    cancelBtn.addEventListener('click', () => document.body.removeChild(mask));

    dlg.append(saveBtn, cancelBtn);
    mask.appendChild(dlg);
    document.body.appendChild(mask);
  }

  // 延迟插入触发按钮,确保 body 已就绪
  function insertTrigger() {
    if (!document.body) {
      return setTimeout(insertTrigger, 100);
    }
    const trigger = document.createElement('div');
    trigger.id = 'clip2gist-trigger';
    trigger.textContent = '📝';
    trigger.addEventListener('click', mainFlow, false);
    document.body.appendChild(trigger);
  }

})();