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
 
(69 revisões intermediárias pelo mesmo usuário não estão sendo mostradas)
Linha 1: Linha 1:
/* jshint esversion: 10 */
// Author: @vitorsilverio
function main() {
// Author: @jaideraf
// 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".
// make collapsible CSS clickable (space or enter to click)
// Toda vez que o DOM é alterado (mais especificamente, quando uma nova
// from: https://alligator.io/css/collapsible/
// child de ".multipleTemplateList" é criada), as funções
let myCollapsibleLabels = document.querySelectorAll(".lbl-toggle");
// makeMarcFieldHelpLink() e authorityLinks() são novamente chamadas.
// https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver


// create an observer instance
Array.from(myCollapsibleLabels).forEach(label => {
const observer = new MutationObserver((mutations) => {
label.addEventListener("keydown", e => {
mutations.forEach((mutation) => {
// 32 === spacebar
const newNodes = mutation.addedNodes; // DOM NodeList
// 13 === enter
if (e.which === 32 || e.which === 13) {
if (newNodes.length !== 0) {
// if there are new nodes added
e.preventDefault();
label.click();
makeMarcFieldHelpLink();
authorityLinks();
}
setIndicators();
}
});
});
});
});
///////////////////////////////////////////////////////////////////
let marcDocSource = "https://www.loc.gov/marc/bibliographic/bd";
let tag = "";
let tagFromDropdown = "";


// select the target node
if (window.location.href.match(/A\d{6}/) ||
const target = document.querySelector('.multipleTemplateList');
window.location.href.match(/AutRecord/)) {
marcDocSource = "https://www.loc.gov/marc/authority/ad";
}


// configuration of the observer
function createMarcFieldHelpLinks() {
const config = {
"use strict";
childList: true,
$(".tagInput").each(function() {
attributes: false,
let marcFieldHelpLink = $("<a>", {
target: "_blank",
subtree: false,
};
text: "(?)"
});
marcFieldHelpLink.hide();
$(this).closest("table").find(".marcFieldHelpLink").html(marcFieldHelpLink);
$(this).closest("table").find("select").change(function() {


// pass in the target node, as well as the observer options
// find the tag value from the chosen dropdown
observer.observe(target, config);
tagFromDropdown = $(this).closest(".instanceMain").find(".select2-selection__rendered").attr("title");
tagFromDropdown = tagFromDropdown.substring(0, 3);


// when clicking save...
// build the URL
const saveBtn = document.body.querySelector('#wpSave');
marcFieldHelpLink.attr("title", "Documentação do campo " + tagFromDropdown);
saveBtn.addEventListener('click', () => {
marcFieldHelpLink.attr("href", marcDocSource + tagFromDropdown + ".html");
observer.disconnect();
marcFieldHelpLink.show();
});
rmTxtFromHiddenFields();
});
rmCarriageReturn();
rmHtmlTags();
normalizeInput();
});
}
}


document.addEventListener('DOMContentLoaded', () => main());
function createAuthorityLinks() {
"use strict";
$("textarea").each(function() {
let authorityLink = $("<a>", {
title: "Abre uma nova aba para criar ou editar um registro de autoridade",
target: "_blank",
text: "Criar autoridade"
});
let pattern = /\$0\sA\d{6}/;
authorityLink.hide();
$(this).closest("table").find(".createAuthorityLink").html(authorityLink);
$(this).focusout(function() {
// if already recorded
if (pattern.test($(this).val())) {
// build the URL
authorityLink.text("Editar autoridade");
authorityLink.attr("href", "/wiki/Special:FormEdit/AutRecord/Autoridade:" +
$(this).val().match(/A\d{6}/));
} else {
// find the tag value from the chosen dropdown
tagFromDropdown = $(this).closest(".instanceMain")
// PageForms 4.8
// .find(".select2-chosen").text();
// Page forms 4.9.1
.find(".select2-selection__rendered").attr("title");
tagFromDropdown = tagFromDropdown.substring(0, 3);


// for no obvious reason to me, the first call to the "main" function is not
// find the tag value from checked radio button
// occurring, so wait 3 seconds and call it anyway.
let tagFromRadio = $(this).closest(".instanceMain")
setTimeout(main, 3000);
.find("input[origname='Field[authorityType]']:checked").val();
let 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 = $(this).closest(".instanceMain")
.find("select[origname='Field[ind1]'] option:selected").val();
let ind2 = $(this).closest(".instanceMain")
.find("select[origname='Field[ind2]'] option:selected").val();

// 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
authorityLink.attr("href", "/wiki/Special:FormEdit/AutRecord?" +
decodeURIComponent($.param({
"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": tag,
"ind1": encodeURIComponent(ind1),
"ind2": encodeURIComponent(ind2),
"data": encodeURIComponent($(this).val())
},
"2": {
"tag": "670",
"data": "$a+"
}
}
})));
}
authorityLink.show();
});
});
}

$(document).ready(function(){
"use strict";
// remove carriage return
$("span.inputSpan").find("textarea").each(function() {
let input = $(this).val();
input = input.replace("&#13;", "")
// remove any html tags
.replace(/<(?:"[^"]*"['"]*|'[^']*'['"]*|[^'">])+>/g, "");
$(this).val(input);
});

// calls main functions
createMarcFieldHelpLinks();
createAuthorityLinks();

// 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), a função
// marcEditorDynamicLinks() é novamente chamada.
// https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

// create an observer instance
let observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
let newNodes = mutation.addedNodes; // DOM NodeList
if(newNodes.length !== 0) { // if there are new nodes added
createMarcFieldHelpLinks();
createAuthorityLinks();
}
});
});

// select the target node
let 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 save, remove text form hidden textareas
$("#wpSave").click(function(){
observer.disconnect();
$("span.hiddenByPF").find("textarea").val("");
$("textarea").each(function() {
let input = $(this).val();
// normalize input
let normalizedInput = input
// "$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");
$(this).val(normalizedInput);
});
});
});

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