Module:OpenHistoricalMap/News

From OpenStreetMap Wiki
Jump to navigation Jump to search
[Edit] [Purge] Documentation

Usage

This module populates {{OpenHistoricalMap/News}} with a list of OpenHistoricalMap project news from Module:OpenHistoricalMap/News/data.json.

main

|date_format =
The date format for the header of each event in the list.
|historical = yes
Formats the list for a historical archive. The list includes old news and is sorted chronologically (instead of reverse-chronologically).

See also

local p = {}
local languages = require("Module:Languages")

function p.main(frame)
	local title = mw.title.getCurrentTitle()
	local lang = mw.getLanguage(languages.languageFromTitle(title))
	local langCode = lang:getCode()
	-- MediaWiki abnormally lowercases ISO 3166 and ISO 15924 codes in locales.
	langCode = langCode:gsub("-(%w%w%w%w)", function (script)
		return "-" .. script:sub(1, 1):upper() .. script:sub(2)
	end):gsub("-(%w%w)$", function (country)
		return "-" .. country:upper()
	end)
	
	local dateFormat = frame.args.date_format and #frame.args.date_format > 0 and frame.args.date_format or "F j, Y"
	local historical = frame.args.historical == "yes"

	local events = mw.loadJsonData("Module:OpenHistoricalMap/News/data.json")
	if not historical then
		-- Clone the read-only JSON data in order to manipulate it; mw.clone() requires write permissions.
		events = mw.text.jsonDecode(mw.text.jsonEncode(events))
		for i, event in ipairs(events) do
			event.date = event.date or event.end_date
		end
		-- Sort the data reverse-chronologically.
		table.sort(events, function (a, b)
			return a.date > b.date
		end)
	end
	
	local aLongTimeAgo = lang:formatDate("c", "-6 months")
	local today = lang:formatDate("c")
	local list = mw.html.create("dl")
	
	local maxEvents = 5
	for i, event in ipairs(events) do
		-- Omit old news.
		if not historical and (i > maxEvents or event.date < aLongTimeAgo) then
			break
		end
		
		local description = event.description[langCode]
		-- Fall back to the description in the same language plus some region.
		if description == nil and langCode:match("-(%w%w)$") == nil then
			for l, d in pairs(event.description) do
				if l:gsub("-(%w%w)$", "") == langCode then
					description = d
					break
				end
			end
		end
		-- Fall back to the description in English.
		if description == nil then
			description = event.description.en
		end
		
		-- Omit embargoed or expired news.
		if not historical and
			((event.start_date and event.start_date > today) or
				(event.end_date and event.end_date < today)) then
			maxEvents = maxEvents + 1
		else
			list:tag("dt")
				:wikitext(lang:formatDate(dateFormat, event.date))
			list:tag("dd")
				:wikitext(frame:preprocess(description))
		end
	end
	
	return list
end

return p