Backend for Template:ko-symbol-nav.


local m_str_utils = require("Module:string utilities")

local codepoint = m_str_utils.codepoint
local concat = table.concat
local insert = table.insert
local len = m_str_utils.len
local u = m_str_utils.char

local export = {}

local function link(char, alt)
	return '[[' .. char .. '|' .. (alt or char) .. ']]'
end

local function mark(char)
	return '<mark><b>' .. char .. '</b></mark>'
end

function export.show(frame)
	local hangul_original = mw.title.getCurrentTitle().text

	if len(hangul_original) ~= 1 then
		return error("Template:ko-symbol-nav is for use on single-Hangul entries.")
	end

	local block_size = 28
	local offset = 44032 -- codepoint('가')
	local hangul_cv_ncr = codepoint(hangul_original) - ((codepoint(hangul_original) - offset) % block_size)
	local hangul_cv = u(hangul_cv_ncr)

	-- Generate the Hangul syllables for the table.
	local i = 0
	local full_hangul_set = { hangul_cv }
	while i < block_size do
		full_hangul_set[i + 1] = u(hangul_cv_ncr + i)
		i = i + 1
	end

	-- Build the table.
	local table_final = {}
	insert(table_final, '<table lang="ko" class="wikitable floatright Kore">')

	-- First table row
	insert(table_final, '<tr>')
	insert(table_final, '<td colspan="2" style="white-space: nowrap;">')
	-- Link to syllables.
	-- Note that ipairs() starts from table item 1, hence full_hangul_set[i + 1] above.
	for i, hangul in ipairs(full_hangul_set) do
		if hangul == hangul_original then
			insert(table_final, mark(hangul))
		else
			insert(table_final, link(hangul))
		end
		-- For every seventh syllable...
		if (i % 7) == 0 then
			insert(table_final, '<br />')
		end
	end
	insert(table_final, '</td>')
	insert(table_final, '</tr>')

	-- Second table row (footer)
	insert(table_final, '<tr>')
	insert(table_final, '<th style="width:50%; text-align:left;">')
	if hangul_cv ~= '가' then
		local prev = u(hangul_cv_ncr - block_size)
		insert(table_final, link(prev, prev .. ' ←'))
	end
	insert(table_final, '</th>')
	insert(table_final, '<th style="width:50%; text-align:right;">')
	if hangul_cv ~= '히' then
		local next = u(hangul_cv_ncr + block_size)
		insert(table_final, link(next, '→ ' .. next))
	end
	insert(table_final, '</th>')
	insert(table_final, '</tr>')

	insert(table_final, '</table>')

	return concat(table_final)
end

return export