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

De Wikincat
Ir para navegação Ir para pesquisar
Sem resumo de edição
Sem resumo de edição
 
(47 revisões intermediárias pelo mesmo usuário não estão sendo mostradas)
Linha 1: Linha 1:
/* jshint esversion: 10 */
// Author: @vitorsilverio
// Author: @jaideraf
if (document.readyState === "complete" || (document.readyState !== "loading")) {
main();
} else {
document.addEventListener("DOMContentLoaded", main);
}

function main() {
function main() {
// calling main functions
let tag = "";
makeMarcFieldHelpLink();
let tagFromDropdown = "";
authorityLinks();
setIndicators();
rmCarriageReturn();
rmHtmlTags();


// Como instâncias do formulário são criadas pelo botão "Adicionar campo",
function createMarcFieldHelpLink() {
// é necessário observar o DOM a partir da classe ".multipleTemplateList".
const tagInputs = document.body.querySelectorAll(".tagInput");
// Toda vez que o DOM é alterado (mais especificamente, quando uma nova
tagInputs.forEach(function (elem) {
// child de ".multipleTemplateList" é criada), as funções
const marcFieldHelpLink = document.createElement("a");
// makeMarcFieldHelpLink() e authorityLinks() são novamente chamadas.
marcFieldHelpLink.setAttribute("target", "_blank");
// https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
marcFieldHelpLink.innerText = `(?)`;


// create an observer instance
const marcFieldHelpLinkClass = elem.closest("table")
const observer = new MutationObserver((mutations) => {
.querySelector(".marcFieldHelpLink");
mutations.forEach((mutation) => {
marcFieldHelpLinkClass.appendChild(marcFieldHelpLink);
const newNodes = mutation.addedNodes; // DOM NodeList
if (newNodes.length !== 0) {
// if there are new nodes added
makeMarcFieldHelpLink();
authorityLinks();
setIndicators();
}
});
});


// select the target node
// find the tag value from the chosen dropdown
const target = document.querySelector('.multipleTemplateList');
marcFieldHelpLinkClass.addEventListener("mouseover", function (event) {
tagFromDropdown = event.target.closest(".instanceMain")
.querySelector(".select2-selection__rendered")
.getAttribute("title");
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`);
}
});
});
}


// configuration of the observer
function createAuthorityLinks() {
const config = {
const textareas = document.body.querySelectorAll("textarea.has-authority-control");
childList: true,
textareas.forEach(function (elem) {
attributes: false,
let authorityLink = document.createElement("a");
subtree: false,
authorityLink.setAttribute("title", "Abre uma nova aba para criar ou editar um registro de autoridade");
};
authorityLink.setAttribute("target", "_blank");
authorityLink.innerText = "Criar autoridade";
authorityLink.style.display = "none";


// pass in the target node, as well as the observer options
let createAuthorityLink = elem.closest("table")
observer.observe(target, config);
.querySelector(".createAuthorityLink");


// when clicking save...
createAuthorityLink.appendChild(authorityLink);
const saveBtn = document.body.querySelector('#wpSave');

saveBtn.addEventListener('click', () => {
const pattern1 = /\$0\sA\d{6}/;
observer.disconnect();
const pattern2 = /\$0\s\(BN\)\d{9}/;
rmTxtFromHiddenFields();

elem.addEventListener("focusout", function () {
// 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 autoridade na BN";
authorityLink.setAttribute("href",
"http://acervo.bn.br/sophia_web/autoridade/detalhe/" +
elem.value.match(/\d{9}/));
} else {
// find the tag value from the chosen dropdown
tagFromDropdown = elem.closest(".instanceMain")
// PageForms 4.8
// .find(".select2-chosen").text();
// Page forms 4.9.1
.querySelector(".select2-selection__rendered")
.getAttribute("title");
tagFromDropdown = tagFromDropdown.substring(0, 3);
// find the tag value from checked radio button

let 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
kindOfRecord = "", // 09
descriptiveCatalogingRules = "c", // 10
subjectHeadingSystem = "n", // 11
typeOfSeries = "n", // 12
numberedOrUnnumberedSeries = "n", // 13
headingUseMainOrAddedEntry = "a", // 14
headingUseSubjectAddedEntry = "a", // 15
headingUseSeriesAddedEntry = "b", // 16
typeOfSubjectSubdivision = "n", // 17
undifferentiatedPersonalName = "n", // 32
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": directOrIndirectGeogSubdiv,
"kindOfRecord": kindOfRecord,
"descriptiveCatalogingRules": descriptiveCatalogingRules,
"subjectHeadingSystem": subjectHeadingSystem,
"typeOfSeries": typeOfSeries,
"numberedOrUnnumberedSeries": numberedOrUnnumberedSeries,
"headingUseMainOrAddedEntry": headingUseMainOrAddedEntry,
"headingUseSubjectAddedEntry": headingUseSubjectAddedEntry,
"headingUseSeriesAddedEntry": headingUseSeriesAddedEntry,
"typeOfSubjectSubdivision": typeOfSubjectSubdivision,
"undifferentiatedPersonalName": undifferentiatedPersonalName,
"levelOfEstablishment": levelOfEstablishment
},
"Field": {
"1": {
"tag": "040",
"data": "$a BR-FlWIK $b por $c BR-FlWIK $d BR-FlUSC"
},
"2": {
"tag": tag,
"ind1": ind1,
"ind2": ind2,
"data": elem.value
},
"3": {
"tag": "670",
"data": "$a "
}
}
};

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

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

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

function rmTxtFromHiddenTexareas() {
const textareas = document.body.querySelectorAll("span.hiddenByPF");
textareas.forEach(elem => {
elem.querySelectorAll("textarea").forEach(elem => {
elem.value = "";
});
});
}

function normalizeInput() {
const textareas = document.body.querySelectorAll("textarea");
textareas.forEach(elem => {
let normalizedInput = elem.value;
normalizedInput = elem.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");
elem.value = normalizedInput;
});
}

// calls main functions
createMarcFieldHelpLink();
createAuthorityLinks();
rmCarriageReturn();
rmCarriageReturn();
rmHtmlTags();
rmHtmlTags();
normalizeInput();
});
}


document.addEventListener('DOMContentLoaded', () => main());
// 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


// for no obvious reason to me, the first call to the "main" function is not
// create an observer instance
// occurring, so wait 3 seconds and call it anyway.
let observer = new MutationObserver(function (mutations) {
setTimeout(main, 3000);
mutations.forEach(mutation => {
let 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
let 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();
rmTxtFromHiddenTexareas();
rmCarriageReturn();
rmHtmlTags();
normalizeInput();
});
}

Edição atual tal como às 14h03min de 19 de agosto de 2024

/* jshint esversion: 10 */
function main() {
  // calling main functions
  makeMarcFieldHelpLink();
  authorityLinks();
  setIndicators();
  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
  // makeMarcFieldHelpLink() e authorityLinks() 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
        makeMarcFieldHelpLink();
        authorityLinks();
        setIndicators();
      }
    });
  });

  // 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();
  });
}

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);