跳转到内容

模組:Carousel

维基百科,自由的百科全书

这是本页的一个历史版本,由PhiLiP留言 | 贡献2017年3月5日 (日) 00:03编辑。这可能和当前版本存在着巨大的差异。

local p = {}
local lang = mw.language.new('zh')

function tostringOrNil(value)
	if value ~= nil then
		value = tostring(value)
	end
end

function getCandidateList(args)
	local page = mw.title.new(args.pageName)
	local candidates =
		mw.text.jsonDecode(page:getContent(), mw.text.JSON_TRY_FIXING)

	-- change mw timestamp to unix timestamp
	for _, item in pairs(candidates) do
		for i in pairs(item.displayTimeRanges) do
			item.displayTimeRanges[i][1] = tonumber(
				lang:formatDate('U', tostring(item.displayTimeRanges[i][1]))
			)
			-- use current time when the "end time" is null
			item.displayTimeRanges[i][2] = tonumber(
				lang:formatDate(
					'U', tostringOrNil(item.displayTimeRanges[i][2])
				)
			)
		end
	end
	return candidates
end

function pickCandidate(candidateList, currentTime, timeStart, timeInterval)
	local processedTime = timeStart
	local minRangeStart = 0xffffffffffffffff
	local currentDisplayStart =
		math.floor(currentTime / timeInterval) * timeInterval
	local currentDisplayEnd = currentDisplayStart + timeInterval
	while true do
		for _, item in pairs(candidateList) do
			for _, range in pairs(item.displayTimeRanges) do
				local rangeStart = range[1]
				local rangeEnd =
					math.ceil(range[2] / timeInterval) * timeInterval
				minRangeStart = math.min(minRangeStart, rangeStart)
				if processedTime < range[1] or
					processedTime > rangeEnd then
					-- continue
				else
					processedTime = processedTime + timeInterval
					break
				end
			end
			if processedTime >= currentDisplayStart and
				processedTime < currentDisplayEnd then
				return item.title
			end
		end
		processedTime = math.max(processedTime, minRangeStart)
	end
end

function p.main(frame)
	local candidateList = getCandidateList{pageName = frame.args.candidateList}
	local currentTime = tonumber(
		lang:formatDate('U', tostringOrNil(frame.args.currentTime))
	)
	local timeStart = tonumber(
		lang:formatDate(
			"U", tostringOrNil(frame.args.timeStart) or '19700101000000'
		)
	)
	local timeInterval = tonumber(frame.args.timeInterval) or 86400
	local title = frame.args.titlePrefix
	local title = title + pickCandidate(
		candidateList, currentTime, timeStart, timeInterval)
	return mw.getCurrentFrame():expandTemplate { title = title }
end

return p