beautify-css.js 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. /*jshint curly:true, eqeqeq:true, laxbreak:true, noempty:false */
  2. /*
  3. The MIT License (MIT)
  4. Copyright (c) 2007-2013 Einar Lielmanis and contributors.
  5. Permission is hereby granted, free of charge, to any person
  6. obtaining a copy of this software and associated documentation files
  7. (the "Software"), to deal in the Software without restriction,
  8. including without limitation the rights to use, copy, modify, merge,
  9. publish, distribute, sublicense, and/or sell copies of the Software,
  10. and to permit persons to whom the Software is furnished to do so,
  11. subject to the following conditions:
  12. The above copyright notice and this permission notice shall be
  13. included in all copies or substantial portions of the Software.
  14. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  15. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  16. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  17. NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  18. BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  19. ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  20. CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21. SOFTWARE.
  22. CSS Beautifier
  23. ---------------
  24. Written by Harutyun Amirjanyan, ([email protected])
  25. Based on code initially developed by: Einar Lielmanis, <[email protected]>
  26. http://jsbeautifier.org/
  27. Usage:
  28. css_beautify(source_text);
  29. css_beautify(source_text, options);
  30. The options are:
  31. indent_size (default 4) — indentation size,
  32. indent_char (default space) — character to indent with,
  33. e.g
  34. css_beautify(css_source_text, {
  35. 'indent_size': 1,
  36. 'indent_char': '\t'
  37. });
  38. */
  39. // http://www.w3.org/TR/CSS21/syndata.html#tokenization
  40. // http://www.w3.org/TR/css3-syntax/
  41. (function () {
  42. function css_beautify(source_text, options, callback) {
  43. "use strict";
  44. // 用webwork的方式来进行格式化,效率更高
  45. let worker = new Worker(URL.createObjectURL(new Blob(["(" + beautifyWebWorker.toString() + ")()"], {type: 'text/javascript'})));
  46. worker.onmessage = function (evt) {
  47. callback && callback(evt.data);
  48. };
  49. worker.postMessage({
  50. source_text: (source_text || '').trim(),
  51. options: options
  52. });
  53. }
  54. function beautifyWebWorker() {
  55. function Beautifier(source_text, options) {
  56. options = options || {};
  57. var indentSize = options.indent_size || 4;
  58. var indentCharacter = options.indent_char || ' ';
  59. // compatibility
  60. if (typeof indentSize === "string") {
  61. indentSize = parseInt(indentSize, 10);
  62. }
  63. // tokenizer
  64. var whiteRe = /^\s+$/;
  65. var wordRe = /[\w$\-_]/;
  66. var pos = -1, ch;
  67. function next() {
  68. ch = source_text.charAt(++pos);
  69. return ch;
  70. }
  71. function peek() {
  72. return source_text.charAt(pos + 1);
  73. }
  74. function eatString(comma) {
  75. var start = pos;
  76. while (next()) {
  77. if (ch === "\\") {
  78. next();
  79. next();
  80. } else if (ch === comma) {
  81. break;
  82. } else if (ch === "\n") {
  83. break;
  84. }
  85. }
  86. return source_text.substring(start, pos + 1);
  87. }
  88. function eatWhitespace() {
  89. var start = pos;
  90. while (whiteRe.test(peek())) {
  91. pos++;
  92. }
  93. return pos !== start;
  94. }
  95. function skipWhitespace() {
  96. var start = pos;
  97. do {
  98. } while (whiteRe.test(next()));
  99. return pos !== start + 1;
  100. }
  101. function eatComment() {
  102. var start = pos;
  103. next();
  104. while (next()) {
  105. if (ch === "*" && peek() === "/") {
  106. pos++;
  107. break;
  108. }
  109. }
  110. return source_text.substring(start, pos + 1);
  111. }
  112. function lookBack(str) {
  113. return source_text.substring(pos - str.length, pos).toLowerCase() === str;
  114. }
  115. // printer
  116. var indentString = source_text.match(/^[\r\n]*[\t ]*/)[0];
  117. var singleIndent = Array(indentSize + 1).join(indentCharacter);
  118. var indentLevel = 0;
  119. function indent() {
  120. indentLevel++;
  121. indentString += singleIndent;
  122. }
  123. function outdent() {
  124. indentLevel--;
  125. indentString = indentString.slice(0, -indentSize);
  126. }
  127. var print = {};
  128. print["{"] = function (ch) {
  129. print.singleSpace();
  130. output.push(ch);
  131. print.newLine();
  132. };
  133. print["}"] = function (ch) {
  134. print.newLine();
  135. output.push(ch);
  136. print.newLine();
  137. };
  138. print.newLine = function (keepWhitespace) {
  139. if (!keepWhitespace) {
  140. while (whiteRe.test(output[output.length - 1])) {
  141. output.pop();
  142. }
  143. }
  144. if (output.length) {
  145. output.push('\n');
  146. }
  147. if (indentString) {
  148. output.push(indentString);
  149. }
  150. };
  151. print.singleSpace = function () {
  152. if (output.length && !whiteRe.test(output[output.length - 1])) {
  153. output.push(' ');
  154. }
  155. };
  156. var output = [];
  157. if (indentString) {
  158. output.push(indentString);
  159. }
  160. /*_____________________--------------------_____________________*/
  161. while (true) {
  162. var isAfterSpace = skipWhitespace();
  163. if (!ch) {
  164. break;
  165. }
  166. if (ch === '{') {
  167. indent();
  168. print["{"](ch);
  169. } else if (ch === '}') {
  170. outdent();
  171. print["}"](ch);
  172. } else if (ch === '"' || ch === '\'') {
  173. output.push(eatString(ch));
  174. } else if (ch === ';') {
  175. output.push(ch, '\n', indentString);
  176. } else if (ch === '/' && peek() === '*') { // comment
  177. print.newLine();
  178. output.push(eatComment(), "\n", indentString);
  179. } else if (ch === '(') { // may be a url
  180. if (lookBack("url")) {
  181. output.push(ch);
  182. eatWhitespace();
  183. if (next()) {
  184. if (ch !== ')' && ch !== '"' && ch !== '\'') {
  185. output.push(eatString(')'));
  186. } else {
  187. pos--;
  188. }
  189. }
  190. } else {
  191. if (isAfterSpace) {
  192. print.singleSpace();
  193. }
  194. output.push(ch);
  195. eatWhitespace();
  196. }
  197. } else if (ch === ')') {
  198. output.push(ch);
  199. } else if (ch === ',') {
  200. eatWhitespace();
  201. output.push(ch);
  202. print.singleSpace();
  203. } else if (ch === ']') {
  204. output.push(ch);
  205. } else if (ch === '[' || ch === '=') { // no whitespace before or after
  206. eatWhitespace();
  207. output.push(ch);
  208. } else {
  209. if (isAfterSpace) {
  210. print.singleSpace();
  211. }
  212. output.push(ch);
  213. }
  214. }
  215. var sweetCode = output.join('').replace(/[\n ]+$/, '');
  216. return sweetCode;
  217. }
  218. self.onmessage = function (evt) {
  219. var result = Beautifier(evt.data.source_text, evt.data.options);
  220. self.postMessage(result);
  221. };
  222. }
  223. window.css_beautify = css_beautify;
  224. }());