Module:Asbox

From Viki
Jump to navigation Jump to search

Documentation for this module may be created at Module:Asbox/doc

  1 --[[
  2 This module was created by User:CodeHydro (Alexander Zhikun He).
  3 User:Jackmcbarn and User:Mr._Stradivarius provided a great deal of assistance in writting p.main()
  4 
  5 p.main() draw heavily from the following version of Template:Asbox of the English Wikipedia, authored primarily by User:Rich_Farmbrough
  6 https://en.wikipedia.org/w/index.php?title=Template:Asbox&oldid=619510287
  7 
  8 p.templatepage() is derived from the following revision of Template:Asbox/templatepage, authored primarily by User:MSGJ
  9 https://en.wikipedia.org/w/index.php?title=Template:Asbox/templatepage&oldid=632914791
 10 
 11 Both templates had significant contributions from numerous others listed in the revision history tab of their respective pages.
 12 --]]
 13 local WRAPPER_TEMPLATE, args = 'Template:Asbox'
 14 local p, Buffer, stubCats = {
 15 	--Prevents dupli-cats... get it? Maybe not?
 16 	cats = setmetatable({}, {__newindex = function(t, i, v)
 17 		if not rawget(t, i) then
 18 			rawset(t, i, v)
 19 			table.insert(t, i)
 20 		end
 21 	end}),
 22 	--initializes variables required by both p.main and p.templatepage
 23 	init = function(self, frame, page)
 24 		args, page = args or require('Module:Arguments').getArgs(frame, {
 25 			wrappers = WRAPPER_TEMPLATE
 26 		}), page or mw.title.getCurrentTitle()
 27 		--Ensures demo parameter will never affect category() output for articles
 28 		self.demo = self.demo or page.namespace ~= 0 and args.demo
 29 		return args, page
 30 	end
 31 }, require('Module:Buffer')
 32 
 33 --[[
 34 Formats category links. Stores them until called with cat.done=true
 35 Takes multiple or single categories in the form of 'cat'
 36 or a table of strings and/or tables containing parts. (See below)
 37 ]]
 38 local attention, catTag, catKey = Buffer'Stub message templates needing attention', '[[Category:%s]]', '%s|%s%s'
 39 local function category(cat)
 40 	for _, v in ipairs((tostring(cat) == cat or cat.t) and {cat} or cat) do
 41 		--[[
 42 		If v is a table:
 43 			[1] = full category name; defaults to local attention if blank
 44 			k = Category sort key. Prefix before v.t
 45 			t = page.text or args.tempsort#; appended after k (or in its place if omitted). Required if v is not a string
 46 		Basically the same as v = (v[1] or attention) .. ' | ' .. (v.k or '') .. v.t
 47 		]]
 48 		if v and v ~= true then--reject v = nil, false, or true
 49 			p.cats[catTag:format(tostring(v) == v and
 50 				v
 51 				or (v[1] and Buffer(v[1]) or attention):_in(v.k):_(v.t):_str(2, nil, nil, '|')
 52 			)] = true
 53 		end
 54 	end
 55 	return cat.done and table.concat(p.cats, p.demo and ' | ' or nil) or ''
 56 end
 57 
 58 --[[
 59 Makes an ombox warning;
 60 Takes table {ifNot = Boolean, text, {cat. sort key, cat. sort name}}
 61 Will return an empty string instead when ifNot evaluates to true 
 62 ]]
 63 local function ombox(v)
 64 	if v.ifNot then return end
 65 	p.ombox = p.ombox or require('Module:Message box').ombox
 66 	category{v[2]}
 67 	return p.ombox{
 68 		type = 'content',
 69 		text = v[1]
 70 	}
 71 end
 72 
 73 --[[
 74 Unlike original template, module now takes unlimited cats! This function also performs
 75 most stub category error checks except for the ombox for when main |category= is omitted (See p.template())
 76 ]]
 77 local function catStub(page, pageDoc)
 78 	stubCats = {missing = {}, v = {}}
 79 	local code
 80 	for k, _ in pairs(args) do
 81 		--Find category parameters and store the number (main cat = '')
 82 		table.insert(stubCats, string.match(k, '^category(%d*)$'))
 83 	end
 84 	table.sort(stubCats)
 85 	for k, v in ipairs(stubCats) do
 86 		--Get category names and, if called by p.templatepage, the optional sort key
 87 		local tsort, cat = args['tempsort' .. v], mw.ustring.gsub(args['category' .. v], '[^%w%p%s]', '')--remove all hidden unicode chars 
 88 		--Do not place template in main category if |tempsort = 'no'. However, DO place articles of that template in the main category.
 89 		table.insert(stubCats.v,
 90 			 page and (--p.templatepage passes page; p.main does not, i.e. articles are categorized without sort keys.
 91 				v=='' and tsort == 'no'--if true, inserts 'true' in table, which category() will reject
 92 				or tsort and {cat, k = ' ', t = tsort}
 93 				or {cat, k = ' *', t = page.text}--note space in front of sort key
 94 			)
 95 			or cat
 96 		)
 97 		--Check category existance only if on the template page (i.e. stub documentation)
 98 		if page then
 99 			if not mw.title.new('Category:' .. cat).exists then
100 				code = code or mw.html.create'code':wikitext'|category'
101 				table.insert(stubCats.missing, tostring(mw.clone(code):wikitext(v)))
102 			end
103 			--[[
104 			Checks non-demo stub template for documentation and flags if doc is present.
105 			All stub cats names are checked and flagged if it does not match 'Category: [] stub'.
106 			The main stub cat is exempt from the name check if the stub template has its own doc
107 			(presumably, this doc would have an explanation as to why the main stub cat is non-conforming).
108 			]]
109 			table.insert(stubCats.v, v == '' and not p.demo and pageDoc.exists and
110 				'Stub message templates with documentation subpages'
111 				or not cat:match' stubs$' and {k = 'S', t = page.text}
112 			)
113 		end
114 	end
115 	--Add category names after loop is completed
116 	category(stubCats.v)
117 	return #stubCats.missing > 0 and ombox{
118 		--Changed, original msg:
119 		--One or more of the stub categories defined in this template do not seem to exist!
120 		--Please double-check the parameters {{para|category}}, {{para|category1}} and {{para|category2}}.
121 		'The following parameter'
122 			.. (#stubCats.missing == 1 and ' defines a stub category that does' or 's define stub categories that do')
123 			.. ' not exist: ' .. mw.text.listToText(stubCats.missing),
124 		{k = 'N', t = page.text}
125 	}
126 end
127 
128 --Shows population of categories found by catStub(). Outputs demo values if none
129 local function population()
130 	local wikitext, base = {}, '* [[:Category:%s]] (population: %s)\n'
131 	if not args.category and stubCats[1] ~= false then
132 		table.insert(stubCats, 1, false)
133 	end
134 	for _, v in ipairs(stubCats) do
135 		table.insert(wikitext, base:format(
136 			v and args['category' .. v] or '{{{category}}}',
137 			v and mw.site.stats.pagesInCategory(args['category' .. v], 'all') or 0
138 		))
139 	end
140 	return table.concat(wikitext)
141 end
142 
143 --Includes standard stub documention and flags stub templates with bad parameter values.
144 function p.templatepage(frame, page)
145 	args, page = p:init(frame, page)
146 	local tStubDoc = mw.title.new'Template:Stub documentation'
147 	local pageDoc = page:subPageTitle('doc')
148 	--Reorganization note: Original Asbox alternates between outputting categories and checking on params |category#=.
149 	--Rather than checking multiple times and switching tasks, all stub category param operations have been rolled into catStub()
150 	return Buffer(
151 		ombox{--Show ombox warnings for missing args.
152 			ifNot = args.category,
153 			'The <code>|category</code> parameter is not set. Please add an appropriate stub category.',
154 			{k = 'C', t = page.text}
155 		})
156 		:_(ombox{
157 			ifNot = args.subject or args.article or args.qualifier,
158 			'This stub template contains no description! At least one of the parameters <code>|subject</code>, <code>|article</code> or <code>|qualifier</code> must be defined.',
159 			{k = 'D', t = page.text}
160 		})
161 		:_(catStub(page, pageDoc))--catStub() may also return an ombox if there are non-existing categories
162 		:_(category{
163 			done = p.demo ~= 'doc',--Outputs categories if not doc demo
164 			'Stub message templates',
165 			'Exclude in print',
166 			args.icon and
167 				'Stub message templates using icon parameter'
168 				or args.image and (
169 					mw.title.new('Media:' .. mw.text.split(args.image, '|')[1]).exists--do nothing if exists. category() will reject true
170 					or {k = 'B', t = page.text}
171 				)
172 				or 'Stub message templates without images',
173 			args.imagealt and {k = 'I', t = page.text},
174 		})
175 		:_((not p.demo or p.demo == 'doc') and--Add standard stub template documentation
176 			require('Module:Documentation').main{
177 				content = Buffer(page.text ~= 'Stub' and--This comparison performed in {{Asbox/stubtree}} before it invokes Module:Asbox stubtree
178 						require('Module:Asbox stubtree').subtree{args = {pagename = page.text}}
179 					)
180 					:_in'\n== About this template ==\nThis template is used to identify a':_(args.subject):_'stub':_(args.qualifier):_out' '--space
181 					:_'. It uses {{[[Template:Asbox|asbox]]}}, which is a meta-template designed to ease the process of creating and maintaining stub templates.\n=== Usage ===\nTyping '
182 					:_(mw.html.create'code'
183 						:wikitext('{{', page.text == 'Stub' and 'stub' or page.text, '}}')
184 					)
185 					:_' produces the message shown at the beginning, and adds the article to the following categor'
186 					:_(#stubCats > 1 and 'ies' or 'y')
187 					:_':\n'
188 					:_(population())
189 					:_(pageDoc.exists and--transclusion of /doc if it exists
190 						frame:expandTemplate{title = pageDoc.text}
191 					)
192 					:_'\n== General information ==\n'
193 					:_(frame:expandTemplate{title = tStubDoc.text})
194 					:_'\n\n'(),
195 				['link box'] = Buffer'This documentation is automatically generated by [[Module:Asbox]].'
196 					:_in'The general information is transcluded from [[Template:Stub documentation]]. '
197 						:_(mw.html.create'span'
198 							:cssText'font-size:smaller;font-style:normal;line-height:130%'
199 							:node(('([%s edit] | [%s history])'):format(
200 								tStubDoc:fullUrl('action=edit', 'relative'),
201 								tStubDoc:fullUrl('action=history', 'relative')
202 							))
203 						)
204 						:_out()
205 					:_(page.protectionLevels.edit and page.protectionLevels.edit[1] == 'sysop' and
206 						"This template is [[WP:PROTECT|fully protected]] and any [[WP:CAT|categories]] should be added to the template's ["
207 						.. pageDoc:fullUrl('action=edit&preload=Template:Category_interwiki/preload', 'relative')
208 						.. '| /doc] subpage, which is not protected.'
209 					)' <br/>'
210 			}
211 		)()
212 end
213 
214 function p.main(frame, page)
215 	args, page = p:init(frame, page)
216 	local output = mw.html.create'table'
217 		:addClass'metadata plainlinks stub'
218 		:css{background = 'transparent'}
219 		:attr{role = 'presentation'}
220 		:tag'tr'
221 			:node((args.icon or args.image) and
222 				mw.html.create'td'
223 					:wikitext(args.icon or ('[[File:%s|%spx|alt=%s]]'):format(
224 						args.image or '',
225 						args.pix or '40x30',
226 						args.imagealt or 'Stub icon'
227 					))
228 			)
229 			:tag'td'
230 				:tag'i'
231 					:wikitext(
232 						Buffer'This':_(args.subject):_(args.article or 'article'):_(args.qualifier)' ',--space
233 						' is a [[wikipedia:Wikipedia:stub|stub]]. You can help Viki by [',
234 						page:fullUrl('action=edit', 'relative'),
235 						' expanding it].'
236 					)
237 				:done()
238 				:node(args.name and
239 					require'Module:Navbar'._navbar{
240 						args.name,
241 						mini = 'yes',
242 						style = 'position: absolute; right: 15px; display: none;'
243 					}
244 				)
245 				:node(args.note and
246 					mw.html.create()
247 						:tag'br':done()
248 						:tag'span'
249 							:css{['font-style'] = 'normal', ['font-size'] = 'smaller'}
250 							:wikitext(args.note)
251 						:done()
252 				)
253 		:allDone()
254 	--[[
255 	Stub categories for templates include a sort key; this ensures that all stub tags appear at the beginning of their respective categories.
256 	Articles using the template do not need a sort key since they have unique names.
257 	When p.demo equals 'doc', the demo stub categories will appear as those for a stub template.
258 	Otherwise, any non-nil p.demo will emulate article space categories (plus any error cats unless set to 'art')
259 	]]
260 	if page.namespace == 0 then -- Main namespace
261 		category'All stub articles'
262 		catStub()
263 	elseif p.demo then
264 		if p.demo ~= 'doc' then catStub() end
265 		--Unless p.demo is set to 'art', it will also include error categories normally only shown on
266 		--the template but not in the article. The elseif after namespace == 0 means demo cats will never show in article space.
267 		p.demodoc = p.demo ~= 'art' and p.templatepage(frame, page)
268 		output = mw.html.create()
269 			:node(output)
270 			:tag'small':wikitext(
271 				'Demo categories: ',
272 				(category{done = true}:gsub('(%[%[)(Category:)([^|%]]-)(%|)', '%1%2%3|%2%3%4'):gsub('(%[%[)(Category:)', '%1:%2'))
273 			):done()
274 			:wikitext(p.demo == 'doc' and p.demodoc or nil)
275 	else
276 		--Checks for valid name; emulates original template's check using {{FULLPAGENAME:{{{name|}}}}}
277 		local normalizedName = mw.title.new(args.name or '')
278 		if normalizedName and normalizedName.fullText == page.fullText then
279 			output = mw.html.create():node(output):wikitext(p.templatepage(frame, page))
280 		elseif not page.isSubpage and page.namespace == 10 then-- Template namespace and not a subpage
281 			category{{k = args.name and 'E' or 'W', t = page.text}}
282 		end
283 	end
284 	return output:wikitext(not p.demo and category{done = true} or nil)
285 end
286 
287 return p