summaryrefslogtreecommitdiff
path: root/lua/clever_f/feedback_service.lua
blob: f7e1dd6488fbb3685d98fdcd800365f0ad1d4878 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
local M = {}
local FeedbackService = {}
FeedbackService.__index = FeedbackService
M.FeedbackService = FeedbackService

M.DEFAULT_LABEL_GROUP = "CleverFDefaultLabel"

local service_records = setmetatable({}, { __mode = "k" })

local DEFAULT_LABEL_DEFINITION = {
  guifg = "red",
  guibg = "NONE",
  gui = {
    bold = true,
    underline = true,
  },
  ctermfg = "red",
  ctermbg = "NONE",
  cterm = {
    bold = true,
    underline = true,
  },
}

local function copy(value)
  if type(value) ~= "table" then
    return value
  end
  local result = {}
  for key, item in pairs(value) do
    result[key] = copy(item)
  end
  return result
end

function M.default_label_definition()
  return copy(DEFAULT_LABEL_DEFINITION)
end

local function fail(message, level)
  error(message, (level or 1) + 1)
end

local function normalize_options(options)
  if type(options) ~= "table" then
    fail("FeedbackService options must be a table", 3)
  end
  if options.host == nil then
    return { host = options }
  end
  return options
end

local function require_host(host)
  if type(host) ~= "table" or type(host.read_highlight_group) ~= "function" then
    fail("FeedbackService host must provide highlight groups", 3)
  end
  return host
end

function FeedbackService.new(options)
  if FeedbackService.is(options) then
    return options
  end
  options = normalize_options(options)
  local service = setmetatable({}, FeedbackService)
  service_records[service] = {
    host = require_host(options.host),
  }
  return service
end

function FeedbackService.is(value)
  return type(value) == "table" and service_records[value] ~= nil
end

function FeedbackService:ensure_default_label()
  local existing = service_records[self].host:read_highlight_group(
    M.DEFAULT_LABEL_GROUP
  )
  if existing ~= nil then
    return {
      group = M.DEFAULT_LABEL_GROUP,
      definition = existing,
      source = "colorscheme",
      applied = false,
    }
  end
  return nil
end

function M.new(options)
  return FeedbackService.new(options)
end

setmetatable(M, {
  __call = function(_, options)
    return FeedbackService.new(options)
  end,
})

return M