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 id = $(this).attr('id');
20 <div id="preview_' + id + '" class="preview {0}">\
22 <input type="hidden" name="has_attachment" id="hasAttachment_' + id + '" value="{2}" />\
23 <input type="hidden" name="attachment_url" id="attachmentUrl_' + id + '" value="{3}" />\
24 <input type="hidden" name="attachment_type" id="attachmentType_' + id + '" value="{4}" />\
27 var attachmentTpl = '\
28 <hr class="previewseparator">\
29 <div id="closePreview_' + id + '" title="Remove" class="closePreview" >\
30 <button type="button" class="previewActionBtn">×</button>\
32 <div id="previewImages_' + id + '" class="previewImages">\
33 <div id="previewImgBtn_' + id + '" class="previewImgBtn">\
34 <button type="button" id="previewChangeImg_' + id + '" class="buttonChangeDeactive previewActionBtn" style="display: none">\
35 <i class="fa fa-exchange" aria-hidden="true"></i>\
38 <div id="previewImage_' + id + '" class="previewImage">\
40 <input type="hidden" id="photoNumber_' + id + '" class="photoNumber" value="0" />\
41 <input type="hidden" name="attachment_img_src" id="attachmentImageSrc_' + id + '" value="" />\
42 <input type="hidden" name="attachment_img_width" id="attachmentImageWidth_' + id + '" value="0" />\
43 <input type="hidden" name="attachment_img_height" id="attachmentImageHeight_' + id + '" value="0" />\
45 <div id="previewContent_' + id + '" class="previewContent">\
46 <h4 id="previewTitle_' + id + '" class="previewTitle"></h4>\
47 <blockquote id="previewDescription_' + id + '" class="previewDescription"></blockquote>\
48 <div id="hiddenDescription_' + id + '" class="hiddenDescription"></div>\
49 <sup id="previewUrl_' + id + '" class="previewUrl"></sup>\
51 <div class="clear"></div>\
52 <hr class="previewseparator">';
56 var blockTitle = false;
57 var blockDescription = false;
62 var firstPosted = false;
64 var isCrawling = false;
65 var defaultTitle = opts.defaultTitle;
66 var defaultDescription = opts.defaultDescription;
69 * Initialize the plugin
73 var init = function() {
76 setTimeout(function () {
81 // on enter, space, ctrl
82 if ((e.which === 13 || e.which === 32 || e.which === 17)) {
88 // Check if we have already attachment bbcode in the textarea
89 // and add it to the attachment preview.
90 var content = $('#' + id).val();
91 addBBCodeToPreview(content);
99 var resetPreview = function() {
100 $('#hasAttachment_' + id).val(0);
106 * Crawl a text string if it contains an url and try
109 * If no text is passed to crawlText() we take
110 * the previous word before the cursor of the textarea.
112 * @param {string} text (optional)
115 var crawlText = function (text) {
120 // If no text is passed to crawlText() we
121 // take the previous word before the cursor.
122 if (typeof text === 'undefined') {
123 text = getPrevWord(id);
128 // Don't procces the textarea input if we have already
129 // an attachment preview.
130 if (!isExtern && isActive) {
134 if (trim(text) !== "" && block === false && urlRegex.test(text)) {
135 binurl = bin2hex(text);
139 $('#profile-rotator').show();
141 if (binurl in cache) {
143 processContentData(cache[binurl]);
145 getContentData(binurl, processContentData);
151 * Process the attachment data according to
152 * its content type (image, audio, video, attachment)
154 * @param {object} result
157 var processContentData = function(result) {
158 if (result.contentType === 'image') {
159 insertImage(result.data);
161 if (result.contentType === 'audio') {
162 insertAudio(result.data);
164 if (result.contentType === 'video') {
165 insertVideo(result.data);
167 if (result.contentType === 'attachment') {
168 insertAttachment(result.data);
170 $('#profile-rotator').hide();
174 * Fetch the content of link which should be attached.
176 * @param {string} binurl Link which should be attached as hexadecimal string.
177 * @param {type} callback
180 var getContentData = function(binurl, callback) {
181 $.get('parse_url?binurl='+ binurl + '&format=json', function (answer) {
182 obj = sanitizeInputData(answer);
184 // Put the data into a cache
194 * Add a [img] bbtag with the image url to the jot editor.
199 var insertImage = function(data) {
203 var bbcode = '\n[img]' + data.url + '[/img]\n';
204 addeditortext(bbcode);
208 * Add a [audio] bbtag with the audio url to the jot editor.
213 var insertAudio = function(data) {
217 var bbcode = '\n[audio]' + data.url + '[/audio]\n';
218 addeditortext(bbcode);
222 * Add a [video] bbtag with the video url to the jot editor.
227 var insertVideo = function(data) {
231 var bbcode = '\n[video]' + data.url + '[/video]\n';
232 addeditortext(bbcode);
236 * Proccess all attachment data and show up a html
237 * attachment preview.
239 * @param {obj} data Attachment data.
242 var insertAttachment = function(data) {
243 // If we have already a preview, leaver here.
244 // Note: if we finish the Preview of other media content type,
245 // we can move this condition to the beggining of crawlText();
247 $('#profile-rotator').hide();
251 if (data.type !== 'link' && data.type !== 'video' && data.type !== 'photo' || data.url === data.title) {
252 $('#profile-rotator').hide();
256 $('#photoNumber_' + id).val(0);
259 processAttachmentTpl(data, 'type-' + data.type);
260 addTitleDescription(data);
261 addHostToAttachment(data.url);
262 addImagesToAttachment(data.images);
264 processEventListener();
265 $('#profile-rotator').hide();
269 * Construct the attachment html from the attachment template and
272 * @param {object} data Attachment data.
275 var processAttachmentTpl = function(data) {
276 // Load and add the template if it isn't allready loaded.
277 if ($('#preview_' + id).length === 0) {
278 var tpl = previewTpl.format(
285 $('#' + id).after(tpl);
292 * Add the attachment title and the description
293 * to the attachment preview.
295 * @param {object} data Attachment data.
298 var addTitleDescription = function(data) {
299 var description = data.text;
301 if (description === '') {
302 description = defaultDescription;
305 $('#previewTitle_' + id).html("\
306 <span id='previewSpanTitle_" + id + "' class='previewSpanTitle' >" + escapeHTML(data.title) + "</span>\
307 <input type='text' name='attachment_title' value='" + escapeHTML(data.title) + "' id='previewInputTitle_" + id + "' class='previewInputTitle inputPreview' style='display: none;'/>"
310 $('#previewDescription_' + id).html("\
311 <span id='previewSpanDescription_" + id + "' class='previewSpanDescription' >" + escapeHTML(description) + "</span>\n\
312 <textarea id='previewInputDescription_" + id + "' name='attachment_text' class='previewInputDescription' style='display: none;' class='inputPreview' >" + escapeHTML(data.text) + "</textarea>"
317 * Add the host to the attachment preview.
319 * @param {string} url The url of the link attachment.
322 var addHostToAttachment = function(url) {
324 var regexpr = "(https?://)([^:^/]*)(:\\d*)?(.*)?";
325 var regResult = url.match(regexpr);
326 var urlHost = regResult[1] + regResult[2];
327 $('#previewUrl_' + id).html("<a href='" + url + "'>" + urlHost + "</a>");
332 * Add preview images to the attachment.
334 * @param {array} images
338 var addImagesToAttachment = function(images) {
339 var imageClass = 'attachment-preview';
341 if (Array.isArray(images)) {
342 $('#previewImages_' + id).show();
343 $('#attachmentImageSrc_' + id).val(bin2hex(images[photoNumber].src));
344 $('#attachmentImageWidth_' + id).val(images[photoNumber].width);
345 $('#attachmentImageHeight_' + id).val(images[photoNumber].height);
347 $('#previewImages_' + id).hide();
350 images.length = parseInt(images.length);
351 var appendImage = "";
353 for (i = 0; i < images.length; i++) {
354 // For small preview images we use a smaller attachment format.
355 ///@todo here we need to add a check for !DI::config()->get('system', 'always_show_preview').
356 if (images[i].width >= 500 && images[i].width >= images[i].height) {
357 imageClass = 'attachment-image';
361 appendImage += "<img id='imagePreview_" + id + "_" + i + "' src='" + images[i].src + "' class='" + imageClass + "' ></img>";
363 appendImage += "<img id='imagePreview_" + id + "_" + i + "' src='" + images[i].src + "' class='" + imageClass + "' style='display: none;'></img>";
367 $('#previewImage_' + id).html(appendImage + "<div id='whiteImage' style='color: transparent; display:none;'>...</div>");
369 // More than just one image.
370 if (images.length > 1) {
371 // Enable the the button to change the preview pictures.
372 $('#previewChangeImg_' + id).show();
374 if (firstPosted === false) {
377 $('#previewChangeImg_' + id).unbind('click').click(function (e) {
379 if (images.length > 1) {
380 $('#imagePreview_' + id + '_' + photoNumber).css({
385 // If have reached the last image, begin with the first image.
386 if (photoNumber === images.length) {
390 $('#imagePreview_' + id + '_' + photoNumber).css({
393 $('#photoNumber_' + id).val(photoNumber);
394 $('#attachmentImageSrc_' + id).val(bin2hex(images[photoNumber].src));
395 $('#attachmentImageWidth_' + id).val(images[photoNumber].width);
396 $('#attachmentImageHeight_' + id).val(images[photoNumber].height);
404 * Add event listener to control the attachment preview.
408 var processEventListener = function() {
409 $('#previewSpanTitle_' + id).unbind('click').click(function (e) {
411 if (blockTitle === false) {
413 $('#previewSpanTitle_' + id).hide();
414 $('#previewInputTitle_' + id).show();
415 $('#previewInputTitle_' + id).val($('#previewInputTitle_' + id).val());
416 $('#previewInputTitle_' + id).focus().select();
420 $('#previewInputTitle_' + id).blur(function () {
422 $('#previewSpanTitle_' + id).html($('#previewInputTitle_' + id).val());
423 $('#previewSpanTitle_' + id).show();
424 $('#previewInputTitle_' + id).hide();
427 $('#previewInputTitle_' + id).keypress(function (e) {
428 if (e.which === 13) {
430 $('#previewSpanTitle_' + id).html($('#previewInputTitle_' + id).val());
431 $('#previewSpanTitle_' + id).show();
432 $('#previewInputTitle_' + id).hide();
436 $('#previewSpanDescription_' + id).unbind('click').click(function (e) {
438 if (blockDescription === false) {
439 blockDescription = true;
440 $('#previewSpanDescription_' + id).hide();
441 $('#previewInputDescription_' + id).show();
442 $('#previewInputDescription_' + id).val($('#previewInputDescription_' + id).val());
443 $('#previewInputDescription_' + id).focus().select();
447 $('#previewInputDescription_' + id).blur(function () {
448 blockDescription = false;
449 $('#previewSpanDescription_' + id).html($('#previewInputDescription_' + id).val());
450 $('#previewSpanDescription_' + id).show();
451 $('#previewInputDescription_' + id).hide();
454 $('#previewInputDescription_' + id).keypress(function (e) {
455 if (e.which === 13) {
456 blockDescription = false;
457 $('#previewSpanDescription_' + id).html($('#previewInputDescription_' + id).val());
458 $('#previewSpanDescription_' + id).show();
459 $('#previewInputDescription_' + id).hide();
463 $('#previewSpanTitle_' + id).mouseover(function () {
464 $('#previewSpanTitle_' + id).css({
465 "background-color": "#ff9"
469 $('#previewSpanTitle_' + id).mouseout(function () {
470 $('#previewSpanTitle_' + id).css({
471 "background-color": "transparent"
475 $('#previewSpanDescription_' + id).mouseover(function () {
476 $('#previewSpanDescription_' + id).css({
477 "background-color": "#ff9"
481 $('#previewSpanDescription_' + id).mouseout(function () {
482 $('#previewSpanDescription_' + id).css({
483 "background-color": "transparent"
487 $('#closePreview_' + id).unbind('click').click(function (e) {
493 $('#preview_' + id).fadeOut("fast", function () {
494 $('#preview_' + id).remove();
495 $('#profile-rotator').hide();
503 * Convert attachmant bbcode into an array.
505 * @param {string} content Text content with the attachment bbcode.
506 * @returns {object || null}
508 var getAttachmentData = function(content) {
511 var match = content.match(/([\s\S]*)\[attachment([\s\S]*?)\]([\s\S]*?)\[\/attachment\]([\s\S]*)/im);
512 if (match === null || match.length < 5) {
516 var attributes = match[2];
517 data.text = trim(match[1]);
520 var matches = attributes.match(/type='([\s\S]*?)'/im);
521 if (matches !== null && typeof matches[1] !== 'undefined') {
522 type = matches[1].toLowerCase();
525 matches = attributes.match(/type="([\s\S]*?)"/im);
526 if (matches !== null && typeof matches[1] !== 'undefined') {
527 type = matches[1].toLowerCase();
549 matches = attributes.match(/url='([\s\S]*?)'/im);
550 if (matches !== null && typeof matches[1] !== 'undefined') {
551 url = matches[1].toLowerCase();
554 matches = attributes.match(/url="([\s\S]*?)"/im);
555 if (matches !== null && typeof matches[1] !== 'undefined') {
556 url = matches[1].toLowerCase();
560 data.url = escapeHTML(url);
565 matches = attributes.match(/title='([\s\S]*?)'/im);
566 if (matches !== null && typeof matches[1] !== 'undefined') {
567 title = matches[1].toLowerCase();
570 matches = attributes.match(/title="([\s\S]*?)"/im);
571 if (matches !== null && typeof matches[1] !== 'undefined') {
572 title = matches[1].toLowerCase();
576 data.title = escapeHTML(title);
581 matches = attributes.match(/image='([\s\S]*?)'/im);
582 if (matches !== null && typeof matches[1] !== 'undefined') {
583 image = matches[1].toLowerCase();
586 matches = attributes.match(/image="([\s\S]*?)"/im);
587 if (matches !== null && typeof matches[1] !== 'undefined') {
588 image = matches[1].toLowerCase();
592 data.image = escapeHTML(image);
597 matches = attributes.match(/preview='([\s\S]*?)'/im);
598 if (matches !== null && typeof matches[1] !== 'undefined') {
599 preview = matches[1].toLowerCase();
602 matches = attributes.match(/preview="([\s\S]*?)"/im);
603 if (matches !== null && typeof matches[1] !== 'undefined') {
604 preview = matches[1].toLowerCase();
607 if (preview !== '') {
608 data.preview = escapeHTML(preview);
611 data.text = trim(match[3]);
612 data.after = trim(match[4]);
618 * Process txt content and if it contains attachment bbcode
619 * add it to the attachment preview .
621 * @param {string} content
624 var addBBCodeToPreview =function(content) {
625 var attachmentData = getAttachmentData(content);
626 if (attachmentData) {
627 reAddAttachment(attachmentData);
628 // Remove the attachment bbcode from the textarea.
629 var content = content.replace(/\[attachment[\s\S]*\[\/attachment]/im, '');
630 $('#' + id).val(content);
636 * Add an Attachment with data from an old bbcode
637 * generated attachment.
639 * @param {object} json The attachment data.
642 var reAddAttachment = function(json) {
644 $('#profile-rotator').hide();
648 if (json.type !== 'link' && json.type !== 'video' && json.type !== 'photo' || json.url === json.title) {
649 $('#profile-rotator').hide();
653 var obj = {data: json};
654 obj = sanitizeInputData(obj);
660 processAttachmentTpl(data);
661 addTitleDescription(data);
662 addHostToAttachment(data.url);
664 // Since we don't have an array of image data,
665 // we need to add the preview images in a different way
666 // than in function addImagesToAttachment().
667 var imageClass = 'attachment-preview';
670 if (data.image !== '') {
671 imageClass = 'attachment-image';
674 image = data.preview;
678 var appendImage = "<img id='imagePreview_" + id + "' src='" + image + "' class='" + imageClass + "' ></img>"
679 $('#previewImage_' + id).html(appendImage);
680 $('#attachmentImageSrc_' + id).val(bin2hex(image));
682 // We need to add the image widht and height when it is
686 $('#attachmentImageWidth_' + id).val(this.width);
687 $('#attachmentImageHeight_' + id).val(this.height);
693 processEventListener();
694 $('#profile-rotator').hide();
698 * Add missing default properties to the input data object.
700 * @param {object} obj Input data.
703 var sanitizeInputData = function(obj) {
704 if (typeof obj.contentType === 'undefined'
705 || obj.contentType === null)
707 obj.contentType = "";
709 if (typeof obj.data.url === 'undefined'
710 || obj.data.url === null)
714 if (typeof obj.data.title === 'undefined'
715 || obj.data.title === null
716 || obj.data.title === "")
718 obj.data.title = defaultTitle;
720 if (typeof obj.data.text === 'undefined'
721 || obj.data.text === null
722 || obj.data.text === "")
726 if (typeof obj.data.images === 'undefined'
727 || obj.data.images === null)
729 obj.data.images = "";
732 if (typeof obj.data.image === 'undefined'
733 || obj.data.image === null)
738 if (typeof obj.data.preview === 'undefined'
739 || obj.data.preview === null)
741 obj.data.preview = "";
748 * Destroy the plugin.
752 var destroy = function() {
753 $('#' + id).unbind();
754 $('#preview_' + id).remove();
758 blockDescription = false;
769 var trim = function(str) {
770 return str.replace(/^\s+|\s+$/g, "");
772 var escapeHTML = function(unsafe_str) {
774 .replace(/&/g, '&')
775 .replace(/</g, '<')
776 .replace(/>/g, '>')
777 .replace(/\"/g, '"')
778 .replace(/\[/g, '[')
779 .replace(/\]/g, ']')
780 .replace(/\'/g, '''); // ''' is not valid HTML 4
783 // Initialize LinkPreview
787 // make crawlText() accessable from the outside.
788 crawlText: function(text) {
791 addBBCodeToPreview: function(content) {
792 addBBCodeToPreview(content);
794 destroy: function() {
800 $.fn.linkPreview.defaults = {
801 defaultDescription: "Enter a description",
802 defaultTitle: "Enter a title"
806 * Get in a textarea the previous word before the cursor.
808 * @param {object} text Textarea elemet.
809 * @param {integer} caretPos Cursor position.
811 * @returns {string} Previous word.
813 function returnWord(text, caretPos) {
814 var index = text.indexOf(caretPos);
815 var preText = text.substring(0, caretPos);
816 // If the last charachter is a space or enter remove it
817 // We need this in friendica for the url preview.
818 var lastChar = preText.slice(-1)
819 if ( lastChar === " "
824 preText = preText.substring(0, preText.length -1);
827 // Replace new line with space.
828 preText = preText.replace(/\n/g, " ");
830 if (preText.indexOf(" ") > 0) {
831 var words = preText.split(" ");
832 return words[words.length - 1]; //return last word
840 * Get in a textarea the previous word before the cursor.
842 * @param {string} id The ID of a textarea element.
843 * @returns {sting|null} Previous word or null if no word is available.
845 function getPrevWord(id) {
846 var text = document.getElementById(id);
847 var caretPos = getCaretPosition(text);
848 var word = returnWord(text.value, caretPos);
856 * Get the cursor posiotion in an text element.
858 * @param {object} ctrl Textarea elemet.
859 * @returns {integer} Position of the cursor.
861 function getCaretPosition(ctrl) {
862 var CaretPos = 0; // IE Support
863 if (document.selection) {
865 var Sel = document.selection.createRange();
866 Sel.moveStart('character', -ctrl.value.length);
867 CaretPos = Sel.text.length;
870 else if (ctrl.selectionStart || ctrl.selectionStart == '0') {
871 CaretPos = ctrl.selectionStart;