index.js 9.5 KB

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