Koki's personal blog

Koki's personal blog

Another fine, responsive site template by HTML5 UP.

Hugoブログのコードブロックにコピーボタンを追加する方法

Hugoで作成したブログのコードブロックにコピーボタンを追加する方法を説明します。

Koki

2 分で読めます

この記事では、Hugoで作成したブログのコードブロックにコピーボタンを追加する方法を説明します。

この記事の内容です。

対象読者

  • Hugoで作成したブログのコードブロックにコピーボタンを追加したい方

環境

  • Hugo 0.57.2
  • Hugo-extended 0.58.2

前提条件

  • HugoおよびHugo-entendedインストール済み

コードブロックへコピーボタンを追加

JavaScriptのコードを追加

下記のコードをstatic/js/add-on.jsへ追加します。
今回、即時関数を使用しているのは、今後機能を追加することを考えると変数のスコープ範囲を広げたくなかったからです。

(() => {
  'use strict';

  if(!document.queryCommandSupported('copy')) {
    return;
  }

  function flashCopyMessage(el, msg) {
    el.textContent = msg;
    setTimeout(() => {
      el.textContent = "Copy";
    }, 1000);
  }

  function selectText(node) {
    let selection = window.getSelection();
    let range = document.createRange();
    if (node.childElementCount === 2) {
      // Skip the title.
      range.selectNodeContents(node.children[1]);
    } else {
      range.selectNodeContents(node);
    }
    selection.removeAllRanges();
    selection.addRange(range);
    return selection;
  }

  function addCopyButton(containerEl) {
    let copyBtn = document.createElement("button");
    copyBtn.className = "highlight-copy-btn";
    copyBtn.textContent = "Copy";

    let codeEl = containerEl.firstElementChild;
    copyBtn.addEventListener('click', () => {
      try {
        let selection = selectText(codeEl);
        document.execCommand('copy');
        selection.removeAllRanges();

        flashCopyMessage(copyBtn, 'Copied!')
      } catch(e) {
        console && console.log(e);
        flashCopyMessage(copyBtn, 'Failed :\'(')
      }
    });

    containerEl.appendChild(copyBtn);
  }

  // Add copy button to code blocks
  let highlightBlocks = document.getElementsByClassName('highlight');
  Array.prototype.forEach.call(highlightBlocks, addCopyButton);
})();

CSSのコードを追加

下記のコードをstatic/css/add-on.cssへ追加します。

.highlight {
    position: relative;
}
.highlight pre {
    padding-right: 75px;
}
.highlight-copy-btn {
    position: absolute;
    bottom: 7px;
    right: 7px;
    border: 0;
    border-radius: 4px;
    padding: 1px;
    font-size: 0.7em;
    line-height: 1.8;
    color: #fff;
    background-color: #777;
    min-width: 55px;
    text-align: center;
}
.highlight-copy-btn:hover {
    background-color: #666;
}

以上です!

参考にさせていただいたページ

最近の投稿

カテゴリー