image-size.js 1.98 KB
Newer Older
Kriengkrai Yothee's avatar
Kriengkrai Yothee committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
import Dimension from '../less/tree/dimension';
import Expression from '../less/tree/expression';
import functionRegistry from './../less/functions/function-registry';

export default environment => {

    function imageSize(functionContext, filePathNode) {
        let filePath = filePathNode.value;
        const currentFileInfo = functionContext.currentFileInfo;
        const currentDirectory = currentFileInfo.rewriteUrls ?
            currentFileInfo.currentDirectory : currentFileInfo.entryPath;

        const fragmentStart = filePath.indexOf('#');
        let fragment = '';
        if (fragmentStart !== -1) {
            fragment = filePath.slice(fragmentStart);
            filePath = filePath.slice(0, fragmentStart);
        }

        const fileManager = environment.getFileManager(filePath, currentDirectory, functionContext.context, environment, true);

        if (!fileManager) {
            throw {
                type: 'File',
                message: `Can not set up FileManager for ${filePathNode}`
            };
        }

        const fileSync = fileManager.loadFileSync(filePath, currentDirectory, functionContext.context, environment);

        if (fileSync.error) {
            throw fileSync.error;
        }

        const sizeOf = require('image-size');
        return sizeOf(fileSync.filename);
    }

    const imageFunctions = {
        'image-size': function(filePathNode) {
            const size = imageSize(this, filePathNode);
            return new Expression([
                new Dimension(size.width, 'px'),
                new Dimension(size.height, 'px')
            ]);
        },
        'image-width': function(filePathNode) {
            const size = imageSize(this, filePathNode);
            return new Dimension(size.width, 'px');
        },
        'image-height': function(filePathNode) {
            const size = imageSize(this, filePathNode);
            return new Dimension(size.height, 'px');
        }
    };

    functionRegistry.addMultiple(imageFunctions);
};