json-format-ent.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. // ==ClosureCompiler==
  2. // @compilation_level ADVANCED_OPTIMIZATIONS
  3. // @output_file_name content.js
  4. // @externs_url http://closure-compiler.googlecode.com/svn/trunk/contrib/externs/chrome_extensions.js
  5. // @js_externs var console = {assert: function(){}};
  6. // @formatting pretty_print
  7. // ==/ClosureCompiler==
  8. /** @license
  9. JSON Formatter | MIT License
  10. Copyright 2012 Callum Locke
  11. Permission is hereby granted, free of charge, to any person obtaining a copy of
  12. this software and associated documentation files (the "Software"), to deal in
  13. the Software without restriction, including without limitation the rights to
  14. use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
  15. of the Software, and to permit persons to whom the Software is furnished to do
  16. so, subject to the following conditions:
  17. The above copyright notice and this permission notice shall be included in all
  18. copies or substantial portions of the Software.
  19. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  25. SOFTWARE.
  26. */
  27. /*jshint eqeqeq:true, forin:true, strict:true */
  28. /*global chrome, console */
  29. var JsonFormatEntrance = (function() {
  30. "use strict" ;
  31. var jfContent,
  32. pre,
  33. jfStyleEl,
  34. formattingMsg,
  35. slowAnalysisTimeout,
  36. port = JsonFormatDealer,
  37. startTime = +(new Date()),
  38. domReadyTime,
  39. isJsonTime,
  40. exitedNotJsonTime,
  41. displayedFormattedJsonTime
  42. ;
  43. // Add listener to receive response from BG when ready
  44. var dealTheMsg = function (msg) {
  45. // console.log('Port msg received', msg[0], (""+msg[1]).substring(0,30)) ;
  46. switch (msg[0]) {
  47. case 'NOT JSON' :
  48. pre.style.display="" ;
  49. // console.log('Unhidden the PRE') ;
  50. jfContent.innerHTML = '<span class="x-json-tips">JSON不合法,请检查:</span>' ;
  51. exitedNotJsonTime = +(new Date()) ;
  52. break ;
  53. case 'FORMATTING' :
  54. isJsonTime = +(new Date()) ;
  55. // It is JSON, and it's now being formatted in the background worker.
  56. // Clear the slowAnalysisTimeout (if the BG worker had taken longer than 1s to respond with an answer to whether or not this is JSON, then it would have fired, unhiding the PRE... But now that we know it's JSON, we can clear this timeout, ensuring the PRE stays hidden.)
  57. clearTimeout(slowAnalysisTimeout) ;
  58. // Create option bar
  59. var optionBar = document.getElementById('optionBar');
  60. if(optionBar) {
  61. optionBar.parentNode.removeChild(optionBar);
  62. }
  63. optionBar = document.createElement('div') ;
  64. optionBar.id = 'optionBar' ;
  65. // Create toggleFormat button
  66. var buttonPlain = document.createElement('button'),
  67. buttonFormatted = document.createElement('button') ;
  68. buttonPlain.id = 'buttonPlain' ;
  69. buttonPlain.innerText = '元数据' ;
  70. buttonFormatted.id = 'buttonFormatted' ;
  71. buttonFormatted.innerText = '格式化' ;
  72. buttonFormatted.classList.add('selected') ;
  73. var plainOn = false ;
  74. buttonPlain.addEventListener('click', function () {
  75. // When plain button clicked...
  76. if (!plainOn) {
  77. plainOn = true ;
  78. pre.style.display="" ;
  79. jfContent.style.display="none" ;
  80. buttonFormatted.classList.remove('selected') ;
  81. buttonPlain.classList.add('selected') ;
  82. }
  83. },false ) ;
  84. buttonFormatted.addEventListener( 'click', function () {
  85. // When formatted button clicked...
  86. if (plainOn) {
  87. plainOn = false ;
  88. pre.style.display="none" ;
  89. jfContent.style.display="" ;
  90. buttonFormatted.classList.add('selected') ;
  91. buttonPlain.classList.remove('selected') ;
  92. }
  93. }, false ) ;
  94. // Put it in optionBar
  95. optionBar.appendChild(buttonPlain) ;
  96. optionBar.appendChild(buttonFormatted) ;
  97. // Attach event handlers
  98. document.addEventListener( 'click', generalClick, false ) ;
  99. // Put option bar in DOM
  100. jfContent.parentNode.appendChild(optionBar) ;
  101. break ;
  102. case 'FORMATTED' :
  103. // Insert HTML content
  104. formattingMsg.style.display="";
  105. jfContent.innerHTML = msg[1] ;
  106. displayedFormattedJsonTime = +(new Date()) ;
  107. // console.markTimeline('JSON formatted and displayed') ;
  108. break ;
  109. default :
  110. throw new Error('Message not understood: ' + msg[0]) ;
  111. }
  112. };
  113. // console.timeEnd('established port') ;
  114. var lastKvovIdGiven = 0 ;
  115. function collapse(elements) {
  116. // console.log('elements', elements) ;
  117. var el, i, blockInner, count ;
  118. for (i = elements.length - 1; i >= 0; i--) {
  119. el = elements[i] ;
  120. el.classList.add('collapsed') ;
  121. // (CSS hides the contents and shows an ellipsis.)
  122. // Add a count of the number of child properties/items (if not already done for this item)
  123. if (!el.id) {
  124. el.id = 'kvov' + (++lastKvovIdGiven) ;
  125. // Find the blockInner
  126. blockInner = el.firstElementChild ;
  127. while ( blockInner && !blockInner.classList.contains('blockInner') ) {
  128. blockInner = blockInner.nextElementSibling ;
  129. }
  130. if (!blockInner)
  131. continue ;
  132. // See how many children in the blockInner
  133. count = blockInner.children.length ;
  134. // Generate comment text eg "4 items"
  135. var comment = count + (count===1 ? ' item' : ' items') ;
  136. // Add CSS that targets it
  137. jfStyleEl.insertAdjacentHTML(
  138. 'beforeend',
  139. '\n#kvov'+lastKvovIdGiven+'.collapsed:after{color: #aaa; content:" // '+comment+'"}'
  140. ) ;
  141. }
  142. }
  143. }
  144. function expand(elements) {
  145. for (var i = elements.length - 1; i >= 0; i--)
  146. elements[i].classList.remove('collapsed') ;
  147. }
  148. var mac = navigator.platform.indexOf('Mac') !== -1,
  149. modKey ;
  150. if (mac)
  151. modKey = function (ev) {
  152. return ev.metaKey ;
  153. } ;
  154. else
  155. modKey = function (ev) {
  156. return ev.ctrlKey ;
  157. } ;
  158. function generalClick(ev) {
  159. // console.log('click', ev) ;
  160. if (ev.which === 1) {
  161. var elem = ev.target ;
  162. if (elem.className === 'e') {
  163. // It's a click on an expander.
  164. ev.preventDefault() ;
  165. var parent = elem.parentNode,
  166. div = jfContent,
  167. prevBodyHeight = document.body.offsetHeight,
  168. scrollTop = document.body.scrollTop,
  169. parentSiblings
  170. ;
  171. // Expand or collapse
  172. if (parent.classList.contains('collapsed')) {
  173. // EXPAND
  174. if (modKey(ev))
  175. expand(parent.parentNode.children) ;
  176. else
  177. expand([parent]) ;
  178. }
  179. else {
  180. // COLLAPSE
  181. if (modKey(ev))
  182. collapse(parent.parentNode.children) ;
  183. else
  184. collapse([parent]) ;
  185. }
  186. // Restore scrollTop somehow
  187. // Clear current extra margin, if any
  188. div.style.marginBottom = 0 ;
  189. // No need to worry if all content fits in viewport
  190. if (document.body.offsetHeight < window.innerHeight) {
  191. // console.log('document.body.offsetHeight < window.innerHeight; no need to adjust height') ;
  192. return ;
  193. }
  194. // And no need to worry if scrollTop still the same
  195. if (document.body.scrollTop === scrollTop) {
  196. // console.log('document.body.scrollTop === scrollTop; no need to adjust height') ;
  197. return ;
  198. }
  199. // console.log('Scrolltop HAS changed. document.body.scrollTop is now '+document.body.scrollTop+'; was '+scrollTop) ;
  200. // The body has got a bit shorter.
  201. // We need to increase the body height by a bit (by increasing the bottom margin on the jfContent div). The amount to increase it is whatever is the difference between our previous scrollTop and our new one.
  202. // Work out how much more our target scrollTop is than this.
  203. var difference = scrollTop - document.body.scrollTop + 8 ; // it always loses 8px; don't know why
  204. // Add this difference to the bottom margin
  205. //var currentMarginBottom = parseInt(div.style.marginBottom) || 0 ;
  206. div.style.marginBottom = difference + 'px' ;
  207. // Now change the scrollTop back to what it was
  208. document.body.scrollTop = scrollTop ;
  209. return ;
  210. }
  211. }
  212. }
  213. var postMessage = function(msg){
  214. dealTheMsg(msg);
  215. };
  216. var disconnect = function(){
  217. };
  218. /**
  219. * 执行代码格式化
  220. * @param {[type]} jsonStr [description]
  221. * @return {[type]}
  222. */
  223. var format = function(jsonStr){
  224. // Send the contents of the PRE to the BG script
  225. // Add jfContent DIV, ready to display stuff
  226. jfContent = document.getElementById('jfContent');
  227. if(!jfContent) {
  228. jfContent = document.createElement('div') ;
  229. jfContent.id = 'jfContent' ;
  230. document.body.appendChild(jfContent) ;
  231. }
  232. jfContent.style.display = '';
  233. pre = document.getElementById('jfContent_pre');
  234. if(!pre) {
  235. pre = document.createElement('pre') ;
  236. pre.id = 'jfContent_pre' ;
  237. document.body.appendChild(pre) ;
  238. }
  239. pre.innerHTML = jsonStr;
  240. pre.style.display="none";
  241. jfStyleEl = document.getElementById('jfStyleEl');
  242. if(!jfStyleEl) {
  243. jfStyleEl = document.createElement('style');
  244. document.head.appendChild(jfStyleEl);
  245. }
  246. formattingMsg = document.getElementById('formattingMsg') ;
  247. if(!formattingMsg) {
  248. formattingMsg = document.createElement('pre') ;
  249. formattingMsg.id = 'formattingMsg' ;
  250. formattingMsg.innerHTML = '<svg id="spinner" width="16" height="16" viewBox="0 0 300 300" xmlns="http://www.w3.org/2000/svg" version="1.1">' +
  251. '<path d="M 150,0 a 150,150 0 0,1 106.066,256.066 l -35.355,-35.355 a -100,-100 0 0,0 -70.711,-170.711 z" fill="#3d7fe6"></path></svg> 格式化中...' ;
  252. document.body.appendChild(formattingMsg) ;
  253. }
  254. // Post the contents of the PRE
  255. port.postMessage({
  256. type: "SENDING TEXT",
  257. text: jsonStr,
  258. length: jsonStr.length
  259. });
  260. };
  261. /**
  262. * 清空
  263. * @return {[type]}
  264. */
  265. var clear = function(){
  266. try{
  267. jfContent.innerHTML = '';
  268. pre.innerHTML = '';
  269. }catch(e){
  270. }
  271. };
  272. return {
  273. format : format,
  274. clear : clear,
  275. postMessage : postMessage,
  276. disconnect : disconnect
  277. }
  278. })();