scratch – Blame information for rev 125

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>'
125 office 27 },
28 ja: {
29 preformatted: 'コードサンプル <pre>'
58 office 30 }
31 },
32 // jshint camelcase:true
33  
34 plugins: {
35 preformatted: {
36 init: function (trumbowyg) {
37 var btnDef = {
38 fn: function () {
39 trumbowyg.saveRange();
40 var text = trumbowyg.getRangeText();
41 if (text.replace(/\s/g, '') !== '') {
42 try {
43 var curtag = getSelectionParentElement().tagName.toLowerCase();
44 if (curtag === 'code' || curtag === 'pre') {
45 return unwrapCode();
46 }
47 else {
48 trumbowyg.execCmd('insertHTML', '<pre><code>' + strip(text) + '</code></pre>');
49 }
50 } catch (e) {
51 }
52 }
53 },
54 tag: 'pre'
55 };
56  
57 trumbowyg.addBtnDef('preformatted', btnDef);
58 }
59 }
60 }
61 });
62  
63 /*
64 * GetSelectionParentElement
65 */
66 function getSelectionParentElement() {
67 var parentEl = null,
68 selection;
69 if (window.getSelection) {
70 selection = window.getSelection();
71 if (selection.rangeCount) {
72 parentEl = selection.getRangeAt(0).commonAncestorContainer;
73 if (parentEl.nodeType !== 1) {
74 parentEl = parentEl.parentNode;
75 }
76 }
77 } else if ((selection = document.selection) && selection.type !== 'Control') {
78 parentEl = selection.createRange().parentElement();
79 }
80 return parentEl;
81 }
82  
83 /*
84 * Strip
85 * returns a text without HTML tags
86 */
87 function strip(html) {
88 var tmp = document.createElement('DIV');
89 tmp.innerHTML = html;
90 return tmp.textContent || tmp.innerText || '';
91 }
92  
93 /*
94 * UnwrapCode
95 * ADD/FIX: to improve, works but can be better
96 * "paranoic" solution
97 */
98 function unwrapCode() {
99 var container = null;
100 if (document.selection) { //for IE
101 container = document.selection.createRange().parentElement();
102 } else {
103 var select = window.getSelection();
104 if (select.rangeCount > 0) {
105 container = select.getRangeAt(0).startContainer.parentNode;
106 }
107 }
108 //'paranoic' unwrap
109 var ispre = $(container).contents().closest('pre').length;
110 var iscode = $(container).contents().closest('code').length;
111 if (ispre && iscode) {
112 $(container).contents().unwrap('code').unwrap('pre');
113 } else if (ispre) {
114 $(container).contents().unwrap('pre');
115 } else if (iscode) {
116 $(container).contents().unwrap('code');
117 }
118 }
119  
120 })(jQuery);