-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.js
348 lines (294 loc) · 16.1 KB
/
main.js
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
/*
* Copyright (c) 2012 Glenn Ruehle
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
/*jslint vars: true, plusplus: true, devel: true, nomen: true, regexp: true, indent: 4, maxerr: 50 */
/*global define, brackets, $, window, PathUtils, CodeMirror */
define(function (require, exports, module) {
"use strict";
// Brackets modules
var CommandManager = brackets.getModule("command/CommandManager"),
EditorManager = brackets.getModule("editor/EditorManager"),
ExtensionUtils = brackets.getModule("utils/ExtensionUtils"),
Menus = brackets.getModule("command/Menus"),
PreferencesManager = brackets.getModule("preferences/PreferencesManager"),
ProjectManager = brackets.getModule("project/ProjectManager");
var PREFERENCES_CLIENT_ID = "gruehle.hoverPreview",
defaultPrefs = { enabled: true };
var enabled = true, // Only show preview if true
prefs = null, // Preferences
previewMark, // CodeMirror marker highlighting the preview text
$previewContainer; // Preview container
var currentImagePreviewContent = ""; // Current image preview content, or "" if no content is showing.
function hidePreview() {
if (previewMark) {
previewMark.clear();
previewMark = null;
}
$previewContainer.empty();
$previewContainer.hide();
$previewContainer.removeClass("small-padding-bottom");
currentImagePreviewContent = "";
}
function positionPreview(xpos, ypos, ybot) {
var top = ypos - $previewContainer.height() - 38;
if (top < 0) {
$previewContainer.removeClass("preview-bubble");
$previewContainer.addClass("preview-bubble-below");
top = ybot + 16;
$previewContainer.offset({
left: xpos - $previewContainer.width() / 2 - 10,
top: top
});
} else {
$previewContainer.removeClass("preview-bubble-below");
$previewContainer.addClass("preview-bubble");
$previewContainer.offset({
left: xpos - $previewContainer.width() / 2 - 10,
top: top
});
}
}
function showPreview(content, xpos, ypos, ybot) {
hidePreview();
$previewContainer.append(content);
$previewContainer.show();
positionPreview(xpos, ypos, ybot);
}
function divContainsMouse($div, event) {
var offset = $div.offset();
return (event.clientX >= offset.left &&
event.clientX <= offset.left + $div.width() &&
event.clientY >= offset.top &&
event.clientY <= offset.top + $div.height());
}
function charCoords(cm, pos) {
var coords = cm.charCoords(pos);
// CodeMirror 2 uses x, y, ybot
// CodeMirror 3 uses left, top, bottom
// Since this code was written for CodeMirror 2, return
// a CM2-normalized struct
return {
x: coords.x || coords.left,
y: coords.y || coords.top,
yBot: coords.ybot || coords.bottom
};
}
function coordsChar(cm, coords) {
if (CodeMirror.version) {
coords.left = coords.x;
coords.top = coords.y;
}
return cm.coordsChar(coords);
}
function markText(cm, start, end, className) {
if (CodeMirror.version) {
return cm.markText(start, end, {className: className});
} else {
return cm.markText(start, end, className);
}
}
function queryPreviewProviders(editor, pos, token, line, event) {
// TODO: Support plugin providers. For now we just hard-code...
var cm = editor._codeMirror;
if (!cm || !editor) {
return;
}
var editorWidth = $(editor.getRootElement()).width();
// Check for gradient
var gradientRegEx = /-webkit-gradient\([^;]*;?|(-moz-|-ms-|-o-|-webkit-|\s)(linear-gradient\([^;]*);?|(-moz-|-ms-|-o-|-webkit-)(radial-gradient\([^;]*);?/;
var gradientMatch = line.match(gradientRegEx);
var prefix = "";
var colorValue;
// If it was a linear-gradient or radial-gradient variant, prefix with "-webkit-" so it
// shows up correctly in Brackets.
if (gradientMatch && gradientMatch[0].indexOf("-webkit-gradient") !== 0) {
prefix = "-webkit-";
}
// For prefixed gradients, use the non-prefixed value as the color value. "-webkit-" will be added
// before this value
if (gradientMatch && gradientMatch[2]) {
colorValue = gradientMatch[2];
}
// Check for color
var colorRegEx = /#[a-f0-9]{6}|#[a-f0-9]{3}|rgb\( ?\b([0-9]{1,2}|1[0-9]{2}|2[0-4][0-9]|25[0-5])\b ?, ?\b([0-9]{1,2}|1[0-9]{2}|2[0-4][0-9]|25[0-5])\b ?, ?\b([0-9]{1,2}|1[0-9]{2}|2[0-4][0-9]|25[0-5])\b ?\)|rgb\( ?\b([0-9]{1,2}%|100%) ?, ?\b([0-9]{1,2}%|100%) ?, ?\b([0-9]{1,2}%|100%) ?\)|rgba\( ?\b([0-9]{1,2}|1[0-9]{2}|2[0-4][0-9]|25[0-5])\b ?, ?\b([0-9]{1,2}|1[0-9]{2}|2[0-4][0-9]|25[0-5])\b ?, ?\b([0-9]{1,2}|1[0-9]{2}|2[0-4][0-9]|25[0-5])\b ?, ?(1|0|0?\.[0-9]{1,3}) ?\)|rgba\( ?\b([0-9]{1,2}%|100%) ?, ?\b([0-9]{1,2}%|100%) ?, ?\b([0-9]{1,2}%|100%) ?, ?(1|0|0?\.[0-9]{1,3}) ?\)|hsl\( ?\b([0-9]{1,2}|[12][0-9]{2}|3[0-5][0-9]|360)\b ?, ?\b([0-9]{1,2}|100)\b% ?, ?\b([0-9]{1,2}|100)\b% ?\)|hsla\( ?\b([0-9]{1,2}|[12][0-9]{2}|3[0-5][0-9]|360)\b ?, ?\b([0-9]{1,2}|100)\b% ?, ?\b([0-9]{1,2}|100)\b% ?, ?(1|0|0?\.[0-9]{1,3}) ?\)|\baliceblue\b|\bantiquewhite\b|\baqua\b|\baquamarine\b|\bazure\b|\bbeige\b|\bbisque\b|\bblack\b|\bblanchedalmond\b|\bblue\b|\bblueviolet\b|\bbrown\b|\bburlywood\b|\bcadetblue\b|\bchartreuse\b|\bchocolate\b|\bcoral\b|\bcornflowerblue\b|\bcornsilk\b|\bcrimson\b|\bcyan\b|\bdarkblue\b|\bdarkcyan\b|\bdarkgoldenrod\b|\bdarkgray\b|\bdarkgreen\b|\bdarkgrey\b|\bdarkkhaki\b|\bdarkmagenta\b|\bdarkolivegreen\b|\bdarkorange\b|\bdarkorchid\b|\bdarkred\b|\bdarksalmon\b|\bdarkseagreen\b|\bdarkslateblue\b|\bdarkslategray\b|\bdarkslategrey\b|\bdarkturquoise\b|\bdarkviolet\b|\bdeeppink\b|\bdeepskyblue\b|\bdimgray\b|\bdimgrey\b|\bdodgerblue\b|\bfirebrick\b|\bfloralwhite\b|\bforestgreen\b|\bfuchsia\b|\bgainsboro\b|\bghostwhite\b|\bgold\b|\bgoldenrod\b|\bgray\b|\bgreen\b|\bgreenyellow\b|\bgrey\b|\bhoneydew\b|\bhotpink\b|\bindianred\b|\bindigo\b|\bivory\b|\bkhaki\b|\blavender\b|\blavenderblush\b|\blawngreen\b|\blemonchiffon\b|\blightblue\b|\blightcoral\b|\blightcyan\b|\blightgoldenrodyellow\b|\blightgray\b|\blightgreen\b|\blightgrey\b|\blightpink\b|\blightsalmon\b|\blightseagreen\b|\blightskyblue\b|\blightslategray\b|\blightslategrey\b|\blightsteelblue\b|\blightyellow\b|\blime\b|\blimegreen\b|\blinen\b|\bmagenta\b|\bmaroon\b|\bmediumaquamarine\b|\bmediumblue\b|\bmediumorchid\b|\bmediumpurple\b|\bmediumseagreen\b|\bmediumslateblue\b|\bmediumspringgreen\b|\bmediumturquoise\b|\bmediumvioletred\b|\bmidnightblue\b|\bmintcream\b|\bmistyrose\b|\bmoccasin\b|\bnavajowhite\b|\bnavy\b|\boldlace\b|\bolive\b|\bolivedrab\b|\borange\b|\borangered\b|\borchid\b|\bpalegoldenrod\b|\bpalegreen\b|\bpaleturquoise\b|\bpalevioletred\b|\bpapayawhip\b|\bpeachpuff\b|\bperu\b|\bpink\b|\bplum\b|\bpowderblue\b|\bpurple\b|\bred\b|\brosybrown\b|\broyalblue\b|\bsaddlebrown\b|\bsalmon\b|\bsandybrown\b|\bseagreen\b|\bseashell\b|\bsienna\b|\bsilver\b|\bskyblue\b|\bslateblue\b|\bslategray\b|\bslategrey\b|\bsnow\b|\bspringgreen\b|\bsteelblue\b|\btan\b|\bteal\b|\bthistle\b|\btomato\b|\bturquoise\b|\bviolet\b|\bwheat\b|\bwhite\b|\bwhitesmoke\b|\byellow\b|\byellowgreen\b/gi;
var colorMatch = colorRegEx.exec(line);
var match = gradientMatch || colorMatch;
while (match) {
if (match && pos.ch >= match.index && pos.ch <= match.index + match[0].length) {
var preview = "<div class='color-swatch-bg'>" +
" <div class='color-swatch' style='background:" +
prefix + (colorValue || match[0]) + ";'>" +
" </div>" +
"</div>";
var startPos = {line: pos.line, ch: match.index},
endPos = {line: pos.line, ch: match.index + match[0].length},
startCoords = charCoords(cm, startPos),
xPos;
xPos = (charCoords(cm, endPos).x - startCoords.x) / 2 + startCoords.x;
showPreview(preview, xPos, startCoords.y, startCoords.yBot);
previewMark = markText(
cm,
startPos,
endPos,
"preview-highlight"
);
return;
}
match = colorRegEx.exec(line);
}
// Check for image name
var urlRegEx = /url\(([^\)]*)\)/;
var tokenString;
var urlMatch = line.match(urlRegEx);
if (urlMatch && pos.ch >= urlMatch.indx && pos.ch <= urlMatch.index + urlMatch[0].length) {
tokenString = urlMatch[1];
} else if (token.className === "string") {
tokenString = token.string;
}
if (tokenString) {
// Strip quotes, if present
var quotesRegEx = /(\'|\")?([^(\'|\")]*)(\'|\")?/;
tokenString = tokenString.replace(quotesRegEx, "$2");
if (/(\.gif|\.png|\.jpg|\.jpeg|\.svg)$/i.test(tokenString)) {
var sPos, ePos;
var docPath = editor.document.file.fullPath;
var imgPath;
if (PathUtils.isAbsoluteUrl(tokenString)) {
imgPath = tokenString;
} else {
imgPath = "file:///" + docPath.substr(0, docPath.lastIndexOf("/") + 1) + tokenString;
}
if (urlMatch) {
sPos = {line: pos.line, ch: urlMatch.index};
ePos = {line: pos.line, ch: urlMatch.index + urlMatch[0].length};
} else {
sPos = {line: pos.line, ch: token.start};
ePos = {line: pos.line, ch: token.end};
}
if (imgPath) {
var imgPreview = "<div class='image-preview'>" +
" <img src=\"" + imgPath + "\">" +
"</div>";
if (imgPreview !== currentImagePreviewContent) {
var coord = charCoords(cm, sPos);
var xpos = (charCoords(cm, ePos).x - coord.x) / 2 + coord.x;
var ypos = coord.y;
var ybot = coord.yBot;
showPreview(imgPreview, xpos, ypos, ybot);
// Hide the preview container until the image is loaded.
$previewContainer.hide();
$previewContainer.find("img").on("load", function () {
$previewContainer.find(".image-preview")
.append("<br/>" +
"<span class='img-size'>" +
this.naturalWidth + " x " + this.naturalHeight +
"</span>"
);
$previewContainer.addClass("small-padding-bottom");
$previewContainer.show();
positionPreview(xpos, ypos, ybot);
});
previewMark = markText(
cm,
sPos,
ePos,
"preview-highlight"
);
currentImagePreviewContent = imgPreview;
}
return;
}
}
}
hidePreview();
}
function handleMouseMove(event) {
if (!enabled) {
return;
}
// Figure out which editor we are over
var fullEditor = EditorManager.getCurrentFullEditor();
if (!fullEditor) {
hidePreview();
return;
}
// Check inlines first
var inlines = fullEditor.getInlineWidgets(),
i,
editor;
for (i = 0; i < inlines.length; i++) {
var $inlineDiv = inlines[i].$editorsDiv;
if (divContainsMouse($inlineDiv, event)) {
editor = inlines[i].editors[0];
break;
}
}
// Check main editor
if (!editor) {
if (divContainsMouse($(fullEditor.getRootElement()), event)) {
editor = fullEditor;
}
}
if (editor && editor._codeMirror) {
var cm = editor._codeMirror;
var pos = coordsChar(cm, {x: event.clientX, y: event.clientY});
var token = cm.getTokenAt(pos);
var line = cm.getLine(pos.line);
queryPreviewProviders(editor, pos, token, line, event);
} else {
hidePreview();
}
}
// Init: Listen to all mousemoves in the editor area
$("#editor-holder")[0].addEventListener("mousemove", handleMouseMove, true);
$("#editor-holder")[0].addEventListener("scroll", hidePreview, true);
// Create the preview container
$previewContainer = $("<div id='hover-preview-container' class='preview-bubble'>").appendTo($("body"));
// Load our stylesheet
ExtensionUtils.loadStyleSheet(module, "HoverPreview.css");
// Add menu command
var ENABLE_HOVER_PREVIEW = "Enable Hover Preview";
var CMD_ENABLE_HOVER_PREVIEW = "gruehle.enableHoverPreview";
function updateMenuItemCheckmark() {
CommandManager.get(CMD_ENABLE_HOVER_PREVIEW).setChecked(enabled);
}
function setEnabled(_enabled) {
if (enabled !== _enabled) {
enabled = _enabled;
if (!enabled) {
hidePreview();
}
prefs.setValue("enabled", enabled);
}
// Always update the checkmark, even if the enabled flag hasn't changed.
updateMenuItemCheckmark();
}
function toggleEnableHoverPreview() {
setEnabled(!enabled);
}
CommandManager.register(ENABLE_HOVER_PREVIEW, CMD_ENABLE_HOVER_PREVIEW, toggleEnableHoverPreview);
var menu = Menus.getMenu(Menus.AppMenuBar.VIEW_MENU);
menu.addMenuItem(CMD_ENABLE_HOVER_PREVIEW);
// Init PreferenceStorage
prefs = PreferencesManager.getPreferenceStorage(PREFERENCES_CLIENT_ID, defaultPrefs);
// Setup initial UI state
setEnabled(prefs.getValue("enabled"));
});