1 // @license magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&dn=expat.txt Expat
2 // @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL
4 * Copyright (c) 2014 Leonardo Cardoso (http://leocardz.com)
5 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
6 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
8 * Restructured by Rabzuarus (https://friendica.kommune4.de/profile/rabuzarus)
9 * to use it in the decentralized social network Friendica (https://friendi.ca).
14 $.fn.linkPreview = function (options) {
15 var opts = jQuery.extend({}, $.fn.linkPreview.defaults, options);
17 var selector = $(this).selector;
18 selector = selector.substr(1);
21 <div id="preview_' + selector + '" class="preview {0}">\
23 <input type="hidden" name="has_attachment" id="hasAttachment_' + selector + '" value="{2}" />\
24 <input type="hidden" name="attachment_url" id="attachmentUrl_' + selector + '" value="{3}" />\
25 <input type="hidden" name="attachment_type" id="attachmentType_' + selector + '" value="{4}" />\
28 var attachmentTpl = '\
29 <hr class="previewseparator">\
30 <div id="closePreview_' + selector + '" title="Remove" class="closePreview" >\
31 <button type="button" class="previewActionBtn">×</button>\
33 <div id="previewImages_' + selector + '" class="previewImages">\
34 <div id="previewImgBtn_' + selector + '" class="previewImgBtn">\
35 <button type="button" id="previewChangeImg_' + selector + '" class="buttonChangeDeactive previewActionBtn" style="display: none">\
36 <i class="fa fa-exchange" aria-hidden="true"></i>\
39 <div id="previewImage_' + selector + '" class="previewImage">\
41 <input type="hidden" id="photoNumber_' + selector + '" class="photoNumber" value="0" />\
42 <input type="hidden" name="attachment_img_src" id="attachmentImageSrc_' + selector + '" value="" />\
43 <input type="hidden" name="attachment_img_width" id="attachmentImageWidth_' + selector + '" value="0" />\
44 <input type="hidden" name="attachment_img_height" id="attachmentImageHeight_' + selector + '" value="0" />\
46 <div id="previewContent_' + selector + '" class="previewContent">\
47 <h4 id="previewTitle_' + selector + '" class="previewTitle"></h4>\
48 <blockquote id="previewDescription_' + selector + '" class="previewDescription"></blockquote>\
49 <div id="hiddenDescription_' + selector + '" class="hiddenDescription"></div>\
50 <sup id="previewUrl_' + selector + '" class="previewUrl"></sup>\
52 <div class="clear"></div>\
53 <hr class="previewseparator">';
57 var blockTitle = false;
58 var blockDescription = false;
63 var firstPosted = false;
65 var isCrawling = false;
66 var defaultTitle = opts.defaultTitle;
67 var defaultDescription = opts.defaultDescription;
70 * Initialize the plugin
74 var init = function() {
75 $('#' + selector).bind({
77 setTimeout(function () {
82 // on enter, space, ctrl
83 if ((e.which === 13 || e.which === 32 || e.which === 17)) {
89 // Check if we have already attachment bbcode in the textarea
90 // and add it to the attachment preview.
91 var content = $('#' + selector).val();
92 addBBCodeToPreview(content);
100 var resetPreview = function() {
101 $('#hasAttachment_' + selector).val(0);
107 * Crawl a text string if it contains an url and try
110 * If no text is passed to crawlText() we take
111 * the previous word before the cursor of the textarea.
113 * @param {string} text (optional)
116 var crawlText = function (text) {
121 // If no text is passed to crawlText() we
122 // take the previous word before the cursor.
123 if (typeof text === 'undefined') {
124 text = getPrevWord(selector);
129 // Don't procces the textarea input if we have already
130 // an attachment preview.
131 if (!isExtern && isActive) {
135 if (trim(text) !== "" && block === false && urlRegex.test(text)) {
136 binurl = bin2hex(text);
140 $('#profile-rotator').show();
142 if (binurl in cache) {
144 processContentData(cache[binurl]);
146 getContentData(binurl, processContentData);
152 * Process the attachment data according to
153 * its content type (image, audio, video, attachment)
155 * @param {object} result
158 var processContentData = function(result) {
159 if (result.contentType === 'image') {
160 insertImage(result.data);
162 if (result.contentType === 'audio') {
163 insertAudio(result.data);
165 if (result.contentType === 'video') {
166 insertVideo(result.data);
168 if (result.contentType === 'attachment') {
169 insertAttachment(result.data);
171 $('#profile-rotator').hide();
175 * Fetch the content of link which should be attached.
177 * @param {string} binurl Link which should be attached as hexadecimal string.
178 * @param {type} callback
181 var getContentData = function(binurl, callback) {
182 $.get('parse_url?binurl='+ binurl + '&format=json', function (answer) {
183 obj = sanitizeInputData(answer);
185 // Put the data into a cache
195 * Add a [img] bbtag with the image url to the jot editor.
200 var insertImage = function(data) {
204 var bbcode = '\n[img]' + data.url + '[/img]\n';
205 addeditortext(bbcode);
209 * Add a [audio] bbtag with the audio url to the jot editor.
214 var insertAudio = function(data) {
218 var bbcode = '\n[audio]' + data.url + '[/audio]\n';
219 addeditortext(bbcode);
223 * Add a [video] bbtag with the video url to the jot editor.
228 var insertVideo = function(data) {
232 var bbcode = '\n[video]' + data.url + '[/video]\n';
233 addeditortext(bbcode);
237 * Proccess all attachment data and show up a html
238 * attachment preview.
240 * @param {obj} data Attachment data.
243 var insertAttachment = function(data) {
244 // If we have already a preview, leaver here.
245 // Note: if we finish the Preview of other media content type,
246 // we can move this condition to the beggining of crawlText();
248 $('#profile-rotator').hide();
252 if (data.type !== 'link' && data.type !== 'video' && data.type !== 'photo' || data.url === data.title) {
253 $('#profile-rotator').hide();
257 $('#photoNumber_' + selector).val(0);
260 processAttachmentTpl(data, 'type-' + data.type);
261 addTitleDescription(data);
262 addHostToAttachment(data.url);
263 addImagesToAttachment(data.images);
265 processEventListener();
266 $('#profile-rotator').hide();
270 * Construct the attachment html from the attachment template and
273 * @param {object} data Attachment data.
276 var processAttachmentTpl = function(data) {
277 // Load and add the template if it isn't allready loaded.
278 if ($('#preview_' + selector).length === 0) {
279 var tpl = previewTpl.format(
286 $('#' + selector).after(tpl);
293 * Add the attachment title and the description
294 * to the attachment preview.
296 * @param {object} data Attachment data.
299 var addTitleDescription = function(data) {
300 var description = data.text;
302 if (description === '') {
303 description = defaultDescription;
306 $('#previewTitle_' + selector).html("\
307 <span id='previewSpanTitle_" + selector + "' class='previewSpanTitle' >" + escapeHTML(data.title) + "</span>\
308 <input type='text' name='attachment_title' value='" + escapeHTML(data.title) + "' id='previewInputTitle_" + selector + "' class='previewInputTitle inputPreview' style='display: none;'/>"
311 $('#previewDescription_' + selector).html("\
312 <span id='previewSpanDescription_" + selector + "' class='previewSpanDescription' >" + escapeHTML(description) + "</span>\n\
313 <textarea id='previewInputDescription_" + selector + "' name='attachment_text' class='previewInputDescription' style='display: none;' class='inputPreview' >" + escapeHTML(data.text) + "</textarea>"
318 * Add the host to the attachment preview.
320 * @param {string} url The url of the link attachment.
323 var addHostToAttachment = function(url) {
325 var regexpr = "(https?://)([^:^/]*)(:\\d*)?(.*)?";
326 var regResult = url.match(regexpr);
327 var urlHost = regResult[1] + regResult[2];
328 $('#previewUrl_' + selector).html("<a href='" + url + "'>" + urlHost + "</a>");
333 * Add preview images to the attachment.
335 * @param {array} images
339 var addImagesToAttachment = function(images) {
340 var imageClass = 'attachment-preview';
342 if (Array.isArray(images)) {
343 $('#previewImages_' + selector).show();
344 $('#attachmentImageSrc_' + selector).val(bin2hex(images[photoNumber].src));
345 $('#attachmentImageWidth_' + selector).val(images[photoNumber].width);
346 $('#attachmentImageHeight_' + selector).val(images[photoNumber].height);
348 $('#previewImages_' + selector).hide();
351 images.length = parseInt(images.length);
352 var appendImage = "";
354 for (i = 0; i < images.length; i++) {
355 // For small preview images we use a smaller attachment format.
356 ///@todo here we need to add a check for !Config::get('system', 'always_show_preview').
357 if (images[i].width >= 500 && images[i].width >= images[i].height) {
358 imageClass = 'attachment-image';
362 appendImage += "<img id='imagePreview_" + selector + "_" + i + "' src='" + images[i].src + "' class='" + imageClass + "' ></img>";
364 appendImage += "<img id='imagePreview_" + selector + "_" + i + "' src='" + images[i].src + "' class='" + imageClass + "' style='display: none;'></img>";
368 $('#previewImage_' + selector).html(appendImage + "<div id='whiteImage' style='color: transparent; display:none;'>...</div>");
370 // More than just one image.
371 if (images.length > 1) {
372 // Enable the the button to change the preview pictures.
373 $('#previewChangeImg_' + selector).show();
375 if (firstPosted === false) {
378 $('#previewChangeImg_' + selector).unbind('click').click(function (e) {
380 if (images.length > 1) {
381 $('#imagePreview_' + selector + '_' + photoNumber).css({
386 // If have reached the last image, begin with the first image.
387 if (photoNumber === images.length) {
391 $('#imagePreview_' + selector + '_' + photoNumber).css({
394 $('#photoNumber_' + selector).val(photoNumber);
395 $('#attachmentImageSrc_' + selector).val(bin2hex(images[photoNumber].src));
396 $('#attachmentImageWidth_' + selector).val(images[photoNumber].width);
397 $('#attachmentImageHeight_' + selector).val(images[photoNumber].height);
405 * Add event listener to control the attachment preview.
409 var processEventListener = function() {
410 $('#previewSpanTitle_' + selector).unbind('click').click(function (e) {
412 if (blockTitle === false) {
414 $('#previewSpanTitle_' + selector).hide();
415 $('#previewInputTitle_' + selector).show();
416 $('#previewInputTitle_' + selector).val($('#previewInputTitle_' + selector).val());
417 $('#previewInputTitle_' + selector).focus().select();
421 $('#previewInputTitle_' + selector).blur(function () {
423 $('#previewSpanTitle_' + selector).html($('#previewInputTitle_' + selector).val());
424 $('#previewSpanTitle_' + selector).show();
425 $('#previewInputTitle_' + selector).hide();
428 $('#previewInputTitle_' + selector).keypress(function (e) {
429 if (e.which === 13) {
431 $('#previewSpanTitle_' + selector).html($('#previewInputTitle_' + selector).val());
432 $('#previewSpanTitle_' + selector).show();
433 $('#previewInputTitle_' + selector).hide();
437 $('#previewSpanDescription_' + selector).unbind('click').click(function (e) {
439 if (blockDescription === false) {
440 blockDescription = true;
441 $('#previewSpanDescription_' + selector).hide();
442 $('#previewInputDescription_' + selector).show();
443 $('#previewInputDescription_' + selector).val($('#previewInputDescription_' + selector).val());
444 $('#previewInputDescription_' + selector).focus().select();
448 $('#previewInputDescription_' + selector).blur(function () {
449 blockDescription = false;
450 $('#previewSpanDescription_' + selector).html($('#previewInputDescription_' + selector).val());
451 $('#previewSpanDescription_' + selector).show();
452 $('#previewInputDescription_' + selector).hide();
455 $('#previewInputDescription_' + selector).keypress(function (e) {
456 if (e.which === 13) {
457 blockDescription = false;
458 $('#previewSpanDescription_' + selector).html($('#previewInputDescription_' + selector).val());
459 $('#previewSpanDescription_' + selector).show();
460 $('#previewInputDescription_' + selector).hide();
464 $('#previewSpanTitle_' + selector).mouseover(function () {
465 $('#previewSpanTitle_' + selector).css({
466 "background-color": "#ff9"
470 $('#previewSpanTitle_' + selector).mouseout(function () {
471 $('#previewSpanTitle_' + selector).css({
472 "background-color": "transparent"
476 $('#previewSpanDescription_' + selector).mouseover(function () {
477 $('#previewSpanDescription_' + selector).css({
478 "background-color": "#ff9"
482 $('#previewSpanDescription_' + selector).mouseout(function () {
483 $('#previewSpanDescription_' + selector).css({
484 "background-color": "transparent"
488 $('#closePreview_' + selector).unbind('click').click(function (e) {
494 $('#preview_' + selector).fadeOut("fast", function () {
495 $('#preview_' + selector).remove();
496 $('#profile-rotator').hide();
497 $('#' + selector).focus();
504 * Convert attachmant bbcode into an array.
506 * @param {string} content Text content with the attachment bbcode.
507 * @returns {object || null}
509 var getAttachmentData = function(content) {
512 var match = content.match(/([\s\S]*)\[attachment([\s\S]*?)\]([\s\S]*?)\[\/attachment\]([\s\S]*)/im);
513 if (match === null || match.length < 5) {
517 var attributes = match[2];
518 data.text = trim(match[1]);
521 var matches = attributes.match(/type='([\s\S]*?)'/im);
522 if (matches !== null && typeof matches[1] !== 'undefined') {
523 type = matches[1].toLowerCase();
526 matches = attributes.match(/type="([\s\S]*?)"/im);
527 if (matches !== null && typeof matches[1] !== 'undefined') {
528 type = matches[1].toLowerCase();
550 matches = attributes.match(/url='([\s\S]*?)'/im);
551 if (matches !== null && typeof matches[1] !== 'undefined') {
552 url = matches[1].toLowerCase();
555 matches = attributes.match(/url="([\s\S]*?)"/im);
556 if (matches !== null && typeof matches[1] !== 'undefined') {
557 url = matches[1].toLowerCase();
561 data.url = escapeHTML(url);
566 matches = attributes.match(/title='([\s\S]*?)'/im);
567 if (matches !== null && typeof matches[1] !== 'undefined') {
568 title = matches[1].toLowerCase();
571 matches = attributes.match(/title="([\s\S]*?)"/im);
572 if (matches !== null && typeof matches[1] !== 'undefined') {
573 title = matches[1].toLowerCase();
577 data.title = escapeHTML(title);
582 matches = attributes.match(/image='([\s\S]*?)'/im);
583 if (matches !== null && typeof matches[1] !== 'undefined') {
584 image = matches[1].toLowerCase();
587 matches = attributes.match(/image="([\s\S]*?)"/im);
588 if (matches !== null && typeof matches[1] !== 'undefined') {
589 image = matches[1].toLowerCase();
593 data.image = escapeHTML(image);
598 matches = attributes.match(/preview='([\s\S]*?)'/im);
599 if (matches !== null && typeof matches[1] !== 'undefined') {
600 preview = matches[1].toLowerCase();
603 matches = attributes.match(/preview="([\s\S]*?)"/im);
604 if (matches !== null && typeof matches[1] !== 'undefined') {
605 preview = matches[1].toLowerCase();
608 if (preview !== '') {
609 data.preview = escapeHTML(preview);
612 data.text = trim(match[3]);
613 data.after = trim(match[4]);
619 * Process txt content and if it contains attachment bbcode
620 * add it to the attachment preview .
622 * @param {string} content
625 var addBBCodeToPreview =function(content) {
626 var attachmentData = getAttachmentData(content);
627 if (attachmentData) {
628 reAddAttachment(attachmentData);
629 // Remove the attachment bbcode from the textarea.
630 var content = content.replace(/\[attachment[\s\S]*\[\/attachment]/im, '');
631 $('#' + selector).val(content);
632 $('#' + selector).focus();
637 * Add an Attachment with data from an old bbcode
638 * generated attachment.
640 * @param {object} json The attachment data.
643 var reAddAttachment = function(json) {
645 $('#profile-rotator').hide();
649 if (json.type !== 'link' && json.type !== 'video' && json.type !== 'photo' || json.url === json.title) {
650 $('#profile-rotator').hide();
654 var obj = {data: json};
655 obj = sanitizeInputData(obj);
661 processAttachmentTpl(data);
662 addTitleDescription(data);
663 addHostToAttachment(data.url);
665 // Since we don't have an array of image data,
666 // we need to add the preview images in a different way
667 // than in function addImagesToAttachment().
668 var imageClass = 'attachment-preview';
671 if (data.image !== '') {
672 imageClass = 'attachment-image';
675 image = data.preview;
679 var appendImage = "<img id='imagePreview_" + selector + "' src='" + image + "' class='" + imageClass + "' ></img>"
680 $('#previewImage_' + selector).html(appendImage);
681 $('#attachmentImageSrc_' + selector).val(bin2hex(image));
683 // We need to add the image widht and height when it is
687 $('#attachmentImageWidth_' + selector).val(this.width);
688 $('#attachmentImageHeight_' + selector).val(this.height);
694 processEventListener();
695 $('#profile-rotator').hide();
699 * Add missing default properties to the input data object.
701 * @param {object} obj Input data.
704 var sanitizeInputData = function(obj) {
705 if (typeof obj.contentType === 'undefined'
706 || obj.contentType === null)
708 obj.contentType = "";
710 if (typeof obj.data.url === 'undefined'
711 || obj.data.url === null)
715 if (typeof obj.data.title === 'undefined'
716 || obj.data.title === null
717 || obj.data.title === "")
719 obj.data.title = defaultTitle;
721 if (typeof obj.data.text === 'undefined'
722 || obj.data.text === null
723 || obj.data.text === "")
727 if (typeof obj.data.images === 'undefined'
728 || obj.data.images === null)
730 obj.data.images = "";
733 if (typeof obj.data.image === 'undefined'
734 || obj.data.image === null)
739 if (typeof obj.data.preview === 'undefined'
740 || obj.data.preview === null)
742 obj.data.preview = "";
749 * Destroy the plugin.
753 var destroy = function() {
754 $('#' + selector).unbind();
755 $('#preview_' + selector).remove();
759 blockDescription = false;
770 var trim = function(str) {
771 return str.replace(/^\s+|\s+$/g, "");
773 var escapeHTML = function(unsafe_str) {
775 .replace(/&/g, '&')
776 .replace(/</g, '<')
777 .replace(/>/g, '>')
778 .replace(/\"/g, '"')
779 .replace(/\[/g, '[')
780 .replace(/\]/g, ']')
781 .replace(/\'/g, '''); // ''' is not valid HTML 4
784 // Initialize LinkPreview
788 // make crawlText() accessable from the outside.
789 crawlText: function(text) {
792 addBBCodeToPreview: function(content) {
793 addBBCodeToPreview(content);
795 destroy: function() {
801 $.fn.linkPreview.defaults = {
802 defaultDescription: "Enter a description",
803 defaultTitle: "Enter a title"
807 * Get in a textarea the previous word before the cursor.
809 * @param {object} text Textarea elemet.
810 * @param {integer} caretPos Cursor position.
812 * @returns {string} Previous word.
814 function returnWord(text, caretPos) {
815 var index = text.indexOf(caretPos);
816 var preText = text.substring(0, caretPos);
817 // If the last charachter is a space or enter remove it
818 // We need this in friendica for the url preview.
819 var lastChar = preText.slice(-1)
820 if ( lastChar === " "
825 preText = preText.substring(0, preText.length -1);
828 // Replace new line with space.
829 preText = preText.replace(/\n/g, " ");
831 if (preText.indexOf(" ") > 0) {
832 var words = preText.split(" ");
833 return words[words.length - 1]; //return last word
841 * Get in a textarea the previous word before the cursor.
843 * @param {string} id The ID of a textarea element.
844 * @returns {sting|null} Previous word or null if no word is available.
846 function getPrevWord(id) {
847 var text = document.getElementById(id);
848 var caretPos = getCaretPosition(text);
849 var word = returnWord(text.value, caretPos);
857 * Get the cursor posiotion in an text element.
859 * @param {object} ctrl Textarea elemet.
860 * @returns {integer} Position of the cursor.
862 function getCaretPosition(ctrl) {
863 var CaretPos = 0; // IE Support
864 if (document.selection) {
866 var Sel = document.selection.createRange();
867 Sel.moveStart('character', -ctrl.value.length);
868 CaretPos = Sel.text.length;
871 else if (ctrl.selectionStart || ctrl.selectionStart == '0') {
872 CaretPos = ctrl.selectionStart;