From 04be92e68cf642ab26faca9c246e795b106b7f9c Mon Sep 17 00:00:00 2001 From: Cruor Date: Tue, 9 Aug 2022 17:02:34 +0200 Subject: [PATCH] Added simple path/filename validation field type Allows specifying what it accepts (folder, filename, filename extensions) Supports having the path/filename relative to the current mod folder --- src/ui/forms/fields/path.lua | 69 ++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 src/ui/forms/fields/path.lua diff --git a/src/ui/forms/fields/path.lua b/src/ui/forms/fields/path.lua new file mode 100644 index 00000000..9bd2e1e1 --- /dev/null +++ b/src/ui/forms/fields/path.lua @@ -0,0 +1,69 @@ +local utils = require("utils") +local mods = require("mods") +local loadedState = require("loaded_state") +local stringField = require("ui.forms.fields.string") + +local pathField = {} + +pathField.fieldType = "path" + +function pathField.getElement(name, value, options) + -- Add extra options and pass it onto string field + + local allowEmpty = options.allowEmpty + local allowMissingPath = options.allowMissingPath + local allowFolders = options.allowFolders + local allowFiles = options.allowFiles + local allowedExtensions = options.allowedExtensions + local relativeToMod = options.relativeToMod + + options.validator = function(filename) + local fieldEmpty = filename == nil or #filename == 0 + + if fieldEmpty then + return allowEmpty ~= false + end + + if relativeToMod ~= false then + local modPath = mods.getFilenameModPath(loadedState.filename) + + if not modPath then + return false + end + + filename = utils.joinpath(modPath, filename) + end + + local attributes = utils.pathAttributes(filename) + + if not attributes and allowMissingPath ~= false then + return false + end + + local attributeMode = attributes.mode or "missing" + + if attributeMode == "directory" and not allowFolders then + return false + end + + if attributeMode == "file" then + local fileExtension = utils.fileExtension(filename) + + if allowFiles == false then + return false + end + + if allowedExtensions and not utils.contains(fileExtension, allowedExtensions) then + return false + end + end + + -- TODO - Custom validator at this point? + + return true + end + + return stringField.getElement(name, value, options) +end + +return pathField \ No newline at end of file