-
Notifications
You must be signed in to change notification settings - Fork 8.2k
/
post-cooked.js
326 lines (274 loc) · 9.66 KB
/
post-cooked.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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
import highlightHTML, { unhighlightHTML } from "discourse/lib/highlight-html";
import I18n from "I18n";
import { ajax } from "discourse/lib/ajax";
import highlightSearch from "discourse/lib/highlight-search";
import { iconHTML } from "discourse-common/lib/icon-library";
import { isValidLink } from "discourse/lib/click-track";
import { number } from "discourse/lib/formatter";
import { spinnerHTML } from "discourse/helpers/loading-spinner";
let _beforeAdoptDecorators = [];
let _afterAdoptDecorators = [];
// Don't call this directly: use `plugin-api/decorateCookedElement`
export function addDecorator(callback, { afterAdopt = false } = {}) {
if (afterAdopt) {
_afterAdoptDecorators.push(callback);
} else {
_beforeAdoptDecorators.push(callback);
}
}
export function resetDecorators() {
_beforeAdoptDecorators = [];
_afterAdoptDecorators = [];
}
let detachedDocument = document.implementation.createHTMLDocument("detached");
function createDetachedElement(nodeName) {
return detachedDocument.createElement(nodeName);
}
export default class PostCooked {
constructor(attrs, decoratorHelper, currentUser) {
this.attrs = attrs;
this.expanding = false;
this._highlighted = false;
this.decoratorHelper = decoratorHelper;
this.currentUser = currentUser;
this.ignoredUsers = this.currentUser
? this.currentUser.ignored_users
: null;
}
update(prev) {
if (
prev.attrs.cooked !== this.attrs.cooked ||
prev.attrs.highlightTerm !== this.attrs.highlightTerm
) {
return this.init();
}
}
init() {
const cookedDiv = this._computeCooked();
const $cookedDiv = $(cookedDiv);
this._insertQuoteControls($cookedDiv);
this._showLinkCounts($cookedDiv);
this._applySearchHighlight($cookedDiv);
this._decorateAndAdopt(cookedDiv);
return cookedDiv;
}
_decorateAndAdopt(cooked) {
_beforeAdoptDecorators.forEach((d) => d(cooked, this.decoratorHelper));
document.adoptNode(cooked);
_afterAdoptDecorators.forEach((d) => d(cooked, this.decoratorHelper));
}
_applySearchHighlight($html) {
const html = $html[0];
const highlight = this.attrs.highlightTerm;
if (highlight && highlight.length > 2) {
if (this._highlighted) {
unhighlightHTML(html);
}
highlightSearch(html, highlight, { defaultClassName: true });
this._highlighted = true;
} else if (this._highlighted) {
unhighlightHTML(html);
this._highlighted = false;
}
}
_showLinkCounts($html) {
const linkCounts = this.attrs.linkCounts;
if (!linkCounts) {
return;
}
// find the best <a> element in each onebox and display link counts only
// for that one (the best element is the most significant one to the
// viewer)
const bestElements = new Map();
$html[0].querySelectorAll("aside.onebox").forEach((onebox) => {
// look in headings first
for (let i = 1; i <= 6; ++i) {
const hLinks = onebox.querySelectorAll(`h${i} a[href]`);
if (hLinks.length > 0) {
bestElements.set(onebox, hLinks[0]);
return;
}
}
// use the header otherwise
const hLinks = onebox.querySelectorAll("header a[href]");
if (hLinks.length > 0) {
bestElements.set(onebox, hLinks[0]);
}
});
linkCounts.forEach((lc) => {
if (!lc.clicks || lc.clicks < 1) {
return;
}
$html.find("a[href]").each((i, e) => {
const $link = $(e);
const href = $link.attr("href");
let valid = href === lc.url;
// this might be an attachment
if (lc.internal && /^\/uploads\//.test(lc.url)) {
valid = href.includes(lc.url);
}
// Match server-side behaviour for internal links with query params
if (lc.internal && /\?/.test(href)) {
valid = href.split("?")[0] === lc.url;
}
// don't display badge counts on category badge & oneboxes (unless when explicitly stated)
if (valid && isValidLink($link[0])) {
const $onebox = $link.closest(".onebox");
if (
$onebox.length === 0 ||
!bestElements.has($onebox[0]) ||
bestElements.get($onebox[0]) === $link[0]
) {
const title = I18n.t("topic_map.clicks", { count: lc.clicks });
$link.append(
` <span class='badge badge-notification clicks' title='${title}'>${number(
lc.clicks
)}</span>`
);
}
}
});
});
}
_toggleQuote($aside) {
if (this.expanding) {
return;
}
this.expanding = true;
const blockQuote = $aside[0].querySelector("blockquote");
$aside.data("expanded", !$aside.data("expanded"));
const finished = () => (this.expanding = false);
if ($aside.data("expanded")) {
this._updateQuoteElements($aside, "chevron-up");
// Show expanded quote
$aside.data("original-contents", blockQuote.innerHTML);
const originalText =
blockQuote.textContent.trim() ||
this.attrs.cooked.querySelector("blockquote").textContent.trim();
blockQuote.innerHTML = spinnerHTML;
let topicId = this.attrs.topicId;
if ($aside.data("topic")) {
topicId = $aside.data("topic");
}
const postId = parseInt($aside.data("post"), 10);
topicId = parseInt(topicId, 10);
ajax(`/posts/by_number/${topicId}/${postId}`)
.then((result) => {
const post = this.decoratorHelper.getModel();
const quotedPosts = post.quoted || {};
quotedPosts[result.id] = result;
post.set("quoted", quotedPosts);
const div = createDetachedElement("div");
div.classList.add("expanded-quote");
div.dataset.postId = result.id;
div.innerHTML = result.cooked;
this._decorateAndAdopt(div);
highlightHTML(div, originalText, {
matchCase: true,
});
blockQuote.innerHTML = "";
blockQuote.appendChild(div);
finished();
})
.catch((e) => {
if ([403, 404].includes(e.jqXHR.status)) {
const icon = e.jqXHR.status === 403 ? "lock" : "far-trash-alt";
blockQuote.innerHTML = `<div class='expanded-quote icon-only'>${iconHTML(
icon
)}</div>`;
}
});
} else {
// Hide expanded quote
this._updateQuoteElements($aside, "chevron-down");
blockQuote.innerHTML = $aside.data("original-contents");
finished();
}
return false;
}
_urlForPostNumber(postNumber) {
return postNumber > 0
? `${this.attrs.topicUrl}/${postNumber}`
: this.attrs.topicUrl;
}
_updateQuoteElements($aside, desc) {
let navLink = "";
const quoteTitle = I18n.t("post.follow_quote");
let postNumber = $aside.data("post");
let topicNumber = $aside.data("topic");
// If we have a post reference
if (topicNumber && topicNumber === this.attrs.topicId && postNumber) {
let icon = iconHTML("arrow-up");
navLink = `<a href='${this._urlForPostNumber(
postNumber
)}' title='${quoteTitle}' class='btn-flat back'>${icon}</a>`;
}
// Only add the expand/contract control if it's not a full post
let expandContract = "";
const isExpanded = $aside.data("expanded") === true;
if (!$aside.data("full")) {
let icon = iconHTML(desc, { title: "post.expand_collapse" });
const quoteId = $aside.find("blockquote").attr("id");
expandContract = `<button aria-controls="${quoteId}" aria-expanded="${isExpanded}" class="quote-toggle btn-flat">${icon}</button>`;
$(".title", $aside).css("cursor", "pointer");
}
if (this.ignoredUsers && this.ignoredUsers.length > 0) {
const username = $aside.find(".title").text().trim().slice(0, -1);
if (username.length > 0 && this.ignoredUsers.includes(username)) {
$aside.find("p").remove();
$aside.addClass("ignored-user");
}
}
$(".quote-controls", $aside).html(expandContract + navLink);
}
_insertQuoteControls($html) {
const $quotes = $html.find("aside.quote");
if ($quotes.length === 0) {
return;
}
$quotes.each((index, e) => {
const $aside = $(e);
if ($aside.data("post")) {
const quoteId = `quote-id-${$aside.data("topic")}-${$aside.data(
"post"
)}-${index}`;
$aside.find("blockquote").attr("id", quoteId);
this._updateQuoteElements($aside, "chevron-down");
const $title = $(".title", $aside);
// If post/topic is not found then display username, skip controls
if (e.classList.contains("quote-post-not-found") && $title.length) {
e.querySelector(".title").innerHTML = e.dataset.username;
return;
}
// Unless it's a full quote, allow click to expand
if (!($aside.data("full") || $title.data("has-quote-controls"))) {
$title.on("click", (e2) => {
let $target = $(e2.target);
if ($target.closest("a").length) {
return true;
}
this._toggleQuote($aside);
});
$title.data("has-quote-controls", true);
}
}
});
}
_computeCooked() {
const cookedDiv = createDetachedElement("div");
cookedDiv.classList.add("cooked");
if (
(this.attrs.firstPost || this.attrs.embeddedPost) &&
this.ignoredUsers &&
this.ignoredUsers.length > 0 &&
this.ignoredUsers.includes(this.attrs.username)
) {
cookedDiv.classList.add("post-ignored");
cookedDiv.innerHTML = I18n.t("post.ignored");
} else {
cookedDiv.innerHTML = this.attrs.cooked;
}
return cookedDiv;
}
}
PostCooked.prototype.type = "Widget";