c-log-kit
Version:
Colourful console log.
92 lines (89 loc) • 2.94 kB
JavaScript
import { capitalizeFirstLetter, typeOf } from './utilities.js';
import packageJSON from '../package.js';
const cLog = {};
const _console = console;
if (!window.cLog) {
window.cLog = cLog;
}
const chalkColors = {
black: "#000000",
white: "#FFFFFF",
red: "#f5222d",
orange: "#faad14",
green: "#52c41a",
blue: "#1890ff"
};
const apiObj = {
log: "black",
info: "blue",
warn: "orange",
error: "red",
success: "green"
};
cLog["hello"] = () => {
console.log(
"%c%s%c%s",
"padding: 2px 4px; border-radius: 3px 0 0 3px; color: #fff; font-weight: bold; background:#1890ff;",
"cLog",
"padding: 2px 4px; color: #000; border-radius: 0 3px 3px 0px; font-weight: bold; background:#e8eaec;",
`V${packageJSON.version}`
);
};
const generateStyle = (color, bg = false, borderRadius = true) => {
const defaultStyle = `padding: 2px;`;
return bg ? `${defaultStyle} color: #FFF; ${borderRadius ? "border-radius: 3px;" : ""} background: ${color};` : `${defaultStyle} color: ${color};`;
};
function generateOutput(type, ...args) {
const replaceCharacters = args.map((arg) => {
return ["object", "array", "function"].includes(typeOf(arg)) ? "%o" : "%s";
});
if (Object.keys(chalkColors).includes(type)) {
const color = chalkColors[type];
return [`%c ${replaceCharacters.join(" ")} `, generateStyle(color), ...args];
}
if (Object.keys(chalkColors).map((item) => `bg${capitalizeFirstLetter(item)}`).includes(type)) {
const color = chalkColors[type.replace("bg", "").toLowerCase()];
return [
`%c ${replaceCharacters.join(" ")} `,
generateStyle(color, true),
...args
];
}
if (Object.keys(apiObj).includes(type)) {
const color = chalkColors[apiObj[type]];
const label = capitalizeFirstLetter(type);
return [
`%c[${label}] ${replaceCharacters.join(" ")} `,
generateStyle(color),
...args
];
}
}
function splicing(...args) {
const results = args.reduce((result, current) => {
const [outputs = "", ...otherContent] = result;
if (typeOf(current) === "array" && current.length > 2) {
const [output, ...others] = current;
return [outputs.concat(output), ...otherContent, ...others];
}
return result;
}, []);
return results;
}
const generatePrintFunc = (methodName) => {
const printFunc = _console[methodName] ? _console[methodName] : _console.log;
return (...args) => printFunc(...args);
};
Object.keys(chalkColors).forEach((key) => {
cLog[key] = (...args) => generateOutput(key, ...args);
});
Object.keys(chalkColors).forEach((key) => {
cLog[`bg${capitalizeFirstLetter(key)}`] = (...args) => generateOutput(`bg${capitalizeFirstLetter(key)}`, ...args);
});
Object.keys(apiObj).forEach((key) => {
cLog[key] = (...args) => generatePrintFunc(key)(...generateOutput(key, ...args));
});
cLog["splice"] = (...args) => {
return _console.log(...splicing(...args));
};
export { cLog as default };