forked from jejacks0n/mercury
/
snippet.js.coffee
106 lines (81 loc) · 2.52 KB
/
snippet.js.coffee
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
102
103
104
105
106
class @Mercury.Snippet
@all: []
@displayOptionsFor: (name) ->
Mercury.modal Mercury.config.snippets.optionsUrl.replace(':name', name), {
title: 'Snippet Options'
handler: 'insertSnippet'
snippetName: name
}
Mercury.snippet = null
@create: (name, options) ->
if @all.length > 0
identity = "snippet_0"
for snippet, i in @all
identity = "snippet_#{i+1}" if snippet.identity == identity
else
identity = "snippet_#{@all.length}"
instance = new Mercury.Snippet(name, identity, options)
@all.push(instance)
return instance
@find: (identity) ->
for snippet in @all
return snippet if snippet.identity == identity
return null
@load: (snippets) ->
for own identity, details of snippets
instance = new Mercury.Snippet(details.name, identity, details.options)
@all.push(instance)
constructor: (@name, @identity, options = {}) ->
@version = 0
@data = ''
@history = new Mercury.HistoryBuffer()
@setOptions(options)
getHTML: (context, callback = null) ->
element = jQuery('<div>', {
class: "mercury-snippet #{@name}-snippet"
contenteditable: "false"
'data-snippet': @identity
'data-version': @version
}, context)
element.html("[#{@identity}]")
@loadPreview(element, callback)
return element
getText: (callback) ->
return "[--#{@identity}--]"
loadPreview: (element, callback = null) ->
jQuery.ajax Mercury.config.snippets.previewUrl.replace(':name', @name), {
headers: Mercury.ajaxHeaders()
type: Mercury.config.snippets.method
data: @options
success: (data) =>
@data = data
element.html(data)
callback() if callback
error: =>
Mercury.notify('Error loading the preview for the \"%s\" snippet.', @name)
}
displayOptions: ->
Mercury.snippet = @
Mercury.modal Mercury.config.snippets.optionsUrl.replace(':name', @name), {
title: 'Snippet Options',
handler: 'insertSnippet',
loadType: Mercury.config.snippets.method,
loadData: @options
}
setOptions: (@options) ->
delete(@options['authenticity_token'])
delete(@options['utf8'])
@version += 1
@history.push(@options)
setVersion: (version = null) ->
version = parseInt(version)
if version && @history.stack[version - 1]
@version = version - 1
@options = @history.stack[@version]
return true
return false
serialize: ->
return {
name: @name
options: @options
}