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) !== "" && block === false && urlRegex.test(text)) {
137 binurl = bin2hex(text);
141 $('#profile-rotator').show();
143 if (binurl in cache) {
145 processContentData(cache[binurl]);
147 getContentData(binurl, processContentData);
153 * Process the attachment data according to
154 * its content type (image, audio, video, attachment)
156 * @param {object} result
159 var processContentData = function(result) {
160 if (result.contentType === 'image') {
161 insertImage(result.data);
163 if (result.contentType === 'audio') {
164 insertAudio(result.data);
166 if (result.contentType === 'video') {
167 insertVideo(result.data);
169 if (result.contentType === 'attachment') {
170 insertAttachment(result.data);
172 $('#profile-rotator').hide();
176 * Fetch the content of link which should be attached.
178 * @param {string} binurl Link which should be attached as hexadecimal string.
179 * @param {type} callback
182 var getContentData = function(binurl, callback) {
183 $.get('parse_url?binurl='+ binurl + '&format=json', function (answer) {
184 obj = sanitizeInputData(answer);
186 // Put the data into a cache
196 * Add a [img] bbtag with the image url to the jot editor.
201 var insertImage = function(data) {
205 var bbcode = '\n[img]' + data.url + '[/img]\n';
206 addeditortext(bbcode);
210 * Add a [audio] bbtag with the audio url to the jot editor.
215 var insertAudio = function(data) {
219 var bbcode = '\n[audio]' + data.url + '[/audio]\n';
220 addeditortext(bbcode);
224 * Add a [video] bbtag with the video url to the jot editor.
229 var insertVideo = function(data) {
233 var bbcode = '\n[video]' + data.url + '[/video]\n';
234 addeditortext(bbcode);
238 * Proccess all attachment data and show up a html
239 * attachment preview.
241 * @param {obj} data Attachment data.
244 var insertAttachment = function(data) {
245 // If we have already a preview, leaver here.
246 // Note: if we finish the Preview of other media content type,
247 // we can move this condition to the beggining of crawlText();
249 $('#profile-rotator').hide();
253 if (data.type !== 'link' && data.type !== 'video' && data.type !== 'photo' || data.url === data.title) {
254 $('#profile-rotator').hide();
258 $('#photoNumber_' + selector).val(0);
261 processAttachmentTpl(data, 'type-' + data.type);
262 addTitleDescription(data);
263 addHostToAttachment(data.url);
264 addImagesToAttachment(data.images);
266 processEventListener();
267 $('#profile-rotator').hide();
271 * Construct the attachment html from the attachment template and
274 * @param {object} data Attachment data.
277 var processAttachmentTpl = function(data) {
278 // Load and add the template if it isn't allready loaded.
279 if ($('#preview_' + selector).length === 0) {
280 var tpl = previewTpl.format(
287 $('#' + selector).after(tpl);
294 * Add the attachment title and the description
295 * to the attachment preview.
297 * @param {object} data Attachment data.
300 var addTitleDescription = function(data) {
301 var description = data.text;
303 if (description === '') {
304 description = defaultDescription;
307 $('#previewTitle_' + selector).html("\
308 <span id='previewSpanTitle_" + selector + "' class='previewSpanTitle' >" + escapeHTML(data.title) + "</span>\
309 <input type='text' name='attachment_title' value='" + escapeHTML(data.title) + "' id='previewInputTitle_" + selector + "' class='previewInputTitle inputPreview' style='display: none;'/>"
312 $('#previewDescription_' + selector).html("\
313 <span id='previewSpanDescription_" + selector + "' class='previewSpanDescription' >" + escapeHTML(description) + "</span>\n\
314 <textarea id='previewInputDescription_" + selector + "' name='attachment_text' class='previewInputDescription' style='display: none;' class='inputPreview' >" + escapeHTML(data.text) + "</textarea>"
319 * Add the host to the attachment preview.
321 * @param {string} url The url of the link attachment.
324 var addHostToAttachment = function(url) {
326 var regexpr = "(https?://)([^:^/]*)(:\\d*)?(.*)?";
327 var regResult = url.match(regexpr);
328 var urlHost = regResult[1] + regResult[2];
329 $('#previewUrl_' + selector).html("<a href='" + url + "'>" + urlHost + "</a>");
334 * Add preview images to the attachment.
336 * @param {array} images
340 var addImagesToAttachment = function(images) {
341 var imageClass = 'attachment-preview';
343 if (Array.isArray(images)) {
344 $('#previewImages_' + selector).show();
345 $('#attachmentImageSrc_' + selector).val(bin2hex(images[photoNumber].src));
346 $('#attachmentImageWidth_' + selector).val(images[photoNumber].width);
347 $('#attachmentImageHeight_' + selector).val(images[photoNumber].height);
349 $('#previewImages_' + selector).hide();
352 images.length = parseInt(images.length);
353 var appendImage = "";
355 for (i = 0; i < images.length; i++) {
356 // For small preview images we use a smaller attachment format.
357 ///@todo here we need to add a check for !Config::get('system', 'always_show_preview').
358 if (images[i].width >= 500 && images[i].width >= images[i].height) {
359 imageClass = 'attachment-image';
363 appendImage += "<img id='imagePreview_" + selector + "_" + i + "' src='" + images[i].src + "' class='" + imageClass + "' ></img>";
365 appendImage += "<img id='imagePreview_" + selector + "_" + i + "' src='" + images[i].src + "' class='" + imageClass + "' style='display: none;'></img>";
369 $('#previewImage_' + selector).html(appendImage + "<div id='whiteImage' style='color: transparent; display:none;'>...</div>");
371 // More than just one image.
372 if (images.length > 1) {
373 // Enable the the button to change the preview pictures.
374 $('#previewChangeImg_' + selector).show();
376 if (firstPosted === false) {
379 $('#previewChangeImg_' + selector).unbind('click').click(function (e) {
381 if (images.length > 1) {
382 $('#imagePreview_' + selector + '_' + photoNumber).css({
387 // If have reached the last image, begin with the first image.
388 if (photoNumber === images.length) {
392 $('#imagePreview_' + selector + '_' + photoNumber).css({
395 $('#photoNumber_' + selector).val(photoNumber);
396 $('#attachmentImageSrc_' + selector).val(bin2hex(images[photoNumber].src));
397 $('#attachmentImageWidth_' + selector).val(images[photoNumber].width);
398 $('#attachmentImageHeight_' + selector).val(images[photoNumber].height);
406 * Add event listener to control the attachment preview.
410 var processEventListener = function() {
411 $('#previewSpanTitle_' + selector).unbind('click').click(function (e) {
413 if (blockTitle === false) {
415 $('#previewSpanTitle_' + selector).hide();
416 $('#previewInputTitle_' + selector).show();
417 $('#previewInputTitle_' + selector).val($('#previewInputTitle_' + selector).val());
418 $('#previewInputTitle_' + selector).focus().select();
422 $('#previewInputTitle_' + selector).blur(function () {
424 $('#previewSpanTitle_' + selector).html($('#previewInputTitle_' + selector).val());
425 $('#previewSpanTitle_' + selector).show();
426 $('#previewInputTitle_' + selector).hide();
429 $('#previewInputTitle_' + selector).keypress(function (e) {
430 if (e.which === 13) {
432 $('#previewSpanTitle_' + selector).html($('#previewInputTitle_' + selector).val());
433 $('#previewSpanTitle_' + selector).show();
434 $('#previewInputTitle_' + selector).hide();
438 $('#previewSpanDescription_' + selector).unbind('click').click(function (e) {
440 if (blockDescription === false) {
441 blockDescription = true;
442 $('#previewSpanDescription_' + selector).hide();
443 $('#previewInputDescription_' + selector).show();
444 $('#previewInputDescription_' + selector).val($('#previewInputDescription_' + selector).val());
445 $('#previewInputDescription_' + selector).focus().select();
449 $('#previewInputDescription_' + selector).blur(function () {
450 blockDescription = false;
451 $('#previewSpanDescription_' + selector).html($('#previewInputDescription_' + selector).val());
452 $('#previewSpanDescription_' + selector).show();
453 $('#previewInputDescription_' + selector).hide();
456 $('#previewInputDescription_' + selector).keypress(function (e) {
457 if (e.which === 13) {
458 blockDescription = false;
459 $('#previewSpanDescription_' + selector).html($('#previewInputDescription_' + selector).val());
460 $('#previewSpanDescription_' + selector).show();
461 $('#previewInputDescription_' + selector).hide();
465 $('#previewSpanTitle_' + selector).mouseover(function () {
466 $('#previewSpanTitle_' + selector).css({
467 "background-color": "#ff9"
471 $('#previewSpanTitle_' + selector).mouseout(function () {
472 $('#previewSpanTitle_' + selector).css({
473 "background-color": "transparent"
477 $('#previewSpanDescription_' + selector).mouseover(function () {
478 $('#previewSpanDescription_' + selector).css({
479 "background-color": "#ff9"
483 $('#previewSpanDescription_' + selector).mouseout(function () {
484 $('#previewSpanDescription_' + selector).css({
485 "background-color": "transparent"
489 $('#closePreview_' + selector).unbind('click').click(function (e) {
495 $('#preview_' + selector).fadeOut("fast", function () {
496 $('#preview_' + selector).remove();
497 $('#profile-rotator').hide();
498 $('#' + selector).focus();
505 * Convert attachmant bbcode into an array.
507 * @param {string} content Text content with the attachment bbcode.
508 * @returns {object || null}
510 var getAttachmentData = function(content) {
513 var match = content.match(/([\s\S]*)\[attachment([\s\S]*?)\]([\s\S]*?)\[\/attachment\]([\s\S]*)/im);
514 if (match === null || match.length < 5) {
518 var attributes = match[2];
519 data.text = trim(match[1]);
522 var matches = attributes.match(/type='([\s\S]*?)'/im);
523 if (matches !== null && typeof matches[1] !== 'undefined') {
524 type = matches[1].toLowerCase();
527 matches = attributes.match(/type="([\s\S]*?)"/im);
528 if (matches !== null && typeof matches[1] !== 'undefined') {
529 type = matches[1].toLowerCase();
551 matches = attributes.match(/url='([\s\S]*?)'/im);
552 if (matches !== null && typeof matches[1] !== 'undefined') {
553 url = matches[1].toLowerCase();
556 matches = attributes.match(/url="([\s\S]*?)"/im);
557 if (matches !== null && typeof matches[1] !== 'undefined') {
558 url = matches[1].toLowerCase();
562 data.url = escapeHTML(url);
567 matches = attributes.match(/title='([\s\S]*?)'/im);
568 if (matches !== null && typeof matches[1] !== 'undefined') {
569 title = matches[1].toLowerCase();
572 matches = attributes.match(/title="([\s\S]*?)"/im);
573 if (matches !== null && typeof matches[1] !== 'undefined') {
574 title = matches[1].toLowerCase();
578 data.title = escapeHTML(title);
583 matches = attributes.match(/image='([\s\S]*?)'/im);
584 if (matches !== null && typeof matches[1] !== 'undefined') {
585 image = matches[1].toLowerCase();
588 matches = attributes.match(/image="([\s\S]*?)"/im);
589 if (matches !== null && typeof matches[1] !== 'undefined') {
590 image = matches[1].toLowerCase();
594 data.image = escapeHTML(image);
599 matches = attributes.match(/preview='([\s\S]*?)'/im);
600 if (matches !== null && typeof matches[1] !== 'undefined') {
601 preview = matches[1].toLowerCase();
604 matches = attributes.match(/preview="([\s\S]*?)"/im);
605 if (matches !== null && typeof matches[1] !== 'undefined') {
606 preview = matches[1].toLowerCase();
609 if (preview !== '') {
610 data.preview = escapeHTML(preview);
613 data.text = trim(match[3]);
614 data.after = trim(match[4]);
620 * Process txt content and if it contains attachment bbcode
621 * add it to the attachment preview .
623 * @param {string} content
626 var addBBCodeToPreview =function(content) {
627 var attachmentData = getAttachmentData(content);
628 if (attachmentData) {
629 reAddAttachment(attachmentData);
630 // Remove the attachment bbcode from the textarea.
631 var content = content.replace(/\[attachment[\s\S]*\[\/attachment]/im, '');
632 $('#' + selector).val(content);
633 $('#' + selector).focus();
638 * Add an Attachment with data from an old bbcode
639 * generated attachment.
641 * @param {object} json The attachment data.
644 var reAddAttachment = function(json) {
646 $('#profile-rotator').hide();
650 if (json.type !== 'link' && json.type !== 'video' && json.type !== 'photo' || json.url === json.title) {
651 $('#profile-rotator').hide();
655 var obj = {data: json};
656 obj = sanitizeInputData(obj);
662 processAttachmentTpl(data);
663 addTitleDescription(data);
664 addHostToAttachment(data.url);
666 // Since we don't have an array of image data,
667 // we need to add the preview images in a different way
668 // than in function addImagesToAttachment().
669 var imageClass = 'attachment-preview';
672 if (data.image !== '') {
673 imageClass = 'attachment-image';
676 image = data.preview;
680 var appendImage = "<img id='imagePreview_" + selector + "' src='" + image + "' class='" + imageClass + "' ></img>"
681 $('#previewImage_' + selector).html(appendImage);
682 $('#attachmentImageSrc_' + selector).val(bin2hex(image));
684 // We need to add the image widht and height when it is
688 $('#attachmentImageWidth_' + selector).val(this.width);
689 $('#attachmentImageHeight_' + selector).val(this.height);
695 processEventListener();
696 $('#profile-rotator').hide();
700 * Add missing default properties to the input data object.
702 * @param {object} obj Input data.
705 var sanitizeInputData = function(obj) {
706 if (typeof obj.contentType === 'undefined'
707 || obj.contentType === null)
709 obj.contentType = "";
711 if (typeof obj.data.url === 'undefined'
712 || obj.data.url === null)
716 if (typeof obj.data.title === 'undefined'
717 || obj.data.title === null
718 || obj.data.title === "")
720 obj.data.title = defaultTitle;
722 if (typeof obj.data.text === 'undefined'
723 || obj.data.text === null
724 || obj.data.text === "")
728 if (typeof obj.data.images === 'undefined'
729 || obj.data.images === null)
731 obj.data.images = "";
734 if (typeof obj.data.image === 'undefined'
735 || obj.data.image === null)
740 if (typeof obj.data.preview === 'undefined'
741 || obj.data.preview === null)
743 obj.data.preview = "";
750 * Destroy the plugin.
754 var destroy = function() {
755 $('#' + selector).unbind();
756 $('#preview_' + selector).remove();
760 blockDescription = false;
771 var trim = function(str) {
772 return str.replace(/^\s+|\s+$/g, "");
774 var escapeHTML = function(unsafe_str) {
776 .replace(/&/g, '&')
777 .replace(/</g, '<')
778 .replace(/>/g, '>')
779 .replace(/\"/g, '"')
780 .replace(/\[/g, '[')
781 .replace(/\]/g, ']')
782 .replace(/\'/g, '''); // ''' is not valid HTML 4
785 // Initialize LinkPreview
789 // make crawlText() accessable from the outside.
790 crawlText: function(text) {
793 addBBCodeToPreview: function(content) {
794 addBBCodeToPreview(content);
796 destroy: function() {
802 $.fn.linkPreview.defaults = {
803 defaultDescription: "Enter a description",
804 defaultTitle: "Enter a title"
808 * Get in a textarea the previous word before the cursor.
810 * @param {object} text Textarea elemet.
811 * @param {integer} caretPos Cursor position.
813 * @returns {string} Previous word.
815 function returnWord(text, caretPos) {
816 var index = text.indexOf(caretPos);
817 var preText = text.substring(0, caretPos);
818 // If the last charachter is a space or enter remove it
819 // We need this in friendica for the url preview.
820 var lastChar = preText.slice(-1)
821 if ( lastChar === " "
826 preText = preText.substring(0, preText.length -1);
829 // Replace new line with space.
830 preText = preText.replace(/\n/g, " ");
832 if (preText.indexOf(" ") > 0) {
833 var words = preText.split(" ");
834 return words[words.length - 1]; //return last word
842 * Get in a textarea the previous word before the cursor.
844 * @param {string} id The ID of a textarea element.
845 * @returns {sting|null} Previous word or null if no word is available.
847 function getPrevWord(id) {
848 var text = document.getElementById(id);
849 var caretPos = getCaretPosition(text);
850 var word = returnWord(text.value, caretPos);
858 * Get the cursor posiotion in an text element.
860 * @param {object} ctrl Textarea elemet.
861 * @returns {integer} Position of the cursor.
863 function getCaretPosition(ctrl) {
864 var CaretPos = 0; // IE Support
865 if (document.selection) {
867 var Sel = document.selection.createRange();
868 Sel.moveStart('character', -ctrl.value.length);
869 CaretPos = Sel.text.length;
872 else if (ctrl.selectionStart || ctrl.selectionStart == '0') {
873 CaretPos = ctrl.selectionStart;