Skip to content

Commit

Permalink
Add javascript to render entities via wbformatentities. Closes #13.
Browse files Browse the repository at this point in the history
  • Loading branch information
wetneb committed Jan 13, 2019
1 parent ccc8761 commit 699395f
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 0 deletions.
81 changes: 81 additions & 0 deletions editgroups/static/js/render-entity-values.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
var wikibaseRootUrl = 'https://www.wikidata.org/wiki/';
var wikibaseApiUrl = 'https://www.wikidata.org/w/api.php';
var lang = 'en';
var entityIdRegex = /^([A-Z][a-z]*:)?[QPL][1-9]\d*/;


/**
* Given a list of entity ids (max 50 values), query the API
* to render them in HTML
*
* entityIds: list of entity ids to render
* elements: map from entity ids to lists of elements to replace by
* the rendered values
*/
function renderEntities(entityIds, elements) {
var renderCallback = function(data) {
if (data.success !== 1) {
return;
}
var renderedEntities = data.wbformatentities
for(var id in renderedEntities) {
if(!renderedEntities.hasOwnProperty(id)) {
continue;
}
var rendered = renderedEntities[id];
for(let elem of elements.get(id).values()) {
elem.replaceWith(rendered);
}
}
};
$.ajax({
url: wikibaseApiUrl,
dataType: 'jsonp',
data: {
'ids': entityIds.join('|'),
'action': 'wbformatentities',
'format': 'json',
'uselang': lang},
success: renderCallback
});
}

/**
* Renders all Wikibase entities linked to in the DOM.
*/
function renderEntitiesInDOM() {
// Gather the mentions of all entities
var elements = new Map();
$('a').each(
function(idx) {
var elem = $(this);
var href = elem.attr('href');
var text = elem.text();
if (wikibaseRootUrl + text === href && entityIdRegex.test(text)) {
// Remove namespace, as it is not expected by wbformatentities
if(text.indexOf(':') !== -1) {
text = text.split(':')[1];
}

// Index element by entity id
var otherElems = elements.get(text);
if(otherElems === undefined) {
otherElems = [];
elements.set(text, otherElems);
}
otherElems.push(elem);
}
});

// Render all the entities
var idsSeen = Array.from(elements.keys());
var batch = idsSeen.splice(0,50);
while (batch.length > 0) {
renderEntities(batch, elements);
batch = idsSeen.splice(0,50);
}
}

$(function() {
renderEntitiesInDOM();
});
1 change: 1 addition & 0 deletions editgroups/templates/editgroups/common.html
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
<link rel="stylesheet" href="{% static "style/style.css" %}" />
<script src="https://tools-static.wmflabs.org/cdnjs/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://tools-static.wmflabs.org/cdnjs/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="{% static "js/render-entity-values.js" %}"></script>
</head>
<body>
<nav class="navbar navbar-default">
Expand Down

0 comments on commit 699395f

Please sign in to comment.