terminal-small.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. const backgroundWhite = '\x1b[47m'
  2. const backgroundBlack = '\x1b[40m'
  3. const foregroundWhite = '\x1b[37m'
  4. const foregroundBlack = '\x1b[30m'
  5. const reset = '\x1b[0m'
  6. const lineSetupNormal = backgroundWhite + foregroundBlack // setup colors
  7. const lineSetupInverse = backgroundBlack + foregroundWhite // setup colors
  8. const createPalette = function (lineSetup, foregroundWhite, foregroundBlack) {
  9. return {
  10. // 1 ... white, 2 ... black, 0 ... transparent (default)
  11. '00': reset + ' ' + lineSetup,
  12. '01': reset + foregroundWhite + '▄' + lineSetup,
  13. '02': reset + foregroundBlack + '▄' + lineSetup,
  14. 10: reset + foregroundWhite + '▀' + lineSetup,
  15. 11: ' ',
  16. 12: '▄',
  17. 20: reset + foregroundBlack + '▀' + lineSetup,
  18. 21: '▀',
  19. 22: '█'
  20. }
  21. }
  22. /**
  23. * Returns code for QR pixel
  24. * @param {boolean[][]} modules
  25. * @param {number} size
  26. * @param {number} x
  27. * @param {number} y
  28. * @return {'0' | '1' | '2'}
  29. */
  30. const mkCodePixel = function (modules, size, x, y) {
  31. const sizePlus = size + 1
  32. if ((x >= sizePlus) || (y >= sizePlus) || (y < -1) || (x < -1)) return '0'
  33. if ((x >= size) || (y >= size) || (y < 0) || (x < 0)) return '1'
  34. const idx = (y * size) + x
  35. return modules[idx] ? '2' : '1'
  36. }
  37. /**
  38. * Returns code for four QR pixels. Suitable as key in palette.
  39. * @param {boolean[][]} modules
  40. * @param {number} size
  41. * @param {number} x
  42. * @param {number} y
  43. * @return {keyof palette}
  44. */
  45. const mkCode = function (modules, size, x, y) {
  46. return (
  47. mkCodePixel(modules, size, x, y) +
  48. mkCodePixel(modules, size, x, y + 1)
  49. )
  50. }
  51. exports.render = function (qrData, options, cb) {
  52. const size = qrData.modules.size
  53. const data = qrData.modules.data
  54. const inverse = !!(options && options.inverse)
  55. const lineSetup = options && options.inverse ? lineSetupInverse : lineSetupNormal
  56. const white = inverse ? foregroundBlack : foregroundWhite
  57. const black = inverse ? foregroundWhite : foregroundBlack
  58. const palette = createPalette(lineSetup, white, black)
  59. const newLine = reset + '\n' + lineSetup
  60. let output = lineSetup // setup colors
  61. for (let y = -1; y < size + 1; y += 2) {
  62. for (let x = -1; x < size; x++) {
  63. output += palette[mkCode(data, size, x, y)]
  64. }
  65. output += palette[mkCode(data, size, size, y)] + newLine
  66. }
  67. output += reset
  68. if (typeof cb === 'function') {
  69. cb(null, output)
  70. }
  71. return output
  72. }