File size: 2,122 Bytes
271613e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
466f65a
afaedf8
271613e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import Tool from '../DevTools/Tool'
import defSnippets from './defSnippets'
import $ from 'licia/$'
import each from 'licia/each'
import escape from 'licia/escape'
import map from 'licia/map'
import remove from 'licia/remove'
import evalCss from '../lib/evalCss'
import { classPrefix as c } from '../lib/util'

export default class Snippets extends Tool {
  constructor() {
    super()

    this._style = evalCss(require('./Snippets.scss'))

    this.name = 'snippets'
    this.displayName = 'γ‚Ήγƒ‹γƒšγƒƒγƒˆ'

    this._snippets = []
  }
  init($el) {
    super.init($el)

    this._bindEvent()
    this._addDefSnippets()
  }
  destroy() {
    super.destroy()

    evalCss.remove(this._style)
  }
  add(name, fn, desc) {
    this._snippets.push({ name, fn, desc })

    this._render()

    return this
  }
  remove(name) {
    remove(this._snippets, (snippet) => snippet.name === name)

    this._render()

    return this
  }
  run(name) {
    const snippets = this._snippets

    for (let i = 0, len = snippets.length; i < len; i++) {
      if (snippets[i].name === name) this._run(i)
    }

    return this
  }
  clear() {
    this._snippets = []
    this._render()

    return this
  }
  _bindEvent() {
    const self = this

    this._$el.on('click', '.eruda-run', function () {
      const idx = $(this).data('idx')

      self._run(idx)
    })
  }
  _run(idx) {
    this._snippets[idx].fn.call(null)
  }
  _addDefSnippets() {
    each(defSnippets, (snippet) => {
      this.add(snippet.name, snippet.fn, snippet.desc)
    })
  }
  _render() {
    const html = map(this._snippets, (snippet, idx) => {
      return `<div class="${c('section run')}" data-idx="${idx}">
        <h2 class="${c('name')}">${escape(snippet.name)}
          <div class="${c('btn')}">
            <span class="${c('icon-play')}"></span>
          </div>
        </h2>
        <div class="${c('description')}">
          ${escape(snippet.desc)}
        </div>
      </div>`
    }).join('')

    this._renderHtml(html)
  }
  _renderHtml(html) {
    if (html === this._lastHtml) return
    this._lastHtml = html
    this._$el.html(html)
  }
}