index.js 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. //
  2. // index.js
  3. // Should expose the additional browser functions on to the less object
  4. //
  5. import {addDataAttr} from './utils';
  6. import lessRoot from '../less';
  7. import browser from './browser';
  8. import FM from './file-manager';
  9. import PluginLoader from './plugin-loader';
  10. import LogListener from './log-listener';
  11. import ErrorReporting from './error-reporting';
  12. import Cache from './cache';
  13. import ImageSize from './image-size';
  14. export default (window, options) => {
  15. const document = window.document;
  16. const less = lessRoot();
  17. less.options = options;
  18. const environment = less.environment;
  19. const FileManager = FM(options, less.logger);
  20. const fileManager = new FileManager();
  21. environment.addFileManager(fileManager);
  22. less.FileManager = FileManager;
  23. less.PluginLoader = PluginLoader;
  24. LogListener(less, options);
  25. const errors = ErrorReporting(window, less, options);
  26. const cache = less.cache = options.cache || Cache(window, options, less.logger);
  27. ImageSize(less.environment);
  28. // Setup user functions - Deprecate?
  29. if (options.functions) {
  30. less.functions.functionRegistry.addMultiple(options.functions);
  31. }
  32. const typePattern = /^text\/(x-)?less$/;
  33. function clone(obj) {
  34. const cloned = {};
  35. for (const prop in obj) {
  36. if (obj.hasOwnProperty(prop)) {
  37. cloned[prop] = obj[prop];
  38. }
  39. }
  40. return cloned;
  41. }
  42. // only really needed for phantom
  43. function bind(func, thisArg) {
  44. const curryArgs = Array.prototype.slice.call(arguments, 2);
  45. return function() {
  46. const args = curryArgs.concat(Array.prototype.slice.call(arguments, 0));
  47. return func.apply(thisArg, args);
  48. };
  49. }
  50. function loadStyles(modifyVars) {
  51. const styles = document.getElementsByTagName('style');
  52. let style;
  53. for (let i = 0; i < styles.length; i++) {
  54. style = styles[i];
  55. if (style.type.match(typePattern)) {
  56. const instanceOptions = clone(options);
  57. instanceOptions.modifyVars = modifyVars;
  58. const lessText = style.innerHTML || '';
  59. instanceOptions.filename = document.location.href.replace(/#.*$/, '');
  60. /* jshint loopfunc:true */
  61. // use closure to store current style
  62. less.render(lessText, instanceOptions,
  63. bind((style, e, result) => {
  64. if (e) {
  65. errors.add(e, 'inline');
  66. } else {
  67. style.type = 'text/css';
  68. if (style.styleSheet) {
  69. style.styleSheet.cssText = result.css;
  70. } else {
  71. style.innerHTML = result.css;
  72. }
  73. }
  74. }, null, style));
  75. }
  76. }
  77. }
  78. function loadStyleSheet(sheet, callback, reload, remaining, modifyVars) {
  79. const instanceOptions = clone(options);
  80. addDataAttr(instanceOptions, sheet);
  81. instanceOptions.mime = sheet.type;
  82. if (modifyVars) {
  83. instanceOptions.modifyVars = modifyVars;
  84. }
  85. function loadInitialFileCallback(loadedFile) {
  86. const data = loadedFile.contents;
  87. const path = loadedFile.filename;
  88. const webInfo = loadedFile.webInfo;
  89. const newFileInfo = {
  90. currentDirectory: fileManager.getPath(path),
  91. filename: path,
  92. rootFilename: path,
  93. rewriteUrls: instanceOptions.rewriteUrls
  94. };
  95. newFileInfo.entryPath = newFileInfo.currentDirectory;
  96. newFileInfo.rootpath = instanceOptions.rootpath || newFileInfo.currentDirectory;
  97. if (webInfo) {
  98. webInfo.remaining = remaining;
  99. const css = cache.getCSS(path, webInfo, instanceOptions.modifyVars);
  100. if (!reload && css) {
  101. webInfo.local = true;
  102. callback(null, css, data, sheet, webInfo, path);
  103. return;
  104. }
  105. }
  106. // TODO add tests around how this behaves when reloading
  107. errors.remove(path);
  108. instanceOptions.rootFileInfo = newFileInfo;
  109. less.render(data, instanceOptions, (e, result) => {
  110. if (e) {
  111. e.href = path;
  112. callback(e);
  113. } else {
  114. cache.setCSS(sheet.href, webInfo.lastModified, instanceOptions.modifyVars, result.css);
  115. callback(null, result.css, data, sheet, webInfo, path);
  116. }
  117. });
  118. }
  119. fileManager.loadFile(sheet.href, null, instanceOptions, environment)
  120. .then(loadedFile => {
  121. loadInitialFileCallback(loadedFile);
  122. }).catch(err => {
  123. console.log(err);
  124. callback(err);
  125. });
  126. }
  127. function loadStyleSheets(callback, reload, modifyVars) {
  128. for (let i = 0; i < less.sheets.length; i++) {
  129. loadStyleSheet(less.sheets[i], callback, reload, less.sheets.length - (i + 1), modifyVars);
  130. }
  131. }
  132. function initRunningMode() {
  133. if (less.env === 'development') {
  134. less.watchTimer = setInterval(() => {
  135. if (less.watchMode) {
  136. fileManager.clearFileCache();
  137. loadStyleSheets((e, css, _, sheet, webInfo) => {
  138. if (e) {
  139. errors.add(e, e.href || sheet.href);
  140. } else if (css) {
  141. browser.createCSS(window.document, css, sheet);
  142. }
  143. });
  144. }
  145. }, options.poll);
  146. }
  147. }
  148. //
  149. // Watch mode
  150. //
  151. less.watch = function () {
  152. if (!less.watchMode ) {
  153. less.env = 'development';
  154. initRunningMode();
  155. }
  156. this.watchMode = true;
  157. return true;
  158. };
  159. less.unwatch = function () {clearInterval(less.watchTimer); this.watchMode = false; return false; };
  160. //
  161. // Synchronously get all <link> tags with the 'rel' attribute set to
  162. // "stylesheet/less".
  163. //
  164. less.registerStylesheetsImmediately = () => {
  165. const links = document.getElementsByTagName('link');
  166. less.sheets = [];
  167. for (let i = 0; i < links.length; i++) {
  168. if (links[i].rel === 'stylesheet/less' || (links[i].rel.match(/stylesheet/) &&
  169. (links[i].type.match(typePattern)))) {
  170. less.sheets.push(links[i]);
  171. }
  172. }
  173. };
  174. //
  175. // Asynchronously get all <link> tags with the 'rel' attribute set to
  176. // "stylesheet/less", returning a Promise.
  177. //
  178. less.registerStylesheets = () => new Promise((resolve, reject) => {
  179. less.registerStylesheetsImmediately();
  180. resolve();
  181. });
  182. //
  183. // With this function, it's possible to alter variables and re-render
  184. // CSS without reloading less-files
  185. //
  186. less.modifyVars = record => less.refresh(true, record, false);
  187. less.refresh = (reload, modifyVars, clearFileCache) => {
  188. if ((reload || clearFileCache) && clearFileCache !== false) {
  189. fileManager.clearFileCache();
  190. }
  191. return new Promise((resolve, reject) => {
  192. let startTime;
  193. let endTime;
  194. let totalMilliseconds;
  195. let remainingSheets;
  196. startTime = endTime = new Date();
  197. // Set counter for remaining unprocessed sheets
  198. remainingSheets = less.sheets.length;
  199. if (remainingSheets === 0) {
  200. endTime = new Date();
  201. totalMilliseconds = endTime - startTime;
  202. less.logger.info('Less has finished and no sheets were loaded.');
  203. resolve({
  204. startTime,
  205. endTime,
  206. totalMilliseconds,
  207. sheets: less.sheets.length
  208. });
  209. } else {
  210. // Relies on less.sheets array, callback seems to be guaranteed to be called for every element of the array
  211. loadStyleSheets((e, css, _, sheet, webInfo) => {
  212. if (e) {
  213. errors.add(e, e.href || sheet.href);
  214. reject(e);
  215. return;
  216. }
  217. if (webInfo.local) {
  218. less.logger.info(`Loading ${sheet.href} from cache.`);
  219. } else {
  220. less.logger.info(`Rendered ${sheet.href} successfully.`);
  221. }
  222. browser.createCSS(window.document, css, sheet);
  223. less.logger.info(`CSS for ${sheet.href} generated in ${new Date() - endTime}ms`);
  224. // Count completed sheet
  225. remainingSheets--;
  226. // Check if the last remaining sheet was processed and then call the promise
  227. if (remainingSheets === 0) {
  228. totalMilliseconds = new Date() - startTime;
  229. less.logger.info(`Less has finished. CSS generated in ${totalMilliseconds}ms`);
  230. resolve({
  231. startTime,
  232. endTime,
  233. totalMilliseconds,
  234. sheets: less.sheets.length
  235. });
  236. }
  237. endTime = new Date();
  238. }, reload, modifyVars);
  239. }
  240. loadStyles(modifyVars);
  241. });
  242. };
  243. less.refreshStyles = loadStyles;
  244. return less;
  245. };