코드 정리/코드 정리 - Tistory

코드 블럭 수정(mac 형태) + 복사

분석가 황규진 2024. 7. 5. 14:11

JS 생성 부분

JS 파일을 스킨 편집 - 파일 업로드 - 추가를 이용하여 업로드 하시면 됩니다.

const COPY_TEXT_CHANGE_OFFSET = 1500;
const COPY_ERROR_MESSAGE = "코드를 복사할 수 없습니다. 다시 시도해 주세요.";
const COPY_ICON = `
  <svg width="14" height="14" fill="currentColor" class="icon" viewBox="0 0 16 16">
    <path fill-rule="evenodd" d="M4 2a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2zm2-1a1 1 0 0 0-1 1v8a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1V2a1 1 0 0 0-1-1zM2 5a1 1 0 0 0-1 1v8a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1v-1h1v1a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h1v1z"/>
  </svg>`;
const CHECK_ICON = `<span class="copied-text">Copied!</span>`;

const func = () => {
    const codeBlocks = document.querySelectorAll("pre > code");

    // 복사 Function
    const copyBlockCode = async (target) => {
        if (!target) return;
        try {
            const code = decodeURI(target.dataset.code);
            await navigator.clipboard.writeText(code);
            target.innerHTML = CHECK_ICON;
            setTimeout(() => {
                target.innerHTML = COPY_ICON;
            }, COPY_TEXT_CHANGE_OFFSET);
        } catch (error) {
            alert(COPY_ERROR_MESSAGE);
            console.error(error);
        }
    };

    // 코드 블럭 생성 및 복사 버튼 삽입
    for (const codeBlock of codeBlocks) {
        console.log("test3");
        const data_ke_language = codeBlock.parentElement.getAttribute("data-ke-language") || "";
        const codes = codeBlock.innerHTML.match(/(.*)(\n|.*$)/g).filter(Boolean);
        const processedCodes = codes.reduce((prev, cur) => prev + `<div class="line">${cur}</div>`, "");

        const copyButtonHTML = `<button type="button" class="copy-btn" data-code="${encodeURI(
            codeBlock.textContent
        )}">${COPY_ICON}</button>`;
        const codeBody = `<div class="code-body">${processedCodes}</div>`;
        const codeHeader = `
    <div class="code-header">
      <span class="red btn"></span>
      <span class="yellow btn"></span>
      <span class="green btn"></span>
      <span class="language-label">${data_ke_language}</span>
      ${copyButtonHTML}
    </div>`;

        codeBlock.innerHTML = codeHeader + codeBody;
    }

    // 복사 버튼에 이벤트 리스너 연결
    const copyButtons = document.querySelectorAll(".copy-btn");
    copyButtons.forEach((button) => {
        button.addEventListener("click", () => copyBlockCode(button));
    });
};

// 랜더링 전 자바스크립트 실행을 막기 위함
window.addEventListener("load", () => {
    func();
});

 

codeblock.js
0.00MB

 

 

 

 

CSS 부분

CSS 파일의 내용을 복사하여 스킨 편집 - CSS에 추가하시면 됩니다.

/* 웹 폰트는 CSS 파일 가장 위에 적기 */
@font-face {
    font-family: "D2Coding";
    src: url("https://fastly.jsdelivr.net/gh/projectnoonnu/noonfonts_three@1.0/D2Coding.woff") format("woff");
    font-weight: normal;
    font-style: normal;
}

/* 코드블럭 CSS Start */
pre {
    position: relative;
}

.hljs {
    display: flex !important;
    flex-direction: column;
    padding: 0 !important;
    font-size: 14px;
    border-radius: 8px;
    box-shadow: 0 12px 24px rgb(0 0 0 / 40%);
    color: #cfd2d1;
    background-color: #343131;
    font-family: D2Coding, Menlo, Courier, monospace;
}

.hljs .language-label {
    margin-left: 10px;
    flex-grow: 1;
    align-self: center;
    font-weight: bold;
    text-transform: capitalize;
    display: flex;
    align-items: center;
    line-height: 1;
    padding-top: 1px;
}

.hljs .line {
    counter-increment: line-idx;
    line-height: 1.5;
    white-space: pre;
}

.hljs .line::before {
    content: counter(line-idx);
    display: inline-block;
    width: 24px;
    margin-right: 16px;
    text-align: right;
    font-size: 0.8rem;
    color: #747a7a;
}

/* 마우스 hover 시 하이라이트 - 쓸 사람은 주석 해제하시길 */
/* .hljs .line:hover {
  background-color: #262830;
}
.hljs .line:hover::before {
  color: #cfd2d1;
} */

.hljs .code-header {
    display: flex;
    align-items: center;
    padding: 14px;
    background-color: #434041;
    border-radius: 8px 8px 0 0;
}

.hljs .code-header .btn {
    width: 15px;
    height: 15px;
    margin: 0 5px;
    border-radius: 50%;
}

.hljs .code-header .btn.red {
    background-color: #f5655b;
}

.hljs .code-header .btn.yellow {
    background-color: #f6bd3b;
}

.hljs .code-header .btn.green {
    background-color: #43c645;
}

.hljs .code-body {
    max-height: 1000px;
    margin: 8px;
    overflow: auto;
    padding-bottom: 10px;
}

.hljs .code-body::-webkit-scrollbar {
    width: 6px;
    height: 6px;
}

.hljs .code-body::-webkit-scrollbar-thumb {
    background-color: rgb(92 90 90);
    border-radius: 4px;
}

.hljs .code-body::-webkit-scrollbar-corner {
    display: none;
}

.hljs .copy-btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    margin-left: auto;
    padding: 0px 12px;
    height: 32px;
    line-height: 1;
    font-size: 12px;
    font-weight: normal;
    color: #fff;
    background-color: #ffffff17;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    white-space: nowrap;
    transition: all 0.3s ease;
}

.hljs .copy-btn:hover {
    background-color: #ffffff30;
}

.copied-text {
    font-size: 12px;
    font-weight: bold;
    display: inline-block;
    vertical-align: middle;
    line-height: 1;
}
/* 코드블럭 CSS End */

 

codeblock.css
0.00MB

 

 

 

 

HTML 부분

HTML 내용을 복사하여 스킨 편집 - HTML 맨 아래에 형식에 맞춰 추가하시면 됩니다.

	</body>
	<script defer src="./images/codeblock.js"></script>
</html>

 


참고

 

2. [hELLO 스킨] 코드 블럭의 테마, 폰트 설정 및 커스터마이징

안녕하세요, 레오입니다. 스킨을 새로운 버전으로 업데이트를 했으니, 이제부터 본격적으로 스킨을 커스터마이징 해보겠습니다. 제가 가장 먼저 수정해야겠다고 마음 먹은 부분은 개발자들이

jake8440.tistory.com