This commit is contained in:
Colin 2024-07-24 15:08:48 -07:00
commit e58dfc8074
3 changed files with 429 additions and 430 deletions

View file

@ -176,4 +176,3 @@ textarea {
#messages li.error { #messages li.error {
background:rgba(102,8,0,0.8); background:rgba(102,8,0,0.8);
} }

View file

@ -3,443 +3,443 @@
///// represents a single document ///// represents a single document
var haste_document = function(app) { var haste_document = function(app) {
this.locked = false; this.locked = false;
this.app = app; this.app = app;
}; };
// Escapes HTML tag characters // Escapes HTML tag characters
haste_document.prototype.htmlEscape = function(s) { haste_document.prototype.htmlEscape = function(s) {
return s return s
.replace(/&/g, '&') .replace(/&/g, '&')
.replace(/>/g, '>') .replace(/>/g, '>')
.replace(/</g, '&lt;') .replace(/</g, '&lt;')
.replace(/"/g, '&quot;'); .replace(/"/g, '&quot;');
}; };
// Get this document from the server and lock it here // Get this document from the server and lock it here
haste_document.prototype.load = function(key, callback, lang) { haste_document.prototype.load = function(key, callback, lang) {
var _this = this; var _this = this;
var selectedLines = this.app.selectedLines; var selectedLines = this.app.selectedLines;
$.ajax(_this.app.baseUrl + 'documents/' + key, { $.ajax(_this.app.baseUrl + 'documents/' + key, {
type: 'get', type: 'get',
dataType: 'json', dataType: 'json',
success: function(res) { success: function(res) {
_this.locked = true; _this.locked = true;
_this.key = key; _this.key = key;
_this.data = res.data; _this.data = res.data;
try { try {
var high = { value: "", language: null}; var high = { value: "", language: null};
var lines = res.data.split("\n"); var lines = res.data.split("\n");
for (var i = 0; i < lines.length; i++) { for (var i = 0; i < lines.length; i++) {
if (lang === "txt") { if (lang === "txt") {
highlighted = _this.htmlEscape(res.data); highlighted = _this.htmlEscape(res.data);
} else if (lang) { } else if (lang) {
highlighted = hljs.highlight(lang, lines[i]).value; highlighted = hljs.highlight(lang, lines[i]).value;
} else { } else {
var highlightedData = hljs.highlightAuto(lines[i]); var highlightedData = hljs.highlightAuto(lines[i]);
high.language = highlightedData.language; high.language = highlightedData.language;
highlighted = highlightedData.value; highlighted = highlightedData.value;
}
var currentLine = i + 1;
var spanClass = "";
if (
currentLine >= selectedLines.startLine &&
currentLine <= selectedLines.endLine
) {
spanClass = "lineHighlight";
}
highlighted = "<span id='line-" + (i+1) + "' class="+spanClass+">" + highlighted + "</span>";
high.value += highlighted + "\n";
} }
//// scroll to position in document after ensuring components h"ve had time to render
setTimeout(function() { var currentLine = i + 1;
// show current line and the one before it var spanClass = "";
if (selectedLines.startLine >= 3) { if (
document.body.scrollTo(0, $("#line-" + (selectedLines.startLine - 2)).offset().top); currentLine >= selectedLines.startLine &&
} else { currentLine <= selectedLines.endLine
// if lines 1-2, go to top of file ) {
document.body.scrollTo(0, 0); spanClass = "lineHighlight";
} }
}, 0); highlighted = "<span id='line-" + (i+1) + "' class="+spanClass+">" + highlighted + "</span>";
} catch(err) { high.value += highlighted + "\n";
// failed highlight, fall back on auto }
high = hljs.highlightAuto(res.data); //// scroll to position in document after ensuring components h"ve had time to render
} setTimeout(function() {
callback({ // show current line and the one before it
value: high.value, if (selectedLines.startLine >= 3) {
key: key, document.body.scrollTo(0, $("#line-" + (selectedLines.startLine - 2)).offset().top);
language: high.language || lang, } else {
lineCount: res.data.split('\n').length // if lines 1-2, go to top of file
}); document.body.scrollTo(0, 0);
}
}, 0);
} catch(err) {
// failed highlight, fall back on auto
high = hljs.highlightAuto(res.data);
}
callback({
value: high.value,
key: key,
language: high.language || lang,
lineCount: res.data.split('\n').length
});
},
error: function() {
callback(false);
}
});
};
// Save this document to the server and lock it here
haste_document.prototype.save = function(data, callback) {
if (this.locked) {
return false;
}
this.data = data;
var _this = this;
$.ajax(_this.app.baseUrl + 'documents', {
type: 'post',
data: data,
dataType: 'json',
contentType: 'text/plain; charset=utf-8',
success: function(res) {
_this.locked = true;
_this.key = res.key;
var high = hljs.highlightAuto(data);
callback(null, {
value: high.value,
key: res.key,
language: high.language,
lineCount: data.split('\n').length
});
},
error: function(res) {
try {
callback($.parseJSON(res.responseText));
}
catch (e) {
callback({message: 'Something went wrong!'});
}
}
});
};
///// represents the paste application
var haste = function(appName, options) {
this.appName = appName;
this.$textarea = $('textarea');
this.$box = $('#box');
this.$code = $('#box code');
this.$linenos = $('#linenos');
this.options = options;
this.configureShortcuts();
this.configureButtons();
// If twitter is disabled, hide the button
if (!options.twitter) {
$('#box2 .twitter').hide();
};
this.baseUrl = options.baseUrl || '/';
this.selectedLines = options.selectedLines;
};
// Set the page title - include the appName
haste.prototype.setTitle = function(ext) {
var title = ext ? this.appName + ' - ' + ext : this.appName;
document.title = title;
};
// Show a message box
haste.prototype.showMessage = function(msg, cls) {
var msgBox = $('<li class="'+(cls || 'info')+'">'+msg+'</li>');
$('#messages').prepend(msgBox);
setTimeout(function() {
msgBox.slideUp('fast', function() { $(this).remove(); });
}, 3000);
};
// Show the light key
haste.prototype.lightKey = function() {
this.configureKey(['new', 'save']);
};
// Show the full key
haste.prototype.fullKey = function() {
this.configureKey(['new', 'duplicate', 'twitter', 'raw']);
};
// Set the key up for certain things to be enabled
haste.prototype.configureKey = function(enable) {
var $this, i = 0;
$('#box2 .function').each(function() {
$this = $(this);
for (i = 0; i < enable.length; i++) {
if ($this.hasClass(enable[i])) {
$this.addClass('enabled');
return true;
}
}
$this.removeClass('enabled');
});
};
// Remove the current document (if there is one)
// and set up for a new one
haste.prototype.newDocument = function(hideHistory) {
this.$box.hide();
this.doc = new haste_document(this);
if (!hideHistory) {
window.history.pushState(null, this.appName, this.baseUrl);
}
this.setTitle();
this.lightKey();
this.$textarea.val('').show('fast', function() {
this.focus();
});
this.selectedLines = { startLine: null, endLine: null };
this.removeLineNumbers();
};
// Map of common extensions
// Note: this list does not need to include anything that IS its extension,
// due to the behavior of lookupTypeByExtension and lookupExtensionByType
// Note: optimized for lookupTypeByExtension
haste.extensionMap = {
rb: 'ruby', py: 'python', pl: 'perl', php: 'php', scala: 'scala', go: 'go',
xml: 'xml', html: 'xml', htm: 'xml', css: 'css', js: 'javascript', vbs: 'vbscript',
lua: 'lua', pas: 'delphi', java: 'java', cpp: 'cpp', cc: 'cpp', m: 'objectivec',
vala: 'vala', sql: 'sql', sm: 'smalltalk', lisp: 'lisp', ini: 'ini',
diff: 'diff', bash: 'bash', sh: 'bash', tex: 'tex', erl: 'erlang', hs: 'haskell',
md: 'markdown', txt: '', coffee: 'coffee', swift: 'swift'
};
// Look up the extension preferred for a type
// If not found, return the type itself - which we'll place as the extension
haste.prototype.lookupExtensionByType = function(type) {
for (var key in haste.extensionMap) {
if (haste.extensionMap[key] === type) return key;
}
return type;
};
// Look up the type for a given extension
// If not found, return the extension - which we'll attempt to use as the type
haste.prototype.lookupTypeByExtension = function(ext) {
return haste.extensionMap[ext] || ext;
};
// Add line numbers to the document
// For the specified number of lines
haste.prototype.addLineNumbers = function(lineCount) {
var h = '';
for (var i = 0; i < lineCount; i++) {
h +=
'<span onclick="handleLineClick(' +
i.toString() +
')" onmouseenter="handleMouseEnter(' +
i.toString() +
')" onmouseleave="handleMouseLeave(' +
i.toString() +
')" onmousedown="handleMouseDown(' +
i.toString() +
')" onmouseup="handleMouseUp(' +
i.toString() +
')" id="line-number-' +
(i + 1) +
'">' +
(i + 1) +
"</span><br/>";
}
$('#linenos').html(h);
};
// Remove the line numbers
haste.prototype.removeLineNumbers = function() {
$('#linenos').html('&gt;');
};
// Load a document and show it
haste.prototype.loadDocument = function(key) {
// Split the key up
var parts = key.split('.', 2);
// Ask for what we want
var _this = this;
_this.doc = new haste_document(this);
_this.doc.load(parts[0], function(ret) {
if (ret) {
_this.$code.html(ret.value);
_this.setTitle(ret.key);
_this.fullKey();
_this.$textarea.val('').hide();
_this.$box.show().focus();
_this.addLineNumbers(ret.lineCount);
}
else {
_this.newDocument();
}
}, this.lookupTypeByExtension(parts[1]));
};
// Duplicate the current document - only if locked
haste.prototype.duplicateDocument = function() {
if (this.doc.locked) {
var currentData = this.doc.data;
this.newDocument();
this.$textarea.val(currentData);
}
};
// Lock the current document
haste.prototype.lockDocument = function() {
var _this = this;
this.doc.save(this.$textarea.val(), function(err, ret) {
if (err) {
_this.showMessage(err.message, 'error');
}
else if (ret) {
_this.$code.html(ret.value);
_this.setTitle(ret.key);
var file = _this.baseUrl + ret.key;
if (ret.language) {
file += '.' + _this.lookupExtensionByType(ret.language);
}
window.history.pushState(null, _this.appName + '-' + ret.key, file);
_this.fullKey();
_this.$textarea.val('').hide();
_this.$box.show().focus();
_this.addLineNumbers(ret.lineCount);
// Load Document Again
var path = window.location.href;
_this.loadDocument(path.split('#')[0].split('/').slice(-1)[0]);
}
});
};
haste.prototype.configureButtons = function() {
var _this = this;
this.buttons = [
{
$where: $('#box2 .save'),
label: 'Save',
shortcutDescription: 'control + s',
shortcut: function(evt) {
return evt.ctrlKey && (evt.keyCode === 83);
}, },
error: function() { action: function() {
callback(false); if (_this.$textarea.val().replace(/^\s+|\s+$/g, '') !== '') {
_this.lockDocument();
}
} }
}); },
}; {
$where: $('#box2 .new'),
// Save this document to the server and lock it here label: 'New',
haste_document.prototype.save = function(data, callback) { shortcut: function(evt) {
if (this.locked) { return evt.ctrlKey && evt.keyCode === 78;
return false;
}
this.data = data;
var _this = this;
$.ajax(_this.app.baseUrl + 'documents', {
type: 'post',
data: data,
dataType: 'json',
contentType: 'text/plain; charset=utf-8',
success: function(res) {
_this.locked = true;
_this.key = res.key;
var high = hljs.highlightAuto(data);
callback(null, {
value: high.value,
key: res.key,
language: high.language,
lineCount: data.split('\n').length
});
}, },
error: function(res) { shortcutDescription: 'control + n',
try { action: function() {
callback($.parseJSON(res.responseText)); _this.newDocument(!_this.doc.key);
}
catch (e) {
callback({message: 'Something went wrong!'});
}
} }
}); },
}; {
$where: $('#box2 .duplicate'),
///// represents the paste application label: 'Duplicate & Edit',
shortcut: function(evt) {
var haste = function(appName, options) { return _this.doc.locked && evt.ctrlKey && evt.keyCode === 68;
this.appName = appName; },
this.$textarea = $('textarea'); shortcutDescription: 'control + d',
this.$box = $('#box'); action: function() {
this.$code = $('#box code'); _this.duplicateDocument();
this.$linenos = $('#linenos'); }
this.options = options; },
this.configureShortcuts(); {
this.configureButtons(); $where: $('#box2 .raw'),
// If twitter is disabled, hide the button label: 'Just Text',
if (!options.twitter) { shortcut: function(evt) {
$('#box2 .twitter').hide(); return evt.ctrlKey && evt.shiftKey && evt.keyCode === 82;
}; },
this.baseUrl = options.baseUrl || '/'; shortcutDescription: 'control + shift + r',
this.selectedLines = options.selectedLines; action: function() {
}; window.location.href = _this.baseUrl + 'raw/' + _this.doc.key;
}
// Set the page title - include the appName },
haste.prototype.setTitle = function(ext) { {
var title = ext ? this.appName + ' - ' + ext : this.appName; $where: $('#box2 .twitter'),
document.title = title; label: 'Twitter',
}; shortcut: function(evt) {
return _this.options.twitter && _this.doc.locked && evt.shiftKey && evt.ctrlKey && evt.keyCode == 84;
// Show a message box },
haste.prototype.showMessage = function(msg, cls) { shortcutDescription: 'control + shift + t',
var msgBox = $('<li class="'+(cls || 'info')+'">'+msg+'</li>'); action: function() {
$('#messages').prepend(msgBox); window.open('https://twitter.com/share?url=' + encodeURI(window.location.href));
setTimeout(function() {
msgBox.slideUp('fast', function() { $(this).remove(); });
}, 3000);
};
// Show the light key
haste.prototype.lightKey = function() {
this.configureKey(['new', 'save']);
};
// Show the full key
haste.prototype.fullKey = function() {
this.configureKey(['new', 'duplicate', 'twitter', 'raw']);
};
// Set the key up for certain things to be enabled
haste.prototype.configureKey = function(enable) {
var $this, i = 0;
$('#box2 .function').each(function() {
$this = $(this);
for (i = 0; i < enable.length; i++) {
if ($this.hasClass(enable[i])) {
$this.addClass('enabled');
return true;
}
} }
$this.removeClass('enabled');
});
};
// Remove the current document (if there is one)
// and set up for a new one
haste.prototype.newDocument = function(hideHistory) {
this.$box.hide();
this.doc = new haste_document(this);
if (!hideHistory) {
window.history.pushState(null, this.appName, this.baseUrl);
} }
this.setTitle(); ];
this.lightKey(); for (var i = 0; i < this.buttons.length; i++) {
this.$textarea.val('').show('fast', function() { this.configureButton(this.buttons[i]);
this.focus(); }
}); };
this.selectedLines = { startLine: null, endLine: null };
this.removeLineNumbers();
};
// Map of common extensions haste.prototype.configureButton = function(options) {
// Note: this list does not need to include anything that IS its extension, // Handle the click action
// due to the behavior of lookupTypeByExtension and lookupExtensionByType options.$where.click(function(evt) {
// Note: optimized for lookupTypeByExtension evt.preventDefault();
haste.extensionMap = { if (!options.clickDisabled && $(this).hasClass('enabled')) {
rb: 'ruby', py: 'python', pl: 'perl', php: 'php', scala: 'scala', go: 'go', options.action();
xml: 'xml', html: 'xml', htm: 'xml', css: 'css', js: 'javascript', vbs: 'vbscript',
lua: 'lua', pas: 'delphi', java: 'java', cpp: 'cpp', cc: 'cpp', m: 'objectivec',
vala: 'vala', sql: 'sql', sm: 'smalltalk', lisp: 'lisp', ini: 'ini',
diff: 'diff', bash: 'bash', sh: 'bash', tex: 'tex', erl: 'erlang', hs: 'haskell',
md: 'markdown', txt: '', coffee: 'coffee', swift: 'swift'
};
// Look up the extension preferred for a type
// If not found, return the type itself - which we'll place as the extension
haste.prototype.lookupExtensionByType = function(type) {
for (var key in haste.extensionMap) {
if (haste.extensionMap[key] === type) return key;
} }
return type; });
}; // Show the label
options.$where.mouseenter(function() {
$('#box3 .label').text(options.label);
$('#box3 .shortcut').text(options.shortcutDescription || '');
$('#box3').show();
$(this).append($('#pointer').remove().show());
});
// Hide the label
options.$where.mouseleave(function() {
$('#box3').hide();
$('#pointer').hide();
});
};
// Look up the type for a given extension // Configure keyboard shortcuts for the textarea
// If not found, return the extension - which we'll attempt to use as the type haste.prototype.configureShortcuts = function() {
haste.prototype.lookupTypeByExtension = function(ext) { var _this = this;
return haste.extensionMap[ext] || ext; $(document.body).keydown(function(evt) {
}; var button;
for (var i = 0 ; i < _this.buttons.length; i++) {
// Add line numbers to the document button = _this.buttons[i];
// For the specified number of lines if (button.shortcut && button.shortcut(evt)) {
haste.prototype.addLineNumbers = function(lineCount) { evt.preventDefault();
var h = ''; button.action();
for (var i = 0; i < lineCount; i++) { return;
h += }
'<span onclick="handleLineClick(' +
i.toString() +
')" onmouseenter="handleMouseEnter(' +
i.toString() +
')" onmouseleave="handleMouseLeave(' +
i.toString() +
')" onmousedown="handleMouseDown(' +
i.toString() +
')" onmouseup="handleMouseUp(' +
i.toString() +
')" id="line-number-' +
(i + 1) +
'">' +
(i + 1) +
"</span><br/>";
} }
$('#linenos').html(h); });
}; };
// Remove the line numbers ///// Tab behavior in the textarea - 2 spaces per tab
haste.prototype.removeLineNumbers = function() { $(function() {
$('#linenos').html('&gt;');
};
// Load a document and show it $('textarea').keydown(function(evt) {
haste.prototype.loadDocument = function(key) { if (evt.keyCode === 9) {
// Split the key up evt.preventDefault();
var parts = key.split('.', 2); var myValue = ' ';
// Ask for what we want // http://stackoverflow.com/questions/946534/insert-text-into-textarea-with-jquery
var _this = this; // For browsers like Internet Explorer
_this.doc = new haste_document(this); if (document.selection) {
_this.doc.load(parts[0], function(ret) { this.focus();
if (ret) { var sel = document.selection.createRange();
_this.$code.html(ret.value); sel.text = myValue;
_this.setTitle(ret.key); this.focus();
_this.fullKey(); }
_this.$textarea.val('').hide(); // Mozilla and Webkit
_this.$box.show().focus(); else if (this.selectionStart || this.selectionStart == '0') {
_this.addLineNumbers(ret.lineCount); var startPos = this.selectionStart;
var endPos = this.selectionEnd;
var scrollTop = this.scrollTop;
this.value = this.value.substring(0, startPos) + myValue +
this.value.substring(endPos,this.value.length);
this.focus();
this.selectionStart = startPos + myValue.length;
this.selectionEnd = startPos + myValue.length;
this.scrollTop = scrollTop;
} }
else { else {
_this.newDocument(); this.value += myValue;
this.focus();
} }
}, this.lookupTypeByExtension(parts[1]));
};
// Duplicate the current document - only if locked
haste.prototype.duplicateDocument = function() {
if (this.doc.locked) {
var currentData = this.doc.data;
this.newDocument();
this.$textarea.val(currentData);
} }
};
// Lock the current document
haste.prototype.lockDocument = function() {
var _this = this;
this.doc.save(this.$textarea.val(), function(err, ret) {
if (err) {
_this.showMessage(err.message, 'error');
}
else if (ret) {
_this.$code.html(ret.value);
_this.setTitle(ret.key);
var file = _this.baseUrl + ret.key;
if (ret.language) {
file += '.' + _this.lookupExtensionByType(ret.language);
}
window.history.pushState(null, _this.appName + '-' + ret.key, file);
_this.fullKey();
_this.$textarea.val('').hide();
_this.$box.show().focus();
_this.addLineNumbers(ret.lineCount);
// Load Document Again
var path = window.location.href;
_this.loadDocument(path.split('#')[0].split('/').slice(-1)[0]);
}
});
};
haste.prototype.configureButtons = function() {
var _this = this;
this.buttons = [
{
$where: $('#box2 .save'),
label: 'Save',
shortcutDescription: 'control + s',
shortcut: function(evt) {
return evt.ctrlKey && (evt.keyCode === 83);
},
action: function() {
if (_this.$textarea.val().replace(/^\s+|\s+$/g, '') !== '') {
_this.lockDocument();
}
}
},
{
$where: $('#box2 .new'),
label: 'New',
shortcut: function(evt) {
return evt.ctrlKey && evt.keyCode === 78;
},
shortcutDescription: 'control + n',
action: function() {
_this.newDocument(!_this.doc.key);
}
},
{
$where: $('#box2 .duplicate'),
label: 'Duplicate & Edit',
shortcut: function(evt) {
return _this.doc.locked && evt.ctrlKey && evt.keyCode === 68;
},
shortcutDescription: 'control + d',
action: function() {
_this.duplicateDocument();
}
},
{
$where: $('#box2 .raw'),
label: 'Just Text',
shortcut: function(evt) {
return evt.ctrlKey && evt.shiftKey && evt.keyCode === 82;
},
shortcutDescription: 'control + shift + r',
action: function() {
window.location.href = _this.baseUrl + 'raw/' + _this.doc.key;
}
},
{
$where: $('#box2 .twitter'),
label: 'Twitter',
shortcut: function(evt) {
return _this.options.twitter && _this.doc.locked && evt.shiftKey && evt.ctrlKey && evt.keyCode == 84;
},
shortcutDescription: 'control + shift + t',
action: function() {
window.open('https://twitter.com/share?url=' + encodeURI(window.location.href));
}
}
];
for (var i = 0; i < this.buttons.length; i++) {
this.configureButton(this.buttons[i]);
}
};
haste.prototype.configureButton = function(options) {
// Handle the click action
options.$where.click(function(evt) {
evt.preventDefault();
if (!options.clickDisabled && $(this).hasClass('enabled')) {
options.action();
}
});
// Show the label
options.$where.mouseenter(function() {
$('#box3 .label').text(options.label);
$('#box3 .shortcut').text(options.shortcutDescription || '');
$('#box3').show();
$(this).append($('#pointer').remove().show());
});
// Hide the label
options.$where.mouseleave(function() {
$('#box3').hide();
$('#pointer').hide();
});
};
// Configure keyboard shortcuts for the textarea
haste.prototype.configureShortcuts = function() {
var _this = this;
$(document.body).keydown(function(evt) {
var button;
for (var i = 0 ; i < _this.buttons.length; i++) {
button = _this.buttons[i];
if (button.shortcut && button.shortcut(evt)) {
evt.preventDefault();
button.action();
return;
}
}
});
};
///// Tab behavior in the textarea - 2 spaces per tab
$(function() {
$('textarea').keydown(function(evt) {
if (evt.keyCode === 9) {
evt.preventDefault();
var myValue = ' ';
// http://stackoverflow.com/questions/946534/insert-text-into-textarea-with-jquery
// For browsers like Internet Explorer
if (document.selection) {
this.focus();
var sel = document.selection.createRange();
sel.text = myValue;
this.focus();
}
// Mozilla and Webkit
else if (this.selectionStart || this.selectionStart == '0') {
var startPos = this.selectionStart;
var endPos = this.selectionEnd;
var scrollTop = this.scrollTop;
this.value = this.value.substring(0, startPos) + myValue +
this.value.substring(endPos,this.value.length);
this.focus();
this.selectionStart = startPos + myValue.length;
this.selectionEnd = startPos + myValue.length;
this.scrollTop = scrollTop;
}
else {
this.value += myValue;
this.focus();
}
}
});
}); });
});

View file

@ -18,7 +18,7 @@
var isHashChange=false; var isHashChange=false;
var isDragging=false; var isDragging=false;
// Handle pops // Handle pops
var handlePop = function (evt) { var handlePop = function(evt) {
if (isHashChange||isDragging) { if (isHashChange||isDragging) {
evt.preventDefault(); evt.preventDefault();
// reset // reset