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">';
55 var urlRegex = /(https?\:\/\/|\s)[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})(\/+[a-z0-9_.\:\;-]*)*(\?[\&\%\|\+a-z0-9_=,\.\:\;-]*)?([\&\%\|\+&a-z0-9_=,\:\;\.-]*)([\!\#\/\&\%\|\+a-z0-9_=,\:\;\.-]*)}*/i;
58 var blockTitle = false;
59 var blockDescription = false;
64 var firstPosted = false;
66 var isCrawling = false;
67 var defaultTitle = opts.defaultTitle;
68 var defaultDescription = opts.defaultDescription;
71 * Initialize the plugin
75 var init = function() {
76 $('#' + selector).bind({
78 setTimeout(function () {
83 // on enter, space, ctrl
84 if ((e.which === 13 || e.which === 32 || e.which === 17)) {
90 // Check if we have already attachment bbcode in the textarea
91 // and add it to the attachment preview.
92 var content = $('#' + selector).val();
93 addBBCodeToPreview(content);
101 var resetPreview = function() {
102 $('#hasAttachment_' + selector).val(0);
108 * Crawl a text string if it contains an url and try
111 * If no text is passed to crawlText() we take
112 * the previous word before the cursor of the textarea.
114 * @param {string} text (optional)
117 var crawlText = function (text) {
122 // If no text is passed to crawlText() we
123 // take the previous word before the cursor.
124 if (typeof text === 'undefined') {
125 text = getPrevWord(selector);
130 // Don't procces the textarea input if we have already
131 // an attachment preview.
132 if (!isExtern && isActive) {
136 if (trim(text) !== "") {
137 if (block === false && urlRegex.test(text)) {
138 binurl = bin2hex(text);
142 $('#profile-rotator').show();
144 if (binurl in cache) {
146 processContentData(cache[binurl]);
148 getContentData(binurl, processContentData);
155 * Process the attachment data according to
156 * its content type (image, audio, video, attachment)
158 * @param {object} result
161 var processContentData = function(result) {
162 if (result.contentType === 'image') {
163 insertImage(result.data);
165 if (result.contentType === 'audio') {
166 insertAudio(result.data);
168 if (result.contentType === 'video') {
169 insertVideo(result.data);
171 if (result.contentType === 'attachment') {
172 insertAttachment(result.data);
174 $('#profile-rotator').hide();
178 * Fetch the content of link which should be attached.
180 * @param {string} binurl Link which should be attached as hexadecimal string.
181 * @param {type} callback
184 var getContentData = function(binurl, callback) {
185 $.get('parse_url?binurl='+ binurl + '&format=json', function (answer) {
186 obj = sanitizeInputData(answer);
188 // Put the data into a cache
198 * Add a [img] bbtag with the image url to the jot editor.
203 var insertImage = function(data) {
207 var bbcode = '\n[img]' + data.url + '[/img]\n';
208 addeditortext(bbcode);
212 * Add a [audio] bbtag with the audio url to the jot editor.
217 var insertAudio = function(data) {
221 var bbcode = '\n[audio]' + data.url + '[/audio]\n';
222 addeditortext(bbcode);
226 * Add a [video] bbtag with the video url to the jot editor.
231 var insertVideo = function(data) {
235 var bbcode = '\n[video]' + json.url + '[/video]\n';
236 addeditortext(bbcode);
240 * Proccess all attachment data and show up a html
241 * attachment preview.
243 * @param {obj} data Attachment data.
246 var insertAttachment = function(data) {
247 // If we have already a preview, leaver here.
248 // Note: if we finish the Preview of other media content type,
249 // we can move this condition to the beggining of crawlText();
251 $('#profile-rotator').hide();
255 if (data.type !== 'link' && data.type !== 'video' && data.type !== 'photo' || data.url === data.title) {
256 $('#profile-rotator').hide();
260 $('#photoNumber_' + selector).val(0);
263 processAttachmentTpl(data, 'type-' + data.type);
264 addTitleDescription(data);
265 addHostToAttachment(data.url);
266 addImagesToAttachment(data.images);
268 processEventListener();
269 $('#profile-rotator').hide();
273 * Construct the attachment html from the attachment template and
276 * @param {object} data Attachment data.
279 var processAttachmentTpl = function(data) {
280 // Load and add the template if it isn't allready loaded.
281 if ($('#preview_' + selector).length === 0) {
282 var tpl = previewTpl.format(
289 $('#' + selector).after(tpl);
296 * Add the attachment title and the description
297 * to the attachment preview.
299 * @param {object} data Attachment data.
302 var addTitleDescription = function(data) {
303 var description = data.text;
305 if (description === '') {
306 description = defaultDescription;
309 $('#previewTitle_' + selector).html("\
310 <span id='previewSpanTitle_" + selector + "' class='previewSpanTitle' >" + escapeHTML(data.title) + "</span>\
311 <input type='text' name='attachment_title' value='" + escapeHTML(data.title) + "' id='previewInputTitle_" + selector + "' class='previewInputTitle inputPreview' style='display: none;'/>"
314 $('#previewDescription_' + selector).html("\
315 <span id='previewSpanDescription_" + selector + "' class='previewSpanDescription' >" + escapeHTML(description) + "</span>\n\
316 <textarea id='previewInputDescription_" + selector + "' name='attachment_text' class='previewInputDescription' style='display: none;' class='inputPreview' >" + escapeHTML(data.text) + "</textarea>"
321 * Add the host to the attachment preview.
323 * @param {string} url The url of the link attachment.
326 var addHostToAttachment = function(url) {
328 var regexpr = "(https?://)([^:^/]*)(:\\d*)?(.*)?";
329 var regResult = url.match(regexpr);
330 var urlHost = regResult[1] + regResult[2];
331 $('#previewUrl_' + selector).html("<a href='" + url + "'>" + urlHost + "</a>");
336 * Add preview images to the attachment.
338 * @param {array} images
342 var addImagesToAttachment = function(images) {
343 var imageClass = 'attachment-preview';
345 if (Array.isArray(images)) {
346 $('#previewImages_' + selector).show();
347 $('#attachmentImageSrc_' + selector).val(bin2hex(images[photoNumber].src));
348 $('#attachmentImageWidth_' + selector).val(images[photoNumber].width);
349 $('#attachmentImageHeight_' + selector).val(images[photoNumber].height);
351 $('#previewImages_' + selector).hide();
354 images.length = parseInt(images.length);
355 var appendImage = "";
357 for (i = 0; i < images.length; i++) {
358 // For small preview images we use a smaller attachment format.
359 ///@todo here we need to add a check for !Config::get('system', 'always_show_preview').
360 if (images[i].width >= 500 && images[i].width >= images[i].height) {
361 imageClass = 'attachment-image';
365 appendImage += "<img id='imagePreview_" + selector + "_" + i + "' src='" + images[i].src + "' class='" + imageClass + "' ></img>";
367 appendImage += "<img id='imagePreview_" + selector + "_" + i + "' src='" + images[i].src + "' class='" + imageClass + "' style='display: none;'></img>";
371 $('#previewImage_' + selector).html(appendImage + "<div id='whiteImage' style='color: transparent; display:none;'>...</div>");
373 // More than just one image.
374 if (images.length > 1) {
375 // Enable the the button to change the preview pictures.
376 $('#previewChangeImg_' + selector).show();
378 if (firstPosted === false) {
381 $('#previewChangeImg_' + selector).unbind('click').click(function (e) {
383 if (images.length > 1) {
384 $('#imagePreview_' + selector + '_' + photoNumber).css({
389 // If have reached the last image, begin with the first image.
390 if (photoNumber === images.length) {
394 $('#imagePreview_' + selector + '_' + photoNumber).css({
397 $('#photoNumber_' + selector).val(photoNumber);
398 $('#attachmentImageSrc_' + selector).val(bin2hex(images[photoNumber].src));
399 $('#attachmentImageWidth_' + selector).val(images[photoNumber].width);
400 $('#attachmentImageHeight_' + selector).val(images[photoNumber].height);
408 * Add event listener to control the attachment preview.
412 var processEventListener = function() {
413 $('#previewSpanTitle_' + selector).unbind('click').click(function (e) {
415 if (blockTitle === false) {
417 $('#previewSpanTitle_' + selector).hide();
418 $('#previewInputTitle_' + selector).show();
419 $('#previewInputTitle_' + selector).val($('#previewInputTitle_' + selector).val());
420 $('#previewInputTitle_' + selector).focus().select();
424 $('#previewInputTitle_' + selector).blur(function () {
426 $('#previewSpanTitle_' + selector).html($('#previewInputTitle_' + selector).val());
427 $('#previewSpanTitle_' + selector).show();
428 $('#previewInputTitle_' + selector).hide();
431 $('#previewInputTitle_' + selector).keypress(function (e) {
432 if (e.which === 13) {
434 $('#previewSpanTitle_' + selector).html($('#previewInputTitle_' + selector).val());
435 $('#previewSpanTitle_' + selector).show();
436 $('#previewInputTitle_' + selector).hide();
440 $('#previewSpanDescription_' + selector).unbind('click').click(function (e) {
442 if (blockDescription === false) {
443 blockDescription = true;
444 $('#previewSpanDescription_' + selector).hide();
445 $('#previewInputDescription_' + selector).show();
446 $('#previewInputDescription_' + selector).val($('#previewInputDescription_' + selector).val());
447 $('#previewInputDescription_' + selector).focus().select();
451 $('#previewInputDescription_' + selector).blur(function () {
452 blockDescription = false;
453 $('#previewSpanDescription_' + selector).html($('#previewInputDescription_' + selector).val());
454 $('#previewSpanDescription_' + selector).show();
455 $('#previewInputDescription_' + selector).hide();
458 $('#previewInputDescription_' + selector).keypress(function (e) {
459 if (e.which === 13) {
460 blockDescription = false;
461 $('#previewSpanDescription_' + selector).html($('#previewInputDescription_' + selector).val());
462 $('#previewSpanDescription_' + selector).show();
463 $('#previewInputDescription_' + selector).hide();
467 $('#previewSpanTitle_' + selector).mouseover(function () {
468 $('#previewSpanTitle_' + selector).css({
469 "background-color": "#ff9"
473 $('#previewSpanTitle_' + selector).mouseout(function () {
474 $('#previewSpanTitle_' + selector).css({
475 "background-color": "transparent"
479 $('#previewSpanDescription_' + selector).mouseover(function () {
480 $('#previewSpanDescription_' + selector).css({
481 "background-color": "#ff9"
485 $('#previewSpanDescription_' + selector).mouseout(function () {
486 $('#previewSpanDescription_' + selector).css({
487 "background-color": "transparent"
491 $('#closePreview_' + selector).unbind('click').click(function (e) {
497 $('#preview_' + selector).fadeOut("fast", function () {
498 $('#preview_' + selector).remove();
499 $('#profile-rotator').hide();
500 $('#' + selector).focus();
507 * Convert attachmant bbcode into an array.
509 * @param {string} content Text content with the attachment bbcode.
510 * @returns {object || null}
512 var getAttachmentData = function(content) {
515 var match = content.match(/(.*)\[attachment(.*?)\](.*?)\[\/attachment\](.*)/ism);
516 if (match === null || match.length < 5) {
520 var attributes = match[2];
521 data.text = trim(match[1]);
524 var matches = attributes.match(/type='(.*?)'/ism);
525 if (matches !== null && typeof matches[1] !== 'undefined') {
526 type = matches[1].toLowerCase();
529 matches = attributes.match(/type="(.*?)"/ism);
530 if (matches !== null && typeof matches[1] !== 'undefined') {
531 type = matches[1].toLowerCase();
553 matches = attributes.match(/url='(.*?)'/ism);
554 if (matches !== null && typeof matches[1] !== 'undefined') {
555 url = matches[1].toLowerCase();
558 matches = attributes.match(/url="(.*?)"/ism);
559 if (matches !== null && typeof matches[1] !== 'undefined') {
560 url = matches[1].toLowerCase();
564 data.url = escapeHTML(url);
569 matches = attributes.match(/title='(.*?)'/ism);
570 if (matches !== null && typeof matches[1] !== 'undefined') {
571 title = matches[1].toLowerCase();
574 matches = attributes.match(/title="(.*?)"/ism);
575 if (matches !== null && typeof matches[1] !== 'undefined') {
576 title = matches[1].toLowerCase();
580 data.title = escapeHTML(title);
585 matches = attributes.match(/image='(.*?)'/ism);
586 if (matches !== null && typeof matches[1] !== 'undefined') {
587 image = matches[1].toLowerCase();
590 matches = attributes.match(/image="(.*?)"/ism);
591 if (matches !== null && typeof matches[1] !== 'undefined') {
592 image = matches[1].toLowerCase();
596 data.image = escapeHTML(image);
601 matches = attributes.match(/preview='(.*?)'/ism);
602 if (matches !== null && typeof matches[1] !== 'undefined') {
603 preview = matches[1].toLowerCase();
606 matches = attributes.match(/preview="(.*?)"/ism);
607 if (matches !== null && typeof matches[1] !== 'undefined') {
608 preview = matches[1].toLowerCase();
611 if (preview !== '') {
612 data.preview = escapeHTML(preview);
615 data.text = trim(match[3]);
616 data.after = trim(match[4]);
622 * Process txt content and if it contains attachment bbcode
623 * add it to the attachment preview .
625 * @param {string} content
628 var addBBCodeToPreview =function(content) {
629 var attachmentData = getAttachmentData(content);
630 if (attachmentData) {
631 reAddAttachment(attachmentData);
632 // Remove the attachment bbcode from the textarea.
633 var content = content.replace(/\[attachment.*\[\/attachment]/ism, '');
634 $('#' + selector).val(content);
635 $('#' + selector).focus();
640 * Add an Attachment with data from an old bbcode
641 * generated attachment.
643 * @param {object} json The attachment data.
646 var reAddAttachment = function(json) {
648 $('#profile-rotator').hide();
652 if (json.type !== 'link' && json.type !== 'video' && json.type !== 'photo' || json.url === json.title) {
653 $('#profile-rotator').hide();
657 var obj = {data: json};
658 obj = sanitizeInputData(obj);
664 processAttachmentTpl(data);
665 addTitleDescription(data);
666 addHostToAttachment(data.url);
668 // Since we don't have an array of image data,
669 // we need to add the preview images in a different way
670 // than in function addImagesToAttachment().
671 var imageClass = 'attachment-preview';
674 if (data.image !== '') {
675 imageClass = 'attachment-image';
678 image = data.preview;
682 var appendImage = "<img id='imagePreview_" + selector + "' src='" + image + "' class='" + imageClass + "' ></img>"
683 $('#previewImage_' + selector).html(appendImage);
684 $('#attachmentImageSrc_' + selector).val(bin2hex(image));
686 // We need to add the image widht and height when it is
690 $('#attachmentImageWidth_' + selector).val(this.width);
691 $('#attachmentImageHeight_' + selector).val(this.height);
697 processEventListener();
698 $('#profile-rotator').hide();
702 * Add missing default properties to the input data object.
704 * @param {object} obj Input data.
707 var sanitizeInputData = function(obj) {
708 if (typeof obj.contentType === 'undefined'
709 || obj.contentType === null)
711 obj.contentType = "";
713 if (typeof obj.data.url === 'undefined'
714 || obj.data.url === null)
718 if (typeof obj.data.title === 'undefined'
719 || obj.data.title === null
720 || obj.data.title === "")
722 obj.data.title = defaultTitle;
724 if (typeof obj.data.text === 'undefined'
725 || obj.data.text === null
726 || obj.data.text === "")
730 if (typeof obj.data.images === 'undefined'
731 || obj.data.images === null)
733 obj.data.images = "";
736 if (typeof obj.data.image === 'undefined'
737 || obj.data.image === null)
742 if (typeof obj.data.preview === 'undefined'
743 || obj.data.preview === null)
745 obj.data.preview = "";
752 * Destroy the plugin.
756 var destroy = function() {
757 $('#' + selector).unbind();
758 $('#preview_' + selector).remove();
762 blockDescription = false;
773 var trim = function(str) {
774 return str.replace(/^\s+|\s+$/g, "");
776 var escapeHTML = function(unsafe_str) {
778 .replace(/&/g, '&')
779 .replace(/</g, '<')
780 .replace(/>/g, '>')
781 .replace(/\"/g, '"')
782 .replace(/\[/g, '[')
783 .replace(/\]/g, ']')
784 .replace(/\'/g, '''); // ''' is not valid HTML 4
787 // Initialize LinkPreview
791 // make crawlText() accessable from the outside.
792 crawlText: function(text) {
795 addBBCodeToPreview: function(content) {
796 addBBCodeToPreview(content);
798 destroy: function() {
804 $.fn.linkPreview.defaults = {
805 defaultDescription: "Enter a description",
806 defaultTitle: "Enter a title"
810 * Get in a textarea the previous word before the cursor.
812 * @param {object} text Textarea elemet.
813 * @param {integer} caretPos Cursor position.
815 * @returns {string} Previous word.
817 function returnWord(text, caretPos) {
818 var index = text.indexOf(caretPos);
819 var preText = text.substring(0, caretPos);
820 // If the last charachter is a space or enter remove it
821 // We need this in friendica for the url preview.
822 var lastChar = preText.slice(-1)
823 if ( lastChar === " "
828 preText = preText.substring(0, preText.length -1);
831 // Replace new line with space.
832 preText = preText.replace(/\n/g, " ");
834 if (preText.indexOf(" ") > 0) {
835 var words = preText.split(" ");
836 return words[words.length - 1]; //return last word
844 * Get in a textarea the previous word before the cursor.
846 * @param {string} id The ID of a textarea element.
847 * @returns {sting|null} Previous word or null if no word is available.
849 function getPrevWord(id) {
850 var text = document.getElementById(id);
851 var caretPos = getCaretPosition(text);
852 var word = returnWord(text.value, caretPos);
860 * Get the cursor posiotion in an text element.
862 * @param {object} ctrl Textarea elemet.
863 * @returns {integer} Position of the cursor.
865 function getCaretPosition(ctrl) {
866 var CaretPos = 0; // IE Support
867 if (document.selection) {
869 var Sel = document.selection.createRange();
870 Sel.moveStart('character', -ctrl.value.length);
871 CaretPos = Sel.text.length;
874 else if (ctrl.selectionStart || ctrl.selectionStart == '0') {
875 CaretPos = ctrl.selectionStart;