익명 게시물을 더 익명화하기 위해, 익명 게시만 활성화된 카테고리에서 인용 표시가 어떻게 표시되는지 오버라이드하려고 합니다. 즉, 기본 설정인
anonymous4302934
some quoted text
대신, 다음과 같이 표시되기를 원합니다.
Anonymous:
some quoted text
툴바 버튼을 통해 인용되는 텍스트는 이 가이드를 기반으로 오버라이드할 수 있습니다(아래에 컨테이너 조회를 추가해야 했는데, 여기의 우회 조치에 따라 작동하게 되었습니다).
코어 파일을 샅샅이 살펴보았지만, 텍스트를 선택하고 인용 버튼을 클릭하여 컴포저에 인용이 삽입될 때 인용이 정확히 어디서 생성되는지 파악할 수 없습니다. quote-button.js의 _selectionChanged()에서 선택된 텍스트가 blockquote 안에 있으면 opts.username이 설정되는 것을 볼 수 있지만, 이를 수정하여 opts.username을 수동으로 설정해도 아무런 영향이 없습니다.
이것이 오버라이드/수정해야 할 올바른 대상이며, modifyClass를 사용하는 것이 이 문제를 해결하는 올바른 방법인가요?
<script type="text/discourse-plugin" version="0.8">
const controller = api.container.lookup('controller:topic');
const anon_categories = [5, 6, 14, 15, 16, 17, 18]
function buildQuote(post, contents, opts = {}) {
if (!post || !contents) {
return "";
}
let anon_name = ``;
// console.log(anon_categories, controller.get("model.category_id"))
if (anon_categories.includes(controller.get("model.category_id"))) {
anon_name = `Anonymous`;
} else {
anon_name = opts.username || post.username;
}
const params = [
anon_name,
`post:${opts.post || post.post_number}`,
`topic:${opts.topic || post.topic_id}`
];
if (opts.full) params.push("full:true");
return `\n[quote="${params.join(", ")}"]\n${contents.trim()}\n[/quote]\n\n`;
}
api.modifyClass('controller:composer', {
pluginId: 'anonymize-quotes',
actions: {
importQuote(toolbarEvent) {
const postStream = this.get("topic.postStream");
let postId = this.get("model.post.id");
// 현재 게시물이 없으면 스트림의 첫 번째 게시물 ID를 사용합니다.
if (!postId && postStream) {
postId = postStream.get("stream.firstObject");
}
// 게시물을 편집 중이라면, 인용을 가져올 때 답글을 가져옵니다.
if (this.get("model.editingPost")) {
const replyToPostNumber = this.get("model.post.reply_to_post_number");
if (replyToPostNumber) {
const replyPost = postStream.posts.findBy(
"post_number",
replyToPostNumber
);
if (replyPost) {
postId = replyPost.id;
}
}
}
if (postId) {
this.set("model.loading", true);
return this.store.find("post", postId).then(post => {
const quote = buildQuote(post, post.raw, {
full: true
});
toolbarEvent.addText(quote);
this.set("model.loading", false);
});
}
}
}
});
api.modifyClass('component:quote-button', {
pluginId: 'anonymize-quotes',
actions: {
_selectionChanged() {
if (this._displayFastEditInput) {
return;
}
const quoteState = this.quoteState;
const selection = window.getSelection();
if (selection.isCollapsed) {
if (this.visible) {
this._hideButton();
}
return;
}
// 1개의 게시물 *안에서만* 콘텐츠를 선택했는지 확인합니다.
let firstRange, postId;
for (let r = 0; r < selection.rangeCount; r++) {
const range = selection.getRangeAt(r);
const $selectionStart = $(range.startContainer);
const $ancestor = $(range.commonAncestorContainer);
if ($selectionStart.closest(".cooked").length === 0) {
return;
}
firstRange = firstRange || range;
postId = postId || $ancestor.closest(".boxed, .reply").data("post-id");
if ($ancestor.closest(".contents").length === 0 || !postId) {
if (this.visible) {
this._hideButton();
}
return;
}
}
const _selectedElement = selectedElement();
const _selectedText = selectedText();
const $selectedElement = $(_selectedElement);
const cooked =
$selectedElement.find(".cooked")[0] ||
$selectedElement.closest(".cooked")[0];
// 긴 게시물에서 마크다운을 계산하는 데 많은 시간이 소요됩니다.
// 이 코드는 패스트 트랙(fast track)이 불가능할 때만 계산하려고 시도합니다.
let opts = {
full:
selectedRange().startOffset > 0
? false
: _selectedText === toMarkdown(cooked.innerHTML),
};
for (
let element = _selectedElement;
element && element.tagName !== "ARTICLE";
element = element.parentElement
) {
if (element.tagName === "ASIDE" && element.classList.contains("quote")) {
opts.username = element.dataset.username || getQuoteTitle(element);
opts.post = element.dataset.post;
opts.topic = element.dataset.topic;
break;
}
}
opts.username = `Anonymous`
quoteState.selected(postId, _selectedText, opts);
this.set("visible", quoteState.buffer.length > 0);
if (this.siteSettings.enable_fast_edit) {
this.set(
"_canEditPost",
this.topic.postStream.findLoadedPost(postId)?.can_edit
);
if (this._canEditPost) {
const regexp = new RegExp(regexSafeStr(quoteState.buffer), "gi");
const matches = cooked.innerHTML.match(regexp);
if (
quoteState.buffer.length < 1 ||
quoteState.buffer.includes("|") || // 테이블은 너무 복잡합니다
quoteState.buffer.match(/\n/g) || // 줄바꿈은 너무 복잡합니다
matches?.length > 1 // 중복은 너무 복잡합니다
) {
this.set("_isFastEditable", false);
this.set("_fastEditInitalSelection", null);
this.set("_fastEditNewSelection", null);
} else if (matches?.length === 1) {
this.set("_isFastEditable", true);
this.set("_fastEditInitalSelection", quoteState.buffer);
this.set("_fastEditNewSelection", quoteState.buffer);
}
}
}
// Firefox에서 텍스트를 3회 클릭하면 인용 선택 시 무한 루프가 발생할 수 있으므로 이를 무조건적으로 방지합니다.
if (this._prevSelection === _selectedText) {
return;
}
this._prevSelection = _selectedText;
// 데스크톱에서는 선택 영역의 시작 부분에 버튼을 표시하고,
// 모바일에서는 선택 영역의 끝 부분에 버튼을 표시합니다.
const isMobileDevice = this.site.isMobileDevice;
const { isIOS, isAndroid, isOpera } = this.capabilities;
const showAtEnd = isMobileDevice || isIOS || isAndroid || isOpera;
const boundaryPosition = this._getRangeBoundaryRect(firstRange, showAtEnd);
// 버튼의 위치를 변경합니다.
schedule("afterRender", () => {
if (!this.element || this.isDestroying || this.isDestroyed) {
return;
}
let top = 0;
let left = 0;
const pxFromSelection = 5;
if (showAtEnd) {
// iOS의 선택 핸들은 반경 약 50px의 히트 영역을 가지므로
// 버튼이 그 반경 밖에 있도록 확인해야 합니다.
// 일관성을 위해 모든 모바일 디바이스에 동일한 로직을 적용합니다.
top = boundaryPosition.bottom + pxFromSelection;
left = boundaryPosition.left;
const safeRadius = 50;
const topicArea = document
.querySelector(".topic-area")
.getBoundingClientRect();
topicArea.x += document.documentElement.scrollLeft;
topicArea.y += document.documentElement.scrollTop;
const endHandlePosition = boundaryPosition;
const width = this.element.clientWidth;
const possiblePositions = [
{
// 왼쪽으로 이동
top,
left: left - width - safeRadius,
},
{
// 오른쪽으로 이동
top,
left: left + safeRadius,
},
{
// 끝 핸들 아래 중앙
top: top + safeRadius,
left: left - width / 2,
},
];
for (const pos of possiblePositions) {
// 버튼이 .topic-area 안에 완전히 들어오는지 확인합니다.
pos.left = Math.max(topicArea.left, pos.left);
pos.left = Math.min(topicArea.right - width, pos.left);
let clearOfStartHandle = true;
if (isAndroid) {
// Android에서는 시작 선택 핸들이 라인 아래로 확장되므로 이것도 피해야 합니다:
const startHandlePosition = this._getRangeBoundaryRect(
firstRange,
false
);
clearOfStartHandle =
pos.top - startHandlePosition.bottom >= safeRadius ||
pos.left + width <= startHandlePosition.left - safeRadius ||
pos.left >= startHandlePosition.left + safeRadius;
}
const clearOfEndHandle =
pos.top - endHandlePosition.top >= safeRadius ||
pos.left + width <= endHandlePosition.left - safeRadius ||
pos.left >= endHandlePosition.left + safeRadius;
if (clearOfStartHandle && clearOfEndHandle) {
left = pos.left;
top = pos.top;
break;
}
}
} else {
// 데스크톱
top =
boundaryPosition.top - this.element.clientHeight - pxFromSelection;
left = boundaryPosition.left;
}
Object.assign(this.element.style, { top: `${top}px`, left: `${left}px` });
if (!this.animated) {
// 초기 위치 설정 후에만 CSS 전환을 활성화합니다.
// 그렇지 않으면 버튼이 화면 밖에서 날아오는 것처럼 보일 수 있습니다.
next(() => this.set("animated", true));
}
});
}
}
});
const composerController = api.container.lookup("controller:composer");
const componentQuoteButton = api.container.lookup("component:quote-button");
</script>