본문으로 이동

모듈:Proofreadpage index template

준보호 중인 문서
위키문헌, 우리 모두의 도서관.
모듈 설명문서[보기] [편집] [역사] [새로 고침]

색인 이름공간에서 호출되는 미디어위키:Proofreadpage index template에서 사용하는 모듈입니다.

--[=[
This is a module to implement logic for [[MediaWiki:Proofreadpage index template]]

It doesn't do everything yet, but over time it can accrete functions from
the template, which will become simpler and simpler until it's just an invoke.

Implemented so far:
 * Status categorisation and field
 * Some auxiliary data fields
]=]

local getArgs = require('Module:Arguments').getArgs
local messageBox = require('Module:Message box')
local ISO_639 = require('Module:ISO 639')

local p = {} --p stands for package

local DEFAULTS = {
	Source = '기타',
}


-- mapping of field ID to field properties
local headings = {
	title = {
		txt = '제목',
	},
	progress = {
		txt = '진행 상황',
	},
	oclc = {
		txt = 'OCLC',
	},
    transclusion = {
    	txt = '끼워넣기',
    },
    validation_date = {
    	txt = '에 검증됨',
    },
    source = {
    	txt = '출처'
    },
    place = {
    	txt = '위치'
    },
    year = {
    	txt = '연도'
    },
    publisher = {
    	txt = '출판사'
    },
    author = {
    	txt = '저자'
    },
    editor = {
    	txt = '편집자'
    },
    translator = {
    	txt = '번역자'
    },
    illustrator = {
    	txt = '삽화가'
    },
    doi = {
    	txt = 'DOI'
    },
    volumes = {
    	txt = '권별 색인'
    }
}

local indicators = {
--	pagegame = {
--		name = "WS Page Game",
--		image = "File:OOjs UI icon page number.svg",
--		link = "{{fullurl:toolforge:ws-page-game|wikisource=en&index={{PAGENAMEE}}&lang=en}}",
--		caption = "Wikisource Page Game (step-by-step pagelist builder)"
--	},
	purge = {
		name = "purge file",
		image = "File:OOjs UI icon reload.svg",
		link = "{{fullurl:commons:File:{{PAGENAME}}|action=purge}}",
		caption = "위키미디어 공용에서 파일 새로 고침"
	},
--	book2scroll = {
--		name = "book2scroll",
--		image = "File:Library-logo-blue-outline.png",
--		link = "{{fullurl:toolforge:book2scroll|lang=en&file={{PAGENAMEE}}}}",
--		caption = "Open in Book2Scroll"
--	},
	bookreader = {
		name = "bookreader",
		image = "File:BookReader-favicon.svg",
		link = "{{fullurl:toolforge:bookreader/ko/{{PAGENAMEE}}}}",
		caption = "BookReader에서 파일 실행"
	},
}

local function get_heading(id)
	
	if headings[id] then
		return headings[id]['txt']
	end
	error( "다음 ID에 대한 머리말을 찾을 수 없습니다: " .. id )
end

-- mapping from status code to category and status text
local index_status_data = {
	T = {
		cat = '검증된 색인',
		txt = '완료—해당 작품의 모든 페이지를 올바르게 검증하였습니다',
	},
	V = {
		cat = '교정된 색인',
		txt = '교정됨—해당 작품의 모든 페이지를 올바르게 교정하였으나, 검증 작업은 거치지 않았습니다',
	},
	C = {
		cat = '교정 안 된 색인',
		txt = '교정되지 않았습니다',
	},
	MS = {
		cat = '색인 - Match & Split 준비',
		txt = 'Match & Split을 할 준비가 되었습니다',
	},
	OCR = {
		cat = '색인 - 텍스트 레이어 필요',
		txt = 'OCR 텍스트 레이어가 필요합니다',
	},
	L = {
		cat = '색인 - 파일 수정 필요',
		txt = '교정 작업을 시작하기에 앞서 원본 파일을 수정해야 합니다',
		error = true,
	},
	X = {
		cat = '색인 - 파일 검토 필요',
		txt = '(파일이 정확한지 확인하기 위해) 교정 작업을 시작하기에 앞서 페이지 목록이 필요합니다',
		error = true
	},
	_default = {
		cat = '색인 - 진행 상황 알 수 없음',
		txt = '진행 상황을 알 수 없습니다(틀 오류)',
		error = true,
	}
}

-- construct a basic "field" row
local function construct_field(id, content)
	
	if id == nil or content == nil then
		return ''
	end
	
	local title = get_heading( id )

	local s = ''
	s = s .. mw.ustring.format('<tr id="ws-index-%s-row" class="ws-index-row">\n', id)
	s = s .. mw.ustring.format('<th id="ws-index-%s-label" class="ws-index-label" scope="row">%s</th>\n', id, title)
	s = s .. mw.ustring.format('<td id="ws-index-%s-value" class="ws-index-value">%s</td>\n', id, content)
	s = s .. '</tr>\n'

	return s
end

local function construct_link(url, text)
	return '[' .. url .. ' ' .. text .. ']'
end

--local function int_link(target, text)
--	return '[' .. '[' .. target .. '|' .. text .. ']]'	
--end

-- handy URL generators (remember to use mw.uri.encode on the bits you need to)
local url_gens = {
	oclc = function(id)
		return 'https://www.worldcat.org/oclc/' .. id	
	end,
	ark = function(id)
		return 'https://n2t.net/' .. mw.uri.encode(id)
	end,
	doi = function(id)
		return 'https://doi.org/' .. id
	end
}

-- construct a span which might be classed "error"
local function maybe_error_span(text, error) 
	local span = mw.html.create('span')
		:wikitext(text)
	if error then
		span:addClass('error')
	end
	return span
end


-- Construct the Title field (includes Vol. after Title if present)
local function construct_title_field(id, title, volume)
	local content = title or ""
	if volume ~= nil and volume ~= "" then
		content = content .. ", " .. volume
	end
	
	return construct_field(id, content)
end

-- construct the source field:
-- - if a file exists, link it
-- - else just the text
local function construct_source_field(source)
	
	local value
	local file = mw.title.new( mw.title.getCurrentTitle().text, 'File' )

	if file.file.exists then
--		value = int_link( ':' .. file.fullText, source )
--	else
		value = source
	end

	local out = construct_field( 'source', value )
	return out
end

local function construct_location_field( loc )
	return construct_field('place', loc)
end

-- construct the status (proofread/validated/...) field
local function construct_status_field(status)

	local out = ''
	local sd = index_status_data[status]
	
	if not sd then
		sd = index_status_data['_default']
	end
	
	out = out .. '[[Category:' .. sd['cat'] .. ']]'

	local link_text = tostring(maybe_error_span(sd['txt'], sd['error']))
	local catlink = '[[:Category:' .. sd['cat'] .. '|' .. link_text .. ']]'
	out = out .. construct_field("progress", catlink)

	return out
end

local transclusion_data = {
	yes = {
		cat = '모두 포함됨',
		text = '모두 포함됨',
		help = '이 작품의 내용은 앞표지, 뒷표지 및 그림 등이 모두 끼워 넣어졌습니다.'
	},
	notimg = {
		cat = '그림이 모두 포함되지 않음',
		text = '그림이 모두 포함되지 않음',
		help = '이 작품은 모두 끼워 넣어졌으나, 일부 그림은 제외되었거나 개선이 필요합니다',
	},
	notadv = {
		cat = '광고가 포함되지 않음',
		text = '광고가 포함되지 않음',
		help = '이 작품의 주요 내용은 모두 정상적으로 끼워 넣어졌으나, 일부 광고는 제외 되었습니다'
	},
	held = {
		cat = '끼워넣기 대기 중',
		text = '끼워넣기 대기 중',
		help = '이 작품을 끼워 넣는데 문제가 발생하였습니다(자세한 사항은 토론 문서에 기재)'
	},
	check = {
		cat = '끼워넣기 확인 필요함',
		text = '끼워넣기 확인 필요함',
		help = '이 작품의 끼워넣기가 불완전하거나 확인이 필요합니다'
	},
	no = {
		cat = '포함되지 않은 색인',
		text = '포함되지 않거나 검토를 거치지 않은 색인',
		help = '이 작품은 아직 끼워 넣지 않았거나, 이를 위한 검토를 거치지 않았습니다'
	}
}

local function construct_cat(cat)
	return "[[Category:" .. cat .. "]]"	
end

--[=[
-- construct the transclusion status
local function construct_transclusion_status(status, date)
	
	-- handle templates with no explicit status
	if status == nil then
		status = "no"
	end
	
	local td = transclusion_data[status]
	
	if td == nil then
		error("알 수 없는 색인 상태: " .. status)
	end

	local catlink = '[[:Category:' .. td['cat'] .. '|' .. td['text'] .. ']]'
	local out = construct_field("transclusion", catlink)
	out = out .. construct_cat( td['cat'])
	return out
end

local function construct_validated_date(date)
	local cat = 'Indexes validated in ' .. date
	local indicator_text = 'Validated in ' .. date
	
	local out = '[[Category:' .. cat .. ']]'
	
	local catlink = '[[:Category:' .. cat .. '|' .. date .. ']]'
	out = out .. construct_field("validation_date", catlink)
	
	out = out .. '<indicator name="validated-index-date">[[File:Yes Check Circle.svg|15px|link=Category:' .. cat .. '|' .. indicator_text .. '|alt=Validated index page.]]</indicator>'
	return out
end
]=]

--[=[
local function getLanguageCat(l)
	-- get the name or nil
	local lang = ISO_639.language_name(l)
	
	if lang then
		return lang .. "작품의 색인 문서"
	end
end
]=]

function p.fields(frame)
	
	local args = getArgs(frame)
	
	-- set any defaults
	for k, v in pairs( DEFAULTS ) do
		if args[ k ] == nil then
			args[ k ] = DEFAULTS[ k ]
		end
	end

	local s = ""

	s = s .. construct_title_field('title', args['제목'], args['권'])
	s = s .. construct_field('author', args['저자'])
	s = s .. construct_field('translator', args['번역자'])
	s = s .. construct_field('editor', args['편집자'])
	s = s .. construct_field('illustrator', args['삽화가'])
	s = s .. construct_field('year', args['연도'])
	s = s .. construct_field('publisher', args['출판사'])
	s = s .. construct_location_field(args['위치'])
	s = s .. construct_source_field(args['출처'])
	
	s = s .. construct_status_field(args['진행 상황'])
	
	-- always do this, even if the arg is not set
--	s = s .. construct_transclusion_status(args["Transclusion"], args['Transclusion_date'])
	
--	if args["Validation_date"] then
--		s = s .. construct_validated_date(args["Validation_date"])	
--	end

	if args["OCLC"] then
		local link = construct_link(url_gens['oclc'](args["OCLC"]), args['OCLC'])
		s = s .. construct_field("oclc", link)
	end
	
	if args["DOI"] then
		local link = construct_link(url_gens['doi'](args["DOI"]), args['DOI'])
		s = s .. construct_field("doi", link)
	end

	s = s .. construct_field('volumes', args['권별 색인'])

--[=[
	-- language categorisations
	if args['언어'] then
		
		local langs = mw.text.split( args['언어'], ',%s?', false)
		for _, lang in pairs(langs) do
			local cat = getLanguageCat(lang)
			if cat then
				s = s .. construct_cat(cat)
			else
				s = s .. construct_cat('알 수 없는 언어로 된 작품의 색인 문서')
			end
		end
		
		if #langs > 1 then
			s = s .. construct_cat('여러 언어로 된 작품의 색인 문서')
		end
	end
]=]
	return s
	
end

function p.talkremarks(frame)
	return _talkremarks(frame)
end

local function _talkremarks(frame)
	local talkTitle = mw.title.getCurrentTitle().talkPageTitle
	local talkText = talkTitle.prefixedText
	if talkTitle.exists then
		local notes = frame:callParserFunction("#lsth", talkText, "참고 사항")
		return frame:expandTemplate{
			title = "색인 토론 안내",
			args = {
				notes = "\n" ..  notes
			}
		}
	end

	return ''
end


function p.indicators(frame)
	return _indicators(frame)
end

local function _indicators(frame)
	local s = ''
	for k, v in pairs(indicators) do
		local link = frame:preprocess(v.link)
		local img = mw.ustring.format("[[%s|20px|link=%s|%s]]", v.image, link, v.caption)
		s = s .. frame:extensionTag{
			name = "indicator",
			content = img,
			args = {
				name = v.name
			}
		}
	end
	return s
end


function p.cover(frame)
	local args = getArgs(frame)

	-- Workaround for pagelist preview that tries to parse this template
	-- without any context and with missing parameters via the API.
	if args['그림'] == nil then
		return ""
	end

	-- If Image param is not a (page) number then this is an image-based
	-- Index, so use the provided image as the cover image.
	if tonumber(args['그림']) == nil then
		local s = ""
		if mw.ustring.find(args['그림'], '^%[%[') ~= nil then
			-- It's a full image specification
			s = s .. args['그림']
		else
			-- Assume it's a filename with or without File: prefix
			local file = mw.ustring.gsub(args['그림'], "^[Ff]ile:", "")
			s = s .. "[[" .. "File:" .. file .. "|250px|class=ws-cover]]"
		end
		-- Add a tracking category
		s = s .. "[[" .. "분류:그림을 기반으로 한 색인" .. "]]"
		return s
	end

	-- Otherwise it's a DjVu/PDF-backed index, in which case we fetch the
	-- cover image from a page in the (multipage) file.
	local indexTitle = mw.title.getCurrentTitle()
	local fileTitle = mw.title.makeTitle('File', indexTitle.text)
	if not fileTitle.file.exists then
		-- Our associated file doesn't exist so use a placeholder
		local s = "[[File:Placeholder book ko.svg|250px|link="
		s = s .. fileTitle.prefixedText .. "|class=ws-cover]]"
		s = s .. "[[" .. "분류:파일이 없는 색인" .. "]]"
		return s
	end

	-- File exists and we have page number for the cover
	local s = "[[" .. fileTitle.prefixedText .. "|250px"
	s = s .. "|page=" .. tonumber(args['그림']) .. "|class=ws-cover]]"
	return s
end

function p.remarks(frame)
	local args = getArgs(frame)

	if args['목차'] ~= nil and args['목차'] ~= "" then
		return '<td id="ws-index-remarks">' .. args['목차'] .. '</td>'
	else
		return '<td id="ws-index-remarks-empty"></td>'
	end
end

function p.sortkey(frame)
	local args = getArgs(frame)

	local sortkey = ""

	if args['정렬 키'] ~= nil and args['정렬 키'] ~= "" then
		sortkey = args['정렬 키']
	else
		sortkey = mw.title.getCurrentTitle().text
	end
	return frame:preprocess{text = "{{" .. "DEFAULTSORT:" .. sortkey .. "}}"} 
end


-- Wrapper to output .fields with containing html table element.
function p.metadata(frame)
	local metadatatable = mw.html.create("table")
	metadatatable:attr("id", "ws-index-metadata")
	local rows = p.fields(frame)
	metadatatable:node(rows)
	return tostring(metadatatable)
end


--
-- NEW EXPERIMENTAL CODE BELOW THIS LINE --
--

local cfg = mw.loadData("Module:Proofreadpage index template/config")

local CATS = {
	categories = {}
}
function CATS:addCat(cat)
	table.insert(self.categories, cat)
end
function CATS:getCats()
	local cats = ""
	for _, cat in ipairs(self.categories) do
		cats = cats .. "[[" .. "Category:" .. cat .. "]]"
	end
	return cats
end
function CATS:makeCatLink(cat, label)
	if label ~= nil and label ~= "" then
		return "[[:" .. "Category:" .. cat .. "|" .. label .. "]]"
	end
	return "[[:" .. "Category:" .. cat .. "]]"
end


-- construct a basic "field" row
local function __makeRow(id, content)
	if id == nil or id == "" or content == nil then
		return ''
	end

	local row = mw.html.create("tr")
	row
		:attr("id", "ws-index-" .. id .. "-row")
		:addClass("ws-index-row")
	:tag("th")
		:attr("scope", "row")
		:attr("id", "ws-index-" .. id .. "-label")
		:addClass("ws-index-label")
		:wikitext(cfg.headings[id].txt)
		:done()
	:tag("td")
		:attr("id", "ws-index-" .. id .. "-value")
		:addClass("ws-index-value")
		:wikitext(content)
	:allDone()

	return tostring(row)
end

-- Create indicator markup based on config
--
-- Loads the config module and creates indicator extension tags after pattern
--   <indicator name="foo">[[File:Foo.png|20px|link=bar]]</indcator>
-- The link is preprocessed as wikitext so it can contain parser functions etc.
local function __getIndicators(frame)
	local indicators = mw.loadData('Module:Proofreadpage index template/indicators')
	local s = ''
	for _, v in pairs(indicators) do
		local link = frame:preprocess(v.link)
		local img = mw.ustring.format("[[%s|20px|link=%s|%s]]", v.image, link, v.caption)
		s = s .. frame:extensionTag{
			name = "indicator",
			content = img,
			args = {
				name = v.name
			}
		}
	end
	return s
end

-- Get talk page notice if present
--
-- If the talk page associated with the current page exists, we use Labelled
-- Section Transclusion to transclude the section titled "Quick notes" and if
-- the result contains any text, return a message box with its contents.
local function __getTalkNotice(frame)
	local talkTitle = mw.title.getCurrentTitle().talkPageTitle
	local talkText = talkTitle.prefixedText
	if talkTitle.exists then
		local notes = frame:callParserFunction("#lsth", talkText, "참고 사항 요약")

		local s = "해당 작품에 대한 스타일 가이드라인이 이미 존재할 수 있습니다."
		s = s .. "자세한 사항은 [[" .. talkText .. "|토론 문서]]를 참고하세요."

		local box = messageBox.main("ombox", {
			type = "content",
		    text = s .. notes
		})
		return box
	end

	return ''
end

-- Get the image to use as the cover image for this index
--
-- If the Image parameter contains an integer it refers to a page in a DjVu/PDF
-- and can be used directly. Otherwise it may be a full image specification
-- that we can use directly, or just an image filename that we can construct
-- an image specification for.
local function __getCoverImage(args)
	local s = ""

	-- If Image param is not a (page) number then this is an image-based
	-- Index, so use the provided image as the cover image.
	if tonumber(args['그림']) == nil then
		if mw.ustring.find(args['그림'], '^%[%[') ~= nil then
			s = s .. args['그림'] -- It's a full image specification
		else
			-- Assume it's a filename with or without File: prefix
			local file = mw.ustring.gsub(args['그림'], "^[Ff]ile:|파일:|그림:", "")
			s = s .. "[[" .. "File:" .. file .. "|250px|class=ws-cover ws-index-cover]]"
		end
		-- Add a tracking category
		CATS:addCat("그림을 기반으로 하는 색인")
		return s
	end

	-- Otherwise it's a DjVu/PDF-backed index, in which case we fetch the
	-- cover image from a page in the (multipage) file.
	local indexTitle = mw.title.getCurrentTitle()
	local fileTitle = mw.title.makeTitle('File', indexTitle.text)
	if not fileTitle.file.exists then
		-- Our associated file doesn't exist so use a placeholder
		s = s .. "[[File:Placeholder book ko.svg|250px|link="
		s = s .. fileTitle.prefixedText .. "|class=ws-cover ws-index-cover]]"
		CATS:addCat("파일이 없는 색인")
		return s
	end

	-- File exists and we have page number for the cover
	s = s .. "[[" .. fileTitle.prefixedText .. "|250px"
	s = s .. "|page=" .. tonumber(args['그림']) .. "|class=ws-cover ws-index-cover]]"
	return s
end

-- Get the pagelist provided by PRP
--
-- PRP furnished a finished rendered pagelist, so we just need to wrap it in a
-- suitable container, add a legend, etc.
local function __getPagelist(args)
	-- Main container
	local plcontainer = mw.html.create("div")
	plcontainer
		:addClass("ws-index-pagelist-container")
		:addClass("mw-collapsible") -- make it collapsible
	:tag("div") -- The heading/legend
		:addClass("ws-index-pagelist-heading")
		:wikitext("Pages")
		:wikitext(" ") -- Force a space between heading and legend.
		:tag("span")
			:addClass("ws-index-pagelist-heading-legend")
			:wikitext("([[위키문헌:페이지 상태|페이지 상태]] 범례)")
			:done()
		:done()
	:tag("div") -- The pagelist itself
		:addClass("ws-index-pagelist")
		:addClass("index-pagelist") -- legacy support
		:addClass("mw-collapsible-content") -- make it collapsible
		:wikitext('\n' .. mw.text.trim(args["쪽별 색인"]) .. '\n')

	return tostring(plcontainer)
end


-- Get the metadata fields.
local function __getMetadata(frame, args)
	-- set any defaults
	for key, _ in pairs(cfg.defaults) do
		if args[key] == nil then
			args[key] = cfg.defaults[key]
		end
	end

	local s = ""

	-- Construct the Title field (includes Vol. after Title if present)
	local title = args['제목'] or ""
	if args['권'] ~= nil and args['권'] ~= "" then
		title =  title .. ", " .. args['권']
	end
	s = s .. __makeRow('title', title)

	s = s .. __makeRow('author',      args['저자'])
	s = s .. __makeRow('translator',  args['번역자'])
	s = s .. __makeRow('editor',      args['편집자'])
	s = s .. __makeRow('illustrator', args['삽화가'])
	
	-- 연도 뒤에 "년"을 추가로 붙이기
	local year = args['연도'] or ""
	if args['연도'] ~= nil and args['연도'] ~= "" then
		year =  year .. "년"
	end
	s = s .. __makeRow('year',        args['연도'])
	
	s = s .. __makeRow('publisher',   args['출판사'])
	s = s .. __makeRow('place',       args['위치'])

	local location = args["출처"]
	local file = mw.title.new(mw.title.getCurrentTitle().text, 'File')
	if file.exists then
		location = "[[:" .. file.fullText .. "|" .. args["출처"] .. "]]"
	end
	s = s .. __makeRow('source', location)


	local status = cfg.status[args['진행 상황']] or cfg.status['_default']
	CATS:addCat(status.cat) -- Add this index to that cat
	local linktext = mw.html.create('span'):wikitext(status.txt)
	if status.error then
		linktext:addClass('error')
	end
	local statuslink = CATS:makeCatLink(status.cat, tostring(linktext))
	s = s .. __makeRow('progress', statuslink)


--	local transclusion = cfg.transclusion[args["Transclusion"] or "no"] -- always do this, even if the arg is not set
--	CATS:addCat(transclusion.cat)
--	local transclusionlink = CATS:makeCatLink(transclusion.cat, transclusion.txt)
--	s = s .. __makeRow("transclusion", transclusionlink)


--[=[
	if args["Validation_date"] then
		local valcat = .. args["Validation_date"] .. '에 검증된 색인'
		local valtxt = .. args["Validation_date"] .. '에 검증됨'
		CATS:addCat(valcat)
		local valcatlink = CATS:makeCatLink(valcat, args["Validation_date"])
		s = s .. __makeRow("validation_date", valcatlink)
		s = s .. frame:extensionTag{ -- FIXME: need the frame here!
			name = "indicator",
			content = '[[File:Yes Check Circle.svg|15px|link=Category:' .. valcat .. '|' .. valtxt .. '|alt=검증된 색인 문서]]',
			args = {
				name = "validated-index-date"
			}
		}
	end
]=]

	if args["OCLC"] then
		local link = construct_link(url_gens['oclc'](args["OCLC"]), args['OCLC'])
		s = s .. __makeRow("oclc", link)
	end
	
	if args["DOI"] then
		local link = construct_link(url_gens['doi'](args["DOI"]), args['DOI'])
		s = s .. __makeRow("doi", link)
	end

	s = s .. __makeRow('volumes', args['권별 색인'])

--[=[
	-- language categorisations
	if args['언어'] then
		local langs = mw.text.split(args['언어'], ',%s?', false)
		for _, lang in pairs(langs) do
			local langcat = "로 된 작품의 색인 문서"
			langcat = ISO_639.language_name(lang) or "알 수 없는 언어" .. langcat
			CATS:addCat(langcat)
		end
		
		if #langs > 1 then
			CATS:addCat('여러 언어로 된 작품의 색인 문서')
		end
	end
]=]

	local metadatatable = mw.html.create("table")
		:addClass("ws-index-metadata")
		:wikitext(s)
	return tostring(metadatatable)
end


local function __main(frame)
	local args = getArgs(frame)

	local s = "" -- Where we collect all the bits and bobs to return

	-- The overall html structure in which each component is inserted
	local indexcontainer = mw.html.create("div")
		:addClass("ws-index-container")
--	if tonumber(args["tmplver"]) == 42 then
--		indexcontainer:addClass("ws-tng") -- Tag for "TNG" mode i asked for.
--	end

	-- Get the indicators (NB! Needs access to the frame!)
	s = s .. __getIndicators(frame)

	-- Get talk page notice if present (NB! Needs access to the frame!)
	s = s .. __getTalkNotice(frame)

	-- Get the image to use as the cover image for this index
	local cover = __getCoverImage(args)
	indexcontainer:tag("div")
		:addClass("ws-index-cover-container")
		:wikitext(cover)

	-- Get metadata table (NB! Needs access to the frame!)
	local metadata = __getMetadata(frame, args)
	indexcontainer:tag("div")
		:addClass("ws-index-metadata-container")
		:wikitext(metadata)

	-- Get the pagelist for the index
	local pagelist = __getPagelist(args)
	indexcontainer:wikitext(pagelist)

	-- Add the remarks field (toc)
	local remarks = indexcontainer:tag("div")
		:addClass("ws-index-remarks-container")
	if args['비고'] == nil or args['비고'] == "" then
		remarks:addClass("ws-index-remarks-empty")
	end
	remarks:wikitext(args['비고'])

	-- Return the HTML structure and the accumulated categories.
	return tostring(indexcontainer) .. CATS:getCats()
end


function p.main(frame)
	local args = getArgs(frame)

	local s = "" -- Where we collect all the bits and bobs to return

	if args["tmplver"] ~= nil and args["tmplver"] ~= "" then
		return __main(frame)
	end

	-- First, the talk remarks notes (nb! needs frame object!)
	s = s .. _talkremarks(frame)

	-- Then the indicators (nb! needs frame object!)
	s = s .. _indicators(frame)

	-- Construct the table
	local outertable = mw.html.create("table")
	outertable:attr("id", "ws-index-container")
	local outertr = outertable:tag("tr")

	local maincell = outertr:tag("td")
	maincell:attr("id", "ws-index-main-cell")

	local maintable = maincell:tag("table")
	maintable:attr("id", "ws-index-main-table")
	local firstrow = maintable:tag("tr")
	local maincell = firstrow:tag("td")
	local coverdiv = maincell:tag("div")
	coverdiv:attr("id", "ws-index-cover-container")
	coverdiv:wikitext(p.cover(frame))
	maincell:wikitext(p.metadata(frame))
	local secondrow = maintable:tag("tr")
	local plcell = secondrow:tag("td")
	local pldiv = plcell:tag("div")
	pldiv:attr("id", "ws-index-pagelist-container")
	pldiv:addClass("mw-collapsible")
	pldiv:wikitext('<em>페이지</em> <span id="ws-index-pagelist-legend">([[위키문헌:페이지 상태{{!}}페이지 상태]] 범례)</span>')
	local plinner = pldiv:tag("div")
	plinner:attr("id", "ws-index-pagelist")
	plinner:addClass("index-pagelist mw-collapsible-content")
	plinner:wikitext('\n' .. mw.text.trim(args["쪽별 색인"] or '') .. '\n')

	outertr:wikitext(p.remarks(frame))

	s = s .. tostring(outertable)

	s = s .. p.sortkey(frame)

	return s
end

return p