Module:FeaturedExtract
From Landrace.wiki
More actions
Documentation for this module may be created at Module:FeaturedExtract/doc
-- Module:FeaturedExtract
-- Pulls content from articles for use in homepage cards.
--
-- p.lead — lead-section text. Strips HTML comments, leading templates
-- and leading File/Image blocks, all <ref> blocks and inline
-- citation and maintenance markers ({{rp}}, {{cn}} and the
-- like), clips at the first == heading, then truncates to
-- a clean length. Emits explicit <p> tags
-- so paragraph breaks survive when wrapped in a block
-- element on the calling page. Set nomore=1 to suppress
-- the trailing "read more" link. Set fill=1 to follow a lead
-- shorter than chars with whole prose paragraphs from the
-- body (headings, lists, tables, templates, galleries and
-- refs skipped), cut at a sentence end.
--
-- p.heroDiv — float-image div for the featured-article panel. Image
-- source priority: an existing explicit Has image value
-- (arg 1), then the first uncommented existing [[File:...]]
-- in page wikitext, then an existing |image= parameter from
-- the leading template. When none yields an image and the
-- caller passes default=<bare filename> of an existing file,
-- that file is used as a decorative picture (empty alt, no
-- link); otherwise returns empty so no broken markup
-- renders. Detects image
-- orientation (wide, landscape, portrait,
-- square-ish) and emits a modifier class so CSS can set a
-- different display width per orientation. Picks a thumb
-- size hint appropriate to the orientation so retina
-- sharpness holds. Caller may override the hint via arg 3.
local p = {}
-- HTML comments are invisible page metadata. Remove them before looking
-- for lead templates or image fallbacks so commented-out figures cannot
-- become homepage media.
local function stripComments(text)
local cleaned = (text or ""):gsub("<!%-%-.-%-%->", "")
return cleaned
end
-- Strip consecutive leading File/Image links. A balanced scanner is used
-- because file captions may themselves contain nested wikilinks.
local function stripLeadingFiles(text)
while true do
local s = text:match("^%s*()")
if not s then return text end
local head = text:sub(s)
if not head:match("^%[%[%s*[Ff]ile%s*:") and
not head:match("^%[%[%s*[Ii]mage%s*:") then
return text
end
local depth, i = 0, s
local closed = false
while i <= #text do
local pair = text:sub(i, i + 1)
if pair == "[[" then
depth = depth + 1
i = i + 2
elseif pair == "]]" then
depth = depth - 1
i = i + 2
if depth == 0 then
text = text:sub(i)
closed = true
break
end
else
i = i + 1
end
end
if not closed then return text end
end
end
-- Return a filename only when its File page exists.
local function existingFile(filename)
if not filename or filename == "" then return "" end
local fileTitle = mw.title.new("File:" .. filename)
if fileTitle and fileTitle.file and fileTitle.file.exists then
return filename
end
return ""
end
-- Strip a balanced {{...}} template block at the start of the text.
local function stripLeadingTemplate(text)
while true do
local s = text:match("^%s*()")
if not s or text:sub(s, s+1) ~= "{{" then return text end
local depth, i = 0, s
local closed = false
while i <= #text do
local c2 = text:sub(i, i+1)
if c2 == "{{" then
depth = depth + 1
i = i + 2
elseif c2 == "}}" then
depth = depth - 1
i = i + 2
if depth == 0 then
text = text:sub(i)
closed = true
break
end
else
i = i + 1
end
end
if not closed then return text end
end
end
-- Inline citation and maintenance markers. A module's output is not expanded
-- again, so a template left in an extract prints as raw braces. These carry no
-- prose, so an extract drops them whether or not they take parameters: the
-- {{rp}} page pin after a stripped <ref>, {{cn|date=...}}, {{or}} and the rest.
local INLINE_MARKERS = {
["rp"] = true, ["cn"] = true, ["citation needed"] = true, ["fact"] = true,
["or"] = true, ["original research"] = true, ["editorializing"] = true,
["verify source"] = true, ["failed verification"] = true,
["better source needed"] = true, ["page needed"] = true,
["who?"] = true, ["which?"] = true, ["when?"] = true,
["clarify"] = true, ["dubious"] = true, ["vague"] = true,
["stub"] = true, ["page stub"] = true, ["section stub"] = true,
}
local function stripInlineMarkers(text)
return (text:gsub("{{([^{}]*)}}", function(inner)
local name = mw.text.trim(inner:match("^[^|]*") or "")
name = mw.ustring.lower((name:gsub("_", " ")))
if INLINE_MARKERS[name] then return "" end
return nil
end))
end
-- Take everything up to the first level-2+ heading.
local function takeLead(text)
local heading = text:find("\n==")
if heading then return text:sub(1, heading - 1) end
return text
end
-- Whole prose paragraphs from the article body after the lead, in order, for
-- fill=1. A line is prose only when it sits outside every template, table and
-- block tag (gallery, poem, blockquote, pre, table) and starts with none of the
-- markup that opens a heading, list, indent, table row, template, tag, file or
-- preformatted block. Consecutive prose lines make one paragraph, as in
-- MediaWiki; a paragraph with unbalanced link brackets or an SMW annotation is
-- dropped.
-- The longest head of text, at most maxChars long, that ends at a sentence end:
-- . ! or ? (with any closing quotes, brackets or italic marks) before a space or
-- the end, not after a lone letter (an initial such as "W. B." or "c."), and
-- with its links and templates closed. nil when there is none.
local function sentenceCut(text, maxChars)
local clip = text:sub(1, maxChars)
if #text <= maxChars then clip = clip .. " " end
local ends = {}
local init = 1
while true do
local s, e = clip:find("[%.%?%!][\"')\226\128\153\157]*%s", init)
if not s then break end
local before = clip:sub(math.max(1, s - 2), s - 1)
if not before:find("^[%s%.]?%a$") and not (s == 2 and before:find("^%a$")) then
table.insert(ends, e - 1)
end
init = e + 1
end
for i = #ends, 1, -1 do
local head = clip:sub(1, ends[i]):gsub("%s+$", "")
local _, lo = head:gsub("%[%[", "")
local _, lc = head:gsub("%]%]", "")
local _, to = head:gsub("{{", "")
local _, tc = head:gsub("}}", "")
if lo == lc and to == tc then return head end
end
return nil
end
local BLOCK_TAGS = { "gallery", "poem", "blockquote", "pre", "table", "math", "syntaxhighlight" }
local function bodyParagraphs(text)
local paras, run = {}, {}
local tplDepth, tableDepth, tagDepth = 0, 0, 0
local function flush()
if #run > 0 then
local para = table.concat(run, " ")
run = {}
local _, opens = para:gsub("%[%[", "")
local _, closes = para:gsub("%]%]", "")
-- [[Property::value]] is an SMW annotation (a hidden data block), not prose
if opens == closes and not para:find("%[%[[^%]]-::") then
table.insert(paras, para)
end
end
end
for line in (text .. "\n"):gmatch("([^\n]*)\n") do
local outside = tplDepth == 0 and tableDepth == 0 and tagDepth == 0
local _, to = line:gsub("{{", "")
local _, tc = line:gsub("}}", "")
tplDepth = math.max(0, tplDepth + to - tc)
if line:find("^%s*{|") then tableDepth = tableDepth + 1 end
if line:find("^%s*|}") then tableDepth = math.max(0, tableDepth - 1) end
local lower = line:lower()
for _, tag in ipairs(BLOCK_TAGS) do
local _, o = lower:gsub("<" .. tag .. "[%s>]", "")
local _, c = lower:gsub("</" .. tag .. "%s*>", "")
tagDepth = math.max(0, tagDepth + o - c)
end
local t = mw.text.trim(line)
local tl = t:lower()
local prose = outside and tplDepth == 0 and tableDepth == 0 and tagDepth == 0
and t ~= "" and not line:find("^%s")
and not t:find("^[=%*#:;|!{<%-_]")
and not tl:find("^%[%[%s*file%s*:")
and not tl:find("^%[%[%s*image%s*:")
and not tl:find("^%[%[%s*category%s*:")
if prose then
table.insert(run, t)
else
flush()
end
end
flush()
return paras
end
-- Truncate at the last sentence boundary (. ! ?) before max chars.
-- Falls back to the last word boundary if no sentence ends in range.
local function truncate(text, maxChars)
if #text <= maxChars then return text, false end
local clip = text:sub(1, maxChars)
local lastSentence = clip:find("[%.%?%!]%s+%u[^%.%?%!]*$")
if lastSentence then
local upTo = clip:sub(1, lastSentence)
upTo = upTo:gsub("%s+$", "")
return upTo, true
end
local lastSpace = clip:find("%s+[^%s]*$")
if lastSpace then
return clip:sub(1, lastSpace - 1), true
end
return clip, true
end
-- Find the first [[File:...]] or [[Image:...]] filename in wikitext.
local function firstFileIn(content)
if not content or content == "" then return "" end
local img = content:match("%[%[%s*[Ff]ile%s*:%s*([^%[%]|]+)")
or content:match("%[%[%s*[Ii]mage%s*:%s*([^%[%]|]+)")
or ""
return mw.text.trim(img)
end
-- Read |image= parameter from the leading infobox call (or, failing that,
-- |logo=, which is how organisation infoboxes name their picture). Handles bare
-- filename, [[File:Foo.jpg]] wrappers, and parameter values with sized
-- options. Limited to the first 3000 chars to scope to the infobox
-- region only.
local function imageFromInfobox(content)
if not content or content == "" then return "" end
local head = content:sub(1, 3000)
local raw = head:match("|%s*image%s*=%s*([^|}\n]+)")
or head:match("|%s*logo%s*=%s*([^|}\n]+)")
if not raw then return "" end
raw = mw.text.trim(raw)
if raw == "" then return "" end
local fromLink = raw:match("^%[%[%s*[Ff]ile%s*:%s*([^%[%]|]+)")
if fromLink then return mw.text.trim(fromLink) end
return raw
end
-- Classify image as wide, landscape, portrait, or square based on dimensions.
-- Returns modifier class fragment and a thumbnail size hint matched
-- to the display width of that orientation tier (~2x for retina).
-- Falls back to square-ish defaults when dimensions can't be read.
local function orientationFor(filename)
local fileTitle = mw.title.new("File:" .. filename)
if fileTitle and fileTitle.file and fileTitle.file.exists then
local w = fileTitle.file.width or 0
local h = fileTitle.file.height or 0
if w > 0 and h > 0 then
local ratio = w / h
-- A very wide picture (a strip of text scanned from a page) is
-- shown whole: a 3:2 crop would cut its lines mid-word.
if ratio >= 1.9 then
return "home-featured__float--wide", "1000px"
elseif ratio >= 1.2 then
return "home-featured__float--landscape", "800px"
elseif ratio <= 0.85 then
return "home-featured__float--portrait", "560px"
end
end
end
return "home-featured__float--square", "640px"
end
-- De-link wikilinks whose targets do not exist. Homepage cards must not
-- surface an article's committed-future redlinks as red form-edit links;
-- the article pages themselves keep them per policy. Interwiki links are
-- preserved. Each existence probe is an expensive parser call, so this
-- runs only on the short homepage extracts.
local function delinkMissing(text)
local function resolve(target, label)
local base = target:gsub("#.*$", "")
base = mw.text.trim(base)
if base == "" then return nil end
local ok, ti = pcall(mw.title.new, base)
if not ok or not ti then return label end
if ti.isExternal or ti.exists then return nil end
return label
end
text = text:gsub("%[%[([^%[%]|]+)|([^%[%]]+)%]%]", function(t, l)
return resolve(t, l)
end)
text = text:gsub("%[%[([^%[%]|]+)%]%]", function(t)
return resolve(t, t)
end)
return text
end
function p.lead(frame)
local args = frame.args
local pagename = args[1] or args.article
if not pagename or pagename == "" then return "" end
local maxChars = tonumber(args.chars or args[2]) or 600
local nomore = args.nomore and args.nomore ~= "" and args.nomore ~= "0"
local fill = args.fill and args.fill ~= "" and args.fill ~= "0"
local title = mw.title.new(pagename)
if not title or not title.exists then return "" end
local content = title:getContent()
if not content then return "" end
content = stripComments(content)
local previous
repeat
previous = content
content = stripLeadingTemplate(content)
content = stripLeadingFiles(content)
until content == previous
local full = content
content = takeLead(content)
content = content:gsub("<ref[^/>]*/>", "")
content = content:gsub("<ref[^>]*>.-</ref>", "")
content = stripInlineMarkers(content)
content = content:gsub("%[%[%s*[Cc]ategory%s*:[^%]]*%]%]", "")
-- A lead extract is prose for a <p> wrapper: block-level wrappers in the
-- source (e.g. a page-spanning <div class="plainlinks">) must not leak in,
-- and an OPEN without its close unbalances the whole calling page.
content = content:gsub("<div[^>]*>", "")
content = content:gsub("</div>", "")
content = content:gsub("^%s+", ""):gsub("%s+$", "")
-- fill=1 (the Main Page card): a lead shorter than chars is followed by
-- whole prose paragraphs from the body, cleaned the same way, until the
-- length is reached; the cut below then ends it at a sentence.
local truncated
if fill then
local cut = false
if #content > maxChars then
local c = sentenceCut(content, maxChars)
if c then content = c else content = truncate(content, maxChars) end
cut = true
else
local body = full:sub(#takeLead(full) + 1)
body = body:gsub("<ref[^/>]*/>", "")
body = body:gsub("<ref[^>]*>.-</ref>", "")
body = stripInlineMarkers(body)
body = body:gsub("%[%[%s*[Cc]ategory%s*:[^%]]*%]%]", "")
body = body:gsub("<div[^>]*>", "")
body = body:gsub("</div>", "")
for _, para in ipairs(bodyParagraphs(body)) do
local room = maxChars - #content - 2
if room <= 0 then cut = true; break end
-- a paragraph that only introduces a list or quotation is skipped with it
if not para:find(":['%s]*$") then
if #para <= room then
content = content .. "\n\n" .. para
else
local c = sentenceCut(para, room)
if c then content = content .. "\n\n" .. c end
cut = true
break
end
end
end
end
truncated = cut
else
content, truncated = truncate(content, maxChars)
end
content = delinkMissing(content)
local readMore = nomore and '' or (' <span class="home-featured__more">[[' .. pagename .. '|read more →]]</span>')
local tail = (truncated and ' …' or '') .. readMore
local paragraphs = {}
for para in (content .. "\n\n"):gmatch("(.-)\n\n+") do
para = para:gsub("^%s+", ""):gsub("%s+$", "")
if para ~= "" then
table.insert(paragraphs, para)
end
end
if #paragraphs == 0 then return "" end
paragraphs[#paragraphs] = paragraphs[#paragraphs] .. tail
local out = {}
for _, para in ipairs(paragraphs) do
table.insert(out, "<p>" .. para .. "</p>")
end
return table.concat(out, "\n")
end
-- Normalise Has image values before using them in homepage media. Most values
-- are bare filenames; one legacy record contains a full [[File:...|thumb]]
-- wrapper. Both forms resolve to the same safe existing filename here.
local function cleanImageValue(raw)
raw = mw.text.trim(raw or "")
if raw == "" then return "" end
local wrapped = raw:match("^%[%[%s*[Ff]ile%s*:%s*([^%]|]+)")
if wrapped then raw = wrapped end
raw = raw:gsub("^%s*[Ff]ile%s*:%s*", "")
raw = mw.text.trim((raw:match("^[^|]+") or raw))
return existingFile(raw)
end
-- A universal accession-image surface. The decorative crop supplies colour
-- to the frame while the foreground always preserves the complete source.
-- Both layers request the same thumbnail, so the browser downloads it once.
function p.accessionMedia(frame)
local img = cleanImageValue(frame.args[1] or "")
if img == "" then return "" end
return string.format(
'<div class="home-featured-accession__media">' ..
'<div class="home-featured-accession__backdrop" aria-hidden="true">[[File:%s|960px|link=|alt=]]</div>' ..
'<div class="home-featured-accession__foreground">[[File:%s|960px|link=|alt=]]</div>' ..
'</div>', img, img
)
end
function p.heroDiv(frame)
local explicit = mw.text.trim(frame.args[1] or "")
local pageName = mw.text.trim(frame.args[2] or "")
local sizeOverride = mw.text.trim(frame.args[3] or "")
local default = mw.text.trim(frame.args.default or "")
local img = existingFile(explicit)
if img == "" and pageName ~= "" then
local title = mw.title.new(pageName)
if title and title.exists then
local content = stripComments(title:getContent() or "")
img = existingFile(firstFileIn(content))
if img == "" then
img = existingFile(imageFromInfobox(content))
end
end
end
-- Last resort, opt-in: a generic picture for an article that has none of its
-- own. It is decorative, so it carries no alt text and no link.
local decorative = false
if img == "" and default ~= "" then
img = existingFile(default)
decorative = (img ~= "")
end
if img == "" then return "" end
local orientationClass, thumbHint = orientationFor(img)
local size = sizeOverride ~= "" and sizeOverride or thumbHint
if decorative then
return string.format(
'<div class="home-featured__float %s">[[File:%s|%s|link=|alt=]]</div>',
orientationClass, img, size
)
end
return string.format(
'<div class="home-featured__float %s">[[File:%s|%s|link=%s|alt=%s]]</div>',
orientationClass, img, size, pageName, pageName
)
end
-- Normalise a file name for comparison: strip any File: prefix, treat
-- underscores and spaces as equivalent, upper-case the first letter (MediaWiki
-- does the same when resolving a title).
local function normFile(name)
name = mw.text.trim(name or ""):gsub("_", " ")
name = name:gsub("^%s*[Ff]ile%s*:%s*", "")
name = mw.text.trim(name)
if name == "" then return "" end
return mw.ustring.upper(mw.ustring.sub(name, 1, 1)) .. mw.ustring.sub(name, 2)
end
-- Split on pipes that sit at nesting depth zero. Figure captions routinely
-- contain wikilinks and templates carrying their own pipes, so a plain
-- string split would cut a caption in half.
local function splitTopLevel(text)
local parts, depth, start, i = {}, 0, 1, 1
while i <= #text do
local two = text:sub(i, i + 1)
if two == "[[" or two == "{{" then
depth = depth + 1
i = i + 2
elseif two == "]]" or two == "}}" then
depth = depth - 1
i = i + 2
elseif text:sub(i, i) == "|" and depth == 0 then
table.insert(parts, text:sub(start, i - 1))
start = i + 1
i = i + 1
else
i = i + 1
end
end
table.insert(parts, text:sub(start))
return parts
end
-- Bare display options, which are never the caption.
local IMAGE_OPTIONS = {
thumb = true, thumbnail = true, frame = true, framed = true,
frameless = true, border = true, right = true, left = true,
center = true, centre = true, none = true, baseline = true,
middle = true, sub = true, super = true, top = true, bottom = true,
["text-top"] = true, ["text-bottom"] = true,
}
-- Named options (alt=, link=, ...) and sizes are not captions either.
local function isImageOption(segment)
local s = mw.text.trim(segment or "")
if s == "" then return true end
local lower = mw.ustring.lower(s)
if IMAGE_OPTIONS[lower] then return true end
if lower:match("^%d+%s*px$") then return true end
if lower:match("^x%d+%s*px$") then return true end
if lower:match("^%d+%s*x%s*%d+%s*px$") then return true end
if lower:match("^upright") then return true end
for _, named in ipairs({ "alt", "link", "lang", "page", "class",
"thumbtime", "start", "end" }) do
if lower:match("^" .. named .. "%s*=") then return true end
end
return false
end
-- Return the caption a page gives one specific file. Scans each [[File:...]]
-- block with bracket balancing, matches on the normalised name, then takes the
-- last segment that is not a display option, which is where MediaWiki puts the
-- caption.
local function captionFromPage(content, filename)
local want = normFile(filename)
if want == "" then return "" end
local searchFrom = 1
while true do
local blockStart = content:find("%[%[%s*[Ff]ile%s*:", searchFrom)
if not blockStart then return "" end
local depth, i, blockEnd = 0, blockStart, nil
while i <= #content do
local two = content:sub(i, i + 1)
if two == "[[" then
depth = depth + 1
i = i + 2
elseif two == "]]" then
depth = depth - 1
i = i + 2
if depth == 0 then
blockEnd = i - 1
break
end
else
i = i + 1
end
end
if not blockEnd then return "" end
local parts = splitTopLevel(content:sub(blockStart + 2, blockEnd - 2))
if normFile(parts[1]) == want then
for k = #parts, 2, -1 do
if not isImageOption(parts[k]) then
return mw.text.trim(parts[k])
end
end
return ""
end
searchFrom = blockEnd + 1
end
end
-- Articles carry their lead figure in the series-navbox slot as |image= with
-- the text in a sibling |caption=, not as a [[File:...]] block. About a third
-- of a portal's pictures take their caption from here, so a File-block scan
-- alone leaves them uncaptioned. captionKeys names the parameters that may
-- hold the caption (default: caption only).
local function captionFromLeadTemplate(content, filename, captionKeys)
local want = normFile(filename)
if want == "" then return "" end
local s = content:match("^%s*()")
if not s or content:sub(s, s + 1) ~= "{{" then return "" end
local depth, i, stop = 0, s, nil
while i <= #content do
local two = content:sub(i, i + 1)
if two == "{{" then
depth = depth + 1
i = i + 2
elseif two == "}}" then
depth = depth - 1
i = i + 2
if depth == 0 then
stop = i - 1
break
end
else
i = i + 1
end
end
if not stop then return "" end
captionKeys = captionKeys or { caption = true }
local image, caption = "", ""
for _, segment in ipairs(splitTopLevel(content:sub(s + 2, stop - 2))) do
local key, value = segment:match("^%s*([%w_ %-]+)%s*=(.*)$")
if key then
key = mw.ustring.lower(mw.text.trim(key))
if key == "image" then
image = mw.text.trim(value)
elseif captionKeys[key] then
caption = mw.text.trim(value)
end
end
end
if image ~= "" and normFile(image) == want then return caption end
return ""
end
-- The caption a page gives a file, from a [[File:...]] block if it uses one,
-- otherwise from the lead template's |caption= (or the keys in captionKeys).
local function captionFor(content, filename, captionKeys)
local caption = captionFromPage(content, filename)
if caption ~= "" then return caption end
return captionFromLeadTemplate(content, filename, captionKeys)
end
-- The portal picture cards also read an infobox's |image_caption=, which is
-- where the source, book and site infoboxes keep it.
local PORTAL_CAPTION_KEYS = { caption = true, image_caption = true }
-- p.fileCaption — the caption `page` gives `file`, as plain wikitext.
-- Empty when the page does not use the file or gives it no caption.
function p.fileCaption(frame)
local filename = mw.text.trim(frame.args[1] or "")
local pagename = mw.text.trim(frame.args[2] or "")
if filename == "" or pagename == "" then return "" end
local title = mw.title.new(pagename)
if not title or not title.exists then return "" end
return captionFor(stripComments(title:getContent() or ""), filename)
end
-- p.pictureCaption — the caption block for the portal "Selected picture" card:
-- the article's own caption for the figure, then an attribution line naming the
-- article it illustrates. A third argument is an explicit caption that replaces the
-- article's. Emitting the whole block here keeps the empty-caption
-- case out of the calling template, where it would cost a second module call.
function p.pictureCaption(frame)
local filename = mw.text.trim(frame.args[1] or "")
local pagename = mw.text.trim(frame.args[2] or "")
if pagename == "" then return "" end
local caption = mw.text.trim(frame.args[3] or "")
if caption == "" and filename ~= "" then
local title = mw.title.new(pagename)
if title and title.exists then
caption = captionFor(stripComments(title:getContent() or ""), filename,
PORTAL_CAPTION_KEYS)
end
end
local out = {}
if caption ~= "" then
table.insert(out, '<div class="lw-hero__caption">' .. caption .. '</div>')
end
table.insert(out,
'<div class="lw-picture__src">From [[' .. pagename .. ']]</div>')
return table.concat(out, "\n")
end
-- The kind of page, read from the name of its infobox: "Archaeological site"
-- from {{Infobox Archaeological site}}. Empty for a page without one.
local function kindFromInfobox(content)
local name = content:match("{{%s*[Ii]nfobox[ _]+([^|}\n]+)")
if not name then return "" end
name = mw.text.trim((name:gsub("_", " ")))
if name == "" then return "" end
return mw.ustring.upper(mw.ustring.sub(name, 1, 1)) ..
mw.ustring.lower(mw.ustring.sub(name, 2))
end
-- The page's Has country values as plain text, joined with commas.
local function countryOf(frame, pagename)
local ok, out = pcall(function()
return frame:callParserFunction('#show', {
pagename, '?Has country', link = 'none', sep = ', '
})
end)
if not ok or not out then return "" end
out = mw.text.trim(out)
if out:find("<", 1, true) or out:find("[[", 1, true) then return "" end
return out
end
-- A cut lead can end inside a wikilink ("... alongside [[Cannabis …"), which
-- prints the brackets raw. Drop the unclosed link and end on the ellipsis.
local function dropOpenLink(html)
local last = 0
for pos in html:gmatch("()%[%[") do last = pos end
if last == 0 or html:find("%]%]", last) then return html end
local head = html:sub(1, last - 1):gsub("[%s,;:']+$", "")
return head .. " …" .. (html:match("</p>%s*$") and "</p>" or "")
end
-- Where the crop of a picture centres when no focal point is given: the
-- middle, except for a tall picture (a title page, a portrait, a plate),
-- where the top quarter usually holds the title or the face.
local function defaultFocal(filename)
local fileTitle = mw.title.new("File:" .. filename)
local f = fileTitle and fileTitle.file
if f and f.exists and (f.width or 0) > 0 and (f.height or 0) > 0 and
f.height / f.width > 1.05 then
return "50% 25%"
end
return ""
end
-- p.portalCard — the wide "Featured article" card on the knowledge portals.
-- The picture sits in a fixed 4:3 frame (cropped to fill it, centred on
-- focal= when given) beside the title, a lead extract and a Read link. An
-- article with no picture gets the text alone, under a line naming its kind
-- and country, so the card never shows an empty frame. Same image priority as
-- heroDiv; the Main Page card keeps heroDiv and lead.
-- Args: image= (Has image value), page=, chars= (default 900), focal=.
function p.portalCard(frame)
local args = frame.args
local pagename = mw.text.trim(args.page or args[2] or "")
if pagename == "" then return "" end
local title = mw.title.new(pagename)
if not title or not title.exists then return "" end
local content = stripComments(title:getContent() or "")
local img = cleanImageValue(args.image or args[1] or "")
if img == "" then img = existingFile(firstFileIn(content)) end
if img == "" then img = existingFile(imageFromInfobox(content)) end
local lead = dropOpenLink(p.lead({ args = {
pagename, chars = args.chars or "900", nomore = "1"
} }))
local more = '<p class="featured-wide__more"><span class="home-featured__more">[[' ..
pagename .. '|Read the article]]</span></p>'
local body = {}
if img == "" then
local kind = kindFromInfobox(content)
local country = countryOf(frame, pagename)
local band = kind
if country ~= "" then
band = (band ~= "" and (band .. " · ") or "") .. country
end
if band ~= "" then
table.insert(body, '<div class="featured-wide__kind">' .. band .. '</div>')
end
end
table.insert(body, '<div class="featured-wide__title">[[' .. pagename .. ']]</div>')
if lead ~= "" then table.insert(body, lead) end
table.insert(body, more)
if img == "" then
return '<div class="featured-wide featured-wide--text">\n' ..
'<div class="featured-wide__body">\n' .. table.concat(body, "\n") ..
'\n</div>\n</div>'
end
local focal = mw.text.trim(args.focal or "")
if focal == "" then focal = defaultFocal(img) end
local style = ""
if focal:match("^%d+%%? %d+%%?$") then
style = ' style="object-position:' .. focal .. '"'
end
local media = {
'<div class="lw-frame"' .. style .. '>[[File:' .. img ..
'|640px|link=' .. pagename .. '|alt=' .. pagename .. ']]</div>'
}
local caption = captionFor(content, img, PORTAL_CAPTION_KEYS)
if caption ~= "" then
table.insert(media, '<div class="lw-hero__caption">' .. caption .. '</div>')
end
return '<div class="featured-wide">\n' ..
'<div class="featured-wide__media">\n' .. table.concat(media, "\n") .. '\n</div>\n' ..
'<div class="featured-wide__body">\n' .. table.concat(body, "\n") .. '\n</div>\n' ..
'</div>'
end
return p