Modul:DataGrid/Smw
Aus Star Citizen Wiki
Weitere Optionen
Die Dokumentation für dieses Modul kann unter Modul:DataGrid/Smw/doc erstellt werden
require('strict')
local metadata = require('Module:BucketQuery')
local structuredData = require('Module:Entity/StructuredData')
local smwStore = require('Module:Entity/StructuredData/Smw')
local Vocab = require('Module:Entity/Vocab')
local locationStarmap = require('Module:Entity/Location/Starmap')
local propertyName = smwStore.property
local storedNumber = smwStore.storedNumber
local storedBoolean = smwStore.storedBoolean
local vocabKey = smwStore.vocab
local p = {}
-- The kinds this datatable path serves are the crosswalk's own supported
-- set, never a copied list: Entity/StructuredData/Smw.supportsKind derives
-- it from every registered manifest whose routing buckets the crosswalk
-- writes, so a kind the crosswalk grows to serves here without an edit, and
-- a kind the writer cannot store fails at the entry points as an editor
-- error instead of falling through to the Bucket query, which a wiki
-- running the SMW backend cannot answer at all. A table without kind
-- bypasses the set: it renders in the entity-bucket-only mode
-- (resolveKindless below), the one cross-kind surface no kind can scope.
--- Whether `kind` is a kind this renderer serves. Answers false, never an
--- error, so a caller can route on it.
--- @param kind string|nil
--- @return boolean
function p.supportsKind(kind)
return smwStore.supportsKind(kind)
end
--- The sorted kind names supportsKind answers true for, for editor-facing
--- error text that cannot drift from the actual coverage.
--- @return string[]
function p.supportedKinds()
return smwStore.supportedKinds()
end
-- field -> manifest display name, built once across every registered
-- manifest (the registry page BucketQuery itself searches) so a German
-- property label can resolve to the full manifest entry (type, repeated)
-- instead of only its own name. First declaration wins per field, registry
-- order: a field name a domain manifest shares with the Entity one keeps
-- the Entity mapping, and the kind still picks the right manifest through
-- resolve's kind-first search. The map is a hint generator; the bucket
-- guard at the callers is what makes a wrong hint resolve nil, never a
-- wrong entry.
local displayNames = nil
local function ensureDisplayNames()
if displayNames == nil then
displayNames = {}
local registry = mw.loadJsonData('Module:BucketQuery/manifests.json')
for _, title in ipairs(registry.manifests) do
for displayName, entry in pairs(mw.loadJsonData(title)) do
if type(entry) == 'table' and entry.field and displayNames[entry.field] == nil then
displayNames[entry.field] = displayName
end
end
end
end
end
local function entryForField(field, kind)
ensureDisplayNames()
local displayName = displayNames[field]
return displayName and metadata.resolve(displayName, kind) or nil
end
-- The one bucket a kindless table serves: the cross-kind surface every
-- Entity page writes. StructuredData.store with kind nil routes only the
-- entity bucket (a page whose kind never resolved), so a kindless read over
-- this bucket answers exactly the fields such a page could have written.
local ENTITY_BUCKET = 'entity'
-- Fail-closed resolution for the kindless table ({{Manufacturer products}}:
-- one manufacturer's vehicles and items in one table, so no kind can scope
-- it). Every name must resolve to one entity-bucket manifest entry whose
-- German property one field alone writes. A field another bucket owns would
-- read one kind's values into a cross-kind table; a property two fields
-- share (label or manifest name: 'Typ' and 'Item type' name the same Typ)
-- would blend them the same way, since one SMW property carries every
-- field's values. Both refuse as editor errors naming the kind to set.
local function resolveKindless(name)
local scopeError = function(bucket)
error(
"SMW datatable: '"
.. tostring(name)
.. "' lives in the "
.. bucket
.. ' bucket; a table without kind serves '
.. ENTITY_BUCKET
.. ' fields only - name a kind'
)
end
local function sharedFields(records)
local fields = {}
for i, record in ipairs(records) do
fields[i] = record.field
end
return table.concat(fields, ', ')
end
local entry = metadata.resolve(name)
if entry ~= nil then
if entry.bucket ~= ENTITY_BUCKET then
scopeError(entry.bucket)
end
-- A manifest name is unique, but the property it queries may not be:
-- the ask would read the sharing fields' values too, so the German
-- label's refusal must apply here as well.
local property = propertyName(entry.field, entry.bucket)
local records = smwStore.fieldsForProperty(property)
if records ~= nil and #records > 1 then
error(
"SMW datatable: '"
.. tostring(name)
.. "' names '"
.. property
.. "', shared by "
.. sharedFields(records)
.. '; name a kind to resolve it'
)
end
return entry
end
local records = smwStore.fieldsForProperty(name)
if records == nil then
return nil
end
if #records > 1 then
error(
"SMW datatable: '"
.. tostring(name)
.. "' is shared by "
.. sharedFields(records)
.. '; name a kind to resolve it'
)
end
entry = entryForField(records[1].field)
if entry ~= nil and records[1].bucket ~= nil and entry.bucket ~= records[1].bucket then
entry = nil
end
if entry ~= nil and entry.bucket ~= ENTITY_BUCKET then
scopeError(entry.bucket)
end
return entry
end
--- Resolves a column or filter name to its manifest entry: the manifest's
--- display name first (the cross-wiki surface), then the German property
--- label the SMW crosswalk writes, which is this wiki's editor surface. A
--- German label two fields share resolves against `kind`; unresolved, it
--- raises (see fieldForProperty) rather than querying a wrong vocabulary.
--- A bucket-qualified label (Rüstungstyp) resolves only when the manifest
--- entry's bucket matches the crosswalk's, so a field name another manifest
--- shares (type is a mission field here, a wearable_set field there) cannot
--- resolve to the wrong manifest row; labels this module has no manifest
--- entry for answer nil, like every unknown column.
--- A nil `kind` never reaches those paths: it resolves through the
--- entity-bucket-only mode above (resolveKindless), whose refusals are
--- editor errors rather than an arbitrary pick among the shared properties
--- (manifest name or German label) a kind would otherwise disambiguate.
--- @param name string
--- @param kind string|nil
--- @return table|nil
function p.resolveColumn(name, kind)
if kind == nil then
return resolveKindless(name)
end
local entry = metadata.resolve(name, kind)
if entry == nil then
local field, bucket = smwStore.fieldForProperty(name, kind)
if field then
entry = entryForField(field, kind)
if entry and bucket ~= nil and entry.bucket ~= bucket then
entry = nil
end
end
end
return entry
end
--- The manifest display name an accepted column or filter spelling resolves
--- to: the name itself when a manifest declares it, else the German label's
--- crosswalk target. Entity/Store's SMW reader resolves manifest names only
--- (its property() never consults the German labels), so canonicalSpec
--- rewrites a spec's property names through this before the query.
--- @param name string
--- @param kind string|nil
--- @return string|nil
local function manifestName(name, kind)
if metadata.resolve(name, kind) ~= nil then
return name
end
local entry = p.resolveColumn(name, kind)
if entry == nil then
return nil
end
ensureDisplayNames()
return displayNames[entry.field]
end
--- A copy of a DataGrid spec whose column and filter property names are
--- manifest display names, the one spelling Entity/Store's SMW reader
--- resolves. The caller's spec is not mutated; aliases, values and category
--- filters pass through untouched (a category string names no property).
--- @param spec table
--- @return table
function p.canonicalSpec(spec)
local kind = spec.kind
local function canon(name)
return manifestName(name, kind) or name
end
local out = {}
for key, value in pairs(spec) do
out[key] = value
end
local filters = {}
for i, filter in ipairs(spec.filters or {}) do
if type(filter) == 'string' or (filter.any and type(filter.any[1]) ~= 'table') then
-- A category filter names no property.
filters[i] = filter
elseif filter.any then
local any = {}
for j, sub in ipairs(filter.any) do
any[j] = { canon(sub[1]), sub[2], sub[3] }
end
filters[i] = { any = any }
else
filters[i] = { canon(filter[1]), filter[2], filter[3] }
end
end
out.filters = filters
local columns = {}
for i, col in ipairs(spec.columns or {}) do
columns[i] = col.builtin ~= nil and col or { property = canon(col.property), as = col.as }
end
out.columns = columns
return out
end
local function safe(value)
local s = tostring(value)
if s:find('[%[%]|{}<>]') or s:find('\0', 1, true) then
error('SMW datatable: unsafe query value')
end
return s
end
-- The star-system fields store canonical page titles (Starmap.systemPageTitle,
-- applied at the SMW store seam); a filter literal derives through the same
-- accessor the writer used, so a short name, an alias and any page spelling
-- query the one stored title. The literal takes the same non-redirect PAGE
-- shaping first (structuredData.shapedPageTitle) that the writer's value took
-- before the seam canonicalized it - the stored title derives from a shaped
-- value, so an underscored or linked literal must shape identically to reach
-- it. destination_system (Sprungpunkt Ziel) stores through the same accessor
-- as system and systems.
local function systemPageLiteral(entry, value)
if type(value) ~= 'string' or not locationStarmap.systemFields[entry.field] then
return value
end
return locationStarmap.systemPageTitle(structuredData.shapedPageTitle(value)) or value
end
local function property(name, kind)
local entry = p.resolveColumn(name, kind)
if not entry then
error('SMW datatable: unknown property ' .. tostring(name))
end
-- An unresolved field's display-name fallback names a property no German
-- page stores: the #ask would answer empty and look valid.
local reason = smwStore.unresolved(entry.field)
if reason then
error(
"SMW datatable: '"
.. tostring(name)
.. "' has no German property yet ("
.. reason
.. '); remove it until the crosswalk maps it'
)
end
return propertyName(entry.field, entry.bucket), entry
end
local function condition(filter, kind)
if type(filter) == 'string' and filter:match('^Category:.+') then
-- [[:+]] keeps the condition main-namespace: SMW's category condition
-- recurses into subcategories, and a category's subcats commonly hold
-- only the File: pages of the subject images. +depth=0 is not a
-- substitute (returns zero rows on some categories on this wiki).
return '[[' .. safe(filter) .. ']][[:+]]'
end
if type(filter) ~= 'table' then
error('SMW datatable: unsupported filter')
end
if filter.any then
local parts = {}
for _, item in ipairs(filter.any) do
parts[#parts + 1] = condition(item, kind)
end
if #parts == 0 then
error('SMW datatable: empty OR filter')
end
return '<q>' .. table.concat(parts, ' OR ') .. '</q>'
end
local name, op, value = filter[1], filter[2], filter[3]
if value == nil and op ~= '+' then
value, op = op, '='
end
local comparators = {
['='] = '',
['!='] = '!',
['<'] = '<<',
['<='] = '<',
['>'] = '>>',
['>='] = '>',
['+'] = '+',
}
local comparator = comparators[op]
if not comparator then
error('SMW datatable: unsupported operator ' .. tostring(op))
end
local prop, entry = property(name, kind)
if entry.field == 'orders' or entry.field == 'rewards' then
error('SMW: display-only field cannot be filtered')
end
if op == '!=' and entry.repeated then
error('SMW datatable: inequality on a list')
end
if op == '<' or op == '<=' or op == '>' or op == '>=' then
if
(entry.type ~= 'INTEGER' and entry.type ~= 'DOUBLE')
or type(value) ~= 'number'
or value ~= value
or math.abs(value) == math.huge
then
error('SMW datatable: invalid numeric comparison')
end
end
if op == '+' then
return '[[' .. prop .. '::+]]'
end
if value == nil then
error('SMW datatable: missing query value')
end
-- Boolean equality takes the probe-verified spellings only (true/ja/1,
-- false/nein/0); anything else fails loudly instead of querying a literal
-- no live row matches. The probe facts live on storedBoolean.
local text
if entry.type == 'BOOLEAN' then
text = storedBoolean(value)
else
-- A numeric field's number value serializes exactly as the writer stores
-- it (spec factor, comma decimal, unit token), so the condition compares
-- in the stored scale, not the Bucket scale filter values speak; a text
-- value in a vocabulary-backed field translates English -> German through
-- the writer spec's vocabulary key, which for tier and classification
-- differs from the field name, and which the entry's bucket scopes for a
-- field name two routing buckets share. Vocab pass-through keeps German
-- input and non-vocab fields verbatim, so an editor literal matches the
-- stored value.
local numericEquality = op == '='
and entry.bucket == 'item_component'
and (entry.field == 'pitch' or entry.field == 'yaw')
text = safe(
type(value) == 'number'
and (entry.type == 'INTEGER' or entry.type == 'DOUBLE' or numericEquality)
and storedNumber(entry.field, value, entry.bucket)
or Vocab.toGerman(vocabKey(entry.field, entry.bucket), systemPageLiteral(entry, value))
)
end
if op == '!=' and text:match('^~') then
error('SMW datatable: unsafe inequality value')
end
if op == '=' and smwStore.comparatorShaped(text) then
error('SMW datatable: unsafe equality value')
end
return '[[' .. prop .. '::' .. comparator .. text .. ']]'
end
function p.render(frame, spec, columns, sort)
if spec.primary and spec.primary ~= 'entity' then
error('SMW datatable: unsupported primary')
end
local conditions = {}
for _, filter in ipairs(spec.filters or {}) do
conditions[#conditions + 1] = condition(filter, spec.kind)
end
if #conditions == 0 then
error('SMW datatable: unbounded query')
end
-- format=table, not the datatables printers: this wiki's SRF build
-- renders one row less than the query returns (a single-row query renders
-- headers only), while the plain table ships every row and stays
-- client-side sortable.
local args = { table.concat(conditions), format = 'table', limit = tostring(spec.limit or 1000) }
local aliases = { Name = '' }
-- The ask keys a printout by its header, so two columns rendering one
-- header collapse onto one; resolveArgs' alias check cannot see these
-- collisions (several names resolve to one property, a label can name
-- another column's bare printout).
local owners = {}
for _, col in ipairs(columns) do
local prop = property(col.property, spec.kind)
-- Editor labels are the header verbatim: a translation could restyle the
-- editor's text or collide with another header. An unlabeled column
-- prints bare, keeping the property page's display alias.
local label = col.label ~= nil and col.label ~= '' and safe(col.label) or nil
local header = label or prop
if owners[header] ~= nil then
error(
"SMW datatable: duplicate header '"
.. header
.. "' (columns '"
.. owners[header]
.. "' and '"
.. tostring(col.property)
.. "')"
)
end
owners[header] = tostring(col.property)
args[#args + 1] = label and '?' .. prop .. '=' .. label or '?' .. prop
aliases[label or safe(col.property)] = prop
end
if sort then
local keys, directions = {}, {}
for _, key in ipairs(sort) do
if aliases[key.alias] == nil then
error('SMW datatable: unsupported sort column')
end
keys[#keys + 1] = aliases[key.alias]
directions[#directions + 1] = key.direction
end
args.sort = table.concat(keys, ',')
args.order = table.concat(directions, ',')
end
return frame:callParserFunction('#ask', args)
end
return p