MediaWiki:MarcEditorDynamicLinks.js: mudanças entre as edições

sem sumário de edição
Sem resumo de edição
Etiqueta: Reversão manual
Sem resumo de edição
/*jshint esversion: 6 */
function main() {
let tag = '';
let tagFromDropdown = '';
 
function createMarcFieldHelpLink() {
const tagInputs = document.body.querySelectorAll('.tagInput');
tagInputs.forEach((elem) => {
const marcFieldHelpLink = document.createElement('a');
marcFieldHelpLink.setAttribute('target', '_blank');
marcFieldHelpLink.innerText = '(?)';
 
const marcFieldHelpLinkClass = elem.closest('table')
.querySelector('.marcFieldHelpLink');
marcFieldHelpLinkClass.innerHTML = "";
marcFieldHelpLinkClass.appendChild(marcFieldHelpLink);
 
// find the tag value from the chosen dropdown
marcFieldHelpLinkClass.addEventListener('mouseover', (event) => {
tagFromDropdown = event.target.closest('.instanceMain')
.querySelector('.oo-ui-inputWidget-input')
.getAttribute('title') || '00x';
tagFromDropdown = tagFromDropdown.substring(0, 3);
marcFieldHelpLink.setAttribute(
'title',
`Documentação do campo ${tagFromDropdown}`
);
// build the URL
if (window.location.href.match(/A\d{6}/)
|| window.location.href.match(/AutRecord/)) {
marcFieldHelpLink.setAttribute(
'href',
`http://marc.febab.org/a${tagFromDropdown}`
);
} else {
marcFieldHelpLink.setAttribute(
'href',
`https://www.loc.gov/marc/bibliographic/bd${tagFromDropdown}.html`
);
}
});
});
}
 
function createAuthorityLinks() {
const inputs = document.body.querySelectorAll('.instanceMain div table .oo-ui-inputWidget-input');
inputs.forEach((elem) => {
const authorityLink = document.createElement('a');
authorityLink.setAttribute('title', 'Abre uma nova aba para criar ou editar um registro de autoridade');
authorityLink.setAttribute('target', '_blank');
authorityLink.innerText = 'Criar registro de autoridade';
authorityLink.style.display = 'none';
 
const createAuthorityLink = elem.closest('table')
.querySelector('.createAuthorityLink');
createAuthorityLink.innerHTML = "";
createAuthorityLink.appendChild(authorityLink);
 
const pattern1 = /\$0\sA\d{6}/;
const pattern2 = /\$0\s\(BN\)\d{9}/;
 
elem.addEventListener('focusout', () => {
// if already recorded
if (pattern1.test(elem.value)) {
// build the URL for Wikincat aut record edit
authorityLink.innerText = 'Editar autoridade';
authorityLink.setAttribute(
'href',
`/wiki/Special:FormEdit/AutRecord/Autoridade:${
elem.value.match(/A\d{6}/)}`
);
} else if (pattern2.test(elem.value)) {
// build the URL for BN aut record view
authorityLink.innerText = 'Ver registro de autoridade na BN';
authorityLink.setAttribute(
'href',
`http://acervo.bn.gov.br/sophia_web/autoridade/detalhe/${
elem.value.match(/\d{9}/)}`
);
} else {
// find the tag value from the chosen dropdown
tagFromDropdown = elem.closest('.instanceMain')
.querySelector('.oo-ui-inputWidget-input')
.getAttribute('title') || '00x';
tagFromDropdown = tagFromDropdown.substring(0, 3);
marcFieldHelpLink.setAttribute(
// find the tag value from checked radio button
'title',
 
`Documentação do campo ${tagFromDropdown}`
const tagFromRadio = elem.closest('.instanceMain')
);
.querySelector('input[origname=\'Field[authorityType]\']:checked')
// build .value;the URL
if (window.location.href.match(/A\d{6}/)
 
|| window.location.href.match(/AutRecord/)) {
const authorityTypes = {
'Pessoa': '100',marcFieldHelpLink.setAttribute(
'Entidade coletiva': '110href',
`http://marc.febab.org/a${tagFromDropdown}`
'Evento': '111',
'Título uniforme': '130',);
} else 'Tópico': '150',{
'Local': '151'marcFieldHelpLink.setAttribute(
}; 'href',
`https://www.loc.gov/marc/bibliographic/bd${tagFromDropdown}.html`
 
if (tagFromRadio in authorityTypes) {;
tag = authorityTypes[tagFromRadio];
}
});
 
});
// declare the indicators default values
}
let ind1 = elem.closest('.instanceMain')
.querySelector('select[origname=\'Field[ind1]\'] option:checked')
function createAuthorityLinks() {
.value;
const let ind2inputs = elemdocument.closestbody.querySelectorAll('.instanceMain div table .oo-ui-inputWidget-input');
inputs.forEach((elem) => {
.querySelector('select[origname=\'Field[ind2]\'] option:checked')
const authorityLink = document.valuecreateElement('a');
authorityLink.setAttribute('title', 'Abre uma nova aba para criar ou editar um registro de autoridade');
 
authorityLink.setAttribute('target', '_blank');
// declare the 008 field default values
authorityLink.innerText = 'Criar registro de autoridade';
let directOrIndirectGeogSubdiv = ''; // 06
let kindOfRecordauthorityLink.style.display = 'none'; // 09
let descriptiveCatalogingRules = 'c'; // 10
const let subjectHeadingSystemcreateAuthorityLink = elem.closest('ntable'; // 11)
let typeOfSeries = .querySelector('n.createAuthorityLink'); // 12
let numberedOrUnnumberedSeriescreateAuthorityLink.innerHTML = 'n'""; // 13
createAuthorityLink.appendChild(authorityLink);
let headingUseMainOrAddedEntry = 'a'; // 14
let headingUseSubjectAddedEntry = 'a'; // 15
const let headingUseSeriesAddedEntrypattern1 = 'b'; /\$0\sA\d{6}/ 16;
const pattern2 = /\$0\s\(BN\)\d{9}/;
let typeOfSubjectSubdivision = 'n'; // 17
let undifferentiatedPersonalName = 'n'; // 32
elem.addEventListener('focusout', () => {
let levelOfEstablishment = 'a'; // 33
// if already recorded
 
if (pattern1.test(elem.value)) {
// set the 008 field and indicadors specific values
if (tag ===// '100')build {the URL for Wikincat aut record edit
undifferentiatedPersonalNameauthorityLink.innerText = 'aEditar autoridade';
ind2 = '';authorityLink.setAttribute(
} 'href',
`/wiki/Special:FormEdit/AutRecord/Autoridade:${
if (tag === '110') {
// in case of autocomplete of 260elem.value.match(/A\d{6}/)}`
if (tagFromDropdown === '260') {;
} else if (pattern2.test(elem.value)) {
directOrIndirectGeogSubdiv = 'n';
// build kindOfRecordthe =URL 'b';for BN aut record view
headingUseMainOrAddedEntryauthorityLink.innerText = 'bVer registro de autoridade na BN';
headingUseSubjectAddedEntry = 'b';authorityLink.setAttribute(
levelOfEstablishment = 'nhref';,
`http://acervo.bn.gov.br/sophia_web/autoridade/detalhe/${
ind1 = '1';
elem.value.match(/\d{9}/)}`
);
} else {
// find the tag value from the chosen dropdown
tagFromDropdown = elem.closest('.instanceMain')
.querySelector('.oo-ui-inputWidget-input')
.getAttribute('title') || '00x';
tagFromDropdown = tagFromDropdown.substring(0, 3);
// find the tag value from checked radio button
const tagFromRadio = elem.closest('.instanceMain')
.querySelector('input[origname=\'Field[authorityType]\']:checked')
.value;
const authorityTypes = {
'Pessoa': '100',
'Entidade coletiva': '110',
'Evento': '111',
'Título uniforme': '130',
'Tópico': '150',
'Local': '151'
};
if (tagFromRadio in authorityTypes) {
tag = authorityTypes[tagFromRadio];
}
ind2 = '';
// declare the indicators default values
}
if (tag ==let ind1 = elem.closest('111.instanceMain') {
.querySelector('select[origname=\'Field[ind1]\'] option:checked')
ind1 = '2';
ind2 = ''.value;
let ind2 = elem.closest('.instanceMain')
}
.querySelector('select[origname=\'Field[ind2]\'] option:checked')
if (tag === '130') {
typeOfSeries = 'a'.value;
numberedOrUnnumberedSeries = 'b';
// declare the 008 field default values
headingUseSeriesAddedEntry = 'a';
iflet (tagFromDropdowndirectOrIndirectGeogSubdiv === '130'; // 06
let || tagFromDropdownkindOfRecord === '630'; // 09
let || tagFromDropdowndescriptiveCatalogingRules === '730c'); // {10
let ind2subjectHeadingSystem = ind1'n'; // an inverted value happens here, see and11
let ind1typeOfSeries = 'n'; // compare bib. and auth. 130 MARC definitions12
let numberedOrUnnumberedSeries = 'n'; // 13
let headingUseMainOrAddedEntry = 'a'; // 14
let headingUseSubjectAddedEntry = 'a'; // 15
let headingUseSeriesAddedEntry = 'b'; // 16
let typeOfSubjectSubdivision = 'n'; // 17
let undifferentiatedPersonalName = 'n'; // 32
let levelOfEstablishment = 'a'; // 33
// set the 008 field and indicadors specific values
if (tag === '100') {
undifferentiatedPersonalName = 'a';
ind2 = '';
}
ind1if (tag === '110';) {
} // in case of autocomplete of 260
if (tag === '150' ||if tag(tagFromDropdown === '151260') {
descriptiveCatalogingRules directOrIndirectGeogSubdiv = 'n';
subjectHeadingSystem kindOfRecord = 'zb';
headingUseMainOrAddedEntry = 'b';
headingUseSubjectAddedEntry = 'b';
ind1 = ''; // 150 and 151 indicators must be empty in
ind2 = ''; // authoritylevelOfEstablishment MARC= records'n';
if (tag == ind1 = '1511') {;
typeOfSubjectSubdivision = 'd';}
ind2 = '';
}
} if (tag === '111') {
// build the URL ind1 = '2';
const autRecordParams ind2 = {'';
AutRecord: {}
if (tag directOrIndirectGeogSubdiv,=== '130') {
kindOfRecord,typeOfSeries = 'a';
descriptiveCatalogingRules,numberedOrUnnumberedSeries = 'b';
subjectHeadingSystem,headingUseSeriesAddedEntry = 'a';
typeOfSeries,if (tagFromDropdown === '130'
numberedOrUnnumberedSeries, || tagFromDropdown === '630'
headingUseMainOrAddedEntry, || tagFromDropdown === '730') {
headingUseSubjectAddedEntry ind2 = ind1; // an inverted value happens here, see and
ind1 = ''; // compare bib. and auth. 130 MARC definitions
headingUseSeriesAddedEntry,
typeOfSubjectSubdivision,}
undifferentiatedPersonalName,ind1 = '';
levelOfEstablishment}
},if (tag === '150' || tag === '151') {
Field: { descriptiveCatalogingRules = 'n';
subjectHeadingSystem = '1z': {;
headingUseMainOrAddedEntry tag:= '040b',;
ind1 data:= '$a'; BR-FlWIK// $b150 porand $c151 BR-FlWIKindicators $dmust BR-FlUSC'be empty in
ind2 = ''; // authority MARC records
if (tag === '151') {
typeOfSubjectSubdivision = 'd';
}
}
// build the URL
const autRecordParams = {
AutRecord: {
directOrIndirectGeogSubdiv,
kindOfRecord,
descriptiveCatalogingRules,
subjectHeadingSystem,
typeOfSeries,
numberedOrUnnumberedSeries,
headingUseMainOrAddedEntry,
headingUseSubjectAddedEntry,
headingUseSeriesAddedEntry,
typeOfSubjectSubdivision,
undifferentiatedPersonalName,
levelOfEstablishment
},
'2'Field: {
tag,'1': {
ind1 tag: '040',
ind2, data: '$a BR-FlWIK $b por $c BR-FlWIK $d BR-FlUSC'
data: elem.value},
}, '2': {
'3': { tag,
tag: '670' ind1,
data: '$a 'ind2,
data: elem.value
},
'3': {
tag: '670',
data: '$a '
}
}
};
};
const url = new URL(`${window.location.origin}/wiki/Special:FormEdit/AutRecord`);
 
// function to transform a 3rd level object to URL query strings
const url = new URL(`${window.location.origin}/wiki/Special:FormEdit/AutRecord`);
// function toconst transformmakeUrlParams a= 3rd(obj) level=> object to URL query strings{
for (const makeUrlParams[key, =value] of Object.entries(obj) =>) {
for (const [key, value] ofif Object.entries(obj)typeof value === 'object') {
if for (typeofconst value[key2, ===value2] 'object'of Object.entries(value)) {
for (const [key2, value2] ofif Object.entries(value)typeof value2 === 'object') {
if for (typeofconst value2[key3, ===value3] 'object'of Object.entries(value2)) {
for (const url.searchParams.set(`${key}[${key2}][${key3}]`, value3] of Object.entries(value2)) {;
url.searchParams.set(`${key}[${key2}][${key3}]`, value3);
} else {
url.searchParams.set(`${key}[${key2}]`, value2);
}
} else {
url.searchParams.set(`${key}[${key2}]`, value2);
}
} else {
url.searchParams.set(key, value);
}
} else {
url.searchParams.set(key, value);
}
};
} makeUrlParams(autRecordParams);
authorityLink.innerText = 'Criar registro de autoridade';
makeUrlParams(autRecordParams);
authorityLink.setAttribute('href', url.pathname + url.search);
authorityLink.innerText = 'Criar registro de autoridade';
}
authorityLink.setAttribute('href', url.pathname + url.search);
authorityLink.style.display = '';
}
authorityLink.style.display = ''});
});
});
}
function rmCarriageReturn() {
 
const textareas = document.body.querySelectorAll('textarea');
function rmCarriageReturn() {
const textareas = documenttextareas.body.querySelectorAllforEach(('textarea'); => {
const element = textarea;
textareas.forEach((textarea) => {
const element.value = textareaelement.value.replace('
', '');
});
element.value = element.value.replace('
', '');
});
}
function rmHtmlTags() {
 
const textareas = document.body.querySelectorAll('textarea');
function rmHtmlTags() {
const textareas = documenttextareas.body.querySelectorAllforEach(('textarea'); => {
const element = textarea;
textareas.forEach((textarea) => {
element.value = element.value.replace(/<(?:"[^"]*"['"]*|'[^']*'['"]*|[^'">])+>/g, '');
const element = textarea;
});
element.value = element.value.replace(/<(?:"[^"]*"['"]*|'[^']*'['"]*|[^'">])+>/g, '');
});
}
function rmTxtFromHiddenFields() {
 
const spans = document.body.querySelectorAll('span.hiddenByPF');
function rmTxtFromHiddenFields() {
spans.forEach((elem) => {
const spans = document.body.querySelectorAll('span.hiddenByPF');
spans elem.querySelectorAll('.input.oo-ui-inputWidget-input').forEach((eleminput) => {
const element = input;
elem.querySelectorAll('.input.oo-ui-inputWidget-input').forEach((input) => {
const element.value = input'';
element.value = ''});
elem.querySelectorAll('textarea').forEach((input) => {
const element = input;
element.value = '';
});
});
}
elem.querySelectorAll('textarea').forEach((input) => {
const element = input;
function normalizeInput() {
element.value = '';
const instanceMains = document.body.querySelectorAll('.instanceMain div table');
instanceMains.forEach((instanceMain) => {
instanceMain.querySelectorAll('.oo-ui-inputWidget-input').forEach((input) => {
const normalizedInput = input;
normalizedInput.value = normalizedInput.value
// "$a Bar \n$b Baz" > " $a Bar $b Baz"
.replace(/\s*(\$[a-z0-8])\s*/g, ' $1 ')
// "$a Bar\nFoo" > "$a Bar Foo" ou "$a Bar Foo" > "$a Bar Foo"
.replace(/\n|\s\s+|\t/g, ' ')
// replace "|" by "%7C" (Ex.: http://viaf.org/processed/WKP|Q2484404)
.replace('|', '%7C');
});
instanceMain.querySelectorAll('textarea').forEach((textarea) => {
const normalizedInput = textarea;
textarea.value = normalizedInput.value
// "$a Bar \n$b Baz" > " $a Bar $b Baz"
.replace(/\s*(\$[a-z0-8])\s*/g, ' $1 ')
// "$a Bar\nFoo" > "$a Bar Foo" ou "$a Bar Foo" > "$a Bar Foo"
.replace(/\n|\s\s+|\t/g, ' ')
// replace "|" by "%7C" (Ex.: http://viaf.org/processed/WKP|Q2484404)
.replace('|', '%7C');
});
});
}
// calls main functions
createMarcFieldHelpLink();
createAuthorityLinks();
rmCarriageReturn();
rmHtmlTags();
// Como instâncias do formulário são criadas pelo botão "Adicionar campo",
// é necessário observar o DOM a partir da classe ".multipleTemplateList".
// Toda vez que o DOM é alterado (mais especificamente, quando uma nova
// child de ".multipleTemplateList" é criada), as funções
// createMarcFieldHelpLink() e createAuthorityLinks() são novamente chamadas.
// https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
// create an observer instance
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
const newNodes = mutation.addedNodes; // DOM NodeList
if (newNodes.length !== 0) { // if there are new nodes added
createMarcFieldHelpLink();
createAuthorityLinks();
}
});
});
}
// select the target node
const target = document.querySelector('.multipleTemplateList');
// configuration of the observer
const config = {
childList: true,
attributes: false,
subtree: false,
};
// pass in the target node, as well as the observer options
observer.observe(target, config);
 
// when clicking save...
function normalizeInput() {
const instanceMainssaveBtn = document.body.querySelectorAllquerySelector('.instanceMain div table#wpSave');
instanceMainssaveBtn.forEachaddEventListener('click', (instanceMain) => {
observer.disconnect();
instanceMain.querySelectorAll('.oo-ui-inputWidget-input').forEach((input) => {
rmTxtFromHiddenFields();
const normalizedInput = input;
rmCarriageReturn();
normalizedInput.value = normalizedInput.value
rmHtmlTags();
// "$a Bar \n$b Baz" > " $a Bar $b Baz"
normalizeInput();
.replace(/\s*(\$[a-z0-8])\s*/g, ' $1 ')
// "$a Bar\nFoo" > "$a Bar Foo" ou "$a Bar Foo" > "$a Bar Foo"
.replace(/\n|\s\s+|\t/g, ' ')
// replace "|" by "%7C" (Ex.: http://viaf.org/processed/WKP|Q2484404)
.replace('|', '%7C');
});
instanceMain.querySelectorAll('textarea').forEach((textarea) => {
const normalizedInput = textarea;
textarea.value = normalizedInput.value
// "$a Bar \n$b Baz" > " $a Bar $b Baz"
.replace(/\s*(\$[a-z0-8])\s*/g, ' $1 ')
// "$a Bar\nFoo" > "$a Bar Foo" ou "$a Bar Foo" > "$a Bar Foo"
.replace(/\n|\s\s+|\t/g, ' ')
// replace "|" by "%7C" (Ex.: http://viaf.org/processed/WKP|Q2484404)
.replace('|', '%7C');
});
});
}
// when clicking adding field...
 
const addBtn = document.body.querySelector('.multipleTemplateAdder');
// calls main functions
addBtn.addEventListener('click', () => {
createMarcFieldHelpLink();
createAuthorityLinks();
rmCarriageReturn();
rmHtmlTags();
 
// Como instâncias do formulário são criadas pelo botão "Adicionar campo",
// é necessário observar o DOM a partir da classe ".multipleTemplateList".
// Toda vez que o DOM é alterado (mais especificamente, quando uma nova
// child de ".multipleTemplateList" é criada), as funções
// createMarcFieldHelpLink() e createAuthorityLinks() são novamente chamadas.
// https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
 
// create an observer instance
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
const newNodes = mutation.addedNodes; // DOM NodeList
if (newNodes.length !== 0) { // if there are new nodes added
createMarcFieldHelpLink();
createAuthorityLinks();
}
});
});
 
// select the target node
const target = document.querySelector('.multipleTemplateList');
 
// configuration of the observer
const config = {
childList: true,
attributes: false,
subtree: false,
};
 
// pass in the target node, as well as the observer options
observer.observe(target, config);
 
// when clicking save...
const saveBtn = document.body.querySelector('#wpSave');
saveBtn.addEventListener('click', () => {
observer.disconnect();
rmTxtFromHiddenFields();
rmCarriageReturn();
rmHtmlTags();
normalizeInput();
});
}
 
if (document.readyState === 'complete' || (document.readyState !== 'loading')) {
main();
} else {
document.addEventListener('DOMContentLoaded', main);
}