on-codemerge
Version:
A WYSIWYG editor for on-codemerge is a user-friendly interface that allows users to edit and view their code in real time, exactly as it will appear in the final product
141 lines (123 loc) • 5.31 kB
JavaScript
/*! on-codemerge v1.3.1 @author Pavel Kuzmin @license MIT @homepage https://s00d.github.io/on-codemerge/ @repository git+https://github.com/s00d/on-codemerge.git Copyright (c) 2026 Pavel Kuzmin - Built on 2026-07-02T13:39:17.947Z */
var i = Object.defineProperty;
var c = (a, e, t) => e in a ? i(a, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : a[e] = t;
var l = (a, e, t) => c(a, typeof e != "symbol" ? e + "" : e, t);
import { Table as d } from "../components/Table.mjs";
class m {
constructor(e, t, r) {
l(this, "options");
l(this, "range");
l(this, "editor");
this.editor = e, this.options = t, this.range = r.cloneRange();
}
execute() {
const e = this.options.tableId || `imported-table-${Date.now()}`, t = new d({ hasHeader: !1, rows: 1, cols: 1 }, this.editor), r = t.getElement();
r.id = e, r.classList.add("imported-table"), r.setAttribute("data-import-url", this.options.url), this.options.selector && r.setAttribute("data-import-selector", this.options.selector);
const s = r.querySelector(".table-cell");
s && (s.textContent = "Импорт таблицы..."), this.range.deleteContents();
const o = document.createDocumentFragment();
o.appendChild(r);
const n = document.createElement("script");
n.type = "text/javascript", n.textContent = this.generateImportScript(e, this.options), o.appendChild(n), this.range.insertNode(o), t.focusFirstCell();
}
generateImportScript(e, t) {
return `
(function() {
var table = document.getElementById('${e}');
if (!table) return;
var url = table.getAttribute('data-import-url');
var selector = table.getAttribute('data-import-selector') || 'table';
function showLoading() {
table.innerHTML = '<div class="table-row"><div class="table-cell" style="text-align:center;padding:20px;">Импорт таблицы...</div></div>';
}
function showError(msg) {
table.innerHTML = '<div class="table-row"><div class="table-cell" style="text-align:center;padding:20px;color:#e74c3c;">Ошибка импорта: ' + msg + '</div></div>';
}
function parseHTMLTable(htmlTable) {
var rows = [];
var headerRow = null;
// Обрабатываем заголовки
var headers = htmlTable.querySelectorAll('thead tr, tr:first-child');
if (headers.length > 0) {
var headerCells = headers[0].querySelectorAll('th, td');
headerRow = Array.from(headerCells).map(function(cell) {
return cell.textContent.trim();
});
}
// Обрабатываем строки данных
var dataRows = htmlTable.querySelectorAll('tbody tr, tr:not(:first-child)');
if (dataRows.length === 0) {
dataRows = htmlTable.querySelectorAll('tr');
}
dataRows.forEach(function(row) {
var cells = row.querySelectorAll('td, th');
var rowData = Array.from(cells).map(function(cell) {
return cell.textContent.trim();
});
if (rowData.length > 0) {
rows.push(rowData);
}
});
return { headers: headerRow, rows: rows };
}
function renderTable(data) {
table.innerHTML = '';
// Добавляем заголовки если есть
if (data.headers && data.headers.length > 0) {
var headerRow = document.createElement('div');
headerRow.className = 'table-header-row';
data.headers.forEach(function(header) {
var cell = document.createElement('div');
cell.className = 'table-header-cell';
cell.textContent = header;
headerRow.appendChild(cell);
});
table.appendChild(headerRow);
}
// Добавляем строки данных
data.rows.forEach(function(row) {
var rowDiv = document.createElement('div');
rowDiv.className = 'table-row';
row.forEach(function(cellData) {
var cell = document.createElement('div');
cell.className = 'table-cell';
cell.textContent = cellData;
rowDiv.appendChild(cell);
});
table.appendChild(rowDiv);
});
// Если нет данных, показываем сообщение
if (data.rows.length === 0) {
table.innerHTML = '<div class="table-row"><div class="table-cell">Таблица не найдена</div></div>';
}
}
showLoading();
// Используем прокси для обхода CORS (если доступен)
var proxyUrl = 'https://api.allorigins.win/raw?url=';
fetch(proxyUrl + encodeURIComponent(url))
.then(function(resp) {
if (!resp.ok) throw new Error('HTTP ' + resp.status);
return resp.text();
})
.then(function(html) {
// Создаем временный DOM для парсинга HTML
var parser = new DOMParser();
var doc = parser.parseFromString(html, 'text/html');
// Ищем таблицу по селектору
var htmlTable = doc.querySelector(selector);
if (!htmlTable) {
throw new Error('Таблица не найдена по селектору: ' + selector);
}
var data = parseHTMLTable(htmlTable);
renderTable(data);
})
.catch(function(e) {
showError(e.message);
});
})();
`;
}
}
export {
m as ImportTableFromHTMLCommand
};