scratch – Blame information for rev 58

Subversion Repositories:
Rev:
Rev Author Line No. Line
58 office 1 /* ===========================================================
2 * trumbowyg.preformatted.js v1.0
3 * Preformatted plugin for Trumbowyg
4 * http://alex-d.github.com/Trumbowyg
5 * ===========================================================
6 * Author : Casella Edoardo (Civile)
7 */
8  
9  
10 (function ($) {
11 'use strict';
12  
13 $.extend(true, $.trumbowyg, {
14 langs: {
15 // jshint camelcase:false
16 en: {
17 preformatted: 'Code sample <pre>'
18 },
19 fr: {
20 preformatted: 'Exemple de code'
21 },
22 it: {
23 preformatted: 'Codice <pre>'
24 },
25 zh_cn: {
26 preformatted: '代码示例 <pre>'
27 }
28 },
29 // jshint camelcase:true
30  
31 plugins: {
32 preformatted: {
33 init: function (trumbowyg) {
34 var btnDef = {
35 fn: function () {
36 trumbowyg.saveRange();
37 var text = trumbowyg.getRangeText();
38 if (text.replace(/\s/g, '') !== '') {
39 try {
40 var curtag = getSelectionParentElement().tagName.toLowerCase();
41 if (curtag === 'code' || curtag === 'pre') {
42 return unwrapCode();
43 }
44 else {
45 trumbowyg.execCmd('insertHTML', '<pre><code>' + strip(text) + '</code></pre>');
46 }
47 } catch (e) {
48 }
49 }
50 },
51 tag: 'pre'
52 };
53  
54 trumbowyg.addBtnDef('preformatted', btnDef);
55 }
56 }
57 }
58 });
59  
60 /*
61 * GetSelectionParentElement
62 */
63 function getSelectionParentElement() {
64 var parentEl = null,
65 selection;
66 if (window.getSelection) {
67 selection = window.getSelection();
68 if (selection.rangeCount) {
69 parentEl = selection.getRangeAt(0).commonAncestorContainer;
70 if (parentEl.nodeType !== 1) {
71 parentEl = parentEl.parentNode;
72 }
73 }
74 } else if ((selection = document.selection) && selection.type !== 'Control') {
75 parentEl = selection.createRange().parentElement();
76 }
77 return parentEl;
78 }
79  
80 /*
81 * Strip
82 * returns a text without HTML tags
83 */
84 function strip(html) {
85 var tmp = document.createElement('DIV');
86 tmp.innerHTML = html;
87 return tmp.textContent || tmp.innerText || '';
88 }
89  
90 /*
91 * UnwrapCode
92 * ADD/FIX: to improve, works but can be better
93 * "paranoic" solution
94 */
95 function unwrapCode() {
96 var container = null;
97 if (document.selection) { //for IE
98 container = document.selection.createRange().parentElement();
99 } else {
100 var select = window.getSelection();
101 if (select.rangeCount > 0) {
102 container = select.getRangeAt(0).startContainer.parentNode;
103 }
104 }
105 //'paranoic' unwrap
106 var ispre = $(container).contents().closest('pre').length;
107 var iscode = $(container).contents().closest('code').length;
108 if (ispre && iscode) {
109 $(container).contents().unwrap('code').unwrap('pre');
110 } else if (ispre) {
111 $(container).contents().unwrap('pre');
112 } else if (iscode) {
113 $(container).contents().unwrap('code');
114 }
115 }
116  
117 })(jQuery);