-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathplugin.js
More file actions
241 lines (207 loc) · 9.52 KB
/
Copy pathplugin.js
File metadata and controls
241 lines (207 loc) · 9.52 KB
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
CKEDITOR.plugins.add('tweet_splitter', {
init: function(editor) {
editor.addContentsCss(this.path + 'styles.css');
editor.addCommand('insertTweetSplitter', {
exec: function(editor) {
const separator = CKEDITOR.dom.element.createFromHtml(
`<div class="tweet-separator" contenteditable="false">
<span class="tweet-separator-line"></span>
<span class="tweet-separator-text">Новый твит
<span class="tweet-separator-remove" title="Объединить твиты" role="button" tabindex="0" aria-label="Объединить твиты">
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M12 4L4 12M4 4L12 12" stroke="#666" stroke-width="2" stroke-linecap="round"/>
</svg>
</span>
</span>
<span class="tweet-separator-line"></span>
</div>`
);
editor.insertElement(separator);
scheduleTweetCountersUpdate(editor);;
const nativeDoc = editor.document.$;
if (!nativeDoc._tweetSplitterRemoveBound) {
nativeDoc._tweetSplitterRemoveBound = true;
nativeDoc.addEventListener('click', (ev) => {
const btn = ev.target.closest && ev.target.closest('.tweet-separator-remove');
if (!btn) return;
const sep = btn.closest('.tweet-separator');
if (sep) {
sep.remove();
scheduleTweetCountersUpdate(editor);
editor.focus();
}
});
nativeDoc.addEventListener('keydown', (ev) => {
if ((ev.key === 'Enter' || ev.key === ' ') && ev.target.classList && ev.target.classList.contains('tweet-separator-remove')) {
ev.preventDefault();
ev.target.click();
}
});
}
}
});
editor.ui.addButton('TweetSplitter', {
label: 'Разбить на твиты',
command: 'insertTweetSplitter',
toolbar: 'insert',
icon: 'horizontalrule',
});
editor.on('instanceReady', function() {
updateTweetCounters(editor);
});
editor.on('key', function() {
scheduleTweetCountersUpdate(editor);;
});
editor.on('afterCommandExec', function() {
scheduleTweetCountersUpdate(editor);;
});
editor.on('contentDom', function() {
editor.document.on('copy', function(evt) {
const e = evt.data.$; // нативный ClipboardEvent
e.preventDefault(); // отменяем стандартное копирование
let html = editor.getSelectedHtml(true);
// Удаляем div tweet-separator и tweet-char-counter целиком
html = html.replace(/<div class="tweet-(separator|char-counter)[^>]*>[\s\S]*?<\/div>/g, '');
// Убираем все теги, оставляем только текст
let text = html.replace(/<[^>]+>/g, '');
// Кладём своё
if (e.clipboardData && e.clipboardData.setData) {
e.clipboardData.setData('text/plain', text);
e.clipboardData.setData('text/html', text);
} else if (window.clipboardData && window.clipboardData.setData) {
// IE fallback
window.clipboardData.setData('Text', text);
}
});
});
}
});
const TWEET_LIMIT = 280;
function twitterLength(text) {
if (!text) return 0;
// Заменяем http/https ссылки и bare domains на 23 символа
const urlRegex = /\b((https?:\/\/[^\s]+)|([a-z0-9.-]+\.[a-z]{2,})(\/[^\s]*)?)/gi;
text = text.replace(urlRegex, 'x'.repeat(23));
// Эмодзи считаем за 2 символа
const emojiRegex = /[\p{Emoji_Presentation}\p{Emoji}\u200d]/gu;
text = text.replace(emojiRegex, 'xx');
return text.length;
}
const container = editor.container && editor.container.$;
const form = container && container.closest ? container.closest('form') : null;
if (form && !form._tweetSplitterBound) {
form._tweetSplitterBound = true;
form.addEventListener('submit', (e) => {
if (!validateTweets(editor)) {
e.preventDefault();
alert("❌ Нельзя сохранить: один или несколько твитов превышают 280 символов!");
}
});
}
function validateTweets(editor) {
const editorData = editor.getData();
const tempDiv = document.createElement('div');
tempDiv.innerHTML = editorData;
const nodes = Array.from(tempDiv.childNodes);
let currentTweet = [];
const tweets = [];
nodes.forEach(node => {
if (node.className === 'tweet-separator') {
tweets.push(currentTweet);
currentTweet = [];
} else {
currentTweet.push(node);
}
});
if (currentTweet.length) tweets.push(currentTweet);
// Проверяем длину
for (let tweet of tweets) {
const div = document.createElement('div');
tweet.forEach(n => div.appendChild(n.cloneNode(true)));
const text = div.textContent || div.innerText || '';
if (twitterLength(text.trim()) > TWEET_LIMIT) {
return false;
}
}
return true;
}
function scheduleTweetCountersUpdate(editor, delay = 120) {
if (editor._tweetCountersTimer) clearTimeout(editor._tweetCountersTimer);
editor._tweetCountersTimer = setTimeout(() => updateTweetCounters(editor), delay);
}
function updateTweetCounters(editor) {
const editorDom = editor.document.$;
// Удаляем старые элементы
editorDom.querySelectorAll('.tweet-numbering, .tweet-arrow, .tweet-char-counter').forEach(el => el.remove());
const content = editor.getData();
const tweetsHtml = content.split(/<div class="tweet-separator"[^>]*>[\s\S]*?<\/div>/g);
const separators = editorDom.querySelectorAll('.tweet-separator');
// Собираем все узлы редактора
let nodes = Array.from(editorDom.body.childNodes);
let tweetNodes = [];
let currentTweet = [];
// Разделяем узлы на твиты
nodes.forEach(node => {
if (node.className === 'tweet-separator') {
if (currentTweet.length) {
tweetNodes.push(currentTweet);
currentTweet = [];
}
} else {
currentTweet.push(node);
}
});
if (currentTweet.length) {
tweetNodes.push(currentTweet);
}
tweetNodes.forEach((tweet, index) => {
const tempDiv = document.createElement("div");
tempDiv.innerHTML = tweetsHtml[index] || '';
const text = tempDiv.textContent || tempDiv.innerText || "";
const textLength = twitterLength(text.trim());
const tweetNumbering = (tweetNodes.length > 1) ? `${index + 1}/${tweetNodes.length} ` : '';
const arrow = (index < tweetNodes.length - 1) ? ' ->' : '';
const tweetNumberingLength = tweetNumbering.length;
const arrowLength = arrow.length;
const finalLength = textLength + tweetNumberingLength + arrowLength;
// Находим первый и последний <p> для твита
const firstP = tweet.find(node => node.nodeName === 'P');
const lastP = tweet.slice().reverse().find(node => node.nodeName === 'P') || firstP;
// Счётчик
const counter = document.createElement('div');
counter.className = 'tweet-char-counter';
counter.setAttribute('contenteditable', 'false');
counter.innerText = `[${finalLength}/${TWEET_LIMIT}]`;
if (finalLength > TWEET_LIMIT) {
counter.style.color = 'red';
}
// Нумерация
if (tweetNumbering && firstP) {
const numbering = document.createElement('span');
numbering.className = 'tweet-numbering';
numbering.setAttribute('contenteditable', 'false');
numbering.innerText = tweetNumbering;
firstP.insertBefore(numbering, firstP.firstChild);
}
// Стрелка
if (arrow && lastP) {
// Убираем лишние <br /> в конце параграфа
while (lastP.lastChild && lastP.lastChild.nodeName === 'BR') {
lastP.removeChild(lastP.lastChild);
}
const arrowEl = document.createElement('span');
arrowEl.className = 'tweet-arrow';
arrowEl.setAttribute('contenteditable', 'false');
arrowEl.innerText = arrow;
lastP.appendChild(arrowEl);
}
// Вставка счётчика
if (index === 0) {
editorDom.body.insertBefore(counter, editorDom.body.firstChild);
} else if (separators[index - 1]) {
separators[index - 1].parentNode.insertBefore(counter, separators[index - 1].nextSibling);
} else {
editorDom.body.appendChild(counter);
}
});
}