Skip to content

A platform for community discussion. Free, open, simple.

DEV: Move discourse-templates to core (#33749)

Jarek Radosz8d705c00c34f
diff --git a/.github/labeler.yml b/.github/labeler.yml
index eb34da0fe97..2758a17a84f 100644
--- a/.github/labeler.yml
+++ b/.github/labeler.yml
@@ -134,6 +134,10 @@ discourse-topic-voting:
- changed-files:
- any-glob-to-any-file: plugins/discourse-topic-voting/**/*
+discourse-templates:
+ - changed-files:
+ - any-glob-to-any-file: plugins/discourse-templates/**/*
+
footnote:
- changed-files:
- any-glob-to-any-file: plugins/footnote/**/*
diff --git a/.gitignore b/.gitignore
index 26dce5793e9..e10e18dd7ae 100644
--- a/.gitignore
+++ b/.gitignore
@@ -76,6 +76,7 @@
!/plugins/discourse-affiliate
!/plugins/discourse-solved
!/plugins/discourse-topic-voting
+!/plugins/discourse-templates
/plugins/*/auto_generated
/spec/fixtures/plugins/my_plugin/auto_generated
diff --git a/plugins/discourse-templates/README.md b/plugins/discourse-templates/README.md
new file mode 100644
index 00000000000..a3ff7ae0f27
--- /dev/null
+++ b/plugins/discourse-templates/README.md
@@ -0,0 +1,17 @@
+# Discourse Templates plugin
+
+This plugin adds support for inserting a template into the composer window via a UI.
+
+For more information please check the [Official Plugin Topic & Documentation](https://meta.discourse.org/t/discourse-templates/229250) on Meta.
+
+## Installation
+
+Follow the directions at [Install a Plugin](https://meta.discourse.org/t/install-a-plugin/19157) using https://github.com/discourse/discourse-templates.git as the repository URL.
+
+## Previous plugin
+
+[Discourse Canned Replies](https://github.com/discourse/discourse-canned-replies)
+
+## License
+
+GNU GPL v2
diff --git a/plugins/discourse-templates/about.json b/plugins/discourse-templates/about.json
new file mode 100644
index 00000000000..71d5e041cd5
--- /dev/null
+++ b/plugins/discourse-templates/about.json
@@ -0,0 +1,7 @@
+{
+ "tests": {
+ "requiredPlugins": [
+ "chat"
+ ]
+ }
+}
\ No newline at end of file
diff --git a/plugins/discourse-templates/app/controllers/discourse_templates/templates_controller.rb b/plugins/discourse-templates/app/controllers/discourse_templates/templates_controller.rb
new file mode 100644
index 00000000000..4518f504d26
--- /dev/null
+++ b/plugins/discourse-templates/app/controllers/discourse_templates/templates_controller.rb
@@ -0,0 +1,47 @@
+# frozen_string_literal: true
+
+module DiscourseTemplates
+ class TemplatesController < ::ApplicationController
+ requires_plugin PLUGIN_NAME
+
+ before_action :ensure_logged_in
+ before_action :ensure_discourse_templates_enabled
+ skip_before_action :check_xhr
+
+ def ensure_discourse_templates_enabled
+ raise Discourse::InvalidAccess.new unless guardian.can_use_templates?
+ end
+
+ def use
+ template_id = params.require(:id)
+ topic = Topic.find_by(id: template_id)
+
+ return render_json_error("Invalid template id", status: 422) if topic.blank?
+
+ unless topic.template?(current_user)
+ return(render_json_error("Id does not belong to a template", status: 422))
+ end
+
+ record = topic.increment_template_item_usage_count!
+
+ render json: record
+ end
+
+ def index
+ list_options = {
+ # limit defined in a hidden setting with a sane default value (1000) that should be enough to fetch all
+ # templates at once in most cases, but it still small enough to prevent things to blow up if the user
+ # selected the wrong category in settings with thousands and thousands of posts
+ per_page: SiteSetting.discourse_templates_max_replies_fetched.to_i,
+ }
+
+ topic_query = TopicQuery.new(current_user, list_options)
+ category_templates = topic_query.list_category_templates&.topics || []
+ private_templates = topic_query.list_private_templates&.topics || []
+
+ templates = category_templates + private_templates
+
+ render json: templates, each_serializer: TemplatesSerializer
+ end
+ end
+end
diff --git a/plugins/discourse-templates/app/models/discourse_templates/usage_count.rb b/plugins/discourse-templates/app/models/discourse_templates/usage_count.rb
new file mode 100644
index 00000000000..af23d0db4e1
--- /dev/null
+++ b/plugins/discourse-templates/app/models/discourse_templates/usage_count.rb
@@ -0,0 +1,26 @@
+# frozen_string_literal: true
+
+module DiscourseTemplates
+ class UsageCount < ActiveRecord::Base
+ self.table_name = "discourse_templates_usage_count"
+
+ belongs_to :topic
+
+ validates_presence_of :topic_id
+ end
+end
+
+# == Schema Information
+#
+# Table name: discourse_templates_usage_count
+#
+# id :bigint not null, primary key
+# topic_id :integer not null
+# usage_count :integer default(0), not null
+# created_at :datetime not null
+# updated_at :datetime not null
+#
+# Indexes
+#
+# index_discourse_templates_usage_count_on_topic_id (topic_id) UNIQUE
+#
diff --git a/plugins/discourse-templates/app/serializers/discourse_templates/templates_serializer.rb b/plugins/discourse-templates/app/serializers/discourse_templates/templates_serializer.rb
new file mode 100644
index 00000000000..6f6b6437d8d
--- /dev/null
+++ b/plugins/discourse-templates/app/serializers/discourse_templates/templates_serializer.rb
@@ -0,0 +1,23 @@
+# frozen_string_literal: true
+
+module DiscourseTemplates
+ class TemplatesSerializer < ApplicationSerializer
+ attributes :id, :title, :slug, :content, :tags, :usages
+
+ def content
+ object.first_post.raw
+ end
+
+ def include_tags?
+ SiteSetting.tagging_enabled
+ end
+
+ def tags
+ object.tags.map(&:name).sort
+ end
+
+ def usages
+ object.template_item_usage_count
+ end
+ end
+end
diff --git a/plugins/discourse-templates/assets/javascripts/discourse/components/d-templates/filterable-list.gjs b/plugins/discourse-templates/assets/javascripts/discourse/components/d-templates/filterable-list.gjs
new file mode 100644
index 00000000000..eeb21aa9a39
--- /dev/null
+++ b/plugins/discourse-templates/assets/javascripts/discourse/components/d-templates/filterable-list.gjs
@@ -0,0 +1,143 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { action, computed } from "@ember/object";
+import didInsert from "@ember/render-modifiers/modifiers/did-insert";
+import { schedule } from "@ember/runloop";
+import { service } from "@ember/service";
+import ConditionalLoadingSpinner from "discourse/components/conditional-loading-spinner";
+import TextField from "discourse/components/text-field";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import { bind } from "discourse/lib/decorators";
+import { i18n } from "discourse-i18n";
+import { ALL_TAGS_ID, NO_TAG_ID } from "select-kit/components/tag-drop";
+import Item from "./item";
+import TagDrop from "./tag-drop";
+
+export default class DTemplatesFilterableList extends Component {
+ @service siteSettings;
+
+ @tracked loading = true;
+ @tracked listFilter = "";
+ @tracked replies = [];
+ @tracked selectedTag = ALL_TAGS_ID;
+ @tracked availableTags = [];
+
+ @computed("replies", "selectedTag", "listFilter")
+ get filteredReplies() {
+ const filterTitle = this.listFilter.toLowerCase();
+ return (
+ this.replies
+ .map((template) => {
+ /* Give a relevant score to each template. */
+ template.score = 0;
+ if (template.title.toLowerCase().includes(filterTitle)) {
+ template.score += 2;
+ } else if (template.content.toLowerCase().includes(filterTitle)) {
+ template.score += 1;
+ }
+ return template;
+ })
+ // Filter irrelevant replies.
+ .filter((template) => template.score !== 0)
+ // Filter only replies tagged with the selected tag.
+ .filter((template) => {
+ if (this.selectedTag === ALL_TAGS_ID) {
+ return true;
+ }
+ if (this.selectedTag === NO_TAG_ID && template.tags.length === 0) {
+ return true;
+ }
+
+ return template.tags.includes(this.selectedTag);
+ })
+ .sort((a, b) => {
+ /* Sort replies by relevance and title. */
+ if (a.score !== b.score) {
+ return a.score > b.score ? -1 : 1; /* descending */
+ } else if (a.title !== b.title) {
+ return a.title < b.title ? -1 : 1; /* ascending */
+ }
+ return 0;
+ })
+ );
+ }
+
+ @bind
+ async load() {
+ try {
+ this.loading = true;
+
+ const results = await ajax("/discourse_templates");
+ this.replies = results.templates;
+
+ if (this.siteSettings.tagging_enabled) {
+ this.availableTags = Object.values(
+ this.replies.reduce((availableTags, template) => {
+ template.tags.forEach((tag) => {
+ if (availableTags[tag]) {
+ availableTags[tag].count += 1;
+ } else {
+ availableTags[tag] = { id: tag, name: tag, count: 1 };
+ }
+ });
+
+ return availableTags;
+ }, {})
+ );
+ }
+ } catch (e) {
+ this.loading = false;
+ popupAjaxError(e);
+ } finally {
+ this.loading = false;
+
+ schedule("afterRender", () =>
+ document.querySelector(".templates-filter")?.focus()
+ );
+ }
+ }
+
+ @action
+ changeSelectedTag(tagId) {
+ this.selectedTag = tagId;
+ }
+
+ @action
+ insertTemplate(template) {
+ this.args.onBeforeInsertTemplate?.();
+ this.args.onInsertTemplate?.(template);
+ this.args.onAfterInsertTemplate?.();
+ }
+
+ <template>
+ <div class="templates-filterable-list" {{didInsert this.load}}>
+
+ <ConditionalLoadingSpinner @condition={{this.loading}}>
+ <div class="templates-filter-bar">
+ {{#if this.siteSettings.tagging_enabled}}
+ <TagDrop
+ @availableTags={{this.availableTags}}
+ @tagId={{this.selectedTag}}
+ @onChangeSelectedTag={{this.changeSelectedTag}}
+ />
+ {{/if}}
+ <TextField
+ class="templates-filter"
+ @value={{this.listFilter}}
+ placeholder={{i18n "templates.filter_hint"}}
+ />
+ </div>
+ <div class="templates-list">
+ {{#each this.filteredReplies as |r|}}
+ <Item
+ @template={{r}}
+ @model={{@model}}
+ @onInsertTemplate={{this.insertTemplate}}
+ />
+ {{/each}}
+ </div>
+ </ConditionalLoadingSpinner>
+ </div>
+ </template>
+}
diff --git a/plugins/discourse-templates/assets/javascripts/discourse/components/d-templates/item-content.gjs b/plugins/discourse-templates/assets/javascripts/discourse/components/d-templates/item-content.gjs
new file mode 100644
index 00000000000..f6aef5aa532
--- /dev/null
+++ b/plugins/discourse-templates/assets/javascripts/discourse/components/d-templates/item-content.gjs
@@ -0,0 +1,21 @@
+import { array } from "@ember/helper";
+import { LinkTo } from "@ember/routing";
+import CookText from "discourse/components/cook-text";
+import icon from "discourse/helpers/d-icon";
+import { i18n } from "discourse-i18n";
+
+const ItemContent = <template>
+ <div class="templates-content">
+ <LinkTo
+ class="template-item-source-link"
+ @route="topic"
+ @models={{array @template.slug @template.id}}
+ >
+ {{icon "crosshairs"}}
+ {{i18n "templates.source"}}
+ </LinkTo>
+ <CookText @rawText={{@template.content}} />
+ </div>
+</template>;
+
+export default ItemContent;
diff --git a/plugins/discourse-templates/assets/javascripts/discourse/components/d-templates/item.gjs b/plugins/discourse-templates/assets/javascripts/discourse/components/d-templates/item.gjs
new file mode 100644
index 00000000000..ef820d6eb58
--- /dev/null
+++ b/plugins/discourse-templates/assets/javascripts/discourse/components/d-templates/item.gjs
@@ -0,0 +1,36 @@
+import Component from "@glimmer/component";
+import { action } from "@ember/object";
+import DButton from "discourse/components/d-button";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import ItemContent from "./item-content";
+
+export default class DTemplatesItem extends Component {
+ @action
+ apply() {
+ // run parametrized action to insert the template
+ this.args.onInsertTemplate?.(this.args.template);
+
+ ajax(`/discourse_templates/${this.args.template.id}/use`, {
+ type: "POST",
+ }).catch(popupAjaxError);
+ }
+
+ <template>
+ <details class="template-item" id="template-item-{{@template.id}}">
+ <summary class="template-item-title">
+ <div class="template-item-title-text">{{@template.title}}</div>
+
+ <div class="actions">
+ <DButton
+ @action={{this.apply}}
+ @icon="far-clipboard"
+ class="templates-apply"
+ />
+ </div>
+ </summary>
+
+ <ItemContent @template={{@template}} />
+ </details>
+ </template>
+}
diff --git a/plugins/discourse-templates/assets/javascripts/discourse/components/d-templates/modal/form.gjs b/plugins/discourse-templates/assets/javascripts/discourse/components/d-templates/modal/form.gjs
new file mode 100644
index 00000000000..df9ee000751
--- /dev/null
+++ b/plugins/discourse-templates/assets/javascripts/discourse/components/d-templates/modal/form.gjs
@@ -0,0 +1,39 @@
+import Component from "@glimmer/component";
+import { service } from "@ember/service";
+import DModal from "discourse/components/d-modal";
+import { i18n } from "discourse-i18n";
+import FilterableList from "../filterable-list";
+
+export default class Form extends Component {
+ @service appEvents;
+
+ constructor() {
+ super(...arguments);
+ if (this.args.closeModal) {
+ this.appEvents.on("page:changed", this, this.args.closeModal);
+ }
+ }
+
+ willDestroy() {
+ super.willDestroy(...arguments);
+ if (this.args.closeModal) {
+ this.appEvents.off("page:changed", this, this.args.closeModal);
+ }
+ }
+
+ <template>
+ <DModal
+ @closeModal={{@closeModal}}
+ @title={{i18n "templates.insert_template"}}
+ class="d-templates d-templates-modal"
+ >
+ <:body>
+ <FilterableList
+ @textarea={{@model.textarea}}
+ @onInsertTemplate={{@model.onInsertTemplate}}
+ @onAfterInsertTemplate={{@closeModal}}
+ />
+ </:body>
+ </DModal>
+ </template>
+}
diff --git a/plugins/discourse-templates/assets/javascripts/discourse/components/d-templates/tag-drop.js b/plugins/discourse-templates/assets/javascripts/discourse/components/d-templates/tag-drop.js
new file mode 100644
index 00000000000..0dde7905f99
--- /dev/null
+++ b/plugins/discourse-templates/assets/javascripts/discourse/components/d-templates/tag-drop.js
@@ -0,0 +1,46 @@
+import { action, computed } from "@ember/object";
+import TagDrop from "select-kit/components/tag-drop";
+
+export default class DTemplatesTagDrop extends TagDrop {
+ @computed("availableTags.[]")
+ get topTags() {
+ // sort tags descending by count and ascending by name
+ return (this.availableTags || []).sort((a, b) => {
+ if (a.count !== b.count) {
+ return b.count - a.count;
+ } // descending
+ if (a.name !== b.name) {
+ return a.name < b.name ? -1 : 1;
+ } // ascending
+ return 0;
+ });
+ }
+
+ search(filter) {
+ return (this.content || [])
+ .map((tag) => {
+ if (tag.id && tag.name) {
+ return tag;
+ }
+ return this.defaultItem(tag, tag);
+ })
+ .filter((tag) => {
+ if (filter == null) {
+ return true;
+ }
+
+ const tagFilter = filter.toLowerCase();
+ return (
+ tag.id.toLowerCase().includes(tagFilter) ||
+ tag.name.toLowerCase().includes(tagFilter)
+ );
+ });
+ }
+
+ @action
+ onChange(tagId, tag) {
+ // overrides the action onChange of the parent with the value received in
+ // the property onChangeSelectedTag in the handlebars template
+ this.onChangeSelectedTag?.(tagId, tag);
+ }
+}
diff --git a/plugins/discourse-templates/assets/javascripts/discourse/connectors/below-footer/d-templates-modal-container.gjs b/plugins/discourse-templates/assets/javascripts/discourse/connectors/below-footer/d-templates-modal-container.gjs
new file mode 100644
index 00000000000..f4f5ed3a591
--- /dev/null
+++ b/plugins/discourse-templates/assets/javascripts/discourse/connectors/below-footer/d-templates-modal-container.gjs
@@ -0,0 +1,18 @@
+import Component from "@glimmer/component";
+import { service } from "@ember/service";
+import DTemplatesModalForm from "../../components/d-templates/modal/form";
+
+export default class DTemplatesModalContainer extends Component {
+ @service dTemplatesModal;
+
+ <template>
+ {{#if this.dTemplatesModal.model}}
+ <div class="modal-container d-templates-modal-container">
+ <DTemplatesModalForm
+ @closeModal={{this.dTemplatesModal.hide}}
+ @model={{this.dTemplatesModal.model}}
+ />
+ </div>
+ {{/if}}
+ </template>
+}
diff --git a/plugins/discourse-templates/assets/javascripts/discourse/connectors/editor-preview/d-templates.gjs b/plugins/discourse-templates/assets/javascripts/discourse/connectors/editor-preview/d-templates.gjs
new file mode 100644
index 00000000000..ca62c7a59b3
--- /dev/null
+++ b/plugins/discourse-templates/assets/javascripts/discourse/connectors/editor-preview/d-templates.gjs
@@ -0,0 +1,73 @@
+import Component from "@ember/component";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import { classNames } from "@ember-decorators/component";
+import DButton from "discourse/components/d-button";
+import FilterableList from "../../components/d-templates/filterable-list";
+
+const SELECTOR_EDITOR_PREVIEW =
+ "#reply-control .d-editor-preview-wrapper > .d-editor-preview";
+
+@classNames("d-templates")
+export default class DTemplatesEditorPreview extends Component {
+ static shouldRender(args, context) {
+ return !context.site.mobileView;
+ }
+
+ @service appEvents;
+ @service site;
+
+ templatesVisible = false;
+ onInsertTemplate;
+
+ constructor() {
+ super(...arguments);
+
+ this.appEvents.on("discourse-templates:show", this, "show");
+ this.appEvents.on("discourse-templates:hide", this, "hide");
+ }
+
+ willDestroy() {
+ super.willDestroy(...arguments);
+
+ this.appEvents.off("discourse-templates:show", this, "show");
+ this.appEvents.off("discourse-templates:hide", this, "hide");
+ }
+
+ @action
+ show({ onInsertTemplate }) {
+ const elemEditorPreview = document.querySelector(SELECTOR_EDITOR_PREVIEW);
+ if (elemEditorPreview) {
+ elemEditorPreview.style.display = "none";
+ }
+
+ this.set("onInsertTemplate", onInsertTemplate);
+ this.set("templatesVisible", true);
+ }
+
+ @action
+ hide() {
+ const elemEditorPreview = document.querySelector(SELECTOR_EDITOR_PREVIEW);
+ if (elemEditorPreview) {
+ elemEditorPreview.style.display = "";
+ }
+
+ this.set("templatesVisible", false);
+ }
+
+ <template>
+ {{#if this.templatesVisible}}
+ <div class="d-templates-container">
+ <DButton
+ @action={{this.hide}}
+ @icon="xmark"
+ class="modal-close close btn-flat"
+ />
+ <FilterableList
+ @onInsertTemplate={{this.onInsertTemplate}}
+ @onAfterInsertTemplate={{this.hide}}
+ />
+ </div>
+ {{/if}}
+ </template>
+}
diff --git a/plugins/discourse-templates/assets/javascripts/discourse/connectors/topic-above-posts/discourse-templates-button.gjs b/plugins/discourse-templates/assets/javascripts/discourse/connectors/topic-above-posts/discourse-templates-button.gjs
new file mode 100644
index 00000000000..254b9b3e9c7
--- /dev/null
+++ b/plugins/discourse-templates/assets/javascripts/discourse/connectors/topic-above-posts/discourse-templates-button.gjs
@@ -0,0 +1,65 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import DButton from "discourse/components/d-button";
+import concatClass from "discourse/helpers/concat-class";
+import { ajax } from "discourse/lib/ajax";
+import discourseDebounce from "discourse/lib/debounce";
+
+export default class DiscourseTemplatesButton extends Component {
+ static shouldRender(outletArgs, helper) {
+ return outletArgs.model.is_template && helper.currentUser?.can_create_topic;
+ }
+
+ @service composer;
+
+ @tracked copyConfirm = false;
+
+ async fetchRaw() {
+ const topic = this.args.outletArgs.model;
+ return await ajax(`/raw/${topic.id}/1`, { dataType: "text" });
+ }
+
+ @action
+ async createNewTopic() {
+ const text = await this.fetchRaw();
+ this.composer.openNewTopic({
+ body: text,
+ });
+ }
+
+ @action
+ async copy() {
+ const text = await this.fetchRaw();
+ navigator.clipboard.writeText(text);
+ this.copyConfirm = true;
+ discourseDebounce(this.resetCopyButton, 2000);
+ }
+
+ @action
+ resetCopyButton() {
+ this.copyConfirm = false;
+ }
+
+ <template>
+ <div class="template-topic-controls">
+ <DButton
+ @icon={{if this.copyConfirm "check" "copy"}}
+ @action={{this.copy}}
+ @label="templates.copy"
+ class={{concatClass
+ "btn-default"
+ "template-copy"
+ (if this.copyConfirm "ok")
+ }}
+ />
+ <DButton
+ @action={{this.createNewTopic}}
+ @label="templates.new_topic"
+ @icon="plus"
+ class="template-new-topic"
+ />
+ </div>
+ </template>
+}
diff --git a/plugins/discourse-templates/assets/javascripts/discourse/initializers/d-templates.js b/plugins/discourse-templates/assets/javascripts/discourse/initializers/d-templates.js
new file mode 100644
index 00000000000..5ee286f3c3e
--- /dev/null
+++ b/plugins/discourse-templates/assets/javascripts/discourse/initializers/d-templates.js
@@ -0,0 +1,152 @@
+import { getOwnerWithFallback } from "discourse/lib/get-owner";
+import { PLATFORM_KEY_MODIFIER } from "discourse/lib/keyboard-shortcuts";
+import { withPluginApi } from "discourse/lib/plugin-api";
+import extractVariablesFromChatChannel from "../../lib/variables-chat-channel";
+import extractVariablesFromChatThread from "../../lib/variables-chat-thread";
+
+export default {
+ name: "discourse-templates-add-ui-builder",
+
+ initialize(container) {
+ const siteSettings = container.lookup("service:site-settings");
+ const currentUser = container.lookup("service:current-user");
+
+ if (
+ siteSettings.discourse_templates_enabled &&
+ currentUser?.can_use_templates
+ ) {
+ withPluginApi("1.13.0", (api) => {
+ addOptionsMenuItem(api);
+ addKeyboardShortcut(api, container);
+ addChatIntegration(api, container);
+ });
+ }
+ },
+};
+
+function addOptionsMenuItem(api) {
+ const dTemplates = api.container.lookup("service:d-templates");
+
+ api.addComposerToolbarPopupMenuOption({
+ icon: "far-clipboard",
+ label: "templates.insert_template",
+ action: () => {
+ dTemplates.showComposerUI();
+ },
+ });
+}
+
+const _templateShortcutTargets = [];
+
+function addKeyboardShortcut(api, container) {
+ api.addKeyboardShortcut(
+ `${PLATFORM_KEY_MODIFIER}+shift+i`,
+ (event) => {
+ event.preventDefault();
+ const dTemplates = container.lookup("service:d-templates");
+
+ if (dTemplates.isComposerFocused) {
+ dTemplates.showComposerUI();
+ return;
+ }
+
+ for (const target of _templateShortcutTargets) {
+ if (
+ dTemplates.isTextAreaFocused &&
+ target?.isFocused?.(document.activeElement)
+ ) {
+ dTemplates.showTextAreaUI(target?.variables);
+ return;
+ }
+ }
+
+ if (dTemplates.isTextAreaFocused) {
+ dTemplates.showTextAreaUI();
+ }
+ },
+ {
+ global: true,
+ help: {
+ category: "templates",
+ name: "templates.insert_template",
+ definition: {
+ keys1: [PLATFORM_KEY_MODIFIER, "shift", "i"],
+ keysDelimiter: "plus",
+ },
+ },
+ }
+ );
+}
+
+function addChatIntegration(api, container) {
+ if (!container.lookup("service:chat")?.userCanChat) {
+ return;
+ }
+
+ const channelVariablesExtractor = function () {
+ const chat = getOwnerWithFallback(this).lookup("service:chat");
+ const activeChannel = chat?.activeChannel;
+ const currentMessage = activeChannel?.draft;
+ const router = getOwnerWithFallback(this).lookup("service:router");
+
+ return extractVariablesFromChatChannel(
+ activeChannel,
+ currentMessage,
+ router
+ );
+ };
+
+ const threadVariablesExtractor = function () {
+ const chat = getOwnerWithFallback(this).lookup("service:chat");
+ const activeThread = chat?.activeChannel?.activeThread;
+ const currentMessage = activeThread?.draft;
+ const router = getOwnerWithFallback(this).lookup("service:router");
+
+ return extractVariablesFromChatThread(activeThread, currentMessage, router);
+ };
+
+ // add a custom chat composer button
+ api.registerChatComposerButton({
+ id: "d-templates-chat-insert-template-btn",
+ icon: "far-clipboard",
+ label: "templates.insert_template",
+ position: "dropdown",
+ action: function () {
+ let contextVariablesExtractor;
+ switch (this.context) {
+ case "channel":
+ contextVariablesExtractor = channelVariablesExtractor.bind(this);
+ break;
+ case "thread":
+ contextVariablesExtractor = threadVariablesExtractor.bind(this);
+ break;
+ default:
+ contextVariablesExtractor = null;
+ }
+
+ const textarea = this.composer?.textarea?.textarea; // this.composer.textarea is a TextareaInteractor instance
+
+ getOwnerWithFallback(this)
+ .lookup("service:d-templates")
+ .showTextAreaUI(contextVariablesExtractor, textarea);
+ },
+ displayed() {
+ return (
+ this.composer?.textarea &&
+ (this.context === "channel" || this.context === "thread")
+ );
+ },
+ });
+
+ // add custom keyboard shortcut handlers for the chat channel composer and chat thread composer
+ _templateShortcutTargets.push(
+ {
+ isFocused: (element) => element?.id === "channel-composer",
+ variables: channelVariablesExtractor,
+ },
+ {
+ isFocused: (element) => element?.id === "thread-composer",
+ variables: threadVariablesExtractor,
+ }
+ );
+}
diff --git a/plugins/discourse-templates/assets/javascripts/discourse/services/d-templates-modal.js b/plugins/discourse-templates/assets/javascripts/discourse/services/d-templates-modal.js
new file mode 100644
index 00000000000..c3f2311e6e3
--- /dev/null
+++ b/plugins/discourse-templates/assets/javascripts/discourse/services/d-templates-modal.js
@@ -0,0 +1,21 @@
+import { tracked } from "@glimmer/tracking";
+import { action } from "@ember/object";
+import Service from "@ember/service";
+
+export default class DTemplatesModalService extends Service {
+ @tracked model = null;
+
+ @action
+ show(model) {
+ this.model = model;
+ }
+
+ @action
+ hide() {
+ // return the focus back to the textarea
+ this.model?.textarea?.focus();
+
+ // clear the model
+ this.model = null;
+ }
+}
diff --git a/plugins/discourse-templates/assets/javascripts/discourse/services/d-templates.js b/plugins/discourse-templates/assets/javascripts/discourse/services/d-templates.js
new file mode 100644
index 00000000000..c5691876a56
--- /dev/null
+++ b/plugins/discourse-templates/assets/javascripts/discourse/services/d-templates.js
@@ -0,0 +1,113 @@
+import { getOwner } from "@ember/application";
+import Service, { service } from "@ember/service";
+import TextareaTextManipulation from "discourse/lib/textarea-text-manipulation";
+import { replaceVariables } from "../../lib/replace-variables";
+import extractVariablesFromComposerModel from "../../lib/variables-composer";
+
+export default class DTemplatesService extends Service {
+ @service appEvents;
+ @service modal;
+ @service site;
+ @service currentUser;
+ @service dTemplatesModal;
+ @service composer;
+
+ showComposerUI() {
+ const onInsertTemplate = this.#insertTemplateIntoComposer.bind(this);
+
+ if (this.site.mobileView || !this.composer.isPreviewVisible) {
+ this.#showModal(null, onInsertTemplate); // textarea must be empty when targeting the composer
+ } else {
+ this.#showComposerPreviewUI(onInsertTemplate);
+ }
+ }
+
+ showTextAreaUI(variablesExtractor = null, textarea = document.activeElement) {
+ if (!this.#isTextArea(textarea)) {
+ return;
+ }
+
+ const modal = document.querySelector(".d-modal");
+ const onInsertTemplate = this.#insertTemplateIntoTextArea.bind(this);
+ const extractVariables = (model) => variablesExtractor?.(model);
+
+ if (modal?.contains(textarea)) {
+ if (!modal.classList.contains("d-templates")) {
+ this.#showModal(textarea, (template) => {
+ const modalModel = this.modal.activeModal?.opts?.model;
+ onInsertTemplate(textarea, template, extractVariables(modalModel));
+ });
+ }
+ } else {
+ this.#showModal(textarea, (template) =>
+ onInsertTemplate(textarea, template, extractVariables())
+ );
+ }
+ }
+
+ get isComposerFocused() {
+ const activeElement = document.activeElement;
+
+ const composerModel = getOwner(this).lookup("service:composer").model;
+ const composerElement = document.querySelector(".d-editor");
+
+ return composerModel && composerElement?.contains(activeElement);
+ }
+
+ get isTextAreaFocused() {
+ return this.#isTextArea(document.activeElement);
+ }
+
+ #isTextArea(element) {
+ return element?.nodeName === "TEXTAREA";
+ }
+
+ #showModal(textarea, onInsertTemplate) {
+ this.dTemplatesModal.show({ textarea, onInsertTemplate });
+ }
+
+ #showComposerPreviewUI(onInsertTemplate) {
+ this.appEvents.trigger("composer-messages:close");
+ this.appEvents.trigger("composer:show-preview");
+ this.appEvents.trigger("discourse-templates:show", { onInsertTemplate });
+ }
+
+ #insertTemplateIntoTextArea(textarea, template, variables) {
+ template = this.#replaceTemplateVariables(
+ template.title,
+ template.content,
+ variables
+ );
+
+ new TextareaTextManipulation(getOwner(this), { textarea }).insertBlock(
+ template.content
+ );
+ }
+
+ #insertTemplateIntoComposer(template) {
+ const composerModel = getOwner(this).lookup("service:composer").model;
+ const templateVariables = extractVariablesFromComposerModel(composerModel);
+
+ template = this.#replaceTemplateVariables(
+ template.title,
+ template.content,
+ templateVariables
+ );
+
+ // insert the title if blank
+ if (composerModel && !composerModel.title) {
+ composerModel.set("title", template.title);
+ }
+
+ // insert the content of the template in the composer
+ this.appEvents.trigger("composer:insert-block", template.content);
+ }
+
+ #replaceTemplateVariables(title, content, variables = {}) {
+ return replaceVariables(title, content, {
+ ...variables,
+ my_username: this.currentUser?.username,
+ my_name: this.currentUser?.displayName,
+ });
+ }
+}
diff --git a/plugins/discourse-templates/assets/javascripts/lib/replace-variables.js b/plugins/discourse-templates/assets/javascripts/lib/replace-variables.js
new file mode 100644
index 00000000000..c118b2a1087
--- /dev/null
+++ b/plugins/discourse-templates/assets/javascripts/lib/replace-variables.js
@@ -0,0 +1,58 @@
+import User from "discourse/models/user";
+
+// keep this list synchronized with the list in spec/plugin_helper.rb
+export const TEMPLATES_ALLOWED_VARIABLES = Object.freeze([
+ "my_username",
+ "my_name",
+ "chat_channel_name",
+ "chat_channel_url",
+ "chat_thread_name",
+ "chat_thread_url",
+ "context_title",
+ "context_url",
+ "topic_title",
+ "topic_url",
+ "original_poster_username",
+ "original_poster_name",
+ "reply_to_username",
+ "reply_to_name",
+ "last_poster_username",
+ "reply_to_or_last_poster_username",
+]);
+
+export function replaceVariables(title, content, modelVariables) {
+ const currentUser = User.current();
+ const variables = {
+ ...(modelVariables || {}),
+ my_username: currentUser?.username,
+ my_name: currentUser?.displayName,
+ };
+
+ if (variables && typeof variables === "object") {
+ for (const key of TEMPLATES_ALLOWED_VARIABLES) {
+ if (variables[key]) {
+ title = title.replace(
+ new RegExp(`%{${key}(,fallback:.[^}]*)?}`, "g"),
+ variables[key]
+ );
+ content = content.replace(
+ new RegExp(`%{${key}(,fallback:.[^}]*)?}`, "g"),
+ variables[key]
+ );
+ } else {
+ title = title.replace(
+ new RegExp(`%{${key},fallback:(.[^}]*)}`, "g"),
+ "$1"
+ );
+ title = title.replace(new RegExp(`%{${key}}`, "g"), "");
+ content = content.replace(
+ new RegExp(`%{${key},fallback:(.[^}]*)}`, "g"),
+ "$1"
+ );
+ content = content.replace(new RegExp(`%{${key}}`, "g"), "");
+ }
+ }
+ }
+
+ return { title, content };
+}
diff --git a/plugins/discourse-templates/assets/javascripts/lib/variables-chat-channel.js b/plugins/discourse-templates/assets/javascripts/lib/variables-chat-channel.js
new file mode 100644
index 00000000000..0e8d68f6376
--- /dev/null
+++ b/plugins/discourse-templates/assets/javascripts/lib/variables-chat-channel.js
@@ -0,0 +1,26 @@
+export default function extractVariablesFromChatChannel(
+ channel,
+ message,
+ router
+) {
+ if (!channel && !message) {
+ return {};
+ }
+
+ const inReplyTo = message?.inReplyTo;
+
+ const channelVariables = {
+ chat_channel_name: channel?.title,
+ chat_channel_url: channel?.routeModels
+ ? router?.urlFor("chat.channel", ...channel.routeModels)
+ : null,
+ reply_to_username: inReplyTo?.user?.username,
+ reply_to_name: inReplyTo?.user?.name,
+ };
+
+ return {
+ ...channelVariables,
+ context_title: channelVariables.chat_channel_name,
+ context_url: channelVariables.chat_channel_url,
+ };
+}
diff --git a/plugins/discourse-templates/assets/javascripts/lib/variables-chat-thread.js b/plugins/discourse-templates/assets/javascripts/lib/variables-chat-thread.js
new file mode 100644
index 00000000000..f7af5a56db4
--- /dev/null
+++ b/plugins/discourse-templates/assets/javascripts/lib/variables-chat-thread.js
@@ -0,0 +1,38 @@
+import extractVariablesFromChatChannel from "./variables-chat-channel";
+
+export default function extractVariablesFromChatThread(
+ thread,
+ message,
+ router
+) {
+ if (!thread && !message) {
+ return {};
+ }
+
+ const channel = thread?.channel;
+ const inReplyTo = thread?.originalMessage;
+
+ const channelVariables = extractVariablesFromChatChannel(
+ channel,
+ message,
+ router
+ );
+
+ const threadVariables = {
+ chat_thread_name: thread?.title,
+ chat_thread_url: thread?.routeModels
+ ? router?.urlFor("chat.channel.thread", ...thread.routeModels)
+ : null,
+ reply_to_username: inReplyTo?.user?.username,
+ reply_to_name: inReplyTo?.user?.name,
+ };
+
+ return {
+ ...channelVariables,
+ ...threadVariables,
+ context_title:
+ threadVariables.chat_thread_name || channelVariables.chat_channel_name,
+ context_url:
+ threadVariables.chat_thread_url || channelVariables.chat_channel_url,
+ };
+}
diff --git a/plugins/discourse-templates/assets/javascripts/lib/variables-composer.js b/plugins/discourse-templates/assets/javascripts/lib/variables-composer.js
new file mode 100644
index 00000000000..2db7dd1832a
--- /dev/null
+++ b/plugins/discourse-templates/assets/javascripts/lib/variables-composer.js
@@ -0,0 +1,23 @@
+export default function extractVariablesFromComposerModel(model) {
+ if (!model) {
+ return {};
+ }
+
+ const composerVariables = {
+ topic_title: model.topic?.title,
+ topic_url: model.topic?.url,
+ original_poster_username: model.topic?.details.created_by.username,
+ original_poster_name: model.topic?.details.created_by.name,
+ reply_to_username: model.post?.username,
+ reply_to_name: model.post?.name,
+ last_poster_username: model.topic?.last_poster_username,
+ reply_to_or_last_poster_username:
+ model.post?.username || model.topic?.last_poster_username,
+ };
+
+ return {
+ ...composerVariables,
+ context_title: composerVariables.topic_title,
+ context_url: composerVariables.topic_url,
+ };
+}
diff --git a/plugins/discourse-templates/assets/stylesheets/discourse-templates.scss b/plugins/discourse-templates/assets/stylesheets/discourse-templates.scss
new file mode 100644
index 00000000000..22189345e0e
--- /dev/null
+++ b/plugins/discourse-templates/assets/stylesheets/discourse-templates.scss
@@ -0,0 +1,148 @@
+.d-templates {
+ .templates-filter-bar {
+ display: flex;
+ max-width: var(--modal-max-width);
+ border-bottom: 1px solid var(--primary-low);
+ margin-bottom: 1em;
+ padding-top: 1px;
+ padding-bottom: 1em;
+
+ .select-kit {
+ width: clamp(30%, 40%, 50%);
+ }
+
+ input {
+ flex: 1;
+ width: 100%;
+ margin: 0 0 0 1em;
+ }
+
+ .close {
+ margin-left: auto;
+ }
+ }
+
+ .templates-footer {
+ align-items: stretch;
+ margin-top: 3px;
+ }
+
+ .templates-list {
+ .template-item {
+ padding-bottom: 1em;
+
+ .template-item-title {
+ display: flex;
+ align-items: center;
+
+ &:hover {
+ background-color: var(--highlight-medium);
+ cursor: pointer;
+ }
+
+ .template-item-title-text {
+ max-width: 75%;
+ }
+
+ .actions {
+ margin-left: auto;
+ }
+ }
+ }
+ }
+
+ .template-item-title-text {
+ font-weight: bold;
+ margin-left: 0.5em;
+
+ @include ellipsis;
+ }
+
+ .templates-content {
+ background: var(--primary-very-low);
+ padding: 0.75em;
+ margin-top: 0.5em;
+ box-sizing: border-box;
+
+ p:first-of-type {
+ margin-top: 0;
+ }
+
+ p:last-of-type {
+ margin-bottom: 0;
+ }
+ }
+
+ .template-item-source-link {
+ color: var(--primary-high);
+ font-size: var(--font-down-1);
+ padding-bottom: 0.5rem;
+ margin-bottom: 1rem;
+ display: block;
+ border-bottom: 1px solid var(--primary-low);
+
+ &:hover {
+ color: var(--tertiary);
+ }
+ }
+}
+
+#reply-control {
+ .d-templates {
+ position: relative;
+ height: 100%;
+ width: 100%;
+
+ .modal-close {
+ position: absolute;
+ right: 0;
+ margin: 0.5rem;
+ }
+
+ .templates-filter-bar {
+ margin-right: 3rem;
+ }
+ }
+}
+
+.d-templates-modal {
+ z-index: 9999;
+
+ .content {
+ margin-top: 10px;
+ }
+
+ .btn.link,
+ .btn.local-dates {
+ display: none;
+ }
+}
+
+.mobile-view .d-templates-modal {
+ min-height: 50vh;
+ box-sizing: border-box;
+ width: 100vw;
+ max-width: var(--modal-max-width);
+ overflow-x: hidden;
+ display: flex;
+ flex-direction: column;
+
+ .content {
+ max-height: 50vh;
+ }
+
+ .d-editor-preview-wrapper {
+ display: none;
+ }
+}
+
+.template-topic-controls {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.5em;
+ margin-bottom: 1em;
+
+ .mobile-view & {
+ font-size: var(--font-down-1);
+ }
+}
diff --git a/plugins/discourse-templates/config/locales/client.ar.yml b/plugins/discourse-templates/config/locales/client.ar.yml
new file mode 100644
index 00000000000..070f3335b6c
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/client.ar.yml
@@ -0,0 +1,26 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+ar:
+ admin_js:
+ discourse_templates:
+ title: "القوالب"
+ admin:
+ site_settings:
+ categories:
+ discourse_templates: "Discourse Templates"
+ js:
+ keyboard_shortcuts_help:
+ templates:
+ title: "القوالب (داخل منطقة نصية)"
+ insert_template: "%{shortcut} إدراج قالب"
+ templates:
+ filter_hint: "التصفية حسب العنوان..."
+ insert_template: "إدراج قالب"
+ close_templates: "إغلاق محدِّد القوالب"
+ copy: "نسخ القالب"
+ new_topic: "موضوع جديد من القالب"
+ source: "المصدر"
diff --git a/plugins/discourse-templates/config/locales/client.be.yml b/plugins/discourse-templates/config/locales/client.be.yml
new file mode 100644
index 00000000000..2ea77a0d350
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/client.be.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+be:
diff --git a/plugins/discourse-templates/config/locales/client.bg.yml b/plugins/discourse-templates/config/locales/client.bg.yml
new file mode 100644
index 00000000000..52333529d3c
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/client.bg.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+bg:
diff --git a/plugins/discourse-templates/config/locales/client.bs_BA.yml b/plugins/discourse-templates/config/locales/client.bs_BA.yml
new file mode 100644
index 00000000000..828a7e65af8
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/client.bs_BA.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+bs_BA:
diff --git a/plugins/discourse-templates/config/locales/client.ca.yml b/plugins/discourse-templates/config/locales/client.ca.yml
new file mode 100644
index 00000000000..ec737bc1a5b
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/client.ca.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+ca:
diff --git a/plugins/discourse-templates/config/locales/client.cs.yml b/plugins/discourse-templates/config/locales/client.cs.yml
new file mode 100644
index 00000000000..041b2f0bd05
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/client.cs.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+cs:
diff --git a/plugins/discourse-templates/config/locales/client.da.yml b/plugins/discourse-templates/config/locales/client.da.yml
new file mode 100644
index 00000000000..8380db9b2c8
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/client.da.yml
@@ -0,0 +1,19 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+da:
+ admin_js:
+ discourse_templates:
+ title: "Skabeloner"
+ js:
+ keyboard_shortcuts_help:
+ templates:
+ title: "Skabeloner (inden for et tekstområde)"
+ insert_template: "%{shortcut} Indsæt skabelon"
+ templates:
+ filter_hint: "Filtrer efter titel..."
+ insert_template: "Indsæt skabelon"
+ close_templates: "Luk skabelonvælgeren"
diff --git a/plugins/discourse-templates/config/locales/client.de.yml b/plugins/discourse-templates/config/locales/client.de.yml
new file mode 100644
index 00000000000..a5e41841d3b
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/client.de.yml
@@ -0,0 +1,26 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+de:
+ admin_js:
+ discourse_templates:
+ title: "Vorlagen"
+ admin:
+ site_settings:
+ categories:
+ discourse_templates: "Discourse – Vorlagen"
+ js:
+ keyboard_shortcuts_help:
+ templates:
+ title: "Vorlagen (innerhalb eines Textbereichs)"
+ insert_template: "%{shortcut} Vorlage einfügen"
+ templates:
+ filter_hint: "Nach Titel filtern …"
+ insert_template: "Vorlage einfügen"
+ close_templates: "Vorlagenauswahl schließen"
+ copy: "Vorlage kopieren"
+ new_topic: "Neues Thema aus Vorlage"
+ source: "Quelle"
diff --git a/plugins/discourse-templates/config/locales/client.el.yml b/plugins/discourse-templates/config/locales/client.el.yml
new file mode 100644
index 00000000000..d872d0ecc40
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/client.el.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+el:
diff --git a/plugins/discourse-templates/config/locales/client.en.yml b/plugins/discourse-templates/config/locales/client.en.yml
new file mode 100644
index 00000000000..c11ba628943
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/client.en.yml
@@ -0,0 +1,20 @@
+en:
+ admin_js:
+ discourse_templates:
+ title: "Templates"
+ admin:
+ site_settings:
+ categories:
+ discourse_templates: "Discourse Templates"
+ js:
+ keyboard_shortcuts_help:
+ templates:
+ title: "Templates (within a textarea)"
+ insert_template: "%{shortcut} Insert template"
+ templates:
+ filter_hint: "Filter by title..."
+ insert_template: "Insert template"
+ close_templates: "Close the templates selector"
+ copy: "Copy template"
+ new_topic: "New topic from template"
+ source: "Source"
diff --git a/plugins/discourse-templates/config/locales/client.en_GB.yml b/plugins/discourse-templates/config/locales/client.en_GB.yml
new file mode 100644
index 00000000000..2d4fa180ec7
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/client.en_GB.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+en_GB:
diff --git a/plugins/discourse-templates/config/locales/client.es.yml b/plugins/discourse-templates/config/locales/client.es.yml
new file mode 100644
index 00000000000..6161b9a2746
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/client.es.yml
@@ -0,0 +1,26 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+es:
+ admin_js:
+ discourse_templates:
+ title: "Plantillas"
+ admin:
+ site_settings:
+ categories:
+ discourse_templates: "Plantillas de Discourse"
+ js:
+ keyboard_shortcuts_help:
+ templates:
+ title: "Plantillas (dentro de un área de texto)"
+ insert_template: "%{shortcut} Insertar plantilla"
+ templates:
+ filter_hint: "Filtrar por título..."
+ insert_template: "Insertar plantilla"
+ close_templates: "Cerrar el selector de plantillas"
+ copy: "Copiar plantilla"
+ new_topic: "Nuevo tema a partir de la plantilla"
+ source: "Fuente"
diff --git a/plugins/discourse-templates/config/locales/client.et.yml b/plugins/discourse-templates/config/locales/client.et.yml
new file mode 100644
index 00000000000..0ea0b6d554b
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/client.et.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+et:
diff --git a/plugins/discourse-templates/config/locales/client.fa_IR.yml b/plugins/discourse-templates/config/locales/client.fa_IR.yml
new file mode 100644
index 00000000000..8a851630bc0
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/client.fa_IR.yml
@@ -0,0 +1,11 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+fa_IR:
+ js:
+ templates:
+ filter_hint: "فیلتر بر اساس عنوان..."
+ source: "منبع"
diff --git a/plugins/discourse-templates/config/locales/client.fi.yml b/plugins/discourse-templates/config/locales/client.fi.yml
new file mode 100644
index 00000000000..7cae8016e45
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/client.fi.yml
@@ -0,0 +1,26 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+fi:
+ admin_js:
+ discourse_templates:
+ title: "Mallit"
+ admin:
+ site_settings:
+ categories:
+ discourse_templates: "Discoursen Mallit"
+ js:
+ keyboard_shortcuts_help:
+ templates:
+ title: "Mallit (tekstialueella)"
+ insert_template: "%{shortcut} Lisää malli"
+ templates:
+ filter_hint: "Suodata nimen mukaan..."
+ insert_template: "Lisää malli"
+ close_templates: "Sulje mallien valitsin"
+ copy: "Kopioi malli"
+ new_topic: "Uusi ketju mallista"
+ source: "Lähde"
diff --git a/plugins/discourse-templates/config/locales/client.fr.yml b/plugins/discourse-templates/config/locales/client.fr.yml
new file mode 100644
index 00000000000..3e297db73f8
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/client.fr.yml
@@ -0,0 +1,26 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+fr:
+ admin_js:
+ discourse_templates:
+ title: "Modèles"
+ admin:
+ site_settings:
+ categories:
+ discourse_templates: "Modèles de Discourse"
+ js:
+ keyboard_shortcuts_help:
+ templates:
+ title: "Modèles (dans une zone de texte)"
+ insert_template: "%{shortcut} Insérer un modèle"
+ templates:
+ filter_hint: "Filtrer par titre…"
+ insert_template: "Insérer un modèle"
+ close_templates: "Fermer le sélecteur de modèles"
+ copy: "Copier le modèle"
+ new_topic: "Nouveau sujet à partir du modèle"
+ source: "Source"
diff --git a/plugins/discourse-templates/config/locales/client.gl.yml b/plugins/discourse-templates/config/locales/client.gl.yml
new file mode 100644
index 00000000000..fb911ce1635
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/client.gl.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+gl:
diff --git a/plugins/discourse-templates/config/locales/client.he.yml b/plugins/discourse-templates/config/locales/client.he.yml
new file mode 100644
index 00000000000..12d85ce168d
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/client.he.yml
@@ -0,0 +1,26 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+he:
+ admin_js:
+ discourse_templates:
+ title: "תבניות"
+ admin:
+ site_settings:
+ categories:
+ discourse_templates: "תבניות Discourse"
+ js:
+ keyboard_shortcuts_help:
+ templates:
+ title: "תבניות (בתוך אזור טקסט)"
+ insert_template: "%{shortcut} הוספת תבנית"
+ templates:
+ filter_hint: "סנן לפי כותרת…"
+ insert_template: "הוספת תבנית"
+ close_templates: "סגירת בורר התבניות"
+ copy: "העתקת תבנית"
+ new_topic: "נושא חדש מתבנית"
+ source: "מקור"
diff --git a/plugins/discourse-templates/config/locales/client.hr.yml b/plugins/discourse-templates/config/locales/client.hr.yml
new file mode 100644
index 00000000000..93343ce6e19
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/client.hr.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+hr:
diff --git a/plugins/discourse-templates/config/locales/client.hu.yml b/plugins/discourse-templates/config/locales/client.hu.yml
new file mode 100644
index 00000000000..76b6e9d8bcb
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/client.hu.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+hu:
diff --git a/plugins/discourse-templates/config/locales/client.hy.yml b/plugins/discourse-templates/config/locales/client.hy.yml
new file mode 100644
index 00000000000..cb18f64d356
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/client.hy.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+hy:
diff --git a/plugins/discourse-templates/config/locales/client.id.yml b/plugins/discourse-templates/config/locales/client.id.yml
new file mode 100644
index 00000000000..596e36b2e13
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/client.id.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+id:
diff --git a/plugins/discourse-templates/config/locales/client.it.yml b/plugins/discourse-templates/config/locales/client.it.yml
new file mode 100644
index 00000000000..af47ab1ba2e
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/client.it.yml
@@ -0,0 +1,26 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+it:
+ admin_js:
+ discourse_templates:
+ title: "Modelli"
+ admin:
+ site_settings:
+ categories:
+ discourse_templates: "Modelli Discourse"
+ js:
+ keyboard_shortcuts_help:
+ templates:
+ title: "Modelli (all'interno di un'area di testo)"
+ insert_template: "%{shortcut} Inserisci modello"
+ templates:
+ filter_hint: "Filtra per titolo..."
+ insert_template: "Inserisci modello"
+ close_templates: "Chiudi il selettore dei modelli"
+ copy: "Copia modello"
+ new_topic: "Nuovo argomento dal modello"
+ source: "Fonte"
diff --git a/plugins/discourse-templates/config/locales/client.ja.yml b/plugins/discourse-templates/config/locales/client.ja.yml
new file mode 100644
index 00000000000..b796fd780d1
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/client.ja.yml
@@ -0,0 +1,26 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+ja:
+ admin_js:
+ discourse_templates:
+ title: "テンプレート"
+ admin:
+ site_settings:
+ categories:
+ discourse_templates: "Discourse テンプレート"
+ js:
+ keyboard_shortcuts_help:
+ templates:
+ title: "テンプレート (テキストエリア内)"
+ insert_template: "%{shortcut} テンプレートの挿入"
+ templates:
+ filter_hint: "タイトルで絞り込みます..."
+ insert_template: "テンプレートの挿入"
+ close_templates: "テンプレートセレクタを閉じる"
+ copy: "テンプレートのコピー"
+ new_topic: "テンプレートの新規トピック"
+ source: "ソース"
diff --git a/plugins/discourse-templates/config/locales/client.ko.yml b/plugins/discourse-templates/config/locales/client.ko.yml
new file mode 100644
index 00000000000..18dd77fd3ec
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/client.ko.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+ko:
diff --git a/plugins/discourse-templates/config/locales/client.lt.yml b/plugins/discourse-templates/config/locales/client.lt.yml
new file mode 100644
index 00000000000..16bb19758dc
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/client.lt.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+lt:
diff --git a/plugins/discourse-templates/config/locales/client.lv.yml b/plugins/discourse-templates/config/locales/client.lv.yml
new file mode 100644
index 00000000000..59e0ef6f4ed
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/client.lv.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+lv:
diff --git a/plugins/discourse-templates/config/locales/client.nb_NO.yml b/plugins/discourse-templates/config/locales/client.nb_NO.yml
new file mode 100644
index 00000000000..2e2224d1472
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/client.nb_NO.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+nb_NO:
diff --git a/plugins/discourse-templates/config/locales/client.nl.yml b/plugins/discourse-templates/config/locales/client.nl.yml
new file mode 100644
index 00000000000..fdf649eb007
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/client.nl.yml
@@ -0,0 +1,26 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+nl:
+ admin_js:
+ discourse_templates:
+ title: "Sjablonen"
+ admin:
+ site_settings:
+ categories:
+ discourse_templates: "Discourse-sjablonen"
+ js:
+ keyboard_shortcuts_help:
+ templates:
+ title: "Sjablonen (binnen een tekstgebied)"
+ insert_template: "%{shortcut} Sjabloon invoegen"
+ templates:
+ filter_hint: "Filteren op titel..."
+ insert_template: "Sjabloon invoegen"
+ close_templates: "Sluit de sjabloonkiezer"
+ copy: "Sjabloon kopiëren"
+ new_topic: "Nieuw topic van sjabloon"
+ source: "Bron"
diff --git a/plugins/discourse-templates/config/locales/client.pl_PL.yml b/plugins/discourse-templates/config/locales/client.pl_PL.yml
new file mode 100644
index 00000000000..dd727fb76c4
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/client.pl_PL.yml
@@ -0,0 +1,19 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+pl_PL:
+ admin_js:
+ discourse_templates:
+ title: "Szablony"
+ js:
+ keyboard_shortcuts_help:
+ templates:
+ title: "Szablony (w obszarze tekstowym)"
+ insert_template: "%{shortcut} Wstaw szablon"
+ templates:
+ filter_hint: "Filtruj według tytułu..."
+ insert_template: "Wstaw szablon"
+ close_templates: "Zamknij selektor szablonów"
diff --git a/plugins/discourse-templates/config/locales/client.pt.yml b/plugins/discourse-templates/config/locales/client.pt.yml
new file mode 100644
index 00000000000..298ba523c1d
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/client.pt.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+pt:
diff --git a/plugins/discourse-templates/config/locales/client.pt_BR.yml b/plugins/discourse-templates/config/locales/client.pt_BR.yml
new file mode 100644
index 00000000000..773fd21d9d8
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/client.pt_BR.yml
@@ -0,0 +1,26 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+pt_BR:
+ admin_js:
+ discourse_templates:
+ title: "Modelos"
+ admin:
+ site_settings:
+ categories:
+ discourse_templates: "Discourse Templates"
+ js:
+ keyboard_shortcuts_help:
+ templates:
+ title: "Modelos (dentro de uma área de texto)"
+ insert_template: "%{shortcut} Inserir modelo"
+ templates:
+ filter_hint: "Filtrar pelo título..."
+ insert_template: "Inserir modelo"
+ close_templates: "Fechar o seletor de modelos"
+ copy: "Copiar modelo"
+ new_topic: "Novo tópico do modelo"
+ source: "Origem"
diff --git a/plugins/discourse-templates/config/locales/client.ro.yml b/plugins/discourse-templates/config/locales/client.ro.yml
new file mode 100644
index 00000000000..08a77f812ee
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/client.ro.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+ro:
diff --git a/plugins/discourse-templates/config/locales/client.ru.yml b/plugins/discourse-templates/config/locales/client.ru.yml
new file mode 100644
index 00000000000..d4a06dd9c76
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/client.ru.yml
@@ -0,0 +1,26 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+ru:
+ admin_js:
+ discourse_templates:
+ title: "Шаблоны"
+ admin:
+ site_settings:
+ categories:
+ discourse_templates: "Плагин Discourse «Шаблоны»"
+ js:
+ keyboard_shortcuts_help:
+ templates:
+ title: "Шаблоны (в текстовом поле)"
+ insert_template: "%{shortcut} Вставить шаблон"
+ templates:
+ filter_hint: "Фильтр по названию…"
+ insert_template: "Вставить шаблон"
+ close_templates: "Закрыть выбор шаблона"
+ copy: "Копировать шаблон"
+ new_topic: "Новая тема из шаблона"
+ source: "Источник"
diff --git a/plugins/discourse-templates/config/locales/client.sk.yml b/plugins/discourse-templates/config/locales/client.sk.yml
new file mode 100644
index 00000000000..6f815624081
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/client.sk.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+sk:
diff --git a/plugins/discourse-templates/config/locales/client.sl.yml b/plugins/discourse-templates/config/locales/client.sl.yml
new file mode 100644
index 00000000000..23489a48b1f
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/client.sl.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+sl:
diff --git a/plugins/discourse-templates/config/locales/client.sq.yml b/plugins/discourse-templates/config/locales/client.sq.yml
new file mode 100644
index 00000000000..7f051b7a7cf
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/client.sq.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+sq:
diff --git a/plugins/discourse-templates/config/locales/client.sr.yml b/plugins/discourse-templates/config/locales/client.sr.yml
new file mode 100644
index 00000000000..88d63d6ae1a
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/client.sr.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+sr:
diff --git a/plugins/discourse-templates/config/locales/client.sv.yml b/plugins/discourse-templates/config/locales/client.sv.yml
new file mode 100644
index 00000000000..1f8f2a6bab0
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/client.sv.yml
@@ -0,0 +1,19 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+sv:
+ admin_js:
+ discourse_templates:
+ title: "Mallar"
+ js:
+ keyboard_shortcuts_help:
+ templates:
+ title: "Mallar (inom ett textområde)"
+ insert_template: "%{shortcut} Infoga mall"
+ templates:
+ filter_hint: "Filtrera efter titel..."
+ insert_template: "Infoga mall"
+ close_templates: "Stäng val av mallar"
diff --git a/plugins/discourse-templates/config/locales/client.sw.yml b/plugins/discourse-templates/config/locales/client.sw.yml
new file mode 100644
index 00000000000..0d7cdd075bf
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/client.sw.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+sw:
diff --git a/plugins/discourse-templates/config/locales/client.te.yml b/plugins/discourse-templates/config/locales/client.te.yml
new file mode 100644
index 00000000000..03967bdbb07
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/client.te.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+te:
diff --git a/plugins/discourse-templates/config/locales/client.th.yml b/plugins/discourse-templates/config/locales/client.th.yml
new file mode 100644
index 00000000000..7de85ff91c4
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/client.th.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+th:
diff --git a/plugins/discourse-templates/config/locales/client.tr_TR.yml b/plugins/discourse-templates/config/locales/client.tr_TR.yml
new file mode 100644
index 00000000000..20892b26a38
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/client.tr_TR.yml
@@ -0,0 +1,26 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+tr_TR:
+ admin_js:
+ discourse_templates:
+ title: "Şablonlar"
+ admin:
+ site_settings:
+ categories:
+ discourse_templates: "Discourse Şablonları"
+ js:
+ keyboard_shortcuts_help:
+ templates:
+ title: "Şablonlar (metin alanı içinde)"
+ insert_template: "%{shortcut} Şablon ekle"
+ templates:
+ filter_hint: "Başlığa göre filtrele..."
+ insert_template: "Şablon ekle"
+ close_templates: "Şablon seçiciyi kapat"
+ copy: "Şablonu kopyala"
+ new_topic: "Şablondan yeni konu"
+ source: "Kaynak"
diff --git a/plugins/discourse-templates/config/locales/client.ug.yml b/plugins/discourse-templates/config/locales/client.ug.yml
new file mode 100644
index 00000000000..a6bf0185ae2
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/client.ug.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+ug:
diff --git a/plugins/discourse-templates/config/locales/client.uk.yml b/plugins/discourse-templates/config/locales/client.uk.yml
new file mode 100644
index 00000000000..f1390545d1d
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/client.uk.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+uk:
diff --git a/plugins/discourse-templates/config/locales/client.ur.yml b/plugins/discourse-templates/config/locales/client.ur.yml
new file mode 100644
index 00000000000..b4a9c21ee2f
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/client.ur.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+ur:
diff --git a/plugins/discourse-templates/config/locales/client.vi.yml b/plugins/discourse-templates/config/locales/client.vi.yml
new file mode 100644
index 00000000000..f629dcf5329
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/client.vi.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+vi:
diff --git a/plugins/discourse-templates/config/locales/client.zh_CN.yml b/plugins/discourse-templates/config/locales/client.zh_CN.yml
new file mode 100644
index 00000000000..1fbedfaa8b6
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/client.zh_CN.yml
@@ -0,0 +1,26 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+zh_CN:
+ admin_js:
+ discourse_templates:
+ title: "模板"
+ admin:
+ site_settings:
+ categories:
+ discourse_templates: "Discourse Templates"
+ js:
+ keyboard_shortcuts_help:
+ templates:
+ title: "模板(文本区域内)"
+ insert_template: "%{shortcut} 插入模板"
+ templates:
+ filter_hint: "按标题筛选…"
+ insert_template: "插入模板"
+ close_templates: "关闭模板选择器"
+ copy: "复制模板"
+ new_topic: "从模板新建话题"
+ source: "来源"
diff --git a/plugins/discourse-templates/config/locales/client.zh_TW.yml b/plugins/discourse-templates/config/locales/client.zh_TW.yml
new file mode 100644
index 00000000000..7e15fab0018
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/client.zh_TW.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+zh_TW:
diff --git a/plugins/discourse-templates/config/locales/server.ar.yml b/plugins/discourse-templates/config/locales/server.ar.yml
new file mode 100644
index 00000000000..73cca5eb66b
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/server.ar.yml
@@ -0,0 +1,23 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+ar:
+ site_settings:
+ discourse_templates_enabled: "السماح للمستخدمين ذوي إذن الوصول إلى العرض في الفئة المحدَّدة أدناه باستخدام القوالب المتاحة"
+ discourse_templates_categories: "الفئات لجلب القوالب منها"
+ discourse_templates_enable_private_templates: "يفعِّل استخدام القوالب الخاصة"
+ discourse_templates_groups_allowed_private_templates: "المجموعات المسموح لها باستخدام قوالب خاصة. مسموح بذلك دائمًا لأعضاء فريق العمل."
+ discourse_templates_private_templates_tags: "الوسوم التي تحدِّد رسالة خاصة كقالبٍ خاص"
+ default_category_template:
+ name: القوالب
+ description: |
+ يتم استخدام هذه الفئة لتخزين القوالب.
+
+ تسمح القوالب للمستخدمين بتخزين المحتوى للاستخدام المتكرر.
+
+ يمثِّل كل موضوع في هذه الفئة قالبًا مختلفًا. يتم استخدام **أول منشور** لكل موضوع كنموذج للقالب.
+
+ لاحظ أنه سيتم السماح لكل مستخدم لديه إذن الوصول في هذه الفئة باستخدام القوالب.
diff --git a/plugins/discourse-templates/config/locales/server.be.yml b/plugins/discourse-templates/config/locales/server.be.yml
new file mode 100644
index 00000000000..2ea77a0d350
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/server.be.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+be:
diff --git a/plugins/discourse-templates/config/locales/server.bg.yml b/plugins/discourse-templates/config/locales/server.bg.yml
new file mode 100644
index 00000000000..52333529d3c
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/server.bg.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+bg:
diff --git a/plugins/discourse-templates/config/locales/server.bs_BA.yml b/plugins/discourse-templates/config/locales/server.bs_BA.yml
new file mode 100644
index 00000000000..828a7e65af8
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/server.bs_BA.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+bs_BA:
diff --git a/plugins/discourse-templates/config/locales/server.ca.yml b/plugins/discourse-templates/config/locales/server.ca.yml
new file mode 100644
index 00000000000..ec737bc1a5b
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/server.ca.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+ca:
diff --git a/plugins/discourse-templates/config/locales/server.cs.yml b/plugins/discourse-templates/config/locales/server.cs.yml
new file mode 100644
index 00000000000..041b2f0bd05
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/server.cs.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+cs:
diff --git a/plugins/discourse-templates/config/locales/server.da.yml b/plugins/discourse-templates/config/locales/server.da.yml
new file mode 100644
index 00000000000..51571216939
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/server.da.yml
@@ -0,0 +1,23 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+da:
+ site_settings:
+ discourse_templates_enabled: "Tillad brugere med visningsadgang i kategorien angivet nedenfor at bruge tilgængelige skabeloner"
+ discourse_templates_categories: "Kategorier at hente skabelonerne fra"
+ discourse_templates_enable_private_templates: "Aktiverer brug af private skabeloner"
+ discourse_templates_groups_allowed_private_templates: "Grupper med tilladelse til at bruge private skabeloner. Personale er altid tilladt."
+ discourse_templates_private_templates_tags: "Mærker, der identificerer en privat besked som en privat skabelon"
+ default_category_template:
+ name: Skabeloner
+ description: |
+ Denne kategori bruges til at gemme skabeloner.
+
+ Skabeloner giver brugerne mulighed for at gemme indhold til hyppigt gentagen brug.
+
+ Hvert emne i denne kategori repræsenterer en anden skabelon. **Det første indlæg** af hvert emne bruges som model for skabelonen.
+
+ Bemærk, at alle brugere med adgang i denne kategori får lov til at bruge skabeloner.
diff --git a/plugins/discourse-templates/config/locales/server.de.yml b/plugins/discourse-templates/config/locales/server.de.yml
new file mode 100644
index 00000000000..7b7e81d6d10
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/server.de.yml
@@ -0,0 +1,23 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+de:
+ site_settings:
+ discourse_templates_enabled: "Benutzern mit Anzeigezugriff auf die unten angegebene Kategorie erlauben, verfügbare Vorlagen zu verwenden"
+ discourse_templates_categories: "Kategorien, aus denen die Vorlagen abgerufen werden sollen"
+ discourse_templates_enable_private_templates: "Aktiviert die Verwendung von privaten Vorlagen"
+ discourse_templates_groups_allowed_private_templates: "Gruppen, die private Vorlagen verwenden dürfen. Team-Mitgliedern ist dies immer erlaubt."
+ discourse_templates_private_templates_tags: "Schlagwörter, die eine private Nachricht als private Vorlage identifizieren"
+ default_category_template:
+ name: Vorlagen
+ description: |
+ Diese Kategorie wird verwendet, um Vorlagen zu speichern.
+
+ Vorlagen erlauben Benutzern, Inhalte für häufig wiederholte Verwendungen zu speichern.
+
+ Jedes Thema in dieser Kategorie stellt eine andere Vorlage dar. **Der erste Beitrag** jedes Themas wird als Modell für die Vorlage verwendet.
+
+ Beachte, dass jeder Benutzer mit Zugriff in dieser Kategorie Vorlagen verwenden darf.
diff --git a/plugins/discourse-templates/config/locales/server.el.yml b/plugins/discourse-templates/config/locales/server.el.yml
new file mode 100644
index 00000000000..d872d0ecc40
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/server.el.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+el:
diff --git a/plugins/discourse-templates/config/locales/server.en.yml b/plugins/discourse-templates/config/locales/server.en.yml
new file mode 100644
index 00000000000..0d6a17da54b
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/server.en.yml
@@ -0,0 +1,17 @@
+en:
+ site_settings:
+ discourse_templates_enabled: "Allow users with view access on the category specified below to use available templates"
+ discourse_templates_categories: "Categories to fetch the templates from"
+ discourse_templates_enable_private_templates: "Enables the use of private templates"
+ discourse_templates_groups_allowed_private_templates: "Groups allowed to use private templates. Staff members are always allowed."
+ discourse_templates_private_templates_tags: "Tags that identify a personal message as a private template"
+ default_category_template:
+ name: Templates
+ description: |
+ This category is used to store templates.
+
+ Templates allow users to store content for frequently repeated use.
+
+ Each topic in this category represents a different template. **The first post** of each topic is used as the model for the template.
+
+ Note that every user with access in this category will be allowed to use templates.
diff --git a/plugins/discourse-templates/config/locales/server.en_GB.yml b/plugins/discourse-templates/config/locales/server.en_GB.yml
new file mode 100644
index 00000000000..2d4fa180ec7
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/server.en_GB.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+en_GB:
diff --git a/plugins/discourse-templates/config/locales/server.es.yml b/plugins/discourse-templates/config/locales/server.es.yml
new file mode 100644
index 00000000000..17b85b2310e
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/server.es.yml
@@ -0,0 +1,23 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+es:
+ site_settings:
+ discourse_templates_enabled: "Permitir a los usuarios con acceso de visualización en la categoría especificada a continuación utilizar las plantillas disponibles"
+ discourse_templates_categories: "Categorías de las que obtener las plantillas"
+ discourse_templates_enable_private_templates: "Permite el uso de plantillas privadas"
+ discourse_templates_groups_allowed_private_templates: "Los grupos pueden usar plantillas privadas. Siempre se permite a los miembros del personal."
+ discourse_templates_private_templates_tags: "Etiquetas que identifican un mensaje privado como plantilla privada"
+ default_category_template:
+ name: Plantillas
+ description: |
+ Esta categoría se utiliza para almacenar plantillas.
+
+ Las plantillas permiten a los usuarios almacenar contenidos que se repiten con frecuencia.
+
+ Cada tema de esta categoría representa una plantilla diferente. **El primer mensaje** de cada tema se utiliza como modelo para la plantilla.
+
+ Ten en cuenta que todo usuario con acceso en esta categoría podrá utilizar plantillas.
diff --git a/plugins/discourse-templates/config/locales/server.et.yml b/plugins/discourse-templates/config/locales/server.et.yml
new file mode 100644
index 00000000000..0ea0b6d554b
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/server.et.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+et:
diff --git a/plugins/discourse-templates/config/locales/server.fa_IR.yml b/plugins/discourse-templates/config/locales/server.fa_IR.yml
new file mode 100644
index 00000000000..56512089fb5
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/server.fa_IR.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+fa_IR:
diff --git a/plugins/discourse-templates/config/locales/server.fi.yml b/plugins/discourse-templates/config/locales/server.fi.yml
new file mode 100644
index 00000000000..c7aed6b19fb
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/server.fi.yml
@@ -0,0 +1,23 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+fi:
+ site_settings:
+ discourse_templates_enabled: "Salli käyttäjien, joilla on alla määritetyn luokan tarkasteluoikeudet, käyttää käytettävissä olevia malleja"
+ discourse_templates_categories: "Alueet, joista malleja haetaan"
+ discourse_templates_enable_private_templates: "Mahdollistaa yksityisten mallien käytön"
+ discourse_templates_groups_allowed_private_templates: "Ryhmät saavat käyttää yksityisiä malleja. Henkilökunnan jäsenet saavat aina käyttää niitä."
+ discourse_templates_private_templates_tags: "Tunnisteet, joista yksityisviestin tunnistaa yksityiseksi malliksi"
+ default_category_template:
+ name: Mallit
+ description: |
+ Tätä aluetta käytetään mallien tallentamiseen.
+
+ Mallien avulla käyttäjät voivat tallentaa sisältöä toistuvaa käyttöä varten.
+
+ Jokainen tämän alueen aihe edustaa eri mallia. Kunkin ketjun **ensimmäistä viestiä** käytetään mallin mallina.
+
+ Jokainen käyttäjä, jolla on tämän alueen käyttöoikeus, voi käyttää malleja.
diff --git a/plugins/discourse-templates/config/locales/server.fr.yml b/plugins/discourse-templates/config/locales/server.fr.yml
new file mode 100644
index 00000000000..a95ecd29815
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/server.fr.yml
@@ -0,0 +1,23 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+fr:
+ site_settings:
+ discourse_templates_enabled: "Autoriser les utilisateurs disposant d'un accès en lecture sur la catégorie spécifiée ci-dessous à utiliser les modèles disponibles"
+ discourse_templates_categories: "Catégories à partir desquelles récupérer les modèles"
+ discourse_templates_enable_private_templates: "Permet l'utilisation de modèles privés"
+ discourse_templates_groups_allowed_private_templates: "Groupes autorisés à utiliser des modèles privés. Les responsables sont toujours autorisés."
+ discourse_templates_private_templates_tags: "Étiquettes identifiant un message privé en tant que modèle privé"
+ default_category_template:
+ name: Modèles
+ description: |
+ Cette catégorie est utilisée pour stocker des modèles.
+
+ Les modèles permettent aux utilisateurs de stocker du contenu pour une utilisation fréquente.
+
+ Chaque sujet de cette catégorie représente un modèle différent. **Le premier message** de chaque sujet est utilisé comme modèle pour le modèle.
+
+ Notez que chaque utilisateur ayant accès à cette catégorie sera autorisé à utiliser des modèles.
diff --git a/plugins/discourse-templates/config/locales/server.gl.yml b/plugins/discourse-templates/config/locales/server.gl.yml
new file mode 100644
index 00000000000..fb911ce1635
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/server.gl.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+gl:
diff --git a/plugins/discourse-templates/config/locales/server.he.yml b/plugins/discourse-templates/config/locales/server.he.yml
new file mode 100644
index 00000000000..17286329cbe
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/server.he.yml
@@ -0,0 +1,23 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+he:
+ site_settings:
+ discourse_templates_enabled: "לאפשר למשתמשים עם גישת צפייה לגשת לקטגוריה שצוינה להלן כדי להשתמש בתבניות הזמינות"
+ discourse_templates_categories: "קטגוריות מהן למשוך את התבניות"
+ discourse_templates_enable_private_templates: "לאפשר שימוש בתבניות פרטיות"
+ discourse_templates_groups_allowed_private_templates: "קבוצות מורשות להשתמש בתבניות פרטיות. לחברי הסגל תמיד מותר."
+ discourse_templates_private_templates_tags: "תגיות שמזהות הודעה פרטית כתבנית פרטית"
+ default_category_template:
+ name: תבניות
+ description: |
+ קטגוריה זו משמשת לאחסון תבניות.
+
+ תבניות מאפשרות למשתמשים לאחסן תוכן לשימוש חוזר תדיר.
+
+ כל נושא בקטגוריה זו מייצג תבנית שונה. **הפוסט הראשון** של כל נושא משמש כדגם לתבנית.
+
+ יש לשים לב שלכל משתמש שיש גישה לקטגוריה זו יורשה להשתמש בתבניות שבשימוש.
diff --git a/plugins/discourse-templates/config/locales/server.hr.yml b/plugins/discourse-templates/config/locales/server.hr.yml
new file mode 100644
index 00000000000..93343ce6e19
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/server.hr.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+hr:
diff --git a/plugins/discourse-templates/config/locales/server.hu.yml b/plugins/discourse-templates/config/locales/server.hu.yml
new file mode 100644
index 00000000000..76b6e9d8bcb
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/server.hu.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+hu:
diff --git a/plugins/discourse-templates/config/locales/server.hy.yml b/plugins/discourse-templates/config/locales/server.hy.yml
new file mode 100644
index 00000000000..cb18f64d356
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/server.hy.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+hy:
diff --git a/plugins/discourse-templates/config/locales/server.id.yml b/plugins/discourse-templates/config/locales/server.id.yml
new file mode 100644
index 00000000000..596e36b2e13
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/server.id.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+id:
diff --git a/plugins/discourse-templates/config/locales/server.it.yml b/plugins/discourse-templates/config/locales/server.it.yml
new file mode 100644
index 00000000000..05ab028e4bf
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/server.it.yml
@@ -0,0 +1,23 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+it:
+ site_settings:
+ discourse_templates_enabled: "Consenti agli utenti con accesso alla visualizzazione nella categoria specificata di seguito di utilizzare i modelli disponibili"
+ discourse_templates_categories: "Categorie da cui prelevare i modelli"
+ discourse_templates_enable_private_templates: "Consente l'uso di modelli privati"
+ discourse_templates_groups_allowed_private_templates: "Gruppi autorizzati a utilizzare modelli privati. I membri dello staff sono sempre autorizzati."
+ discourse_templates_private_templates_tags: "Tag che identificano un messaggio privato come modello privato"
+ default_category_template:
+ name: Modelli
+ description: |
+ Questa categoria è utilizzata per archiviare i modelli.
+
+ I modelli consentono agli utenti di archiviare contenuti per un uso ripetuto frequente.
+
+ Ciascun argomento in questa categoria rappresenta un modello diverso. **Il primo messaggio** di ogni argomento viene utilizzato come formato per il modello.
+
+ Si noti che tutti gli utenti con accesso a questa categoria potranno utilizzare i modelli.
diff --git a/plugins/discourse-templates/config/locales/server.ja.yml b/plugins/discourse-templates/config/locales/server.ja.yml
new file mode 100644
index 00000000000..19d15e712ff
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/server.ja.yml
@@ -0,0 +1,23 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+ja:
+ site_settings:
+ discourse_templates_enabled: "以下に指定されたカテゴリの表示アクセス権を持つユーザーに、利用可能なテンプレートの使用を許可する"
+ discourse_templates_categories: "テンプレートを取得するカテゴリ"
+ discourse_templates_enable_private_templates: "プライベートテンプレートの使用を有効にします"
+ discourse_templates_groups_allowed_private_templates: "プライベートテンプレートの使用が許可されたグループ。スタッフメンバーは常に許可されます。"
+ discourse_templates_private_templates_tags: "プライベートメッセージをプライベートテンプレートとして識別するタグ"
+ default_category_template:
+ name: テンプレート
+ description: |
+ このカテゴリはテンプレートの保存に使用されます。
+
+ テンプレートを使うと、ユーザーは頻繁に繰り返し使用するコンテンツを保存できます。
+
+ このカテゴリの各トピックは、異なるテンプレートです。各トピックの**最初の投稿**はテンプレートのモデルとして使用されます。
+
+ このカテゴリにアクセスできるすべてのユーザーは、テンプレートを使用できることに注意してください。
diff --git a/plugins/discourse-templates/config/locales/server.ko.yml b/plugins/discourse-templates/config/locales/server.ko.yml
new file mode 100644
index 00000000000..18dd77fd3ec
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/server.ko.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+ko:
diff --git a/plugins/discourse-templates/config/locales/server.lt.yml b/plugins/discourse-templates/config/locales/server.lt.yml
new file mode 100644
index 00000000000..16bb19758dc
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/server.lt.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+lt:
diff --git a/plugins/discourse-templates/config/locales/server.lv.yml b/plugins/discourse-templates/config/locales/server.lv.yml
new file mode 100644
index 00000000000..59e0ef6f4ed
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/server.lv.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+lv:
diff --git a/plugins/discourse-templates/config/locales/server.nb_NO.yml b/plugins/discourse-templates/config/locales/server.nb_NO.yml
new file mode 100644
index 00000000000..2e2224d1472
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/server.nb_NO.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+nb_NO:
diff --git a/plugins/discourse-templates/config/locales/server.nl.yml b/plugins/discourse-templates/config/locales/server.nl.yml
new file mode 100644
index 00000000000..a4e6aca8de6
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/server.nl.yml
@@ -0,0 +1,23 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+nl:
+ site_settings:
+ discourse_templates_enabled: "Sta gebruikers met weergaverechten voor de hieronder opgegeven categorie toe om beschikbare sjablonen te gebruiken"
+ discourse_templates_categories: "Categorieën om de sjablonen uit op te halen"
+ discourse_templates_enable_private_templates: "Schakelt het gebruik van privésjablonen in"
+ discourse_templates_groups_allowed_private_templates: "Groepen mogen privésjablonen gebruiken. Medewerkers zijn altijd toegestaan."
+ discourse_templates_private_templates_tags: "Tags die een privébericht identificeren als een privésjabloon"
+ default_category_template:
+ name: Sjablonen
+ description: |
+ Deze categorie wordt gebruikt om sjablonen op te slaan.
+
+ Met sjablonen kunnen gebruikers inhoud opslaan voor herhaald gebruik.
+
+ Elk topic in deze categorie vertegenwoordigt een ander sjabloon. **Het eerste bericht** van elk topic wordt gebruikt als model voor het sjabloon.
+
+ Elke gebruiker met toegang tot deze categorie mag sjablonen gebruiken.
diff --git a/plugins/discourse-templates/config/locales/server.pl_PL.yml b/plugins/discourse-templates/config/locales/server.pl_PL.yml
new file mode 100644
index 00000000000..5c421e67c8c
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/server.pl_PL.yml
@@ -0,0 +1,23 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+pl_PL:
+ site_settings:
+ discourse_templates_enabled: "Zezwól użytkownikom z dostępem do wyświetlania w kategorii określonej poniżej na korzystanie z dostępnych szablonów"
+ discourse_templates_categories: "Kategorie, z których mają zostać pobrane szablony"
+ discourse_templates_enable_private_templates: "Umożliwia korzystanie z prywatnych szablonów"
+ discourse_templates_groups_allowed_private_templates: "Grupy uprawnione do korzystania z prywatnych szablonów. Członkowie personelu są zawsze dozwoleni"
+ discourse_templates_private_templates_tags: "Tagi, które identyfikują prywatną wiadomość jako prywatny szablon"
+ default_category_template:
+ name: Szablony
+ description: |
+ Ta kategoria służy do przechowywania szablonów.
+
+ Szablony umożliwiają użytkownikom przechowywanie treści do częstego użytku.
+
+ Każdy temat w tej kategorii reprezentuje inny szablon. **Pierwszy post** każdego tematu jest używany jako wzór dla szablonu.
+
+ Pamiętaj, że każdy użytkownik z dostępem w tej kategorii będzie mógł korzystać z szablonów.
diff --git a/plugins/discourse-templates/config/locales/server.pt.yml b/plugins/discourse-templates/config/locales/server.pt.yml
new file mode 100644
index 00000000000..298ba523c1d
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/server.pt.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+pt:
diff --git a/plugins/discourse-templates/config/locales/server.pt_BR.yml b/plugins/discourse-templates/config/locales/server.pt_BR.yml
new file mode 100644
index 00000000000..91c3c268884
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/server.pt_BR.yml
@@ -0,0 +1,23 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+pt_BR:
+ site_settings:
+ discourse_templates_enabled: "Permitir que usuários com acesso de visualização na categoria especificada abaixo usem os modelos disponíveis"
+ discourse_templates_categories: "Categorias para buscar os modelos"
+ discourse_templates_enable_private_templates: "Permitir o uso de modelos privados"
+ discourse_templates_groups_allowed_private_templates: "Grupos autorizados a usar modelos privados. Os membros da equipe são sempre permitidos."
+ discourse_templates_private_templates_tags: "Etiquetas que identificam uma mensagem privada como um modelo privado"
+ default_category_template:
+ name: Modelos
+ description: |
+ Esta categoria é usada para armazenar modelos.
+
+ Os modelos permitem que os usuários armazenem conteúdo para uso frequente.
+
+ Cada tópico nesta categoria representa um modelo diferente. **A primeira postagem** de cada tópico é usada como conteúdo para o modelo.
+
+ Observe que todos os usuários com acesso nesta categoria terão permissão para usar os modelos.
diff --git a/plugins/discourse-templates/config/locales/server.ro.yml b/plugins/discourse-templates/config/locales/server.ro.yml
new file mode 100644
index 00000000000..08a77f812ee
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/server.ro.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+ro:
diff --git a/plugins/discourse-templates/config/locales/server.ru.yml b/plugins/discourse-templates/config/locales/server.ru.yml
new file mode 100644
index 00000000000..83b0c1b8284
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/server.ru.yml
@@ -0,0 +1,23 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+ru:
+ site_settings:
+ discourse_templates_enabled: "Разрешить пользователям с доступом на просмотр указанной ниже категории использовать имеющиеся шаблоны"
+ discourse_templates_categories: "Категории для получения шаблонов"
+ discourse_templates_enable_private_templates: "Позволяет использовать приватные шаблоны"
+ discourse_templates_groups_allowed_private_templates: "Группам разрешается использовать приватные шаблоны. Сотрудники могут использовать их всегда."
+ discourse_templates_private_templates_tags: "Теги, указывающее, что личное сообщение — приватный шаблон"
+ default_category_template:
+ name: Шаблоны
+ description: |
+ Это категория для хранения шаблонов.
+
+ Шаблоны позволяют сохранять контент для повторного использования.
+
+ Каждая тема в категории представляет собой отдельный шаблон. **Первая запись** каждой темы используется в качестве модели для шаблона.
+
+ Внимание: использовать шаблоны могут все пользователи с доступом к этой категории.
diff --git a/plugins/discourse-templates/config/locales/server.sk.yml b/plugins/discourse-templates/config/locales/server.sk.yml
new file mode 100644
index 00000000000..6f815624081
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/server.sk.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+sk:
diff --git a/plugins/discourse-templates/config/locales/server.sl.yml b/plugins/discourse-templates/config/locales/server.sl.yml
new file mode 100644
index 00000000000..23489a48b1f
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/server.sl.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+sl:
diff --git a/plugins/discourse-templates/config/locales/server.sq.yml b/plugins/discourse-templates/config/locales/server.sq.yml
new file mode 100644
index 00000000000..7f051b7a7cf
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/server.sq.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+sq:
diff --git a/plugins/discourse-templates/config/locales/server.sr.yml b/plugins/discourse-templates/config/locales/server.sr.yml
new file mode 100644
index 00000000000..88d63d6ae1a
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/server.sr.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+sr:
diff --git a/plugins/discourse-templates/config/locales/server.sv.yml b/plugins/discourse-templates/config/locales/server.sv.yml
new file mode 100644
index 00000000000..8b18bba21fd
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/server.sv.yml
@@ -0,0 +1,23 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+sv:
+ site_settings:
+ discourse_templates_enabled: "Tillåt användare med visningsbehörighet för den kategori som anges nedan att använda tillgängliga mallar"
+ discourse_templates_categories: "Kategorier för att hämta mallarna från"
+ discourse_templates_enable_private_templates: "Möjliggör användning av privata mallar"
+ discourse_templates_groups_allowed_private_templates: "Grupper som tillåts använda privata mallar. Personal är alltid tillåtna."
+ discourse_templates_private_templates_tags: "Taggar som identifierar ett privat meddelande som en privat mall"
+ default_category_template:
+ name: Mallar
+ description: |
+ Denna kategori används för att lagra mallar.
+
+ Mallar gör det möjligt för användare att lagra innehåll för regelbunden upprepad användning.
+
+ Varje ämne i den här kategorin representerar en separat mall. **Det första inlägget** i varje ämne används som modell för mallen.
+
+ Observera att alla användare som har tillgång till den här kategorin har rätt att använda mallar.
diff --git a/plugins/discourse-templates/config/locales/server.sw.yml b/plugins/discourse-templates/config/locales/server.sw.yml
new file mode 100644
index 00000000000..0d7cdd075bf
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/server.sw.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+sw:
diff --git a/plugins/discourse-templates/config/locales/server.te.yml b/plugins/discourse-templates/config/locales/server.te.yml
new file mode 100644
index 00000000000..03967bdbb07
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/server.te.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+te:
diff --git a/plugins/discourse-templates/config/locales/server.th.yml b/plugins/discourse-templates/config/locales/server.th.yml
new file mode 100644
index 00000000000..7de85ff91c4
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/server.th.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+th:
diff --git a/plugins/discourse-templates/config/locales/server.tr_TR.yml b/plugins/discourse-templates/config/locales/server.tr_TR.yml
new file mode 100644
index 00000000000..7477a7e7d08
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/server.tr_TR.yml
@@ -0,0 +1,23 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+tr_TR:
+ site_settings:
+ discourse_templates_enabled: "Aşağıda belirtilen kategoride görüntüleme erişimine sahip kullanıcıların mevcut şablonları kullanmasına izin verin"
+ discourse_templates_categories: "Şablonların alınacağı kategoriler"
+ discourse_templates_enable_private_templates: "Özel şablonların kullanımını etkinleştirir"
+ discourse_templates_groups_allowed_private_templates: "Grupların özel şablonları kullanmasına izin verilir. Personel üyelerine her zaman izin verilir."
+ discourse_templates_private_templates_tags: "Bir özel mesajı özel şablon olarak tanımlayan etiketler"
+ default_category_template:
+ name: Şablonlar
+ description: |
+ Bu kategori şablonları saklamak için kullanılır.
+
+ Şablonlar, kullanıcıların sık tekrarlanan kullanımlar için içerik depolamasına olanak tanır.
+
+ Bu kategorideki her konu farklı bir şablonu temsil eder. Her konunun **ilk gönderisi** şablon için model olarak kullanılır.
+
+ Bu kategoriye erişimi olan her kullanıcının şablon kullanmasına izin verileceğini unutmayın.
diff --git a/plugins/discourse-templates/config/locales/server.ug.yml b/plugins/discourse-templates/config/locales/server.ug.yml
new file mode 100644
index 00000000000..a6bf0185ae2
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/server.ug.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+ug:
diff --git a/plugins/discourse-templates/config/locales/server.uk.yml b/plugins/discourse-templates/config/locales/server.uk.yml
new file mode 100644
index 00000000000..f1390545d1d
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/server.uk.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+uk:
diff --git a/plugins/discourse-templates/config/locales/server.ur.yml b/plugins/discourse-templates/config/locales/server.ur.yml
new file mode 100644
index 00000000000..b4a9c21ee2f
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/server.ur.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+ur:
diff --git a/plugins/discourse-templates/config/locales/server.vi.yml b/plugins/discourse-templates/config/locales/server.vi.yml
new file mode 100644
index 00000000000..f629dcf5329
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/server.vi.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+vi:
diff --git a/plugins/discourse-templates/config/locales/server.zh_CN.yml b/plugins/discourse-templates/config/locales/server.zh_CN.yml
new file mode 100644
index 00000000000..ca62369f237
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/server.zh_CN.yml
@@ -0,0 +1,23 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+zh_CN:
+ site_settings:
+ discourse_templates_enabled: "允许对下面指定的类别具有查看访问权限的用户使用可用模板"
+ discourse_templates_categories: "要从中获取模板的类别"
+ discourse_templates_enable_private_templates: "允许使用私有模板"
+ discourse_templates_groups_allowed_private_templates: "允许使用私有模板的群组。始终允许管理人员使用。"
+ discourse_templates_private_templates_tags: "将私有消息标识为私有模板的标签"
+ default_category_template:
+ name: 模板
+ description: |
+ 此类别用于存储模板。
+
+ 模板允许用户存储内容以便经常重复使用。
+
+ 此类别中的每个话题都代表一个不同的模板。每个话题的**第一篇帖子**用作模板的模型。
+
+ 请注意,每个具有此类别访问权限的用户都可以使用模板。
diff --git a/plugins/discourse-templates/config/locales/server.zh_TW.yml b/plugins/discourse-templates/config/locales/server.zh_TW.yml
new file mode 100644
index 00000000000..7e15fab0018
--- /dev/null
+++ b/plugins/discourse-templates/config/locales/server.zh_TW.yml
@@ -0,0 +1,7 @@
+# WARNING: Never edit this file.
+# It will be overwritten when translations are pulled from Crowdin.
+#
+# To work with us on translations, join this project:
+# https://translate.discourse.org/
+
+zh_TW:
diff --git a/plugins/discourse-templates/config/settings.yml b/plugins/discourse-templates/config/settings.yml
new file mode 100644
index 00000000000..215f3c79ff5
--- /dev/null
+++ b/plugins/discourse-templates/config/settings.yml
@@ -0,0 +1,19 @@
+discourse_templates:
+ discourse_templates_enabled:
+ default: true
+ client: true
+ discourse_templates_categories:
+ default: ""
+ type: category_list
+ discourse_templates_max_replies_fetched:
+ default: 1000
+ hidden: true
+ discourse_templates_enable_private_templates:
+ default: false
+ type: boolean
+ discourse_templates_groups_allowed_private_templates:
+ default: ""
+ type: group_list
+ discourse_templates_private_templates_tags:
+ default: ""
+ type: tag_list
diff --git a/plugins/discourse-templates/db/migrate/20220303012356_create_discourse_templates_usage_count.rb b/plugins/discourse-templates/db/migrate/20220303012356_create_discourse_templates_usage_count.rb
new file mode 100644
index 00000000000..bd82d007299
--- /dev/null
+++ b/plugins/discourse-templates/db/migrate/20220303012356_create_discourse_templates_usage_count.rb
@@ -0,0 +1,17 @@
+# frozen_string_literal: true
+
+class CreateDiscourseTemplatesUsageCount < ActiveRecord::Migration[6.1]
+ def up
+ create_table :discourse_templates_usage_count do |t|
+ t.integer :topic_id, null: false
+ t.integer :usage_count, null: false, default: 0
+
+ t.timestamps
+ end
+ add_index :discourse_templates_usage_count, :topic_id, unique: true
+ end
+
+ def down
+ raise ActiveRecord::IrreversibleMigration
+ end
+end
diff --git a/plugins/discourse-templates/db/migrate/20220714022309_rename_category_setting.rb b/plugins/discourse-templates/db/migrate/20220714022309_rename_category_setting.rb
new file mode 100644
index 00000000000..48768320284
--- /dev/null
+++ b/plugins/discourse-templates/db/migrate/20220714022309_rename_category_setting.rb
@@ -0,0 +1,15 @@
+# frozen_string_literal: true
+
+class RenameCategorySetting < ActiveRecord::Migration[6.1]
+ def up
+ execute <<~SQL
+ UPDATE site_settings
+ SET name = 'discourse_templates_categories'
+ WHERE name = 'discourse_templates_category'
+ SQL
+ end
+
+ def down
+ raise ActiveRecord::IrreversibleMigration
+ end
+end
diff --git a/plugins/discourse-templates/lib/discourse_templates/guardian_extension.rb b/plugins/discourse-templates/lib/discourse_templates/guardian_extension.rb
new file mode 100644
index 00000000000..77f8b0ee0db
--- /dev/null
+++ b/plugins/discourse-templates/lib/discourse_templates/guardian_extension.rb
@@ -0,0 +1,15 @@
+# frozen_string_literal: true
+
+module DiscourseTemplates::GuardianExtension
+ def can_use_templates?
+ user&.can_use_templates? || false
+ end
+
+ def can_use_category_templates?
+ user&.can_use_category_templates? || false
+ end
+
+ def can_use_private_templates?
+ user&.can_use_private_templates? || false
+ end
+end
diff --git a/plugins/discourse-templates/lib/discourse_templates/topic_extension.rb b/plugins/discourse-templates/lib/discourse_templates/topic_extension.rb
new file mode 100644
index 00000000000..9e3c5350848
--- /dev/null
+++ b/plugins/discourse-templates/lib/discourse_templates/topic_extension.rb
@@ -0,0 +1,47 @@
+# frozen_string_literal: true
+
+module DiscourseTemplates::TopicExtension
+ def self.prepended(base)
+ base.has_one :template_item_usage,
+ class_name: "DiscourseTemplates::UsageCount",
+ dependent: :destroy
+ end
+
+ def template_item_usage_count
+ self.template_item_usage&.usage_count.to_i
+ end
+
+ def increment_template_item_usage_count!
+ DB.exec(<<~SQL, topic_id: self.id)
+ INSERT INTO discourse_templates_usage_count AS uc
+ (topic_id, usage_count, created_at, updated_at)
+ VALUES
+ (:topic_id, 1, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
+ ON CONFLICT (topic_id) DO UPDATE SET
+ usage_count = uc.usage_count + 1,
+ updated_at = CURRENT_TIMESTAMP
+ WHERE uc.topic_id = :topic_id
+ SQL
+ end
+
+ def template?(user)
+ parent_categories_ids = SiteSetting.discourse_templates_categories&.split("|")&.map(&:to_i)
+
+ all_templates_categories_ids =
+ parent_categories_ids.flat_map { |category_id| Category.subcategory_ids(category_id) }
+
+ # it is template if the topic belongs to any of the template categories
+ return true if all_templates_categories_ids.include?(self.category_id)
+
+ unless SiteSetting.tagging_enabled && SiteSetting.discourse_templates_enable_private_templates
+ return false
+ end
+
+ # or is a private message where the user is the author and at least one tag
+ # matches with the tags configured in the plugin for private templates
+ private_template_tags = SiteSetting.discourse_templates_private_templates_tags&.split("|")
+
+ archetype == Archetype.private_message && user_id == user&.id &&
+ (tags.map(&:name) & private_template_tags).any?
+ end
+end
diff --git a/plugins/discourse-templates/lib/discourse_templates/topic_query_extension.rb b/plugins/discourse-templates/lib/discourse_templates/topic_query_extension.rb
new file mode 100644
index 00000000000..f0b1e14a025
--- /dev/null
+++ b/plugins/discourse-templates/lib/discourse_templates/topic_query_extension.rb
@@ -0,0 +1,46 @@
+# frozen_string_literal: true
+
+module DiscourseTemplates::TopicQueryExtension
+ def list_category_templates
+ return unless @guardian.can_use_category_templates?
+
+ parent_categories = SiteSetting.discourse_templates_categories&.split("|")&.map(&:to_i)
+ all_templates_categories =
+ parent_categories.flat_map { |category_id| Category.subcategory_ids(category_id) }
+
+ list =
+ default_results(options.reverse_merge(unordered: true, no_definitions: true))
+ .references(:category)
+ .includes(:first_post)
+ .includes(:template_item_usage)
+ .where(
+ "topics.category_id IN (?)",
+ all_templates_categories,
+ ) # filter only topics in the configured categories and subs
+ .where(visible: true, archived: false) # filter out archived or unlisted topics
+ .reorder("topics.title ASC")
+
+ create_list(:templates, {}, list)
+ end
+
+ def list_private_templates
+ return unless @guardian.can_use_private_templates?
+
+ private_template_tags = SiteSetting.discourse_templates_private_templates_tags&.split("|")
+
+ list = private_messages_for(user, :user).includes(:first_post).includes(:template_item_usage)
+
+ list = not_archived(list, user)
+
+ # a private message is only considered a template if the user is the author and the message
+ # is tagged with at least one of the expected tags
+ list =
+ list
+ .where(user_id: user.id)
+ .joins(:tags)
+ .where("tags.name in (?)", private_template_tags)
+ .reorder("topics.title ASC")
+
+ create_list(:templates, {}, list)
+ end
+end
diff --git a/plugins/discourse-templates/lib/discourse_templates/user_extension.rb b/plugins/discourse-templates/lib/discourse_templates/user_extension.rb
new file mode 100644
index 00000000000..32b65c7dfbc
--- /dev/null
+++ b/plugins/discourse-templates/lib/discourse_templates/user_extension.rb
@@ -0,0 +1,40 @@
+# frozen_string_literal: true
+
+module DiscourseTemplates::UserExtension
+ def can_use_templates?
+ can_use_category_templates? || can_use_private_templates?
+ end
+
+ def can_use_category_templates?
+ return false if SiteSetting.discourse_templates_categories.blank?
+
+ parent_categories_ids = SiteSetting.discourse_templates_categories&.split("|")&.map(&:to_i)
+
+ parent_categories_ids.any? do |category_id|
+ return false if category_id == 0
+
+ category = Category.find_by(id: category_id)
+ return false if category.blank?
+
+ # the user can use templates if can see topics in at least one of the source categories
+ guardian.can_see?(category)
+ end
+ end
+
+ def can_use_private_templates?
+ return false unless SiteSetting.discourse_templates_enable_private_templates
+ return false unless SiteSetting.tagging_enabled
+ return false if SiteSetting.discourse_templates_private_templates_tags.blank?
+ return true if guardian.is_staff?
+
+ allowed_groups_ids =
+ SiteSetting.discourse_templates_groups_allowed_private_templates&.split("|")&.map(&:to_i)
+
+ allowed_groups_ids.any? do |group_id|
+ return true if group_id == Group::AUTO_GROUPS[:everyone]
+
+ # the user can use templates if belongs to at least one of the allowed groups
+ GroupUser.exists?(group_id: group_id, user_id: self.id)
+ end
+ end
+end
diff --git a/plugins/discourse-templates/lib/tasks/discourse-templates.rake b/plugins/discourse-templates/lib/tasks/discourse-templates.rake
new file mode 100644
index 00000000000..5c1f7c96adb
--- /dev/null
+++ b/plugins/discourse-templates/lib/tasks/discourse-templates.rake
@@ -0,0 +1,207 @@
+# frozen_string_literal: true
+
+desc "Migrate data from discourse-canned-replies to discourse-templates"
+task "discourse-templates:migrate-from-canned-replies" => :environment do
+ ENV["RAILS_DB"] ? migrate_data : migrate_data_all_sites
+end
+
+desc "Purge old data from canned replies"
+task "discourse-templates:purge-old-canned-replies-data" => :environment do
+ ENV["RAILS_DB"] ? purge_old_data : purge_old_data_all_sites
+end
+
+def create_category
+ old_settings_canned_replies_groups =
+ SiteSetting.find_by(name: "canned_replies_groups")&.value || ""
+ old_settings_canned_replies_everyone_enabled =
+ SiteSetting.find_by(name: "canned_replies_everyone_enabled")&.value&.starts_with?("t") || false
+ old_settings_canned_replies_everyone_can_edit =
+ SiteSetting.find_by(name: "canned_replies_everyone_can_edit")&.value&.starts_with?("t") || false
+
+ category = nil
+
+ I18n.with_locale(SiteSetting.default_locale) do
+ category =
+ Category.new(
+ name: I18n.t("default_category_template.name")[0...50], # category names are limited to 50 chars in discourse
+ description: I18n.t("default_category_template.description"),
+ user: Discourse.system_user,
+ all_topics_wiki: true,
+ )
+ end
+
+ permissions = { staff: :full } # staff is always allowed to use and edit canned replies
+
+ # get the existing groups and compares with the groups allowed to used canned replies
+ # using the same algorithm that the plugin used to ensure that the same groups are authorized
+ # if they are available
+ groups = Group.all
+
+ granted_group_list = old_settings_canned_replies_groups.split("|").map(&:downcase)
+
+ groups
+ .select { |group| granted_group_list.include?(group.name.downcase) }
+ .each { |group| permissions.merge!({ group.name => :full }) }
+
+ # insert privileges (or not) for everyone to use and edit canned replies
+ # based on the two settings available
+ if old_settings_canned_replies_everyone_enabled
+ permissions.merge!(
+ { everyone: old_settings_canned_replies_everyone_can_edit ? :full : :readonly },
+ )
+ end
+
+ category.set_permissions(permissions)
+
+ raise <<~ERROR unless category.save!
+ ****************************
+ ERROR while creating the existing_category to store the templates: #{category.errors.full_messages}
+
+ If you can't fix the reason of the error, you can create a existing_category manually
+ to store the templates and define it in Settings.discourse_templates_categories.
+
+ Then proceed with this migration.
+ ERROR
+
+ puts "Created category #{category.name}(id: #{category.id}) to store the templates"
+
+ category
+end
+
+def create_topic_from_v1_reply(reply, category)
+ topic = Topic.new(title: reply[:title], user: Discourse.system_user, category_id: category.id)
+ topic.custom_fields = { DiscourseTemplates::PLUGIN_NAME => reply[:id] }
+ topic.skip_callbacks = true
+
+ unless topic.save!(validate: false)
+ raise "ERROR importing #{reply[:id]}: #{reply[:title]} - #{errors.full_messages}"
+ end
+
+ post = topic.posts.build(raw: reply[:content], user: Discourse.system_user, wiki: true)
+ unless post.save!(validate: false)
+ raise "ERROR importing #{reply[:id]}: #{reply[:title]} - #{errors.full_messages}"
+ end
+
+ usage_count =
+ DiscourseTemplates::UsageCount.new(topic_id: topic.id, usage_count: reply[:usages] || 0)
+ usage_count.save
+
+ topic
+end
+
+def migrate_data_all_sites
+ RailsMultisite::ConnectionManagement.each_connection do |db|
+ puts "Starting DB: #{db} >>>>>>>>>>>>>>>>>>>>>>>>>"
+ migrate_data
+ puts "Ended DB: #{db} >>>>>>>>>>>>>>>>>>>>>>>>>"
+ end
+end
+
+def migrate_data
+ puts "Migrating data from discourse-canned-replies to discourse-templates"
+
+ begin
+ ActiveRecord::Base.transaction do
+ category =
+ if SiteSetting.discourse_templates_categories.blank?
+ new_category = create_category
+ SiteSetting.discourse_templates_categories = new_category.id.to_s
+
+ new_category
+ else
+ existing_category =
+ Category.find_by(id: SiteSetting.discourse_templates_categories&.split("|")&.first.to_i)
+
+ if existing_category.blank?
+ raise "Category specified not found. Check Settings.discourse_templates_categories"
+ end
+
+ puts "",
+ "****************************",
+ "Using existing category #{existing_category.name}(id: #{existing_category.id}) defined in Settings.discourse_templates_categories",
+ "Please note that access to templates will follow this existing category security settings",
+ "****************************",
+ ""
+
+ existing_category
+ end
+
+ canned_replies_plugin_name = "discourse-canned-replies"
+ canned_replies_store_name = "replies"
+ replies_v1 = PluginStore.get(canned_replies_plugin_name, canned_replies_store_name)
+
+ count = replies_v1&.size || 0
+ puts "no canned replies from v1 were located to be migrated to v2" if count == 0
+
+ # duplicate topic titles must be temporarily enabled to ensure that all
+ # canned replies can be imported since there is no guarantee that a previous
+ # topic does not exist with the same title
+ allow_duplicate_topic_titles = SiteSetting.allow_duplicate_topic_titles
+
+ SiteSetting.allow_duplicate_topic_titles = true
+
+ (replies_v1 || {}).each_with_index do |(_, reply), index|
+ position = index + 1
+
+ # search if a previous topic was already imported from this canned reply
+ existing_topic =
+ TopicCustomField.find_by(name: DiscourseTemplates::PLUGIN_NAME, value: reply[:id])
+
+ if existing_topic.blank?
+ topic = create_topic_from_v1_reply(reply, category)
+
+ puts "[#{position}/#{count}] canned reply #{reply[:id]}: #{reply[:title]} imported to topic #{topic.id}"
+ else
+ puts "[#{position}/#{count}] skipping #{reply[:title]}. Topic previously imported found!"
+ end
+ end
+
+ # restores the setting to the previous value after importing the topics
+ SiteSetting.allow_duplicate_topic_titles = allow_duplicate_topic_titles
+ end
+ puts "", "Canned replies migration to templates finished!"
+ rescue StandardError => e
+ puts e
+ puts "Transaction aborted! All changes were rolled back!"
+ end
+end
+
+def purge_old_data_all_sites
+ RailsMultisite::ConnectionManagement.each_connection do |db|
+ puts "Starting DB: #{db} >>>>>>>>>>>>>>>>>>>>>>>>>"
+ purge_old_data
+ puts "Ended DB: #{db} >>>>>>>>>>>>>>>>>>>>>>>>>"
+ end
+end
+
+def purge_old_data
+ puts "Removing canned replies data"
+
+ begin
+ ActiveRecord::Base.transaction do
+ DB.exec <<~SQL
+ DELETE FROM site_settings#{" "}
+ WHERE name IN (
+ 'canned_replies_groups',#{" "}
+ 'canned_replies_everyone_enabled',#{" "}
+ 'canned_replies_everyone_can_edit'
+ )
+ SQL
+
+ canned_replies_plugin_name = "discourse-canned-replies"
+ canned_replies_store_name = "replies"
+ old_replies =
+ PluginStoreRow.find_by(
+ plugin_name: canned_replies_plugin_name,
+ key: canned_replies_store_name,
+ )
+
+ old_replies.destroy! if old_replies.present?
+
+ puts "Finished!"
+ rescue StandardError => e
+ puts e
+ puts "Transaction aborted! All changes were rolled back!"
+ end
+ end
+end
diff --git a/plugins/discourse-templates/plugin.rb b/plugins/discourse-templates/plugin.rb
new file mode 100644
index 00000000000..51873be4183
--- /dev/null
+++ b/plugins/discourse-templates/plugin.rb
@@ -0,0 +1,58 @@
+# frozen_string_literal: true
+
+# name: discourse-templates
+# about: Allows the creation of content templates for repeated use.
+# meta_topic_id: 229250
+# version: 2.5.0
+# authors: Discourse (discourse-templates), Jay Pfaffman and André Pereira (canned-replies)
+# url: https://github.com/discourse/discourse/tree/main/plugins/discourse-templates
+
+enabled_site_setting :discourse_templates_enabled
+
+register_asset "stylesheets/discourse-templates.scss"
+
+register_svg_icon "far-clipboard" if respond_to?(:register_svg_icon)
+
+after_initialize do
+ module ::DiscourseTemplates
+ PLUGIN_NAME = "discourse-templates".freeze
+
+ class Engine < ::Rails::Engine
+ engine_name DiscourseTemplates::PLUGIN_NAME
+ isolate_namespace DiscourseTemplates
+ end
+ end
+
+ require_relative "app/controllers/discourse_templates/templates_controller"
+ require_relative "app/models/discourse_templates/usage_count"
+ require_relative "app/serializers/discourse_templates/templates_serializer"
+ require_relative "lib/discourse_templates/guardian_extension"
+ require_relative "lib/discourse_templates/topic_extension"
+ require_relative "lib/discourse_templates/topic_query_extension"
+ require_relative "lib/discourse_templates/user_extension"
+
+ reloadable_patch do |plugin|
+ Guardian.prepend(DiscourseTemplates::GuardianExtension)
+ Topic.prepend(DiscourseTemplates::TopicExtension)
+ TopicQuery.prepend(DiscourseTemplates::TopicQueryExtension)
+ User.prepend(DiscourseTemplates::UserExtension)
+ end
+
+ add_to_serializer(:current_user, :can_use_templates) { object.can_use_templates? }
+
+ add_to_serializer(
+ :topic_view,
+ :is_template,
+ include_condition: -> { object.topic.template?(scope.user) },
+ ) { true }
+
+ Discourse::Application.routes.append do
+ mount ::DiscourseTemplates::Engine, at: "/discourse_templates"
+ end
+
+ DiscourseTemplates::Engine.routes.draw do
+ resources :templates, path: "/", only: [:index] do
+ member { post "use" }
+ end
+ end
+end
diff --git a/plugins/discourse-templates/spec/fabricators/templates_fabricator.rb b/plugins/discourse-templates/spec/fabricators/templates_fabricator.rb
new file mode 100644
index 00000000000..15db1801613
--- /dev/null
+++ b/plugins/discourse-templates/spec/fabricators/templates_fabricator.rb
@@ -0,0 +1,41 @@
+# frozen_string_literal: true
+
+Fabricator(:template_item, from: :topic) do
+ transient :content
+
+ title { sequence(:title) { |i| "This is a test template #{i.to_s.rjust(6, "0")}" } }
+
+ after_create do |topic, transients|
+ Fabricate(:post, topic: topic) do
+ raw do
+ if transients[:content]
+ transients[:content]
+ else
+ sequence(:title) do |i|
+ "This is the content of an awesome template #{i.to_s.rjust(6, "0")}"
+ end
+ end
+ end
+ end
+ end
+end
+
+Fabricator(:private_template_item, from: :private_message_topic) do
+ transient :content
+
+ title { sequence(:title) { |i| "This is a private test template #{i.to_s.rjust(6, "0")}" } }
+
+ after_create do |topic, transients|
+ Fabricate(:post, topic: topic) do
+ raw do
+ if transients[:content]
+ transients[:content]
+ else
+ sequence(:title) do |i|
+ "This is the content of an awesome private template #{i.to_s.rjust(6, "0")}"
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-templates/spec/helpers/topics_helper.rb b/plugins/discourse-templates/spec/helpers/topics_helper.rb
new file mode 100644
index 00000000000..bf0e7ef76ba
--- /dev/null
+++ b/plugins/discourse-templates/spec/helpers/topics_helper.rb
@@ -0,0 +1,12 @@
+# frozen_string_literal: true
+
+module DiscourseTemplates::TopicsHelper
+ def serialize_topics(topics)
+ JSON.parse(
+ ActiveModel::ArraySerializer.new(
+ topics,
+ each_serializer: DiscourseTemplates::TemplatesSerializer,
+ ).to_json,
+ )
+ end
+end
diff --git a/plugins/discourse-templates/spec/lib/guardian_extension_spec.rb b/plugins/discourse-templates/spec/lib/guardian_extension_spec.rb
new file mode 100644
index 00000000000..78fe123eafc
--- /dev/null
+++ b/plugins/discourse-templates/spec/lib/guardian_extension_spec.rb
@@ -0,0 +1,149 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+
+describe DiscourseTemplates::GuardianExtension do
+ fab!(:moderator) do
+ moderator = Fabricate(:moderator)
+ Group.refresh_automatic_groups!(:moderators)
+ moderator
+ end
+ fab!(:user)
+ fab!(:other_user) { Fabricate(:user) }
+ fab!(:group) do
+ group = Fabricate(:group)
+ Fabricate(:group_user, group: group, user: user)
+ group
+ end
+ fab!(:other_group) do
+ group = Fabricate(:group)
+ Fabricate(:group_user, group: group, user: other_user)
+ group
+ end
+ fab!(:discourse_templates_category) { Fabricate(:category_with_definition) }
+ fab!(:templates_private_category) do
+ Fabricate(:private_category_with_definition, group: Group[:moderators])
+ end
+ fab!(:templates_private_category2) do
+ Fabricate(:private_category_with_definition, group: Group[:admins])
+ end
+
+ describe "can_use_templates?" do
+ let!(:guardian) { Guardian.new(user) }
+
+ before do
+ SiteSetting.discourse_templates_categories = discourse_templates_category.id.to_s
+ SiteSetting.tagging_enabled = true
+ SiteSetting.discourse_templates_enable_private_templates = true
+ SiteSetting.discourse_templates_groups_allowed_private_templates =
+ "#{group.id}|#{other_group.id}"
+ SiteSetting.discourse_templates_private_templates_tags = "templates"
+ end
+
+ it "returns true only when both can_use_category_templates? and can_use_private_templates? are true" do
+ expect(guardian.can_use_category_templates?).to eq(true)
+ expect(guardian.can_use_private_templates?).to eq(true)
+ expect(guardian.can_use_templates?).to eq(true)
+ end
+
+ it "returns true only when only can_use_category_templates? is true" do
+ SiteSetting.discourse_templates_enable_private_templates = false
+
+ expect(guardian.can_use_category_templates?).to eq(true)
+ expect(guardian.can_use_private_templates?).to eq(false)
+ expect(guardian.can_use_templates?).to eq(true)
+ end
+
+ it "returns true only when only can_use_private_templates? is true" do
+ SiteSetting.discourse_templates_categories = ""
+
+ expect(guardian.can_use_category_templates?).to eq(false)
+ expect(guardian.can_use_private_templates?).to eq(true)
+ expect(guardian.can_use_templates?).to eq(true)
+ end
+
+ it "returns false only when both can_use_category_templates? and can_use_private_templates? are false" do
+ SiteSetting.discourse_templates_enable_private_templates = false
+ SiteSetting.discourse_templates_categories = ""
+
+ expect(guardian.can_use_category_templates?).to eq(false)
+ expect(guardian.can_use_private_templates?).to eq(false)
+ expect(guardian.can_use_templates?).to eq(false)
+ end
+ end
+
+ describe "can_use_category_templates??" do
+ it "is false for anonymous users" do
+ expect(Guardian.new.can_use_category_templates?).to eq(false)
+ end
+
+ context "when only one parent categories is specified" do
+ it "is true when user can access category" do
+ SiteSetting.discourse_templates_categories = discourse_templates_category.id.to_s
+ expect(Guardian.new(moderator).can_use_category_templates?).to eq(true)
+ expect(Guardian.new(user).can_use_category_templates?).to eq(true)
+
+ SiteSetting.discourse_templates_categories = templates_private_category.id.to_s
+ expect(Guardian.new(moderator).can_use_category_templates?).to eq(true)
+ end
+
+ it "is false when user can't access category" do
+ SiteSetting.discourse_templates_categories = templates_private_category.id.to_s
+ expect(Guardian.new(user).can_use_category_templates?).to eq(false)
+ end
+ end
+
+ context "when multiple parent categories are specified" do
+ it "is true when user can access at least one category" do
+ SiteSetting.discourse_templates_categories = [
+ templates_private_category,
+ templates_private_category2,
+ ].map(&:id).join("|")
+ expect(Guardian.new(moderator).can_use_category_templates?).to eq(true)
+ end
+
+ it "is false when user can't access any category" do
+ SiteSetting.discourse_templates_categories = [
+ templates_private_category,
+ templates_private_category2,
+ ].map(&:id).join("|")
+ expect(Guardian.new(user).can_use_category_templates?).to eq(false)
+ end
+ end
+ end
+
+ describe "can_use_private_templates?" do
+ before do
+ SiteSetting.tagging_enabled = true
+ SiteSetting.discourse_templates_enable_private_templates = true
+ SiteSetting.discourse_templates_groups_allowed_private_templates = ""
+ SiteSetting.discourse_templates_private_templates_tags = "private-templates|templates"
+ end
+
+ it "is false for anonymous users" do
+ expect(Guardian.new.can_use_private_templates?).to eq(false)
+ end
+
+ it "is true for staff" do
+ expect(Guardian.new(moderator).can_use_private_templates?).to eq(true)
+ expect(Guardian.new(user).can_use_private_templates?).to eq(false)
+ end
+
+ it "only returns true to staff or members of the allowed groups" do
+ expect(Guardian.new(moderator).can_use_private_templates?).to eq(true)
+
+ SiteSetting.discourse_templates_groups_allowed_private_templates = group.id.to_s
+ expect(Guardian.new(user).can_use_private_templates?).to eq(true)
+ expect(Guardian.new(other_user).can_use_private_templates?).to eq(false)
+
+ SiteSetting.discourse_templates_groups_allowed_private_templates = other_group.id.to_s
+ expect(Guardian.new(user).can_use_private_templates?).to eq(false)
+ expect(Guardian.new(other_user).can_use_private_templates?).to eq(true)
+
+ SiteSetting.discourse_templates_groups_allowed_private_templates =
+ "#{group.id}|#{other_group.id}"
+ expect(Guardian.new(user).can_use_private_templates?).to eq(true)
+ expect(Guardian.new(other_user).can_use_private_templates?).to eq(true)
+ end
+ end
+end
diff --git a/plugins/discourse-templates/spec/lib/topic_extension_spec.rb b/plugins/discourse-templates/spec/lib/topic_extension_spec.rb
new file mode 100644
index 00000000000..6da032acdda
--- /dev/null
+++ b/plugins/discourse-templates/spec/lib/topic_extension_spec.rb
@@ -0,0 +1,144 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+
+describe DiscourseTemplates::TopicExtension do
+ fab!(:topic)
+
+ describe Topic, type: :model do
+ it { is_expected.to have_one :template_item_usage }
+ end
+
+ describe "template_item_usage_count" do
+ it "retrieves usage count as expected" do
+ expect(topic.template_item_usage_count).to eq(0)
+ end
+ end
+
+ describe "increment_template_item_usage_count!" do
+ it "increments usage count as expected" do
+ expect(topic.template_item_usage_count).to eq(0)
+
+ topic.increment_template_item_usage_count!
+ topic.reload
+
+ expect(topic.template_item_usage_count).to eq(1)
+
+ topic.increment_template_item_usage_count!
+ topic.reload
+
+ expect(topic.template_item_usage_count).to eq(2)
+
+ topic.increment_template_item_usage_count!
+ topic.reload
+
+ expect(topic.template_item_usage_count).to eq(3)
+ end
+ end
+
+ describe "template?" do
+ fab!(:user)
+
+ context "with normal topics" do
+ fab!(:templates_category) { Fabricate(:category_with_definition) }
+ fab!(:template) { Fabricate(:template_item, category: templates_category) }
+ fab!(:templates_subcategory) do
+ Fabricate(:category_with_definition, parent_category: templates_category)
+ end
+ fab!(:template_on_sub) { Fabricate(:template_item, category: templates_category) }
+ fab!(:other_category) { Fabricate(:category_with_definition) }
+ fab!(:other_topic) { Fabricate(:topic, category: other_category) }
+
+ before { SiteSetting.discourse_templates_categories = templates_category.id.to_s }
+
+ it "returns true when topic belongs to one of the assigned categories" do
+ SiteSetting.discourse_templates_categories = "#{templates_category.id}|#{other_category.id}"
+ expect(template.template?(user)).to eq(true)
+ expect(other_topic.template?(user)).to eq(true)
+ end
+
+ it "returns true when topic belongs to a sub-category of one of the assigned categories" do
+ expect(template_on_sub.template?(user)).to eq(true)
+ end
+
+ it "returns false when topic does not belong to one of the assigned categories" do
+ expect(other_topic.template?(user)).to eq(false)
+ end
+ end
+
+ describe "private messages" do
+ fab!(:other_user) { Fabricate(:user) }
+
+ fab!(:tag_a) { Fabricate(:tag, name: "tag-a") }
+ fab!(:tag_b) { Fabricate(:tag, name: "tag-b") }
+ fab!(:private_template_tag_a) { Fabricate(:private_template_item, user: user, tags: [tag_a]) }
+ fab!(:private_template_tag_b) { Fabricate(:private_template_item, user: user, tags: [tag_b]) }
+
+ before do
+ SiteSetting.tagging_enabled = true
+ SiteSetting.discourse_templates_enable_private_templates = true
+ SiteSetting.discourse_templates_private_templates_tags = "tag-a|tag-b"
+ end
+
+ it "returns false unless SiteSetting.tagging_enabled" do
+ expect(private_template_tag_a.template?(user)).to eq(true)
+
+ SiteSetting.tagging_enabled = false
+ expect(private_template_tag_a.template?(user)).to eq(false)
+ end
+
+ it "returns false unless SiteSetting.discourse_templates_enable_private_templates" do
+ expect(private_template_tag_a.template?(user)).to eq(true)
+
+ SiteSetting.tagging_enabled = false
+ expect(private_template_tag_a.template?(user)).to eq(false)
+ end
+
+ it "returns false when user is not the author of the private message" do
+ expect(private_template_tag_a.template?(other_user)).to eq(false)
+ end
+
+ it "returns true only when the private message is tagged with at least one the allowed tags" do
+ expect(private_template_tag_a.template?(user)).to eq(true)
+ expect(private_template_tag_b.template?(user)).to eq(true)
+
+ SiteSetting.discourse_templates_private_templates_tags = "tag-a"
+ expect(private_template_tag_a.template?(user)).to eq(true)
+ expect(private_template_tag_b.template?(user)).to eq(false)
+
+ SiteSetting.discourse_templates_private_templates_tags = "tag-b"
+ expect(private_template_tag_a.template?(user)).to eq(false)
+ expect(private_template_tag_b.template?(user)).to eq(true)
+ end
+ end
+
+ it "won't leak state into the Category.subcategory_ids cache" do
+ category = Fabricate(:category_with_definition)
+ subcategory = Fabricate(:category_with_definition, parent_category: category)
+ topic = Fabricate(:template_item, category: subcategory)
+ SiteSetting.discourse_templates_categories = category.id.to_s
+
+ # assert that the return of Category.subcategory_ids is what we expect before
+ # calling template? on the topic
+ expect(Category.subcategory_ids(category.id).size).to eq(2)
+ expect(Category.subcategory_ids(category.id)).to contain_exactly(category.id, subcategory.id)
+
+ expect(topic.template?(user)).to eq(true)
+
+ # the return of Category.subcategory_ids is what was not changed by the call to template?
+ expect(Category.subcategory_ids(category.id).size).to eq(2)
+ expect(Category.subcategory_ids(category.id)).to contain_exactly(category.id, subcategory.id)
+
+ # Now we'll change the category of the topic to a category that is not a template category
+ topic.update!(category: Fabricate(:category))
+
+ # The cache should be invalidated and the topic should no longer be considered a template
+ expect(topic.template?(user)).to eq(false)
+
+ # the return of Category.subcategory_ids is also not changed by the call to template? in a topic
+ # that is not a template
+ expect(Category.subcategory_ids(category.id).size).to eq(2)
+ expect(Category.subcategory_ids(category.id)).to contain_exactly(category.id, subcategory.id)
+ end
+ end
+end
diff --git a/plugins/discourse-templates/spec/lib/topic_query_extension_spec.rb b/plugins/discourse-templates/spec/lib/topic_query_extension_spec.rb
new file mode 100644
index 00000000000..c28ec55f6f7
--- /dev/null
+++ b/plugins/discourse-templates/spec/lib/topic_query_extension_spec.rb
@@ -0,0 +1,195 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+require_relative "../helpers/topics_helper"
+
+RSpec.configure { |c| c.include DiscourseTemplates::TopicsHelper }
+
+describe DiscourseTemplates::TopicQueryExtension do
+ fab!(:user)
+ let!(:topic_query) do
+ TopicQuery.new(user, per_page: SiteSetting.discourse_templates_max_replies_fetched.to_i)
+ end
+
+ describe "list_category_templates" do
+ fab!(:other_category) { Fabricate(:category_with_definition) }
+ fab!(:other_topics) { Fabricate.times(5, :topic, category: other_category) }
+ fab!(:discourse_templates_category) { Fabricate(:category_with_definition) }
+ fab!(:templates) do
+ Fabricate.times(100, :template_item, category: discourse_templates_category)
+ end
+
+ before { SiteSetting.discourse_templates_categories = discourse_templates_category.id.to_s }
+
+ let!(:topic_query) do
+ TopicQuery.new(user, per_page: SiteSetting.discourse_templates_max_replies_fetched.to_i)
+ end
+
+ it "returns nil when user can't use category templates" do
+ SiteSetting.discourse_templates_categories = ""
+ expect(topic_query.list_category_templates).to be_nil
+ end
+
+ it "retrieves all topics in the category" do
+ topics = topic_query.list_category_templates.topics
+ expect(topics.size).to eq(templates.size)
+ end
+
+ it "retrieves topics from multiple parent_categories" do
+ SiteSetting.discourse_templates_categories = [
+ discourse_templates_category,
+ other_category,
+ ].map(&:id).join("|")
+
+ topics = topic_query.list_category_templates.topics
+ expect(topics.size).to eq(templates.size + other_topics.size)
+ end
+
+ it "filter out the category description topic" do
+ expect(discourse_templates_category.topic_id).not_to eq(nil)
+
+ topics = topic_query.list_category_templates.topics
+ topics_without_category_description =
+ topics.filter { |topic| topic.id != discourse_templates_category.topic_id }
+
+ expect(topics.size).to eq(topics_without_category_description.size)
+ end
+
+ it "retrieves closed topics" do
+ topics = topic_query.list_category_templates.topics
+ expect(topics.size).to eq(templates.size)
+
+ closed_replies = templates.sample(templates.size * 0.2)
+ closed_replies.each { |template| template.update_status("closed", true, user) }
+
+ topics = topic_query.list_category_templates.topics
+ expect(topics.size).to eq(templates.size)
+ end
+
+ it "filter out unlisted topics" do
+ topics = topic_query.list_category_templates.topics
+ expect(topics.size).to eq(templates.size)
+
+ unlisted_replies = templates.sample(templates.size * 0.15)
+ unlisted_replies.each { |template| template.update_status("visible", false, user) }
+
+ topics = topic_query.list_category_templates.topics
+ expect(topics.size).to eq(templates.size - unlisted_replies.size)
+ end
+
+ it "filter out archived topics" do
+ topics = topic_query.list_category_templates.topics
+ expect(topics.size).to eq(templates.size)
+
+ archived_replies = templates.sample(templates.size * 0.25)
+ archived_replies.each { |template| template.update_attribute :archived, true }
+
+ topics = topic_query.list_category_templates.topics
+ expect(topics.size).to eq(templates.size - archived_replies.size)
+ end
+
+ it "filter out deleted topics" do
+ topics = topic_query.list_category_templates.topics
+ expect(topics.size).to eq(templates.size)
+
+ deleted_replies = templates.sample(templates.size * 0.2)
+ deleted_replies.each { |template| template.trash! }
+
+ topics = topic_query.list_category_templates.topics
+ expect(topics.size).to eq(templates.size - deleted_replies.size)
+ end
+
+ it "sorts retrieved replies by title" do
+ sorted_replies = templates.sort_by(&:title)
+
+ # just to ensure the test sample isn't sorted because that would render the test after the
+ # query to be useless
+ templates.shuffle! if (templates == sorted_replies)
+
+ topics = topic_query.list_category_templates.topics
+ expect(topics).to eq(sorted_replies)
+ end
+ end
+
+ describe "list_private_templates" do
+ fab!(:user_a) { Fabricate(:user) }
+ fab!(:user_b) { Fabricate(:user) }
+ fab!(:group) do
+ group = Fabricate(:group)
+ Fabricate(:group_user, group: group, user: user)
+ group
+ end
+ fab!(:other_group) do
+ group = Fabricate(:group)
+ Fabricate(:group_user, group: group, user: user_a)
+ group
+ end
+
+ fab!(:tag_a) { Fabricate(:tag, name: "templates") }
+ fab!(:tag_b) { Fabricate(:tag, name: "private-templates") }
+ fab!(:private_templates_tag_a) do
+ Fabricate.times(25, :private_template_item, user: user, tags: [tag_a])
+ end
+ fab!(:private_templates_tag_b) do
+ Fabricate.times(18, :private_template_item, user: user, tags: [tag_b])
+ end
+ fab!(:private_messages_from_user_a) do
+ Fabricate.times(5, :private_template_item, user: user_a, recipient: user, tags: [tag_a])
+ end
+
+ before do
+ SiteSetting.tagging_enabled = true
+ SiteSetting.discourse_templates_enable_private_templates = true
+ SiteSetting.discourse_templates_groups_allowed_private_templates = group.id.to_s
+ SiteSetting.discourse_templates_private_templates_tags = "private-templates|templates"
+ end
+
+ it "returns nil when user cannot use private templates" do
+ SiteSetting.discourse_templates_enable_private_templates = false
+ expect(topic_query.list_private_templates).to be_nil
+ end
+
+ it "returns nil if user do not belong to assigned group" do
+ SiteSetting.discourse_templates_groups_allowed_private_templates = other_group.id.to_s
+ # user wasn't added to the group so shouldn't be able to use private templates
+ expect(topic_query.list_private_templates).to be_nil
+ end
+
+ it "returns empty if private messages do not belong to assigned tag" do
+ SiteSetting.discourse_templates_private_templates_tags = "some_other_tag"
+ expect(topic_query.list_private_templates.topics).to be_empty
+ end
+
+ it "retrieves all private templates in assigned tags" do
+ topics = topic_query.list_private_templates.topics
+ expect(topics.size).to eq(private_templates_tag_a.size + private_templates_tag_b.size)
+ end
+
+ it "retrieves only private messages in assigned tags as templates" do
+ topics = topic_query.list_private_templates.topics
+ expect(topics.size).to eq(private_templates_tag_a.size + private_templates_tag_b.size)
+
+ # changing the tags that mark a private message as template should change the templates recovered
+ SiteSetting.discourse_templates_private_templates_tags = "private-templates"
+
+ topics = topic_query.list_private_templates.topics
+ expect(topics.size).to eq(private_templates_tag_b.size)
+
+ SiteSetting.discourse_templates_private_templates_tags = "templates"
+
+ topics = topic_query.list_private_templates.topics
+ expect(topics.size).to eq(private_templates_tag_a.size)
+
+ # it shouldn't return any template if none of the tags match
+ SiteSetting.discourse_templates_private_templates_tags = "other_unrelated_tag"
+
+ topics = topic_query.list_private_templates.topics
+ expect(topics.size).to eq(0)
+ end
+
+ it "won't list private messages received as templates" do
+ topics = topic_query.list_private_templates.topics
+ expect(((topics.map(&:id) & private_messages_from_user_a.map(&:id)).any?)).to eq(false)
+ end
+ end
+end
diff --git a/plugins/discourse-templates/spec/lib/user_extension_spec.rb b/plugins/discourse-templates/spec/lib/user_extension_spec.rb
new file mode 100644
index 00000000000..546e42019f3
--- /dev/null
+++ b/plugins/discourse-templates/spec/lib/user_extension_spec.rb
@@ -0,0 +1,140 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+
+describe DiscourseTemplates::UserExtension do
+ fab!(:admin)
+ fab!(:moderator)
+ fab!(:user)
+
+ describe "can_use_category_templates?" do
+ fab!(:discourse_templates_category) { Fabricate(:category_with_definition) }
+ fab!(:templates_private_category) do
+ Fabricate(:private_category_with_definition, group: Group[:moderators])
+ end
+ fab!(:templates_private_category2) do
+ Fabricate(:private_category_with_definition, group: Group[:admins])
+ end
+
+ before { Group.refresh_automatic_groups!(:moderators) }
+
+ it "is false when SiteSetting.discourse_templates_categories is empty" do
+ SiteSetting.discourse_templates_categories = ""
+ expect(moderator.can_use_templates?).to eq(false)
+ expect(user.can_use_templates?).to eq(false)
+ end
+
+ context "when only one parent categories is specified" do
+ it "is false when SiteSetting.discourse_templates_categories points to category that does not exist" do
+ SiteSetting.discourse_templates_categories = "-99999"
+ expect(moderator.can_use_templates?).to eq(false)
+ expect(user.can_use_templates?).to eq(false)
+ end
+
+ it "is true when user can access category" do
+ SiteSetting.discourse_templates_categories = discourse_templates_category.id.to_s
+ expect(moderator.can_use_templates?).to eq(true)
+ expect(user.can_use_templates?).to eq(true)
+ end
+
+ it "is false when user can't access category" do
+ SiteSetting.discourse_templates_categories = templates_private_category.id.to_s
+ expect(user.can_use_templates?).to eq(false)
+ end
+ end
+
+ context "when multiples parent categories are specified" do
+ it "is false when the user cannot access any of the parent categories" do
+ SiteSetting.discourse_templates_categories = [
+ templates_private_category,
+ templates_private_category2,
+ ].map(&:id).join("|")
+ expect(user.can_use_templates?).to eq(false)
+ end
+
+ it "is true when user can access at least one of the parent categories" do
+ SiteSetting.discourse_templates_categories = [
+ templates_private_category,
+ templates_private_category2,
+ ].map(&:id).join("|")
+ expect(moderator.can_use_templates?).to eq(true)
+ end
+ end
+ end
+
+ describe "can_use_private_templates?" do
+ fab!(:other_user) { Fabricate(:user) }
+
+ fab!(:group) do
+ group = Fabricate(:group)
+ Fabricate(:group_user, group: group, user: user)
+ group
+ end
+ fab!(:other_group) do
+ group = Fabricate(:group)
+ Fabricate(:group_user, group: group, user: other_user)
+ group
+ end
+
+ before do
+ Group.refresh_automatic_groups!(:moderators)
+
+ SiteSetting.tagging_enabled = true
+ SiteSetting.discourse_templates_enable_private_templates = true
+ SiteSetting.discourse_templates_groups_allowed_private_templates = ""
+ SiteSetting.discourse_templates_private_templates_tags = "private-templates|templates"
+ end
+
+ it "is false when SiteSetting.discourse_templates_enable_private_templates is false" do
+ SiteSetting.discourse_templates_enable_private_templates = false
+ expect(moderator.can_use_private_templates?).to eq(false)
+ expect(user.can_use_private_templates?).to eq(false)
+ end
+
+ it "is false when SiteSetting.tagging_enabled is false" do
+ SiteSetting.tagging_enabled = false
+ expect(moderator.can_use_private_templates?).to eq(false)
+ expect(user.can_use_private_templates?).to eq(false)
+ end
+
+ it "is false when SiteSetting.discourse_templates_private_templates_tags is empty" do
+ SiteSetting.discourse_templates_private_templates_tags = ""
+ expect(moderator.can_use_private_templates?).to eq(false)
+ expect(user.can_use_private_templates?).to eq(false)
+ end
+
+ it "is true when settings are configured and user is staff" do
+ expect(admin.can_use_private_templates?).to eq(true)
+ expect(moderator.can_use_private_templates?).to eq(true)
+ expect(user.can_use_private_templates?).to eq(false)
+ end
+
+ it "is true when group is 'everyone'" do
+ expect(admin.can_use_private_templates?).to eq(true)
+ expect(moderator.can_use_private_templates?).to eq(true)
+ expect(user.can_use_private_templates?).to eq(false)
+
+ SiteSetting.discourse_templates_groups_allowed_private_templates =
+ Group::AUTO_GROUPS[:everyone].to_s
+ expect(user.can_use_private_templates?).to eq(true)
+ end
+
+ it "only returns true to staff or members of the allowed groups" do
+ expect(admin.can_use_private_templates?).to eq(true)
+ expect(moderator.can_use_private_templates?).to eq(true)
+
+ SiteSetting.discourse_templates_groups_allowed_private_templates = group.id.to_s
+ expect(user.can_use_private_templates?).to eq(true)
+ expect(other_user.can_use_private_templates?).to eq(false)
+
+ SiteSetting.discourse_templates_groups_allowed_private_templates = other_group.id.to_s
+ expect(user.can_use_private_templates?).to eq(false)
+ expect(other_user.can_use_private_templates?).to eq(true)
+
+ SiteSetting.discourse_templates_groups_allowed_private_templates =
+ "#{group.id}|#{other_group.id}"
+ expect(user.can_use_private_templates?).to eq(true)
+ expect(other_user.can_use_private_templates?).to eq(true)
+ end
+ end
+end
diff --git a/plugins/discourse-templates/spec/models/usage_count_spec.rb b/plugins/discourse-templates/spec/models/usage_count_spec.rb
new file mode 100644
index 00000000000..3b73368e9e5
--- /dev/null
+++ b/plugins/discourse-templates/spec/models/usage_count_spec.rb
@@ -0,0 +1,8 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+
+describe DiscourseTemplates::UsageCount do
+ it { is_expected.to belong_to :topic }
+ it { is_expected.to validate_presence_of :topic_id }
+end
diff --git a/plugins/discourse-templates/spec/plugin_helper.rb b/plugins/discourse-templates/spec/plugin_helper.rb
new file mode 100644
index 00000000000..88d33e183fe
--- /dev/null
+++ b/plugins/discourse-templates/spec/plugin_helper.rb
@@ -0,0 +1,32 @@
+# frozen_string_literal: true
+
+module DiscourseTemplatesSpecHelpers
+ # keep this list synchronized with the list in assets/javascripts/lib/replace-variables.js
+ TEMPLATES_ALLOWED_VARIABLES =
+ Set.new(
+ %w[
+ my_username
+ my_name
+ chat_channel_name
+ chat_channel_url
+ chat_thread_name
+ chat_thread_url
+ context_title
+ context_url
+ topic_title
+ topic_url
+ original_poster_username
+ original_poster_name
+ reply_to_username
+ reply_to_name
+ last_poster_username
+ reply_to_or_last_poster_username
+ ],
+ )
+
+ def templates_allowed_variables
+ TEMPLATES_ALLOWED_VARIABLES
+ end
+end
+
+RSpec.configure { |config| config.include DiscourseTemplatesSpecHelpers }
diff --git a/plugins/discourse-templates/spec/requests/templates_controller_spec.rb b/plugins/discourse-templates/spec/requests/templates_controller_spec.rb
new file mode 100644
index 00000000000..a04f30214cc
--- /dev/null
+++ b/plugins/discourse-templates/spec/requests/templates_controller_spec.rb
@@ -0,0 +1,394 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+require_relative "../helpers/topics_helper"
+
+RSpec.configure { |c| c.include DiscourseTemplates::TopicsHelper }
+
+describe DiscourseTemplates::TemplatesController do
+ fab!(:admin)
+ fab!(:moderator)
+ fab!(:user)
+ fab!(:user_in_group1) { Fabricate(:user) }
+ fab!(:user_in_group2) { Fabricate(:user) }
+ fab!(:group1) do
+ group = Fabricate(:group)
+ group.add(user_in_group1)
+ group.save
+ group
+ end
+ fab!(:group2) do
+ group = Fabricate(:group)
+ group.add(user_in_group2)
+ group.save
+ group
+ end
+ fab!(:templates_parent_category) { Fabricate(:category_with_definition) }
+ fab!(:templates_other_parent_category) { Fabricate(:category_with_definition) }
+ fab!(:templates_sub_category_moderators) do
+ Fabricate(
+ :private_category_with_definition,
+ parent_category_id: templates_parent_category.id,
+ group: Group[:moderators],
+ )
+ end
+ fab!(:templates_sub_category_group) do
+ Fabricate(
+ :private_category_with_definition,
+ parent_category_id: templates_parent_category.id,
+ group: group1,
+ )
+ end
+ fab!(:templates_sub_category_group2) do
+ Fabricate(
+ :private_category_with_definition,
+ parent_category_id: templates_parent_category.id,
+ group: group2,
+ )
+ end
+ fab!(:templates_sub_category_everyone) do
+ Fabricate(:category_with_definition, parent_category_id: templates_parent_category.id)
+ end
+ fab!(:template_item0) { Fabricate(:template_item, category: templates_parent_category) }
+ fab!(:template_item1) { Fabricate(:template_item, category: templates_parent_category) }
+ fab!(:template_item2) { Fabricate(:template_item, category: templates_parent_category) }
+ fab!(:template_item3) { Fabricate(:template_item, category: templates_sub_category_moderators) }
+ fab!(:template_item4) { Fabricate(:template_item, category: templates_sub_category_group) }
+ fab!(:template_item5) { Fabricate(:template_item, category: templates_sub_category_group2) }
+ fab!(:template_item6) { Fabricate(:template_item, category: templates_sub_category_everyone) }
+ fab!(:template_item7) { Fabricate(:template_item, category: templates_sub_category_everyone) }
+ fab!(:template_item_from_other_parent) do
+ Fabricate(:template_item, category: templates_other_parent_category)
+ end
+ fab!(:other_topic1) { Fabricate(:template_item) } # uncategorized
+ fab!(:other_topic2) { Fabricate(:template_item) } # uncategorized
+ fab!(:other_topic3) { Fabricate(:template_item) } # uncategorized
+ fab!(:tag) do
+ Fabricate(
+ :tag,
+ topics: [template_item4],
+ categories: [templates_sub_category_moderators],
+ name: "category-tag",
+ )
+ end
+ fab!(:everyone_tag) do
+ Fabricate(
+ :tag,
+ topics: [template_item0, template_item1, template_item2, template_item6, template_item7],
+ name: "use-anywhere",
+ )
+ end
+ fab!(:group_tag) { Fabricate(:tag, topics: [template_item4, template_item5], name: "use-group") }
+
+ before { SiteSetting.discourse_templates_enabled = true }
+
+ describe "#list" do
+ context "when a regular user is logged" do
+ before { sign_in(user) }
+
+ it "should list topics in the category assigned as templates" do
+ SiteSetting.discourse_templates_categories = templates_sub_category_everyone.id.to_s
+
+ get "/discourse_templates"
+ expect(response.status).to eq(200)
+
+ parsed = response.parsed_body
+ expected_response = serialize_topics([template_item6, template_item7].sort_by(&:title))
+
+ expect(parsed["templates"]).to eq(expected_response)
+ end
+
+ it "should list topics from multiple parent categories" do
+ SiteSetting.discourse_templates_categories = [
+ templates_sub_category_everyone,
+ templates_other_parent_category,
+ ].map(&:id).join("|")
+
+ get "/discourse_templates"
+ expect(response.status).to eq(200)
+
+ parsed = response.parsed_body
+ expected_response =
+ serialize_topics(
+ [template_item6, template_item7, template_item_from_other_parent].sort_by(&:title),
+ )
+
+ expect(parsed["templates"]).to eq(expected_response)
+ end
+
+ it "should list topics in the parent category and subcategories that the user can see" do
+ SiteSetting.discourse_templates_categories = templates_parent_category.id.to_s
+
+ get "/discourse_templates"
+ expect(response.status).to eq(200)
+
+ parsed = response.parsed_body
+ expected_response =
+ serialize_topics(
+ [
+ template_item0,
+ template_item1,
+ template_item2,
+ template_item6,
+ template_item7,
+ ].sort_by(&:title),
+ )
+
+ expect(parsed["templates"]).to eq(expected_response)
+ end
+
+ it "should not be able to use templates if can't see topics in the category" do
+ SiteSetting.discourse_templates_categories = templates_sub_category_moderators.id.to_s
+
+ get "/discourse_templates"
+ expect(response.status).to eq(403)
+
+ SiteSetting.discourse_templates_categories = templates_sub_category_group.id.to_s
+
+ get "/discourse_templates"
+ expect(response.status).to eq(403)
+
+ SiteSetting.discourse_templates_categories = templates_sub_category_group2.id.to_s
+
+ get "/discourse_templates"
+ expect(response.status).to eq(403)
+ end
+ end
+
+ context "when a moderator is logged" do
+ before do
+ Group.refresh_automatic_groups!(:moderators)
+ sign_in(moderator)
+ end
+
+ it "should list topics in the parent category and subcategories that the moderator can see" do
+ SiteSetting.discourse_templates_categories = [
+ templates_parent_category,
+ templates_other_parent_category,
+ ].map(&:id).join("|")
+
+ get "/discourse_templates"
+ expect(response.status).to eq(200)
+
+ parsed = response.parsed_body
+ expected_response =
+ serialize_topics(
+ [
+ template_item0,
+ template_item1,
+ template_item2,
+ template_item3,
+ template_item6,
+ template_item7,
+ template_item_from_other_parent,
+ ].sort_by(&:title),
+ )
+
+ expect(parsed["templates"]).to eq(expected_response)
+ end
+ end
+
+ context "when an user belonging to a group is logged" do
+ it "should list topics in the parent category and subcategories that the user can see" do
+ SiteSetting.discourse_templates_categories = [
+ templates_parent_category,
+ templates_other_parent_category,
+ ].map(&:id).join("|")
+
+ sign_in(user_in_group1)
+
+ get "/discourse_templates"
+ expect(response.status).to eq(200)
+
+ parsed = response.parsed_body
+ expected_response =
+ serialize_topics(
+ [
+ template_item0,
+ template_item1,
+ template_item2,
+ template_item4,
+ template_item6,
+ template_item7,
+ template_item_from_other_parent,
+ ].sort_by(&:title),
+ )
+
+ expect(parsed["templates"]).to eq(expected_response)
+
+ sign_in(user_in_group2)
+
+ get "/discourse_templates"
+ expect(response.status).to eq(200)
+
+ parsed = response.parsed_body
+ expected_response =
+ serialize_topics(
+ [
+ template_item0,
+ template_item1,
+ template_item2,
+ template_item5,
+ template_item6,
+ template_item7,
+ template_item_from_other_parent,
+ ].sort_by(&:title),
+ )
+
+ expect(parsed["templates"]).to eq(expected_response)
+ end
+ end
+
+ context "when an admin is logged" do
+ before do
+ SiteSetting.discourse_templates_categories = [
+ templates_parent_category,
+ templates_other_parent_category,
+ ].map(&:id).join("|")
+
+ sign_in(admin)
+ Group.refresh_automatic_groups!
+ end
+
+ it "should list topics in the parent category and subcategories that the admin can see" do
+ get "/discourse_templates"
+ expect(response.status).to eq(200)
+
+ parsed = response.parsed_body
+ expected_response =
+ serialize_topics(
+ [
+ template_item0,
+ template_item1,
+ template_item2,
+ template_item3,
+ template_item4,
+ template_item5,
+ template_item6,
+ template_item7,
+ template_item_from_other_parent,
+ ].sort_by(&:title),
+ )
+
+ expect(parsed["templates"]).to eq(expected_response)
+ end
+
+ it "should not list delete, archived and unlisted topics" do
+ template_item0.trash!(admin)
+ expect(template_item0.deleted_at).not_to eq(nil)
+
+ template_item1.update_attribute :archived, true
+ expect(template_item1).to be_archived
+
+ template_item2.update_status("visible", false, admin)
+ template_item2.reload
+ expect(template_item2).not_to be_visible
+
+ get "/discourse_templates"
+ expect(response.status).to eq(200)
+
+ parsed = response.parsed_body
+ expected_response =
+ serialize_topics(
+ [
+ template_item3,
+ template_item4,
+ template_item5,
+ template_item6,
+ template_item7,
+ template_item_from_other_parent,
+ ].sort_by(&:title),
+ )
+
+ expect(parsed["templates"]).to eq(expected_response)
+ end
+ end
+
+ context "when no user is signed in" do
+ it "should return 404" do
+ SiteSetting.discourse_templates_categories = templates_sub_category_everyone.id.to_s
+
+ get "/discourse_templates"
+ expect(response.status).to eq(404)
+ end
+ end
+ end
+
+ describe "#use" do
+ describe "check if the id received belongs to a template" do
+ before do
+ SiteSetting.discourse_templates_categories = templates_parent_category.id.to_s
+
+ sign_in(admin)
+ Group.refresh_automatic_groups!
+ end
+
+ it "should return 422 when id does not belong to a valid topic" do
+ # to avoid flaky testing we create a topic and immediately destroy it to obtain
+ # an invalid topic id
+ invalid_topic_id = Fabricate(:template_item).tap(&:destroy!).id
+
+ post "/discourse_templates/#{invalid_topic_id}/use"
+ expect(response.status).to eq(422)
+ end
+
+ it "should return 422 when topic does not belong to template category or its subcategories" do
+ post "/discourse_templates/#{other_topic1.id}/use"
+ expect(response.status).to eq(422)
+ end
+
+ it "should return 200 if the topic belongs to the templates category" do
+ post "/discourse_templates/#{template_item0.id}/use"
+ expect(response.status).to eq(200)
+ end
+
+ it "should return 200 if the topic belongs to the templates subcategories" do
+ post "/discourse_templates/#{template_item3.id}/use"
+ expect(response.status).to eq(200)
+
+ post "/discourse_templates/#{template_item4.id}/use"
+ expect(response.status).to eq(200)
+
+ post "/discourse_templates/#{template_item5.id}/use"
+ expect(response.status).to eq(200)
+
+ post "/discourse_templates/#{template_item6.id}/use"
+ expect(response.status).to eq(200)
+ end
+ end
+
+ context "when a template is used" do
+ before do
+ SiteSetting.discourse_templates_categories = templates_sub_category_moderators.id.to_s
+
+ Group.refresh_automatic_groups!(:moderators)
+ sign_in(moderator)
+ end
+
+ it "should increment usage count" do
+ get "/discourse_templates"
+ expect(response.status).to eq(200)
+
+ parsed = response.parsed_body
+ expected_response = serialize_topics([template_item3])
+
+ expect(parsed["templates"]).to eq(expected_response)
+ expect(parsed["templates"][0]["usages"]).to eq(0)
+
+ post "/discourse_templates/#{template_item3.id}/use"
+ expect(response.status).to eq(200)
+
+ get "/discourse_templates"
+ expect(response.status).to eq(200)
+
+ parsed = response.parsed_body
+
+ template_item3.reload
+ expected_response = serialize_topics([template_item3])
+
+ expect(parsed["templates"]).to eq(expected_response)
+ expect(parsed["templates"][0]["usages"]).to eq(1)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-templates/spec/serializers/current_user_serializer_spec.rb b/plugins/discourse-templates/spec/serializers/current_user_serializer_spec.rb
new file mode 100644
index 00000000000..0d7fb59e597
--- /dev/null
+++ b/plugins/discourse-templates/spec/serializers/current_user_serializer_spec.rb
@@ -0,0 +1,17 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+
+describe CurrentUserSerializer, type: :serializer do
+ subject(:serializer) { described_class.new(user, scope: guardian, root: false) }
+
+ describe "CurrentUserSerializer extension" do
+ let!(:user) { Fabricate(:user) }
+ let!(:guardian) { Guardian.new(user) }
+
+ it "includes can_use_templates in serialization" do
+ json = serializer.as_json
+ expect(json).to have_key(:can_use_templates)
+ end
+ end
+end
diff --git a/plugins/discourse-templates/spec/serializers/templates_serializer_spec.rb b/plugins/discourse-templates/spec/serializers/templates_serializer_spec.rb
new file mode 100644
index 00000000000..17c124c93a3
--- /dev/null
+++ b/plugins/discourse-templates/spec/serializers/templates_serializer_spec.rb
@@ -0,0 +1,44 @@
+# frozen_string_literal: true
+
+require "rails_helper"
+require_relative "../helpers/topics_helper"
+
+RSpec.configure { |c| c.include DiscourseTemplates::TopicsHelper }
+
+describe DiscourseTemplates::TemplatesSerializer do
+ fab!(:template_item) # uncategorized
+ fab!(:tag1) { Fabricate(:tag, topics: [template_item], name: "tag1") }
+ fab!(:tag2) { Fabricate(:tag, topics: [template_item], name: "tag2") }
+
+ subject(:serializer) { described_class.new(template_item, root: false) }
+
+ context "when serializing templates" do
+ it "serializes correctly to json including tags when tagging is enabled" do
+ SiteSetting.tagging_enabled = true
+
+ json = serializer.as_json
+ expect(json).to have_key(:tags)
+
+ expect(json[:id]).to eq(template_item.id)
+ expect(json[:title]).to eq(template_item.title)
+ expect(json[:slug]).to eq(template_item.slug)
+ expect(json[:content]).to eq(template_item.first_post.raw)
+ expect(json[:tags]).to match_array(template_item.tags.map(&:name))
+ expect(json[:usages]).to eq(0)
+ end
+
+ it "serializes correctly to json excluding tags when tagging is disabled" do
+ SiteSetting.tagging_enabled = false
+
+ json = serializer.as_json
+ expect(json).to_not have_key(:tags)
+
+ expect(json[:id]).to eq(template_item.id)
+ expect(json[:title]).to eq(template_item.title)
+ expect(json[:slug]).to eq(template_item.slug)
+ expect(json[:content]).to eq(template_item.first_post.raw)
+ expect(json[:tags]).to eq(nil)
+ expect(json[:usages]).to eq(0)
+ end
+ end
+end
diff --git a/plugins/discourse-templates/spec/system/chat_composer_spec.rb b/plugins/discourse-templates/spec/system/chat_composer_spec.rb
new file mode 100644
index 00000000000..4ecd7783b66
--- /dev/null
+++ b/plugins/discourse-templates/spec/system/chat_composer_spec.rb
@@ -0,0 +1,241 @@
+# frozen_string_literal: true
+
+RSpec.describe "Inserting templates in the chat composer", type: :system do
+ fab!(:current_user) { Fabricate(:user) }
+ fab!(:other_user) { Fabricate(:user) }
+ fab!(:templates_category) { Fabricate(:category) }
+ fab!(:template_simple) { Fabricate(:template_item, category: templates_category) }
+ fab!(:template_variables) do
+ Fabricate(
+ :template_item,
+ content: templates_allowed_variables.map { |v| "#{v} = %{#{v}}" }.join("\n"),
+ category: templates_category,
+ )
+ end
+
+ fab!(:channel_1) { Fabricate(:chat_channel) }
+ fab!(:message_1) do
+ Fabricate(:chat_message, user: current_user, chat_channel: channel_1, use_service: true)
+ end
+ fab!(:message_2) do
+ Fabricate(:chat_message, user: other_user, in_reply_to: message_1, use_service: true)
+ end
+ fab!(:message_3) do
+ Fabricate(:chat_message, user: other_user, chat_channel: channel_1, use_service: true)
+ end
+
+ let(:chat_page) { PageObjects::Pages::Chat.new }
+ let(:channel_page) { PageObjects::Pages::ChatChannel.new }
+ let(:thread_page) { PageObjects::Pages::ChatThread.new }
+ let(:insert_template_modal) { PageObjects::Modals::DTemplatesInsertTemplate.new }
+
+ let(:expected_values_channel) do
+ {
+ my_username: "#{current_user.username}",
+ my_name: "#{current_user.name}",
+ chat_channel_name: "#{channel_1.name}",
+ chat_channel_url: "/chat/c/#{channel_1.slug}/#{channel_1.id}",
+ context_title: "#{channel_1.name}",
+ context_url: "/chat/c/#{channel_1.slug}/#{channel_1.id}",
+ }
+ end
+ let(:reply_values) do
+ { reply_to_username: "#{current_user.username}", reply_to_name: "#{current_user.name}" }
+ end
+ let(:template_variables_no_reply_expected_content_channel) do
+ templates_allowed_variables.map { |v| "#{v} = #{expected_values_channel[v.to_sym]}" }.join("\n")
+ end
+ let(:template_variables_replying_expected_content_channel) do
+ templates_allowed_variables
+ .map { |v| "#{v} = #{expected_values_channel[v.to_sym] || reply_values[v.to_sym]}" }
+ .join("\n")
+ end
+
+ let(:expected_values_thread) do
+ {
+ my_username: "#{current_user.username}",
+ my_name: "#{current_user.name}",
+ chat_channel_name: "#{channel_1.name}",
+ chat_channel_url: "/chat/c/#{channel_1.slug}/#{channel_1.id}",
+ chat_thread_name: "#{message_2.thread.title}",
+ chat_thread_url: "/chat/c/#{channel_1.slug}/#{channel_1.id}/t/#{message_2.thread.id}",
+ context_title: "#{message_2.thread.title}",
+ context_url: "/chat/c/#{channel_1.slug}/#{channel_1.id}/t/#{message_2.thread.id}",
+ reply_to_username: "#{current_user.username}",
+ reply_to_name: "#{current_user.name}",
+ }
+ end
+ let(:template_variables_expected_content_thread) do
+ templates_allowed_variables.map { |v| "#{v} = #{expected_values_thread[v.to_sym]}" }.join("\n")
+ end
+
+ before do
+ chat_system_bootstrap
+ channel_1.add(current_user)
+ channel_1.add(other_user)
+
+ SiteSetting.discourse_templates_enabled = true
+ SiteSetting.discourse_templates_categories = templates_category.id.to_s
+
+ sign_in(current_user)
+ end
+
+ context "when typing a message in the channel composer" do
+ context "when the template is inserted using the action button" do
+ it "inserting a template works" do
+ chat_page.visit_channel(channel_1)
+ channel_page.open_action_menu
+ channel_page.click_action_button("d-templates-chat-insert-template-btn")
+
+ insert_template_modal.open?
+ insert_template_modal.select_template(template_simple.id)
+
+ expect(channel_page.composer.value.strip).to eq(template_simple.first_post.raw.strip)
+ end
+
+ it "the variables are replaced with correct values" do
+ chat_page.visit_channel(channel_1)
+ channel_page.open_action_menu
+ channel_page.click_action_button("d-templates-chat-insert-template-btn")
+
+ insert_template_modal.open?
+ insert_template_modal.select_template(template_variables.id)
+
+ expect(channel_page.composer.value.strip).to eq(
+ template_variables_no_reply_expected_content_channel.strip,
+ )
+ end
+
+ it "the variables are replaced with correct values when replying a message" do
+ chat_page.visit_channel(channel_1)
+ channel_page.reply_to(message_1)
+
+ channel_page.open_action_menu
+ channel_page.click_action_button("d-templates-chat-insert-template-btn")
+
+ insert_template_modal.open?
+ insert_template_modal.select_template(template_variables.id)
+
+ expect(channel_page.composer.value.strip).to eq(
+ template_variables_replying_expected_content_channel.strip,
+ )
+ end
+ end
+
+ context "when the template is inserted using keyboard shortcut" do
+ it "inserting a template works" do
+ chat_page.visit_channel(channel_1)
+
+ channel_page.composer.focus # ensure the focus is the textarea
+ expect(channel_page.composer).to be_focused
+
+ insert_template_modal.open_with_keyboard_shortcut
+ insert_template_modal.open?
+ insert_template_modal.select_template(template_simple.id)
+
+ expect(channel_page.composer.value.strip).to eq(template_simple.first_post.raw.strip)
+ end
+
+ it "the variables are replaced with correct values" do
+ chat_page.visit_channel(channel_1)
+
+ channel_page.composer.focus # ensure the focus is the textarea
+ expect(channel_page.composer).to be_focused
+
+ insert_template_modal.open_with_keyboard_shortcut
+ insert_template_modal.open?
+ insert_template_modal.select_template(template_variables.id)
+
+ expect(channel_page.composer.value.strip).to eq(
+ template_variables_no_reply_expected_content_channel.strip,
+ )
+ end
+
+ it "the variables are replaced with correct values when replying a message" do
+ chat_page.visit_channel(channel_1)
+ channel_page.reply_to(message_1)
+
+ channel_page.composer.focus # ensure the focus is the textarea
+ expect(channel_page.composer).to be_focused
+
+ insert_template_modal.open_with_keyboard_shortcut
+ insert_template_modal.open?
+ insert_template_modal.select_template(template_variables.id)
+
+ expect(channel_page.composer.value.strip).to eq(
+ template_variables_replying_expected_content_channel.strip,
+ )
+ end
+ end
+ end
+
+ context "when typing a message in the thread composer" do
+ before do
+ channel_1.threading_enabled = true
+ channel_1.save!
+
+ message_2.thread.title = "New thread title"
+ message_2.thread.save!
+ end
+
+ context "when the template is inserted using the action button" do
+ it "inserting a template works" do
+ chat_page.visit_thread(message_2.thread)
+
+ # thread page does not define the methods open_action_menu and click_action_button
+ thread_page.composer.component.find(".chat-composer-dropdown__trigger-btn").click
+ find(".chat-composer-dropdown__action-btn.d-templates-chat-insert-template-btn").click
+
+ insert_template_modal.open?
+ insert_template_modal.select_template(template_simple.id)
+
+ expect(thread_page.composer.value.strip).to eq(template_simple.first_post.raw.strip)
+ end
+
+ it "the variables are replaced with correct values" do
+ chat_page.visit_thread(message_2.thread)
+
+ # thread page does not define the methods open_action_menu and click_action_button
+ thread_page.composer.component.find(".chat-composer-dropdown__trigger-btn").click
+ find(".chat-composer-dropdown__action-btn.d-templates-chat-insert-template-btn").click
+
+ insert_template_modal.open?
+ insert_template_modal.select_template(template_variables.id)
+
+ expect(thread_page.composer.value.strip).to eq(
+ template_variables_expected_content_thread.strip,
+ )
+ end
+ end
+
+ context "when the template is inserted using keyboard shortcut" do
+ it "inserting a template works" do
+ chat_page.visit_thread(message_2.thread)
+
+ thread_page.composer.focus # ensure the focus is the textarea
+ expect(thread_page.composer).to be_focused
+
+ insert_template_modal.open_with_keyboard_shortcut
+ insert_template_modal.open?
+ insert_template_modal.select_template(template_simple.id)
+
+ expect(thread_page.composer.value.strip).to eq(template_simple.first_post.raw.strip)
+ end
+
+ it "the variables are replaced with correct values" do
+ chat_page.visit_thread(message_2.thread)
+
+ thread_page.composer.focus # ensure the focus is the textarea
+ expect(thread_page.composer).to be_focused
+
+ insert_template_modal.open_with_keyboard_shortcut
+ insert_template_modal.open?
+ insert_template_modal.select_template(template_variables.id)
+
+ expect(thread_page.composer.value.strip).to eq(
+ template_variables_expected_content_thread.strip,
+ )
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-templates/spec/system/core_features_spec.rb b/plugins/discourse-templates/spec/system/core_features_spec.rb
new file mode 100644
index 00000000000..db86db283bd
--- /dev/null
+++ b/plugins/discourse-templates/spec/system/core_features_spec.rb
@@ -0,0 +1,7 @@
+# frozen_string_literal: true
+
+RSpec.describe "Core features", type: :system do
+ before { enable_current_plugin }
+
+ it_behaves_like "having working core features"
+end
diff --git a/plugins/discourse-templates/spec/system/page_objects/modals/insert_template.rb b/plugins/discourse-templates/spec/system/page_objects/modals/insert_template.rb
new file mode 100644
index 00000000000..d17ba327b7a
--- /dev/null
+++ b/plugins/discourse-templates/spec/system/page_objects/modals/insert_template.rb
@@ -0,0 +1,27 @@
+# frozen_string_literal: true
+
+module PageObjects
+ module Modals
+ class DTemplatesInsertTemplate < PageObjects::Modals::Base
+ include SystemHelpers
+
+ MODAL_SELECTOR = ".d-templates-modal"
+
+ def open_with_keyboard_shortcut
+ send_keys([PLATFORM_KEY_MODIFIER, :shift, "i"])
+ end
+
+ def open?
+ super && finished_loading?
+ end
+
+ def finished_loading?
+ has_no_css?("#{MODAL_SELECTOR} .spinner")
+ end
+
+ def select_template(id)
+ find("#template-item-#{id} .templates-apply").click
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-templates/test/javascripts/acceptance/lib/replace-variables-test.js b/plugins/discourse-templates/test/javascripts/acceptance/lib/replace-variables-test.js
new file mode 100644
index 00000000000..83c26aa50c0
--- /dev/null
+++ b/plugins/discourse-templates/test/javascripts/acceptance/lib/replace-variables-test.js
@@ -0,0 +1,276 @@
+import EmberObject from "@ember/object";
+import { test } from "qunit";
+import { acceptance } from "discourse/tests/helpers/qunit-helpers";
+import {
+ replaceVariables,
+ TEMPLATES_ALLOWED_VARIABLES,
+} from "discourse/plugins/discourse-templates/lib/replace-variables";
+import extractVariablesFromChatChannel from "discourse/plugins/discourse-templates/lib/variables-chat-channel";
+import extractVariablesFromComposerModel from "discourse/plugins/discourse-templates/lib/variables-composer";
+
+acceptance(
+ "Acceptance | Plugins | discourse-templates | Lib | replace-variables | models",
+ function (needs) {
+ needs.user({ username: "heisenberg", name: "Walter White", id: 1 });
+
+ test("composer variables", function (assert) {
+ const expectedVariables = {
+ my_username: "heisenberg",
+ my_name: "Walter White",
+ topic_title: "Villains",
+ topic_url: "/t/villains/6",
+ context_title: "Villains",
+ context_url: "/t/villains/6",
+ original_poster_username: "mr_hide",
+ original_poster_name: "Dr. Henry Jekyll",
+ reply_to_username: "dracula",
+ reply_to_name: "Vlad",
+ last_poster_username: "frankenstein",
+ reply_to_or_last_poster_username: "dracula",
+ };
+
+ const fakeModel = EmberObject.create({
+ topic: {
+ details: {
+ created_by: {
+ username: expectedVariables.original_poster_username,
+ name: expectedVariables.original_poster_name,
+ },
+ },
+ last_poster_username: expectedVariables.last_poster_username,
+ title: "Villains",
+ url: "/t/villains/6",
+ },
+ post: {
+ username: expectedVariables.reply_to_username,
+ name: expectedVariables.reply_to_name,
+ },
+ });
+
+ for (const key of TEMPLATES_ALLOWED_VARIABLES) {
+ let template, expected, preparedTemplate;
+
+ // simple replacement
+ template = {
+ title: `test title:%{${key}}`,
+ content: `test response:%{${key}}, %{${key}}, %{${key}}`,
+ };
+ expected = {
+ title: `test title:${expectedVariables[key] || ""}`,
+ content: `test response:${expectedVariables[key] || ""}, ${
+ expectedVariables[key] || ""
+ }, ${expectedVariables[key] || ""}`,
+ };
+
+ const templateVariables = extractVariablesFromComposerModel(fakeModel);
+
+ preparedTemplate = replaceVariables(
+ template.title,
+ template.content,
+ templateVariables
+ );
+ assert.strictEqual(
+ preparedTemplate.title,
+ expected.title,
+ `%{${key}} simple replacement/title`
+ );
+ assert.strictEqual(
+ preparedTemplate.content,
+ expected.content,
+ `%{${key}} simple replacement/content`
+ );
+
+ // replacement with fallback (variables defined)
+ if (templateVariables[key]) {
+ template = {
+ title: `test title:%{${key},fallback:${key.toUpperCase()}}`,
+ content: `test response:%{${key},fallback:${key.toUpperCase()}}, %{${key},fallback:${key.toUpperCase()}}, %{${key},fallback:${key.toUpperCase()}}`,
+ };
+
+ preparedTemplate = replaceVariables(
+ template.title,
+ template.content,
+ templateVariables
+ );
+ assert.strictEqual(
+ preparedTemplate.title,
+ expected.title,
+ `%{${key}} replacement with fallback - variable defined/title`
+ );
+ assert.strictEqual(
+ preparedTemplate.content,
+ expected.content,
+ `%{${key}} replacement with fallback - variable defined/content`
+ );
+ }
+ }
+ });
+
+ test("chat variables", function (assert) {
+ const router = this.container.lookup("service:router");
+
+ const expectedVariables = {
+ my_username: "heisenberg",
+ my_name: "Walter White",
+ chat_channel_name: "Villains",
+ chat_channel_url: "/chat/c/villains/6",
+ context_title: "Villains",
+ context_url: "/chat/c/villains/6",
+ reply_to_username: "dracula",
+ reply_to_name: "Vlad",
+ };
+
+ const fakeChannelModel = EmberObject.create({
+ title: "Villains",
+ routeModels: ["villains", 6],
+ lastMessage: {
+ user: {
+ username: expectedVariables.last_poster_username,
+ },
+ },
+ });
+
+ const fakeMessageModel = EmberObject.create({
+ inReplyTo: {
+ user: {
+ username: expectedVariables.reply_to_username,
+ name: expectedVariables.reply_to_name,
+ },
+ },
+ });
+
+ for (const key of TEMPLATES_ALLOWED_VARIABLES) {
+ let template, expected, preparedTemplate;
+
+ // simple replacement
+ template = {
+ title: `test title:%{${key}}`,
+ content: `test response:%{${key}}, %{${key}}, %{${key}}`,
+ };
+ expected = {
+ title: `test title:${expectedVariables[key] || ""}`,
+ content: `test response:${expectedVariables[key] || ""}, ${
+ expectedVariables[key] || ""
+ }, ${expectedVariables[key] || ""}`,
+ };
+
+ const templateVariables = extractVariablesFromChatChannel(
+ fakeChannelModel,
+ fakeMessageModel,
+ router
+ );
+
+ preparedTemplate = replaceVariables(
+ template.title,
+ template.content,
+ templateVariables
+ );
+ assert.strictEqual(
+ preparedTemplate.title,
+ expected.title,
+ `%{${key}} simple replacement/title`
+ );
+ assert.strictEqual(
+ preparedTemplate.content,
+ expected.content,
+ `%{${key}} simple replacement/content`
+ );
+
+ // replacement with fallback (variables defined)
+ if (templateVariables[key]) {
+ template = {
+ title: `test title:%{${key},fallback:${key.toUpperCase()}}`,
+ content: `test response:%{${key},fallback:${key.toUpperCase()}}, %{${key},fallback:${key.toUpperCase()}}, %{${key},fallback:${key.toUpperCase()}}`,
+ };
+
+ preparedTemplate = replaceVariables(
+ template.title,
+ template.content,
+ templateVariables
+ );
+ assert.strictEqual(
+ preparedTemplate.title,
+ expected.title,
+ `%{${key}} replacement with fallback - variable defined/title`
+ );
+ assert.strictEqual(
+ preparedTemplate.content,
+ expected.content,
+ `%{${key}} replacement with fallback - variable defined/content`
+ );
+ }
+ }
+ });
+ }
+);
+
+acceptance(
+ "Acceptance | Plugins | discourse-templates | Lib | replace-variables | model undefined",
+ function () {
+ test("all variables", function (assert) {
+ const router = this.container.lookup("service:router");
+
+ for (const key of TEMPLATES_ALLOWED_VARIABLES) {
+ let template, expected, preparedTemplate;
+
+ // simple replacement
+ template = {
+ title: `test title:%{${key}}`,
+ content: `test response:%{${key}}, %{${key}}, %{${key}}`,
+ };
+ expected = {
+ title: `test title:`,
+ content: `test response:, , `,
+ };
+
+ const templateVariables = extractVariablesFromChatChannel(
+ null,
+ null,
+ router
+ );
+
+ preparedTemplate = replaceVariables(
+ template.title,
+ template.content,
+ templateVariables
+ );
+ assert.strictEqual(
+ preparedTemplate.title,
+ expected.title,
+ `%{${key}} simple replacement/title`
+ );
+ assert.strictEqual(
+ preparedTemplate.content,
+ expected.content,
+ `%{${key}} simple replacement/content`
+ );
+
+ // replacement with fallback (variables undefined)
+ template = {
+ title: `test title:%{${key},fallback:${key.toUpperCase()}}`,
+ content: `test response:%{${key},fallback:${key.toUpperCase()}}, %{${key},fallback:${key.toUpperCase()}}, %{${key},fallback:${key.toUpperCase()}}`,
+ };
+ expected = {
+ title: `test title:${key.toUpperCase()}`,
+ content: `test response:${key.toUpperCase()}, ${key.toUpperCase()}, ${key.toUpperCase()}`,
+ };
+
+ preparedTemplate = replaceVariables(
+ template.title,
+ template.content,
+ {}
+ );
+ assert.strictEqual(
+ preparedTemplate.title,
+ expected.title,
+ `%{${key}} replacement with fallback - variable undefined/title`
+ );
+ assert.strictEqual(
+ preparedTemplate.content,
+ expected.content,
+ `%{${key}} replacement with fallback - variable undefined/content`
+ );
+ }
+ });
+ }
+);
diff --git a/plugins/discourse-templates/test/javascripts/acceptance/templates-test.js b/plugins/discourse-templates/test/javascripts/acceptance/templates-test.js
new file mode 100644
index 00000000000..2e36e66f49a
--- /dev/null
+++ b/plugins/discourse-templates/test/javascripts/acceptance/templates-test.js
@@ -0,0 +1,422 @@
+/* eslint-disable qunit/no-assert-equal */
+/* eslint-disable qunit/no-loose-assertions */
+import {
+ click,
+ currentURL,
+ fillIn,
+ triggerKeyEvent,
+ visit,
+} from "@ember/test-helpers";
+import { test } from "qunit";
+import { PLATFORM_KEY_MODIFIER } from "discourse/lib/keyboard-shortcuts";
+import { cloneJSON } from "discourse/lib/object";
+import {
+ acceptance,
+ count,
+ exists,
+ query,
+} from "discourse/tests/helpers/qunit-helpers";
+import selectKit from "discourse/tests/helpers/select-kit-helper";
+import { i18n } from "discourse-i18n";
+import TemplatesFixtures from "../fixtures/templates-fixtures";
+
+function templatesPretender(server, helper) {
+ const repliesPath = "/discourse_templates";
+ const replies = TemplatesFixtures[repliesPath];
+
+ server.get(repliesPath, () => helper.response(replies));
+ replies.templates.forEach((template) =>
+ server.post(`${repliesPath}/${template.id}/use`, () => helper.response({}))
+ );
+}
+
+async function selectCategory() {
+ const categoryChooser = selectKit(".category-chooser");
+ await categoryChooser.expand();
+ await categoryChooser.selectRowByValue(2);
+}
+
+acceptance("discourse-templates", function (needs) {
+ needs.settings({
+ discourse_templates_enabled: true,
+ allow_uncategorized_topics: true,
+ tagging_enabled: true,
+ });
+ needs.user({
+ can_use_templates: true,
+ });
+
+ needs.pretender(templatesPretender);
+
+ test("Filtering by tags", async (assert) => {
+ await visit("/");
+
+ await click("#create-topic");
+ await selectCategory();
+ await click(".toolbar-menu__options-trigger");
+ await click(`button[title="${i18n("templates.insert_template")}"]`);
+
+ const tagDropdown = selectKit(".templates-filter-bar .tag-drop");
+ await tagDropdown.expand();
+
+ await tagDropdown.fillInFilter(
+ "cupcake",
+ ".templates-filter-bar .tag-drop input"
+ );
+ assert.deepEqual(
+ tagDropdown.displayedContent(),
+ [
+ {
+ name: "cupcakes",
+ id: "cupcakes",
+ },
+ ],
+ "it should filter tags in the dropdown"
+ );
+
+ await tagDropdown.selectRowByIndex(0);
+ assert.equal(
+ count(".templates-list .template-item"),
+ 1,
+ "it should filter replies by tag"
+ );
+
+ await click("#template-item-1 .templates-apply");
+
+ assert.equal(
+ query(".d-editor-input").value.trim(),
+ "Cupcake ipsum dolor sit amet cotton candy cheesecake jelly. Candy canes sugar plum soufflé sweet roll jelly-o danish jelly muffin. I love jelly-o powder topping carrot cake toffee.",
+ "it should insert the template in the composer"
+ );
+ });
+
+ test("Filtering by text", async (assert) => {
+ await visit("/");
+
+ await click("#create-topic");
+ await selectCategory();
+ await click(".toolbar-menu__options-trigger");
+ await click(`button[title="${i18n("templates.insert_template")}"]`);
+
+ await fillIn(".templates-filter-bar input.templates-filter", "test");
+ assert.equal(
+ count(".templates-list .template-item"),
+ 2,
+ "it should filter by text"
+ );
+
+ await click("#template-item-8 .templates-apply");
+
+ assert.equal(
+ query(".d-editor-input").value.trim(),
+ "Testing testin **123**",
+ "it should insert the template in the composer"
+ );
+ });
+
+ test("Replacing variables", async (assert) => {
+ await visit("/");
+
+ await click("#create-topic");
+ await selectCategory();
+ await click(".toolbar-menu__options-trigger");
+ await click(`button[title="${i18n("templates.insert_template")}"]`);
+
+ await click("#template-item-9 .templates-apply");
+
+ assert.equal(
+ query(".d-editor-input").value.trim(),
+ "Hi there, regards eviltrout.",
+ "it should replace variables"
+ );
+ });
+
+ test("Navigate to source", async (assert) => {
+ await visit("/");
+
+ await click("#create-topic");
+ await selectCategory();
+ await click(".toolbar-menu__options-trigger");
+ await click(`button[title="${i18n("templates.insert_template")}"]`);
+
+ const tagDropdown = selectKit(".templates-filter-bar .tag-drop");
+ await tagDropdown.expand();
+
+ await tagDropdown.fillInFilter(
+ "lorem",
+ ".templates-filter-bar .tag-drop input"
+ );
+ assert.deepEqual(
+ tagDropdown.displayedContent(),
+ [
+ {
+ name: "lorem",
+ id: "lorem",
+ },
+ ],
+ "it should filter tags in the dropdown"
+ );
+
+ await tagDropdown.selectRowByIndex(0);
+ assert.equal(
+ count(".templates-list .template-item"),
+ 1,
+ "it should filter replies by tag"
+ );
+
+ await click("#template-item-130 .template-item-title");
+ await click("#template-item-130 .template-item-source-link");
+
+ assert.equal(
+ currentURL(),
+ "/t/lorem-ipsum-dolor-sit-amet/130",
+ "it should navigate to the source"
+ );
+ });
+});
+
+acceptance(
+ "discourse-templates - with tags disabled in Settings",
+ function (needs) {
+ needs.settings({
+ discourse_templates_enabled: true,
+ tagging_enabled: false,
+ });
+ needs.user({
+ can_use_templates: true,
+ });
+
+ needs.pretender(templatesPretender);
+
+ test("Filtering by tags", async (assert) => {
+ await visit("/");
+
+ await click("#create-topic");
+ await selectCategory();
+ await click(".toolbar-menu__options-trigger");
+ await click(`button[title="${i18n("templates.insert_template")}"]`);
+
+ assert.notOk(
+ exists(".templates-filter-bar .tag-drop"),
+ "tag drop down is not displayed"
+ );
+ });
+ }
+);
+
+acceptance("discourse-templates | keyboard shortcut", function (needs) {
+ needs.settings({
+ discourse_templates_enabled: true,
+ tagging_enabled: true,
+ });
+ needs.user({
+ can_use_templates: true,
+ });
+
+ needs.pretender(templatesPretender);
+
+ const triggerKeyboardShortcut = async () => {
+ // Testing keyboard events is tough!
+ const isMac = PLATFORM_KEY_MODIFIER.toLowerCase() === "meta";
+ await triggerKeyEvent(document, "keydown", "I", {
+ ...(isMac ? { metaKey: true } : { ctrlKey: true }),
+ shiftKey: true,
+ });
+ };
+
+ const assertTemplateWasInserted = async (assert, textarea) => {
+ const tagDropdown = selectKit(".templates-filter-bar .tag-drop");
+ await tagDropdown.expand();
+
+ await tagDropdown.fillInFilter(
+ "cupcake",
+ ".templates-filter-bar .tag-drop input"
+ );
+ await tagDropdown.selectRowByIndex(0);
+ await click("#template-item-1 .templates-apply");
+
+ assert.equal(
+ textarea.value.trim(),
+ "Cupcake ipsum dolor sit amet cotton candy cheesecake jelly. Candy canes sugar plum soufflé sweet roll jelly-o danish jelly muffin. I love jelly-o powder topping carrot cake toffee.",
+ "it should insert the template in the textarea"
+ );
+ };
+
+ test("Help | Added shortcut to help modal", async function (assert) {
+ await visit("/");
+ await triggerKeyEvent(document, "keypress", "?".charCodeAt(0));
+
+ assert.ok(exists(".shortcut-category-templates"));
+ assert.strictEqual(count(".shortcut-category-templates li"), 1);
+ });
+
+ test("Composer | Title field focused | Template is inserted", async (assert) => {
+ await visit("/");
+
+ await click("#create-topic");
+ await selectCategory();
+ const textarea = query(".d-editor-input");
+
+ await triggerKeyboardShortcut();
+ await assertTemplateWasInserted(assert, textarea);
+ });
+
+ test("Composer | Textarea focused | Template is inserted", async (assert) => {
+ await visit("/");
+
+ await click("#create-topic");
+ await selectCategory();
+
+ const textarea = query(".d-editor-input");
+ await textarea.focus();
+
+ await triggerKeyboardShortcut();
+ await assertTemplateWasInserted(assert, textarea);
+ });
+
+ test("Modal | Templates modal | Show the modal if the preview is hidden", async (assert) => {
+ await visit("/");
+
+ await click("#create-topic");
+ await selectCategory();
+
+ await click(".toggle-preview");
+
+ const textarea = query(".d-editor-input");
+ await textarea.focus();
+
+ await triggerKeyboardShortcut();
+ assert.ok(
+ exists(".d-modal.d-templates"),
+ "It displayed the standard templates modal"
+ );
+ });
+
+ test("Modal | Templates modal | Show the modal if a textarea is focused", async (assert) => {
+ // if the text area is outside a modal then simply show the insert template modal
+ // because there is no need to hijack
+ await visit("/u/charlie/preferences/profile");
+
+ const textarea = query(".d-editor-input");
+ await textarea.focus();
+
+ await triggerKeyboardShortcut();
+ assert.ok(
+ exists(".d-modal.d-templates"),
+ "It displayed the standard templates modal"
+ );
+ });
+
+ test("Modal | Templates modal | Template is inserted", async (assert) => {
+ await visit("/u/charlie/preferences/profile");
+
+ const textarea = query(".d-editor-input");
+ await textarea.focus();
+
+ await triggerKeyboardShortcut();
+ await assertTemplateWasInserted(assert, textarea);
+ });
+
+ test("Modal | Templates modal | Template is inserted", async (assert) => {
+ await visit("/u/charlie/preferences/profile");
+
+ const textarea = query(".d-editor-input");
+ await textarea.focus();
+
+ await triggerKeyboardShortcut();
+
+ const tagDropdown = selectKit(".templates-filter-bar .tag-drop");
+ await tagDropdown.expand();
+
+ await tagDropdown.fillInFilter(
+ "lorem",
+ ".templates-filter-bar .tag-drop input"
+ );
+ assert.deepEqual(
+ tagDropdown.displayedContent(),
+ [
+ {
+ name: "lorem",
+ id: "lorem",
+ },
+ ],
+ "it should filter tags in the dropdown"
+ );
+
+ await tagDropdown.selectRowByIndex(0);
+ assert.equal(
+ count(".templates-list .template-item"),
+ 1,
+ "it should filter replies by tag"
+ );
+
+ await click("#template-item-130 .template-item-title");
+ await click("#template-item-130 .template-item-source-link");
+
+ assert.equal(
+ currentURL(),
+ "/t/lorem-ipsum-dolor-sit-amet/130",
+ "it should navigate to the source"
+ );
+ });
+
+ test("Modal | Templates Modal | Stacked Modals | Template is inserted", async (assert) => {
+ await visit("/t/topic-for-group-moderators/2480");
+ await click(".show-more-actions");
+ await click(".show-post-admin-menu");
+ await click(".add-notice");
+
+ const textarea = query(".d-modal__body textarea");
+ await textarea.focus();
+
+ await triggerKeyboardShortcut();
+ await assertTemplateWasInserted(assert, textarea);
+ });
+
+ test("Modal | Templates Modal | Stacked Modals | Closing the template modal returns the focus to the original modal textarea", async (assert) => {
+ await visit("/t/topic-for-group-moderators/2480");
+ await click(".show-more-actions");
+ await click(".show-post-admin-menu");
+ await click(".add-notice");
+
+ const textarea = query(".d-modal__body textarea");
+ await textarea.focus();
+ assert.notOk(
+ exists(".d-templates-modal"),
+ "the templates modal does not exist yet"
+ );
+ await triggerKeyboardShortcut();
+ assert.ok(exists(".d-templates-modal"), "it displayed the templates modal");
+
+ await click(".d-templates-modal .btn.modal-close");
+ assert.strictEqual(
+ textarea,
+ document.activeElement,
+ "it focused the original textarea again after closing the templates modal"
+ );
+ });
+});
+
+import topicFixtures from "discourse/tests/fixtures/topic";
+
+acceptance("discourse-templates - buttons on topics", function (needs) {
+ needs.user();
+ needs.settings({
+ allow_uncategorized_topics: true,
+ });
+
+ needs.pretender((server, helper) => {
+ const topicResponse = cloneJSON(topicFixtures["/t/280/1.json"]);
+ topicResponse.is_template = true;
+
+ server.get("/t/280.json", () => helper.response(topicResponse));
+ server.get("/raw/280/1", () => [200, {}, "post raw content"]);
+ });
+
+ test("Can open composer using button on topic", async function (assert) {
+ await visit("/t/280");
+
+ await click(".template-new-topic");
+ assert.dom("textarea.d-editor-input").hasValue("post raw content");
+ });
+});
diff --git a/plugins/discourse-templates/test/javascripts/fixtures/templates-fixtures.js b/plugins/discourse-templates/test/javascripts/fixtures/templates-fixtures.js
new file mode 100644
index 00000000000..b39274299e8
--- /dev/null
+++ b/plugins/discourse-templates/test/javascripts/fixtures/templates-fixtures.js
@@ -0,0 +1,94 @@
+export default {
+ "/discourse_templates": {
+ templates: [
+ {
+ id: 1,
+ slug: "cupcake-ipsum-excerpt",
+ title: "Cupcake Ipsum excerpt",
+ content:
+ "Cupcake ipsum dolor sit amet cotton candy cheesecake jelly. Candy canes sugar plum soufflé sweet roll jelly-o danish jelly muffin. I love jelly-o powder topping carrot cake toffee.",
+ tags: ["cupcakes", "ipsum"],
+ usages: 20,
+ },
+ {
+ id: 2,
+ slug: "hipster-ipsum-excerpt",
+ title: "Hipster ipsum excerpt",
+ content:
+ "Qui butcher farm-to-table locavore sunt quinoa. Bicycle rights pariatur marfa etsy, four loko lomo veniam fashion axe aesthetic. Actually irony quis selfies readymade narwhal. Nesciunt pinterest cillum, wolf swag american apparel carles ex butcher non veniam.",
+ tags: ["ipsum", "hipster"],
+ usages: 7,
+ },
+ {
+ id: 3,
+ slug: "liquor-ipsum-excerpt",
+ title: "Liquor ipsum excerpt",
+ content:
+ "Prince shnell hi-fi harper’s chupacabra; charro negro; tequila sunrise vodka mcgovern, glenlossie seven and seven gibbon matador singapore sling imperial. Quentão jagertee, port charlotte southern comfort pisco sour anisette glenlivet churchill sake bomb glenallachie brandy daisy?",
+ tags: ["ipsum", "liquor"],
+ usages: 3,
+ },
+ {
+ id: 5,
+ slug: "mussum-ipsum-excerpt",
+ title: "Mussum Ipsum excerpt",
+ content:
+ "Mussum Ipsum, cacilds vidis litro abertis. Interagi no mé, cursus quis, vehicula ac nisi.A ordem dos tratores não altera o pão duris.Diuretics paradis num copo é motivis de denguis.Mais vale um bebadis conhecidiss, que um alcoolatra anonimis.",
+ tags: ["ipsum", "mussum"],
+ usages: 3,
+ },
+ {
+ id: 6,
+ slug: "my-first-template",
+ title: "My first template",
+ content:
+ "This is an example template.\nYou can user **markdown** to style your replies. Click the **new** button to create new replies or the **edit** button to edit or remove an existing template.\n\n*This template will be added when the replies list is empty.*",
+ tags: ["old-tests"],
+ usages: 0,
+ },
+ {
+ id: 7,
+ slug: "testing",
+ title: "Testing",
+ content: "<script>alert('ahah')</script>",
+ tags: ["old-tests", "scripts"],
+ usages: 1,
+ },
+ {
+ id: 8,
+ slug: "this-is-a-test",
+ title: "This is a test",
+ content: "Testing testin **123**",
+ tags: ["old-tests"],
+ usages: 1,
+ },
+ {
+ id: 9,
+ slug: "using-variables-1",
+ title: "Using variables (1)",
+ content:
+ "Hi %{reply_to_username,fallback:there}, regards %{my_username}.",
+ tags: ["old-tests", "variables"],
+ usages: 0,
+ },
+ {
+ id: 10,
+ slug: "using-variables-2",
+ title: "Using variables (2)",
+ content:
+ "Hi %{reply_to_or_last_poster_username,fallback:there}, regards %{my_name}.",
+ tags: ["old-tests", "variables"],
+ usages: 0,
+ },
+ {
+ id: 130,
+ slug: "lorem-ipsum-dolor-sit-amet",
+ title: "Lorem ipsum dolor sit amet",
+ content:
+ "\u003e **Lorem ipsum** dolor sit amet, consectetur adipiscing elit. Aenean ut tellus laoreet, mattis justo a, facilisis tellus. Curabitur purus arcu, auctor vel lobortis id, accumsan iaculis sapien. Duis aliquam libero velit, eget tincidunt turpis volutpat at. Nulla aliquet volutpat ipsum, non vehicula velit ultrices id. In hac habitasse platea dictumst. Proin eget mauris nec ligula interdum tincidunt nec nec diam. Pellentesque mauris lectus, sollicitudin ac libero sed, ornare volutpat ante. Maecenas ante dui, ultricies et odio id, consequat placerat dui. Sed vel magna ac neque luctus lacinia. Aenean diam massa, porttitor eget mi et, scelerisque maximus odio. Cras at mi augue. Maecenas efficitur augue a lectus auctor mattis. Aliquam non mauris in diam interdum semper a ac elit. Donec euismod justo in velit aliquet tempor. Nullam condimentum congue ligula, id vehicula purus malesuada vitae.",
+ tags: ["lorem"],
+ usages: 0,
+ },
+ ],
+ },
+};
diff --git a/translator.yml b/translator.yml
index 93661c90b1d..a1b8b7a6117 100644
--- a/translator.yml
+++ b/translator.yml
@@ -288,3 +288,10 @@ files:
- source_path: plugins/discourse-topic-voting/config/locales/server.en.yml
destination_path: plugins/topic-voting/server.yml
label: topic-voting
+
+ - source_path: plugins/discourse-templates/config/locales/client.en.yml
+ destination_path: plugins/templates/client.yml
+ label: templates
+ - source_path: plugins/discourse-templates/config/locales/server.en.yml
+ destination_path: plugins/templates/server.yml
+ label: templates