Debian Codegraph @

linkify-it/support/demo_template/index.js

raw
1 'use strict';
2
3 /*eslint-env browser*/
4 /*global $, _*/
5
6 var linkify = require('../../')({ fuzzyIP: true });
7 var mdurl = require('mdurl');
8 var permalink;
9
10 function escape(str) {
11 return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
12 }
13
14 function setLinkifiedContent(selector, content) {
15 var out = escape(content),
16 matches = linkify.match(content),
17 result = [],
18 last;
19
20 if (matches) {
21 last = 0;
22 matches.forEach(function (match) {
23 if (last < match.index) {
24 result.push(escape(content.slice(last, match.index)).replace(/\r?\n/g, '<br>'));
25 }
26 result.push('<a target="_blank" href="');
27 result.push(escape(match.url));
28 result.push('">');
29 result.push(escape(match.text));
30 result.push('</a>');
31 last = match.lastIndex;
32 });
33 if (last < content.length) {
34 result.push(escape(content.slice(last)).replace(/\r?\n/g, '<br>'));
35 }
36 out = result.join('');
37 }
38
39 $(selector).html(out);
40 }
41
42 function updateResult() {
43 var source = $('.source').val();
44
45 setLinkifiedContent('.result-html', source);
46
47 if (source) {
48 permalink.href = '#t1=' + mdurl.encode(source, mdurl.encode.componentChars);
49 } else {
50 permalink.href = '';
51 }
52 }
53
54
55 //////////////////////////////////////////////////////////////////////////////
56 // Init on page load
57 //
58 $(function () {
59
60 // Restore content if opened by permalink
61 if (location.hash && /^(#t1=)/.test(location.hash)) {
62 $('.source').val(mdurl.decode(location.hash.slice(4), mdurl.decode.componentChars));
63 }
64
65 // Activate tooltips
66 $('._tip').tooltip({ container: 'body' });
67
68 permalink = document.getElementById('permalink');
69
70 // Setup listeners
71 $('.source').on('keyup paste cut mouseup', _.debounce(updateResult, 300, { maxWait: 500 }));
72
73 $('.source-clear').on('click', function (event) {
74 $('.source').val('');
75 updateResult();
76 event.preventDefault();
77 });
78
79 updateResult();
80 });