Skip to content

Commit

Permalink
Merge pull request #12 from willothy/feat-validator-combinators
Browse files Browse the repository at this point in the history
Feat validator combinators
  • Loading branch information
mobily authored Apr 1, 2024
2 parents 087030d + c627111 commit 6202be4
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 6 deletions.
11 changes: 9 additions & 2 deletions docs/pages/docs/components/form.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,14 @@ n.form(

#### on_submit

<Property
<Property
defaultValue="fn.ignore"
types={['fun(is_valid: boolean): nil']}
/>

#### submit_key

<Property
<Property
defaultValue="<C-CR>"
types={['string[]', 'string']}
/>
Expand All @@ -63,4 +63,11 @@ Available validation functions:
- `equals`
- `contains`

Available combinators:

- `all`: ensures all validators pass
- `any`: ensures at least one validator passes
- `none`: ensures no validators pass
- `compose` (deprecated, use `all`)


43 changes: 39 additions & 4 deletions lua/nui-components/validators.lua
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
local M = {}

---@type fun(min: integer): fun(arg: string): boolean
function M.min_length(min)
return function(arg)
return #arg >= min
end
end

---@type fun(arg: string): boolean
M.is_not_empty = M.min_length(1)

function M.max_length(max)
Expand All @@ -14,23 +16,52 @@ function M.max_length(max)
end
end

---@type fun(pattern: string): fun(arg: string): boolean
function M.contains(pattern)
return function(arg)
return string.find(arg, pattern)
return string.find(arg, pattern) ~= nil
end
end

---@type fun(value: any): fun(arg: any): boolean
function M.equals(value)
return function(arg)
return vim.deep_equal(value, arg)
end
end

function M.compose(...)
local tbl = { ... }
---@type fun(...: fun(arg: any): boolean): fun(arg: any): boolean
function M.none(...)
local validators = { ... }
return function(value)
for _, fn in ipairs(validators) do
if fn(value) then
return false
end
end
return true
end
end

---@type fun(...: fun(arg: any): boolean): fun(arg: any): boolean
function M.any(...)
local validators = { ... }
return function(value)
for _, fn in ipairs(validators) do
if fn(value) then
return true
end
end
return false
end
end

---@type fun(...: fun(arg: any): boolean): fun(arg: any): boolean
local function all(...)
local validators = { ... }

return function(value)
for _, fn in ipairs(tbl) do
for _, fn in ipairs(validators) do
if not fn(value) then
return false
end
Expand All @@ -40,4 +71,8 @@ function M.compose(...)
end
end

M.all = all

M.compose = all

return M

0 comments on commit 6202be4

Please sign in to comment.