|
| 1 | +local files = require "files" |
| 2 | +local guide = require "parser.guide" |
| 3 | + |
| 4 | +local colorPattern = string.rep('%x', 8) |
| 5 | +---@param source parser.object |
| 6 | +---@return boolean |
| 7 | +local function isColor(source) |
| 8 | + ---@type string |
| 9 | + local text = source[1] |
| 10 | + if text:len() ~= 8 then |
| 11 | + return false |
| 12 | + end |
| 13 | + return text:match(colorPattern) |
| 14 | +end |
| 15 | + |
| 16 | + |
| 17 | +---@param colorText string |
| 18 | +---@return Color |
| 19 | +local function textToColor(colorText) |
| 20 | + return { |
| 21 | + alpha = tonumber(colorText:sub(1, 2), 16) / 255, |
| 22 | + red = tonumber(colorText:sub(3, 4), 16) / 255, |
| 23 | + green = tonumber(colorText:sub(5, 6), 16) / 255, |
| 24 | + blue = tonumber(colorText:sub(7, 8), 16) / 255, |
| 25 | + } |
| 26 | +end |
| 27 | + |
| 28 | + |
| 29 | +---@param color Color |
| 30 | +---@return string |
| 31 | +local function colorToText(color) |
| 32 | + return ('' |
| 33 | + .. string.format('%02x', math.tointeger(color.alpha * 255)) |
| 34 | + .. string.format('%02x', math.tointeger(color.red * 255)) |
| 35 | + .. string.format('%02x', math.tointeger(color.green * 255)) |
| 36 | + .. string.format('%02x', math.tointeger(color.blue * 255))):upper() |
| 37 | +end |
| 38 | + |
| 39 | +---@class Color |
| 40 | +---@field red number |
| 41 | +---@field green number |
| 42 | +---@field blue number |
| 43 | +---@field alpha number |
| 44 | + |
| 45 | +---@class ColorValue |
| 46 | +---@field color Color |
| 47 | +---@field start integer |
| 48 | +---@field finish integer |
| 49 | + |
| 50 | +---@async |
| 51 | +function colors(uri) |
| 52 | + local state = files.getState(uri) |
| 53 | + local text = files.getText(uri) |
| 54 | + if not state or not text then |
| 55 | + return nil |
| 56 | + end |
| 57 | + ---@type ColorValue[] |
| 58 | + local colors = {} |
| 59 | + |
| 60 | + guide.eachSource(state.ast, function (source) ---@async |
| 61 | + if source.type == 'string' and isColor(source) then |
| 62 | + ---@type string |
| 63 | + local colorText = source[1] |
| 64 | + |
| 65 | + colors[#colors+1] = { |
| 66 | + start = source.start + 1, |
| 67 | + finish = source.finish - 1, |
| 68 | + color = textToColor(colorText) |
| 69 | + } |
| 70 | + end |
| 71 | + end) |
| 72 | + return colors |
| 73 | +end |
| 74 | +return { |
| 75 | + colors = colors, |
| 76 | + colorToText = colorToText |
| 77 | +} |
0 commit comments