Debian Codegraph @

extensions/Scribunto/includes/Engines/LuaCommon/lualib/mw.html.lua

raw symbols SCIP
1 --[[
2 A module for building complex HTML from Lua using a
3 fluent interface.
4
5 Originally written on the English Wikipedia by
6 Toohool and Mr. Stradivarius.
7
8 Code released under the GPL v2+ as per:
9 https://en.wikipedia.org/w/index.php?diff=next&oldid=581399786
10 https://en.wikipedia.org/w/index.php?diff=next&oldid=581403025
11
12 @license GNU GPL v2+
13 @author Marius Hoch < [email protected] >
14 ]]
15
16 local HtmlBuilder = {}
17 local options
18
19 local util = require 'libraryUtil'
20 local checkType = util.checkType
21 local checkTypeMulti = util.checkTypeMulti
22
23 local metatable = {}
24 local methodtable = {}
25
26 local selfClosingTags = {
27 area = true,
28 base = true,
29 br = true,
30 col = true,
31 command = true,
32 embed = true,
33 hr = true,
34 img = true,
35 input = true,
36 keygen = true,
37 link = true,
38 meta = true,
39 param = true,
40 source = true,
41 track = true,
42 wbr = true,
43 }
44
45 local htmlencodeMap = {
46 ['>'] = '&gt;',
47 ['<'] = '&lt;',
48 ['&'] = '&amp;',
49 ['"'] = '&quot;',
50 }
51
52 metatable.__index = methodtable
53
54 metatable.__tostring = function( t )
55 local ret = {}
56 t:_build( ret )
57 return table.concat( ret )
58 end
59
60 -- Get an attribute table (name, value) and its index
61 --
62 -- @param name
63 local function getAttr( t, name )
64 for i, attr in ipairs( t.attributes ) do
65 if attr.name == name then
66 return attr, i
67 end
68 end
69 end
70
71 -- Is this a valid attribute name?
72 --
73 -- @param s
74 local function isValidAttributeName( s )
75 -- Good estimate: http://www.w3.org/TR/2000/REC-xml-20001006#NT-Name
76 return s:match( '^[a-zA-Z_:][a-zA-Z0-9_.:-]*$' )
77 end
78
79 -- Is this a valid tag name?
80 --
81 -- @param s
82 local function isValidTag( s )
83 return s:match( '^[a-zA-Z0-9]+$' )
84 end
85
86 -- Escape a value, for use in HTML
87 --
88 -- @param s
89 local function htmlEncode( s )
90 -- The parentheses ensure that there is only one return value
91 local tmp = string.gsub( s, '[<>&"]', htmlencodeMap );
92 -- Don't encode strip markers here (T110143)
93 tmp = string.gsub( tmp, options.encodedUniqPrefixPat, options.uniqPrefixRepl )
94 tmp = string.gsub( tmp, options.encodedUniqSuffixPat, options.uniqSuffixRepl )
95 return tmp
96 end
97
98 local function cssEncode( s )
99 -- mw.ustring is so slow that it's worth searching the whole string
100 -- for non-ASCII characters to avoid it if possible
101 return ( string.find( s, '[^%z\1-\127]' ) and mw.ustring or string )
102 -- XXX: I'm not sure this character set is complete.
103 -- bug #68011: allow delete character (\127)
104 .gsub( s, '[^\32-\57\60-\127]', function ( m )
105 return string.format( '\\%X ', mw.ustring.codepoint( m ) )
106 end )
107 end
108
109 -- Create a builder object. This is a separate function so that we can show the
110 -- correct error levels in both HtmlBuilder.create and metatable.tag.
111 --
112 -- @param tagName
113 -- @param args
114 local function createBuilder( tagName, args )
115 if tagName ~= nil and tagName ~= '' and not isValidTag( tagName ) then
116 error( string.format( "invalid tag name '%s'", tagName ), 3 )
117 end
118
119 args = args or {}
120 local builder = {}
121 setmetatable( builder, metatable )
122 builder.nodes = {}
123 builder.attributes = {}
124 builder.styles = {}
125
126 if tagName ~= '' then
127 builder.tagName = tagName
128 end
129
130 builder.parent = args.parent
131 builder.selfClosing = selfClosingTags[tagName] or args.selfClosing or false
132 return builder
133 end
134
135 -- Append a builder to the current node. This is separate from methodtable.node
136 -- so that we can show the correct error level in both methodtable.node and
137 -- methodtable.wikitext.
138 --
139 -- @param builder
140 local function appendBuilder( t, builder )
141 if t.selfClosing then
142 error( "self-closing tags can't have child nodes", 3 )
143 end
144
145 if builder then
146 table.insert( t.nodes, builder )
147 end
148 return t
149 end
150
151 methodtable._build = function( t, ret )
152 if t.tagName then
153 table.insert( ret, '<' .. t.tagName )
154 for i, attr in ipairs( t.attributes ) do
155 table.insert(
156 ret,
157 -- Note: Attribute names have already been validated
158 ' ' .. attr.name .. '="' .. htmlEncode( attr.val ) .. '"'
159 )
160 end
161 if #t.styles > 0 then
162 table.insert( ret, ' style="' )
163 local css = {}
164 for i, prop in ipairs( t.styles ) do
165 if type( prop ) ~= 'table' then -- added with cssText()
166 table.insert( css, htmlEncode( prop ) )
167 else -- added with css()
168 table.insert(
169 css,
170 htmlEncode( cssEncode( prop.name ) .. ':' .. cssEncode( prop.val ) )
171 )
172 end
173 end
174 table.insert( ret, table.concat( css, ';' ) )
175 table.insert( ret, '"' )
176 end
177 if t.selfClosing then
178 table.insert( ret, ' />' )
179 return
180 end
181 table.insert( ret, '>' )
182 end
183 for i, node in ipairs( t.nodes ) do
184 if node then
185 if type( node ) == 'table' then
186 node:_build( ret )
187 else
188 table.insert( ret, tostring( node ) )
189 end
190 end
191 end
192 if t.tagName then
193 table.insert( ret, '</' .. t.tagName .. '>' )
194 end
195 end
196
197 -- Append a builder to the current node
198 --
199 -- @param builder
200 methodtable.node = function( t, builder )
201 return appendBuilder( t, builder )
202 end
203
204 -- Appends some markup to the node. This will be treated as wikitext.
205 methodtable.wikitext = function( t, ... )
206 for k,v in ipairs{...} do
207 checkTypeMulti( 'wikitext', k, v, { 'string', 'number' } )
208 appendBuilder( t, v )
209 end
210 return t
211 end
212
213 -- Appends a newline character to the node.
214 methodtable.newline = function( t )
215 return t:wikitext( '\n' )
216 end
217
218 -- Appends a new child node to the builder, and returns an HtmlBuilder instance
219 -- representing that new node.
220 --
221 -- @param tagName
222 -- @param args
223 methodtable.tag = function( t, tagName, args )
224 checkType( 'tag', 1, tagName, 'string' )
225 checkType( 'tag', 2, args, 'table', true )
226 args = args or {}
227
228 args.parent = t
229 local builder = createBuilder( tagName, args )
230 t:node( builder )
231 return builder
232 end
233
234 -- Get the value of an html attribute
235 --
236 -- @param name
237 methodtable.getAttr = function( t, name )
238 checkType( 'getAttr', 1, name, 'string' )
239
240 local attr = getAttr( t, name )
241 return attr and attr.val
242 end
243
244 -- Set an HTML attribute on the node.
245 --
246 -- @param name Attribute to set, alternative table of name-value pairs
247 -- @param val Value of the attribute. Nil causes the attribute to be unset
248 methodtable.attr = function( t, name, val )
249 if type( name ) == 'table' then
250 if val ~= nil then
251 error(
252 "bad argument #2 to 'attr' " ..
253 '(if argument #1 is a table, argument #2 must be left empty)',
254 2
255 )
256 end
257
258 local callForTable = function()
259 for attrName, attrValue in pairs( name ) do
260 t:attr( attrName, attrValue )
261 end
262 end
263
264 if not pcall( callForTable ) then
265 error(
266 "bad argument #1 to 'attr' " ..
267 '(table keys must be strings, and values must be strings or numbers)',
268 2
269 )
270 end
271
272 return t
273 end
274
275 checkType( 'attr', 1, name, 'string' )
276 checkTypeMulti( 'attr', 2, val, { 'string', 'number', 'nil' } )
277
278 -- if caller sets the style attribute explicitly, then replace all styles
279 -- previously added with css() and cssText()
280 if name == 'style' then
281 t.styles = { val }
282 return t
283 end
284
285 if not isValidAttributeName( name ) then
286 error( string.format(
287 "bad argument #1 to 'attr' (invalid attribute name '%s')",
288 name
289 ), 2 )
290 end
291
292 local attr, i = getAttr( t, name )
293 if attr then
294 if val ~= nil then
295 attr.val = val
296 else
297 table.remove( t.attributes, i )
298 end
299 elseif val ~= nil then
300 table.insert( t.attributes, { name = name, val = val } )
301 end
302
303 return t
304 end
305
306 -- Adds a class name to the node's class attribute. Spaces will be
307 -- automatically added to delimit each added class name.
308 --
309 -- @param class
310 methodtable.addClass = function( t, class )
311 checkTypeMulti( 'addClass', 1, class, { 'string', 'number', 'nil' } )
312
313 if class ~= nil then
314 local attr = getAttr( t, 'class' )
315 if attr then
316 attr.val = attr.val .. ' ' .. class
317 else
318 t:attr( 'class', class )
319 end
320 end
321 return t
322 end
323
324 -- Set a CSS property to be added to the node's style attribute.
325 --
326 -- @param name CSS attribute to set, alternative table of name-value pairs
327 -- @param val The value to set. Nil causes it to be unset
328 methodtable.css = function( t, name, val )
329 if type( name ) == 'table' then
330 if val ~= nil then
331 error(
332 "bad argument #2 to 'css' " ..
333 '(if argument #1 is a table, argument #2 must be left empty)',
334 2
335 )
336 end
337
338 local callForTable = function()
339 for attrName, attrValue in pairs( name ) do
340 t:css( attrName, attrValue )
341 end
342 end
343
344 if not pcall( callForTable ) then
345 error(
346 "bad argument #1 to 'css' " ..
347 '(table keys and values must be strings or numbers)',
348 2
349 )
350 end
351
352 return t
353 end
354
355 checkTypeMulti( 'css', 1, name, { 'string', 'number' } )
356 checkTypeMulti( 'css', 2, val, { 'string', 'number', 'nil' } )
357
358 for i, prop in ipairs( t.styles ) do
359 if prop.name == name then
360 if val ~= nil then
361 prop.val = val
362 else
363 table.remove( t.styles, i )
364 end
365 return t
366 end
367 end
368
369 if val ~= nil then
370 table.insert( t.styles, { name = name, val = val } )
371 end
372
373 return t
374 end
375
376 -- Add some raw CSS to the node's style attribute. This is typically used
377 -- when a template allows some CSS to be passed in as a parameter
378 --
379 -- @param css
380 methodtable.cssText = function( t, css )
381 checkTypeMulti( 'cssText', 1, css, { 'string', 'number', 'nil' } )
382 table.insert( t.styles, css )
383 return t
384 end
385
386 -- Returns the parent node under which the current node was created. Like
387 -- jQuery.end, this is a convenience function to allow the construction of
388 -- several child nodes to be chained together into a single statement.
389 methodtable.done = function( t )
390 return t.parent or t
391 end
392
393 -- Like .done(), but traverses all the way to the root node of the tree and
394 -- returns it.
395 methodtable.allDone = function( t )
396 while t.parent do
397 t = t.parent
398 end
399 return t
400 end
401
402 -- Create a new instance
403 --
404 -- @param tagName
405 -- @param args
406 function HtmlBuilder.create( tagName, args )
407 checkType( 'mw.html.create', 1, tagName, 'string', true )
408 checkType( 'mw.html.create', 2, args, 'table', true )
409 return createBuilder( tagName, args )
410 end
411
412 function HtmlBuilder.setupInterface( opts )
413 -- Boilerplate
414 HtmlBuilder.setupInterface = nil
415 mw_interface = nil
416 options = opts
417
418 -- Prepare patterns for unencoding strip markers
419 options.encodedUniqPrefixPat = string.gsub( options.uniqPrefix, '[<>&"]', htmlencodeMap );
420 options.encodedUniqPrefixPat = string.gsub( options.encodedUniqPrefixPat, '%p', '%%%0' );
421 options.uniqPrefixRepl = string.gsub( options.uniqPrefix, '%%', '%%%0' );
422 options.encodedUniqSuffixPat = string.gsub( options.uniqSuffix, '[<>&"]', htmlencodeMap );
423 options.encodedUniqSuffixPat = string.gsub( options.encodedUniqSuffixPat, '%p', '%%%0' );
424 options.uniqSuffixRepl = string.gsub( options.uniqSuffix, '%%', '%%%0' );
425
426 -- Register this library in the "mw" global
427 mw = mw or {}
428 mw.html = HtmlBuilder
429
430 package.loaded['mw.html'] = HtmlBuilder
431 end
432
433 return HtmlBuilder