-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommon.js
267 lines (245 loc) · 10.1 KB
/
common.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
const ID = {
DB_TB: '664677863',
API: '671341366',
ROLE: '674301853',
FORM: '664677976',
FT: '664677853',
BT: '664676998'
}
const SERVER_URL = 'https://confluence.rt.ru'
function createIdLink(pageTitle, headerText) {
var id = "id-" + pageTitle + "-" + headerText;
return id.replace(/\s/g, "");
}
function createHeader(lvl, text, pageTitle) {
try {
id = createIdLink(pageTitle, text)
const header = $("<" + lvl + "/>").text(text).attr("id", id);
return header[0];
} catch (error) {
console.log("Error in createHeader function:", error);
}
}
function fillCell(cell, content) {
if (content.rowspan) {
cell.attr("rowspan", content.rowspan).css("vertical-align", "middle");
}
if (content.link) {
const a = $("<a>").attr("href", content.link).text(content.text);
cell.append(a);
} else {
cell.text(content.text);
}
return cell;
}
function createTable(arrObjects) { // двумерный массив объектов {text, link, rowspan}
try {
arrObjects.slice(1).sort((a, b) => a[0].text.localeCompare(b[0].text)); // сортировка по полю текст
let indexLast = 0;
for (i = 1; i < arrObjects.length; i++) { //объединение одинаковых названий
if (arrObjects[i][0].text != arrObjects[indexLast][0].text) {
if (i - indexLast > 1) {
arrObjects[indexLast][0].rowspan = i - indexLast;
}
indexLast = i;
continue;
} else if (i == arrObjects.length - 1) {
arrObjects[indexLast][0].rowspan = i - indexLast + 1;
}
arrObjects[i].splice(0, 1);
}
const table = $("<table>").addClass("confluenceTable").addClass("wrapped");
// Создаем заголовок таблицы
const head = arrObjects[0];
const tableHead = $("<thead>");
const headRow = $("<tr>");
head.forEach(cellData => {
var th = $("<th>").addClass("confluenceTh");
th = fillCell(th, cellData);
headRow.append(th);
});
tableHead.append(headRow);
table.append(tableHead);
// Создаем тело таблицы
const tableBody = $("<tbody>");
for (let i = 1; i < arrObjects.length; i++) {
const row = arrObjects[i];
const bodyRow = $("<tr>");
row.forEach(cellData => {
var td = $("<td>").addClass("confluenceTd");
td = fillCell(td, cellData);
bodyRow.append(td);
});
tableBody.append(bodyRow);
}
const divWrap = $("<div>").addClass("table-wrap");
divWrap.append(table.append(tableBody));
return divWrap[0];
} catch (error) {
console.log("Error in createTable function:", error);
}
}
function splitTable(selector, columnNumber) {
try {
const sourceTable = $(selector)[0];
let groupColumnValue = {};
$(sourceTable).find("tr").each(function (index, row) {
if (index !== 0) { // Skip the header row
const columnValue = $(row).find('td').eq(columnNumber).text();
if (!groupColumnValue[columnValue]) {
groupColumnValue[columnValue] = [];
}
groupColumnValue[columnValue].push(row);
}
});
const mainContent = $("#main-content");
const pageTitle = $("#title-text").text().trim();
for (const columnValue in groupColumnValue) {
const header = $(createHeader('h2', columnValue, pageTitle));
mainContent.append(header);
const newTable = createTable($(sourceTable).find("tr")[0].cloneNode(true),
groupColumnValue[columnValue]);
mainContent.append(newTable);
}
} catch (error) {
console.log("Error in splitTable function:", error);
}
}
function addLinkToColumn(link, tableSelector, columnNumber) {
$(document).ready(function () {
const sourceTable = $(tableSelector);
fetch(link)
.then(response => {
if (!response.ok) {
new Error('Network response was not ok');
}
return response.text();
})
.then(html => {
pageTitle = html.match(/<title>(.*?) -.*?<\/title>/i)[1];
sourceTable.find('tr').each(function (index, row) {
if (index > 0) {
const tdElements = $(row).find('td');
if (tdElements.length >= columnNumber) {
const cell = $(row).find(`td:eq(${columnNumber - 1})`);
const cellText = cell.text();
let cellLink = link + '#' + createIdLink(pageTitle, cellText);
const linkElement = $('<a></a>').attr('href', cellLink).attr('rel', 'nofollow').text(cellText);
cell.empty().append(linkElement);
} else {
console.log("Not enough <td> elements in the row.");
}
}
});
})
.catch(error => {
console.error('Error during fetch:', error);
});
});
}
async function getTypeOfPage(pageId) {
var parentsIds = [];
await $.get(`${SERVER_URL}/rest/api/content/${pageId}?expand=ancestors`)
.done(function (data) {
ancestors = data.ancestors; //поиск родителей
parentsIds = $.map(ancestors, function (obj) {
return obj.id;
});
parentsIds.reverse();
})
.fail(function (error) {
console.log('Error in function getTypeOfPage: ', error);
})
for (const id of parentsIds) {
for (const type in ID) {
if (id == ID[type]) {
return ID[type];
}
}
}
return NaN;
}
async function getChildPages(pageId) {
var arr = [];
await $.get(`${SERVER_URL}/rest/api/content/${pageId}/child/page`)
.done(function (data) {
re = /(.*?)\s\((.*?)\)/;
arr = data.results.map(obj => ({
ruName: obj.title.match(re)[1],
enName: obj.title.match(re)[2],
link: obj._links.webui
}));
})
.fail(function (error) {
console.log('Error in function getDbTbPages: ', error);
})
return arr;
}
async function addUsingOnPage(pageType) {
let cfPages = { [ID.DB_TB]: await getChildPages(ID.DB_TB) };
$(document).ready(function () {
const mainContent = $("#main-content");
const pageTitle = $("#title-text").text().trim();
switch (pageType) {
case ID.API:
/*
Заполнение раздела "База данных"
*/
sourceTable = $('#description_table')[0]
if (sourceTable) {
let foundTables = []; //массив найденных таблиц и атрибутов в них
$(sourceTable).find('tr').each(function (index, row) {
let re = /(\w*)\.(\w*)/
if (index > 0) { // кроме заголовка
$(row).find('td').each(function () { //ячейка
if ($(this).text().match(re)) {
foundTables.push({
tbName: $(this).text().match(re)[1],
attrName: $(this).text().match(re)[2]
});
}
})
}
});
if (foundTables.length) {
const h3db = $(`#${pageTitle}-Базаданных`.replace(/ /, '').replace(/\//, '\\/'))[0];
let table = [];
for (foundTable of foundTables) {
cfPages[[ID.DB_TB]].forEach(function (page) {
if (foundTable.tbName == page.enName) {
table.push([{
text: `${page.ruName} (${page.enName})`,
link: page.link
},
{
text: foundTable.attrName
}])
}
})
};
if (table.length) {
table.unshift([{ text: "Таблица" }, { text: "Атрибут" }]);
h3db.after(createTable(table));
} else {
h3db
.after($("<p>").text("Использование атрибутов таблиц БД не найдено."))
.after($("<p>").text("Это может быть произойти по следующим причинам:"))
.after($("<p>").text("- неправильно прописаны атрибуты в таблице (пример: table.attribute);"))
.after($("<p>").text("- статья про таблицу ещё не заведена, названа неправильно или расположена в необычном месте.1"))
}
}
}
/*
Заполнение раздела "Ролевая система"
*/
}
})
}
const pageId = $(location).attr('href').match(/.*=(\d*)/)[1];
pageType = "";
(async function () {
pageType = await getTypeOfPage(pageId);
if (pageType) {
addUsingOnPage(pageType);
}
})();