0.1.1Updated a month ago
export interface LoggerProps {
  /** A single-char emoji or unicode character */
  glyph?: string | (() => string)
  /** A color string, or a function returning a color string */
  glyph_color?: string | (() => string)
  /** The name that will be prepended to each log */
  name: string
  /** A color string, or a function returning a color string */
  name_color?: string | (() => string)
}

export const logger = ({ glyph, glyph_color, name, name_color }: LoggerProps) => (...data: unknown[]) => {
  let start_string = `%c${new Date().toISOString()}%c  `;
  const style_rules: string[] = ["color: grey", ""];

  if(glyph !== undefined) {
    let glyph_text: string;

    if(typeof glyph == 'string') {
      glyph_text = glyph;
    } else {
      glyph_text = glyph();
    }

    glyph_text = glyph_text.substring(0, 1).padEnd(1, '?');

    if(glyph_color !== undefined) {
      start_string += `%c${glyph_text}%c `;
      if(typeof glyph_color == 'string') {
        style_rules.push(`color: ${glyph_color}`, "");
      } else {
        style_rules.push(`color: ${glyph_color()}`, "");
      }
    } else {
      start_string += `${glyph_text} `;
    }
  }

  const name_max_length = glyph ? 12 : 14;

  let name_string = name;
  if(name_string.length > name_max_length) {
    name_string = name_string.substring(0, name_max_length - 1) + '';
  }
  name_string = name_string.padEnd(name_max_length);

  if(name_color !== undefined) {
    start_string += `%c${name_string}%c `;
    if(typeof name_color == 'string') {
      style_rules.push(`color: ${name_color}`, "");
    } else {
      style_rules.push(`color: ${name_color()}`, "");
    }
  } else {
    start_string += `${name_string} `;
  }

  let style_rules_to_shift = 0;

  while(data.length && (data[0] as string | undefined)?.includes?.('%c')) {
    const text = (data as string[]).shift()!;
    start_string += ' ' + text;
    style_rules_to_shift += text.split('%c').length - 1;
  }

  if(style_rules_to_shift > 0) {
    style_rules.push(...(data as string[]).splice(0, style_rules_to_shift));
  }

  console.log(start_string + '%c', ...style_rules, "", ...data);
}