User:Nikki/DisplayColourSwatches.js
Note: After publishing, you may have to bypass your browser's cache to see the changes.
- Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
- Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
- Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
- Opera: Press Ctrl-F5.
/**
* This script adds colour swatches under colour statements.
*
* It is a fork of [[User:Teester/DisplayColourSwatches.js]] which adds support
* for multiple statements for a property. The code has also been heavily edited
* but that should not cause any visible changes.
*
* To use it, add the following line to your common.js:
* mw.loader.load("//www.wikidata.org/w/index.php?title=User:Nikki/DisplayColourSwatches.js&action=raw&ctype=text/javascript");
*/
// jshint esnext: false, esversion: 8
(function () {
"use strict";
async function showColour_addColour(e) {
const hexprop = "P465";
const properties = ["P462", "P2827", "P6364", "P11220"];
const statements = {};
const colours = {};
mw.util.addCSS(".colourswatch { height: 50px; width: 100%; }");
if (e.claims[hexprop]) {
for (const st of e.claims[hexprop]) {
if (st.mainsnak.snaktype !== "value") {
continue;
}
const value = st.mainsnak.datavalue.value;
showColour_addDiv(st.id, value);
}
}
for (const prop of properties) {
if (!e.claims[prop]) {
continue;
}
for (const st of e.claims[prop]) {
if (st.mainsnak.snaktype !== "value") {
continue;
}
const value = st.mainsnak.datavalue.value.id;
statements[st.id] = value;
}
}
if (Object.keys(statements).length === 0) {
return;
}
const api = new mw.Api();
const data = await api.get({
"action": "wbgetentities",
"ids": Object.values(statements),
});
for (const item of Object.values(data.entities)) {
if (!item.claims || !item.claims[hexprop]) {
continue;
}
const st = item.claims[hexprop][0];
if (st.mainsnak.snaktype !== "value") {
continue;
}
const colour = st.mainsnak.datavalue.value;
colours[item.id] = colour;
}
for (const stid of Object.keys(statements)) {
const qid = statements[stid];
showColour_addDiv(stid, colours[qid]);
}
}
function showColour_addDiv(stid, colour) {
const div = document.getElementById(stid).querySelector(".wikibase-statementview-mainsnak .wikibase-snakview-body");
div.insertAdjacentHTML("beforeend", "<div class='colourswatch' style='background-color: #" + mw.html.escape(colour) + "'></div>");
}
mw.hook("wikibase.entityPage.entityView.rendered").add(function () {
mw.hook("wikibase.entityPage.entityLoaded").add(showColour_addColour);
});
})();