B000004 e MediaWiki:MarcEditorDynamicLinks.js: mudanças entre as páginas

De Wikincat
(Diferenças entre páginas)
Ir para navegação Ir para pesquisar
Sem resumo de edição
 
Sem resumo de edição
 
Linha 1: Linha 1:
// Author: @vitorsilverio
{{BibRecord
// Author: @jaideraf
|dateEnteredOnFile=030415
/*jshint esversion: 6 */
|recordStatus=n
function main() {
|typeOfRecord=a
let tag = '';
|bibliographicLevel=m
let tagFromDropdown = '';
|encodingLevel= 
|descriptiveCatalogingForm=a
function createMarcFieldHelpLink() {
|multipartResourceRecordLevel= 
const tagInputs = document.body.querySelectorAll('.tagInput');
|controlField006=
tagInputs.forEach((elem) => {
|controlField007=
const marcFieldHelpLink = document.createElement('a');
|typeOfDate=s
marcFieldHelpLink.setAttribute('target', '_blank');
|date1=2000
marcFieldHelpLink.innerText = '(?)';
|date2=
|placeOfPublication=spb
const marcFieldHelpLinkClass = elem.closest('table')
|illustrations=a
.querySelector('.marcFieldHelpLink');
|targetAudience=g
marcFieldHelpLinkClass.innerHTML = "";
|formOfItem= 
marcFieldHelpLinkClass.appendChild(marcFieldHelpLink);
|natureOfContents= 
|governmentPublication= 
// find the tag value from the chosen dropdown
|conferencePublication= 
marcFieldHelpLinkClass.addEventListener('mouseover', (event) => {
|festschrift= 
tagFromDropdown = event.target.closest('.instanceMain')
|index= 
.querySelector('.oo-ui-inputWidget-input')
|literaryForm=1
.getAttribute('title') || '00x';
|biography=d
tagFromDropdown = tagFromDropdown.substring(0, 3);
|language=por
marcFieldHelpLink.setAttribute(
|modifiedRecord= 
'title',
|catalogingSource=d
`Documentação do campo ${tagFromDropdown}`
}}
);
{{Field
// build the URL
|tag=020
if (window.location.href.match(/A\d{6}/)
|authorityType=Nenhuma
|| window.location.href.match(/AutRecord/)) {
|ind1=#
marcFieldHelpLink.setAttribute(
|ind2=#
'href',
|data=$a 8533613377 $q v. 1
`http://marc.febab.org/a${tagFromDropdown}`
|authorityData100=
);
|authorityData110=
} else {
|authorityData111=
marcFieldHelpLink.setAttribute(
|authorityData130=
'href',
|authorityData150=
`https://www.loc.gov/marc/bibliographic/bd${tagFromDropdown}.html`
|authorityData151=
);
}}
}
{{Field
});
|tag=020
});
|authorityType=Nenhuma
}
|ind1=#
|ind2=#
function createAuthorityLinks() {
|data=$a 9788533613379 $q reimpr.
const inputs = document.body.querySelectorAll('.instanceMain div table .oo-ui-inputWidget-input');
|authorityData100=
inputs.forEach((elem) => {
|authorityData110=
const authorityLink = document.createElement('a');
|authorityData111=
authorityLink.setAttribute('title', 'Abre uma nova aba para criar ou editar um registro de autoridade');
|authorityData130=
authorityLink.setAttribute('target', '_blank');
|authorityData150=
authorityLink.innerText = 'Criar registro de autoridade';
|authorityData151=
authorityLink.style.display = 'none';
}}
{{Field
const createAuthorityLink = elem.closest('table')
|tag=020
.querySelector('.createAuthorityLink');
|authorityType=Nenhuma
createAuthorityLink.innerHTML = "";
|ind1=#
createAuthorityLink.appendChild(authorityLink);
|ind2=#
|data=$a 9788533613386 $q reimpr.
const pattern1 = /\$0\sA\d{6}/;
|authorityData100=
const pattern2 = /\$0\s\(BN\)\d{9}/;
|authorityData110=
|authorityData111=
elem.addEventListener('focusout', () => {
|authorityData130=
// if already recorded
|authorityData150=
if (pattern1.test(elem.value)) {
|authorityData151=
// build the URL for Wikincat aut record edit
}}
authorityLink.innerText = 'Editar autoridade';
{{Field
authorityLink.setAttribute(
|tag=020
'href',
|authorityType=Nenhuma
`/wiki/Special:FormEdit/AutRecord/Autoridade:${
|ind1=#
elem.value.match(/A\d{6}/)}`
|ind2=#
);
|data=$a 8533613385 $q v. 2
} else if (pattern2.test(elem.value)) {
|authorityData100=
// build the URL for BN aut record view
|authorityData110=
authorityLink.innerText = 'Ver registro de autoridade na BN';
|authorityData111=
authorityLink.setAttribute(
|authorityData130=
'href',
|authorityData150=
`http://acervo.bn.gov.br/sophia_web/autoridade/detalhe/${
|authorityData151=
elem.value.match(/\d{9}/)}`
}}
);
{{Field
} else {
|tag=020
// find the tag value from the chosen dropdown
|authorityType=Nenhuma
tagFromDropdown = elem.closest('.instanceMain')
|ind1=#
.querySelector('.oo-ui-inputWidget-input')
|ind2=#
.getAttribute('title') || '00x';
|data=$a 8533613393 $q v. 3
tagFromDropdown = tagFromDropdown.substring(0, 3);
|authorityData100=
// find the tag value from checked radio button
|authorityData110=
|authorityData111=
const tagFromRadio = elem.closest('.instanceMain')
|authorityData130=
.querySelector('input[origname=\'Field[authorityType]\']:checked')
|authorityData150=
.value;
|authorityData151=
}}
const authorityTypes = {
{{Field
'Pessoa': '100',
|tag=035
'Entidade coletiva': '110',
|authorityType=Nenhuma
'Evento': '111',
|ind1=#
'Título uniforme': '130',
|ind2=#
'Tópico': '150',
|data=$a (BIBLIODATA)SC000644855
'Local': '151'
|authorityData100=
};
|authorityData110=
|authorityData111=
if (tagFromRadio in authorityTypes) {
|authorityData130=
tag = authorityTypes[tagFromRadio];
|authorityData150=
}
|authorityData151=
}}
// declare the indicators default values
{{Field
let ind1 = elem.closest('.instanceMain')
|tag=040
.querySelector('select[origname=\'Field[ind1]\'] option:checked')
|authorityType=Nenhuma
.value;
|ind1=#
let ind2 = elem.closest('.instanceMain')
|ind2=#
.querySelector('select[origname=\'Field[ind2]\'] option:checked')
|data=$a BR-FlUSC $c BR-FlUSC $d BR-FlWIK
.value;
|authorityData100=
|authorityData110=
// declare the 008 field default values
|authorityData111=
let directOrIndirectGeogSubdiv = ''; // 06
|authorityData130=
let kindOfRecord = ''; // 09
|authorityData150=
let descriptiveCatalogingRules = 'c'; // 10
|authorityData151=
let subjectHeadingSystem = 'n'; // 11
}}
let typeOfSeries = 'n'; // 12
{{Field
let numberedOrUnnumberedSeries = 'n'; // 13
|tag=041
let headingUseMainOrAddedEntry = 'a'; // 14
|authorityType=Nenhuma
let headingUseSubjectAddedEntry = 'a'; // 15
|ind1=1
let headingUseSeriesAddedEntry = 'b'; // 16
|ind2=#
let typeOfSubjectSubdivision = 'n'; // 17
|data=$a por $h eng
let undifferentiatedPersonalName = 'n'; // 32
|authorityData100=
let levelOfEstablishment = 'a'; // 33
|authorityData110=
|authorityData111=
// set the 008 field and indicadors specific values
|authorityData130=
if (tag === '100') {
|authorityData150=
undifferentiatedPersonalName = 'a';
|authorityData151=
ind2 = '';
}}
}
{{Field
if (tag === '110') {
|tag=080
// in case of autocomplete of 260
|authorityType=Nenhuma
if (tagFromDropdown === '260') {
|ind1=#
directOrIndirectGeogSubdiv = 'n';
|ind2=#
kindOfRecord = 'b';
|data=$a 820-31
headingUseMainOrAddedEntry = 'b';
|authorityData100=
headingUseSubjectAddedEntry = 'b';
|authorityData110=
levelOfEstablishment = 'n';
|authorityData111=
ind1 = '1';
|authorityData130=
}
|authorityData150=
ind2 = '';
|authorityData151=
}
}}
if (tag === '111') {
{{Field
ind1 = '2';
|tag=090
ind2 = '';
|authorityType=Nenhuma
}
|ind1=#
if (tag === '130') {
|ind2=#
typeOfSeries = 'a';
|data=$a 820-31 $b T649s $c 2.ed.
numberedOrUnnumberedSeries = 'b';
|authorityData100=
headingUseSeriesAddedEntry = 'a';
|authorityData110=
if (tagFromDropdown === '130'
|authorityData111=
|| tagFromDropdown === '630'
|authorityData130=
|| tagFromDropdown === '730') {
|authorityData150=
ind2 = ind1; // an inverted value happens here, see and
|authorityData151=
ind1 = ''; // compare bib. and auth. 130 MARC definitions
}}
}
{{Field
ind1 = '';
|tag=100
}
|authorityType=Pessoa
if (tag === '150' || tag === '151') {
|ind1=1
descriptiveCatalogingRules = 'n';
|ind2=#
subjectHeadingSystem = 'z';
|data=
headingUseMainOrAddedEntry = 'b';
|authorityData100=$a Tolkien, J. R. R. $q (John Ronald Reuel), $d 1892-1973 $0 A000012
ind1 = ''; // 150 and 151 indicators must be empty in
|authorityData110=
ind2 = ''; // authority MARC records
|authorityData111=
if (tag === '151') {
|authorityData130=
typeOfSubjectSubdivision = 'd';
|authorityData150=
}
|authorityData151=
}
}}
// build the URL
{{Field
const autRecordParams = {
|tag=240
AutRecord: {
|authorityType=Nenhuma
directOrIndirectGeogSubdiv,
|ind1=1
kindOfRecord,
|ind2=4
descriptiveCatalogingRules,
|data=$a The lord of the rings. $l Português
subjectHeadingSystem,
|authorityData100=
typeOfSeries,
|authorityData110=
numberedOrUnnumberedSeries,
|authorityData111=
headingUseMainOrAddedEntry,
|authorityData130=
headingUseSubjectAddedEntry,
|authorityData150=
headingUseSeriesAddedEntry,
|authorityData151=
typeOfSubjectSubdivision,
}}
undifferentiatedPersonalName,
{{Field
levelOfEstablishment
|tag=245
},
|authorityType=Nenhuma
Field: {
|ind1=1
'1': {
|ind2=2
tag: '040',
|data=$a O senhor dos anéis / $c J. R. R. Tolkien ; tradução: Lenita Maria Rímoli Esteves, Almiro Pisetta ; revisão técnica e consultoria: Ronald Eduard Kyrmse ; coordenação: Luís Carlos Borges
data: '$a BR-FlWIK $b por $c BR-FlWIK $d BR-FlUSC'
|authorityData100=
},
|authorityData110=
'2': {
|authorityData111=
tag,
|authorityData130=
ind1,
|authorityData150=
ind2,
|authorityData151=
data: elem.value
}}
},
{{Field
'3': {
|tag=250
tag: '670',
|authorityType=Nenhuma
data: '$a '
|ind1=#
}
|ind2=#
}
|data=$a 2. ed.
};
|authorityData100=
|authorityData110=
const url = new URL(`${window.location.origin}/wiki/Special:FormEdit/AutRecord`);
|authorityData111=
// function to transform a 3rd level object to URL query strings
|authorityData130=
const makeUrlParams = (obj) => {
|authorityData150=
for (const [key, value] of Object.entries(obj)) {
|authorityData151=
if (typeof value === 'object') {
}}
for (const [key2, value2] of Object.entries(value)) {
{{Field
if (typeof value2 === 'object') {
|tag=260
for (const [key3, value3] of Object.entries(value2)) {
|authorityType=Nenhuma
url.searchParams.set(`${key}[${key2}][${key3}]`, value3);
|ind1=#
}
|ind2=#
} else {
|data=$a São Paulo : $b M. Fontes, $c 2000.
url.searchParams.set(`${key}[${key2}]`, value2);
|authorityData100=
}
|authorityData110=
}
|authorityData111=
} else {
|authorityData130=
url.searchParams.set(key, value);
|authorityData150=
}
|authorityData151=
}
}}
};
{{Field
makeUrlParams(autRecordParams);
|tag=300
authorityLink.innerText = 'Criar registro de autoridade';
|authorityType=Nenhuma
authorityLink.setAttribute('href', url.pathname + url.search);
|ind1=#
}
|ind2=#
authorityLink.style.display = '';
|data=$a v. : $b il. ; $c 20 cm
});
|authorityData100=
});
|authorityData110=
}
|authorityData111=
|authorityData130=
function rmCarriageReturn() {
|authorityData150=
const textareas = document.body.querySelectorAll('textarea');
|authorityData151=
textareas.forEach((textarea) => {
}}
const element = textarea;
{{Field
element.value = element.value.replace('
', '');
|tag=505
});
|authorityType=Nenhuma
}
|ind1=8
|ind2=#
function rmHtmlTags() {
|data=$a v. 1. A sociedade do anel -- v. 2. As duas torres -- v. 3. O retorno do rei.
const textareas = document.body.querySelectorAll('textarea');
|authorityData100=
textareas.forEach((textarea) => {
|authorityData110=
const element = textarea;
|authorityData111=
element.value = element.value.replace(/<(?:"[^"]*"['"]*|'[^']*'['"]*|[^'">])+>/g, '');
|authorityData130=
});
|authorityData150=
}
|authorityData151=
}}
function rmTxtFromHiddenFields() {
{{Field
const spans = document.body.querySelectorAll('span.hiddenByPF');
|tag=590
spans.forEach((elem) => {
|authorityType=Nenhuma
elem.querySelectorAll('.input.oo-ui-inputWidget-input').forEach((input) => {
|ind1=#
const element = input;
|ind2=#
element.value = '';
|data=$a A Biblioteca possui a 3. tiragem 2001, 4. tiragem 2002, 7. tiragem 2009, 12. e 13. reimpr. de 2014, 14. reimpr. de 2015.
});
|authorityData100=
elem.querySelectorAll('textarea').forEach((input) => {
|authorityData110=
const element = input;
|authorityData111=
element.value = '';
|authorityData130=
});
|authorityData150=
});
|authorityData151=
}
}}
{{Field
function normalizeInput() {
|tag=650
const instanceMains = document.body.querySelectorAll('.instanceMain div table');
|authorityType=Nenhuma
instanceMains.forEach((instanceMain) => {
|ind1=0
instanceMain.querySelectorAll('.oo-ui-inputWidget-input').forEach((input) => {
|ind2=4
const normalizedInput = input;
|data=$a Ficção inglesa
normalizedInput.value = normalizedInput.value
|authorityData100=
// "$a Bar \n$b Baz" > " $a Bar $b Baz"
|authorityData110=
.replace(/\s*(\$[a-z0-8])\s*/g, ' $1 ')
|authorityData111=
// "$a Bar\nFoo" > "$a Bar Foo" ou "$a Bar Foo" > "$a Bar Foo"
|authorityData130=
.replace(/\n|\s\s+|\t/g, ' ')
|authorityData150=
// replace "|" by "%7C" (Ex.: http://viaf.org/processed/WKP|Q2484404)
|authorityData151=
.replace('|', '%7C');
}}
});
{{Field
instanceMain.querySelectorAll('textarea').forEach((textarea) => {
|tag=650
const normalizedInput = textarea;
|authorityType=Nenhuma
textarea.value = normalizedInput.value
|ind1=0
// "$a Bar \n$b Baz" > " $a Bar $b Baz"
|ind2=4
.replace(/\s*(\$[a-z0-8])\s*/g, ' $1 ')
|data=$a Literatura inglesa
// "$a Bar\nFoo" > "$a Bar Foo" ou "$a Bar Foo" > "$a Bar Foo"
|authorityData100=
.replace(/\n|\s\s+|\t/g, ' ')
|authorityData110=
// replace "|" by "%7C" (Ex.: http://viaf.org/processed/WKP|Q2484404)
|authorityData111=
.replace('|', '%7C');
|authorityData130=
});
|authorityData150=
});
|authorityData151=
}
}}
{{Field
// calls main functions
|tag=740
createMarcFieldHelpLink();
|authorityType=Nenhuma
createAuthorityLinks();
|ind1=2
rmCarriageReturn();
|ind2=2
rmHtmlTags();
|data=$a A sociedade do anel
|authorityData100=
// Como instâncias do formulário são criadas pelo botão "Adicionar campo",
|authorityData110=
// é necessário observar o DOM a partir da classe ".multipleTemplateList".
|authorityData111=
// Toda vez que o DOM é alterado (mais especificamente, quando uma nova
|authorityData130=
// child de ".multipleTemplateList" é criada), as funções
|authorityData150=
// createMarcFieldHelpLink() e createAuthorityLinks() são novamente chamadas.
|authorityData151=
// https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
}}
{{Field
// create an observer instance
|tag=740
const observer = new MutationObserver((mutations) => {
|authorityType=Nenhuma
mutations.forEach((mutation) => {
|ind1=3
const newNodes = mutation.addedNodes; // DOM NodeList
|ind2=2
if (newNodes.length !== 0) { // if there are new nodes added
|data=$a As duas torres
createMarcFieldHelpLink();
|authorityData100=
createAuthorityLinks();
|authorityData110=
}
|authorityData111=
});
|authorityData130=
});
|authorityData150=
|authorityData151=
// select the target node
}}
const target = document.querySelector('.multipleTemplateList');
{{Field
|tag=740
// configuration of the observer
|authorityType=Nenhuma
const config = {
|ind1=2
childList: true,
|ind2=2
attributes: false,
|data=$a O retorno do rei
subtree: false,
|authorityData100=
};
|authorityData110=
|authorityData111=
// pass in the target node, as well as the observer options
|authorityData130=
observer.observe(target, config);
|authorityData150=

|authorityData151=
// when clicking save...
}}
const saveBtn = document.body.querySelector('#wpSave');
{{EndOfRecord}}
saveBtn.addEventListener('click', () => {
observer.disconnect();
rmTxtFromHiddenFields();
rmCarriageReturn();
rmHtmlTags();
normalizeInput();
});
// when clicking adding field...
const addBtn = document.body.querySelector('.multipleTemplateAdder');
addBtn.addEventListener('click', () => {
createMarcFieldHelpLink();
});
}
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);

Edição das 14h25min 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();
    });
  
    // when clicking adding field...
    const addBtn = document.body.querySelector('.multipleTemplateAdder');
    addBtn.addEventListener('click', () => {
        createMarcFieldHelpLink();
    });
}
  
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);