לדלג לתוכן

משתמש:מוטי בוט/ניסוי4.js

מתוך המכלול, האנציקלופדיה היהודית

לתשומת ליבך: לאחר הפרסום, ייתכן שיהיה צורך לנקות את זיכרון המטמון (cache) של הדפדפן כדי להבחין בשינויים.

  • פיירפוקס / ספארי: להחזיק את המקש Shift בעת לחיצה על טעינה מחדש (Reload) או ללחוץ על צירוף המקשים Ctrl-F5 או Ctrl-R (במחשב מק: ⌘-R).
  • גוגל כרום: ללחוץ על צירוף המקשים Ctrl-Shift-R (במחשב מק: ⌘-Shift-R).
  • אדג': להחזיק את המקש Ctrl בעת לחיצה על רענן (Refresh) או ללחוץ על צירוף המקשים Ctrl-F5.
/**
 * Fetches data from a specified URL and returns it as a JSON object.
 * @returns {Promise<Object>} The fetched data as a JSON object.
 * @throws {Error} If there is an error fetching the data.
 */
async function fetchData() {
  try {
    const response = await fetch(
      "https://www.hamichlol.org.il/w/index.php?title=משתמש:מוטי_בוט/רשימת_תבניות.json&action=raw"
    );
    const data = await response.json();
    return data;
  } catch (error) {
    console.error("Error fetching data:", error);
    throw error;
  }
}

/**
 * Asynchronous function that processes an input text.
 * It splits the text into words, fetches data from a remote server,
 * and constructs template strings based on the words and fetched data.
 * The template strings are logged to the console.
 *
 * @param {string} text - The input text to be processed.
 * @returns {Promise<string>}
 */
async function processText(text) {
  const data = await fetchData();
  console.log(data);

  let template_text = findMatchingTemplate(text, data);
  console.log(template_text);
  if (!template_text) {
    return prompt("לא נמצאו תבניות תקינות להחלפה, תוכל להזין ידנית.");
  } else {
    const nextWords = template_text[1].slice(0, 3);
    console.log(nextWords);
    const textTemplate = constructTemplate(template_text[0], nextWords);
    console.log(textTemplate);
    return prompt(
      `טקסט להחלפה:\n"${text}"\nנא לוודא שהתבנית תקינה!`,
      textTemplate
    );
  }
}

/**
 * Finds the first element in the given list that includes the specified text.
 *
 * @param {string} text - The text to search for.
 * @param {Array} list - The list to search within.
 * @return {string|boolean} The first element that includes the text, or false if no such element is found.
 */
function findtow(text, list) {
  for (let i = 0; i < list.length; i++) {
    if (list[i].includes(text)) {
      return list[i];
    }
  }
  return false;
}

/**
 * Finds a matching template for a given word in a list of templates.
 * @param {string} word - The word to find a matching template for.
 * @param {Object<string>} templates - The list of templates to search in.
 * @param {boolean} object - Flag indicating whether to search for the word in the entire template object or in each item of the template.
 * @returns {[string, string]|null} - The matching template and the matching word or item, or null if no match is found.
 */
function findMatchingTemplate(word, listes) {
  for (const template in listes.list2) {
    console.log(template);

    const match = checkIfItemExists(word, listes.list2[template]);
    if (match) {
      return [listes.list2[template], match];
    }
  }
  for (const template in listes.list) {
    for (const item of listes.list[template]) {
      const match = checkIfItemExists(word, item, true);
      if (match) {
        return [template, match];
      }
    }
  }

  return null;
}

/**
 * Searches for the first occurrence of a word in an array of strings.
 *
 * @param {string} word - The word to search for in the array.
 * @param {string[]} arr - The array of strings to search through.
 * @returns {string|boolean} - The first string in the array that includes the given word, or false if no string includes the word.
 */
function findWord(word, arr) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].includes(word)) {
      return arr[i];
    }
  }
  return false;
}

/**
 * Constructs a template string using a template and a list of words.
 * @param {string} template - The template to use.
 * @param {Array<string>} words - The list of words to include in the template.
 * @returns {string} - The constructed template string.
 */
function constructTemplate(template, words) {
  return `{{${template}|${words.join("|")}}}`;
}

/**
 * Retrieves the text from an HTML element, processes the selected text, and replaces it with the processed template.
 * @returns {Promise<void>}
 */

async function main() {
  const textElement = document.getElementById("wpTextbox1");
  const text = textElement.value;
  const selectedText = window.getSelection().toString();
  const template = await processText(selectedText);

  if (!template) return;

  const updatedText = text.replace(selectedText, template);
  textElement.value = updatedText;
}

function addButton() {
  const button = document.createElement("a");
  button.textContent = "יצירת תבנית";
  button.href = "#";
  button.addEventListener("click", main);
  const targetElement = document.querySelector(
    "#wikiEditor-section-advanced > div.group.group-search > span > a"
  );

  targetElement?.before(button);
}

/**
 * Checks if an item exists in a given text and returns an array of
 * words that come after the item in the text.
 *
 * @param {string} text - The text to search for the item.
 * @param {string} item - The item to check if it exists in the text.
 * @param {boolean} include - If set to `true`, the item itself will be included in the returned array.
 * @return {array} An array of words that come after the item in the text,
 * or an empty array if the item doesn't exist.
 */
function checkIfItemExists(text, item, include = false) {
  if (!text.includes(item)) {
    return null;
  }
  const pattern =
    /מסכת |ספר |דף |עמוד |סימן |סעיף |פרק |פסוק |הלכות |הלכה |פרשת |"|'|\./g;
  const startIndex = text.indexOf(item) + item.length + 1;
  const result = text.slice(startIndex);
  const parameters = result
    .replace(/(?<!דף )ע"/g, "")
    .replace(pattern, "")
    .split(" ");

  if (include) {
    parameters.unshift(item);
  }

  return parameters;
}

setTimeout(addButton, 500)