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

De Wikincat
Ir para navegação Ir para pesquisar
Sem resumo de edição
Etiqueta: Revertido
Sem resumo de edição
Etiqueta: Reversão manual
Linha 3: Linha 3:
/*jshint esversion: 6 */
/*jshint esversion: 6 */
function main() {
function main() {
let tag = '';
let tag = '';
let tagFromDropdown = '';
let tagFromDropdown = '';

function createMarcFieldHelpLink() {
function createMarcFieldHelpLink() {
const tagInputs = document.body.querySelectorAll('.tagInput');
const tagInputs = document.body.querySelectorAll('.tagInput');
tagInputs.forEach((elem) => {
tagInputs.forEach((elem) => {
const marcFieldHelpLink = document.createElement('a');
const marcFieldHelpLink = document.createElement('a');
marcFieldHelpLink.setAttribute('target', '_blank');
marcFieldHelpLink.setAttribute('target', '_blank');
marcFieldHelpLink.innerText = '(?)';
marcFieldHelpLink.innerText = '(?)';

const marcFieldHelpLinkClass = elem.closest('table')
const marcFieldHelpLinkClass = elem.closest('table')
.querySelector('.marcFieldHelpLink');
.querySelector('.marcFieldHelpLink');
marcFieldHelpLinkClass.innerHTML = "";
marcFieldHelpLinkClass.innerHTML = "";
marcFieldHelpLinkClass.appendChild(marcFieldHelpLink);
marcFieldHelpLinkClass.appendChild(marcFieldHelpLink);

// find the tag value from the chosen dropdown
// find the tag value from the chosen dropdown
marcFieldHelpLinkClass.addEventListener('mouseover', (event) => {
marcFieldHelpLinkClass.addEventListener('mouseover', (event) => {
tagFromDropdown = event.target.closest('.instanceMain')
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')
.querySelector('.oo-ui-inputWidget-input')
.getAttribute('title') || '00x';
.getAttribute('title') || '00x';
tagFromDropdown = tagFromDropdown.substring(0, 3);
tagFromDropdown = tagFromDropdown.substring(0, 3);
// find the tag value from checked radio button
marcFieldHelpLink.setAttribute(

'title',
const tagFromRadio = elem.closest('.instanceMain')
`Documentação do campo ${tagFromDropdown}`
.querySelector('input[origname=\'Field[authorityType]\']:checked')
);
// build the URL
.value;

if (window.location.href.match(/A\d{6}/)
const authorityTypes = {
|| window.location.href.match(/AutRecord/)) {
marcFieldHelpLink.setAttribute(
'Pessoa': '100',
'href',
'Entidade coletiva': '110',
'Evento': '111',
`http://marc.febab.org/a${tagFromDropdown}`
);
'Título uniforme': '130',
} else {
'Tópico': '150',
marcFieldHelpLink.setAttribute(
'Local': '151'
'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')
.value;
function createAuthorityLinks() {
const inputs = document.body.querySelectorAll('.instanceMain div table .oo-ui-inputWidget-input');
let ind2 = elem.closest('.instanceMain')
.querySelector('select[origname=\'Field[ind2]\'] option:checked')
inputs.forEach((elem) => {
const authorityLink = document.createElement('a');
.value;

authorityLink.setAttribute('title', 'Abre uma nova aba para criar ou editar um registro de autoridade');
// declare the 008 field default values
authorityLink.setAttribute('target', '_blank');
let directOrIndirectGeogSubdiv = ''; // 06
authorityLink.innerText = 'Criar registro de autoridade';
authorityLink.style.display = 'none';
let kindOfRecord = ''; // 09
let descriptiveCatalogingRules = 'c'; // 10
const createAuthorityLink = elem.closest('table')
let subjectHeadingSystem = 'n'; // 11
.querySelector('.createAuthorityLink');
let typeOfSeries = 'n'; // 12
createAuthorityLink.innerHTML = "";
let numberedOrUnnumberedSeries = 'n'; // 13
let headingUseMainOrAddedEntry = 'a'; // 14
createAuthorityLink.appendChild(authorityLink);
let headingUseSubjectAddedEntry = 'a'; // 15
const pattern1 = /\$0\sA\d{6}/;
let headingUseSeriesAddedEntry = 'b'; // 16
let typeOfSubjectSubdivision = 'n'; // 17
const pattern2 = /\$0\s\(BN\)\d{9}/;
let undifferentiatedPersonalName = 'n'; // 32
let levelOfEstablishment = 'a'; // 33
elem.addEventListener('focusout', () => {

// if already recorded
// set the 008 field and indicadors specific values
if (pattern1.test(elem.value)) {
// build the URL for Wikincat aut record edit
if (tag === '100') {
authorityLink.innerText = 'Editar autoridade';
undifferentiatedPersonalName = 'a';
authorityLink.setAttribute(
ind2 = '';
'href',
}
if (tag === '110') {
`/wiki/Special:FormEdit/AutRecord/Autoridade:${
elem.value.match(/A\d{6}/)}`
// in case of autocomplete of 260
);
if (tagFromDropdown === '260') {
directOrIndirectGeogSubdiv = 'n';
} else if (pattern2.test(elem.value)) {
// build the URL for BN aut record view
kindOfRecord = 'b';
authorityLink.innerText = 'Ver registro de autoridade na BN';
headingUseMainOrAddedEntry = 'b';
authorityLink.setAttribute(
headingUseSubjectAddedEntry = 'b';
'href',
levelOfEstablishment = 'n';
ind1 = '1';
`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);
// 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
let ind1 = elem.closest('.instanceMain')
if (tag === '111') {
ind1 = '2';
.querySelector('select[origname=\'Field[ind1]\'] option:checked')
.value;
ind2 = '';
}
let ind2 = elem.closest('.instanceMain')
if (tag === '130') {
.querySelector('select[origname=\'Field[ind2]\'] option:checked')
.value;
typeOfSeries = 'a';
numberedOrUnnumberedSeries = 'b';
headingUseSeriesAddedEntry = 'a';
// declare the 008 field default values
let directOrIndirectGeogSubdiv = ''; // 06
if (tagFromDropdown === '130'
let kindOfRecord = ''; // 09
|| tagFromDropdown === '630'
let descriptiveCatalogingRules = 'c'; // 10
|| tagFromDropdown === '730') {
let subjectHeadingSystem = 'n'; // 11
ind2 = ind1; // an inverted value happens here, see and
let typeOfSeries = 'n'; // 12
ind1 = ''; // compare bib. and auth. 130 MARC definitions
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 = '';
}
}
if (tag === '110') {
ind1 = '';
// in case of autocomplete of 260
}
if (tagFromDropdown === '260') {
if (tag === '150' || tag === '151') {
directOrIndirectGeogSubdiv = 'n';
descriptiveCatalogingRules = 'n';
kindOfRecord = 'b';
subjectHeadingSystem = 'z';
headingUseMainOrAddedEntry = 'b';
headingUseMainOrAddedEntry = 'b';
ind1 = ''; // 150 and 151 indicators must be empty in
headingUseSubjectAddedEntry = 'b';
levelOfEstablishment = 'n';
ind2 = ''; // authority MARC records
ind1 = '1';
if (tag === '151') {
}
typeOfSubjectSubdivision = 'd';
ind2 = '';
}
}
if (tag === '111') {
}
ind1 = '2';
// build the URL
ind2 = '';
const autRecordParams = {
}
AutRecord: {
if (tag === '130') {
directOrIndirectGeogSubdiv,
typeOfSeries = 'a';
kindOfRecord,
numberedOrUnnumberedSeries = 'b';
descriptiveCatalogingRules,
headingUseSeriesAddedEntry = 'a';
subjectHeadingSystem,
if (tagFromDropdown === '130'
typeOfSeries,
|| tagFromDropdown === '630'
numberedOrUnnumberedSeries,
|| tagFromDropdown === '730') {
headingUseMainOrAddedEntry,
ind2 = ind1; // an inverted value happens here, see and
headingUseSubjectAddedEntry,
headingUseSeriesAddedEntry,
ind1 = ''; // compare bib. and auth. 130 MARC definitions
}
typeOfSubjectSubdivision,
ind1 = '';
undifferentiatedPersonalName,
}
levelOfEstablishment
if (tag === '150' || tag === '151') {
},
descriptiveCatalogingRules = 'n';
Field: {
subjectHeadingSystem = 'z';
'1': {
headingUseMainOrAddedEntry = 'b';
tag: '040',
ind1 = ''; // 150 and 151 indicators must be empty in
data: '$a BR-FlWIK $b por $c BR-FlWIK $d BR-FlUSC'
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
},
},
Field: {
'2': {
'1': {
tag,
tag: '040',
ind1,
data: '$a BR-FlWIK $b por $c BR-FlWIK $d BR-FlUSC'
ind2,
},
data: elem.value
'2': {
},
tag,
'3': {
ind1,
tag: '670',
ind2,
data: '$a '
data: elem.value
},
'3': {
tag: '670',
data: '$a '
}
}
}
};
}
};

const url = new URL(`${window.location.origin}/wiki/Special:FormEdit/AutRecord`);
const url = new URL(`${window.location.origin}/wiki/Special:FormEdit/AutRecord`);
// function to transform a 3rd level object to URL query strings
const makeUrlParams = (obj) => {
// function to transform a 3rd level object to URL query strings
for (const [key, value] of Object.entries(obj)) {
const makeUrlParams = (obj) => {
if (typeof value === 'object') {
for (const [key, value] of Object.entries(obj)) {
for (const [key2, value2] of Object.entries(value)) {
if (typeof value === 'object') {
if (typeof value2 === 'object') {
for (const [key2, value2] of Object.entries(value)) {
for (const [key3, value3] of Object.entries(value2)) {
if (typeof value2 === 'object') {
url.searchParams.set(`${key}[${key2}][${key3}]`, value3);
for (const [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);
};
makeUrlParams(autRecordParams);
authorityLink.innerText = 'Criar registro de autoridade';
authorityLink.innerText = 'Criar registro de autoridade';
authorityLink.setAttribute('href', url.pathname + url.search);
authorityLink.setAttribute('href', url.pathname + url.search);
}
}
authorityLink.style.display = '';
});
authorityLink.style.display = '';
});
});
}
});
}

function rmCarriageReturn() {
function rmCarriageReturn() {
const textareas = document.body.querySelectorAll('textarea');
textareas.forEach((textarea) => {
const textareas = document.body.querySelectorAll('textarea');
textareas.forEach((textarea) => {
const element = textarea;
element.value = element.value.replace('
', '');
const element = textarea;
element.value = element.value.replace('
', '');
});
}

function rmHtmlTags() {
const textareas = document.body.querySelectorAll('textarea');
textareas.forEach((textarea) => {
const element = textarea;
element.value = element.value.replace(/<(?:"[^"]*"['"]*|'[^']*'['"]*|[^'">])+>/g, '');
});
}

function rmTxtFromHiddenFields() {
const spans = document.body.querySelectorAll('span.hiddenByPF');
spans.forEach((elem) => {
elem.querySelectorAll('.input.oo-ui-inputWidget-input').forEach((input) => {
const element = input;
element.value = '';
});
});
elem.querySelectorAll('textarea').forEach((input) => {
}
const element = input;
element.value = '';
function rmHtmlTags() {
const textareas = document.body.querySelectorAll('textarea');
textareas.forEach((textarea) => {
const element = textarea;
element.value = element.value.replace(/<(?:"[^"]*"['"]*|'[^']*'['"]*|[^'">])+>/g, '');
});
}
function rmTxtFromHiddenFields() {
const spans = document.body.querySelectorAll('span.hiddenByPF');
spans.forEach((elem) => {
elem.querySelectorAll('.input.oo-ui-inputWidget-input').forEach((input) => {
const element = input;
element.value = '';
});
elem.querySelectorAll('textarea').forEach((input) => {
const element = input;
element.value = '';
});
});
}
function normalizeInput() {
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
function normalizeInput() {
const target = document.querySelector('.multipleTemplateList');
const instanceMains = document.body.querySelectorAll('.instanceMain div table');
instanceMains.forEach((instanceMain) => {
// configuration of the observer
instanceMain.querySelectorAll('.oo-ui-inputWidget-input').forEach((input) => {
const config = {
const normalizedInput = input;
childList: true,
normalizedInput.value = normalizedInput.value
attributes: false,
// "$a Bar \n$b Baz" > " $a Bar $b Baz"
subtree: false,
.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, ' ')
// pass in the target node, as well as the observer options
// replace "|" by "%7C" (Ex.: http://viaf.org/processed/WKP|Q2484404)
observer.observe(target, config);
.replace('|', '%7C');
});
// when clicking save...
instanceMain.querySelectorAll('textarea').forEach((textarea) => {
const saveBtn = document.body.querySelector('#wpSave');
const normalizedInput = textarea;
saveBtn.addEventListener('click', () => {
textarea.value = normalizedInput.value
observer.disconnect();
// "$a Bar \n$b Baz" > " $a Bar $b Baz"
rmTxtFromHiddenFields();
.replace(/\s*(\$[a-z0-8])\s*/g, ' $1 ')
rmCarriageReturn();
// "$a Bar\nFoo" > "$a Bar Foo" ou "$a Bar Foo" > "$a Bar Foo"
rmHtmlTags();
.replace(/\n|\s\s+|\t/g, ' ')
normalizeInput();
// 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...
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);
}
}

// if (document.readyState === 'complete' || (document.readyState !== 'loading')) {
// main();
// } else {
// document.addEventListener('DOMContentLoaded', main);
// }
// for no obvious reason to me, the first call to the "main" function is not
// for no obvious reason to me, the first call to the "main" function is not
// occurring, so wait 3 seconds and call it anyway.
// occurring, so wait 3 seconds and call it anyway.
setInterval(main, 3000);
setTimeout(main, 3000);

Edição das 13h14min de 14 de março de 2024

// Author: @vitorsilverio
// Author: @jaideraf
/*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);
          // 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];
          }

          // declare the indicators default values
          let ind1 = elem.closest('.instanceMain')
            .querySelector('select[origname=\'Field[ind1]\'] option:checked')
            .value;
          let ind2 = elem.closest('.instanceMain')
            .querySelector('select[origname=\'Field[ind2]\'] option:checked')
            .value;

          // declare the 008 field default values
          let directOrIndirectGeogSubdiv = ''; // 06
          let kindOfRecord = ''; // 09
          let descriptiveCatalogingRules = 'c'; // 10
          let subjectHeadingSystem = 'n'; // 11
          let typeOfSeries = 'n'; // 12
          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 = '';
          }
          if (tag === '110') {
            // in case of autocomplete of 260
            if (tagFromDropdown === '260') {
              directOrIndirectGeogSubdiv = 'n';
              kindOfRecord = 'b';
              headingUseMainOrAddedEntry = 'b';
              headingUseSubjectAddedEntry = 'b';
              levelOfEstablishment = 'n';
              ind1 = '1';
            }
            ind2 = '';
          }
          if (tag === '111') {
            ind1 = '2';
            ind2 = '';
          }
          if (tag === '130') {
            typeOfSeries = 'a';
            numberedOrUnnumberedSeries = 'b';
            headingUseSeriesAddedEntry = 'a';
            if (tagFromDropdown === '130'
                            || tagFromDropdown === '630'
                            || tagFromDropdown === '730') {
              ind2 = ind1; // an inverted value happens here, see and
              ind1 = ''; // compare bib. and auth. 130 MARC definitions
            }
            ind1 = '';
          }
          if (tag === '150' || tag === '151') {
            descriptiveCatalogingRules = 'n';
            subjectHeadingSystem = 'z';
            headingUseMainOrAddedEntry = 'b';
            ind1 = ''; // 150 and 151 indicators must 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
            },
            Field: {
              '1': {
                tag: '040',
                data: '$a BR-FlWIK $b por $c BR-FlWIK $d BR-FlUSC'
              },
              '2': {
                tag,
                ind1,
                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 makeUrlParams = (obj) => {
            for (const [key, value] of Object.entries(obj)) {
              if (typeof value === 'object') {
                for (const [key2, value2] of Object.entries(value)) {
                  if (typeof value2 === 'object') {
                    for (const [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, value);
              }
            }
          };
          makeUrlParams(autRecordParams);
          authorityLink.innerText = 'Criar registro de autoridade';
          authorityLink.setAttribute('href', url.pathname + url.search);
        }
        authorityLink.style.display = '';
      });
    });
  }

  function rmCarriageReturn() {
    const textareas = document.body.querySelectorAll('textarea');
    textareas.forEach((textarea) => {
      const element = textarea;
      element.value = element.value.replace('&#13;', '');
    });
  }

  function rmHtmlTags() {
    const textareas = document.body.querySelectorAll('textarea');
    textareas.forEach((textarea) => {
      const element = textarea;
      element.value = element.value.replace(/<(?:"[^"]*"['"]*|'[^']*'['"]*|[^'">])+>/g, '');
    });
  }

  function rmTxtFromHiddenFields() {
    const spans = document.body.querySelectorAll('span.hiddenByPF');
    spans.forEach((elem) => {
      elem.querySelectorAll('.input.oo-ui-inputWidget-input').forEach((input) => {
        const element = input;
        element.value = '';
      });
      elem.querySelectorAll('textarea').forEach((input) => {
        const element = input;
        element.value = '';
      });
    });
  }

  function normalizeInput() {
    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...
  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);
}

// for no obvious reason to me, the first call to the "main" function is not 
// occurring, so wait 3 seconds and call it anyway.
setTimeout(main, 3000);