Savelyev_Vyacheslav

attach set Data by server

Nov 25th, 2024 (edited)
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2.  
  3. <div id="init">
  4. </div>
  5.  
  6.     #fileInput {
  7.         padding: 10px;
  8.         font-size: 1rem;
  9.         border: 1px solid #ced4da;
  10.         border-radius: 4px;
  11.         background-color: #fff;
  12.     }
  13.  
  14. #init button {
  15.         background-color: #007bff;
  16.         color: #fff;
  17.         border: none;
  18.         padding: 10px 15px;
  19.         font-size: 1rem;
  20.         cursor: pointer;
  21.         border-radius: 4px;
  22.         margin: 5px 0;
  23.         transition: background-color 0.3s ease;
  24.     }
  25.  
  26.     button:hover {
  27.         background-color: #0056b3;
  28.     }
  29.  
  30.     .file-item {
  31.         display: flex;
  32.         justify-content: space-between;
  33.         align-items: center;
  34.         padding: 10px;
  35.         border: 1px solid #dee2e6;
  36.         border-radius: 4px;
  37.         margin-bottom: 10px;
  38.         background-color: #fff;
  39.     }
  40.  
  41.     .file-item button {
  42.         margin-left: 10px;
  43.     }
  44.  
  45.     ul {
  46.         list-style-type: none;
  47.         padding: 0;
  48.     }
  49.  
  50.     #fileList {
  51.         max-height: 300px;
  52.         overflow-y: auto;
  53.         border: 1px solid #ced4da;
  54.         border-radius: 4px;
  55.         padding: 10px;
  56.         background-color: #fff;
  57.     }
  58.  
  59.     #clearButton, #saveData {
  60.         width: 100%;
  61.         margin-top: 10px;
  62.     }
  63.  
  64.     .download-link {
  65.         color: #007bff;
  66.         text-decoration: none;
  67.     }
  68.  
  69.     .download-link:hover {
  70.         text-decoration: underline;
  71.     }
  72.  
  73.     #output {
  74.         margin-top: 20px;
  75.         padding: 10px;
  76.         border: 1px solid #ced4da;
  77.         border-radius: 4px;
  78.         background-color: #fff;
  79.         font-size: 0.9rem;
  80.         color: #6c757d;
  81.     }
  82. */
  83.  
  84. /*Server Script
  85.  
  86. (() => {
  87.  
  88. if(input.action === "INIT") {
  89.     let preferenceID = input.recordID
  90.  
  91.     const prefData = getPreferenceDefault(preferenceID)
  92.  
  93.     if(!!prefData) Object.assign(data, prefData)
  94.  
  95. }
  96.  
  97. if (input.action === "SAVE") {
  98.  
  99.     let preferenceID = input.recordID;
  100.     function extractFields() {
  101.         return { ...input }; // Возвращает все ключи и значения из obj
  102.     }
  103.     const saveData = extractFields();
  104.     let preferenceValue = JSON.stringify(saveData);
  105.  
  106.     const preference2 = new SimpleRecord('c_checklist_task');
  107.     preference2.get(preferenceID);
  108.     preference2.setValue("value", preferenceValue);
  109.     const res = preference2.update();
  110.     if (!!Number(res)) ss.addInfoMessage('Изменения сохранены!');
  111.     ss.setRedirect()
  112. }
  113.  
  114. })();
  115.  
  116. function getPreferenceDefault(preferenceID) {
  117.         const preference = new SimpleRecord('c_checklist_task');
  118.         preference.get(preferenceID);
  119.         if(!preference.sys_id) return ""
  120.         const data_ = JSON.parse(preference.value);
  121.         return data_
  122. }
  123.  
  124. */
  125.  
  126. /*Client Script
  127. (async () => {
  128.     window.s_widget_custom = window.s_widget_custom || {};
  129.     const recordID = await getValueByKey('recordID')
  130.     const varibleNameAttach = await getValueByKey('varibleNameAttach')
  131.     await s_widget.setFieldValue('action', 'INIT');
  132.     await s_widget.setFieldValue('recordID', recordID);
  133.     await s_widget.setFieldValue('varibleNameAttach', varibleNameAttach);
  134.     await s_widget.serverUpdate();
  135.  
  136.     await insertTemplateAsync()
  137.     await init();
  138.  
  139.     // Асинхронная функция для получения значения по ключу из SimpleStorage
  140.     async function getValueByKey(key) {
  141.         if (SimpleStorage.hasItem(key)) {
  142.             const value = SimpleStorage.getItem(key);
  143.             // console.log(`Value for key "${key}":**`, value);
  144.             return value;
  145.         } else {
  146.             console.log(`Key "${key}" not found in SimpleStorage.`);
  147.             return null;
  148.         }
  149.     }
  150.  
  151.     // Асинхронная функция для вставки шаблона и инициализации
  152.     async function insertTemplateAsync() {
  153.         const template = `
  154.     <input type="file" id="fileInput" multiple>
  155.     <button id="addFiles">Add Files</button>
  156.     <ul id="fileList">
  157.     </ul>
  158.     <button id="clearButton">Clear</button>
  159.     <button id="saveData">SAVE</button>
  160.     <div id="output"></div>
  161. `;
  162.         // Ждем завершения потенциальных асинхронных операций
  163.         await new Promise(resolve => setTimeout(resolve, 0));
  164.  
  165.         // Вставляем шаблон в элемент с id "init"
  166.         const initElement = document.getElementById("init");
  167.         if (initElement) {
  168.             initElement.innerHTML = template;
  169.  
  170.             // После вставки вызываем init(), если она определена
  171.             if (typeof init === "function") {
  172.                 init();
  173.             }
  174.         } else {
  175.             console.error('Element with id "init" not found.');
  176.         }
  177.     }
  178.  
  179.     async function init() {
  180.         const fileInput = document.getElementById('fileInput');
  181.         const addFilesButton = document.getElementById('addFiles');
  182.         const fileList = document.getElementById('fileList');
  183.         const clearButton = document.getElementById('clearButton');
  184.         const saveDataButton = document.getElementById('saveData');
  185.         const outputDiv = document.getElementById('output');
  186.  
  187.         let filesArray = [];
  188.         let base64Files = [];
  189.  
  190.         // Function to display a file in the list
  191.         function displayFile(file) {
  192.             // Проверяем, есть ли уже элемент с таким названием файла в списке
  193.             if (Array.from(fileList.children).some(li => li.textContent.includes(file.name))) {
  194.                 return; // Пропускаем дублирование
  195.             }
  196.  
  197.             const li = document.createElement('li');
  198.             li.className = 'file-item';
  199.             li.textContent = file.name;
  200.  
  201.             const removeButton = document.createElement('button');
  202.             removeButton.textContent = 'Remove';
  203.             removeButton.addEventListener('click', () => {
  204.                 filesArray = filesArray.filter(f => f !== file);
  205.                 fileList.removeChild(li);
  206.             });
  207.  
  208.             const downloadButton = document.createElement('button');
  209.             downloadButton.textContent = 'Download';
  210.             downloadButton.addEventListener('click', async () => {
  211.                 const reader = new FileReader();
  212.                 reader.onload = function (e) {
  213.                     const downloadLink = document.createElement('a');
  214.                     downloadLink.href = e.target.result;
  215.                     downloadLink.download = file.name;
  216.                     downloadLink.click();
  217.                 };
  218.                 reader.readAsDataURL(file);
  219.             });
  220.  
  221.             li.appendChild(removeButton);
  222.             li.appendChild(downloadButton);
  223.             fileList.appendChild(li);
  224.         }
  225.  
  226.         // Add multiple files to the list
  227.         addFilesButton.addEventListener('click', () => {
  228.             const files = Array.from(fileInput.files);
  229.             if (!files.length) {
  230.                 // alert('No files selected!');
  231.                 return;
  232.             }
  233.  
  234.             files.forEach(file => {
  235.                 if (!filesArray.some(existingFile => existingFile.name === file.name)) {
  236.                     filesArray.push(file);
  237.                     displayFile(file);
  238.                 }
  239.             });
  240.  
  241.             fileInput.value = ''; // Clear input
  242.         });
  243.  
  244.         // Clear all files and Base64 data
  245.         clearButton.addEventListener('click', () => {
  246.             filesArray = [];
  247.             base64Files = [];
  248.             fileList.innerHTML = '';
  249.             outputDiv.innerHTML = '';
  250.             // alert('All files and data cleared!');
  251.         });
  252.  
  253.         // Save data
  254.         // Save data with a delay        
  255.         saveDataButton.addEventListener('click', async () => {
  256.             if (!filesArray.length) {
  257.  
  258.                 base64Files = []
  259.                 const data = {
  260.                     filesArray: filesArray.map(file => ({ name: file.name, type: file.type })),
  261.                     base64Files
  262.                 };
  263.                 fileList.innerHTML = '';
  264.                 outputDiv.innerHTML = '';
  265.                 // Уведомление пользователю
  266.                 // alert('No files to save! All data has been cleared.');
  267.                 return;
  268.             }
  269.  
  270.             // Блокируем кнопку
  271.             saveDataButton.disabled = true;
  272.  
  273.             base64Files = [];
  274.  
  275.             const filePromises = filesArray.map(file => {
  276.                 return new Promise((resolve) => {
  277.                     const reader = new FileReader();
  278.                     reader.onload = (e) => {
  279.                         const base64 = e.target.result;
  280.                         resolve({ name: file.name, type: file.type, base64 });
  281.                     };
  282.                     reader.readAsDataURL(file);
  283.                 });
  284.             });
  285.  
  286.             try {
  287.                 base64Files = await Promise.all(filePromises);
  288.                 const data = {
  289.                     filesArray: filesArray.map(file => ({ name: file.name, type: file.type })),
  290.                     base64Files
  291.                 };
  292.  
  293.                 // Сохраняем данные
  294.                 const varibleNameAttach = await getValueByKey('varibleNameAttach')
  295.                 s_widget.setFieldValue(varibleNameAttach, JSON.stringify(data, null, 2));
  296.                 s_widget.setFieldValue('action', 'SAVE');
  297.                 s_widget.serverUpdate();
  298.             } catch (error) {
  299.                 console.error('Error saving data:', error);
  300.                 // alert('An error occurred while saving data!');
  301.             } finally {
  302.                 // Устанавливаем задержку перед разблокировкой кнопки
  303.                 setTimeout(() => {
  304.                     saveDataButton.disabled = false;
  305.                 }, 500); // Задержка в 0,5 секунды
  306.             }
  307.         });
  308.  
  309.         // Load files from inputData
  310.         async function loadFilesFromInputData(data) {
  311.             if (data.filesArray && Array.isArray(data.filesArray) && data.base64Files) {
  312.                 data.base64Files.forEach(base64File => {
  313.                     const blob = base64ToBlob(base64File.base64, base64File.type || "application/octet-stream");
  314.                     const mockFile = new File([blob], base64File.name, { type: base64File.type || "" });
  315.  
  316.                     // Проверяем, что файл не добавлен ранее
  317.                     if (!filesArray.some(existingFile => existingFile.name === mockFile.name && existingFile.size === mockFile.size)) {
  318.                         filesArray.push(mockFile);
  319.                         displayFile(mockFile);
  320.                     }
  321.                 });
  322.             }
  323.         }
  324.  
  325.  
  326.         const varibleNameAttach = await getValueByKey('varibleNameAttach')
  327.         const inputData = await s_widget.getFieldValue(varibleNameAttach) || 'No Set'
  328.  
  329.         if (inputData.trim()) {
  330.             try {
  331.                 const inputDataObj = JSON.parse(inputData);
  332.  
  333.                 // Загрузка файлов из данных
  334.                 async function loadFilesFromInputData(data) {
  335.                     if (data.filesArray && Array.isArray(data.filesArray) && data.base64Files) {
  336.                         data.base64Files.forEach(base64File => {
  337.                             const blob = base64ToBlob(base64File.base64, base64File.type || "application/octet-stream");
  338.                             const mockFile = new File([blob], base64File.name, { type: base64File.type || "" });
  339.                             filesArray.push(mockFile);
  340.                             displayFile(mockFile);
  341.                         });
  342.                     }
  343.                 }
  344.  
  345.                 // Функция для преобразования Base64 в Blob
  346.                 function base64ToBlob(base64, mimeType) {
  347.                     const byteString = atob(base64.split(',')[1]);
  348.                     const arrayBuffer = new ArrayBuffer(byteString.length);
  349.                     const uint8Array = new Uint8Array(arrayBuffer);
  350.  
  351.                     for (let i = 0; i < byteString.length; i++) {
  352.                         uint8Array[i] = byteString.charCodeAt(i);
  353.                     }
  354.  
  355.                     return new Blob([arrayBuffer], { type: mimeType });
  356.                 }
  357.  
  358.                 await loadFilesFromInputData(inputDataObj);
  359.             } catch (error) {
  360.                 console.error("Failed to parse inputData:", error);
  361.             }
  362.         }
  363.  
  364.     }
  365. })();
  366.  
  367.  
  368. */
Add Comment
Please, Sign In to add comment