Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- <div id="init">
- </div>
- #fileInput {
- padding: 10px;
- font-size: 1rem;
- border: 1px solid #ced4da;
- border-radius: 4px;
- background-color: #fff;
- }
- #init button {
- background-color: #007bff;
- color: #fff;
- border: none;
- padding: 10px 15px;
- font-size: 1rem;
- cursor: pointer;
- border-radius: 4px;
- margin: 5px 0;
- transition: background-color 0.3s ease;
- }
- button:hover {
- background-color: #0056b3;
- }
- .file-item {
- display: flex;
- justify-content: space-between;
- align-items: center;
- padding: 10px;
- border: 1px solid #dee2e6;
- border-radius: 4px;
- margin-bottom: 10px;
- background-color: #fff;
- }
- .file-item button {
- margin-left: 10px;
- }
- ul {
- list-style-type: none;
- padding: 0;
- }
- #fileList {
- max-height: 300px;
- overflow-y: auto;
- border: 1px solid #ced4da;
- border-radius: 4px;
- padding: 10px;
- background-color: #fff;
- }
- #clearButton, #saveData {
- width: 100%;
- margin-top: 10px;
- }
- .download-link {
- color: #007bff;
- text-decoration: none;
- }
- .download-link:hover {
- text-decoration: underline;
- }
- #output {
- margin-top: 20px;
- padding: 10px;
- border: 1px solid #ced4da;
- border-radius: 4px;
- background-color: #fff;
- font-size: 0.9rem;
- color: #6c757d;
- }
- */
- /*Server Script
- (() => {
- if(input.action === "INIT") {
- let preferenceID = input.recordID
- const prefData = getPreferenceDefault(preferenceID)
- if(!!prefData) Object.assign(data, prefData)
- }
- if (input.action === "SAVE") {
- let preferenceID = input.recordID;
- function extractFields() {
- return { ...input }; // Возвращает все ключи и значения из obj
- }
- const saveData = extractFields();
- let preferenceValue = JSON.stringify(saveData);
- const preference2 = new SimpleRecord('c_checklist_task');
- preference2.get(preferenceID);
- preference2.setValue("value", preferenceValue);
- const res = preference2.update();
- if (!!Number(res)) ss.addInfoMessage('Изменения сохранены!');
- ss.setRedirect()
- }
- })();
- function getPreferenceDefault(preferenceID) {
- const preference = new SimpleRecord('c_checklist_task');
- preference.get(preferenceID);
- if(!preference.sys_id) return ""
- const data_ = JSON.parse(preference.value);
- return data_
- }
- */
- /*Client Script
- (async () => {
- window.s_widget_custom = window.s_widget_custom || {};
- const recordID = await getValueByKey('recordID')
- const varibleNameAttach = await getValueByKey('varibleNameAttach')
- await s_widget.setFieldValue('action', 'INIT');
- await s_widget.setFieldValue('recordID', recordID);
- await s_widget.setFieldValue('varibleNameAttach', varibleNameAttach);
- await s_widget.serverUpdate();
- await insertTemplateAsync()
- await init();
- // Асинхронная функция для получения значения по ключу из SimpleStorage
- async function getValueByKey(key) {
- if (SimpleStorage.hasItem(key)) {
- const value = SimpleStorage.getItem(key);
- // console.log(`Value for key "${key}":**`, value);
- return value;
- } else {
- console.log(`Key "${key}" not found in SimpleStorage.`);
- return null;
- }
- }
- // Асинхронная функция для вставки шаблона и инициализации
- async function insertTemplateAsync() {
- const template = `
- <input type="file" id="fileInput" multiple>
- <button id="addFiles">Add Files</button>
- <ul id="fileList">
- </ul>
- <button id="clearButton">Clear</button>
- <button id="saveData">SAVE</button>
- <div id="output"></div>
- `;
- // Ждем завершения потенциальных асинхронных операций
- await new Promise(resolve => setTimeout(resolve, 0));
- // Вставляем шаблон в элемент с id "init"
- const initElement = document.getElementById("init");
- if (initElement) {
- initElement.innerHTML = template;
- // После вставки вызываем init(), если она определена
- if (typeof init === "function") {
- init();
- }
- } else {
- console.error('Element with id "init" not found.');
- }
- }
- async function init() {
- const fileInput = document.getElementById('fileInput');
- const addFilesButton = document.getElementById('addFiles');
- const fileList = document.getElementById('fileList');
- const clearButton = document.getElementById('clearButton');
- const saveDataButton = document.getElementById('saveData');
- const outputDiv = document.getElementById('output');
- let filesArray = [];
- let base64Files = [];
- // Function to display a file in the list
- function displayFile(file) {
- // Проверяем, есть ли уже элемент с таким названием файла в списке
- if (Array.from(fileList.children).some(li => li.textContent.includes(file.name))) {
- return; // Пропускаем дублирование
- }
- const li = document.createElement('li');
- li.className = 'file-item';
- li.textContent = file.name;
- const removeButton = document.createElement('button');
- removeButton.textContent = 'Remove';
- removeButton.addEventListener('click', () => {
- filesArray = filesArray.filter(f => f !== file);
- fileList.removeChild(li);
- });
- const downloadButton = document.createElement('button');
- downloadButton.textContent = 'Download';
- downloadButton.addEventListener('click', async () => {
- const reader = new FileReader();
- reader.onload = function (e) {
- const downloadLink = document.createElement('a');
- downloadLink.href = e.target.result;
- downloadLink.download = file.name;
- downloadLink.click();
- };
- reader.readAsDataURL(file);
- });
- li.appendChild(removeButton);
- li.appendChild(downloadButton);
- fileList.appendChild(li);
- }
- // Add multiple files to the list
- addFilesButton.addEventListener('click', () => {
- const files = Array.from(fileInput.files);
- if (!files.length) {
- // alert('No files selected!');
- return;
- }
- files.forEach(file => {
- if (!filesArray.some(existingFile => existingFile.name === file.name)) {
- filesArray.push(file);
- displayFile(file);
- }
- });
- fileInput.value = ''; // Clear input
- });
- // Clear all files and Base64 data
- clearButton.addEventListener('click', () => {
- filesArray = [];
- base64Files = [];
- fileList.innerHTML = '';
- outputDiv.innerHTML = '';
- // alert('All files and data cleared!');
- });
- // Save data
- // Save data with a delay
- saveDataButton.addEventListener('click', async () => {
- if (!filesArray.length) {
- base64Files = []
- const data = {
- filesArray: filesArray.map(file => ({ name: file.name, type: file.type })),
- base64Files
- };
- fileList.innerHTML = '';
- outputDiv.innerHTML = '';
- // Уведомление пользователю
- // alert('No files to save! All data has been cleared.');
- return;
- }
- // Блокируем кнопку
- saveDataButton.disabled = true;
- base64Files = [];
- const filePromises = filesArray.map(file => {
- return new Promise((resolve) => {
- const reader = new FileReader();
- reader.onload = (e) => {
- const base64 = e.target.result;
- resolve({ name: file.name, type: file.type, base64 });
- };
- reader.readAsDataURL(file);
- });
- });
- try {
- base64Files = await Promise.all(filePromises);
- const data = {
- filesArray: filesArray.map(file => ({ name: file.name, type: file.type })),
- base64Files
- };
- // Сохраняем данные
- const varibleNameAttach = await getValueByKey('varibleNameAttach')
- s_widget.setFieldValue(varibleNameAttach, JSON.stringify(data, null, 2));
- s_widget.setFieldValue('action', 'SAVE');
- s_widget.serverUpdate();
- } catch (error) {
- console.error('Error saving data:', error);
- // alert('An error occurred while saving data!');
- } finally {
- // Устанавливаем задержку перед разблокировкой кнопки
- setTimeout(() => {
- saveDataButton.disabled = false;
- }, 500); // Задержка в 0,5 секунды
- }
- });
- // Load files from inputData
- async function loadFilesFromInputData(data) {
- if (data.filesArray && Array.isArray(data.filesArray) && data.base64Files) {
- data.base64Files.forEach(base64File => {
- const blob = base64ToBlob(base64File.base64, base64File.type || "application/octet-stream");
- const mockFile = new File([blob], base64File.name, { type: base64File.type || "" });
- // Проверяем, что файл не добавлен ранее
- if (!filesArray.some(existingFile => existingFile.name === mockFile.name && existingFile.size === mockFile.size)) {
- filesArray.push(mockFile);
- displayFile(mockFile);
- }
- });
- }
- }
- const varibleNameAttach = await getValueByKey('varibleNameAttach')
- const inputData = await s_widget.getFieldValue(varibleNameAttach) || 'No Set'
- if (inputData.trim()) {
- try {
- const inputDataObj = JSON.parse(inputData);
- // Загрузка файлов из данных
- async function loadFilesFromInputData(data) {
- if (data.filesArray && Array.isArray(data.filesArray) && data.base64Files) {
- data.base64Files.forEach(base64File => {
- const blob = base64ToBlob(base64File.base64, base64File.type || "application/octet-stream");
- const mockFile = new File([blob], base64File.name, { type: base64File.type || "" });
- filesArray.push(mockFile);
- displayFile(mockFile);
- });
- }
- }
- // Функция для преобразования Base64 в Blob
- function base64ToBlob(base64, mimeType) {
- const byteString = atob(base64.split(',')[1]);
- const arrayBuffer = new ArrayBuffer(byteString.length);
- const uint8Array = new Uint8Array(arrayBuffer);
- for (let i = 0; i < byteString.length; i++) {
- uint8Array[i] = byteString.charCodeAt(i);
- }
- return new Blob([arrayBuffer], { type: mimeType });
- }
- await loadFilesFromInputData(inputDataObj);
- } catch (error) {
- console.error("Failed to parse inputData:", error);
- }
- }
- }
- })();
- */
Add Comment
Please, Sign In to add comment