forked from jkroso/atom-browser-refresh-on-save
-
Notifications
You must be signed in to change notification settings - Fork 1
/
plugin.coffee
110 lines (95 loc) · 2.64 KB
/
plugin.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
107
108
109
110
platform = require('os').platform()
{BufferedProcess} = require 'atom'
path = require 'path'
# Code to run in the browser
scripts = {
js: 'location.reload()'
css: """
[].forEach.call(document.getElementsByTagName('link'), function(el){
var rel = el.getAttribute('rel')
if (rel && 0 == rel.indexOf('style')) {
el.parentNode.replaceChild(el.cloneNode(true), el)
}
})
"""
}
scripts['md'] =
scripts['html'] =
scripts['jade'] =
scripts['json'] = scripts['js']
scripts['styl'] = scripts['css']
for key, value of scripts
scripts[key] = {
type: 'string'
default: value
}
plugin = {
config:
chrome:
type: 'boolean'
order: 1
default: true
safari:
type: 'boolean'
order: 2
default: true
vivaldi:
type: 'boolean'
order: 3
default: true
scripts:
type: 'object'
properties: scripts
subscriptions: []
activate: (state) ->
if platform not of refresh
return error("#{platform} is not supported")
atom.workspace.observeTextEditors (editor) =>
sub = editor.onDidSave (event) ->
scripts = atom.config.get('browser-refresh-on-save.scripts')
type = path.extname(event.path).slice(1)
if type of scripts then refreshAll(scripts[type])
@subscriptions.push(sub)
deactivate: ->
for sub in @subscriptions
sub.dispose()
@subscriptions = []
}
error = (message) ->
atom.notifications.addError("Browser Refresh on Save: #{message}")
MacChromeCmd = """
if (count window of application "Google Chrome") = 0 then return
tell application "Google Chrome"
set winref to a reference to (first window whose title does not start with "Developer Tools - ")
set theTab to active tab of winref
if theTab's URL starts with "http://localhost" or theTab's URL starts with "file:" then
tell theTab to execute javascript "{js}"
end if
end tell
"""
MacSafariCmd = """
tell application "Safari" to do JavaScript "{js}" in document 1
"""
commands = {
darwin: {
chrome: MacChromeCmd,
vivaldi: MacChromeCmd.replace(/Google Chrome/g, "Vivaldi"),
safari: MacSafariCmd
}
}
refresh = (browser, js) ->
refresh[platform](commands[platform][browser], js)
refresh.darwin = (cmd, js) ->
new BufferedProcess({
command: 'osascript'
args: ['-e', cmd.replace('{js}', js)]
stderr: (data) -> error(data.toString())
})
refreshAll = (js) ->
if atom.config.get('browser-refresh-on-save.chrome')
refresh('chrome', js)
if atom.config.get('browser-refresh-on-save.vivaldi')
refresh('vivaldi', js)
if atom.config.get('browser-refresh-on-save.safari')
refresh('safari', js)
module.exports = plugin