トピックリストのタグ表示コンポーネント - トピックリストのタグを展開/折りたたむ

クラス内で使用します。それ以外では機能しません。

3.6.0.beta1 と記述する必要があります。そうでなければ、現時点では誰もインストールできません。

少し確認しましたが、確かに簡単な方法はありません。しかし、API を使用して、興味深く簡略化された方法を見つけました。

  • トピックモデルを使用して、テンプレートが生成される前に表示されるタグが何であるかを変更します。これは DOM 操作や設定に依存しないことを意味します。状態(revealTags)に応じて、元のリストまたは部分的なリストが返されます。

  • トグルボタンを作成するために、API を使用してボタンの HTML を持つタグを追加します(残念ながら、ここにはプラグインのアウトレットがありません)。クリックイベントは別途処理されます。クリックすると、トグル状態が更新され(revealTags)、タグリストの再レンダリングがトリガーされます。

この方法の大きな利点は、HTML をいじって、さまざまなスタイルに基づいて CSS で何を表示/非表示にするかを特定する必要がないことです。

chrome_lSKqwYt5Z7

テストコードを共有します。

import { apiInitializer } from "discourse/lib/api";
import { i18n } from "discourse-i18n";
import { computed } from "@ember/object";

export default apiInitializer((api) => {
  const siteSettings = api.container.lookup("service:site-settings");

  const maxVisibleTags = Math.min(
    settings.max_tags_visible,
    siteSettings.max_tags_per_topic
  );

  let topicModels = {};

  api.modifyClass(
    "model:topic",
    (Superclass) =>
      class extends Superclass {
        revealTags = false;

        init() {
          super.init(...arguments);
          topicModels[this.id] = this;
        }

        @computed("tags")
        get visibleListTags() {
          if (this.revealTags) {
            return super.visibleListTags;
          }
          return super.visibleListTags.slice(0, maxVisibleTags);
        }
      }
  );

  api.addTagsHtmlCallback(
    (topic, params) => {
      if (topic.tags.length <= maxVisibleTags) {
        return "";
      }

      const isExpanded = topic.revealTags;
      const label = isExpanded
        ? i18n(themePrefix("js.tag_reveal.hide"))
        : i18n(themePrefix("js.tag_reveal.more_tags"), {
            count: topic.tags.length - maxVisibleTags,
          });

      return `<a class="reveal-tag-action" role="button" aria-expanded="${isExpanded}">${label}</a>`;
    },
    {
      priority: siteSettings.max_tags_per_topic + 1,
    }
  );

  document.addEventListener("click", (event) => {
    const target = event.target;
    if (!target?.matches(".reveal-tag-action")) {
      return;
    }

    event.preventDefault();
    event.stopPropagation();

    const element =
      target.closest("[data-topic-id]") ||
      document.querySelector("h1[data-topic-id]");
    const topicId = element?.dataset.topicId;
    if (!topicId) {
      return;
    }

    const topicModel = topicModels[topicId];
    if (!topicModel) {
      return;
    }

    topicModel.revealTags = !topicModel.revealTags;
    topicModel.notifyPropertyChange("tags");
  });
});
.reveal-tag-action {
  background-color: var(--primary-50);
  border: 1px solid var(--primary-200);
  color: var(--primary-800);
  font-size: small;
  padding-inline: 3px;
}

.discourse-tags__tag-separator:has(+ .reveal-tag-action) {
  visibility: hidden;
}

「いいね!」 2