AtCoder copy button adder

AtCoderの問題文中の文字列にの横にコピーボタンを置きます。

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// ==UserScript==
// @name         AtCoder copy button adder
// @namespace    https://github.com/H20-DHMO
// @version      1.1
// @description  AtCoderの問題文中の文字列にの横にコピーボタンを置きます。
// @author       H20_dhmo
// @license      MIT
// @match        https://atcoder.jp/contests/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    // copy button
    function copyButton() {
        window.getSelection().removeAllRanges();
        try {
            const targetId = $(this).data('target');
            const text = $('#' + targetId).text();
            navigator.clipboard.writeText(text).then(() => {
                $(this).tooltip('show');
                $(this).blur();
                setTimeout(() => { $(this).tooltip('hide'); }, 800);
            });
        } catch (err) {
            console.log(err);
        }
        window.getSelection().removeAllRanges();
    }


    function addCopyButton(element) {
        // コピー用のボタン(span要素)を作成
        const uuid = self.crypto.randomUUID();
        element.setAttribute('id', uuid);

        const copyBtn = $(`<span class="btn btn-default btn-xs btn-copy ml-1" tabindex="0" data-toggle="tooltip" data-trigger="manual" title="Copied!" data-target="${uuid}">Copy</span>`);
        $(element).after(copyBtn);
        copyBtn.click(copyButton);
    }

    // 問題内の<code>要素を取得
    const codes = document.querySelectorAll('#task-statement .part code');
    codes.forEach(function(elm) {
        addCopyButton(elm);
    });

})();