decl-processor.js 4.08 KB
Newer Older
jatuporn Tonggasem's avatar
jatuporn Tonggasem 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 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
'use strict';

const matchOptions = require('./match-options');
const paths = require('./paths');

const getPathDeclFile = paths.getPathDeclFile;
const getDirDeclFile = paths.getDirDeclFile;
const prepareAsset = paths.prepareAsset;

/**
 * @typedef UrlRegExp
 * @name UrlRegExp
 * @desc A regex for match url with parentheses:
 *   (before url)(the url)(after url).
 *    (the url) will be replace with new url, and before and after will remain
 * @type RegExp
 */
/**
 * @type {UrlRegExp[]}
 */
const URL_PATTERNS = [
    /(url\(\s*['"]?)([^"')]+)(["']?\s*\))/g,
    /(AlphaImageLoader\(\s*src=['"]?)([^"')]+)(["'])/g
];

const WITH_QUOTES = /^['"]/;

/**
 * Restricted modes
 *
 * @type {String[]}
 */
const PROCESS_TYPES = ['rebase', 'inline', 'copy', 'custom'];

const getUrlProcessorType = (optionUrl) =>
    typeof optionUrl === 'function' ? 'custom' : (optionUrl || 'rebase');

/**
 * @param {String} optionUrl
 * @returns {PostcssUrl~UrlProcessor}
 */
function getUrlProcessor(optionUrl) {
    const mode = getUrlProcessorType(optionUrl);

    if (PROCESS_TYPES.indexOf(mode) === -1) {
        throw new Error(`Unknown mode for postcss-url: ${mode}`);
    }

    return require(`../type/${mode}`);
}

/**
 * @param {PostcssUrl~UrlProcessor} urlProcessor
 * @param {Result} result
 * @param {Decl} decl
 * @returns {Function}
 */
const wrapUrlProcessor = (urlProcessor, result, decl) => {
    const warn = (message) => decl.warn(result, message);
    const addDependency = (file) => result.messages.push({
        type: 'dependency',
        file,
        parent: getPathDeclFile(decl)
    });

    return (asset, dir, option) =>
        urlProcessor(asset, dir, option, decl, warn, result, addDependency);
};

/**
 * @param {Decl} decl
 * @returns {RegExp}
 */
const getPattern = (decl) =>
    URL_PATTERNS.find((pattern) => pattern.test(decl.value));

/**
 * @param {String} url
 * @param {Dir} dir
 * @param {Options} options
 * @param {Result} result
 * @param {Decl} decl
 * @returns {String|undefined}
 */
const replaceUrl = (url, dir, options, result, decl) => {
    const asset = prepareAsset(url, dir, decl);

    const matchedOptions = matchOptions(asset, options);

    if (!matchedOptions) return;

    const process = (option) => {
        const wrappedUrlProcessor = wrapUrlProcessor(getUrlProcessor(option.url), result, decl);

        return wrappedUrlProcessor(asset, dir, option);
    };

    if (Array.isArray(matchedOptions)) {
        matchedOptions.forEach((option) => asset.url = process(option));
    } else {
        asset.url = process(matchedOptions);
    }

    return asset.url;
};

/**
 * @param {String} from
 * @param {String} to
 * @param {PostcssUrl~Options} options
 * @param {Result} result
 * @param {Decl} decl
 * @returns {PostcssUrl~DeclProcessor}
 */
const declProcessor = (from, to, options, result, decl) => {
    const dir = { from, to, file: getDirDeclFile(decl) };
    const pattern = getPattern(decl);

    if (!pattern) return;

    decl.value = decl.value
        .replace(pattern, (matched, before, url, after) => {
            const newUrl = replaceUrl(url, dir, options, result, decl);

            if (!newUrl) return matched;

            if (WITH_QUOTES.test(newUrl) && WITH_QUOTES.test(after)) {
                before = before.slice(0, -1);
                after = after.slice(1);
            }

            return `${before}${newUrl}${after}`;
        });
};

module.exports = {
    replaceUrl,
    declProcessor
};

/**
 * @typedef {Object} PostcssUrl~Options - postcss-url Options
 * @property {String} [url=^rebase|inline|copy|custom] - processing mode
 * @property {Minimatch|RegExp|Function} [filter] - filter assets by relative pathname
 * @property {String} [assetsPath] - absolute or relative path to copy assets
 * @property {String|String[]} [basePath] - absolute or relative paths to search, when copy or inline
 * @property {Number} [maxSize] - max file size in kbytes for inline mode
 * @property {String} [fallback] - fallback mode if file exceeds maxSize
 * @property {Boolean} [useHash] - use file hash instead filename
 * @property {HashOptions} [hashOptions] - params for generating hash name
 */