A platform for community discussion. Free, open, simple.
FEATURE: Inline policy editing in rich editor (#39820)
Sama20a6a465cea
diff --git a/plugins/discourse-policy/assets/javascripts/discourse/components/modal/policy-builder.gjs b/plugins/discourse-policy/assets/javascripts/discourse/components/modal/policy-builder.gjsindex 1242c1f5617..40aa6efbcda 100644--- a/plugins/discourse-policy/assets/javascripts/discourse/components/modal/policy-builder.gjs+++ b/plugins/discourse-policy/assets/javascripts/discourse/components/modal/policy-builder.gjs@@ -1,9 +1,7 @@import Component from "@glimmer/component";-import { tracked } from "@glimmer/tracking";-import { fn } from "@ember/helper";-import { action, set } from "@ember/object";-import { trackedObject } from "@ember/reactive/collections";-import { isBlank, isPresent } from "@ember/utils";+import { cached, tracked } from "@glimmer/tracking";+import { action } from "@ember/object";+import { isPresent } from "@ember/utils";import DButton from "discourse/components/d-button";import DModal from "discourse/components/d-modal";import { ajax } from "discourse/lib/ajax";@@ -11,21 +9,78 @@ import { cook } from "discourse/lib/text";import { i18n } from "discourse-i18n";import PolicyBuilderForm from "../policy-builder-form";+const POLICY_MARKDOWN_FIELDS = [+ ["groups", "groups"],+ ["version", "version"],+ ["renew", "renew"],+ ["renewStart", "renew-start"],+ ["reminder", "reminder"],+ ["accept", "accept"],+ ["revoke", "revoke"],+ ["addUsersToGroup", "add-users-to-group"],+];++function policyValue(policy, ...keys) {+ for (const key of keys) {+ const value = policy?.get?.(key) ?? policy?.[key];++ if (isPresent(value)) {+ return value;+ }+ }+}++function isPrivate(value) {+ return value === true || value === "true";+}++function policyToFormData(policy) {+ return {+ groups: policyValue(policy, "groups", "group") ?? "",+ version: policyValue(policy, "version") ?? 1,+ renew: policyValue(policy, "renew") ?? "",+ renewStart: policyValue(policy, "renewStart", "renew-start") ?? "",+ reminder: policyValue(policy, "reminder") ?? null,+ accept: policyValue(policy, "accept") ?? "",+ revoke: policyValue(policy, "revoke") ?? "",+ addUsersToGroup:+ policyValue(policy, "addUsersToGroup", "add-users-to-group") ?? "",+ private: isPrivate(policy?.get?.("private") ?? policy?.private),+ };+}+export default class PolicyBuilder extends Component {@tracked isSaving = false;- @tracked flash;- policy =- this.args.model.policy || trackedObject({ reminder: null, version: 1 });+ formApi;++ @cached+ get formData() {+ return policyToFormData(this.args.model.policy);+ }@action- insertPolicy() {- if (!this.validateForm()) {- return;+ onRegisterApi(api) {+ this.formApi = api;+ }++ @action+ submitForm() {+ this.formApi?.submit();+ }++ @action+ async onSubmit(data) {+ if (this.args.model.insertMode) {+ this.insertPolicy(data);+ } else {+ await this.updatePolicy(data);}+ }+ insertPolicy(data) {this.args.model.toolbarEvent?.addText("\n\n" +- `[policy ${this.markdownParams}]\n${i18n(+ `[policy ${this.markdownParams(data)}]\n${i18n("discourse_policy.accept_policy_template")}\n[/policy]` +"\n\n"@@ -33,9 +88,10 @@ export default class PolicyBuilder extends Component {this.args.closeModal();}- @action- async updatePolicy() {- if (!this.validateForm()) {+ async updatePolicy(data) {+ if (this.args.model.onApply) {+ this.args.model.onApply(data);+ this.args.closeModal();return;}@@ -43,14 +99,17 @@ export default class PolicyBuilder extends Component {try {const result = await ajax(`/posts/${this.args.model.post.id}`);- const newRaw = this.replaceRaw(result.raw);+ const newRaw = this.replaceRaw(result.raw, data);if (newRaw) {- this.args.model.post.save({+ const cooked = await cook(newRaw);+ await this.args.model.post.save({raw: newRaw,- cooked: (await cook(result.raw)).toString(),+ cooked: cooked.toString(),edit_reason: i18n("discourse_policy.edit_reason"),});++ await this.refreshPostPolicyState();}} finally {this.isSaving = false;@@ -58,53 +117,62 @@ export default class PolicyBuilder extends Component {}}- get markdownParams() {+ markdownParams(data) {const markdownParams = [];- for (const [key, value] of Object.entries(this.policy)) {++ for (const [formKey, markdownKey] of POLICY_MARKDOWN_FIELDS) {+ const value = data[formKey];+if (isPresent(value)) {- markdownParams.push(`${key}="${value}"`);+ markdownParams.push(`${markdownKey}="${value}"`);}}++ if (data.private) {+ markdownParams.push('private="true"');+ }+return markdownParams.join(" ");}- replaceRaw(raw) {+ replaceRaw(raw, data) {const policyRegex = new RegExp(`\\[policy\\s(.*?)\\]`, "m");const policyMatches = raw.match(policyRegex);if (policyMatches?.[1]) {- return raw.replace(policyRegex, `[policy ${this.markdownParams}]`);+ return raw.replace(policyRegex, `[policy ${this.markdownParams(data)}]`);}return false;}- validateForm() {- if (isBlank(this.policy.groups)) {- this.flash = i18n("discourse_policy.builder.errors.group");- return false;- }-- if (isBlank(this.policy.version)) {- this.flash = i18n("discourse_policy.builder.errors.version");- return false;- }-- return true;+ async refreshPostPolicyState() {+ const result = await ajax(`/posts/${this.args.model.post.id}.json`);++ this.args.model.post.setProperties({+ policy_can_accept: result.policy_can_accept,+ policy_can_revoke: result.policy_can_revoke,+ policy_accepted: result.policy_accepted,+ policy_revoked: result.policy_revoked,+ policy_not_accepted_by: result.policy_not_accepted_by || [],+ policy_not_accepted_by_count: result.policy_not_accepted_by_count,+ policy_accepted_by: result.policy_accepted_by || [],+ policy_accepted_by_count: result.policy_accepted_by_count,+ policy_stats: result.policy_stats,+ });}<template><DModal@title={{i18n "discourse_policy.builder.title"}}@closeModal={{@closeModal}}- @flash={{this.flash}}- @flashType="error"class="policy-builder"><:body><PolicyBuilderForm- @policy={{this.policy}}- @onChange={{fn set this.policy}}+ @data={{this.formData}}+ @onSubmit={{this.onSubmit}}+ @onRegisterApi={{this.onRegisterApi}}/></:body>@@ -112,13 +180,13 @@ export default class PolicyBuilder extends Component {{{#if @model.insertMode}}<DButton@label="discourse_policy.builder.insert"- @action={{this.insertPolicy}}+ @action={{this.submitForm}}class="btn-primary"/>{{else}}<DButton@label="discourse_policy.builder.save"- @action={{this.updatePolicy}}+ @action={{this.submitForm}}@isLoading={{this.isSaving}}class="btn-primary"/>diff --git a/plugins/discourse-policy/assets/javascripts/discourse/components/policy-builder-form.gjs b/plugins/discourse-policy/assets/javascripts/discourse/components/policy-builder-form.gjsindex 19cd5ce21ce..9417d378566 100644--- a/plugins/discourse-policy/assets/javascripts/discourse/components/policy-builder-form.gjs+++ b/plugins/discourse-policy/assets/javascripts/discourse/components/policy-builder-form.gjs@@ -1,97 +1,163 @@import Component from "@glimmer/component";-import { fn } from "@ember/helper";-import { on } from "@ember/modifier";-import { action, get } from "@ember/object";-import PolicyFormField from "./policy-form-field";+import { action } from "@ember/object";+import { isBlank } from "@ember/utils";+import Form from "discourse/components/form";+import { i18n } from "discourse-i18n";import PolicyGroupInput from "./policy-group-input";import PolicyReminderInput from "./policy-reminder-input";export default class PolicyBuilderForm extends Component {@action- changeValue(field, event) {- this.args.onChange(field, event.target.value);- }+ validatePolicy(data, { addError, removeError }) {+ if (isBlank(data.groups)) {+ addError("groups", {+ title: i18n("discourse_policy.builder.groups.label"),+ message: i18n("discourse_policy.builder.errors.group"),+ });+ } else {+ removeError("groups");+ }- @action- changeBoolValue(field, event) {- this.args.onChange(field, event.target.checked);+ if (isBlank(data.version)) {+ addError("version", {+ title: i18n("discourse_policy.builder.version.label"),+ message: i18n("discourse_policy.builder.errors.version"),+ });+ } else {+ removeError("version");+ }}<template>- <PolicyFormField @name="groups" @required={{true}}>- <PolicyGroupInput- @groups={{@policy.groups}}- @onChangeGroup={{fn @onChange "groups"}}- />- </PolicyFormField>+ <Form+ @data={{@data}}+ @onSubmit={{@onSubmit}}+ @onRegisterApi={{@onRegisterApi}}+ @validate={{this.validatePolicy}}+ as |form data|+ >+ <form.Field+ @name="groups"+ @title={{i18n "discourse_policy.builder.groups.label"}}+ @tooltip={{i18n "discourse_policy.builder.groups.description"}}+ @format="large"+ @type="custom"+ class="groups"+ as |field|+ >+ <field.Control>+ <div class="policy-builder-form__groups">+ <PolicyGroupInput+ @groups={{data.groups}}+ @onChangeGroup={{field.set}}+ />+ </div>+ </field.Control>+ </form.Field>- <PolicyFormField @name="version" @required={{true}}>- <input- name="version"- type="number"- value={{readonly @policy.version}}- {{on "input" (fn this.changeValue "version")}}- />- </PolicyFormField>+ <form.Field+ @name="version"+ @title={{i18n "discourse_policy.builder.version.label"}}+ @tooltip={{i18n "discourse_policy.builder.version.description"}}+ @validation="required"+ @format="small"+ @type="input-number"+ as |field|+ >+ <field.Control />+ </form.Field>- <PolicyFormField @name="renew">- <input- name="renew"- type="number"- value={{readonly @policy.renew}}- {{on "input" (fn this.changeValue "renew")}}- />- </PolicyFormField>+ <form.Field+ @name="renew"+ @title={{i18n "discourse_policy.builder.renew.label"}}+ @tooltip={{i18n "discourse_policy.builder.renew.description"}}+ @format="small"+ @type="input-number"+ as |field|+ >+ <field.Control />+ </form.Field>- <PolicyFormField @name="renew-start">- <input- type="date"- placeholder="2020-03-31"- name="renew-start"- value={{readonly (get @policy "renew-start")}}- {{on "input" (fn this.changeValue "renew-start")}}- />- </PolicyFormField>+ <form.Field+ @name="renewStart"+ @title={{i18n "discourse_policy.builder.renew-start.label"}}+ @tooltip={{i18n "discourse_policy.builder.renew-start.description"}}+ @format="large"+ @type="input-date"+ as |field|+ >+ <field.Control />+ </form.Field>- <PolicyFormField @name="reminder">- <PolicyReminderInput- @reminder={{@policy.reminder}}- @onChangeReminder={{fn @onChange "reminder"}}- />- </PolicyFormField>+ <form.Field+ @name="reminder"+ @title={{i18n "discourse_policy.builder.reminder.label"}}+ @tooltip={{i18n "discourse_policy.builder.reminder.description"}}+ @format="large"+ @type="custom"+ as |field|+ >+ <field.Control>+ <PolicyReminderInput+ @reminder={{data.reminder}}+ @onChangeReminder={{field.set}}+ />+ </field.Control>+ </form.Field>- <PolicyFormField @name="accept">- <input- type="text"- name="accept"- value={{readonly @policy.accept}}- {{on "input" (fn this.changeValue "accept")}}- />- </PolicyFormField>+ <form.Field+ @name="accept"+ @title={{i18n "discourse_policy.builder.accept.label"}}+ @tooltip={{i18n "discourse_policy.builder.accept.description"}}+ @format="large"+ @type="input-text"+ as |field|+ >+ <field.Control />+ </form.Field>- <PolicyFormField @name="revoke">- <input- type="text"- name="revoke"- value={{readonly @policy.revoke}}- {{on "input" (fn this.changeValue "revoke")}}- />- </PolicyFormField>+ <form.Field+ @name="revoke"+ @title={{i18n "discourse_policy.builder.revoke.label"}}+ @tooltip={{i18n "discourse_policy.builder.revoke.description"}}+ @format="large"+ @type="input-text"+ as |field|+ >+ <field.Control />+ </form.Field>- <PolicyFormField @name="add-users-to-group">- <PolicyGroupInput- @groups={{get @policy "add-users-to-group"}}- @onChangeGroup={{fn @onChange "add-users-to-group"}}- />- </PolicyFormField>+ <form.Field+ @name="addUsersToGroup"+ @title={{i18n "discourse_policy.builder.add-users-to-group.label"}}+ @tooltip={{i18n+ "discourse_policy.builder.add-users-to-group.description"+ }}+ @format="large"+ @type="custom"+ class="add-users-to-group"+ as |field|+ >+ <field.Control>+ <div class="policy-builder-form__add-users-to-group">+ <PolicyGroupInput+ @groups={{data.addUsersToGroup}}+ @excludeAutomaticGroups={{true}}+ @onChangeGroup={{field.set}}+ />+ </div>+ </field.Control>+ </form.Field>- <PolicyFormField @name="private">- <input- type="checkbox"- name="private"- checked={{readonly @policy.private}}- {{on "click" (fn this.changeBoolValue "private")}}- />- </PolicyFormField>+ <form.Field+ @name="private"+ @title={{i18n "discourse_policy.builder.private.label"}}+ @tooltip={{i18n "discourse_policy.builder.private.description"}}+ @type="checkbox"+ as |field|+ >+ <field.Control />+ </form.Field>+ </Form></template>}diff --git a/plugins/discourse-policy/assets/javascripts/discourse/components/policy-form-field.gjs b/plugins/discourse-policy/assets/javascripts/discourse/components/policy-form-field.gjsdeleted file mode 100644index a87a357da97..00000000000--- a/plugins/discourse-policy/assets/javascripts/discourse/components/policy-form-field.gjs+++ /dev/null@@ -1,27 +0,0 @@-import { concat } from "@ember/helper";-import { i18n } from "discourse-i18n";--const PolicyFormFields = <template>- <div class="policy-field {{@name}}">- <div class="policy-field-label">- <span class="label">- {{i18n (concat "discourse_policy.builder." @name ".label")}}- {{#if @required}}- <span class="required-field">*</span>- {{/if}}- </span>- </div>-- <div class="policy-field-control">- {{yield}}- </div>-- <span class="policy-field-description">- <span class="description">- {{i18n (concat "discourse_policy.builder." @name ".description")}}- </span>- </span>- </div>-</template>;--export default PolicyFormFields;diff --git a/plugins/discourse-policy/assets/javascripts/discourse/components/policy-group-input.gjs b/plugins/discourse-policy/assets/javascripts/discourse/components/policy-group-input.gjsindex 68de56946b7..98c3a5d4178 100644--- a/plugins/discourse-policy/assets/javascripts/discourse/components/policy-group-input.gjs+++ b/plugins/discourse-policy/assets/javascripts/discourse/components/policy-group-input.gjs@@ -4,6 +4,10 @@ import { service } from "@ember/service";import { AUTO_GROUPS } from "discourse/lib/constants";import GroupChooser from "discourse/select-kit/components/group-chooser";+const AUTOMATIC_GROUP_IDS = new Set(+ Object.values(AUTO_GROUPS).map((g) => g.id)+);+export default class PolicyGroupInput extends Component {@service site;@@ -13,10 +17,13 @@ export default class PolicyGroupInput extends Component {get availableGroups() {return (this.site.groups || [])- .map((g) =>- // prevents group "everyone" to be listed- g.id === AUTO_GROUPS.everyone.id ? null : g.name- )+ .map((g) => {+ if (this.args.excludeAutomaticGroups) {+ return g.automatic || AUTOMATIC_GROUP_IDS.has(g.id) ? null : g.name;+ }++ return g.id === AUTO_GROUPS.everyone.id ? null : g.name;+ }).filter(Boolean);}diff --git a/plugins/discourse-policy/assets/javascripts/discourse/initializers/rich-editor-extension.js b/plugins/discourse-policy/assets/javascripts/discourse/initializers/rich-editor-extension.jsindex 0ecb572c41f..4359e5fd01f 100644--- a/plugins/discourse-policy/assets/javascripts/discourse/initializers/rich-editor-extension.js+++ b/plugins/discourse-policy/assets/javascripts/discourse/initializers/rich-editor-extension.js@@ -1,6 +1,9 @@import { camelize } from "@ember/string";import { camelCaseToDash } from "discourse/lib/case-converter";+import { iconHTML } from "discourse/lib/icon-library";import { withPluginApi } from "discourse/lib/plugin-api";+import { i18n } from "discourse-i18n";+import PolicyBuilder from "../components/modal/policy-builder";const POLICY_ATTRIBUTES = {group: { default: null },@@ -9,10 +12,220 @@ const POLICY_ATTRIBUTES = {accept: { default: null },revoke: { default: null },reminder: { default: null },+ renew: { default: null },renewStart: { default: null },+ addUsersToGroup: { default: null },private: { default: null },};+const DISPLAYED_POLICY_ATTRIBUTES = [+ "groups",+ "group",+ "version",+ "renew",+ "renewStart",+ "reminder",+ "accept",+ "revoke",+ "addUsersToGroup",+ "private",+];++function hasAttributeValue(value) {+ return (+ value !== null &&+ value !== undefined &&+ String(value).trim() !== "" &&+ String(value) !== '\"\"'+ );+}++function policyAttrsToFormPolicy(attrs) {+ const policy = {};++ Object.entries(attrs).forEach(([key, value]) => {+ if (!hasAttributeValue(value)) {+ return;+ }++ policy[key] = key === "private" ? value === "true" : value;+ });++ if (!policy.groups && policy.group) {+ policy.groups = policy.group;+ delete policy.group;+ }++ return policy;+}++function formPolicyToPolicyAttrs(policy) {+ const attrs = {};++ Object.keys(POLICY_ATTRIBUTES).forEach((key) => {+ attrs[key] = null;+ });++ Object.entries(policy).forEach(([key, value]) => {+ if (key === "private") {+ attrs.private = value === true || value === "true" ? "true" : null;+ return;+ }++ attrs[camelize(key)] = hasAttributeValue(value) ? String(value) : null;+ });++ return attrs;+}++const createPolicyNodeView =+ ({ getContext, pmState: { NodeSelection } }) =>+ (node, view, getPos) =>+ new PolicyNodeView({ node, view, getPos, getContext, NodeSelection });++class PolicyNodeView {+ node;+ view;+ getPos;+ getContext;+ NodeSelection;+ dom;+ details;+ contentDOM;+ editButton;++ openEditModal = (event) => {+ event.preventDefault();+ event.stopPropagation();++ const { modal } = this.getContext();+ modal.show(PolicyBuilder, {+ model: {+ policy: policyAttrsToFormPolicy(this.node.attrs),+ onApply: (policy) => this.#applyEdit(policy),+ },+ });+ };++ constructor({ node, view, getPos, getContext, NodeSelection }) {+ this.node = node;+ this.view = view;+ this.getPos = getPos;+ this.getContext = getContext;+ this.NodeSelection = NodeSelection;++ this.dom = document.createElement("div");+ this.dom.classList.add("policy");++ this.#syncAttributes();++ const header = document.createElement("div");+ header.classList.add("policy-header");+ header.setAttribute("contenteditable", "false");++ const title = document.createElement("span");+ title.textContent = i18n("discourse_policy.title");+ header.appendChild(title);++ this.editButton = document.createElement("button");+ this.editButton.type = "button";+ this.editButton.classList.add("btn-flat", "policy-node-edit-button");+ this.editButton.setAttribute("contenteditable", "false");+ this.editButton.setAttribute(+ "title",+ i18n("discourse_policy.builder.edit")+ );+ this.editButton.setAttribute(+ "aria-label",+ i18n("discourse_policy.builder.edit")+ );+ this.editButton.innerHTML = iconHTML("pencil");+ this.editButton.addEventListener("click", this.openEditModal);+ header.appendChild(this.editButton);++ this.dom.appendChild(header);++ this.details = document.createElement("dl");+ this.details.classList.add("policy-attrs");+ this.details.setAttribute("contenteditable", "false");+ this.dom.appendChild(this.details);++ this.contentDOM = document.createElement("div");+ this.contentDOM.classList.add("policy-body");+ this.dom.appendChild(this.contentDOM);++ this.#syncDetails();+ }++ update(node) {+ if (node.type !== this.node.type) {+ return false;+ }++ this.node = node;+ this.#syncAttributes();+ this.#syncDetails();++ return true;+ }++ stopEvent(event) {+ return event.target instanceof Node+ ? this.editButton.contains(event.target)+ : false;+ }++ ignoreMutation(mutation) {+ return !this.contentDOM.contains(mutation.target);+ }++ destroy() {+ this.editButton.removeEventListener("click", this.openEditModal);+ }++ #syncAttributes() {+ Object.keys(POLICY_ATTRIBUTES).forEach((key) => {+ this.dom.removeAttribute(`data-${camelCaseToDash(key)}`);+ });++ Object.entries(this.node.attrs).forEach(([key, value]) => {+ if (hasAttributeValue(value)) {+ const dataKey = camelCaseToDash(key);+ this.dom.setAttribute(`data-${dataKey}`, value);+ }+ });+ }++ #syncDetails() {+ this.details.replaceChildren();++ DISPLAYED_POLICY_ATTRIBUTES.forEach((key) => {+ const value = this.node.attrs[key];++ if (!hasAttributeValue(value)) {+ return;+ }++ const name = document.createElement("dt");+ const labelKey = key === "group" ? "groups" : camelCaseToDash(key);+ name.textContent = i18n(`discourse_policy.builder.${labelKey}.label`);++ const definition = document.createElement("dd");+ definition.textContent = value;++ this.details.append(name, definition);+ });+ }++ #applyEdit(policy) {+ const pos = this.getPos();+ const attrs = formPolicyToPolicyAttrs(policy);+ const tr = this.view.state.tr.setNodeMarkup(pos, null, attrs);+ tr.setSelection(this.NodeSelection.create(tr.doc, pos));+ this.view.dispatch(tr);+ }+}+/** @type {RichEditorExtension} */const extension = {nodeSpec: {@@ -27,7 +240,7 @@ const extension = {getAttrs: (dom) => {const attrs = {};Object.entries(dom.dataset).forEach(([key, value]) => {- if (value && value.trim() !== "" && value !== '""') {+ if (hasAttributeValue(value)) {attrs[camelize(key)] = value;}});@@ -39,7 +252,7 @@ const extension = {const attrs = { class: "policy" };Object.entries(node.attrs).forEach(([key, value]) => {- if (value && value.trim() !== "" && value !== '""') {+ if (hasAttributeValue(value)) {const dataKey = camelCaseToDash(key);attrs[`data-${dataKey}`] = value;}@@ -51,49 +264,7 @@ const extension = {},nodeViews: {- policy: () => (node) => {- const dom = document.createElement("div");- dom.classList.add("policy");-- Object.entries(node.attrs).forEach(([key, value]) => {- if (value && value.trim() !== "" && value !== '""') {- const dataKey = camelCaseToDash(key);- dom.setAttribute(`data-${dataKey}`, value);- }- });-- // Create policy header- const header = document.createElement("div");- header.classList.add("policy-header");- header.textContent = "Policy";- dom.appendChild(header);-- // Create content wrapper- const contentDOM = document.createElement("div");- contentDOM.classList.add("policy-body");- dom.appendChild(contentDOM);-- return {- dom,- contentDOM,- update: (updatedNode) => {- if (updatedNode.type !== node.type) {- return false;- }-- Object.entries(updatedNode.attrs).forEach(([key, value]) => {- const dataKey = camelCaseToDash(key);- if (value && value.trim() !== "" && value !== '""') {- dom.setAttribute(`data-${dataKey}`, value);- } else {- dom.removeAttribute(`data-${dataKey}`);- }- });-- return true;- },- };- },+ policy: createPolicyNodeView,},parse: {@@ -109,7 +280,7 @@ const extension = {token.attrs?.forEach(([key, value]) => {if (key.startsWith("data-")) {const attrName = camelize(key.slice(5));- if (value && value.trim() !== "" && value !== '""') {+ if (hasAttributeValue(value)) {attrs[attrName] = value;}}@@ -129,7 +300,7 @@ const extension = {state.write("[policy");Object.entries(node.attrs).forEach(([key, value]) => {- if (value && value.trim() !== "" && value !== '""') {+ if (hasAttributeValue(value)) {const kebabKey = camelCaseToDash(key);state.write(` ${kebabKey}="${value}"`);}diff --git a/plugins/discourse-policy/assets/stylesheets/common/discourse-policy-builder.scss b/plugins/discourse-policy/assets/stylesheets/common/discourse-policy-builder.scssindex c687a547759..be40ddd6854 100644--- a/plugins/discourse-policy/assets/stylesheets/common/discourse-policy-builder.scss+++ b/plugins/discourse-policy/assets/stylesheets/common/discourse-policy-builder.scss@@ -22,20 +22,4 @@input[type="checkbox"] {margin: 0;}-- .policy-field {- margin-bottom: 0.5em;-- &:last-child {- margin: 0;- }-- .policy-field-label {- font-weight: 700;- }-- .policy-field-description {- font-size: var(--font-down-1);- }- }}diff --git a/plugins/discourse-policy/assets/stylesheets/common/discourse-policy.scss b/plugins/discourse-policy/assets/stylesheets/common/discourse-policy.scssindex 96b94e5fe41..a6ae5a378fd 100644--- a/plugins/discourse-policy/assets/stylesheets/common/discourse-policy.scss+++ b/plugins/discourse-policy/assets/stylesheets/common/discourse-policy.scss@@ -151,6 +151,37 @@border: 1px solid var(--primary-low);margin-block: var(--space-4);+ .policy-header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: var(--space-2);+ font-size: var(--font-up-1);+ font-weight: 700;+ }++ .policy-node-edit-button {+ padding: var(--space-1);+ }++ .policy-attrs {+ display: grid;+ grid-template-columns: max-content 1fr;+ gap: var(--space-1) var(--space-2);+ margin: var(--space-2) 0;+ padding: var(--space-2);+ background: var(--primary-very-low);++ dt {+ font-weight: 700;+ }++ dd {+ margin: 0;+ overflow-wrap: anywhere;+ }+ }+.policy-preview {font-size: var(--font-up-1);font-weight: 700;diff --git a/plugins/discourse-policy/config/locales/client.en.yml b/plugins/discourse-policy/config/locales/client.en.ymlindex 5b42cacfc44..cb2d3ee2393 100644--- a/plugins/discourse-policy/config/locales/client.en.yml+++ b/plugins/discourse-policy/config/locales/client.en.yml@@ -13,6 +13,7 @@ en:title: Policyattach: Create Policysave: Save changes+ edit: Edit policy settingsinsert: Inserterrors:group: Group is requireddiff --git a/plugins/discourse-policy/test/javascripts/acceptance/policy-test.js b/plugins/discourse-policy/test/javascripts/acceptance/policy-test.jsindex d8e5cd68703..68d72b58ba1 100644--- a/plugins/discourse-policy/test/javascripts/acceptance/policy-test.js+++ b/plugins/discourse-policy/test/javascripts/acceptance/policy-test.js@@ -62,7 +62,7 @@ acceptance("post", function (needs) {assert.strictEqual(raw.trim(),- '[policy reminder="daily" version="1" groups="staff"]\nI accept this policy\n[/policy]'+ '[policy groups="staff" version="1" reminder="daily"]\nI accept this policy\n[/policy]');});diff --git a/plugins/discourse-policy/test/javascripts/integration/components/policy-builder-form-test.gjs b/plugins/discourse-policy/test/javascripts/integration/components/policy-builder-form-test.gjsindex e137c226f20..44b7cbfea38 100644--- a/plugins/discourse-policy/test/javascripts/integration/components/policy-builder-form-test.gjs+++ b/plugins/discourse-policy/test/javascripts/integration/components/policy-builder-form-test.gjs@@ -1,8 +1,7 @@-import EmberObject from "@ember/object";import { click, fillIn, render } from "@ember/test-helpers";import { module, test } from "qunit";+import { AUTO_GROUPS } from "discourse/lib/constants";import { setupRenderingTest } from "discourse/tests/helpers/component-test";-import { query } from "discourse/tests/helpers/qunit-helpers";import selectKit from "discourse/tests/helpers/select-kit-helper";import { i18n } from "discourse-i18n";import PolicyBuilderForm from "discourse/plugins/discourse-policy/discourse/components/policy-builder-form";@@ -12,35 +11,42 @@ module(function (hooks) {setupRenderingTest(hooks);- test("onChange", async function (assert) {- this.set("policy", new EmberObject());- this.set("onChange", (key, value) => {- query(".output").innerText = `${key}=${value}`;- });+ hooks.beforeEach(function () {+ this.site = this.owner.lookup("service:site");+ this.site.groups = [+ AUTO_GROUPS.everyone,+ AUTO_GROUPS.admins,+ AUTO_GROUPS.moderators,+ AUTO_GROUPS.staff,+ AUTO_GROUPS.trust_level_0,+ { id: 100, name: "team" },+ ];++ this.set("data", { reminder: null, version: 1 });+ this.set("onRegisterApi", (api) => (this.formApi = api));+ this.set("onSubmit", (data) => (this.submittedData = data));+ });+ test("submits form data", async function (assert) {await render(<template>- <span class="output"></span><PolicyBuilderForm- @onChange={{this.onChange}}- @policy={{this.policy}}+ @data={{this.data}}+ @onRegisterApi={{this.onRegisterApi}}+ @onSubmit={{this.onSubmit}}/></template>);- const groupsChooser = selectKit(".groups .group-chooser");+ const groupsChooser = selectKit(+ ".policy-builder-form__groups .group-chooser"+ );await groupsChooser.expand();await groupsChooser.selectRowByValue("admins");- assert.dom(".output").hasText("groups=admins");await fillIn("input[name='version']", "1");- assert.dom(".output").hasText("version=1");-await fillIn("input[name='renew']", "1");- assert.dom(".output").hasText("renew=1");-- await fillIn("input[name='renew-start']", "2022-06-07");- assert.dom(".output").hasText("renew-start=2022-06-07");+ await fillIn("input[name='renewStart']", "2022-06-07");const reminderChooser = selectKit(".combo-box");assert@@ -52,21 +58,53 @@ module(await reminderChooser.expand();await reminderChooser.selectRowByValue("weekly");- assert.dom(".output").hasText("reminder=weekly");await fillIn("input[name='accept']", "foo");- assert.dom(".output").hasText("accept=foo");-await fillIn("input[name='revoke']", "bar");- assert.dom(".output").hasText("revoke=bar");- const addGroupsChooser = selectKit(".add-users-to-group .group-chooser");+ const addGroupsChooser = selectKit(+ ".policy-builder-form__add-users-to-group .group-chooser"+ );await addGroupsChooser.expand();- await addGroupsChooser.selectRowByValue("moderators");- assert.dom(".output").hasText("add-users-to-group=moderators");+ assert+ .dom(addGroupsChooser.rowByValue("moderators").el())+ .doesNotExist("automatic groups are not listed");+ await addGroupsChooser.selectRowByValue("team");await click("input[name='private']");- assert.dom(".output").hasText("private=true");+ await this.formApi.submit();++ assert.deepEqual(this.submittedData, {+ groups: "admins",+ version: 1,+ renew: 1,+ renewStart: "2022-06-07",+ reminder: "weekly",+ accept: "foo",+ revoke: "bar",+ addUsersToGroup: "team",+ private: true,+ });+ });++ test("does not submit invalid form data", async function (assert) {+ this.set("data", { version: 1 });+ this.set("onSubmit", () => (this.submitted = true));+ this.submitted = false;++ await render(+ <template>+ <PolicyBuilderForm+ @data={{this.data}}+ @onRegisterApi={{this.onRegisterApi}}+ @onSubmit={{this.onSubmit}}+ />+ </template>+ );++ await this.formApi.submit();++ assert.false(this.submitted, "onSubmit is not called");});});diff --git a/plugins/discourse-policy/test/javascripts/integration/rich-editor-extension-test.js b/plugins/discourse-policy/test/javascripts/integration/rich-editor-extension-test.jsindex e2a1f2fd3a6..059ee62410b 100644--- a/plugins/discourse-policy/test/javascripts/integration/rich-editor-extension-test.js+++ b/plugins/discourse-policy/test/javascripts/integration/rich-editor-extension-test.js@@ -24,7 +24,7 @@ module(});test("policy with all attributes", async function (assert) {- const markdown = `[policy group="staff" version="1" accept="true" revoke="false" reminder="daily" renew-start="2023-01-01" private="true"]\nComplex policy\n\n[/policy]\n\n`;+ const markdown = `[policy group="staff" version="1" accept="true" revoke="false" reminder="daily" renew="30" renew-start="2023-01-01" add-users-to-group="members" private="true"]\nComplex policy\n\n[/policy]\n\n`;const [{ value }] = await setupRichEditor(assert, markdown);const policyElement = document.querySelector(".ProseMirror .policy");@@ -33,8 +33,15 @@ module(assert.dom(policyElement).hasAttribute("data-accept", "true");assert.dom(policyElement).hasAttribute("data-revoke", "false");assert.dom(policyElement).hasAttribute("data-reminder", "daily");+ assert.dom(policyElement).hasAttribute("data-renew", "30");assert.dom(policyElement).hasAttribute("data-renew-start", "2023-01-01");+ assert+ .dom(policyElement)+ .hasAttribute("data-add-users-to-group", "members");assert.dom(policyElement).hasAttribute("data-private", "true");+ assert.dom(".policy-node-edit-button", policyElement).exists();+ assert.dom(".policy-attrs dt", policyElement).exists({ count: 9 });+ assert.dom(".policy-attrs dd", policyElement).exists({ count: 9 });assert.dom("p", policyElement).hasText("Complex policy");assert.strictEqual(value, markdown);