Gebruiker:1Veertje/delpher-1.0.js
Uiterlijk
Opmerking: na het publiceren moet je misschien je browsercache legen om de veranderingen te zien.
- Firefox / Safari: houd Shift ingedrukt terwijl u:je op Vernieuwen klikt of druk op Ctrl-F5 of Ctrl-R (⌘-Shift-R op een Mac)
- Google Chrome: druk op Ctrl-Shift-R (⌘-Shift-R op een Mac)
- Edge: houd Ctrl ingedrukt terwijl u:je op Vernieuwen klikt of druk op Ctrl-F5.
// ==UserScript==
// @name Delpher met Wikitext
// @supportURL https://nl.wikipedia.org/wiki/Gebruiker:1Veertje/Delpher_userscript
// @namespace https://*.delpher.nl/nl/*
// @version 0.9
// @description Delpher WP improvement
// @author 1Veertje
// @match https://*.delpher.nl/nl/*
// @grant none
// ==/UserScript==
//<noinclude><nowiki>
// Language mappings
const languages = {"Nederlands":"nl", "nl":"nl", "dut":"nl","Frans":"fr","fr":"fr", "fra":"fr", "Duits":"de", "de":"de"};
const today = new Date().toISOString().slice(0,10);
let coll = ''
// Wait for document to be ready
$(document).ready(function() {
// Extract metadata and collection information
const meta = JSON.parse(document.querySelector("div.js-object-viewer-wrapper").dataset.metadata);
coll = document.querySelector("input[name=coll]").value;
// Fetch data using AJAX
$.ajax({
dataType: "json",
url: 'https://www.delpher.nl/nl/api/resource',
data: {"identifier": meta.objectlevelId , "coll" : coll, "type":"dc"},
success: handleData
});
});
// Handle fetched data
function handleData(data) {
const label = $( "label" )
.map((i, el) => el.innerText.trim()).get()
.filter(e => e !== 'Pagina')
.reverse()[0].toLowerCase();
const meta = {};
// Process metadata
meta.title = data.title;
data.date = data.date.replace("-01-01 (schatting)", "").replace(" (schatting)", "").replace(" 00:00:00", "").replace("[","").replace("]","");
meta.pubdate = new Date(data.date).toISOString().slice(0,data.date.toString().length);
// Map language if available
if (typeof data.language === "string" && data.language in languages) {
meta.language = languages[data.language];
}
const reverseDate = data.date.split('-').reverse().join('-');
// Determine URL and additional metadata based on collection
switch (coll) {
case 'ddd': // Newspapers
meta.url = `https://resolver.kb.nl/resolve?urn=${data.metadataKey}`;
meta.work = data.papertitle;
break;
case 'dts': // Magazines
// Set URL to the title page
meta.url = data.titlePage;
// Reverse the date format found in data.date
if (data.title.includes(reverseDate)) {
// If an alternative title exists without numbers, use it
if (Array.isArray(data.alternative) && data.alternative.length > 0) {
for (let altTitle of data.alternative) {
if (!/\d/.test(altTitle)) {
meta.title = altTitle;
break;
}
}
} else {
// If no alternative title, remove the date from the current title
meta.title = meta.title.replace(reverseDate, '').trim();
}
}
// Set magazine title
meta.magazine = meta.title;
// Append subtitle if available
if (data.subtitle) {
meta.magazine += `: ${data.subtitle}`;
}
// Set creator and contributors
meta.creator = data.creator || '';
meta.contributors = data.contributor || '';
// Initialize work and issue
meta.work = '';
// Check if issue number exists and add it to title
if (typeof data.issuenumber !== "undefined") {
if (data.issuenumber.startsWith("nr.") || data.issuenumber.startsWith("no.")) {
meta.title += ` ${data.issuenumber}`;
} else {
meta.title += ` nr. ${data.issuenumber}`;
}
meta.issue = data.issuenumber;
}
// Set volume information
meta.volume = data.volumeNumber || '';
// Set volume number if available
if (data.volumeNumber) {
meta.title += ` vol. ${data.volumeNumber}`;
}
// Set title with volume information if available
if (typeof data.volumeNumber !== "undefined") {
meta.title += ` jrg ${data.volumeNumber}`;
} else if (typeof data.volumeYear !== "undefined") {
meta.title += ` jrg ${data.volumeYear}`;
}
// Set year (deprecated?)
meta.year = data.volumeYear || ''; // Is this deprecated? Consider removing if not used.
break;
case 'boeken': // Books
meta.url = data.identifier;
if (data.subtitle){
meta.title += `: ${data.subtitle}`;
}
meta.publisher = data.publisher || '';
meta.location = data.publisherSpatial || '';
meta.creator = data.creator || '';
meta.contributors = data.contributor || '';
break;
default:
break;
}
// Build references
const citeArticle = (coll === 'boeken') ? buildCiteBookTemplate(meta) : buildRef(meta);
// Insert references into the page
meta.url = document.querySelector(".js-share-input-i3").value;
meta.page = meta.url.replace(/.+?0*(\d+)$/,'$1');
meta.title = (meta.page === "1" ? "Voorpagina " : "") + data.title + (meta.page !== "1" ? ' p. '+ meta.page : "");
let citePage = '';
switch (coll) {
case 'ddd': // Newspapers
citePage = buildRef(meta);
break;
case 'dts': // Magazines
citePage = buildMagazineTemplate(meta);
break;
case 'boeken': // Books
citePage = buildCiteBookTemplate(meta);
break;
}
insertLabels("Ref pagina", citePage);
insertLabels(`Ref ${label}`, citeArticle);
}
function splitAndFormatNames(names) {
let result = '';
var one_author = false;
// Ensure meta.contributors is an array
names = names.filter(Boolean)
// Filter out null or undefined values
names.forEach((name, index) => {
if (name.includes(',')) {
const [lastName, firstName] = name.split(", ");
result += `|first${index + 1}= ${htmlEntities(firstName)} |last${index + 1}=${htmlEntities(lastName)} `;
} else if (!one_author) {
result += `|author= ${htmlEntities(name)}`;
one_author = true;
}
});
return result;
}
function buildCiteBookTemplate(meta) {
let contributorFields = splitAndFormatNames([meta.creator , ...(Array.isArray(meta.contributors) ? meta.contributors : [meta.contributors])]);
return `<ref>{{Cite book
| title = ${htmlEntities(meta.title)}
${contributorFields}
| date = ${meta.pubdate || ''}
| publisher = ${meta.publisher || ''}
| location = ${meta.location || ''}
| pages = ${meta.page || ''}
| language = ${meta.language || ''}
| url = ${meta.url}
| access-date = ${today}
}}</ref>`;
}
function buildMagazineTemplate(meta) {
let contributorFields = splitAndFormatNames([meta.creator, ...(Array.isArray(meta.contributors) ? meta.contributors : [meta.contributors])]);
const year_field = meta.year ? `| year = ${meta.year}` : '';
return `<ref>{{Cite magazine
| title = ${htmlEntities(meta.title)}
${contributorFields}
| date = ${meta.pubdate || ''}
| magazine = ${htmlEntities(meta.magazine) || ''}
| issue = ${meta.issue || ''}
| volume = ${meta.volume || ''}
${year_field}
| pages = ${meta.page || ''}
| language = ${meta.language || ''}
| url = ${meta.url}
| access-date = ${today}
}}</ref>`;
}
// Build reference text
function buildRef(meta) {
return `<ref>{{Cite web
| title = ${htmlEntities(meta.title)}
| date = ${meta.pubdate}
| url = ${meta.url}
| work = ${htmlEntities(meta.work)}
| via = Delpher
| accessdate = ${today}
}}</ref>`;
}
// Convert characters to HTML entities
function htmlEntities(str) {
return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
}
// Insert labels into the page
function insertLabels(label, wikitext) {
// For mobile share
const htmlRefPage1 = $('<div/>').html(label_html_mobile(label, wikitext));
$(htmlRefPage1[0]).insertBefore($($('dl')[0]));
// For normal share
const htmlRefPage2 = $('<div/>').html(label_html(label, wikitext));
$(htmlRefPage2[0]).insertBefore($($('div.object-view-menu__share-links-details')[0]));
}
// Generate HTML for normal share label
function label_html(label, input) {
const identifier = Math.random().toString(36).substring(7);
return `<div class="object-view-menu__share-links-details hidden-input" style="display: flex;">
<label for="${identifier}" class="object-view-menu__share-links-details-label">${label}</label>
<div id="${identifier}" class="object-view-menu__share-links-details-link">
<input class="object-view-menu__share-links-details-input input-field" type="text" onclick="this.setSelectionRange(0, this.value.length)" onchange="$(this).val(\'${input}\')" value="${input}" readonly="">
</div>
</div>`;
}
// Generate HTML for mobile share label
function label_html_mobile(label, input) {
return `<label class="metadata__details-label">${label}</label>
<div class="metadata__details-input-wrapper">
<input type="text" class="js-share-input-i5 persistent-id input-field metadata__details-input" onclick="this.setSelectionRange(0, this.value.length)" onchange="$(this).val(\'${input}\')" value="${input}" readonly="">
</div>`;
}
//</nowiki></noinclude>