Small style tweaks

This commit is contained in:
Dan Mindru 2021-09-01 22:24:51 +02:00
parent 2387d542e7
commit 1026fe53d2
2 changed files with 46 additions and 38 deletions

View File

@ -5,7 +5,7 @@ const minifyInline = require('gulp-minify-inline');
const preprocess = require('gulp-preprocess'); const preprocess = require('gulp-preprocess');
const rename = require('gulp-rename'); const rename = require('gulp-rename');
const del = require('del'); const del = require('del');
const { inlineimg } = require('./check-for-image-url'); const { inlineImg } = require('./check-for-image-url');
const { getConfigsForDir, getFilePathsForDir, getCssLinkTagsFromFilelist } = require('./util/util'); const { getConfigsForDir, getFilePathsForDir, getCssLinkTagsFromFilelist } = require('./util/util');
function buildTask(options) { function buildTask(options) {
@ -34,7 +34,7 @@ function buildTask(options) {
return options return options
.src([cwd + '/**/*.html', '!' + cwd + '/**/*.inc.html']) .src([cwd + '/**/*.html', '!' + cwd + '/**/*.inc.html'])
.pipe(preprocess({ context })) .pipe(preprocess({ context }))
.pipe(inlineimg()) .pipe(inlineImg())
.pipe( .pipe(
inlineCss({ inlineCss({
applyTableAttributes: true, applyTableAttributes: true,

View File

@ -8,15 +8,17 @@ const PluginError = require('plugin-error');
const through = require('through2'); const through = require('through2');
const cheerio = require('cheerio'); const cheerio = require('cheerio');
const { log } = require('./util/util');
const PLUGIN_NAME = 'gulp-inline-images'; const PLUGIN_NAME = 'gulp-inline-images';
const MIME_TYPE_REGEX = /.+\/([^\s]*)/; const MIME_TYPE_REGEX = /.+\/([^\s]*)/;
const INLINE_ATTR = 'inline'; const INLINE_ATTR = 'inline';
const NOT_INLINE_ATTR = `!${INLINE_ATTR}`; const NOT_INLINE_ATTR = `!${INLINE_ATTR}`;
function inlineimg(options = {}) { function inlineImg(options = {}) {
var selector = options.selector || 'img[src]'; const selector = options.selector || 'img[src]';
var attribute = options.attribute || 'src'; const attribute = options.attribute || 'src';
var getHTTP = options.getHTTP || false; const getHTTP = options.getHTTP || false;
return through.obj(function(file, encoding, callback) { return through.obj(function(file, encoding, callback) {
if (file.isStream()) { if (file.isStream()) {
@ -25,29 +27,30 @@ function inlineimg(options = {}) {
} }
if (file.isBuffer()) { if (file.isBuffer()) {
var contents = file.contents.toString(encoding); const contents = file.contents.toString(encoding);
// Load it into cheerio's virtual DOM for easy manipulation // Load it into cheerio's virtual DOM for easy manipulation
var $ = cheerio.load(contents); const $ = cheerio.load(contents);
var inline_flag = $(`img[${INLINE_ATTR}]`); const inlineFlag = $(`img[${INLINE_ATTR}]`);
// If images with an inline attr are found that is the selection we want // If images with an inline attr are found that is the selection we want
var img_tags = inline_flag.length ? inline_flag : $(selector); const imgTags = inlineFlag.length ? inlineFlag : $(selector);
var count = 0; let count = 0;
imgTags.each(function() {
const $img = $(this);
const src = $img.attr(attribute);
img_tags.each(function() {
var $img = $(this);
var src = $img.attr(attribute);
// Save the file format from the extension // Save the file format from the extension
var ext_format = path.extname(src).substr(1); const extFormat = path.extname(src).substr(1);
// If inline_flag tags were found we want to remove the inline tag // If inlineFlag tags were found we want to remove the inline tag
if (inline_flag.length) { if (inlineFlag.length) {
$img.removeAttr(INLINE_ATTR); $img.removeAttr(INLINE_ATTR);
} }
// Find !inline attribute // Find !inline attribute
var not_inline_flag = $img.attr(NOT_INLINE_ATTR); const notInlineFlag = $img.attr(NOT_INLINE_ATTR);
if (typeof not_inline_flag !== typeof undefined && not_inline_flag !== false) { if (typeof notInlineFlag !== typeof undefined && notInlineFlag !== false) {
// Remove the tag and don't process this file // Remove the tag and don't process this file
return $img.removeAttr(NOT_INLINE_ATTR); return $img.removeAttr(NOT_INLINE_ATTR);
} }
@ -55,18 +58,18 @@ function inlineimg(options = {}) {
// Count async ops // Count async ops
count++; count++;
getSrcBase64(options.basedir || file.base, getHTTP, src, function(err, result, res_format, skip_formatting) { getSrcBase64(options.basedir || file.base, getHTTP, src, (err, result, resFormat, skipFormatting) => {
if (err) { if (err) {
console.error(err); log.error(err);
} else { } else {
// Need a format in and a result for this to work // Need a format in and a result for this to work
if (!skip_formatting) { if (!skipFormatting) {
if (result && (ext_format || res_format)) { if (result && (extFormat || resFormat)) {
$img.attr('src', `data:image/${ext_format};base64,${result}`); $img.attr('src', `data:image/${extFormat};base64,${result}`);
} else { } else {
$img.attr('src', ``); $img.attr('src', ``);
$img.attr('alt', `Image not found, Please check Url`); $img.attr('alt', `Image not found, Please check Url`);
console.error(`Failed to identify format of ${src}!`); log.warn(`Failed to read image. Check the format of ${src}.`);
} }
} }
@ -79,7 +82,7 @@ function inlineimg(options = {}) {
}); });
// If no files are processing we don't need to wait as none were ever started // If no files are processing we don't need to wait as none were ever started
if (!img_tags.length) { if (!imgTags.length) {
file.contents = Buffer.from($.html()); file.contents = Buffer.from($.html());
callback(null, file); callback(null, file);
} }
@ -89,9 +92,9 @@ function inlineimg(options = {}) {
function getHTTPBase64(url, callback) { function getHTTPBase64(url, callback) {
// Get applicable library // Get applicable library
var lib = url.startsWith('https') ? https : http; const lib = url.startsWith('https') ? https : http;
// Initiate a git request to our URL // Initiate a git request to our URL
var req = lib.get(url, res => { const req = lib.get(url, res => {
// Check for redirect // Check for redirect
if (res.statusCode >= 301 && res.statusCode < 400 && res.headers.location) { if (res.statusCode >= 301 && res.statusCode < 400 && res.headers.location) {
// Redirect // Redirect
@ -102,14 +105,16 @@ function getHTTPBase64(url, callback) {
return callback(new Error('Failed to load page, status code: ' + res.statusCode)); return callback(new Error('Failed to load page, status code: ' + res.statusCode));
} }
// Get file format // Get file format
var format; let format;
if (res.headers['content-type']) { if (res.headers['content-type']) {
var matches = res.headers['content-type'].match(MIME_TYPE_REGEX); const matches = res.headers['content-type'].match(MIME_TYPE_REGEX);
if (matches) format = matches[1]; if (matches) {
format = matches[1];
}
} }
// Create an empty buffer to store the body in // Create an empty buffer to store the body in
var body = Buffer.from([]); let body = Buffer.from([]);
// Append each chunk to the body // Append each chunk to the body
res.on('data', chunk => (body = Buffer.concat([body, chunk]))); res.on('data', chunk => (body = Buffer.concat([body, chunk])));
@ -123,11 +128,12 @@ function getHTTPBase64(url, callback) {
} }
function getSrcBase64(base, getHTTP, src, callback) { function getSrcBase64(base, getHTTP, src, callback) {
// TODO: @deprecated — since v11.0.0 url.parse should be replaced with url.URL() ctor
if (!url.parse(src).hostname) { if (!url.parse(src).hostname) {
// Get local file // Get local file
var file_path = path.join(base, src); const filePath = path.join(base, src);
if (fs.existsSync(file_path)) { if (fs.existsSync(filePath)) {
fs.readFile(file_path, 'base64', callback); fs.readFile(filePath, 'base64', callback);
} else { } else {
callback(null); callback(null);
} }
@ -141,6 +147,8 @@ function getSrcBase64(base, getHTTP, src, callback) {
} }
} }
module.exports.inlineimg = inlineimg; module.exports = {
module.exports.getHTTPBase64 = getHTTPBase64; inlineImg,
module.exports.getSrcBase64 = getSrcBase64; getHTTPBase64,
getSrcBase64
};