quoteState オプションをオーバーライドしますか?

匿名投稿をより匿名化するために、匿名投稿のみが有効なカテゴリで引用の表示方法をオーバーライドしようとしています。つまり、デフォルトの

anonymous4302934
引用されたテキスト

ではなく、以下のようにしたいのです。

匿名:
引用されたテキスト

ツールバーボタンを通じて引用されたテキストについては、How to override the buildQuote function? - #7 by Canapin に基づいてこれを達成できています(動作させるために、この回避策に従って最下部にコンテナのルックアップを追加する必要がありました: api.modifyClass sometimes(!) not working - #12 by RGJ )。

コアファイルを掘り下げて調べましたが、選択して引用ボタンをクリックして作曲器に引用が挿入される際に、引用がどこで構築されているのか正確にわかりません。_selectionChanged() in quote-button.js では、選択されたテキストがブロッククォート内にある場合に 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 = `匿名`;
        } 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];

    // マークダウンの計算は長い投稿では時間がかかる
    // このコードは、高速化できない場合にのみ計算を試みる
    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 = `匿名`

    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 でテキストをトリプルクリックすると発生する可能性がある
    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>

もし他の人がこれを見つけたら、quote-button.js の insertQuote で quoteState オプションをオーバーライドする方法を見つけました。以下に完全なコードを示します。これにより、指定されたカテゴリで、ツールバーの引用と選択された引用ボタンの両方で、引用内のユーザー名が置き換えられます。

<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");
        
              // If there is no current post, use the first post id from the stream
              if (!postId && postStream) {
                postId = postStream.get("stream.firstObject");
              }
        
              // If we're editing a post, fetch the reply when importing a quote
              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: {
            insertQuote() {
                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;
                }
                this.attrs.quoteState.value.opts.username = anon_name;
                this.attrs.selectText().then(() => this._hideButton());
                console.log(anon_name, this.attrs.quoteState.value.opts)
              }
        }
    });
    
    const composerController = api.container.lookup("controller:composer");
    const quoteButton = api.container.lookup("component:quote-button");
</script>