color-yiq.js 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. let yiqThreshold = 0
  2. let yiqTextDark = ''
  3. let yiqTextLight = ''
  4. //
  5. // Helper Functions
  6. //
  7. function lookupVariable(context, variableName) {
  8. const { frames, importantScope } = context
  9. return tree.Variable.prototype.find(frames, frame => {
  10. const { value, important } = frame.variable(variableName) || {}
  11. if (value === undefined)
  12. return
  13. if (important && importantScope[importantScope.length - 1])
  14. importantScope[importantScope.length - 1].important = important
  15. return value.eval(context)
  16. })
  17. }
  18. //
  19. // Less Functions
  20. //
  21. functions.add('color-yiq', function ({ rgb: [r, g, b] }, dark, light) {
  22. const yiq = ((r * 299) + (g * 587) + (b * 114)) / 1000
  23. if (yiqThreshold === 0)
  24. yiqThreshold = lookupVariable(this.context, '@yiq-contrasted-threshold').value
  25. if (yiqTextDark === '')
  26. yiqTextDark = lookupVariable(this.context, '@yiq-text-dark')
  27. if (yiqTextLight === '')
  28. yiqTextLight = lookupVariable(this.context, '@yiq-text-light')
  29. if (! dark)
  30. dark = yiqTextDark
  31. if (! light)
  32. light = yiqTextLight
  33. return (yiq >= yiqThreshold) ? dark : light
  34. })