image-size.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import Dimension from '../less/tree/dimension';
  2. import Expression from '../less/tree/expression';
  3. import functionRegistry from './../less/functions/function-registry';
  4. export default environment => {
  5. function imageSize(functionContext, filePathNode) {
  6. let filePath = filePathNode.value;
  7. const currentFileInfo = functionContext.currentFileInfo;
  8. const currentDirectory = currentFileInfo.rewriteUrls ?
  9. currentFileInfo.currentDirectory : currentFileInfo.entryPath;
  10. const fragmentStart = filePath.indexOf('#');
  11. let fragment = '';
  12. if (fragmentStart !== -1) {
  13. fragment = filePath.slice(fragmentStart);
  14. filePath = filePath.slice(0, fragmentStart);
  15. }
  16. const fileManager = environment.getFileManager(filePath, currentDirectory, functionContext.context, environment, true);
  17. if (!fileManager) {
  18. throw {
  19. type: 'File',
  20. message: `Can not set up FileManager for ${filePathNode}`
  21. };
  22. }
  23. const fileSync = fileManager.loadFileSync(filePath, currentDirectory, functionContext.context, environment);
  24. if (fileSync.error) {
  25. throw fileSync.error;
  26. }
  27. const sizeOf = require('image-size');
  28. return sizeOf(fileSync.filename);
  29. }
  30. const imageFunctions = {
  31. 'image-size': function(filePathNode) {
  32. const size = imageSize(this, filePathNode);
  33. return new Expression([
  34. new Dimension(size.width, 'px'),
  35. new Dimension(size.height, 'px')
  36. ]);
  37. },
  38. 'image-width': function(filePathNode) {
  39. const size = imageSize(this, filePathNode);
  40. return new Dimension(size.width, 'px');
  41. },
  42. 'image-height': function(filePathNode) {
  43. const size = imageSize(this, filePathNode);
  44. return new Dimension(size.height, 'px');
  45. }
  46. };
  47. functionRegistry.addMultiple(imageFunctions);
  48. };