UNPKG

vuepress-playground

Version:
81 lines (73 loc) 2.73 kB
/* eslint-disable no-new */ import hashChangeHandler from './rewrite' import injectCss from './inject' import create from './create' import jsfiddle from './jsfiddle' import codepen from './codepen' import { toArray } from './utils' import { getDetail, getScriptObj } from './detail' import getSettings from './settings' import './style.less' hashChangeHandler(init) window.addEventListener('load', init) window.addEventListener('popstate', init) const classNames = { showlink: 'vuepress-playground-control-box-show-link', code: 'vuepress-playground-code-box', wrapper: 'vuepress-playground-wrapper', display: 'vuepress-playground-display-box', control: 'vuepress-playground-control-box', expand: 'vuepress-playground-expand-btn', btn: 'vuepress-playground-btn-text', expandText: 'vuepress-playground-expand-text' } function init () { const codeBoxs = toArray(document.querySelectorAll(`.${classNames.code}`)) codeBoxs.forEach(codeBox => { const codeSection = codeBox.querySelector('pre') const parent = codeBox.parentNode const wrapper = create('div', { className: classNames.wrapper }) const displayBox = create('div', { className: classNames.display }) const expandBox = create('button', { className: `${classNames.expand} ${classNames.btn}`, __children: [ { tag: 'span', attrs: { innerHTML: '展开', className: classNames.expandText } } ] }) const controlBox = create('div', { className: classNames.control }) const emptyBox = create('div') const height = codeSection.clientHeight const detail = getDetail(codeSection) injectCss(detail.css) let scriptObj = getScriptObj(detail) expandBox.dataset.isExpand = '0' controlBox.appendChild(expandBox) if (getSettings('jsfiddle')) { controlBox.appendChild(jsfiddle(detail)) } if (getSettings('codepen')) { controlBox.appendChild(codepen(detail)) } displayBox.appendChild(emptyBox) parent.insertBefore(wrapper, codeBox) wrapper.appendChild(displayBox) wrapper.appendChild(codeBox) wrapper.appendChild(controlBox) new window.Vue(Object.assign({ el: emptyBox }, scriptObj)) expandBox.addEventListener('click', _ => { const isExpand = expandBox.dataset.isExpand === '0' const expandText = expandBox.querySelector(`.${classNames.expandText}`) expandText.innerHTML = isExpand ? '关闭' : '展开' codeBox.style.height = isExpand ? `${height}px` : 0 if (isExpand) { controlBox.classList.add(classNames.showlink) } else { controlBox.classList.remove(classNames.showlink) } expandBox.dataset.isExpand = isExpand ? '1' : '0' }) }) }