Module:Term

From Space Station 14 Wiki
Revision as of 21:08, 14 March 2025 by Aliser (talk | contribs) (fixed display for when listing all terms)
Module documentation
View or edit this documentation (about module documentation)
Uses JSON data
This module uses JSON data pages:

Implements {{Term}}.

Adding new terms

Go to the JSON file linked at the top of this page.

That file contains definitions for terms.

Term is defined with a lowercase key and an object value.

The object value has following format:

{
	"proper name": "[optional] proper term name, for example: LRP",
    "definition": "[optional] term definition",
    "link": "[optional] a page to link the term to",
}

Note that at least a definition or a link should be provided for a term.


local p = {}
local getArgs = require('Module:Arguments').getArgs

local terms_json = mw.loadJsonData("Module:Term/terms.json")

local function assert_not_nil(value, error_message)
    if value == nil then
        if error_message == nil then
            error("value is nil")
        else
            error(error_message)
        end
    end
end

-- =========================

-- Lookups term from the json. If a term is defined, returns the object defining it, or `nil` otherwise.
local function lookup_term(term)
	return terms_json[string.lower(term)]
end

-- Generates a term element with a tooltip and/or a link.
function p.main(frame)
	local args = getArgs(frame)
	local term = args[1]
	assert_not_nil(term, "failed to generate term: term not provided")
	
	local term_obj = lookup_term(term)
	if not term_obj then
		error("failed to lookup term: term '" .. term .. "' not defined. Make sure the term is defined in the terms JSON file")	
	end
	
	local term_definition = term_obj["definition"]
	local term_link = term_obj["link"]
	local term_proper_name = term_obj["proper name"] or term
	
	if term_definition == nil and term_link == nil then
		error("failed to generate term: found term in the terms JSON file, but it doesn't have a definition nor a link'" .. term .. "'")
	end
	
	local term_wikitext = term_link == nil and term_proper_name or "[[" .. term_link .. "|" .. term_proper_name .. "]]"
	
	if term_definition == nil then
		-- no definition = return just the link
		return term_wikitext
	else
		-- yes definition = generate a tooltip
		return frame:expandTemplate{
			title = 'Tooltip',
			args = {
				term_wikitext,
				term_definition
			}
		}
	end
end

-- Generates a list of terms.
-- 
-- @param `columns` - amount of columns to generate for all terms. Default is `4`.
function p.list_all_terms(frame)
	frame = frame or mw.getCurrentFrame()
	
	local columns = frame.columns or 4

	local term_els = {}
	for term, _ in pairs(terms_json) do
		frame.args[1] = term

		local wrapper_el_str = mw.html.create('div')
			:node(p.main(frame))

		table.insert(term_els, tostring(wrapper_el_str))
	end

	return frame:expandTemplate{
		title = 'Cols',
		args = {
			columns,
			table.concat(term_els, '')
		}
	}
end

return p